hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
d50041e9d240d32bc192ae4ee715cacb00f41eeb
11,497
hpp
C++
include/System/Linq/Expressions/Interpreter/NullableMethodCallInstruction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Linq/Expressions/Interpreter/NullableMethodCallInstruction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Linq/Expressions/Interpreter/NullableMethodCallInstruction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Linq.Expressions.Interpreter.Instruction #include "System/Linq/Expressions/Interpreter/Instruction.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Linq::Expressions::Interpreter namespace System::Linq::Expressions::Interpreter { } // Forward declaring namespace: System::Reflection namespace System::Reflection { // Forward declaring type: MethodInfo class MethodInfo; } // Completed forward declares // Type namespace: System.Linq.Expressions.Interpreter namespace System::Linq::Expressions::Interpreter { // Forward declaring type: NullableMethodCallInstruction class NullableMethodCallInstruction; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction); DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*, "System.Linq.Expressions.Interpreter", "NullableMethodCallInstruction"); // Type namespace: System.Linq.Expressions.Interpreter namespace System::Linq::Expressions::Interpreter { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.Linq.Expressions.Interpreter.NullableMethodCallInstruction // [TokenAttribute] Offset: FFFFFFFF class NullableMethodCallInstruction : public ::System::Linq::Expressions::Interpreter::Instruction { public: // Nested type: ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::HasValue class HasValue; // Nested type: ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValue class GetValue; // Nested type: ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault class GetValueOrDefault; // Nested type: ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetValueOrDefault1 class GetValueOrDefault1; // Nested type: ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::EqualsClass class EqualsClass; // Nested type: ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::ToStringClass class ToStringClass; // Nested type: ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::GetHashCodeClass class GetHashCodeClass; // Get static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_hasValue static ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* _get_s_hasValue(); // Set static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_hasValue static void _set_s_hasValue(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* value); // Get static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_value static ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* _get_s_value(); // Set static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_value static void _set_s_value(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* value); // Get static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_equals static ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* _get_s_equals(); // Set static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_equals static void _set_s_equals(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* value); // Get static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_getHashCode static ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* _get_s_getHashCode(); // Set static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_getHashCode static void _set_s_getHashCode(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* value); // Get static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_getValueOrDefault1 static ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* _get_s_getValueOrDefault1(); // Set static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_getValueOrDefault1 static void _set_s_getValueOrDefault1(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* value); // Get static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_toString static ::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* _get_s_toString(); // Set static field: static private System.Linq.Expressions.Interpreter.NullableMethodCallInstruction s_toString static void _set_s_toString(::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction* value); // static public System.Linq.Expressions.Interpreter.Instruction Create(System.String method, System.Int32 argCount, System.Reflection.MethodInfo mi) // Offset: 0xE95768 static ::System::Linq::Expressions::Interpreter::Instruction* Create(::StringW method, int argCount, ::System::Reflection::MethodInfo* mi); // static public System.Linq.Expressions.Interpreter.Instruction CreateGetValue() // Offset: 0xE95ADC static ::System::Linq::Expressions::Interpreter::Instruction* CreateGetValue(); // public override System.Int32 get_ConsumedStack() // Offset: 0xE9570C // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.Int32 Instruction::get_ConsumedStack() int get_ConsumedStack(); // public override System.Int32 get_ProducedStack() // Offset: 0xE95714 // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.Int32 Instruction::get_ProducedStack() int get_ProducedStack(); // public override System.String get_InstructionName() // Offset: 0xE9571C // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.String Instruction::get_InstructionName() ::StringW get_InstructionName(); // private System.Void .ctor() // Offset: 0xE95760 // Implemented from: System.Linq.Expressions.Interpreter.Instruction // Base method: System.Void Instruction::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NullableMethodCallInstruction* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NullableMethodCallInstruction*, creationType>())); } }; // System.Linq.Expressions.Interpreter.NullableMethodCallInstruction #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::Create // Il2CppName: Create template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Interpreter::Instruction* (*)(::StringW, int, ::System::Reflection::MethodInfo*)>(&System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::Create)> { static const MethodInfo* get() { static auto* method = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* argCount = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* mi = &::il2cpp_utils::GetClassFromName("System.Reflection", "MethodInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*), "Create", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{method, argCount, mi}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::CreateGetValue // Il2CppName: CreateGetValue template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Interpreter::Instruction* (*)()>(&System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::CreateGetValue)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*), "CreateGetValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::get_ConsumedStack // Il2CppName: get_ConsumedStack template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::*)()>(&System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::get_ConsumedStack)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*), "get_ConsumedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::get_ProducedStack // Il2CppName: get_ProducedStack template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::*)()>(&System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::get_ProducedStack)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*), "get_ProducedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::get_InstructionName // Il2CppName: get_InstructionName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::*)()>(&System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::get_InstructionName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NullableMethodCallInstruction*), "get_InstructionName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NullableMethodCallInstruction::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
71.409938
262
0.782726
[ "vector" ]
d501ba9482f68db9e6f1a7229b12069526e9825a
785
cpp
C++
example/stringWrite/stringWrite.cpp
BillyDonahue/jsoncpp
c161f4ac69633deb2ed43bc8569cb9b183f63c32
[ "MIT" ]
4,538
2017-10-20T05:19:03.000Z
2022-03-30T02:29:30.000Z
example/stringWrite/stringWrite.cpp
BillyDonahue/jsoncpp
c161f4ac69633deb2ed43bc8569cb9b183f63c32
[ "MIT" ]
1,088
2017-10-21T07:57:22.000Z
2022-03-31T08:15:49.000Z
example/stringWrite/stringWrite.cpp
BillyDonahue/jsoncpp
c161f4ac69633deb2ed43bc8569cb9b183f63c32
[ "MIT" ]
1,860
2017-10-20T05:22:35.000Z
2022-03-27T10:54:14.000Z
#include "json/json.h" #include <iostream> /** \brief Write a Value object to a string. * Example Usage: * $g++ stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite * $./stringWrite * { * "action" : "run", * "data" : * { * "number" : 1 * } * } */ int main() { Json::Value root; Json::Value data; constexpr bool shouldUseOldWay = false; root["action"] = "run"; data["number"] = 1; root["data"] = data; if (shouldUseOldWay) { Json::FastWriter writer; const std::string json_file = writer.write(root); std::cout << json_file << std::endl; } else { Json::StreamWriterBuilder builder; const std::string json_file = Json::writeString(builder, root); std::cout << json_file << std::endl; } return EXIT_SUCCESS; }
23.088235
67
0.598726
[ "object" ]
d507227689183461a75ffa3d4f1ef1d9516fd7fc
115,283
cpp
C++
minstall.cpp
dolphinoracle/gazelle-installer
8e58f18bf3785f3fa4a915a5316e14f3a150cd8c
[ "Apache-2.0" ]
null
null
null
minstall.cpp
dolphinoracle/gazelle-installer
8e58f18bf3785f3fa4a915a5316e14f3a150cd8c
[ "Apache-2.0" ]
null
null
null
minstall.cpp
dolphinoracle/gazelle-installer
8e58f18bf3785f3fa4a915a5316e14f3a150cd8c
[ "Apache-2.0" ]
1
2020-03-10T12:53:57.000Z
2020-03-10T12:53:57.000Z
/**************************************************************************** * Copyright (C) 2003-2010 by Warren Woodford * Heavily edited, with permision, by anticapitalista for antiX 2011-2014. * Heavily revised by dolphin oracle, adrian, and anticaptialista 2018. * additional mount and compression oftions for btrfs by rob 2018 * Major GUI update and user experience improvements by AK-47 2019. * 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 <QDebug> #include <QFileInfo> #include <QProcess> #include <QProcessEnvironment> #include <QTimeZone> #include <QTimer> #include <QToolTip> #include <cstdlib> #include <fcntl.h> #include <sys/stat.h> #include <sys/statvfs.h> #include "version.h" #include "minstall.h" enum Step { Splash, Terms, Disk, Partitions, Boot, Services, Network, Localization, UserAccounts, OldHome, Progress, End }; MInstall::MInstall(const QCommandLineParser &args, const QString &cfgfile) : proc(this), partman(proc, *this, this) { setupUi(this); listLog->addItem("Version " VERSION); proc.setupUI(listLog, progInstall); updateCursor(Qt::WaitCursor); setWindowFlags(Qt::Window); // for the close, min and max buttons boxInstall->hide(); oobe = args.isSet("oobe"); pretend = args.isSet("pretend"); nocopy = args.isSet("nocopy"); sync = args.isSet("sync"); if (!oobe) { partman.brave = brave = args.isSet("brave"); automatic = args.isSet("auto"); oem = args.isSet("oem"); partman.gptoverride = args.isSet("gpt-override"); mountkeep = args.isSet("mount-keep"); } else { brave = automatic = oem = false; pushClose->setText(tr("Shutdown")); phase = 2; // dark palette for the OOBE screen QColor charcoal(56, 56, 56); QPalette pal; pal.setColor(QPalette::Window, charcoal); pal.setColor(QPalette::WindowText, Qt::white); pal.setColor(QPalette::Base, charcoal.darker()); pal.setColor(QPalette::AlternateBase, charcoal); pal.setColor(QPalette::Text, Qt::white); pal.setColor(QPalette::Button, charcoal); pal.setColor(QPalette::ButtonText, Qt::white); pal.setColor(QPalette::Active, QPalette::Button, charcoal); pal.setColor(QPalette::Disabled, QPalette::Light, charcoal.darker()); pal.setColor(QPalette::Disabled, QPalette::Text, Qt::darkGray); pal.setColor(QPalette::Disabled, QPalette::WindowText, Qt::darkGray); pal.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::darkGray); pal.setColor(QPalette::Highlight, Qt::lightGray); pal.setColor(QPalette::HighlightedText, Qt::black); pal.setColor(QPalette::ToolTipBase, Qt::black); pal.setColor(QPalette::ToolTipText, Qt::white); pal.setColor(QPalette::Link, Qt::cyan); qApp->setPalette(pal); } //if (pretend) listHomes = qApp->arguments(); // dummy existing homes // setup system variables QSettings settings("/usr/share/gazelle-installer-data/installer.conf", QSettings::NativeFormat); PROJECTNAME = settings.value("PROJECT_NAME").toString(); PROJECTSHORTNAME = settings.value("PROJECT_SHORTNAME").toString(); PROJECTVERSION = settings.value("VERSION").toString(); PROJECTURL = settings.value("PROJECT_URL").toString(); PROJECTFORUM = settings.value("FORUM_URL").toString(); INSTALL_FROM_ROOT_DEVICE = settings.value("INSTALL_FROM_ROOT_DEVICE").toBool(); DEFAULT_HOSTNAME = settings.value("DEFAULT_HOSTNAME").toString(); ENABLE_SERVICES = settings.value("ENABLE_SERVICES").toStringList(); POPULATE_MEDIA_MOUNTPOINTS = settings.value("POPULATE_MEDIA_MOUNTPOINTS").toBool(); REMOVE_NOSPLASH = settings.value("REMOVE_NOSPLASH", "false").toBool(); ROOT_BUFFER = settings.value("ROOT_BUFFER", 5000).toInt(); HOME_BUFFER = settings.value("HOME_BUFFER", 2000).toInt(); setWindowTitle(tr("%1 Installer").arg(PROJECTNAME)); gotoPage(Step::Splash); // config file config = new MSettings(cfgfile, this); // Link block QString link_block; settings.beginGroup("LINKS"); QStringList links = settings.childKeys(); for (const QString &link : links) link_block += "\n\n" + tr(link.toUtf8().constData()) + ": " + settings.value(link).toString(); settings.endGroup(); // set some distro-centric text textReminders->setPlainText(tr("Support %1\n\n%1 is supported by people like you. Some help others at the support forum - %2, or translate help files into different languages, or make suggestions, write documentation, or help test new software.").arg(PROJECTNAME, PROJECTFORUM) + "\n" + link_block); // ensure the help widgets are displayed correctly when started // Qt will delete the heap-allocated event object when posted qApp->postEvent(this, new QEvent(QEvent::PaletteChange)); QTimer::singleShot(0, this, &MInstall::startup); } MInstall::~MInstall() { } // meant to be run after the installer becomes visible void MInstall::startup() { proc.log(__PRETTY_FUNCTION__); resizeEvent(nullptr); if (oobe) { containsSystemD = QFileInfo("/usr/bin/systemctl").isExecutable(); if (QFile::exists("/etc/service") && QFile::exists("/lib/runit/runit-init")) containsRunit = true; checkSaveDesktop->hide(); } else { containsSystemD = QFileInfo("/live/aufs/bin/systemctl").isExecutable(); if (QFile::exists("/live/aufs/etc/service") && QFile::exists("/live/aufs/sbin/runit")) containsRunit = true; rootSources << "/live/aufs/bin" << "/live/aufs/dev" << "/live/aufs/etc" << "/live/aufs/lib" << "/live/aufs/libx32" << "/live/aufs/lib64" << "/live/aufs/media" << "/live/aufs/mnt" << "/live/aufs/opt" << "/live/aufs/root" << "/live/aufs/sbin" << "/live/aufs/usr" << "/live/aufs/var" << "/live/aufs/home"; //load some live variables QSettings livesettings("/live/config/initrd.out",QSettings::NativeFormat); SQFILE_FULL = livesettings.value("SQFILE_FULL", "/live/boot-dev/antiX/linuxfs").toString(); // check the linuxfs squashfs for a home/demo folder, which indicates a remaster perserving /home. isRemasteredDemoPresent = QFileInfo("/live/linux/home/demo").isDir(); qDebug() << "check for remastered home demo folder:" << isRemasteredDemoPresent; // calculate required disk space bootSource = "/live/aufs/boot"; partman.bootSpaceNeeded = proc.execOut("du -sb " + bootSource).section('\t', 0, 0).toLongLong(); if (!pretend && partman.bootSpaceNeeded==0) { QMessageBox::critical(this, windowTitle(), tr("Cannot access installation source.")); exit(EXIT_FAILURE); } //rootspaceneeded is the size of the linuxfs file * a compression factor + contents of the rootfs. conservative but fast //factors are same as used in live-remaster //get compression factor by reading the linuxfs squasfs file, if available qDebug() << "linuxfs file is at : " << SQFILE_FULL; long long compression_factor; QString linuxfs_compression_type = "xz"; //default conservative if (QFileInfo::exists(SQFILE_FULL)) linuxfs_compression_type = proc.execOut("dd if=" + SQFILE_FULL + " bs=1 skip=20 count=2 status=none 2>/dev/null | od -An -tdI"); // gzip, xz, or lz4 switch (linuxfs_compression_type.toInt()) { case 1: // gzip compression_factor = 30; break; case 2: // lzo, not used by antiX case 3: // lzma, not used by antiX case 5: // lz4 compression_factor = 42; break; case 4: // xz default: // anythng else or linuxfs not reachable (toram), should be pretty conservative compression_factor = 25; } qDebug() << "linuxfs compression type is " << linuxfs_compression_type << "compression factor is " << compression_factor; long long rootfs_file_size = 0; long long linuxfs_file_size = (proc.execOut("df /live/linux --output=used --total |tail -n1").toLongLong() * 1024 * 100) / compression_factor; if (QFileInfo::exists("/live/perist-root")) { rootfs_file_size = proc.execOut("df /live/persist-root --output=used --total |tail -n1").toLongLong() * 1024; } qDebug() << "linuxfs file size is " << linuxfs_file_size << " rootfs file size is " << rootfs_file_size; //add rootfs file size to the calculated linuxfs file size. probaby conservative, as rootfs will likely have some overlap with linuxfs long long safety_factor = 1024 * 1024 * 1024; // 1GB safety factor partman.rootSpaceNeeded = linuxfs_file_size + rootfs_file_size + safety_factor; const long long spaceBlock = 134217728; // 128MB partman.bootSpaceNeeded += 2*spaceBlock - (partman.bootSpaceNeeded % spaceBlock); qDebug() << "Minimum space:" << partman.bootSpaceNeeded << "(boot)," << partman.rootSpaceNeeded << "(root)"; // uefi = false if not uefi, or if a bad combination, like 32 bit iso and 64 bit uefi) if (proc.exec("uname -m | grep -q i686", false) && proc.exec("grep -q 64 /sys/firmware/efi/fw_platform_size")) { const int ans = QMessageBox::question(this, windowTitle(), tr("You are running 32bit OS started in 64 bit UEFI mode, the system will not" " be able to boot unless you select Legacy Boot or similar at restart.\n" "We recommend you quit now and restart in Legacy Boot\n\n" "Do you want to continue the installation?"), QMessageBox::Yes, QMessageBox::No); if (ans != QMessageBox::Yes) exit(EXIT_FAILURE); uefi = false; } else { uefi = QFileInfo("/sys/firmware/efi").isDir(); } partman.uefi = uefi; qDebug() << "uefi =" << uefi; autoMountEnabled = true; // disable auto mount by force if (!pretend) setupAutoMount(false); partman.defaultLabels["/boot"] = "boot"; partman.defaultLabels["/"] = "root" + PROJECTSHORTNAME + PROJECTVERSION; partman.defaultLabels["/home"] = "home" + PROJECTSHORTNAME; partman.defaultLabels["SWAP"] = "swap" + PROJECTSHORTNAME; // Detect snapshot-backup account(s) // test if there's another user other than demo in /home, // indicating a possible snapshot or complicated live-usb haveSnapshotUserAccounts = proc.exec("/bin/ls -1 /home" " | grep -Ev '(lost\\+found|demo|snapshot)' | grep -q [a-zA-Z0-9]", false); qDebug() << "check for possible snapshot:" << haveSnapshotUserAccounts; } // Password box setup textCryptoPass->setup(textCryptoPass2, progCryptoPassMeter, 1, 32, 9); textCryptoPassCust->setup(textCryptoPassCust2, progCryptoPassMeterCust, 1, 32, 9); textUserPass->setup(textUserPass2, progUserPassMeter); textRootPass->setup(textRootPass2, progRootPassMeter); connect(textCryptoPass, &MPassEdit::validationChanged, this, &MInstall::diskPassValidationChanged); connect(textCryptoPassCust, &MPassEdit::validationChanged, this, &MInstall::diskPassValidationChanged); connect(textUserPass, &MPassEdit::validationChanged, this, &MInstall::userPassValidationChanged); connect(textRootPass, &MPassEdit::validationChanged, this, &MInstall::userPassValidationChanged); // User name is required connect(textUserName, &QLineEdit::textChanged, this, &MInstall::userPassValidationChanged); // Root account connect(boxRootAccount, &QGroupBox::toggled, this, &MInstall::userPassValidationChanged); // set default host name textComputerName->setText(DEFAULT_HOSTNAME); setupkeyboardbutton(); // timezone lists listTimeZones = proc.execOutLines("find -L /usr/share/zoneinfo/posix -mindepth 2 -type f -printf %P\\n", true); comboTimeArea->clear(); for (const QString &zone : listTimeZones) { const QString &area = zone.section('/', 0, 0); if (comboTimeArea->findData(QVariant(area)) < 0) { QString text(area); if (area == "Indian" || area == "Pacific" || area == "Atlantic" || area == "Arctic") text.append(" Ocean"); comboTimeArea->addItem(text, area); } } comboTimeArea->model()->sort(0); // locale list comboLocale->clear(); QStringList loclist = proc.execOutLines("locale -a | grep -Ev '^(C|POSIX)\\.?' | grep -E 'utf8|UTF-8'"); for (QString &strloc : loclist) { strloc.replace("utf8", "UTF-8", Qt::CaseInsensitive); QLocale loc(strloc); comboLocale->addItem(loc.nativeCountryName() + " - " + loc.nativeLanguageName(), QVariant(strloc)); } comboLocale->model()->sort(0); // default locale selection int ixLocale = comboLocale->findData(QVariant(QLocale::system().name() + ".UTF-8")); if (comboLocale->currentIndex() != ixLocale) comboLocale->setCurrentIndex(ixLocale); else on_comboLocale_currentIndexChanged(ixLocale); // if it looks like an apple... if (proc.exec("grub-probe -d /dev/sda2 2>/dev/null | grep hfsplus", false)) { mactest = true; checkLocalClock->setChecked(true); } //check for samba QFileInfo info("/etc/init.d/smbd"); if (!info.exists()) { labelComputerGroup->setEnabled(false); textComputerGroup->setEnabled(false); textComputerGroup->setText(""); checkSamba->setChecked(false); checkSamba->setEnabled(false); } // check for the Samba server QString val = proc.execOut("dpkg -s samba | grep '^Status.*ok.*' | sed -e 's/.*ok //'"); haveSamba = (val.compare("installed") == 0); buildServiceList(); if (oobe) manageConfig(ConfigLoadB); else { updatePartitionWidgets(true); manageConfig(ConfigLoadA); } stashServices(true); if (oobe) gotoPage(Step::Network); else { textCopyright->setPlainText(tr("%1 is an independent Linux distribution based on Debian Stable.\n\n" "%1 uses some components from MEPIS Linux which are released under an Apache free license." " Some MEPIS components have been modified for %1.\n\nEnjoy using %1").arg(PROJECTNAME)); gotoPage(Step::Terms); } updateCursor(); // automatic installation if (automatic) pushNext->click(); } // turn auto-mount off and on void MInstall::setupAutoMount(bool enabled) { proc.log(__PRETTY_FUNCTION__); if (autoMountEnabled == enabled) return; QFileInfo finfo; // check if the systemctl program is present bool have_sysctl = false; const QStringList &envpath = QProcessEnvironment::systemEnvironment().value("PATH").split(':'); for (const QString &path : envpath) { finfo.setFile(path + "/systemctl"); if (finfo.isExecutable()) { have_sysctl = true; break; } } // check if udisksd is running. bool udisksd_running = false; if (proc.exec("ps -e | grep 'udisksd'")) udisksd_running = true; // create a list of rules files that are being temporarily overridden QStringList udev_temp_mdadm_rules; finfo.setFile("/run/udev"); if (finfo.isDir()) { udev_temp_mdadm_rules = proc.execOutLines("egrep -l '^[^#].*mdadm (-I|--incremental)' /lib/udev/rules.d"); for (QString &rule : udev_temp_mdadm_rules) { rule.replace("/lib/udev", "/run/udev"); } } // auto-mount setup if (!enabled) { // disable auto-mount if (have_sysctl) { // Use systemctl to prevent automount by masking currently unmasked mount points listMaskedMounts = proc.execOutLines("systemctl list-units --full --all -t mount --no-legend 2>/dev/null | grep -v masked | cut -f1 -d' '" " | egrep -v '^(dev-hugepages|dev-mqueue|proc-sys-fs-binfmt_misc|run-user-.*-gvfs|sys-fs-fuse-connections|sys-kernel-config|sys-kernel-debug)'").join(' '); if (!listMaskedMounts.isEmpty()) proc.exec("systemctl --runtime mask --quiet -- " + listMaskedMounts); } // create temporary blank overrides for all udev rules which // automatically start Linux Software RAID array members proc.mkpath("/run/udev/rules.d"); for (const QString &rule : udev_temp_mdadm_rules) proc.exec("touch " + rule); if (udisksd_running) { proc.exec("echo 'SUBSYSTEM==\"block\", ENV{UDISKS_IGNORE}=\"1\"' > /run/udev/rules.d/91-mx-udisks-inhibit.rules"); proc.exec("udevadm control --reload"); proc.exec("udevadm trigger --subsystem-match=block"); } } else { // enable auto-mount if (udisksd_running) { proc.exec("rm -f /run/udev/rules.d/91-mx-udisks-inhibit.rules"); proc.exec("udevadm control --reload"); proc.exec("partprobe -s"); proc.sleep(1000); } // clear the rules that were temporarily overridden for (const QString &rule : udev_temp_mdadm_rules) proc.exec("rm -f " + rule); // Use systemctl to restore that status of any mount points changed above if (have_sysctl && !listMaskedMounts.isEmpty()) { proc.exec("systemctl --runtime unmask --quiet -- $MOUNTLIST"); } } autoMountEnabled = enabled; } ///////////////////////////////////////////////////////////////////////// // util functions // Check if running inside VirtualBox bool MInstall::isInsideVB() { return proc.exec("lspci -n | grep -qE '80ee:beef|80ee:cafe'", false); } bool MInstall::replaceStringInFile(const QString &oldtext, const QString &newtext, const QString &filepath) { QString cmd = QString("sed -i 's/%1/%2/g' %3").arg(oldtext, newtext, filepath); return proc.exec(cmd); } QString MInstall::sliderSizeString(long long size) { QString strout(QLocale::system().formattedDataSize(size, 1, QLocale::DataSizeTraditionalFormat)); if (strout.length() > 6) return QLocale::system().formattedDataSize(size, 0, QLocale::DataSizeTraditionalFormat); return strout; } void MInstall::updateCursor(const Qt::CursorShape shape) { if (shape != Qt::ArrowCursor) { qApp->setOverrideCursor(QCursor(shape)); } else { while (qApp->overrideCursor() != nullptr) qApp->restoreOverrideCursor(); } qApp->processEvents(); } bool MInstall::pretendToInstall(int space, long steps) { proc.advance(space, steps); proc.status(tr("Pretending to install %1").arg(PROJECTNAME)); for (long ixi = 0; ixi < steps; ++ixi) { proc.sleep(100, true); proc.status(); if (phase < 0) return false; } return true; } bool MInstall::writeKeyFile() { if (phase < 0) return false; static const char *const rngfile = "/dev/urandom"; const unsigned int keylength = 4096; const QLineEdit *passedit = radioEntireDisk->isChecked() ? textCryptoPass : textCryptoPassCust; const QByteArray password(passedit->text().toUtf8()); const char *keyfile = nullptr; bool newkey = true; if (partman.isEncrypt("/")) { // if encrypting root newkey = (key.length() == 0); keyfile = "/mnt/antiX/root/keyfile"; if (newkey) key.load(rngfile, keylength); key.save(keyfile, 0400); } else if (partman.isEncrypt("/home") && partman.isEncrypt(QString())>1) { // if encrypting /home without encrypting root keyfile = "/mnt/antiX/home/.keyfileDONOTdelete"; key.load(rngfile, keylength); key.save(keyfile, 0400); key.erase(); } if (!partman.fixCryptoSetup(QString(keyfile).remove(0,10), newkey)) { failUI(tr("Failed to finalize encryption setup.")); return false; } return true; } // disable hibernate when using encrypted swap void MInstall::disablehiberanteinitramfs() { if (phase < 0) return; if (partman.isEncrypt("SWAP")) { proc.exec("touch /mnt/antiX/initramfs-tools/conf.d/resume"); QFile file("/mnt/antiX/etc/initramfs-tools/conf.d/resume"); if (file.open(QIODevice::WriteOnly)) { QTextStream out(&file); out << "RESUME=none"; } file.close(); } } // process the next phase of installation if possible bool MInstall::processNextPhase() { widgetStack->setEnabled(true); // Phase < 0 = install has been aborted (Phase -2 on close) if (phase < 0) return false; // Phase 0 = install not started yet, Phase 1 = install in progress // Phase 2 = waiting for operator input, Phase 3 = post-install steps if (phase == 0) { // no install started yet proc.advance(-1, -1); proc.status(tr("Preparing to install %1").arg(PROJECTNAME)); if (!partman.checkTargetDrivesOK()) return false; phase = 1; // installation. // cleanup previous mounts cleanup(false); // the core of the installation if (!pretend) { proc.advance(12, partman.countPrepSteps()); bool ok = partman.preparePartitions(); if (ok) ok = partman.formatPartitions(); if (ok) ok = partman.mountPartitions(); if (!ok) { failUI(tr("Failed to prepare required partitions.")); return false; } //run blkid -c /dev/null to freshen UUID cache proc.exec("blkid -c /dev/null", true); if (!installLinux()) return false; } else { if (!pretendToInstall(14, 200)) return false; if (!pretendToInstall(80, 500)) return false; } if (widgetStack->currentWidget() != pageProgress) { progInstall->setEnabled(false); proc.status(tr("Paused for required operator input")); QApplication::beep(); } phase = 2; } if (phase == 2 && widgetStack->currentWidget() == pageProgress) { phase = 3; progInstall->setEnabled(true); pushBack->setEnabled(false); if (!pretend) { proc.advance(1, 1); proc.status(tr("Setting system configuration")); if (!isInsideVB() && !oobe) { proc.exec("/bin/mv -f /mnt/antiX/etc/rc5.d/S*virtualbox-guest-utils /mnt/antiX/etc/rc5.d/K01virtualbox-guest-utils >/dev/null 2>&1", false); proc.exec("/bin/mv -f /mnt/antiX/etc/rc4.d/S*virtualbox-guest-utils /mnt/antiX/etc/rc4.d/K01virtualbox-guest-utils >/dev/null 2>&1", false); proc.exec("/bin/mv -f /mnt/antiX/etc/rc3.d/S*virtualbox-guest-utils /mnt/antiX/etc/rc3.d/K01virtualbox-guest-utils >/dev/null 2>&1", false); proc.exec("/bin/mv -f /mnt/antiX/etc/rc2.d/S*virtualbox-guest-utils /mnt/antiX/etc/rc2.d/K01virtualbox-guest-utils >/dev/null 2>&1", false); proc.exec("/bin/mv -f /mnt/antiX/etc/rcS.d/S*virtualbox-guest-x11 /mnt/antiX/etc/rcS.d/K21virtualbox-guest-x11 >/dev/null 2>&1", false); } if (oem) enableOOBE(); else if (!processOOBE()) return false; manageConfig(ConfigSave); config->dumpDebug(); proc.exec("/bin/sync", true); // the sync(2) system call will block the GUI if (!installLoader()) return false; } else if (!pretendToInstall(5, 100)) { return false; } phase = 4; proc.advance(1, 1); proc.status(tr("Cleaning up")); cleanup(); proc.status(tr("Finished")); gotoPage(Step::End); } return true; } void MInstall::manageConfig(enum ConfigAction mode) { if (mode == ConfigSave) { delete config; config = new MSettings("/mnt/antiX/etc/minstall.conf", this); } if (!config) return; config->bad = false; if (mode == ConfigSave) { config->setSave(true); config->clear(); config->setValue("Version", VERSION); config->setValue("Product", PROJECTNAME + " " + PROJECTVERSION); } if ((mode == ConfigSave || mode == ConfigLoadA) && !oobe) { config->startGroup("Storage", pageDisk); const char *diskChoices[] = {"Drive", "Partitions"}; QRadioButton *diskRadios[] = {radioEntireDisk, radioCustomPart}; config->manageRadios("Target", 2, diskChoices, diskRadios); const bool targetDrive = radioEntireDisk->isChecked(); if (targetDrive || mode!=ConfigSave) { config->manageComboBox("Drive", comboDisk, true); config->manageGroupCheckBox("DriveEncrypt", boxEncryptAuto); if (mode==ConfigSave) config->setValue("RootPortion", sliderPart->value()); else if (config->contains("RootPortion")) { const int sliderVal = config->value("RootPortion").toInt(); sliderPart->setValue(sliderVal); on_sliderPart_valueChanged(sliderVal); if (sliderPart->value() != sliderVal) config->markBadWidget(sliderPart); } } config->endGroup(); // Custom partitions page. PartMan handles its config groups automatically. if (!targetDrive || mode!=ConfigSave) { config->setGroupWidget(pagePartitions); partman.manageConfig(*config, mode==ConfigSave); } // Encryption config->startGroup("Encryption", targetDrive ? pageDisk : pagePartitions); if (mode != ConfigSave) { const QString &epass = config->value("Pass").toString(); if (targetDrive) { textCryptoPass->setText(epass); textCryptoPass2->setText(epass); } else { textCryptoPassCust->setText(epass); textCryptoPassCust2->setText(epass); } const QString &keyfile = config->value("KeyMaterial").toString(); if (!keyfile.isEmpty()) { key.load(keyfile.toUtf8().constData(), -1); const int keylen = key.length(); if (keylen>0) { proc.log(QStringLiteral("Loaded %1-byte key material: ").arg(keylen) + keyfile, MProcess::Standard); } } } config->endGroup(); } if (mode == ConfigSave || mode == ConfigLoadB) { if (!oobe) { // GRUB page config->startGroup("GRUB", pageBoot); config->manageGroupCheckBox("Install", boxBoot); const char *grubChoices[] = {"MBR", "PBR", "ESP"}; QRadioButton *grubRadios[] = {radioBootMBR, radioBootPBR, radioBootESP}; config->manageRadios("TargetType", 3, grubChoices, grubRadios); config->manageComboBox("Location", comboBoot, true); config->endGroup(); } // Services page config->startGroup("Services", pageServices); QTreeWidgetItemIterator it(treeServices); while (*it) { if ((*it)->parent() != nullptr) { const QString &itext = (*it)->text(0); const QVariant checkval((*it)->checkState(0) == Qt::Checked); if (mode == ConfigSave) config->setValue(itext, checkval); else { const bool val = config->value(itext, checkval).toBool(); (*it)->setCheckState(0, val ? Qt::Checked : Qt::Unchecked); } } ++it; } config->endGroup(); // Network page config->startGroup("Network", pageNetwork); config->manageLineEdit("ComputerName", textComputerName); config->manageLineEdit("Domain", textComputerDomain); config->manageLineEdit("Workgroup", textComputerGroup); config->manageCheckBox("Samba", checkSamba); config->endGroup(); // Localization page config->startGroup("Localization", pageLocalization); config->manageComboBox("Locale", comboLocale, true); config->manageCheckBox("LocalClock", checkLocalClock); const char *clockChoices[] = {"24", "12"}; QRadioButton *clockRadios[] = {radioClock24, radioClock12}; config->manageRadios("ClockHours", 2, clockChoices, clockRadios); if (mode == ConfigSave) { config->setValue("Timezone", comboTimeZone->currentData().toString()); } else { QVariant def = QString(QTimeZone::systemTimeZoneId()); const int rc = selectTimeZone(config->value("Timezone", def).toString()); if (rc == 1) config->markBadWidget(comboTimeArea); else if (rc == 2) config->markBadWidget(comboTimeZone); } config->manageComboBox("Timezone", comboTimeZone, true); config->endGroup(); // User Accounts page config->startGroup("User", pageUserAccounts); config->manageLineEdit("Username", textUserName); config->manageCheckBox("Autologin", checkAutoLogin); config->manageCheckBox("SaveDesktop", checkSaveDesktop); if (oobe) checkSaveDesktop->setCheckState(Qt::Unchecked); const char *oldHomeActions[] = {"Use", "Save", "Delete"}; QRadioButton *oldHomeRadios[] = {radioOldHomeUse, radioOldHomeSave, radioOldHomeDelete}; config->manageRadios("OldHomeAction", 3, oldHomeActions, oldHomeRadios); config->manageGroupCheckBox("EnableRoot", boxRootAccount); if (mode != ConfigSave) { const QString &upass = config->value("UserPass").toString(); textUserPass->setText(upass); textUserPass2->setText(upass); const QString &rpass = config->value("RootPass").toString(); textRootPass->setText(rpass); textRootPass2->setText(rpass); } config->endGroup(); } if (mode == ConfigSave) { config->sync(); QFile::remove("/etc/minstalled.conf"); QFile::copy(config->fileName(), "/etc/minstalled.conf"); } if (config->bad) { QMessageBox::critical(this, windowTitle(), tr("Invalid settings found in configuration file (%1)." " Please review marked fields as you encounter them.").arg(config->fileName())); } } bool MInstall::saveHomeBasic() { proc.log(__PRETTY_FUNCTION__); QString homedir("/"); QString homedev = partman.getMountDev("/home", true); if (homedev.isEmpty() || partman.willFormat("/home")) { if (partman.willFormat("/")) return true; homedev = partman.getMountDev("/", true); homedir = "/home"; } mkdir("/mnt/antiX", 0755); const bool ok = proc.exec("/bin/mount -o ro " + homedev + " /mnt/antiX"); // Store a listing of /home to compare with the user name given later. if (ok) listHomes = proc.execOutLines("/bin/ls -1 /mnt/antiX" + homedir); proc.exec("/bin/umount -l /mnt/antiX", false); return ok; } bool MInstall::installLinux() { proc.log(__PRETTY_FUNCTION__); if (phase < 0) return false; proc.advance(1, 2); if (!partman.willFormat("/")) { // if root was not formatted and not using --sync option then re-use it // remove all folders in root except for /home proc.status(tr("Deleting old system")); proc.exec("find /mnt/antiX -mindepth 1 -maxdepth 1 ! -name home -exec rm -r {} \\;", false); if (proc.exitStatus() != QProcess::NormalExit) { failUI(tr("Failed to delete old %1 on destination.\nReturning to Step 1.").arg(PROJECTNAME)); return false; } } // make empty dirs for opt, dev, proc, sys, run, // home already done proc.status(tr("Creating system directories")); mkdir("/mnt/antiX/opt", 0755); mkdir("/mnt/antiX/dev", 0755); mkdir("/mnt/antiX/proc", 0755); mkdir("/mnt/antiX/sys", 0755); mkdir("/mnt/antiX/run", 0755); setupAutoMount(true); if (!copyLinux()) return false; proc.advance(1, 1); proc.status(tr("Fixing configuration")); mkdir("/mnt/antiX/tmp", 01777); chmod("/mnt/antiX/tmp", 01777); // Copy live set up to install and clean up. proc.exec("/usr/sbin/live-to-installed /mnt/antiX", false); qDebug() << "Desktop menu"; proc.exec("chroot /mnt/antiX desktop-menu --write-out-global", false); // if POPULATE_MEDIA_MOUNTPOINTS is true in gazelle-installer-data, then use the --mntpnt switch partman.makeFstab(POPULATE_MEDIA_MOUNTPOINTS); if(!writeKeyFile()) return false; disablehiberanteinitramfs(); //remove home unless a demo home is found in remastered linuxfs if (!isRemasteredDemoPresent) proc.exec("/bin/rm -rf /mnt/antiX/home/demo"); // if POPULATE_MEDIA_MOUNTPOINTS is true in gazelle-installer-data, don't clean /media folder // modification to preserve points that are still mounted. if (!POPULATE_MEDIA_MOUNTPOINTS) { proc.exec("/bin/rmdir --ignore-fail-on-non-empty /mnt/antiX/media/sd*", false); } // guess localtime vs UTC if (proc.execOut("guess-hwclock") == "localtime") checkLocalClock->setChecked(true); // create a /etc/machine-id file and /var/lib/dbus/machine-id file proc.exec("/bin/mount --rbind --make-rslave /dev /mnt/antiX/dev", true); proc.exec("chroot /mnt/antiX rm /var/lib/dbus/machine-id /etc/machine-id", false); proc.exec("chroot /mnt/antiX dbus-uuidgen --ensure=/etc/machine-id", false); proc.exec("chroot /mnt/antiX dbus-uuidgen --ensure", false); proc.exec("/bin/umount -R /mnt/antiX/dev", true); return true; } bool MInstall::copyLinux() { proc.log(__PRETTY_FUNCTION__); if (phase < 0) return false; // copy most except usr, mnt and home // must copy boot even if saving, the new files are required // media is already ok, usr will be done next, home will be done later // setup and start the process QString prog = "/bin/cp"; QStringList args("-av"); if (sync) { prog = "rsync"; args << "--delete"; if (!partman.willFormat("/")) args << "--filter" << "protect home/*"; } args << bootSource << rootSources << "/mnt/antiX"; struct statvfs svfs; fsfilcnt_t sourceInodes = 1; if (statvfs("/live/linux", &svfs) == 0) { sourceInodes = svfs.f_files - svfs.f_ffree; } proc.advance(80, sourceInodes); proc.status(tr("Copying new system")); if (!nocopy) { if (phase < 0) return false; const QString &joined = MProcess::joinCommand(prog, args); qDebug().noquote() << "Exec COPY:" << joined; QListWidgetItem *logEntry = proc.log(joined, MProcess::Exec); QEventLoop eloop; connect(&proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), &eloop, &QEventLoop::quit); connect(&proc, &QProcess::readyRead, &eloop, &QEventLoop::quit); proc.start(prog, args); long ncopy = 0; while (proc.state() != QProcess::NotRunning) { eloop.exec(); ncopy += proc.readAllStandardOutput().count('\n'); proc.status(ncopy); } disconnect(&proc, &QProcess::readyRead, nullptr, nullptr); disconnect(&proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), nullptr, nullptr); const QByteArray &StdErr = proc.readAllStandardError(); if (!StdErr.isEmpty()) { qDebug() << "SErr COPY:" << StdErr; QFont logFont = logEntry->font(); logFont.setItalic(true); logEntry->setFont(logFont); } qDebug() << "Exit COPY:" << proc.exitCode() << proc.exitStatus(); if (proc.exitStatus() != QProcess::NormalExit) { proc.log(logEntry, -1); failUI(tr("Failed to write %1 to destination.\nReturning to Step 1.").arg(PROJECTNAME)); return false; } proc.log(logEntry, proc.exitCode() ? 0 : 1); } return (phase >= 0); // Reduces domino effect if the copy is aborted. } /////////////////////////////////////////////////////////////////////////// // install loader // build a grub configuration and install grub bool MInstall::installLoader() { proc.log(__PRETTY_FUNCTION__); if (phase < 0) return false; proc.advance(4, 4); QString cmd; QString val = proc.execOut("/bin/ls /mnt/antiX/boot | grep 'initrd.img-3.6'"); // the old initrd is not valid for this hardware if (!val.isEmpty()) proc.exec("/bin/rm -f /mnt/antiX/boot/" + val); bool efivarfs = QFileInfo("/sys/firmware/efi/efivars").isDir(); bool efivarfs_mounted = false; if (efivarfs) { QFile file("/proc/self/mounts"); if (file.open(QFile::ReadOnly | QFile::Text)) { while (!file.atEnd() && !efivarfs_mounted) { if (file.readLine().startsWith("efivarfs")) efivarfs_mounted = true; } file.close(); } } if (efivarfs && !efivarfs_mounted) proc.exec("/bin/mount -t efivarfs efivarfs /sys/firmware/efi/efivars", true); if (!boxBoot->isChecked()) { // skip it proc.status(tr("Updating initramfs")); //if useing f2fs, then add modules to /etc/initramfs-tools/modules qDebug() << "Update initramfs"; //if (rootTypeCombo->currentText() == "f2fs" || homeTypeCombo->currentText() == "f2fs") { //proc.exec("grep -q f2fs /mnt/antiX/etc/initramfs-tools/modules || echo f2fs >> /mnt/antiX/etc/initramfs-tools/modules"); //proc.exec("grep -q crypto-crc32 /mnt/antiX/etc/initramfs-tools/modules || echo crypto-crc32 >> /mnt/antiX/etc/initramfs-tools/modules"); //} return proc.exec("chroot /mnt/antiX update-initramfs -u -t -k all"); } proc.status(tr("Installing GRUB")); // set mounts for chroot proc.exec("/bin/mount --rbind --make-rslave /dev /mnt/antiX/dev", true); proc.exec("/bin/mount --rbind --make-rslave /sys /mnt/antiX/sys", true); proc.exec("/bin/mount --rbind /proc /mnt/antiX/proc", true); proc.exec("/bin/mount -t tmpfs -o size=100m,nodev,mode=755 tmpfs /mnt/antiX/run", true); proc.exec("/bin/mkdir /mnt/antiX/run/udev", true); proc.exec("/bin/mount --rbind /run/udev /mnt/antiX/run/udev", true); QString arch; // install new Grub now const QString &boot = "/dev/" + comboBoot->currentData().toString(); if (!radioBootESP->isChecked()) { cmd = QString("grub-install --target=i386-pc --recheck --no-floppy --force --boot-directory=/mnt/antiX/boot %1").arg(boot); } else { mkdir("/mnt/antiX/boot/efi", 0755); QString mount = QString("/bin/mount %1 /mnt/antiX/boot/efi").arg(boot); proc.exec(mount); // rename arch to match grub-install target arch = proc.execOut("cat /sys/firmware/efi/fw_platform_size"); arch = (arch == "32") ? "i386" : "x86_64"; // fix arch name for 32bit cmd = QString("chroot /mnt/antiX grub-install --force-extra-removable --target=%1-efi --efi-directory=/boot/efi --bootloader-id=%2%3 --recheck").arg(arch, PROJECTSHORTNAME, PROJECTVERSION); } qDebug() << "Installing Grub"; if (!proc.exec(cmd)) { // error QMessageBox::critical(this, windowTitle(), tr("GRUB installation failed. You can reboot to the live medium and use the GRUB Rescue menu to repair the installation.")); proc.exec("/bin/umount -R /mnt/antiX/run", true); proc.exec("/bin/umount -R /mnt/antiX/proc", true); proc.exec("/bin/umount -R /mnt/antiX/sys", true); proc.exec("/bin/umount -R /mnt/antiX/dev", true); if (proc.exec("mountpoint -q /mnt/antiX/boot/efi", true)) proc.exec("/bin/umount /mnt/antiX/boot/efi", true); return false; } //added non-live boot codes to those in /etc/default/grub, remove duplicates //get non-live boot codes QString cmdline = proc.execOut("/live/bin/non-live-cmdline"); //get /etc/default/grub codes QSettings grubSettings("/etc/default/grub", QSettings::NativeFormat); QString grubDefault=grubSettings.value("GRUB_CMDLINE_LINUX_DEFAULT").toString(); qDebug() << "grubDefault is " << grubDefault; //covert qstrings to qstringlists and join the default and non-live lists together QStringList finalcmdline=cmdline.split(" "); finalcmdline.append(grubDefault.split(" ")); qDebug() << "intermediate" << finalcmdline; //remove any duplicate codes in list (typically splash) finalcmdline.removeDuplicates(); //remove vga=ask finalcmdline.removeAll("vga=ask"); //remove boot_image code finalcmdline.removeAll("BOOT_IMAGE=/antiX/vmlinuz"); //remove nosplash boot code if configured in installer.conf if (REMOVE_NOSPLASH) finalcmdline.removeAll("nosplash"); //remove in null or empty strings that might have crept in finalcmdline.removeAll({}); qDebug() << "Add cmdline options to Grub" << finalcmdline; //convert qstringlist back into normal qstring QString finalcmdlinestring = finalcmdline.join(" "); qDebug() << "cmdlinestring" << finalcmdlinestring; //get qstring boot codes read for sed command finalcmdlinestring.replace('\\', "\\\\"); finalcmdlinestring.replace('|', "\\|"); //do the replacement in /etc/default/grub qDebug() << "Add cmdline options to Grub"; cmd = QString("sed -i -r 's|^(GRUB_CMDLINE_LINUX_DEFAULT=).*|\\1\"%1\"|' /mnt/antiX/etc/default/grub").arg(finalcmdlinestring); proc.exec(cmd, false); //copy memtest efi files if needed if (uefi) { mkdir("/mnt/antiX/boot/uefi-mt", 0755); if (arch == "i386") proc.exec("/bin/cp /live/boot-dev/boot/uefi-mt/mtest-32.efi /mnt/antiX/boot/uefi-mt", true); else proc.exec("/bin/cp /live/boot-dev/boot/uefi-mt/mtest-64.efi /mnt/antiX/boot/uefi-mt", true); } proc.status(); //update grub with new config qDebug() << "Update Grub"; proc.exec("chroot /mnt/antiX update-grub"); proc.status(tr("Updating initramfs")); //if useing f2fs, then add modules to /etc/initramfs-tools/modules //if (rootTypeCombo->currentText() == "f2fs" || homeTypeCombo->currentText() == "f2fs") { //proc.exec("grep -q f2fs /mnt/antiX/etc/initramfs-tools/modules || echo f2fs >> /mnt/antiX/etc/initramfs-tools/modules"); //proc.exec("grep -q crypto-crc32 /mnt/antiX/etc/initramfs-tools/modules || echo crypto-crc32 >> /mnt/antiX/etc/initramfs-tools/modules"); //} proc.exec("chroot /mnt/antiX update-initramfs -u -t -k all"); proc.status(); qDebug() << "clear chroot env"; proc.exec("/bin/umount -R /mnt/antiX/run", true); proc.exec("/bin/umount -R /mnt/antiX/proc", true); proc.exec("/bin/umount -R /mnt/antiX/sys", true); proc.exec("/bin/umount -R /mnt/antiX/dev", true); if (proc.exec("mountpoint -q /mnt/antiX/boot/efi", true)) proc.exec("/bin/umount /mnt/antiX/boot/efi", true); return true; } // out-of-box experience void MInstall::enableOOBE() { QTreeWidgetItemIterator it(treeServices); for (; *it; ++it) { if ((*it)->parent()) setService((*it)->text(0), false); // Speed up the OOBE boot. } proc.exec("chroot /mnt/antiX/ update-rc.d oobe defaults", true); } bool MInstall::processOOBE() { QTreeWidgetItemIterator it(treeServices); for (; *it; ++it) { if ((*it)->parent()) setService((*it)->text(0), (*it)->checkState(0) == Qt::Checked); } if (!setComputerName()) return false; setLocale(); if (haveSnapshotUserAccounts) { // skip user account creation QString cmd = "rsync -a /home/ /mnt/antiX/home/" " --exclude '.cache' --exclude '.gvfs' --exclude '.dbus' --exclude '.Xauthority'" " --exclude '.ICEauthority' --exclude '.config/session'"; proc.exec(cmd); } else { if (!setUserInfo()) return false; } if (oobe) proc.exec("update-rc.d oobe disable", false); return true; } ///////////////////////////////////////////////////////////////////////// // user account functions bool MInstall::validateUserInfo() { const QString &userName = textUserName->text(); nextFocus = textUserName; // see if username is reasonable length if (!userName.contains(QRegExp("^[a-zA-Z_][a-zA-Z0-9_-]*[$]?$"))) { QMessageBox::critical(this, windowTitle(), tr("The user name cannot contain special characters or spaces.\n" "Please choose another name before proceeding.")); return false; } // check that user name is not already used QFile file("/etc/passwd"); if (file.open(QFile::ReadOnly | QFile::Text)) { const QByteArray &match = QString("%1:").arg(userName).toUtf8(); while (!file.atEnd()) { if (file.readLine().startsWith(match)) { QMessageBox::critical(this, windowTitle(), tr("Sorry, that name is in use.\n" "Please select a different name.")); return false; } } } if (!automatic && boxRootAccount->isChecked() && textRootPass->text().isEmpty()) { // Confirm that an empty root password is not accidental. const QMessageBox::StandardButton ans = QMessageBox::warning(this, windowTitle(), tr("You did not provide a password for the root account." " Do you want to continue?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ans!=QMessageBox::Yes) return false; } // Check for pre-existing /home directory // see if user directory already exists haveOldHome = listHomes.contains(userName); if (haveOldHome) { const QString &str = tr("The home directory for %1 already exists."); labelOldHome->setText(str.arg(userName)); } nextFocus = nullptr; return true; } // setup the user, cannot be rerun bool MInstall::setUserInfo() { if (nocopy) return true; if (phase < 0) return false; // set the user passwords first bool ok = true; QString cmdChRoot; if (!oobe) cmdChRoot = "chroot /mnt/antiX "; const QString &userPass = textUserPass->text(); QByteArray userinfo; if (!(boxRootAccount->isChecked())) ok = proc.exec(cmdChRoot + "passwd -l root", true); else { const QString &rootPass = textRootPass->text(); if (rootPass.isEmpty()) ok = proc.exec(cmdChRoot + "passwd -d root", true); else userinfo.append(QString("root:" + rootPass).toUtf8()); } if (ok && userPass.isEmpty()) ok = proc.exec(cmdChRoot + "passwd -d demo", true); else { if (!userinfo.isEmpty()) userinfo.append('\n'); userinfo.append(QString("demo:" + userPass).toUtf8()); } if (ok && !userinfo.isEmpty()) ok = proc.exec(cmdChRoot + "chpasswd", true, &userinfo); if (!ok) { failUI(tr("Failed to set user account passwords.")); return false; } QString rootpath; if (!oobe) rootpath = "/mnt/antiX"; QString skelpath = rootpath + "/etc/skel"; QString dpath = rootpath + "/home/" + textUserName->text(); if (QFileInfo::exists(dpath)) { if (radioOldHomeSave->isChecked()) { bool ok = false; QString cmd = QString("/bin/mv -f %1 %1.00%2").arg(dpath); for (int ixi = 1; ixi < 10 && !ok; ++ixi) ok = proc.exec(cmd.arg(ixi)); if (!ok) { failUI(tr("Failed to save old home directory.")); return false; } } else if (radioOldHomeDelete->isChecked()) { if (!proc.exec("/bin/rm -rf " + dpath)) { failUI(tr("Failed to delete old home directory.")); return false; } } proc.exec("/bin/sync", true); // The sync(2) system call will block the GUI. } if (QFileInfo::exists(dpath.toUtf8())) { // Still exists. proc.exec("/bin/cp -n " + skelpath + "/.bash_profile " + dpath, true); proc.exec("/bin/cp -n " + skelpath + "/.bashrc " + dpath, true); proc.exec("/bin/cp -n " + skelpath + "/.gtkrc " + dpath, true); proc.exec("/bin/cp -n " + skelpath + "/.gtkrc-2.0 " + dpath, true); proc.exec("/bin/cp -Rn " + skelpath + "/.config " + dpath, true); proc.exec("/bin/cp -Rn " + skelpath + "/.local " + dpath, true); } else { // dir does not exist, must create it // Copy skel to demo, unless demo folder exists in remastered linuxfs. if (!isRemasteredDemoPresent) { if (!proc.exec("/bin/cp -a " + skelpath + ' ' + dpath)) { failUI(tr("Sorry, failed to create user directory.")); return false; } } else { // still rename the demo directory even if remastered demo home folder is detected if (!proc.exec("/bin/mv -f " + rootpath + "/home/demo " + dpath)) { failUI(tr("Sorry, failed to name user directory.")); return false; } } } // saving Desktop changes if (checkSaveDesktop->isChecked()) { resetBlueman(); rsynchomefolder(dpath); } // check if remaster exists and checkSaveDesktop not checked, modify the remastered demo folder if (isRemasteredDemoPresent && ! checkSaveDesktop->isChecked()) { resetBlueman(); changeRemasterdemoToNewUser(dpath); } // fix the ownership, demo=newuser if (!proc.exec("chown -R demo:demo " + dpath)) { failUI(tr("Sorry, failed to set ownership of user directory.")); return false; } // change in files replaceStringInFile("demo", textUserName->text(), rootpath + "/etc/group"); replaceStringInFile("demo", textUserName->text(), rootpath + "/etc/gshadow"); replaceStringInFile("demo", textUserName->text(), rootpath + "/etc/passwd"); replaceStringInFile("demo", textUserName->text(), rootpath + "/etc/shadow"); replaceStringInFile("demo", textUserName->text(), rootpath + "/etc/slim.conf"); replaceStringInFile("demo", textUserName->text(), rootpath + "/etc/lightdm/lightdm.conf"); replaceStringInFile("demo", textUserName->text(), rootpath + "/home/*/.gtkrc-2.0"); replaceStringInFile("demo", textUserName->text(), rootpath + "/root/.gtkrc-2.0"); if (checkAutoLogin->isChecked()) { replaceStringInFile("#auto_login", "auto_login", rootpath + "/etc/slim.conf"); replaceStringInFile("#default_user ", "default_user ", rootpath + "/etc/slim.conf"); replaceStringInFile("User=", "User=" + textUserName->text(), rootpath + "/etc/sddm.conf"); } else { replaceStringInFile("auto_login", "#auto_login", rootpath + "/etc/slim.conf"); replaceStringInFile("default_user ", "#default_user ", rootpath + "/etc/slim.conf"); replaceStringInFile("autologin-user=", "#autologin-user=", rootpath + "/etc/lightdm/lightdm.conf"); replaceStringInFile("User=.*", "User=", rootpath + "/etc/sddm.conf"); } proc.exec("touch " + rootpath + "/var/mail/" + textUserName->text()); return true; } ///////////////////////////////////////////////////////////////////////// // computer name functions bool MInstall::validateComputerName() { // see if name is reasonable nextFocus = textComputerName; if (textComputerName->text().isEmpty()) { QMessageBox::critical(this, windowTitle(), tr("Please enter a computer name.")); return false; } else if (textComputerName->text().contains(QRegExp("[^0-9a-zA-Z-.]|^[.-]|[.-]$|\\.\\."))) { QMessageBox::critical(this, windowTitle(), tr("Sorry, your computer name contains invalid characters.\nYou'll have to select a different\nname before proceeding.")); return false; } // see if name is reasonable nextFocus = textComputerDomain; if (textComputerDomain->text().isEmpty()) { QMessageBox::critical(this, windowTitle(), tr("Please enter a domain name.")); return false; } else if (textComputerDomain->text().contains(QRegExp("[^0-9a-zA-Z-.]|^[.-]|[.-]$|\\.\\."))) { QMessageBox::critical(this, windowTitle(), tr("Sorry, your computer domain contains invalid characters.\nYou'll have to select a different\nname before proceeding.")); return false; } if (haveSamba) { // see if name is reasonable if (textComputerGroup->text().isEmpty()) { QMessageBox::critical(this, windowTitle(), tr("Please enter a workgroup.")); nextFocus = textComputerGroup; return false; } } else { textComputerGroup->clear(); } nextFocus = nullptr; return true; } // set the computer name, can not be rerun bool MInstall::setComputerName() { if (phase < 0) return false; QString etcpath = oobe ? "/etc" : "/mnt/antiX/etc"; if (haveSamba) { //replaceStringInFile(PROJECTSHORTNAME + "1", textComputerName->text(), "/mnt/antiX/etc/samba/smb.conf"); replaceStringInFile("WORKGROUP", textComputerGroup->text(), etcpath + "/samba/smb.conf"); const bool enable = checkSamba->isChecked(); setService("smbd", enable); setService("nmbd", enable); setService("samba-ad-dc", enable); } //replaceStringInFile(PROJECTSHORTNAME + "1", textComputerName->text(), "/mnt/antiX/etc/hosts"); const QString &compname = textComputerName->text(); QString cmd("sed -i 's/'\"$(grep 127.0.0.1 /etc/hosts | grep -v localhost" " | head -1 | awk '{print $2}')\"'/" + compname + "/' "); if (!oobe) proc.exec(cmd + "/mnt/antiX/etc/hosts", false); else { proc.exec(cmd + "/tmp/hosts", false); proc.exec("/bin/mv -f /tmp/hosts " + etcpath, true); } proc.exec("echo \"" + compname + "\" | cat > " + etcpath + "/hostname", false); proc.exec("echo \"" + compname + "\" | cat > " + etcpath + "/mailname", false); proc.exec("sed -i 's/.*send host-name.*/send host-name \"" + compname + "\";/g' " + etcpath + "/dhcp/dhclient.conf", false); proc.exec("echo \"" + compname + "\" | cat > " + etcpath + "/defaultdomain", false); return true; } void MInstall::setLocale() { proc.log(__PRETTY_FUNCTION__); if (phase < 0) return; QString cmd2; QString cmd; //locale if (!oobe) cmd = "chroot /mnt/antiX "; cmd += QString("/usr/sbin/update-locale \"LANG=%1\"").arg(comboLocale->currentData().toString()); qDebug() << "Update locale"; proc.exec(cmd); cmd = QString("Language=%1").arg(comboLocale->currentData().toString()); // /etc/localtime is either a file or a symlink to a file in /usr/share/zoneinfo. Use the one selected by the user. //replace with link if (!oobe) { cmd = QString("/bin/ln -nfs /usr/share/zoneinfo/%1 /mnt/antiX/etc/localtime").arg(comboTimeZone->currentData().toString()); proc.exec(cmd, false); } cmd = QString("/bin/ln -nfs /usr/share/zoneinfo/%1 /etc/localtime").arg(comboTimeZone->currentData().toString()); proc.exec(cmd, false); // /etc/timezone is text file with the timezone written in it. Write the user-selected timezone in it now. if (!oobe) { cmd = QString("echo %1 > /mnt/antiX/etc/timezone").arg(comboTimeZone->currentData().toString()); proc.exec(cmd, false); } cmd = QString("echo %1 > /etc/timezone").arg(comboTimeZone->currentData().toString()); proc.exec(cmd, false); // Set clock to use LOCAL if (checkLocalClock->isChecked()) proc.exec("echo '0.0 0 0.0\n0\nLOCAL' > /etc/adjtime", false); else proc.exec("echo '0.0 0 0.0\n0\nUTC' > /etc/adjtime", false); proc.exec("hwclock --hctosys"); if (!oobe) { proc.exec("/bin/cp -f /etc/adjtime /mnt/antiX/etc/"); proc.exec("/bin/cp -f /etc/default/rcS /mnt/antiX/etc/default"); } // Set clock format QString skelpath = oobe ? "/etc/skel" : "/mnt/antiX/etc/skel"; if (radioClock12->isChecked()) { //mx systems proc.exec("sed -i '/data0=/c\\data0=%l:%M' /home/demo/.config/xfce4/panel/xfce4-orageclock-plugin-1.rc", false); proc.exec("sed -i '/data0=/c\\data0=%l:%M' " + skelpath + "/.config/xfce4/panel/xfce4-orageclock-plugin-1.rc", false); proc.exec("sed -i '/time_format=/c\\time_format=%l:%M' /home/demo/.config/xfce4/panel/datetime-1.rc", false); proc.exec("sed -i '/time_format=/c\\time_format=%l:%M' " + skelpath + "/.config/xfce4/panel/datetime-1.rc", false); //mx kde proc.exec("sed -i '/use24hFormat=/c\\use24hFormat=0' /home/demo/.config/plasma-org.kde.plasma.desktop-appletsrc", false); proc.exec("sed -i '/use24hFormat=/c\\use24hFormat=0' " + skelpath + "/.config/plasma-org.kde.plasma.desktop-appletsrc", false); //antix systems proc.exec("sed -i 's/%H:%M/%l:%M/g' " + skelpath + "/.icewm/preferences", false); proc.exec("sed -i 's/%k:%M/%l:%M/g' " + skelpath + "/.fluxbox/init", false); proc.exec("sed -i 's/%k:%M/%l:%M/g' " + skelpath + "/.jwm/tray", false); } else { //mx systems proc.exec("sed -i '/data0=/c\\data0=%H:%M' /home/demo/.config/xfce4/panel/xfce4-orageclock-plugin-1.rc", false); proc.exec("sed -i '/data0=/c\\data0=%H:%M' " + skelpath + "/.config/xfce4/panel/xfce4-orageclock-plugin-1.rc", false); proc.exec("sed -i '/time_format=/c\\time_format=%H:%M' /home/demo/.config/xfce4/panel/datetime-1.rc", false); proc.exec("sed -i '/time_format=/c\\time_format=%H:%M' " + skelpath + "/.config/xfce4/panel/datetime-1.rc", false); //mx kde proc.exec("sed -i '/use24hFormat=/c\\use24hFormat=2' /home/demo/.config/plasma-org.kde.plasma.desktop-appletsrc", false); proc.exec("sed -i '/use24hFormat=/c\\use24hFormat=2' " + skelpath + "/.config/plasma-org.kde.plasma.desktop-appletsrc", false); //antix systems proc.exec("sed -i 's/%H:%M/%H:%M/g' " + skelpath + "/.icewm/preferences", false); proc.exec("sed -i 's/%k:%M/%k:%M/g' " + skelpath + "/.fluxbox/init", false); proc.exec("sed -i 's/%k:%M/%k:%M/g' " + skelpath + "/.jwm/tray", false); } // localize repo qDebug() << "Localize repo"; if (oobe) proc.exec("localize-repo default"); else proc.exec("chroot /mnt/antiX localize-repo default"); } void MInstall::stashServices(bool save) { QTreeWidgetItemIterator it(treeServices); while (*it) { if ((*it)->parent() != nullptr) { (*it)->setCheckState(save?2:0, (*it)->checkState(save?0:2)); } ++it; } } void MInstall::setService(const QString &service, bool enabled) { qDebug() << "Set service:" << service << enabled; QString chroot, rootpath; if (!oobe) { chroot = "chroot /mnt/antiX "; rootpath = "/mnt/antiX"; } if (enabled) { proc.exec(chroot + "update-rc.d " + service + " defaults"); if (containsSystemD) proc.exec(chroot + "systemctl enable " + service); if (containsRunit) { QFile::remove(rootpath+"/etc/sv/" + service + "/down"); if (!QFile::exists(rootpath+"/etc/sv/" + service)) { proc.mkpath(rootpath+"/etc/sv/" + service); proc.exec(chroot + "ln -fs /etc/sv/" + service + " /etc/service/"); } } } else { proc.exec(chroot + "update-rc.d " + service + " remove"); if (containsSystemD) { proc.exec(chroot + "systemctl disable " + service); proc.exec(chroot + "systemctl mask " + service); } if (containsRunit) { if (!QFile::exists(rootpath+"/etc/sv/" + service)) { proc.mkpath(rootpath+"/etc/sv/" + service); proc.exec(chroot + "ln -fs /etc/sv/" + service + " /etc/service/"); } proc.exec(chroot + "touch /etc/sv/" + service + "/down"); } } } void MInstall::failUI(const QString &msg) { proc.log("FAILED Phase " + QString::number(phase) + " - " + msg); if (phase >= 0) { boxMain->setEnabled(false); QMessageBox::critical(this, windowTitle(), msg); updateCursor(Qt::WaitCursor); } } // logic displaying pages int MInstall::showPage(int curr, int next) { if (curr == Step::Disk && next > curr) { if (radioEntireDisk->isChecked()) { if (!automatic) { QString msg = tr("OK to format and use the entire disk (%1) for %2?"); if (!uefi) { DeviceItem *devit = partman.findDevice(comboDisk->currentData().toString()); if (devit && devit->size >= (2048LL*1073741824LL)) { msg += "\n\n" + tr("WARNING: The selected drive has a capacity of at least 2TB and must be formatted using GPT." " On some systems, a GPT-formatted disk will not boot."); return curr; } } int ans = QMessageBox::warning(this, windowTitle(), msg.arg(comboDisk->currentData().toString(), PROJECTNAME), QMessageBox::Yes, QMessageBox::No); if (ans != QMessageBox::Yes) return curr; // don't format - stop install } partman.clearAllUses(); partman.selectedDriveAuto()->layoutDefault(-1, boxEncryptAuto->isChecked()); if (!partman.composeValidate(true, PROJECTNAME)) { nextFocus = treePartitions; return curr; } return Step::Boot; } } else if (curr == Step::Partitions && next > curr) { if (!partman.composeValidate(automatic, PROJECTNAME)) { nextFocus = treePartitions; return curr; } if (!pretend && !saveHomeBasic()) { QMessageBox::critical(this, windowTitle(), tr("The data in /home cannot be preserved because" " the required information could not be obtained.")); return curr; } return Step::Boot; } else if (curr == Step::Boot && next > curr) { if (oem) return Step::Progress; return Step::Services + 1; } else if (curr == Step::UserAccounts && next > curr) { if (!validateUserInfo()) return curr; if (!haveOldHome) return Step::Progress; // Skip pageOldHome } else if (curr == Step::Network && next > curr) { if (!validateComputerName()) return curr; } else if (curr == Step::Network && next < curr) { // Backward return Step::Boot; // Skip pageServices } else if (curr == Step::Localization && next > curr) { if (!pretend && haveSnapshotUserAccounts) { return Step::Progress; // Skip pageUserAccounts and pageOldHome } } else if (curr == Step::OldHome && next < curr) { // Backward if (!pretend && haveSnapshotUserAccounts) { return Step::Localization; // Skip pageUserAccounts and pageOldHome } } else if (curr == Step::Progress && next < curr) { // Backward if (oem) return Step::Boot; if (!haveOldHome) { // skip pageOldHome if (!pretend && haveSnapshotUserAccounts) return Step::Localization; return Step::UserAccounts; } } else if (curr == Step::Services) { // Backward or forward stashServices(next > curr); return Step::Localization; // The page that called pageServices } return next; } void MInstall::pageDisplayed(int next) { if (!oobe) { const int ixProgress = widgetStack->indexOf(pageProgress); // progress bar shown only for install and configuration pages. boxInstall->setVisible(next >= widgetStack->indexOf(pageBoot) && next <= ixProgress); // save the last tip and stop it updating when the progress page is hidden. if (next != ixProgress) ixTipStart = ixTip; } // These calculations are only for display text, and do not affect the installation. long long rootMin = partman.rootSpaceNeeded + 1048575; const QString &tminroot = QLocale::system().formattedDataSize(rootMin, 0, QLocale::DataSizeTraditionalFormat); rootMin = (4 * rootMin) + ROOT_BUFFER * 1048576; // (Root + snapshot [squashfs + ISO] + backup) + buffer. const QString &trecroot = QLocale::system().formattedDataSize(rootMin, 0, QLocale::DataSizeTraditionalFormat); switch (next) { case Step::Terms: textHelp->setText("<p><b>" + tr("General Instructions") + "</b><br/>" + tr("BEFORE PROCEEDING, CLOSE ALL OTHER APPLICATIONS.") + "</p>" "<p>" + tr("On each page, please read the instructions, make your selections, and then click on Next when you are ready to proceed." " You will be prompted for confirmation before any destructive actions are performed.") + "</p>" + "<p><b>" + tr("Limitations") + "</b><br/>" + tr("Remember, this software is provided AS-IS with no warranty what-so-ever." " It is solely your responsibility to backup your data before proceeding.") + "</p>"); pushNext->setDefault(true); break; case Step::Disk: textHelp->setText("<p><b>" + tr("Installation Options") + "</b><br/>" + tr("Installation requires about %1 of space. %2 or more is preferred.").arg(tminroot, trecroot) + "</p>" "<p>" + tr("If you are running Mac OS or Windows OS (from Vista onwards), you may have to use that system's software to set up partitions and boot manager before installing.") + "</p>" "<p><b>" + tr("Using the root-home space slider") + "</b><br/>" + tr("The drive can be divided into separate system (root) and user data (home) partitions using the slider.") + "</p>" "<p>" + tr("The <b>root</b> partition will contain the operating system and applications.") + "<br/>" + tr("The <b>home</b> partition will contain the data of all users, such as their settings, files, documents, pictures, music, videos, etc.") + "</p>" "<p>" + tr("Move the slider to the right to increase the space for <b>root</b>. Move it to the left to increase the space for <b>home</b>.") + "<br/>" + tr("Move the slider all the way to the right if you want both root and home on the same partition.") + "</p>" "<p>" + tr("Keeping the home directory in a separate partition improves the reliability of operating system upgrades. It also makes backing up and recovery easier." " This can also improve overall performance by constraining the system files to a defined portion of the drive.") + "</p>" "<p><b>" + tr("Encryption") + "</b><br/>" + tr("Encryption is possible via LUKS. A password is required.") + "</p>" "<p>" + tr("A separate unencrypted boot partition is required.") + "</p>" "<p>" + tr("When encryption is used with autoinstall, the separate boot partition will be automatically created.") + "</p>" "<p><b>" + tr("Using a custom disk layout") + "</b><br/>" + tr("If you need more control over where %1 is installed to, select \"<b>%2</b>\" and click <b>Next</b>." " On the next page, you will then be able to select and configure the storage devices and" " partitions you need.").arg(PROJECTNAME, radioCustomPart->text().remove('&')) + "</p>"); if (phase < 0) { updateCursor(Qt::WaitCursor); phase = 0; proc.unhalt(); updatePartitionWidgets(true); updateCursor(); } pushBack->setEnabled(true); pushNext->setEnabled(radioCustomPart->isChecked() || !boxEncryptAuto->isChecked() || textCryptoPass->isValid()); return; // avoid the end that enables both Back and Next buttons case Step::Partitions: textHelp->setText("<p><b>" + tr("Choose Partitions") + "</b><br/>" + tr("The partition list allows you to choose what partitions are used for this installation.") + "</p>" "<p>" + tr("<i>Device</i> - This is the block device name that is, or will be, assigned to the created partition.") + "</p>" "<p>" + tr("<i>Size</i> - The size of the partition. This can only be changed on a new layout.") + "</p>" "<p>" + tr("<i>Use For</i> - To use this partition in an installation, you must select something here.") + "<br/>" " - " + tr("Format - Format without mounting.") + "<br/>" " - " + tr("BIOS-GRUB - BIOS Boot GPT partition for GRUB.") + "<br/>" " - " + tr("EFI - EFI System Partition.") + "<br/>" " - " + tr("boot - Boot manager (/boot).") + "<br/>" " - " + tr("root - System root (/).") + "<br/>" " - " + tr("swap - Swap space.") + "<br/>" " - " + tr("home - User data (/home).") + "<br/>" + tr("In addition to the above, you can also type your own mount point. Custom mount points must start with a slash (\"/\").") + "<br/>" + tr("The installer treats \"/boot\", \"/\", and \"/home\" exactly the same as \"boot\", \"root\", and \"home\", respectively.") + "</p>" "<p>" + tr("<i>Label</i> - The label that is assigned to the partition once it has been formatted.") + "</p>" "<p>" + tr("<i>Encrypt</i> - Use LUKS encryption for this partition. The password applies to all partitions selected for encryption.") + "</p>" "<p>" + tr("<i>Format</i> - This is the partition's format. Available formats depend on what the partition is used for." " When working with an existing layout, you may be able to preserve the format of the partition by selecting <b>Preserve</b>.") + "<br/>" + tr("Selecting <b>Preserve /home</b> for the root partition preserves the contents of the /home directory, deleting everything else." " This option can only be used when /home is on the same partition as the root.") + "</p>" "<p>" + tr("The ext2, ext3, ext4, jfs, xfs, btrfs and reiserfs Linux filesystems are supported and ext4 is recommended.") + "</p>" "<p>" + tr("<i>Check</i> - Check and correct for bad blocks on the drive (not supported for all formats)." " This is very time consuming, so you may want to skip this step unless you suspect that your drive has bad blocks.") + "</p>" "<p>" + tr("<i>Mount Options</i> - This specifies mounting options that will be used for this partition.") + "</p>" "<p>" + tr("<i>Dump</i> - Instructs the dump utility to include this partition in the backup.") + "</p>" "<p>" + tr("<i>Pass</i> - The sequence in which this file system is to be checked at boot. If zero, the file system is not checked.") + "</p>" "<p><b>" + tr("Menus and actions") + "</b><br/>" + tr("A variety of actions are available by right-clicking any drive or partition item in the list.") + "<br/>" + tr("The buttons to the right of the list can also be used to manipulate the entries.") + "</p>" "<p>" + tr("The installer cannot modify the layout already on the drive." " To create a custom layout, mark the drive for a new layout with the <b>New layout</b> menu action" " or button (%1). This clears the existing layout.").arg("<img src=':/edit-clear-all'/>") + "</p>" "<p><b>" + tr("Basic layout requirements") + "</b><br/>" + tr("%1 requires a root partition. The swap partition is optional but highly recommended." " If you want to use the Suspend-to-Disk feature of %1, you will need a swap partition that is larger than your physical memory size.").arg(PROJECTNAME) + "</p>" "<p>" + tr("If you choose a separate /home partition it will be easier for you to upgrade in the future," " but this will not be possible if you are upgrading from an installation that does not have a separate home partition.") + "</p>" "<p><b>" + tr("Active partition") + "</b><br/>" + tr("For the installed operating system to boot, the appropriate partition (usually the boot or root partition) must be the marked as active.") + "</p>" "<p>" + tr("The active partition of a drive can be chosen using the <b>Active partition</b> menu action.") + "<br/>" + tr("A partition with an asterisk (*) next to its device name is, or will become, the active partition.") + "</p>" "<p><b>" + tr("Boot partition") + "</b><br/>" + tr("This partition is generally only required for root partitions on virtual devices such as encrypted, LVM or software RAID volumes.") + "<br/>" + tr("It contains a basic kernel and drivers used to access the encrypted disk or virtual devices.") + "</p>" "<p><b>" + tr("BIOS-GRUB partition") + "</b><br/>" + tr("When using a GPT-formatted drive on a non-EFI system, a 1MB BIOS boot partition is required when using GRUB.") + "<br/>" + tr("New drives are formatted in GPT if more than 4 partitions are to be created, or the drive has a capacity greater than 2TB." " If the installer is about to format the disk in GPT, and there is no BIOS-GRUB partition, a warning will be displayed before the installation starts.") + "</p>" "<p><b>" + tr("Need help creating a layout?") + "</b><br/>" + tr("Just right-click on a drive to bring up a menu, and select a layout template. These layouts are similar to that of the regular install.") + "</p>" "<p>" + tr("<i>Standard install</i> - Suited to most setups. This template does not add a separate boot partition, and so it is unsuitable for use with an encrypted operating system.") + "</p>" "<p>" + tr("<i>Encrypted system</i> - Contains the boot partition required to load an encrypted operating system. This template can also be used as the basis for a multi-boot system.") + "</p>" "<p><b>" + tr("Upgrading") + "</b><br/>" + tr("To upgrade from an existing Linux installation, select the same home partition as before and select <b>Preserve</b> as the format.") + "</p>" "<p>" + tr("If you do not use a separate home partition, select <b>Preserve /home</b> on the root file system entry to preserve the existing /home directory located on your root partition." " The installer will only preserve /home, and will delete everything else. As a result, the installation will take much longer than usual.") + "</p>" "<p><b>" + tr("Preferred Filesystem Type") + "</b><br/>" + tr("For %1, you may choose to format the partitions as ext2, ext3, ext4, f2fs, jfs, xfs, btrfs or reiser.").arg(PROJECTNAME) + "</p>" "<p>" + tr("Additional compression options are available for drives using btrfs." " Lzo is fast, but the compression is lower. Zlib is slower, with higher compression.") + "</p>" "<p><b>" + tr("System partition management tool") + "</b><br/>" + tr("For more control over the drive layouts (such as modifying the existing layout on a disk), click the" " partition management button (%1). This will run the operating system's partition management tool," " which will allow you to create the exact layout you need.").arg("<img src=':/partitionmanager'/>") + "</p>" "<p><b>" + tr("Encryption") + "</b><br/>" + tr("Encryption is possible via LUKS. A password is required.") + "</p>" "<p>" + tr("A separate unencrypted boot partition is required.") + "</p>" "<p>" + tr("To preserve an encrypted partition, right-click on it and select <b>Unlock</b>. In the dialog that appears, enter a name for the virtual device and the password." " When the device is unlocked, the name you chose will appear under <i>Virtual Devices</i>, with similar options to that of a regular partition.") + "</p><p>" + tr("For the encrypted partition to be unlocked at boot, it needs to be added to the crypttab file. Use the <b>Add to crypttab</b> menu action to do this.") + "</p>" "<p><b>" + tr("Other partitions") + "</b><br/>" + tr("The installer allows other partitions to be created or used for other purposes, however be mindful that older systems cannot handle drives with more than 4 partitions.") + "</p>" "<p><b>" + tr("Subvolumes") + "</b><br/>" + tr("Some file systems, such as Btrfs, support multiple subvolumes in a single partition." " These are not physical subdivisions, and so their order does not matter.") + "<br/>" + tr("Use the <b>Scan subvolumes</b> menu action to search an existing Btrfs partition for subvolumes." " To create a new subvolume, use the <b>New subvolume</b> menu action.") + "</p><p>" + tr("Existing subvolumes can be preserved, however the name must remain the same.") + "</p>" "<p><b>" + tr("Virtual Devices") + "</b><br/>" + tr("If the intaller detects any virtual devices such as opened LUKS partitions, LVM logical volumes or software-based RAID volumes, they may be used for the installation.") + "</p>" "<p>" + tr("The use of virtual devices (beyond preserving encrypted file systems) is an advanced feature. You may have to edit some files (eg. initramfs, crypttab, fstab) to ensure the virtual devices used are created upon boot.") + "</p>"); pushBack->setEnabled(true); pushNext->setEnabled(!(boxCryptoPass->isEnabledTo(boxCryptoPass->parentWidget())) || textCryptoPassCust->isValid()); return; // avoid the end that enables both Back and Next buttons case Step::Boot: // Start of installation. textHelp->setText(tr("<p><b>Select Boot Method</b><br/> %1 uses the GRUB bootloader to boot %1 and MS-Windows. " "<p>By default GRUB2 is installed in the Master Boot Record (MBR) or ESP (EFI System Partition for 64-bit UEFI boot systems) of your boot drive and replaces the boot loader you were using before. This is normal.</p>" "<p>If you choose to install GRUB2 to Partition Boot Record (PBR) instead, then GRUB2 will be installed at the beginning of the specified partition. This option is for experts only.</p>" "<p>If you uncheck the Install GRUB box, GRUB will not be installed at this time. This option is for experts only.</p>").arg(PROJECTNAME)); pushBack->setEnabled(false); pushNext->setEnabled(true); if (phase <= 0) { buildBootLists(); manageConfig(ConfigLoadB); } return; // avoid the end that enables both Back and Next buttons case Step::Services: textHelp->setText(tr("<p><b>Common Services to Enable</b><br/>Select any of these common services that you might need with your system configuration and the services will be started automatically when you start %1.</p>").arg(PROJECTNAME)); break; case Step::Network: textHelp->setText(tr("<p><b>Computer Identity</b><br/>The computer name is a common unique name which will identify your computer if it is on a network. " "The computer domain is unlikely to be used unless your ISP or local network requires it.</p>" "<p>The computer and domain names can contain only alphanumeric characters, dots, hyphens. They cannot contain blank spaces, start or end with hyphens</p>" "<p>The SaMBa Server needs to be activated if you want to use it to share some of your directories or printer " "with a local computer that is running MS-Windows or Mac OSX.</p>")); if (oobe) { pushBack->setEnabled(false); pushNext->setEnabled(true); return; // avoid the end that enables both Back and Next buttons } break; case Step::Localization: textHelp->setText("<p><b>" + tr("Localization Defaults") + "</b><br/>" + tr("Set the default locale. This will apply unless they are overridden later by the user.") + "</p>" "<p><b>" + tr("Configure Clock") + "</b><br/>" + tr("If you have an Apple or a pure Unix computer, by default the system clock is set to Greenwich Meridian Time (GMT) or Coordinated Universal Time (UTC)." " To change this, check the \"<b>System clock uses local time</b>\" box.") + "</p>" "<p>" + tr("The system boots with the timezone preset to GMT/UTC." " To change the timezone, after you reboot into the new installation, right click on the clock in the Panel and select Properties.") + "</p>" "<p><b>" + tr("Service Settings") + "</b><br/>" + tr("Most users should not change the defaults." " Users with low-resource computers sometimes want to disable unneeded services in order to keep the RAM usage as low as possible." " Make sure you know what you are doing!")); break; case Step::UserAccounts: textHelp->setText("<p><b>" + tr("Default User Login") + "</b><br/>" + tr("The root user is similar to the Administrator user in some other operating systems." " You should not use the root user as your daily user account." " Please enter the name for a new (default) user account that you will use on a daily basis." " If needed, you can add other user accounts later with %1 User Manager.").arg(PROJECTNAME) + "</p>" "<p><b>" + tr("Passwords") + "</b><br/>" + tr("Enter a new password for your default user account and for the root account." " Each password must be entered twice.") + "</p>" "<p><b>" + tr("No passwords") + "</b><br/>" + tr("If you want the default user account to have no password, leave its password fields empty." " This allows you to log in without requiring a password.") + "<br/>" + tr("Obviously, this should only be done in situations where the user account" " does not need to be secure, such as a public terminal.") + "</p>"); if (!nextFocus) nextFocus = textUserName; pushBack->setEnabled(true); userPassValidationChanged(); return; // avoid the end that enables both Back and Next buttons case Step::OldHome: textHelp->setText("<p><b>" + tr("Old Home Directory") + "</b><br/>" + tr("A home directory already exists for the user name you have chosen." " This screen allows you to choose what happens to this directory.") + "</p>" "<p><b>" + tr("Re-use it for this installation") + "</b><br/>" + tr("The old home directory will be used for this user account." " This is a good choice when upgrading, and your files and settings will be readily available.") + "</p>" "<p><b>" + tr("Rename it and create a new directory") + "</b><br/>" + tr("A new home directory will be created for the user, but the old home directory will be renamed." " Your files and settings will not be immediately visible in the new installation, but can be accessed using the renamed directory.") + "</p>" "<p>" + tr("The old directory will have a number at the end of it, depending on how many times the directory has been renamed before.") + "</p>" "<p><b>" + tr("Delete it and create a new directory") + +"</b><br/>" + tr("The old home directory will be deleted, and a new one will be created from scratch.") + "<br/>" "<b>" + tr("Warning") + "</b>: " + tr("All files and settings will be deleted permanently if this option is selected." " Your chances of recovering them are low.") + "</p>"); // disable the Next button if none of the old home options are selected on_radioOldHomeUse_toggled(false); // if the Next button is disabled, avoid enabling both Back and Next at the end if (pushNext->isEnabled() == false) { pushBack->setEnabled(true); return; } break; case Step::Progress: if (ixTipStart >= 0) { iLastProgress = progInstall->value(); on_progInstall_valueChanged(iLastProgress); } textHelp->setText("<p><b>" + tr("Installation in Progress") + "</b><br/>" + tr("%1 is installing. For a fresh install, this will probably take 3-20 minutes, depending on the speed of your system and the size of any partitions you are reformatting.").arg(PROJECTNAME) + "</p><p>" + tr("If you click the Abort button, the installation will be stopped as soon as possible.") + "</p><p>" + "<b>" + tr("Change settings while you wait") + "</b><br/>" + tr("While %1 is being installed, you can click on the <b>Next</b> or <b>Back</b> buttons to enter other information required for the installation.").arg(PROJECTNAME) + "</p><p>" + tr("Complete these steps at your own pace. The installer will wait for your input if necessary.") + "</p>"); pushBack->setEnabled(true); pushNext->setEnabled(false); return; // avoid enabling both Back and Next buttons at the end case Step::End: pushClose->setEnabled(false); textHelp->setText(tr("<p><b>Congratulations!</b><br/>You have completed the installation of %1</p>" "<p><b>Finding Applications</b><br/>There are hundreds of excellent applications installed with %1 " "The best way to learn about them is to browse through the Menu and try them. " "Many of the apps were developed specifically for the %1 project. " "These are shown in the main menus. " "<p>In addition %1 includes many standard Linux applications that are run only from the command line and therefore do not show up in the Menu.</p>").arg(PROJECTNAME)); break; default: // other textHelp->setText("<p><b>" + tr("Enjoy using %1</b></p>").arg(PROJECTNAME) + "\n\n " + tr("<p><b>Support %1</b><br/>" "%1 is supported by people like you. Some help others at the " "support forum - %2 - or translate help files into different " "languages, or make suggestions, write documentation, or help test new software.</p>").arg(PROJECTNAME).arg(PROJECTFORUM)); pushNext->setDefault(true); break; } pushBack->setEnabled(true); pushNext->setEnabled(true); } void MInstall::gotoPage(int next) { pushBack->setEnabled(false); pushNext->setEnabled(false); widgetStack->setEnabled(false); int curr = widgetStack->currentIndex(); next = showPage(curr, next); // modify ui for standard cases pushClose->setHidden(next == 0); pushBack->setHidden(next <= 1); pushNext->setHidden(next == 0); QSize isize = pushNext->iconSize(); isize.setWidth(isize.height()); if (next >= Step::End) { // entering the last page pushBack->hide(); pushNext->setText(tr("Finish")); } else if (next == Step::Services){ isize.setWidth(0); pushNext->setText(tr("OK")); } else { pushNext->setText(tr("Next")); } pushNext->setIconSize(isize); if (next > Step::End) { // finished updateCursor(Qt::WaitCursor); if (!pretend && checkExitReboot->isChecked()) { proc.exec("/usr/local/bin/persist-config --shutdown --command reboot &", false); } qApp->exit(EXIT_SUCCESS); return; } // display the next page widgetStack->setCurrentIndex(next); qApp->processEvents(); // anything to do after displaying the page pageDisplayed(next); widgetStack->setEnabled(true); if (nextFocus) { nextFocus->setFocus(); nextFocus = nullptr; } // automatic installation if (automatic) { if (!MSettings::isBadWidget(widgetStack->currentWidget()) && next > curr) pushNext->click(); else if (curr!=0) automatic = false; // failed validation } // process next installation phase if (next == widgetStack->indexOf(pageBoot) || next == widgetStack->indexOf(pageProgress)) { if (oobe) { updateCursor(Qt::BusyCursor); labelSplash->setText(tr("Configuring sytem. Please wait.")); gotoPage(Step::Splash); if (processOOBE()) { labelSplash->setText(tr("Configuration complete. Restarting system.")); proc.exec("/usr/sbin/reboot", true); qApp->exit(EXIT_SUCCESS); } else { labelSplash->setText(tr("Could not complete configuration.")); pushClose->show(); } } else if (!processNextPhase() && phase > -2) { cleanup(false); gotoPage(Step::Disk); boxMain->setEnabled(true); } updateCursor(); } } void MInstall::updatePartitionWidgets(bool all) { proc.log(__PRETTY_FUNCTION__); comboDisk->setEnabled(false); comboDisk->clear(); comboDisk->addItem(tr("Loading...")); partman.scan(); if (mactest) { for (DeviceItemIterator it(partman); DeviceItem *item = *it; it.next()) { if (item->device.startsWith("sda")) { item->flags.nasty = true; partman.notifyChange(item); } } } // disk combo box comboDisk->clear(); for (DeviceItemIterator it(partman); DeviceItem *item = *it; it.next()) { if (item->type == DeviceItem::Drive && item->size >= partman.rootSpaceNeeded && (!item->flags.bootRoot || INSTALL_FROM_ROOT_DEVICE)) { item->addToCombo(comboDisk); } } comboDisk->setCurrentIndex(0); comboDisk->setEnabled(true); if (all) { // whole-disk vs custom-partition radio buttons radioEntireDisk->setChecked(true); for (DeviceItemIterator it(partman); *it; it.next()) { if ((*it)->isVolume()) { // found at least one partition radioCustomPart->setChecked(true); break; } } } // Partition slider. setupPartitionSlider(); } void MInstall::setupPartitionSlider() { // Allow the slider labels to fit all possible formatted sizes. const QString &strMB = sliderSizeString(1072693248) + '\n'; // "1,023 GB" const QFontMetrics &fmetrics = labelSliderRoot->fontMetrics(); int mwidth = fmetrics.boundingRect(QRect(), Qt::AlignCenter, strMB + tr("Root")).width(); labelSliderRoot->setMinimumWidth(mwidth); mwidth = fmetrics.boundingRect(QRect(), Qt::AlignCenter, strMB + tr("Home")).width(); labelSliderHome->setMinimumWidth(mwidth); labelSliderRoot->setText("----"); labelSliderHome->setText("----"); // Snap the slider to the legal range. on_sliderPart_valueChanged(sliderPart->value()); } void MInstall::buildServiceList() { //setup treeServices treeServices->header()->setMinimumSectionSize(150); treeServices->header()->resizeSection(0,150); QSettings services_desc("/usr/share/gazelle-installer-data/services.list", QSettings::NativeFormat); for (const QString &service : qAsConst(ENABLE_SERVICES)) { const QString &lang = QLocale::system().bcp47Name().toLower(); QString lang_str = (lang == "en")? "" : "_" + lang; QStringList list = services_desc.value(service + lang_str).toStringList(); if (list.size() != 2) { list = services_desc.value(service).toStringList(); // Use English definition if (list.size() != 2) continue; } QString category, description; category = list.at(0); description = list.at(1); if (QFile::exists("/etc/init.d/"+service) || QFile::exists("/etc/sv/"+service)) { QList<QTreeWidgetItem *> found_items = treeServices->findItems(category, Qt::MatchExactly, 0); QTreeWidgetItem *top_item; QTreeWidgetItem *item; QTreeWidgetItem *parent; if (found_items.size() == 0) { // add top item if no top items found top_item = new QTreeWidgetItem(treeServices); top_item->setText(0, category); parent = top_item; } else { parent = found_items.last(); } item = new QTreeWidgetItem(parent); item->setText(0, service); item->setText(1, description); item->setCheckState(0, Qt::Checked); } } treeServices->expandAll(); treeServices->resizeColumnToContents(0); treeServices->resizeColumnToContents(1); } ///////////////////////////////////////////////////////////////////////// // event handlers void MInstall::changeEvent(QEvent *event) { const QEvent::Type etype = event->type(); if (etype == QEvent::ApplicationPaletteChange || etype == QEvent::PaletteChange || etype == QEvent::StyleChange) { QPalette pal = qApp->palette(textHelp); QColor col = pal.color(QPalette::Base); col.setAlpha(200); pal.setColor(QPalette::Base, col); textHelp->setPalette(pal); setupPartitionSlider(); resizeEvent(nullptr); } } void MInstall::resizeEvent(QResizeEvent *) { textHelp->resize(tabHelp->size()); labelHelpBackdrop->resize(textHelp->size()); } void MInstall::closeEvent(QCloseEvent *event) { if (abort(true)) { event->accept(); if (!oobe) cleanup(); else if (!pretend) { proc.unhalt(); proc.exec("/usr/sbin/shutdown -hP now"); } QWidget::closeEvent(event); if (widgetStack->currentWidget() != pageEnd) { qApp->exit(EXIT_FAILURE); } else { proc.waitForFinished(); qApp->exit(EXIT_SUCCESS); } } else { event->ignore(); } } void MInstall::reject() { // dummy (overrides QDialog::reject() so Escape won't close the window) } ///////////////////////////////////////////////////////////////////////// // slots void MInstall::on_splitter_splitterMoved(int, int) { resizeEvent(nullptr); } void MInstall::on_tabsMain_currentChanged(int index) { // Make the help widgets the correct size. if (index == 0) resizeEvent(nullptr); } void MInstall::diskPassValidationChanged(bool valid) { pushNext->setEnabled(valid); } void MInstall::userPassValidationChanged() { bool ok = !textUserName->text().isEmpty(); if (ok) ok = textUserPass->isValid() || textUserName->text().isEmpty(); if (ok && boxRootAccount->isChecked()) { ok = textRootPass->isValid() || textRootPass->text().isEmpty(); } pushNext->setEnabled(ok); } void MInstall::on_pushNext_clicked() { gotoPage(widgetStack->currentIndex() + 1); } void MInstall::on_pushBack_clicked() { gotoPage(widgetStack->currentIndex() - 1); } void MInstall::on_pushAbort_clicked() { abort(false); QApplication::beep(); } // clicking advanced button to go to Services page void MInstall::on_pushServices_clicked() { gotoPage(Step::Services); } void MInstall::on_pushPartReload_clicked() { updateCursor(Qt::WaitCursor); boxMain->setEnabled(false); updatePartitionWidgets(false); boxMain->setEnabled(true); updateCursor(); } void MInstall::on_pushRunPartMan_clicked() { updateCursor(Qt::WaitCursor); boxMain->setEnabled(false); if (QFile::exists("/usr/sbin/gparted")) proc.exec("/usr/sbin/gparted", true); else proc.exec("/usr/bin/partitionmanager", true); updatePartitionWidgets(false); boxMain->setEnabled(true); updateCursor(); } bool MInstall::abort(bool onclose) { proc.log(__PRETTY_FUNCTION__); boxMain->setEnabled(false); // ask for confirmation when installing (except for some steps that don't need confirmation) if (phase > 0 && phase < 4) { const QMessageBox::StandardButton rc = QMessageBox::warning(this, tr("Confirmation"), tr("The installation and configuration" " is incomplete.\nDo you really want to stop now?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (rc == QMessageBox::No) { boxMain->setEnabled(true); return false; } } updateCursor(Qt::WaitCursor); proc.halt(); // help the installer if it was stuck at the config pages if (onclose) { phase = -2; } else if (phase == 2 && widgetStack->currentWidget() != pageProgress) { phase = -1; gotoPage(Step::Disk); } else { phase = -1; } if (!onclose) boxMain->setEnabled(true); return true; } // run before closing the app, do some cleanup void MInstall::cleanup(bool endclean) { proc.log(__PRETTY_FUNCTION__); if (pretend) return; proc.unhalt(); if (endclean) { setupAutoMount(true); proc.exec("/bin/cp /var/log/minstall.log /mnt/antiX/var/log >/dev/null 2>&1", false); proc.exec("/bin/rm -rf /mnt/antiX/mnt/antiX >/dev/null 2>&1", false); } proc.exec("/bin/umount -l /mnt/antiX/boot/efi", true); proc.exec("/bin/umount -l /mnt/antiX/proc", true); proc.exec("/bin/umount -l /mnt/antiX/sys", true); proc.exec("/bin/umount -l /mnt/antiX/dev/shm", true); proc.exec("/bin/umount -l /mnt/antiX/dev", true); if (!mountkeep) partman.unmount(); } void MInstall::on_progInstall_valueChanged(int value) { if (ixTipStart < 0 || widgetStack->currentWidget() != pageProgress) return; // no point displaying a new hint if it will be invisible const int tipcount = 6; ixTip = tipcount; if (ixTipStart < tipcount) { int imax = (progInstall->maximum() - iLastProgress) / (tipcount - ixTipStart); if (imax != 0) ixTip = ixTipStart + (value - iLastProgress) / imax; } switch(ixTip) { case 0: textTips->setText(tr("<p><b>Getting Help</b><br/>" "Basic information about %1 is at %2.</p><p>" "There are volunteers to help you at the %3 forum, %4</p>" "<p>If you ask for help, please remember to describe your problem and your computer " "in some detail. Usually statements like 'it didn't work' are not helpful.</p>").arg(PROJECTNAME).arg(PROJECTURL).arg(PROJECTSHORTNAME).arg(PROJECTFORUM)); break; case 1: textTips->setText(tr("<p><b>Repairing Your Installation</b><br/>" "If %1 stops working from the hard drive, sometimes it's possible to fix the problem by booting from LiveDVD or LiveUSB and running one of the included utilities in %1 or by using one of the regular Linux tools to repair the system.</p>" "<p>You can also use your %1 LiveDVD or LiveUSB to recover data from MS-Windows systems!</p>").arg(PROJECTNAME)); break; case 2: textTips->setText(tr("<p><b>Support %1</b><br/>" "%1 is supported by people like you. Some help others at the " "support forum - %2 - or translate help files into different " "languages, or make suggestions, write documentation, or help test new software.</p>").arg(PROJECTNAME).arg(PROJECTFORUM)); break; case 3: textTips->setText(tr("<p><b>Adjusting Your Sound Mixer</b><br/>" " %1 attempts to configure the sound mixer for you but sometimes it will be " "necessary for you to turn up volumes and unmute channels in the mixer " "in order to hear sound.</p> " "<p>The mixer shortcut is located in the menu. Click on it to open the mixer. </p>").arg(PROJECTNAME)); break; case 4: textTips->setText(tr("<p><b>Keep Your Copy of %1 up-to-date</b><br/>" "For more information and updates please visit</p><p> %2</p>").arg(PROJECTNAME).arg(PROJECTFORUM)); break; default: textTips->setText(tr("<p><b>Special Thanks</b><br/>Thanks to everyone who has chosen to support %1 with their time, money, suggestions, work, praise, ideas, promotion, and/or encouragement.</p>" "<p>Without you there would be no %1.</p>" "<p>%2 Dev Team</p>").arg(PROJECTNAME).arg(PROJECTSHORTNAME)); break; } } void MInstall::on_pushClose_clicked() { close(); } void MInstall::setupkeyboardbutton() { QFile file("/etc/default/keyboard"); if (file.open(QFile::ReadOnly | QFile::Text)) { while (!file.atEnd()) { QString line(file.readLine().trimmed()); QLabel *plabel = nullptr; if (line.startsWith("XKBMODEL")) plabel = labelKeyboardModel; else if (line.startsWith("XKBLAYOUT")) plabel = labelKeyboardLayout; else if (line.startsWith("XKBVARIANT")) plabel = labelKeyboardVariant; if (plabel != nullptr) { line = line.section('=', 1); line.replace(",", " "); line.remove(QChar('"')); plabel->setText(line); } } file.close(); } } void MInstall::on_pushSetKeyboard_clicked() { hide(); if (proc.exec("command -v system-keyboard-qt >/dev/null 2>&1", false)) proc.exec("system-keyboard-qt", false); else proc.exec("env GTK_THEME='Adwaita' fskbsetting", false); show(); setupkeyboardbutton(); } void MInstall::on_comboDisk_currentIndexChanged(int) { on_sliderPart_valueChanged(sliderPart->value()); } void MInstall::on_sliderPart_sliderPressed() { QString tipText(tr("%1% root\n%2% home")); const int val = sliderPart->value(); if (val==100) tipText = tr("Combined root and home"); else if (val<1) tipText = tipText.arg(">0", "<100"); else tipText = tipText.arg(val).arg(100-val); sliderPart->setToolTip(tipText); if (sliderPart->isSliderDown()) QToolTip::showText(QCursor::pos(), tipText, sliderPart); } void MInstall::on_sliderPart_valueChanged(int value) { const bool crypto = boxEncryptAuto->isChecked(); DeviceItem *drvitem = partman.selectedDriveAuto(); if (!drvitem) return; long long available = drvitem->layoutDefault(100, crypto, false); if (!available) return; const long long roundUp = available - 1; const long long rootMinMB = (partman.rootSpaceNeeded + 1048575) / 1048576; const long long homeMinMB = 16; // 16MB for basic profile and setup files const long long rootRecMB = (4 * rootMinMB) + ROOT_BUFFER; // (Root + snapshot [squashfs + ISO] + backup) + buffer const long long homeRecMB = homeMinMB + HOME_BUFFER; const int minPercent = ((rootMinMB * 100) + roundUp) / available; const int maxPercent = 100 - (((homeMinMB * 100) + roundUp) / available); const int recPercentMin = ((rootRecMB * 100) + roundUp) / available; // Recommended root size. const int recPercentMax = 100 - (((homeRecMB * 100) + roundUp) / available); // Recommended minimum home. const int origValue = value; if (value < minPercent) value = minPercent; else if (value > maxPercent) value = 100; if (value != origValue) { qApp->beep(); sliderPart->blockSignals(true); sliderPart->setValue(value); sliderPart->blockSignals(false); } const long long availRoot = drvitem->layoutDefault(value, crypto, false); QString valstr = sliderSizeString(availRoot*1048576); available -= availRoot; labelSliderRoot->setText(valstr + "\n" + tr("Root")); QPalette palRoot = QApplication::palette(); QPalette palHome = QApplication::palette(); if (value < recPercentMin) palRoot.setColor(QPalette::WindowText, Qt::red); if (value==100) valstr = tr("----"); else { valstr = sliderSizeString(available*1048576); valstr += "\n" + tr("Home"); if (value > recPercentMax) palHome.setColor(QPalette::WindowText, Qt::red); } labelSliderHome->setText(valstr); labelSliderRoot->setPalette(palRoot); labelSliderHome->setPalette(palHome); on_sliderPart_sliderPressed(); // For the tool tip. } void MInstall::on_boxEncryptAuto_toggled(bool checked) { pushNext->setEnabled(!checked || textCryptoPass->isValid()); radioBootPBR->setDisabled(checked); // Account for addition/removal of the boot partition. on_sliderPart_valueChanged(sliderPart->value()); } void MInstall::on_radioCustomPart_toggled(bool checked) { if (checked) pushNext->setEnabled(true); else on_boxEncryptAuto_toggled(boxEncryptAuto->isChecked()); } void MInstall::on_radioBootMBR_toggled() { comboBoot->clear(); for (DeviceItemIterator it(partman); DeviceItem *item = *it; it.next()) { if (item->type == DeviceItem::Drive && (!item->flags.bootRoot || INSTALL_FROM_ROOT_DEVICE)) { if (!item->flags.nasty || brave) item->addToCombo(comboBoot, true); } } selectBootMain(); labelBoot->setText(tr("System boot disk:")); } void MInstall::on_radioBootPBR_toggled() { comboBoot->clear(); for (DeviceItemIterator it(partman); DeviceItem *item = *it; it.next()) { if (item->type == DeviceItem::Partition && (!item->flags.bootRoot || INSTALL_FROM_ROOT_DEVICE)) { if (item->realUseFor() == "ESP") continue; else if (!item->format.compare("SWAP", Qt::CaseInsensitive)) continue; else if (item->format == "crypto_LUKS") continue; else if (item->format.isEmpty() || item->format == "PRESERVE") { if (item->curFormat == "crypto_LUKS") continue; if (!item->curFormat.compare("SWAP", Qt::CaseInsensitive)) continue; } if (!item->flags.nasty || brave) item->addToCombo(comboBoot, true); } } selectBootMain(); labelBoot->setText(tr("Partition to use:")); } void MInstall::on_radioBootESP_toggled() { comboBoot->clear(); for (DeviceItemIterator it(partman); DeviceItem *item = *it; it.next()) { if (item->realUseFor() == "ESP" && (!item->flags.bootRoot || INSTALL_FROM_ROOT_DEVICE)) { item->addToCombo(comboBoot); } } selectBootMain(); labelBoot->setText(tr("Partition to use:")); } void MInstall::selectBootMain() { const DeviceItem *twit = partman.mounts.value("/boot"); if (!twit) twit = partman.mounts.value("/"); if (twit->origin) twit = twit->origin; while (twit && twit->type != DeviceItem::Partition) twit = twit->parent(); if (!radioBootPBR->isChecked() && twit) twit = twit->parent(); if (!twit) return; int ixsel = comboBoot->findData(twit->device); // Boot drive or partition for(int ixi = 0; ixsel < 0 && ixi < comboBoot->count(); ++ixi) { const QStringList &s = DeviceItem::split(comboBoot->itemData(ixi).toString()); if (s.at(0) == twit->device) ixsel = ixi; // Partition on boot drive } if (ixsel >= 0) comboBoot->setCurrentIndex(ixsel); } // build ESP list available to install GRUB void MInstall::buildBootLists() { // refresh lists and enable or disable options according to device presence on_radioBootMBR_toggled(); const bool canMBR = (comboBoot->count() > 0); radioBootMBR->setEnabled(canMBR); on_radioBootPBR_toggled(); const bool canPBR = (comboBoot->count() > 0); radioBootPBR->setEnabled(canPBR); on_radioBootESP_toggled(); const bool canESP = (uefi && comboBoot->count() > 0); radioBootESP->setEnabled(canESP); // load one as the default in preferential order: ESP, MBR, PBR if (canESP) radioBootESP->setChecked(true); else if (canMBR) { on_radioBootMBR_toggled(); radioBootMBR->setChecked(true); } else if (canPBR) { on_radioBootPBR_toggled(); radioBootPBR->setChecked(true); } } void MInstall::on_comboLocale_currentIndexChanged(int index) { // riot control QLocale locale(comboLocale->itemData(index).toString()); if (locale.timeFormat().startsWith('h')) radioClock12->setChecked(true); else radioClock24->setChecked(true); } // return 0 = success, 1 = bad area, 2 = bad zone int MInstall::selectTimeZone(const QString &zone) { int index = comboTimeArea->findData(QVariant(zone.section('/', 0, 0))); if (index < 0) return 1; comboTimeArea->setCurrentIndex(index); qApp->processEvents(); index = comboTimeZone->findData(QVariant(zone)); if (index < 0) return 2; comboTimeZone->setCurrentIndex(index); return 0; } void MInstall::on_comboTimeArea_currentIndexChanged(int index) { if (index < 0 || index >= comboTimeArea->count()) return; const QString &area = comboTimeArea->itemData(index).toString(); comboTimeZone->clear(); for (const QString &zone : listTimeZones) { if (zone.startsWith(area)) { QString text(QString(zone).section('/', 1)); text.replace('_', ' '); comboTimeZone->addItem(text, QVariant(zone)); } } comboTimeZone->model()->sort(0); } void MInstall::on_radioOldHomeUse_toggled(bool) { pushNext->setEnabled(radioOldHomeUse->isChecked() || radioOldHomeSave->isChecked() || radioOldHomeDelete->isChecked()); } void MInstall::on_radioOldHomeSave_toggled(bool) { on_radioOldHomeUse_toggled(false); } void MInstall::on_radioOldHomeDelete_toggled(bool) { on_radioOldHomeUse_toggled(false); } void MInstall::rsynchomefolder(QString dpath) { QString cmd = ("rsync -a --info=name1 /home/demo/ %1" " --exclude '.cache' --exclude '.gvfs' --exclude '.dbus' --exclude '.Xauthority' --exclude '.ICEauthority'" " --exclude '.mozilla' --exclude 'Installer.desktop' --exclude 'minstall.desktop' --exclude 'Desktop/antixsources.desktop'" " --exclude '.idesktop/gazelle.lnk' --exclude '.jwm/menu' --exclude '.icewm/menu' --exclude '.fluxbox/menu'" " --exclude '.config/rox.sourceforge.net/ROX-Filer/pb_antiX-fluxbox'" " --exclude '.config/rox.sourceforge.net/ROX-Filer/pb_antiX-icewm'" " --exclude '.config/rox.sourceforge.net/ROX-Filer/pb_antiX-jwm'" " --exclude '.config/session' | xargs -I '$' sed -i 's|home/demo|home/" + textUserName->text() + "|g' %1/$").arg(dpath); proc.exec(cmd); } void MInstall::changeRemasterdemoToNewUser(QString dpath) { QString cmd = ("find " + dpath + " -maxdepth 1 -type f -name '.*' -print0 | xargs -0 sed -i 's|home/demo|home/" + textUserName->text() + "|g'").arg(dpath); proc.exec(cmd); cmd = ("find " + dpath + "/.config -type f -print0 | xargs -0 sed -i 's|home/demo|home/" + textUserName->text() + "|g'").arg(dpath); proc.exec(cmd); cmd = ("find " + dpath + "/.local -type f -print0 | xargs -0 sed -i 's|home/demo|home/" + textUserName->text() + "|g'").arg(dpath); proc.exec(cmd); } void MInstall::resetBlueman() { proc.exec("runuser -l demo -c 'dconf reset /org/blueman/transfer/shared-path'"); //reset blueman path }
46.654391
282
0.593574
[ "object", "shape", "model" ]
d5090c33eefae0fef64efdbcd5d4696b71885ec1
17,762
cc
C++
modules/dreamview/backend/hmi/hmi.cc
fukatani/apollo
8677d8fd9d74e625c9dfaf184775d9e7cd24c8e2
[ "Apache-2.0" ]
1
2018-02-22T13:22:18.000Z
2018-02-22T13:22:18.000Z
modules/dreamview/backend/hmi/hmi.cc
LiuGuoJiang/apollo
ca0e14af13c06bc5ff9cc5b3200c06351a07ee1d
[ "Apache-2.0" ]
null
null
null
modules/dreamview/backend/hmi/hmi.cc
LiuGuoJiang/apollo
ca0e14af13c06bc5ff9cc5b3200c06351a07ee1d
[ "Apache-2.0" ]
1
2021-03-30T07:50:50.000Z
2021-03-30T07:50:50.000Z
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/dreamview/backend/hmi/hmi.h" #include <cstdlib> #include <thread> #include <vector> #include "gflags/gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/kv_db/kv_db.h" #include "modules/common/util/http_client.h" #include "modules/common/util/json_util.h" #include "modules/common/util/map_util.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/util/util.h" #include "modules/control/proto/pad_msg.pb.h" #include "modules/data/proto/static_info.pb.h" #include "modules/data/util/info_collector.h" #include "modules/dreamview/backend/common/dreamview_gflags.h" #include "modules/dreamview/backend/hmi/vehicle_manager.h" #include "modules/monitor/proto/system_status.pb.h" DEFINE_string(global_flagfile, "modules/common/data/global_flagfile.txt", "Global flagfile shared by all modules."); DEFINE_string(map_data_path, "/apollo/modules/map/data", "Path to map data."); DEFINE_string(vehicle_data_path, "/apollo/modules/calibration/data", "Path to vehicle data."); DEFINE_string(ota_service_url, "http://180.76.145.202:5000/query", "OTA service url. [Attention! It's still in experiment.]"); DEFINE_string(ota_vehicle_info_file, "modules/tools/ota/vehicle_info.pb.txt", "Vehicle info to request OTA."); DEFINE_double(system_status_lifetime_seconds, 30, "Lifetime of a valid SystemStatus message."); namespace apollo { namespace dreamview { namespace { using apollo::canbus::Chassis; using apollo::common::VehicleConfigHelper; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; using apollo::common::util::FindOrNull; using apollo::common::util::GetProtoFromASCIIFile; using apollo::common::util::JsonUtil; using apollo::common::util::StringTokenizer; using apollo::control::DrivingAction; using apollo::data::VehicleInfo; using google::protobuf::Map; using Json = WebSocketHandler::Json; // Convert a string to be title-like. E.g.: "hello_world" -> "Hello World". std::string TitleCase(const std::string &origin, const std::string &delimiter = "_") { std::vector<std::string> parts = StringTokenizer::Split(origin, delimiter); for (auto &part : parts) { if (!part.empty()) { // Upper case the first char. part[0] = toupper(part[0]); } } return apollo::common::util::PrintIter(parts); } // List subdirs and return a dict of {subdir_title: subdir_path}. Map<std::string, std::string> ListDirAsDict(const std::string &dir) { Map<std::string, std::string> result; const auto subdirs = apollo::common::util::ListSubDirectories(dir); for (const auto &subdir : subdirs) { const auto subdir_title = TitleCase(subdir); const auto subdir_path = apollo::common::util::StrCat(dir, "/", subdir); result.insert({subdir_title, subdir_path}); } return result; } // Send PadMessage to change driving mode to target mode. // Retry for several times to try to guarantee the result. bool GuaranteeDrivingMode(const Chassis::DrivingMode target_mode, const bool reset_first) { if (reset_first) { if (!GuaranteeDrivingMode(Chassis::COMPLETE_MANUAL, false)) { return false; } } control::PadMessage pad; switch (target_mode) { case Chassis::COMPLETE_MANUAL: pad.set_action(DrivingAction::RESET); break; case Chassis::COMPLETE_AUTO_DRIVE: pad.set_action(DrivingAction::START); break; default: AFATAL << "Unknown action to change driving mode to " << target_mode; } constexpr int kMaxTries = 3; constexpr auto kTryInterval = std::chrono::milliseconds(500); auto *chassis = CHECK_NOTNULL(AdapterManager::GetChassis()); for (int i = 0; i < kMaxTries; ++i) { // Send driving action periodically until entering target driving mode. AdapterManager::FillPadHeader("HMI", &pad); AdapterManager::PublishPad(pad); std::this_thread::sleep_for(kTryInterval); chassis->Observe(); if (chassis->Empty()) { AERROR << "No Chassis message received!"; } else if (chassis->GetLatestObserved().driving_mode() == target_mode) { return true; } } AERROR << "Failed to change driving mode to " << target_mode; return false; } } // namespace HMI::HMI(WebSocketHandler *websocket, MapService *map_service) : websocket_(websocket), map_service_(map_service), logger_(apollo::common::monitor::MonitorMessageItem::HMI) { CHECK(common::util::GetProtoFromFile(FLAGS_hmi_config_filename, &config_)) << "Unable to parse HMI config file " << FLAGS_hmi_config_filename; config_.set_docker_image(apollo::data::InfoCollector::GetDockerImage()); // If the module path doesn't exist, remove it from list. auto *modules = config_.mutable_modules(); for (auto iter = modules->begin(); iter != modules->end();) { const auto &conf = iter->second; if (conf.has_path() && !common::util::PathExists(conf.path())) { iter = modules->erase(iter); } else { ++iter; } } // If the default mode is unavailable, select the first one. const auto &modes = config_.modes(); if (!ContainsKey(modes, status_.current_mode())) { CHECK(!modes.empty()); status_.set_current_mode(modes.begin()->first); } // Get available maps and vehicles by listing data directory. *config_.mutable_available_maps() = ListDirAsDict(FLAGS_map_data_path); *config_.mutable_available_vehicles() = ListDirAsDict(FLAGS_vehicle_data_path); ADEBUG << "Loaded HMI config: " << config_.DebugString(); // Register websocket message handlers. if (websocket_) { RegisterMessageHandlers(); } } void HMI::RegisterMessageHandlers() { // Send current config and status to new HMI client. websocket_->RegisterConnectionReadyHandler( [this](WebSocketHandler::Connection *conn) { websocket_->SendData( conn, JsonUtil::ProtoToTypedJson("HMIConfig", config_).dump()); websocket_->SendData( conn, JsonUtil::ProtoToTypedJson("HMIStatus", status_).dump()); SendVehicleParam(conn); }); // HMI client asks for executing module command. websocket_->RegisterMessageHandler( "ExecuteModuleCommand", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain {module: "module_name", command: "command_name"}. // If module_name is "all", then run the command on all modules. std::string module; std::string command; if (JsonUtil::GetStringFromJson(json, "module", &module) && JsonUtil::GetStringFromJson(json, "command", &command)) { RunComponentCommand(config_.modules(), module, command); } else { AERROR << "Truncated module command."; } }); // HMI client asks for executing tool command. websocket_->RegisterMessageHandler( "ExecuteToolCommand", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain {tool: "tool_name", command: "command_name"}. std::string tool; std::string command; if (JsonUtil::GetStringFromJson(json, "tool", &tool) && JsonUtil::GetStringFromJson(json, "command", &command)) { RunComponentCommand(config_.tools(), tool, command); } else { AERROR << "Truncated tool command."; } }); // HMI client asks for executing mode command. websocket_->RegisterMessageHandler( "ExecuteModeCommand", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain {command: "command_name"}. // Supported commands are: "start", "stop". std::string command; if (JsonUtil::GetStringFromJson(json, "command", &command)) { RunModeCommand(command); } else { AERROR << "Truncated mode command."; } }); // HMI client asks for changing driving mode. websocket_->RegisterMessageHandler( "ChangeDrivingMode", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain {new_mode: "DrivingModeName"}. // DrivingModeName should be one of canbus::Chassis::DrivingMode. // For now it is either COMPLETE_MANUAL or COMPLETE_AUTO_DRIVE. std::string new_mode; if (JsonUtil::GetStringFromJson(json, "new_mode", &new_mode)) { ChangeDrivingModeTo(new_mode); } else { AERROR << "Truncated ChangeDrivingMode request."; } }); // HMI client asks for changing map. websocket_->RegisterMessageHandler( "ChangeMap", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain {new_map: "MapName"}. // MapName should be a key of config_.available_maps. std::string new_map; if (JsonUtil::GetStringFromJson(json, "new_map", &new_map)) { ChangeMapTo(new_map); } else { AERROR << "Truncated ChangeMap request."; } }); // HMI client asks for changing vehicle. websocket_->RegisterMessageHandler( "ChangeVehicle", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain {new_vehicle: "VehicleName"}. // VehicleName should be a key of config_.available_vehicles. std::string new_vehicle; if (JsonUtil::GetStringFromJson(json, "new_vehicle", &new_vehicle)) { ChangeVehicleTo(new_vehicle); } else { AERROR << "Truncated ChangeVehicle request."; } }); // HMI client asks for changing mode. websocket_->RegisterMessageHandler( "ChangeMode", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain {new_mode: "ModeName"}. // ModeName should be a key of config_.modes. std::string new_mode; if (JsonUtil::GetStringFromJson(json, "new_mode", &new_mode)) { ChangeModeTo(new_mode); } else { AERROR << "Truncated ChangeMode request."; } }); // HMI client asks for adding new DriveEvent. websocket_->RegisterMessageHandler( "SubmitDriveEvent", [this](const Json &json, WebSocketHandler::Connection *conn) { // json should contain event_time_ms and event_msg. uint64_t event_time_ms; std::string event_msg; if (JsonUtil::GetNumberFromJson(json, "event_time_ms", &event_time_ms) && JsonUtil::GetStringFromJson(json, "event_msg", &event_msg)) { SubmitDriveEvent(event_time_ms, event_msg); } else { AERROR << "Truncated SubmitDriveEvent request."; } }); // Received new system status, broadcast to clients. AdapterManager::AddSystemStatusCallback( [this](const monitor::SystemStatus &system_status) { if (Clock::NowInSeconds() - system_status.header().timestamp_sec() < FLAGS_system_status_lifetime_seconds) { *status_.mutable_system_status() = system_status; BroadcastHMIStatus(); } }); } void HMI::BroadcastHMIStatus() { // In unit tests, we may leave websocket_ as NULL and skip broadcasting. if (websocket_) { websocket_->BroadcastData( JsonUtil::ProtoToTypedJson("HMIStatus", status_).dump()); } // Broadcast messages. apollo::common::monitor::MonitorLogBuffer log_buffer(&logger_); if (status_.current_map().empty()) { log_buffer.WARN("You haven't select map yet!"); } if (status_.current_vehicle().empty()) { log_buffer.WARN("You haven't select vehicle yet!"); } } void HMI::SendVehicleParam(WebSocketHandler::Connection *conn) { if (websocket_ == nullptr) { return; } const auto json_str = JsonUtil::ProtoToTypedJson( "VehicleParam", VehicleConfigHelper::GetConfig().vehicle_param()) .dump(); if (conn != nullptr) { websocket_->SendData(conn, json_str); } else { websocket_->BroadcastData(json_str); } } int HMI::RunComponentCommand(const Map<std::string, Component> &components, const std::string &component_name, const std::string &command_name) { const auto *component = FindOrNull(components, component_name); if (component == nullptr) { AERROR << "Cannot find component " << component_name; return -1; } const auto *cmd = FindOrNull(component->supported_commands(), command_name); if (cmd == nullptr) { AERROR << "Cannot find command " << component_name << "." << command_name; return -1; } AINFO << "Execute system command: " << *cmd; const int ret = std::system(cmd->c_str()); AERROR_IF(ret != 0) << "Command returns " << ret << ": " << *cmd; return ret; } void HMI::RunModeCommand(const std::string &command_name) { RunModeCommand(status_.current_mode(), command_name); } void HMI::RunModeCommand(const std::string &mode, const std::string &command_name) { const Mode &mode_conf = config_.modes().at(mode); if (command_name == "start" || command_name == "stop") { // Run the command on all live modules. for (const auto &module : mode_conf.live_modules()) { RunComponentCommand(config_.modules(), module, command_name); } } } void HMI::ChangeDrivingModeTo(const std::string &new_mode) { Chassis::DrivingMode mode; if (!Chassis::DrivingMode_Parse(new_mode, &mode)) { AERROR << "Unknown driving mode " << new_mode; return; } const bool reset_first = (mode != Chassis::COMPLETE_MANUAL); GuaranteeDrivingMode(mode, reset_first); } void HMI::ChangeMapTo(const std::string &map_name) { if (status_.current_map() == map_name) { return; } const auto *map_dir = FindOrNull(config_.available_maps(), map_name); if (map_dir == nullptr) { AERROR << "Unknown map " << map_name; return; } status_.set_current_map(map_name); apollo::common::KVDB::Put("apollo:dreamview:map", map_name); FLAGS_map_dir = *map_dir; // Append new map_dir flag to global flagfile. std::ofstream fout(FLAGS_global_flagfile, std::ios_base::app); CHECK(fout) << "Fail to open " << FLAGS_global_flagfile; fout << "\n--map_dir=" << *map_dir << std::endl; // Also reload simulation map. CHECK(map_service_->ReloadMap(true)) << "Failed to load map from " << *map_dir; RunModeCommand("stop"); BroadcastHMIStatus(); } void HMI::ChangeVehicleTo(const std::string &vehicle_name) { if (status_.current_vehicle() == vehicle_name) { return; } const auto *vehicle = FindOrNull(config_.available_vehicles(), vehicle_name); if (vehicle == nullptr) { AERROR << "Unknown vehicle " << vehicle_name; return; } status_.set_current_vehicle(vehicle_name); apollo::common::KVDB::Put("apollo:dreamview:vehicle", vehicle_name); CHECK(VehicleManager::instance()->UseVehicle(*vehicle)); RunModeCommand("stop"); // Check available updates for current vehicle. // CheckOTAUpdates(); BroadcastHMIStatus(); // Broadcast new VehicleParam. SendVehicleParam(); } void HMI::ChangeModeTo(const std::string &mode_name) { if (status_.current_mode() == mode_name) { return; } if (!ContainsKey(config_.modes(), mode_name)) { AERROR << "Unknown mode " << mode_name; return; } const std::string previous_mode = status_.current_mode(); status_.set_current_mode(mode_name); apollo::common::KVDB::Put("apollo:dreamview:mode", mode_name); RunModeCommand(previous_mode, "stop"); BroadcastHMIStatus(); } void HMI::CheckOTAUpdates() { VehicleInfo vehicle_info; if (!GetProtoFromASCIIFile(FLAGS_ota_vehicle_info_file, &vehicle_info)) { return; } Json ota_request; ota_request["car_type"] = apollo::common::util::StrCat( VehicleInfo::Brand_Name(vehicle_info.brand()), ".", VehicleInfo::Model_Name(vehicle_info.model())); ota_request["vin"] = vehicle_info.license().vin(); ota_request["tag"] = apollo::data::InfoCollector::GetDockerImage(); Json ota_response; const auto status = apollo::common::util::HttpClient::Post( FLAGS_ota_service_url, ota_request, &ota_response); if (status.ok()) { CHECK(JsonUtil::GetStringFromJson(ota_response, "tag", status_.mutable_ota_update())); AINFO << "Found available OTA update: " << status_.ota_update(); } } void HMI::SubmitDriveEvent(const uint64_t event_time_ms, const std::string &event_msg) const { apollo::common::DriveEvent drive_event; AdapterManager::FillDriveEventHeader("HMI", &drive_event); drive_event.mutable_header()->set_timestamp_sec(event_time_ms / 1000.0); drive_event.set_event(event_msg); AdapterManager::PublishDriveEvent(drive_event); } } // namespace dreamview } // namespace apollo
35.955466
80
0.667155
[ "vector", "model" ]
d50afdc05f166d3705f827222429ffe429ccfa9a
3,263
cpp
C++
src/BinaryMeshReader.cpp
odinsbane/toy-model-cell-gl
a1e976d51e9673a364f130cf5685d86ed0d50ea4
[ "MIT" ]
null
null
null
src/BinaryMeshReader.cpp
odinsbane/toy-model-cell-gl
a1e976d51e9673a364f130cf5685d86ed0d50ea4
[ "MIT" ]
null
null
null
src/BinaryMeshReader.cpp
odinsbane/toy-model-cell-gl
a1e976d51e9673a364f130cf5685d86ed0d50ea4
[ "MIT" ]
null
null
null
#include "BinaryMeshReader.h" int getInt(char* integer); /* * test.bmf * frame: 0 with 2274 position indices with 4536 connection indices and 4536 triangle indices * */ int nextInt(std::ifstream* stream); double nextDouble(std::ifstream* stream); BinaryMeshReader::BinaryMeshReader(const std::string &filename){ std::ifstream* inputStream = new std::ifstream(filename, std::ifstream::binary); int count = nextInt(inputStream); connection_count = new int[count]; triangle_count = new int[count]; position_count = new int[count]; printf("%d meshes included \n", count); for(int i = 0; i<count; i++){ int frame = nextInt(inputStream); printf("loading mesh for frame %d \n",frame); int p_count = nextInt(inputStream); printf("with %d position doubles\n", p_count); double* positions = new double[p_count]; for(int j = 0; j<p_count; j++){ positions[j] = nextDouble(inputStream); } int c_count = nextInt(inputStream); int* connections = new int[c_count]; for(int j = 0; j<c_count; j++){ connections[j] = nextInt(inputStream); } int t_count = nextInt(inputStream); int* triangles = new int[t_count]; for(int j = 0; j<t_count; j++){ triangles[j] = nextInt(inputStream); } printf("frame %d: %d position doubles, %d connection indices, %d triangle indices.\n",frame, p_count, c_count, t_count); connection_count[i] = c_count/2; triangle_count[i] = t_count/3; position_count[i] = p_count/3; all_positions.push_back(positions); all_triangles.push_back(triangles); all_connections.push_back(connections); } } char* first = new char[8]; char* second = new char[8]; int nextInt(std::ifstream* stream){ stream->read(first, 4); for(int i = 0; i<4; i++){ second[i] = first[3 - i]; } return ((int*)second)[0]; } double nextDouble(std::ifstream* stream){ stream->read(first, 8); for(int i = 0; i<8; i++){ second[i] = first[7-i]; } return ((double*)second)[0]; } int getInt(char* integer){ /*unsigned int v = 0; for(int i = 0; i<4; i++){ unsigned char c = (unsigned char)integer[i]; //v = v + ((integer[i]&0xff)<<(8*(3-i))); v = (v<<8) + c; } printf(" %ud \n",v);*/ return ((int*)integer)[0]; } void BinaryMeshReader::shutdown(){ for(double* positions: all_positions){ delete[] positions; } for(int* triangles: all_triangles){ delete[] triangles; } for(int* connections: all_connections){ delete[] connections; } } BinaryMesh BinaryMeshReader::getMesh(int frame){ BinaryMesh b; b.position_count = position_count[frame]; b.triangle_count = triangle_count[frame]; b.connection_count = connection_count[frame]; b.positions = all_positions[frame]; b.connection_indicies = all_connections[frame]; b.triangle_indicies = all_triangles[frame]; return b; }
27.888889
128
0.574625
[ "mesh" ]
d50b0534b5cab8f62a5375dd78c29d5fd9bba850
9,127
cpp
C++
apps/yview.cpp
kxf3199/gltf_tool
b060135209dff2127095575b8fc87849b5bfbdf4
[ "MIT" ]
1
2022-03-04T10:53:42.000Z
2022-03-04T10:53:42.000Z
apps/yview.cpp
spindro/disney_brdf_for_yocto-gl
aa79c60ec9603240f35a6c70ed20586d3fe5df45
[ "MIT" ]
null
null
null
apps/yview.cpp
spindro/disney_brdf_for_yocto-gl
aa79c60ec9603240f35a6c70ed20586d3fe5df45
[ "MIT" ]
null
null
null
// // LICENSE: // // Copyright (c) 2016 -- 2017 Fabio Pellacini // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY 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. // #include "../yocto/yocto_gl.h" using namespace std::literals; // Application state struct app_state { ygl::scene* scn = nullptr; ygl::camera* view = nullptr; ygl::camera* cam = nullptr; std::string filename; std::string imfilename; std::string outfilename; ygl::gl_stdsurface_params params = {}; ygl::gl_stdsurface_program prog; std::unordered_map<ygl::texture*, ygl::gl_texture> textures; std::unordered_map<ygl::shape*, ygl::gl_shape> shapes; ygl::gl_lights lights; bool navigation_fps = false; ygl::scene_selection selection = {}; std::vector<ygl::scene_selection> update_list; ygl::proc_scene* pscn = nullptr; float time = 0; ygl::vec2f time_range = ygl::zero2f; bool animate = false; ~app_state() { if (scn) delete scn; if (view) delete view; if (pscn) delete pscn; } }; // draw with shading inline void draw(ygl::gl_window* win) { auto app = (app_state*)get_user_pointer(win); auto framebuffer_size = get_framebuffer_size(win); app->params.resolution = framebuffer_size.y; static auto last_time = 0.0f; for (auto& sel : app->update_list) { if (sel.txt) { ygl::update_gl_texture(app->textures, app->selection.txt); } if (sel.sgr) { for (auto shp : app->selection.sgr->shapes) { ygl::update_gl_shape(app->shapes, shp); } } if (sel.shp) { ygl::update_gl_shape(app->shapes, app->selection.shp); } if (sel.nde || sel.anm || sel.agr || app->time != last_time) { ygl::update_transforms(app->scn, app->time); last_time = app->time; } if (sel.shp || sel.sgr || sel.mat || sel.nde) { app->lights = ygl::make_gl_lights(app->scn); if (app->lights.pos.empty()) app->params.eyelight = true; } } app->update_list.clear(); ygl::gl_clear_buffers(app->params.background); ygl::gl_enable_depth_test(true); ygl::gl_enable_culling(app->params.cull_backface); ygl::draw_stdsurface_scene(app->scn, app->cam, app->prog, app->shapes, app->textures, app->lights, framebuffer_size, get_untyped_selection(app->selection), app->params); if (ygl::begin_widgets(win, "yview")) { if (ygl::draw_header_widget(win, "view")) { ygl::draw_value_widget(win, "scene", app->filename); if (ygl::draw_button_widget(win, "new")) { delete app->pscn; app->pscn = ygl::proc_scene_presets().at("plane_al"); delete app->scn; app->scn = new ygl::scene(); ygl::clear_gl_shapes(app->shapes); ygl::clear_gl_textures(app->textures); ygl::update_proc_elems(app->scn, app->pscn); app->textures = ygl::make_gl_textures(app->scn); app->shapes = ygl::make_gl_shapes(app->scn); } ygl::draw_continue_widget(win); if (ygl::draw_button_widget(win, "load")) { app->scn = ygl::load_scene(app->filename, {}); ygl::clear_gl_shapes(app->shapes); ygl::clear_gl_textures(app->textures); app->textures = ygl::make_gl_textures(app->scn); app->shapes = ygl::make_gl_shapes(app->scn); } ygl::draw_continue_widget(win); if (ygl::draw_button_widget(win, "save")) { ygl::save_scene(app->filename, app->scn, {}); } ygl::draw_continue_widget(win); if (draw_button_widget(win, "save proc")) { ygl::save_proc_scene( ygl::replace_path_extension(app->filename, ".json"), app->pscn); } ygl::draw_camera_selection_widget( win, "camera", app->cam, app->scn, app->view); ygl::draw_value_widget(win, "fps", app->navigation_fps); if (app->time_range != ygl::zero2f) { ygl::draw_value_widget(win, "time", app->time, app->time_range.x, app->time_range.y); ygl::draw_value_widget(win, "animate", app->animate); } } if (ygl::draw_header_widget(win, "params")) { ygl::draw_params_widgets(win, "", app->params); } if (ygl::draw_header_widget(win, "scene")) { ygl::draw_scene_widgets(win, "", app->scn, app->selection, app->update_list, app->textures, app->pscn); } } ygl::end_widgets(win); ygl::swap_buffers(win); } // run ui loop void run_ui(app_state* app) { // window auto win = ygl::make_window( (int)std::round(app->cam->aspect * app->params.resolution), app->params.resolution, "yview | " + app->filename, app); ygl::set_window_callbacks(win, nullptr, nullptr, draw); // load textures and vbos app->prog = ygl::make_stdsurface_program(); app->textures = ygl::make_gl_textures(app->scn); app->shapes = ygl::make_gl_shapes(app->scn); ygl::update_transforms(app->scn, app->time); app->lights = ygl::make_gl_lights(app->scn); if (app->lights.pos.empty()) app->params.eyelight = true; // init widget ygl::init_widgets(win); // loop while (!should_close(win)) { // handle mouse and keyboard for navigation if (app->cam == app->view) { ygl::handle_camera_navigation(win, app->view, app->navigation_fps); } // animation if (app->animate) { app->time += 1 / 60.0f; if (app->time < app->time_range.x || app->time > app->time_range.y) app->time = app->time_range.x; } // draw draw(win); // event hadling ygl::poll_events(win); } ygl::clear_window(win); } int main(int argc, char* argv[]) { // create empty scene auto app = new app_state(); // parse command line auto parser = ygl::make_parser(argc, argv, "yview", "views scenes inteactively"); app->params = ygl::parse_params(parser, "", app->params); auto preserve_quads = ygl::parse_flag( parser, "--preserve-quads", "-q", "Preserve quads on load"); auto preserve_facevarying = ygl::parse_flag( parser, "--preserve-facevarying", "-f", "Preserve facevarying on load"); app->imfilename = ygl::parse_opt( parser, "--output-image", "-o", "Image filename", "out.hdr"s); app->filename = ygl::parse_arg(parser, "scene", "Scene filename", ""s); if (ygl::should_exit(parser)) { printf("%s\n", get_usage(parser).c_str()); exit(1); } // scene loading ygl::log_info("loading scene {}", app->filename); try { auto opts = ygl::load_options(); opts.preserve_quads = preserve_quads; opts.preserve_facevarying = preserve_facevarying; opts.preserve_hierarchy = true; app->scn = load_scene(app->filename, opts); } catch (std::exception e) { ygl::log_fatal("cannot load scene {}", app->filename); } // tesselate input shapes ygl::tesselate_shapes(app->scn, true, !preserve_facevarying, !preserve_quads && !preserve_facevarying, false); // add missing data ygl::add_elements(app->scn); // view camera app->view = ygl::make_view_camera(app->scn, 0); app->cam = app->view; // animation app->time_range = ygl::compute_animation_range(app->scn); app->time = app->time_range.x; // lights app->lights = ygl::make_gl_lights(app->scn); // editing app->pscn = new ygl::proc_scene(); // run ui run_ui(app); // clear delete app; // done return 0; }
35.792157
80
0.604142
[ "shape", "vector" ]
d50fe67a9589f6be16df8561655826353d9ae0a6
3,927
cc
C++
mindspore/core/ops/grad/maximum_grad.cc
httpsgithu/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
1
2022-02-23T09:13:43.000Z
2022-02-23T09:13:43.000Z
mindspore/core/ops/grad/maximum_grad.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
mindspore/core/ops/grad/maximum_grad.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020-2021 Huawei Technologies Co., Ltd * * 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 "ops/grad/maximum_grad.h" #include <vector> #include <set> #include "ops/op_utils.h" #include "utils/check_convert_utils.h" #include "abstract/ops/primitive_infer_map.h" #include "mindapi/src/helper.h" namespace mindspore { namespace ops { namespace { abstract::TupleShapePtr MaximumGradInferShape(const PrimitivePtr &primitive, const std::vector<AbstractBasePtr> &input_args) { MS_EXCEPTION_IF_NULL(primitive); auto prim_name = primitive->name(); const int64_t input_num = 3; (void)CheckAndConvertUtils::CheckInteger("input number", SizeToLong(input_args.size()), kEqual, input_num, prim_name); for (const auto &item : input_args) { MS_EXCEPTION_IF_NULL(item); } auto x = input_args[0]->BuildShape(); auto y = input_args[1]->BuildShape(); MS_EXCEPTION_IF_NULL(x); MS_EXCEPTION_IF_NULL(y); auto x_element = x->cast<abstract::ShapePtr>(); auto y_element = y->cast<abstract::ShapePtr>(); MS_EXCEPTION_IF_NULL(x_element); MS_EXCEPTION_IF_NULL(y_element); return std::make_shared<abstract::TupleShape>(std::vector<abstract::BaseShapePtr>{x_element, y_element}); } TuplePtr MaximumGradInferType(const PrimitivePtr &primitive, const std::vector<AbstractBasePtr> &input_args) { MS_EXCEPTION_IF_NULL(primitive); auto prim_name = primitive->name(); const int64_t INPUT_GRADS_IDX = 2; auto x1 = CheckAndConvertUtils::CheckArgs<abstract::AbstractTensor>(prim_name, input_args, 0); auto x2 = CheckAndConvertUtils::CheckArgs<abstract::AbstractTensor>(prim_name, input_args, 1); CheckAndConvertUtils::CheckArgs<abstract::AbstractTensor>(prim_name, input_args, INPUT_GRADS_IDX); (void)abstract::CheckDtypeSame(prim_name, x1, x2); auto x_type = input_args[0]->BuildType(); MS_EXCEPTION_IF_NULL(x_type); (void)CheckAndConvertUtils::CheckTensorTypeValid("x", x_type, common_valid_types, prim_name); std::vector<TypePtr> type_tuple; type_tuple.push_back(x_type); type_tuple.push_back(x_type); return std::make_shared<Tuple>(type_tuple); } } // namespace MIND_API_OPERATOR_IMPL(MaximumGrad, BaseOperator); abstract::AbstractBasePtr MaximumGradInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive, const std::vector<abstract::AbstractBasePtr> &input_args) { MS_EXCEPTION_IF_NULL(primitive); auto infer_type = MaximumGradInferType(primitive, input_args); auto infer_shape = MaximumGradInferShape(primitive, input_args); return abstract::MakeAbstract(infer_shape, infer_type); } void MaximumGrad::Init(const bool grad_x, const bool grad_y) { set_grad_x(grad_x); set_grad_y(grad_y); } void MaximumGrad::set_grad_x(const bool grad_x) { (void)this->AddAttr(kGradX, api::MakeValue(grad_x)); } void MaximumGrad::set_grad_y(const bool grad_y) { (void)this->AddAttr(kGradY, api::MakeValue(grad_y)); } bool MaximumGrad::get_grad_x() const { auto value_ptr = GetAttr(kGradX); MS_EXCEPTION_IF_NULL(value_ptr); return GetValue<bool>(value_ptr); } bool MaximumGrad::get_grad_y() const { auto value_ptr = GetAttr(kGradY); MS_EXCEPTION_IF_NULL(value_ptr); return GetValue<bool>(value_ptr); } REGISTER_PRIMITIVE_EVAL_IMPL(MaximumGrad, prim::kPrimMaximumGrad, MaximumGradInfer, nullptr, true); } // namespace ops } // namespace mindspore
40.90625
120
0.75121
[ "vector" ]
d510820d759ee8697c4afb8b9d1357aa44099cbb
102,917
cc
C++
p2p/base/p2p_transport_channel.cc
asdfghjjklllllaaa/src
d2d6e4da56e5f5cc9157f4992693f78372f52247
[ "BSD-3-Clause" ]
1
2019-03-02T17:26:11.000Z
2019-03-02T17:26:11.000Z
p2p/base/p2p_transport_channel.cc
asdfghjjklllllaaa/src
d2d6e4da56e5f5cc9157f4992693f78372f52247
[ "BSD-3-Clause" ]
null
null
null
p2p/base/p2p_transport_channel.cc
asdfghjjklllllaaa/src
d2d6e4da56e5f5cc9157f4992693f78372f52247
[ "BSD-3-Clause" ]
2
2020-09-06T12:28:03.000Z
2021-02-17T14:39:06.000Z
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "p2p/base/p2p_transport_channel.h" #include <iterator> #include <set> #include <utility> #include "absl/algorithm/container.h" #include "absl/memory/memory.h" #include "api/candidate.h" #include "logging/rtc_event_log/ice_logger.h" #include "p2p/base/candidate_pair_interface.h" #include "p2p/base/connection.h" #include "p2p/base/port.h" #include "rtc_base/checks.h" #include "rtc_base/crc32.h" #include "rtc_base/logging.h" #include "rtc_base/net_helper.h" #include "rtc_base/net_helpers.h" #include "rtc_base/string_encode.h" #include "rtc_base/time_utils.h" #include "system_wrappers/include/field_trial.h" #include "system_wrappers/include/metrics.h" namespace { // The minimum improvement in RTT that justifies a switch. const int kMinImprovement = 10; bool IsRelayRelay(const cricket::Connection* conn) { return conn->local_candidate().type() == cricket::RELAY_PORT_TYPE && conn->remote_candidate().type() == cricket::RELAY_PORT_TYPE; } bool IsUdp(cricket::Connection* conn) { return conn->local_candidate().relay_protocol() == cricket::UDP_PROTOCOL_NAME; } cricket::PortInterface::CandidateOrigin GetOrigin(cricket::PortInterface* port, cricket::PortInterface* origin_port) { if (!origin_port) return cricket::PortInterface::ORIGIN_MESSAGE; else if (port == origin_port) return cricket::PortInterface::ORIGIN_THIS_PORT; else return cricket::PortInterface::ORIGIN_OTHER_PORT; } // TODO(qingsi) Use an enum to replace the following constants for all // comparision results. static constexpr int a_is_better = 1; static constexpr int b_is_better = -1; static constexpr int a_and_b_equal = 0; bool LocalCandidateUsesPreferredNetwork( const cricket::Connection* conn, absl::optional<rtc::AdapterType> network_preference) { rtc::AdapterType network_type = conn->port()->Network()->type(); return network_preference.has_value() && (network_type == network_preference); } int CompareCandidatePairsByNetworkPreference( const cricket::Connection* a, const cricket::Connection* b, absl::optional<rtc::AdapterType> network_preference) { bool a_uses_preferred_network = LocalCandidateUsesPreferredNetwork(a, network_preference); bool b_uses_preferred_network = LocalCandidateUsesPreferredNetwork(b, network_preference); if (a_uses_preferred_network && !b_uses_preferred_network) { return a_is_better; } else if (!a_uses_preferred_network && b_uses_preferred_network) { return b_is_better; } return a_and_b_equal; } uint32_t GetWeakPingIntervalInFieldTrial() { uint32_t weak_ping_interval = ::strtoul( webrtc::field_trial::FindFullName("WebRTC-StunInterPacketDelay").c_str(), nullptr, 10); if (weak_ping_interval) { return static_cast<int>(weak_ping_interval); } return cricket::WEAK_PING_INTERVAL; } } // unnamed namespace namespace cricket { using webrtc::RTCErrorType; using webrtc::RTCError; bool IceCredentialsChanged(const std::string& old_ufrag, const std::string& old_pwd, const std::string& new_ufrag, const std::string& new_pwd) { // The standard (RFC 5245 Section 9.1.1.1) says that ICE restarts MUST change // both the ufrag and password. However, section 9.2.1.1 says changing the // ufrag OR password indicates an ICE restart. So, to keep compatibility with // endpoints that only change one, we'll treat this as an ICE restart. return (old_ufrag != new_ufrag) || (old_pwd != new_pwd); } P2PTransportChannel::P2PTransportChannel(const std::string& transport_name, int component, PortAllocator* allocator) : P2PTransportChannel(transport_name, component, allocator, nullptr) {} P2PTransportChannel::P2PTransportChannel( const std::string& transport_name, int component, PortAllocator* allocator, webrtc::AsyncResolverFactory* async_resolver_factory, webrtc::RtcEventLog* event_log) : transport_name_(transport_name), component_(component), allocator_(allocator), async_resolver_factory_(async_resolver_factory), network_thread_(rtc::Thread::Current()), incoming_only_(false), error_(0), sort_dirty_(false), remote_ice_mode_(ICEMODE_FULL), ice_role_(ICEROLE_UNKNOWN), tiebreaker_(0), gathering_state_(kIceGatheringNew), config_(RECEIVING_TIMEOUT, BACKUP_CONNECTION_PING_INTERVAL, GATHER_ONCE /* continual_gathering_policy */, false /* prioritize_most_likely_candidate_pairs */, STRONG_AND_STABLE_WRITABLE_CONNECTION_PING_INTERVAL, true /* presume_writable_when_fully_relayed */, REGATHER_ON_FAILED_NETWORKS_INTERVAL, RECEIVING_SWITCHING_DELAY) { RTC_DCHECK(allocator_ != nullptr); weak_ping_interval_ = GetWeakPingIntervalInFieldTrial(); // Validate IceConfig even for mostly built-in constant default values in case // we change them. RTC_DCHECK(ValidateIceConfig(config_).ok()); webrtc::BasicRegatheringController::Config regathering_config( config_.regather_all_networks_interval_range, config_.regather_on_failed_networks_interval_or_default()); regathering_controller_ = absl::make_unique<webrtc::BasicRegatheringController>( regathering_config, this, network_thread_); // We populate the change in the candidate filter to the session taken by // the transport. allocator_->SignalCandidateFilterChanged.connect( this, &P2PTransportChannel::OnCandidateFilterChanged); ice_event_log_.set_event_log(event_log); } P2PTransportChannel::~P2PTransportChannel() { for (auto& p : resolvers_) { p.resolver_->Destroy(false); } resolvers_.clear(); RTC_DCHECK_RUN_ON(network_thread_); } // Add the allocator session to our list so that we know which sessions // are still active. void P2PTransportChannel::AddAllocatorSession( std::unique_ptr<PortAllocatorSession> session) { RTC_DCHECK_RUN_ON(network_thread_); session->set_generation(static_cast<uint32_t>(allocator_sessions_.size())); session->SignalPortReady.connect(this, &P2PTransportChannel::OnPortReady); session->SignalPortsPruned.connect(this, &P2PTransportChannel::OnPortsPruned); session->SignalCandidatesReady.connect( this, &P2PTransportChannel::OnCandidatesReady); session->SignalCandidateError.connect(this, &P2PTransportChannel::OnCandidateError); session->SignalCandidatesRemoved.connect( this, &P2PTransportChannel::OnCandidatesRemoved); session->SignalCandidatesAllocationDone.connect( this, &P2PTransportChannel::OnCandidatesAllocationDone); if (!allocator_sessions_.empty()) { allocator_session()->PruneAllPorts(); } allocator_sessions_.push_back(std::move(session)); regathering_controller_->set_allocator_session(allocator_session()); // We now only want to apply new candidates that we receive to the ports // created by this new session because these are replacing those of the // previous sessions. PruneAllPorts(); } void P2PTransportChannel::AddConnection(Connection* connection) { RTC_DCHECK_RUN_ON(network_thread_); connections_.push_back(connection); unpinged_connections_.insert(connection); connection->set_remote_ice_mode(remote_ice_mode_); connection->set_receiving_timeout(config_.receiving_timeout); connection->set_unwritable_timeout(config_.ice_unwritable_timeout); connection->set_unwritable_min_checks(config_.ice_unwritable_min_checks); connection->set_inactive_timeout(config_.ice_inactive_timeout); connection->SignalReadPacket.connect( this, &P2PTransportChannel::OnReadPacket); connection->SignalReadyToSend.connect( this, &P2PTransportChannel::OnReadyToSend); connection->SignalStateChange.connect( this, &P2PTransportChannel::OnConnectionStateChange); connection->SignalDestroyed.connect( this, &P2PTransportChannel::OnConnectionDestroyed); connection->SignalNominated.connect(this, &P2PTransportChannel::OnNominated); had_connection_ = true; connection->set_ice_event_log(&ice_event_log_); LogCandidatePairConfig(connection, webrtc::IceCandidatePairConfigType::kAdded); } // Determines whether we should switch the selected connection to // |new_connection| based the writable/receiving state, the nomination state, // and the last data received time. This prevents the controlled side from // switching the selected connection too frequently when the controlling side // is doing aggressive nominations. The precedence of the connection switching // criteria is as follows: // i) write/receiving/connected states // ii) For controlled side, // a) nomination state, // b) last data received time. // iii) Lower cost / higher priority. // iv) rtt. // To further prevent switching to high-cost networks, does not switch to // a high-cost connection if it is not receiving. // TODO(honghaiz): Stop the aggressive nomination on the controlling side and // implement the ice-renomination option. bool P2PTransportChannel::ShouldSwitchSelectedConnection( Connection* new_connection, bool* missed_receiving_unchanged_threshold) const { RTC_DCHECK_RUN_ON(network_thread_); if (!ReadyToSend(new_connection) || selected_connection_ == new_connection) { return false; } if (selected_connection_ == nullptr) { return true; } // Do not switch to a connection that is not receiving if it is not on a // preferred network or it has higher cost because it may be just spuriously // better. int compare_a_b_by_networks = CompareCandidatePairNetworks( new_connection, selected_connection_, config_.network_preference); if (compare_a_b_by_networks == b_is_better && !new_connection->receiving()) { return false; } absl::optional<int64_t> receiving_unchanged_threshold( rtc::TimeMillis() - config_.receiving_switching_delay_or_default()); int cmp = CompareConnections(selected_connection_, new_connection, receiving_unchanged_threshold, missed_receiving_unchanged_threshold); if (cmp != 0) { return cmp < 0; } // If everything else is the same, switch only if rtt has improved by // a margin. return new_connection->rtt() <= selected_connection_->rtt() - kMinImprovement; } bool P2PTransportChannel::MaybeSwitchSelectedConnection( Connection* new_connection, const std::string& reason) { RTC_DCHECK_RUN_ON(network_thread_); bool missed_receiving_unchanged_threshold = false; if (ShouldSwitchSelectedConnection(new_connection, &missed_receiving_unchanged_threshold)) { RTC_LOG(LS_INFO) << "Switching selected connection due to: " << reason; SwitchSelectedConnection(new_connection); return true; } if (missed_receiving_unchanged_threshold && config_.receiving_switching_delay_or_default()) { // If we do not switch to the connection because it missed the receiving // threshold, the new connection is in a better receiving state than the // currently selected connection. So we need to re-check whether it needs // to be switched at a later time. const std::string reason_to_sort = reason + " (after switching dampening interval)"; invoker_.AsyncInvokeDelayed<void>( RTC_FROM_HERE, thread(), rtc::Bind(&P2PTransportChannel::SortConnectionsAndUpdateState, this, reason_to_sort), config_.receiving_switching_delay_or_default()); } return false; } void P2PTransportChannel::SetIceRole(IceRole ice_role) { RTC_DCHECK_RUN_ON(network_thread_); if (ice_role_ != ice_role) { ice_role_ = ice_role; for (PortInterface* port : ports_) { port->SetIceRole(ice_role); } // Update role on pruned ports as well, because they may still have // connections alive that should be using the correct role. for (PortInterface* port : pruned_ports_) { port->SetIceRole(ice_role); } } } IceRole P2PTransportChannel::GetIceRole() const { RTC_DCHECK_RUN_ON(network_thread_); return ice_role_; } void P2PTransportChannel::SetIceTiebreaker(uint64_t tiebreaker) { RTC_DCHECK_RUN_ON(network_thread_); if (!ports_.empty() || !pruned_ports_.empty()) { RTC_LOG(LS_ERROR) << "Attempt to change tiebreaker after Port has been allocated."; return; } tiebreaker_ = tiebreaker; } IceTransportState P2PTransportChannel::GetState() const { RTC_DCHECK_RUN_ON(network_thread_); return state_; } webrtc::IceTransportState P2PTransportChannel::GetIceTransportState() const { RTC_DCHECK_RUN_ON(network_thread_); return standardized_state_; } const std::string& P2PTransportChannel::transport_name() const { RTC_DCHECK_RUN_ON(network_thread_); return transport_name_; } int P2PTransportChannel::component() const { RTC_DCHECK_RUN_ON(network_thread_); return component_; } bool P2PTransportChannel::writable() const { RTC_DCHECK_RUN_ON(network_thread_); return writable_; } bool P2PTransportChannel::receiving() const { RTC_DCHECK_RUN_ON(network_thread_); return receiving_; } IceGatheringState P2PTransportChannel::gathering_state() const { RTC_DCHECK_RUN_ON(network_thread_); return gathering_state_; } absl::optional<int> P2PTransportChannel::GetRttEstimate() { RTC_DCHECK_RUN_ON(network_thread_); if (selected_connection_ != nullptr && selected_connection_->rtt_samples() > 0) { return selected_connection_->rtt(); } else { return absl::nullopt; } } // A channel is considered ICE completed once there is at most one active // connection per network and at least one active connection. IceTransportState P2PTransportChannel::ComputeState() const { RTC_DCHECK_RUN_ON(network_thread_); if (!had_connection_) { return IceTransportState::STATE_INIT; } std::vector<Connection*> active_connections; for (Connection* connection : connections_) { if (connection->active()) { active_connections.push_back(connection); } } if (active_connections.empty()) { return IceTransportState::STATE_FAILED; } std::set<rtc::Network*> networks; for (Connection* connection : active_connections) { rtc::Network* network = connection->port()->Network(); if (networks.find(network) == networks.end()) { networks.insert(network); } else { RTC_LOG(LS_VERBOSE) << ToString() << ": Ice not completed yet for this channel as " << network->ToString() << " has more than 1 connection."; return IceTransportState::STATE_CONNECTING; } } ice_event_log_.DumpCandidatePairDescriptionToMemoryAsConfigEvents(); return IceTransportState::STATE_COMPLETED; } // Compute the current RTCIceTransportState as described in // https://www.w3.org/TR/webrtc/#dom-rtcicetransportstate // TODO(bugs.webrtc.org/9218): Start signaling kCompleted once we have // implemented end-of-candidates signalling. webrtc::IceTransportState P2PTransportChannel::ComputeIceTransportState() const { RTC_DCHECK_RUN_ON(network_thread_); bool has_connection = false; for (Connection* connection : connections_) { if (connection->active()) { has_connection = true; break; } } if (had_connection_ && !has_connection) { return webrtc::IceTransportState::kFailed; } if (!writable() && has_been_writable_) { return webrtc::IceTransportState::kDisconnected; } if (!had_connection_ && !has_connection) { return webrtc::IceTransportState::kNew; } if (has_connection && !writable()) { // A candidate pair has been formed by adding a remote candidate // and gathering a local candidate. return webrtc::IceTransportState::kChecking; } return webrtc::IceTransportState::kConnected; } void P2PTransportChannel::SetIceParameters(const IceParameters& ice_params) { RTC_DCHECK_RUN_ON(network_thread_); RTC_LOG(LS_INFO) << "Set ICE ufrag: " << ice_params.ufrag << " pwd: " << ice_params.pwd << " on transport " << transport_name(); ice_parameters_ = ice_params; // Note: Candidate gathering will restart when MaybeStartGathering is next // called. } void P2PTransportChannel::SetRemoteIceParameters( const IceParameters& ice_params) { RTC_DCHECK_RUN_ON(network_thread_); RTC_LOG(LS_INFO) << "Received remote ICE parameters: ufrag=" << ice_params.ufrag << ", renomination " << (ice_params.renomination ? "enabled" : "disabled"); IceParameters* current_ice = remote_ice(); if (!current_ice || *current_ice != ice_params) { // Keep the ICE credentials so that newer connections // are prioritized over the older ones. remote_ice_parameters_.push_back(ice_params); } // Update the pwd of remote candidate if needed. for (RemoteCandidate& candidate : remote_candidates_) { if (candidate.username() == ice_params.ufrag && candidate.password().empty()) { candidate.set_password(ice_params.pwd); } } // We need to update the credentials and generation for any peer reflexive // candidates. for (Connection* conn : connections_) { conn->MaybeSetRemoteIceParametersAndGeneration( ice_params, static_cast<int>(remote_ice_parameters_.size() - 1)); } // Updating the remote ICE candidate generation could change the sort order. RequestSortAndStateUpdate("remote candidate generation maybe changed"); } void P2PTransportChannel::SetRemoteIceMode(IceMode mode) { RTC_DCHECK_RUN_ON(network_thread_); remote_ice_mode_ = mode; } // TODO(qingsi): We apply the convention that setting a absl::optional parameter // to null restores its default value in the implementation. However, some // absl::optional parameters are only processed below if non-null, e.g., // regather_on_failed_networks_interval, and thus there is no way to restore the // defaults. Fix this issue later for consistency. void P2PTransportChannel::SetIceConfig(const IceConfig& config) { RTC_DCHECK_RUN_ON(network_thread_); if (config_.continual_gathering_policy != config.continual_gathering_policy) { if (!allocator_sessions_.empty()) { RTC_LOG(LS_ERROR) << "Trying to change continual gathering policy " "when gathering has already started!"; } else { config_.continual_gathering_policy = config.continual_gathering_policy; RTC_LOG(LS_INFO) << "Set continual_gathering_policy to " << config_.continual_gathering_policy; } } if (config_.backup_connection_ping_interval != config.backup_connection_ping_interval) { config_.backup_connection_ping_interval = config.backup_connection_ping_interval; RTC_LOG(LS_INFO) << "Set backup connection ping interval to " << config_.backup_connection_ping_interval_or_default() << " milliseconds."; } if (config_.receiving_timeout != config.receiving_timeout) { config_.receiving_timeout = config.receiving_timeout; for (Connection* connection : connections_) { connection->set_receiving_timeout(config_.receiving_timeout); } RTC_LOG(LS_INFO) << "Set ICE receiving timeout to " << config_.receiving_timeout_or_default() << " milliseconds"; } config_.prioritize_most_likely_candidate_pairs = config.prioritize_most_likely_candidate_pairs; RTC_LOG(LS_INFO) << "Set ping most likely connection to " << config_.prioritize_most_likely_candidate_pairs; if (config_.stable_writable_connection_ping_interval != config.stable_writable_connection_ping_interval) { config_.stable_writable_connection_ping_interval = config.stable_writable_connection_ping_interval; RTC_LOG(LS_INFO) << "Set stable_writable_connection_ping_interval to " << config_.stable_writable_connection_ping_interval_or_default(); } if (config_.presume_writable_when_fully_relayed != config.presume_writable_when_fully_relayed) { if (!connections_.empty()) { RTC_LOG(LS_ERROR) << "Trying to change 'presume writable' " "while connections already exist!"; } else { config_.presume_writable_when_fully_relayed = config.presume_writable_when_fully_relayed; RTC_LOG(LS_INFO) << "Set presume writable when fully relayed to " << config_.presume_writable_when_fully_relayed; } } config_.surface_ice_candidates_on_ice_transport_type_changed = config.surface_ice_candidates_on_ice_transport_type_changed; if (config_.surface_ice_candidates_on_ice_transport_type_changed && config_.continual_gathering_policy != GATHER_CONTINUALLY) { RTC_LOG(LS_WARNING) << "surface_ice_candidates_on_ice_transport_type_changed is " "ineffective since we do not gather continually."; } if (config_.regather_on_failed_networks_interval != config.regather_on_failed_networks_interval) { config_.regather_on_failed_networks_interval = config.regather_on_failed_networks_interval; RTC_LOG(LS_INFO) << "Set regather_on_failed_networks_interval to " << config_.regather_on_failed_networks_interval_or_default(); } if (config_.regather_all_networks_interval_range != config.regather_all_networks_interval_range) { // Config validation is assumed to have already happened at the API layer. RTC_DCHECK(config.continual_gathering_policy != GATHER_ONCE); config_.regather_all_networks_interval_range = config.regather_all_networks_interval_range; RTC_LOG(LS_INFO) << "Set regather_all_networks_interval_range to " << config.regather_all_networks_interval_range .value_or(rtc::IntervalRange(-1, 0)) .ToString(); } if (config_.receiving_switching_delay != config.receiving_switching_delay) { config_.receiving_switching_delay = config.receiving_switching_delay; RTC_LOG(LS_INFO) << "Set receiving_switching_delay to " << config_.receiving_switching_delay_or_default(); } if (config_.default_nomination_mode != config.default_nomination_mode) { config_.default_nomination_mode = config.default_nomination_mode; RTC_LOG(LS_INFO) << "Set default nomination mode to " << static_cast<int>(config_.default_nomination_mode); } if (config_.ice_check_interval_strong_connectivity != config.ice_check_interval_strong_connectivity) { config_.ice_check_interval_strong_connectivity = config.ice_check_interval_strong_connectivity; RTC_LOG(LS_INFO) << "Set strong ping interval to " << config_.ice_check_interval_strong_connectivity_or_default(); } if (config_.ice_check_interval_weak_connectivity != config.ice_check_interval_weak_connectivity) { config_.ice_check_interval_weak_connectivity = config.ice_check_interval_weak_connectivity; RTC_LOG(LS_INFO) << "Set weak ping interval to " << config_.ice_check_interval_weak_connectivity_or_default(); } if (config_.ice_check_min_interval != config.ice_check_min_interval) { config_.ice_check_min_interval = config.ice_check_min_interval; RTC_LOG(LS_INFO) << "Set min ping interval to " << config_.ice_check_min_interval_or_default(); } if (config_.ice_unwritable_timeout != config.ice_unwritable_timeout) { config_.ice_unwritable_timeout = config.ice_unwritable_timeout; for (Connection* conn : connections_) { conn->set_unwritable_timeout(config_.ice_unwritable_timeout); } RTC_LOG(LS_INFO) << "Set unwritable timeout to " << config_.ice_unwritable_timeout_or_default(); } if (config_.ice_unwritable_min_checks != config.ice_unwritable_min_checks) { config_.ice_unwritable_min_checks = config.ice_unwritable_min_checks; for (Connection* conn : connections_) { conn->set_unwritable_min_checks(config_.ice_unwritable_min_checks); } RTC_LOG(LS_INFO) << "Set unwritable min checks to " << config_.ice_unwritable_min_checks_or_default(); } if (config_.ice_inactive_timeout != config.ice_inactive_timeout) { config_.ice_inactive_timeout = config.ice_inactive_timeout; for (Connection* conn : connections_) { conn->set_inactive_timeout(config_.ice_inactive_timeout); } RTC_LOG(LS_INFO) << "Set inactive timeout to " << config_.ice_inactive_timeout_or_default(); } if (config_.network_preference != config.network_preference) { config_.network_preference = config.network_preference; RequestSortAndStateUpdate("network preference changed"); RTC_LOG(LS_INFO) << "Set network preference to " << (config_.network_preference.has_value() ? config_.network_preference.value() : -1); // network_preference cannot be bound to // int with value_or. } // TODO(qingsi): Resolve the naming conflict of stun_keepalive_delay in // UDPPort and stun_keepalive_interval. if (config_.stun_keepalive_interval != config.stun_keepalive_interval) { config_.stun_keepalive_interval = config.stun_keepalive_interval; allocator_session()->SetStunKeepaliveIntervalForReadyPorts( config_.stun_keepalive_interval); RTC_LOG(LS_INFO) << "Set STUN keepalive interval to " << config.stun_keepalive_interval_or_default(); } if (webrtc::field_trial::IsEnabled("WebRTC-ExtraICEPing")) { RTC_LOG(LS_INFO) << "Set WebRTC-ExtraICEPing: Enabled"; } if (webrtc::field_trial::IsEnabled("WebRTC-TurnAddMultiMapping")) { RTC_LOG(LS_INFO) << "Set WebRTC-TurnAddMultiMapping: Enabled"; } webrtc::BasicRegatheringController::Config regathering_config( config_.regather_all_networks_interval_range, config_.regather_on_failed_networks_interval_or_default()); regathering_controller_->SetConfig(regathering_config); RTC_DCHECK(ValidateIceConfig(config_).ok()); } const IceConfig& P2PTransportChannel::config() const { RTC_DCHECK_RUN_ON(network_thread_); return config_; } // TODO(qingsi): Add tests for the config validation starting from // PeerConnection::SetConfiguration. // Static RTCError P2PTransportChannel::ValidateIceConfig(const IceConfig& config) { if (config.regather_all_networks_interval_range && config.continual_gathering_policy == GATHER_ONCE) { return RTCError(RTCErrorType::INVALID_PARAMETER, "regather_all_networks_interval_range specified but " "continual gathering policy is GATHER_ONCE"); } if (config.ice_check_interval_strong_connectivity_or_default() < config.ice_check_interval_weak_connectivity.value_or( GetWeakPingIntervalInFieldTrial())) { return RTCError(RTCErrorType::INVALID_PARAMETER, "Ping interval of candidate pairs is shorter when ICE is " "strongly connected than that when ICE is weakly " "connected"); } if (config.receiving_timeout_or_default() < std::max(config.ice_check_interval_strong_connectivity_or_default(), config.ice_check_min_interval_or_default())) { return RTCError( RTCErrorType::INVALID_PARAMETER, "Receiving timeout is shorter than the minimal ping interval."); } if (config.backup_connection_ping_interval_or_default() < config.ice_check_interval_strong_connectivity_or_default()) { return RTCError(RTCErrorType::INVALID_PARAMETER, "Ping interval of backup candidate pairs is shorter than " "that of general candidate pairs when ICE is strongly " "connected"); } if (config.stable_writable_connection_ping_interval_or_default() < config.ice_check_interval_strong_connectivity_or_default()) { return RTCError(RTCErrorType::INVALID_PARAMETER, "Ping interval of stable and writable candidate pairs is " "shorter than that of general candidate pairs when ICE is " "strongly connected"); } if (config.ice_unwritable_timeout_or_default() > config.ice_inactive_timeout_or_default()) { return RTCError(RTCErrorType::INVALID_PARAMETER, "The timeout period for the writability state to become " "UNRELIABLE is longer than that to become TIMEOUT."); } if (config.regather_all_networks_interval_range && config.regather_all_networks_interval_range.value().min() < 0) { return RTCError( RTCErrorType::INVALID_RANGE, "The minimum regathering interval for all networks is negative."); } return RTCError::OK(); } const Connection* P2PTransportChannel::selected_connection() const { RTC_DCHECK_RUN_ON(network_thread_); return selected_connection_; } int P2PTransportChannel::check_receiving_interval() const { RTC_DCHECK_RUN_ON(network_thread_); return std::max(MIN_CHECK_RECEIVING_INTERVAL, config_.receiving_timeout_or_default() / 10); } void P2PTransportChannel::MaybeStartGathering() { RTC_DCHECK_RUN_ON(network_thread_); if (ice_parameters_.ufrag.empty() || ice_parameters_.pwd.empty()) { RTC_LOG(LS_ERROR) << "Cannot gather candidates because ICE parameters are empty" " ufrag: " << ice_parameters_.ufrag << " pwd: " << ice_parameters_.pwd; return; } // Start gathering if we never started before, or if an ICE restart occurred. if (allocator_sessions_.empty() || IceCredentialsChanged(allocator_sessions_.back()->ice_ufrag(), allocator_sessions_.back()->ice_pwd(), ice_parameters_.ufrag, ice_parameters_.pwd)) { if (gathering_state_ != kIceGatheringGathering) { gathering_state_ = kIceGatheringGathering; SignalGatheringState(this); } if (!allocator_sessions_.empty()) { IceRestartState state; if (writable()) { state = IceRestartState::CONNECTED; } else if (IsGettingPorts()) { state = IceRestartState::CONNECTING; } else { state = IceRestartState::DISCONNECTED; } RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRestartState", static_cast<int>(state), static_cast<int>(IceRestartState::MAX_VALUE)); } // Time for a new allocator. std::unique_ptr<PortAllocatorSession> pooled_session = allocator_->TakePooledSession(transport_name(), component(), ice_parameters_.ufrag, ice_parameters_.pwd); if (pooled_session) { AddAllocatorSession(std::move(pooled_session)); PortAllocatorSession* raw_pooled_session = allocator_sessions_.back().get(); // Process the pooled session's existing candidates/ports, if they exist. OnCandidatesReady(raw_pooled_session, raw_pooled_session->ReadyCandidates()); for (PortInterface* port : allocator_sessions_.back()->ReadyPorts()) { OnPortReady(raw_pooled_session, port); } if (allocator_sessions_.back()->CandidatesAllocationDone()) { OnCandidatesAllocationDone(raw_pooled_session); } } else { AddAllocatorSession(allocator_->CreateSession( transport_name(), component(), ice_parameters_.ufrag, ice_parameters_.pwd)); allocator_sessions_.back()->StartGettingPorts(); } } } // A new port is available, attempt to make connections for it void P2PTransportChannel::OnPortReady(PortAllocatorSession *session, PortInterface* port) { RTC_DCHECK_RUN_ON(network_thread_); // Set in-effect options on the new port for (OptionMap::const_iterator it = options_.begin(); it != options_.end(); ++it) { int val = port->SetOption(it->first, it->second); if (val < 0) { // Errors are frequent, so use LS_INFO. bugs.webrtc.org/9221 RTC_LOG(LS_INFO) << port->ToString() << ": SetOption(" << it->first << ", " << it->second << ") failed: " << port->GetError(); } } // Remember the ports and candidates, and signal that candidates are ready. // The session will handle this, and send an initiate/accept/modify message // if one is pending. port->SetIceRole(ice_role_); port->SetIceTiebreaker(tiebreaker_); ports_.push_back(port); port->SignalUnknownAddress.connect( this, &P2PTransportChannel::OnUnknownAddress); port->SignalDestroyed.connect(this, &P2PTransportChannel::OnPortDestroyed); port->SignalRoleConflict.connect( this, &P2PTransportChannel::OnRoleConflict); port->SignalSentPacket.connect(this, &P2PTransportChannel::OnSentPacket); // Attempt to create a connection from this new port to all of the remote // candidates that we were given so far. std::vector<RemoteCandidate>::iterator iter; for (iter = remote_candidates_.begin(); iter != remote_candidates_.end(); ++iter) { CreateConnection(port, *iter, iter->origin_port()); } SortConnectionsAndUpdateState( "new candidate pairs created from a new local candidate"); } // A new candidate is available, let listeners know void P2PTransportChannel::OnCandidatesReady( PortAllocatorSession* session, const std::vector<Candidate>& candidates) { RTC_DCHECK_RUN_ON(network_thread_); for (size_t i = 0; i < candidates.size(); ++i) { SignalCandidateGathered(this, candidates[i]); } } void P2PTransportChannel::OnCandidateError( PortAllocatorSession* session, const IceCandidateErrorEvent& event) { RTC_DCHECK(network_thread_ == rtc::Thread::Current()); SignalCandidateError(this, event); } void P2PTransportChannel::OnCandidatesAllocationDone( PortAllocatorSession* session) { RTC_DCHECK_RUN_ON(network_thread_); if (config_.gather_continually()) { RTC_LOG(LS_INFO) << "P2PTransportChannel: " << transport_name() << ", component " << component() << " gathering complete, but using continual " "gathering so not changing gathering state."; return; } gathering_state_ = kIceGatheringComplete; RTC_LOG(LS_INFO) << "P2PTransportChannel: " << transport_name() << ", component " << component() << " gathering complete"; SignalGatheringState(this); } // Handle stun packets void P2PTransportChannel::OnUnknownAddress( PortInterface* port, const rtc::SocketAddress& address, ProtocolType proto, IceMessage* stun_msg, const std::string &remote_username, bool port_muxed) { RTC_DCHECK_RUN_ON(network_thread_); // Port has received a valid stun packet from an address that no Connection // is currently available for. See if we already have a candidate with the // address. If it isn't we need to create new candidate for it. // // TODO(qingsi): There is a caveat of the logic below if we have remote // candidates with hostnames. We could create a prflx candidate that is // identical to a host candidate that are currently in the process of name // resolution. We would not have a duplicate candidate since when adding the // resolved host candidate, FinishingAddingRemoteCandidate does // MaybeUpdatePeerReflexiveCandidate, and the prflx candidate would be updated // to a host candidate. As a result, for a brief moment we would have a prflx // candidate showing a private IP address, though we do not signal prflx // candidates to applications and we could obfuscate the IP addresses of prflx // candidates in P2PTransportChannel::GetStats. The difficulty of preventing // creating the prflx from the beginning is that we do not have a reliable way // to claim two candidates are identical without the address information. If // we always pause the addition of a prflx candidate when there is ongoing // name resolution and dedup after we have a resolved address, we run into the // risk of losing/delaying the addition of a non-identical candidate that // could be the only way to have a connection, if the resolution never // completes or is significantly delayed. const Candidate* candidate = nullptr; for (const Candidate& c : remote_candidates_) { if (c.username() == remote_username && c.address() == address && c.protocol() == ProtoToString(proto)) { candidate = &c; break; } } uint32_t remote_generation = 0; std::string remote_password; // The STUN binding request may arrive after setRemoteDescription and before // adding remote candidate, so we need to set the password to the shared // password and set the generation if the user name matches. const IceParameters* ice_param = FindRemoteIceFromUfrag(remote_username, &remote_generation); // Note: if not found, the remote_generation will still be 0. if (ice_param != nullptr) { remote_password = ice_param->pwd; } Candidate remote_candidate; bool remote_candidate_is_new = (candidate == nullptr); if (!remote_candidate_is_new) { remote_candidate = *candidate; } else { // Create a new candidate with this address. // The priority of the candidate is set to the PRIORITY attribute // from the request. const StunUInt32Attribute* priority_attr = stun_msg->GetUInt32(STUN_ATTR_PRIORITY); if (!priority_attr) { RTC_LOG(LS_WARNING) << "P2PTransportChannel::OnUnknownAddress - " "No STUN_ATTR_PRIORITY found in the " "stun request message"; port->SendBindingErrorResponse(stun_msg, address, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST); return; } int remote_candidate_priority = priority_attr->value(); uint16_t network_id = 0; uint16_t network_cost = 0; const StunUInt32Attribute* network_attr = stun_msg->GetUInt32(STUN_ATTR_NETWORK_INFO); if (network_attr) { uint32_t network_info = network_attr->value(); network_id = static_cast<uint16_t>(network_info >> 16); network_cost = static_cast<uint16_t>(network_info); } // RFC 5245 // If the source transport address of the request does not match any // existing remote candidates, it represents a new peer reflexive remote // candidate. remote_candidate = Candidate( component(), ProtoToString(proto), address, remote_candidate_priority, remote_username, remote_password, PRFLX_PORT_TYPE, remote_generation, "", network_id, network_cost); // From RFC 5245, section-7.2.1.3: // The foundation of the candidate is set to an arbitrary value, different // from the foundation for all other remote candidates. remote_candidate.set_foundation( rtc::ToString(rtc::ComputeCrc32(remote_candidate.id()))); } // RFC5245, the agent constructs a pair whose local candidate is equal to // the transport address on which the STUN request was received, and a // remote candidate equal to the source transport address where the // request came from. // There shouldn't be an existing connection with this remote address. // When ports are muxed, this channel might get multiple unknown address // signals. In that case if the connection is already exists, we should // simply ignore the signal otherwise send server error. if (port->GetConnection(remote_candidate.address())) { if (port_muxed) { RTC_LOG(LS_INFO) << "Connection already exists for peer reflexive " "candidate: " << remote_candidate.ToString(); return; } else { RTC_NOTREACHED(); port->SendBindingErrorResponse(stun_msg, address, STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR); return; } } Connection* connection = port->CreateConnection(remote_candidate, PortInterface::ORIGIN_THIS_PORT); if (!connection) { // This could happen in some scenarios. For example, a TurnPort may have // had a refresh request timeout, so it won't create connections. port->SendBindingErrorResponse(stun_msg, address, STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR); return; } RTC_LOG(LS_INFO) << "Adding connection from " << (remote_candidate_is_new ? "peer reflexive" : "resurrected") << " candidate: " << remote_candidate.ToString(); AddConnection(connection); connection->HandleBindingRequest(stun_msg); // Update the list of connections since we just added another. We do this // after sending the response since it could (in principle) delete the // connection in question. SortConnectionsAndUpdateState( "a new candidate pair created from an unknown remote address"); } void P2PTransportChannel::OnCandidateFilterChanged(uint32_t prev_filter, uint32_t cur_filter) { RTC_DCHECK_RUN_ON(network_thread_); if (prev_filter == cur_filter || allocator_session() == nullptr) { return; } if (config_.surface_ice_candidates_on_ice_transport_type_changed) { allocator_session()->SetCandidateFilter(cur_filter); } } void P2PTransportChannel::OnRoleConflict(PortInterface* port) { SignalRoleConflict(this); // STUN ping will be sent when SetRole is called // from Transport. } const IceParameters* P2PTransportChannel::FindRemoteIceFromUfrag( const std::string& ufrag, uint32_t* generation) { RTC_DCHECK_RUN_ON(network_thread_); const auto& params = remote_ice_parameters_; auto it = std::find_if( params.rbegin(), params.rend(), [ufrag](const IceParameters& param) { return param.ufrag == ufrag; }); if (it == params.rend()) { // Not found. return nullptr; } *generation = params.rend() - it - 1; return &(*it); } void P2PTransportChannel::OnNominated(Connection* conn) { RTC_DCHECK_RUN_ON(network_thread_); RTC_DCHECK(ice_role_ == ICEROLE_CONTROLLED); if (selected_connection_ == conn) { return; } // TODO(qingsi): RequestSortAndStateUpdate will eventually call // MaybeSwitchSelectedConnection again. Rewrite this logic. if (MaybeSwitchSelectedConnection(conn, "nomination on the controlled side")) { // Now that we have selected a connection, it is time to prune other // connections and update the read/write state of the channel. RequestSortAndStateUpdate("nomination on the controlled side"); } else { RTC_LOG(LS_INFO) << "Not switching the selected connection on controlled side yet: " << conn->ToString(); } } void P2PTransportChannel::ResolveHostnameCandidate(const Candidate& candidate) { RTC_DCHECK_RUN_ON(network_thread_); if (!async_resolver_factory_) { RTC_LOG(LS_WARNING) << "Dropping ICE candidate with hostname address " << "(no AsyncResolverFactory)"; return; } rtc::AsyncResolverInterface* resolver = async_resolver_factory_->Create(); resolvers_.emplace_back(candidate, resolver); resolver->SignalDone.connect(this, &P2PTransportChannel::OnCandidateResolved); resolver->Start(candidate.address()); RTC_LOG(LS_INFO) << "Asynchronously resolving ICE candidate hostname " << candidate.address().HostAsSensitiveURIString(); } void P2PTransportChannel::AddRemoteCandidate(const Candidate& candidate) { RTC_DCHECK_RUN_ON(network_thread_); uint32_t generation = GetRemoteCandidateGeneration(candidate); // If a remote candidate with a previous generation arrives, drop it. if (generation < remote_ice_generation()) { RTC_LOG(LS_WARNING) << "Dropping a remote candidate because its ufrag " << candidate.username() << " indicates it was for a previous generation."; return; } Candidate new_remote_candidate(candidate); new_remote_candidate.set_generation(generation); // ICE candidates don't need to have username and password set, but // the code below this (specifically, ConnectionRequest::Prepare in // port.cc) uses the remote candidates's username. So, we set it // here. if (remote_ice()) { if (candidate.username().empty()) { new_remote_candidate.set_username(remote_ice()->ufrag); } if (new_remote_candidate.username() == remote_ice()->ufrag) { if (candidate.password().empty()) { new_remote_candidate.set_password(remote_ice()->pwd); } } else { // The candidate belongs to the next generation. Its pwd will be set // when the new remote ICE credentials arrive. RTC_LOG(LS_WARNING) << "A remote candidate arrives with an unknown ufrag: " << candidate.username(); } } if (new_remote_candidate.address().IsUnresolvedIP()) { ResolveHostnameCandidate(new_remote_candidate); return; } FinishAddingRemoteCandidate(new_remote_candidate); } P2PTransportChannel::CandidateAndResolver::CandidateAndResolver( const Candidate& candidate, rtc::AsyncResolverInterface* resolver) : candidate_(candidate), resolver_(resolver) {} P2PTransportChannel::CandidateAndResolver::~CandidateAndResolver() {} void P2PTransportChannel::OnCandidateResolved( rtc::AsyncResolverInterface* resolver) { RTC_DCHECK_RUN_ON(network_thread_); auto p = absl::c_find_if(resolvers_, [resolver](const CandidateAndResolver& cr) { return cr.resolver_ == resolver; }); if (p == resolvers_.end()) { RTC_LOG(LS_ERROR) << "Unexpected AsyncResolver signal"; RTC_NOTREACHED(); return; } Candidate candidate = p->candidate_; resolvers_.erase(p); AddRemoteCandidateWithResolver(candidate, resolver); invoker_.AsyncInvoke<void>( RTC_FROM_HERE, thread(), rtc::Bind(&rtc::AsyncResolverInterface::Destroy, resolver, false)); } void P2PTransportChannel::AddRemoteCandidateWithResolver( Candidate candidate, rtc::AsyncResolverInterface* resolver) { RTC_DCHECK_RUN_ON(network_thread_); if (resolver->GetError()) { RTC_LOG(LS_WARNING) << "Failed to resolve ICE candidate hostname " << candidate.address().HostAsSensitiveURIString() << " with error " << resolver->GetError(); return; } rtc::SocketAddress resolved_address; // Prefer IPv6 to IPv4 if we have it (see RFC 5245 Section 15.1). // TODO(zstein): This won't work if we only have IPv4 locally but receive an // AAAA DNS record. bool have_address = resolver->GetResolvedAddress(AF_INET6, &resolved_address) || resolver->GetResolvedAddress(AF_INET, &resolved_address); if (!have_address) { RTC_LOG(LS_INFO) << "ICE candidate hostname " << candidate.address().HostAsSensitiveURIString() << " could not be resolved"; return; } RTC_LOG(LS_INFO) << "Resolved ICE candidate hostname " << candidate.address().HostAsSensitiveURIString() << " to " << resolved_address.ipaddr().ToSensitiveString(); candidate.set_address(resolved_address); FinishAddingRemoteCandidate(candidate); } void P2PTransportChannel::FinishAddingRemoteCandidate( const Candidate& new_remote_candidate) { RTC_DCHECK_RUN_ON(network_thread_); // If this candidate matches what was thought to be a peer reflexive // candidate, we need to update the candidate priority/etc. for (Connection* conn : connections_) { conn->MaybeUpdatePeerReflexiveCandidate(new_remote_candidate); } // Create connections to this remote candidate. CreateConnections(new_remote_candidate, NULL); // Resort the connections list, which may have new elements. SortConnectionsAndUpdateState( "new candidate pairs created from a new remote candidate"); } void P2PTransportChannel::RemoveRemoteCandidate( const Candidate& cand_to_remove) { RTC_DCHECK_RUN_ON(network_thread_); auto iter = std::remove_if(remote_candidates_.begin(), remote_candidates_.end(), [cand_to_remove](const Candidate& candidate) { return cand_to_remove.MatchesForRemoval(candidate); }); if (iter != remote_candidates_.end()) { RTC_LOG(LS_VERBOSE) << "Removed remote candidate " << cand_to_remove.ToString(); remote_candidates_.erase(iter, remote_candidates_.end()); } } void P2PTransportChannel::RemoveAllRemoteCandidates() { RTC_DCHECK_RUN_ON(network_thread_); remote_candidates_.clear(); } // Creates connections from all of the ports that we care about to the given // remote candidate. The return value is true if we created a connection from // the origin port. bool P2PTransportChannel::CreateConnections(const Candidate& remote_candidate, PortInterface* origin_port) { RTC_DCHECK_RUN_ON(network_thread_); // If we've already seen the new remote candidate (in the current candidate // generation), then we shouldn't try creating connections for it. // We either already have a connection for it, or we previously created one // and then later pruned it. If we don't return, the channel will again // re-create any connections that were previously pruned, which will then // immediately be re-pruned, churning the network for no purpose. // This only applies to candidates received over signaling (i.e. origin_port // is NULL). if (!origin_port && IsDuplicateRemoteCandidate(remote_candidate)) { // return true to indicate success, without creating any new connections. return true; } // Add a new connection for this candidate to every port that allows such a // connection (i.e., if they have compatible protocols) and that does not // already have a connection to an equivalent candidate. We must be careful // to make sure that the origin port is included, even if it was pruned, // since that may be the only port that can create this connection. bool created = false; std::vector<PortInterface *>::reverse_iterator it; for (it = ports_.rbegin(); it != ports_.rend(); ++it) { if (CreateConnection(*it, remote_candidate, origin_port)) { if (*it == origin_port) created = true; } } if ((origin_port != NULL) && !absl::c_linear_search(ports_, origin_port)) { if (CreateConnection(origin_port, remote_candidate, origin_port)) created = true; } // Remember this remote candidate so that we can add it to future ports. RememberRemoteCandidate(remote_candidate, origin_port); return created; } // Setup a connection object for the local and remote candidate combination. // And then listen to connection object for changes. bool P2PTransportChannel::CreateConnection(PortInterface* port, const Candidate& remote_candidate, PortInterface* origin_port) { RTC_DCHECK_RUN_ON(network_thread_); if (!port->SupportsProtocol(remote_candidate.protocol())) { return false; } // Look for an existing connection with this remote address. If one is not // found or it is found but the existing remote candidate has an older // generation, then we can create a new connection for this address. Connection* connection = port->GetConnection(remote_candidate.address()); if (connection == nullptr || connection->remote_candidate().generation() < remote_candidate.generation()) { // Don't create a connection if this is a candidate we received in a // message and we are not allowed to make outgoing connections. PortInterface::CandidateOrigin origin = GetOrigin(port, origin_port); if (origin == PortInterface::ORIGIN_MESSAGE && incoming_only_) { return false; } Connection* connection = port->CreateConnection(remote_candidate, origin); if (!connection) { return false; } AddConnection(connection); RTC_LOG(LS_INFO) << ToString() << ": Created connection with origin: " << origin << ", total: " << connections_.size(); return true; } // No new connection was created. // It is not legal to try to change any of the parameters of an existing // connection; however, the other side can send a duplicate candidate. if (!remote_candidate.IsEquivalent(connection->remote_candidate())) { RTC_LOG(INFO) << "Attempt to change a remote candidate." " Existing remote candidate: " << connection->remote_candidate().ToString() << "New remote candidate: " << remote_candidate.ToString(); } return false; } bool P2PTransportChannel::FindConnection(Connection* connection) const { RTC_DCHECK_RUN_ON(network_thread_); return absl::c_linear_search(connections_, connection); } uint32_t P2PTransportChannel::GetRemoteCandidateGeneration( const Candidate& candidate) { RTC_DCHECK_RUN_ON(network_thread_); // If the candidate has a ufrag, use it to find the generation. if (!candidate.username().empty()) { uint32_t generation = 0; if (!FindRemoteIceFromUfrag(candidate.username(), &generation)) { // If the ufrag is not found, assume the next/future generation. generation = static_cast<uint32_t>(remote_ice_parameters_.size()); } return generation; } // If candidate generation is set, use that. if (candidate.generation() > 0) { return candidate.generation(); } // Otherwise, assume the generation from remote ice parameters. return remote_ice_generation(); } // Check if remote candidate is already cached. bool P2PTransportChannel::IsDuplicateRemoteCandidate( const Candidate& candidate) { RTC_DCHECK_RUN_ON(network_thread_); for (size_t i = 0; i < remote_candidates_.size(); ++i) { if (remote_candidates_[i].IsEquivalent(candidate)) { return true; } } return false; } // Maintain our remote candidate list, adding this new remote one. void P2PTransportChannel::RememberRemoteCandidate( const Candidate& remote_candidate, PortInterface* origin_port) { RTC_DCHECK_RUN_ON(network_thread_); // Remove any candidates whose generation is older than this one. The // presence of a new generation indicates that the old ones are not useful. size_t i = 0; while (i < remote_candidates_.size()) { if (remote_candidates_[i].generation() < remote_candidate.generation()) { RTC_LOG(INFO) << "Pruning candidate from old generation: " << remote_candidates_[i].address().ToSensitiveString(); remote_candidates_.erase(remote_candidates_.begin() + i); } else { i += 1; } } // Make sure this candidate is not a duplicate. if (IsDuplicateRemoteCandidate(remote_candidate)) { RTC_LOG(INFO) << "Duplicate candidate: " << remote_candidate.ToString(); return; } // Try this candidate for all future ports. remote_candidates_.push_back(RemoteCandidate(remote_candidate, origin_port)); } // Set options on ourselves is simply setting options on all of our available // port objects. int P2PTransportChannel::SetOption(rtc::Socket::Option opt, int value) { RTC_DCHECK_RUN_ON(network_thread_); OptionMap::iterator it = options_.find(opt); if (it == options_.end()) { options_.insert(std::make_pair(opt, value)); } else if (it->second == value) { return 0; } else { it->second = value; } for (PortInterface* port : ports_) { int val = port->SetOption(opt, value); if (val < 0) { // Because this also occurs deferred, probably no point in reporting an // error RTC_LOG(WARNING) << "SetOption(" << opt << ", " << value << ") failed: " << port->GetError(); } } return 0; } bool P2PTransportChannel::GetOption(rtc::Socket::Option opt, int* value) { RTC_DCHECK_RUN_ON(network_thread_); const auto& found = options_.find(opt); if (found == options_.end()) { return false; } *value = found->second; return true; } int P2PTransportChannel::GetError() { RTC_DCHECK_RUN_ON(network_thread_); return error_; } // Send data to the other side, using our selected connection. int P2PTransportChannel::SendPacket(const char *data, size_t len, const rtc::PacketOptions& options, int flags) { RTC_DCHECK_RUN_ON(network_thread_); if (flags != 0) { error_ = EINVAL; return -1; } // If we don't think the connection is working yet, return ENOTCONN // instead of sending a packet that will probably be dropped. if (!ReadyToSend(selected_connection_)) { error_ = ENOTCONN; return -1; } last_sent_packet_id_ = options.packet_id; rtc::PacketOptions modified_options(options); modified_options.info_signaled_after_sent.packet_type = rtc::PacketType::kData; int sent = selected_connection_->Send(data, len, modified_options); if (sent <= 0) { RTC_DCHECK(sent < 0); error_ = selected_connection_->GetError(); } return sent; } bool P2PTransportChannel::GetStats(ConnectionInfos* candidate_pair_stats_list, CandidateStatsList* candidate_stats_list) { RTC_DCHECK_RUN_ON(network_thread_); // Gather candidate and candidate pair stats. candidate_stats_list->clear(); candidate_pair_stats_list->clear(); if (!allocator_sessions_.empty()) { allocator_session()->GetCandidateStatsFromReadyPorts(candidate_stats_list); } // TODO(qingsi): Remove naming inconsistency for candidate pair/connection. for (Connection* connection : connections_) { ConnectionInfo candidate_pair_stats = connection->stats(); candidate_pair_stats.best_connection = (selected_connection_ == connection); candidate_pair_stats_list->push_back(std::move(candidate_pair_stats)); connection->set_reported(true); } return true; } absl::optional<rtc::NetworkRoute> P2PTransportChannel::network_route() const { RTC_DCHECK_RUN_ON(network_thread_); return network_route_; } rtc::DiffServCodePoint P2PTransportChannel::DefaultDscpValue() const { RTC_DCHECK_RUN_ON(network_thread_); OptionMap::const_iterator it = options_.find(rtc::Socket::OPT_DSCP); if (it == options_.end()) { return rtc::DSCP_NO_CHANGE; } return static_cast<rtc::DiffServCodePoint> (it->second); } // Monitor connection states. void P2PTransportChannel::UpdateConnectionStates() { RTC_DCHECK_RUN_ON(network_thread_); int64_t now = rtc::TimeMillis(); // We need to copy the list of connections since some may delete themselves // when we call UpdateState. for (Connection* c : connections_) { c->UpdateState(now); } } // Prepare for best candidate sorting. void P2PTransportChannel::RequestSortAndStateUpdate( const std::string& reason_to_sort) { RTC_DCHECK_RUN_ON(network_thread_); if (!sort_dirty_) { invoker_.AsyncInvoke<void>( RTC_FROM_HERE, thread(), rtc::Bind(&P2PTransportChannel::SortConnectionsAndUpdateState, this, reason_to_sort)); sort_dirty_ = true; } } void P2PTransportChannel::MaybeStartPinging() { RTC_DCHECK_RUN_ON(network_thread_); if (started_pinging_) { return; } int64_t now = rtc::TimeMillis(); if (absl::c_any_of(connections_, [this, now](const Connection* c) { return IsPingable(c, now); })) { RTC_LOG(LS_INFO) << ToString() << ": Have a pingable connection for the first time; " "starting to ping."; invoker_.AsyncInvoke<void>( RTC_FROM_HERE, thread(), rtc::Bind(&P2PTransportChannel::CheckAndPing, this)); regathering_controller_->Start(); started_pinging_ = true; } } int P2PTransportChannel::CompareCandidatePairNetworks( const Connection* a, const Connection* b, absl::optional<rtc::AdapterType> network_preference) const { RTC_DCHECK_RUN_ON(network_thread_); int compare_a_b_by_network_preference = CompareCandidatePairsByNetworkPreference(a, b, config_.network_preference); // The network preference has a higher precedence than the network cost. if (compare_a_b_by_network_preference != a_and_b_equal) { return compare_a_b_by_network_preference; } uint32_t a_cost = a->ComputeNetworkCost(); uint32_t b_cost = b->ComputeNetworkCost(); // Prefer lower network cost. if (a_cost < b_cost) { return a_is_better; } if (a_cost > b_cost) { return b_is_better; } return a_and_b_equal; } // Compare two connections based on their writing, receiving, and connected // states. int P2PTransportChannel::CompareConnectionStates( const Connection* a, const Connection* b, absl::optional<int64_t> receiving_unchanged_threshold, bool* missed_receiving_unchanged_threshold) const { RTC_DCHECK_RUN_ON(network_thread_); // First, prefer a connection that's writable or presumed writable over // one that's not writable. bool a_writable = a->writable() || PresumedWritable(a); bool b_writable = b->writable() || PresumedWritable(b); if (a_writable && !b_writable) { return a_is_better; } if (!a_writable && b_writable) { return b_is_better; } // Sort based on write-state. Better states have lower values. if (a->write_state() < b->write_state()) { return a_is_better; } if (b->write_state() < a->write_state()) { return b_is_better; } // We prefer a receiving connection to a non-receiving, higher-priority // connection when sorting connections and choosing which connection to // switch to. if (a->receiving() && !b->receiving()) { return a_is_better; } if (!a->receiving() && b->receiving()) { if (!receiving_unchanged_threshold || (a->receiving_unchanged_since() <= *receiving_unchanged_threshold && b->receiving_unchanged_since() <= *receiving_unchanged_threshold)) { return b_is_better; } *missed_receiving_unchanged_threshold = true; } // WARNING: Some complexity here about TCP reconnecting. // When a TCP connection fails because of a TCP socket disconnecting, the // active side of the connection will attempt to reconnect for 5 seconds while // pretending to be writable (the connection is not set to the unwritable // state). On the passive side, the connection also remains writable even // though it is disconnected, and a new connection is created when the active // side connects. At that point, there are two TCP connections on the passive // side: 1. the old, disconnected one that is pretending to be writable, and // 2. the new, connected one that is maybe not yet writable. For purposes of // pruning, pinging, and selecting the selected connection, we want to treat // the new connection as "better" than the old one. We could add a method // called something like Connection::ImReallyBadEvenThoughImWritable, but that // is equivalent to the existing Connection::connected(), which we already // have. So, in code throughout this file, we'll check whether the connection // is connected() or not, and if it is not, treat it as "worse" than a // connected one, even though it's writable. In the code below, we're doing // so to make sure we treat a new writable connection as better than an old // disconnected connection. // In the case where we reconnect TCP connections, the original best // connection is disconnected without changing to WRITE_TIMEOUT. In this case, // the new connection, when it becomes writable, should have higher priority. if (a->write_state() == Connection::STATE_WRITABLE && b->write_state() == Connection::STATE_WRITABLE) { if (a->connected() && !b->connected()) { return a_is_better; } if (!a->connected() && b->connected()) { return b_is_better; } } return 0; } // Compares two connections based only on the candidate and network information. // Returns positive if |a| is better than |b|. int P2PTransportChannel::CompareConnectionCandidates( const Connection* a, const Connection* b) const { RTC_DCHECK_RUN_ON(network_thread_); int compare_a_b_by_networks = CompareCandidatePairNetworks(a, b, config_.network_preference); if (compare_a_b_by_networks != a_and_b_equal) { return compare_a_b_by_networks; } // Compare connection priority. Lower values get sorted last. if (a->priority() > b->priority()) { return a_is_better; } if (a->priority() < b->priority()) { return b_is_better; } // If we're still tied at this point, prefer a younger generation. // (Younger generation means a larger generation number). int cmp = (a->remote_candidate().generation() + a->port()->generation()) - (b->remote_candidate().generation() + b->port()->generation()); if (cmp != 0) { return cmp; } // A periodic regather (triggered by the regather_all_networks_interval_range) // will produce candidates that appear the same but would use a new port. We // want to use the new candidates and purge the old candidates as they come // in, so use the fact that the old ports get pruned immediately to rank the // candidates with an active port/remote candidate higher. bool a_pruned = IsPortPruned(a->port()) || IsRemoteCandidatePruned(a->remote_candidate()); bool b_pruned = IsPortPruned(b->port()) || IsRemoteCandidatePruned(b->remote_candidate()); if (!a_pruned && b_pruned) { return a_is_better; } if (a_pruned && !b_pruned) { return b_is_better; } // Otherwise, must be equal return 0; } bool P2PTransportChannel::IsPortPruned(const Port* port) const { RTC_DCHECK_RUN_ON(network_thread_); return !absl::c_linear_search(ports_, port); } bool P2PTransportChannel::IsRemoteCandidatePruned(const Candidate& cand) const { RTC_DCHECK_RUN_ON(network_thread_); return !absl::c_linear_search(remote_candidates_, cand); } int P2PTransportChannel::CompareConnections( const Connection* a, const Connection* b, absl::optional<int64_t> receiving_unchanged_threshold, bool* missed_receiving_unchanged_threshold) const { RTC_DCHECK_RUN_ON(network_thread_); RTC_CHECK(a != nullptr); RTC_CHECK(b != nullptr); // We prefer to switch to a writable and receiving connection over a // non-writable or non-receiving connection, even if the latter has // been nominated by the controlling side. int state_cmp = CompareConnectionStates(a, b, receiving_unchanged_threshold, missed_receiving_unchanged_threshold); if (state_cmp != 0) { return state_cmp; } if (ice_role_ == ICEROLE_CONTROLLED) { // Compare the connections based on the nomination states and the last data // received time if this is on the controlled side. if (a->remote_nomination() > b->remote_nomination()) { return a_is_better; } if (a->remote_nomination() < b->remote_nomination()) { return b_is_better; } if (a->last_data_received() > b->last_data_received()) { return a_is_better; } if (a->last_data_received() < b->last_data_received()) { return b_is_better; } } // Compare the network cost and priority. return CompareConnectionCandidates(a, b); } bool P2PTransportChannel::PresumedWritable(const Connection* conn) const { RTC_DCHECK_RUN_ON(network_thread_); return (conn->write_state() == Connection::STATE_WRITE_INIT && config_.presume_writable_when_fully_relayed && conn->local_candidate().type() == RELAY_PORT_TYPE && (conn->remote_candidate().type() == RELAY_PORT_TYPE || conn->remote_candidate().type() == PRFLX_PORT_TYPE)); } // Sort the available connections to find the best one. We also monitor // the number of available connections and the current state. void P2PTransportChannel::SortConnectionsAndUpdateState( const std::string& reason_to_sort) { RTC_DCHECK_RUN_ON(network_thread_); // Make sure the connection states are up-to-date since this affects how they // will be sorted. UpdateConnectionStates(); // Any changes after this point will require a re-sort. sort_dirty_ = false; // Find the best alternative connection by sorting. It is important to note // that amongst equal preference, writable connections, this will choose the // one whose estimated latency is lowest. So it is the only one that we // need to consider switching to. // TODO(honghaiz): Don't sort; Just use std::max_element in the right places. absl::c_stable_sort( connections_, [this](const Connection* a, const Connection* b) { int cmp = CompareConnections(a, b, absl::nullopt, nullptr); if (cmp != 0) { return cmp > 0; } // Otherwise, sort based on latency estimate. return a->rtt() < b->rtt(); }); RTC_LOG(LS_VERBOSE) << "Sorting " << connections_.size() << " available connections"; for (size_t i = 0; i < connections_.size(); ++i) { RTC_LOG(LS_VERBOSE) << connections_[i]->ToString(); } Connection* top_connection = (connections_.size() > 0) ? connections_[0] : nullptr; // If necessary, switch to the new choice. Note that |top_connection| doesn't // have to be writable to become the selected connection although it will // have higher priority if it is writable. MaybeSwitchSelectedConnection(top_connection, reason_to_sort); // The controlled side can prune only if the selected connection has been // nominated because otherwise it may prune the connection that will be // selected by the controlling side. // TODO(honghaiz): This is not enough to prevent a connection from being // pruned too early because with aggressive nomination, the controlling side // will nominate every connection until it becomes writable. if (ice_role_ == ICEROLE_CONTROLLING || (selected_connection_ && selected_connection_->nominated())) { PruneConnections(); } // Check if all connections are timedout. bool all_connections_timedout = true; for (size_t i = 0; i < connections_.size(); ++i) { if (connections_[i]->write_state() != Connection::STATE_WRITE_TIMEOUT) { all_connections_timedout = false; break; } } // Now update the writable state of the channel with the information we have // so far. if (all_connections_timedout) { HandleAllTimedOut(); } // Update the state of this channel. UpdateState(); // Also possibly start pinging. // We could start pinging if: // * The first connection was created. // * ICE credentials were provided. // * A TCP connection became connected. MaybeStartPinging(); } std::map<rtc::Network*, Connection*> P2PTransportChannel::GetBestConnectionByNetwork() const { RTC_DCHECK_RUN_ON(network_thread_); // |connections_| has been sorted, so the first one in the list on a given // network is the best connection on the network, except that the selected // connection is always the best connection on the network. std::map<rtc::Network*, Connection*> best_connection_by_network; if (selected_connection_) { best_connection_by_network[selected_connection_->port()->Network()] = selected_connection_; } // TODO(honghaiz): Need to update this if |connections_| are not sorted. for (Connection* conn : connections_) { rtc::Network* network = conn->port()->Network(); // This only inserts when the network does not exist in the map. best_connection_by_network.insert(std::make_pair(network, conn)); } return best_connection_by_network; } std::vector<Connection*> P2PTransportChannel::GetBestWritableConnectionPerNetwork() const { std::vector<Connection*> connections; for (auto kv : GetBestConnectionByNetwork()) { Connection* conn = kv.second; if (conn->writable() && conn->connected()) { connections.push_back(conn); } } return connections; } void P2PTransportChannel::PruneConnections() { // We can prune any connection for which there is a connected, writable // connection on the same network with better or equal priority. We leave // those with better priority just in case they become writable later (at // which point, we would prune out the current selected connection). We leave // connections on other networks because they may not be using the same // resources and they may represent very distinct paths over which we can // switch. If |best_conn_on_network| is not connected, we may be reconnecting // a TCP connection and should not prune connections in this network. // See the big comment in CompareConnectionStates. // // An exception is made for connections on an "any address" network, meaning // not bound to any specific network interface. We don't want to keep one of // these alive as a backup, since it could be using the same network // interface as the higher-priority, selected candidate pair. RTC_DCHECK_RUN_ON(network_thread_); auto best_connection_by_network = GetBestConnectionByNetwork(); for (Connection* conn : connections_) { Connection* best_conn = selected_connection_; if (!rtc::IPIsAny(conn->port()->Network()->ip())) { // If the connection is bound to a specific network interface (not an // "any address" network), compare it against the best connection for // that network interface rather than the best connection overall. This // ensures that at least one connection per network will be left // unpruned. best_conn = best_connection_by_network[conn->port()->Network()]; } // Do not prune connections if the connection being compared against is // weak. Otherwise, it may delete connections prematurely. if (best_conn && conn != best_conn && !best_conn->weak() && CompareConnectionCandidates(best_conn, conn) >= 0) { conn->Prune(); } } } // Change the selected connection, and let listeners know. void P2PTransportChannel::SwitchSelectedConnection(Connection* conn) { RTC_DCHECK_RUN_ON(network_thread_); // Note: if conn is NULL, the previous |selected_connection_| has been // destroyed, so don't use it. Connection* old_selected_connection = selected_connection_; selected_connection_ = conn; LogCandidatePairConfig(conn, webrtc::IceCandidatePairConfigType::kSelected); network_route_.reset(); if (old_selected_connection) { old_selected_connection->set_selected(false); } if (selected_connection_) { ++nomination_; selected_connection_->set_selected(true); if (old_selected_connection) { RTC_LOG(LS_INFO) << ToString() << ": Previous selected connection: " << old_selected_connection->ToString(); } RTC_LOG(LS_INFO) << ToString() << ": New selected connection: " << selected_connection_->ToString(); SignalRouteChange(this, selected_connection_->remote_candidate()); // This is a temporary, but safe fix to webrtc issue 5705. // TODO(honghaiz): Make all ENOTCONN error routed through the transport // channel so that it knows whether the media channel is allowed to // send; then it will only signal ready-to-send if the media channel // has been disallowed to send. if (selected_connection_->writable() || PresumedWritable(selected_connection_)) { SignalReadyToSend(this); } network_route_.emplace(rtc::NetworkRoute()); network_route_->connected = ReadyToSend(selected_connection_); network_route_->local_network_id = selected_connection_->local_candidate().network_id(); network_route_->remote_network_id = selected_connection_->remote_candidate().network_id(); network_route_->last_sent_packet_id = last_sent_packet_id_; network_route_->packet_overhead = GetIpOverhead( selected_connection_->local_candidate().address().family()) + GetProtocolOverhead(selected_connection_->local_candidate().protocol()); } else { RTC_LOG(LS_INFO) << ToString() << ": No selected connection"; } SignalNetworkRouteChanged(network_route_); } // Warning: UpdateState should eventually be called whenever a connection // is added, deleted, or the write state of any connection changes so that the // transport controller will get the up-to-date channel state. However it // should not be called too often; in the case that multiple connection states // change, it should be called after all the connection states have changed. For // example, we call this at the end of SortConnectionsAndUpdateState. void P2PTransportChannel::UpdateState() { RTC_DCHECK_RUN_ON(network_thread_); // If our selected connection is "presumed writable" (TURN-TURN with no // CreatePermission required), act like we're already writable to the upper // layers, so they can start media quicker. bool writable = selected_connection_ && (selected_connection_->writable() || PresumedWritable(selected_connection_)); SetWritable(writable); bool receiving = false; for (const Connection* connection : connections_) { if (connection->receiving()) { receiving = true; break; } } SetReceiving(receiving); IceTransportState state = ComputeState(); webrtc::IceTransportState current_standardized_state = ComputeIceTransportState(); if (state_ != state) { RTC_LOG(LS_INFO) << ToString() << ": Transport channel state changed from " << static_cast<int>(state_) << " to " << static_cast<int>(state); // Check that the requested transition is allowed. Note that // P2PTransportChannel does not (yet) implement a direct mapping of the ICE // states from the standard; the difference is covered by // TransportController and PeerConnection. switch (state_) { case IceTransportState::STATE_INIT: // TODO(deadbeef): Once we implement end-of-candidates signaling, // we shouldn't go from INIT to COMPLETED. RTC_DCHECK(state == IceTransportState::STATE_CONNECTING || state == IceTransportState::STATE_COMPLETED); break; case IceTransportState::STATE_CONNECTING: RTC_DCHECK(state == IceTransportState::STATE_COMPLETED || state == IceTransportState::STATE_FAILED); break; case IceTransportState::STATE_COMPLETED: // TODO(deadbeef): Once we implement end-of-candidates signaling, // we shouldn't go from COMPLETED to CONNECTING. // Though we *can* go from COMPlETED to FAILED, if consent expires. RTC_DCHECK(state == IceTransportState::STATE_CONNECTING || state == IceTransportState::STATE_FAILED); break; case IceTransportState::STATE_FAILED: // TODO(deadbeef): Once we implement end-of-candidates signaling, // we shouldn't go from FAILED to CONNECTING or COMPLETED. RTC_DCHECK(state == IceTransportState::STATE_CONNECTING || state == IceTransportState::STATE_COMPLETED); break; default: RTC_NOTREACHED(); break; } state_ = state; SignalStateChanged(this); } if (standardized_state_ != current_standardized_state) { standardized_state_ = current_standardized_state; SignalIceTransportStateChanged(this); } } void P2PTransportChannel::MaybeStopPortAllocatorSessions() { RTC_DCHECK_RUN_ON(network_thread_); if (!IsGettingPorts()) { return; } for (const auto& session : allocator_sessions_) { if (session->IsStopped()) { continue; } // If gathering continually, keep the last session running so that // it can gather candidates if the networks change. if (config_.gather_continually() && session == allocator_sessions_.back()) { session->ClearGettingPorts(); } else { session->StopGettingPorts(); } } } // If all connections timed out, delete them all. void P2PTransportChannel::HandleAllTimedOut() { RTC_DCHECK_RUN_ON(network_thread_); for (Connection* connection : connections_) { connection->Destroy(); } } bool P2PTransportChannel::weak() const { RTC_DCHECK_RUN_ON(network_thread_); return !selected_connection_ || selected_connection_->weak(); } bool P2PTransportChannel::ReadyToSend(Connection* connection) const { RTC_DCHECK_RUN_ON(network_thread_); // Note that we allow sending on an unreliable connection, because it's // possible that it became unreliable simply due to bad chance. // So this shouldn't prevent attempting to send media. return connection != nullptr && (connection->writable() || connection->write_state() == Connection::STATE_WRITE_UNRELIABLE || PresumedWritable(connection)); } // Handle queued up check-and-ping request void P2PTransportChannel::CheckAndPing() { RTC_DCHECK_RUN_ON(network_thread_); // Make sure the states of the connections are up-to-date (since this affects // which ones are pingable). UpdateConnectionStates(); // When the selected connection is not receiving or not writable, or any // active connection has not been pinged enough times, use the weak ping // interval. bool need_more_pings_at_weak_interval = absl::c_any_of(connections_, [](Connection* conn) { return conn->active() && conn->num_pings_sent() < MIN_PINGS_AT_WEAK_PING_INTERVAL; }); int ping_interval = (weak() || need_more_pings_at_weak_interval) ? weak_ping_interval() : strong_ping_interval(); if (rtc::TimeMillis() >= last_ping_sent_ms_ + ping_interval) { Connection* conn = FindNextPingableConnection(); if (conn) { PingConnection(conn); MarkConnectionPinged(conn); } } int delay = std::min(ping_interval, check_receiving_interval()); invoker_.AsyncInvokeDelayed<void>( RTC_FROM_HERE, thread(), rtc::Bind(&P2PTransportChannel::CheckAndPing, this), delay); } // A connection is considered a backup connection if the channel state // is completed, the connection is not the selected connection and it is active. bool P2PTransportChannel::IsBackupConnection(const Connection* conn) const { RTC_DCHECK_RUN_ON(network_thread_); return state_ == IceTransportState::STATE_COMPLETED && conn != selected_connection_ && conn->active(); } // Is the connection in a state for us to even consider pinging the other side? // We consider a connection pingable even if it's not connected because that's // how a TCP connection is kicked into reconnecting on the active side. bool P2PTransportChannel::IsPingable(const Connection* conn, int64_t now) const { RTC_DCHECK_RUN_ON(network_thread_); const Candidate& remote = conn->remote_candidate(); // We should never get this far with an empty remote ufrag. RTC_DCHECK(!remote.username().empty()); if (remote.username().empty() || remote.password().empty()) { // If we don't have an ICE ufrag and pwd, there's no way we can ping. return false; } // A failed connection will not be pinged. if (conn->state() == IceCandidatePairState::FAILED) { return false; } // An never connected connection cannot be written to at all, so pinging is // out of the question. However, if it has become WRITABLE, it is in the // reconnecting state so ping is needed. if (!conn->connected() && !conn->writable()) { return false; } // If the channel is weakly connected, ping all connections. if (weak()) { return true; } // Always ping active connections regardless whether the channel is completed // or not, but backup connections are pinged at a slower rate. if (IsBackupConnection(conn)) { return conn->rtt_samples() == 0 || (now >= conn->last_ping_response_received() + config_.backup_connection_ping_interval_or_default()); } // Don't ping inactive non-backup connections. if (!conn->active()) { return false; } // Do ping unwritable, active connections. if (!conn->writable()) { return true; } // Ping writable, active connections if it's been long enough since the last // ping. return WritableConnectionPastPingInterval(conn, now); } bool P2PTransportChannel::WritableConnectionPastPingInterval( const Connection* conn, int64_t now) const { RTC_DCHECK_RUN_ON(network_thread_); int interval = CalculateActiveWritablePingInterval(conn, now); return conn->last_ping_sent() + interval <= now; } int P2PTransportChannel::CalculateActiveWritablePingInterval( const Connection* conn, int64_t now) const { RTC_DCHECK_RUN_ON(network_thread_); // Ping each connection at a higher rate at least // MIN_PINGS_AT_WEAK_PING_INTERVAL times. if (conn->num_pings_sent() < MIN_PINGS_AT_WEAK_PING_INTERVAL) { return weak_ping_interval(); } int stable_interval = config_.stable_writable_connection_ping_interval_or_default(); int weak_or_stablizing_interval = std::min( stable_interval, WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL); // If the channel is weak or the connection is not stable yet, use the // weak_or_stablizing_interval. return (!weak() && conn->stable(now)) ? stable_interval : weak_or_stablizing_interval; } // Returns the next pingable connection to ping. Connection* P2PTransportChannel::FindNextPingableConnection() { RTC_DCHECK_RUN_ON(network_thread_); int64_t now = rtc::TimeMillis(); // Rule 1: Selected connection takes priority over non-selected ones. if (selected_connection_ && selected_connection_->connected() && selected_connection_->writable() && WritableConnectionPastPingInterval(selected_connection_, now)) { return selected_connection_; } // Rule 2: If the channel is weak, we need to find a new writable and // receiving connection, probably on a different network. If there are lots of // connections, it may take several seconds between two pings for every // non-selected connection. This will cause the receiving state of those // connections to be false, and thus they won't be selected. This is // problematic for network fail-over. We want to make sure at least one // connection per network is pinged frequently enough in order for it to be // selectable. So we prioritize one connection per network. // Rule 2.1: Among such connections, pick the one with the earliest // last-ping-sent time. if (weak()) { std::vector<Connection*> pingable_selectable_connections; absl::c_copy_if(GetBestWritableConnectionPerNetwork(), std::back_inserter(pingable_selectable_connections), [this, now](Connection* conn) { return WritableConnectionPastPingInterval(conn, now); }); auto iter = absl::c_min_element(pingable_selectable_connections, [](Connection* conn1, Connection* conn2) { return conn1->last_ping_sent() < conn2->last_ping_sent(); }); if (iter != pingable_selectable_connections.end()) { return *iter; } } // Rule 3: Triggered checks have priority over non-triggered connections. // Rule 3.1: Among triggered checks, oldest takes precedence. Connection* oldest_triggered_check = FindOldestConnectionNeedingTriggeredCheck(now); if (oldest_triggered_check) { return oldest_triggered_check; } // Rule 4: Unpinged connections have priority over pinged ones. RTC_CHECK(connections_.size() == pinged_connections_.size() + unpinged_connections_.size()); // If there are unpinged and pingable connections, only ping those. // Otherwise, treat everything as unpinged. // TODO(honghaiz): Instead of adding two separate vectors, we can add a state // "pinged" to filter out unpinged connections. if (absl::c_none_of(unpinged_connections_, [this, now](Connection* conn) { return this->IsPingable(conn, now); })) { unpinged_connections_.insert(pinged_connections_.begin(), pinged_connections_.end()); pinged_connections_.clear(); } // Among un-pinged pingable connections, "more pingable" takes precedence. std::vector<Connection*> pingable_connections; absl::c_copy_if( unpinged_connections_, std::back_inserter(pingable_connections), [this, now](Connection* conn) { return IsPingable(conn, now); }); auto iter = absl::c_max_element(pingable_connections, [this](Connection* conn1, Connection* conn2) { // Some implementations of max_element // compare an element with itself. if (conn1 == conn2) { return false; } return MorePingable(conn1, conn2) == conn2; }); if (iter != pingable_connections.end()) { return *iter; } return nullptr; } void P2PTransportChannel::MarkConnectionPinged(Connection* conn) { RTC_DCHECK_RUN_ON(network_thread_); if (conn && pinged_connections_.insert(conn).second) { unpinged_connections_.erase(conn); } } // Apart from sending ping from |conn| this method also updates // |use_candidate_attr| and |nomination| flags. One of the flags is set to // nominate |conn| if this channel is in CONTROLLING. void P2PTransportChannel::PingConnection(Connection* conn) { RTC_DCHECK_RUN_ON(network_thread_); bool use_candidate_attr = false; uint32_t nomination = 0; if (ice_role_ == ICEROLE_CONTROLLING) { bool renomination_supported = ice_parameters_.renomination && !remote_ice_parameters_.empty() && remote_ice_parameters_.back().renomination; if (renomination_supported) { nomination = GetNominationAttr(conn); } else { use_candidate_attr = GetUseCandidateAttr(conn, config_.default_nomination_mode); } } conn->set_nomination(nomination); conn->set_use_candidate_attr(use_candidate_attr); last_ping_sent_ms_ = rtc::TimeMillis(); conn->Ping(last_ping_sent_ms_); } uint32_t P2PTransportChannel::GetNominationAttr(Connection* conn) const { RTC_DCHECK_RUN_ON(network_thread_); return (conn == selected_connection_) ? nomination_ : 0; } // Nominate a connection based on the NominationMode. bool P2PTransportChannel::GetUseCandidateAttr(Connection* conn, NominationMode mode) const { RTC_DCHECK_RUN_ON(network_thread_); switch (mode) { case NominationMode::REGULAR: // TODO(honghaiz): Implement regular nomination. return false; case NominationMode::AGGRESSIVE: if (remote_ice_mode_ == ICEMODE_LITE) { return GetUseCandidateAttr(conn, NominationMode::REGULAR); } return true; case NominationMode::SEMI_AGGRESSIVE: { // Nominate if // a) Remote is in FULL ICE AND // a.1) |conn| is the selected connection OR // a.2) there is no selected connection OR // a.3) the selected connection is unwritable OR // a.4) |conn| has higher priority than selected_connection. // b) Remote is in LITE ICE AND // b.1) |conn| is the selected_connection AND // b.2) |conn| is writable. bool selected = conn == selected_connection_; if (remote_ice_mode_ == ICEMODE_LITE) { return selected && conn->writable(); } bool better_than_selected = !selected_connection_ || !selected_connection_->writable() || CompareConnectionCandidates(selected_connection_, conn) < 0; return selected || better_than_selected; } default: RTC_NOTREACHED(); return false; } } // When a connection's state changes, we need to figure out who to use as // the selected connection again. It could have become usable, or become // unusable. void P2PTransportChannel::OnConnectionStateChange(Connection* connection) { RTC_DCHECK_RUN_ON(network_thread_); // May stop the allocator session when at least one connection becomes // strongly connected after starting to get ports and the local candidate of // the connection is at the latest generation. It is not enough to check // that the connection becomes weakly connected because the connection may be // changing from (writable, receiving) to (writable, not receiving). bool strongly_connected = !connection->weak(); bool latest_generation = connection->local_candidate().generation() >= allocator_session()->generation(); if (strongly_connected && latest_generation) { MaybeStopPortAllocatorSessions(); } // We have to unroll the stack before doing this because we may be changing // the state of connections while sorting. RequestSortAndStateUpdate("candidate pair state changed"); } // When a connection is removed, edit it out, and then update our best // connection. void P2PTransportChannel::OnConnectionDestroyed(Connection* connection) { RTC_DCHECK_RUN_ON(network_thread_); // Note: the previous selected_connection_ may be destroyed by now, so don't // use it. // Remove this connection from the list. auto iter = absl::c_find(connections_, connection); RTC_DCHECK(iter != connections_.end()); pinged_connections_.erase(connection); unpinged_connections_.erase(connection); connections_.erase(iter); RTC_LOG(LS_INFO) << ToString() << ": Removed connection " << connection << " (" << connections_.size() << " remaining)"; // If this is currently the selected connection, then we need to pick a new // one. The call to SortConnectionsAndUpdateState will pick a new one. It // looks at the current selected connection in order to avoid switching // between fairly similar ones. Since this connection is no longer an option, // we can just set selected to nullptr and re-choose a best assuming that // there was no selected connection. if (selected_connection_ == connection) { RTC_LOG(LS_INFO) << "Selected connection destroyed. Will choose a new one."; SwitchSelectedConnection(nullptr); RequestSortAndStateUpdate("selected candidate pair destroyed"); } else { // If a non-selected connection was destroyed, we don't need to re-sort but // we do need to update state, because we could be switching to "failed" or // "completed". UpdateState(); } } // When a port is destroyed, remove it from our list of ports to use for // connection attempts. void P2PTransportChannel::OnPortDestroyed(PortInterface* port) { RTC_DCHECK_RUN_ON(network_thread_); ports_.erase(std::remove(ports_.begin(), ports_.end(), port), ports_.end()); pruned_ports_.erase( std::remove(pruned_ports_.begin(), pruned_ports_.end(), port), pruned_ports_.end()); RTC_LOG(INFO) << "Removed port because it is destroyed: " << ports_.size() << " remaining"; } void P2PTransportChannel::OnPortsPruned( PortAllocatorSession* session, const std::vector<PortInterface*>& ports) { RTC_DCHECK_RUN_ON(network_thread_); for (PortInterface* port : ports) { if (PrunePort(port)) { RTC_LOG(INFO) << "Removed port: " << port->ToString() << " " << ports_.size() << " remaining"; } } } void P2PTransportChannel::OnCandidatesRemoved( PortAllocatorSession* session, const std::vector<Candidate>& candidates) { RTC_DCHECK_RUN_ON(network_thread_); // Do not signal candidate removals if continual gathering is not enabled, or // if this is not the last session because an ICE restart would have signaled // the remote side to remove all candidates in previous sessions. if (!config_.gather_continually() || session != allocator_session()) { return; } std::vector<Candidate> candidates_to_remove; for (Candidate candidate : candidates) { candidate.set_transport_name(transport_name()); candidates_to_remove.push_back(candidate); } SignalCandidatesRemoved(this, candidates_to_remove); } void P2PTransportChannel::PruneAllPorts() { RTC_DCHECK_RUN_ON(network_thread_); pruned_ports_.insert(pruned_ports_.end(), ports_.begin(), ports_.end()); ports_.clear(); } bool P2PTransportChannel::PrunePort(PortInterface* port) { RTC_DCHECK_RUN_ON(network_thread_); auto it = absl::c_find(ports_, port); // Don't need to do anything if the port has been deleted from the port list. if (it == ports_.end()) { return false; } ports_.erase(it); pruned_ports_.push_back(port); return true; } // We data is available, let listeners know void P2PTransportChannel::OnReadPacket(Connection* connection, const char* data, size_t len, int64_t packet_time_us) { RTC_DCHECK_RUN_ON(network_thread_); // Do not deliver, if packet doesn't belong to the correct transport channel. if (!FindConnection(connection)) return; // Let the client know of an incoming packet SignalReadPacket(this, data, len, packet_time_us, 0); // May need to switch the sending connection based on the receiving media path // if this is the controlled side. if (ice_role_ == ICEROLE_CONTROLLED) { MaybeSwitchSelectedConnection(connection, "data received"); } } void P2PTransportChannel::OnSentPacket(const rtc::SentPacket& sent_packet) { RTC_DCHECK_RUN_ON(network_thread_); SignalSentPacket(this, sent_packet); } void P2PTransportChannel::OnReadyToSend(Connection* connection) { RTC_DCHECK_RUN_ON(network_thread_); if (connection == selected_connection_ && writable()) { SignalReadyToSend(this); } } // Find "triggered checks". We ping first those connections that have // received a ping but have not sent a ping since receiving it // (last_ping_received > last_ping_sent). But we shouldn't do // triggered checks if the connection is already writable. Connection* P2PTransportChannel::FindOldestConnectionNeedingTriggeredCheck( int64_t now) { RTC_DCHECK_RUN_ON(network_thread_); Connection* oldest_needing_triggered_check = nullptr; for (auto* conn : connections_) { if (!IsPingable(conn, now)) { continue; } bool needs_triggered_check = (!conn->writable() && conn->last_ping_received() > conn->last_ping_sent()); if (needs_triggered_check && (!oldest_needing_triggered_check || (conn->last_ping_received() < oldest_needing_triggered_check->last_ping_received()))) { oldest_needing_triggered_check = conn; } } if (oldest_needing_triggered_check) { RTC_LOG(LS_INFO) << "Selecting connection for triggered check: " << oldest_needing_triggered_check->ToString(); } return oldest_needing_triggered_check; } Connection* P2PTransportChannel::MostLikelyToWork(Connection* conn1, Connection* conn2) { RTC_DCHECK_RUN_ON(network_thread_); bool rr1 = IsRelayRelay(conn1); bool rr2 = IsRelayRelay(conn2); if (rr1 && !rr2) { return conn1; } else if (rr2 && !rr1) { return conn2; } else if (rr1 && rr2) { bool udp1 = IsUdp(conn1); bool udp2 = IsUdp(conn2); if (udp1 && !udp2) { return conn1; } else if (udp2 && udp1) { return conn2; } } return nullptr; } Connection* P2PTransportChannel::LeastRecentlyPinged(Connection* conn1, Connection* conn2) { RTC_DCHECK_RUN_ON(network_thread_); if (conn1->last_ping_sent() < conn2->last_ping_sent()) { return conn1; } if (conn1->last_ping_sent() > conn2->last_ping_sent()) { return conn2; } return nullptr; } Connection* P2PTransportChannel::MorePingable(Connection* conn1, Connection* conn2) { RTC_DCHECK_RUN_ON(network_thread_); RTC_DCHECK(conn1 != conn2); if (config_.prioritize_most_likely_candidate_pairs) { Connection* most_likely_to_work_conn = MostLikelyToWork(conn1, conn2); if (most_likely_to_work_conn) { return most_likely_to_work_conn; } } Connection* least_recently_pinged_conn = LeastRecentlyPinged(conn1, conn2); if (least_recently_pinged_conn) { return least_recently_pinged_conn; } // During the initial state when nothing has been pinged yet, return the first // one in the ordered |connections_|. return *(absl::c_find_if(connections_, [conn1, conn2](Connection* conn) { return conn == conn1 || conn == conn2; })); } void P2PTransportChannel::SetWritable(bool writable) { RTC_DCHECK_RUN_ON(network_thread_); if (writable_ == writable) { return; } RTC_LOG(LS_VERBOSE) << ToString() << ": Changed writable_ to " << writable; writable_ = writable; if (writable_) { has_been_writable_ = true; SignalReadyToSend(this); } SignalWritableState(this); } void P2PTransportChannel::SetReceiving(bool receiving) { RTC_DCHECK_RUN_ON(network_thread_); if (receiving_ == receiving) { return; } receiving_ = receiving; SignalReceivingState(this); } void P2PTransportChannel::LogCandidatePairConfig( Connection* conn, webrtc::IceCandidatePairConfigType type) { RTC_DCHECK_RUN_ON(network_thread_); if (conn == nullptr) { return; } ice_event_log_.LogCandidatePairConfig(type, conn->id(), conn->ToLogDescription()); } } // namespace cricket
38.939463
80
0.699952
[ "object", "vector" ]
d510c19d47b001ad5db11066bf0e93461dcb992d
7,000
cpp
C++
src/demo/ahe/gemm-benchmark.cpp
carlzhangweiwen/gazelle_mpc
45818ccf6375100a8fe2680f44f37d713380aa5c
[ "MIT" ]
50
2018-10-05T02:46:53.000Z
2022-03-20T08:47:46.000Z
src/demo/ahe/gemm-benchmark.cpp
WeiBenqiang/gazelle_mpc
f4eb3bae09bf4897f2651946eac7dee17e094a6f
[ "MIT" ]
7
2018-10-11T17:19:12.000Z
2022-03-08T16:45:11.000Z
src/demo/ahe/gemm-benchmark.cpp
WeiBenqiang/gazelle_mpc
f4eb3bae09bf4897f2651946eac7dee17e094a6f
[ "MIT" ]
20
2018-12-09T17:44:11.000Z
2022-03-01T12:13:21.000Z
/* NN-Layers-Benchmarking: This code benchmarks FC and Conv layers for a neural network List of Authors: Chiraag Juvekar, chiraag@mit.edu License Information: MIT License Copyright (c) 2017, Massachusetts Institute of Technology (MIT) */ #include <pke/gazelle.h> #include <iostream> #include <random> #include <algorithm> #include "math/bit_twiddle.h" using namespace std; using namespace lbcrypto; int main() { std::cout << "GEMM Benchmark (ms):" << std::endl; //------------------ Setup Parameters ------------------ ui64 nRep = 1; double start, stop; ui64 z = opt::z; ui64 z_p = opt::z_p; ftt_precompute(z, opt::q, opt::logn); ftt_precompute(z_p, opt::p, opt::logn); encoding_precompute(opt::p, opt::logn); precompute_automorph_index(opt::phim); DiscreteGaussianGenerator dgg = DiscreteGaussianGenerator(4.0); FVParams slow_params { false, opt::q, opt::p, opt::logn, opt::phim, (opt::q/opt::p), OPTIMIZED, std::make_shared<DiscreteGaussianGenerator>(dgg), 8 }; FVParams fast_params = slow_params; fast_params.fast_modulli = true; FVParams test_params = fast_params; //------------------- Synthetic Data ------------------- ui32 window_size = 20; ui32 k = 128; ui32 num_rows_s = 128, num_cols_s = k; ui32 num_rows_c = k, num_cols_c = 128; ui32 mat_window_size = 20; ui32 mat_num_windows = 1; // std::cin >> num_rows >> num_cols >> window_size; test_params.window_size = window_size; std::vector<uv64> mat_s(num_rows_s, uv64(num_cols_s)); std::vector<uv64> mat_s_t(num_cols_s, uv64(num_rows_s)); for(ui32 row=0; row<num_rows_s; row++){ mat_s[row] = get_dgg_testvector(num_cols_s, opt::p); } // std::cout << mat_to_str(mat_s) << std::endl; for(ui32 row=0; row<num_rows_s; row++){ for(ui32 col=0; col<num_cols_s; col++){ mat_s_t[col][row] = mat_s[row][col]; } } std::vector<uv64> mat_c(num_rows_c, uv64(num_cols_c)); for(ui32 row=0; row<num_rows_c; row++){ mat_c[row] = get_dgg_testvector(num_cols_c, opt::p); } //----------------------- KeyGen ----------------------- nRep = 10; auto kp = KeyGen(test_params); ui32 rows_per_ct = test_params.phim/num_cols_c; uv32 index_list; for (ui32 i = 1; i < rows_per_ct; i++){ index_list.push_back(test_params.phim-i*num_cols_c); // index_list.push_back(i+(opt::phim/2)); } start = currentDateTime(); for(ui64 i=0; i < nRep; i++){ kp = KeyGen(test_params); EvalAutomorphismKeyGen(kp.sk, index_list, test_params); } stop = currentDateTime(); std::cout << " KeyGen ("<< index_list.size() <<" keys): " << (stop-start)/nRep << std::endl; //-------------- Preprocess Client Matrix -------------- nRep = 1; auto ct_mat_c = preprocess_gemm_c(kp.sk, mat_c, mat_window_size, mat_num_windows, test_params); start = currentDateTime(); for(ui64 i=0; i < nRep; i++){ ct_mat_c = preprocess_gemm_c(kp.sk, mat_c, mat_window_size, mat_num_windows, test_params); } stop = currentDateTime(); std::cout << " Preprocess Client Matrix ("<< mat_num_windows <<" windows): " << (stop-start)/nRep << std::endl; //----------------- Preprocess Matrix ------------------ EncMat enc_mat_s; if(rows_per_ct > 1){ //enc_mat_s = preprocess_gemm_s(mat_s, num_cols_c, mat_window_size, mat_num_windows, test_params); start = currentDateTime(); for(ui64 i=0; i < nRep; i++){ enc_mat_s = preprocess_gemm_s(mat_s, num_cols_c, mat_window_size, mat_num_windows, test_params); } stop = currentDateTime(); std::cout << " Preprocess Matrix ("<< num_rows_s <<"x"<< num_cols_s << "): " << (stop-start)/nRep << std::endl; } //--------------------- Multiply ----------------------- CTVec ct_prod; if(rows_per_ct > 1){ //ct_prod = gemm_online(ct_mat_c, enc_mat_s, num_cols_c, test_params); start = currentDateTime(); for(ui64 i=0; i < nRep; i++){ ct_prod = gemm_online(ct_mat_c, enc_mat_s, num_cols_c, test_params); } stop = currentDateTime(); } else { ct_prod = gemm_phim_online(ct_mat_c, mat_s_t, mat_window_size, mat_num_windows, test_params); start = currentDateTime(); for(ui64 i=0; i < nRep; i++){ ct_prod = gemm_phim_online(ct_mat_c, mat_s_t, mat_window_size, mat_num_windows, test_params); } stop = currentDateTime(); } std::cout << " Multiply: " << (stop-start)/nRep << std::endl; //------------------- Post-Process --------------------- auto prod = postprocess_gemm(kp.sk, ct_prod, num_rows_s, num_cols_c, test_params); start = currentDateTime(); for(ui64 i=0; i < nRep; i++){ prod = postprocess_gemm(kp.sk, ct_prod, num_rows_s, num_cols_c, test_params); } stop = currentDateTime(); std::cout << " Post-Process: " << (stop-start)/nRep << std::endl; //------------------- Multiply PT ---------------------- auto prod_ref = gemm_pt(mat_c, mat_s_t, opt::p); start = currentDateTime(); for(ui64 i=0; i < nRep; i++){ prod_ref = gemm_pt(mat_c, mat_s_t, opt::p); } stop = currentDateTime(); std::cout << " Multiply PT: " << (stop-start)/nRep << std::endl; //----------------------- Check ------------------------ std::cout << std::endl; for(ui32 w=0; w<mat_num_windows; w++){ std::cout << "Margin ct("<<w<<"): " << NoiseMargin(kp.sk, ct_mat_c[0][w], test_params) << std::endl; } double noise = 100; for(ui32 n=0; n<ct_prod.size(); n++){ double noise_new = NoiseMargin(kp.sk, ct_prod[n], test_params); if(noise_new < noise){ noise = noise_new; } } std::cout << "Margin prod: " << noise << std::endl; std::cout << std::endl; /*auto pt = packed_decode(Decrypt(kp.sk, ct_prod[0], test_params), test_params.p, test_params.logn); std::cout << vec_to_str(pt) << std::endl; auto pt_in = packed_decode(Decrypt(kp.sk, ct_mat_c[0][0], test_params), test_params.p, test_params.logn); std::cout << vec_to_str(pt_in) << std::endl; std::cout << vec_to_str(mat_c[0]) << std::endl; */ /* ui32 err = */ check_mat_eq(prod_ref, prod, "mat_mul mismatch:\n"); /* if(err != prod_ref.size()){ std::cout << "Margin err: " << NoiseMargin(kp.sk, ct_prod[err], test_params) << std::endl; std::cout << "Coeff err: " << mat_s_t[0][err] << std::endl; Ciphertext prod_vec(test_params.phim); ui64 coeff = mat_s_t[0][err]; for(ui32 n=0; n<test_params.phim; n++){ prod_vec.a[n] = opt::mul_modq_part(ct_mat_c[0][0].a[n], coeff); prod_vec.b[n] = opt::mul_modq_part(ct_mat_c[0][0].b[n], coeff); } std::cout << "Margin: " << NoiseMargin(kp.sk, prod_vec, test_params) << std::endl; } */ return 0; }
35.175879
119
0.581143
[ "vector" ]
d516b1e9630d247238e74adde6c500e6bfc8330d
864
cpp
C++
077. Combinations AC 1 [TODO].cpp
Lywx/CppLeetcode
ad80eb8305f2317ca7d3712976c82cffdf2046fc
[ "MIT" ]
null
null
null
077. Combinations AC 1 [TODO].cpp
Lywx/CppLeetcode
ad80eb8305f2317ca7d3712976c82cffdf2046fc
[ "MIT" ]
null
null
null
077. Combinations AC 1 [TODO].cpp
Lywx/CppLeetcode
ad80eb8305f2317ca7d3712976c82cffdf2046fc
[ "MIT" ]
null
null
null
#include <vector> #include <unordered_set> #include <algorithm> #include <set> #include <unordered_map> #include <numeric> using namespace std; class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> combinations; vector<int> combination(k, 0); auto positionIndex = 0; while (positionIndex >= 0) { ++combination[positionIndex]; if (combination[positionIndex] > n) { --positionIndex; } else if (positionIndex == k - 1) { combinations.push_back(combination); } else { ++positionIndex; combination[positionIndex] = combination[positionIndex - 1]; } } return combinations; } };
21.073171
76
0.516204
[ "vector" ]
d51b064633c45c42822851beb8f43e9e77d70b85
41,437
cpp
C++
llvm/tools/lli/lli.cpp
guitard0g/llvm-project
283e39c7a0d1bf97a67b77638e9194bd1eb9dae6
[ "Apache-2.0" ]
6
2022-01-20T02:15:30.000Z
2022-02-23T13:55:31.000Z
tools/lli/lli.cpp
nullhook/ollvm-14.x
ec365c42bbaa74c9ee029d32468f7781c37d6b43
[ "Apache-2.0" ]
null
null
null
tools/lli/lli.cpp
nullhook/ollvm-14.x
ec365c42bbaa74c9ee029d32468f7781c37d6b43
[ "Apache-2.0" ]
null
null
null
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an interpreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "ExecutionUtils.h" #include "ForwardingMemoryManager.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/Bitcode/BitcodeReader.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/CodeGen/LinkAllCodegenComponents.h" #include "llvm/Config/llvm-config.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/Interpreter.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/ExecutionEngine/JITSymbol.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/ExecutionEngine/ObjectCache.h" #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h" #include "llvm/ExecutionEngine/Orc/DebugUtils.h" #include "llvm/ExecutionEngine/Orc/EPCDebugObjectRegistrar.h" #include "llvm/ExecutionEngine/Orc/EPCEHFrameRegistrar.h" #include "llvm/ExecutionEngine/Orc/EPCGenericRTDyldMemoryManager.h" #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/LLJIT.h" #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" #include "llvm/ExecutionEngine/Orc/SimpleRemoteEPC.h" #include "llvm/ExecutionEngine/Orc/SymbolStringPool.h" #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h" #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h" #include "llvm/ExecutionEngine/Orc/TargetProcess/TargetExecutionUtils.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Object/Archive.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Format.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/Memory.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/Process.h" #include "llvm/Support/Program.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/WithColor.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Instrumentation.h" #include <cerrno> #if !defined(_MSC_VER) && !defined(__MINGW32__) #include <unistd.h> #else #include <io.h> #endif #ifdef __CYGWIN__ #include <cygwin/version.h> #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 #define DO_NOTHING_ATEXIT 1 #endif #endif using namespace llvm; static codegen::RegisterCodeGenFlags CGF; #define DEBUG_TYPE "lli" namespace { enum class JITKind { MCJIT, Orc, OrcLazy }; enum class JITLinkerKind { Default, RuntimeDyld, JITLink }; cl::opt<std::string> InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<JITKind> UseJITKind( "jit-kind", cl::desc("Choose underlying JIT kind."), cl::init(JITKind::Orc), cl::values(clEnumValN(JITKind::MCJIT, "mcjit", "MCJIT"), clEnumValN(JITKind::Orc, "orc", "Orc JIT"), clEnumValN(JITKind::OrcLazy, "orc-lazy", "Orc-based lazy JIT."))); cl::opt<JITLinkerKind> JITLinker("jit-linker", cl::desc("Choose the dynamic linker/loader."), cl::init(JITLinkerKind::Default), cl::values(clEnumValN(JITLinkerKind::Default, "default", "Default for platform and JIT-kind"), clEnumValN(JITLinkerKind::RuntimeDyld, "rtdyld", "RuntimeDyld"), clEnumValN(JITLinkerKind::JITLink, "jitlink", "Orc-specific linker"))); cl::opt<unsigned> LazyJITCompileThreads("compile-threads", cl::desc("Choose the number of compile threads " "(jit-kind=orc-lazy only)"), cl::init(0)); cl::list<std::string> ThreadEntryPoints("thread-entry", cl::desc("calls the given entry-point on a new thread " "(jit-kind=orc-lazy only)")); cl::opt<bool> PerModuleLazy( "per-module-lazy", cl::desc("Performs lazy compilation on whole module boundaries " "rather than individual functions"), cl::init(false)); cl::list<std::string> JITDylibs("jd", cl::desc("Specifies the JITDylib to be used for any subsequent " "-extra-module arguments.")); cl::list<std::string> Dylibs("dlopen", cl::desc("Dynamic libraries to load before linking"), cl::ZeroOrMore); // The MCJIT supports building for a target address space separate from // the JIT compilation process. Use a forked process and a copying // memory manager with IPC to execute using this functionality. cl::opt<bool> RemoteMCJIT("remote-mcjit", cl::desc("Execute MCJIT'ed code in a separate process."), cl::init(false)); // Manually specify the child process for remote execution. This overrides // the simulated remote execution that allocates address space for child // execution. The child process will be executed and will communicate with // lli via stdin/stdout pipes. cl::opt<std::string> ChildExecPath("mcjit-remote-process", cl::desc("Specify the filename of the process to launch " "for remote MCJIT execution. If none is specified," "\n\tremote execution will be simulated in-process."), cl::value_desc("filename"), cl::init("")); // Determine optimization level. cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " "(default = '-O2')"), cl::Prefix, cl::ZeroOrMore, cl::init(' ')); cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); cl::opt<std::string> EntryFunc("entry-function", cl::desc("Specify the entry function (default = 'main') " "of the executable"), cl::value_desc("function"), cl::init("main")); cl::list<std::string> ExtraModules("extra-module", cl::desc("Extra modules to be loaded"), cl::value_desc("input bitcode")); cl::list<std::string> ExtraObjects("extra-object", cl::desc("Extra object files to be loaded"), cl::value_desc("input object")); cl::list<std::string> ExtraArchives("extra-archive", cl::desc("Extra archive files to be loaded"), cl::value_desc("input archive")); cl::opt<bool> EnableCacheManager("enable-cache-manager", cl::desc("Use cache manager to save/load modules"), cl::init(false)); cl::opt<std::string> ObjectCacheDir("object-cache-dir", cl::desc("Directory to store cached object files " "(must be user writable)"), cl::init("")); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); cl::opt<bool> DisableCoreFiles("disable-core-files", cl::Hidden, cl::desc("Disable emission of core files if possible")); cl::opt<bool> NoLazyCompilation("disable-lazy-compilation", cl::desc("Disable JIT lazy compilation"), cl::init(false)); cl::opt<bool> GenerateSoftFloatCalls("soft-float", cl::desc("Generate software floating point library calls"), cl::init(false)); cl::opt<bool> NoProcessSymbols( "no-process-syms", cl::desc("Do not resolve lli process symbols in JIT'd code"), cl::init(false)); enum class LLJITPlatform { Inactive, DetectHost, GenericIR }; cl::opt<LLJITPlatform> Platform("lljit-platform", cl::desc("Platform to use with LLJIT"), cl::init(LLJITPlatform::DetectHost), cl::values(clEnumValN(LLJITPlatform::DetectHost, "DetectHost", "Select based on JIT target triple"), clEnumValN(LLJITPlatform::GenericIR, "GenericIR", "Use LLJITGenericIRPlatform"), clEnumValN(LLJITPlatform::Inactive, "Inactive", "Disable platform support explicitly")), cl::Hidden); enum class DumpKind { NoDump, DumpFuncsToStdOut, DumpModsToStdOut, DumpModsToDisk }; cl::opt<DumpKind> OrcDumpKind( "orc-lazy-debug", cl::desc("Debug dumping for the orc-lazy JIT."), cl::init(DumpKind::NoDump), cl::values(clEnumValN(DumpKind::NoDump, "no-dump", "Don't dump anything."), clEnumValN(DumpKind::DumpFuncsToStdOut, "funcs-to-stdout", "Dump function names to stdout."), clEnumValN(DumpKind::DumpModsToStdOut, "mods-to-stdout", "Dump modules to stdout."), clEnumValN(DumpKind::DumpModsToDisk, "mods-to-disk", "Dump modules to the current " "working directory. (WARNING: " "will overwrite existing files).")), cl::Hidden); cl::list<BuiltinFunctionKind> GenerateBuiltinFunctions( "generate", cl::desc("Provide built-in functions for access by JITed code " "(jit-kind=orc-lazy only)"), cl::values(clEnumValN(BuiltinFunctionKind::DumpDebugDescriptor, "__dump_jit_debug_descriptor", "Dump __jit_debug_descriptor contents to stdout"), clEnumValN(BuiltinFunctionKind::DumpDebugObjects, "__dump_jit_debug_objects", "Dump __jit_debug_descriptor in-memory debug " "objects as tool output")), cl::Hidden); ExitOnError ExitOnErr; } LLVM_ATTRIBUTE_USED void linkComponents() { errs() << (void *)&llvm_orc_registerEHFrameSectionWrapper << (void *)&llvm_orc_deregisterEHFrameSectionWrapper << (void *)&llvm_orc_registerJITLoaderGDBWrapper; } //===----------------------------------------------------------------------===// // Object cache // // This object cache implementation writes cached objects to disk to the // directory specified by CacheDir, using a filename provided in the module // descriptor. The cache tries to load a saved object using that path if the // file exists. CacheDir defaults to "", in which case objects are cached // alongside their originating bitcodes. // class LLIObjectCache : public ObjectCache { public: LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) { // Add trailing '/' to cache dir if necessary. if (!this->CacheDir.empty() && this->CacheDir[this->CacheDir.size() - 1] != '/') this->CacheDir += '/'; } ~LLIObjectCache() override {} void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override { const std::string &ModuleID = M->getModuleIdentifier(); std::string CacheName; if (!getCacheFilename(ModuleID, CacheName)) return; if (!CacheDir.empty()) { // Create user-defined cache dir. SmallString<128> dir(sys::path::parent_path(CacheName)); sys::fs::create_directories(Twine(dir)); } std::error_code EC; raw_fd_ostream outfile(CacheName, EC, sys::fs::OF_None); outfile.write(Obj.getBufferStart(), Obj.getBufferSize()); outfile.close(); } std::unique_ptr<MemoryBuffer> getObject(const Module* M) override { const std::string &ModuleID = M->getModuleIdentifier(); std::string CacheName; if (!getCacheFilename(ModuleID, CacheName)) return nullptr; // Load the object from the cache filename ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer = MemoryBuffer::getFile(CacheName, /*IsText=*/false, /*RequiresNullTerminator=*/false); // If the file isn't there, that's OK. if (!IRObjectBuffer) return nullptr; // MCJIT will want to write into this buffer, and we don't want that // because the file has probably just been mmapped. Instead we make // a copy. The filed-based buffer will be released when it goes // out of scope. return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer()); } private: std::string CacheDir; bool getCacheFilename(const std::string &ModID, std::string &CacheName) { std::string Prefix("file:"); size_t PrefixLength = Prefix.length(); if (ModID.substr(0, PrefixLength) != Prefix) return false; std::string CacheSubdir = ModID.substr(PrefixLength); #if defined(_WIN32) // Transform "X:\foo" => "/X\foo" for convenience. if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') { CacheSubdir[1] = CacheSubdir[0]; CacheSubdir[0] = '/'; } #endif CacheName = CacheDir + CacheSubdir; size_t pos = CacheName.rfind('.'); CacheName.replace(pos, CacheName.length() - pos, ".o"); return true; } }; // On Mingw and Cygwin, an external symbol named '__main' is called from the // generated 'main' function to allow static initialization. To avoid linking // problems with remote targets (because lli's remote target support does not // currently handle external linking) we add a secondary module which defines // an empty '__main' function. static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context, StringRef TargetTripleStr) { IRBuilder<> Builder(Context); Triple TargetTriple(TargetTripleStr); // Create a new module. std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context); M->setTargetTriple(TargetTripleStr); // Create an empty function named "__main". Type *ReturnTy; if (TargetTriple.isArch64Bit()) ReturnTy = Type::getInt64Ty(Context); else ReturnTy = Type::getInt32Ty(Context); Function *Result = Function::Create(FunctionType::get(ReturnTy, {}, false), GlobalValue::ExternalLinkage, "__main", M.get()); BasicBlock *BB = BasicBlock::Create(Context, "__main", Result); Builder.SetInsertPoint(BB); Value *ReturnVal = ConstantInt::get(ReturnTy, 0); Builder.CreateRet(ReturnVal); // Add this new module to the ExecutionEngine. EE.addModule(std::move(M)); } CodeGenOpt::Level getOptLevel() { switch (OptLevel) { default: WithColor::error(errs(), "lli") << "invalid optimization level.\n"; exit(1); case '0': return CodeGenOpt::None; case '1': return CodeGenOpt::Less; case ' ': case '2': return CodeGenOpt::Default; case '3': return CodeGenOpt::Aggressive; } llvm_unreachable("Unrecognized opt level."); } [[noreturn]] static void reportError(SMDiagnostic Err, const char *ProgName) { Err.print(ProgName, errs()); exit(1); } Error loadDylibs(); int runOrcJIT(const char *ProgName); void disallowOrcOptions(); Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote(); //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { InitLLVM X(argc, argv); if (argc > 1) ExitOnErr.setBanner(std::string(argv[0]) + ": "); // If we have a native target, initialize it to ensure it is linked in and // usable by the JIT. InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); InitializeNativeTargetAsmParser(); cl::ParseCommandLineOptions(argc, argv, "llvm interpreter & dynamic compiler\n"); // If the user doesn't want core files, disable them. if (DisableCoreFiles) sys::Process::PreventCoreFiles(); ExitOnErr(loadDylibs()); if (UseJITKind == JITKind::MCJIT) disallowOrcOptions(); else return runOrcJIT(argv[0]); // Old lli implementation based on ExecutionEngine and MCJIT. LLVMContext Context; // Load the bitcode... SMDiagnostic Err; std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context); Module *Mod = Owner.get(); if (!Mod) reportError(Err, argv[0]); if (EnableCacheManager) { std::string CacheName("file:"); CacheName.append(InputFile); Mod->setModuleIdentifier(CacheName); } // If not jitting lazily, load the whole bitcode file eagerly too. if (NoLazyCompilation) { // Use *argv instead of argv[0] to work around a wrong GCC warning. ExitOnError ExitOnErr(std::string(*argv) + ": bitcode didn't read correctly: "); ExitOnErr(Mod->materializeAll()); } std::string ErrorMsg; EngineBuilder builder(std::move(Owner)); builder.setMArch(codegen::getMArch()); builder.setMCPU(codegen::getCPUStr()); builder.setMAttrs(codegen::getFeatureList()); if (auto RM = codegen::getExplicitRelocModel()) builder.setRelocationModel(RM.getValue()); if (auto CM = codegen::getExplicitCodeModel()) builder.setCodeModel(CM.getValue()); builder.setErrorStr(&ErrorMsg); builder.setEngineKind(ForceInterpreter ? EngineKind::Interpreter : EngineKind::JIT); // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) Mod->setTargetTriple(Triple::normalize(TargetTriple)); // Enable MCJIT if desired. RTDyldMemoryManager *RTDyldMM = nullptr; if (!ForceInterpreter) { if (RemoteMCJIT) RTDyldMM = new ForwardingMemoryManager(); else RTDyldMM = new SectionMemoryManager(); // Deliberately construct a temp std::unique_ptr to pass in. Do not null out // RTDyldMM: We still use it below, even though we don't own it. builder.setMCJITMemoryManager( std::unique_ptr<RTDyldMemoryManager>(RTDyldMM)); } else if (RemoteMCJIT) { WithColor::error(errs(), argv[0]) << "remote process execution does not work with the interpreter.\n"; exit(1); } builder.setOptLevel(getOptLevel()); TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple(TargetTriple)); if (codegen::getFloatABIForCalls() != FloatABI::Default) Options.FloatABIType = codegen::getFloatABIForCalls(); builder.setTargetOptions(Options); std::unique_ptr<ExecutionEngine> EE(builder.create()); if (!EE) { if (!ErrorMsg.empty()) WithColor::error(errs(), argv[0]) << "error creating EE: " << ErrorMsg << "\n"; else WithColor::error(errs(), argv[0]) << "unknown error creating EE!\n"; exit(1); } std::unique_ptr<LLIObjectCache> CacheManager; if (EnableCacheManager) { CacheManager.reset(new LLIObjectCache(ObjectCacheDir)); EE->setObjectCache(CacheManager.get()); } // Load any additional modules specified on the command line. for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) { std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context); if (!XMod) reportError(Err, argv[0]); if (EnableCacheManager) { std::string CacheName("file:"); CacheName.append(ExtraModules[i]); XMod->setModuleIdentifier(CacheName); } EE->addModule(std::move(XMod)); } for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) { Expected<object::OwningBinary<object::ObjectFile>> Obj = object::ObjectFile::createObjectFile(ExtraObjects[i]); if (!Obj) { // TODO: Actually report errors helpfully. consumeError(Obj.takeError()); reportError(Err, argv[0]); } object::OwningBinary<object::ObjectFile> &O = Obj.get(); EE->addObjectFile(std::move(O)); } for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) { ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]); if (!ArBufOrErr) reportError(Err, argv[0]); std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get(); Expected<std::unique_ptr<object::Archive>> ArOrErr = object::Archive::create(ArBuf->getMemBufferRef()); if (!ArOrErr) { std::string Buf; raw_string_ostream OS(Buf); logAllUnhandledErrors(ArOrErr.takeError(), OS); OS.flush(); errs() << Buf; exit(1); } std::unique_ptr<object::Archive> &Ar = ArOrErr.get(); object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf)); EE->addArchive(std::move(OB)); } // If the target is Cygwin/MingW and we are generating remote code, we // need an extra module to help out with linking. if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) { addCygMingExtraModule(*EE, Context, Mod->getTargetTriple()); } // The following functions have no effect if their respective profiling // support wasn't enabled in the build configuration. EE->RegisterJITEventListener( JITEventListener::createOProfileJITEventListener()); EE->RegisterJITEventListener( JITEventListener::createIntelJITEventListener()); if (!RemoteMCJIT) EE->RegisterJITEventListener( JITEventListener::createPerfJITEventListener()); if (!NoLazyCompilation && RemoteMCJIT) { WithColor::warning(errs(), argv[0]) << "remote mcjit does not support lazy compilation\n"; NoLazyCompilation = true; } EE->DisableLazyCompilation(NoLazyCompilation); // If the user specifically requested an argv[0] to pass into the program, // do it now. if (!FakeArgv0.empty()) { InputFile = static_cast<std::string>(FakeArgv0); } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (StringRef(InputFile).endswith(".bc")) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *EntryFn = Mod->getFunction(EntryFunc); if (!EntryFn) { WithColor::error(errs(), argv[0]) << '\'' << EntryFunc << "\' function not found in module.\n"; return -1; } // Reset errno to zero on entry to main. errno = 0; int Result = -1; // Sanity check use of remote-jit: LLI currently only supports use of the // remote JIT on Unix platforms. if (RemoteMCJIT) { #ifndef LLVM_ON_UNIX WithColor::warning(errs(), argv[0]) << "host does not support external remote targets.\n"; WithColor::note() << "defaulting to local execution\n"; return -1; #else if (ChildExecPath.empty()) { WithColor::error(errs(), argv[0]) << "-remote-mcjit requires -mcjit-remote-process.\n"; exit(1); } else if (!sys::fs::can_execute(ChildExecPath)) { WithColor::error(errs(), argv[0]) << "unable to find usable child executable: '" << ChildExecPath << "'\n"; return -1; } #endif } std::unique_ptr<orc::ExecutorProcessControl> EPC = RemoteMCJIT ? ExitOnErr(launchRemote()) : ExitOnErr(orc::SelfExecutorProcessControl::Create()); if (!RemoteMCJIT) { // If the program doesn't explicitly call exit, we will need the Exit // function later on to make an explicit call, so get the function now. FunctionCallee Exit = Mod->getOrInsertFunction( "exit", Type::getVoidTy(Context), Type::getInt32Ty(Context)); // Run static constructors. if (!ForceInterpreter) { // Give MCJIT a chance to apply relocations and set page permissions. EE->finalizeObject(); } EE->runStaticConstructorsDestructors(false); // Trigger compilation separately so code regions that need to be // invalidated will be known. (void)EE->getPointerToFunction(EntryFn); // Clear instruction cache before code will be executed. if (RTDyldMM) static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache(); // Run main. Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); // Run static destructors. EE->runStaticConstructorsDestructors(true); // If the program didn't call exit explicitly, we should call it now. // This ensures that any atexit handlers get called correctly. if (Function *ExitF = dyn_cast<Function>(Exit.getCallee()->stripPointerCasts())) { if (ExitF->getFunctionType() == Exit.getFunctionType()) { std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = APInt(32, Result); Args.push_back(ResultGV); EE->runFunction(ExitF, Args); WithColor::error(errs(), argv[0]) << "exit(" << Result << ") returned!\n"; abort(); } } WithColor::error(errs(), argv[0]) << "exit defined with wrong prototype!\n"; abort(); } else { // else == "if (RemoteMCJIT)" // Remote target MCJIT doesn't (yet) support static constructors. No reason // it couldn't. This is a limitation of the LLI implementation, not the // MCJIT itself. FIXME. // Create a remote memory manager. auto RemoteMM = ExitOnErr( orc::EPCGenericRTDyldMemoryManager::CreateWithDefaultBootstrapSymbols( *EPC)); // Forward MCJIT's memory manager calls to the remote memory manager. static_cast<ForwardingMemoryManager*>(RTDyldMM)->setMemMgr( std::move(RemoteMM)); // Forward MCJIT's symbol resolution calls to the remote. static_cast<ForwardingMemoryManager *>(RTDyldMM)->setResolver( ExitOnErr(RemoteResolver::Create(*EPC))); // Grab the target address of the JIT'd main function on the remote and call // it. // FIXME: argv and envp handling. auto Entry = orc::ExecutorAddr(EE->getFunctionAddress(EntryFn->getName().str())); EE->finalizeObject(); LLVM_DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x" << format("%llx", Entry.getValue()) << "\n"); Result = ExitOnErr(EPC->runAsMain(Entry, {})); // Like static constructors, the remote target MCJIT support doesn't handle // this yet. It could. FIXME. // Delete the EE - we need to tear it down *before* we terminate the session // with the remote, otherwise it'll crash when it tries to release resources // on a remote that has already been disconnected. EE.reset(); // Signal the remote target that we're done JITing. ExitOnErr(EPC->disconnect()); } return Result; } static std::function<void(Module &)> createDebugDumper() { switch (OrcDumpKind) { case DumpKind::NoDump: return [](Module &M) {}; case DumpKind::DumpFuncsToStdOut: return [](Module &M) { printf("[ "); for (const auto &F : M) { if (F.isDeclaration()) continue; if (F.hasName()) { std::string Name(std::string(F.getName())); printf("%s ", Name.c_str()); } else printf("<anon> "); } printf("]\n"); }; case DumpKind::DumpModsToStdOut: return [](Module &M) { outs() << "----- Module Start -----\n" << M << "----- Module End -----\n"; }; case DumpKind::DumpModsToDisk: return [](Module &M) { std::error_code EC; raw_fd_ostream Out(M.getModuleIdentifier() + ".ll", EC, sys::fs::OF_TextWithCRLF); if (EC) { errs() << "Couldn't open " << M.getModuleIdentifier() << " for dumping.\nError:" << EC.message() << "\n"; exit(1); } Out << M; }; } llvm_unreachable("Unknown DumpKind"); } Error loadDylibs() { for (const auto &Dylib : Dylibs) { std::string ErrMsg; if (sys::DynamicLibrary::LoadLibraryPermanently(Dylib.c_str(), &ErrMsg)) return make_error<StringError>(ErrMsg, inconvertibleErrorCode()); } return Error::success(); } static void exitOnLazyCallThroughFailure() { exit(1); } Expected<orc::ThreadSafeModule> loadModule(StringRef Path, orc::ThreadSafeContext TSCtx) { SMDiagnostic Err; auto M = parseIRFile(Path, Err, *TSCtx.getContext()); if (!M) { std::string ErrMsg; { raw_string_ostream ErrMsgStream(ErrMsg); Err.print("lli", ErrMsgStream); } return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode()); } if (EnableCacheManager) M->setModuleIdentifier("file:" + M->getModuleIdentifier()); return orc::ThreadSafeModule(std::move(M), std::move(TSCtx)); } int runOrcJIT(const char *ProgName) { // Start setting up the JIT environment. // Parse the main module. orc::ThreadSafeContext TSCtx(std::make_unique<LLVMContext>()); auto MainModule = ExitOnErr(loadModule(InputFile, TSCtx)); // Get TargetTriple and DataLayout from the main module if they're explicitly // set. Optional<Triple> TT; Optional<DataLayout> DL; MainModule.withModuleDo([&](Module &M) { if (!M.getTargetTriple().empty()) TT = Triple(M.getTargetTriple()); if (!M.getDataLayout().isDefault()) DL = M.getDataLayout(); }); orc::LLLazyJITBuilder Builder; Builder.setJITTargetMachineBuilder( TT ? orc::JITTargetMachineBuilder(*TT) : ExitOnErr(orc::JITTargetMachineBuilder::detectHost())); TT = Builder.getJITTargetMachineBuilder()->getTargetTriple(); if (DL) Builder.setDataLayout(DL); if (!codegen::getMArch().empty()) Builder.getJITTargetMachineBuilder()->getTargetTriple().setArchName( codegen::getMArch()); Builder.getJITTargetMachineBuilder() ->setCPU(codegen::getCPUStr()) .addFeatures(codegen::getFeatureList()) .setRelocationModel(codegen::getExplicitRelocModel()) .setCodeModel(codegen::getExplicitCodeModel()); // FIXME: Setting a dummy call-through manager in non-lazy mode prevents the // JIT builder to instantiate a default (which would fail with an error for // unsupported architectures). if (UseJITKind != JITKind::OrcLazy) { auto ES = std::make_unique<orc::ExecutionSession>( ExitOnErr(orc::SelfExecutorProcessControl::Create())); Builder.setLazyCallthroughManager( std::make_unique<orc::LazyCallThroughManager>(*ES, 0, nullptr)); Builder.setExecutionSession(std::move(ES)); } Builder.setLazyCompileFailureAddr( pointerToJITTargetAddress(exitOnLazyCallThroughFailure)); Builder.setNumCompileThreads(LazyJITCompileThreads); // If the object cache is enabled then set a custom compile function // creator to use the cache. std::unique_ptr<LLIObjectCache> CacheManager; if (EnableCacheManager) { CacheManager = std::make_unique<LLIObjectCache>(ObjectCacheDir); Builder.setCompileFunctionCreator( [&](orc::JITTargetMachineBuilder JTMB) -> Expected<std::unique_ptr<orc::IRCompileLayer::IRCompiler>> { if (LazyJITCompileThreads > 0) return std::make_unique<orc::ConcurrentIRCompiler>(std::move(JTMB), CacheManager.get()); auto TM = JTMB.createTargetMachine(); if (!TM) return TM.takeError(); return std::make_unique<orc::TMOwningSimpleCompiler>(std::move(*TM), CacheManager.get()); }); } // Set up LLJIT platform. { LLJITPlatform P = Platform; if (P == LLJITPlatform::DetectHost) P = LLJITPlatform::GenericIR; switch (P) { case LLJITPlatform::GenericIR: // Nothing to do: LLJITBuilder will use this by default. break; case LLJITPlatform::Inactive: Builder.setPlatformSetUp(orc::setUpInactivePlatform); break; default: llvm_unreachable("Unrecognized platform value"); } } std::unique_ptr<orc::ExecutorProcessControl> EPC = nullptr; if (JITLinker == JITLinkerKind::JITLink) { EPC = ExitOnErr(orc::SelfExecutorProcessControl::Create( std::make_shared<orc::SymbolStringPool>())); Builder.setObjectLinkingLayerCreator([&EPC](orc::ExecutionSession &ES, const Triple &) { auto L = std::make_unique<orc::ObjectLinkingLayer>(ES, EPC->getMemMgr()); L->addPlugin(std::make_unique<orc::EHFrameRegistrationPlugin>( ES, ExitOnErr(orc::EPCEHFrameRegistrar::Create(ES)))); L->addPlugin(std::make_unique<orc::DebugObjectManagerPlugin>( ES, ExitOnErr(orc::createJITLoaderGDBRegistrar(ES)))); return L; }); } auto J = ExitOnErr(Builder.create()); auto *ObjLayer = &J->getObjLinkingLayer(); if (auto *RTDyldObjLayer = dyn_cast<orc::RTDyldObjectLinkingLayer>(ObjLayer)) RTDyldObjLayer->registerJITEventListener( *JITEventListener::createGDBRegistrationListener()); if (PerModuleLazy) J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule); auto Dump = createDebugDumper(); J->getIRTransformLayer().setTransform( [&](orc::ThreadSafeModule TSM, const orc::MaterializationResponsibility &R) { TSM.withModuleDo([&](Module &M) { if (verifyModule(M, &dbgs())) { dbgs() << "Bad module: " << &M << "\n"; exit(1); } Dump(M); }); return TSM; }); orc::MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout()); // Unless they've been explicitly disabled, make process symbols available to // JIT'd code. if (!NoProcessSymbols) J->getMainJITDylib().addGenerator( ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( J->getDataLayout().getGlobalPrefix(), [MainName = Mangle("main")](const orc::SymbolStringPtr &Name) { return Name != MainName; }))); if (GenerateBuiltinFunctions.size() > 0) J->getMainJITDylib().addGenerator( std::make_unique<LLIBuiltinFunctionGenerator>(GenerateBuiltinFunctions, Mangle)); // Regular modules are greedy: They materialize as a whole and trigger // materialization for all required symbols recursively. Lazy modules go // through partitioning and they replace outgoing calls with reexport stubs // that resolve on call-through. auto AddModule = [&](orc::JITDylib &JD, orc::ThreadSafeModule M) { return UseJITKind == JITKind::OrcLazy ? J->addLazyIRModule(JD, std::move(M)) : J->addIRModule(JD, std::move(M)); }; // Add the main module. ExitOnErr(AddModule(J->getMainJITDylib(), std::move(MainModule))); // Create JITDylibs and add any extra modules. { // Create JITDylibs, keep a map from argument index to dylib. We will use // -extra-module argument indexes to determine what dylib to use for each // -extra-module. std::map<unsigned, orc::JITDylib *> IdxToDylib; IdxToDylib[0] = &J->getMainJITDylib(); for (auto JDItr = JITDylibs.begin(), JDEnd = JITDylibs.end(); JDItr != JDEnd; ++JDItr) { orc::JITDylib *JD = J->getJITDylibByName(*JDItr); if (!JD) { JD = &ExitOnErr(J->createJITDylib(*JDItr)); J->getMainJITDylib().addToLinkOrder(*JD); JD->addToLinkOrder(J->getMainJITDylib()); } IdxToDylib[JITDylibs.getPosition(JDItr - JITDylibs.begin())] = JD; } for (auto EMItr = ExtraModules.begin(), EMEnd = ExtraModules.end(); EMItr != EMEnd; ++EMItr) { auto M = ExitOnErr(loadModule(*EMItr, TSCtx)); auto EMIdx = ExtraModules.getPosition(EMItr - ExtraModules.begin()); assert(EMIdx != 0 && "ExtraModule should have index > 0"); auto JDItr = std::prev(IdxToDylib.lower_bound(EMIdx)); auto &JD = *JDItr->second; ExitOnErr(AddModule(JD, std::move(M))); } for (auto EAItr = ExtraArchives.begin(), EAEnd = ExtraArchives.end(); EAItr != EAEnd; ++EAItr) { auto EAIdx = ExtraArchives.getPosition(EAItr - ExtraArchives.begin()); assert(EAIdx != 0 && "ExtraArchive should have index > 0"); auto JDItr = std::prev(IdxToDylib.lower_bound(EAIdx)); auto &JD = *JDItr->second; JD.addGenerator(ExitOnErr(orc::StaticLibraryDefinitionGenerator::Load( J->getObjLinkingLayer(), EAItr->c_str(), *TT))); } } // Add the objects. for (auto &ObjPath : ExtraObjects) { auto Obj = ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ObjPath))); ExitOnErr(J->addObjectFile(std::move(Obj))); } // Run any static constructors. ExitOnErr(J->initialize(J->getMainJITDylib())); // Run any -thread-entry points. std::vector<std::thread> AltEntryThreads; for (auto &ThreadEntryPoint : ThreadEntryPoints) { auto EntryPointSym = ExitOnErr(J->lookup(ThreadEntryPoint)); typedef void (*EntryPointPtr)(); auto EntryPoint = reinterpret_cast<EntryPointPtr>(static_cast<uintptr_t>(EntryPointSym.getAddress())); AltEntryThreads.push_back(std::thread([EntryPoint]() { EntryPoint(); })); } // Resolve and run the main function. JITEvaluatedSymbol MainSym = ExitOnErr(J->lookup(EntryFunc)); int Result; if (EPC) { // ExecutorProcessControl-based execution with JITLink. Result = ExitOnErr( EPC->runAsMain(orc::ExecutorAddr(MainSym.getAddress()), InputArgv)); } else { // Manual in-process execution with RuntimeDyld. using MainFnTy = int(int, char *[]); auto MainFn = jitTargetAddressToFunction<MainFnTy *>(MainSym.getAddress()); Result = orc::runAsMain(MainFn, InputArgv, StringRef(InputFile)); } // Wait for -entry-point threads. for (auto &AltEntryThread : AltEntryThreads) AltEntryThread.join(); // Run destructors. ExitOnErr(J->deinitialize(J->getMainJITDylib())); return Result; } void disallowOrcOptions() { // Make sure nobody used an orc-lazy specific option accidentally. if (LazyJITCompileThreads != 0) { errs() << "-compile-threads requires -jit-kind=orc-lazy\n"; exit(1); } if (!ThreadEntryPoints.empty()) { errs() << "-thread-entry requires -jit-kind=orc-lazy\n"; exit(1); } if (PerModuleLazy) { errs() << "-per-module-lazy requires -jit-kind=orc-lazy\n"; exit(1); } } Expected<std::unique_ptr<orc::ExecutorProcessControl>> launchRemote() { #ifndef LLVM_ON_UNIX llvm_unreachable("launchRemote not supported on non-Unix platforms"); #else int PipeFD[2][2]; pid_t ChildPID; // Create two pipes. if (pipe(PipeFD[0]) != 0 || pipe(PipeFD[1]) != 0) perror("Error creating pipe: "); ChildPID = fork(); if (ChildPID == 0) { // In the child... // Close the parent ends of the pipes close(PipeFD[0][1]); close(PipeFD[1][0]); // Execute the child process. std::unique_ptr<char[]> ChildPath, ChildIn, ChildOut; { ChildPath.reset(new char[ChildExecPath.size() + 1]); std::copy(ChildExecPath.begin(), ChildExecPath.end(), &ChildPath[0]); ChildPath[ChildExecPath.size()] = '\0'; std::string ChildInStr = utostr(PipeFD[0][0]); ChildIn.reset(new char[ChildInStr.size() + 1]); std::copy(ChildInStr.begin(), ChildInStr.end(), &ChildIn[0]); ChildIn[ChildInStr.size()] = '\0'; std::string ChildOutStr = utostr(PipeFD[1][1]); ChildOut.reset(new char[ChildOutStr.size() + 1]); std::copy(ChildOutStr.begin(), ChildOutStr.end(), &ChildOut[0]); ChildOut[ChildOutStr.size()] = '\0'; } char * const args[] = { &ChildPath[0], &ChildIn[0], &ChildOut[0], nullptr }; int rc = execv(ChildExecPath.c_str(), args); if (rc != 0) perror("Error executing child process: "); llvm_unreachable("Error executing child process"); } // else we're the parent... // Close the child ends of the pipes close(PipeFD[0][0]); close(PipeFD[1][1]); // Return a SimpleRemoteEPC instance connected to our end of the pipes. return orc::SimpleRemoteEPC::Create<orc::FDSimpleRemoteEPCTransport>( std::make_unique<llvm::orc::InPlaceTaskDispatcher>(), llvm::orc::SimpleRemoteEPC::Setup(), PipeFD[1][0], PipeFD[0][1]); #endif }
35.814175
90
0.644183
[ "object", "vector", "transform" ]
d51feeb572d22fd1fbc6752bced61945be0ebc84
6,422
cc
C++
src/cfg/paths.cc
sdasgup3/strata-stoke
b9981a48a82a72069896d29863649cfad1b4d98c
[ "ECL-2.0", "Apache-2.0" ]
2
2019-02-18T04:18:41.000Z
2020-08-26T06:42:46.000Z
src/cfg/paths.cc
sdasgup3/strata-stoke
b9981a48a82a72069896d29863649cfad1b4d98c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/cfg/paths.cc
sdasgup3/strata-stoke
b9981a48a82a72069896d29863649cfad1b4d98c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2013-2016 Stanford University // // 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 "src/cfg/paths.h" using namespace stoke; using namespace std; using namespace x64asm; //#define DEBUG_PATH_ENUM 1 vector<vector<Cfg::id_type>> CfgPaths::enumerate_paths(const Cfg& cfg, size_t max_len, Cfg::id_type start, Cfg::id_type end, std::vector<Cfg::id_type>* nopass) { if (start == (Cfg::id_type)-1) start = cfg.get_entry(); if (end == (Cfg::id_type)-1) end = cfg.get_exit(); vector<vector<Cfg::id_type>> results; vector<Cfg::id_type> path_so_far; path_so_far.push_back(start); std::map<Cfg::id_type, size_t> node_counts; if (max_len > 0) enumerate_paths_helper(cfg, path_so_far, end, max_len, node_counts, results, nopass); // Remove all blocks with zero instructions for (auto& path : results) { for (auto iter = path.begin(); iter != path.end(); ) { if (!cfg.num_instrs(*iter)) { iter = path.erase(iter); } else { ++iter; } } } return results; } void CfgPaths::enumerate_paths_helper(const Cfg& cfg, std::vector<Cfg::id_type> path_so_far, Cfg::id_type end_block, size_t max_count, std::map<Cfg::id_type, size_t> counts, std::vector<std::vector<Cfg::id_type>>& results, std::vector<Cfg::id_type>* nopass) { size_t len = path_so_far.size(); Cfg::id_type last_block = path_so_far[len - 1]; #ifdef DEBUG_PATH_ENUM for (size_t i = 0; i < len; ++i) { cout << " "; } cout << "Path: "; for (size_t i = 0; i < len; ++i) { cout << path_so_far[i] << " "; } cout << endl; #endif // check for end if (last_block == end_block && path_so_far.size() > 1) { #ifdef DEBUG_PATH_ENUM for (size_t i = 0; i < len; ++i) { cout << " "; } cout << "* Adding solution!" << endl; #endif results.push_back(path_so_far); } if (nopass && path_so_far.size() > 1 && find(nopass->begin(), nopass->end(), last_block) != nopass->end()) { return; } if (last_block == cfg.get_exit()) return; // iterate for (auto it = cfg.succ_begin(last_block), ie = cfg.succ_end(last_block); it != ie; ++it) { size_t this_count = ++counts[*it]; if (this_count > max_count) { counts[*it]--; #ifdef DEBUG_PATH_ENUM for (size_t i = 0; i < len; ++i) { cout << " "; } cout << "* Successor dead end: " << *it << endl; #endif continue; } #ifdef DEBUG_PATH_ENUM for (size_t i = 0; i < len; ++i) { cout << " "; } cout << "* Exploring successor: " << *it << endl; #endif path_so_far.push_back(*it); enumerate_paths_helper(cfg, path_so_far, end_block, max_count, counts, results, nopass); path_so_far.erase(path_so_far.begin() + path_so_far.size()-1); counts[*it]--; } } Cfg CfgPaths::rewrite_cfg_with_path(const Cfg& cfg, const CfgPath& p) { Code code; for (auto node : p) { if (cfg.num_instrs(node) == 0) continue; size_t start_index = cfg.get_index(std::pair<Cfg::id_type, size_t>(node, 0)); size_t end_index = start_index + cfg.num_instrs(node); for (size_t i = start_index; i < end_index; ++i) { if (cfg.get_code()[i].is_jump()) { code.push_back(Instruction(NOP)); } else { code.push_back(cfg.get_code()[i]); } } } Cfg new_cfg(code, cfg.def_ins(), cfg.live_outs()); //cout << "path cfg for " << print(p) << " is " << endl; //cout << TUnit(code) << endl; return new_cfg; } /** Find the path this testcase takes through the CFG. */ bool CfgPaths::learn_path(CfgPath& path, const Cfg& cfg, const CpuState& tc) { auto code = cfg.get_code(); auto label = code[0].get_operand<x64asm::Label>(0); sandbox_->reset(); sandbox_->insert_input(tc); sandbox_->insert_function(cfg); sandbox_->set_entrypoint(label); /** Insert code either before or after the first instruction in a block to * record the path took */ vector<pair<CfgPaths*, Cfg::id_type>*> to_delete; for (size_t i = 0; i < code.size(); ++i) { // figure out if we're at the beginning of a block auto loc = cfg.get_loc(i); auto steps = loc.second; if (steps > 0) continue; // build a pair with a pointer to our object and the basic block of this // instruction auto pair = new std::pair<CfgPaths*, Cfg::id_type>(this, loc.first); to_delete.push_back(pair); // insert callback after labels (so jumps don't skip them), but before // returns and everything else (so if segfault or exit we still get // called). auto instr = code[i]; if (instr.is_label_defn()) { sandbox_->insert_after(label, i, learn_path_callback, pair); } else { sandbox_->insert_before(label, i, learn_path_callback, pair); } } // Now learn the path! current_path_ = &path; sandbox_->run(); for (auto it : to_delete) delete it; auto err = sandbox_->get_output(0)->code; return (err == ErrorCode::NORMAL); } /** Returns true if first path is a prefix of the second. */ bool CfgPaths::is_prefix(const CfgPath& p, const CfgPath& q) { if (q.size() < p.size()) return false; for (size_t i = 0; i < p.size(); ++i) { if (p[i] != q[i]) return false; } return true; } /** Callback used for learning a path. */ void CfgPaths::learn_path_callback(const StateCallbackData&, void* arg) { auto pair = (std::pair<CfgPaths*, Cfg::id_type>*)arg; auto bb = pair->second; pair->first->current_path_->push_back(bb); } namespace std { ostream& operator<<(ostream& os, const stoke::CfgPath& path) { for (size_t i = 0; i < path.size(); ++i) { os << path[i]; if (i < path.size() - 1) os << " "; } return os; } }
26.870293
161
0.607599
[ "object", "vector" ]
d523cd9c86732780f20ba65a25b83f73e73dae4a
6,758
cpp
C++
modules/juce_core/text/juce_LocalisedStrings.cpp
genkiinstruments/juce_emscripten
9fcda4deecf1f6d8cefc483a8858e1bbecc72809
[ "ISC" ]
80
2019-12-31T15:16:19.000Z
2022-02-17T22:52:25.000Z
modules/juce_core/text/juce_LocalisedStrings.cpp
genkiinstruments/juce_emscripten
9fcda4deecf1f6d8cefc483a8858e1bbecc72809
[ "ISC" ]
4
2019-02-11T11:52:13.000Z
2020-10-09T06:39:18.000Z
modules/juce_core/text/juce_LocalisedStrings.cpp
genkiinstruments/juce_emscripten
9fcda4deecf1f6d8cefc483a8858e1bbecc72809
[ "ISC" ]
9
2019-12-26T12:18:29.000Z
2021-12-27T18:51:38.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { LocalisedStrings::LocalisedStrings (const String& fileContents, bool ignoreCase) { loadFromText (fileContents, ignoreCase); } LocalisedStrings::LocalisedStrings (const File& fileToLoad, bool ignoreCase) { loadFromText (fileToLoad.loadFileAsString(), ignoreCase); } LocalisedStrings::LocalisedStrings (const LocalisedStrings& other) : languageName (other.languageName), countryCodes (other.countryCodes), translations (other.translations), fallback (createCopyIfNotNull (other.fallback.get())) { } LocalisedStrings& LocalisedStrings::operator= (const LocalisedStrings& other) { languageName = other.languageName; countryCodes = other.countryCodes; translations = other.translations; fallback.reset (createCopyIfNotNull (other.fallback.get())); return *this; } LocalisedStrings::~LocalisedStrings() { } //============================================================================== String LocalisedStrings::translate (const String& text) const { if (fallback != nullptr && ! translations.containsKey (text)) return fallback->translate (text); return translations.getValue (text, text); } String LocalisedStrings::translate (const String& text, const String& resultIfNotFound) const { if (fallback != nullptr && ! translations.containsKey (text)) return fallback->translate (text, resultIfNotFound); return translations.getValue (text, resultIfNotFound); } namespace { #if JUCE_CHECK_MEMORY_LEAKS // By using this object to force a LocalisedStrings object to be created // before the currentMappings object, we can force the static order-of-destruction to // delete the currentMappings object first, which avoids a bogus leak warning. // (Oddly, just creating a LocalisedStrings on the stack doesn't work in gcc, it // has to be created with 'new' for this to work..) struct LeakAvoidanceTrick { LeakAvoidanceTrick() { const std::unique_ptr<LocalisedStrings> dummy (new LocalisedStrings (String(), false)); } }; LeakAvoidanceTrick leakAvoidanceTrick; #endif SpinLock currentMappingsLock; std::unique_ptr<LocalisedStrings> currentMappings; static int findCloseQuote (const String& text, int startPos) { juce_wchar lastChar = 0; auto t = text.getCharPointer() + startPos; for (;;) { auto c = t.getAndAdvance(); if (c == 0 || (c == '"' && lastChar != '\\')) break; lastChar = c; ++startPos; } return startPos; } static String unescapeString (const String& s) { return s.replace ("\\\"", "\"") .replace ("\\\'", "\'") .replace ("\\t", "\t") .replace ("\\r", "\r") .replace ("\\n", "\n"); } } void LocalisedStrings::loadFromText (const String& fileContents, bool ignoreCase) { translations.setIgnoresCase (ignoreCase); StringArray lines; lines.addLines (fileContents); for (auto& l : lines) { auto line = l.trim(); if (line.startsWithChar ('"')) { auto closeQuote = findCloseQuote (line, 1); auto originalText = unescapeString (line.substring (1, closeQuote)); if (originalText.isNotEmpty()) { auto openingQuote = findCloseQuote (line, closeQuote + 1); closeQuote = findCloseQuote (line, openingQuote + 1); auto newText = unescapeString (line.substring (openingQuote + 1, closeQuote)); if (newText.isNotEmpty()) translations.set (originalText, newText); } } else if (line.startsWithIgnoreCase ("language:")) { languageName = line.substring (9).trim(); } else if (line.startsWithIgnoreCase ("countries:")) { countryCodes.addTokens (line.substring (10).trim(), true); countryCodes.trim(); countryCodes.removeEmptyStrings(); } } translations.minimiseStorageOverheads(); } void LocalisedStrings::addStrings (const LocalisedStrings& other) { jassert (languageName == other.languageName); jassert (countryCodes == other.countryCodes); translations.addArray (other.translations); } void LocalisedStrings::setFallback (LocalisedStrings* f) { fallback.reset (f); } //============================================================================== void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) { const SpinLock::ScopedLockType sl (currentMappingsLock); currentMappings.reset (newTranslations); } LocalisedStrings* LocalisedStrings::getCurrentMappings() { return currentMappings.get(); } String LocalisedStrings::translateWithCurrentMappings (const String& text) { return juce::translate (text); } String LocalisedStrings::translateWithCurrentMappings (const char* text) { return juce::translate (text); } JUCE_API String translate (const String& text) { return juce::translate (text, text); } JUCE_API String translate (const char* text) { return juce::translate (String (text)); } JUCE_API String translate (CharPointer_UTF8 text) { return juce::translate (String (text)); } JUCE_API String translate (const String& text, const String& resultIfNotFound) { const SpinLock::ScopedLockType sl (currentMappingsLock); if (auto* mappings = LocalisedStrings::getCurrentMappings()) return mappings->translate (text, resultIfNotFound); return resultIfNotFound; } } // namespace juce
32.647343
111
0.616455
[ "object" ]
d526cb7742a1a2d1e3a1681d88ad52fe2edfee56
7,456
cc
C++
content/browser/streams/stream_url_request_job.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
content/browser/streams/stream_url_request_job.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/streams/stream_url_request_job.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/streams/stream_url_request_job.h" #include "base/profiler/scoped_tracker.h" #include "base/strings/string_number_conversions.h" #include "content/browser/streams/stream.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_byte_range.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/http/http_util.h" #include "net/url_request/url_request.h" namespace content { StreamURLRequestJob::StreamURLRequestJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, scoped_refptr<Stream> stream) : net::URLRequestJob(request, network_delegate), stream_(stream), headers_set_(false), pending_buffer_size_(0), total_bytes_read_(0), max_range_(0), request_failed_(false), weak_factory_(this) { DCHECK(stream_.get()); stream_->SetReadObserver(this); } StreamURLRequestJob::~StreamURLRequestJob() { ClearStream(); } void StreamURLRequestJob::OnDataAvailable(Stream* stream) { // Clear the IO_PENDING status. SetStatus(net::URLRequestStatus()); // Do nothing if pending_buffer_ is empty, i.e. there's no ReadRawData() // operation waiting for IO completion. if (!pending_buffer_.get()) return; // pending_buffer_ is set to the IOBuffer instance provided to ReadRawData() // by URLRequestJob. int bytes_read; switch (stream_->ReadRawData( pending_buffer_.get(), pending_buffer_size_, &bytes_read)) { case Stream::STREAM_HAS_DATA: DCHECK_GT(bytes_read, 0); break; case Stream::STREAM_COMPLETE: // Ensure this. Calling NotifyReadComplete call with 0 signals // completion. bytes_read = 0; break; case Stream::STREAM_EMPTY: NOTREACHED(); break; case Stream::STREAM_ABORTED: // Handle this as connection reset. NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, net::ERR_CONNECTION_RESET)); break; } // Clear the buffers before notifying the read is complete, so that it is // safe for the observer to read. pending_buffer_ = NULL; pending_buffer_size_ = 0; total_bytes_read_ += bytes_read; NotifyReadComplete(bytes_read); } // net::URLRequestJob methods. void StreamURLRequestJob::Start() { // Continue asynchronously. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&StreamURLRequestJob::DidStart, weak_factory_.GetWeakPtr())); } void StreamURLRequestJob::Kill() { net::URLRequestJob::Kill(); weak_factory_.InvalidateWeakPtrs(); ClearStream(); } bool StreamURLRequestJob::ReadRawData(net::IOBuffer* buf, int buf_size, int* bytes_read) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "423948 StreamURLRequestJob::ReadRawData")); if (request_failed_) return true; DCHECK(buf); DCHECK(bytes_read); int to_read = buf_size; if (max_range_ && to_read) { if (to_read + total_bytes_read_ > max_range_) to_read = max_range_ - total_bytes_read_; if (to_read <= 0) { *bytes_read = 0; return true; } } switch (stream_->ReadRawData(buf, to_read, bytes_read)) { case Stream::STREAM_HAS_DATA: case Stream::STREAM_COMPLETE: total_bytes_read_ += *bytes_read; return true; case Stream::STREAM_EMPTY: pending_buffer_ = buf; pending_buffer_size_ = to_read; SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0)); return false; case Stream::STREAM_ABORTED: // Handle this as connection reset. NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, net::ERR_CONNECTION_RESET)); return false; } NOTREACHED(); return false; } bool StreamURLRequestJob::GetMimeType(std::string* mime_type) const { if (!response_info_) return false; // TODO(zork): Support registered MIME types if needed. return response_info_->headers->GetMimeType(mime_type); } void StreamURLRequestJob::GetResponseInfo(net::HttpResponseInfo* info) { if (response_info_) *info = *response_info_; } int StreamURLRequestJob::GetResponseCode() const { if (!response_info_) return -1; return response_info_->headers->response_code(); } void StreamURLRequestJob::SetExtraRequestHeaders( const net::HttpRequestHeaders& headers) { std::string range_header; if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) { std::vector<net::HttpByteRange> ranges; if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) { if (ranges.size() == 1) { // Streams don't support seeking, so a non-zero starting position // doesn't make sense. if (ranges[0].first_byte_position() == 0) { max_range_ = ranges[0].last_byte_position() + 1; } else { NotifyFailure(net::ERR_METHOD_NOT_SUPPORTED); return; } } else { NotifyFailure(net::ERR_METHOD_NOT_SUPPORTED); return; } } } } void StreamURLRequestJob::DidStart() { // We only support GET request. if (request()->method() != "GET") { NotifyFailure(net::ERR_METHOD_NOT_SUPPORTED); return; } HeadersCompleted(net::HTTP_OK); } void StreamURLRequestJob::NotifyFailure(int error_code) { request_failed_ = true; // If we already return the headers on success, we can't change the headers // now. Instead, we just error out. if (headers_set_) { NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED, error_code)); return; } // TODO(zork): Share these with BlobURLRequestJob. net::HttpStatusCode status_code = net::HTTP_INTERNAL_SERVER_ERROR; switch (error_code) { case net::ERR_ACCESS_DENIED: status_code = net::HTTP_FORBIDDEN; break; case net::ERR_FILE_NOT_FOUND: status_code = net::HTTP_NOT_FOUND; break; case net::ERR_METHOD_NOT_SUPPORTED: status_code = net::HTTP_METHOD_NOT_ALLOWED; break; case net::ERR_FAILED: break; default: DCHECK(false); break; } HeadersCompleted(status_code); } void StreamURLRequestJob::HeadersCompleted(net::HttpStatusCode status_code) { std::string status("HTTP/1.1 "); status.append(base::IntToString(status_code)); status.append(" "); status.append(net::GetHttpReasonPhrase(status_code)); status.append("\0\0", 2); net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status); if (status_code == net::HTTP_OK) { std::string content_type_header(net::HttpRequestHeaders::kContentType); content_type_header.append(": "); content_type_header.append("text/plain"); headers->AddHeader(content_type_header); } response_info_.reset(new net::HttpResponseInfo()); response_info_->headers = headers; headers_set_ = true; NotifyHeadersComplete(); } void StreamURLRequestJob::ClearStream() { if (stream_.get()) { stream_->RemoveReadObserver(this); stream_ = NULL; } } } // namespace content
29.239216
78
0.685622
[ "vector" ]
d5278f816d24ca4274bae3fd9d6970a80b8020e3
57,859
cc
C++
servlib/conv_layers/SeqpacketConvergenceLayer.cc
lauramazzuca21/DTNME
c97b598b09a8c8e97c2e4136879d9f0e157c8df7
[ "Apache-2.0" ]
7
2021-02-11T16:54:24.000Z
2021-08-20T06:15:30.000Z
servlib/conv_layers/SeqpacketConvergenceLayer.cc
lauramazzuca21/DTNME
c97b598b09a8c8e97c2e4136879d9f0e157c8df7
[ "Apache-2.0" ]
3
2020-09-18T13:48:53.000Z
2021-05-27T18:28:14.000Z
servlib/conv_layers/SeqpacketConvergenceLayer.cc
lauramazzuca21/DTNME
c97b598b09a8c8e97c2e4136879d9f0e157c8df7
[ "Apache-2.0" ]
10
2020-09-26T05:08:40.000Z
2022-01-25T12:57:55.000Z
/* * Copyright 2009-2010 Darren Long, darren.long@mac.com * Copyright 2006 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications made to this file by the patch file dtnme_mfs-33289-1.patch * are Copyright 2015 United States Government as represented by NASA * Marshall Space Flight Center. All Rights Reserved. * * Released under the NASA Open Source Software Agreement version 1.3; * You may obtain a copy of the Agreement at: * * http://ti.arc.nasa.gov/opensource/nosa/ * * The subject software is provided "AS IS" WITHOUT ANY WARRANTY of any kind, * either expressed, implied or statutory and this agreement does not, * in any manner, constitute an endorsement by government agency of any * results, designs or products resulting from use of the subject software. * See the Agreement for the specific language governing permissions and * limitations. */ #ifdef HAVE_CONFIG_H # include <dtn-config.h> #endif #include <oasys/util/OptParser.h> #include "SeqpacketConvergenceLayer.h" #include "bundling/BundleDaemon.h" #include "bundling/SDNV.h" #include "bundling/TempBundle.h" #include "contacts/ContactManager.h" namespace dtn { //---------------------------------------------------------------------- SeqpacketConvergenceLayer::SeqpacketLinkParams::SeqpacketLinkParams(bool init_defaults) : LinkParams(init_defaults), segment_ack_enabled_(true), negative_ack_enabled_(true), keepalive_interval_(10), segment_length_(4096), ack_window_(8) { } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::SeqpacketLinkParams::serialize(oasys::SerializeAction *a) { log_debug_p("StreamLinkParams", "StreamLinkParams::serialize"); ConnectionConvergenceLayer::LinkParams::serialize(a); a->process("segment_ack_enabled", &segment_ack_enabled_); a->process("negative_ack_enabled", &negative_ack_enabled_); a->process("keepalive_interval", &keepalive_interval_); a->process("segment_length", &segment_length_); a->process("ack_window", &ack_window_); } //---------------------------------------------------------------------- SeqpacketConvergenceLayer::SeqpacketConvergenceLayer(const char* logpath, const char* cl_name, u_int8_t cl_version) : ConnectionConvergenceLayer(logpath, cl_name), cl_version_(cl_version) { } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::parse_link_params(LinkParams* lparams, int argc, const char** argv, const char** invalidp) { // all subclasses should create a params structure that derives // from SeqpacketLinkParams SeqpacketLinkParams* params = dynamic_cast<SeqpacketLinkParams*>(lparams); ASSERT(params != NULL); oasys::OptParser p; p.addopt(new oasys::BoolOpt("segment_ack_enabled", &params->segment_ack_enabled_)); p.addopt(new oasys::BoolOpt("negative_ack_enabled", &params->negative_ack_enabled_)); p.addopt(new oasys::UIntOpt("keepalive_interval", &params->keepalive_interval_)); p.addopt(new oasys::UIntOpt("segment_length", &params->segment_length_)); p.addopt(new oasys::UIntOpt("ack_window", &params->ack_window_)); p.addopt(new oasys::UInt8Opt("cl_version", &cl_version_)); int count = p.parse_and_shift(argc, argv, invalidp); if (count == -1) { return false; } argc -= count; return ConnectionConvergenceLayer::parse_link_params(lparams, argc, argv, invalidp); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::finish_init_link(const LinkRef& link, LinkParams* lparams) { SeqpacketLinkParams* params = dynamic_cast<SeqpacketLinkParams*>(lparams); ASSERT(params != NULL); // make sure to set the reliability bit in the link structure if (params->segment_ack_enabled_) { link->set_reliable(true); } return true; } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::dump_link(const LinkRef& link, oasys::StringBuffer* buf) { ASSERT(link != NULL); ASSERT(!link->isdeleted()); ASSERT(link->cl_info() != NULL); ConnectionConvergenceLayer::dump_link(link, buf); SeqpacketLinkParams* params = dynamic_cast<SeqpacketLinkParams*>(link->cl_info()); ASSERT(params != NULL); buf->appendf("segment_ack_enabled: %u\n", params->segment_ack_enabled_); buf->appendf("negative_ack_enabled: %u\n", params->negative_ack_enabled_); buf->appendf("keepalive_interval: %u\n", params->keepalive_interval_); buf->appendf("segment_length: %u\n", params->segment_length_); buf->appendf("ack_window: %u\n", params->ack_window_); buf->appendf("cl_version: %u\n", cl_version_); } //---------------------------------------------------------------------- SeqpacketConvergenceLayer::Connection::Connection(const char* classname, const char* logpath, SeqpacketConvergenceLayer* cl, SeqpacketLinkParams* params, bool active_connector) : CLConnection(classname, logpath, cl, params, active_connector), current_inflight_(NULL), send_segment_todo_(0), recv_segment_todo_(0), breaking_contact_(false), contact_initiated_(false), ack_window_todo_(0) { } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::initiate_contact() { size_t local_eid_len; log_debug("initiate_contact called"); // format the contact header ContactHeader contacthdr; contacthdr.magic = htonl(MAGIC); contacthdr.version = ((SeqpacketConvergenceLayer*)cl_)->cl_version_; contacthdr.flags = 0; SeqpacketLinkParams* params = seqpacket_lparams(); if (params->segment_ack_enabled_) contacthdr.flags |= SEGMENT_ACK_ENABLED; if (params->reactive_frag_enabled_) contacthdr.flags |= REACTIVE_FRAG_ENABLED; contacthdr.keepalive_interval = htons(params->keepalive_interval_); // copy the contact header into the send buffer ASSERT(sendbuf_.fullbytes() == 0); if (sendbuf_.tailbytes() < sizeof(ContactHeader)) { log_warn("send buffer too short: %zu < needed %zu", sendbuf_.tailbytes(), sizeof(ContactHeader)); sendbuf_.reserve(sizeof(ContactHeader)); } memcpy(sendbuf_.start(), &contacthdr, sizeof(ContactHeader)); sendbuf_.fill(sizeof(ContactHeader)); // follow up with the local endpoint id length + data BundleDaemon* bd = BundleDaemon::instance(); if(!bd->params_.announce_ipn_) local_eid_len = bd->local_eid().length(); else local_eid_len = bd->local_eid_ipn().length(); size_t sdnv_len = SDNV::encoding_len(local_eid_len); if (sendbuf_.tailbytes() < sdnv_len + local_eid_len) { log_warn("send buffer too short: %zu < needed %zu", sendbuf_.tailbytes(), sdnv_len + local_eid_len); sendbuf_.reserve(sizeof(ContactHeader) + sdnv_len + local_eid_len); } sdnv_len = SDNV::encode(local_eid_len, (u_char*)sendbuf_.end(), sendbuf_.tailbytes()); sendbuf_.fill(sdnv_len); if(!bd->params_.announce_ipn_) memcpy(sendbuf_.end(), bd->local_eid().data(), local_eid_len); else memcpy(sendbuf_.end(), bd->local_eid_ipn().data(), local_eid_len); sendbuf_.fill(local_eid_len); sendbuf_sequence_delimiters_.push(sizeof(ContactHeader) + sdnv_len + local_eid_len); log_info("adding pending sequence: %zu to sequence delimiters queue, queue depth: %zu", sizeof(ContactHeader) + sdnv_len + local_eid_len, sendbuf_sequence_delimiters_.size()); // drain the send buffer note_data_sent(); send_data(); /* * Now we initialize the various timers that are used for * keepalives / idle timeouts to make sure they're not used * uninitialized. */ ::gettimeofday(&data_rcvd_, 0); ::gettimeofday(&data_sent_, 0); ::gettimeofday(&keepalive_sent_, 0); // XXX/demmer need to add a test for nothing coming back contact_initiated_ = true; } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::handle_contact_initiation() { ASSERT(! contact_up_); /* * First check for valid magic number. */ u_int32_t magic = 0; size_t len_needed = sizeof(magic); if (recvbuf_.fullbytes() < len_needed) { tooshort: log_debug("handle_contact_initiation: not enough data received " "(need > %zu, got %zu)", len_needed, recvbuf_.fullbytes()); return; } memcpy(&magic, recvbuf_.start(), sizeof(magic)); magic = ntohl(magic); if (magic != MAGIC) { log_warn("remote sent magic number 0x%.8x, expected 0x%.8x " "-- disconnecting.", magic, MAGIC); break_contact(ContactEvent::CL_ERROR); oasys::Breaker::break_here(); return; } /* * Now check that we got a full contact header */ len_needed = sizeof(ContactHeader); if (recvbuf_.fullbytes() < len_needed) { goto tooshort; } /* * Now check for enough data for the peer's eid */ u_int64_t peer_eid_len; int sdnv_len = SDNV::decode((u_char*)recvbuf_.start() + sizeof(ContactHeader), recvbuf_.fullbytes() - sizeof(ContactHeader), &peer_eid_len); if (sdnv_len < 0) { goto tooshort; } len_needed = sizeof(ContactHeader) + sdnv_len + peer_eid_len; if (recvbuf_.fullbytes() < len_needed) { goto tooshort; } /* * Ok, we have enough data, parse the contact header. */ ContactHeader contacthdr; memcpy(&contacthdr, recvbuf_.start(), sizeof(ContactHeader)); contacthdr.magic = ntohl(contacthdr.magic); contacthdr.keepalive_interval = ntohs(contacthdr.keepalive_interval); recvbuf_.consume(sizeof(ContactHeader)); /* * In this implementation, we can't handle other versions than our * own, but if the other side presents a higher version, we allow * it to go through and thereby allow them to downgrade to this * version. */ u_int8_t cl_version = ((SeqpacketConvergenceLayer*)cl_)->cl_version_; if (contacthdr.version < cl_version) { log_warn("remote sent version %d, expected version %d " "-- disconnecting.", contacthdr.version, cl_version); break_contact(ContactEvent::CL_VERSION); return; } /* * Now do parameter negotiation. */ SeqpacketLinkParams* params = seqpacket_lparams(); // DML - tweaked to use std::max instead of std::min. We want to be // conservative about channel usage. If we time out, that is too bad. // Reason for this hack is that the listener sends out a keepalive in its // contact header before it knows that the link in question should have a // non-default keepalive_interval, and uses the default, which is lower // than what we want, hence the need to use max. Perhaps a better bet is to // send out a contact header from the listener after receiving the // inbound contact header from the initiator. Or, we could simply increase // the default timeout. params->keepalive_interval_ = std::max(params->keepalive_interval_, (u_int)contacthdr.keepalive_interval); params->segment_ack_enabled_ = params->segment_ack_enabled_ && (contacthdr.flags & SEGMENT_ACK_ENABLED); params->reactive_frag_enabled_ = params->reactive_frag_enabled_ && (contacthdr.flags & REACTIVE_FRAG_ENABLED); params->negative_ack_enabled_ = params->negative_ack_enabled_ && (contacthdr.flags & NEGATIVE_ACK_ENABLED); /* * Make sure to readjust poll_timeout in case we have a smaller * keepalive interval than data timeout */ if (params->keepalive_interval_ != 0 && (params->keepalive_interval_ * 1000) < params->data_timeout_) { poll_timeout_ = params->keepalive_interval_ * 1000; } /* * Now skip the sdnv that encodes the peer's eid length since we * parsed it above. */ recvbuf_.consume(sdnv_len); /* * Finally, parse the peer node's eid and give it to the base * class to handle (i.e. by linking us to a Contact if we don't * have one). */ EndpointID peer_eid; if (! peer_eid.assign(recvbuf_.start(), peer_eid_len)) { log_err("protocol error: invalid endpoint id '%s' (len %llu)", peer_eid.c_str(), U64FMT(peer_eid_len)); break_contact(ContactEvent::CL_ERROR); return; } if (!find_contact(peer_eid)) { ASSERT(contact_ == NULL); log_debug("SeqpacketConvergenceLayer::Connection::" "handle_contact_initiation: failed to find contact"); break_contact(ContactEvent::CL_ERROR); return; } recvbuf_.consume(peer_eid_len); /* * Make sure that the link's remote eid field is properly set. */ LinkRef link = contact_->link(); if (link->remote_eid().str() == EndpointID::NULL_EID().str()) { link->set_remote_eid(peer_eid); } else if (link->remote_eid() != peer_eid) { log_warn("handle_contact_initiation: remote eid mismatch: " "link remote eid was set to %s but peer eid is %s", link->remote_eid().c_str(), peer_eid.c_str()); } /* * Finally, we note that the contact is now up. */ contact_up(); } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::handle_bundles_queued() { // since the main run loop checks the link queue to see if there // are bundles that should be put in flight, we simply log a debug // message here. the point of the message is to kick the thread // out of poll() which forces the main loop to check the queue log_debug("handle_bundles_queued: %u bundles on link queue", contact_->link()->bundles_queued()); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::send_pending_data() { // if the outgoing data buffer is full, we can't do anything until // we poll() if (sendbuf_.tailbytes() == 0) { return false; } // if we're in the middle of sending a segment, we need to continue // sending it. only if we completely send the segment do we fall // through to send acks, otherwise we return to try to finish it // again later. if (send_segment_todo_ != 0) { ASSERT(current_inflight_ != NULL); send_data_todo(current_inflight_); } // see if we're broken or write blocked if (contact_broken_ || (send_segment_todo_ != 0)) { if (params_->test_write_delay_ != 0) { return true; } return false; } // now check if there are acks we need to send -- even if it // returns true (i.e. we sent an ack), we continue on and try to // send some real payload data, otherwise we could get starved by // arriving data and never send anything out. bool sent_ack = send_pending_acks(); // if the connection failed during ack transmission, stop if (contact_broken_) { return sent_ack; } // check if we need to start a new bundle. if we do, then // start_next_bundle handles the correct return code bool sent_data; if (current_inflight_ == NULL) { sent_data = start_next_bundle(); } else { // otherwise send the next segment of the current bundle sent_data = send_next_segment(current_inflight_); } return sent_ack || sent_data; } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::send_pending_acks() { if (contact_broken_ || incoming_.empty()) { return false; // nothing to do } IncomingBundle* incoming = incoming_.front(); DataBitmap::iterator iter = incoming->ack_data_.begin(); bool generated_ack = false; size_t encoding_len, totol_ack_len=0; // DML TODO: the bitmask stuff incoming->ack_data_ // seems nugatory, so perhaps it can go. I've definitely broken it, but // it doesn't stop the this working anyway. // If it does go, then perhaps the while loop can go too, as data segments // should always be received in order and without scope gaps. // when data segment headers are received, the last bit of the // segment is marked in ack_data, thus if there's nothing in // there, we don't need to send out an ack. if (iter == incoming->ack_data_.end() || incoming->rcvd_data_.empty()) { goto check_done; } // however, we have to be careful to check the recv_data as well // to make sure we've actually gotten the segment, since the bit // in ack_data is marked when the segment is begun, not when it's // completed while (1) { size_t rcvd_bytes = incoming->rcvd_data_.num_contiguous(); size_t ack_len = rcvd_bytes; // DML hack // *iter + 1; //size_t segment_len = ack_len - incoming->acked_length_; //(void)segment_len; SeqpacketLinkParams* params = seqpacket_lparams(); // DML - If we have a whole bundle's worth of data we want to ack now // otherwise, we want to see if we have a whole window's worth to ack, // and if we have, ack that. If not, we'll deal with it later. // DML -If we don't have a full bundle or we have haven't reached the // ack window yet, bail. The ack_window_todo attribute is decremented // or set to zero in handle_data_segment(). if(0 != ack_window_todo_) { log_debug("send_pending_acks: " "waiting to send ack for window %u segments " "since need %u more segments", params->ack_window_, ack_window_todo_); break; } else { // we need to reinitialise the ack_window_todo_ ack_window_todo_ = params->ack_window_; } // make sure we have space in the send buffer encoding_len = 1 + SDNV::encoding_len(ack_len); if (encoding_len > sendbuf_.tailbytes()) { log_debug("send_pending_acks: " "no space for ack in buffer (need %zu, have %zu)", encoding_len, sendbuf_.tailbytes()); break; } if (totol_ack_len + encoding_len > params->segment_length_ ) { log_debug("send_pending_acks: " "no space for additional ack in segment sized %u, sending %zu bytes)", params->segment_length_ , totol_ack_len); break; } log_debug("send_pending_acks: " "sending ack length %zu " "[range %u..%u] ack_data *%p", ack_len, incoming->acked_length_, *iter, &incoming->ack_data_); *sendbuf_.end() = ACK_SEGMENT; int len = SDNV::encode(ack_len, (u_char*)sendbuf_.end() + 1, sendbuf_.tailbytes() - 1); ASSERT(encoding_len = len + 1); sendbuf_.fill(encoding_len); totol_ack_len += encoding_len; generated_ack = true; incoming->acked_length_ = ack_len; incoming->ack_data_.clear(*iter); iter = incoming->ack_data_.begin(); if (iter == incoming->ack_data_.end()) { // XXX/demmer this should check if there's another bundle // with acks we could send break; } log_debug("send_pending_acks: " "found another segment (%u)", *iter); } if (generated_ack) { sendbuf_sequence_delimiters_.push(totol_ack_len); // may hold many segments log_info("adding pending sequence: %zu to sequence delimiters queue, queue depth: %zu", totol_ack_len, sendbuf_sequence_delimiters_.size()); send_data(); note_data_sent(); } // now, check if a) we've gotten everything we're supposed to // (i.e. total_length_ isn't zero), and b) we're done with all the // acks we need to send check_done: if ((incoming->total_length_ != 0) && (incoming->total_length_ == incoming->acked_length_)) { log_debug("send_pending_acks: acked all %u bytes of bundle %" PRIbid, incoming->total_length_, incoming->bundle_->bundleid()); incoming_.pop_front(); delete incoming; } else { log_debug("send_pending_acks: " "still need to send acks -- acked_range %u", incoming->ack_data_.num_contiguous()); } // return true if we've sent something return generated_ack; } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::start_next_bundle() { ASSERT(current_inflight_ == NULL); if (! contact_up_) { log_debug("start_next_bundle: contact not yet set up"); return false; } const LinkRef& link = contact_->link(); BundleRef bundle("StreamCL::Connection::start_next_bundle"); // try to pop the next bundle off the link queue and put it in // flight, making sure to hold the link queue lock until it's // safely on the link's inflight queue oasys::ScopeLock l(link->queue()->lock(), "StreamCL::Connection::start_next_bundle"); bundle = link->queue()->front(); if (bundle == NULL) { log_debug("start_next_bundle: nothing to start"); return false; } InFlightBundle* inflight = new InFlightBundle(bundle.object()); log_debug("trying to find xmit blocks for bundle id:%" PRIbid " on link %s", bundle->bundleid(), link->name()); inflight->blocks_ = bundle->xmit_blocks()->find_blocks(contact_->link()); ASSERT(inflight->blocks_ != NULL); inflight->total_length_ = BundleProtocol::total_length(inflight->blocks_); inflight_.push_back(inflight); current_inflight_ = inflight; link->add_to_inflight(bundle, inflight->total_length_); link->del_from_queue(bundle, inflight->total_length_); // release the lock before calling send_next_segment since it // might take a while l.unlock(); // now send the first segment for the bundle return send_next_segment(current_inflight_); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::send_next_segment(InFlightBundle* inflight) { if (sendbuf_.tailbytes() == 0) { return false; } ASSERT(send_segment_todo_ == 0); SeqpacketLinkParams* params = seqpacket_lparams(); size_t bytes_sent = inflight->sent_data_.empty() ? 0 : inflight->sent_data_.last() + 1; if (bytes_sent == inflight->total_length_) { log_debug("send_next_segment: " "already sent all %zu bytes, finishing bundle", bytes_sent); ASSERT(inflight->send_complete_); return finish_bundle(inflight); } u_int8_t flags = 0; size_t segment_len; if (bytes_sent == 0) { flags |= BUNDLE_START; } if (params->segment_length_ >= inflight->total_length_ - bytes_sent) { flags |= BUNDLE_END; segment_len = inflight->total_length_ - bytes_sent; } else { segment_len = params->segment_length_; } size_t sdnv_len = SDNV::encoding_len(segment_len); if (sendbuf_.tailbytes() < 1 + sdnv_len) { log_debug("send_next_segment: " "not enough space for segment header [need %zu, have %zu]", 1 + sdnv_len, sendbuf_.tailbytes()); return false; } log_debug("send_next_segment: " "starting %zu byte segment [block byte range %zu..%zu]", segment_len, bytes_sent, bytes_sent + segment_len); u_char* bp = (u_char*)sendbuf_.end(); *bp++ = DATA_SEGMENT | flags; int cc = SDNV::encode(segment_len, bp, sendbuf_.tailbytes() - 1); ASSERT(cc == (int)sdnv_len); bp += sdnv_len; sendbuf_.reserve(1 + sdnv_len + segment_len); sendbuf_.fill(1 + sdnv_len); sendbuf_sequence_delimiters_.push(1 + sdnv_len + segment_len); // may hold many segments log_info("adding pending sequence: %lu to sequence delimiters queue, queue depth: %zu", static_cast<unsigned long>(1 + sdnv_len + segment_len), sendbuf_sequence_delimiters_.size()); send_segment_todo_ = segment_len; // send_data_todo actually does the deed return send_data_todo(inflight); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::send_data_todo(InFlightBundle* inflight) { ASSERT(send_segment_todo_ != 0); // loop since it may take multiple calls to send on the socket // before we can actually drain the todo amount while (send_segment_todo_ != 0 && sendbuf_.tailbytes() != 0) { size_t bytes_sent = inflight->sent_data_.empty() ? 0 : inflight->sent_data_.last() + 1; size_t send_len = std::min(send_segment_todo_, sendbuf_.tailbytes()); Bundle* bundle = inflight->bundle_.object(); BlockInfoVec* blocks = inflight->blocks_; size_t ret = BundleProtocol::produce(bundle, blocks, (u_char*)sendbuf_.end(), bytes_sent, send_len, &inflight->send_complete_); ASSERT(ret == send_len); sendbuf_.fill(send_len); inflight->sent_data_.set(bytes_sent, send_len); log_debug("send_data_todo: " "sent %zu/%zu of current segment from block offset %zu " "(%zu todo), updated sent_data *%p", send_len, send_segment_todo_, bytes_sent, send_segment_todo_ - send_len, &inflight->sent_data_); send_segment_todo_ -= send_len; note_data_sent(); send_data(); // XXX/demmer once send_complete_ is true, we could post an // event to free up space in the queue for more bundles to be // sent down. note that it's possible the bundle isn't really // out on the wire yet, but we don't have any way of knowing // when it gets out of the sendbuf_ and into the kernel (nor // for that matter actually onto the wire), so this is the // best we can do for now. if (contact_broken_) return true; // if test_write_delay is set, then we only send one segment // at a time before bouncing back to poll if (params_->test_write_delay_ != 0) { log_debug("send_data_todo done, returning more to send " "(send_segment_todo_==%zu) since test_write_delay is non-zero", send_segment_todo_); return true; } } return (send_segment_todo_ == 0); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::finish_bundle(InFlightBundle* inflight) { ASSERT(inflight->send_complete_); ASSERT(current_inflight_ == inflight); current_inflight_ = NULL; check_completed(inflight); return true; } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::check_completed(InFlightBundle* inflight) { // we can pop the inflight bundle off of the queue and clean it up // only when both finish_bundle is called (so current_inflight_ no // longer points to the inflight bundle), and after the final ack // for the bundle has been received (determined by looking at // inflight->ack_data_) if (current_inflight_ == inflight) { log_debug("check_completed: bundle %" PRIbid " still waiting for finish_bundle", inflight->bundle_->bundleid()); return; } u_int32_t acked_len = inflight->ack_data_.num_contiguous(); if (acked_len < inflight->total_length_) { log_debug("check_completed: bundle %" PRIbid " only acked %u/%u", inflight->bundle_->bundleid(), acked_len, inflight->total_length_); return; } log_debug("check_completed: bundle %" PRIbid " transmission complete", inflight->bundle_->bundleid()); ASSERT(inflight == inflight_.front()); inflight_.pop_front(); delete inflight; } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::send_keepalive() { // there's no point in putting another byte in the buffer if // there's already data waiting to go out, since the arrival of // that data on the other end will do the same job as the // keepalive byte if (sendbuf_.fullbytes() != 0) { log_debug("send_keepalive: " "send buffer has %zu bytes queued, suppressing keepalive", sendbuf_.fullbytes()); return; } ASSERT(sendbuf_.tailbytes() > 0); // similarly, we must not send a keepalive if send_segment_todo_ is // nonzero, because that would likely insert the keepalive in the middle // of a bundle currently being sent -- verified in check_keepalive ASSERT(send_segment_todo_ == 0); ::gettimeofday(&keepalive_sent_, 0); *(sendbuf_.end()) = KEEPALIVE; sendbuf_.fill(1); // don't note_data_sent() here since keepalive messages shouldn't // be counted for keeping an idle link open sendbuf_sequence_delimiters_.push(1); // may hold many segments log_info("adding pending sequence: %u to sequence delimiters queue, queue depth: %zu", 1, sendbuf_sequence_delimiters_.size()); send_data(); } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::handle_cancel_bundle(Bundle* bundle) { // if the bundle is already actually in flight (i.e. we've already // sent all or part of it), we can't currently cancel it. however, // in the case where it's not already in flight, we can cancel it // and accordingly signal with an event InFlightList::iterator iter; for (iter = inflight_.begin(); iter != inflight_.end(); ++iter) { InFlightBundle* inflight = *iter; if (inflight->bundle_ == bundle) { if (inflight->sent_data_.empty()) { // this bundle might be current_inflight_ but with no // data sent yet; check for this case so we do not have // a dangling pointer if (inflight == current_inflight_) { // we may have sent a segment length without any bundle // data; if so we must send the segment so we can't // cancel the send now if (send_segment_todo_ != 0) { log_debug("handle_cancel_bundle: bundle %" PRIbid " " "already in flight, can't cancel send", bundle->bundleid()); return; } current_inflight_ = NULL; } log_debug("handle_cancel_bundle: " "bundle %" PRIbid " not yet in flight, cancelling send", bundle->bundleid()); inflight_.erase(iter); delete inflight; BundleDaemon::post( new BundleSendCancelledEvent(bundle, contact_->link())); return; } else { log_debug("handle_cancel_bundle: " "bundle %" PRIbid " already in flight, can't cancel send", bundle->bundleid()); return; } } } log_warn("handle_cancel_bundle: " "can't find bundle %" PRIbid " in the in flight list", bundle->bundleid()); } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::handle_poll_timeout() { // Allow the BundleDaemon to call for a close of the connection if // a shutdown is in progress. This must be done to avoid a // deadlock caused by simultaneous poll_timeout and close_contact // activities. // // Before we return, sleep a bit to avoid continuous // handle_poll_timeout calls if (BundleDaemon::shutting_down()) { sleep(1); return; } // avoid performing connection timeout operations on // connections which have not been initiated yet if (!contact_initiated_) { return; } struct timeval now; u_int elapsed, elapsed2; SeqpacketLinkParams* params = dynamic_cast<SeqpacketLinkParams*>(params_); ASSERT(params != NULL); ::gettimeofday(&now, 0); // check that it hasn't been too long since we got some data from // the other side elapsed = TIMEVAL_DIFF_MSEC(now, data_rcvd_); if (elapsed > params->data_timeout_) { log_info("handle_poll_timeout: no data heard for %d msecs " "(keepalive_sent %u.%u, data_rcvd %u.%u, now %u.%u, poll_timeout %d) " "-- closing contact", elapsed, (u_int)keepalive_sent_.tv_sec, (u_int)keepalive_sent_.tv_usec, (u_int)data_rcvd_.tv_sec, (u_int)data_rcvd_.tv_usec, (u_int)now.tv_sec, (u_int)now.tv_usec, poll_timeout_); break_contact(ContactEvent::BROKEN); return; } //make sure the contact still exists ContactManager* cm = BundleDaemon::instance()->contactmgr(); oasys::ScopeLock l(cm->lock(),"SeqpacketConvergenceLayer::Connection::handle_poll_timeout"); if (contact_ == NULL) { return; } // check if the connection has been idle for too long // (on demand links only) if (contact_->link()->type() == Link::ONDEMAND) { u_int idle_close_time = contact_->link()->params().idle_close_time_; elapsed = TIMEVAL_DIFF_MSEC(now, data_rcvd_); elapsed2 = TIMEVAL_DIFF_MSEC(now, data_sent_); if (idle_close_time != 0 && (elapsed > idle_close_time * 1000) && (elapsed2 > idle_close_time * 1000)) { log_info("closing idle connection " "(no data received for %d msecs or sent for %d msecs)", elapsed, elapsed2); break_contact(ContactEvent::IDLE); return; } else { log_debug("connection not idle: recvd %d / sent %d <= timeout %d", elapsed, elapsed2, idle_close_time * 1000); } } // check if it's time for us to send a keepalive (i.e. that we // haven't sent some data or another keepalive in at least the // configured keepalive_interval) check_keepalive(); } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::check_keepalive() { struct timeval now; u_int elapsed, elapsed2; SeqpacketLinkParams* params = dynamic_cast<SeqpacketLinkParams*>(params_); ASSERT(params != NULL); ::gettimeofday(&now, 0); if (params->keepalive_interval_ != 0) { elapsed = TIMEVAL_DIFF_MSEC(now, data_sent_); elapsed2 = TIMEVAL_DIFF_MSEC(now, keepalive_sent_); // XXX/demmer this is bogus -- we should really adjust // poll_timeout to take into account the next time we should // send a keepalive // // give a 500ms fudge to the keepalive interval to make sure // we send it when we should if (std::min(elapsed, elapsed2) > ((params->keepalive_interval_ * 1000) - 500)) { // it's possible that the link is blocked while in the // middle of a segment, triggering a poll timeout, so make // sure not to send a keepalive in this case if (send_segment_todo_ != 0) { log_debug("not issuing keepalive in the middle of a segment"); return; } send_keepalive(); } } } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::process_data() { if (recvbuf_.fullbytes() == 0) { return; } log_debug("processing up to %zu bytes from receive buffer", recvbuf_.fullbytes()); // all data (keepalives included) should be noted since the last // reception time is used to determine when to generate new // keepalives note_data_rcvd(); // the first thing we need to do is handle the contact initiation // sequence, i.e. the contact header and the announce bundle. we // know we need to do this if we haven't yet called contact_up() if (! contact_up_) { handle_contact_initiation(); return; } // if a data segment is bigger than the receive buffer. when // processing a data segment, we mark the unread amount in the // recv_segment_todo__ field, so if that's not zero, we need to // drain it, then fall through to handle the rest of the buffer if (recv_segment_todo_ != 0) { bool ok = handle_data_todo(); if (!ok) { return; } } // now, drain cl messages from the receive buffer. we peek at the // first byte and dispatch to the correct handler routine // depending on the type of the CL message. we don't consume the // byte yet since there's a possibility that we need to read more // from the remote side to handle the whole message while (recvbuf_.fullbytes() != 0) { if (contact_broken_) return; u_int8_t type = *recvbuf_.start() & 0xf0; u_int8_t flags = *recvbuf_.start() & 0x0f; log_debug("recvbuf has %zu full bytes, dispatching to handler routine", recvbuf_.fullbytes()); bool ok; switch (type) { case DATA_SEGMENT: ok = handle_data_segment(flags); break; case ACK_SEGMENT: ok = handle_ack_segment(flags); break; case REFUSE_BUNDLE: ok = handle_refuse_bundle(flags); break; case KEEPALIVE: ok = handle_keepalive(flags); break; case SHUTDOWN: ok = handle_shutdown(flags); break; default: log_err("invalid CL message type code 0x%x (flags 0x%x)", type >> 4, flags); break_contact(ContactEvent::CL_ERROR); return; } // if there's not enough data in the buffer to handle the // message, make sure there's space to receive more if (! ok) { if (recvbuf_.fullbytes() == recvbuf_.size()) { log_warn("process_data: " "%zu byte recv buffer full but too small for msg %u... " "doubling buffer size", recvbuf_.size(), type); recvbuf_.reserve(recvbuf_.size() * 2); } else if (recvbuf_.tailbytes() == 0) { // force it to move the full bytes up to the front recvbuf_.reserve(recvbuf_.size() - recvbuf_.fullbytes()); ASSERT(recvbuf_.tailbytes() != 0); } return; } } } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::note_data_rcvd() { log_debug("noting data_rcvd"); ::gettimeofday(&data_rcvd_, 0); } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::note_data_sent() { log_debug("noting data_sent"); ::gettimeofday(&data_sent_, 0); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::handle_data_segment(u_int8_t flags) { SeqpacketLinkParams* params = dynamic_cast<SeqpacketLinkParams*>(params_); ASSERT(params != NULL); IncomingBundle* incoming = NULL; if (flags & BUNDLE_START) { // make sure we're done with the last bundle if we got a new // BUNDLE_START flag... note that we need to be careful in // case there's not enough data to decode the length of the // segment, since we'll be called again bool create_new_incoming = true; if (!incoming_.empty()) { incoming = incoming_.back(); if (incoming->rcvd_data_.empty() && incoming->ack_data_.empty()) { log_debug("found empty incoming bundle for BUNDLE_START"); create_new_incoming = false; } else if (incoming->total_length_ == 0) { log_err("protocol error: " "got BUNDLE_START before bundle completed"); break_contact(ContactEvent::CL_ERROR); return false; } } if (create_new_incoming) { log_debug("got BUNDLE_START segment, creating new IncomingBundle"); IncomingBundle* incoming = new IncomingBundle(new Bundle()); incoming_.push_back(incoming); ack_window_todo_ = params->ack_window_; // start counting towards the ack window now } ack_window_todo_ = params->ack_window_; // start counting towards the ack window now } else if (incoming_.empty()) { log_err("protocol error: " "first data segment doesn't have BUNDLE_START flag set"); break_contact(ContactEvent::CL_ERROR); return false; } // Note that there may be more than one incoming bundle on the // IncomingList, but it's the one at the back that we're reading // in data for. Others are waiting for acks to be sent. incoming = incoming_.back(); u_char* bp = (u_char*)recvbuf_.start(); // Decode the segment length and then call handle_data_todo u_int32_t segment_len; int sdnv_len = SDNV::decode(bp + 1, recvbuf_.fullbytes() - 1, &segment_len); if (sdnv_len < 0) { log_debug("handle_data_segment: " "too few bytes in buffer for sdnv (%zu)", recvbuf_.fullbytes()); return false; } recvbuf_.consume(1 + sdnv_len); if (segment_len == 0) { log_err("protocol error -- zero length segment"); break_contact(ContactEvent::CL_ERROR); return false; } size_t segment_offset = incoming->rcvd_data_.num_contiguous(); log_debug("handle_data_segment: " "got segment of length %u at offset %zu ", segment_len, segment_offset); incoming->ack_data_.set(segment_offset + segment_len - 1); log_debug("handle_data_segment: " "updated ack_data (segment_offset %zu) *%p ack_data *%p", segment_offset, &incoming->rcvd_data_, &incoming->ack_data_); // if this is the last segment for the bundle, we calculate and // store the total length in the IncomingBundle structure so // send_pending_acks knows when we're done. if (flags & BUNDLE_END) { incoming->total_length_ = incoming->rcvd_data_.num_contiguous() + segment_len; log_debug("got BUNDLE_END: total length %u", incoming->total_length_); ack_window_todo_ = 0; // trigger an ack now } else { ASSERT(0 != ack_window_todo_); ack_window_todo_--; // count this towards the window } recv_segment_todo_ = segment_len; return handle_data_todo(); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::handle_data_todo() { // We shouldn't get ourselves here unless there's something // incoming and there's something left to read ASSERT(!incoming_.empty()); ASSERT(recv_segment_todo_ != 0); // Note that there may be more than one incoming bundle on the // IncomingList. There's always only one (at the back) that we're // reading in data for, the rest are waiting for acks to go out IncomingBundle* incoming = incoming_.back(); size_t rcvd_offset = incoming->rcvd_data_.num_contiguous(); size_t rcvd_len = recvbuf_.fullbytes(); size_t chunk_len = std::min(rcvd_len, recv_segment_todo_); if (rcvd_len == 0) { return false; // nothing to do } log_debug("handle_data_todo: " "reading todo segment %zu/%zu at offset %zu", chunk_len, recv_segment_todo_, rcvd_offset); bool last; int cc = BundleProtocol::consume(incoming->bundle_.object(), (u_char*)recvbuf_.start(), chunk_len, &last); if (cc < 0) { log_err("protocol error parsing bundle data segment"); break_contact(ContactEvent::CL_ERROR); return false; } ASSERT(cc == (int)chunk_len); recv_segment_todo_ -= chunk_len; recvbuf_.consume(chunk_len); incoming->rcvd_data_.set(rcvd_offset, chunk_len); log_debug("handle_data_todo: " "updated recv_data (rcvd_offset %zu) *%p ack_data *%p", rcvd_offset, &incoming->rcvd_data_, &incoming->ack_data_); if (recv_segment_todo_ == 0) { check_completed(incoming); return true; // completed segment } return false; } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::check_completed(IncomingBundle* incoming) { u_int32_t rcvd_len = incoming->rcvd_data_.num_contiguous(); // if we don't know the total length yet, we haven't seen the // BUNDLE_END message if (incoming->total_length_ == 0) { return; } u_int32_t formatted_len = BundleProtocol::total_length(&incoming->bundle_->recv_blocks()); log_debug("check_completed: rcvd %u / %u (formatted length %u)", rcvd_len, incoming->total_length_, formatted_len); if (rcvd_len < incoming->total_length_) { return; } if (rcvd_len > incoming->total_length_) { log_err("protocol error: received too much data -- " "got %u, total length %u", rcvd_len, incoming->total_length_); // we pretend that we got nothing so the cleanup code in // ConnectionCL::close_contact doesn't try to post a received // event for the bundle protocol_err: incoming->rcvd_data_.clear(); break_contact(ContactEvent::CL_ERROR); return; } // validate that the total length as conveyed by the convergence // layer matches the length according to the bundle protocol if (incoming->total_length_ != formatted_len) { log_err("protocol error: CL total length %u " "doesn't match bundle protocol total %u", incoming->total_length_, formatted_len); goto protocol_err; } BundleDaemon::post( new BundleReceivedEvent(incoming->bundle_.object(), EVENTSRC_PEER, incoming->total_length_, contact_->link()->remote_eid(), contact_->link().object())); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::handle_ack_segment(u_int8_t flags) { (void)flags; u_char* bp = (u_char*)recvbuf_.start(); u_int32_t acked_len; int sdnv_len = SDNV::decode(bp + 1, recvbuf_.fullbytes() - 1, &acked_len); if (sdnv_len < 0) { log_debug("handle_ack_segment: too few bytes for sdnv (%zu)", recvbuf_.fullbytes()); return false; } recvbuf_.consume(1 + sdnv_len); if (inflight_.empty()) { log_err("protocol error: got ack segment with no inflight bundle"); break_contact(ContactEvent::CL_ERROR); return false; } InFlightBundle* inflight = inflight_.front(); size_t ack_begin; DataBitmap::iterator i = inflight->ack_data_.begin(); if (i == inflight->ack_data_.end()) { ack_begin = 0; } else { i.skip_contiguous(); ack_begin = *i + 1; } if (acked_len < ack_begin) { log_err("protocol error: got ack for length %u but already acked up to %zu", acked_len, ack_begin); // DML - Hack - not sure if commenting this out is a good idea, we'll see ... //break_contact(ContactEvent::CL_ERROR); return false; } inflight->ack_data_.set(0, acked_len); // now check if this was the last ack for the bundle, in which // case we can pop it off the list and post a // BundleTransmittedEvent if (acked_len == inflight->total_length_) { log_debug("handle_ack_segment: got final ack for %zu byte range -- " "acked_len %u, ack_data *%p", (size_t)acked_len - ack_begin, acked_len, &inflight->ack_data_); inflight->transmit_event_posted_ = true; BundleDaemon::post( new BundleTransmittedEvent(inflight->bundle_.object(), contact_, contact_->link(), inflight->sent_data_.num_contiguous(), inflight->ack_data_.num_contiguous())); // might delete inflight check_completed(inflight); } else { log_debug("handle_ack_segment: " "got acked_len %u (%zu byte range) -- ack_data *%p", acked_len, (size_t)acked_len - ack_begin, &inflight->ack_data_); } return true; } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::handle_refuse_bundle(u_int8_t flags) { (void)flags; log_debug("got refuse_bundle message"); log_err("REFUSE_BUNDLE not implemented"); break_contact(ContactEvent::CL_ERROR); return true; } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::handle_keepalive(u_int8_t flags) { (void)flags; log_debug("got keepalive message"); recvbuf_.consume(1); return true; } //---------------------------------------------------------------------- void SeqpacketConvergenceLayer::Connection::break_contact(ContactEvent::reason_t reason) { // it's possible that we can end up calling break_contact multiple // times, if for example we have an error when sending out the // shutdown message below. we simply ignore the multiple calls if (breaking_contact_) { return; } breaking_contact_ = true; // we can only send a shutdown byte if we're not in the middle // of sending a segment, otherwise the shutdown byte could be // interpreted as a part of the payload bool send_shutdown = false; shutdown_reason_t shutdown_reason = SHUTDOWN_NO_REASON; switch (reason) { case ContactEvent::USER: // if the user is closing this link, we say that we're busy send_shutdown = true; shutdown_reason = SHUTDOWN_BUSY; break; case ContactEvent::IDLE: // if we're idle, indicate as such send_shutdown = true; shutdown_reason = SHUTDOWN_IDLE_TIMEOUT; break; case ContactEvent::SHUTDOWN: // if the other side shuts down first, we send the // corresponding SHUTDOWN byte for a clean handshake, but // don't give any more reason send_shutdown = true; break; case ContactEvent::BROKEN: case ContactEvent::CL_ERROR: // no shutdown send_shutdown = false; break; case ContactEvent::CL_VERSION: // version mismatch send_shutdown = true; shutdown_reason = SHUTDOWN_VERSION_MISMATCH; break; case ContactEvent::INVALID: case ContactEvent::NO_INFO: case ContactEvent::RECONNECT: case ContactEvent::TIMEOUT: case ContactEvent::DISCOVERY: NOTREACHED; break; } // of course, we can't send anything if we were interrupted in the // middle of sending a block. // // XXX/demmer if we receive a SHUTDOWN byte from the other side, // we don't have any way of continuing to transmit our own blocks // and then shut down afterwards if (send_shutdown && sendbuf_.fullbytes() == 0 && send_segment_todo_ == 0) { log_debug("break_contact: sending shutdown"); char typecode = SHUTDOWN; if (shutdown_reason != SHUTDOWN_NO_REASON) { typecode |= SHUTDOWN_HAS_REASON; } // XXX/demmer should we send a reconnect delay?? *sendbuf_.end() = typecode; sendbuf_.fill(1); int seqsize = 1; if (shutdown_reason != SHUTDOWN_NO_REASON) { *sendbuf_.end() = shutdown_reason; sendbuf_.fill(1); seqsize=2; } sendbuf_sequence_delimiters_.push(seqsize); // may hold many segments send_data(); } CLConnection::break_contact(reason); } //---------------------------------------------------------------------- bool SeqpacketConvergenceLayer::Connection::handle_shutdown(u_int8_t flags) { log_debug("got SHUTDOWN byte"); size_t shutdown_len = 1; if (flags & SHUTDOWN_HAS_REASON) { shutdown_len += 1; } if (flags & SHUTDOWN_HAS_DELAY) { shutdown_len += 2; } if (recvbuf_.fullbytes() < shutdown_len) { // rare case where there's not enough data in the buffer // to handle the shutdown message data log_debug("got %zu/%zu bytes for shutdown data... waiting for more", recvbuf_.fullbytes(), shutdown_len); return false; } // now handle the message, first skipping the typecode byte recvbuf_.consume(1); shutdown_reason_t reason = SHUTDOWN_NO_REASON; if (flags & SHUTDOWN_HAS_REASON) { switch ((unsigned char) *recvbuf_.start()) { case SHUTDOWN_NO_REASON: reason = SHUTDOWN_NO_REASON; break; case SHUTDOWN_IDLE_TIMEOUT: reason = SHUTDOWN_IDLE_TIMEOUT; break; case SHUTDOWN_VERSION_MISMATCH: reason = SHUTDOWN_VERSION_MISMATCH; break; case SHUTDOWN_BUSY: reason = SHUTDOWN_BUSY; break; default: log_err("invalid shutdown reason code 0x%x", *recvbuf_.start()); } recvbuf_.consume(1); } u_int16_t delay = 0; if (flags & SHUTDOWN_HAS_DELAY) { memcpy(&delay, recvbuf_.start(), 2); delay = ntohs(delay); recvbuf_.consume(2); } log_info("got SHUTDOWN (%s) [reconnect delay %u]", shutdown_reason_to_str(reason), delay); break_contact(ContactEvent::SHUTDOWN); return false; } } // namespace dtn
35.172644
111
0.583954
[ "object" ]
d52e3c5dad7634e278a30490f1a5ae564d01a3bb
7,363
cpp
C++
src/eeg/txt2nii.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/eeg/txt2nii.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
src/eeg/txt2nii.cpp
wmotte/toolkid
2a8f82e1492c9efccde9a4935ce3019df1c68cde
[ "MIT" ]
null
null
null
/* * copyinfo.cpp * * Created on: Jul 27, 2009 * Author: wim */ #include "itkImageIOFactory.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImage.h" #include "tkdCmdParser.h" #include <iostream> #include <fstream> #include <string> #include <boost/shared_ptr.hpp> #include <boost/regex.hpp> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> /** * Convert SignallExpress Voltage.txt ascii output (EEG monitoring; National Instruments). * To nii.gz Image. */ class Txt2Nii { protected: /** * Replace all sub-strings. */ inline std::string replaceAll( const std::string& s, const std::string& f, const std::string& r ) { if ( s.empty() || f.empty() || f == r || s.find( f ) == std::string::npos ) { return s; } std::ostringstream build_it; size_t i = 0; for ( size_t pos; ( pos = s.find( f, i ) ) != std::string::npos; ) { build_it.write( &s[i], pos - i ); build_it << r; i = pos + f.size(); } if ( i != s.size() ) { build_it.write( &s[i], s.size() - i ); } return build_it.str(); } public: /** * Run app. */ void run( const std::string& input, const std::string& output, float seconds ) { process( input, output, seconds ); } /** * New. */ std::vector< std::vector< double > > getChannels2( const std::string& inputFileName ) { typedef boost::tokenizer< boost::char_separator< char > > TokenizerType; std::vector< std::vector< double > > data; std::ifstream in; in.open( inputFileName.c_str() ); if ( !in ) { std::cerr << "Unable to open: " << inputFileName; exit( EXIT_FAILURE ); } std::string line; // header ... boost::regex dataTag( "data:" ); boost::smatch m; boost::sregex_token_iterator end; if( UseRowNames() ) // bet line ... while ( getline( in, line ) ) { if ( boost::regex_search( line, m, dataTag ) ) { break; } } // continue with data ... while ( getline( in, line ) ) { // replace comma's with dots... boost::regex commaDotTag( ",", boost::regex_constants::icase | boost::regex_constants::perl ); std::string newLine = boost::regex_replace( line, commaDotTag, "." ); try { std::vector< double > line_data; TokenizerType tok( newLine, boost::char_separator< char >( "\t" ) ); for ( TokenizerType::iterator id = tok.begin(); id != tok.end(); ++id ) { double value = boost::lexical_cast< double >( *id ); line_data.push_back( value ); } data.push_back( line_data ); } catch ( boost::bad_lexical_cast& e ) { // If parsing fails, try ss method ... return getChannels( inputFileName ); } } return data; } /** * Get channels as vectors from given ascii-file. * * First read header and determine number of channels. */ std::vector< std::vector< double > > getChannels( const std::string& inputFileName ) { std::ifstream in; in.open( inputFileName.c_str() ); if ( !in ) { std::cerr << "Unable to open: " << inputFileName; exit( EXIT_FAILURE ); } // first read header, which should end with "data: "... bool inHeader = true; while ( !in.eof() && in.good() && inHeader ) { std::string line; std::getline( in, line ); int pos = line.find( "data:" ); if ( pos == 0 ) { inHeader = false; break; } } std::vector< std::vector< double > > data; while ( !in.eof() && in.good() ) { std::string line; std::getline( in, line ); // replace komma's by dots... std::string goodLine = replaceAll( line, ",", "." ); std::stringstream ss; ss.precision( 6 ); ss << goodLine; std::vector< double > line_data; bool valid = false; while ( !ss.eof() && ss.good() ) { double x; ss >> x; if ( ss.good() ) { line_data.push_back( x ); valid = true; } } if ( valid ) { data.push_back( line_data ); } } in.close(); return data; } /** * Write 4D image with each voxel a channel over time... */ void process( const std::string& inputFileName, const std::string& outputFileName, const float seconds ) { if ( seconds > 30 ) { std::cerr << "Series are restricted to < 30 seconds (NIFTI-header restriction)!" << std::endl; exit( EXIT_FAILURE ); } unsigned int milliseconds = seconds * 1000; const unsigned int Dimension = 4; typedef double PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileWriter< ImageType > WriterType; ImageType::Pointer image = ImageType::New(); //std::vector< std::vector< double > > channels = getChannels( inputFileName ); std::vector< std::vector< double > > channels = getChannels2( inputFileName ); if ( !channels.empty() ) { // set image size and allocate data... ImageType::RegionType region; ImageType::SizeType size; unsigned int numberOfChannels = channels[0].size(); unsigned int totalSize = channels.size(); unsigned int timeSize = totalSize; size[0] = numberOfChannels; size[1] = ( channels.size() / milliseconds ) + 1; size[2] = 1; size[3] = milliseconds; region.SetSize( size ); image -> SetRegions( region ); image -> Allocate(); image -> FillBuffer( 0 ); ImageType::IndexType index; // for all channels... for ( unsigned int channelIndex = 0; channelIndex < numberOfChannels; channelIndex++ ) { // Cut data in blocks of 30 sec... unsigned int blockCount = -1; // each channel... for ( unsigned int timeIndex = 0; timeIndex < timeSize; timeIndex++ ) { // switch to new voxel... if ( ( timeIndex % milliseconds ) == 0 ) { blockCount++; } index[0] = channelIndex; index[1] = blockCount; index[2] = 0; index[3] = ( timeIndex - ( blockCount * milliseconds ) ); std::vector< double > points = channels[timeIndex]; double pixelValue = points[channelIndex]; image -> SetPixel( index, pixelValue ); } } WriterType::Pointer writer = WriterType::New(); writer -> SetFileName( outputFileName ); writer -> SetInput( image ); try { writer -> Update(); } catch ( itk::ExceptionObject & exp ) { std::cerr << "ERROR - could not write: " << inputFileName << std::endl; exit( EXIT_FAILURE ); } } else { std::cerr << "ERROR - No channels in: " << inputFileName << std::endl; exit( EXIT_FAILURE ); } } }; /** * Main. */ int main( int argc, char * argv[] ) { std::string input; std::string output; float seconds = 30.0; tkd::CmdParser parser( argv[0], "EEG - Convert 'SignallExpress' ascii-file to NIFTI 4D Image" ); parser.AddArgument( input, "input" ) -> AddAlias( "i" ) -> SetInput( "<string>" ) -> SetDescription( "Input file (ascii)" ) -> SetRequired( true ) -> SetMinMax( 1, 1 ); parser.AddArgument( output, "output" ) -> AddAlias( "o" ) -> SetInput( "<string>" ) -> SetDescription( "Output file (image)" ) -> SetRequired( true ) -> SetMinMax( 1, 1 ); parser.AddArgument( seconds, "seconds" ) -> AddAlias( "s" ) -> SetInput( "<float>" ) -> SetDescription( "Seconds per time-series (default 30)" ) -> SetRequired( false ) -> SetMinMax( 1, 1 ); if ( !parser.Parse( argc, argv ) ) { parser.PrintUsage( std::cout ); return EXIT_FAILURE; } Txt2Nii txt2nii = Txt2Nii(); txt2nii.run( input, output, seconds ); }
22.795666
143
0.605052
[ "vector" ]
d52fe52d0dfe77b94377bd14056717733843a545
3,285
hpp
C++
soccer/vision/robot/KalmanRobot.hpp
AniruddhaG123/robocup-software
0eb3b3957428894f2f39341594800be803665f44
[ "Apache-2.0" ]
1
2019-09-24T22:59:25.000Z
2019-09-24T22:59:25.000Z
soccer/vision/robot/KalmanRobot.hpp
ananth-kumar01/robocup-software
4043a7f9590d02f617d8e9a762697e4aaa27f1a6
[ "Apache-2.0" ]
null
null
null
soccer/vision/robot/KalmanRobot.hpp
ananth-kumar01/robocup-software
4043a7f9590d02f617d8e9a762697e4aaa27f1a6
[ "Apache-2.0" ]
null
null
null
#pragma once #include <boost/circular_buffer.hpp> #include <Geometry2d/Point.hpp> #include <Utils.hpp> #include <Configuration.hpp> #include "vision/robot/CameraRobot.hpp" #include "vision/filter/KalmanFilter3D.hpp" class WorldRobot; /** * Filtered robot estimation for a single camera */ class KalmanRobot { public: /** * Checks previousWorldRobot to see if it's valid * * @param cameraID ID of the camera this filter is applied to * @param creationTime Time this filter was created * @param initMeasurement Initial robot measurement * @param previousWorldRobot World robot from last frame (or invalid world robot) */ KalmanRobot(unsigned int cameraID, RJ::Time creationTime, CameraRobot initMeasurement, const WorldRobot& previousWorldRobot); /** * Predicts one time step forward * * @param currentTime Current time of the prediction step */ void predict(RJ::Time currentTime); /** * Predicts one time step forward then triangulates toward the measurement * * @param currentTime Current time of the prediction/update step * @param updateRobot Robot measurement that we are using as feedback */ void predictAndUpdate(RJ::Time currentTime, CameraRobot updateRobot); /** * Returns true when the filter hasn't been updated in a while and should be deleted */ bool isUnhealthy() const; /** * @return The camera id this belongs to */ unsigned int getCameraID() const; /** * @return This robot's id */ int getRobotID() const; /** * @return How healthy this filter is. AKA How often it's been updated */ int getHealth() const; /** * @return Best estimate of the linear position of the robot */ Geometry2d::Point getPos() const; /** * @return Best estimate of the heading. Not bounded */ double getTheta() const; /** * @return Best estimate of the linear velocity of the robot */ Geometry2d::Point getVel() const; /** * @return Best estimate of the angular velocity */ double getOmega() const; /** * @return Covariance in X and Y linear direction of the position of the robot */ Geometry2d::Point getPosCov() const; /** * @return Covariance of theta of the robot */ double getThetaCov() const; /** * @return Covariance in X and Y linear direction of the velocity of the robot */ Geometry2d::Point getVelCov() const; /** * @return Covariance of omega of the robot */ double getOmegaCov() const; /** * @return List of previous camera robot measurements for kick detection */ const boost::circular_buffer<CameraRobot>& getPrevMeasurements() const; static void createConfiguration(Configuration* cfg); private: RJ::Time lastUpdateTime; RJ::Time lastPredictTime; boost::circular_buffer<CameraRobot> previousMeasurements; KalmanFilter3D filter; double previousTheta; int unwrapThetaCtr; int health; int robotID; unsigned int cameraID; // Max number of seconds without a measurement before the object // is deleted static ConfigDouble* max_time_outside_vision; };
25.076336
88
0.663014
[ "object" ]
d53324ea8d71c1cb914a56cd23d3a00c91cd57b0
521
cpp
C++
Extern/include/ThorsSerializer/test/HomeBrewTest.cpp
rafalohaki/C4USMultiHack-Metin2
7aa4f322425df9f65e6cb2ad4fd33dc3288f95de
[ "Apache-2.0" ]
272
2015-02-03T19:30:37.000Z
2022-03-21T10:23:27.000Z
Extern/include/ThorsSerializer/test/HomeBrewTest.cpp
rafalohaki/C4USMultiHack-Metin2
7aa4f322425df9f65e6cb2ad4fd33dc3288f95de
[ "Apache-2.0" ]
63
2015-06-12T16:51:27.000Z
2022-02-17T15:21:01.000Z
Extern/include/ThorsSerializer/test/HomeBrewTest.cpp
rafalohaki/C4USMultiHack-Metin2
7aa4f322425df9f65e6cb2ad4fd33dc3288f95de
[ "Apache-2.0" ]
70
2015-01-15T22:39:28.000Z
2022-03-01T09:32:02.000Z
#include "SerializeConfig.h" #include "gtest/gtest.h" #include "HomeBrewTest.h" #include <sstream> #include <iostream> #include <string> TEST(HomeBrewTest, homeBrewTest) { using ThorsAnvil::Serialize::jsonImporter; using ThorsAnvil::Serialize::jsonExporter; std::stringstream inputData(R"({"key":"XYZ","code":37373})"); HomeBrewBlock object; inputData >> jsonImporter(object); if (object.key != "XYZ" || object.code != 37373) { std::cerr << "Fail"; } std::cerr << "OK"; }
22.652174
67
0.648752
[ "object" ]
d5338f6842f18dcfc89e183942895d33aaa8273d
306
cpp
C++
Sid's Levels/Level - 3/Dynamic Programming/Kadane Algo.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 3/Dynamic Programming/Kadane Algo.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 3/Dynamic Programming/Kadane Algo.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: int maxSubArray(vector<int>& nums) { int sum = nums[0]; int maxSum = nums[0]; for(int i = 1; i < nums.size(); i++) { sum = max(nums[i], sum + nums[i]); maxSum = max(maxSum, sum); } return maxSum; } };
21.857143
46
0.45098
[ "vector" ]
d53395ff19c0af205844e9068052a08b2064385e
15,176
cpp
C++
c++/src/algo/blast/api/objmgr_query_data.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/algo/blast/api/objmgr_query_data.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/algo/blast/api/objmgr_query_data.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef SKIP_DOXYGEN_PROCESSING static char const rcsid[] = "$Id: objmgr_query_data.cpp 382127 2012-12-03 19:47:11Z rafanovi $"; #endif /* SKIP_DOXYGEN_PROCESSING */ /* =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Christiam Camacho, Kevin Bealer * */ /** @file objmgr_query_data.cpp * NOTE: This file contains work in progress and the APIs are likely to change, * please do not rely on them until this notice is removed. */ #include <ncbi_pch.hpp> #include <corelib/ncbi_limits.hpp> #include <algo/blast/api/objmgr_query_data.hpp> #include <algo/blast/api/blast_options.hpp> #include <objmgr/util/sequence.hpp> #include "blast_setup.hpp" #include "blast_objmgr_priv.hpp" #include <algo/blast/api/seqinfosrc_seqdb.hpp> #include "blast_seqalign.hpp" /** @addtogroup AlgoBlast * * @{ */ BEGIN_NCBI_SCOPE USING_SCOPE(objects); BEGIN_SCOPE(blast) ///////////////////////////////////////////////////////////////////////////// /// Produces a BioseqSet from a CBlastQueryVector /// @param queries queries as a CBlastQueryVector /// @retval CRef to BioseqSet static CRef<CBioseq_set> s_QueryVectorToBioseqSet(const CBlastQueryVector & queries) { list< CRef<CSeq_entry> > se_list; for(size_t i = 0; i < queries.Size(); i++) { CScope & scope = *queries.GetScope(i); const CBioseq * cbs = scope.GetBioseqHandle(*queries.GetQuerySeqLoc(i)).GetBioseqCore(); CRef<CBioseq> bs(const_cast<CBioseq*>(cbs)); CRef<CSeq_entry> se(new CSeq_entry); se->SetSeq(*bs); se_list.push_back(se); } CRef<CBioseq_set> rv; if ( !se_list.empty() ) { rv.Reset(new CBioseq_set); rv->SetSeq_set().swap(se_list); } return rv; } /// Produces a BioseqSet from a TSeqLocVector /// @param queries queries as a TSeqLocVector /// @retval Cref to BioseqSet static CRef<CBioseq_set> s_TSeqLocVectorToBioseqSet(const TSeqLocVector* queries) { list< CRef<CSeq_entry> > se_list; ITERATE(TSeqLocVector, query, *queries) { if ( !query->seqloc->GetId() ) { continue; } const CBioseq * cbs = query->scope->GetBioseqHandle(*query->seqloc->GetId()).GetBioseqCore(); CRef<CSeq_entry> se(new CSeq_entry); se->SetSeq(*const_cast<CBioseq*>(cbs)); se_list.push_back(se); } CRef<CBioseq_set> rv(new CBioseq_set); rv->SetSeq_set().swap(se_list); return rv; } /// Produces a vector of SeqLocs from a TSeqLocVector /// @param queries queries as a TSeqLocVector /// @retval vector of SeqLocs. static IRemoteQueryData::TSeqLocs s_TSeqLocVectorToTSeqLocs(const TSeqLocVector* queries) { IRemoteQueryData::TSeqLocs retval; ITERATE(TSeqLocVector, query, *queries) { CRef<CSeq_loc> sl(const_cast<CSeq_loc *>(&* query->seqloc)); retval.push_back(sl); } return retval; } /// Produces a vector of SeqLocs from a CBlastQueryVector /// @param queries queries as a CBlastQueryVector /// @retval vector of SeqLocs. static IRemoteQueryData::TSeqLocs s_QueryVectorToTSeqLocs(const CBlastQueryVector & queries) { IRemoteQueryData::TSeqLocs retval; for(size_t i = 0; i < queries.Size(); i++) { CSeq_loc * slp = const_cast<CSeq_loc *>(&* queries.GetQuerySeqLoc(i)); retval.push_back(CRef<CSeq_loc>(slp)); } return retval; } ///////////////////////////////////////////////////////////////////////////// // // CObjMgr_LocalQueryData // ///////////////////////////////////////////////////////////////////////////// /// Provides access (not ownership) to the C structures used to configure local /// BLAST search class implementations. class CObjMgr_LocalQueryData : public ILocalQueryData { public: /// Ctor that takes a vector of SSeqLocs /// @param queries queries as a vector of SSeqLoc [in] /// @param options Blast options [in] CObjMgr_LocalQueryData(TSeqLocVector* queries, const CBlastOptions* options); /// Ctor that takes a CBlastQueryVector (preferred over TSeqLocVector). /// @param queries queries as a CBlastQueryVector [in] /// @param options Blast options [in] CObjMgr_LocalQueryData(CBlastQueryVector & queries, const CBlastOptions* options); virtual BLAST_SequenceBlk* GetSequenceBlk(); virtual BlastQueryInfo* GetQueryInfo(); /// Get the number of queries. virtual size_t GetNumQueries(); /// Get the Seq_loc for the sequence indicated by index. virtual CConstRef<CSeq_loc> GetSeq_loc(size_t index); /// Get the length of the sequence indicated by index. virtual size_t GetSeqLength(size_t index); private: const TSeqLocVector* m_Queries; ///< Adaptee in adapter design pattern CRef<CBlastQueryVector> m_QueryVector; const CBlastOptions* m_Options; AutoPtr<IBlastQuerySource> m_QuerySource; }; CObjMgr_LocalQueryData::CObjMgr_LocalQueryData(TSeqLocVector * queries, const CBlastOptions * opts) : m_Queries(queries), m_Options(opts) { m_QuerySource.reset(new CBlastQuerySourceOM(*queries, opts)); } CObjMgr_LocalQueryData::CObjMgr_LocalQueryData(CBlastQueryVector & qv, const CBlastOptions * opts) : m_Queries(NULL), m_QueryVector(& qv), m_Options(opts) { m_QuerySource.reset(new CBlastQuerySourceOM(qv, opts)); } BLAST_SequenceBlk* CObjMgr_LocalQueryData::GetSequenceBlk() { if (m_SeqBlk.Get() == NULL) { if (m_Queries || m_QueryVector.NotEmpty()) { m_SeqBlk.Reset(SafeSetupQueries(*m_QuerySource, m_Options, GetQueryInfo(), m_Messages)); } else { abort(); } } return m_SeqBlk.Get(); } BlastQueryInfo* CObjMgr_LocalQueryData::GetQueryInfo() { if (m_QueryInfo.Get() == NULL) { if (m_QuerySource) { m_QueryInfo.Reset(SafeSetupQueryInfo(*m_QuerySource, m_Options)); } else { abort(); } } return m_QueryInfo.Get(); } size_t CObjMgr_LocalQueryData::GetNumQueries() { size_t retval = m_QuerySource->Size(); _ASSERT(retval == (size_t)GetQueryInfo()->num_queries); return retval; } CConstRef<CSeq_loc> CObjMgr_LocalQueryData::GetSeq_loc(size_t index) { return m_QuerySource->GetSeqLoc(index); } size_t CObjMgr_LocalQueryData::GetSeqLength(size_t index) { return m_QuerySource->GetLength(index); } ///////////////////////////////////////////////////////////////////////////// // // CObjMgr_RemoteQueryData // ///////////////////////////////////////////////////////////////////////////// class CObjMgr_RemoteQueryData : public IRemoteQueryData { public: /// Construct query data from a TSeqLocVector. /// @param queries Queries expressed as a TSeqLocVector. CObjMgr_RemoteQueryData(const TSeqLocVector* queries); /// Construct query data from a CBlastQueryVector. /// @param queries Queries expressed as a CBlastQueryVector. CObjMgr_RemoteQueryData(CBlastQueryVector & queries); /// Accessor for the CBioseq_set. virtual CRef<objects::CBioseq_set> GetBioseqSet(); /// Accessor for the TSeqLocs. virtual TSeqLocs GetSeqLocs(); private: /// Queries, if input representation is TSeqLocVector, or NULL. const TSeqLocVector* m_Queries; /// Queries, if input representation is a CBlastQueryVector, or NULL. const CRef<CBlastQueryVector> m_QueryVector; }; CObjMgr_RemoteQueryData::CObjMgr_RemoteQueryData(const TSeqLocVector* queries) : m_Queries(queries) {} CObjMgr_RemoteQueryData::CObjMgr_RemoteQueryData(CBlastQueryVector & qv) : m_QueryVector(& qv) {} CRef<CBioseq_set> CObjMgr_RemoteQueryData::GetBioseqSet() { if (m_Bioseqs.Empty()) { if (m_QueryVector.NotEmpty()) { m_Bioseqs.Reset(s_QueryVectorToBioseqSet(*m_QueryVector)); } else if (m_Queries) { m_Bioseqs.Reset(s_TSeqLocVectorToBioseqSet(m_Queries)); } else { abort(); } } return m_Bioseqs; } IRemoteQueryData::TSeqLocs CObjMgr_RemoteQueryData::GetSeqLocs() { if (m_SeqLocs.empty()) { if (m_QueryVector.NotEmpty()) { m_SeqLocs = s_QueryVectorToTSeqLocs(*m_QueryVector); } else if (m_Queries) { m_SeqLocs = s_TSeqLocVectorToTSeqLocs(m_Queries); } else { abort(); } } return m_SeqLocs; } ///////////////////////////////////////////////////////////////////////////// // // CObjMgr_QueryFactory // ///////////////////////////////////////////////////////////////////////////// CObjMgr_QueryFactory::CObjMgr_QueryFactory(TSeqLocVector& queries) { if (queries.empty()) { NCBI_THROW(CBlastException, eInvalidArgument, "Empty TSeqLocVector"); } bool found_packedint = false; ITERATE(TSeqLocVector, itr, queries) { if (((*itr).seqloc)->IsPacked_int()) { found_packedint = true; break; } } if (found_packedint) { NON_CONST_ITERATE(TSeqLocVector, itr, queries) { if (((*itr).seqloc)->IsPacked_int()) { CSeq_loc* mix = const_cast<CSeq_loc *> (&* (*itr).seqloc); NON_CONST_ITERATE(CPacked_seqint::Tdata, it, mix->SetPacked_int().Set()) { CRef<CSeq_loc> ival(new CSeq_loc); ival->SetInt(**it); m_SSeqLocVector.push_back(SSeqLoc(ival, (*itr).scope, (*itr).mask)); } } else { m_SSeqLocVector.push_back(*itr); } } } else { NON_CONST_ITERATE(TSeqLocVector, itr, queries) { m_SSeqLocVector.push_back(*itr); } } } CObjMgr_QueryFactory::CObjMgr_QueryFactory(CBlastQueryVector & queries) : m_QueryVector(& queries) { if (queries.Empty()) { NCBI_THROW(CBlastException, eInvalidArgument, "Empty CBlastQueryVector"); } } vector< CRef<CScope> > CObjMgr_QueryFactory::ExtractScopes() { vector< CRef<CScope> > retval; if ( !m_SSeqLocVector.empty() ) { NON_CONST_ITERATE(TSeqLocVector, itr, m_SSeqLocVector) retval.push_back(itr->scope); } else if (m_QueryVector.NotEmpty()) { for (CBlastQueryVector::size_type i = 0; i < m_QueryVector->Size(); i++) retval.push_back(m_QueryVector->GetScope(i)); } else { abort(); } return retval; } TSeqLocVector CObjMgr_QueryFactory::GetTSeqLocVector() { TSeqLocVector retval; if ( !m_SSeqLocVector.empty() ) { retval = m_SSeqLocVector; } else if (m_QueryVector.NotEmpty()) { // FIXME: this is inefficient as it might be copying the masks too many // times for (CBlastQueryVector::size_type i = 0; i < m_QueryVector->Size(); i++) { TMaskedQueryRegions mqr = m_QueryVector->GetMaskedRegions(i); CRef<CSeq_loc> masks; CRef<CPacked_seqint> conv_masks = mqr.ConvertToCPacked_seqint(); if (conv_masks.NotEmpty()) { masks.Reset(new CSeq_loc); masks->SetPacked_int(*conv_masks); } SSeqLoc sl(m_QueryVector->GetQuerySeqLoc(i), m_QueryVector->GetScope(i), masks); retval.push_back(sl); } } else { abort(); } return retval; } /// Auxiliary function to help guess the program type from a CSeq-loc. This /// should only be used in the context of /// CObjMgr_QueryFactory::ExtractUserSpecifiedMasks static EBlastProgramType s_GuessProgram(CConstRef<CSeq_loc> mask) { // if we cannot safely determine the program from the mask, specifying // nucleotide query for a protein will result in a duplicate mask in the // worst case... not great, but acceptable. EBlastProgramType retval = eBlastTypeBlastn; if (mask.Empty() || mask->GetStrand() == eNa_strand_unknown) { return retval; } return retval; } TSeqLocInfoVector CObjMgr_QueryFactory::ExtractUserSpecifiedMasks() { TSeqLocInfoVector retval; if ( !m_SSeqLocVector.empty() ) { const EBlastProgramType kProgram = s_GuessProgram(m_SSeqLocVector.front().mask); NON_CONST_ITERATE(TSeqLocVector, itr, m_SSeqLocVector) { TMaskedQueryRegions mqr = PackedSeqLocToMaskedQueryRegions(itr->mask, kProgram, itr->ignore_strand_in_mask); retval.push_back(mqr); } } else if (m_QueryVector.NotEmpty()) { for (CBlastQueryVector::size_type i = 0; i < m_QueryVector->Size(); i++) retval.push_back(m_QueryVector->GetMaskedRegions(i)); } else { abort(); } return retval; } CRef<ILocalQueryData> CObjMgr_QueryFactory::x_MakeLocalQueryData(const CBlastOptions* opts) { CRef<ILocalQueryData> retval; if ( !m_SSeqLocVector.empty() ) { retval.Reset(new CObjMgr_LocalQueryData(&m_SSeqLocVector, opts)); } else if (m_QueryVector.NotEmpty()) { retval.Reset(new CObjMgr_LocalQueryData(*m_QueryVector, opts)); } else { abort(); } return retval; } CRef<IRemoteQueryData> CObjMgr_QueryFactory::x_MakeRemoteQueryData() { CRef<IRemoteQueryData> retval; if ( !m_SSeqLocVector.empty() ) { retval.Reset(new CObjMgr_RemoteQueryData(&m_SSeqLocVector)); } else if (m_QueryVector.NotEmpty()) { retval.Reset(new CObjMgr_RemoteQueryData(*m_QueryVector)); } else { abort(); } return retval; } END_SCOPE(blast) END_NCBI_SCOPE /* @} */
29.932939
90
0.616038
[ "vector" ]
d534c11f0861f458b26d33f389feef99f48597ca
5,198
cc
C++
rds/src/model/DescribeDBProxyResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
rds/src/model/DescribeDBProxyResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
rds/src/model/DescribeDBProxyResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/rds/model/DescribeDBProxyResult.h> #include <json/json.h> using namespace AlibabaCloud::Rds; using namespace AlibabaCloud::Rds::Model; DescribeDBProxyResult::DescribeDBProxyResult() : ServiceResult() {} DescribeDBProxyResult::DescribeDBProxyResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDBProxyResult::~DescribeDBProxyResult() {} void DescribeDBProxyResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allDBProxyConnectStringItemsNode = value["DBProxyConnectStringItems"]["DBProxyConnectStringItemsItem"]; for (auto valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem : allDBProxyConnectStringItemsNode) { DBProxyConnectStringItemsItem dBProxyConnectStringItemsObject; if(!valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyEndpointId"].isNull()) dBProxyConnectStringItemsObject.dBProxyEndpointId = valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyEndpointId"].asString(); if(!valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectString"].isNull()) dBProxyConnectStringItemsObject.dBProxyConnectString = valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectString"].asString(); if(!valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectStringPort"].isNull()) dBProxyConnectStringItemsObject.dBProxyConnectStringPort = valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectStringPort"].asString(); if(!valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectStringNetType"].isNull()) dBProxyConnectStringItemsObject.dBProxyConnectStringNetType = valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectStringNetType"].asString(); if(!valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyVpcInstanceId"].isNull()) dBProxyConnectStringItemsObject.dBProxyVpcInstanceId = valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyVpcInstanceId"].asString(); if(!valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyEndpointName"].isNull()) dBProxyConnectStringItemsObject.dBProxyEndpointName = valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyEndpointName"].asString(); if(!valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectStringNetWorkType"].isNull()) dBProxyConnectStringItemsObject.dBProxyConnectStringNetWorkType = valueDBProxyConnectStringItemsDBProxyConnectStringItemsItem["DBProxyConnectStringNetWorkType"].asString(); dBProxyConnectStringItems_.push_back(dBProxyConnectStringItemsObject); } if(!value["DBProxyServiceStatus"].isNull()) dBProxyServiceStatus_ = value["DBProxyServiceStatus"].asString(); if(!value["DBProxyInstanceType"].isNull()) dBProxyInstanceType_ = value["DBProxyInstanceType"].asString(); if(!value["DBProxyInstanceNum"].isNull()) dBProxyInstanceNum_ = std::stoi(value["DBProxyInstanceNum"].asString()); if(!value["DBProxyInstanceStatus"].isNull()) dBProxyInstanceStatus_ = value["DBProxyInstanceStatus"].asString(); if(!value["DBProxyInstanceCurrentMinorVersion"].isNull()) dBProxyInstanceCurrentMinorVersion_ = value["DBProxyInstanceCurrentMinorVersion"].asString(); if(!value["DBProxyInstanceLatestMinorVersion"].isNull()) dBProxyInstanceLatestMinorVersion_ = value["DBProxyInstanceLatestMinorVersion"].asString(); if(!value["DBProxyInstanceName"].isNull()) dBProxyInstanceName_ = value["DBProxyInstanceName"].asString(); } std::string DescribeDBProxyResult::getDBProxyInstanceName()const { return dBProxyInstanceName_; } std::string DescribeDBProxyResult::getDBProxyInstanceCurrentMinorVersion()const { return dBProxyInstanceCurrentMinorVersion_; } std::string DescribeDBProxyResult::getDBProxyServiceStatus()const { return dBProxyServiceStatus_; } int DescribeDBProxyResult::getDBProxyInstanceNum()const { return dBProxyInstanceNum_; } std::string DescribeDBProxyResult::getDBProxyInstanceLatestMinorVersion()const { return dBProxyInstanceLatestMinorVersion_; } std::vector<DescribeDBProxyResult::DBProxyConnectStringItemsItem> DescribeDBProxyResult::getDBProxyConnectStringItems()const { return dBProxyConnectStringItems_; } std::string DescribeDBProxyResult::getDBProxyInstanceStatus()const { return dBProxyInstanceStatus_; } std::string DescribeDBProxyResult::getDBProxyInstanceType()const { return dBProxyInstanceType_; }
43.680672
175
0.833205
[ "vector", "model" ]
d53718e976ee353f30caab740535c91352a17f58
50,099
cpp
C++
src/frontends/lean/structure_cmd.cpp
javra/lean
cc70845332e63a1f1be21dc1f96d17269fc85909
[ "Apache-2.0" ]
130
2016-12-02T22:46:10.000Z
2022-03-22T01:09:48.000Z
src/frontends/lean/structure_cmd.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
8
2017-05-03T01:21:08.000Z
2020-02-25T11:38:05.000Z
src/frontends/lean/structure_cmd.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
28
2016-12-02T22:46:20.000Z
2022-03-18T21:28:20.000Z
/* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <memory> #include <utility> #include <vector> #include <algorithm> #include <string> #include "util/sstream.h" #include "util/fresh_name.h" #include "util/sexpr/option_declarations.h" #include "kernel/type_checker.h" #include "kernel/instantiate.h" #include "kernel/abstract.h" #include "kernel/replace_fn.h" #include "kernel/error_msgs.h" #include "kernel/inductive/inductive.h" #include "library/trace.h" #include "library/attribute_manager.h" #include "library/scoped_ext.h" #include "library/normalize.h" #include "library/placeholder.h" #include "library/locals.h" #include "library/reducible.h" #include "library/unifier.h" #include "library/module.h" #include "library/aliases.h" #include "library/annotation.h" #include "library/coercion.h" #include "library/explicit.h" #include "library/protected.h" #include "library/class.h" #include "library/constants.h" #include "library/util.h" #include "library/projection.h" #include "library/kernel_serializer.h" #include "library/definitional/rec_on.h" #include "library/definitional/induction_on.h" #include "library/definitional/cases_on.h" #include "library/definitional/projection.h" #include "library/definitional/no_confusion.h" #include "frontends/lean/parser.h" #include "frontends/lean/util.h" #include "frontends/lean/decl_cmds.h" #include "frontends/lean/tokens.h" #include "frontends/lean/elaborator_exception.h" #include "frontends/lean/type_util.h" #ifndef LEAN_DEFAULT_STRUCTURE_INTRO #define LEAN_DEFAULT_STRUCTURE_INTRO "mk" #endif #ifndef LEAN_DEFAULT_STRUCTURE_ETA #define LEAN_DEFAULT_STRUCTURE_ETA false #endif #ifndef LEAN_DEFAULT_STRUCTURE_PROJ_MK #define LEAN_DEFAULT_STRUCTURE_PROJ_MK false #endif namespace lean { static name * g_tmp_prefix = nullptr; static name * g_gen_eta = nullptr; static name * g_gen_proj_mk = nullptr; bool get_structure_eta_thm(options const & o) { return o.get_bool(*g_gen_eta, LEAN_DEFAULT_STRUCTURE_ETA); } bool get_structure_proj_mk_thm(options const & o) { return o.get_bool(*g_gen_proj_mk, LEAN_DEFAULT_STRUCTURE_ETA); } /** \brief Return the universe parameters, number of parameters and introduction rule for the given parent structure \pre is_structure_like(env, S) */ static auto get_structure_info(environment const & env, name const & S) -> std::tuple<level_param_names, unsigned, inductive::intro_rule> { lean_assert(is_structure_like(env, S)); inductive::inductive_decls idecls = *inductive::is_inductive_decl(env, S); inductive::intro_rule intro = head(inductive::inductive_decl_intros(head(std::get<2>(idecls)))); return std::make_tuple(std::get<0>(idecls), std::get<1>(idecls), intro); } struct structure_cmd_fn { typedef std::unique_ptr<type_checker> type_checker_ptr; typedef std::vector<pair<name, name>> rename_vector; // field_map[i] contains the position of the \c i-th field of a parent structure into this one. typedef std::vector<unsigned> field_map; typedef type_modifiers modifiers; parser & m_p; environment m_env; type_checker_ptr m_tc; name m_namespace; name m_name; pos_info m_name_pos; buffer<name> m_level_names; modifiers m_modifiers; buffer<expr> m_params; expr m_type; buffer<optional<name>> m_parent_refs; buffer<expr> m_parents; buffer<bool> m_private_parents; name m_mk; name m_mk_short; pos_info m_mk_pos; implicit_infer_kind m_mk_infer; buffer<expr> m_fields; std::vector<rename_vector> m_renames; std::vector<field_map> m_field_maps; bool m_explicit_universe_params; bool m_infer_result_universe; bool m_inductive_predicate; levels m_ctx_levels; // context levels for creating aliases buffer<expr> m_ctx_locals; // context local constants for creating aliases bool m_gen_eta; bool m_gen_proj_mk; structure_cmd_fn(parser & p):m_p(p), m_env(p.env()), m_namespace(get_namespace(m_env)) { m_tc = mk_type_checker(m_env); m_explicit_universe_params = false; m_infer_result_universe = false; m_inductive_predicate = false; m_gen_eta = get_structure_eta_thm(p.get_options()); m_gen_proj_mk = get_structure_proj_mk_thm(p.get_options()); } /** \brief Parse structure name and (optional) universe parameters */ void parse_decl_name() { m_name_pos = m_p.pos(); m_name = m_p.check_decl_id_next("invalid 'structure', identifier expected"); m_name = m_namespace + m_name; buffer<name> ls_buffer; if (parse_univ_params(m_p, ls_buffer)) { m_explicit_universe_params = true; m_infer_result_universe = false; m_level_names.append(ls_buffer); } else { m_explicit_universe_params = false; m_infer_result_universe = true; } m_modifiers.parse(m_p); } /** \brief Parse structure parameters */ void parse_params() { if (!m_p.curr_is_token(get_extends_tk()) && !m_p.curr_is_token(get_assign_tk()) && !m_p.curr_is_token(get_colon_tk())) { unsigned rbp = 0; m_p.parse_binders(m_params, rbp); } for (expr const & l : m_params) m_p.add_local(l); } /** \brief Check whether \c parent is really an inductive datatype declaration that can be viewed as a "record". That is, it is not part of a mutually recursive declaration, it has only one constructor, and it does not have indicies. */ void check_parent(expr const & parent, pos_info const & pos) { expr const & fn = get_app_fn(parent); if (!is_constant(fn)) throw parser_error("invalid 'structure', expression must be a 'parent' structure", pos); name const & S = const_name(fn); if (!is_structure_like(m_env, S)) throw parser_error(sstream() << "invalid 'structure' extends, '" << S << "' is not a structure", pos); } /** \brief Return the universe parameters, number of parameters and introduction rule for the given parent structure */ std::tuple<level_param_names, unsigned, inductive::intro_rule> get_parent_info(name const & parent) { return get_structure_info(m_env, parent); } /** \brief Sign an error if the constructor \c intro_type does not have a field named \c from_id */ void check_from_rename(name const & parent_name, expr intro_type, name const & from_id, pos_info const & from_pos) { while (is_pi(intro_type)) { if (binding_name(intro_type) == from_id) return; intro_type = binding_body(intro_type); } throw parser_error(sstream() << "invalid 'structure' renaming, parent structure '" << parent_name << "' " << "does not contain field '" << from_id << "'", from_pos); } /** \brief Parse optional extends clause */ void parse_extends() { if (m_p.curr_is_token(get_extends_tk())) { m_p.next(); while (true) { auto pos = m_p.pos(); bool is_private_parent = false; if (m_p.curr_is_token(get_private_tk())) { m_p.next(); is_private_parent = true; } pair<optional<name>, expr> qparent = m_p.parse_qualified_expr(); m_parent_refs.push_back(qparent.first); expr const & parent = qparent.second; m_parents.push_back(parent); m_private_parents.push_back(is_private_parent); check_parent(parent, pos); name const & parent_name = const_name(get_app_fn(parent)); auto parent_info = get_parent_info(parent_name); unsigned nparams = std::get<1>(parent_info); inductive::intro_rule intro = std::get<2>(parent_info); expr intro_type = inductive::intro_rule_type(intro); for (unsigned i = 0; i < nparams; i++) { if (!is_pi(intro_type)) throw parser_error("invalid 'structure' extends, parent structure seems to be ill-formed", pos); intro_type = binding_body(intro_type); } m_renames.push_back(rename_vector()); if (m_p.curr_is_token(get_renaming_tk())) { m_p.next(); rename_vector & v = m_renames.back(); while (m_p.curr_is_identifier()) { auto from_pos = m_p.pos(); name from_id = m_p.get_name_val(); if (std::find_if(v.begin(), v.end(), [&](pair<name, name> const & p) { return p.first == from_id; }) != v.end()) throw parser_error(sstream() << "invalid 'structure' renaming, a rename from '" << from_id << "' has already been defined", from_pos); check_from_rename(parent_name, intro_type, from_id, from_pos); m_p.next(); m_p.check_token_next(get_arrow_tk(), "invalid 'structure' renaming, '->' expected"); name to_id = m_p.check_id_next("invalid 'structure' renaming, identifier expected"); if (from_id == to_id) throw parser_error(sstream() << "invalid 'structure' renaming, redundant rename", from_pos); v.emplace_back(from_id, to_id); } } if (!m_p.curr_is_token(get_comma_tk())) break; m_p.next(); } } } void throw_explicit_universe(pos_info const & pos) { throw parser_error("invalid 'structure', the resultant universe must be provided when explicit universe levels are being used", pos); } /** \brief Parse resultant universe */ void parse_result_type() { auto pos = m_p.pos(); if (m_p.curr_is_token(get_colon_tk())) { m_p.next(); m_type = m_p.parse_expr(); while (is_annotation(m_type)) m_type = get_annotation_arg(m_type); m_inductive_predicate = m_env.impredicative() && is_zero(sort_level(m_type)); if (!is_sort(m_type)) throw parser_error("invalid 'structure', 'Type' expected", pos); if (m_inductive_predicate) m_infer_result_universe = false; if (m_infer_result_universe) { if (!is_placeholder(sort_level(m_type))) throw parser_error("invalid 'structure', resultant universe level is computed " "automatically when universe level parameters are not provided", pos); } else { if (has_placeholder(m_type)) throw_explicit_universe(pos); } } else { if (!m_infer_result_universe) throw_explicit_universe(pos); m_type = m_p.save_pos(mk_sort(mk_level_placeholder()), pos); } } /** \brief Parse parameters, extends clauses and resultant type */ void parse_header() { parser::local_scope scope(m_p); parse_decl_name(); parse_params(); parse_extends(); parse_result_type(); } /** \brief Update the local constants in \c locals using the content of the Pi expression \c new_tmp. This method assumes that new_tmp contains at least locals.size() nested Pi's. */ expr update_locals(expr new_tmp, buffer<expr> & locals) { for (unsigned i = 0; i < locals.size(); i++) { expr new_local = mk_local(mlocal_name(locals[i]), binding_name(new_tmp), binding_domain(new_tmp), binding_info(new_tmp)); locals[i] = new_local; new_tmp = instantiate(binding_body(new_tmp), new_local); } return new_tmp; } expr update_parents(expr new_tmp, bool inst) { for (unsigned i = 0; i < m_parents.size(); i++) { m_parents[i] = copy_tag(m_parents[i], expr(binding_domain(new_tmp))); new_tmp = binding_body(new_tmp); if (inst) new_tmp = instantiate(new_tmp, mk_parent_expr(i)); } return new_tmp; } /** \brief elaborate parameters and "parent" types */ void elaborate_header() { buffer<expr> include_vars; m_p.get_include_variables(include_vars); buffer<expr> tmp_locals; tmp_locals.append(m_params); for (expr const & parent : m_parents) tmp_locals.push_back(mk_local(mk_fresh_name(), parent)); collected_locals dep_set; for (expr const & v : include_vars) { ::lean::collect_locals(mlocal_type(v), dep_set); dep_set.insert(v); } for (expr const & p : m_params) ::lean::collect_locals(mlocal_type(p), dep_set); collect_annonymous_inst_implicit(m_p, dep_set); /* Copy the locals from dep_set that are NOT in m_params to dep_set_minus_params */ buffer<expr> dep_set_minus_params; for (auto d : dep_set.get_collected()) { if (std::all_of(m_params.begin(), m_params.end(), [&](expr const & p) { return mlocal_name(d) != mlocal_name(p); })) dep_set_minus_params.push_back(d); } /* Sort dep_set_minus_params and store result in ctx */ buffer<expr> ctx; sort_locals(dep_set_minus_params, m_p, ctx); expr tmp = Pi_as_is(ctx, Pi(tmp_locals, m_type, m_p), m_p); level_param_names new_ls; expr new_tmp; std::tie(new_tmp, new_ls) = m_p.elaborate_type(tmp, list<expr>()); levels new_meta_ls = map2<level>(new_ls, [](name const & n) { return mk_meta_univ(n); }); new_tmp = instantiate_univ_params(new_tmp, new_ls, new_meta_ls); new_tmp = update_locals(new_tmp, ctx); new_tmp = update_locals(new_tmp, m_params); buffer<expr> explicit_params; explicit_params.append(m_params); m_params.clear(); m_params.append(ctx); m_params.append(explicit_params); new_tmp = update_parents(new_tmp, false); m_type = new_tmp; } void throw_ill_formed_parent(name const & parent_name) { throw exception(sstream() << "invalid 'structure' header, parent structure '" << parent_name << "' is ill-formed"); } /** \brief Check if \c fname has been renamed, and return new name */ name rename(rename_vector const & v, name const & fname) { for (auto const & p : v) { if (p.first == fname) return p.second; } return fname; } /** \brief If \c fname matches the name of an existing field, then check if the types are definitionally equal (store any generated unification constraints in cseq), and return the index of the existing field. */ optional<unsigned> merge(expr const & parent, name const & fname, expr const & ftype, constraint_seq & cseq) { for (unsigned i = 0; i < m_fields.size(); i++) { if (local_pp_name(m_fields[i]) == fname) { if (m_tc->is_def_eq(mlocal_type(m_fields[i]), ftype, justification(), cseq)) { return optional<unsigned>(i); } else { expr prev_ftype = mlocal_type(m_fields[i]); throw_elaborator_exception(parent, [=](formatter const & fmt) { format r = format("invalid 'structure' header, field '"); r += format(fname); r += format("' from '"); r += format(const_name(get_app_fn(parent))); r += format("' has already been declared with a different type"); r += pp_indent_expr(fmt, prev_ftype); r += compose(line(), format("and")); r += pp_indent_expr(fmt, ftype); return r; }); } } } return optional<unsigned>(); } /** \brief Process extends clauses. Return unification constraints when processing fields of parent structures. The constraints are generated when "merging" the fields from different parents. This method also populates the vector m_field_maps and m_fields. */ constraint_seq process_extends() { lean_assert(m_fields.empty()); lean_assert(m_field_maps.empty()); constraint_seq cseq; for (unsigned i = 0; i < m_parents.size(); i++) { expr const & parent = m_parents[i]; rename_vector const & renames = m_renames[i]; m_field_maps.push_back(field_map()); field_map & fmap = m_field_maps.back(); buffer<expr> args; expr const & parent_fn = get_app_args(parent, args); level_param_names lparams; unsigned nparams; inductive::intro_rule intro; name const & parent_name = const_name(parent_fn); std::tie(lparams, nparams, intro) = get_parent_info(parent_name); expr intro_type = inductive::intro_rule_type(intro); intro_type = instantiate_univ_params(intro_type, lparams, const_levels(parent_fn)); if (nparams != args.size()) { throw_elaborator_exception(sstream() << "invalid 'structure' header, number of argument " "mismatch for parent structure '" << parent_name << "'", parent); } for (expr const & arg : args) { if (!is_pi(intro_type)) throw_ill_formed_parent(parent_name); intro_type = instantiate(binding_body(intro_type), arg); } while (is_pi(intro_type)) { name fname = binding_name(intro_type); fname = rename(renames, fname); expr const & ftype = binding_domain(intro_type); expr field; if (auto fidx = merge(parent, fname, ftype, cseq)) { fmap.push_back(*fidx); field = m_fields[*fidx]; if (local_info(field) != binding_info(intro_type)) { throw_elaborator_exception(sstream() << "invalid 'structure' header, field '" << fname << "' has already been declared with a different binder annotation", parent); } } else { field = mk_local(fname, ftype, binding_info(intro_type)); fmap.push_back(m_fields.size()); m_fields.push_back(field); } intro_type = instantiate(binding_body(intro_type), field); } } lean_assert(m_parents.size() == m_field_maps.size()); return cseq; } void solve_constraints(constraint_seq const & cseq) { if (!cseq) return; buffer<constraint> cs; cseq.linearize(cs); bool use_exceptions = true; bool discard = true; unifier_config cfg(use_exceptions, discard); unify_result_seq rseq = unify(m_env, cs.size(), cs.data(), substitution(), cfg); auto p = rseq.pull(); lean_assert(p); substitution subst = p->first.first; for (expr & parent : m_parents) parent = subst.instantiate(parent); for (expr & param : m_params) param = subst.instantiate(param); for (expr & field : m_fields) field = subst.instantiate(field); } /** \brief Parse header, elaborate it, and process parents (aka extends clauses) */ void process_header() { parse_header(); elaborate_header(); constraint_seq cseq = process_extends(); solve_constraints(cseq); } /** \brief Create expression of type \c m_parents[i] from corresponding fields */ expr mk_parent_expr(unsigned i) { expr const & parent = m_parents[i]; field_map const & fmap = m_field_maps[i]; buffer<expr> parent_params; expr const & parent_fn = get_app_args(parent, parent_params); levels const & parent_ls = const_levels(parent_fn); name const & parent_name = const_name(parent_fn); auto parent_info = get_parent_info(parent_name); name const & parent_intro_name = inductive::intro_rule_name(std::get<2>(parent_info)); expr parent_intro = mk_app(mk_constant(parent_intro_name, parent_ls), parent_params); for (unsigned idx : fmap) { expr const & field = m_fields[idx]; parent_intro = mk_app(parent_intro, field); } return parent_intro; } /** \brief Add params, fields and references to parent structures into parser local scope */ void add_locals() { if (m_explicit_universe_params) { for (name const & l : m_level_names) m_p.add_local_level(l, mk_param_univ(l)); } for (expr const & param : m_params) m_p.add_local(param); for (expr const & field : m_fields) m_p.add_local(field); for (unsigned i = 0; i < m_parents.size(); i++) { if (auto n = m_parent_refs[i]) m_p.add_local_expr(*n, mk_as_is(mk_parent_expr(i))); } } /** \brief Check if new field names collide with fields inherited from parent datastructures */ void check_new_field_names(buffer<expr> const & new_fields) { for (expr const & new_field : new_fields) { if (std::find_if(m_fields.begin(), m_fields.end(), [&](expr const & inherited_field) { return local_pp_name(inherited_field) == local_pp_name(new_field); }) != m_fields.end()) { throw_elaborator_exception(sstream() << "field '" << local_pp_name(new_field) << "' has been declared in parent structure", new_field); } } } void parse_field_block(buffer<expr> & new_fields, binder_info const & bi) { buffer<pair<pos_info, name>> names; while (m_p.curr_is_identifier()) { auto p = m_p.pos(); names.emplace_back(p, m_p.check_atomic_id_next("invalid field, atomic identifier expected")); } if (names.empty()) throw parser_error("invalid field, identifier expected", m_p.pos()); m_p.check_token_next(get_colon_tk(), "invalid field, ':' expected"); expr type = m_p.parse_expr(); for (auto p : names) { expr local = m_p.save_pos(mk_local(p.second, type, bi), p.first); m_p.add_local(local); new_fields.push_back(local); } } /** \brief Parse new fields declared in this structure */ void parse_new_fields(buffer<expr> & new_fields) { parser::local_scope scope(m_p); add_locals(); while (!m_p.curr_is_command_like()) { if (m_p.curr_is_identifier()) { parse_field_block(new_fields, binder_info()); } else { binder_info bi = m_p.parse_binder_info(); parse_field_block(new_fields, bi); m_p.parse_close_binder_info(bi); } } check_new_field_names(new_fields); } /** \brief Elaborate new fields, and copy them to m_fields */ void elaborate_new_fields(buffer<expr> & new_fields) { expr tmp = Pi_as_is(m_fields, Pi(new_fields, mk_Prop(), m_p), m_p); unsigned j = m_parents.size(); while (j > 0) { --j; tmp = mk_arrow(mk_as_is(m_parents[j]), tmp); } tmp = Pi_as_is(m_params, tmp, m_p); level_param_names new_ls; expr new_tmp; std::tie(new_tmp, new_ls) = m_p.elaborate_type(tmp, list<expr>()); for (auto new_l : new_ls) m_level_names.push_back(new_l); new_tmp = update_locals(new_tmp, m_params); new_tmp = update_parents(new_tmp, true); new_tmp = update_locals(new_tmp, m_fields); new_tmp = update_locals(new_tmp, new_fields); lean_assert(new_tmp == mk_Prop()); m_fields.append(new_fields); } /** \brief Parse new fields declared by this structure, and elaborate them. */ void process_new_fields() { buffer<expr> new_fields; parse_new_fields(new_fields); elaborate_new_fields(new_fields); } void process_empty_new_fields() { buffer<expr> new_fields; elaborate_new_fields(new_fields); } /** \brief Traverse fields and collect the universes they reside in \c r_lvls. This information is used to compute the resultant universe level for the inductive datatype declaration. */ void accumulate_levels(buffer<level> & r_lvls) { for (expr const & field : m_fields) { expr s = m_tc->ensure_type(mlocal_type(field)).first; level l = sort_level(s); if (std::find(r_lvls.begin(), r_lvls.end(), l) == r_lvls.end()) { r_lvls.push_back(l); } } } /** \brief Compute resultant universe (if it was not provided explicitly) based on the universes where the fields "reside" */ void infer_resultant_universe() { if (m_infer_result_universe) { buffer<level> r_lvls; accumulate_levels(r_lvls); level r_lvl = mk_result_level(m_env, r_lvls); m_type = mk_sort(r_lvl); } } /** \brief Display m_fields (for debugging purposes) */ void display_fields(std::ostream & out) { for (expr const & field : m_fields) { out << ">> " << mlocal_name(field) << " : " << mlocal_type(field) << "\n"; } } /** \brief Collect context local constants used in the declaration. */ void collect_ctx_locals(buffer<expr> & locals) { if (!m_p.has_locals()) return; expr dummy = mk_Prop(); expr tmp = Pi(m_params, Pi(m_fields, dummy)); collected_locals local_set; ::lean::collect_locals(tmp, local_set); collect_annonymous_inst_implicit(m_p, local_set); sort_locals(local_set.get_collected(), m_p, locals); } /** \brief Add context locals as extra parameters */ void add_ctx_locals(buffer<expr> const & ctx_locals) { buffer<expr> params; params.append(m_params); m_params.clear(); m_params.append(ctx_locals); m_params.append(params); } /** \brief Initialize m_ctx_locals field */ void set_ctx_locals() { buffer<expr> new_ctx_locals; collect_ctx_locals(new_ctx_locals); add_ctx_locals(new_ctx_locals); for (expr const & p : m_params) { if (m_p.is_local_decl(p) && !m_p.is_local_variable(p)) m_ctx_locals.push_back(p); } } /** \brief Include in m_level_names any local level referenced m_type and m_fields */ void include_ctx_levels() { name_set all_lvl_params; all_lvl_params = collect_univ_params(m_type); for (expr const & p : m_params) all_lvl_params = collect_univ_params(mlocal_type(p), all_lvl_params); for (expr const & f : m_fields) all_lvl_params = collect_univ_params(mlocal_type(f), all_lvl_params); buffer<name> section_lvls; all_lvl_params.for_each([&](name const & l) { if (std::find(m_level_names.begin(), m_level_names.end(), l) == m_level_names.end()) section_lvls.push_back(l); }); std::sort(section_lvls.begin(), section_lvls.end(), [&](name const & n1, name const & n2) { return m_p.get_local_level_index(n1) < m_p.get_local_level_index(n2); }); buffer<name> new_levels; new_levels.append(section_lvls); new_levels.append(m_level_names); m_level_names.clear(); m_level_names.append(new_levels); } expr mk_structure_type() { return Pi(m_params, m_type); } expr mk_intro_type() { levels ls = param_names_to_levels(to_list(m_level_names.begin(), m_level_names.end())); expr r = mk_app(mk_constant(m_name, ls), m_params); r = Pi(m_params, Pi(m_fields, r)); return infer_implicit_params(r, m_params.size(), m_mk_infer); } void save_info(name const & n, name const & k, pos_info const & pos) { expr type = m_env.get(n).get_type(); m_p.add_decl_index(n, pos, k, type); } void add_alias(name const & n, bool composite = true) { m_env = ::lean::add_alias(m_p, m_env, composite, n, m_ctx_levels, m_ctx_locals); } void add_rec_alias(name const & n) { bool composite = true; m_env = ::lean::add_alias(m_p, m_env, composite, n, levels(mk_level_placeholder(), m_ctx_levels), m_ctx_locals); } void declare_inductive_type() { expr structure_type = mk_structure_type(); expr intro_type = mk_intro_type(); level_param_names lnames = to_list(m_level_names.begin(), m_level_names.end()); inductive::intro_rule intro = inductive::mk_intro_rule(m_mk, intro_type); inductive::inductive_decl decl(m_name, structure_type, to_list(intro)); m_env = module::add_inductive(m_env, lnames, m_params.size(), to_list(decl)); save_info(m_name, "structure", m_name_pos); name rec_name = inductive::get_elim_name(m_name); save_info(rec_name, "recursor", m_name_pos); save_info(m_mk, "intro", m_mk_pos); m_env = add_namespace(m_env, m_name); m_env = add_protected(m_env, rec_name); add_alias(m_name, false); add_alias(m_mk); add_rec_alias(rec_name); if (m_modifiers.is_class()) m_env = add_class(m_env, m_name, get_namespace(m_env), true); } void save_def_info(name const & n) { save_info(n, "definition", m_name_pos); } void save_proj_info(name const & n) { save_info(n, "projection", m_name_pos); } void save_thm_info(name const & n) { save_info(n, "theorem", m_name_pos); } void declare_projections() { m_env = mk_projections(m_env, m_name, m_mk_infer, m_modifiers.is_class()); for (expr const & field : m_fields) { name field_name = m_name + mlocal_name(field); save_proj_info(field_name); add_alias(field_name); } } void add_rec_on_alias(name const & n) { name rec_on_name(m_name, "rec_on"); declaration rec_on_decl = m_env.get(rec_on_name); declaration new_decl = mk_definition(m_env, n, rec_on_decl.get_univ_params(), rec_on_decl.get_type(), rec_on_decl.get_value()); m_env = module::add(m_env, check(m_env, new_decl)); m_env = set_reducible(m_env, n, reducible_status::Reducible, get_namespace(m_env), true); if (list<unsigned> idx = has_unfold_hint(m_env, rec_on_name)) m_env = add_unfold_hint(m_env, n, idx, get_namespace(m_env), true); save_def_info(n); add_alias(n); } void declare_auxiliary() { m_env = mk_rec_on(m_env, m_name); name rec_on_name(m_name, "rec_on"); add_rec_alias(rec_on_name); save_def_info(rec_on_name); if (m_env.impredicative()) { m_env = mk_induction_on(m_env, m_name); name induction_on_name(m_name, "induction_on"); add_rec_alias(induction_on_name); save_def_info(induction_on_name); } add_rec_on_alias(name(m_name, "destruct")); add_rec_on_alias(name(m_name, "cases_on")); } // Return the parent names without namespace prefix void get_truncated_parent_names(buffer<name> & parent_names) { for (expr const & parent : m_parents) { name n = const_name(get_app_fn(parent)); if (!n.is_atomic() && n.is_string()) n = name(n.get_string()); parent_names.push_back(n); } } void mk_coercion_names(buffer<name> & coercion_names) { buffer<name> parent_names; get_truncated_parent_names(parent_names); name_set found; name_map<unsigned> non_unique; for (name const & n : parent_names) { if (found.contains(n)) non_unique.insert(n, 1); found.insert(n); } for (name & n : parent_names) { if (auto it = non_unique.find(n)) { unsigned idx = *it; non_unique.insert(n, idx+1); n = n.append_after(idx); } name coercion_name = m_name + n.append_before("to_"); coercion_names.push_back(coercion_name); } } void declare_coercions() { lean_assert(m_parents.size() == m_field_maps.size()); buffer<name> coercion_names; mk_coercion_names(coercion_names); level_param_names lnames = to_list(m_level_names.begin(), m_level_names.end()); levels st_ls = param_names_to_levels(lnames); for (unsigned i = 0; i < m_parents.size(); i++) { expr const & parent = m_parents[i]; field_map const & fmap = m_field_maps[i]; buffer<expr> parent_params; expr const & parent_fn = get_app_args(parent, parent_params); levels const & parent_ls = const_levels(parent_fn); name const & parent_name = const_name(parent_fn); auto parent_info = get_parent_info(parent_name); name const & parent_intro_name = inductive::intro_rule_name(std::get<2>(parent_info)); expr parent_intro = mk_app(mk_constant(parent_intro_name, parent_ls), parent_params); expr parent_type = m_tc->infer(parent).first; if (!is_sort(parent_type)) throw_ill_formed_parent(parent_name); level parent_rlvl = sort_level(parent_type); expr st_type = mk_app(mk_constant(m_name, st_ls), m_params); binder_info bi; if (m_modifiers.is_class()) bi = mk_inst_implicit_binder_info(); expr st = mk_local(mk_fresh_name(), "s", st_type, bi); expr coercion_type = infer_implicit(Pi(m_params, Pi(st, parent)), m_params.size(), true);; expr coercion_value = parent_intro; for (unsigned idx : fmap) { expr const & field = m_fields[idx]; name proj_name = m_name + mlocal_name(field); expr proj = mk_app(mk_app(mk_constant(proj_name, st_ls), m_params), st); coercion_value = mk_app(coercion_value, proj); } coercion_value = Fun(m_params, Fun(st, coercion_value)); name coercion_name = coercion_names[i]; bool use_conv_opt = false; declaration coercion_decl = mk_definition(m_env, coercion_name, lnames, coercion_type, coercion_value, use_conv_opt); m_env = module::add(m_env, check(m_env, coercion_decl)); m_env = set_reducible(m_env, coercion_name, reducible_status::Reducible, get_namespace(m_env), true); save_def_info(coercion_name); add_alias(coercion_name); if (!m_private_parents[i]) { if (!m_modifiers.is_class() || !is_class(m_env, parent_name)) m_env = add_coercion(m_env, m_p.ios(), coercion_name, get_namespace(m_env), true); if (m_modifiers.is_class() && is_class(m_env, parent_name)) { // if both are classes, then we also mark coercion_name as an instance m_env = add_trans_instance(m_env, coercion_name, LEAN_DEFAULT_PRIORITY, get_namespace(m_env), true); } } } } void declare_eta() { if (!m_gen_eta) return; if (!has_eq_decls(m_env)) return; level_param_names lnames = to_list(m_level_names.begin(), m_level_names.end()); levels st_ls = param_names_to_levels(lnames); expr st_type = mk_app(mk_constant(m_name, st_ls), m_params); expr st = mk_local(mk_fresh_name(), "s", st_type, binder_info()); expr lhs = mk_app(mk_constant(m_mk, st_ls), m_params); for (expr const & field : m_fields) { expr proj = mk_app(mk_app(mk_constant(m_name + mlocal_name(field), st_ls), m_params), st); lhs = mk_app(lhs, proj); } expr eq = mk_app(mk_constant(get_eq_name(), to_list(sort_level(m_type))), st_type, lhs, st); level eq_lvl = sort_level(m_tc->ensure_type(eq).first); levels rec_ls = levels(eq_lvl, st_ls); expr rec = mk_app(mk_constant(inductive::get_elim_name(m_name), rec_ls), m_params); expr type_former = Fun(st, eq); expr mk = mk_app(mk_app(mk_constant(m_mk, st_ls), m_params), m_fields); expr refl = mk_app(mk_constant(get_eq_refl_name(), to_list(sort_level(m_type))), st_type, mk); refl = Fun(m_fields, refl); rec = mk_app(rec, type_former, refl, st); expr eta_type = infer_implicit(Pi(m_params, Pi(st, eq)), true); expr eta_value = Fun(m_params, Fun(st, rec)); name eta_name(m_name, "eta"); declaration eta_decl = mk_theorem(m_env, eta_name, lnames, eta_type, eta_value); m_env = module::add(m_env, check(m_env, eta_decl)); save_thm_info(eta_name); add_alias(eta_name); } void declare_proj_over_mk() { if (!m_gen_proj_mk) return; if (!has_eq_decls(m_env)) return; level_param_names lnames = to_list(m_level_names.begin(), m_level_names.end()); levels st_ls = param_names_to_levels(lnames); expr st_type = mk_app(mk_constant(m_name, st_ls), m_params); expr mk_fields = mk_app(mk_app(mk_constant(m_mk, st_ls), m_params), m_fields); for (unsigned i = 0; i < m_fields.size(); i++) { expr const & field = m_fields[i]; name const & field_name = mlocal_name(field); expr const & field_type = mlocal_type(field); if (m_env.prop_proof_irrel() && m_tc->is_prop(field_type).first) continue; level field_level = sort_level(m_tc->ensure_type(field_type).first); name proj_name = m_name + field_name; expr lhs = mk_app(mk_app(mk_constant(proj_name, st_ls), m_params), mk_fields); expr rhs = field; expr eq = mk_app(mk_constant(get_eq_name(), to_list(field_level)), field_type, lhs, rhs); expr refl = mk_app(mk_constant(get_eq_refl_name(), to_list(field_level)), field_type, lhs); name proj_over_name = m_name + field_name + m_mk_short; expr proj_over_type = infer_implicit(Pi(m_params, Pi(m_fields, eq)), m_params.size(), true); expr proj_over_value = Fun(m_params, Fun(m_fields, refl)); declaration proj_over_decl = mk_theorem(m_env, proj_over_name, lnames, proj_over_type, proj_over_value); m_env = module::add(m_env, check(m_env, proj_over_decl)); save_thm_info(proj_over_name); add_alias(proj_over_name); } } void declare_no_confustion() { if (!has_eq_decls(m_env)) return; if (m_env.impredicative() && !has_heq_decls(m_env)) return; if (!m_env.impredicative() && !has_lift_decls(m_env)) return; m_env = mk_no_confusion(m_env, m_name); name no_confusion_name(m_name, "no_confusion"); save_def_info(no_confusion_name); add_alias(no_confusion_name); } environment operator()() { process_header(); if (m_p.curr_is_token(get_assign_tk())) { m_p.check_token_next(get_assign_tk(), "invalid 'structure', ':=' expected"); m_mk_pos = m_p.pos(); if (m_p.curr_is_token(get_lparen_tk()) || m_p.curr_is_token(get_lcurly_tk()) || m_p.curr_is_token(get_lbracket_tk())) { m_mk_short = LEAN_DEFAULT_STRUCTURE_INTRO; m_mk_infer = implicit_infer_kind::Implicit; } else { m_mk_short = m_p.check_atomic_id_next("invalid 'structure', atomic identifier expected"); m_mk_infer = parse_implicit_infer_modifier(m_p); if (!m_p.curr_is_command_like()) m_p.check_token_next(get_dcolon_tk(), "invalid 'structure', '::' expected"); } m_mk = m_name + m_mk_short; process_new_fields(); } else { m_mk_pos = m_name_pos; m_mk_short = LEAN_DEFAULT_STRUCTURE_INTRO; m_mk_infer = implicit_infer_kind::Implicit; m_mk = m_name + m_mk_short; process_empty_new_fields(); } infer_resultant_universe(); set_ctx_locals(); include_ctx_levels(); m_ctx_levels = collect_local_nonvar_levels(m_p, to_list(m_level_names.begin(), m_level_names.end())); declare_inductive_type(); declare_projections(); declare_auxiliary(); declare_coercions(); if (!m_inductive_predicate) { declare_eta(); declare_proj_over_mk(); declare_no_confustion(); } return m_env; } }; environment structure_cmd(parser & p) { return structure_cmd_fn(p)(); } void get_structure_fields(environment const & env, name const & S, buffer<name> & fields) { lean_assert(is_structure_like(env, S)); level_param_names ls; unsigned nparams; inductive::intro_rule intro; std::tie(ls, nparams, intro) = get_structure_info(env, S); expr intro_type = inductive::intro_rule_type(intro); unsigned i = 0; while (is_pi(intro_type)) { if (i >= nparams) fields.push_back(S + binding_name(intro_type)); i++; intro_type = binding_body(intro_type); } } bool is_structure(environment const & env, name const & S) { if (!is_structure_like(env, S)) return false; level_param_names ls; unsigned nparams; inductive::intro_rule intro; std::tie(ls, nparams, intro) = get_structure_info(env, S); expr intro_type = inductive::intro_rule_type(intro); for (unsigned i = 0; i < nparams; i++) { if (!is_pi(intro_type)) return false; intro_type = binding_body(intro_type); } if (!is_pi(intro_type)) return false; name field_name = S + binding_name(intro_type); return get_projection_info(env, field_name) != nullptr; } static name * g_structure_instance_name = nullptr; static std::string * g_structure_instance_opcode = nullptr; void register_structure_cmd(cmd_table & r) { add_cmd(r, cmd_info("structure", "declare a new structure/record type", structure_cmd)); } [[ noreturn ]] static void throw_se_ex() { throw exception("unexpected occurrence of 'structure instance' expression"); } // We encode a 'structure instance' expression using a macro. // This is a trick to avoid creating a new kind of expression. // 'Structure instance' expressions are temporary objects used by the elaborator. // Example: Given // structure point (A B : Type) := (x : A) (y : B) // the structure instance // {| point, x := 10, y := 20 |} // is compiled into // point.mk 10 20 class structure_instance_macro_cell : public macro_definition_cell { list<name> m_fields; public: structure_instance_macro_cell(list<name> const & fs):m_fields(fs) {} virtual name get_name() const { return *g_structure_instance_name; } virtual pair<expr, constraint_seq> check_type(expr const &, extension_context &, bool) const { throw_se_ex(); } virtual optional<expr> expand(expr const &, extension_context &) const { throw_se_ex(); } virtual void write(serializer & s) const { s << *g_structure_instance_opcode; write_list(s, m_fields); } list<name> const & get_field_names() const { return m_fields; } }; static expr mk_structure_instance(list<name> const & fs, unsigned num, expr const * args) { lean_assert(num >= length(fs) + 1); macro_definition def(new structure_instance_macro_cell(fs)); return mk_macro(def, num, args); } bool is_structure_instance(expr const & e) { return is_macro(e) && macro_def(e).get_name() == *g_structure_instance_name; } void destruct_structure_instance(expr const & e, expr & t, buffer<name> & field_names, buffer<expr> & field_values, buffer<expr> & using_exprs) { lean_assert(is_structure_instance(e)); t = macro_arg(e, 0); list<name> const & fns = static_cast<structure_instance_macro_cell const*>(macro_def(e).raw())->get_field_names(); unsigned num_fileds = length(fns); to_buffer(fns, field_names); for (unsigned i = 1; i < num_fileds+1; i++) field_values.push_back(macro_arg(e, i)); for (unsigned i = num_fileds+1; i < macro_num_args(e); i++) using_exprs.push_back(macro_arg(e, i)); } static expr parse_struct_expr_core(parser & p, pos_info const & pos, bool curly_bar) { expr t = p.parse_expr(); buffer<name> field_names; buffer<expr> field_values; buffer<expr> using_exprs; while (p.curr_is_token(get_comma_tk())) { p.next(); pair<optional<name>, expr> id_e = p.parse_optional_assignment(); if (id_e.first) { field_names.push_back(*id_e.first); field_values.push_back(id_e.second); } else { using_exprs.push_back(id_e.second); } } if (curly_bar) p.check_token_next(get_rcurlybar_tk(), "invalid structure expression, '|}' expected"); else p.check_token_next(get_rdcurly_tk(), "invalid structure expression, '⦄' expected"); buffer<expr> args; args.push_back(t); args.append(field_values); args.append(using_exprs); return p.save_pos(mk_structure_instance(to_list(field_names), args.size(), args.data()), pos); } static expr parse_struct_curly_bar(parser & p, unsigned, expr const *, pos_info const & pos) { bool curly_bar = true; return parse_struct_expr_core(p, pos, curly_bar); } static expr parse_struct_dcurly(parser & p, unsigned, expr const *, pos_info const & pos) { bool curly_bar = false; return parse_struct_expr_core(p, pos, curly_bar); } void init_structure_instance_parsing_rules(parse_table & r) { expr x0 = mk_var(0); r = r.add({notation::transition("{|", notation::mk_ext_action(parse_struct_curly_bar))}, x0); r = r.add({notation::transition("⦃", notation::mk_ext_action(parse_struct_dcurly))}, x0); } void initialize_structure_cmd() { g_tmp_prefix = new name(name::mk_internal_unique_name()); g_gen_eta = new name{"structure", "eta_thm"}; g_gen_proj_mk = new name{"structure", "proj_mk_thm"}; register_bool_option(*g_gen_eta, LEAN_DEFAULT_STRUCTURE_ETA, "(structure) automatically generate 'eta' theorem whenever declaring a new structure"); register_bool_option(*g_gen_proj_mk, LEAN_DEFAULT_STRUCTURE_PROJ_MK, "(structure) automatically gneerate projection over introduction theorem when " "declaring a new structure, the theorem is never generated for proof irrelevant fields"); g_structure_instance_name = new name("structure instance"); g_structure_instance_opcode = new std::string("STI"); register_macro_deserializer(*g_structure_instance_opcode, [](deserializer & d, unsigned num, expr const * args) { list<name> fs; fs = read_list<name>(d); if (num < length(fs) + 1) throw corrupted_stream_exception(); return mk_structure_instance(fs, num, args); }); } void finalize_structure_cmd() { delete g_tmp_prefix; delete g_gen_eta; delete g_gen_proj_mk; delete g_structure_instance_opcode; delete g_structure_instance_name; } }
44.062445
141
0.596399
[ "vector" ]
d53a44403ca92405f5aa28b67264f7e5f1199c5c
948
cpp
C++
atcoder.jp/abc121/abc121_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc121/abc121_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc121/abc121_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i) #define reps(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i) #define rrep(i, n) for (int i = ((int)(n)-1); i >= 0; --i) #define rreps(i, n) for (int i = ((int)(n)); i > 0; --i) #define all(x) (x).begin(), (x).end() #define sz(x) ((int)(x).size()) void solve() { int n, m, c; cin >> n >> m >> c; vector<int> a(m), b(m); for (int i = 0; i < m; i++) { cin >> b[i]; } int cnt = 0; for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < m; j++) { cin >> a[j]; sum += a[j] * b[j]; } if(sum + c > 0){ cnt++; } } cout << cnt << endl; } signed main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); cout << fixed << setprecision(15); solve(); return 0; }
22.571429
68
0.433544
[ "vector" ]
d53a9d31e60cb1a92afe0ef01c44bbef415b5d34
10,339
cpp
C++
Gems/Atom/RHI/Code/Tests/ImagePropertyTests.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RHI/Code/Tests/ImagePropertyTests.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RHI/Code/Tests/ImagePropertyTests.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "RHITestFixture.h" #include <Atom/RHI/ImageProperty.h> namespace UnitTest { using namespace AZ; class ImagePropertyTests : public RHITestFixture { public: ImagePropertyTests() : RHITestFixture() {} void SetUp() override { RHITestFixture::SetUp(); m_imageDescriptor.m_arraySize = 10; m_imageDescriptor.m_mipLevels = 5; m_imageDescriptor.m_format = RHI::Format::D32_FLOAT_S8X24_UINT; } protected: RHI::ImageProperty<int> m_property; RHI::ImageDescriptor m_imageDescriptor; }; TEST_F(ImagePropertyTests, TestNoop) { RHI::ImageProperty<double> noopProp; } TEST_F(ImagePropertyTests, TestInitialization) { EXPECT_FALSE(m_property.IsInitialized()); m_property.Init(m_imageDescriptor); EXPECT_TRUE(m_property.IsInitialized()); } TEST_F(ImagePropertyTests, TesNoInit) { EXPECT_FALSE(m_property.IsInitialized()); auto range = RHI::ImageSubresourceRange(m_imageDescriptor); AZ_TEST_START_TRACE_SUPPRESSION; m_property.Set(range, 1337); auto overlapInterval = m_property.Get(range); AZ_TEST_STOP_TRACE_SUPPRESSION(2); } TEST_F(ImagePropertyTests, TestFullRange) { auto range = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); m_property.Set(range, 1337); auto overlapInterval = m_property.Get(range); EXPECT_EQ(overlapInterval.size(), 1); const auto& resultRange = overlapInterval.front(); EXPECT_EQ(resultRange.m_range, range); EXPECT_EQ(resultRange.m_property, 1337); } TEST_F(ImagePropertyTests, TestFullRangeOver) { auto range = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); m_property.Set(range, 1337); auto newRange = range; newRange.m_arraySliceMax += 10; newRange.m_mipSliceMax += 10; auto overlapInterval = m_property.Get(newRange); EXPECT_EQ(overlapInterval.size(), 1); const auto& resultRange = overlapInterval.front(); EXPECT_EQ(resultRange.m_range, range); EXPECT_EQ(resultRange.m_property, 1337); } TEST_F(ImagePropertyTests, TestPartialRange) { auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); auto range = fullRange; range.m_mipSliceMax -= 1; m_property.Set(range, 1337); auto overlapInterval = m_property.Get(fullRange); EXPECT_EQ(overlapInterval.size(), 1); const auto& resultRange = overlapInterval.front(); EXPECT_EQ(resultRange.m_range, range); EXPECT_EQ(resultRange.m_property, 1337); } TEST_F(ImagePropertyTests, TestPerArrayRange) { auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); m_property.Set(fullRange, 1337); auto range = fullRange; range.m_arraySliceMax -= 1; auto overlapInterval = m_property.Get(range); EXPECT_EQ(overlapInterval.size(), m_imageDescriptor.m_mipLevels); for (uint16_t i = 0; i < overlapInterval.size(); ++i) { RHI::ImageSubresourceRange mipRange = range; mipRange.m_mipSliceMin = i; mipRange.m_mipSliceMax = i; const auto& intervalProperty = overlapInterval[i]; EXPECT_EQ(intervalProperty.m_property, 1337); EXPECT_EQ(intervalProperty.m_range, mipRange); } } TEST_F(ImagePropertyTests, TestMerge) { m_property.Init(m_imageDescriptor); auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); auto range1 = fullRange; range1.m_mipSliceMax = range1.m_mipSliceMax / 2; m_property.Set(range1, 1337); auto range2 = fullRange; range2.m_mipSliceMin = range1.m_mipSliceMax + 1; m_property.Set(range2, 1337); auto overlapInterval = m_property.Get(fullRange); EXPECT_EQ(overlapInterval.size(), 1); const auto& resultRange = overlapInterval.front(); EXPECT_EQ(resultRange.m_range, fullRange); EXPECT_EQ(resultRange.m_property, 1337); } TEST_F(ImagePropertyTests, TestNoMergeDifferentProperty) { m_property.Init(m_imageDescriptor); auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); auto range1 = fullRange; range1.m_mipSliceMax = range1.m_mipSliceMax / 2; m_property.Set(range1, 1337); auto range2 = fullRange; range2.m_mipSliceMin = range1.m_mipSliceMax + 1; m_property.Set(range2, 1338); auto overlapInterval = m_property.Get(fullRange); EXPECT_EQ(overlapInterval.size(), 2); const auto& resultRange1 = overlapInterval.front(); EXPECT_EQ(resultRange1.m_range, range1); EXPECT_EQ(resultRange1.m_property, 1337); const auto& resultRange2 = overlapInterval.back(); EXPECT_EQ(resultRange2.m_range, range2); EXPECT_EQ(resultRange2.m_property, 1338); } TEST_F(ImagePropertyTests, TestNoMergeNoContinous) { m_property.Init(m_imageDescriptor); auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); auto range1 = fullRange; range1.m_mipSliceMax = range1.m_mipSliceMax / 2; m_property.Set(range1, 1337); auto range2 = fullRange; range2.m_mipSliceMin = range1.m_mipSliceMax + 2; m_property.Set(range2, 1337); auto overlapInterval = m_property.Get(fullRange); EXPECT_EQ(overlapInterval.size(), 2); const auto& resultRange1 = overlapInterval.front(); EXPECT_EQ(resultRange1.m_range, range1); EXPECT_EQ(resultRange1.m_property, 1337); const auto& resultRange2 = overlapInterval.back(); EXPECT_EQ(resultRange2.m_range, range2); EXPECT_EQ(resultRange2.m_property, 1337); } TEST_F(ImagePropertyTests, TestPartialRangeImageAspect) { auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); m_property.Set(fullRange, 1337); auto range = fullRange; range.m_aspectFlags = RHI::ResetBits(range.m_aspectFlags, RHI::ImageAspectFlags::Depth); auto overlapInterval = m_property.Get(range); EXPECT_EQ(overlapInterval.size(), 1); const auto& resultRange = overlapInterval.front(); EXPECT_EQ(resultRange.m_range, range); EXPECT_EQ(resultRange.m_property, 1337); } TEST_F(ImagePropertyTests, TestNoOverlap) { auto range1 = RHI::ImageSubresourceRange(m_imageDescriptor); range1.m_mipSliceMin = m_imageDescriptor.m_mipLevels / 2; range1.m_mipSliceMax = m_imageDescriptor.m_mipLevels - 1; m_property.Init(m_imageDescriptor); m_property.Set(range1, 1337); auto range2 = range1; range2.m_mipSliceMin = 0; range2.m_mipSliceMax = range1.m_mipSliceMin - 1; auto overlapInterval = m_property.Get(range2); EXPECT_TRUE(overlapInterval.empty()); } TEST_F(ImagePropertyTests, TestNoOverlapImageAspect) { auto range = RHI::ImageSubresourceRange(m_imageDescriptor); range.m_aspectFlags = RHI::ImageAspectFlags::Depth; m_property.Init(m_imageDescriptor); m_property.Set(range, 1337); range.m_aspectFlags = RHI::ImageAspectFlags::Stencil; auto overlapInterval = m_property.Get(range); EXPECT_TRUE(overlapInterval.empty()); } TEST_F(ImagePropertyTests, TestMergeDifferentProperty) { auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); m_property.Set(fullRange, 1337); auto range1 = fullRange; range1.m_mipSliceMax = fullRange.m_mipSliceMax / 2; m_property.Set(range1, 1338); auto range2 = fullRange; range2.m_mipSliceMin = range1.m_mipSliceMax + 1; m_property.Set(range2, 1338); auto overlapInterval = m_property.Get(fullRange); EXPECT_EQ(overlapInterval.size(), 1); const auto& resultRange = overlapInterval.front(); EXPECT_EQ(resultRange.m_range, fullRange); EXPECT_EQ(resultRange.m_property, 1338); } TEST_F(ImagePropertyTests, TestPartialMergeDifferentProperty) { auto fullRange = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); m_property.Set(fullRange, 1337); auto range1 = fullRange; range1.m_mipSliceMax = 1; m_property.Set(range1, 1338); auto range2 = fullRange; range2.m_mipSliceMin = fullRange.m_mipSliceMax - 1; m_property.Set(range2, 1338); auto newRange = fullRange; newRange.m_mipSliceMin = range1.m_mipSliceMax + 1; newRange.m_mipSliceMax = range2.m_mipSliceMin - 1; auto overlapInterval = m_property.Get(fullRange); EXPECT_EQ(overlapInterval.size(), 3); const auto& resultRange1 = overlapInterval[0]; const auto& resultRange2 = overlapInterval[1]; const auto& resultRange3 = overlapInterval[2]; EXPECT_EQ(resultRange1.m_range, range1); EXPECT_EQ(resultRange1.m_property, 1338); EXPECT_EQ(resultRange2.m_range, newRange); EXPECT_EQ(resultRange2.m_property, 1337); EXPECT_EQ(resultRange3.m_range, range2); EXPECT_EQ(resultRange3.m_property, 1338); } TEST_F(ImagePropertyTests, TestReset) { auto range = RHI::ImageSubresourceRange(m_imageDescriptor); m_property.Init(m_imageDescriptor); m_property.Set(range, 1337); auto overlapInterval = m_property.Get(range); EXPECT_FALSE(overlapInterval.empty()); m_property.Reset(); overlapInterval = m_property.Get(range); EXPECT_TRUE(overlapInterval.empty()); } }
35.286689
100
0.667666
[ "3d" ]
d53dd725fea35ddcdd5936cae301af8aaef907a4
64,889
cpp
C++
hphp/runtime/vm/jit/vasm-arm.cpp
kkopachev/hhvm
a9f242ec029c37b1e9d1715b13661e66293d87ab
[ "PHP-3.01", "Zend-2.0" ]
1
2021-06-19T23:31:58.000Z
2021-06-19T23:31:58.000Z
hphp/runtime/vm/jit/vasm-arm.cpp
kkopachev/hhvm
a9f242ec029c37b1e9d1715b13661e66293d87ab
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/jit/vasm-arm.cpp
kkopachev/hhvm
a9f242ec029c37b1e9d1715b13661e66293d87ab
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ /* * The HHVM's ARM64 backend works with an early-truncation policy. * That means that: * * A Vreg8 is an extended W-register with a u8 value. * A Vreg16 is an extended W-register with a u16 value. * A Vreg32 is a W-register with a u32 value. * A Vreg64 is a X-register with a u64 value. * * This allows to omit truncation instructions for sub-32-bit * operations. E.g. a testb{Vreg8 s0, Vreg8 s1} has to truncate * s0 and s1 before emitting a tst instruction. When using the * early-truncation policy, the testb{} emitter can rely on the * fact, that s0 and s1 are already truncated and can emit a * cmp instruction without preceding uxtb's. * * Conversely any arithmetic instruction has to sign extend any * Vreg8 before operating on it. Vasm is light on these instructions, * with only the following, currently: csinc[bw]{} and cmp[bw][i]{}. * * Early-truncation has also consequences to extension/truncation * vasm instructions. The following list shows how to use them: * * movzbw: Vreg8 -> Vreg16: mov w0, w0 #nop if s==d * movzbl: Vreg8 -> Vreg32: mov w0, w0 #nop if s==d * movzbq: Vreg8 -> Vreg64: uxtb x0, x0 * movzwl: Vreg16 -> Vreg32 mov w0, w0 #nop if s==d * movzwq: Vreg16 -> Vreg64 uxth x0, x0 * movzlq: Vreg32 -> Vreg64 uxtw x0, x0 * movtqb: Vreg64 -> Vreg8: uxtb w0, w0 * movtql: Vreg64 -> Vreg32: uxtw w0, w0 * * Early-truncation also implies, that instructions have to truncate * after performing the actual operation if it cannot guarantee that * the resulting VregN type matches. E.g. emitting code for the vasm * instruction andbi{Immed imm, Vreg8 s, Vreg8 d} has to truncate the * result to guarantee that register d indeed holds a u8 value. * * Note, that the early-truncation policy allows aarch64 specific * optimizations, which are not relevant on other architectures. * E.g. the x86_64 does not need this policy as the ISA allows * direct register accesses for Vreg8, Vreg16, Vreg32 and Vreg64 * (e.g. AL, AX, EAX, RAX). * * The early-truncation policy relies on the following * requirements of the Vreg type-system: * * * All VregNs are created for values of up to N bits * * All conversions between VregNs are done via movz/movt vasm instructions */ #include "hphp/runtime/vm/jit/vasm-emit.h" #include "hphp/runtime/vm/jit/abi-arm.h" #include "hphp/runtime/vm/jit/ir-instruction.h" #include "hphp/runtime/vm/jit/print.h" #include "hphp/runtime/vm/jit/service-requests.h" #include "hphp/runtime/vm/jit/smashable-instr-arm.h" #include "hphp/runtime/vm/jit/timer.h" #include "hphp/runtime/vm/jit/vasm-gen.h" #include "hphp/runtime/vm/jit/vasm.h" #include "hphp/runtime/vm/jit/vasm-instr.h" #include "hphp/runtime/vm/jit/vasm-internal.h" #include "hphp/runtime/vm/jit/vasm-lower.h" #include "hphp/runtime/vm/jit/vasm-print.h" #include "hphp/runtime/vm/jit/vasm-reg.h" #include "hphp/runtime/vm/jit/vasm-unit.h" #include "hphp/runtime/vm/jit/vasm-util.h" #include "hphp/runtime/vm/jit/vasm-visit.h" #include "hphp/vixl/a64/macro-assembler-a64.h" TRACE_SET_MOD(vasm); namespace HPHP { namespace jit { /////////////////////////////////////////////////////////////////////////////// using namespace arm; using namespace vixl; namespace arm { struct ImmFolder; } namespace { /////////////////////////////////////////////////////////////////////////////// static_assert(folly::kIsLittleEndian, "Code contains little-endian specific optimizations."); vixl::Register X(Vreg64 r) { PhysReg pr(r.asReg()); return x2a(pr); } vixl::Register W(Vreg64 r) { PhysReg pr(r.asReg()); return x2a(pr).W(); } vixl::Register W(Vreg32 r) { PhysReg pr(r.asReg()); return x2a(pr).W(); } vixl::Register W(Vreg16 r) { PhysReg pr(r.asReg()); return x2a(pr).W(); } vixl::Register W(Vreg8 r) { PhysReg pr(r.asReg()); return x2a(pr).W(); } vixl::FPRegister D(Vreg r) { return x2f(r); } vixl::VRegister V(Vreg r) { return x2v(r); } uint8_t Log2(uint8_t value) { switch (value) { case 1: return 0; case 2: return 1; case 4: return 2; case 8: return 3; default: always_assert(false); } } vixl::MemOperand M(Vptr p) { assertx(p.base.isValid()); if (p.index.isValid()) { assertx(p.disp == 0); return MemOperand(X(p.base), X(p.index), LSL, Log2(p.scale)); } return MemOperand(X(p.base), p.disp); } vixl::Condition C(ConditionCode cc) { return arm::convertCC(cc); } /* * Uses the flags from the Vinstr which defs SF to determine * whether or not the Vixl assembler should emit code which * sets the status flags. */ vixl::FlagsUpdate UF(Vflags flags) { return flags ? SetFlags : LeaveFlags; } /* * There are numerous ARM instructions that don't set status flags, and * therefore those flags must be set synthetically in the emitters. This * assertion is applied to the emitters which don't set all of the status * flags required by the Vinstr which defs SF. The flags field of the * Vinstr is used to determine which bits are required. Those required * bits are compared against the bits which are actually set by the * implementation. */ template<class Inst> void checkSF(const Inst& i, StatusFlags s) { Vflags required = i.fl; Vflags set = static_cast<Vflags>(s); always_assert_flog((required & set) == required, "should def SF but does not: {}\n", vinst_names[Vinstr(i).op]); } template<class Inst> void checkSF(const Inst& i) { checkSF(i, StatusFlags::None); } /* * Returns true if the queried flag(s) is in the set of required flags. */ bool flagRequired(Vflags flags, StatusFlags flag) { return (flags & static_cast<Vflags>(flag)); } /////////////////////////////////////////////////////////////////////////////// struct Vgen { explicit Vgen(Venv& env) : env(env) , assem(*env.cb) , a(&assem) , base(a->frontier()) , current(env.current) , next(env.next) , jmps(env.jmps) , jccs(env.jccs) , catches(env.catches) {} ~Vgen() { env.cb->sync(base); } static void emitVeneers(Venv& env); static void handleLiterals(Venv& env); static void patch(Venv& env); static void pad(CodeBlock& cb) { vixl::MacroAssembler a { cb }; auto const begin = cb.frontier(); while (cb.available() >= 4) a.Brk(1); assertx(cb.available() == 0); cb.sync(begin); } ///////////////////////////////////////////////////////////////////////////// template<class Inst> void emit(const Inst& i) { always_assert_flog(false, "unimplemented instruction: {} in B{}\n", vinst_names[Vinstr(i).op], size_t(current)); } // intrinsics void emit(const copy& i); void emit(const copy2& i); void emit(const debugtrap& /*i*/) { a->Brk(0); } void emit(const fallthru& /*i*/); void emit(const ldimmb& i); void emit(const ldimml& i); void emit(const ldimmq& i); void emit(const ldimmw& i); void emit(const load& i); void emit(const store& i); void emit(const mcprep& i); // native function abi void emit(const call& i); void emit(const callr& i) { a->Blr(X(i.target)); } void emit(const calls& i); void emit(const ret& /*i*/) { a->Ret(); } // stub function abi void emit(const callstub& i); void emit(const callfaststub& i); // php function abi void emit(const callunpack& i); void emit(const contenter& i); void emit(const phpret& i); // vm entry abi void emit(const calltc& i); void emit(const inittc& /*i*/) {} void emit(const leavetc& i); // exceptions void emit(const landingpad& /*i*/) {} void emit(const nothrow& i); void emit(const syncpoint& i); void emit(const unwind& i); // instructions void emit(const absdbl& i) { a->Fabs(D(i.d), D(i.s)); } void emit(const addl& i) { a->Add(W(i.d), W(i.s1), W(i.s0), UF(i.fl)); } void emit(const addli& i) { a->Add(W(i.d), W(i.s1), i.s0.l(), UF(i.fl)); } void emit(const addq& i) { a->Add(X(i.d), X(i.s1), X(i.s0), UF(i.fl));} void emit(const addqi& i) { a->Add(X(i.d), X(i.s1), i.s0.q(), UF(i.fl)); } void emit(const addsd& i) { a->Fadd(D(i.d), D(i.s1), D(i.s0)); } void emit(const andb& i) { a->And(W(i.d), W(i.s1), W(i.s0), UF(i.fl)); } void emit(const andbi& i) { a->And(W(i.d), W(i.s1), i.s0.ub(), UF(i.fl)); } void emit(const andl& i) { a->And(W(i.d), W(i.s1), W(i.s0), UF(i.fl)); } void emit(const andli& i) { a->And(W(i.d), W(i.s1), i.s0.l(), UF(i.fl)); } void emit(const andq& i) { a->And(X(i.d), X(i.s1), X(i.s0), UF(i.fl)); } void emit(const andqi& i) { a->And(X(i.d), X(i.s1), i.s0.q(), UF(i.fl)); } void emit(const andqi64& i) { a->And(X(i.d), X(i.s1), i.s0.q(), UF(i.fl)); } void emit(const cmovb& i) { a->Csel(W(i.d), W(i.t), W(i.f), C(i.cc)); } void emit(const cmovw& i) { a->Csel(W(i.d), W(i.t), W(i.f), C(i.cc)); } void emit(const cmovl& i) { a->Csel(W(i.d), W(i.t), W(i.f), C(i.cc)); } void emit(const cmovq& i) { a->Csel(X(i.d), X(i.t), X(i.f), C(i.cc)); } // note: cmp{bw}[i] are emitted only for narrow comparisons and _do not_ sign // extend their arguments--these instructions are lowered to cmp{lq}[i] if // the comparison is not narrow or not equality/inequality void emit(const cmpb& i) { a->Cmp(W(i.s1), W(i.s0)); } void emit(const cmpbi& i) { a->Cmp(W(i.s1), static_cast<uint8_t>(i.s0.b())); } void emit(const cmpw& i) { a->Cmp(W(i.s1), W(i.s0)); } void emit(const cmpwi& i) { a->Cmp(W(i.s1), static_cast<uint16_t>(i.s0.w())); } void emit(const cmpl& i) { a->Cmp(W(i.s1), W(i.s0)); } void emit(const cmpli& i) { a->Cmp(W(i.s1), i.s0.l()); } void emit(const cmpq& i) { a->Cmp(X(i.s1), X(i.s0)); } void emit(const cmpqi& i) { a->Cmp(X(i.s1), i.s0.q()); } void emit(const cmpsd& i); // TODO(CDE): csinc[bw]{} Should a) sign extend and b) set SF for overflow void emit(const csincb& i) { a->Csinc(W(i.d), W(i.t), W(i.f), C(i.cc)); } void emit(const csincw& i) { a->Csinc(W(i.d), W(i.t), W(i.f), C(i.cc)); } void emit(const csincl& i) { a->Csinc(W(i.d), W(i.t), W(i.f), C(i.cc)); } void emit(const csincq& i) { a->Csinc(X(i.d), X(i.t), X(i.f), C(i.cc)); } void emit(const cvtsi2sd& i) { a->Scvtf(D(i.d), X(i.s)); } void emit(const decl& i) { a->Sub(W(i.d), W(i.s), 1, UF(i.fl)); } void emit(const decq& i) { a->Sub(X(i.d), X(i.s), 1, UF(i.fl)); } void emit(const decqmlock& i); void emit(const divint& i) { a->Sdiv(X(i.d), X(i.s0), X(i.s1)); } void emit(const divsd& i) { a->Fdiv(D(i.d), D(i.s1), D(i.s0)); } void emit(const imul& i); void emit(const incl& i) { a->Add(W(i.d), W(i.s), 1, UF(i.fl)); } void emit(const incq& i) { a->Add(X(i.d), X(i.s), 1, UF(i.fl)); } void emit(const incw& i) { a->Add(W(i.d), W(i.s), 1, UF(i.fl)); } void emit(const jcc& i); void emit(const jcci& i); void emit(const jmp& i); void emit(const jmpi& i); void emit(const jmpr& i) { a->Br(X(i.target)); } void emit(const lea& i); void emit(const leap& i); void emit(const lead& i); void emit(const loadb& i) { a->Ldrb(W(i.d), M(i.s)); } void emit(const loadl& i) { a->Ldr(W(i.d), M(i.s)); } void emit(const loadsd& i) { a->Ldr(D(i.d), M(i.s)); } void emit(const loadtqb& i) { a->Ldrb(W(i.d), M(i.s)); } void emit(const loadtql& i) { a->Ldr(W(i.d), M(i.s)); } void emit(const loadups& i); void emit(const loadw& i) { a->Ldrh(W(i.d), M(i.s)); } void emit(const loadzbl& i) { a->Ldrb(W(i.d), M(i.s)); } void emit(const loadzbq& i) { a->Ldrb(W(i.d), M(i.s)); } void emit(const loadsbq& i) { a->Ldrsb(X(i.d), M(i.s)); } void emit(const loadsbl& i) { a->Ldrsb(W(i.d), M(i.s)); } void emit(const loadzlq& i) { a->Ldr(W(i.d), M(i.s)); } void emit(const movb& i) { if (i.d != i.s) a->Mov(W(i.d), W(i.s)); } void emit(const movw& i) { if (i.d != i.s) a->Mov(W(i.d), W(i.s)); } void emit(const movl& i) { if (i.d != i.s) a->Mov(W(i.d), W(i.s)); } void emit(const movsbl& i) { a->Sxtb(W(i.d), W(i.s)); } void emit(const movsbq& i) { a->Sxtb(X(i.d), W(i.s).X()); } void emit(const movswl& i) { a->Sxth(W(i.d), W(i.s)); } void emit(const movtqb& i) { a->Uxtb(W(i.d), W(i.s)); } void emit(const movtqw& i) { a->Uxth(W(i.d), W(i.s)); } void emit(const movtql& i) { a->Uxtw(W(i.d), W(i.s)); } void emit(const movzbq& i) { a->Uxtb(X(i.d), W(i.s).X()); } void emit(const movzwq& i) { a->Uxth(X(i.d), W(i.s).X()); } void emit(const movzlq& i) { a->Uxtw(X(i.d), W(i.s).X()); } void emit(const mulsd& i) { a->Fmul(D(i.d), D(i.s1), D(i.s0)); } void emit(const neg& i) { a->Neg(X(i.d), X(i.s), UF(i.fl)); } void emit(const nop& /*i*/) { a->Nop(); } void emit(const notb& i) { a->Mvn(W(i.d), W(i.s)); } void emit(const not& i) { a->Mvn(X(i.d), X(i.s)); } void emit(const orq& i); void emit(const orqi& i); void emit(const pop& i); void emit(const popp& i); void emit(const push& i); void emit(const pushp& i); void emit(const roundsd& i); void emit(const sar& i); void emit(const sarqi& i); void emit(const setcc& i) { a->Cset(W(i.d), C(i.cc)); } void emit(const shl& i); void emit(const shlli& i); void emit(const shlqi& i); void emit(const shrli& i); void emit(const shrqi& i); void emit(const sqrtsd& i) { a->Fsqrt(D(i.d), D(i.s)); } void emit(const srem& i); void emit(const storeb& i) { a->Strb(W(i.s), M(i.m)); } void emit(const storel& i) { a->Str(W(i.s), M(i.m)); } void emit(const storesd& i) { emit(store{i.s, i.m}); } void emit(const storeups& i); void emit(const storew& i) { a->Strh(W(i.s), M(i.m)); } void emit(const subl& i) { a->Sub(W(i.d), W(i.s1), W(i.s0), UF(i.fl)); } void emit(const subli& i) { a->Sub(W(i.d), W(i.s1), i.s0.l(), UF(i.fl)); } void emit(const subq& i) { a->Sub(X(i.d), X(i.s1), X(i.s0), UF(i.fl)); } void emit(const subqi& i) { a->Sub(X(i.d), X(i.s1), i.s0.q(), UF(i.fl)); } void emit(const subsd& i) { a->Fsub(D(i.d), D(i.s1), D(i.s0)); } void emit(const testb& i){ a->Tst(W(i.s1), W(i.s0)); } void emit(const testbi& i){ a->Tst(W(i.s1), i.s0.ub()); } void emit(const testw& i){ a->Tst(W(i.s1), W(i.s0)); } void emit(const testwi& i){ a->Tst(W(i.s1), i.s0.uw()); } void emit(const testl& i) { a->Tst(W(i.s1), W(i.s0)); } void emit(const testli& i) { a->Tst(W(i.s1), i.s0.l()); } void emit(const testq& i) { a->Tst(X(i.s1), X(i.s0)); } void emit(const testqi& i) { a->Tst(X(i.s1), i.s0.q()); } void emit(const trap& /*i*/); void emit(const ucomisd& i) { a->Fcmp(D(i.s0), D(i.s1)); } void emit(const unpcklpd&); void emit(const xorb& i); void emit(const xorbi& i); void emit(const xorl& i); void emit(const xorq& i); void emit(const xorqi& i); // arm intrinsics void emit(const fcvtzs& i) { a->Fcvtzs(X(i.d), D(i.s)); } void emit(const mrs& i) { a->Mrs(X(i.r), vixl::SystemRegister(i.s.l())); } void emit(const msr& i) { a->Msr(vixl::SystemRegister(i.s.l()), X(i.r)); } void emit(const ubfmli& i) { a->ubfm(W(i.d), W(i.s), i.mr.w(), i.ms.w()); } void emit_nop() { a->Nop(); } private: CodeBlock& frozen() { return env.text.frozen().code; } static void recordAddressImmediate(Venv& env, TCA addr) { env.meta.addressImmediates.insert(addr); } void recordAddressImmediate() { env.meta.addressImmediates.insert(env.cb->frontier()); } private: Venv& env; vixl::MacroAssembler assem; vixl::MacroAssembler* a; Address base; const Vlabel current; const Vlabel next; jit::vector<Venv::LabelPatch>& jmps; jit::vector<Venv::LabelPatch>& jccs; jit::vector<Venv::LabelPatch>& catches; }; /////////////////////////////////////////////////////////////////////////////// static CodeBlock* getBlock(Venv& env, CodeAddress a) { for (auto const& area : env.text.areas()) { if (area.code.contains(a)) { return &area.code; } } return nullptr; } static CodeAddress toReal(Venv& env, CodeAddress a) { CodeBlock* b = getBlock(env, a); return (b == nullptr) ? a : b->toDestAddress(a); } void Vgen::emitVeneers(Venv& env) { auto& meta = env.meta; decltype(env.meta.veneers) notEmitted; for (auto const& veneer : meta.veneers) { auto cb = getBlock(env, veneer.source); if (!cb) { // If we can't find the code block, it must have been emitted by a Vunit // wrapping this one (retransopt emits a Vunit within a Vunit). notEmitted.push_back(veneer); continue; } auto const vaddr = cb->frontier(); FTRACE(1, "emitVeneers: source = {}, target = {}, veneer at {}\n", veneer.source, veneer.target, vaddr); // Emit the veneer code: LDR + BR. meta.veneerAddrs.insert(vaddr); MacroAssembler av{*cb}; vixl::Label target_data; meta.addressImmediates.insert(vaddr); poolLiteral(*cb, meta, (uint64_t)makeTarget32(veneer.target), 32, true); av.bind(&target_data); av.Ldr(rAsm_w, &target_data); av.Br(rAsm); // Update the veneer source instruction to jump/call the veneer. auto const realSource = toReal(env, veneer.source); CodeBlock tmpBlock; tmpBlock.init(realSource, kInstructionSize, "emitVeneers"); MacroAssembler at{tmpBlock}; int64_t offset = vaddr - veneer.source; auto sourceInst = Instruction::Cast(realSource); if (sourceInst->Mask(UnconditionalBranchMask) == B) { always_assert(is_int28(offset)); at.b(offset >> kInstructionSizeLog2); } else if (sourceInst->Mask(UnconditionalBranchMask) == BL) { always_assert(is_int28(offset)); at.bl(offset >> kInstructionSizeLog2); } else if (sourceInst->IsCondBranchImm()) { auto const cond = static_cast<Condition>(sourceInst->ConditionBranch()); if (is_int21(offset)) { at.b(offset >> kInstructionSizeLog2, cond); } else { // The offset doesn't fit in a conditional jump. Hopefully it still fits // in an unconditional jump, in which case we add an appendix to the // veneer. offset += 2 * kInstructionSize; always_assert(is_int28(offset)); // Add an appendix to the veneer, and jump to it instead. The full // veneer in this case looks like: // VENEER: // LDR RX, LITERAL_ADDR // BR RX // APPENDIX: // B.CC VENEER // B NEXT // And the conditional jump into the veneer is turned into a jump to the // appendix: // B APPENDIX // NEXT: // Turn the original conditional branch into an unconditional one. at.b(offset >> kInstructionSizeLog2); // Emit appendix. auto const appendix = cb->frontier(); av.b(-2 /* veneer starts 2 instructions before the appendix */, cond); const int64_t nextOffset = (veneer.source + kInstructionSize) - // NEXT (vaddr + 3 * kInstructionSize); // addr of "B NEXT" always_assert(is_int28(nextOffset)); av.b(nextOffset >> kInstructionSizeLog2); // Replace veneer.source with appendix in the relevant metadata. meta.smashableLocations.erase(veneer.source); meta.smashableLocations.insert(appendix); for (auto& tj : meta.inProgressTailJumps) { if (tj.toSmash() == veneer.source) tj.adjust(appendix); } for (auto& stub : env.stubs) { if (stub.jcc == veneer.source) stub.jcc = appendix; } } } else { always_assert_flog(0, "emitVeneers: invalid source instruction at source" " {} (realSource = {})", veneer.source, realSource); } } env.meta.veneers.swap(notEmitted); } void Vgen::handleLiterals(Venv& env) { decltype(env.meta.literalsToPool) notEmitted; for (auto const& pl : env.meta.literalsToPool) { auto const cb = getBlock(env, pl.patchAddress); if (!cb) { // If we can't find the code block it must have been emitted by a Vunit // wrapping this one. (retransopt emits a Vunit within a Vunit) notEmitted.push_back(pl); continue; } // Emit the literal. auto literalAddress = cb->frontier(); if (pl.width == 32) { cb->dword(static_cast<uint32_t>(pl.value)); } else if (pl.width == 64) { if (pl.smashable) { // Although the region is actually dead, we mark it as live, so that // the relocator can remove the padding. align(*cb, &env.meta, Alignment::QuadWordSmashable, AlignContext::Live); literalAddress = cb->frontier(); } cb->qword(pl.value); } else { not_reached(); } // Patch the LDR. auto const patchAddressActual = Instruction::Cast(toReal(env, pl.patchAddress)); assertx(patchAddressActual->IsLoadLiteral()); patchAddressActual->SetImmPCOffsetTarget( Instruction::Cast(literalAddress), Instruction::Cast(pl.patchAddress)); } if (env.meta.fallthru) { auto const fallthru = *env.meta.fallthru; auto const cb = getBlock(env, fallthru); if (!cb) { always_assert_flog(false, "Fallthrus shouldn't be used in nested Vunits."); } auto const blockEndAddr = cb->frontier(); auto const startAddr = cb->toDestAddress(fallthru); CodeBlock tmp; tmp.init(startAddr, kInstructionSize, "Tmp"); // Write the jmp. Assembler a { tmp }; recordAddressImmediate(env, fallthru); a.b((blockEndAddr - fallthru) >> kInstructionSizeLog2); } env.meta.literalsToPool.swap(notEmitted); } void Vgen::patch(Venv& env) { // Patch the 32 bit target of the LDR auto patch = [&env](TCA instr, TCA target) { // The LDR loading the address to branch to. auto ldr = Instruction::Cast(instr); auto const DEBUG_ONLY br = ldr->NextInstruction(); assertx(ldr->Mask(LoadLiteralMask) == LDR_w_lit && br->Mask(UnconditionalBranchToRegisterMask) == BR && ldr->Rd() == br->Rn()); // The address the LDR loads. auto targetAddr = ldr->LiteralAddress(); // Patch the 32 bit target following the LDR and BR patchTarget32(targetAddr, target); }; for (auto& p : env.jmps) { auto addr = toReal(env, p.instr); auto const target = env.addrs[p.target]; assertx(target); if (env.meta.smashableLocations.count(p.instr)) { assertx(possiblySmashableJmp(addr)); // Update `addr' to point to the veneer. addr = TCA(vixl::Instruction::Cast(addr)->ImmPCOffsetTarget()); } // Patch the address we are jumping to. patch(addr, target); } for (auto& p : env.jccs) { auto addr = toReal(env, p.instr); auto const target = env.addrs[p.target]; assertx(target); if (env.meta.smashableLocations.count(p.instr)) { assertx(possiblySmashableJcc(addr)); // Update `addr' to point to the veneer. addr = TCA(vixl::Instruction::Cast(addr)->ImmPCOffsetTarget()); } else { assertx(Instruction::Cast(addr)->IsCondBranchImm()); // If the jcc starts with a conditional jump, patch the next instruction // (which should start with a LDR). addr += kInstructionSize; } patch(addr, target); } } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const copy& i) { if (i.s == i.d) return; if (i.s.isGP() && i.d.isGP()) { a->Mov(X(i.d), X(i.s)); } else if (i.s.isSIMD() && i.d.isGP()) { a->Fmov(X(i.d), D(i.s)); } else if (i.s.isGP() && i.d.isSIMD()) { a->Fmov(D(i.d), X(i.s)); } else { assertx(i.s.isSIMD() && i.d.isSIMD()); a->mov(V(i.d), V(i.s)); } } void Vgen::emit(const copy2& i) { assertx(i.s0.isValid() && i.s1.isValid() && i.d0.isValid() && i.d1.isValid()); auto s0 = i.s0, s1 = i.s1, d0 = i.d0, d1 = i.d1; assertx(d0 != d1); if (d0 == s1) { if (d1 == s0) { a->Eor(X(d0), X(d0), X(s0)); a->Eor(X(s0), X(d0), X(s0)); a->Eor(X(d0), X(d0), X(s0)); } else { // could do this in a simplify pass if (s1 != d1) a->Mov(X(s1), X(d1)); // save s1 first; d1 != s0 if (s0 != d0) a->Mov(X(s0), X(d0)); } } else { // could do this in a simplify pass if (s0 != d0) a->Mov(X(s0), X(d0)); if (s1 != d1) a->Mov(X(s1), X(d1)); } } void emitSimdImmInt(vixl::MacroAssembler* a, uint64_t val, Vreg d) { // Assembler::fmov emits a ldr from a literal pool if IsImmFP64 is false. // In that case, emit the raw bits into a GPR first and then move them // unmodified into destination SIMD union { double dval; uint64_t ival; }; ival = val; if (vixl::Assembler::IsImmFP64(dval)) { a->Fmov(D(d), dval); } else if (ival == 0) { a->Fmov(D(d), vixl::xzr); } else { a->Mov(rAsm, ival); a->Fmov(D(d), rAsm); } } void Vgen::emit(const fallthru& /*i*/) { always_assert(!env.meta.fallthru); env.meta.fallthru = a->frontier(); a->nop(); } #define Y(vasm_opc, simd_w, vr_w, gpr_w, imm) \ void Vgen::emit(const vasm_opc& i) { \ if (i.d.isSIMD()) { \ emitSimdImmInt(a, static_cast<uint##vr_w##_t>(i.s.simd_w()), i.d); \ } else { \ Vreg##vr_w d = i.d; \ a->Mov(gpr_w(d), imm); \ } \ } Y(ldimmb, ub, 8, W, i.s.ub()) Y(ldimmw, uw, 16, W, i.s.uw()) Y(ldimml, l, 32, W, i.s.l()) Y(ldimmq, q, 64, X, i.s.q()) #undef Y void Vgen::emit(const load& i) { if (i.d.isGP()) { a->Ldr(X(i.d), M(i.s)); } else { a->Ldr(D(i.d), M(i.s)); } } void Vgen::emit(const store& i) { if (i.s.isGP()) { if (i.s == rsp()) { a->Mov(rAsm, X(i.s)); a->Str(rAsm, M(i.d)); } else { a->Str(X(i.s), M(i.d)); } } else { a->Str(D(i.s), M(i.d)); } } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const mcprep& i) { /* * Initially, we set the cache to hold (addr << 1) | 1 (where `addr' is the * address of the movq) so that we can find the movq from the handler. * * We set the low bit for two reasons: the Class* will never be a valid * Class*, so we'll always miss the inline check before it's smashed, and * handlePrimeCacheInit can tell it's not been smashed yet */ align(*env.cb, &env.meta, Alignment::SmashMovq, AlignContext::Live); auto const imm = reinterpret_cast<uint64_t>(a->frontier()); emitSmashableMovq(*env.cb, env.meta, (imm << 1) | 1, r64(i.d)); env.meta.addressImmediates.insert(reinterpret_cast<TCA>(~imm)); } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const call& i) { recordAddressImmediate(); a->Mov(rAsm, i.target); a->Blr(rAsm); if (i.watch) { *i.watch = a->frontier(); env.meta.watchpoints.push_back(i.watch); } } void Vgen::emit(const calls& i) { emitSmashableCall(*env.cb, env.meta, i.target); } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const callstub& i) { emit(call{i.target, i.args}); } void Vgen::emit(const callfaststub& i) { emit(call{i.target, i.args}); emit(syncpoint{i.fix}); } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const phpret& i) { // prefer load-pair instruction if (!i.noframe) { a->ldp(X(i.d), X(rlr()), X(i.fp)[AROFF(m_sfp)]); } else { a->Ldr(X(rlr()), X(i.fp)[AROFF(m_savedRip)]); } emit(ret{}); } void Vgen::emit(const callunpack& i) { emit(call{i.target, i.args}); } void Vgen::emit(const contenter& i) { vixl::Label stub, end; // Jump past the stub below. recordAddressImmediate(); a->B(&end); // We call into this stub from the end below. Take that LR and store it in // m_savedRip. Then jump to the target. a->bind(&stub); a->Str(X(rlr()), M(i.fp[AROFF(m_savedRip)])); a->Br(X(i.target)); // Call to stub above and then unwind. a->bind(&end); recordAddressImmediate(); a->Bl(&stub); emit(unwind{{i.targets[0], i.targets[1]}}); } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const calltc& i) { vixl::Label stub; // Preserve the LR (exittc) on the stack, pushing twice for SP alignment. recordAddressImmediate(); a->Mov(rAsm, i.exittc); a->Stp(rAsm, rAsm, MemOperand(sp, -16, PreIndex)); // Branch and link to nowhere to balance the LR stack. recordAddressImmediate(); a->bl(&stub); a->bind(&stub); // Load the saved RIP into LR and branch without link. a->Ldr(X(rlr()), M(i.fp[AROFF(m_savedRip)])); a->Br(X(i.target)); } void Vgen::emit(const leavetc& /*i*/) { // The LR was preserved on the stack by calltc above. Pop it while preserving // SP alignment and return. a->Ldp(rAsm, X(rlr()), MemOperand(sp, 16, PostIndex)); a->Ret(); } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const nothrow& /*i*/) { env.meta.catches.emplace_back(a->frontier(), nullptr); env.record_inline_stack(a->frontier()); } void Vgen::emit(const syncpoint& i) { FTRACE(5, "IR recordSyncPoint: {} {} {}\n", a->frontier(), i.fix.pcOffset, i.fix.spOffset); env.meta.fixups.emplace_back(a->frontier(), i.fix); env.record_inline_stack(a->frontier()); } void Vgen::emit(const unwind& i) { catches.push_back({a->frontier(), i.targets[1]}); env.record_inline_stack(a->frontier()); emit(jmp{i.targets[0]}); } /////////////////////////////////////////////////////////////////////////////// /* * Flags * SF should be set to MSB of the result * CF, OF should be set to (1, 1) if the result is truncated, (0, 0) otherwise * ZF, AF, PF are undefined * * In the following implementation, * N, Z, V are updated according to result * C is cleared (FIXME) */ void Vgen::emit(const imul& i) { // Do the multiplication a->Mul(X(i.d), X(i.s0), X(i.s1)); // If we have to set any flags, then always set N and Z since it's cheap. // Only set V when absolutely necessary. C is not supported. if (i.fl) { vixl::Label after; checkSF(i, StatusFlags::NotC); if (flagRequired(i.fl, StatusFlags::V)) { vixl::Label checkSign; vixl::Label Overflow; // Do the multiplication for the upper 64 bits of a 128 bit result. // If the result is not all zeroes or all ones, then we have overflow. // If the result is all zeroes or all ones, and the sign is the same, // for both hi and low, then there is no overflow. a->smulh(rAsm, X(i.s0), X(i.s1)); // If hi is all 0's or 1's, then check the sign, else overflow // (fallthrough). recordAddressImmediate(); a->Cbz(rAsm, &checkSign); a->Cmp(rAsm, -1); recordAddressImmediate(); a->B(&checkSign, vixl::eq); // Overflow, so conditionally set N and Z bits and then or in V bit. a->Bind(&Overflow); a->Bic(vixl::xzr, X(i.d), vixl::xzr, SetFlags); a->Mrs(rAsm, NZCV); a->Orr(rAsm, rAsm, 1<<28); a->Msr(NZCV, rAsm); recordAddressImmediate(); a->B(&after); // Check the signs of hi and lo. a->Bind(&checkSign); a->Eor(rAsm, rAsm, X(i.d)); recordAddressImmediate(); a->Tbnz(rAsm, 63, &Overflow); } // No Overflow, so conditionally set the N and Z only a->Bic(vixl::xzr, X(i.d), vixl::xzr, SetFlags); a->bind(&after); } } void Vgen::emit(const decqmlock& i) { auto adr = M(i.m); /* Use VIXL's macroassembler scratch regs. */ a->SetScratchRegisters(vixl::NoReg, vixl::NoReg); if (RuntimeOption::EvalJitArmLse) { a->Mov(rVixlScratch0, -1); a->ldaddal(rVixlScratch0, rVixlScratch0, adr); a->Sub(rAsm, rVixlScratch0, 1, SetFlags); } else { vixl::Label again; a->bind(&again); a->ldxr(rAsm, adr); a->Sub(rAsm, rAsm, 1, SetFlags); a->stxr(rVixlScratch0, rAsm, adr); recordAddressImmediate(); a->Cbnz(rVixlScratch0, &again); } /* Restore VIXL's scratch regs. */ a->SetScratchRegisters(rVixlScratch0, rVixlScratch1); } void Vgen::emit(const jcc& i) { if (i.targets[1] != i.targets[0]) { if (next == i.targets[1]) { return emit(jcc{ccNegate(i.cc), i.sf, {i.targets[1], i.targets[0]}}); } auto taken = i.targets[1]; jccs.push_back({a->frontier(), taken}); vixl::Label skip, data; // Emit a "far JCC" sequence for easy patching later. Static relocation // might be able to simplify this later (see optimizeFarJcc()). recordAddressImmediate(); a->B(&skip, vixl::InvertCondition(C(i.cc))); recordAddressImmediate(); poolLiteral(*env.cb, env.meta, (uint64_t)makeTarget32(a->frontier()), 32, false); a->bind(&data); // This will be remmaped during the handleLiterals phase. a->Ldr(rAsm_w, &data); a->Br(rAsm); a->bind(&skip); } emit(jmp{i.targets[0]}); } void Vgen::emit(const jcci& i) { vixl::Label skip; recordAddressImmediate(); a->B(&skip, vixl::InvertCondition(C(i.cc))); emit(jmpi{i.taken}); a->bind(&skip); emit(jmp{i.target}); } void Vgen::emit(const jmp& i) { if (next == i.target) return; jmps.push_back({a->frontier(), i.target}); vixl::Label data; // Emit a "far JMP" sequence for easy patching later. Static relocation // might be able to simplify this (see optimizeFarJmp()). recordAddressImmediate(); poolLiteral(*env.cb, env.meta, (uint64_t)a->frontier(), 32, false); a->bind(&data); // This will be remapped during the handleLiterals phase. a->Ldr(rAsm_w, &data); a->Br(rAsm); } void Vgen::emit(const jmpi& i) { vixl::Label data; // If target can be addressed by pc relative offset (signed 26 bits), emit // PC relative jump. Else, emit target address into code and load from there. auto diff = (i.target - a->frontier()) >> vixl::kInstructionSizeLog2; if (vixl::is_int26(diff)) { recordAddressImmediate(); a->b(diff); } else { // Cannot use simple a->Mov() since such a sequence cannot be // adjusted while live following a relocation. recordAddressImmediate(); poolLiteral(*env.cb, env.meta, (uint64_t)i.target, 32, false); a->bind(&data); // This will be remapped during the handleLiterals phase. a->Ldr(rAsm_w, &data); a->Br(rAsm); } } void Vgen::emit(const lea& i) { auto p = i.s; assertx(p.base.isValid()); if (p.index.isValid()) { assertx(p.disp == 0); a->Add(X(i.d), X(p.base), Operand(X(p.index), LSL, Log2(p.scale))); } else { a->Add(X(i.d), X(p.base), p.disp); } } void Vgen::emit(const leap& i) { vixl::Label imm_data; vixl::Label after_data; // Cannot use simple a->Mov() since such a sequence cannot be // adjusted while live following a relocation. recordAddressImmediate(); poolLiteral(*env.cb, env.meta, (uint64_t)makeTarget32(i.s.r.disp), 32, false); a->bind(&imm_data); // This will be remapped during the handleLiterals phase. a->Ldr(W(i.d), &imm_data); } void Vgen::emit(const lead& i) { recordAddressImmediate(); a->Mov(X(i.d), i.s.get()); } #define Y(vasm_opc, arm_opc, src_dst, m) \ void Vgen::emit(const vasm_opc& i) { \ assertx(i.m.base.isValid()); \ a->Mov(rAsm, X(i.m.base)); \ if (i.m.index.isValid()) { \ a->Add(rAsm, rAsm, Operand(X(i.m.index), LSL, Log2(i.m.scale))); \ } \ if (i.m.disp != 0) { \ a->Add(rAsm, rAsm, i.m.disp); \ } \ a->arm_opc(V(i.src_dst), MemOperand(rAsm)); \ } Y(loadups, ld1, d, s) Y(storeups, st1, s, m) #undef Y /* * Flags * SF, ZF, PF should be updated according to result * CF, OF should be cleared * AF is undefined * * In the following implementation, * N, Z are updated according to result * C, V are cleared */ #define Y(vasm_opc, arm_opc, gpr_w, s0, zr) \ void Vgen::emit(const vasm_opc& i) { \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), s0); \ if (i.fl) { \ a->Bic(vixl::zr, gpr_w(i.d), vixl::zr, SetFlags); \ } \ } Y(orqi, Orr, X, i.s0.q(), xzr); Y(orq, Orr, X, X(i.s0), xzr); Y(xorb, Eor, W, W(i.s0), wzr); Y(xorbi, Eor, W, i.s0.ub(), wzr); Y(xorl, Eor, W, W(i.s0), wzr); Y(xorq, Eor, X, X(i.s0), xzr); Y(xorqi, Eor, X, i.s0.q(), xzr); #undef Y void Vgen::emit(const pop& i) { // SP access must be 8 byte aligned. Use rAsm instead. a->Mov(rAsm, sp); a->Ldr(X(i.d), MemOperand(rAsm, 8, PostIndex)); a->Mov(sp, rAsm); } void Vgen::emit(const push& i) { // SP access must be 8 byte aligned. Use rAsm instead. a->Mov(rAsm, sp); a->Str(X(i.s), MemOperand(rAsm, -8, PreIndex)); a->Mov(sp, rAsm); } void Vgen::emit(const roundsd& i) { switch (i.dir) { case RoundDirection::nearest: { a->frintn(D(i.d), D(i.s)); break; } case RoundDirection::floor: { a->frintm(D(i.d), D(i.s)); break; } case RoundDirection:: ceil: { a->frintp(D(i.d), D(i.s)); break; } default: { assertx(i.dir == RoundDirection::truncate); a->frintz(D(i.d), D(i.s)); } } } void Vgen::emit(const srem& i) { a->Sdiv(rAsm, X(i.s0), X(i.s1)); a->Msub(X(i.d), rAsm, X(i.s1), X(i.s0)); } void Vgen::emit(const trap& i) { env.meta.trapReasons.emplace_back(a->frontier(), i.reason); a->Brk(1); } void Vgen::emit(const unpcklpd& i) { // i.d and i.s1 can be same, i.s0 is unique. if (i.d != i.s1) a->fmov(D(i.d), D(i.s1)); a->fmov(rAsm, D(i.s0)); a->fmov(D(i.d), 1, rAsm); } /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const cmpsd& i) { /* * cmpsd doesn't update SD, so read the flags into a temp. * Use one of the macroassembler scratch regs . */ a->SetScratchRegisters(vixl::NoReg, vixl::NoReg); a->Mrs(rVixlScratch0, NZCV); a->Fcmp(D(i.s0), D(i.s1)); switch (i.pred) { case ComparisonPred::eq_ord: a->Csetm(rAsm, C(jit::CC_E)); break; case ComparisonPred::ne_unord: a->Csetm(rAsm, C(jit::CC_NE)); break; default: always_assert(false); } a->Fmov(D(i.d), rAsm); /* Copy the flags back to the system register. */ a->Msr(NZCV, rVixlScratch0); a->SetScratchRegisters(rVixlScratch0, rVixlScratch1); } /////////////////////////////////////////////////////////////////////////////// /* * For the shifts: * * C is set through inspection * N, Z are updated according to result * V is cleared (FIXME) * PF, AF are not available * * Only set the flags if there are any required flags (i.fl). * Setting the C flag is particularly expensive, so when setting * flags check this flag specifically. */ #define Y(vasm_opc, arm_opc, gpr_w, zr) \ void Vgen::emit(const vasm_opc& i) { \ if (!i.fl) { \ /* Just perform the shift. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), gpr_w(i.s0)); \ } else { \ checkSF(i, StatusFlags::NotV); \ if (!flagRequired(i.fl, StatusFlags::C)) { \ /* Perform the shift and set N and Z. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), gpr_w(i.s0)); \ a->Bic(vixl::zr, gpr_w(i.d), vixl::zr, SetFlags); \ } else { \ /* Use VIXL's macroassembler scratch regs. */ \ a->SetScratchRegisters(vixl::NoReg, vixl::NoReg); \ /* Perform the shift using temp and set N and Z. */ \ a->arm_opc(rVixlScratch0, gpr_w(i.s1), gpr_w(i.s0)); \ a->Bic(vixl::zr, rVixlScratch0, vixl::zr, SetFlags); \ /* Read the flags into a temp. */ \ a->Mrs(rAsm, NZCV); \ /* Reshift right leaving the last bit as bit 0. */ \ a->Sub(rVixlScratch1, gpr_w(i.s0), 1); \ a->Lsr(rVixlScratch1, gpr_w(i.s1), rVixlScratch1); \ /* Negate the bits, including bit 0 to match X64. */ \ a->Mvn(rVixlScratch1, rVixlScratch1); \ /* Copy bit zero into bit 29 of the flags. */ \ a->bfm(rAsm, rVixlScratch1, 35, 0); \ /* Copy the flags back to the system register. */ \ a->Msr(NZCV, rAsm); \ /* Copy the result to the destination. */ \ a->Mov(gpr_w(i.d), rVixlScratch0); \ /* Restore VIXL's scratch regs. */ \ a->SetScratchRegisters(rVixlScratch0, rVixlScratch1); \ } \ } \ } Y(sar, Asr, X, xzr) #undef Y #define Y(vasm_opc, arm_opc, gpr_w, sz, zr) \ void Vgen::emit(const vasm_opc& i) { \ if (!i.fl) { \ /* Just perform the shift. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), gpr_w(i.s0)); \ } else { \ checkSF(i, StatusFlags::NotV); \ if (!flagRequired(i.fl, StatusFlags::C)) { \ /* Perform the shift and set N and Z. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), gpr_w(i.s0)); \ a->Bic(vixl::zr, gpr_w(i.d), vixl::zr, SetFlags); \ } else { \ /* Use VIXL's macroassembler scratch regs. */ \ a->SetScratchRegisters(vixl::NoReg, vixl::NoReg); \ /* Perform the shift using temp and set N and Z. */ \ a->arm_opc(rVixlScratch0, gpr_w(i.s1), gpr_w(i.s0)); \ a->Bic(vixl::zr, rVixlScratch0, vixl::zr, SetFlags); \ /* Read the flags into a temp. */ \ a->Mrs(rAsm, NZCV); \ /* Reshift right leaving the last bit as bit 0. */ \ a->Mov(rVixlScratch1, sz); \ a->Sub(rVixlScratch1, rVixlScratch1, gpr_w(i.s0)); \ a->Lsr(rVixlScratch1, gpr_w(i.s1), rVixlScratch1); \ /* Negate the bits, including bit 0 to match X64. */ \ a->Mvn(rVixlScratch1, rVixlScratch1); \ /* Copy bit zero into bit 29 of the flags. */ \ a->bfm(rAsm, rVixlScratch1, 35, 0); \ /* Copy the flags back to the system register. */ \ a->Msr(NZCV, rAsm); \ /* Copy the result to the destination. */ \ a->Mov(gpr_w(i.d), rVixlScratch0); \ /* Restore VIXL's scratch regs. */ \ a->SetScratchRegisters(rVixlScratch0, rVixlScratch1); \ } \ } \ } Y(shl, Lsl, X, 64, xzr) #undef Y #define Y(vasm_opc, arm_opc, gpr_w, zr) \ void Vgen::emit(const vasm_opc& i) { \ if (!i.fl) { \ /* Just perform the shift. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), i.s0.l()); \ } else { \ checkSF(i, StatusFlags::NotV); \ if (!flagRequired(i.fl, StatusFlags::C)) { \ /* Perform the shift and set N and Z. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), i.s0.l()); \ a->Bic(vixl::zr, gpr_w(i.d), vixl::zr, SetFlags); \ } else { \ /* Use VIXL's macroassembler scratch regs. */ \ a->SetScratchRegisters(vixl::NoReg, vixl::NoReg); \ /* Perform the shift using temp and set N and Z. */ \ a->arm_opc(rVixlScratch0, gpr_w(i.s1), i.s0.l()); \ a->Bic(vixl::zr, rVixlScratch0, vixl::zr, SetFlags); \ /* Read the flags into a temp. */ \ a->Mrs(rAsm, NZCV); \ /* Reshift right leaving the last bit as bit 0. */ \ a->Lsr(rVixlScratch1, gpr_w(i.s1), i.s0.l() - 1); \ /* Negate the bits, including bit 0 to match X64. */ \ a->Mvn(rVixlScratch1, rVixlScratch1); \ /* Copy bit zero into bit 29 of the flags. */ \ a->bfm(rAsm, rVixlScratch1, 35, 0); \ /* Copy the flags back to the system register. */ \ a->Msr(NZCV, rAsm); \ /* Copy the result to the destination. */ \ a->Mov(gpr_w(i.d), rVixlScratch0); \ /* Restore VIXL's scratch regs. */ \ a->SetScratchRegisters(rVixlScratch0, rVixlScratch1); \ } \ } \ } Y(sarqi, Asr, X, xzr) Y(shrli, Lsr, W, wzr) Y(shrqi, Lsr, X, xzr) #undef Y #define Y(vasm_opc, arm_opc, gpr_w, sz, zr) \ void Vgen::emit(const vasm_opc& i) { \ if (!i.fl) { \ /* Just perform the shift. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), i.s0.l()); \ } else { \ checkSF(i, StatusFlags::NotV); \ if (!flagRequired(i.fl, StatusFlags::C)) { \ /* Perform the shift and set N and Z. */ \ a->arm_opc(gpr_w(i.d), gpr_w(i.s1), i.s0.l()); \ a->Bic(vixl::zr, gpr_w(i.d), vixl::zr, SetFlags); \ } else { \ /* Use VIXL's macroassembler scratch regs. */ \ a->SetScratchRegisters(vixl::NoReg, vixl::NoReg); \ /* Perform the shift using temp and set N and Z. */ \ a->arm_opc(rVixlScratch0, gpr_w(i.s1), i.s0.l()); \ a->Bic(vixl::zr, rVixlScratch0, vixl::zr, SetFlags); \ /* Read the flags into a temp. */ \ a->Mrs(rAsm, NZCV); \ /* Reshift right leaving the last bit as bit 0. */ \ a->Lsr(rVixlScratch1, gpr_w(i.s1), sz - i.s0.l()); \ /* Negate the bits, including bit 0 to match X64. */ \ a->Mvn(rVixlScratch1, rVixlScratch1); \ /* Copy bit zero into bit 29 of the flags. */ \ a->bfm(rAsm, rVixlScratch1, 35, 0); \ /* Copy the flags back to the system register. */ \ a->Msr(NZCV, rAsm); \ /* Copy the result to the destination. */ \ a->Mov(gpr_w(i.d), rVixlScratch0); \ /* Restore VIXL's scratch regs. */ \ a->SetScratchRegisters(rVixlScratch0, rVixlScratch1); \ } \ } \ } Y(shlli, Lsl, W, 32, wzr) Y(shlqi, Lsl, X, 64, xzr) #undef Y /////////////////////////////////////////////////////////////////////////////// void Vgen::emit(const popp& i) { a->Ldp(X(i.d0), X(i.d1), MemOperand(sp, 16, PostIndex)); } void Vgen::emit(const pushp& i) { a->Stp(X(i.s1), X(i.s0), MemOperand(sp, -16, PreIndex)); } /////////////////////////////////////////////////////////////////////////////// template<typename Lower> void lower_impl(Vunit& unit, Vlabel b, size_t i, Lower lower) { vmodify(unit, b, i, [&] (Vout& v) { lower(v); return 1; }); } template <typename Inst> void lower(const VLS& /*env*/, Inst& /*inst*/, Vlabel /*b*/, size_t /*i*/) {} /////////////////////////////////////////////////////////////////////////////// /* * TODO: Using load size (ldr[bh]?), apply scaled address if 'disp' is unsigned */ void lowerVptr(Vptr& p, Vout& v) { enum { BASE = 1, INDEX = 2, DISP = 4 }; uint8_t mode = (((p.base.isValid() & 0x1) << 0) | ((p.index.isValid() & 0x1) << 1) | (((p.disp != 0) & 0x1) << 2)); switch (mode) { case BASE: case BASE | INDEX: // ldr/str allow [base] and [base, index], nothing to lower. break; case INDEX: // Not supported, convert to [base]. if (p.scale > 1) { auto t = v.makeReg(); v << shlqi{Log2(p.scale), p.index, t, v.makeReg()}; p.base = t; } else { p.base = p.index; } p.index = Vreg{}; p.scale = 1; break; case BASE | DISP: { // ldr/str allow [base, #imm], where #imm is [-256 .. 255]. if (p.disp >= -256 && p.disp <= 255) break; // #imm is out of range, convert to [base, index] auto index = v.makeReg(); v << ldimmq{Immed64(p.disp), index}; p.index = index; p.scale = 1; p.disp = 0; break; } case DISP: { // Not supported, convert to [base]. auto base = v.makeReg(); v << ldimmq{Immed64(p.disp), base}; p.base = base; p.index = Vreg{}; p.scale = 1; p.disp = 0; break; } case INDEX | DISP: // Not supported, convert to [base, #imm] or [base, index]. if (p.scale > 1) { auto t = v.makeReg(); v << shlqi{Log2(p.scale), p.index, t, v.makeReg()}; p.base = t; } else { p.base = p.index; } if (p.disp >= -256 && p.disp <= 255) { p.index = Vreg{}; p.scale = 1; } else { auto index = v.makeReg(); v << ldimmq{Immed64(p.disp), index}; p.index = index; p.scale = 1; p.disp = 0; } break; case BASE | INDEX | DISP: { // Not supported, convert to [base, index]. auto index = v.makeReg(); if (p.scale > 1) { auto t = v.makeReg(); v << shlqi{Log2(p.scale), p.index, t, v.makeReg()}; v << addqi{p.disp, t, index, v.makeReg()}; } else { v << addqi{p.disp, p.index, index, v.makeReg()}; } p.index = index; p.scale = 1; p.disp = 0; break; } } } #define Y(vasm_opc, m) \ void lower(const VLS& e, vasm_opc& i, Vlabel b, size_t z) { \ lower_impl(e.unit, b, z, [&] (Vout& v) { \ lowerVptr(i.m, v); \ v << i; \ }); \ } Y(decqmlock, m) Y(lea, s) Y(load, s) Y(loadb, s) Y(loadl, s) Y(loadsd, s) Y(loadtqb, s) Y(loadtql, s) Y(loadups, s) Y(loadw, s) Y(loadzbl, s) Y(loadzbq, s) Y(loadzlq, s) Y(store, d) Y(storeb, m) Y(storel, m) Y(storesd, m) Y(storeups, m) Y(storew, m) #undef Y #define Y(vasm_opc, lower_opc, load_opc, store_opc, arg, m) \ void lower(const VLS& e, vasm_opc& i, Vlabel b, size_t z) { \ lower_impl(e.unit, b, z, [&] (Vout& v) { \ lowerVptr(i.m, v); \ auto r0 = v.makeReg(), r1 = v.makeReg(); \ v << load_opc{i.m, r0}; \ v << lower_opc{arg, r0, r1, i.sf, i.fl}; \ v << store_opc{r1, i.m}; \ }); \ } Y(addlim, addli, loadl, storel, i.s0, m) Y(addlm, addl, loadl, storel, i.s0, m) Y(addwm, addl, loadw, storew, Reg32(i.s0), m) Y(addqim, addqi, load, store, i.s0, m) Y(andbim, andbi, loadb, storeb, i.s, m) Y(orbim, orqi, loadb, storeb, i.s0, m) Y(orqim, orqi, load, store, i.s0, m) Y(orwim, orqi, loadw, storew, i.s0, m) Y(orlim, orqi, loadl, storel, i.s0, m) #undef Y #define Y(vasm_opc, lower_opc, movs_opc) \ void lower(const VLS& e, vasm_opc& i, Vlabel b, size_t z) { \ if (!i.fl || (i.fl & static_cast<Vflags>(StatusFlags::NV))) { \ lower_impl(e.unit, b, z, [&] (Vout& v) { \ auto r0 = v.makeReg(), r1 = v.makeReg(); \ v << movs_opc{i.s0, r0}; \ v << movs_opc{i.s1, r1}; \ v << lower_opc{r0, r1, i.sf, i.fl}; \ }); \ } \ } Y(cmpb, cmpl, movsbl) Y(cmpw, cmpl, movswl) #undef Y #define Y(vasm_opc, lower_opc, movs_opc) \ void lower(const VLS& e, vasm_opc& i, Vlabel b, size_t z) { \ if (!i.fl || (i.fl & static_cast<Vflags>(StatusFlags::NV))) { \ lower_impl(e.unit, b, z, [&] (Vout& v) { \ auto r = v.makeReg(); \ v << movs_opc{i.s1, r}; \ v << lower_opc{i.s0, r, i.sf, i.fl}; \ }); \ } \ } Y(cmpbi, cmpli, movsbl) Y(cmpwi, cmpli, movswl) #undef Y #define Y(vasm_opc, lower_opc, load_opc) \ void lower(const VLS& e, vasm_opc& i, Vlabel b, size_t z) { \ lower_impl(e.unit, b, z, [&] (Vout& v) { \ lowerVptr(i.s1, v); \ auto r = e.allow_vreg() ? v.makeReg() : Vreg(PhysReg(rAsm)); \ v << load_opc{i.s1, r}; \ v << lower_opc{i.s0, r, i.sf, i.fl}; \ }); \ } Y(cmpbim, cmpbi, loadb) Y(cmplim, cmpli, loadl) Y(cmpbm, cmpb, loadb) Y(cmpwm, cmpw, loadb) Y(cmplm, cmpl, loadl) Y(cmpqim, cmpqi, load) Y(cmpqm, cmpq, load) Y(cmpwim, cmpwi, loadw) Y(testbim, testli, loadb) Y(testlim, testli, loadl) Y(testqim, testqi, load) Y(testqm, testq, load) Y(testwim, testli, loadw) #undef Y void lower(const VLS& e, cvtsi2sdm& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { lowerVptr(i.s, v); auto r = v.makeReg(); v << load{i.s, r}; v << cvtsi2sd{r, i.d}; }); } #define Y(vasm_opc, lower_opc, load_opc, store_opc, m) \ void lower(const VLS& e, vasm_opc& i, Vlabel b, size_t z) { \ lower_impl(e.unit, b, z, [&] (Vout& v) { \ lowerVptr(i.m, v); \ auto r0 = e.allow_vreg() ? v.makeReg() : Vreg(PhysReg(rAsm)); \ auto r1 = e.allow_vreg() ? v.makeReg() : Vreg(PhysReg(rAsm)); \ v << load_opc{i.m, r0}; \ v << lower_opc{r0, r1, i.sf, i.fl}; \ v << store_opc{r1, i.m}; \ }); \ } Y(declm, decl, loadl, storel, m) Y(decqm, decq, load, store, m) Y(inclm, incl, loadl, storel, m) Y(incqm, incq, load, store, m) Y(incwm, incw, loadw, storew, m) #undef Y void lower(const VLS& e, cvttsd2siq& i, Vlabel b, size_t idx) { lower_impl(e.unit, b, idx, [&] (Vout& v) { // Clear FPSR IOC flag. auto const tmp1 = v.makeReg(); auto const tmp2 = v.makeReg(); v << mrs{FPSR, tmp1}; v << andqi{~0x01, tmp1, tmp2, v.makeReg()}; v << msr{tmp2, FPSR}; // Load error value. auto const err = v.makeReg(); v << ldimmq{0x8000000000000000, err}; // Do ARM64's double to signed int64 conversion. auto const res = v.makeReg(); v << fcvtzs{i.s, res}; // Check if there was a conversion error. auto const fpsr = v.makeReg(); auto const sf = v.makeReg(); v << mrs{FPSR, fpsr}; v << testqi{1, fpsr, sf}; // Move converted value or error. v << cmovq{CC_NZ, sf, res, err, i.d}; }); } void lower(const VLS& e, callm& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { lowerVptr(i.target, v); auto const scratch = v.makeReg(); // Load the target from memory and then call it. v << load{i.target, scratch}; v << callr{scratch, i.args}; }); } void lower(const VLS& e, jmpm& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { lowerVptr(i.target, v); auto const scratch = v.makeReg(); v << load{i.target, scratch}; v << jmpr{scratch, i.args}; }); } /////////////////////////////////////////////////////////////////////////////// void lower(const VLS& e, stublogue& /*i*/, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Push both the LR and FP regardless of i.saveframe to align SP. v << pushp{rlr(), rvmfp()}; }); } void lower(const VLS& e, stubret& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Pop LR and (optionally) FP. if (i.saveframe) { v << popp{rvmfp(), rlr()}; } else { v << popp{PhysReg(rAsm), rlr()}; } v << ret{i.args}; }); } void lower(const VLS& e, tailcallstub& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Restore LR from native stack and adjust SP. v << popp{PhysReg(rAsm), rlr()}; // Then directly jump to the target. v << jmpi{i.target, i.args}; }); } void lower(const VLS& e, stubunwind& /*i*/, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Pop the call frame. v << lea{rsp()[16], rsp()}; }); } void lower(const VLS& e, stubtophp& /*i*/, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Pop the call frame v << lea{rsp()[16], rsp()}; }); } void lower(const VLS& e, loadstubret& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Load the LR to the destination. v << load{rsp()[AROFF(m_savedRip)], i.d}; }); } /////////////////////////////////////////////////////////////////////////////// void lower(const VLS& e, phplogue& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { v << store{rlr(), i.fp[AROFF(m_savedRip)]}; }); } void lower(const VLS& e, tailcallphp& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Undoes the prologue by restoring LR from saved RIP. v << load{i.fp[AROFF(m_savedRip)], rlr()}; v << jmpr{i.target, i.args}; }); } /////////////////////////////////////////////////////////////////////////////// void lower(const VLS& e, resumetc& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { // Call the translation target. v << callr{i.target, i.args}; // After returning to the translation, jump directly to the exit. v << jmpi{i.exittc}; }); } /////////////////////////////////////////////////////////////////////////////// void lower(const VLS& e, popm& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto r = v.makeReg(); v << pop{r}; lowerVptr(i.d, v); v << store{r, i.d}; }); } void lower(const VLS& e, poppm& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto r0 = v.makeReg(); auto r1 = v.makeReg(); v << popp{r0, r1}; lowerVptr(i.d0, v); lowerVptr(i.d1, v); v << store{r0, i.d0}; v << store{r1, i.d1}; }); } void lower(const VLS& e, pushm& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto r = v.makeReg(); lowerVptr(i.s, v); v << load{i.s, r}; v << push{r}; }); } void lower(const VLS& e, pushpm& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto r0 = v.makeReg(); auto r1 = v.makeReg(); lowerVptr(i.s0, v); lowerVptr(i.s1, v); v << load{i.s0, r0}; v << load{i.s1, r1}; v << pushp{r0, r1}; }); } template<typename movz> void lower_movz(const VLS& e, movz& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { v << copy{i.s, i.d}; }); } void lower(const VLS& e, movzbw& i, Vlabel b, size_t z) { lower_movz(e, i, b, z); } void lower(const VLS& e, movzbl& i, Vlabel b, size_t z) { lower_movz(e, i, b, z); } void lower(const VLS& e, movzwl& i, Vlabel b, size_t z) { lower_movz(e, i, b, z); } void lower(const VLS& e, movtdb& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto d = v.makeReg(); v << copy{i.s, d}; v << movtqb{d, i.d}; }); } void lower(const VLS& e, movtdq& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { v << copy{i.s, i.d}; }); } #define Y(vasm_opc, lower_opc, load_opc, imm, zr, sz) \ void lower(const VLS& e, vasm_opc& i, Vlabel b, size_t z) { \ lower_impl(e.unit, b, z, [&] (Vout& v) { \ lowerVptr(i.m, v); \ if (imm.sz() == 0u) { \ v << lower_opc{PhysReg(vixl::zr), i.m}; \ } else { \ auto r = v.makeReg(); \ v << load_opc{imm, r}; \ v << lower_opc{r, i.m}; \ } \ }); \ } Y(storebi, storeb, ldimmb, i.s, wzr, b) Y(storewi, storew, ldimmw, i.s, wzr, w) Y(storeli, storel, ldimml, i.s, wzr, l) //storeqi only supports 32-bit immediates Y(storeqi, store, ldimmq, Immed64(i.s.l()), wzr, q) #undef Y void lower(const VLS& e, cloadq& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto const scratch = v.makeReg(); lowerVptr(i.t, v); v << load{i.t, scratch}; v << cmovq{i.cc, i.sf, i.f, scratch, i.d}; }); } void lower(const VLS& e, loadqp& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto const scratch = v.makeReg(); v << leap{i.s, scratch}; v << load{scratch[0], i.d}; }); } void lower(const VLS& e, loadqd& i, Vlabel b, size_t z) { lower_impl(e.unit, b, z, [&] (Vout& v) { auto const scratch = v.makeReg(); v << lead{i.s.getRaw(), scratch}; v << load{scratch[0], i.d}; }); } /////////////////////////////////////////////////////////////////////////////// void lowerForARM(Vunit& unit) { vasm_lower(unit, [&] (const VLS& env, Vinstr& inst, Vlabel b, size_t i) { switch (inst.op) { #define O(name, ...) \ case Vinstr::name: \ lower(env, inst.name##_, b, i); \ break; VASM_OPCODES #undef O } }); } /////////////////////////////////////////////////////////////////////////////// } void optimizeARM(Vunit& unit, const Abi& abi, bool regalloc) { Timer timer(Timer::vasm_optimize); removeTrivialNops(unit); optimizePhis(unit); fuseBranches(unit); optimizeJmps(unit); optimizeExits(unit); assertx(checkWidths(unit)); simplify(unit); annotateSFUses(unit); lowerForARM(unit); simplify(unit); if (!unit.constToReg.empty()) { foldImms<arm::ImmFolder>(unit); } reuseImmq(unit); optimizeCopies(unit, abi); annotateSFUses(unit); if (unit.needsRegAlloc()) { removeDeadCode(unit); if (regalloc) allocateRegisters(unit, abi); } if (unit.blocks.size() > 1) { optimizeJmps(unit); } } void emitARM(Vunit& unit, Vtext& text, CGMeta& fixups, AsmInfo* asmInfo) { vasm_emit<Vgen>(unit, text, fixups, asmInfo); } /////////////////////////////////////////////////////////////////////////////// }}
33.379115
81
0.524989
[ "vector" ]
d53e4dd80c14b3df70c0b19c37d88748c3342f34
5,050
cc
C++
UVa Online Judge/v1/173.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
1
2021-12-08T08:58:43.000Z
2021-12-08T08:58:43.000Z
UVa Online Judge/v1/173.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
UVa Online Judge/v1/173.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
/*============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 173.cc # Description: UVa Online Judge - 173 =============================================================================*/ #include <bits/stdc++.h> #pragma GCC optimizer("Ofast") #pragma GCC target("avx2") using namespace std; typedef pair<int, int> ii; typedef pair<long long, long long> ll; typedef pair<double, double> dd; typedef tuple<int, int, int> iii; typedef vector<string> vs; typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef vector<long long> vl; typedef vector<vector<long long>> vvl; typedef vector<double> vd; typedef vector<vector<double>> vvd; typedef vector<ii> vii; typedef vector<ll> vll; typedef vector<dd> vdd; template <class Ch, class Tr, class Container> basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os, Container const& x) { os << "{ "; for (auto& y : x) os << y << " "; return os << "}"; } template <class X, class Y> ostream& operator<<(ostream& os, pair<X, Y> const& p) { return os << "[ " << p.first << ", " << p.second << "]"; } vs split(string line, regex re) { vs output; sregex_token_iterator it(line.begin(), line.end(), re, -1), it_end; while (it != it_end) { output.push_back(it->str()); it++; } return output; } const int INF_INT = 1e9 + 7; const long long INF_LL = 1e18; const int MAXN = 300; vi V[MAXN], visited; bool space, print_paskill, print_lisper; void dfs(int lisper, int paskill, int& done) { if (done) return; visited[paskill] |= (1 << 0); visited[lisper] |= (1 << 1); // Currently at the same location if (paskill == lisper) { done = true; cout << "Both annihilated in node " << (char)paskill; return; } int order; int next_lisper = -1, order_lisper = -1; int next_paskill = -1, order_paskill = -1; for (auto& node : V[paskill]) { if (visited[node] & (1 << 0)) continue; if (visited[node] & (1 << 1)) continue; if (node > paskill) order = node - paskill; else order = MAXN + node; if (next_paskill == -1 or order < order_paskill) { next_paskill = node; order_paskill = order; } } for (auto& node : V[lisper]) { if (visited[node] & (1 << 1)) continue; if (node > lisper) order = MAXN + (MAXN - node); else order = lisper - node; if (next_lisper == -1 or order < order_lisper) { next_lisper = node; order_lisper = order; } } if (next_paskill == -1) next_paskill = paskill; if (next_lisper == -1) next_lisper = lisper; // Cannot move paskill if (next_paskill == paskill) { if (not print_paskill) { if (space) cout << " "; space = true; cout << "Paskill trapped in node " << (char)paskill; print_paskill = true; } } // Cannot move lisper if (next_lisper == lisper) { if (not print_lisper) { if (space) cout << " "; space = true; cout << "Lisper trapped in node " << (char)lisper; print_lisper = true; } } // Can move both and to the same location if (next_paskill == next_lisper and next_paskill != -1) { if (space) cout << " "; space = true; cout << "Both annihilated in node " << (char)next_paskill; done = true; return; } // Move lisper into the nodes visited by paskill if (visited[next_lisper] & (1 << 0)) { if (space) cout << " "; space = true; cout << "Lisper destroyed in node " << (char)next_lisper; done = true; return; } if (next_lisper == lisper or next_paskill == paskill) { done = true; return; } dfs(next_lisper, next_paskill, done); } int main() { ios::sync_with_stdio(false); cin.tie(0); string line; while (true) { getline(cin, line); if (line == "#") break; for (int i = 0; i < MAXN; i++) V[i].clear(); visited = vi(MAXN); vs tokens = split(line, regex("(\\.\\s|\\s|\\.)")); int lisper, paskill; if (tokens.size() == 3) { lisper = tokens[1][0]; paskill = tokens[2][0]; } else if (tokens.size() == 2) { lisper = tokens[1][0]; paskill = tokens[1][1]; } for (auto& edges : split(tokens[0], regex(";"))) { vs nodes = split(edges, regex(":")); for (auto& node : nodes[1]) { V[nodes[0][0]].push_back(node); V[node].push_back(nodes[0][0]); } } int done = 0; space = print_paskill = print_lisper = false; dfs(paskill, lisper, done); cout << endl; } return 0; }
27.297297
79
0.511881
[ "vector" ]
d53f7b6d11657e2d33cde41728d9ff9f915a7121
1,790
cpp
C++
Source/AllProjects/Samples/Basic/Beeper/Beeper.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/Samples/Basic/Beeper/Beeper.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/Samples/Basic/Beeper/Beeper.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: Beeper.cpp // // AUTHOR: Dean Roddey // // CREATED: 07/24/1997 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the main module for a very simple program that just does a beep. // It's about as simple as you can get. Being very simple this one does not have // a 'facility object', it's just a thread started on a local function. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Includes. We just need the basic CIDLib facility // --------------------------------------------------------------------------- #include "CIDLib.hpp" // --------------------------------------------------------------------------- // Do the magic main module code // --------------------------------------------------------------------------- tCIDLib::EExitCodes eMainThreadFunc(TThread&, tCIDLib::TVoid*); CIDLib_MainModule(TThread(L"BeeperMainThread", eMainThreadFunc)) // --------------------------------------------------------------------------- // Local functions // --------------------------------------------------------------------------- // // This is the the thread function for the main thread. It is started by // CIDLib_MainModule() above. // tCIDLib::EExitCodes eMainThreadFunc(TThread& thrThis, tCIDLib::TVoid*) { // We have to let our calling thread go first thrThis.Sync(); // Beep and return. Not worth even catching exceptions for this simple guy TAudio::Beep(880, 500); return tCIDLib::EExitCodes::Normal; }
29.344262
81
0.512291
[ "object" ]
d53fdfa05bd76a15f497f03b2a2a1d95f06379ad
385,874
cpp
C++
matrix_old/python/rgbmatrix/core.cpp
hammal/macapar
05fb84b8f5e967ed6d3edb0891ac58674e6b60bc
[ "MIT" ]
null
null
null
matrix_old/python/rgbmatrix/core.cpp
hammal/macapar
05fb84b8f5e967ed6d3edb0891ac58674e6b60bc
[ "MIT" ]
null
null
null
matrix_old/python/rgbmatrix/core.cpp
hammal/macapar
05fb84b8f5e967ed6d3edb0891ac58674e6b60bc
[ "MIT" ]
null
null
null
/* Generated by Cython 0.25.2 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_25_2" #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && PY_VERSION_HEX >= 0x02070000) #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifndef __cplusplus #error "Cython files generated with the C++ option must be compiled with a C++ compiler." #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #else #define CYTHON_INLINE inline #endif #endif template<typename T> void __Pyx_call_destructor(T& x) { x.~T(); } template<typename T> class __Pyx_FakeReference { public: __Pyx_FakeReference() : ptr(NULL) { } __Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { } T *operator->() { return ptr; } T *operator&() { return ptr; } operator T&() { return *ptr; } template<typename U> bool operator ==(U other) { return *ptr == other; } template<typename U> bool operator !=(U other) { return *ptr != other; } private: T *ptr; }; #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__rgbmatrix__core #define __PYX_HAVE_API__rgbmatrix__core #include <stdint.h> #include "canvas.h" #include "led-matrix.h" #include "ios" #include "new" #include "stdexcept" #include "typeinfo" #include "graphics.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) && defined (_M_X64) #define __Pyx_sst_abs(value) _abs64(value) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char *__pyx_f[] = { "rgbmatrix/core.pyx", }; /*--- Type declarations ---*/ struct __pyx_obj_9rgbmatrix_4core_Canvas; struct __pyx_obj_9rgbmatrix_4core_FrameCanvas; struct __pyx_obj_9rgbmatrix_4core_RGBMatrix; struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions; /* "rgbmatrix/core.pxd":3 * cimport cppinc * * cdef class Canvas: # <<<<<<<<<<<<<< * cdef cppinc.Canvas *__getCanvas(self) except + * */ struct __pyx_obj_9rgbmatrix_4core_Canvas { PyObject_HEAD struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas *__pyx_vtab; }; /* "rgbmatrix/core.pxd":6 * cdef cppinc.Canvas *__getCanvas(self) except + * * cdef class FrameCanvas(Canvas): # <<<<<<<<<<<<<< * cdef cppinc.FrameCanvas *__canvas * */ struct __pyx_obj_9rgbmatrix_4core_FrameCanvas { struct __pyx_obj_9rgbmatrix_4core_Canvas __pyx_base; rgb_matrix::FrameCanvas *__pyx___canvas; }; /* "rgbmatrix/core.pxd":9 * cdef cppinc.FrameCanvas *__canvas * * cdef class RGBMatrix(Canvas): # <<<<<<<<<<<<<< * cdef cppinc.RGBMatrix *__matrix * */ struct __pyx_obj_9rgbmatrix_4core_RGBMatrix { struct __pyx_obj_9rgbmatrix_4core_Canvas __pyx_base; rgb_matrix::RGBMatrix *__pyx___matrix; }; /* "rgbmatrix/core.pxd":12 * cdef cppinc.RGBMatrix *__matrix * * cdef class RGBMatrixOptions: # <<<<<<<<<<<<<< * cdef cppinc.Options __options * cdef cppinc.RuntimeOptions __runtime_options */ struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions { PyObject_HEAD struct rgb_matrix::RGBMatrix::Options __pyx___options; struct rgb_matrix::RuntimeOptions __pyx___runtime_options; PyObject *__pyx___py_encoded_hardware_mapping; }; /* "rgbmatrix/core.pyx":8 * import cython * * cdef class Canvas: # <<<<<<<<<<<<<< * cdef cppinc.Canvas* __getCanvas(self) except +: * raise Exception("Not implemented") */ struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas { rgb_matrix::Canvas *(*__pyx___getCanvas)(struct __pyx_obj_9rgbmatrix_4core_Canvas *); }; static struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas *__pyx_vtabptr_9rgbmatrix_4core_Canvas; /* "rgbmatrix/core.pyx":56 * my_canvas.SetPixel(xstart+col, ystart+row, r, g, b) * * cdef class FrameCanvas(Canvas): # <<<<<<<<<<<<<< * def __dealloc__(self): * if <void*>self.__canvas != NULL: */ struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas { struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas __pyx_base; rgb_matrix::Canvas *(*__pyx___getCanvas)(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *); }; static struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *__pyx_vtabptr_9rgbmatrix_4core_FrameCanvas; /* "rgbmatrix/core.pyx":162 * * * cdef class RGBMatrix(Canvas): # <<<<<<<<<<<<<< * def __cinit__(self, int rows = 0, int chains = 0, int parallel = 0, * RGBMatrixOptions options = None): */ struct __pyx_vtabstruct_9rgbmatrix_4core_RGBMatrix { struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas __pyx_base; rgb_matrix::Canvas *(*__pyx___getCanvas)(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *); }; static struct __pyx_vtabstruct_9rgbmatrix_4core_RGBMatrix *__pyx_vtabptr_9rgbmatrix_4core_RGBMatrix; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = PyThreadState_GET(); #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* IncludeStringH.proto */ #include <string.h> /* BytesEquals.proto */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /* UnicodeEquals.proto */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /* StrEquals.proto */ #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals #else #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* IterFinish.proto */ static CYTHON_INLINE int __Pyx_IterFinish(void); /* UnpackItemEndCheck.proto */ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs); #else #define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) #endif #endif /* PyCFunctionFastCall.proto */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else #define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) #endif /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /* PyObjectCallNoArg.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); #else #define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) #endif /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) PyErr_SetObject(PyExc_KeyError, args); Py_XDECREF(args); } return NULL; } Py_INCREF(value); return value; } #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif /* KeywordStringCheck.proto */ static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); /* ArgTypeTest.proto */ static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /* PyObjectSetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS #define __Pyx_PyObject_DelAttrStr(o,n) __Pyx_PyObject_SetAttrStr(o,n,NULL) static CYTHON_INLINE int __Pyx_PyObject_SetAttrStr(PyObject* obj, PyObject* attr_name, PyObject* value) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_setattro)) return tp->tp_setattro(obj, attr_name, value); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_setattr)) return tp->tp_setattr(obj, PyString_AS_STRING(attr_name), value); #endif return PyObject_SetAttr(obj, attr_name, value); } #else #define __Pyx_PyObject_DelAttrStr(o,n) PyObject_DelAttr(o,n) #define __Pyx_PyObject_SetAttrStr(o,n,v) PyObject_SetAttr(o,n,v) #endif /* SetVTable.proto */ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* ImportFrom.proto */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CppExceptionConversion.proto */ #ifndef __Pyx_CppExn2PyErr #include <new> #include <typeinfo> #include <stdexcept> #include <ios> static void __Pyx_CppExn2PyErr() { try { if (PyErr_Occurred()) ; // let the latest Python exn pass through and ignore the current one else throw; } catch (const std::bad_alloc& exn) { PyErr_SetString(PyExc_MemoryError, exn.what()); } catch (const std::bad_cast& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::bad_typeid& exn) { PyErr_SetString(PyExc_TypeError, exn.what()); } catch (const std::domain_error& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::invalid_argument& exn) { PyErr_SetString(PyExc_ValueError, exn.what()); } catch (const std::ios_base::failure& exn) { PyErr_SetString(PyExc_IOError, exn.what()); } catch (const std::out_of_range& exn) { PyErr_SetString(PyExc_IndexError, exn.what()); } catch (const std::overflow_error& exn) { PyErr_SetString(PyExc_OverflowError, exn.what()); } catch (const std::range_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::underflow_error& exn) { PyErr_SetString(PyExc_ArithmeticError, exn.what()); } catch (const std::exception& exn) { PyErr_SetString(PyExc_RuntimeError, exn.what()); } catch (...) { PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); } } #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint8_t(uint8_t value); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE uint8_t __Pyx_PyInt_As_uint8_t(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE uint32_t __Pyx_PyInt_As_uint32_t(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_6Canvas___getCanvas(CYTHON_UNUSED struct __pyx_obj_9rgbmatrix_4core_Canvas *__pyx_v_self); /* proto*/ rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_11FrameCanvas___getCanvas(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto*/ rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_11FrameCanvas___getCanvas__pyx_wrap_1(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto*/ rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_9RGBMatrix___getCanvas(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto*/ rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_9RGBMatrix___getCanvas__pyx_wrap_1(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto*/ /* Module declarations from 'libcpp' */ /* Module declarations from 'libc.stdint' */ /* Module declarations from 'rgbmatrix.cppinc' */ /* Module declarations from 'cython' */ /* Module declarations from 'rgbmatrix.core' */ static PyTypeObject *__pyx_ptype_9rgbmatrix_4core_Canvas = 0; static PyTypeObject *__pyx_ptype_9rgbmatrix_4core_FrameCanvas = 0; static PyTypeObject *__pyx_ptype_9rgbmatrix_4core_RGBMatrix = 0; static PyTypeObject *__pyx_ptype_9rgbmatrix_4core_RGBMatrixOptions = 0; static PyObject *__pyx_f_9rgbmatrix_4core___createFrameCanvas(rgb_matrix::FrameCanvas *); /*proto*/ #define __Pyx_MODULE_NAME "rgbmatrix.core" int __pyx_module_is_main_rgbmatrix__core = 0; /* Implementation of 'rgbmatrix.core' */ static PyObject *__pyx_builtin_range; static const char __pyx_k_x[] = "x"; static const char __pyx_k_y[] = "y"; static const char __pyx_k_im[] = "im"; static const char __pyx_k_PIL[] = "PIL"; static const char __pyx_k_RGB[] = "RGB"; static const char __pyx_k_red[] = "red"; static const char __pyx_k_blue[] = "blue"; static const char __pyx_k_load[] = "load"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mode[] = "mode"; static const char __pyx_k_rows[] = "rows"; static const char __pyx_k_size[] = "size"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_Image[] = "Image"; static const char __pyx_k_green[] = "green"; static const char __pyx_k_image[] = "image"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_utf_8[] = "utf-8"; static const char __pyx_k_width[] = "width"; static const char __pyx_k_chains[] = "chains"; static const char __pyx_k_encode[] = "encode"; static const char __pyx_k_height[] = "height"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_unsafe[] = "unsafe"; static const char __pyx_k_xstart[] = "xstart"; static const char __pyx_k_ystart[] = "ystart"; static const char __pyx_k_image32[] = "image32"; static const char __pyx_k_options[] = "options"; static const char __pyx_k_SetPixel[] = "SetPixel"; static const char __pyx_k_offset_x[] = "offset_x"; static const char __pyx_k_offset_y[] = "offset_y"; static const char __pyx_k_parallel[] = "parallel"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_unsafe_ptrs[] = "unsafe_ptrs"; static const char __pyx_k_chain_length[] = "chain_length"; static const char __pyx_k_Not_implemented[] = "Not implemented"; static const char __pyx_k_SetPixelsPillow[] = "SetPixelsPillow"; static const char __pyx_k_Canvas_was_destroyed_or_not_init[] = "Canvas was destroyed or not initialized, you cannot use this object anymore"; static const char __pyx_k_Currently_only_RGB_mode_is_suppo[] = "Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)"; static PyObject *__pyx_kp_s_Canvas_was_destroyed_or_not_init; static PyObject *__pyx_kp_s_Currently_only_RGB_mode_is_suppo; static PyObject *__pyx_n_s_Image; static PyObject *__pyx_kp_s_Not_implemented; static PyObject *__pyx_n_s_PIL; static PyObject *__pyx_n_s_RGB; static PyObject *__pyx_n_s_SetPixel; static PyObject *__pyx_n_s_SetPixelsPillow; static PyObject *__pyx_n_s_blue; static PyObject *__pyx_n_s_chain_length; static PyObject *__pyx_n_s_chains; static PyObject *__pyx_n_s_encode; static PyObject *__pyx_n_s_green; static PyObject *__pyx_n_s_height; static PyObject *__pyx_n_s_im; static PyObject *__pyx_n_s_image; static PyObject *__pyx_n_s_image32; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_load; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_offset_x; static PyObject *__pyx_n_s_offset_y; static PyObject *__pyx_n_s_options; static PyObject *__pyx_n_s_parallel; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_red; static PyObject *__pyx_n_s_rows; static PyObject *__pyx_n_s_size; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_unsafe; static PyObject *__pyx_n_s_unsafe_ptrs; static PyObject *__pyx_kp_s_utf_8; static PyObject *__pyx_n_s_width; static PyObject *__pyx_n_s_x; static PyObject *__pyx_n_s_xstart; static PyObject *__pyx_n_s_y; static PyObject *__pyx_n_s_ystart; static PyObject *__pyx_pf_9rgbmatrix_4core_6Canvas_SetImage(struct __pyx_obj_9rgbmatrix_4core_Canvas *__pyx_v_self, PyObject *__pyx_v_image, int __pyx_v_offset_x, int __pyx_v_offset_y, PyObject *__pyx_v_unsafe); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_6Canvas_2SetPixelsPillow(struct __pyx_obj_9rgbmatrix_4core_Canvas *__pyx_v_self, int __pyx_v_xstart, int __pyx_v_ystart, int __pyx_v_width, int __pyx_v_height, PyObject *__pyx_v_image); /* proto */ static void __pyx_pf_9rgbmatrix_4core_11FrameCanvas___dealloc__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_2Fill(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_4Clear(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_6SetPixel(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, int __pyx_v_x, int __pyx_v_y, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_5width___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_6height___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_7pwmBits___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_11FrameCanvas_7pwmBits_2__set__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, PyObject *__pyx_v_pwmBits); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_10brightness___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_11FrameCanvas_10brightness_2__set__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, PyObject *__pyx_v_val); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions___cinit__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_4rows___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_4rows_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8parallel___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint32_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_10brightness___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_6daemon___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value); /* proto */ static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix___cinit__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, int __pyx_v_rows, int __pyx_v_chains, int __pyx_v_parallel, struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_options); /* proto */ static void __pyx_pf_9rgbmatrix_4core_9RGBMatrix_2__dealloc__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_4Fill(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_6SetPixel(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, int __pyx_v_x, int __pyx_v_y, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_8Clear(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_10CreateFrameCanvas(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_12SwapOnVSync(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_newFrame); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, PyObject *__pyx_v_luminanceCorrect); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_7pwmBits___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix_7pwmBits_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, PyObject *__pyx_v_pwmBits); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_10brightness___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix_10brightness_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, PyObject *__pyx_v_brightness); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_6height___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_5width___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self); /* proto */ static PyObject *__pyx_tp_new_9rgbmatrix_4core_Canvas(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_9rgbmatrix_4core_FrameCanvas(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_9rgbmatrix_4core_RGBMatrix(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_9rgbmatrix_4core_RGBMatrixOptions(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; /* "rgbmatrix/core.pyx":9 * * cdef class Canvas: * cdef cppinc.Canvas* __getCanvas(self) except +: # <<<<<<<<<<<<<< * raise Exception("Not implemented") * */ static rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_6Canvas___getCanvas(CYTHON_UNUSED struct __pyx_obj_9rgbmatrix_4core_Canvas *__pyx_v_self) { rgb_matrix::Canvas *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__getCanvas", 0); /* "rgbmatrix/core.pyx":10 * cdef class Canvas: * cdef cppinc.Canvas* __getCanvas(self) except +: * raise Exception("Not implemented") # <<<<<<<<<<<<<< * * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])), __pyx_tuple_, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(0, 10, __pyx_L1_error) /* "rgbmatrix/core.pyx":9 * * cdef class Canvas: * cdef cppinc.Canvas* __getCanvas(self) except +: # <<<<<<<<<<<<<< * raise Exception("Not implemented") * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.Canvas.__getCanvas", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":12 * raise Exception("Not implemented") * * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): # <<<<<<<<<<<<<< * if (image.mode != "RGB"): * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_6Canvas_1SetImage(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_6Canvas_1SetImage(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_image = 0; int __pyx_v_offset_x; int __pyx_v_offset_y; PyObject *__pyx_v_unsafe = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("SetImage (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_image,&__pyx_n_s_offset_x,&__pyx_n_s_offset_y,&__pyx_n_s_unsafe,0}; PyObject* values[4] = {0,0,0,0}; values[3] = ((PyObject *)Py_True); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_image)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_offset_x); if (value) { values[1] = value; kw_args--; } } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_offset_y); if (value) { values[2] = value; kw_args--; } } case 3: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unsafe); if (value) { values[3] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "SetImage") < 0)) __PYX_ERR(0, 12, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_image = values[0]; if (values[1]) { __pyx_v_offset_x = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_offset_x == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 12, __pyx_L3_error) } else { __pyx_v_offset_x = ((int)0); } if (values[2]) { __pyx_v_offset_y = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_offset_y == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 12, __pyx_L3_error) } else { __pyx_v_offset_y = ((int)0); } __pyx_v_unsafe = values[3]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("SetImage", 0, 1, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 12, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.Canvas.SetImage", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_6Canvas_SetImage(((struct __pyx_obj_9rgbmatrix_4core_Canvas *)__pyx_v_self), __pyx_v_image, __pyx_v_offset_x, __pyx_v_offset_y, __pyx_v_unsafe); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_6Canvas_SetImage(struct __pyx_obj_9rgbmatrix_4core_Canvas *__pyx_v_self, PyObject *__pyx_v_image, int __pyx_v_offset_x, int __pyx_v_offset_y, PyObject *__pyx_v_unsafe) { PyObject *__pyx_v_img_width = NULL; PyObject *__pyx_v_img_height = NULL; PyObject *__pyx_v_pixels = NULL; PyObject *__pyx_v_x = NULL; PyObject *__pyx_v_y = NULL; PyObject *__pyx_v_r = NULL; PyObject *__pyx_v_g = NULL; PyObject *__pyx_v_b = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *(*__pyx_t_6)(PyObject *); PyObject *__pyx_t_7 = NULL; int __pyx_t_8; PyObject *__pyx_t_9 = NULL; long __pyx_t_10; long __pyx_t_11; Py_ssize_t __pyx_t_12; PyObject *(*__pyx_t_13)(PyObject *); Py_ssize_t __pyx_t_14; PyObject *(*__pyx_t_15)(PyObject *); PyObject *__pyx_t_16 = NULL; PyObject *__pyx_t_17 = NULL; __Pyx_RefNannySetupContext("SetImage", 0); /* "rgbmatrix/core.pyx":13 * * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): * if (image.mode != "RGB"): # <<<<<<<<<<<<<< * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") * */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_image, __pyx_n_s_mode); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_1, __pyx_n_s_RGB, Py_NE)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 13, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_2) { /* "rgbmatrix/core.pyx":14 * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): * if (image.mode != "RGB"): * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") # <<<<<<<<<<<<<< * * if unsafe: */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])), __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(0, 14, __pyx_L1_error) /* "rgbmatrix/core.pyx":13 * * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): * if (image.mode != "RGB"): # <<<<<<<<<<<<<< * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") * */ } /* "rgbmatrix/core.pyx":16 * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") * * if unsafe: # <<<<<<<<<<<<<< * #In unsafe mode we directly access the underlying PIL image array * #in cython, which is considered unsafe pointer accecss, */ __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_unsafe); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 16, __pyx_L1_error) if (__pyx_t_2) { /* "rgbmatrix/core.pyx":21 * #however it's super fast and seems to work fine * #https://groups.google.com/forum/#!topic/cython-users/Dc1ft5W6KM4 * img_width, img_height = image.size # <<<<<<<<<<<<<< * self.SetPixelsPillow(offset_x, offset_y, img_width, img_height, image) * else: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_image, __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { PyObject* sequence = __pyx_t_1; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(0, 21, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (likely(PyTuple_CheckExact(sequence))) { __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); } else { __pyx_t_3 = PyList_GET_ITEM(sequence, 0); __pyx_t_4 = PyList_GET_ITEM(sequence, 1); } __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { Py_ssize_t index = -1; __pyx_t_5 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; index = 0; __pyx_t_3 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_3)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_3); index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L5_unpacking_failed; __Pyx_GOTREF(__pyx_t_4); if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __pyx_t_6 = NULL; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L6_unpacking_done; __pyx_L5_unpacking_failed:; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); __PYX_ERR(0, 21, __pyx_L1_error) __pyx_L6_unpacking_done:; } __pyx_v_img_width = __pyx_t_3; __pyx_t_3 = 0; __pyx_v_img_height = __pyx_t_4; __pyx_t_4 = 0; /* "rgbmatrix/core.pyx":22 * #https://groups.google.com/forum/#!topic/cython-users/Dc1ft5W6KM4 * img_width, img_height = image.size * self.SetPixelsPillow(offset_x, offset_y, img_width, img_height, image) # <<<<<<<<<<<<<< * else: * # First implementation of a SetImage(). OPTIMIZE_ME: A more native */ __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_SetPixelsPillow); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_offset_x); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_offset_y); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_7 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_7)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_7); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); __pyx_t_8 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[6] = {__pyx_t_7, __pyx_t_3, __pyx_t_5, __pyx_v_img_width, __pyx_v_img_height, __pyx_v_image}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_8, 5+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { PyObject *__pyx_temp[6] = {__pyx_t_7, __pyx_t_3, __pyx_t_5, __pyx_v_img_width, __pyx_v_img_height, __pyx_v_image}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_8, 5+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } else #endif { __pyx_t_9 = PyTuple_New(5+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_7) { __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; } __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_t_5); __Pyx_INCREF(__pyx_v_img_width); __Pyx_GIVEREF(__pyx_v_img_width); PyTuple_SET_ITEM(__pyx_t_9, 2+__pyx_t_8, __pyx_v_img_width); __Pyx_INCREF(__pyx_v_img_height); __Pyx_GIVEREF(__pyx_v_img_height); PyTuple_SET_ITEM(__pyx_t_9, 3+__pyx_t_8, __pyx_v_img_height); __Pyx_INCREF(__pyx_v_image); __Pyx_GIVEREF(__pyx_v_image); PyTuple_SET_ITEM(__pyx_t_9, 4+__pyx_t_8, __pyx_v_image); __pyx_t_3 = 0; __pyx_t_5 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":16 * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") * * if unsafe: # <<<<<<<<<<<<<< * #In unsafe mode we directly access the underlying PIL image array * #in cython, which is considered unsafe pointer accecss, */ goto __pyx_L4; } /* "rgbmatrix/core.pyx":27 * # implementation that directly reads the buffer and calls the underlying * # C functions can certainly be faster. * img_width, img_height = image.size # <<<<<<<<<<<<<< * pixels = image.load() * for x in range(max(0, -offset_x), min(img_width, self.width - offset_x)): */ /*else*/ { __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_image, __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 27, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { PyObject* sequence = __pyx_t_1; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(0, 27, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (likely(PyTuple_CheckExact(sequence))) { __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_9 = PyTuple_GET_ITEM(sequence, 1); } else { __pyx_t_4 = PyList_GET_ITEM(sequence, 0); __pyx_t_9 = PyList_GET_ITEM(sequence, 1); } __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx_t_9); #else __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 27, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_9 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 27, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { Py_ssize_t index = -1; __pyx_t_5 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 27, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_6 = Py_TYPE(__pyx_t_5)->tp_iternext; index = 0; __pyx_t_4 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_4)) goto __pyx_L7_unpacking_failed; __Pyx_GOTREF(__pyx_t_4); index = 1; __pyx_t_9 = __pyx_t_6(__pyx_t_5); if (unlikely(!__pyx_t_9)) goto __pyx_L7_unpacking_failed; __Pyx_GOTREF(__pyx_t_9); if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_5), 2) < 0) __PYX_ERR(0, 27, __pyx_L1_error) __pyx_t_6 = NULL; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L8_unpacking_done; __pyx_L7_unpacking_failed:; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); __PYX_ERR(0, 27, __pyx_L1_error) __pyx_L8_unpacking_done:; } __pyx_v_img_width = __pyx_t_4; __pyx_t_4 = 0; __pyx_v_img_height = __pyx_t_9; __pyx_t_9 = 0; /* "rgbmatrix/core.pyx":28 * # C functions can certainly be faster. * img_width, img_height = image.size * pixels = image.load() # <<<<<<<<<<<<<< * for x in range(max(0, -offset_x), min(img_width, self.width - offset_x)): * for y in range(max(0, -offset_y), min(img_height, self.height - offset_y)): */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_image, __pyx_n_s_load); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 28, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_9))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_9); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_9, function); } } if (__pyx_t_4) { __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_9, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 28, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } else { __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_9); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 28, __pyx_L1_error) } __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_pixels = __pyx_t_1; __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":29 * img_width, img_height = image.size * pixels = image.load() * for x in range(max(0, -offset_x), min(img_width, self.width - offset_x)): # <<<<<<<<<<<<<< * for y in range(max(0, -offset_y), min(img_height, self.height - offset_y)): * (r, g, b) = pixels[x, y] */ __pyx_t_8 = (-__pyx_v_offset_x); __pyx_t_10 = 0; if (((__pyx_t_8 > __pyx_t_10) != 0)) { __pyx_t_11 = __pyx_t_8; } else { __pyx_t_11 = __pyx_t_10; } __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_9 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_width); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_offset_x); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyNumber_Subtract(__pyx_t_9, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_INCREF(__pyx_v_img_width); __pyx_t_4 = __pyx_v_img_width; __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_t_4, Py_LT); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 29, __pyx_L1_error) __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_2) { __Pyx_INCREF(__pyx_t_5); __pyx_t_9 = __pyx_t_5; } else { __Pyx_INCREF(__pyx_t_4); __pyx_t_9 = __pyx_t_4; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __Pyx_INCREF(__pyx_t_9); __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_9); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_range, __pyx_t_5, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (likely(PyList_CheckExact(__pyx_t_9)) || PyTuple_CheckExact(__pyx_t_9)) { __pyx_t_5 = __pyx_t_9; __Pyx_INCREF(__pyx_t_5); __pyx_t_12 = 0; __pyx_t_13 = NULL; } else { __pyx_t_12 = -1; __pyx_t_5 = PyObject_GetIter(__pyx_t_9); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_13 = Py_TYPE(__pyx_t_5)->tp_iternext; if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 29, __pyx_L1_error) } __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; for (;;) { if (likely(!__pyx_t_13)) { if (likely(PyList_CheckExact(__pyx_t_5))) { if (__pyx_t_12 >= PyList_GET_SIZE(__pyx_t_5)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_9 = PyList_GET_ITEM(__pyx_t_5, __pyx_t_12); __Pyx_INCREF(__pyx_t_9); __pyx_t_12++; if (unlikely(0 < 0)) __PYX_ERR(0, 29, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_5, __pyx_t_12); __pyx_t_12++; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif } else { if (__pyx_t_12 >= PyTuple_GET_SIZE(__pyx_t_5)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_5, __pyx_t_12); __Pyx_INCREF(__pyx_t_9); __pyx_t_12++; if (unlikely(0 < 0)) __PYX_ERR(0, 29, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_5, __pyx_t_12); __pyx_t_12++; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif } } else { __pyx_t_9 = __pyx_t_13(__pyx_t_5); if (unlikely(!__pyx_t_9)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 29, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_9); } __Pyx_XDECREF_SET(__pyx_v_x, __pyx_t_9); __pyx_t_9 = 0; /* "rgbmatrix/core.pyx":30 * pixels = image.load() * for x in range(max(0, -offset_x), min(img_width, self.width - offset_x)): * for y in range(max(0, -offset_y), min(img_height, self.height - offset_y)): # <<<<<<<<<<<<<< * (r, g, b) = pixels[x, y] * self.SetPixel(x + offset_x, y + offset_y, r, g, b) */ __pyx_t_8 = (-__pyx_v_offset_y); __pyx_t_11 = 0; if (((__pyx_t_8 > __pyx_t_11) != 0)) { __pyx_t_10 = __pyx_t_8; } else { __pyx_t_10 = __pyx_t_11; } __pyx_t_9 = __Pyx_PyInt_From_long(__pyx_t_10); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_height); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_offset_y); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_t_1, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_INCREF(__pyx_v_img_height); __pyx_t_4 = __pyx_v_img_height; __pyx_t_7 = PyObject_RichCompare(__pyx_t_3, __pyx_t_4, Py_LT); __Pyx_XGOTREF(__pyx_t_7); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 30, __pyx_L1_error) __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_7); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (__pyx_t_2) { __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = __pyx_t_3; } else { __Pyx_INCREF(__pyx_t_4); __pyx_t_1 = __pyx_t_4; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_9); __Pyx_INCREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_range, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { __pyx_t_3 = __pyx_t_1; __Pyx_INCREF(__pyx_t_3); __pyx_t_14 = 0; __pyx_t_15 = NULL; } else { __pyx_t_14 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_15 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 30, __pyx_L1_error) } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; for (;;) { if (likely(!__pyx_t_15)) { if (likely(PyList_CheckExact(__pyx_t_3))) { if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_1 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) __PYX_ERR(0, 30, __pyx_L1_error) #else __pyx_t_1 = PySequence_ITEM(__pyx_t_3, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); #endif } else { if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) __PYX_ERR(0, 30, __pyx_L1_error) #else __pyx_t_1 = PySequence_ITEM(__pyx_t_3, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 30, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); #endif } } else { __pyx_t_1 = __pyx_t_15(__pyx_t_3); if (unlikely(!__pyx_t_1)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(0, 30, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_1); } __Pyx_XDECREF_SET(__pyx_v_y, __pyx_t_1); __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":31 * for x in range(max(0, -offset_x), min(img_width, self.width - offset_x)): * for y in range(max(0, -offset_y), min(img_height, self.height - offset_y)): * (r, g, b) = pixels[x, y] # <<<<<<<<<<<<<< * self.SetPixel(x + offset_x, y + offset_y, r, g, b) * */ __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_x); __Pyx_GIVEREF(__pyx_v_x); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_x); __Pyx_INCREF(__pyx_v_y); __Pyx_GIVEREF(__pyx_v_y); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_y); __pyx_t_9 = PyObject_GetItem(__pyx_v_pixels, __pyx_t_1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if ((likely(PyTuple_CheckExact(__pyx_t_9))) || (PyList_CheckExact(__pyx_t_9))) { PyObject* sequence = __pyx_t_9; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 3)) { if (size > 3) __Pyx_RaiseTooManyValuesError(3); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(0, 31, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS if (likely(PyTuple_CheckExact(sequence))) { __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __pyx_t_7 = PyTuple_GET_ITEM(sequence, 2); } else { __pyx_t_1 = PyList_GET_ITEM(sequence, 0); __pyx_t_4 = PyList_GET_ITEM(sequence, 1); __pyx_t_7 = PyList_GET_ITEM(sequence, 2); } __Pyx_INCREF(__pyx_t_1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx_t_7); #else __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_7 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #endif __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { Py_ssize_t index = -1; __pyx_t_16 = PyObject_GetIter(__pyx_t_9); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_6 = Py_TYPE(__pyx_t_16)->tp_iternext; index = 0; __pyx_t_1 = __pyx_t_6(__pyx_t_16); if (unlikely(!__pyx_t_1)) goto __pyx_L13_unpacking_failed; __Pyx_GOTREF(__pyx_t_1); index = 1; __pyx_t_4 = __pyx_t_6(__pyx_t_16); if (unlikely(!__pyx_t_4)) goto __pyx_L13_unpacking_failed; __Pyx_GOTREF(__pyx_t_4); index = 2; __pyx_t_7 = __pyx_t_6(__pyx_t_16); if (unlikely(!__pyx_t_7)) goto __pyx_L13_unpacking_failed; __Pyx_GOTREF(__pyx_t_7); if (__Pyx_IternextUnpackEndCheck(__pyx_t_6(__pyx_t_16), 3) < 0) __PYX_ERR(0, 31, __pyx_L1_error) __pyx_t_6 = NULL; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; goto __pyx_L14_unpacking_done; __pyx_L13_unpacking_failed:; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; __pyx_t_6 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); __PYX_ERR(0, 31, __pyx_L1_error) __pyx_L14_unpacking_done:; } __Pyx_XDECREF_SET(__pyx_v_r, __pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF_SET(__pyx_v_g, __pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF_SET(__pyx_v_b, __pyx_t_7); __pyx_t_7 = 0; /* "rgbmatrix/core.pyx":32 * for y in range(max(0, -offset_y), min(img_height, self.height - offset_y)): * (r, g, b) = pixels[x, y] * self.SetPixel(x + offset_x, y + offset_y, r, g, b) # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_SetPixel); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_offset_x); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = PyNumber_Add(__pyx_v_x, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_offset_y); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_16 = PyNumber_Add(__pyx_v_y, __pyx_t_4); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_7); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_7, function); __pyx_t_8 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_7)) { PyObject *__pyx_temp[6] = {__pyx_t_4, __pyx_t_1, __pyx_t_16, __pyx_v_r, __pyx_v_g, __pyx_v_b}; __pyx_t_9 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_8, 5+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { PyObject *__pyx_temp[6] = {__pyx_t_4, __pyx_t_1, __pyx_t_16, __pyx_v_r, __pyx_v_g, __pyx_v_b}; __pyx_t_9 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_8, 5+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; } else #endif { __pyx_t_17 = PyTuple_New(5+__pyx_t_8); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_17); if (__pyx_t_4) { __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_17, 0, __pyx_t_4); __pyx_t_4 = NULL; } __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_17, 0+__pyx_t_8, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_16); PyTuple_SET_ITEM(__pyx_t_17, 1+__pyx_t_8, __pyx_t_16); __Pyx_INCREF(__pyx_v_r); __Pyx_GIVEREF(__pyx_v_r); PyTuple_SET_ITEM(__pyx_t_17, 2+__pyx_t_8, __pyx_v_r); __Pyx_INCREF(__pyx_v_g); __Pyx_GIVEREF(__pyx_v_g); PyTuple_SET_ITEM(__pyx_t_17, 3+__pyx_t_8, __pyx_v_g); __Pyx_INCREF(__pyx_v_b); __Pyx_GIVEREF(__pyx_v_b); PyTuple_SET_ITEM(__pyx_t_17, 4+__pyx_t_8, __pyx_v_b); __pyx_t_1 = 0; __pyx_t_16 = 0; __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_17, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 32, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; } __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; /* "rgbmatrix/core.pyx":30 * pixels = image.load() * for x in range(max(0, -offset_x), min(img_width, self.width - offset_x)): * for y in range(max(0, -offset_y), min(img_height, self.height - offset_y)): # <<<<<<<<<<<<<< * (r, g, b) = pixels[x, y] * self.SetPixel(x + offset_x, y + offset_y, r, g, b) */ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "rgbmatrix/core.pyx":29 * img_width, img_height = image.size * pixels = image.load() * for x in range(max(0, -offset_x), min(img_width, self.width - offset_x)): # <<<<<<<<<<<<<< * for y in range(max(0, -offset_y), min(img_height, self.height - offset_y)): * (r, g, b) = pixels[x, y] */ } __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __pyx_L4:; /* "rgbmatrix/core.pyx":12 * raise Exception("Not implemented") * * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): # <<<<<<<<<<<<<< * if (image.mode != "RGB"): * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_16); __Pyx_XDECREF(__pyx_t_17); __Pyx_AddTraceback("rgbmatrix.core.Canvas.SetImage", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_img_width); __Pyx_XDECREF(__pyx_v_img_height); __Pyx_XDECREF(__pyx_v_pixels); __Pyx_XDECREF(__pyx_v_x); __Pyx_XDECREF(__pyx_v_y); __Pyx_XDECREF(__pyx_v_r); __Pyx_XDECREF(__pyx_v_g); __Pyx_XDECREF(__pyx_v_b); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":36 * @cython.boundscheck(False) * @cython.wraparound(False) * def SetPixelsPillow(self, int xstart, int ystart, int width, int height, image): # <<<<<<<<<<<<<< * cdef cppinc.FrameCanvas* my_canvas = <cppinc.FrameCanvas*>self.__getCanvas() * cdef int frame_width = my_canvas.width() */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_6Canvas_3SetPixelsPillow(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_6Canvas_3SetPixelsPillow(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_xstart; int __pyx_v_ystart; int __pyx_v_width; int __pyx_v_height; PyObject *__pyx_v_image = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("SetPixelsPillow (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_xstart,&__pyx_n_s_ystart,&__pyx_n_s_width,&__pyx_n_s_height,&__pyx_n_s_image,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_xstart)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_ystart)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixelsPillow", 1, 5, 5, 1); __PYX_ERR(0, 36, __pyx_L3_error) } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_width)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixelsPillow", 1, 5, 5, 2); __PYX_ERR(0, 36, __pyx_L3_error) } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_height)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixelsPillow", 1, 5, 5, 3); __PYX_ERR(0, 36, __pyx_L3_error) } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_image)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixelsPillow", 1, 5, 5, 4); __PYX_ERR(0, 36, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "SetPixelsPillow") < 0)) __PYX_ERR(0, 36, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } __pyx_v_xstart = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_xstart == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 36, __pyx_L3_error) __pyx_v_ystart = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_ystart == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 36, __pyx_L3_error) __pyx_v_width = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_width == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 36, __pyx_L3_error) __pyx_v_height = __Pyx_PyInt_As_int(values[3]); if (unlikely((__pyx_v_height == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 36, __pyx_L3_error) __pyx_v_image = values[4]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("SetPixelsPillow", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 36, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.Canvas.SetPixelsPillow", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_6Canvas_2SetPixelsPillow(((struct __pyx_obj_9rgbmatrix_4core_Canvas *)__pyx_v_self), __pyx_v_xstart, __pyx_v_ystart, __pyx_v_width, __pyx_v_height, __pyx_v_image); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_6Canvas_2SetPixelsPillow(struct __pyx_obj_9rgbmatrix_4core_Canvas *__pyx_v_self, int __pyx_v_xstart, int __pyx_v_ystart, int __pyx_v_width, int __pyx_v_height, PyObject *__pyx_v_image) { rgb_matrix::FrameCanvas *__pyx_v_my_canvas; int __pyx_v_frame_width; int __pyx_v_frame_height; int __pyx_v_row; int __pyx_v_col; uint8_t __pyx_v_r; uint8_t __pyx_v_g; uint8_t __pyx_v_b; uint32_t **__pyx_v_image_ptr; uint32_t __pyx_v_pixel; PyObject *__pyx_v_ptr_tmp = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; uintptr_t __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; long __pyx_t_9; long __pyx_t_10; int __pyx_t_11; int __pyx_t_12; long __pyx_t_13; __Pyx_RefNannySetupContext("SetPixelsPillow", 0); /* "rgbmatrix/core.pyx":37 * @cython.wraparound(False) * def SetPixelsPillow(self, int xstart, int ystart, int width, int height, image): * cdef cppinc.FrameCanvas* my_canvas = <cppinc.FrameCanvas*>self.__getCanvas() # <<<<<<<<<<<<<< * cdef int frame_width = my_canvas.width() * cdef int frame_height = my_canvas.height() */ try { __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas *)__pyx_v_self->__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); } catch(...) { __Pyx_CppExn2PyErr(); __PYX_ERR(0, 37, __pyx_L1_error) } __pyx_v_my_canvas = ((rgb_matrix::FrameCanvas *)__pyx_t_1); /* "rgbmatrix/core.pyx":38 * def SetPixelsPillow(self, int xstart, int ystart, int width, int height, image): * cdef cppinc.FrameCanvas* my_canvas = <cppinc.FrameCanvas*>self.__getCanvas() * cdef int frame_width = my_canvas.width() # <<<<<<<<<<<<<< * cdef int frame_height = my_canvas.height() * cdef int row, col */ __pyx_v_frame_width = __pyx_v_my_canvas->width(); /* "rgbmatrix/core.pyx":39 * cdef cppinc.FrameCanvas* my_canvas = <cppinc.FrameCanvas*>self.__getCanvas() * cdef int frame_width = my_canvas.width() * cdef int frame_height = my_canvas.height() # <<<<<<<<<<<<<< * cdef int row, col * cdef uint8_t r, g, b */ __pyx_v_frame_height = __pyx_v_my_canvas->height(); /* "rgbmatrix/core.pyx":44 * cdef uint32_t **image_ptr * cdef uint32_t pixel * image.load() # <<<<<<<<<<<<<< * ptr_tmp = dict(image.im.unsafe_ptrs)['image32'] * image_ptr = (<uint32_t **>(<uintptr_t>ptr_tmp)) */ __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_image, __pyx_n_s_load); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 44, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } if (__pyx_t_4) { __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 44, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } else { __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 44, __pyx_L1_error) } __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "rgbmatrix/core.pyx":45 * cdef uint32_t pixel * image.load() * ptr_tmp = dict(image.im.unsafe_ptrs)['image32'] # <<<<<<<<<<<<<< * image_ptr = (<uint32_t **>(<uintptr_t>ptr_tmp)) * */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_image, __pyx_n_s_im); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 45, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_unsafe_ptrs); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 45, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 45, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)(&PyDict_Type)), __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 45, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyDict_GetItem(__pyx_t_3, __pyx_n_s_image32); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 45, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_ptr_tmp = __pyx_t_2; __pyx_t_2 = 0; /* "rgbmatrix/core.pyx":46 * image.load() * ptr_tmp = dict(image.im.unsafe_ptrs)['image32'] * image_ptr = (<uint32_t **>(<uintptr_t>ptr_tmp)) # <<<<<<<<<<<<<< * * for col in range(max(0, -xstart), min(width, frame_width - xstart)): */ __pyx_t_5 = __Pyx_PyInt_As_size_t(__pyx_v_ptr_tmp); if (unlikely((__pyx_t_5 == ((uintptr_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 46, __pyx_L1_error) __pyx_v_image_ptr = ((uint32_t **)((uintptr_t)__pyx_t_5)); /* "rgbmatrix/core.pyx":48 * image_ptr = (<uint32_t **>(<uintptr_t>ptr_tmp)) * * for col in range(max(0, -xstart), min(width, frame_width - xstart)): # <<<<<<<<<<<<<< * for row in range(max(0, -ystart), min(height, frame_height - ystart)): * pixel = image_ptr[row][col] */ __pyx_t_6 = (__pyx_v_frame_width - __pyx_v_xstart); __pyx_t_7 = __pyx_v_width; if (((__pyx_t_6 < __pyx_t_7) != 0)) { __pyx_t_8 = __pyx_t_6; } else { __pyx_t_8 = __pyx_t_7; } __pyx_t_6 = __pyx_t_8; __pyx_t_8 = (-__pyx_v_xstart); __pyx_t_9 = 0; if (((__pyx_t_8 > __pyx_t_9) != 0)) { __pyx_t_10 = __pyx_t_8; } else { __pyx_t_10 = __pyx_t_9; } for (__pyx_t_8 = __pyx_t_10; __pyx_t_8 < __pyx_t_6; __pyx_t_8+=1) { __pyx_v_col = __pyx_t_8; /* "rgbmatrix/core.pyx":49 * * for col in range(max(0, -xstart), min(width, frame_width - xstart)): * for row in range(max(0, -ystart), min(height, frame_height - ystart)): # <<<<<<<<<<<<<< * pixel = image_ptr[row][col] * r = (pixel ) & 0xFF */ __pyx_t_7 = (__pyx_v_frame_height - __pyx_v_ystart); __pyx_t_11 = __pyx_v_height; if (((__pyx_t_7 < __pyx_t_11) != 0)) { __pyx_t_12 = __pyx_t_7; } else { __pyx_t_12 = __pyx_t_11; } __pyx_t_7 = __pyx_t_12; __pyx_t_12 = (-__pyx_v_ystart); __pyx_t_9 = 0; if (((__pyx_t_12 > __pyx_t_9) != 0)) { __pyx_t_13 = __pyx_t_12; } else { __pyx_t_13 = __pyx_t_9; } for (__pyx_t_12 = __pyx_t_13; __pyx_t_12 < __pyx_t_7; __pyx_t_12+=1) { __pyx_v_row = __pyx_t_12; /* "rgbmatrix/core.pyx":50 * for col in range(max(0, -xstart), min(width, frame_width - xstart)): * for row in range(max(0, -ystart), min(height, frame_height - ystart)): * pixel = image_ptr[row][col] # <<<<<<<<<<<<<< * r = (pixel ) & 0xFF * g = (pixel >> 8) & 0xFF */ __pyx_v_pixel = ((__pyx_v_image_ptr[__pyx_v_row])[__pyx_v_col]); /* "rgbmatrix/core.pyx":51 * for row in range(max(0, -ystart), min(height, frame_height - ystart)): * pixel = image_ptr[row][col] * r = (pixel ) & 0xFF # <<<<<<<<<<<<<< * g = (pixel >> 8) & 0xFF * b = (pixel >> 16) & 0xFF */ __pyx_v_r = (__pyx_v_pixel & 0xFF); /* "rgbmatrix/core.pyx":52 * pixel = image_ptr[row][col] * r = (pixel ) & 0xFF * g = (pixel >> 8) & 0xFF # <<<<<<<<<<<<<< * b = (pixel >> 16) & 0xFF * my_canvas.SetPixel(xstart+col, ystart+row, r, g, b) */ __pyx_v_g = ((__pyx_v_pixel >> 8) & 0xFF); /* "rgbmatrix/core.pyx":53 * r = (pixel ) & 0xFF * g = (pixel >> 8) & 0xFF * b = (pixel >> 16) & 0xFF # <<<<<<<<<<<<<< * my_canvas.SetPixel(xstart+col, ystart+row, r, g, b) * */ __pyx_v_b = ((__pyx_v_pixel >> 16) & 0xFF); /* "rgbmatrix/core.pyx":54 * g = (pixel >> 8) & 0xFF * b = (pixel >> 16) & 0xFF * my_canvas.SetPixel(xstart+col, ystart+row, r, g, b) # <<<<<<<<<<<<<< * * cdef class FrameCanvas(Canvas): */ __pyx_v_my_canvas->SetPixel((__pyx_v_xstart + __pyx_v_col), (__pyx_v_ystart + __pyx_v_row), __pyx_v_r, __pyx_v_g, __pyx_v_b); } } /* "rgbmatrix/core.pyx":36 * @cython.boundscheck(False) * @cython.wraparound(False) * def SetPixelsPillow(self, int xstart, int ystart, int width, int height, image): # <<<<<<<<<<<<<< * cdef cppinc.FrameCanvas* my_canvas = <cppinc.FrameCanvas*>self.__getCanvas() * cdef int frame_width = my_canvas.width() */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("rgbmatrix.core.Canvas.SetPixelsPillow", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_ptr_tmp); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":57 * * cdef class FrameCanvas(Canvas): * def __dealloc__(self): # <<<<<<<<<<<<<< * if <void*>self.__canvas != NULL: * self.__canvas = NULL */ /* Python wrapper */ static void __pyx_pw_9rgbmatrix_4core_11FrameCanvas_1__dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_pw_9rgbmatrix_4core_11FrameCanvas_1__dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_pf_9rgbmatrix_4core_11FrameCanvas___dealloc__(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_9rgbmatrix_4core_11FrameCanvas___dealloc__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "rgbmatrix/core.pyx":58 * cdef class FrameCanvas(Canvas): * def __dealloc__(self): * if <void*>self.__canvas != NULL: # <<<<<<<<<<<<<< * self.__canvas = NULL * */ __pyx_t_1 = ((((void *)__pyx_v_self->__pyx___canvas) != NULL) != 0); if (__pyx_t_1) { /* "rgbmatrix/core.pyx":59 * def __dealloc__(self): * if <void*>self.__canvas != NULL: * self.__canvas = NULL # <<<<<<<<<<<<<< * * cdef cppinc.Canvas* __getCanvas(self) except *: */ __pyx_v_self->__pyx___canvas = NULL; /* "rgbmatrix/core.pyx":58 * cdef class FrameCanvas(Canvas): * def __dealloc__(self): * if <void*>self.__canvas != NULL: # <<<<<<<<<<<<<< * self.__canvas = NULL * */ } /* "rgbmatrix/core.pyx":57 * * cdef class FrameCanvas(Canvas): * def __dealloc__(self): # <<<<<<<<<<<<<< * if <void*>self.__canvas != NULL: * self.__canvas = NULL */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "rgbmatrix/core.pyx":61 * self.__canvas = NULL * * cdef cppinc.Canvas* __getCanvas(self) except *: # <<<<<<<<<<<<<< * if <void*>self.__canvas != NULL: * return self.__canvas */ rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_11FrameCanvas___getCanvas(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { rgb_matrix::Canvas *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__getCanvas", 0); /* "rgbmatrix/core.pyx":62 * * cdef cppinc.Canvas* __getCanvas(self) except *: * if <void*>self.__canvas != NULL: # <<<<<<<<<<<<<< * return self.__canvas * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") */ __pyx_t_1 = ((((void *)__pyx_v_self->__pyx___canvas) != NULL) != 0); if (__pyx_t_1) { /* "rgbmatrix/core.pyx":63 * cdef cppinc.Canvas* __getCanvas(self) except *: * if <void*>self.__canvas != NULL: * return self.__canvas # <<<<<<<<<<<<<< * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") * */ __pyx_r = __pyx_v_self->__pyx___canvas; goto __pyx_L0; /* "rgbmatrix/core.pyx":62 * * cdef cppinc.Canvas* __getCanvas(self) except *: * if <void*>self.__canvas != NULL: # <<<<<<<<<<<<<< * return self.__canvas * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") */ } /* "rgbmatrix/core.pyx":64 * if <void*>self.__canvas != NULL: * return self.__canvas * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") # <<<<<<<<<<<<<< * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): */ __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])), __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 64, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 64, __pyx_L1_error) /* "rgbmatrix/core.pyx":61 * self.__canvas = NULL * * cdef cppinc.Canvas* __getCanvas(self) except *: # <<<<<<<<<<<<<< * if <void*>self.__canvas != NULL: * return self.__canvas */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.__getCanvas", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_11FrameCanvas___getCanvas__pyx_wrap_1(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { return __pyx_f_9rgbmatrix_4core_11FrameCanvas___getCanvas(__pyx_v_self); } /* "rgbmatrix/core.pyx":66 * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * (<cppinc.FrameCanvas*>self.__getCanvas()).Fill(red, green, blue) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_3Fill(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_3Fill(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { uint8_t __pyx_v_red; uint8_t __pyx_v_green; uint8_t __pyx_v_blue; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Fill (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_red,&__pyx_n_s_green,&__pyx_n_s_blue,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_red)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_green)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("Fill", 1, 3, 3, 1); __PYX_ERR(0, 66, __pyx_L3_error) } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_blue)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("Fill", 1, 3, 3, 2); __PYX_ERR(0, 66, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "Fill") < 0)) __PYX_ERR(0, 66, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } __pyx_v_red = __Pyx_PyInt_As_uint8_t(values[0]); if (unlikely((__pyx_v_red == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 66, __pyx_L3_error) __pyx_v_green = __Pyx_PyInt_As_uint8_t(values[1]); if (unlikely((__pyx_v_green == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 66, __pyx_L3_error) __pyx_v_blue = __Pyx_PyInt_As_uint8_t(values[2]); if (unlikely((__pyx_v_blue == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 66, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("Fill", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 66, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.Fill", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_2Fill(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self), __pyx_v_red, __pyx_v_green, __pyx_v_blue); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_2Fill(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; __Pyx_RefNannySetupContext("Fill", 0); /* "rgbmatrix/core.pyx":67 * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): * (<cppinc.FrameCanvas*>self.__getCanvas()).Fill(red, green, blue) # <<<<<<<<<<<<<< * * def Clear(self): */ __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 67, __pyx_L1_error) ((rgb_matrix::FrameCanvas *)__pyx_t_1)->Fill(__pyx_v_red, __pyx_v_green, __pyx_v_blue); /* "rgbmatrix/core.pyx":66 * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * (<cppinc.FrameCanvas*>self.__getCanvas()).Fill(red, green, blue) * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.Fill", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":69 * (<cppinc.FrameCanvas*>self.__getCanvas()).Fill(red, green, blue) * * def Clear(self): # <<<<<<<<<<<<<< * (<cppinc.FrameCanvas*>self.__getCanvas()).Clear() * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_5Clear(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_5Clear(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Clear (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_4Clear(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_4Clear(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; __Pyx_RefNannySetupContext("Clear", 0); /* "rgbmatrix/core.pyx":70 * * def Clear(self): * (<cppinc.FrameCanvas*>self.__getCanvas()).Clear() # <<<<<<<<<<<<<< * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): */ __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 70, __pyx_L1_error) ((rgb_matrix::FrameCanvas *)__pyx_t_1)->Clear(); /* "rgbmatrix/core.pyx":69 * (<cppinc.FrameCanvas*>self.__getCanvas()).Fill(red, green, blue) * * def Clear(self): # <<<<<<<<<<<<<< * (<cppinc.FrameCanvas*>self.__getCanvas()).Clear() * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.Clear", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":72 * (<cppinc.FrameCanvas*>self.__getCanvas()).Clear() * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * (<cppinc.FrameCanvas*>self.__getCanvas()).SetPixel(x, y, red, green, blue) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_7SetPixel(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_7SetPixel(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_x; int __pyx_v_y; uint8_t __pyx_v_red; uint8_t __pyx_v_green; uint8_t __pyx_v_blue; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("SetPixel (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_x,&__pyx_n_s_y,&__pyx_n_s_red,&__pyx_n_s_green,&__pyx_n_s_blue,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 1); __PYX_ERR(0, 72, __pyx_L3_error) } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_red)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 2); __PYX_ERR(0, 72, __pyx_L3_error) } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_green)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 3); __PYX_ERR(0, 72, __pyx_L3_error) } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_blue)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 4); __PYX_ERR(0, 72, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "SetPixel") < 0)) __PYX_ERR(0, 72, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } __pyx_v_x = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_x == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 72, __pyx_L3_error) __pyx_v_y = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_y == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 72, __pyx_L3_error) __pyx_v_red = __Pyx_PyInt_As_uint8_t(values[2]); if (unlikely((__pyx_v_red == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 72, __pyx_L3_error) __pyx_v_green = __Pyx_PyInt_As_uint8_t(values[3]); if (unlikely((__pyx_v_green == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 72, __pyx_L3_error) __pyx_v_blue = __Pyx_PyInt_As_uint8_t(values[4]); if (unlikely((__pyx_v_blue == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 72, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 72, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.SetPixel", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_6SetPixel(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self), __pyx_v_x, __pyx_v_y, __pyx_v_red, __pyx_v_green, __pyx_v_blue); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_6SetPixel(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, int __pyx_v_x, int __pyx_v_y, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; __Pyx_RefNannySetupContext("SetPixel", 0); /* "rgbmatrix/core.pyx":73 * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): * (<cppinc.FrameCanvas*>self.__getCanvas()).SetPixel(x, y, red, green, blue) # <<<<<<<<<<<<<< * * */ __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 73, __pyx_L1_error) ((rgb_matrix::FrameCanvas *)__pyx_t_1)->SetPixel(__pyx_v_x, __pyx_v_y, __pyx_v_red, __pyx_v_green, __pyx_v_blue); /* "rgbmatrix/core.pyx":72 * (<cppinc.FrameCanvas*>self.__getCanvas()).Clear() * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * (<cppinc.FrameCanvas*>self.__getCanvas()).SetPixel(x, y, red, green, blue) * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.SetPixel", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":77 * * property width: * def __get__(self): return (<cppinc.FrameCanvas*>self.__getCanvas()).width() # <<<<<<<<<<<<<< * * property height: */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_5width_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_5width_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_5width___get__(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_5width___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 77, __pyx_L1_error) __pyx_t_2 = __Pyx_PyInt_From_int(((rgb_matrix::FrameCanvas *)__pyx_t_1)->width()); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.width.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":80 * * property height: * def __get__(self): return (<cppinc.FrameCanvas*>self.__getCanvas()).height() # <<<<<<<<<<<<<< * * property pwmBits: */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_6height_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_6height_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_6height___get__(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_6height___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 80, __pyx_L1_error) __pyx_t_2 = __Pyx_PyInt_From_int(((rgb_matrix::FrameCanvas *)__pyx_t_1)->height()); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.height.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":83 * * property pwmBits: * def __get__(self): return (<cppinc.FrameCanvas*>self.__getCanvas()).pwmbits() # <<<<<<<<<<<<<< * def __set__(self, pwmBits): (<cppinc.FrameCanvas*>self.__getCanvas()).SetPWMBits(pwmBits) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_7pwmBits_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_7pwmBits_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_7pwmBits___get__(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_7pwmBits___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 83, __pyx_L1_error) __pyx_t_2 = __Pyx_PyInt_From_uint8_t(((rgb_matrix::FrameCanvas *)__pyx_t_1)->pwmbits()); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.pwmBits.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":84 * property pwmBits: * def __get__(self): return (<cppinc.FrameCanvas*>self.__getCanvas()).pwmbits() * def __set__(self, pwmBits): (<cppinc.FrameCanvas*>self.__getCanvas()).SetPWMBits(pwmBits) # <<<<<<<<<<<<<< * * property brightness: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_11FrameCanvas_7pwmBits_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_pwmBits); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_11FrameCanvas_7pwmBits_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_pwmBits) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_7pwmBits_2__set__(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self), ((PyObject *)__pyx_v_pwmBits)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_11FrameCanvas_7pwmBits_2__set__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, PyObject *__pyx_v_pwmBits) { int __pyx_r; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; uint8_t __pyx_t_2; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 84, __pyx_L1_error) __pyx_t_2 = __Pyx_PyInt_As_uint8_t(__pyx_v_pwmBits); if (unlikely((__pyx_t_2 == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 84, __pyx_L1_error) ((rgb_matrix::FrameCanvas *)__pyx_t_1)->SetPWMBits(__pyx_t_2); /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.pwmBits.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":87 * * property brightness: * def __get__(self): return (<cppinc.FrameCanvas*>self.__getCanvas()).brightness() # <<<<<<<<<<<<<< * def __set__(self, val): (<cppinc.FrameCanvas*>self.__getCanvas()).SetBrightness(val) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_10brightness_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_11FrameCanvas_10brightness_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_10brightness___get__(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_11FrameCanvas_10brightness___get__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 87, __pyx_L1_error) __pyx_t_2 = __Pyx_PyInt_From_uint8_t(((rgb_matrix::FrameCanvas *)__pyx_t_1)->brightness()); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.brightness.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":88 * property brightness: * def __get__(self): return (<cppinc.FrameCanvas*>self.__getCanvas()).brightness() * def __set__(self, val): (<cppinc.FrameCanvas*>self.__getCanvas()).SetBrightness(val) # <<<<<<<<<<<<<< * * */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_11FrameCanvas_10brightness_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_val); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_11FrameCanvas_10brightness_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_val) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_11FrameCanvas_10brightness_2__set__(((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self), ((PyObject *)__pyx_v_val)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_11FrameCanvas_10brightness_2__set__(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_self, PyObject *__pyx_v_val) { int __pyx_r; __Pyx_RefNannyDeclarations rgb_matrix::Canvas *__pyx_t_1; uint8_t __pyx_t_2; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = ((struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx___getCanvas(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 88, __pyx_L1_error) __pyx_t_2 = __Pyx_PyInt_As_uint8_t(__pyx_v_val); if (unlikely((__pyx_t_2 == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 88, __pyx_L1_error) ((rgb_matrix::FrameCanvas *)__pyx_t_1)->SetBrightness(__pyx_t_2); /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.FrameCanvas.brightness.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":92 * * cdef class RGBMatrixOptions: * def __cinit__(self): # <<<<<<<<<<<<<< * self.__options = cppinc.Options() * self.__runtime_options = cppinc.RuntimeOptions() */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions___cinit__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions___cinit__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { int __pyx_r; __Pyx_RefNannyDeclarations struct rgb_matrix::RGBMatrix::Options __pyx_t_1; struct rgb_matrix::RuntimeOptions __pyx_t_2; __Pyx_RefNannySetupContext("__cinit__", 0); /* "rgbmatrix/core.pyx":93 * cdef class RGBMatrixOptions: * def __cinit__(self): * self.__options = cppinc.Options() # <<<<<<<<<<<<<< * self.__runtime_options = cppinc.RuntimeOptions() * */ __pyx_v_self->__pyx___options = __pyx_t_1; /* "rgbmatrix/core.pyx":94 * def __cinit__(self): * self.__options = cppinc.Options() * self.__runtime_options = cppinc.RuntimeOptions() # <<<<<<<<<<<<<< * * # RGBMatrix::Options properties */ __pyx_v_self->__pyx___runtime_options = __pyx_t_2; /* "rgbmatrix/core.pyx":92 * * cdef class RGBMatrixOptions: * def __cinit__(self): # <<<<<<<<<<<<<< * self.__options = cppinc.Options() * self.__runtime_options = cppinc.RuntimeOptions() */ /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":98 * # RGBMatrix::Options properties * property hardware_mapping: * def __get__(self): return self.__options.hardware_mapping # <<<<<<<<<<<<<< * def __set__(self, value): * self.__py_encoded_hardware_mapping = value.encode('utf-8') */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->__pyx___options.hardware_mapping); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 98, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.hardware_mapping.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":99 * property hardware_mapping: * def __get__(self): return self.__options.hardware_mapping * def __set__(self, value): # <<<<<<<<<<<<<< * self.__py_encoded_hardware_mapping = value.encode('utf-8') * self.__options.hardware_mapping = self.__py_encoded_hardware_mapping */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; char const *__pyx_t_3; __Pyx_RefNannySetupContext("__set__", 0); /* "rgbmatrix/core.pyx":100 * def __get__(self): return self.__options.hardware_mapping * def __set__(self, value): * self.__py_encoded_hardware_mapping = value.encode('utf-8') # <<<<<<<<<<<<<< * self.__options.hardware_mapping = self.__py_encoded_hardware_mapping * */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_value, __pyx_n_s_encode); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 100, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (!(likely(PyBytes_CheckExact(__pyx_t_2))||((__pyx_t_2) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_2)->tp_name), 0))) __PYX_ERR(0, 100, __pyx_L1_error) __Pyx_GIVEREF(__pyx_t_2); __Pyx_GOTREF(__pyx_v_self->__pyx___py_encoded_hardware_mapping); __Pyx_DECREF(__pyx_v_self->__pyx___py_encoded_hardware_mapping); __pyx_v_self->__pyx___py_encoded_hardware_mapping = ((PyObject*)__pyx_t_2); __pyx_t_2 = 0; /* "rgbmatrix/core.pyx":101 * def __set__(self, value): * self.__py_encoded_hardware_mapping = value.encode('utf-8') * self.__options.hardware_mapping = self.__py_encoded_hardware_mapping # <<<<<<<<<<<<<< * * property rows: */ __pyx_t_3 = __Pyx_PyObject_AsString(__pyx_v_self->__pyx___py_encoded_hardware_mapping); if (unlikely((!__pyx_t_3) && PyErr_Occurred())) __PYX_ERR(0, 101, __pyx_L1_error) __pyx_v_self->__pyx___options.hardware_mapping = __pyx_t_3; /* "rgbmatrix/core.pyx":99 * property hardware_mapping: * def __get__(self): return self.__options.hardware_mapping * def __set__(self, value): # <<<<<<<<<<<<<< * self.__py_encoded_hardware_mapping = value.encode('utf-8') * self.__options.hardware_mapping = self.__py_encoded_hardware_mapping */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.hardware_mapping.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":104 * * property rows: * def __get__(self): return self.__options.rows # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__options.rows = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_4rows_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_4rows_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_4rows___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_4rows___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___options.rows); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 104, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.rows.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":105 * property rows: * def __get__(self): return self.__options.rows * def __set__(self, uint8_t value): self.__options.rows = value # <<<<<<<<<<<<<< * * property chain_length: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_4rows_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_4rows_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 105, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.rows.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_4rows_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_4rows_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___options.rows = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":108 * * property chain_length: * def __get__(self): return self.__options.chain_length # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__options.chain_length = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___options.chain_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 108, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.chain_length.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":109 * property chain_length: * def __get__(self): return self.__options.chain_length * def __set__(self, uint8_t value): self.__options.chain_length = value # <<<<<<<<<<<<<< * * property parallel: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 109, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.chain_length.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___options.chain_length = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":112 * * property parallel: * def __get__(self): return self.__options.parallel # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__options.parallel = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8parallel___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8parallel___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___options.parallel); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.parallel.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":113 * property parallel: * def __get__(self): return self.__options.parallel * def __set__(self, uint8_t value): self.__options.parallel = value # <<<<<<<<<<<<<< * * property pwm_bits: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 113, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.parallel.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___options.parallel = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":116 * * property pwm_bits: * def __get__(self): return self.__options.pwm_bits # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__options.pwm_bits = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___options.pwm_bits); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 116, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.pwm_bits.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":117 * property pwm_bits: * def __get__(self): return self.__options.pwm_bits * def __set__(self, uint8_t value): self.__options.pwm_bits = value # <<<<<<<<<<<<<< * * property pwm_lsb_nanoseconds: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 117, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.pwm_bits.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___options.pwm_bits = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":120 * * property pwm_lsb_nanoseconds: * def __get__(self): return self.__options.pwm_lsb_nanoseconds # <<<<<<<<<<<<<< * def __set__(self, uint32_t value): self.__options.pwm_lsb_nanoseconds = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___options.pwm_lsb_nanoseconds); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 120, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.pwm_lsb_nanoseconds.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":121 * property pwm_lsb_nanoseconds: * def __get__(self): return self.__options.pwm_lsb_nanoseconds * def __set__(self, uint32_t value): self.__options.pwm_lsb_nanoseconds = value # <<<<<<<<<<<<<< * * property brightness: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint32_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint32_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 121, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.pwm_lsb_nanoseconds.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint32_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint32_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___options.pwm_lsb_nanoseconds = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":124 * * property brightness: * def __get__(self): return self.__options.brightness # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__options.brightness = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_10brightness___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_10brightness___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___options.brightness); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 124, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.brightness.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":125 * property brightness: * def __get__(self): return self.__options.brightness * def __set__(self, uint8_t value): self.__options.brightness = value # <<<<<<<<<<<<<< * * property scan_mode: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 125, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.brightness.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___options.brightness = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":128 * * property scan_mode: * def __get__(self): return self.__options.scan_mode # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__options.scan_mode = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___options.scan_mode); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 128, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.scan_mode.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":129 * property scan_mode: * def __get__(self): return self.__options.scan_mode * def __set__(self, uint8_t value): self.__options.scan_mode = value # <<<<<<<<<<<<<< * * property disable_hardware_pulsing: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 129, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.scan_mode.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___options.scan_mode = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":132 * * property disable_hardware_pulsing: * def __get__(self): return self.__options.disable_hardware_pulsing # <<<<<<<<<<<<<< * def __set__(self, value): self.__options.disable_hardware_pulsing = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->__pyx___options.disable_hardware_pulsing); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 132, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.disable_hardware_pulsing.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":133 * property disable_hardware_pulsing: * def __get__(self): return self.__options.disable_hardware_pulsing * def __set__(self, value): self.__options.disable_hardware_pulsing = value # <<<<<<<<<<<<<< * * property show_refresh_rate: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations bool __pyx_t_1; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_value); if (unlikely((__pyx_t_1 == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 133, __pyx_L1_error) __pyx_v_self->__pyx___options.disable_hardware_pulsing = __pyx_t_1; /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.disable_hardware_pulsing.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":136 * * property show_refresh_rate: * def __get__(self): return self.__options.show_refresh_rate # <<<<<<<<<<<<<< * def __set__(self, value): self.__options.show_refresh_rate = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->__pyx___options.show_refresh_rate); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 136, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.show_refresh_rate.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":137 * property show_refresh_rate: * def __get__(self): return self.__options.show_refresh_rate * def __set__(self, value): self.__options.show_refresh_rate = value # <<<<<<<<<<<<<< * * property swap_green_blue: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations bool __pyx_t_1; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_value); if (unlikely((__pyx_t_1 == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 137, __pyx_L1_error) __pyx_v_self->__pyx___options.show_refresh_rate = __pyx_t_1; /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.show_refresh_rate.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":140 * * property swap_green_blue: * def __get__(self): return self.__options.swap_green_blue # <<<<<<<<<<<<<< * def __set__(self, value): self.__options.swap_green_blue = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->__pyx___options.swap_green_blue); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 140, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.swap_green_blue.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":141 * property swap_green_blue: * def __get__(self): return self.__options.swap_green_blue * def __set__(self, value): self.__options.swap_green_blue = value # <<<<<<<<<<<<<< * * property inverse_colors: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations bool __pyx_t_1; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_value); if (unlikely((__pyx_t_1 == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 141, __pyx_L1_error) __pyx_v_self->__pyx___options.swap_green_blue = __pyx_t_1; /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.swap_green_blue.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":144 * * property inverse_colors: * def __get__(self): return self.__options.inverse_colors # <<<<<<<<<<<<<< * def __set__(self, value): self.__options.inverse_colors = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->__pyx___options.inverse_colors); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 144, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.inverse_colors.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":145 * property inverse_colors: * def __get__(self): return self.__options.inverse_colors * def __set__(self, value): self.__options.inverse_colors = value # <<<<<<<<<<<<<< * * # RuntimeOptions properties */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations bool __pyx_t_1; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_value); if (unlikely((__pyx_t_1 == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 145, __pyx_L1_error) __pyx_v_self->__pyx___options.inverse_colors = __pyx_t_1; /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.inverse_colors.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":150 * * property gpio_slowdown: * def __get__(self): return self.__runtime_options.gpio_slowdown # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__runtime_options.gpio_slowdown = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___runtime_options.gpio_slowdown); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 150, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.gpio_slowdown.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":151 * property gpio_slowdown: * def __get__(self): return self.__runtime_options.gpio_slowdown * def __set__(self, uint8_t value): self.__runtime_options.gpio_slowdown = value # <<<<<<<<<<<<<< * * property daemon: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 151, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.gpio_slowdown.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___runtime_options.gpio_slowdown = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":154 * * property daemon: * def __get__(self): return self.__runtime_options.daemon # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__runtime_options.daemon = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_6daemon___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_6daemon___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___runtime_options.daemon); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 154, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.daemon.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":155 * property daemon: * def __get__(self): return self.__runtime_options.daemon * def __set__(self, uint8_t value): self.__runtime_options.daemon = value # <<<<<<<<<<<<<< * * property drop_privileges: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 155, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.daemon.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___runtime_options.daemon = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":158 * * property drop_privileges: * def __get__(self): return self.__runtime_options.drop_privileges # <<<<<<<<<<<<<< * def __set__(self, uint8_t value): self.__runtime_options.drop_privileges = value * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___runtime_options.drop_privileges); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 158, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.drop_privileges.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":159 * property drop_privileges: * def __get__(self): return self.__runtime_options.drop_privileges * def __set__(self, uint8_t value): self.__runtime_options.drop_privileges = value # <<<<<<<<<<<<<< * * */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_arg_value) { uint8_t __pyx_v_value; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); assert(__pyx_arg_value); { __pyx_v_value = __Pyx_PyInt_As_uint8_t(__pyx_arg_value); if (unlikely((__pyx_v_value == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 159, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrixOptions.drop_privileges.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_v_self), ((uint8_t)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_self, uint8_t __pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__", 0); __pyx_v_self->__pyx___runtime_options.drop_privileges = __pyx_v_value; /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":163 * * cdef class RGBMatrix(Canvas): * def __cinit__(self, int rows = 0, int chains = 0, int parallel = 0, # <<<<<<<<<<<<<< * RGBMatrixOptions options = None): * */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_rows; int __pyx_v_chains; int __pyx_v_parallel; struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_options = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_rows,&__pyx_n_s_chains,&__pyx_n_s_parallel,&__pyx_n_s_options,0}; PyObject* values[4] = {0,0,0,0}; /* "rgbmatrix/core.pyx":164 * cdef class RGBMatrix(Canvas): * def __cinit__(self, int rows = 0, int chains = 0, int parallel = 0, * RGBMatrixOptions options = None): # <<<<<<<<<<<<<< * * # If RGBMatrixOptions not provided, create defaults and set any optional */ values[3] = (PyObject *)((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)Py_None); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_rows); if (value) { values[0] = value; kw_args--; } } case 1: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_chains); if (value) { values[1] = value; kw_args--; } } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_parallel); if (value) { values[2] = value; kw_args--; } } case 3: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_options); if (value) { values[3] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(0, 163, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } } if (values[0]) { __pyx_v_rows = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_rows == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 163, __pyx_L3_error) } else { __pyx_v_rows = ((int)0); } if (values[1]) { __pyx_v_chains = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_chains == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 163, __pyx_L3_error) } else { __pyx_v_chains = ((int)0); } if (values[2]) { __pyx_v_parallel = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_parallel == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 163, __pyx_L3_error) } else { __pyx_v_parallel = ((int)0); } __pyx_v_options = ((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)values[3]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 0, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 163, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_options), __pyx_ptype_9rgbmatrix_4core_RGBMatrixOptions, 1, "options", 0))) __PYX_ERR(0, 164, __pyx_L1_error) __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix___cinit__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self), __pyx_v_rows, __pyx_v_chains, __pyx_v_parallel, __pyx_v_options); /* "rgbmatrix/core.pyx":163 * * cdef class RGBMatrix(Canvas): * def __cinit__(self, int rows = 0, int chains = 0, int parallel = 0, # <<<<<<<<<<<<<< * RGBMatrixOptions options = None): * */ /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix___cinit__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, int __pyx_v_rows, int __pyx_v_chains, int __pyx_v_parallel, struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *__pyx_v_options) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF((PyObject *)__pyx_v_options); /* "rgbmatrix/core.pyx":168 * # If RGBMatrixOptions not provided, create defaults and set any optional * # parameters supplied * if options == None: # <<<<<<<<<<<<<< * options = RGBMatrixOptions() * */ __pyx_t_1 = PyObject_RichCompare(((PyObject *)__pyx_v_options), Py_None, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 168, __pyx_L1_error) __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 168, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_2) { /* "rgbmatrix/core.pyx":169 * # parameters supplied * if options == None: * options = RGBMatrixOptions() # <<<<<<<<<<<<<< * * if rows > 0: */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_9rgbmatrix_4core_RGBMatrixOptions), __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 169, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF_SET(__pyx_v_options, ((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)__pyx_t_1)); __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":168 * # If RGBMatrixOptions not provided, create defaults and set any optional * # parameters supplied * if options == None: # <<<<<<<<<<<<<< * options = RGBMatrixOptions() * */ } /* "rgbmatrix/core.pyx":171 * options = RGBMatrixOptions() * * if rows > 0: # <<<<<<<<<<<<<< * options.rows = rows * if chains > 0: */ __pyx_t_2 = ((__pyx_v_rows > 0) != 0); if (__pyx_t_2) { /* "rgbmatrix/core.pyx":172 * * if rows > 0: * options.rows = rows # <<<<<<<<<<<<<< * if chains > 0: * options.chain_length = chains */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_rows); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 172, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (__Pyx_PyObject_SetAttrStr(((PyObject *)__pyx_v_options), __pyx_n_s_rows, __pyx_t_1) < 0) __PYX_ERR(0, 172, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":171 * options = RGBMatrixOptions() * * if rows > 0: # <<<<<<<<<<<<<< * options.rows = rows * if chains > 0: */ } /* "rgbmatrix/core.pyx":173 * if rows > 0: * options.rows = rows * if chains > 0: # <<<<<<<<<<<<<< * options.chain_length = chains * if parallel > 0: */ __pyx_t_2 = ((__pyx_v_chains > 0) != 0); if (__pyx_t_2) { /* "rgbmatrix/core.pyx":174 * options.rows = rows * if chains > 0: * options.chain_length = chains # <<<<<<<<<<<<<< * if parallel > 0: * options.parallel = parallel */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_chains); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 174, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (__Pyx_PyObject_SetAttrStr(((PyObject *)__pyx_v_options), __pyx_n_s_chain_length, __pyx_t_1) < 0) __PYX_ERR(0, 174, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":173 * if rows > 0: * options.rows = rows * if chains > 0: # <<<<<<<<<<<<<< * options.chain_length = chains * if parallel > 0: */ } /* "rgbmatrix/core.pyx":175 * if chains > 0: * options.chain_length = chains * if parallel > 0: # <<<<<<<<<<<<<< * options.parallel = parallel * */ __pyx_t_2 = ((__pyx_v_parallel > 0) != 0); if (__pyx_t_2) { /* "rgbmatrix/core.pyx":176 * options.chain_length = chains * if parallel > 0: * options.parallel = parallel # <<<<<<<<<<<<<< * * self.__matrix = cppinc.CreateMatrixFromOptions(options.__options, */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_parallel); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (__Pyx_PyObject_SetAttrStr(((PyObject *)__pyx_v_options), __pyx_n_s_parallel, __pyx_t_1) < 0) __PYX_ERR(0, 176, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":175 * if chains > 0: * options.chain_length = chains * if parallel > 0: # <<<<<<<<<<<<<< * options.parallel = parallel * */ } /* "rgbmatrix/core.pyx":178 * options.parallel = parallel * * self.__matrix = cppinc.CreateMatrixFromOptions(options.__options, # <<<<<<<<<<<<<< * options.__runtime_options) * */ __pyx_v_self->__pyx___matrix = rgb_matrix::CreateMatrixFromOptions(__pyx_v_options->__pyx___options, __pyx_v_options->__pyx___runtime_options); /* "rgbmatrix/core.pyx":163 * * cdef class RGBMatrix(Canvas): * def __cinit__(self, int rows = 0, int chains = 0, int parallel = 0, # <<<<<<<<<<<<<< * RGBMatrixOptions options = None): * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_options); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":181 * options.__runtime_options) * * def __dealloc__(self): # <<<<<<<<<<<<<< * self.__matrix.Clear() * del self.__matrix */ /* Python wrapper */ static void __pyx_pw_9rgbmatrix_4core_9RGBMatrix_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_pw_9rgbmatrix_4core_9RGBMatrix_3__dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_pf_9rgbmatrix_4core_9RGBMatrix_2__dealloc__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_9rgbmatrix_4core_9RGBMatrix_2__dealloc__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); /* "rgbmatrix/core.pyx":182 * * def __dealloc__(self): * self.__matrix.Clear() # <<<<<<<<<<<<<< * del self.__matrix * */ __pyx_v_self->__pyx___matrix->Clear(); /* "rgbmatrix/core.pyx":183 * def __dealloc__(self): * self.__matrix.Clear() * del self.__matrix # <<<<<<<<<<<<<< * * cdef cppinc.Canvas* __getCanvas(self) except *: */ delete __pyx_v_self->__pyx___matrix; /* "rgbmatrix/core.pyx":181 * options.__runtime_options) * * def __dealloc__(self): # <<<<<<<<<<<<<< * self.__matrix.Clear() * del self.__matrix */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "rgbmatrix/core.pyx":185 * del self.__matrix * * cdef cppinc.Canvas* __getCanvas(self) except *: # <<<<<<<<<<<<<< * if <void*>self.__matrix != NULL: * return self.__matrix */ rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_9RGBMatrix___getCanvas(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { rgb_matrix::Canvas *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannySetupContext("__getCanvas", 0); /* "rgbmatrix/core.pyx":186 * * cdef cppinc.Canvas* __getCanvas(self) except *: * if <void*>self.__matrix != NULL: # <<<<<<<<<<<<<< * return self.__matrix * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") */ __pyx_t_1 = ((((void *)__pyx_v_self->__pyx___matrix) != NULL) != 0); if (__pyx_t_1) { /* "rgbmatrix/core.pyx":187 * cdef cppinc.Canvas* __getCanvas(self) except *: * if <void*>self.__matrix != NULL: * return self.__matrix # <<<<<<<<<<<<<< * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") * */ __pyx_r = __pyx_v_self->__pyx___matrix; goto __pyx_L0; /* "rgbmatrix/core.pyx":186 * * cdef cppinc.Canvas* __getCanvas(self) except *: * if <void*>self.__matrix != NULL: # <<<<<<<<<<<<<< * return self.__matrix * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") */ } /* "rgbmatrix/core.pyx":188 * if <void*>self.__matrix != NULL: * return self.__matrix * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") # <<<<<<<<<<<<<< * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): */ __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0])), __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 188, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 188, __pyx_L1_error) /* "rgbmatrix/core.pyx":185 * del self.__matrix * * cdef cppinc.Canvas* __getCanvas(self) except *: # <<<<<<<<<<<<<< * if <void*>self.__matrix != NULL: * return self.__matrix */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.__getCanvas", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } rgb_matrix::Canvas *__pyx_f_9rgbmatrix_4core_9RGBMatrix___getCanvas__pyx_wrap_1(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { return __pyx_f_9rgbmatrix_4core_9RGBMatrix___getCanvas(__pyx_v_self); } /* "rgbmatrix/core.pyx":190 * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * self.__matrix.Fill(red, green, blue) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_5Fill(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_5Fill(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { uint8_t __pyx_v_red; uint8_t __pyx_v_green; uint8_t __pyx_v_blue; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Fill (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_red,&__pyx_n_s_green,&__pyx_n_s_blue,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_red)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_green)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("Fill", 1, 3, 3, 1); __PYX_ERR(0, 190, __pyx_L3_error) } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_blue)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("Fill", 1, 3, 3, 2); __PYX_ERR(0, 190, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "Fill") < 0)) __PYX_ERR(0, 190, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } __pyx_v_red = __Pyx_PyInt_As_uint8_t(values[0]); if (unlikely((__pyx_v_red == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 190, __pyx_L3_error) __pyx_v_green = __Pyx_PyInt_As_uint8_t(values[1]); if (unlikely((__pyx_v_green == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 190, __pyx_L3_error) __pyx_v_blue = __Pyx_PyInt_As_uint8_t(values[2]); if (unlikely((__pyx_v_blue == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 190, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("Fill", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 190, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.Fill", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_4Fill(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self), __pyx_v_red, __pyx_v_green, __pyx_v_blue); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_4Fill(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Fill", 0); /* "rgbmatrix/core.pyx":191 * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): * self.__matrix.Fill(red, green, blue) # <<<<<<<<<<<<<< * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): */ __pyx_v_self->__pyx___matrix->Fill(__pyx_v_red, __pyx_v_green, __pyx_v_blue); /* "rgbmatrix/core.pyx":190 * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * self.__matrix.Fill(red, green, blue) * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":193 * self.__matrix.Fill(red, green, blue) * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * self.__matrix.SetPixel(x, y, red, green, blue) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_7SetPixel(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_7SetPixel(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { int __pyx_v_x; int __pyx_v_y; uint8_t __pyx_v_red; uint8_t __pyx_v_green; uint8_t __pyx_v_blue; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("SetPixel (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_x,&__pyx_n_s_y,&__pyx_n_s_red,&__pyx_n_s_green,&__pyx_n_s_blue,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 1); __PYX_ERR(0, 193, __pyx_L3_error) } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_red)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 2); __PYX_ERR(0, 193, __pyx_L3_error) } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_green)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 3); __PYX_ERR(0, 193, __pyx_L3_error) } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_blue)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, 4); __PYX_ERR(0, 193, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "SetPixel") < 0)) __PYX_ERR(0, 193, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } __pyx_v_x = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_x == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 193, __pyx_L3_error) __pyx_v_y = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_y == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 193, __pyx_L3_error) __pyx_v_red = __Pyx_PyInt_As_uint8_t(values[2]); if (unlikely((__pyx_v_red == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 193, __pyx_L3_error) __pyx_v_green = __Pyx_PyInt_As_uint8_t(values[3]); if (unlikely((__pyx_v_green == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 193, __pyx_L3_error) __pyx_v_blue = __Pyx_PyInt_As_uint8_t(values[4]); if (unlikely((__pyx_v_blue == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 193, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("SetPixel", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 193, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.SetPixel", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_6SetPixel(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self), __pyx_v_x, __pyx_v_y, __pyx_v_red, __pyx_v_green, __pyx_v_blue); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_6SetPixel(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, int __pyx_v_x, int __pyx_v_y, uint8_t __pyx_v_red, uint8_t __pyx_v_green, uint8_t __pyx_v_blue) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("SetPixel", 0); /* "rgbmatrix/core.pyx":194 * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): * self.__matrix.SetPixel(x, y, red, green, blue) # <<<<<<<<<<<<<< * * def Clear(self): */ __pyx_v_self->__pyx___matrix->SetPixel(__pyx_v_x, __pyx_v_y, __pyx_v_red, __pyx_v_green, __pyx_v_blue); /* "rgbmatrix/core.pyx":193 * self.__matrix.Fill(red, green, blue) * * def SetPixel(self, int x, int y, uint8_t red, uint8_t green, uint8_t blue): # <<<<<<<<<<<<<< * self.__matrix.SetPixel(x, y, red, green, blue) * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":196 * self.__matrix.SetPixel(x, y, red, green, blue) * * def Clear(self): # <<<<<<<<<<<<<< * self.__matrix.Clear() * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_9Clear(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_9Clear(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Clear (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_8Clear(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_8Clear(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("Clear", 0); /* "rgbmatrix/core.pyx":197 * * def Clear(self): * self.__matrix.Clear() # <<<<<<<<<<<<<< * * def CreateFrameCanvas(self): */ __pyx_v_self->__pyx___matrix->Clear(); /* "rgbmatrix/core.pyx":196 * self.__matrix.SetPixel(x, y, red, green, blue) * * def Clear(self): # <<<<<<<<<<<<<< * self.__matrix.Clear() * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":199 * self.__matrix.Clear() * * def CreateFrameCanvas(self): # <<<<<<<<<<<<<< * return __createFrameCanvas(self.__matrix.CreateFrameCanvas()) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_11CreateFrameCanvas(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_11CreateFrameCanvas(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("CreateFrameCanvas (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_10CreateFrameCanvas(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_10CreateFrameCanvas(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("CreateFrameCanvas", 0); /* "rgbmatrix/core.pyx":200 * * def CreateFrameCanvas(self): * return __createFrameCanvas(self.__matrix.CreateFrameCanvas()) # <<<<<<<<<<<<<< * * def SwapOnVSync(self, FrameCanvas newFrame): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_f_9rgbmatrix_4core___createFrameCanvas(__pyx_v_self->__pyx___matrix->CreateFrameCanvas()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 200, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "rgbmatrix/core.pyx":199 * self.__matrix.Clear() * * def CreateFrameCanvas(self): # <<<<<<<<<<<<<< * return __createFrameCanvas(self.__matrix.CreateFrameCanvas()) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.CreateFrameCanvas", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":202 * return __createFrameCanvas(self.__matrix.CreateFrameCanvas()) * * def SwapOnVSync(self, FrameCanvas newFrame): # <<<<<<<<<<<<<< * return __createFrameCanvas(self.__matrix.SwapOnVSync(newFrame.__canvas)) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_13SwapOnVSync(PyObject *__pyx_v_self, PyObject *__pyx_v_newFrame); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_13SwapOnVSync(PyObject *__pyx_v_self, PyObject *__pyx_v_newFrame) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("SwapOnVSync (wrapper)", 0); if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_newFrame), __pyx_ptype_9rgbmatrix_4core_FrameCanvas, 1, "newFrame", 0))) __PYX_ERR(0, 202, __pyx_L1_error) __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_12SwapOnVSync(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self), ((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_v_newFrame)); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_12SwapOnVSync(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_newFrame) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("SwapOnVSync", 0); /* "rgbmatrix/core.pyx":203 * * def SwapOnVSync(self, FrameCanvas newFrame): * return __createFrameCanvas(self.__matrix.SwapOnVSync(newFrame.__canvas)) # <<<<<<<<<<<<<< * * property luminanceCorrect: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_f_9rgbmatrix_4core___createFrameCanvas(__pyx_v_self->__pyx___matrix->SwapOnVSync(__pyx_v_newFrame->__pyx___canvas)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 203, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "rgbmatrix/core.pyx":202 * return __createFrameCanvas(self.__matrix.CreateFrameCanvas()) * * def SwapOnVSync(self, FrameCanvas newFrame): # <<<<<<<<<<<<<< * return __createFrameCanvas(self.__matrix.SwapOnVSync(newFrame.__canvas)) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.SwapOnVSync", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":206 * * property luminanceCorrect: * def __get__(self): return self.__matrix.luminance_correct() # <<<<<<<<<<<<<< * def __set__(self, luminanceCorrect): self.__matrix.set_luminance_correct(luminanceCorrect) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->__pyx___matrix->luminance_correct()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 206, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.luminanceCorrect.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":207 * property luminanceCorrect: * def __get__(self): return self.__matrix.luminance_correct() * def __set__(self, luminanceCorrect): self.__matrix.set_luminance_correct(luminanceCorrect) # <<<<<<<<<<<<<< * * property pwmBits: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_luminanceCorrect); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_luminanceCorrect) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self), ((PyObject *)__pyx_v_luminanceCorrect)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, PyObject *__pyx_v_luminanceCorrect) { int __pyx_r; __Pyx_RefNannyDeclarations bool __pyx_t_1; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_luminanceCorrect); if (unlikely((__pyx_t_1 == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 207, __pyx_L1_error) __pyx_v_self->__pyx___matrix->set_luminance_correct(__pyx_t_1); /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.luminanceCorrect.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":210 * * property pwmBits: * def __get__(self): return self.__matrix.pwmbits() # <<<<<<<<<<<<<< * def __set__(self, pwmBits): self.__matrix.SetPWMBits(pwmBits) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_7pwmBits_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_7pwmBits_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_7pwmBits___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_7pwmBits___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_uint8_t(__pyx_v_self->__pyx___matrix->pwmbits()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 210, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.pwmBits.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":211 * property pwmBits: * def __get__(self): return self.__matrix.pwmbits() * def __set__(self, pwmBits): self.__matrix.SetPWMBits(pwmBits) # <<<<<<<<<<<<<< * * property brightness: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_7pwmBits_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_pwmBits); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_7pwmBits_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_pwmBits) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_7pwmBits_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self), ((PyObject *)__pyx_v_pwmBits)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix_7pwmBits_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, PyObject *__pyx_v_pwmBits) { int __pyx_r; __Pyx_RefNannyDeclarations uint8_t __pyx_t_1; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = __Pyx_PyInt_As_uint8_t(__pyx_v_pwmBits); if (unlikely((__pyx_t_1 == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 211, __pyx_L1_error) __pyx_v_self->__pyx___matrix->SetPWMBits(__pyx_t_1); /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.pwmBits.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":214 * * property brightness: * def __get__(self): return self.__matrix.brightness() # <<<<<<<<<<<<<< * def __set__(self, brightness): self.__matrix.SetBrightness(brightness) * */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_10brightness_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_10brightness_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_10brightness___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_10brightness___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_uint8_t(__pyx_v_self->__pyx___matrix->brightness()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 214, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.brightness.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":215 * property brightness: * def __get__(self): return self.__matrix.brightness() * def __set__(self, brightness): self.__matrix.SetBrightness(brightness) # <<<<<<<<<<<<<< * * property height: */ /* Python wrapper */ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_10brightness_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_brightness); /*proto*/ static int __pyx_pw_9rgbmatrix_4core_9RGBMatrix_10brightness_3__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_brightness) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_10brightness_2__set__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self), ((PyObject *)__pyx_v_brightness)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_9rgbmatrix_4core_9RGBMatrix_10brightness_2__set__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self, PyObject *__pyx_v_brightness) { int __pyx_r; __Pyx_RefNannyDeclarations uint8_t __pyx_t_1; __Pyx_RefNannySetupContext("__set__", 0); __pyx_t_1 = __Pyx_PyInt_As_uint8_t(__pyx_v_brightness); if (unlikely((__pyx_t_1 == ((uint8_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 215, __pyx_L1_error) __pyx_v_self->__pyx___matrix->SetBrightness(__pyx_t_1); /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.brightness.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":218 * * property height: * def __get__(self): return self.__matrix.height() # <<<<<<<<<<<<<< * * property width: */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_6height_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_6height_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_6height___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_6height___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___matrix->height()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.height.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":221 * * property width: * def __get__(self): return self.__matrix.width() # <<<<<<<<<<<<<< * * cdef __createFrameCanvas(cppinc.FrameCanvas* newCanvas): */ /* Python wrapper */ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_5width_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_9rgbmatrix_4core_9RGBMatrix_5width_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_9rgbmatrix_4core_9RGBMatrix_5width___get__(((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_9rgbmatrix_4core_9RGBMatrix_5width___get__(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__get__", 0); __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->__pyx___matrix->width()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 221, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.RGBMatrix.width.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "rgbmatrix/core.pyx":223 * def __get__(self): return self.__matrix.width() * * cdef __createFrameCanvas(cppinc.FrameCanvas* newCanvas): # <<<<<<<<<<<<<< * canvas = FrameCanvas() * canvas.__canvas = newCanvas */ static PyObject *__pyx_f_9rgbmatrix_4core___createFrameCanvas(rgb_matrix::FrameCanvas *__pyx_v_newCanvas) { struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *__pyx_v_canvas = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__createFrameCanvas", 0); /* "rgbmatrix/core.pyx":224 * * cdef __createFrameCanvas(cppinc.FrameCanvas* newCanvas): * canvas = FrameCanvas() # <<<<<<<<<<<<<< * canvas.__canvas = newCanvas * return canvas */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_9rgbmatrix_4core_FrameCanvas), __pyx_empty_tuple, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 224, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_canvas = ((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)__pyx_t_1); __pyx_t_1 = 0; /* "rgbmatrix/core.pyx":225 * cdef __createFrameCanvas(cppinc.FrameCanvas* newCanvas): * canvas = FrameCanvas() * canvas.__canvas = newCanvas # <<<<<<<<<<<<<< * return canvas * */ __pyx_v_canvas->__pyx___canvas = __pyx_v_newCanvas; /* "rgbmatrix/core.pyx":226 * canvas = FrameCanvas() * canvas.__canvas = newCanvas * return canvas # <<<<<<<<<<<<<< * * # Local Variables: */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_canvas)); __pyx_r = ((PyObject *)__pyx_v_canvas); goto __pyx_L0; /* "rgbmatrix/core.pyx":223 * def __get__(self): return self.__matrix.width() * * cdef __createFrameCanvas(cppinc.FrameCanvas* newCanvas): # <<<<<<<<<<<<<< * canvas = FrameCanvas() * canvas.__canvas = newCanvas */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("rgbmatrix.core.__createFrameCanvas", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_canvas); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas __pyx_vtable_9rgbmatrix_4core_Canvas; static PyObject *__pyx_tp_new_9rgbmatrix_4core_Canvas(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_obj_9rgbmatrix_4core_Canvas *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_obj_9rgbmatrix_4core_Canvas *)o); p->__pyx_vtab = __pyx_vtabptr_9rgbmatrix_4core_Canvas; return o; } static void __pyx_tp_dealloc_9rgbmatrix_4core_Canvas(PyObject *o) { #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif (*Py_TYPE(o)->tp_free)(o); } static PyMethodDef __pyx_methods_9rgbmatrix_4core_Canvas[] = { {"SetImage", (PyCFunction)__pyx_pw_9rgbmatrix_4core_6Canvas_1SetImage, METH_VARARGS|METH_KEYWORDS, 0}, {"SetPixelsPillow", (PyCFunction)__pyx_pw_9rgbmatrix_4core_6Canvas_3SetPixelsPillow, METH_VARARGS|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; static PyTypeObject __pyx_type_9rgbmatrix_4core_Canvas = { PyVarObject_HEAD_INIT(0, 0) "rgbmatrix.core.Canvas", /*tp_name*/ sizeof(struct __pyx_obj_9rgbmatrix_4core_Canvas), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_9rgbmatrix_4core_Canvas, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_9rgbmatrix_4core_Canvas, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_9rgbmatrix_4core_Canvas, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static struct __pyx_vtabstruct_9rgbmatrix_4core_FrameCanvas __pyx_vtable_9rgbmatrix_4core_FrameCanvas; static PyObject *__pyx_tp_new_9rgbmatrix_4core_FrameCanvas(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *p; PyObject *o = __pyx_tp_new_9rgbmatrix_4core_Canvas(t, a, k); if (unlikely(!o)) return 0; p = ((struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas*)__pyx_vtabptr_9rgbmatrix_4core_FrameCanvas; return o; } static void __pyx_tp_dealloc_9rgbmatrix_4core_FrameCanvas(PyObject *o) { #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_pw_9rgbmatrix_4core_11FrameCanvas_1__dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } __pyx_tp_dealloc_9rgbmatrix_4core_Canvas(o); } static PyObject *__pyx_getprop_9rgbmatrix_4core_11FrameCanvas_width(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_11FrameCanvas_5width_1__get__(o); } static PyObject *__pyx_getprop_9rgbmatrix_4core_11FrameCanvas_height(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_11FrameCanvas_6height_1__get__(o); } static PyObject *__pyx_getprop_9rgbmatrix_4core_11FrameCanvas_pwmBits(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_11FrameCanvas_7pwmBits_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_11FrameCanvas_pwmBits(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_11FrameCanvas_7pwmBits_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_11FrameCanvas_brightness(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_11FrameCanvas_10brightness_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_11FrameCanvas_brightness(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_11FrameCanvas_10brightness_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyMethodDef __pyx_methods_9rgbmatrix_4core_FrameCanvas[] = { {"Fill", (PyCFunction)__pyx_pw_9rgbmatrix_4core_11FrameCanvas_3Fill, METH_VARARGS|METH_KEYWORDS, 0}, {"Clear", (PyCFunction)__pyx_pw_9rgbmatrix_4core_11FrameCanvas_5Clear, METH_NOARGS, 0}, {"SetPixel", (PyCFunction)__pyx_pw_9rgbmatrix_4core_11FrameCanvas_7SetPixel, METH_VARARGS|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_9rgbmatrix_4core_FrameCanvas[] = { {(char *)"width", __pyx_getprop_9rgbmatrix_4core_11FrameCanvas_width, 0, (char *)0, 0}, {(char *)"height", __pyx_getprop_9rgbmatrix_4core_11FrameCanvas_height, 0, (char *)0, 0}, {(char *)"pwmBits", __pyx_getprop_9rgbmatrix_4core_11FrameCanvas_pwmBits, __pyx_setprop_9rgbmatrix_4core_11FrameCanvas_pwmBits, (char *)0, 0}, {(char *)"brightness", __pyx_getprop_9rgbmatrix_4core_11FrameCanvas_brightness, __pyx_setprop_9rgbmatrix_4core_11FrameCanvas_brightness, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type_9rgbmatrix_4core_FrameCanvas = { PyVarObject_HEAD_INIT(0, 0) "rgbmatrix.core.FrameCanvas", /*tp_name*/ sizeof(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_9rgbmatrix_4core_FrameCanvas, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_9rgbmatrix_4core_FrameCanvas, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_9rgbmatrix_4core_FrameCanvas, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_9rgbmatrix_4core_FrameCanvas, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static struct __pyx_vtabstruct_9rgbmatrix_4core_RGBMatrix __pyx_vtable_9rgbmatrix_4core_RGBMatrix; static PyObject *__pyx_tp_new_9rgbmatrix_4core_RGBMatrix(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *p; PyObject *o = __pyx_tp_new_9rgbmatrix_4core_Canvas(t, a, k); if (unlikely(!o)) return 0; p = ((struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_9rgbmatrix_4core_Canvas*)__pyx_vtabptr_9rgbmatrix_4core_RGBMatrix; if (unlikely(__pyx_pw_9rgbmatrix_4core_9RGBMatrix_1__cinit__(o, a, k) < 0)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_9rgbmatrix_4core_RGBMatrix(PyObject *o) { #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_pw_9rgbmatrix_4core_9RGBMatrix_3__dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } __pyx_tp_dealloc_9rgbmatrix_4core_Canvas(o); } static PyObject *__pyx_getprop_9rgbmatrix_4core_9RGBMatrix_luminanceCorrect(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_9RGBMatrix_luminanceCorrect(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_16luminanceCorrect_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_9RGBMatrix_pwmBits(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_7pwmBits_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_9RGBMatrix_pwmBits(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_7pwmBits_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_9RGBMatrix_brightness(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_10brightness_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_9RGBMatrix_brightness(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_10brightness_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_9RGBMatrix_height(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_6height_1__get__(o); } static PyObject *__pyx_getprop_9rgbmatrix_4core_9RGBMatrix_width(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_9RGBMatrix_5width_1__get__(o); } static PyMethodDef __pyx_methods_9rgbmatrix_4core_RGBMatrix[] = { {"Fill", (PyCFunction)__pyx_pw_9rgbmatrix_4core_9RGBMatrix_5Fill, METH_VARARGS|METH_KEYWORDS, 0}, {"SetPixel", (PyCFunction)__pyx_pw_9rgbmatrix_4core_9RGBMatrix_7SetPixel, METH_VARARGS|METH_KEYWORDS, 0}, {"Clear", (PyCFunction)__pyx_pw_9rgbmatrix_4core_9RGBMatrix_9Clear, METH_NOARGS, 0}, {"CreateFrameCanvas", (PyCFunction)__pyx_pw_9rgbmatrix_4core_9RGBMatrix_11CreateFrameCanvas, METH_NOARGS, 0}, {"SwapOnVSync", (PyCFunction)__pyx_pw_9rgbmatrix_4core_9RGBMatrix_13SwapOnVSync, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_9rgbmatrix_4core_RGBMatrix[] = { {(char *)"luminanceCorrect", __pyx_getprop_9rgbmatrix_4core_9RGBMatrix_luminanceCorrect, __pyx_setprop_9rgbmatrix_4core_9RGBMatrix_luminanceCorrect, (char *)0, 0}, {(char *)"pwmBits", __pyx_getprop_9rgbmatrix_4core_9RGBMatrix_pwmBits, __pyx_setprop_9rgbmatrix_4core_9RGBMatrix_pwmBits, (char *)0, 0}, {(char *)"brightness", __pyx_getprop_9rgbmatrix_4core_9RGBMatrix_brightness, __pyx_setprop_9rgbmatrix_4core_9RGBMatrix_brightness, (char *)0, 0}, {(char *)"height", __pyx_getprop_9rgbmatrix_4core_9RGBMatrix_height, 0, (char *)0, 0}, {(char *)"width", __pyx_getprop_9rgbmatrix_4core_9RGBMatrix_width, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type_9rgbmatrix_4core_RGBMatrix = { PyVarObject_HEAD_INIT(0, 0) "rgbmatrix.core.RGBMatrix", /*tp_name*/ sizeof(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_9rgbmatrix_4core_RGBMatrix, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_9rgbmatrix_4core_RGBMatrix, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_9rgbmatrix_4core_RGBMatrix, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_9rgbmatrix_4core_RGBMatrix, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyObject *__pyx_tp_new_9rgbmatrix_4core_RGBMatrixOptions(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)o); p->__pyx___py_encoded_hardware_mapping = ((PyObject*)Py_None); Py_INCREF(Py_None); if (unlikely(__pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_9rgbmatrix_4core_RGBMatrixOptions(PyObject *o) { struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *p = (struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif Py_CLEAR(p->__pyx___py_encoded_hardware_mapping); (*Py_TYPE(o)->tp_free)(o); } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_hardware_mapping(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_hardware_mapping(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_16hardware_mapping_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_rows(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_4rows_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_rows(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_4rows_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_chain_length(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_chain_length(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_12chain_length_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_parallel(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_parallel(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8parallel_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_bits(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_bits(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_8pwm_bits_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_lsb_nanoseconds(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_lsb_nanoseconds(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_19pwm_lsb_nanoseconds_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_brightness(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_brightness(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_10brightness_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_scan_mode(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_scan_mode(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_9scan_mode_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_disable_hardware_pulsing(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_disable_hardware_pulsing(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_24disable_hardware_pulsing_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_show_refresh_rate(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_show_refresh_rate(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_17show_refresh_rate_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_swap_green_blue(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_swap_green_blue(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15swap_green_blue_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_inverse_colors(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_inverse_colors(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_14inverse_colors_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_gpio_slowdown(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_gpio_slowdown(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_13gpio_slowdown_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_daemon(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_daemon(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_6daemon_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyObject *__pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_drop_privileges(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_1__get__(o); } static int __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_drop_privileges(PyObject *o, PyObject *v, CYTHON_UNUSED void *x) { if (v) { return __pyx_pw_9rgbmatrix_4core_16RGBMatrixOptions_15drop_privileges_3__set__(o, v); } else { PyErr_SetString(PyExc_NotImplementedError, "__del__"); return -1; } } static PyMethodDef __pyx_methods_9rgbmatrix_4core_RGBMatrixOptions[] = { {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_9rgbmatrix_4core_RGBMatrixOptions[] = { {(char *)"hardware_mapping", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_hardware_mapping, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_hardware_mapping, (char *)0, 0}, {(char *)"rows", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_rows, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_rows, (char *)0, 0}, {(char *)"chain_length", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_chain_length, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_chain_length, (char *)0, 0}, {(char *)"parallel", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_parallel, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_parallel, (char *)0, 0}, {(char *)"pwm_bits", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_bits, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_bits, (char *)0, 0}, {(char *)"pwm_lsb_nanoseconds", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_lsb_nanoseconds, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_pwm_lsb_nanoseconds, (char *)0, 0}, {(char *)"brightness", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_brightness, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_brightness, (char *)0, 0}, {(char *)"scan_mode", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_scan_mode, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_scan_mode, (char *)0, 0}, {(char *)"disable_hardware_pulsing", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_disable_hardware_pulsing, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_disable_hardware_pulsing, (char *)0, 0}, {(char *)"show_refresh_rate", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_show_refresh_rate, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_show_refresh_rate, (char *)0, 0}, {(char *)"swap_green_blue", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_swap_green_blue, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_swap_green_blue, (char *)0, 0}, {(char *)"inverse_colors", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_inverse_colors, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_inverse_colors, (char *)0, 0}, {(char *)"gpio_slowdown", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_gpio_slowdown, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_gpio_slowdown, (char *)0, 0}, {(char *)"daemon", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_daemon, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_daemon, (char *)0, 0}, {(char *)"drop_privileges", __pyx_getprop_9rgbmatrix_4core_16RGBMatrixOptions_drop_privileges, __pyx_setprop_9rgbmatrix_4core_16RGBMatrixOptions_drop_privileges, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type_9rgbmatrix_4core_RGBMatrixOptions = { PyVarObject_HEAD_INIT(0, 0) "rgbmatrix.core.RGBMatrixOptions", /*tp_name*/ sizeof(struct __pyx_obj_9rgbmatrix_4core_RGBMatrixOptions), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_9rgbmatrix_4core_RGBMatrixOptions, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_9rgbmatrix_4core_RGBMatrixOptions, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_9rgbmatrix_4core_RGBMatrixOptions, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_9rgbmatrix_4core_RGBMatrixOptions, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "core", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_Canvas_was_destroyed_or_not_init, __pyx_k_Canvas_was_destroyed_or_not_init, sizeof(__pyx_k_Canvas_was_destroyed_or_not_init), 0, 0, 1, 0}, {&__pyx_kp_s_Currently_only_RGB_mode_is_suppo, __pyx_k_Currently_only_RGB_mode_is_suppo, sizeof(__pyx_k_Currently_only_RGB_mode_is_suppo), 0, 0, 1, 0}, {&__pyx_n_s_Image, __pyx_k_Image, sizeof(__pyx_k_Image), 0, 0, 1, 1}, {&__pyx_kp_s_Not_implemented, __pyx_k_Not_implemented, sizeof(__pyx_k_Not_implemented), 0, 0, 1, 0}, {&__pyx_n_s_PIL, __pyx_k_PIL, sizeof(__pyx_k_PIL), 0, 0, 1, 1}, {&__pyx_n_s_RGB, __pyx_k_RGB, sizeof(__pyx_k_RGB), 0, 0, 1, 1}, {&__pyx_n_s_SetPixel, __pyx_k_SetPixel, sizeof(__pyx_k_SetPixel), 0, 0, 1, 1}, {&__pyx_n_s_SetPixelsPillow, __pyx_k_SetPixelsPillow, sizeof(__pyx_k_SetPixelsPillow), 0, 0, 1, 1}, {&__pyx_n_s_blue, __pyx_k_blue, sizeof(__pyx_k_blue), 0, 0, 1, 1}, {&__pyx_n_s_chain_length, __pyx_k_chain_length, sizeof(__pyx_k_chain_length), 0, 0, 1, 1}, {&__pyx_n_s_chains, __pyx_k_chains, sizeof(__pyx_k_chains), 0, 0, 1, 1}, {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, {&__pyx_n_s_green, __pyx_k_green, sizeof(__pyx_k_green), 0, 0, 1, 1}, {&__pyx_n_s_height, __pyx_k_height, sizeof(__pyx_k_height), 0, 0, 1, 1}, {&__pyx_n_s_im, __pyx_k_im, sizeof(__pyx_k_im), 0, 0, 1, 1}, {&__pyx_n_s_image, __pyx_k_image, sizeof(__pyx_k_image), 0, 0, 1, 1}, {&__pyx_n_s_image32, __pyx_k_image32, sizeof(__pyx_k_image32), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_load, __pyx_k_load, sizeof(__pyx_k_load), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, {&__pyx_n_s_offset_x, __pyx_k_offset_x, sizeof(__pyx_k_offset_x), 0, 0, 1, 1}, {&__pyx_n_s_offset_y, __pyx_k_offset_y, sizeof(__pyx_k_offset_y), 0, 0, 1, 1}, {&__pyx_n_s_options, __pyx_k_options, sizeof(__pyx_k_options), 0, 0, 1, 1}, {&__pyx_n_s_parallel, __pyx_k_parallel, sizeof(__pyx_k_parallel), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_red, __pyx_k_red, sizeof(__pyx_k_red), 0, 0, 1, 1}, {&__pyx_n_s_rows, __pyx_k_rows, sizeof(__pyx_k_rows), 0, 0, 1, 1}, {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_unsafe, __pyx_k_unsafe, sizeof(__pyx_k_unsafe), 0, 0, 1, 1}, {&__pyx_n_s_unsafe_ptrs, __pyx_k_unsafe_ptrs, sizeof(__pyx_k_unsafe_ptrs), 0, 0, 1, 1}, {&__pyx_kp_s_utf_8, __pyx_k_utf_8, sizeof(__pyx_k_utf_8), 0, 0, 1, 0}, {&__pyx_n_s_width, __pyx_k_width, sizeof(__pyx_k_width), 0, 0, 1, 1}, {&__pyx_n_s_x, __pyx_k_x, sizeof(__pyx_k_x), 0, 0, 1, 1}, {&__pyx_n_s_xstart, __pyx_k_xstart, sizeof(__pyx_k_xstart), 0, 0, 1, 1}, {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, {&__pyx_n_s_ystart, __pyx_k_ystart, sizeof(__pyx_k_ystart), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 29, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "rgbmatrix/core.pyx":10 * cdef class Canvas: * cdef cppinc.Canvas* __getCanvas(self) except +: * raise Exception("Not implemented") # <<<<<<<<<<<<<< * * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Not_implemented); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 10, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "rgbmatrix/core.pyx":14 * def SetImage(self, image, int offset_x = 0, int offset_y = 0, unsafe=True): * if (image.mode != "RGB"): * raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") # <<<<<<<<<<<<<< * * if unsafe: */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_Currently_only_RGB_mode_is_suppo); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "rgbmatrix/core.pyx":64 * if <void*>self.__canvas != NULL: * return self.__canvas * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") # <<<<<<<<<<<<<< * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_Canvas_was_destroyed_or_not_init); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 64, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "rgbmatrix/core.pyx":100 * def __get__(self): return self.__options.hardware_mapping * def __set__(self, value): * self.__py_encoded_hardware_mapping = value.encode('utf-8') # <<<<<<<<<<<<<< * self.__options.hardware_mapping = self.__py_encoded_hardware_mapping * */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_utf_8); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 100, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "rgbmatrix/core.pyx":188 * if <void*>self.__matrix != NULL: * return self.__matrix * raise Exception("Canvas was destroyed or not initialized, you cannot use this object anymore") # <<<<<<<<<<<<<< * * def Fill(self, uint8_t red, uint8_t green, uint8_t blue): */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_Canvas_was_destroyed_or_not_init); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(0, 188, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initcore(void); /*proto*/ PyMODINIT_FUNC initcore(void) #else PyMODINIT_FUNC PyInit_core(void); /*proto*/ PyMODINIT_FUNC PyInit_core(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_core(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("core", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_rgbmatrix__core) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "rgbmatrix.core")) { if (unlikely(PyDict_SetItemString(modules, "rgbmatrix.core", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ __pyx_vtabptr_9rgbmatrix_4core_Canvas = &__pyx_vtable_9rgbmatrix_4core_Canvas; __pyx_vtable_9rgbmatrix_4core_Canvas.__pyx___getCanvas = (rgb_matrix::Canvas *(*)(struct __pyx_obj_9rgbmatrix_4core_Canvas *))__pyx_f_9rgbmatrix_4core_6Canvas___getCanvas; if (PyType_Ready(&__pyx_type_9rgbmatrix_4core_Canvas) < 0) __PYX_ERR(0, 8, __pyx_L1_error) __pyx_type_9rgbmatrix_4core_Canvas.tp_print = 0; if (__Pyx_SetVtable(__pyx_type_9rgbmatrix_4core_Canvas.tp_dict, __pyx_vtabptr_9rgbmatrix_4core_Canvas) < 0) __PYX_ERR(0, 8, __pyx_L1_error) if (PyObject_SetAttrString(__pyx_m, "Canvas", (PyObject *)&__pyx_type_9rgbmatrix_4core_Canvas) < 0) __PYX_ERR(0, 8, __pyx_L1_error) __pyx_ptype_9rgbmatrix_4core_Canvas = &__pyx_type_9rgbmatrix_4core_Canvas; __pyx_vtabptr_9rgbmatrix_4core_FrameCanvas = &__pyx_vtable_9rgbmatrix_4core_FrameCanvas; __pyx_vtable_9rgbmatrix_4core_FrameCanvas.__pyx_base = *__pyx_vtabptr_9rgbmatrix_4core_Canvas; __pyx_vtable_9rgbmatrix_4core_FrameCanvas.__pyx_base.__pyx___getCanvas = (rgb_matrix::Canvas *(*)(struct __pyx_obj_9rgbmatrix_4core_Canvas *))__pyx_f_9rgbmatrix_4core_11FrameCanvas___getCanvas__pyx_wrap_1; __pyx_vtable_9rgbmatrix_4core_FrameCanvas.__pyx___getCanvas = (rgb_matrix::Canvas *(*)(struct __pyx_obj_9rgbmatrix_4core_FrameCanvas *))__pyx_f_9rgbmatrix_4core_11FrameCanvas___getCanvas; __pyx_type_9rgbmatrix_4core_FrameCanvas.tp_base = __pyx_ptype_9rgbmatrix_4core_Canvas; if (PyType_Ready(&__pyx_type_9rgbmatrix_4core_FrameCanvas) < 0) __PYX_ERR(0, 56, __pyx_L1_error) __pyx_type_9rgbmatrix_4core_FrameCanvas.tp_print = 0; if (__Pyx_SetVtable(__pyx_type_9rgbmatrix_4core_FrameCanvas.tp_dict, __pyx_vtabptr_9rgbmatrix_4core_FrameCanvas) < 0) __PYX_ERR(0, 56, __pyx_L1_error) if (PyObject_SetAttrString(__pyx_m, "FrameCanvas", (PyObject *)&__pyx_type_9rgbmatrix_4core_FrameCanvas) < 0) __PYX_ERR(0, 56, __pyx_L1_error) __pyx_ptype_9rgbmatrix_4core_FrameCanvas = &__pyx_type_9rgbmatrix_4core_FrameCanvas; __pyx_vtabptr_9rgbmatrix_4core_RGBMatrix = &__pyx_vtable_9rgbmatrix_4core_RGBMatrix; __pyx_vtable_9rgbmatrix_4core_RGBMatrix.__pyx_base = *__pyx_vtabptr_9rgbmatrix_4core_Canvas; __pyx_vtable_9rgbmatrix_4core_RGBMatrix.__pyx_base.__pyx___getCanvas = (rgb_matrix::Canvas *(*)(struct __pyx_obj_9rgbmatrix_4core_Canvas *))__pyx_f_9rgbmatrix_4core_9RGBMatrix___getCanvas__pyx_wrap_1; __pyx_vtable_9rgbmatrix_4core_RGBMatrix.__pyx___getCanvas = (rgb_matrix::Canvas *(*)(struct __pyx_obj_9rgbmatrix_4core_RGBMatrix *))__pyx_f_9rgbmatrix_4core_9RGBMatrix___getCanvas; __pyx_type_9rgbmatrix_4core_RGBMatrix.tp_base = __pyx_ptype_9rgbmatrix_4core_Canvas; if (PyType_Ready(&__pyx_type_9rgbmatrix_4core_RGBMatrix) < 0) __PYX_ERR(0, 162, __pyx_L1_error) __pyx_type_9rgbmatrix_4core_RGBMatrix.tp_print = 0; if (__Pyx_SetVtable(__pyx_type_9rgbmatrix_4core_RGBMatrix.tp_dict, __pyx_vtabptr_9rgbmatrix_4core_RGBMatrix) < 0) __PYX_ERR(0, 162, __pyx_L1_error) if (PyObject_SetAttrString(__pyx_m, "RGBMatrix", (PyObject *)&__pyx_type_9rgbmatrix_4core_RGBMatrix) < 0) __PYX_ERR(0, 162, __pyx_L1_error) __pyx_ptype_9rgbmatrix_4core_RGBMatrix = &__pyx_type_9rgbmatrix_4core_RGBMatrix; if (PyType_Ready(&__pyx_type_9rgbmatrix_4core_RGBMatrixOptions) < 0) __PYX_ERR(0, 91, __pyx_L1_error) __pyx_type_9rgbmatrix_4core_RGBMatrixOptions.tp_print = 0; if (PyObject_SetAttrString(__pyx_m, "RGBMatrixOptions", (PyObject *)&__pyx_type_9rgbmatrix_4core_RGBMatrixOptions) < 0) __PYX_ERR(0, 91, __pyx_L1_error) __pyx_ptype_9rgbmatrix_4core_RGBMatrixOptions = &__pyx_type_9rgbmatrix_4core_RGBMatrixOptions; /*--- Type import code ---*/ /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "rgbmatrix/core.pyx":5 * from libcpp cimport bool * from libc.stdint cimport uint8_t, uint32_t, uintptr_t * from PIL import Image # <<<<<<<<<<<<<< * import cython * */ __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_n_s_Image); __Pyx_GIVEREF(__pyx_n_s_Image); PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_Image); __pyx_t_2 = __Pyx_Import(__pyx_n_s_PIL, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_Image); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_Image, __pyx_t_1) < 0) __PYX_ERR(0, 5, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "rgbmatrix/core.pyx":1 * # distutils: language = c++ # <<<<<<<<<<<<<< * * from libcpp cimport bool */ __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init rgbmatrix.core", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init rgbmatrix.core"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } #if PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* BytesEquals */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else if (s1 == s2) { return (equals == Py_EQ); } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { const char *ps1, *ps2; Py_ssize_t length = PyBytes_GET_SIZE(s1); if (length != PyBytes_GET_SIZE(s2)) return (equals == Py_NE); ps1 = PyBytes_AS_STRING(s1); ps2 = PyBytes_AS_STRING(s2); if (ps1[0] != ps2[0]) { return (equals == Py_NE); } else if (length == 1) { return (equals == Py_EQ); } else { int result = memcmp(ps1, ps2, (size_t)length); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { return (equals == Py_NE); } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { return (equals == Py_NE); } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } #endif } /* UnicodeEquals */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else #if PY_MAJOR_VERSION < 3 PyObject* owned_ref = NULL; #endif int s1_is_unicode, s2_is_unicode; if (s1 == s2) { goto return_eq; } s1_is_unicode = PyUnicode_CheckExact(s1); s2_is_unicode = PyUnicode_CheckExact(s2); #if PY_MAJOR_VERSION < 3 if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { owned_ref = PyUnicode_FromObject(s2); if (unlikely(!owned_ref)) return -1; s2 = owned_ref; s2_is_unicode = 1; } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { owned_ref = PyUnicode_FromObject(s1); if (unlikely(!owned_ref)) return -1; s1 = owned_ref; s1_is_unicode = 1; } else if (((!s2_is_unicode) & (!s1_is_unicode))) { return __Pyx_PyBytes_Equals(s1, s2, equals); } #endif if (s1_is_unicode & s2_is_unicode) { Py_ssize_t length; int kind; void *data1, *data2; if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) return -1; length = __Pyx_PyUnicode_GET_LENGTH(s1); if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { goto return_ne; } kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ); return_ne: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_NE); #endif } /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* IterFinish */ static CYTHON_INLINE int __Pyx_IterFinish(void) { #if CYTHON_FAST_THREAD_STATE PyThreadState *tstate = PyThreadState_GET(); PyObject* exc_type = tstate->curexc_type; if (unlikely(exc_type)) { if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { PyObject *exc_value, *exc_tb; exc_value = tstate->curexc_value; exc_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; Py_DECREF(exc_type); Py_XDECREF(exc_value); Py_XDECREF(exc_tb); return 0; } else { return -1; } } return 0; #else if (unlikely(PyErr_Occurred())) { if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { PyErr_Clear(); return 0; } else { return -1; } } return 0; #endif } /* UnpackItemEndCheck */ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { if (unlikely(retval)) { Py_DECREF(retval); __Pyx_RaiseTooManyValuesError(expected); return -1; } else { return __Pyx_IterFinish(); } return 0; } /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL #include "frameobject.h" static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = PyThreadState_GET(); PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = f->f_localsplus; for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; #if PY_MAJOR_VERSION >= 3 PyObject *kwdefs; #endif PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { return NULL; } if ( #if PY_MAJOR_VERSION >= 3 co->co_kwonlyargcount == 0 && #endif likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); #if PY_MAJOR_VERSION >= 3 kwdefs = PyFunction_GET_KW_DEFAULTS(func); #endif if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, closure); #endif Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif // CPython < 3.6 #endif // CYTHON_FAST_PYCALL /* PyCFunctionFastCall */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { PyCFunctionObject *func = (PyCFunctionObject*)func_obj; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST))); assert(nargs >= 0); assert(nargs == 0 || args != NULL); /* _PyCFunction_FastCallDict() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs, NULL); } #endif // CYTHON_FAST_PYCCALL /* PyObjectCallMethO */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = PyCFunction_GET_FUNCTION(func); self = PyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectCallOneArg */ #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, &arg, 1); } #endif #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); #if CYTHON_FAST_PYCCALL } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { return __Pyx_PyCFunction_FastCall(func, &arg, 1); #endif } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif /* PyObjectCallNoArg */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, NULL, 0); } #endif #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { return __Pyx_PyObject_CallMethO(func, NULL); } } return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); } #endif /* KeywordStringCheck */ static CYTHON_INLINE int __Pyx_CheckKeywordStrings( PyObject *kwdict, const char* function_name, int kw_allowed) { PyObject* key = 0; Py_ssize_t pos = 0; #if CYTHON_COMPILING_IN_PYPY if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) goto invalid_keyword; return 1; #else while (PyDict_Next(kwdict, &pos, &key, 0)) { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) #endif if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; } if ((!kw_allowed) && unlikely(key)) goto invalid_keyword; return 1; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); return 0; #endif invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif return 0; } /* ArgTypeTest */ static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); } static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (likely(Py_TYPE(obj) == type)) return 1; #if PY_MAJOR_VERSION == 2 else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(PyObject_TypeCheck(obj, type))) return 1; } __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } /* SetVTable */ static int __Pyx_SetVtable(PyObject *dict, void *vtable) { #if PY_VERSION_HEX >= 0x02070000 PyObject *ob = PyCapsule_New(vtable, 0, 0); #else PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); #endif if (!ob) goto bad; if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) goto bad; Py_DECREF(ob); return 0; bad: Py_XDECREF(ob); return -1; } /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_VERSION_HEX < 0x03030000 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* ImportFrom */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_ImportError, #if PY_MAJOR_VERSION < 3 "cannot import name %.230s", PyString_AS_STRING(name)); #else "cannot import name %S", name); #endif } return value; } /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint8_t(uint8_t value) { const uint8_t neg_one = (uint8_t) -1, const_zero = (uint8_t) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(uint8_t) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(uint8_t) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(uint8_t) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(uint8_t) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(uint8_t) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(uint8_t), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntFromPy */ static CYTHON_INLINE uint8_t __Pyx_PyInt_As_uint8_t(PyObject *x) { const uint8_t neg_one = (uint8_t) -1, const_zero = (uint8_t) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(uint8_t) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(uint8_t, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (uint8_t) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (uint8_t) 0; case 1: __PYX_VERIFY_RETURN_INT(uint8_t, digit, digits[0]) case 2: if (8 * sizeof(uint8_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) >= 2 * PyLong_SHIFT) { return (uint8_t) (((((uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0])); } } break; case 3: if (8 * sizeof(uint8_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) >= 3 * PyLong_SHIFT) { return (uint8_t) (((((((uint8_t)digits[2]) << PyLong_SHIFT) | (uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0])); } } break; case 4: if (8 * sizeof(uint8_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) >= 4 * PyLong_SHIFT) { return (uint8_t) (((((((((uint8_t)digits[3]) << PyLong_SHIFT) | (uint8_t)digits[2]) << PyLong_SHIFT) | (uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (uint8_t) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(uint8_t) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(uint8_t, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(uint8_t) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(uint8_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (uint8_t) 0; case -1: __PYX_VERIFY_RETURN_INT(uint8_t, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(uint8_t, digit, +digits[0]) case -2: if (8 * sizeof(uint8_t) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) - 1 > 2 * PyLong_SHIFT) { return (uint8_t) (((uint8_t)-1)*(((((uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0]))); } } break; case 2: if (8 * sizeof(uint8_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) - 1 > 2 * PyLong_SHIFT) { return (uint8_t) ((((((uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0]))); } } break; case -3: if (8 * sizeof(uint8_t) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) - 1 > 3 * PyLong_SHIFT) { return (uint8_t) (((uint8_t)-1)*(((((((uint8_t)digits[2]) << PyLong_SHIFT) | (uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0]))); } } break; case 3: if (8 * sizeof(uint8_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) - 1 > 3 * PyLong_SHIFT) { return (uint8_t) ((((((((uint8_t)digits[2]) << PyLong_SHIFT) | (uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0]))); } } break; case -4: if (8 * sizeof(uint8_t) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) - 1 > 4 * PyLong_SHIFT) { return (uint8_t) (((uint8_t)-1)*(((((((((uint8_t)digits[3]) << PyLong_SHIFT) | (uint8_t)digits[2]) << PyLong_SHIFT) | (uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0]))); } } break; case 4: if (8 * sizeof(uint8_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint8_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint8_t) - 1 > 4 * PyLong_SHIFT) { return (uint8_t) ((((((((((uint8_t)digits[3]) << PyLong_SHIFT) | (uint8_t)digits[2]) << PyLong_SHIFT) | (uint8_t)digits[1]) << PyLong_SHIFT) | (uint8_t)digits[0]))); } } break; } #endif if (sizeof(uint8_t) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(uint8_t, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(uint8_t) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(uint8_t, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else uint8_t val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (uint8_t) -1; } } else { uint8_t val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (uint8_t) -1; val = __Pyx_PyInt_As_uint8_t(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to uint8_t"); return (uint8_t) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to uint8_t"); return (uint8_t) -1; } /* CIntFromPy */ static CYTHON_INLINE uint32_t __Pyx_PyInt_As_uint32_t(PyObject *x) { const uint32_t neg_one = (uint32_t) -1, const_zero = (uint32_t) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(uint32_t) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(uint32_t, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (uint32_t) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (uint32_t) 0; case 1: __PYX_VERIFY_RETURN_INT(uint32_t, digit, digits[0]) case 2: if (8 * sizeof(uint32_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) >= 2 * PyLong_SHIFT) { return (uint32_t) (((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])); } } break; case 3: if (8 * sizeof(uint32_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) >= 3 * PyLong_SHIFT) { return (uint32_t) (((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])); } } break; case 4: if (8 * sizeof(uint32_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) >= 4 * PyLong_SHIFT) { return (uint32_t) (((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (uint32_t) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(uint32_t) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(uint32_t, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(uint32_t) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(uint32_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (uint32_t) 0; case -1: __PYX_VERIFY_RETURN_INT(uint32_t, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(uint32_t, digit, +digits[0]) case -2: if (8 * sizeof(uint32_t) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT) { return (uint32_t) (((uint32_t)-1)*(((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); } } break; case 2: if (8 * sizeof(uint32_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT) { return (uint32_t) ((((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); } } break; case -3: if (8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT) { return (uint32_t) (((uint32_t)-1)*(((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); } } break; case 3: if (8 * sizeof(uint32_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT) { return (uint32_t) ((((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); } } break; case -4: if (8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) - 1 > 4 * PyLong_SHIFT) { return (uint32_t) (((uint32_t)-1)*(((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); } } break; case 4: if (8 * sizeof(uint32_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(uint32_t) - 1 > 4 * PyLong_SHIFT) { return (uint32_t) ((((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); } } break; } #endif if (sizeof(uint32_t) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(uint32_t, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(uint32_t) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(uint32_t, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else uint32_t val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (uint32_t) -1; } } else { uint32_t val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (uint32_t) -1; val = __Pyx_PyInt_As_uint32_t(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to uint32_t"); return (uint32_t) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to uint32_t"); return (uint32_t) -1; } /* CIntFromPy */ static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *x) { const size_t neg_one = (size_t) -1, const_zero = (size_t) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(size_t) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(size_t, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (size_t) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (size_t) 0; case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, digits[0]) case 2: if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 2 * PyLong_SHIFT) { return (size_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; case 3: if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 3 * PyLong_SHIFT) { return (size_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; case 4: if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) >= 4 * PyLong_SHIFT) { return (size_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (size_t) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(size_t) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(size_t) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (size_t) 0; case -1: __PYX_VERIFY_RETURN_INT(size_t, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, +digits[0]) case -2: if (8 * sizeof(size_t) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 2: if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { return (size_t) ((((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case -3: if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 3: if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { return (size_t) ((((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case -4: if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { return (size_t) (((size_t)-1)*(((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; case 4: if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { return (size_t) ((((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); } } break; } #endif if (sizeof(size_t) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(size_t) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(size_t, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else size_t val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (size_t) -1; } } else { size_t val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (size_t) -1; val = __Pyx_PyInt_As_size_t(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to size_t"); return (size_t) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to size_t"); return (size_t) -1; } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif #else res = PyNumber_Int(x); #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
41.806501
273
0.680479
[ "object" ]
d540999783f098dd656dbd7dc3292d3da676a284
4,169
hpp
C++
modules/gapi/src/backends/fluid/gfluidbackend.hpp
ghennadii/opencv
c6a4bad3692e62ff6733fe98f51b557d75ce65a0
[ "BSD-3-Clause" ]
4
2019-03-04T05:47:18.000Z
2019-06-24T08:14:43.000Z
modules/gapi/src/backends/fluid/gfluidbackend.hpp
ghennadii/opencv
c6a4bad3692e62ff6733fe98f51b557d75ce65a0
[ "BSD-3-Clause" ]
2
2019-03-23T03:53:50.000Z
2019-03-23T03:53:52.000Z
modules/gapi/src/backends/fluid/gfluidbackend.hpp
ghennadii/opencv
c6a4bad3692e62ff6733fe98f51b557d75ce65a0
[ "BSD-3-Clause" ]
2
2019-07-21T08:20:06.000Z
2020-08-09T06:07:37.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #ifndef OPENCV_GAPI_FLUID_BACKEND_HPP #define OPENCV_GAPI_FLUID_BACKEND_HPP // FIXME? Actually gfluidbackend.hpp is not included anywhere // and can be placed in gfluidbackend.cpp #include "opencv2/gapi/garg.hpp" #include "opencv2/gapi/gproto.hpp" #include "opencv2/gapi/fluid/gfluidkernel.hpp" #include "opencv2/gapi/fluid/gfluidbuffer.hpp" // PRIVATE STUFF! #include "backends/common/gbackend.hpp" #include "compiler/gislandmodel.hpp" namespace cv { namespace gimpl { struct FluidUnit { static const char *name() { return "FluidUnit"; } GFluidKernel k; gapi::fluid::BorderOpt border; int border_size; std::vector<int> line_consumption; double ratio; }; struct FluidUseOwnBorderBuffer { static const char *name() { return "FluidUseOwnBorderBuffer"; } bool use; }; struct FluidData { static const char *name() { return "FluidData"; } // FIXME: This structure starts looking like "FluidBuffer" meta int latency = 0; int skew = 0; int max_consumption = 1; int border_size = 0; int lpi_write = 1; bool internal = false; // is node internal to any fluid island gapi::fluid::BorderOpt border; }; struct FluidAgent { public: virtual ~FluidAgent() = default; FluidAgent(const ade::Graph &g, ade::NodeHandle nh); GFluidKernel k; ade::NodeHandle op_handle; // FIXME: why it is here??// std::string op_name; // < 0 - not a buffer // >= 0 - a buffer with RcID std::vector<int> in_buffer_ids; std::vector<int> out_buffer_ids; cv::GArgs in_args; std::vector<cv::gapi::fluid::View> in_views; // sparce list of IN views std::vector<cv::gapi::fluid::Buffer*> out_buffers; // FIXME Current assumption is that outputs have EQUAL SIZES int m_outputLines = 0; int m_producedLines = 0; // Execution methods void reset(); bool canWork() const; bool canRead() const; bool canWrite() const; void doWork(); bool done() const; void debug(std::ostream& os); // FIXME: // refactor (implement a more solid replacement or // drop this method completely) virtual void setRatio(double ratio) = 0; private: // FIXME!!! // move to another class virtual int firstWindow(std::size_t inPort) const = 0; virtual std::pair<int,int> linesReadAndnextWindow(std::size_t inPort) const = 0; }; class GFluidExecutable final: public GIslandExecutable { const ade::Graph &m_g; GModel::ConstGraph m_gm; std::vector<std::unique_ptr<FluidAgent>> m_agents; std::vector<cv::gapi::fluid::Buffer> m_buffers; std::vector<FluidAgent*> m_script; using Magazine = detail::magazine<cv::gapi::own::Scalar>; Magazine m_res; std::size_t m_num_int_buffers; // internal buffers counter (m_buffers - num_scratch) std::vector<std::size_t> m_scratch_users; std::unordered_map<int, std::size_t> m_id_map; // GMat id -> buffer idx map std::map<std::size_t, ade::NodeHandle> m_all_gmat_ids; void bindInArg (const RcDesc &rc, const GRunArg &arg); void bindOutArg(const RcDesc &rc, const GRunArgP &arg); void packArg (GArg &in_arg, const GArg &op_arg); void initBufferRois(std::vector<int>& readStarts, std::vector<cv::gapi::own::Rect>& rois, const std::vector<gapi::own::Rect> &out_rois); void makeReshape(const std::vector<cv::gapi::own::Rect>& out_rois); public: GFluidExecutable(const ade::Graph &g, const std::vector<ade::NodeHandle> &nodes, const std::vector<cv::gapi::own::Rect> &outputRois); virtual inline bool canReshape() const override { return true; } virtual void reshape(ade::Graph& g, const GCompileArgs& args) override; virtual void run(std::vector<InObj> &&input_objs, std::vector<OutObj> &&output_objs) override; }; }} // cv::gimpl #endif // OPENCV_GAPI_FLUID_BACKEND_HPP
29.778571
140
0.675702
[ "vector", "solid" ]
d541bc426c7d1e9b1a6fb975108de3e1796018eb
7,971
cpp
C++
contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/scan_MSSMNoFV.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
null
null
null
contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/scan_MSSMNoFV.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
null
null
null
contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/scan_MSSMNoFV.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
null
null
null
// ==================================================================== // This file is part of FlexibleSUSY. // // FlexibleSUSY 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. // // FlexibleSUSY 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 FlexibleSUSY. If not, see // <http://www.gnu.org/licenses/>. // ==================================================================== // File generated at Sat 27 Aug 2016 12:50:22 #include "MSSMNoFV_input_parameters.hpp" #include "MSSMNoFV_spectrum_generator.hpp" #include "MSSMNoFV_two_scale_model_slha.hpp" #include "command_line_options.hpp" #include "scan.hpp" #include "lowe.h" #include "logger.hpp" #include <iostream> #include <cstring> #define INPUTPARAMETER(p) input.p namespace flexiblesusy { void print_usage() { std::cout << "Usage: scan_MSSMNoFV.x [options]\n" "Options:\n" " --TanBeta=<value>\n" " --SignMu=<value>\n" " --Qin=<value>\n" " --M1=<value>\n" " --M2=<value>\n" " --M3=<value>\n" " --AtIN=<value>\n" " --AbIN=<value>\n" " --AtauIN=<value>\n" " --AcIN=<value>\n" " --AsIN=<value>\n" " --AmuonIN=<value>\n" " --AuIN=<value>\n" " --AdIN=<value>\n" " --AeIN=<value>\n" " --mHd2IN=<value>\n" " --mHu2IN=<value>\n" " --ml11IN=<value>\n" " --ml22IN=<value>\n" " --ml33IN=<value>\n" " --me11IN=<value>\n" " --me22IN=<value>\n" " --me33IN=<value>\n" " --mq11IN=<value>\n" " --mq22IN=<value>\n" " --mq33IN=<value>\n" " --mu11IN=<value>\n" " --mu22IN=<value>\n" " --mu33IN=<value>\n" " --md11IN=<value>\n" " --md22IN=<value>\n" " --md33IN=<value>\n" " --help,-h print this help message" << std::endl; } void set_command_line_parameters(int argc, char* argv[], MSSMNoFV_input_parameters& input) { for (int i = 1; i < argc; ++i) { const char* option = argv[i]; if(Command_line_options::get_parameter_value(option, "--TanBeta=", input.TanBeta)) continue; if(Command_line_options::get_parameter_value(option, "--SignMu=", input.SignMu)) continue; if(Command_line_options::get_parameter_value(option, "--Qin=", input.Qin)) continue; if(Command_line_options::get_parameter_value(option, "--M1=", input.M1)) continue; if(Command_line_options::get_parameter_value(option, "--M2=", input.M2)) continue; if(Command_line_options::get_parameter_value(option, "--M3=", input.M3)) continue; if(Command_line_options::get_parameter_value(option, "--AtIN=", input.AtIN)) continue; if(Command_line_options::get_parameter_value(option, "--AbIN=", input.AbIN)) continue; if(Command_line_options::get_parameter_value(option, "--AtauIN=", input.AtauIN)) continue; if(Command_line_options::get_parameter_value(option, "--AcIN=", input.AcIN)) continue; if(Command_line_options::get_parameter_value(option, "--AsIN=", input.AsIN)) continue; if(Command_line_options::get_parameter_value(option, "--AmuonIN=", input.AmuonIN)) continue; if(Command_line_options::get_parameter_value(option, "--AuIN=", input.AuIN)) continue; if(Command_line_options::get_parameter_value(option, "--AdIN=", input.AdIN)) continue; if(Command_line_options::get_parameter_value(option, "--AeIN=", input.AeIN)) continue; if(Command_line_options::get_parameter_value(option, "--mHd2IN=", input.mHd2IN)) continue; if(Command_line_options::get_parameter_value(option, "--mHu2IN=", input.mHu2IN)) continue; if(Command_line_options::get_parameter_value(option, "--ml11IN=", input.ml11IN)) continue; if(Command_line_options::get_parameter_value(option, "--ml22IN=", input.ml22IN)) continue; if(Command_line_options::get_parameter_value(option, "--ml33IN=", input.ml33IN)) continue; if(Command_line_options::get_parameter_value(option, "--me11IN=", input.me11IN)) continue; if(Command_line_options::get_parameter_value(option, "--me22IN=", input.me22IN)) continue; if(Command_line_options::get_parameter_value(option, "--me33IN=", input.me33IN)) continue; if(Command_line_options::get_parameter_value(option, "--mq11IN=", input.mq11IN)) continue; if(Command_line_options::get_parameter_value(option, "--mq22IN=", input.mq22IN)) continue; if(Command_line_options::get_parameter_value(option, "--mq33IN=", input.mq33IN)) continue; if(Command_line_options::get_parameter_value(option, "--mu11IN=", input.mu11IN)) continue; if(Command_line_options::get_parameter_value(option, "--mu22IN=", input.mu22IN)) continue; if(Command_line_options::get_parameter_value(option, "--mu33IN=", input.mu33IN)) continue; if(Command_line_options::get_parameter_value(option, "--md11IN=", input.md11IN)) continue; if(Command_line_options::get_parameter_value(option, "--md22IN=", input.md22IN)) continue; if(Command_line_options::get_parameter_value(option, "--md33IN=", input.md33IN)) continue; if (strcmp(option,"--help") == 0 || strcmp(option,"-h") == 0) { print_usage(); exit(EXIT_SUCCESS); } ERROR("Unrecognized command line option: " << option); exit(EXIT_FAILURE); } } } // namespace flexiblesusy int main(int argc, char* argv[]) { using namespace flexiblesusy; typedef Two_scale algorithm_type; MSSMNoFV_input_parameters input; set_command_line_parameters(argc, argv, input); softsusy::QedQcd qedqcd; try { qedqcd.to(qedqcd.displayPoleMZ()); // run SM fermion masses to MZ } catch (const std::string& s) { ERROR(s); return EXIT_FAILURE; } MSSMNoFV_spectrum_generator<algorithm_type> spectrum_generator; spectrum_generator.set_precision_goal(1.0e-4); spectrum_generator.set_max_iterations(0); // 0 == automatic spectrum_generator.set_calculate_sm_masses(0); // 0 == no spectrum_generator.set_parameter_output_scale(0); // 0 == susy scale const std::vector<double> range(float_range(0., 100., 10)); cout << "# " << std::setw(12) << std::left << "TanBeta" << ' ' << std::setw(12) << std::left << "Mhh(0)/GeV" << ' ' << std::setw(12) << std::left << "error" << '\n'; for (std::vector<double>::const_iterator it = range.begin(), end = range.end(); it != end; ++it) { INPUTPARAMETER(TanBeta) = *it; spectrum_generator.run(qedqcd, input); const MSSMNoFV_slha<algorithm_type> model(spectrum_generator.get_model()); const MSSMNoFV_physical& pole_masses = model.get_physical_slha(); const Problems<MSSMNoFV_info::NUMBER_OF_PARTICLES>& problems = spectrum_generator.get_problems(); const double higgs = pole_masses.Mhh(0); const bool error = problems.have_problem(); cout << " " << std::setw(12) << std::left << *it << ' ' << std::setw(12) << std::left << higgs << ' ' << std::setw(12) << std::left << error; if (error) { cout << "\t# " << problems; } cout << '\n'; } return 0; }
31.630952
88
0.609334
[ "vector", "model" ]
d541ef344c388a198abbc27c54cb22a7d9e5a32c
3,843
cpp
C++
src/org/apache/poi/sl/draw/DrawSheet.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/DrawSheet.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/DrawSheet.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/sl/draw/DrawSheet.java #include <org/apache/poi/sl/draw/DrawSheet.hpp> #include <java/awt/Color.hpp> #include <java/awt/Dimension.hpp> #include <java/awt/Graphics2D.hpp> #include <java/awt/geom/AffineTransform.hpp> #include <java/lang/Boolean.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/util/Iterator.hpp> #include <java/util/List.hpp> #include <org/apache/poi/sl/draw/DrawFactory.hpp> #include <org/apache/poi/sl/draw/DrawMasterSheet.hpp> #include <org/apache/poi/sl/draw/Drawable_DrawableHint.hpp> #include <org/apache/poi/sl/draw/Drawable.hpp> #include <org/apache/poi/sl/usermodel/MasterSheet.hpp> #include <org/apache/poi/sl/usermodel/Shape.hpp> #include <org/apache/poi/sl/usermodel/Sheet.hpp> #include <org/apache/poi/sl/usermodel/SlideShow.hpp> template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::sl::draw::DrawSheet::DrawSheet(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::sl::draw::DrawSheet::DrawSheet(::poi::sl::usermodel::Sheet* sheet) : DrawSheet(*static_cast< ::default_init_tag* >(0)) { ctor(sheet); } void poi::sl::draw::DrawSheet::ctor(::poi::sl::usermodel::Sheet* sheet) { super::ctor(); this->sheet = sheet; } void poi::sl::draw::DrawSheet::draw(::java::awt::Graphics2D* graphics) { auto dim = npc(npc(sheet)->getSlideShow())->getPageSize(); auto whiteTrans = new ::java::awt::Color(1.0f, 1.0f, 1.0f, 0.0f); npc(graphics)->setColor(whiteTrans); npc(graphics)->fillRect(0, 0, static_cast< int32_t >(npc(dim)->getWidth()), static_cast< int32_t >(npc(dim)->getHeight())); auto drawFact = DrawFactory::getInstance(graphics); auto master = npc(sheet)->getMasterSheet(); if(npc(sheet)->getFollowMasterGraphics() && master != nullptr) { Drawable* drawer = npc(drawFact)->getDrawable(static_cast< ::poi::sl::usermodel::MasterSheet* >(master)); npc(drawer)->draw(graphics); } npc(graphics)->setRenderingHint(Drawable::GROUP_TRANSFORM(), new ::java::awt::geom::AffineTransform()); for (auto _i = npc(npc(sheet)->getShapes())->iterator(); _i->hasNext(); ) { ::poi::sl::usermodel::Shape* shape = java_cast< ::poi::sl::usermodel::Shape* >(_i->next()); { if(!canDraw(graphics, shape)) { continue; } auto at = npc(graphics)->getTransform(); npc(graphics)->setRenderingHint(Drawable::GSAVE(), ::java::lang::Boolean::valueOf(true)); auto drawer = npc(drawFact)->getDrawable(static_cast< ::poi::sl::usermodel::Shape* >(shape)); npc(drawer)->applyTransform(graphics); npc(drawer)->draw(graphics); npc(graphics)->setTransform(at); npc(graphics)->setRenderingHint(Drawable::GRESTORE(), ::java::lang::Boolean::valueOf(true)); } } } void poi::sl::draw::DrawSheet::applyTransform(::java::awt::Graphics2D* context) { } void poi::sl::draw::DrawSheet::drawContent(::java::awt::Graphics2D* context) { } bool poi::sl::draw::DrawSheet::canDraw(::java::awt::Graphics2D* graphics, ::poi::sl::usermodel::Shape* shape) { return true; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::sl::draw::DrawSheet::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.sl.draw.DrawSheet", 32); return c; } java::lang::Class* poi::sl::draw::DrawSheet::getClass0() { return class_(); }
34.00885
127
0.664585
[ "object", "shape" ]
d546616060d7c59ea6bfa6471936b9f026cc531f
7,283
cpp
C++
libs/timed_execution/tests/unit/minimal_timed_sync_executor.cpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
libs/timed_execution/tests/unit/minimal_timed_sync_executor.cpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
libs/timed_execution/tests/unit/minimal_timed_sync_executor.cpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2017 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // 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 <hpx/hpx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/include/parallel_executors.hpp> #include <hpx/testing.hpp> #include <hpx/timed_execution.hpp> #include <algorithm> #include <array> #include <atomic> #include <chrono> #include <cstddef> #include <cstdlib> #include <functional> #include <iterator> #include <string> #include <type_traits> #include <utility> #include <vector> using namespace std::chrono; /////////////////////////////////////////////////////////////////////////////// hpx::thread::id sync_test(int passed_through) { HPX_TEST_EQ(passed_through, 42); return hpx::this_thread::get_id(); } void apply_test( hpx::lcos::local::latch& l, hpx::thread::id& id, int passed_through) { HPX_TEST_EQ(passed_through, 42); id = hpx::this_thread::get_id(); l.count_down(1); } /////////////////////////////////////////////////////////////////////////////// template <typename Executor> void test_timed_apply(Executor& exec) { { hpx::lcos::local::latch l(2); hpx::thread::id id; hpx::parallel::execution::timed_executor<Executor> timed_exec( exec, milliseconds(10)); hpx::parallel::execution::post( timed_exec, &apply_test, std::ref(l), std::ref(id), 42); l.count_down_and_wait(); HPX_TEST_EQ(id, hpx::this_thread::get_id()); } { hpx::lcos::local::latch l(2); hpx::thread::id id; hpx::parallel::execution::timed_executor<Executor> timed_exec( exec, steady_clock::now() + milliseconds(10)); hpx::parallel::execution::post( timed_exec, &apply_test, std::ref(l), std::ref(id), 42); l.count_down_and_wait(); HPX_TEST_EQ(id, hpx::this_thread::get_id()); } } template <typename Executor> void test_timed_sync(Executor& exec) { { hpx::parallel::execution::timed_executor<Executor> timed_exec( exec, milliseconds(10)); HPX_TEST(hpx::parallel::execution::sync_execute( timed_exec, &sync_test, 42) == hpx::this_thread::get_id()); } { hpx::parallel::execution::timed_executor<Executor> timed_exec( exec, steady_clock::now() + milliseconds(10)); HPX_TEST(hpx::parallel::execution::sync_execute( timed_exec, &sync_test, 42) == hpx::this_thread::get_id()); } } template <typename Executor> void test_timed_async(Executor& exec) { { hpx::parallel::execution::timed_executor<Executor> timed_exec( exec, milliseconds(10)); HPX_TEST( hpx::parallel::execution::async_execute(timed_exec, &sync_test, 42) .get() == hpx::this_thread::get_id()); } { hpx::parallel::execution::timed_executor<Executor> timed_exec( exec, steady_clock::now() + milliseconds(10)); HPX_TEST( hpx::parallel::execution::async_execute(timed_exec, &sync_test, 42) .get() == hpx::this_thread::get_id()); } } std::atomic<std::size_t> count_sync(0); std::atomic<std::size_t> count_apply(0); std::atomic<std::size_t> count_sync_at(0); std::atomic<std::size_t> count_apply_at(0); template <typename Executor> void test_timed_executor(std::array<std::size_t, 4> expected) { typedef typename hpx::traits::executor_execution_category<Executor>::type execution_category; HPX_TEST((std::is_same<hpx::parallel::execution::sequenced_execution_tag, execution_category>::value)); count_sync.store(0); count_apply.store(0); count_sync_at.store(0); count_apply_at.store(0); Executor exec; test_timed_apply(exec); test_timed_sync(exec); test_timed_async(exec); HPX_TEST_EQ(expected[0], count_sync.load()); HPX_TEST_EQ(expected[1], count_apply.load()); HPX_TEST_EQ(expected[2], count_sync_at.load()); HPX_TEST_EQ(expected[3], count_apply_at.load()); } /////////////////////////////////////////////////////////////////////////////// struct test_sync_executor1 { typedef hpx::parallel::execution::sequenced_execution_tag execution_category; template <typename F, typename... Ts> typename hpx::util::detail::invoke_deferred_result<F, Ts...>::type static sync_execute(F&& f, Ts&&... ts) { ++count_sync; return hpx::util::invoke(std::forward<F>(f), std::forward<Ts>(ts)...); } }; struct test_timed_sync_executor1 : test_sync_executor1 { typedef hpx::parallel::execution::sequenced_execution_tag execution_category; template <typename F, typename... Ts> typename hpx::util::detail::invoke_deferred_result<F, Ts...>::type static sync_execute_at(hpx::util::steady_time_point const& abs_time, F&& f, Ts&&... ts) { ++count_sync_at; hpx::this_thread::sleep_until(abs_time); return hpx::util::invoke(std::forward<F>(f), std::forward<Ts>(ts)...); } }; namespace hpx { namespace parallel { namespace execution { template <> struct is_one_way_executor<test_sync_executor1> : std::true_type { }; template <> struct is_one_way_executor<test_timed_sync_executor1> : std::true_type { }; }}} // namespace hpx::parallel::execution struct test_sync_executor2 : test_sync_executor1 { typedef hpx::parallel::execution::sequenced_execution_tag execution_category; template <typename F, typename... Ts> static void post(F&& f, Ts&&... ts) { ++count_apply; hpx::util::invoke(std::forward<F>(f), std::forward<Ts>(ts)...); } }; struct test_timed_sync_executor2 : test_sync_executor2 { template <typename F, typename... Ts> static void post_at( hpx::util::steady_time_point const& abs_time, F&& f, Ts&&... ts) { ++count_apply_at; hpx::this_thread::sleep_until(abs_time); hpx::util::invoke(std::forward<F>(f), std::forward<Ts>(ts)...); } }; namespace hpx { namespace parallel { namespace execution { template <> struct is_one_way_executor<test_sync_executor2> : std::true_type { }; template <> struct is_one_way_executor<test_timed_sync_executor2> : std::true_type { }; }}} // namespace hpx::parallel::execution /////////////////////////////////////////////////////////////////////////////// int hpx_main(int argc, char* argv[]) { test_timed_executor<test_sync_executor1>({{6, 0, 0, 0}}); test_timed_executor<test_sync_executor2>({{4, 2, 0, 0}}); test_timed_executor<test_timed_sync_executor1>({{2, 0, 4, 0}}); test_timed_executor<test_timed_sync_executor2>({{4, 0, 0, 2}}); return hpx::finalize(); } int main(int argc, char* argv[]) { // By default this test should run on all available cores std::vector<std::string> const cfg = {"hpx.os_threads=all"}; // Initialize and run HPX HPX_TEST_EQ_MSG( hpx::init(argc, argv, cfg), 0, "HPX main exited with non-zero status"); return hpx::util::report_errors(); }
28.560784
80
0.618289
[ "vector" ]
d5478453ccffbcbfb35209a41403986ef03e3923
10,938
cpp
C++
OpenSim/Tools/Test/testExternalLoads.cpp
mcx/opensim-core
c109f8cec3a81c732f335cd39752da6ae573b604
[ "Apache-2.0" ]
532
2015-03-13T18:51:10.000Z
2022-03-27T08:08:29.000Z
OpenSim/Tools/Test/testExternalLoads.cpp
mcx/opensim-core
c109f8cec3a81c732f335cd39752da6ae573b604
[ "Apache-2.0" ]
2,701
2015-01-03T21:33:34.000Z
2022-03-30T07:13:41.000Z
OpenSim/Tools/Test/testExternalLoads.cpp
mcx/opensim-core
c109f8cec3a81c732f335cd39752da6ae573b604
[ "Apache-2.0" ]
271
2015-02-16T23:25:29.000Z
2022-03-30T20:12:17.000Z
/* -------------------------------------------------------------------------- * * OpenSim: testExternalLoads.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ajay Seth * * * * 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 <iostream> #include <OpenSim/OpenSim.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; void testExternalLoad(); void testExternalLoadDefaultProperties(); int main() { SimTK_START_TEST("testExternalLoads"); SimTK_SUBTEST(testExternalLoad); SimTK_SUBTEST(testExternalLoadDefaultProperties); SimTK_END_TEST(); } void addLoadToStorage(Storage &forceStore, SimTK::Vec3 force, SimTK::Vec3 point, SimTK::Vec3 torque) { int nLoads = forceStore.getColumnLabels().getSize()/9; string labels[9] = { "forceX", "forceY", "forceZ", "pointX", "pointY", "pointZ","torqueX", "torqueY", "torqueZ"}; Array<string> col_labels; col_labels.append("time"); StateVector dataRow; dataRow.setTime(0); double data[9]; for(int i = 0; i<9; i++){ col_labels.append(labels[i]); if(i<3){ data[i] = force[i]; continue; } else if(i<6){ data[i] = point[i-3]; continue; } else data[i] = torque[i-6]; } dataRow.setStates(0, SimTK::Vector_<double>(9, data)); Storage *forces = NULL; Storage tempStore; if(nLoads == 0) forces = &forceStore; else if (nLoads > 0) forces = &tempStore; else throw OpenSim::Exception("addLoadToStorage: ERROR"); forces->setColumnLabels(col_labels); forces->append(dataRow); dataRow.setTime(1.0); forces->append(dataRow); dataRow.setTime(2.0); forces->append(dataRow); if (nLoads > 0) forces->addToRdStorage(forceStore, 0.0, 1.0); } void testExternalLoad() { using namespace SimTK; Model model("Pendulum.osim"); State &s = model.initSystem(); // Simulate gravity double init_t =-1e-8; double final_t = 2.0; int nsteps = 10; double dt = final_t/nsteps; //initial state double q_init = Pi/4; model.updCoordinateSet()[0].setValue(s, q_init); Vector_<double> q_grav(nsteps+1); // Integrator and integration manager double integ_accuracy = 1e-6; Manager manager(model); manager.setIntegratorAccuracy(integ_accuracy); s.setTime(init_t); manager.initialize(s); for(int i = 0; i < nsteps+1; i++){ manager.integrate(dt*i); q_grav[i] = model.updCoordinateSet()[0].getValue(s); } //q_grav.dump("Coords due to gravity."); /***************************** CASE 1 ************************************/ // Simulate the same system without gravity but with an equivalent external load OpenSim::Body &pendulum = model.getBodySet().get(model.getNumBodies()-1); string pendBodyName = pendulum.getName(); Vec3 comInB = pendulum.getMassCenter(); Storage forceStore; addLoadToStorage(forceStore, pendulum.getMass()*model.getGravity(), comInB, Vec3(0, 0, 0)); forceStore.setName("test_external_loads.sto"); forceStore.print(forceStore.getName()); // Apply external force with force in ground, point in body, zero torque ExternalForce xf(forceStore, "force", "point", "torque", pendBodyName, "ground", pendBodyName); xf.setName("grav"); ExternalLoads* extLoads = new ExternalLoads(); extLoads->adoptAndAppend(&xf); extLoads->print("ExternalLoads_test.xml"); model.addModelComponent(extLoads); // Create the force reporter ForceReporter* reporter = new ForceReporter(); model.addAnalysis(reporter); Kinematics* kin = new Kinematics(); kin->setInDegrees(false); model.addAnalysis(kin); PointKinematics* pKin = new PointKinematics(); pKin->setBody(&pendulum); pKin->setPoint(comInB); pKin->setPointName(pendulum.getName()+"_com_p"); model.addAnalysis(pKin); SimTK::State& s2 = model.initSystem(); // Turn-off gravity in the model model.updGravityForce().disable(s2); // initial position model.updCoordinateSet()[0].setValue(s2, q_init); Manager manager2(model); manager2.setIntegratorAccuracy(integ_accuracy); s2.setTime(init_t); manager2.initialize(s2); // Simulate with the external force applied instead of gravity Vector_<double> q_xf(nsteps+1); Vector_<Vec3> pcom_xf(nsteps+1); for(int i = 0; i < nsteps+1; i++){ manager2.integrate(dt*i); q_xf[i] = model.updCoordinateSet()[0].getValue(s2); } //q_xf.dump("Coords due to external force point expressed in pendulum."); Vector err = q_xf-q_grav; double norm_err = err.norm(); // kinematics should match to within integ accuracy ASSERT_EQUAL(0.0, norm_err, integ_accuracy); /***************************** CASE 2 ************************************/ // Simulate the same system without gravity but with an equivalent external // force but this time with the point expressed in ground and using // previous kinematics to transform point to pendulum. // Construct a new Storage for ExternalForce data source with point // described in ground Storage forceStore2 = reporter->getForceStorage(); forceStore2.print("ForcesTest.sto"); Storage *pStore = pKin->getPositionStorage(); pStore->print("PointInGroundTest.sto"); pStore->addToRdStorage(forceStore2, init_t, final_t); forceStore2.setName("ExternalForcePointInGround.sto"); forceStore2.print(forceStore2.getName()); Storage *qStore = kin->getPositionStorage(); qStore->print("LoadKinematics.sto"); string id_base = pendBodyName+"_"+xf.getName(); string point_id = pKin->getPointName(); ExternalForce xf2(forceStore2, id_base+"_F", point_id, id_base+"_T", pendBodyName, "ground", "ground"); xf2.setName("xf_pInG"); xf2.finalizeFromProperties(); // Empty out existing external forces extLoads->setMemoryOwner(false); extLoads->setSize(0); extLoads->adoptAndAppend(&xf2); //Ask external loads to transform point expressed in ground to the applied body extLoads->setDataFileName(forceStore2.getName()); extLoads->transformPointsExpressedInGroundToAppliedBodies(*qStore); // recreate dynamical system to reflect new force SimTK::State &s3 = model.initSystem(); // Turn-off gravity in the model model.updGravityForce().disable(s3); // initial position model.updCoordinateSet()[0].setValue(s3, q_init); Manager manager3(model); manager3.setIntegratorAccuracy(integ_accuracy); s3.setTime(init_t); manager3.initialize(s3); // Simulate with the external force applied instead of gravity Vector_<double> q_xf2(nsteps+1); for(int i = 0; i < nsteps+1; i++){ manager3.integrate(dt*i); q_xf2[i] = model.updCoordinateSet()[0].getValue(s3); } //q_xf2.dump("Coords due to external force point expressed in ground."); err = q_xf2-q_grav; //err.dump("Coordinate error after transforming point."); norm_err = err.norm(); // kinematics should match to within integ accuracy ASSERT_EQUAL(0.0, norm_err, integ_accuracy); } // Ensure the default values for the ExternalForce properties work as expected. void testExternalLoadDefaultProperties() { using namespace SimTK; Model model("Pendulum.osim"); auto& pendulum = model.getBodySet().get(model.getNumBodies()-1); string pendBodyName = pendulum.getName(); Vec3 comInB = pendulum.getMassCenter(); Storage forceStore; addLoadToStorage(forceStore, pendulum.getMass()*model.getGravity(), comInB, Vec3(0, 0, 0)); forceStore.setName("test_external_load_default_properties.sto"); forceStore.print(forceStore.getName()); ExternalForce* xf = new ExternalForce(); xf->setName("grav"); xf->setDataSource(forceStore); SimTK_TEST(!xf->appliesForce()); SimTK_TEST(!xf->specifiesPoint()); SimTK_TEST(!xf->appliesTorque()); xf->set_force_identifier("force"); SimTK_TEST(xf->appliesForce()); xf->set_point_identifier("point"); SimTK_TEST(xf->specifiesPoint()); xf->set_torque_identifier("torque"); SimTK_TEST(xf->appliesTorque()); SimTK_TEST(xf->getAppliedToBodyName() == ""); xf->set_applied_to_body(pendBodyName); SimTK_TEST(xf->getPointExpressedInBodyName() == "ground"); xf->set_point_expressed_in_body(pendBodyName); SimTK_TEST(xf->getForceExpressedInBodyName() == "ground"); // Leave force_expressed_in_body as default ("ground"). ExternalLoads* extLoads = new ExternalLoads(); extLoads->adoptAndAppend(xf); extLoads->print("testExternalLoadDefaultProperties_ExternalLoads.xml"); for(int i=0; i<extLoads->getSize(); i++) model.addForce(&(*extLoads)[i]); // Ensure that, even when force_expressed_in_body is unspecified, no issues // occur when initializing ExternalForce. model.initSystem(); // ExternalForce throws an exception if it can't find the applied_to_body. xf->set_applied_to_body(""); SimTK_TEST_MUST_THROW_EXC(model.initSystem(), OpenSim::Exception); xf->set_applied_to_body(pendBodyName); // If force_expressed_in_body can't be found, it's set to ground; no error. xf->set_force_expressed_in_body("nonexistent"); model.initSystem(); }
35.745098
117
0.633571
[ "vector", "model", "transform" ]
d54f58eb5b1ad1c13c1937fc8cf131a9562e9f0d
8,017
cpp
C++
super-mario-dx10/05-SceneManager/Mario.cpp
HoangTuan0611/Game
64bbf4396ff38d17d3516c1eae687033f954d769
[ "MIT" ]
null
null
null
super-mario-dx10/05-SceneManager/Mario.cpp
HoangTuan0611/Game
64bbf4396ff38d17d3516c1eae687033f954d769
[ "MIT" ]
null
null
null
super-mario-dx10/05-SceneManager/Mario.cpp
HoangTuan0611/Game
64bbf4396ff38d17d3516c1eae687033f954d769
[ "MIT" ]
null
null
null
#include <algorithm> #include "debug.h" #include "Mario.h" #include "Game.h" #include "Goomba.h" #include "Coin.h" #include "Portal.h" #include "Collision.h" #include "Block.h" #include "QuestionBrick.h" #include "MushRoom.h" void CMario::Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects) { vy += ay * dt; vx += ax * dt; if (abs(vx) > abs(maxVx)) vx = maxVx; // reset untouchable timer if untouchable time has passed if (GetTickCount64() - untouchable_start > MARIO_UNTOUCHABLE_TIME) { untouchable_start = 0; untouchable = 0; } isOnPlatform = false; for (int i = 0; i < coObjects->size(); i++) { LPGAMEOBJECT obj = coObjects->at(i); if (dynamic_cast<CBlock*>(obj)) { if (obj->getY() - 16 < this->y) { obj->SetIsBlocking(0); } else { obj->SetIsBlocking(1); } } } CCollision::GetInstance()->Process(this, dt, coObjects); } void CMario::OnNoCollision(DWORD dt) { x += vx * dt; y += vy * dt; } void CMario::OnCollisionWith(LPCOLLISIONEVENT e) { if (e->ny != 0 && e->obj->IsBlocking()) { vy = 0; if (e->ny < 0) isOnPlatform = true; } else { if (e->nx != 0 && e->obj->IsBlocking()) { if (!dynamic_cast<CBlock*>(e->obj)) vx = 0; } } if (dynamic_cast<CBlock*>(e->obj)) OnCollisionWithBlock(e); else if (dynamic_cast<CGoomba*>(e->obj)) OnCollisionWithGoomba(e); else if (dynamic_cast<CCoin*>(e->obj)) OnCollisionWithCoin(e); else if (dynamic_cast<CPortal*>(e->obj)) OnCollisionWithPortal(e); else if (dynamic_cast<QuestionBrick*>(e->obj)) OnCollisionWithQuestionBrick(e); else if (dynamic_cast<CMushRoom*>(e->obj)) OnCollisionWithMushRoom(e); } void CMario::OnCollisionWithBlock(LPCOLLISIONEVENT e) { //if (e->nx != 0) //{ // e->obj->SetIsBlocking(0); //} //if (e->ny < 0) //{ // e->obj->SetIsBlocking(1); //} //if (e->ny > 0 && vy < 0) //{ // e->obj->SetIsBlocking(0); //} } void CMario::OnCollisionWithGoomba(LPCOLLISIONEVENT e) { CGoomba* goomba = dynamic_cast<CGoomba*>(e->obj); if (e->ny < 0) { if (goomba->GetState() != GOOMBA_STATE_DIE) { if (goomba->tag == GOOMBA_RED) goomba->SetTag(GOOMBA_RED_NORMAL); else if (goomba->tag == GOOMBA_SUPER) goomba->SetTag(GOOMBA_NORMAL); else goomba->SetState(GOOMBA_STATE_DIE); vy = -MARIO_JUMP_DEFLECT_SPEED; } } else // hit by Goomba { if (untouchable == 0) { if (goomba->GetState() != GOOMBA_STATE_DIE) { if (level > MARIO_LEVEL_SMALL) { level = MARIO_LEVEL_SMALL; StartUntouchable(); } else { DebugOut(L">>> Mario DIE >>> \n"); //SetState(MARIO_STATE_DIE); } } } } } void CMario::OnCollisionWithCoin(LPCOLLISIONEVENT e) { e->obj->Delete(); coin++; } void CMario::OnCollisionWithMushRoom(LPCOLLISIONEVENT e) { e->obj->Delete(); SetLevel(MARIO_LEVEL_BIG); } void CMario::OnCollisionWithPortal(LPCOLLISIONEVENT e) { CPortal* p = (CPortal*)e->obj; CGame::GetInstance()->InitiateSwitchScene(p->GetSceneId()); } void CMario::OnCollisionWithQuestionBrick(LPCOLLISIONEVENT e) { QuestionBrick* qBrick = dynamic_cast<QuestionBrick*>(e->obj); // Hit from bottom if (e->ny > 0) { vy = 0; qBrick->SetState(QUESTION_BRICK_HIT); } } int CMario::GetAniIdSmall() { int aniId = -1; if (!isOnPlatform) { if (abs(ax) == MARIO_ACCEL_RUN_X) { if (nx >= 0) aniId = MARIO_ANI_SMALL_RUNNING_RIGHT; else aniId = MARIO_ANI_SMALL_RUNNING_LEFT; } else { if (nx >= 0) aniId = MARIO_ANI_SMALL_WALKING_FAST_RIGHT; else aniId = MARIO_ANI_SMALL_WALKING_FAST_LEFT; } } else if (isSitting) { if (nx > 0) aniId = MARIO_ANI_SMALL_IDLE_RIGHT; else aniId = MARIO_ANI_SMALL_IDLE_LEFT; } else if (vx == 0) { if (nx > 0) aniId = MARIO_ANI_SMALL_IDLE_RIGHT; else aniId = MARIO_ANI_SMALL_IDLE_LEFT; } else if (vx > 0) { if (ax < 0) aniId = MARIO_ANI_SMALL_BRAKING_RIGHT; else if (ax == MARIO_ACCEL_RUN_X) aniId = MARIO_ANI_SMALL_RUNNING_RIGHT; else if (ax == MARIO_ACCEL_WALK_X) aniId = MARIO_ANI_SMALL_WALKING_RIGHT; } else // vx < 0 { if (ax > 0) aniId = MARIO_ANI_SMALL_BRAKING_LEFT; else if (ax == -MARIO_ACCEL_RUN_X) aniId = MARIO_ANI_SMALL_RUNNING_LEFT; else if (ax == -MARIO_ACCEL_WALK_X) aniId = MARIO_ANI_SMALL_WALKING_LEFT; } if (aniId == -1) aniId = MARIO_ANI_SMALL_IDLE_RIGHT; return aniId; } int CMario::GetAniIdBig() { int aniId = -1; if (!isOnPlatform) { if (abs(ax) == MARIO_ACCEL_RUN_X) { if (nx >= 0) aniId = MARIO_ANI_BIG_RUNNING_RIGHT; else aniId = MARIO_ANI_BIG_RUNNING_LEFT; } else { if (nx >= 0) aniId = MARIO_ANI_BIG_WALKING_FAST_RIGHT; else aniId = MARIO_ANI_BIG_WALKING_FAST_LEFT; } } else if (isSitting) { if (nx > 0) aniId = MARIO_ANI_BIG_SITTING_RIGHT; else aniId = MARIO_ANI_BIG_SITTING_LEFT; } else if (vx == 0) { if (nx > 0) aniId = MARIO_ANI_BIG_IDLE_RIGHT; else aniId = MARIO_ANI_BIG_IDLE_LEFT; } else if (vx > 0) { if (ax < 0) aniId = MARIO_ANI_BIG_BRAKING_RIGHT; else if (ax == MARIO_ACCEL_RUN_X) aniId = MARIO_ANI_BIG_RUNNING_RIGHT; else if (ax == MARIO_ACCEL_WALK_X) aniId = MARIO_ANI_BIG_WALKING_RIGHT; } else // vx < 0 { if (ax > 0) aniId = MARIO_ANI_BIG_BRAKING_LEFT; else if (ax == -MARIO_ACCEL_RUN_X) aniId = MARIO_ANI_BIG_RUNNING_LEFT; else if (ax == -MARIO_ACCEL_WALK_X) aniId = MARIO_ANI_BIG_WALKING_LEFT; } if (aniId == -1) aniId = MARIO_ANI_BIG_IDLE_RIGHT; return aniId; } void CMario::Render() { int aniId = -1; if (state == MARIO_STATE_DIE) aniId = MARIO_ANI_DIE; else if (level == MARIO_LEVEL_BIG) aniId = GetAniIdBig(); else if (level == MARIO_LEVEL_SMALL) aniId = GetAniIdSmall(); if (isSitting) animation_set->at(aniId)->Render(x, y + 4); else animation_set->at(aniId)->Render(x, y); RenderBoundingBox(); } void CMario::SetState(int state) { // DIE is the end state, cannot be changed! if (this->state == MARIO_STATE_DIE) return; switch (state) { case MARIO_STATE_RUNNING_RIGHT: if (isSitting) break; maxVx = MARIO_RUNNING_SPEED; ax = MARIO_ACCEL_RUN_X; nx = 1; break; case MARIO_STATE_RUNNING_LEFT: if (isSitting) break; maxVx = -MARIO_RUNNING_SPEED; ax = -MARIO_ACCEL_RUN_X; nx = -1; break; case MARIO_STATE_WALKING_RIGHT: if (isSitting) break; maxVx = MARIO_WALKING_SPEED; ax = MARIO_ACCEL_WALK_X; nx = 1; break; case MARIO_STATE_WALKING_LEFT: if (isSitting) break; maxVx = -MARIO_WALKING_SPEED; ax = -MARIO_ACCEL_WALK_X; nx = -1; break; case MARIO_STATE_JUMP: if (isSitting) break; if (isOnPlatform) { if (abs(this->vx) == MARIO_RUNNING_SPEED) vy = -MARIO_JUMP_RUN_SPEED_Y; else vy = -MARIO_JUMP_SPEED_Y; } break; case MARIO_STATE_RELEASE_JUMP: if (vy < 0) vy += MARIO_JUMP_SPEED_Y / 2; break; case MARIO_STATE_SIT: if (isOnPlatform && level != MARIO_LEVEL_SMALL) { state = MARIO_STATE_IDLE; isSitting = true; vx = 0; vy = 0.0f; y += MARIO_SIT_HEIGHT_ADJUST; } break; case MARIO_STATE_SIT_RELEASE: if (isSitting) { isSitting = false; state = MARIO_STATE_IDLE; y -= MARIO_SIT_HEIGHT_ADJUST; } break; case MARIO_STATE_IDLE: ax = 0.0f; vx = 0.0f; break; case MARIO_STATE_DIE: vy = -MARIO_JUMP_DEFLECT_SPEED; vx = 0; ax = 0; break; } CGameObject::SetState(state); } void CMario::GetBoundingBox(float& left, float& top, float& right, float& bottom) { left = x; top = y; if (level != MARIO_LEVEL_SMALL) { right = x + MARIO_BIG_BBOX_WIDTH; bottom = y + MARIO_BIG_BBOX_HEIGHT; if (state == MARIO_STATE_SIT) { bottom = top + MARIO_BBOX_SIT_HEIGHT; } } else { right = x + MARIO_SMALL_BBOX_WIDTH; bottom = y + MARIO_SMALL_BBOX_HEIGHT; } } void CMario::SetLevel(int l) { // Adjust position to avoid falling off platform if (this->level == MARIO_LEVEL_SMALL) { y -= (MARIO_BIG_BBOX_HEIGHT - MARIO_SMALL_BBOX_HEIGHT); } level = l; }
19.601467
81
0.653112
[ "render", "vector" ]
d555f7b70d9b8621237edd58a44a2d431ce5214b
10,556
cxx
C++
DiscreteRemeshing/Examples/ACVD.cxx
djelouze/ACVD
f3e31cf61f54e33c40d5a1e10cd91a7953b07c7d
[ "CECILL-B" ]
null
null
null
DiscreteRemeshing/Examples/ACVD.cxx
djelouze/ACVD
f3e31cf61f54e33c40d5a1e10cd91a7953b07c7d
[ "CECILL-B" ]
null
null
null
DiscreteRemeshing/Examples/ACVD.cxx
djelouze/ACVD
f3e31cf61f54e33c40d5a1e10cd91a7953b07c7d
[ "CECILL-B" ]
null
null
null
/*========================================================================= Program: Aproximated Centroidal Voronoi Diagrams Module: ACVD.cxx Language: C++ Date: 2003/11 Author: Sebastien Valette =========================================================================*/ /* --------------------------------------------------------------------- * Copyright (c) CREATIS-LRMN (Centre de Recherche en Imagerie Medicale) * Author : Sebastien Valette * * This software is governed by the CeCILL-B license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL-B * license as circulated by CEA, CNRS and INRIA at the following URL * http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html * or in the file LICENSE.txt. * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. * ------------------------------------------------------------------------ */ // .NAME ACVD // .SECTION Description #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include "vtkIsotropicDiscreteRemeshing.h" using namespace std; ///////////////////////////////////////////////////////////////////////////////////////// // ACVD program: // // Adaptive coarsening of triangular meshes // References: // [1] " Approximated Centroidal Voronoi Diagrams for Uniform // Polygonal Mesh Coarsening", Valette & Chassery, Eurographics 2004. // [2] "Adaptive Polygonal Mesh Simplification With Discrete Centroidal Voronoi Diagrams" // by, S. Valette, I. Kompatsiaris and J.-M. Chassery ///////////////////////////////////////////////////////////////////////////////////////// int main( int argc, char *argv[] ) { int Display=0; // defines whether there will be a graphic display (0: No, 1: yes) int NumberOfSamples = 0; // number of desired vertices double Gradation = 0; // gamma parameter for simplification (if gamma=0: uniform) // other appropriates values range between 0 and 2 int SubsamplingThreshold = 10; int QuadricsOptimizationLevel = 1; char* OutputDirectory = 0; char outputfile[500]; strcpy (outputfile, "simplification.ply"); if(argc > 3) { std::cout << "load : " << argv[1] << endl; NumberOfSamples = atoi(argv[2]); Gradation = atof(argv[3]); } else { cout << "Usage : ACVD file nvertices gradation [options]" << endl; cout << "nvertices is the desired number of vertices" << endl; cout << "gradation defines the influence of local curvature (0=uniform meshing)" << endl; cout << endl << "Optionnal arguments : " << endl; cout << "-b 0/1 : sets mesh boundary fixing off/on (default : 0)" << endl; cout << "-s threshold : defines the subsampling threshold i.e. the input mesh will be subdivided until its number " << endl; cout << "-o directory : sets the output directory " << endl; cout << "-of file : sets the output file name " << endl; cout << " of vertices is above nvertices*threshold (default=10)" << endl; cout << "-d 0/1/2 : enables display (default : 0)" << endl; cout << "-l ratio : split the edges longer than ( averageLength * ratio )" << endl; cout << "-q 0/1/2 : set the number of eigenvalues for quadrics post-processing (default : 3)" << endl; cout << "-cd file : set custom imagedata file containing density information" << endl; cout << "-cmin value : set minimum custom indicator value" << endl; cout << "-cmax value : set maximum custom indicator value" << endl; cout << "-cf value : set custom indicator multiplication factor" << endl; cout << "-m 0/1 : enforce a manifold output ON/OFF (default : 0)" << endl; cout << "-sf spare_factor : sets the spare factor" << endl; cout << "-sc number_of_spare_clusters : sets the number of spare clusters" << endl; return (0); } vtkSurface *Mesh = vtkSurface::New(); Mesh->CreateFromFile(argv[1]); Mesh->GetCellData()->Initialize(); Mesh->GetPointData()->Initialize(); Mesh->DisplayMeshProperties(); vtkIsotropicDiscreteRemeshing *Remesh = vtkIsotropicDiscreteRemeshing::New(); // Parse optionnal arguments int ArgumentsIndex = 4; while (ArgumentsIndex < argc) { char* key = argv[ArgumentsIndex]; char* value = argv[ArgumentsIndex + 1]; if (strcmp(key, "-m") == 0) { Remesh->SetForceManifold(atoi(value)); cout << "Force Manifold=" << atoi(value) << endl; } if (strcmp(key, "-s") == 0) { SubsamplingThreshold = atoi(value); cout << "Subsampling Threshold=" << SubsamplingThreshold << endl; } if (strcmp(key, "-d") == 0) { Display = atoi(value); cout << "Display=" << Display << endl; } #ifdef DOmultithread if (strcmp(key, "-np") == 0) { int NumberOfThreads = atoi(value); cout << "Number of threads=" << NumberOfThreads << endl; Remesh->SetNumberOfThreads(NumberOfThreads); } #endif if (strcmp(key, "-o") == 0) { OutputDirectory = value; cout << "OutputDirectory: " << OutputDirectory << endl; Remesh->SetOutputDirectory(value); } if (strcmp(key, "-of") == 0) { strcpy(outputfile, value); cout << "Output file name: " << outputfile << endl; } if (strcmp(key, "-l") == 0) { Mesh->SplitLongEdges(atof(value)); cout << "Splitting edges longer than " << atof(value) << " times the average edge length" << endl; } if (strcmp(key, "-w") == 0) { cout << "Setting writing energy log file to " << atoi(value) << endl; Remesh->SetWriteToGlobalEnergyLog(atoi(value)); } if (strcmp(key, "-q") == 0) { cout << "Setting number of eigenvalues for quadrics to " << atoi(value) << endl; QuadricsOptimizationLevel = atoi(value); } if (strcmp(key, "-cd") == 0) { cout << "Setting custom file for density info : " << value << endl; Remesh->SetInputDensityFile(value); } if (strcmp(key, "-cmax") == 0) { cout << "Setting maximum custom density to : " << value << endl; Remesh->SetMaxCustomDensity(atof(value)); } if (strcmp(key,"-cmin")==0) { cout<<"Setting minimum custom density to : " << value << endl; Remesh->SetMinCustomDensity(atof(value)); } if (strcmp(key, "-cf") == 0) { cout<<"Setting custom density multiplication factor to : "<< value << endl; Remesh->SetCustomDensityMultiplicationFactor(atof(value)); } if (strcmp(key, "-sc") == 0) { cout << "Setting number of spare clusters to : " << value << endl; Remesh->SetMinNumberOfSpareClusters(atoi(value)); } if (strcmp(key, "-sf") == 0) { cout << "Setting spare factor to : " << value << endl; Remesh->SetSpareFactor(atof(value)); } if (strcmp(key, "-b") == 0) { cout << "Setting boundary fixing to : " << value << endl; Remesh->SetBoundaryFixing(atoi(value)); } ArgumentsIndex += 2; } RenderWindow *Window = 0; if (Display) { Window = RenderWindow::New(); vtkPolyData *Visu=vtkPolyData::New(); Visu->ShallowCopy(Mesh); Window->SetInputData(Visu); Visu->Delete(); Remesh->SetAnchorRenderWindow(Window); Window->Render(); Window->SetWindowName(argv[1]); Window->GetCamera()->Zoom(1.6); Window->Interact(); } Remesh->SetInput(Mesh); Remesh->SetFileLoadSaveOption(0); Remesh->SetNumberOfClusters(NumberOfSamples); Remesh->SetConsoleOutput(2); Remesh->SetSubsamplingThreshold(SubsamplingThreshold); Remesh->GetMetric()->SetGradation(Gradation); Remesh->SetDisplay(Display); Remesh->Remesh(); if (QuadricsOptimizationLevel != 0) { // Note : this is an adaptation of Siggraph 2000 Paper : // Out-of-core simplification of large polygonal models vtkIntArray *Clustering = Remesh->GetClustering(); char REALFILE[5000]; char FileBeforeProcessing[500]; strcpy (FileBeforeProcessing,"smooth_"); strcat (FileBeforeProcessing, outputfile); if (OutputDirectory) { strcpy (REALFILE, OutputDirectory); strcat (REALFILE, FileBeforeProcessing); } else { strcpy (REALFILE, FileBeforeProcessing); } Remesh->GetOutput()->WriteToFile(REALFILE); int Cluster,NumberOfMisclassedItems = 0; double **ClustersQuadrics = new double*[NumberOfSamples]; for (int i = 0; i < NumberOfSamples; i++) { ClustersQuadrics[i] = new double[9]; for (int j = 0; j < 9; j++) { ClustersQuadrics[i][j] = 0; } } vtkIdList *FList = vtkIdList::New(); for (int i = 0; i < Remesh->GetNumberOfItems (); i++) { Cluster = Clustering->GetValue (i); if ((Cluster >= 0)&& (Cluster < NumberOfSamples)) { if (Remesh->GetClusteringType() == 0) { vtkQuadricTools::AddTriangleQuadric( ClustersQuadrics[Cluster], Remesh->GetInput(), i, false); } else { Remesh->GetInput()->GetVertexNeighbourFaces(i, FList); for (int j = 0;j < FList->GetNumberOfIds(); j++) vtkQuadricTools::AddTriangleQuadric( ClustersQuadrics[Cluster], Remesh->GetInput(), FList->GetId(j), false); } } else { NumberOfMisclassedItems++; } } FList->Delete(); if (NumberOfMisclassedItems) { cout << NumberOfMisclassedItems << " Items with wrong cluster association" << endl; } double P[3]; for (int i = 0; i < NumberOfSamples; i++) { Remesh->GetOutput()->GetPoint (i, P); vtkQuadricTools::ComputeRepresentativePoint(ClustersQuadrics[i], P, QuadricsOptimizationLevel); Remesh->GetOutput()->SetPointCoordinates (i, P); delete[] ClustersQuadrics[i]; } delete [] ClustersQuadrics; Mesh->GetPoints()->Modified (); cout << "After Quadrics Post-processing : " << endl; Remesh->GetOutput()->DisplayMeshProperties(); if (Display) { RenderWindow *OptimizedMeshWindow = RenderWindow::New(); OptimizedMeshWindow->AttachToRenderWindow(Remesh->GetDisplayWindow()); OptimizedMeshWindow->SetInputData(Remesh->GetOutput()); OptimizedMeshWindow->SetWindowName("Coarsened model (quadric based placement)"); OptimizedMeshWindow->Render (); OptimizedMeshWindow->Interact (); } } // save the output mesh to .ply format char REALFILE[500]; strcpy (REALFILE, ""); if (OutputDirectory) { strcpy (REALFILE, OutputDirectory); strcat (REALFILE, "/"); } strcat (REALFILE, outputfile); Remesh->GetOutput()->WriteToFile(REALFILE); Remesh->Delete(); Mesh->Delete(); if (Display) { // Window->Delete(); } }
33.405063
126
0.642194
[ "mesh", "render", "model" ]
d558de2762f14bc51f8a88b2d26befb7e4c650eb
6,317
hpp
C++
m+m/m+mPortArgumentDescriptor.hpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
m+m/m+mPortArgumentDescriptor.hpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
m+m/m+mPortArgumentDescriptor.hpp
opendragon/Core_MPlusM
c82bb00761551a86abe50c86e0df1f247704c848
[ "BSD-3-Clause" ]
null
null
null
//-------------------------------------------------------------------------------------------------- // // File: m+m/m+mPortArgumentDescriptor.hpp // // Project: m+m // // Contains: The class declaration for the minimal functionality required to represent a port // number command-line argument. // // Written by: Norman Jaffe // // Copyright: (c) 2015 by H Plus Technologies Ltd. and Simon Fraser University. // // All rights reserved. Redistribution and use in source and binary forms, with or // without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and / or // other materials provided with the distribution. // * Neither the name of the copyright holders nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // Created: 2015-05-21 // //-------------------------------------------------------------------------------------------------- #if (! defined(MpMPortArgumentDescriptor_HPP_)) # define MpMPortArgumentDescriptor_HPP_ /* Header guard */ # include <m+m/m+mIntArgumentDescriptor.hpp> # if defined(__APPLE__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wunknown-pragmas" # pragma clang diagnostic ignored "-Wdocumentation-unknown-command" # endif // defined(__APPLE__) /*! @file @brief The class declaration for the minimal functionality required to represent a port number command-line argument. */ # if defined(__APPLE__) # pragma clang diagnostic pop # endif // defined(__APPLE__) namespace MplusM { namespace Utilities { /*! @brief A port number argument description. The external representation of a port number argument description is: portTagAndInfo ::= 'P' sep systemOrRegular; systemOrRegular ::= 's' | 'r'; */ class PortArgumentDescriptor : public IntArgumentDescriptor { public : protected : private : /*! @brief The class that this class is derived from. */ typedef IntArgumentDescriptor inherited; public : /*! @brief The constructor. @param[in] argName The name of the command-line argument. @param[in] argDescription A description of the command-line argument. @param[in] argMode The mode of the command-line argument. @param[in] defaultValue The default value for the command-line argument. @param[in] isSystemPort @c true if the value can be a system port and @c false otherwise. */ PortArgumentDescriptor(const YarpString & argName, const YarpString & argDescription, const ArgumentMode argMode, const int defaultValue, const bool isSystemPort); /*! @brief The destructor. */ virtual ~PortArgumentDescriptor(void); /*! @brief Construct a descriptor, if at all possible, from the input string. @param[in] inString The input string in 'arguments' format. @return A valid descriptor or @c NULL if the input is not recognized. */ static BaseArgumentDescriptor * parseArgString(const YarpString & inString); protected : private : /*! @brief The copy constructor. @param[in] other The object to be copied. */ PortArgumentDescriptor(const PortArgumentDescriptor & other); /*! @brief Return a copy of the descriptor, with only non-pointer types duplicated. @return A copy of the descriptor, with only non-pointer types duplicated. */ virtual BaseArgumentDescriptor * clone(void); /*! @brief The assignment operator. @param[in] other The object to be copied. @return The updated object. */ PortArgumentDescriptor & operator =(const PortArgumentDescriptor & other); /*! @brief Convert to a printable representation. @return A printable representation of the descriptor. */ virtual YarpString toString(void); public : protected : private : /*! @brief @c true if the value can be a system port and @c false otherwise. */ bool _isSystemPort; # if defined(__APPLE__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wunused-private-field" # endif // defined(__APPLE__) /*! @brief Filler to pad to alignment boundary */ char _filler[7]; # if defined(__APPLE__) # pragma clang diagnostic pop # endif // defined(__APPLE__) }; // PortArgumentDescriptor } // Utilities } // MplusM #endif // ! defined(MpMPortArgumentDescriptor_HPP_)
41.019481
100
0.608517
[ "object" ]
d55902639289af98580396e925a508eb1c2b7906
2,551
cxx
C++
VTK/Rendering/Testing/Cxx/TestTextureRGBA.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
VTK/Rendering/Testing/Cxx/TestTextureRGBA.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
VTK/Rendering/Testing/Cxx/TestTextureRGBA.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile$ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME Test of an RGBA texture on a vtkActor. // .SECTION Description // this program tests the rendering of an vtkActor with a translucent texture // with alpha blending. #include "vtkPlaneSource.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkTexture.h" #include "vtkImageData.h" #include "vtkPNGReader.h" #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" int TestTextureRGBA(int argc, char *argv[]) { char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/textureRGBA.png"); vtkPNGReader *PNGReader = vtkPNGReader::New(); PNGReader->SetFileName(fname); PNGReader->Update(); vtkTexture *texture = vtkTexture::New(); texture->SetInputConnection(PNGReader->GetOutputPort()); PNGReader->Delete(); texture->InterpolateOn(); vtkPlaneSource *planeSource = vtkPlaneSource::New(); planeSource->Update(); vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput(planeSource->GetOutput()); planeSource->Delete(); vtkActor *actor = vtkActor::New(); actor->SetTexture(texture); texture->Delete(); actor->SetMapper(mapper); mapper->Delete(); vtkRenderer *renderer = vtkRenderer::New(); renderer->AddActor(actor); actor->Delete(); renderer->SetBackground(0.5,0.7,0.7); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *interactor = vtkRenderWindowInteractor::New(); interactor->SetRenderWindow(renWin); renWin->SetSize(400,400); renWin->Render(); interactor->Initialize(); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if( retVal == vtkRegressionTester::DO_INTERACTOR) { interactor->Start(); } renderer->Delete(); renWin->Delete(); interactor->Delete(); delete [] fname; return !retVal; }
27.728261
77
0.683653
[ "render" ]
f65a722d655b0f8381cf200ef3d34b91902cb20a
15,634
cpp
C++
src/method/query_method.cpp
Yechan0815/cubrid
da09d9e60b583d0b7ce5f665429f397976728d99
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/method/query_method.cpp
Yechan0815/cubrid
da09d9e60b583d0b7ce5f665429f397976728d99
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/method/query_method.cpp
Yechan0815/cubrid
da09d9e60b583d0b7ce5f665429f397976728d99
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2008 Search Solution Corporation * Copyright 2016 CUBRID Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * query_method.c - Method calls in queries */ #ident "$Id$" #include "query_method.hpp" #include <unordered_map> #include <vector> #include "dbtype.h" #if !defined (SERVER_MODE) #include "authenticate.h" /* AU_ENABLE, AU_DISABLE */ #include "dbi.h" /* db_enable_modification(), db_disable_modification() */ #include "object_accessor.h" /* obj_ */ #include "object_primitive.h" /* pr_is_set_type() */ #include "set_object.h" /* set_convert_oids_to_objects() */ #include "virtual_object.h" /* vid_oid_to_object() */ #include "network.h" #include "network_interface_cl.h" #include "mem_block.hpp" /* cubmem::extensible_block */ #include "method_callback.hpp" #include "method_def.hpp" /* method_sig_list, method_sig_node */ #include "method_query_handler.hpp" #include "transaction_cl.h" #include "packer.hpp" /* packing_packer */ #endif #if defined (SERVER_MODE) || defined (SA_MODE) #include "method_invoke_group.hpp" #include "method_struct_invoke.hpp" #include "thread_compat.hpp" #endif #if defined (SA_MODE) int method_Num_method_jsp_calls = 0; extern unsigned int db_on_server; #define ENTER_SERVER_IN_METHOD_CALL(save_pri_heap_id_) \ do { \ db_on_server = 1; \ private_heap_id = save_pri_heap_id_; \ } while (0) #define EXIT_SERVER_IN_METHOD_CALL(save_pri_heap_id_) \ do { \ save_pri_heap_id_ = private_heap_id; \ private_heap_id = 0; \ db_on_server = 0; \ } while (0) #endif #if !defined (SERVER_MODE) /* For builtin C Method */ static std::unordered_map <UINT64, std::vector<DB_VALUE>> runtime_args; /* data queue */ static std::queue <cubmem::extensible_block> data_queue; static void method_erase_runtime_arguments (UINT64 id); static void method_set_runtime_arguments (UINT64 id, std::vector<DB_VALUE> &args); static int method_prepare_arguments (packing_unpacker &unpacker); static int method_invoke_builtin (packing_unpacker &unpacker, DB_VALUE &result); static int method_invoke_builtin_internal (DB_VALUE &result, std::vector<DB_VALUE> &args, method_sig_node *meth_sig_p); static int method_dispatch_internal (packing_unpacker &unpacker); /* FIXME: duplicated function implementation; The following three functions are ported from the client cursor (cursor.c) */ static bool method_has_set_vobjs (DB_SET *set); static int method_fixup_set_vobjs (DB_VALUE *value_p); static int method_fixup_vobjs (DB_VALUE *value_p); #endif #if defined (CS_MODE) /* * method_dispatch () - Dispatch method protocol from the server * return: * rc(in) : enquiry return code * host(in) : host name * server_name(in) : server name * methoddata (in) : data buffer * methoddata_size (in) : data buffer size */ int method_dispatch (unsigned int rc, char *methoddata, int methoddata_size) { int error = NO_ERROR; packing_unpacker unpacker (methoddata, (size_t) methoddata_size); tran_begin_libcas_function (); int depth = tran_get_libcas_depth (); if (depth > METHOD_MAX_RECURSION_DEPTH) { er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_SP_TOO_MANY_NESTED_CALL, 0); error = ER_SP_TOO_MANY_NESTED_CALL; } if (error == NO_ERROR) { cubmethod::mcon_set_connection_info (depth - 1, rc); error = method_dispatch_internal (unpacker); } tran_end_libcas_function (); return error; } /* * method_error () - Send error code to the server * return: * rc(in) : enquiry return code * host(in) : host name * server_name(in) : server name * error_id (in) : error code */ int method_error (unsigned int rc, int error_id) { int error = NO_ERROR; tran_begin_libcas_function(); int depth = tran_get_libcas_depth (); cubmethod::mcon_set_connection_info (depth - 1, rc); error = cubmethod::mcon_send_data_to_server (METHOD_ERROR, error_id); tran_end_libcas_function(); return error; } #elif defined (SA_MODE) /* * method_dispatch () - Dispatch method protocol for SA Mode * return: * unpacker(in) : unpacker for request */ int method_dispatch (packing_unpacker &unpacker) { int error = NO_ERROR; HL_HEAPID save_pri_heap_id; EXIT_SERVER_IN_METHOD_CALL (save_pri_heap_id); ++method_Num_method_jsp_calls; tran_begin_libcas_function (); int depth = tran_get_libcas_depth (); if (depth > METHOD_MAX_RECURSION_DEPTH) { er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_SP_TOO_MANY_NESTED_CALL, 0); error = ER_SP_TOO_MANY_NESTED_CALL; } if (error == NO_ERROR) { error = method_dispatch_internal (unpacker); } tran_end_libcas_function (); --method_Num_method_jsp_calls; ENTER_SERVER_IN_METHOD_CALL (save_pri_heap_id); return error; } #endif #if !defined (SERVER_MODE) /* * method_dispatch_internal () - Dispatch method protocol from the server * return: * rc(in) : enquiry return code * host(in) : host name * server_name(in) : server name * methoddata (in) : data buffer * methoddata_size (in) : data buffer size */ int method_dispatch_internal (packing_unpacker &unpacker) { int error = NO_ERROR; int method_dispatch_code; unpacker.unpack_int (method_dispatch_code); if (error == NO_ERROR) { int save_auth = 0; switch (method_dispatch_code) { case METHOD_REQUEST_ARG_PREPARE: error = method_prepare_arguments (unpacker); break; case METHOD_REQUEST_INVOKE: AU_SAVE_AND_ENABLE (save_auth); DB_VALUE value; error = method_invoke_builtin (unpacker, value); AU_RESTORE (save_auth); break; case METHOD_REQUEST_CALLBACK: AU_SAVE_AND_ENABLE (save_auth); error = cubmethod::get_callback_handler()->callback_dispatch (unpacker); AU_RESTORE (save_auth); break; case METHOD_REQUEST_END: { uint64_t id; std::vector <int> handlers; unpacker.unpack_all (id, handlers); for (int i = 0; i < handlers.size (); i++) { cubmethod::get_callback_handler()->free_query_handle (handlers[i], false); } } break; default: assert (false); // the other callbacks are disabled now return ER_FAILED; break; } } return error; } /* * method_invoke_builtin () - Invoke C Method with runtime arguments * return: * unpacker (in) : unpacker * result (out) : result */ static int method_invoke_builtin (packing_unpacker &unpacker, DB_VALUE &result) { int error = NO_ERROR; UINT64 id; METHOD_SIG sig; unpacker.unpack_bigint (id); sig.unpack (unpacker); auto search = runtime_args.find (id); if (search != runtime_args.end()) { std::vector<DB_VALUE> &args = search->second; error = method_invoke_builtin_internal (result, args, &sig); if (error == NO_ERROR) { /* send a result value to server */ error = cubmethod::mcon_send_data_to_server (METHOD_SUCCESS, result); } } else { error = ER_GENERIC_ERROR; } sig.freemem (); return error; } /* * method_prepare_arguments () - Stores at DB_VALUE arguments (runtime_args) for C Method * return: * unpacker (in) : unpacker * conn_info (in) : enquiry return code, host name, server name */ static int method_prepare_arguments (packing_unpacker &unpacker) { UINT64 id; std::vector<DB_VALUE> arguments; unpacker.unpack_all (id, arguments); method_erase_runtime_arguments (id); method_set_runtime_arguments (id, arguments); return NO_ERROR; } /* * method_erase_runtime_arguments () - * return: void * id (in) : method_invoke_group's id */ void method_erase_runtime_arguments (UINT64 id) { auto search = runtime_args.find (id); if (search != runtime_args.end()) { std::vector<DB_VALUE> &prev_args = search->second; pr_clear_value_vector (prev_args); runtime_args.erase (search); } } /* * method_set_runtime_arguments () - * return: void * id (in) : method_invoke_group's id * args (in) : DB_VALUE arguments */ void method_set_runtime_arguments (UINT64 id, std::vector<DB_VALUE> &args) { for (DB_VALUE &v : args) { method_fixup_vobjs (&v); } runtime_args.insert ({id, args}); } /* * method_invoke_builtin_internal () - * return: int * result (out) : * args (in) : objects & arguments DB_VALUEs * meth_sig_p (in) : Method signatures */ // *INDENT-OFF* int method_invoke_builtin_internal (DB_VALUE & result, std::vector<DB_VALUE> &args, method_sig_node * meth_sig_p) // *INDENT-ON* { int error = NO_ERROR; int turn_on_auth = 1; assert (meth_sig_p != NULL); assert (meth_sig_p->method_type == METHOD_TYPE_CLASS_METHOD || meth_sig_p->method_type == METHOD_TYPE_INSTANCE_METHOD); /* The first position # is for the object ID */ int num_args = meth_sig_p->num_method_args + 1; // *INDENT-OFF* std::vector <DB_VALUE *> arg_val_p (num_args + 1, NULL); /* + 1 for C method */ // *INDENT-ON* for (int i = 0; i < num_args; ++i) { int pos = meth_sig_p->method_arg_pos[i]; arg_val_p[i] = &args[pos]; } db_make_null (&result); if (meth_sig_p->method_type == METHOD_TYPE_INSTANCE_METHOD || meth_sig_p->method_type == METHOD_TYPE_CLASS_METHOD) { /* Don't call the method if the object is NULL or it has been deleted. A method call on a NULL object is * NULL. */ if (!DB_IS_NULL (arg_val_p[0])) { error = db_is_any_class (db_get_object (arg_val_p[0])); if (error == 0) { error = db_is_instance (db_get_object (arg_val_p[0])); } } if (error == ER_HEAP_UNKNOWN_OBJECT) { error = NO_ERROR; } else if (error > 0) { /* methods must run with authorization turned on and database modifications turned off. */ turn_on_auth = 0; AU_ENABLE (turn_on_auth); db_disable_modification (); error = obj_send_array (db_get_object (arg_val_p[0]), meth_sig_p->method_name, &result, &arg_val_p[1]); db_enable_modification (); AU_DISABLE (turn_on_auth); } } else { /* java stored procedure is not handled here anymore */ assert (false); error = ER_GENERIC_ERROR; } /* error handling */ if (error != NO_ERROR) { pr_clear_value (&result); error = ER_FAILED; } else if (DB_VALUE_TYPE (&result) == DB_TYPE_ERROR) { if (er_errid () == NO_ERROR) /* caller has not set an error */ { er_set (ER_ERROR_SEVERITY, ARG_FILE_LINE, ER_GENERIC_ERROR, 1); } pr_clear_value (&result); error = ER_GENERIC_ERROR; } return error; } /* * method_has_set_vobjs () - * return: nonzero iff set has some vobjs, zero otherwise * set (in): set/sequence db_value */ static bool method_has_set_vobjs (DB_SET *set) { int i, size; DB_VALUE element; size = db_set_size (set); for (i = 0; i < size; i++) { if (db_set_get (set, i, &element) != NO_ERROR) { return false; } if (DB_VALUE_TYPE (&element) == DB_TYPE_VOBJ) { pr_clear_value (&element); return true; } pr_clear_value (&element); } return false; } /* * method_fixup_set_vobjs() - if val is a set/seq of vobjs then * turn it into a set/seq of vmops * return: NO_ERROR on all ok, ER status( or ER_FAILED) otherwise * value_p (in/out): a db_value */ static int method_fixup_set_vobjs (DB_VALUE *value_p) { DB_TYPE type; int rc, i, size; DB_VALUE element; DB_SET *set, *new_set; type = DB_VALUE_TYPE (value_p); if (!pr_is_set_type (type)) { return ER_FAILED; } set = db_get_set (value_p); size = db_set_size (set); if (method_has_set_vobjs (set) == false) { return set_convert_oids_to_objects (set); } switch (type) { case DB_TYPE_SET: new_set = db_set_create_basic (NULL, NULL); break; case DB_TYPE_MULTISET: new_set = db_set_create_multi (NULL, NULL); break; case DB_TYPE_SEQUENCE: new_set = db_seq_create (NULL, NULL, size); break; default: return ER_FAILED; } /* fixup element vobjs into vmops and add them to new */ for (i = 0; i < size; i++) { if (db_set_get (set, i, &element) != NO_ERROR) { db_set_free (new_set); return ER_FAILED; } if (method_fixup_vobjs (&element) != NO_ERROR) { db_set_free (new_set); return ER_FAILED; } if (type == DB_TYPE_SEQUENCE) { rc = db_seq_put (new_set, i, &element); } else { rc = db_set_add (new_set, &element); } if (rc != NO_ERROR) { db_set_free (new_set); return ER_FAILED; } } pr_clear_value (value_p); switch (type) { case DB_TYPE_SET: db_make_set (value_p, new_set); break; case DB_TYPE_MULTISET: db_make_multiset (value_p, new_set); break; case DB_TYPE_SEQUENCE: db_make_sequence (value_p, new_set); break; default: db_set_free (new_set); return ER_FAILED; } return NO_ERROR; } /* * method_fixup_vobjs () - * return: NO_ERROR on all ok, ER status( or ER_FAILED) otherwise * value_p (in/out): a db_value * Note: if value_p is an OID then turn it into an OBJECT type value * if value_p is a VOBJ then turn it into a vmop * if value_p is a set/seq then do same fixups on its elements */ static int method_fixup_vobjs (DB_VALUE *value_p) { DB_OBJECT *obj; int rc; switch (DB_VALUE_DOMAIN_TYPE (value_p)) { case DB_TYPE_OID: rc = vid_oid_to_object (value_p, &obj); db_make_object (value_p, obj); break; case DB_TYPE_VOBJ: if (DB_IS_NULL (value_p)) { pr_clear_value (value_p); db_value_domain_init (value_p, DB_TYPE_OBJECT, DB_DEFAULT_PRECISION, DB_DEFAULT_SCALE); rc = NO_ERROR; } else { rc = vid_vobj_to_object (value_p, &obj); pr_clear_value (value_p); db_make_object (value_p, obj); } break; case DB_TYPE_SET: case DB_TYPE_MULTISET: case DB_TYPE_SEQUENCE: // fixup any set/seq of vobjs into a set/seq of vmops rc = method_fixup_set_vobjs (value_p); value_p->need_clear = true; break; default: rc = NO_ERROR; break; } return rc; } #endif #if defined (SERVER_MODE) || defined (SA_MODE) /* * xmethod_invoke_fold_constants () - perform constant folding for method * return : error code * thread_p (in) : worker thread * sig_list(in) : method signature * args(in) : method argument */ int xmethod_invoke_fold_constants (THREAD_ENTRY *thread_p, const method_sig_list &sig_list, std::vector<std::reference_wrapper<DB_VALUE>> &args, DB_VALUE &result) { int error_code = NO_ERROR; cubmethod::method_invoke_group *method_group = cubmethod::get_rctx (thread_p)->create_invoke_group (thread_p, sig_list, false); method_group->begin (); error_code = method_group->prepare (args); if (error_code != NO_ERROR) { return error_code; } error_code = method_group->execute (args); if (error_code != NO_ERROR) { return error_code; } DB_VALUE &res = method_group->get_return_value (0); db_value_clone (&res, &result); return error_code; } #endif
24.855326
123
0.679097
[ "object", "vector" ]
f65ba204d8abba2de97efb2ca47c53c2633cb5a3
11,080
cc
C++
remoting/host/local_input_monitor_linux.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-05-03T06:33:56.000Z
2021-11-14T18:39:42.000Z
remoting/host/local_input_monitor_linux.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
remoting/host/local_input_monitor_linux.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/local_input_monitor.h" #include <sys/select.h> #include <unistd.h> #define XK_MISCELLANY #include <X11/keysymdef.h> #include "base/basictypes.h" #include "base/bind.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/location.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/message_pump_libevent.h" #include "base/posix/eintr_wrapper.h" #include "base/single_thread_task_runner.h" #include "base/threading/non_thread_safe.h" #include "remoting/host/client_session_control.h" #include "third_party/skia/include/core/SkPoint.h" // These includes need to be later than dictated by the style guide due to // Xlib header pollution, specifically the min, max, and Status macros. #include <X11/XKBlib.h> #include <X11/Xlibint.h> #include <X11/extensions/record.h> namespace remoting { namespace { class LocalInputMonitorLinux : public base::NonThreadSafe, public LocalInputMonitor { public: LocalInputMonitorLinux( scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, scoped_refptr<base::SingleThreadTaskRunner> input_task_runner, base::WeakPtr<ClientSessionControl> client_session_control); virtual ~LocalInputMonitorLinux(); private: // The actual implementation resides in LocalInputMonitorLinux::Core class. class Core : public base::RefCountedThreadSafe<Core>, public base::MessagePumpLibevent::Watcher { public: Core(scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, scoped_refptr<base::SingleThreadTaskRunner> input_task_runner, base::WeakPtr<ClientSessionControl> client_session_control); void Start(); void Stop(); private: friend class base::RefCountedThreadSafe<Core>; virtual ~Core(); void StartOnInputThread(); void StopOnInputThread(); // base::MessagePumpLibevent::Watcher interface. virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE; virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE; // Processes key and mouse events. void ProcessXEvent(xEvent* event); static void ProcessReply(XPointer self, XRecordInterceptData* data); // Task runner on which public methods of this class must be called. scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner_; // Task runner on which X Window events are received. scoped_refptr<base::SingleThreadTaskRunner> input_task_runner_; // Points to the object receiving mouse event notifications and session // disconnect requests. base::WeakPtr<ClientSessionControl> client_session_control_; // Used to receive base::MessagePumpLibevent::Watcher events. base::MessagePumpLibevent::FileDescriptorWatcher controller_; // True when Alt is pressed. bool alt_pressed_; // True when Ctrl is pressed. bool ctrl_pressed_; Display* display_; Display* x_record_display_; XRecordRange* x_record_range_[2]; XRecordContext x_record_context_; DISALLOW_COPY_AND_ASSIGN(Core); }; scoped_refptr<Core> core_; DISALLOW_COPY_AND_ASSIGN(LocalInputMonitorLinux); }; LocalInputMonitorLinux::LocalInputMonitorLinux( scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, scoped_refptr<base::SingleThreadTaskRunner> input_task_runner, base::WeakPtr<ClientSessionControl> client_session_control) : core_(new Core(caller_task_runner, input_task_runner, client_session_control)) { core_->Start(); } LocalInputMonitorLinux::~LocalInputMonitorLinux() { core_->Stop(); } LocalInputMonitorLinux::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, scoped_refptr<base::SingleThreadTaskRunner> input_task_runner, base::WeakPtr<ClientSessionControl> client_session_control) : caller_task_runner_(caller_task_runner), input_task_runner_(input_task_runner), client_session_control_(client_session_control), alt_pressed_(false), ctrl_pressed_(false), display_(NULL), x_record_display_(NULL), x_record_context_(0) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); DCHECK(client_session_control_.get()); x_record_range_[0] = NULL; x_record_range_[1] = NULL; } void LocalInputMonitorLinux::Core::Start() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); input_task_runner_->PostTask(FROM_HERE, base::Bind(&Core::StartOnInputThread, this)); } void LocalInputMonitorLinux::Core::Stop() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); input_task_runner_->PostTask(FROM_HERE, base::Bind(&Core::StopOnInputThread, this)); } LocalInputMonitorLinux::Core::~Core() { DCHECK(!display_); DCHECK(!x_record_display_); DCHECK(!x_record_range_[0]); DCHECK(!x_record_range_[1]); DCHECK(!x_record_context_); } void LocalInputMonitorLinux::Core::StartOnInputThread() { DCHECK(input_task_runner_->BelongsToCurrentThread()); DCHECK(!display_); DCHECK(!x_record_display_); DCHECK(!x_record_range_[0]); DCHECK(!x_record_range_[1]); DCHECK(!x_record_context_); // TODO(jamiewalch): We should pass the display in. At that point, since // XRecord needs a private connection to the X Server for its data channel // and both channels are used from a separate thread, we'll need to duplicate // them with something like the following: // XOpenDisplay(DisplayString(display)); display_ = XOpenDisplay(NULL); x_record_display_ = XOpenDisplay(NULL); if (!display_ || !x_record_display_) { LOG(ERROR) << "Couldn't open X display"; return; } int xr_opcode, xr_event, xr_error; if (!XQueryExtension(display_, "RECORD", &xr_opcode, &xr_event, &xr_error)) { LOG(ERROR) << "X Record extension not available."; return; } x_record_range_[0] = XRecordAllocRange(); x_record_range_[1] = XRecordAllocRange(); if (!x_record_range_[0] || !x_record_range_[1]) { LOG(ERROR) << "XRecordAllocRange failed."; return; } x_record_range_[0]->device_events.first = MotionNotify; x_record_range_[0]->device_events.last = MotionNotify; x_record_range_[1]->device_events.first = KeyPress; x_record_range_[1]->device_events.last = KeyRelease; XRecordClientSpec client_spec = XRecordAllClients; x_record_context_ = XRecordCreateContext( x_record_display_, 0, &client_spec, 1, x_record_range_, arraysize(x_record_range_)); if (!x_record_context_) { LOG(ERROR) << "XRecordCreateContext failed."; return; } if (!XRecordEnableContextAsync(x_record_display_, x_record_context_, &Core::ProcessReply, reinterpret_cast<XPointer>(this))) { LOG(ERROR) << "XRecordEnableContextAsync failed."; return; } // Register OnFileCanReadWithoutBlocking() to be called every time there is // something to read from |x_record_display_|. base::MessageLoopForIO* message_loop = base::MessageLoopForIO::current(); int result = message_loop->WatchFileDescriptor(ConnectionNumber(x_record_display_), true, base::MessageLoopForIO::WATCH_READ, &controller_, this); if (!result) { LOG(ERROR) << "Failed to create X record task."; return; } // Fetch pending events if any. while (XPending(x_record_display_)) { XEvent ev; XNextEvent(x_record_display_, &ev); } } void LocalInputMonitorLinux::Core::StopOnInputThread() { DCHECK(input_task_runner_->BelongsToCurrentThread()); // Context must be disabled via the control channel because we can't send // any X protocol traffic over the data channel while it's recording. if (x_record_context_) { XRecordDisableContext(display_, x_record_context_); XFlush(display_); } controller_.StopWatchingFileDescriptor(); if (x_record_range_[0]) { XFree(x_record_range_[0]); x_record_range_[0] = NULL; } if (x_record_range_[1]) { XFree(x_record_range_[1]); x_record_range_[1] = NULL; } if (x_record_context_) { XRecordFreeContext(x_record_display_, x_record_context_); x_record_context_ = 0; } if (x_record_display_) { XCloseDisplay(x_record_display_); x_record_display_ = NULL; } if (display_) { XCloseDisplay(display_); display_ = NULL; } } void LocalInputMonitorLinux::Core::OnFileCanReadWithoutBlocking(int fd) { DCHECK(input_task_runner_->BelongsToCurrentThread()); // Fetch pending events if any. while (XPending(x_record_display_)) { XEvent ev; XNextEvent(x_record_display_, &ev); } } void LocalInputMonitorLinux::Core::OnFileCanWriteWithoutBlocking(int fd) { NOTREACHED(); } void LocalInputMonitorLinux::Core::ProcessXEvent(xEvent* event) { DCHECK(input_task_runner_->BelongsToCurrentThread()); if (event->u.u.type == MotionNotify) { SkIPoint position(SkIPoint::Make(event->u.keyButtonPointer.rootX, event->u.keyButtonPointer.rootY)); caller_task_runner_->PostTask( FROM_HERE, base::Bind(&ClientSessionControl::OnLocalMouseMoved, client_session_control_, position)); } else { int key_code = event->u.u.detail; bool down = event->u.u.type == KeyPress; KeySym key_sym = XkbKeycodeToKeysym(display_, key_code, 0, 0); if (key_sym == XK_Control_L || key_sym == XK_Control_R) { ctrl_pressed_ = down; } else if (key_sym == XK_Alt_L || key_sym == XK_Alt_R) { alt_pressed_ = down; } else if (key_sym == XK_Escape && down && alt_pressed_ && ctrl_pressed_) { caller_task_runner_->PostTask( FROM_HERE, base::Bind(&ClientSessionControl::DisconnectSession, client_session_control_)); } } } // static void LocalInputMonitorLinux::Core::ProcessReply(XPointer self, XRecordInterceptData* data) { if (data->category == XRecordFromServer) { xEvent* event = reinterpret_cast<xEvent*>(data->data); reinterpret_cast<Core*>(self)->ProcessXEvent(event); } XRecordFreeData(data); } } // namespace scoped_ptr<LocalInputMonitor> LocalInputMonitor::Create( scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, scoped_refptr<base::SingleThreadTaskRunner> input_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, base::WeakPtr<ClientSessionControl> client_session_control) { return scoped_ptr<LocalInputMonitor>( new LocalInputMonitorLinux(caller_task_runner, input_task_runner, client_session_control)); } } // namespace remoting
33.273273
79
0.704061
[ "object" ]
f65dc24f4884b5e6c075474df89ea284953acc15
132,204
cpp
C++
gdal/frmts/ecw/ecwdataset.cpp
HongqiangWei/gdal
f7c427926438cc39d31e4459fa6401321f8e62f0
[ "MIT" ]
null
null
null
gdal/frmts/ecw/ecwdataset.cpp
HongqiangWei/gdal
f7c427926438cc39d31e4459fa6401321f8e62f0
[ "MIT" ]
null
null
null
gdal/frmts/ecw/ecwdataset.cpp
HongqiangWei/gdal
f7c427926438cc39d31e4459fa6401321f8e62f0
[ "MIT" ]
null
null
null
/****************************************************************************** * $Id$ * * Project: GDAL * Purpose: ECW (ERDAS Wavelet Compression Format) Driver * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2001, Frank Warmerdam <warmerdam@pobox.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gdal_ecw.h" #include "cpl_minixml.h" #include "ogr_spatialref.h" #include "ogr_api.h" #include "ogr_geometry.h" CPL_CVSID("$Id$"); #undef NOISY_DEBUG #ifdef FRMT_ecw static const unsigned char jpc_header[] = {0xff,0x4f}; static const unsigned char jp2_header[] = {0x00,0x00,0x00,0x0c,0x6a,0x50,0x20,0x20,0x0d,0x0a,0x87,0x0a}; static void *hECWDatasetMutex = NULL; static int bNCSInitialized = FALSE; void ECWInitialize( void ); extern "C" int CPL_DLL GDALIsInGlobalDestructor(void); #define BLOCK_SIZE 256 GDALDataset* ECWDatasetOpenJPEG2000(GDALOpenInfo* poOpenInfo); /************************************************************************/ /* ECWReportError() */ /************************************************************************/ void ECWReportError(CNCSError& oErr, const char* pszMsg) { #if ECWSDK_VERSION<50 char* pszErrorMessage = oErr.GetErrorMessage(); CPLError( CE_Failure, CPLE_AppDefined, "%s%s", pszMsg, pszErrorMessage ); NCSFree(pszErrorMessage); #else CPLError( CE_Failure, CPLE_AppDefined, "%s%s", pszMsg, NCSGetLastErrorText(oErr) ); #endif } /************************************************************************/ /* ECWRasterBand() */ /************************************************************************/ ECWRasterBand::ECWRasterBand( ECWDataset *poDS, int nBand, int iOverview ) { this->poDS = poDS; poGDS = poDS; this->iOverview = iOverview; this->nBand = nBand; eDataType = poDS->eRasterDataType; nRasterXSize = poDS->GetRasterXSize() / ( 1 << (iOverview+1)); nRasterYSize = poDS->GetRasterYSize() / ( 1 << (iOverview+1)); nBlockXSize = BLOCK_SIZE; nBlockYSize = BLOCK_SIZE; /* -------------------------------------------------------------------- */ /* Work out band color interpretation. */ /* -------------------------------------------------------------------- */ if( poDS->psFileInfo->eColorSpace == NCSCS_NONE ) eBandInterp = GCI_Undefined; else if( poDS->psFileInfo->eColorSpace == NCSCS_GREYSCALE ) { eBandInterp = GCI_GrayIndex; //we could also have alpha band. if ( strcmp(poDS->psFileInfo->pBands[nBand-1].szDesc, NCS_BANDDESC_AllOpacity) == 0 || strcmp(poDS->psFileInfo->pBands[nBand-1].szDesc, NCS_BANDDESC_GreyscaleOpacity) ==0 ){ eBandInterp = GCI_AlphaBand; } }else if (poDS->psFileInfo->eColorSpace == NCSCS_MULTIBAND ){ eBandInterp = ECWGetColorInterpretationByName(poDS->psFileInfo->pBands[nBand-1].szDesc); }else if (poDS->psFileInfo->eColorSpace == NCSCS_sRGB){ if( nBand == 1 ) eBandInterp = GCI_RedBand; else if( nBand == 2 ) eBandInterp = GCI_GreenBand; else if( nBand == 3 ) eBandInterp = GCI_BlueBand; else if (nBand == 4 ) { if (strcmp(poDS->psFileInfo->pBands[nBand-1].szDesc, NCS_BANDDESC_AllOpacity) == 0) eBandInterp = GCI_AlphaBand; else eBandInterp = GCI_Undefined; } else { eBandInterp = GCI_Undefined; } } else if( poDS->psFileInfo->eColorSpace == NCSCS_YCbCr ) { if( CSLTestBoolean( CPLGetConfigOption("CONVERT_YCBCR_TO_RGB","YES") )) { if( nBand == 1 ) eBandInterp = GCI_RedBand; else if( nBand == 2 ) eBandInterp = GCI_GreenBand; else if( nBand == 3 ) eBandInterp = GCI_BlueBand; else eBandInterp = GCI_Undefined; } else { if( nBand == 1 ) eBandInterp = GCI_YCbCr_YBand; else if( nBand == 2 ) eBandInterp = GCI_YCbCr_CbBand; else if( nBand == 3 ) eBandInterp = GCI_YCbCr_CrBand; else eBandInterp = GCI_Undefined; } } else eBandInterp = GCI_Undefined; /* -------------------------------------------------------------------- */ /* If this is the base level, create a set of overviews. */ /* -------------------------------------------------------------------- */ if( iOverview == -1 ) { int i; for( i = 0; nRasterXSize / (1 << (i+1)) > 128 && nRasterYSize / (1 << (i+1)) > 128; i++ ) { apoOverviews.push_back( new ECWRasterBand( poDS, nBand, i ) ); } } bPromoteTo8Bit = poDS->psFileInfo->nBands == 4 && nBand == 4 && poDS->psFileInfo->pBands[0].nBits == 8 && poDS->psFileInfo->pBands[1].nBits == 8 && poDS->psFileInfo->pBands[2].nBits == 8 && poDS->psFileInfo->pBands[3].nBits == 1 && eBandInterp == GCI_AlphaBand && CSLTestBoolean(CPLGetConfigOption("GDAL_ECW_PROMOTE_1BIT_ALPHA_AS_8BIT", "YES")); if( bPromoteTo8Bit ) CPLDebug("ECW", "Fourth (alpha) band is promoted from 1 bit to 8 bit"); if( (poDS->psFileInfo->pBands[nBand-1].nBits % 8) != 0 && !bPromoteTo8Bit ) SetMetadataItem("NBITS", CPLString().Printf("%d",poDS->psFileInfo->pBands[nBand-1].nBits), "IMAGE_STRUCTURE" ); SetDescription(poDS->psFileInfo->pBands[nBand-1].szDesc); } /************************************************************************/ /* ~ECWRasterBand() */ /************************************************************************/ ECWRasterBand::~ECWRasterBand() { FlushCache(); while( apoOverviews.size() > 0 ) { delete apoOverviews.back(); apoOverviews.pop_back(); } } /************************************************************************/ /* GetOverview() */ /************************************************************************/ GDALRasterBand *ECWRasterBand::GetOverview( int iOverview ) { if( iOverview >= 0 && iOverview < (int) apoOverviews.size() ) return apoOverviews[iOverview]; else return NULL; } /************************************************************************/ /* GetColorInterpretation() */ /************************************************************************/ GDALColorInterp ECWRasterBand::GetColorInterpretation() { return eBandInterp; } /************************************************************************/ /* SetColorInterpretation() */ /* */ /* This would normally just be used by folks using the ECW code */ /* to read JP2 streams in other formats (such as NITF) and */ /* providing their own color interpretation regardless of what */ /* ECW might think the stream itself says. */ /************************************************************************/ CPLErr ECWRasterBand::SetColorInterpretation( GDALColorInterp eNewInterp ) { eBandInterp = eNewInterp; return CE_None; } /************************************************************************/ /* AdviseRead() */ /************************************************************************/ CPLErr ECWRasterBand::AdviseRead( int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eDT, char **papszOptions ) { int nResFactor = 1 << (iOverview+1); return poGDS->AdviseRead( nXOff * nResFactor, nYOff * nResFactor, nXSize * nResFactor, nYSize * nResFactor, nBufXSize, nBufYSize, eDT, 1, &nBand, papszOptions ); } //statistics support: #if ECWSDK_VERSION >= 50 /************************************************************************/ /* GetDefaultHistogram() */ /************************************************************************/ CPLErr ECWRasterBand::GetDefaultHistogram( double *pdfMin, double *pdfMax, int *pnBuckets, int ** ppanHistogram, int bForce, GDALProgressFunc f, void *pProgressData) { int bForceCoalesced = bForce; // If file version is smaller than 3, there will be no statistics in the file. But if it is version 3 or higher we don't want underlying implementation to compute histogram // so we set bForceCoalesced to FALSE. if (poGDS->psFileInfo->nFormatVersion >= 3){ bForceCoalesced = FALSE; } // We check if we have PAM histogram. If we have them we return them. This will allow to override statistics stored in the file. CPLErr pamError = GDALPamRasterBand::GetDefaultHistogram(pdfMin, pdfMax, pnBuckets, ppanHistogram, bForceCoalesced, f, pProgressData); if ( pamError == CE_None || poGDS->psFileInfo->nFormatVersion<3 || eBandInterp == GCI_AlphaBand){ return pamError; } NCS::CError error = poGDS->StatisticsEnsureInitialized(); if (!error.Success()){ CPLError( CE_Warning, CPLE_AppDefined, "ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::GetDefaultHistogram. " ); return CE_Failure; } GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount); bool bHistogramFromFile = false; if ( poGDS->pStatistics != NULL ){ NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex]; if ( bandStats.Histogram != NULL && bandStats.nHistBucketCount > 0 ){ *pnBuckets = bandStats.nHistBucketCount; *ppanHistogram = (int *)VSIMalloc(bandStats.nHistBucketCount *sizeof(int)); for (size_t i = 0; i < bandStats.nHistBucketCount; i++){ (*ppanHistogram)[i] = (int) bandStats.Histogram[i]; } //JTO: this is not perfect as You can't tell who wrote the histogram !!! //It will offset it unnecesarilly for files with hists not modified by GDAL. double dfHalfBucket = (bandStats.fMaxHist - bandStats.fMinHist) / (2 * (*pnBuckets - 1)); if ( pdfMin != NULL ){ *pdfMin = bandStats.fMinHist - dfHalfBucket; } if ( pdfMax != NULL ){ *pdfMax = bandStats.fMaxHist + dfHalfBucket; } bHistogramFromFile = true; }else{ bHistogramFromFile = false; } }else{ bHistogramFromFile = false; } if (!bHistogramFromFile ){ if (bForce == TRUE){ //compute. Save. pamError = GDALPamRasterBand::GetDefaultHistogram(pdfMin, pdfMax, pnBuckets, ppanHistogram, TRUE, f,pProgressData); if (pamError == CE_None){ CPLErr error = SetDefaultHistogram(*pdfMin, *pdfMax, *pnBuckets, *ppanHistogram); if (error != CE_None){ //Histogram is there but we failed to save it back to file. CPLError (CE_Warning, CPLE_AppDefined, "SetDefaultHistogram failed in ECWRasterBand::GetDefaultHistogram. Histogram might not be saved in .ecw file." ); } return CE_None; }else{ //Something went wrong during histogram computation. return pamError; } }else{ //No histogram, no forced computation. return CE_Warning; } }else { //Statistics were already there and were used. return CE_None; } } /************************************************************************/ /* SetDefaultHistogram() */ /************************************************************************/ CPLErr ECWRasterBand::SetDefaultHistogram( double dfMin, double dfMax, int nBuckets, int *panHistogram ) { //Only version 3 supports saving statistics. if (poGDS->psFileInfo->nFormatVersion < 3 || eBandInterp == GCI_AlphaBand){ return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram); } //determine if there are statistics in PAM file. double dummy; int dummy_i; int *dummy_histogram; bool hasPAMDefaultHistogram = GDALPamRasterBand::GetDefaultHistogram(&dummy, &dummy, &dummy_i, &dummy_histogram, FALSE, NULL, NULL) == CE_None; if (hasPAMDefaultHistogram){ VSIFree(dummy_histogram); } //ECW SDK ignores statistics for opacity bands. So we need to compute number of bands without opacity. GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount); UINT32 bucketCounts[256]; std::fill_n(bucketCounts, nStatsBandCount, 0); bucketCounts[nStatsBandIndex] = nBuckets; NCS::CError error = poGDS->StatisticsEnsureInitialized(); if (!error.Success()){ CPLError( CE_Warning, CPLE_AppDefined, "ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::SetDefaultHistogram. Default histogram will be written to PAM. " ); return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram); } NCSFileStatistics *pStatistics = poGDS->pStatistics; if (pStatistics == NULL){ error = NCSEcwInitStatistics(&pStatistics, nStatsBandCount, bucketCounts); poGDS->bStatisticsDirty = TRUE; poGDS->pStatistics = pStatistics; if (!error.Success()){ CPLError( CE_Warning, CPLE_AppDefined, "NCSEcwInitStatistics failed in ECWRasterBand::SetDefaultHistogram." ); return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram); } //no error statistics properly initialized but there were no statistics previously. }else{ //is there a room for our band already? //This should account for following cases: //1. Existing histogram (for this or different band) has smaller bucket count. //2. There is no existing histogram but statistics are set for one or more bands (pStatistics->nHistBucketCounts is zero). if ((int)pStatistics->BandsStats[nStatsBandIndex].nHistBucketCount != nBuckets){ //no. There is no room. We need more! NCSFileStatistics *pNewStatistics = NULL; for (size_t i=0;i<pStatistics->nNumberOfBands;i++){ bucketCounts[i] = pStatistics->BandsStats[i].nHistBucketCount; } bucketCounts[nStatsBandIndex] = nBuckets; if (nBuckets < (int)pStatistics->BandsStats[nStatsBandIndex].nHistBucketCount){ pStatistics->BandsStats[nStatsBandIndex].nHistBucketCount = nBuckets; } error = NCSEcwInitStatistics(&pNewStatistics, nStatsBandCount, bucketCounts); if (!error.Success()){ CPLError( CE_Warning, CPLE_AppDefined, "NCSEcwInitStatistics failed in ECWRasterBand::SetDefaultHistogram (realocate)." ); return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram); } //we need to copy existing statistics. error = NCSEcwCopyStatistics(&pNewStatistics, pStatistics); if (!error.Success()){ CPLError( CE_Warning, CPLE_AppDefined, "NCSEcwCopyStatistics failed in ECWRasterBand::SetDefaultHistogram." ); NCSEcwFreeStatistics(pNewStatistics); return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram); } pNewStatistics->nNumberOfBands = nStatsBandCount; NCSEcwFreeStatistics(pStatistics); pStatistics = pNewStatistics; poGDS->pStatistics = pStatistics; poGDS->bStatisticsDirty = TRUE; } } //at this point we have allocated statistics structure. double dfHalfBucket = (dfMax - dfMin) / (2 * nBuckets); pStatistics->BandsStats[nStatsBandIndex].fMinHist = (IEEE4) (dfMin + dfHalfBucket); pStatistics->BandsStats[nStatsBandIndex].fMaxHist = (IEEE4) (dfMax - dfHalfBucket); for (int i=0;i<nBuckets;i++){ pStatistics->BandsStats[nStatsBandIndex].Histogram[i] = (UINT64)panHistogram[i]; } if (hasPAMDefaultHistogram){ CPLError( CE_Debug, CPLE_AppDefined, "PAM default histogram will be overwritten." ); return GDALPamRasterBand::SetDefaultHistogram(dfMin, dfMax, nBuckets, panHistogram); } return CE_None; } /************************************************************************/ /* GetBandIndexAndCountForStatistics() */ /************************************************************************/ void ECWRasterBand::GetBandIndexAndCountForStatistics(int &bandIndex, int &bandCount){ bandIndex = nBand-1; bandCount = poGDS->nBands; for (int i=0;i<poGDS->nBands;i++){ if (poDS->GetRasterBand(i+1)->GetColorInterpretation() == GCI_AlphaBand){ bandCount--; if ( i < nBand-1 ){ bandIndex--; } } } } /************************************************************************/ /* GetMinimum() */ /************************************************************************/ double ECWRasterBand::GetMinimum(int* pbSuccess) { if( poGDS->psFileInfo->nFormatVersion >= 3 ) { NCS::CError error = poGDS->StatisticsEnsureInitialized(); if ( error.Success() ) { GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount); if ( poGDS->pStatistics != NULL ) { NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex]; if ( bandStats.fMinVal == bandStats.fMinVal ) { if( pbSuccess ) *pbSuccess = TRUE; return bandStats.fMinVal; } } } } return GDALPamRasterBand::GetMinimum(pbSuccess); } /************************************************************************/ /* GetMaximum() */ /************************************************************************/ double ECWRasterBand::GetMaximum(int* pbSuccess) { if( poGDS->psFileInfo->nFormatVersion >= 3 ) { NCS::CError error = poGDS->StatisticsEnsureInitialized(); if ( error.Success() ) { GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount); if ( poGDS->pStatistics != NULL ) { NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex]; if ( bandStats.fMaxVal == bandStats.fMaxVal ) { if( pbSuccess ) *pbSuccess = TRUE; return bandStats.fMaxVal; } } } } return GDALPamRasterBand::GetMaximum(pbSuccess); } /************************************************************************/ /* GetStatistics() */ /************************************************************************/ CPLErr ECWRasterBand::GetStatistics( int bApproxOK, int bForce, double *pdfMin, double *pdfMax, double *pdfMean, double *padfStdDev ) { int bForceCoalesced = bForce; // If file version is smaller than 3, there will be no statistics in the file. But if it is version 3 or higher we don't want underlying implementation to compute histogram // so we set bForceCoalesced to FALSE. if (poGDS->psFileInfo->nFormatVersion >= 3){ bForceCoalesced = FALSE; } // We check if we have PAM histogram. If we have them we return them. This will allow to override statistics stored in the file. CPLErr pamError = GDALPamRasterBand::GetStatistics(bApproxOK, bForceCoalesced, pdfMin, pdfMax, pdfMean, padfStdDev); if ( pamError == CE_None || poGDS->psFileInfo->nFormatVersion<3 || eBandInterp == GCI_AlphaBand){ return pamError; } NCS::CError error = poGDS->StatisticsEnsureInitialized(); if (!error.Success()){ CPLError( CE_Failure, CPLE_AppDefined, "ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::GetStatistic. " ); return CE_Failure; } GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount); bool bStatisticsFromFile = false; if ( poGDS->pStatistics != NULL ) { bStatisticsFromFile = true; NCSBandStats& bandStats = poGDS->pStatistics->BandsStats[nStatsBandIndex]; if ( pdfMin != NULL && bandStats.fMinVal == bandStats.fMinVal){ *pdfMin = bandStats.fMinVal; }else{ bStatisticsFromFile = false; } if ( pdfMax != NULL && bandStats.fMaxVal == bandStats.fMaxVal){ *pdfMax = bandStats.fMaxVal; }else{ bStatisticsFromFile = false; } if ( pdfMean != NULL && bandStats.fMeanVal == bandStats.fMeanVal){ *pdfMean = bandStats.fMeanVal; }else{ bStatisticsFromFile = false; } if ( padfStdDev != NULL && bandStats.fStandardDev == bandStats.fStandardDev){ *padfStdDev = bandStats.fStandardDev; }else{ bStatisticsFromFile = false; } if (bStatisticsFromFile) return CE_None; } //no required statistics. if (!bStatisticsFromFile && bForce == TRUE){ double dfMin, dfMax, dfMean,dfStdDev; pamError = GDALPamRasterBand::GetStatistics(bApproxOK, TRUE, &dfMin, &dfMax, &dfMean, &dfStdDev); if (pdfMin!=NULL) { *pdfMin = dfMin; } if (pdfMax !=NULL){ *pdfMax = dfMax; } if (pdfMean !=NULL){ *pdfMean = dfMean; } if (padfStdDev!=NULL){ *padfStdDev = dfStdDev; } if ( pamError == CE_None){ CPLErr err = SetStatistics(dfMin,dfMax,dfMean,dfStdDev); if (err !=CE_None){ CPLError (CE_Warning, CPLE_AppDefined, "SetStatistics failed in ECWRasterBand::GetDefaultHistogram. Statistics might not be saved in .ecw file." ); } return CE_None; }else{ //whatever happened we return. return pamError; } }else{ //no statistics and we are not forced to return. return CE_Warning; } } /************************************************************************/ /* SetStatistics() */ /************************************************************************/ CPLErr ECWRasterBand::SetStatistics( double dfMin, double dfMax, double dfMean, double dfStdDev ){ if (poGDS->psFileInfo->nFormatVersion < 3 || eBandInterp == GCI_AlphaBand){ return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev); } double dummy; bool hasPAMStatistics = GDALPamRasterBand::GetStatistics(TRUE, FALSE, &dummy, &dummy, &dummy, &dummy) == CE_None; NCS::CError error = poGDS->StatisticsEnsureInitialized(); if (!error.Success()){ CPLError( CE_Warning, CPLE_AppDefined, "ECWRDataset::StatisticsEnsureInitialized failed in ECWRasterBand::SetStatistic. Statistics will be written to PAM. " ); return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev); } GetBandIndexAndCountForStatistics(nStatsBandIndex, nStatsBandCount); if (poGDS->pStatistics == NULL){ error = NCSEcwInitStatistics(&poGDS->pStatistics, nStatsBandCount, NULL); if (!error.Success()){ CPLError( CE_Warning, CPLE_AppDefined, "NCSEcwInitStatistics failed in ECWRasterBand::SetStatistic. Statistics will be written to PAM." ); return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev); } } poGDS->pStatistics->BandsStats[nStatsBandIndex].fMinVal = (IEEE4) dfMin; poGDS->pStatistics->BandsStats[nStatsBandIndex].fMaxVal = (IEEE4)dfMax; poGDS->pStatistics->BandsStats[nStatsBandIndex].fMeanVal = (IEEE4)dfMean; poGDS->pStatistics->BandsStats[nStatsBandIndex].fStandardDev = (IEEE4)dfStdDev; poGDS->bStatisticsDirty = TRUE; //if we have PAM statistics we need to save them as well. Better option would be to remove them from PAM file but I don't know how to do that without messing in PAM internals. if ( hasPAMStatistics ){ CPLError( CE_Debug, CPLE_AppDefined, "PAM statistics will be overwritten." ); return GDALPamRasterBand::SetStatistics(dfMin, dfMax, dfMean, dfStdDev); } return CE_None; } #endif //#if !defined(SDK_CAN_DO_SUPERSAMPLING) /************************************************************************/ /* OldIRasterIO() */ /************************************************************************/ /* This implementation of IRasterIO(), derived from the one of GDAL 1.9 */ /* and older versions, is meant at making over-sampling */ /* work with ECW SDK 3.3. Newer versions of the SDK can do super-sampling in their */ /* SetView() call. */ CPLErr ECWRasterBand::OldIRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { int iBand, bDirect; GByte *pabyWorkBuffer = NULL; int nResFactor = 1 << (iOverview+1); nXOff *= nResFactor; nYOff *= nResFactor; nXSize *= nResFactor; nYSize *= nResFactor; /* -------------------------------------------------------------------- */ /* Try to do it based on existing "advised" access. */ /* -------------------------------------------------------------------- */ if( poGDS->TryWinRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, (GByte *) pData, nBufXSize, nBufYSize, eBufType, 1, &nBand, nPixelSpace, nLineSpace, 0 ) ) return CE_None; /* -------------------------------------------------------------------- */ /* The ECW SDK doesn't supersample, so adjust for this case. */ /* -------------------------------------------------------------------- */ int nNewXSize = nBufXSize, nNewYSize = nBufYSize; if ( nXSize < nBufXSize ) nNewXSize = nXSize; if ( nYSize < nBufYSize ) nNewYSize = nYSize; /* -------------------------------------------------------------------- */ /* Can we perform direct loads, or must we load into a working */ /* buffer, and transform? */ /* -------------------------------------------------------------------- */ int nRawPixelSize = GDALGetDataTypeSize(poGDS->eRasterDataType) / 8; bDirect = nPixelSpace == 1 && eBufType == GDT_Byte && nNewXSize == nBufXSize && nNewYSize == nBufYSize; if( !bDirect ) pabyWorkBuffer = (GByte *) CPLMalloc(nNewXSize * nRawPixelSize); /* -------------------------------------------------------------------- */ /* Establish access at the desired resolution. */ /* -------------------------------------------------------------------- */ CNCSError oErr; poGDS->CleanupWindow(); iBand = nBand-1; poGDS->nBandIndexToPromoteTo8Bit = ( bPromoteTo8Bit ) ? 0 : -1; oErr = poGDS->poFileView->SetView( 1, (unsigned int *) (&iBand), nXOff, nYOff, nXOff + nXSize - 1, nYOff + nYSize - 1, nNewXSize, nNewYSize ); if( oErr.GetErrorNumber() != NCS_SUCCESS ) { CPLFree( pabyWorkBuffer ); ECWReportError(oErr); return CE_Failure; } /* -------------------------------------------------------------------- */ /* Read back one scanline at a time, till request is satisfied. */ /* Supersampling is not supported by the ECW API, so we will do */ /* it ourselves. */ /* -------------------------------------------------------------------- */ double dfSrcYInc = (double)nNewYSize / nBufYSize; double dfSrcXInc = (double)nNewXSize / nBufXSize; int iSrcLine, iDstLine; for( iSrcLine = 0, iDstLine = 0; iDstLine < nBufYSize; iDstLine++ ) { NCSEcwReadStatus eRStatus; int iDstLineOff = iDstLine * nLineSpace; unsigned char *pabySrcBuf; if( bDirect ) pabySrcBuf = ((GByte *)pData) + iDstLineOff; else pabySrcBuf = pabyWorkBuffer; if ( nNewYSize == nBufYSize || iSrcLine == (int)(iDstLine * dfSrcYInc) ) { eRStatus = poGDS->poFileView->ReadLineBIL( poGDS->eNCSRequestDataType, 1, (void **) &pabySrcBuf ); if( eRStatus != NCSECW_READ_OK ) { CPLFree( pabyWorkBuffer ); CPLDebug( "ECW", "ReadLineBIL status=%d", (int) eRStatus ); CPLError( CE_Failure, CPLE_AppDefined, "NCScbmReadViewLineBIL failed." ); return CE_Failure; } if( bPromoteTo8Bit ) { for ( int iX = 0; iX < nNewXSize; iX++ ) { pabySrcBuf[iX] *= 255; } } if( !bDirect ) { if ( nNewXSize == nBufXSize ) { GDALCopyWords( pabyWorkBuffer, poGDS->eRasterDataType, nRawPixelSize, ((GByte *)pData) + iDstLine * nLineSpace, eBufType, nPixelSpace, nBufXSize ); } else { int iPixel; for ( iPixel = 0; iPixel < nBufXSize; iPixel++ ) { GDALCopyWords( pabyWorkBuffer + nRawPixelSize*((int)(iPixel*dfSrcXInc)), poGDS->eRasterDataType, nRawPixelSize, (GByte *)pData + iDstLineOff + iPixel * nPixelSpace, eBufType, nPixelSpace, 1 ); } } } iSrcLine++; } else { // Just copy the previous line in this case GDALCopyWords( (GByte *)pData + (iDstLineOff - nLineSpace), eBufType, nPixelSpace, (GByte *)pData + iDstLineOff, eBufType, nPixelSpace, nBufXSize ); } } CPLFree( pabyWorkBuffer ); return CE_None; } //#endif !defined(SDK_CAN_DO_SUPERSAMPLING) /************************************************************************/ /* IRasterIO() */ /************************************************************************/ CPLErr ECWRasterBand::IRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nPixelSpace, int nLineSpace ) { if( eRWFlag == GF_Write ) return CE_Failure; /* -------------------------------------------------------------------- */ /* Default line and pixel spacing if needed. */ /* -------------------------------------------------------------------- */ if ( nPixelSpace == 0 ) nPixelSpace = GDALGetDataTypeSize( eBufType ) / 8; if ( nLineSpace == 0 ) nLineSpace = nPixelSpace * nBufXSize; CPLDebug( "ECWRasterBand", "RasterIO(nBand=%d,iOverview=%d,nXOff=%d,nYOff=%d,nXSize=%d,nYSize=%d -> %dx%d)", nBand, iOverview, nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize ); #if !defined(SDK_CAN_DO_SUPERSAMPLING) if( poGDS->bUseOldBandRasterIOImplementation ) { return OldIRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nPixelSpace, nLineSpace ); } #endif int nResFactor = 1 << (iOverview+1); return poGDS->IRasterIO(eRWFlag, nXOff * nResFactor, nYOff * nResFactor, (nXSize == nRasterXSize) ? poGDS->nRasterXSize : nXSize * nResFactor, (nYSize == nRasterYSize) ? poGDS->nRasterYSize : nYSize * nResFactor, pData, nBufXSize, nBufYSize, eBufType, 1, &nBand, nPixelSpace, nLineSpace, nLineSpace*nBufYSize); } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr ECWRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage ) { int nXOff = nBlockXOff * nBlockXSize, nYOff = nBlockYOff * nBlockYSize, nXSize = nBlockXSize, nYSize = nBlockYSize; if( nXOff + nXSize > nRasterXSize ) nXSize = nRasterXSize - nXOff; if( nYOff + nYSize > nRasterYSize ) nYSize = nRasterYSize - nYOff; int nPixelSpace = GDALGetDataTypeSize(eDataType) / 8; int nLineSpace = nPixelSpace * nBlockXSize; return IRasterIO( GF_Read, nXOff, nYOff, nXSize, nYSize, pImage, nXSize, nYSize, eDataType, nPixelSpace, nLineSpace ); } /************************************************************************/ /* ==================================================================== */ /* ECWDataset */ /* ==================================================================== */ /************************************************************************/ /************************************************************************/ /* ECWDataset() */ /************************************************************************/ ECWDataset::ECWDataset(int bIsJPEG2000) { this->bIsJPEG2000 = bIsJPEG2000; bUsingCustomStream = FALSE; pszProjection = NULL; poFileView = NULL; bWinActive = FALSE; panWinBandList = NULL; eRasterDataType = GDT_Byte; nGCPCount = 0; pasGCPList = NULL; papszGMLMetadata = NULL; bGeoTransformValid = FALSE; adfGeoTransform[0] = 0.0; adfGeoTransform[1] = 1.0; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = 0.0; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = 1.0; bHdrDirty = FALSE; bGeoTransformChanged = FALSE; bProjectionChanged = FALSE; bProjCodeChanged = FALSE; bDatumCodeChanged = FALSE; bUnitsCodeChanged = FALSE; bUseOldBandRasterIOImplementation = FALSE; #if ECWSDK_VERSION>=50 pStatistics = NULL; bStatisticsDirty = FALSE; bStatisticsInitialized = FALSE; bFileMetaDataDirty = FALSE; #endif sCachedMultiBandIO.bEnabled = FALSE; sCachedMultiBandIO.nBandsTried = 0; sCachedMultiBandIO.nXOff = 0; sCachedMultiBandIO.nYOff = 0; sCachedMultiBandIO.nXSize = 0; sCachedMultiBandIO.nYSize = 0; sCachedMultiBandIO.nBufXSize = 0; sCachedMultiBandIO.nBufYSize = 0; sCachedMultiBandIO.eBufType = GDT_Unknown; sCachedMultiBandIO.pabyData = NULL; bPreventCopyingSomeMetadata = FALSE; nBandIndexToPromoteTo8Bit = -1; poDriver = (GDALDriver*) GDALGetDriverByName( bIsJPEG2000 ? "JP2ECW" : "ECW" ); } /************************************************************************/ /* ~ECWDataset() */ /************************************************************************/ ECWDataset::~ECWDataset() { FlushCache(); CleanupWindow(); #if ECWSDK_VERSION>=50 NCSFileMetaData* pFileMetaDataCopy = NULL; if( bFileMetaDataDirty ) { NCSCopyMetaData(&pFileMetaDataCopy, psFileInfo->pFileMetaData); } #endif /* -------------------------------------------------------------------- */ /* Release / dereference iostream. */ /* -------------------------------------------------------------------- */ // The underlying iostream of the CNCSJP2FileView (poFileView) object may // also be the underlying iostream of other CNCSJP2FileView (poFileView) // objects. Consequently, when we delete the CNCSJP2FileView (poFileView) // object, we must decrement the nFileViewCount attribute of the underlying // VSIIOStream object, and only delete the VSIIOStream object when // nFileViewCount is equal to zero. CPLMutexHolder oHolder( &hECWDatasetMutex ); // bInGDALGlobalDestructor is set to TRUE by gdaldllmain.cpp/GDALDestroy() so as // to avoid an issue with the ECW SDK 3.3 where the destructor of CNCSJP2File::CNCSJP2FileVector CNCSJP2File::sm_Files; // static ressource allocated in NCJP2File.cpp can be called before GDALDestroy(), causing // ECW SDK resources ( CNCSJP2File files ) to be closed before we get here. if( poFileView != NULL && (!bIsJPEG2000 || !GDALIsInGlobalDestructor()) ) { VSIIOStream *poUnderlyingIOStream = (VSIIOStream *)NULL; poUnderlyingIOStream = ((VSIIOStream *)(poFileView->GetStream())); delete poFileView; if( bUsingCustomStream ) { if( --poUnderlyingIOStream->nFileViewCount == 0 ) delete poUnderlyingIOStream; } } /* WriteHeader() must be called after closing the file handle to work */ /* on Windows */ if( bHdrDirty ) WriteHeader(); #if ECWSDK_VERSION>=50 if (bStatisticsDirty){ StatisticsWrite(); } CleanupStatistics(); if( bFileMetaDataDirty ) { WriteFileMetaData(pFileMetaDataCopy); NCSFreeMetaData(pFileMetaDataCopy); } #endif CPLFree( pszProjection ); CSLDestroy( papszGMLMetadata ); if( nGCPCount > 0 ) { GDALDeinitGCPs( nGCPCount, pasGCPList ); CPLFree( pasGCPList ); } CPLFree(sCachedMultiBandIO.pabyData); } #if ECWSDK_VERSION>=50 /************************************************************************/ /* StatisticsEnsureInitialized() */ /************************************************************************/ NCS::CError ECWDataset::StatisticsEnsureInitialized(){ if (bStatisticsInitialized == TRUE){ return NCS_SUCCESS; } NCS::CError error = poFileView->GetClientStatistics(&pStatistics); if (error.Success()){ bStatisticsInitialized = TRUE; } return error; } /************************************************************************/ /* StatisticsWrite() */ /************************************************************************/ NCS::CError ECWDataset::StatisticsWrite() { CPLDebug("ECW", "In StatisticsWrite()"); NCSFileView* view = NCSEcwEditOpen( GetDescription() ); NCS::CError error; if ( view != NULL ){ error = NCSEcwEditSetStatistics(view, pStatistics); if (error.Success()){ error = NCSEcwEditFlushAll(view); if (error.Success()){ error = NCSEcwEditClose(view); } } } bStatisticsDirty = FALSE; return error; } /************************************************************************/ /* CleanupStatistics() */ /************************************************************************/ void ECWDataset::CleanupStatistics(){ if (bStatisticsInitialized == TRUE && pStatistics !=NULL){ NCSEcwFreeStatistics(pStatistics); } } #endif // #if ECWSDK_VERSION>=50 /************************************************************************/ /* SetGeoTransform() */ /************************************************************************/ CPLErr ECWDataset::SetGeoTransform( double * padfGeoTransform ) { if ( bIsJPEG2000 || eAccess == GA_ReadOnly ) return GDALPamDataset::SetGeoTransform(padfGeoTransform); if ( !bGeoTransformValid || adfGeoTransform[0] != padfGeoTransform[0] || adfGeoTransform[1] != padfGeoTransform[1] || adfGeoTransform[2] != padfGeoTransform[2] || adfGeoTransform[3] != padfGeoTransform[3] || adfGeoTransform[4] != padfGeoTransform[4] || adfGeoTransform[5] != padfGeoTransform[5] ) { memcpy(adfGeoTransform, padfGeoTransform, 6 * sizeof(double)); bGeoTransformValid = TRUE; bHdrDirty = TRUE; bGeoTransformChanged = TRUE; } return CE_None; } /************************************************************************/ /* SetProjection() */ /************************************************************************/ CPLErr ECWDataset::SetProjection( const char* pszProjectionIn ) { if ( bIsJPEG2000 || eAccess == GA_ReadOnly ) return GDALPamDataset::SetProjection(pszProjectionIn); if ( !( (pszProjection == NULL && pszProjectionIn == NULL) || (pszProjection != NULL && pszProjectionIn != NULL && strcmp(pszProjection, pszProjectionIn) == 0) ) ) { CPLFree(pszProjection); pszProjection = pszProjectionIn ? CPLStrdup(pszProjectionIn) : NULL; bHdrDirty = TRUE; bProjectionChanged = TRUE; } return CE_None; } /************************************************************************/ /* SetMetadataItem() */ /************************************************************************/ CPLErr ECWDataset::SetMetadataItem( const char * pszName, const char * pszValue, const char * pszDomain ) { if ( !bIsJPEG2000 && eAccess == GA_Update && (pszDomain == NULL || EQUAL(pszDomain, "") || (pszDomain != NULL && EQUAL(pszDomain, "ECW"))) && pszName != NULL && (strcmp(pszName, "PROJ") == 0 || strcmp( pszName, "DATUM") == 0 || strcmp( pszName, "UNITS") == 0 ) ) { CPLString osNewVal = pszValue ? pszValue : ""; if (osNewVal.size() > 31) osNewVal.resize(31); if (strcmp(pszName, "PROJ") == 0) { bProjCodeChanged = (osNewVal != m_osProjCode); m_osProjCode = osNewVal; bHdrDirty |= bProjCodeChanged; } else if (strcmp( pszName, "DATUM") == 0) { bDatumCodeChanged |= (osNewVal != m_osDatumCode)? TRUE:FALSE ; m_osDatumCode = osNewVal; bHdrDirty |= bDatumCodeChanged; } else { bUnitsCodeChanged |= (osNewVal != m_osUnitsCode)?TRUE:FALSE; m_osUnitsCode = osNewVal; bHdrDirty |= bUnitsCodeChanged; } return CE_None; } #if ECWSDK_VERSION >=50 else if ( psFileInfo != NULL && psFileInfo->nFormatVersion >= 3 && eAccess == GA_Update && (pszDomain == NULL || EQUAL(pszDomain, "")) && pszName != NULL && strncmp(pszName, "FILE_METADATA_", strlen("FILE_METADATA_")) == 0 ) { bFileMetaDataDirty = TRUE; if( psFileInfo->pFileMetaData == NULL ) NCSInitMetaData(&(psFileInfo->pFileMetaData)); if( strcmp(pszName, "FILE_METADATA_CLASSIFICATION") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sClassification); psFileInfo->pFileMetaData->sClassification = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_ACQUISITION_DATE") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sAcquisitionDate); psFileInfo->pFileMetaData->sAcquisitionDate = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_ACQUISITION_SENSOR_NAME") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sAcquisitionSensorName); psFileInfo->pFileMetaData->sAcquisitionSensorName = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_COMPRESSION_SOFTWARE") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sCompressionSoftware); psFileInfo->pFileMetaData->sCompressionSoftware = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_AUTHOR") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sAuthor); psFileInfo->pFileMetaData->sAuthor = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_COPYRIGHT") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sCopyright); psFileInfo->pFileMetaData->sCopyright = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_COMPANY") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sCompany); psFileInfo->pFileMetaData->sCompany = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_EMAIL") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sEmail); psFileInfo->pFileMetaData->sEmail = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_ADDRESS") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sAddress); psFileInfo->pFileMetaData->sAddress = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else if( strcmp(pszName, "FILE_METADATA_TELEPHONE") == 0 ) { NCSFree(psFileInfo->pFileMetaData->sTelephone); psFileInfo->pFileMetaData->sTelephone = pszValue ? NCSStrDupT(NCS::CString(pszValue).c_str()) : NULL; return GDALDataset::SetMetadataItem( pszName, pszValue, pszDomain ); } else { return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain); } } #endif else return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain); } /************************************************************************/ /* SetMetadata() */ /************************************************************************/ CPLErr ECWDataset::SetMetadata( char ** papszMetadata, const char * pszDomain ) { /* The bPreventCopyingSomeMetadata is set by ECWCreateCopy() */ /* just before calling poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); */ if( bPreventCopyingSomeMetadata && (pszDomain == NULL || EQUAL(pszDomain, "")) ) { char** papszMetadataDup = NULL; char** papszIter = papszMetadata; while( *papszIter ) { char* pszKey = NULL; CPLParseNameValue(*papszIter, &pszKey); /* Remove a few metadata item from the source that we don't want in */ /* the target metadata */ if( pszKey != NULL && ( EQUAL(pszKey, "VERSION") || EQUAL(pszKey, "COMPRESSION_RATE_TARGET") || EQUAL(pszKey, "COMPRESSION_RATE_ACTUAL") || EQUAL(pszKey, "CLOCKWISE_ROTATION_DEG") || EQUAL(pszKey, "COLORSPACE") || EQUAL(pszKey, "COMPRESSION_DATE") || EQUALN(pszKey, "FILE_METADATA_", strlen("FILE_METADATA_")) ) ) { /* do nothing */ } else { papszMetadataDup = CSLAddString(papszMetadataDup, *papszIter); } CPLFree(pszKey); papszIter ++; } bPreventCopyingSomeMetadata = FALSE; CPLErr eErr = SetMetadata(papszMetadataDup, pszDomain); bPreventCopyingSomeMetadata = TRUE; CSLDestroy(papszMetadataDup); return eErr; } if ( ((pszDomain == NULL || EQUAL(pszDomain, "") || EQUAL(pszDomain, "ECW")) && (CSLFetchNameValue(papszMetadata, "PROJ") != NULL || CSLFetchNameValue(papszMetadata, "DATUM") != NULL || CSLFetchNameValue(papszMetadata, "UNITS") != NULL)) #if ECWSDK_VERSION >=50 || (psFileInfo != NULL && psFileInfo->nFormatVersion >= 3 && eAccess == GA_Update && (pszDomain == NULL || EQUAL(pszDomain, "")) && (CSLFetchNameValue(papszMetadata, "FILE_METADATA_CLASSIFICATION") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_ACQUISITION_DATE") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_ACQUISITION_SENSOR_NAME") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_COMPRESSION_SOFTWARE") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_AUTHOR") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_COPYRIGHT") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_COMPANY") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_EMAIL") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_ADDRESS") != NULL || CSLFetchNameValue(papszMetadata, "FILE_METADATA_TELEPHONE") != NULL)) #endif ) { CPLStringList osNewMetadata; char** papszIter = papszMetadata; while(*papszIter) { if (strncmp(*papszIter, "PROJ=", 5) == 0 || strncmp(*papszIter, "DATUM=", 6) == 0 || strncmp(*papszIter, "UNITS=", 6) == 0 || (strncmp(*papszIter, "FILE_METADATA_", strlen("FILE_METADATA_")) == 0 && strchr(*papszIter, '=') != NULL) ) { char* pszKey = NULL; const char* pszValue = CPLParseNameValue(*papszIter, &pszKey ); SetMetadataItem(pszKey, pszValue, pszDomain); CPLFree(pszKey); } else osNewMetadata.AddString(*papszIter); papszIter ++; } if (osNewMetadata.size() != 0) return GDALPamDataset::SetMetadata(osNewMetadata.List(), pszDomain); else return CE_None; } else return GDALPamDataset::SetMetadata(papszMetadata, pszDomain); } /************************************************************************/ /* WriteHeader() */ /************************************************************************/ void ECWDataset::WriteHeader() { if (!bHdrDirty) return; CPLAssert(eAccess == GA_Update); CPLAssert(!bIsJPEG2000); bHdrDirty = FALSE; NCSEcwEditInfo *psEditInfo = NULL; NCSError eErr; /* Load original header info */ #if ECWSDK_VERSION<50 eErr = NCSEcwEditReadInfo((char*) GetDescription(), &psEditInfo); #else eErr = NCSEcwEditReadInfo( NCS::CString::Utf8Decode(GetDescription()).c_str(), &psEditInfo); #endif if (eErr != NCS_SUCCESS) { CPLError(CE_Failure, CPLE_AppDefined, "NCSEcwEditReadInfo() failed"); return; } /* To avoid potential cross-heap issues, we keep the original */ /* strings, and restore them before freeing the structure */ char* pszOriginalCode = psEditInfo->szDatum; char* pszOriginalProj = psEditInfo->szProjection; /* Alter the structure with user modified information */ char szProjCode[32], szDatumCode[32], szUnits[32]; if (bProjectionChanged) { if (ECWTranslateFromWKT( pszProjection, szProjCode, sizeof(szProjCode), szDatumCode, sizeof(szDatumCode), szUnits ) ) { psEditInfo->szDatum = szDatumCode; psEditInfo->szProjection = szProjCode; psEditInfo->eCellSizeUnits = ECWTranslateToCellSizeUnits(szUnits); CPLDebug("ECW", "Rewrite DATUM : %s", psEditInfo->szDatum); CPLDebug("ECW", "Rewrite PROJ : %s", psEditInfo->szProjection); CPLDebug("ECW", "Rewrite UNITS : %s", ECWTranslateFromCellSizeUnits(psEditInfo->eCellSizeUnits)); } } if (bDatumCodeChanged) { psEditInfo->szDatum = (char*) ((m_osDatumCode.size()) ? m_osDatumCode.c_str() : "RAW"); CPLDebug("ECW", "Rewrite DATUM : %s", psEditInfo->szDatum); } if (bProjCodeChanged) { psEditInfo->szProjection = (char*) ((m_osProjCode.size()) ? m_osProjCode.c_str() : "RAW"); CPLDebug("ECW", "Rewrite PROJ : %s", psEditInfo->szProjection); } if (bUnitsCodeChanged) { psEditInfo->eCellSizeUnits = ECWTranslateToCellSizeUnits(m_osUnitsCode.c_str()); CPLDebug("ECW", "Rewrite UNITS : %s", ECWTranslateFromCellSizeUnits(psEditInfo->eCellSizeUnits)); } if (bGeoTransformChanged) { psEditInfo->fOriginX = adfGeoTransform[0]; psEditInfo->fCellIncrementX = adfGeoTransform[1]; psEditInfo->fOriginY = adfGeoTransform[3]; psEditInfo->fCellIncrementY = adfGeoTransform[5]; CPLDebug("ECW", "Rewrite Geotransform"); } /* Write modified header info */ #if ECWSDK_VERSION<50 eErr = NCSEcwEditWriteInfo((char*) GetDescription(), psEditInfo, NULL, NULL, NULL); #else eErr = NCSEcwEditWriteInfo( NCS::CString::Utf8Decode(GetDescription()).c_str(), psEditInfo, NULL, NULL, NULL); #endif if (eErr != NCS_SUCCESS) { CPLError(CE_Failure, CPLE_AppDefined, "NCSEcwEditWriteInfo() failed"); } /* Restore original pointers before free'ing */ psEditInfo->szDatum = pszOriginalCode; psEditInfo->szProjection = pszOriginalProj; NCSEcwEditFreeInfo(psEditInfo); } /************************************************************************/ /* AdviseRead() */ /************************************************************************/ CPLErr ECWDataset::AdviseRead( int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eDT, int nBandCount, int *panBandList, char **papszOptions ) { int *panAdjustedBandList = NULL; CPLDebug( "ECW", "ECWDataset::AdviseRead(%d,%d,%d,%d->%d,%d)", nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize ); #if !defined(SDK_CAN_DO_SUPERSAMPLING) if( nBufXSize > nXSize || nBufYSize > nYSize ) { CPLError( CE_Warning, CPLE_AppDefined, "Supersampling not directly supported by ECW toolkit,\n" "ignoring AdviseRead() request." ); return CE_Warning; } #endif /* -------------------------------------------------------------------- */ /* Adjust band numbers to be zero based. */ /* -------------------------------------------------------------------- */ panAdjustedBandList = (int *) CPLMalloc(sizeof(int) * nBandCount ); nBandIndexToPromoteTo8Bit = -1; for( int ii= 0; ii < nBandCount; ii++ ) { if( ((ECWRasterBand*)GetRasterBand(panBandList[ii]))->bPromoteTo8Bit ) nBandIndexToPromoteTo8Bit = ii; panAdjustedBandList[ii] = panBandList[ii] - 1; } /* -------------------------------------------------------------------- */ /* Cleanup old window cache information. */ /* -------------------------------------------------------------------- */ CleanupWindow(); /* -------------------------------------------------------------------- */ /* Set the new requested window. */ /* -------------------------------------------------------------------- */ CNCSError oErr; oErr = poFileView->SetView( nBandCount, (UINT32 *) panAdjustedBandList, nXOff, nYOff, nXOff + nXSize-1, nYOff + nYSize-1, nBufXSize, nBufYSize ); CPLFree( panAdjustedBandList ); if( oErr.GetErrorNumber() != NCS_SUCCESS ) { ECWReportError(oErr); bWinActive = FALSE; return CE_Failure; } bWinActive = TRUE; /* -------------------------------------------------------------------- */ /* Record selected window. */ /* -------------------------------------------------------------------- */ nWinXOff = nXOff; nWinYOff = nYOff; nWinXSize = nXSize; nWinYSize = nYSize; nWinBufXSize = nBufXSize; nWinBufYSize = nBufYSize; panWinBandList = (int *) CPLMalloc(sizeof(int)*nBandCount); memcpy( panWinBandList, panBandList, sizeof(int)* nBandCount); nWinBandCount = nBandCount; nWinBufLoaded = -1; /* -------------------------------------------------------------------- */ /* Allocate current scanline buffer. */ /* -------------------------------------------------------------------- */ papCurLineBuf = (void **) CPLMalloc(sizeof(void*) * nWinBandCount ); for( int iBand = 0; iBand < nWinBandCount; iBand++ ) papCurLineBuf[iBand] = CPLMalloc(nBufXSize * (GDALGetDataTypeSize(eRasterDataType)/8) ); return CE_None; } /************************************************************************/ /* TryWinRasterIO() */ /* */ /* Try to satisfy the given request based on the currently */ /* defined window. Return TRUE on success or FALSE on */ /* failure. On failure, the caller should satisfy the request */ /* another way (not report an error). */ /************************************************************************/ int ECWDataset::TryWinRasterIO( GDALRWFlag eFlag, int nXOff, int nYOff, int nXSize, int nYSize, GByte *pabyData, int nBufXSize, int nBufYSize, GDALDataType eDT, int nBandCount, int *panBandList, int nPixelSpace, int nLineSpace, int nBandSpace ) { int iBand, i; /* -------------------------------------------------------------------- */ /* Provide default buffer organization. */ /* -------------------------------------------------------------------- */ if( nPixelSpace == 0 ) nPixelSpace = GDALGetDataTypeSize( eDT ) / 8; if( nLineSpace == 0 ) nLineSpace = nPixelSpace * nBufXSize; if( nBandSpace == 0 ) nBandSpace = nLineSpace * nBufYSize; /* -------------------------------------------------------------------- */ /* Do some simple tests to see if the current window can */ /* satisfy our requirement. */ /* -------------------------------------------------------------------- */ #ifdef NOISY_DEBUG CPLDebug( "ECW", "TryWinRasterIO(%d,%d,%d,%d,%d,%d)", nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize ); #endif if( !bWinActive ) return FALSE; if( nXOff != nWinXOff || nXSize != nWinXSize ) return FALSE; if( nBufXSize != nWinBufXSize ) return FALSE; for( iBand = 0; iBand < nBandCount; iBand++ ) { for( i = 0; i < nWinBandCount; i++ ) { if( panWinBandList[i] == panBandList[iBand] ) break; } if( i == nWinBandCount ) return FALSE; } if( nYOff < nWinYOff || nYOff + nYSize > nWinYOff + nWinYSize ) return FALSE; /* -------------------------------------------------------------------- */ /* Now we try more subtle tests. */ /* -------------------------------------------------------------------- */ { static int nDebugCount = 0; if( nDebugCount < 30 ) CPLDebug( "ECW", "TryWinRasterIO(%d,%d,%d,%d -> %dx%d) - doing advised read.", nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize ); if( nDebugCount == 29 ) CPLDebug( "ECW", "No more TryWinRasterIO messages will be reported" ); nDebugCount++; } /* -------------------------------------------------------------------- */ /* Actually load data one buffer line at a time. */ /* -------------------------------------------------------------------- */ int iBufLine; for( iBufLine = 0; iBufLine < nBufYSize; iBufLine++ ) { double fFileLine = ((iBufLine+0.5) / nBufYSize) * nYSize + nYOff; int iWinLine = (int) (((fFileLine - nWinYOff) / nWinYSize) * nWinBufYSize); if( iWinLine == nWinBufLoaded + 1 ) LoadNextLine(); if( iWinLine != nWinBufLoaded ) return FALSE; /* -------------------------------------------------------------------- */ /* Copy out all our target bands. */ /* -------------------------------------------------------------------- */ int iWinBand; for( iBand = 0; iBand < nBandCount; iBand++ ) { for( iWinBand = 0; iWinBand < nWinBandCount; iWinBand++ ) { if( panWinBandList[iWinBand] == panBandList[iBand] ) break; } GDALCopyWords( papCurLineBuf[iWinBand], eRasterDataType, GDALGetDataTypeSize( eRasterDataType ) / 8, pabyData + nBandSpace * iBand + iBufLine * nLineSpace, eDT, nPixelSpace, nBufXSize ); } } return TRUE; } /************************************************************************/ /* LoadNextLine() */ /************************************************************************/ CPLErr ECWDataset::LoadNextLine() { if( !bWinActive ) return CE_Failure; if( nWinBufLoaded == nWinBufYSize-1 ) { CleanupWindow(); return CE_Failure; } NCSEcwReadStatus eRStatus; eRStatus = poFileView->ReadLineBIL( eNCSRequestDataType, (UINT16) nWinBandCount, papCurLineBuf ); if( eRStatus != NCSECW_READ_OK ) return CE_Failure; if( nBandIndexToPromoteTo8Bit >= 0 ) { for(int iX = 0; iX < nWinBufXSize; iX ++ ) { ((GByte*)papCurLineBuf[nBandIndexToPromoteTo8Bit])[iX] *= 255; } } nWinBufLoaded++; return CE_None; } /************************************************************************/ /* CleanupWindow() */ /************************************************************************/ void ECWDataset::CleanupWindow() { if( !bWinActive ) return; bWinActive = FALSE; CPLFree( panWinBandList ); panWinBandList = NULL; for( int iBand = 0; iBand < nWinBandCount; iBand++ ) CPLFree( papCurLineBuf[iBand] ); CPLFree( papCurLineBuf ); papCurLineBuf = NULL; } /************************************************************************/ /* IRasterIO() */ /************************************************************************/ CPLErr ECWDataset::IRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int *panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace) { if( eRWFlag == GF_Write ) return CE_Failure; if( nBandCount > 100 ) return CE_Failure; if( bUseOldBandRasterIOImplementation ) /* Sanity check. Shouldn't happen */ return CE_Failure; int nDataTypeSize = (GDALGetDataTypeSize(eRasterDataType) / 8); if ( nPixelSpace == 0 ){ nPixelSpace = nDataTypeSize; } if (nLineSpace == 0 ) { nLineSpace = nPixelSpace*nBufXSize; } if ( nBandSpace == 0 ){ nBandSpace = nDataTypeSize*nBufXSize*nBufYSize; } /* -------------------------------------------------------------------- */ /* ECW SDK 3.3 has a bug with the ECW format when we query the */ /* number of bands of the dataset, but not in the "natural order". */ /* It ignores the content of panBandMap. (#4234) */ /* -------------------------------------------------------------------- */ #if ECWSDK_VERSION < 40 if( !bIsJPEG2000 && nBandCount == nBands ) { int i; int bDoBandIRasterIO = FALSE; for( i = 0; i < nBandCount; i++ ) { if( panBandMap[i] != i + 1 ) { bDoBandIRasterIO = TRUE; } } if( bDoBandIRasterIO ) { return GDALDataset::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace); } } #endif /* -------------------------------------------------------------------- */ /* Check if we can directly return the data in case we have cached */ /* it from a previous call in a multi-band reading pattern. */ /* -------------------------------------------------------------------- */ if( nBandCount == 1 && *panBandMap > 1 && *panBandMap <= nBands && sCachedMultiBandIO.nXOff == nXOff && sCachedMultiBandIO.nYOff == nYOff && sCachedMultiBandIO.nXSize == nXSize && sCachedMultiBandIO.nYSize == nYSize && sCachedMultiBandIO.nBufXSize == nBufXSize && sCachedMultiBandIO.nBufYSize == nBufYSize && sCachedMultiBandIO.eBufType == eBufType ) { sCachedMultiBandIO.nBandsTried ++; if( sCachedMultiBandIO.bEnabled && sCachedMultiBandIO.pabyData != NULL ) { int j; int nDataTypeSize = GDALGetDataTypeSize(eBufType) / 8; for(j = 0; j < nBufYSize; j++) { GDALCopyWords(sCachedMultiBandIO.pabyData + (*panBandMap - 1) * nBufXSize * nBufYSize * nDataTypeSize + j * nBufXSize * nDataTypeSize, eBufType, nDataTypeSize, ((GByte*)pData) + j * nLineSpace, eBufType, nPixelSpace, nBufXSize); } return CE_None; } if( !(sCachedMultiBandIO.bEnabled) && sCachedMultiBandIO.nBandsTried == nBands && CSLTestBoolean(CPLGetConfigOption("ECW_CLEVER", "YES")) ) { sCachedMultiBandIO.bEnabled = TRUE; CPLDebug("ECW", "Detecting successive band reading pattern (for next time)"); } } /* -------------------------------------------------------------------- */ /* Try to do it based on existing "advised" access. */ /* -------------------------------------------------------------------- */ if( TryWinRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, (GByte *) pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace ) ) return CE_None; /* -------------------------------------------------------------------- */ /* If we are requesting a single line at 1:1, we do a multi-band */ /* AdviseRead() and then TryWinRasterIO() again. */ /* */ /* Except for reading a 1x1 window when reading a scanline might */ /* be longer. */ /* -------------------------------------------------------------------- */ if( nXSize == 1 && nYSize == 1 && nBufXSize == 1 && nBufYSize == 1 ) { /* do nothing */ } #if !defined(SDK_CAN_DO_SUPERSAMPLING) /* -------------------------------------------------------------------- */ /* If we are supersampling we need to fall into the general */ /* purpose logic. */ /* -------------------------------------------------------------------- */ else if( nXSize < nBufXSize || nYSize < nBufYSize ) { bUseOldBandRasterIOImplementation = TRUE; CPLErr eErr = GDALDataset::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace); bUseOldBandRasterIOImplementation = FALSE; return eErr; } #endif else if( nBufYSize == 1 ) { //JTO: this is tricky, because it expects the rest of the image with this bufer width to be //read. The prefered way to achieve this behaviour would be to call AdviseRead before call IRasterIO. //ERO; indeed, the logic could be improved to detect successive pattern of single line reading //before doing an AdviseRead. CPLErr eErr; eErr = AdviseRead( nXOff, nYOff, nXSize, GetRasterYSize() - nYOff, nBufXSize, (nRasterYSize - nYOff) / nYSize, eBufType, nBandCount, panBandMap, NULL ); if( eErr == CE_None && TryWinRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, (GByte *) pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace ) ) return CE_None; } CPLDebug( "ECW", "RasterIO(%d,%d,%d,%d -> %dx%d) - doing interleaved read.", nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize ); /* -------------------------------------------------------------------- */ /* Setup view. */ /* -------------------------------------------------------------------- */ UINT32 anBandIndices[100]; int i; NCSError eNCSErr; CNCSError oErr; for( i = 0; i < nBandCount; i++ ) anBandIndices[i] = panBandMap[i] - 1; CleanupWindow(); /* -------------------------------------------------------------------- */ /* Cache data in the context of a multi-band reading pattern. */ /* -------------------------------------------------------------------- */ if( nBandCount == 1 && *panBandMap == 1 && (nBands == 3 || nBands == 4) ) { if( sCachedMultiBandIO.bEnabled && sCachedMultiBandIO.nBandsTried != nBands ) { sCachedMultiBandIO.bEnabled = FALSE; CPLDebug("ECW", "Disabling successive band reading pattern"); } sCachedMultiBandIO.nXOff = nXOff; sCachedMultiBandIO.nYOff = nYOff; sCachedMultiBandIO.nXSize = nXSize; sCachedMultiBandIO.nYSize = nYSize; sCachedMultiBandIO.nBufXSize = nBufXSize; sCachedMultiBandIO.nBufYSize = nBufYSize; sCachedMultiBandIO.eBufType = eBufType; sCachedMultiBandIO.nBandsTried = 1; int nDataTypeSize = GDALGetDataTypeSize(eBufType) / 8; if( sCachedMultiBandIO.bEnabled ) { GByte* pNew = (GByte*)VSIRealloc( sCachedMultiBandIO.pabyData, nBufXSize * nBufYSize * nBands * nDataTypeSize); if( pNew == NULL ) CPLFree(sCachedMultiBandIO.pabyData); sCachedMultiBandIO.pabyData = pNew; } if( sCachedMultiBandIO.bEnabled && sCachedMultiBandIO.pabyData != NULL ) { nBandIndexToPromoteTo8Bit = -1; for( i = 0; i < nBands; i++ ) { if( ((ECWRasterBand*)GetRasterBand(i+1))->bPromoteTo8Bit ) nBandIndexToPromoteTo8Bit = i; anBandIndices[i] = i; } oErr = poFileView->SetView( nBands, anBandIndices, nXOff, nYOff, nXOff + nXSize - 1, nYOff + nYSize - 1, nBufXSize, nBufYSize ); eNCSErr = oErr.GetErrorNumber(); if( eNCSErr != NCS_SUCCESS ) { CPLError( CE_Failure, CPLE_AppDefined, "%s", NCSGetErrorText(eNCSErr) ); return CE_Failure; } CPLErr eErr = ReadBands(sCachedMultiBandIO.pabyData, nBufXSize, nBufYSize, eBufType, nBands, nDataTypeSize, nBufXSize * nDataTypeSize, nBufXSize * nBufYSize * nDataTypeSize); if( eErr != CE_None ) return eErr; int j; for(j = 0; j < nBufYSize; j++) { GDALCopyWords(sCachedMultiBandIO.pabyData + j * nBufXSize * nDataTypeSize, eBufType, nDataTypeSize, ((GByte*)pData) + j * nLineSpace, eBufType, nPixelSpace, nBufXSize); } return CE_None; } } nBandIndexToPromoteTo8Bit = -1; for( i = 0; i < nBandCount; i++ ) { if( ((ECWRasterBand*)GetRasterBand(anBandIndices[i]+1))->bPromoteTo8Bit ) nBandIndexToPromoteTo8Bit = i; } oErr = poFileView->SetView( nBandCount, anBandIndices, nXOff, nYOff, nXOff + nXSize - 1, nYOff + nYSize - 1, nBufXSize, nBufYSize ); eNCSErr = oErr.GetErrorNumber(); if( eNCSErr != NCS_SUCCESS ) { CPLError( CE_Failure, CPLE_AppDefined, "%s", NCSGetErrorText(eNCSErr) ); return CE_Failure; } return ReadBands(pData, nBufXSize, nBufYSize, eBufType, nBandCount, nPixelSpace, nLineSpace, nBandSpace); } /************************************************************************/ /* ReadBandsDirectly() */ /************************************************************************/ CPLErr ECWDataset::ReadBandsDirectly(void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int nPixelSpace, int nLineSpace, int nBandSpace) { CPLDebug( "ECW", "ReadBandsDirectly(-> %dx%d) - reading lines directly.", nBufXSize, nBufYSize); UINT8 **pBIL = (UINT8**)NCSMalloc(nBandCount * sizeof(UINT8*), FALSE); for(int nB = 0; nB < nBandCount; nB++) { pBIL[nB] = ((UINT8*)pData) + (nBandSpace*nB);//for any bit depth } for(int nR = 0; nR < nBufYSize; nR++) { if (poFileView->ReadLineBIL(eNCSRequestDataType,(UINT16) nBandCount, (void**)pBIL) != NCSECW_READ_OK) { if(pBIL) { NCSFree(pBIL); } return CE_Failure; } for(int nB = 0; nB < nBandCount; nB++) { if( nB == nBandIndexToPromoteTo8Bit ) { for(int iX = 0; iX < nBufXSize; iX ++ ) { pBIL[nB][iX] *= 255; } } pBIL[nB] += nLineSpace; } } if(pBIL) { NCSFree(pBIL); } return CE_None; } /************************************************************************/ /* ReadBands() */ /************************************************************************/ CPLErr ECWDataset::ReadBands(void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int nPixelSpace, int nLineSpace, int nBandSpace) { int i; /* -------------------------------------------------------------------- */ /* Setup working scanline, and the pointers into it. */ /* -------------------------------------------------------------------- */ int nDataTypeSize = (GDALGetDataTypeSize(eRasterDataType) / 8); bool bDirect = (eBufType == eRasterDataType) && nDataTypeSize == nPixelSpace && nLineSpace == (nPixelSpace*nBufXSize) && nBandSpace == (nDataTypeSize*nBufXSize*nBufYSize) ; if (bDirect) { return ReadBandsDirectly(pData, nBufXSize, nBufYSize,eBufType, nBandCount, nPixelSpace, nLineSpace, nBandSpace); } CPLDebug( "ECW", "ReadBands(-> %dx%d) - reading lines using GDALCopyWords.", nBufXSize, nBufYSize); CPLErr eErr = CE_None; GByte *pabyBILScanline = (GByte *) CPLMalloc(nBufXSize * nDataTypeSize * nBandCount); GByte **papabyBIL = (GByte **) CPLMalloc(nBandCount * sizeof(void*)); for( i = 0; i < nBandCount; i++ ) papabyBIL[i] = pabyBILScanline + i * nBufXSize * nDataTypeSize; /* -------------------------------------------------------------------- */ /* Read back all the data for the requested view. */ /* -------------------------------------------------------------------- */ for( int iScanline = 0; iScanline < nBufYSize; iScanline++ ) { NCSEcwReadStatus eRStatus; eRStatus = poFileView->ReadLineBIL( eNCSRequestDataType, (UINT16) nBandCount, (void **) papabyBIL ); if( eRStatus != NCSECW_READ_OK ) { eErr = CE_Failure; CPLError( CE_Failure, CPLE_AppDefined, "NCScbmReadViewLineBIL failed." ); break; } for( i = 0; i < nBandCount; i++ ) { if( i == nBandIndexToPromoteTo8Bit ) { for(int iX = 0; iX < nBufXSize; iX ++ ) { papabyBIL[i][iX] *= 255; } } GDALCopyWords( pabyBILScanline + i * nDataTypeSize * nBufXSize, eRasterDataType, nDataTypeSize, ((GByte *) pData) + nLineSpace * iScanline + nBandSpace * i, eBufType, nPixelSpace, nBufXSize ); } } CPLFree( pabyBILScanline ); CPLFree( papabyBIL ); return eErr; } /************************************************************************/ /* IdentifyJPEG2000() */ /* */ /* Open method that only supports JPEG2000 files. */ /************************************************************************/ int ECWDataset::IdentifyJPEG2000( GDALOpenInfo * poOpenInfo ) { if( EQUALN(poOpenInfo->pszFilename,"J2K_SUBFILE:",12) ) return TRUE; else if( poOpenInfo->nHeaderBytes >= 16 && (memcmp( poOpenInfo->pabyHeader, jpc_header, sizeof(jpc_header) ) == 0 || memcmp( poOpenInfo->pabyHeader, jp2_header, sizeof(jp2_header) ) == 0) ) return TRUE; else return FALSE; } /************************************************************************/ /* OpenJPEG2000() */ /* */ /* Open method that only supports JPEG2000 files. */ /************************************************************************/ GDALDataset *ECWDataset::OpenJPEG2000( GDALOpenInfo * poOpenInfo ) { if (!IdentifyJPEG2000(poOpenInfo)) return NULL; return Open( poOpenInfo, TRUE ); } /************************************************************************/ /* IdentifyECW() */ /* */ /* Identify method that only supports ECW files. */ /************************************************************************/ int ECWDataset::IdentifyECW( GDALOpenInfo * poOpenInfo ) { /* -------------------------------------------------------------------- */ /* This has to either be a file on disk ending in .ecw or a */ /* ecwp: protocol url. */ /* -------------------------------------------------------------------- */ if( (!EQUAL(CPLGetExtension(poOpenInfo->pszFilename),"ecw") || poOpenInfo->nHeaderBytes == 0) && !EQUALN(poOpenInfo->pszFilename,"ecwp:",5) && !EQUALN(poOpenInfo->pszFilename,"ecwps:",5) ) return FALSE; return TRUE; } /************************************************************************/ /* OpenECW() */ /* */ /* Open method that only supports ECW files. */ /************************************************************************/ GDALDataset *ECWDataset::OpenECW( GDALOpenInfo * poOpenInfo ) { if (!IdentifyECW(poOpenInfo)) return NULL; return Open( poOpenInfo, FALSE ); } /************************************************************************/ /* OpenFileView() */ /************************************************************************/ CNCSJP2FileView *ECWDataset::OpenFileView( const char *pszDatasetName, bool bProgressive, int &bUsingCustomStream, bool bWrite ) { /* -------------------------------------------------------------------- */ /* First we try to open it as a normal CNCSFile, letting the */ /* ECW SDK manage the IO itself. This will only work for real */ /* files, and ecwp: or ecwps: sources. */ /* -------------------------------------------------------------------- */ CNCSJP2FileView *poFileView = NULL; NCSError eErr; CNCSError oErr; bUsingCustomStream = FALSE; poFileView = new CNCSFile(); //we always open in read only mode. This should be improved in the future. oErr = poFileView->Open( (char *) pszDatasetName, bProgressive, false ); eErr = oErr.GetErrorNumber(); /* -------------------------------------------------------------------- */ /* If that did not work, trying opening as a virtual file. */ /* -------------------------------------------------------------------- */ if( eErr != NCS_SUCCESS ) { CPLDebug( "ECW", "NCScbmOpenFileView(%s): eErr=%d, will try VSIL stream.", pszDatasetName, (int) eErr ); delete poFileView; VSILFILE *fpVSIL = VSIFOpenL( pszDatasetName, "rb" ); if( fpVSIL == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open %s.", pszDatasetName ); return NULL; } if( hECWDatasetMutex == NULL ) { hECWDatasetMutex = CPLCreateMutex(); } else if( !CPLAcquireMutex( hECWDatasetMutex, 60.0 ) ) { CPLDebug( "ECW", "Failed to acquire mutex in 60s." ); } else { CPLDebug( "ECW", "Got mutex." ); } VSIIOStream *poIOStream = new VSIIOStream(); poIOStream->Access( fpVSIL, FALSE, TRUE, pszDatasetName, 0, -1 ); poFileView = new CNCSJP2FileView(); oErr = poFileView->Open( poIOStream, bProgressive ); // The CNCSJP2FileView (poFileView) object may not use the iostream // (poIOStream) passed to the CNCSJP2FileView::Open() method if an // iostream is already available to the ECW JPEG 2000 SDK for a given // file. Consequently, if the iostream passed to // CNCSJP2FileView::Open() does not become the underlying iostream // of the CNCSJP2FileView object, then it should be deleted. // // In addition, the underlying iostream of the CNCSJP2FileView object // should not be deleted until all CNCSJP2FileView objects using the // underlying iostream are deleted. Consequently, each time a // CNCSJP2FileView object is created, the nFileViewCount attribute // of the underlying VSIIOStream object must be incremented for use // in the ECWDataset destructor. VSIIOStream * poUnderlyingIOStream = ((VSIIOStream *)(poFileView->GetStream())); if ( poUnderlyingIOStream ) poUnderlyingIOStream->nFileViewCount++; if ( poIOStream != poUnderlyingIOStream ) { delete poIOStream; } else { bUsingCustomStream = TRUE; } CPLReleaseMutex( hECWDatasetMutex ); if( oErr.GetErrorNumber() != NCS_SUCCESS ) { if (poFileView) delete poFileView; ECWReportError(oErr); return NULL; } } return poFileView; } /************************************************************************/ /* Open() */ /************************************************************************/ GDALDataset *ECWDataset::Open( GDALOpenInfo * poOpenInfo, int bIsJPEG2000 ) { CNCSJP2FileView *poFileView = NULL; int i; int bUsingCustomStream = FALSE; CPLString osFilename = poOpenInfo->pszFilename; ECWInitialize(); /* Note: J2K_SUBFILE is somehow an obsolete concept that predates /vsisubfile/ */ /* syntax and was used mainly(only?) by the NITF driver before its switch */ /* to /vsisubfile */ /* -------------------------------------------------------------------- */ /* If we get a J2K_SUBFILE style name, convert it into the */ /* corresponding /vsisubfile/ path. */ /* */ /* From: J2K_SUBFILE:offset,size,filename */ /* To: /vsisubfile/offset_size,filename */ /* -------------------------------------------------------------------- */ if (EQUALN(osFilename,"J2K_SUBFILE:",12)) { char** papszTokens = CSLTokenizeString2(osFilename.c_str()+12, ",", 0); if (CSLCount(papszTokens) >= 3) { osFilename.Printf( "/vsisubfile/%s_%s,%s", papszTokens[0], papszTokens[1], papszTokens[2]); } else { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to parse J2K_SUBFILE specification." ); CSLDestroy(papszTokens); return NULL; } CSLDestroy(papszTokens); } /* -------------------------------------------------------------------- */ /* Open the client interface. */ /* -------------------------------------------------------------------- */ poFileView = OpenFileView( osFilename.c_str(), false, bUsingCustomStream, poOpenInfo->eAccess == GA_Update ); if( poFileView == NULL ) { #if ECWSDK_VERSION < 50 /* Detect what is apparently the ECW v3 file format signature */ if( EQUAL(CPLGetExtension(osFilename), "ECW") && poOpenInfo->nHeaderBytes > 0x30 && EQUALN((const char*)(poOpenInfo->pabyHeader + 0x20), "ecw ECW3", 8) ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot open %s which looks like a ECW format v3 file, that requires ECW SDK 5.0 or later", osFilename.c_str()); } #endif return NULL; } /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ ECWDataset *poDS; poDS = new ECWDataset(bIsJPEG2000); poDS->poFileView = poFileView; poDS->eAccess = poOpenInfo->eAccess; // Disable .aux.xml writing for subfiles and such. Unfortunately // this will also disable it in some cases where it might be // applicable. if( bUsingCustomStream ) poDS->nPamFlags |= GPF_DISABLED; poDS->bUsingCustomStream = bUsingCustomStream; /* -------------------------------------------------------------------- */ /* Fetch general file information. */ /* -------------------------------------------------------------------- */ poDS->psFileInfo = poFileView->GetFileInfo(); CPLDebug( "ECW", "FileInfo: SizeXY=%d,%d Bands=%d\n" " OriginXY=%g,%g CellIncrementXY=%g,%g\n" " ColorSpace=%d, eCellType=%d\n", poDS->psFileInfo->nSizeX, poDS->psFileInfo->nSizeY, poDS->psFileInfo->nBands, poDS->psFileInfo->fOriginX, poDS->psFileInfo->fOriginY, poDS->psFileInfo->fCellIncrementX, poDS->psFileInfo->fCellIncrementY, (int) poDS->psFileInfo->eColorSpace, (int) poDS->psFileInfo->eCellType ); /* -------------------------------------------------------------------- */ /* Establish raster info. */ /* -------------------------------------------------------------------- */ poDS->nRasterXSize = poDS->psFileInfo->nSizeX; poDS->nRasterYSize = poDS->psFileInfo->nSizeY; /* -------------------------------------------------------------------- */ /* Establish the GDAL data type that corresponds. A few NCS */ /* data types have no direct corresponding value in GDAL so we */ /* will coerce to something sufficiently similar. */ /* -------------------------------------------------------------------- */ poDS->eNCSRequestDataType = poDS->psFileInfo->eCellType; switch( poDS->psFileInfo->eCellType ) { case NCSCT_UINT8: poDS->eRasterDataType = GDT_Byte; break; case NCSCT_UINT16: poDS->eRasterDataType = GDT_UInt16; break; case NCSCT_UINT32: case NCSCT_UINT64: poDS->eRasterDataType = GDT_UInt32; poDS->eNCSRequestDataType = NCSCT_UINT32; break; case NCSCT_INT8: case NCSCT_INT16: poDS->eRasterDataType = GDT_Int16; poDS->eNCSRequestDataType = NCSCT_INT16; break; case NCSCT_INT32: case NCSCT_INT64: poDS->eRasterDataType = GDT_Int32; poDS->eNCSRequestDataType = NCSCT_INT32; break; case NCSCT_IEEE4: poDS->eRasterDataType = GDT_Float32; break; case NCSCT_IEEE8: poDS->eRasterDataType = GDT_Float64; break; default: CPLDebug("ECW", "Unhandled case : eCellType = %d", (int)poDS->psFileInfo->eCellType ); break; } /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ for( i=0; i < poDS->psFileInfo->nBands; i++ ) poDS->SetBand( i+1, new ECWRasterBand( poDS, i+1 ) ); /* -------------------------------------------------------------------- */ /* Look for supporting coordinate system information. */ /* -------------------------------------------------------------------- */ if( bIsJPEG2000 ) { GDALJP2Metadata oJP2Geo; if ( oJP2Geo.ReadAndParse( osFilename ) ) { poDS->pszProjection = CPLStrdup(oJP2Geo.pszProjection); poDS->bGeoTransformValid = oJP2Geo.bHaveGeoTransform; memcpy( poDS->adfGeoTransform, oJP2Geo.adfGeoTransform, sizeof(double) * 6 ); poDS->nGCPCount = oJP2Geo.nGCPCount; poDS->pasGCPList = oJP2Geo.pasGCPList; oJP2Geo.pasGCPList = NULL; oJP2Geo.nGCPCount = 0; } if (oJP2Geo.pszXMPMetadata) { char *apszMDList[2]; apszMDList[0] = (char *) oJP2Geo.pszXMPMetadata; apszMDList[1] = NULL; poDS->SetMetadata(apszMDList, "xml:XMP"); } } else { poDS->ECW2WKTProjection(); } poDS->SetMetadataItem("COMPRESSION_RATE_TARGET", CPLString().Printf("%d", poDS->psFileInfo->nCompressionRate)); poDS->SetMetadataItem("COLORSPACE", ECWGetColorSpaceName(poDS->psFileInfo->eColorSpace)); #if ECWSDK_VERSION>=50 poDS->SetMetadataItem("VERSION", CPLString().Printf("%d", poDS->psFileInfo->nFormatVersion)); if ( poDS->psFileInfo->nFormatVersion >=3 ){ poDS->SetMetadataItem("COMPRESSION_RATE_ACTUAL", CPLString().Printf("%f", poDS->psFileInfo->fActualCompressionRate)); poDS->SetMetadataItem("CLOCKWISE_ROTATION_DEG", CPLString().Printf("%f", poDS->psFileInfo->fCWRotationDegrees)); poDS->SetMetadataItem("COMPRESSION_DATE", poDS->psFileInfo->sCompressionDate); //Get file metadata. poDS->ReadFileMetaDataFromFile(); } #else poDS->SetMetadataItem("VERSION", CPLString().Printf("%d",bIsJPEG2000?1:2)); #endif /* -------------------------------------------------------------------- */ /* Check for world file. */ /* -------------------------------------------------------------------- */ if( !poDS->bGeoTransformValid ) { poDS->bGeoTransformValid |= GDALReadWorldFile2( osFilename, NULL, poDS->adfGeoTransform, poOpenInfo->papszSiblingFiles, NULL ) || GDALReadWorldFile2( osFilename, ".wld", poDS->adfGeoTransform, poOpenInfo->papszSiblingFiles, NULL ); } /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( osFilename ); poDS->TryLoadXML(); return( poDS ); } /************************************************************************/ /* GetGCPCount() */ /************************************************************************/ int ECWDataset::GetGCPCount() { if( nGCPCount != 0 ) return nGCPCount; else return GDALPamDataset::GetGCPCount(); } /************************************************************************/ /* GetGCPProjection() */ /************************************************************************/ const char *ECWDataset::GetGCPProjection() { if( nGCPCount > 0 ) return pszProjection; else return GDALPamDataset::GetGCPProjection(); } /************************************************************************/ /* GetGCP() */ /************************************************************************/ const GDAL_GCP *ECWDataset::GetGCPs() { if( nGCPCount != 0 ) return pasGCPList; else return GDALPamDataset::GetGCPs(); } /************************************************************************/ /* GetProjectionRef() */ /* */ /* We let PAM coordinate system override the one stored inside */ /* our file. */ /************************************************************************/ const char *ECWDataset::GetProjectionRef() { const char* pszPamPrj = GDALPamDataset::GetProjectionRef(); if( pszProjection != NULL && strlen(pszPamPrj) == 0 ) return pszProjection; else return pszPamPrj; } /************************************************************************/ /* GetGeoTransform() */ /* */ /* Let the PAM geotransform override the native one if it is */ /* available. */ /************************************************************************/ CPLErr ECWDataset::GetGeoTransform( double * padfTransform ) { CPLErr eErr = GDALPamDataset::GetGeoTransform( padfTransform ); if( eErr != CE_None && bGeoTransformValid ) { memcpy( padfTransform, adfGeoTransform, sizeof(double) * 6 ); return( CE_None ); } else return eErr; } /************************************************************************/ /* GetMetadataItem() */ /************************************************************************/ const char *ECWDataset::GetMetadataItem( const char * pszName, const char * pszDomain ) { if (!bIsJPEG2000 && pszDomain != NULL && EQUAL(pszDomain, "ECW") && pszName != NULL) { if (EQUAL(pszName, "PROJ")) return m_osProjCode.size() ? m_osProjCode.c_str() : "RAW"; if (EQUAL(pszName, "DATUM")) return m_osDatumCode.size() ? m_osDatumCode.c_str() : "RAW"; if (EQUAL(pszName, "UNITS")) return m_osUnitsCode.size() ? m_osUnitsCode.c_str() : "METERS"; } return GDALPamDataset::GetMetadataItem(pszName, pszDomain); } /************************************************************************/ /* GetMetadata() */ /************************************************************************/ char **ECWDataset::GetMetadata( const char *pszDomain ) { if( !bIsJPEG2000 && pszDomain != NULL && EQUAL(pszDomain, "ECW") ) { oECWMetadataList.Clear(); oECWMetadataList.AddString(CPLSPrintf("%s=%s", "PROJ", GetMetadataItem("PROJ", "ECW"))); oECWMetadataList.AddString(CPLSPrintf("%s=%s", "DATUM", GetMetadataItem("DATUM", "ECW"))); oECWMetadataList.AddString(CPLSPrintf("%s=%s", "UNITS", GetMetadataItem("UNITS", "ECW"))); return oECWMetadataList.List(); } else if( pszDomain == NULL || !EQUAL(pszDomain,"GML") ) return GDALPamDataset::GetMetadata( pszDomain ); else return papszGMLMetadata; } /************************************************************************/ /* ReadFileMetaDataFromFile() */ /* */ /* Gets relevant information from NCSFileMetadata and populates */ /* GDAL metadata */ /* */ /************************************************************************/ #if ECWSDK_VERSION >= 50 void ECWDataset::ReadFileMetaDataFromFile() { if (psFileInfo->pFileMetaData == NULL) return; if (psFileInfo->pFileMetaData->sClassification != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_CLASSIFICATION", NCS::CString(psFileInfo->pFileMetaData->sClassification).a_str()); if (psFileInfo->pFileMetaData->sAcquisitionDate != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_ACQUISITION_DATE", NCS::CString(psFileInfo->pFileMetaData->sAcquisitionDate)); if (psFileInfo->pFileMetaData->sAcquisitionSensorName != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_ACQUISITION_SENSOR_NAME", NCS::CString(psFileInfo->pFileMetaData->sAcquisitionSensorName)); if (psFileInfo->pFileMetaData->sCompressionSoftware != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_COMPRESSION_SOFTWARE", NCS::CString(psFileInfo->pFileMetaData->sCompressionSoftware)); if (psFileInfo->pFileMetaData->sAuthor != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_AUTHOR", NCS::CString(psFileInfo->pFileMetaData->sAuthor)); if (psFileInfo->pFileMetaData->sCopyright != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_COPYRIGHT", NCS::CString(psFileInfo->pFileMetaData->sCopyright)); if (psFileInfo->pFileMetaData->sCompany != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_COMPANY", NCS::CString(psFileInfo->pFileMetaData->sCompany)); if (psFileInfo->pFileMetaData->sEmail != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_EMAIL", NCS::CString(psFileInfo->pFileMetaData->sEmail)); if (psFileInfo->pFileMetaData->sAddress != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_ADDRESS", NCS::CString(psFileInfo->pFileMetaData->sAddress)); if (psFileInfo->pFileMetaData->sTelephone != NULL ) GDALDataset::SetMetadataItem("FILE_METADATA_TELEPHONE", NCS::CString(psFileInfo->pFileMetaData->sTelephone)); } /************************************************************************/ /* WriteFileMetaData() */ /************************************************************************/ void ECWDataset::WriteFileMetaData(NCSFileMetaData* pFileMetaDataCopy) { if (!bFileMetaDataDirty ) return; CPLAssert(eAccess == GA_Update); CPLAssert(!bIsJPEG2000); bFileMetaDataDirty = FALSE; NCSFileView *psFileView = NULL; NCSError eErr; psFileView = NCSEditOpen( GetDescription() ); if (psFileView == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "NCSEditOpen() failed"); return; } eErr = NCSEditSetFileMetaData(psFileView, pFileMetaDataCopy); if( eErr != NCS_SUCCESS ) { CPLError(CE_Failure, CPLE_AppDefined, "NCSEditSetFileMetaData() failed : %s", NCSGetLastErrorText(eErr)); } NCSEditFlushAll(psFileView); NCSEditClose(psFileView); } #endif /************************************************************************/ /* ECW2WKTProjection() */ /* */ /* Set the dataset pszProjection string in OGC WKT format by */ /* looking up the ECW (GDT) coordinate system info in */ /* ecw_cs.dat support data file. */ /* */ /* This code is likely still broken in some circumstances. For */ /* instance, I haven't been careful about changing the linear */ /* projection parameters (false easting/northing) if the units */ /* is feet. Lots of cases missing here, and in ecw_cs.dat. */ /************************************************************************/ void ECWDataset::ECW2WKTProjection() { if( psFileInfo == NULL ) return; /* -------------------------------------------------------------------- */ /* Capture Geotransform. */ /* */ /* We will try to ignore the provided file information if it is */ /* origin (0,0) and pixel size (1,1). I think sometimes I have */ /* also seen pixel increments of 0 on invalid datasets. */ /* -------------------------------------------------------------------- */ if( psFileInfo->fOriginX != 0.0 || psFileInfo->fOriginY != 0.0 || (psFileInfo->fCellIncrementX != 0.0 && psFileInfo->fCellIncrementX != 1.0) || (psFileInfo->fCellIncrementY != 0.0 && psFileInfo->fCellIncrementY != 1.0) ) { bGeoTransformValid = TRUE; adfGeoTransform[0] = psFileInfo->fOriginX; adfGeoTransform[1] = psFileInfo->fCellIncrementX; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = psFileInfo->fOriginY; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = -fabs(psFileInfo->fCellIncrementY); } /* -------------------------------------------------------------------- */ /* do we have projection and datum? */ /* -------------------------------------------------------------------- */ CPLString osUnits = ECWTranslateFromCellSizeUnits(psFileInfo->eCellSizeUnits); CPLDebug( "ECW", "projection=%s, datum=%s, units=%s", psFileInfo->szProjection, psFileInfo->szDatum, osUnits.c_str()); if( EQUAL(psFileInfo->szProjection,"RAW") ) return; /* -------------------------------------------------------------------- */ /* Set projection if we have it. */ /* -------------------------------------------------------------------- */ OGRSpatialReference oSRS; /* For backward-compatible with previous behaviour. Should we only */ /* restrict to those 2 values ? */ if (psFileInfo->eCellSizeUnits != ECW_CELL_UNITS_METERS && psFileInfo->eCellSizeUnits != ECW_CELL_UNITS_FEET) osUnits = ECWTranslateFromCellSizeUnits(ECW_CELL_UNITS_METERS); m_osDatumCode = psFileInfo->szDatum; m_osProjCode = psFileInfo->szProjection; m_osUnitsCode = osUnits; if( oSRS.importFromERM( psFileInfo->szProjection, psFileInfo->szDatum, osUnits ) == OGRERR_NONE ) { oSRS.exportToWkt( &pszProjection ); } CPLErrorReset(); /* see #4187 */ } /************************************************************************/ /* ECWTranslateFromWKT() */ /************************************************************************/ int ECWTranslateFromWKT( const char *pszWKT, char *pszProjection, int nProjectionLen, char *pszDatum, int nDatumLen, char *pszUnits) { OGRSpatialReference oSRS; char *pszWKTIn = (char *) pszWKT; strcpy( pszProjection, "RAW" ); strcpy( pszDatum, "RAW" ); strcpy( pszUnits, "METERS" ); if( pszWKT == NULL || strlen(pszWKT) == 0 ) return FALSE; oSRS.importFromWkt( &pszWKTIn ); if( oSRS.IsLocal() ) return TRUE; /* -------------------------------------------------------------------- */ /* Do we have an overall EPSG number for this coordinate system? */ /* -------------------------------------------------------------------- */ const char *pszAuthorityCode = NULL; const char *pszAuthorityName = NULL; UINT32 nEPSGCode = 0; if( oSRS.IsProjected() ) { pszAuthorityCode = oSRS.GetAuthorityCode( "PROJCS" ); pszAuthorityName = oSRS.GetAuthorityName( "PROJCS" ); } else if( oSRS.IsGeographic() ) { pszAuthorityCode = oSRS.GetAuthorityCode( "GEOGCS" ); pszAuthorityName = oSRS.GetAuthorityName( "GEOGCS" ); } if( pszAuthorityName != NULL && EQUAL(pszAuthorityName,"EPSG") && pszAuthorityCode != NULL && atoi(pszAuthorityCode) > 0 ) nEPSGCode = (UINT32) atoi(pszAuthorityCode); if( nEPSGCode != 0 ) { char *pszEPSGProj = NULL, *pszEPSGDatum = NULL; CNCSError oErr; oErr = CNCSJP2FileView::GetProjectionAndDatum( atoi(pszAuthorityCode), &pszEPSGProj, &pszEPSGDatum ); CPLDebug( "ECW", "GetGDTProjDat(%d) = %s/%s", atoi(pszAuthorityCode), pszEPSGProj ? pszEPSGProj : "(null)", pszEPSGDatum ? pszEPSGDatum : "(null)"); if( oErr.GetErrorNumber() == NCS_SUCCESS && pszEPSGProj != NULL && pszEPSGDatum != NULL ) { strncpy( pszProjection, pszEPSGProj, nProjectionLen ); strncpy( pszDatum, pszEPSGDatum, nDatumLen ); pszProjection[nProjectionLen - 1] = 0; pszDatum[nDatumLen - 1] = 0; NCSFree( pszEPSGProj ); NCSFree( pszEPSGDatum ); return TRUE; } NCSFree( pszEPSGProj ); NCSFree( pszEPSGDatum ); } /* -------------------------------------------------------------------- */ /* Fallback to translating based on the ecw_cs.wkt file, and */ /* various jiffy rules. */ /* -------------------------------------------------------------------- */ return oSRS.exportToERM( pszProjection, pszDatum, pszUnits ) == OGRERR_NONE; } /************************************************************************/ /* ECWTranslateToCellSizeUnits() */ /************************************************************************/ CellSizeUnits ECWTranslateToCellSizeUnits(const char* pszUnits) { if (EQUAL(pszUnits, "METERS")) return ECW_CELL_UNITS_METERS; else if (EQUAL(pszUnits, "DEGREES")) return ECW_CELL_UNITS_DEGREES; else if (EQUAL(pszUnits, "FEET")) return ECW_CELL_UNITS_FEET; else if (EQUAL(pszUnits, "UNKNOWN")) return ECW_CELL_UNITS_UNKNOWN; else if (EQUAL(pszUnits, "INVALID")) return ECW_CELL_UNITS_INVALID; else { CPLError(CE_Warning, CPLE_AppDefined, "Unrecognized value for UNITS : %s", pszUnits); return ECW_CELL_UNITS_INVALID; } } /************************************************************************/ /* ECWGetColorInterpretationByName() */ /************************************************************************/ GDALColorInterp ECWGetColorInterpretationByName(const char *pszName) { if (EQUAL(pszName, NCS_BANDDESC_AllOpacity)) return GCI_AlphaBand; else if (EQUAL(pszName, NCS_BANDDESC_Blue)) return GCI_BlueBand; else if (EQUAL(pszName, NCS_BANDDESC_Green)) return GCI_GreenBand; else if (EQUAL(pszName, NCS_BANDDESC_Red)) return GCI_RedBand; else if (EQUAL(pszName, NCS_BANDDESC_Greyscale)) return GCI_GrayIndex; else if (EQUAL(pszName, NCS_BANDDESC_GreyscaleOpacity)) return GCI_AlphaBand; return GCI_Undefined; } /************************************************************************/ /* ECWGetColorInterpretationName() */ /************************************************************************/ const char* ECWGetColorInterpretationName(GDALColorInterp eColorInterpretation, int nBandNumber) { const char *result; switch (eColorInterpretation){ case GCI_AlphaBand: result = NCS_BANDDESC_AllOpacity; break; case GCI_GrayIndex: result = NCS_BANDDESC_Greyscale; break; case GCI_RedBand: case GCI_GreenBand: case GCI_BlueBand: result = GDALGetColorInterpretationName(eColorInterpretation); break; case GCI_Undefined: if (nBandNumber <=3){ if (nBandNumber == 0 ) { result = "Red"; }else if (nBandNumber == 1) { result = "Green"; }else if (nBandNumber == 2) { result = "Blue"; } } result = CPLSPrintf(NCS_BANDDESC_Band,nBandNumber + 1); break; default: result = CPLSPrintf(NCS_BANDDESC_Band,nBandNumber + 1); } return result; } /************************************************************************/ /* ECWGetColorSpaceName() */ /************************************************************************/ const char* ECWGetColorSpaceName(NCSFileColorSpace colorSpace) { switch (colorSpace) { case NCSCS_NONE: return "NONE"; break; case NCSCS_GREYSCALE: return "GREYSCALE"; break; case NCSCS_YUV: return "YUV"; break; case NCSCS_MULTIBAND: return "MULTIBAND"; break; case NCSCS_sRGB: return "RGB"; break; case NCSCS_YCbCr: return "YCbCr"; break; default: return "unrecognised"; } } /************************************************************************/ /* ECWTranslateFromCellSizeUnits() */ /************************************************************************/ const char* ECWTranslateFromCellSizeUnits(CellSizeUnits eUnits) { if (eUnits == ECW_CELL_UNITS_METERS) return "METERS"; else if (eUnits == ECW_CELL_UNITS_DEGREES) return "DEGREES"; else if (eUnits == ECW_CELL_UNITS_FEET) return "FEET"; else if (eUnits == ECW_CELL_UNITS_UNKNOWN) return "UNKNOWN"; else return "INVALID"; } #endif /* def FRMT_ecw */ /************************************************************************/ /* ECWInitialize() */ /* */ /* Initialize NCS library. We try to defer this as late as */ /* possible since de-initializing it seems to be expensive/slow */ /* on some system. */ /************************************************************************/ void ECWInitialize() { CPLMutexHolder oHolder( &hECWDatasetMutex ); if( bNCSInitialized ) return; #ifndef WIN32 NCSecwInit(); #endif bNCSInitialized = TRUE; /* -------------------------------------------------------------------- */ /* This will disable automatic conversion of YCbCr to RGB by */ /* the toolkit. */ /* -------------------------------------------------------------------- */ if( !CSLTestBoolean( CPLGetConfigOption("CONVERT_YCBCR_TO_RGB","YES") ) ) NCSecwSetConfig(NCSCFG_JP2_MANAGE_ICC, FALSE); #if ECWSDK_VERSION>= 50 NCSecwSetConfig(NCSCFG_ECWP_CLIENT_HTTP_USER_AGENT, "ECW GDAL Driver/" NCS_ECWJP2_FULL_VERSION_STRING_DOT_DEL); #endif /* -------------------------------------------------------------------- */ /* Initialize cache memory limit. Default is apparently 1/4 RAM. */ /* -------------------------------------------------------------------- */ const char *pszEcwCacheSize = CPLGetConfigOption("GDAL_ECW_CACHE_MAXMEM",NULL); if( pszEcwCacheSize == NULL ) pszEcwCacheSize = CPLGetConfigOption("ECW_CACHE_MAXMEM",NULL); if( pszEcwCacheSize != NULL ) NCSecwSetConfig(NCSCFG_CACHE_MAXMEM, (UINT32) atoi(pszEcwCacheSize) ); /* -------------------------------------------------------------------- */ /* Version 3.x and 4.x of the ECWJP2 SDK did not resolve datum and */ /* projection to EPSG code using internal mapping. */ /* Version 5.x do so we provide means to achieve old */ /* behaviour. */ /* -------------------------------------------------------------------- */ #if ECWSDK_VERSION >= 50 if( CSLTestBoolean( CPLGetConfigOption("ECW_DO_NOT_RESOLVE_DATUM_PROJECTION","NO") ) == TRUE) NCSecwSetConfig(NCSCFG_PROJECTION_FORMAT, NCS_PROJECTION_ERMAPPER_FORMAT); #endif /* -------------------------------------------------------------------- */ /* Allow configuration of a local cache based on configuration */ /* options. Setting the location turns things on. */ /* -------------------------------------------------------------------- */ const char *pszOpt; #if ECWSDK_VERSION >= 40 pszOpt = CPLGetConfigOption( "ECWP_CACHE_SIZE_MB", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_ECWP_CACHE_SIZE_MB, (INT32) atoi( pszOpt ) ); pszOpt = CPLGetConfigOption( "ECWP_CACHE_LOCATION", NULL ); if( pszOpt ) { NCSecwSetConfig( NCSCFG_ECWP_CACHE_LOCATION, pszOpt ); NCSecwSetConfig( NCSCFG_ECWP_CACHE_ENABLED, (BOOLEAN) TRUE ); } #endif /* -------------------------------------------------------------------- */ /* Various other configuration items. */ /* -------------------------------------------------------------------- */ pszOpt = CPLGetConfigOption( "ECWP_BLOCKING_TIME_MS", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_BLOCKING_TIME_MS, (NCSTimeStampMs) atoi(pszOpt) ); // I believe 10s means we wait for complete data back from // ECWP almost all the time which is good for our blocking model. pszOpt = CPLGetConfigOption( "ECWP_REFRESH_TIME_MS", "10000" ); if( pszOpt ) NCSecwSetConfig( NCSCFG_REFRESH_TIME_MS, (NCSTimeStampMs) atoi(pszOpt) ); pszOpt = CPLGetConfigOption( "ECW_TEXTURE_DITHER", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_TEXTURE_DITHER, (BOOLEAN) CSLTestBoolean( pszOpt ) ); pszOpt = CPLGetConfigOption( "ECW_FORCE_FILE_REOPEN", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_FORCE_FILE_REOPEN, (BOOLEAN) CSLTestBoolean( pszOpt ) ); pszOpt = CPLGetConfigOption( "ECW_CACHE_MAXOPEN", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_CACHE_MAXOPEN, (UINT32) atoi(pszOpt) ); #if ECWSDK_VERSION >= 40 pszOpt = CPLGetConfigOption( "ECW_AUTOGEN_J2I", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_JP2_AUTOGEN_J2I, (BOOLEAN) CSLTestBoolean( pszOpt ) ); pszOpt = CPLGetConfigOption( "ECW_OPTIMIZE_USE_NEAREST_NEIGHBOUR", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_OPTIMIZE_USE_NEAREST_NEIGHBOUR, (BOOLEAN) CSLTestBoolean( pszOpt ) ); pszOpt = CPLGetConfigOption( "ECW_RESILIENT_DECODING", NULL ); if( pszOpt ) NCSecwSetConfig( NCSCFG_RESILIENT_DECODING, (BOOLEAN) CSLTestBoolean( pszOpt ) ); #endif } /************************************************************************/ /* GDALDeregister_ECW() */ /************************************************************************/ void GDALDeregister_ECW( GDALDriver * ) { /* For unknown reason, this cleanup can take up to 3 seconds (see #3134) for SDK 3.3. */ /* Not worth it */ #if ECWSDK_VERSION >= 50 #ifndef WIN32 if( bNCSInitialized ) { bNCSInitialized = FALSE; if( !GDALIsInGlobalDestructor() ) { NCSecwShutdown(); } } #endif #endif if( hECWDatasetMutex != NULL ) { CPLDestroyMutex( hECWDatasetMutex ); hECWDatasetMutex = NULL; } } /************************************************************************/ /* GDALRegister_ECW() */ /************************************************************************/ /* Needed for v4.3 and v5.0 */ #if !defined(NCS_ECWSDK_VERSION_STRING) && defined(NCS_ECWJP2_VERSION_STRING) #define NCS_ECWSDK_VERSION_STRING NCS_ECWJP2_VERSION_STRING #endif void GDALRegister_ECW() { #ifdef FRMT_ecw GDALDriver *poDriver; if (! GDAL_CHECK_VERSION("ECW driver")) return; if( GDALGetDriverByName( "ECW" ) == NULL ) { poDriver = new GDALDriver(); poDriver->SetDescription( "ECW" ); CPLString osLongName = "ERDAS Compressed Wavelets (SDK "; #ifdef NCS_ECWSDK_VERSION_STRING osLongName += NCS_ECWSDK_VERSION_STRING; #else osLongName += "3.x"; #endif osLongName += ")"; poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, osLongName ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_ecw.html" ); poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "ecw" ); poDriver->pfnIdentify = ECWDataset::IdentifyECW; poDriver->pfnOpen = ECWDataset::OpenECW; poDriver->pfnUnloadDriver = GDALDeregister_ECW; #ifdef HAVE_COMPRESS // The create method does not work with SDK 3.3 ( crash in CNCSJP2FileView::WriteLineBIL() due to m_pFile being NULL ) #if ECWSDK_VERSION >= 50 poDriver->pfnCreate = ECWCreateECW; #endif poDriver->pfnCreateCopy = ECWCreateCopyECW; #if ECWSDK_VERSION >= 50 poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte UInt16" ); #else poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte" ); #endif poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList>" " <Option name='TARGET' type='float' description='Compression Percentage' />" " <Option name='PROJ' type='string' description='ECW Projection Name'/>" " <Option name='DATUM' type='string' description='ECW Datum Name' />" #if ECWSDK_VERSION < 40 " <Option name='LARGE_OK' type='boolean' description='Enable compressing 500+MB files'/>" #else " <Option name='ECW_ENCODE_KEY' type='string' description='OEM Compress Key from ERDAS.'/>" " <Option name='ECW_ENCODE_COMPANY' type='string' description='OEM Company Name.'/>" #endif #if ECWSDK_VERSION >= 50 " <Option name='ECW_FORMAT_VERSION' type='integer' description='ECW format version (2 or 3).' default='2'/>" #endif "</CreationOptionList>" ); #else /* In read-only mode, we support VirtualIO. This is not the case */ /* for ECWCreateCopyECW() */ poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); #endif GetGDALDriverManager()->RegisterDriver( poDriver ); } #endif /* def FRMT_ecw */ } /************************************************************************/ /* GDALRegister_ECW_JP2ECW() */ /* */ /* This function exists so that when built as a plugin, there */ /* is a function that will register both drivers. */ /************************************************************************/ void GDALRegister_ECW_JP2ECW() { GDALRegister_ECW(); GDALRegister_JP2ECW(); } /************************************************************************/ /* ECWDatasetOpenJPEG2000() */ /************************************************************************/ GDALDataset* ECWDatasetOpenJPEG2000(GDALOpenInfo* poOpenInfo) { return ECWDataset::OpenJPEG2000(poOpenInfo); } /************************************************************************/ /* GDALRegister_JP2ECW() */ /************************************************************************/ void GDALRegister_JP2ECW() { #ifdef FRMT_ecw GDALDriver *poDriver; if (! GDAL_CHECK_VERSION("JP2ECW driver")) return; if( GDALGetDriverByName( "JP2ECW" ) == NULL ) { poDriver = new GDALDriver(); poDriver->SetDescription( "JP2ECW" ); CPLString osLongName = "ERDAS JPEG2000 (SDK "; #ifdef NCS_ECWSDK_VERSION_STRING osLongName += NCS_ECWSDK_VERSION_STRING; #else osLongName += "3.x"; #endif osLongName += ")"; poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, osLongName ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_jp2ecw.html" ); poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "jp2" ); poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); poDriver->pfnIdentify = ECWDataset::IdentifyJPEG2000; poDriver->pfnOpen = ECWDataset::OpenJPEG2000; #ifdef HAVE_COMPRESS poDriver->pfnCreate = ECWCreateJPEG2000; poDriver->pfnCreateCopy = ECWCreateCopyJPEG2000; poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte UInt16 Int16 UInt32 Int32 Float32 Float64" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList>" " <Option name='TARGET' type='float' description='Compression Percentage' />" " <Option name='PROJ' type='string' description='ECW Projection Name'/>" " <Option name='DATUM' type='string' description='ECW Datum Name' />" " <Option name='UNITS' type='string-select' description='ECW Projection Units'>" " <Value>METERS</Value>" " <Value>FEET</Value>" " </Option>" #if ECWSDK_VERSION < 40 " <Option name='LARGE_OK' type='boolean' description='Enable compressing 500+MB files'/>" #else " <Option name='ECW_ENCODE_KEY' type='string' description='OEM Compress Key from ERDAS.'/>" " <Option name='ECW_ENCODE_COMPANY' type='string' description='OEM Company Name.'/>" #endif " <Option name='GeoJP2' type='boolean' description='defaults to ON'/>" " <Option name='GMLJP2' type='boolean' description='defaults to ON'/>" " <Option name='PROFILE' type='string-select'>" " <Value>BASELINE_0</Value>" " <Value>BASELINE_1</Value>" " <Value>BASELINE_2</Value>" " <Value>NPJE</Value>" " <Value>EPJE</Value>" " </Option>" " <Option name='PROGRESSION' type='string-select'>" " <Value>LRCP</Value>" " <Value>RLCP</Value>" " <Value>RPCL</Value>" " </Option>" " <Option name='CODESTREAM_ONLY' type='boolean' description='No JP2 wrapper'/>" " <Option name='LEVELS' type='int'/>" " <Option name='LAYERS' type='int'/>" " <Option name='PRECINCT_WIDTH' type='int'/>" " <Option name='PRECINCT_HEIGHT' type='int'/>" " <Option name='TILE_WIDTH' type='int'/>" " <Option name='TILE_HEIGHT' type='int'/>" " <Option name='INCLUDE_SOP' type='boolean'/>" " <Option name='INCLUDE_EPH' type='boolean'/>" " <Option name='DECOMPRESS_LAYERS' type='int'/>" " <Option name='DECOMPRESS_RECONSTRUCTION_PARAMETER' type='float'/>" "</CreationOptionList>" ); #endif GetGDALDriverManager()->RegisterDriver( poDriver ); } #endif /* def FRMT_ecw */ }
39.287964
180
0.486059
[ "object", "model", "transform" ]
f65de9b4de7e12294ca31ef2a667e20f0f0215ca
1,163
cpp
C++
DerydocaEngine/src/Helpers/StringUtils.cpp
Derydoca/derydocaengine
a9cdb71082fbb879d9448dc0c1a95581681d61f1
[ "BSD-3-Clause" ]
37
2018-05-21T15:21:26.000Z
2020-11-16T17:50:44.000Z
DerydocaEngine/src/Helpers/StringUtils.cpp
Derydoca/derydocaengine
a9cdb71082fbb879d9448dc0c1a95581681d61f1
[ "BSD-3-Clause" ]
38
2018-03-09T23:57:07.000Z
2020-07-10T20:52:42.000Z
DerydocaEngine/src/Helpers/StringUtils.cpp
Derydoca/derydocaengine
a9cdb71082fbb879d9448dc0c1a95581681d61f1
[ "BSD-3-Clause" ]
5
2018-08-28T11:12:18.000Z
2019-09-05T09:30:41.000Z
#include "EnginePch.h" #include "Helpers/StringUtils.h" #include <algorithm> namespace DerydocaEngine { bool endsWith(std::string const& string, std::string const& suffix) { // If the suffix is longer than the string then there is no way it could end in that string if (suffix.length() > string.length()) { return false; } // Check each character in the suffix to see if it matches the source string's suffix size_t stringSuffixIndex = string.length() - suffix.length(); for (size_t i = 0; i < suffix.length(); i++) { if (string[stringSuffixIndex + i] != suffix[i]) { return false; } } // If no mismatch was found then the string contains the suffix return true; } std::string getFileExtension(std::string const& path) { auto p = std::filesystem::path(path); auto ext = p.extension(); if (ext.empty()) { return ""; } else { auto extStr = ext.string(); extStr = extStr.substr(1, extStr.length() - 1); toLower(extStr); return extStr; } } void toLower(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); }); } }
21.537037
103
0.647463
[ "transform" ]
f65fa4d3ef0810f0623fdd03b7c8b9463fe68755
11,676
hpp
C++
plugins/ibc_plugin/include/eosio/ibc_plugin/protocol.hpp
boscore/ibc_plugin_wax
945e98a8c82430299abc13dbf9634bb965731182
[ "MIT" ]
1
2021-04-03T14:50:46.000Z
2021-04-03T14:50:46.000Z
plugins/ibc_plugin/include/eosio/ibc_plugin/protocol.hpp
boscore/ibc_plugin_wax
945e98a8c82430299abc13dbf9634bb965731182
[ "MIT" ]
null
null
null
plugins/ibc_plugin/include/eosio/ibc_plugin/protocol.hpp
boscore/ibc_plugin_wax
945e98a8c82430299abc13dbf9634bb965731182
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in bos/LICENSE.txt */ #pragma once #include <eosio/chain/block.hpp> #include <eosio/chain/types.hpp> #include <chrono> namespace eosio { namespace ibc { using namespace chain; using namespace fc; static_assert(sizeof(std::chrono::system_clock::duration::rep) >= 8, "system_clock is expected to be at least 64 bits"); typedef std::chrono::system_clock::duration::rep tstamp; struct handshake_message { uint16_t network_version = 0; ///< incremental value above a computed base fc::sha256 chain_id; ///< used to identify chain fc::sha256 node_id; ///< used to identify peers and prevent self-connect chain::public_key_type key; ///< authentication key; may be a producer or peer key, or empty tstamp time; fc::sha256 token; ///< digest of time to prove we own the private key of the key above chain::signature_type sig; ///< signature for the digest string p2p_address; uint32_t last_irreversible_block_num = 0; block_id_type last_irreversible_block_id; uint32_t head_num = 0; block_id_type head_id; string os; string agent; int16_t generation; }; enum go_away_reason { no_reason, ///< no reason to go away self, ///< the connection is to itself duplicate, ///< the connection is redundant wrong_chain, ///< the peer's chain id doesn't match same_chain, ///< the connection is to same chain wrong_version, ///< the peer's network version doesn't match forked, ///< the peer's irreversible blocks are different unlinkable, ///< the peer sent a block we couldn't use bad_transaction, ///< the peer sent a transaction that failed verification validation, ///< the peer sent a block that failed validation benign_other, ///< reasons such as a timeout. not fatal but warrant resetting fatal_other, ///< a catch-all for errors we don't have discriminated authentication ///< peer failed authenicatio }; constexpr auto reason_str( go_away_reason rsn ) { switch (rsn ) { case no_reason : return "no reason"; case self : return "self connect"; case duplicate : return "duplicate"; case wrong_chain : return "wrong chain"; case same_chain : return "same chain"; case wrong_version : return "wrong version"; case forked : return "chain is forked"; case unlinkable : return "unlinkable block received"; case bad_transaction : return "bad transaction"; case validation : return "invalid block"; case authentication : return "authentication failure"; case fatal_other : return "some other failure"; case benign_other : return "some other non-fatal condition"; default : return "some crazy reason"; } } struct go_away_message { go_away_message (go_away_reason r = no_reason) : reason(r), node_id() {} go_away_reason reason; fc::sha256 node_id; ///< for duplicate notification }; struct time_message { tstamp org; //!< origin timestamp tstamp rec; //!< receive timestamp tstamp xmt; //!< transmit timestamp mutable tstamp dst; //!< destination timestamp }; enum contract_state { none, ///< contract has not deployed or account not exist deployed, ///< constract has deployed, but not initialized working, ///< constract has been initialized and in working state stoped ///< contract at non-active state }; constexpr auto contract_state_str( contract_state s ) { switch ( s ) { case none : return "none"; case deployed : return "deployed"; case working : return "working"; case stoped : return "stoped"; default : return "unknown"; } } /** * Abbreviated vocabulary description: * "lwc" means eosio light weight client * "ls" or "lwcls" means eosio light weight client last section in ibc.chain contract */ struct lwc_section_type { lwc_section_type():first_num(0),last_num(0),lib_num(0),first_id(),last_id(),lib_id(),valid(false){} uint32_t first_num; uint32_t last_num; uint32_t lib_num; block_id_type first_id; block_id_type last_id; block_id_type lib_id; bool valid; bool operator == ( lwc_section_type b ){ return first_num == b.first_num && last_num == b.last_num && lib_num == b.lib_num && first_id == b.first_id && last_id == b.last_id && lib_id == b.lib_id && valid == b.valid; } bool operator != ( lwc_section_type b ){ return !( *this == b ); } }; /** * this hearbeat message should broadcast every 3 seconds and when the lwcls has any update broadcast this too. * when received ibc_heartbeat_message, first, get all original transactions and cashconfirm transactions according to origtrxs and cashtrxs range info. * then, combine with new_producers_block_num, start to get block header for the mininum block number, to let it into lib of lwc section. * when required blocks enter the lib, push transactions of origtrxs and cashtrxs, */ typedef std::pair<uint64_t,uint64_t> range_type; struct ibc_heartbeat_message { ibc_heartbeat_message(): head_block_num(0),lib_block_num(0),ibc_chain_state(none),ibc_token_state(none),lwcls(), origtrxs_table_id_range(),cashtrxs_table_seq_num_range(),new_producers_block_num(0){} uint32_t head_block_num; uint32_t lib_block_num; contract_state ibc_chain_state; contract_state ibc_token_state; lwc_section_type lwcls; ///< lwc last section info, used under both dpos and pbft consensus eosio chains range_type origtrxs_table_id_range; range_type cashtrxs_table_seq_num_range; uint32_t new_producers_block_num; // the first new producers replacement range after lwcls's lib; }; /** * send when last section's first blcok number is 0 */ struct lwc_init_message { lwc_init_message():header(),active_schedule(),blockroot_merkle(){} signed_block_header header; producer_schedule_type active_schedule; incremental_merkle blockroot_merkle; }; struct lwc_section_request_message { lwc_section_request_message():start_block_num(0),end_block_num(0){} uint32_t start_block_num; uint32_t end_block_num; }; struct lwc_section_data_message { lwc_section_data_message():headers(),blockroot_merkle(){} std::vector<signed_block_header> headers; incremental_merkle blockroot_merkle; }; struct lwc_block_commits_request_message { lwc_block_commits_request_message():block_num(0){} uint32_t block_num; }; struct lwc_block_commits_data_message { lwc_block_commits_data_message():headers(),blockroot_merkle(),proof_data(),proof_type(){} std::vector<signed_block_header> headers; incremental_merkle blockroot_merkle; std::vector<char> proof_data; name proof_type; // (commit)pbft_commits or (checkpoint)pbft_checkpoints }; struct ibc_trx_rich_info { // used by local multi_index and ibc message uint64_t table_id; // same with id of origtrxs table or seq_num of cashtrxs table transaction_id_type trx_id; // redundant, for convenience std::vector<char> packed_trx_receipt; std::vector<digest_type> trx_merkle_path; uint32_t block_num; // redundant, for convenience std::vector<char> block_header; std::vector<digest_type> block_id_merkle_path; uint32_t anchor_block_num; }; struct ibc_trxs_request_message { ibc_trxs_request_message():table(),range(){} name table; range_type range; }; struct ibc_trxs_data_message { ibc_trxs_data_message():table(),trxs_rich_info(){} name table; std::vector<ibc_trx_rich_info> trxs_rich_info; }; struct ibc_block_merkle_path_request_message { ibc_block_merkle_path_request_message():table(),block_nums(),anchor_block_num(0){} name table; std::vector<uint32_t> block_nums; uint32_t anchor_block_num; }; struct ibc_block_merkle_path_data_message { ibc_block_merkle_path_data_message():table(),block_merkle_paths(),anchor_block_num(0){} name table; std::vector<std::pair<uint32_t, std::vector<digest_type>>> block_merkle_paths; uint32_t anchor_block_num; }; using ibc_message = static_variant< handshake_message, go_away_message, time_message, ibc_heartbeat_message, lwc_init_message, lwc_section_request_message, lwc_section_data_message, lwc_block_commits_request_message, lwc_block_commits_data_message, ibc_trxs_request_message, ibc_trxs_data_message, ibc_block_merkle_path_request_message, ibc_block_merkle_path_data_message >; } // namespace ibc } // namespace eosio FC_REFLECT( eosio::ibc::handshake_message, (network_version)(chain_id)(node_id)(key) (time)(token)(sig)(p2p_address) (last_irreversible_block_num)(last_irreversible_block_id) (head_num)(head_id) (os)(agent)(generation) ) FC_REFLECT( eosio::ibc::go_away_message, (reason)(node_id) ) FC_REFLECT( eosio::ibc::time_message, (org)(rec)(xmt)(dst) ) FC_REFLECT( eosio::ibc::lwc_section_type, (first_num)(last_num)(lib_num)(first_id)(last_id)(lib_id)(valid) ) FC_REFLECT( eosio::ibc::ibc_heartbeat_message, (head_block_num)(lib_block_num)(ibc_chain_state)(ibc_token_state) (lwcls)(origtrxs_table_id_range)(cashtrxs_table_seq_num_range)(new_producers_block_num) ) FC_REFLECT( eosio::ibc::lwc_init_message, (header)(active_schedule)(blockroot_merkle) ) FC_REFLECT( eosio::ibc::lwc_section_request_message, (start_block_num)(end_block_num) ) FC_REFLECT( eosio::ibc::lwc_section_data_message, (headers)(blockroot_merkle) ) FC_REFLECT( eosio::ibc::lwc_block_commits_request_message, (block_num) ) FC_REFLECT( eosio::ibc::lwc_block_commits_data_message, (headers)(blockroot_merkle)(proof_data)(proof_type) ) FC_REFLECT( eosio::ibc::ibc_trx_rich_info, (table_id)(trx_id)(packed_trx_receipt)(trx_merkle_path) (block_num)(block_header)(block_id_merkle_path)(anchor_block_num) ) FC_REFLECT( eosio::ibc::ibc_trxs_request_message, (table)(range) ) FC_REFLECT( eosio::ibc::ibc_trxs_data_message, (table)(trxs_rich_info) ) FC_REFLECT( eosio::ibc::ibc_block_merkle_path_request_message, (table)(block_nums)(anchor_block_num) ) FC_REFLECT( eosio::ibc::ibc_block_merkle_path_data_message, (table)(block_merkle_paths)(anchor_block_num) )
44.060377
155
0.641316
[ "vector" ]
f66079c8fcc43b7e90ac1534e49c3ef4a3bf8898
80,601
cpp
C++
programming/sampleProject/traderNormalLong.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
2
2020-12-10T02:05:29.000Z
2021-05-30T15:23:56.000Z
programming/sampleProject/traderNormalLong.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
null
null
null
programming/sampleProject/traderNormalLong.cpp
ljyang100/dataScience
ad2b243673c570c18d83ab1a0cd1bb4694c17eac
[ "MIT" ]
1
2020-04-21T11:18:18.000Z
2020-04-21T11:18:18.000Z
#include "traderNormalLong.h" void TraderNormalLong::TraderNormalLongEntryPoint() { //Sleep(10000); //***** Part I time_t nextHeartBeatPosition = time(0); int counter = 0; bool done = false; while (1) { std::chrono::high_resolution_clock::time_point now; bool b = true; try{ a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_timeDeque.size() < a.m_messageLimitPerSecond) { m_EC->reqPositions(); now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); done = true; } a.m_csTimeDeque.LeaveCriticalSection(); } if (done == true) break; else { Sleep(100); counter = counter + 1; } if (counter >a.m_traderParameters.maxTimeToWaitSendingMessage) { printf("***CS*** %s %d\n", __FILE__, __LINE__); } } //end of while(1) while (1) { bool b = true, break1 = false; try{ a.m_csPositionUpdateDoneLong.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_positionUpdateDoneLong) break1 = true; // I cannot break here because otherwise I will be always in the critical section. a.m_csPositionUpdateDoneLong.LeaveCriticalSection(); } if ((time(0) - nextHeartBeatPosition) >= 60 && time(0) != nextHeartBeatPosition) { printf(" I am waiting for position update for long client.\n"); nextHeartBeatPosition = time(0); //*****For position update, I cannot use non-blocking strategy to get out. Otherwise it may cause big diaster. For example, the app may keep opening repetitive positions. } if (break1) break; else Sleep(500); /// } //***** Part II counter = 0; done = false; while (1) { std::chrono::high_resolution_clock::time_point now; bool b = true; try{ a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_timeDeque.size() < a.m_messageLimitPerSecond) { m_EC->reqIds(1); //Note this reqIds has nothing to do with the reqId used all through my applications. Here the reqIs() requests an next valid orderId. Its correspondong EWrapper is nextValidId(). Also here I request only one orderId. now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); done = true; } a.m_csTimeDeque.LeaveCriticalSection(); } if (done == true) break; else { Sleep(100); counter = counter + 1; } if (counter >a.m_traderParameters.maxTimeToWaitSendingMessage) { printf("***CS*** %s %d\n", __FILE__, __LINE__); } } //end of while(1) bool c = false; while (1) //This part is a little bit overkill. { bool b = true; try{ a.m_csOrderIdReadyLong.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { c = a.m_orderIdReadyLong; a.m_csOrderIdReadyLong.LeaveCriticalSection(); } if (!c) Sleep(100); else break; } //***** Once run into here, the m_orderId has already been set in TraderEWrapper. //***** Part III Calculated some parameters used in this class. bool b = true; //***** Note the following m_csVectorS critical seciton is within that of m_traderStructureVector and thus is a nested critical section with the specific entering order. There is a nested critical section with opposite entering order in setup.cpp. However, there will be no deadlock because the trader.cpp and setup.cpp do not run simultaneously. try{ a.m_csVectorS.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { a.m_barIndexShift = a.m_VectorS[0][0].size() - a.m_wholeDayTradeDuration / a.m_bardurationS; //**** Note that m_wholeDayTradeDuration is already in units of seconds, same as m_bardurationS. a.m_csVectorS.LeaveCriticalSection(); } Sleep(5000); //**** For the position in other thread to be populated. //***** Part IV. The start of trade. time_t nextHeartbeat1 = time(0), nextHeartbeat2 = time(0), nextHeartbeat3 = time(0), nextHeartbeat4 = time(0), nextHeartbeat5 = time(0), lastDownloadTime = time(0), lastFileSavingTime = time(0); time_t heartBeat1 = time(0); //******* Because I may use part of IB accurate bars and part of my constructed bars to constructed even bigger bars, it might be dangerous to use IB bars because its volume is much bigger than mine and thus may overweight my bars in the big-bar construction. time_t lastMarketDataRequestTime = time(0); while (1) { Sleep(2000); //*****This should be OK for normal stock long-term trading. if (time(0) > a.m_initime && time(0) <= a.m_tradingEndTime) //**** When traderClientAlive = false or dataClientAlive = false, normally I don't have to do anything. In fact, I cannot do anything when client is inactive. { if (((time(0) - nextHeartbeat2) >= 20) && (time(0) != nextHeartbeat2)) //**** This might not be run if the loop below takes long time. { cleaning(); manualReset(); //***** Note this is with critical sections, see details in the function. a.unhandledSymbols(); nextHeartbeat2 = time(0); } if (m_openOrderCounter < 1) { //**** This branch guarantee that the trader vector will be populated by open orders at least once before trading. m_traderEWrapper.update_traderStructureVector_by_EWrappers(); //**** this function is with a lot of critical sections. So don't let it in a nested critical sections here. lastDownloadTime = time(0); m_openOrderCounter = m_openOrderCounter + 1; } else { if (((time(0) - a.m_initime) % a.m_traderParameters.timeBetweenReqOpenOrders == 0) && (time(0) != lastDownloadTime)) { m_traderEWrapper.update_traderStructureVector_by_EWrappers(); lastDownloadTime = time(0); } } m_numLoops = m_numLoops + 1; for (unsigned int reqId = 0; reqId < a.m_newtxtVector.size(); reqId++) { if (((time(0) - heartBeat1) >= 60) && (time(0) != heartBeat1)) { bool b = true; try{ a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << tempString << ":" << " hedge related current exposure is " << (a.m_traderVector.longBuy[0].totalLongValue + a.m_traderVector.shortSell[0].totalShortValue) << std::endl; printf("hedge related current exposure is %f. \n", a.m_traderVector.longBuy[0].totalLongValue + a.m_traderVector.shortSell[0].totalShortValue); remove(a.m_manuals_OLD.c_str()); rename(a.m_manuals_NEW.c_str(), a.m_manuals_OLD.c_str()); //**** rename new.txt to old.txt, but not the opposite. std::ofstream o_new(a.m_manuals_NEW.c_str(), std::ios::app); for (unsigned int reqId = 0; reqId < a.m_newtxtVector.size(); reqId++) { if (a.m_traderVector.longBuy[reqId].totalPosition < 0) { a.m_myfileLong << tempString << " A weird negative position " << a.m_traderVector.longBuy[reqId].totalPosition << " occurs for symbol " << a.m_newtxtVector[reqId] << std::endl; printf("%s: A weird negative position %d occurs in long client for symbol %s.\n", tempString.c_str(), a.m_traderVector.longBuy[reqId].totalPosition, a.m_newtxtVector[reqId].c_str()); } if (a.m_traderVector.shortSell[reqId].totalPosition > 0) { a.m_myfileLong << tempString << " A weird positive " << a.m_traderVector.shortSell[reqId].totalPosition << " occurs for symbol " << a.m_newtxtVector[reqId] << std::endl; printf("%s: A weird positive position %d occurs in Short client for symbol %s.\n", tempString.c_str(), a.m_traderVector.shortSell[reqId].totalPosition, a.m_newtxtVector[reqId].c_str()); } int totalPosition = 0; if (a.m_traderVector.longBuy[reqId].totalPosition > 0) totalPosition = a.m_traderVector.longBuy[reqId].totalPosition; else if (a.m_traderVector.shortSell[reqId].totalPosition < 0) totalPosition = a.m_traderVector.shortSell[reqId].totalPosition; // feeding back poision should be in the same client? if (totalPosition != 0) { o_new << a.m_newtxtVector[reqId] << ',' << a.m_traderVector.longBuy[reqId].stopLossLong << ',' << a.m_traderVector.shortSell[reqId].stopLossShort << ',' << a.m_traderVector.longBuy[reqId].algoString << ',' << a.m_traderVector.shortSell[reqId].algoString << ',' << totalPosition << std::endl; } } o_new.close(); //time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" //a.m_myfileLong << "At " << tempString << ":" << " manuals successfully written to a new file " << m_manuals_NEW << std::endl; a.m_csTraderVector.LeaveCriticalSection(); } heartBeat1 = time(0); } //***** The following sentence is for testing. m_numSymbolsPassed = m_numSymbolsPassed + 1; b = true; try{ a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { //****For testing. Do not delete, I need know the code is running. Similar to the market data. int timePassed = 120; if ((time(0) - nextHeartbeat3) > timePassed && time(0) != nextHeartbeat3) { double minutes = timePassed / 60; time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << "At " << tempString << ":" << " total number of Long modifications is " << m_numModifications << " and within last " << minutes << " minutes the app has calculated " << m_numSymbolsPassed << " symbols. " << std::endl; nextHeartbeat3 = time(0); m_numSymbolsPassed = 0; } //****End of for testing. if (a.m_traderVector.shortSell[reqId].opening || a.m_traderVector.shortBuy[reqId].closing || a.m_traderVector.shortSell[reqId].totalPosition < 0) { //******The purpose of this branch is to make sure that we will never simultaneously both long and short a symbol. cancelExistingLongBuyOrder(reqId, "There are short-related order or position.\n"); cancelExistingLongSellOrder(reqId, "There are short-related order or position.\n"); } else // shortRelated = false, meaning the specific symbol is not being shorted and is not with any short position. { if (a.m_traderVector.longBuy[reqId].opening) //***** Note in Normal case, opening = true always means a long opening order. { //***** Be careful, I cannot use the buySharesChanged=true as a condition to run modifyOrder(), because even shares not changed I still need run modifyOrder for the market price change. bool b = true; //***** Note here I used nested critical sections: csTraderSTructureVector first and csCurrentDataStructureVector second. I need always keep this ordering. Also note, it is not that nested critical sections always bad. try{ a.m_csCurrentDataStructureVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_currentDataStructureVector[reqId].bid > 0 && a.m_currentDataStructureVector[reqId].ask > 0 && a.m_currentDataStructureVector[reqId].last > 0 && a.m_currentDataStructureVector[reqId].close > 0 && a.m_currentDataStructureVector[reqId].open > 0 && a.m_currentDataStructureVector[reqId].high > 0 && a.m_currentDataStructureVector[reqId].low > 0) { if (((time(0) - a.m_traderVector.longBuy[reqId].lastModifiedTimeBuy) > 5) && (a.m_traderVector.longBuy[reqId].modifiedBuy == false)) { a.m_traderVector.longBuy[reqId].modifiedBuy = true; time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << "At " << tempString << ":" << " entryPoint: modifiedBuy is set to be true for symbol " << a.m_newtxtVector[reqId] << std::endl; printf("At %s, modifiedBuy is set to be true for symbol %s.\n", tempString.c_str(), a.m_newtxtVector[reqId].c_str()); a.m_traderVector.longBuy[reqId].lastModifiedTimeBuy = time(0); } if (a.m_traderVector.longBuy[reqId].modifiedBuy) { if (a.m_traderVector.longBuy[reqId].manualOrder == false && a.m_newtxtVector[reqId] != "SPY" && a.m_traderVector.longBuy[reqId].noBuyLong == false) modifyBuyOrder(reqId, a.m_currentDataStructureVector[reqId]); } } a.m_csCurrentDataStructureVector.LeaveCriticalSection(); } } // if (a.m_traderVector.longBuy[reqId].opening) else // a.m_traderVector.longBuy[reqId].opening = false. **** Note in Normal case, even opening = false, it does not means closing = true. For the first half orders, opening can be either true or false, but false does not means closing = true. { bool b = true; //***** Note here I used nested critical sections: csTraderSTructureVector first and csCurrentDataStructureVector second. I need always keep this ordering. Also note, it is not that nested critical sections always bad. try{ a.m_csCurrentDataStructureVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_currentDataStructureVector[reqId].bid > 0 && a.m_currentDataStructureVector[reqId].ask > 0 && a.m_currentDataStructureVector[reqId].last > 0 && a.m_currentDataStructureVector[reqId].close > 0 && a.m_currentDataStructureVector[reqId].open > 0 && a.m_currentDataStructureVector[reqId].high > 0 && a.m_currentDataStructureVector[reqId].low > 0) { if ( a.m_traderVector.longBuy[reqId].manualOrder == false && a.m_newtxtVector[reqId] != "SPY" && a.m_traderVector.longBuy[reqId].noBuyLong == false) //****This make sure buy and sell order will never co-exist. Note I cannot use .closing == false because closing = true will not be set when the selling order is fully filled at once, without partial fill. { if (a.m_traderParameters.dayTrading == true) { if (time(0) <= (a.m_initime + a.m_traderParameters.timeShiftToOpenOrder)) createBuyOrder(reqId, a.m_currentDataStructureVector[reqId]); } else createBuyOrder(reqId, a.m_currentDataStructureVector[reqId]); } } a.m_csCurrentDataStructureVector.LeaveCriticalSection(); } } // end of !a.m_traderVector.longBuy[reqId].opening. //****************************************************** //****************************************************** ////For selling orders if (a.m_traderVector.longSell[reqId].closing) { bool timeOK = (time(0) > a.m_traderVector.longBuy[reqId].positionUpdatedTime) && ((time(0) - a.m_traderVector.longBuy[reqId].positionUpdatedTime) < a.m_traderParameters.timeBetweenReqOpenOrders); if (timeOK) //***** I request position every 20 seconds. { if (a.m_traderVector.longBuy[reqId].totalPosition < (int) a.m_traderVector.longSell[reqId].sellingShares) { if (!a.m_traderVector.longSell[reqId].cancelling) { if (a.m_traderVector.longSell[reqId].orderId > 0) { a.m_traderVector.longSell[reqId].totalCancellationsSell = a.m_traderVector.longSell[reqId].totalCancellationsSell + 1; cancelExistingLongSellOrder(reqId, " A long sell order is cancelled because totalPositoin is less than .sellingShares"); a.m_traderVector.longSell[reqId].cancelling = true; } } } } bool b = true; //***** Note here I used nested critical sections: csTraderSTructureVector first and csCurrentDataStructureVector second. I need always keep this ordering. Also note, it is not that nested critical sections always bad. try{ a.m_csCurrentDataStructureVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_currentDataStructureVector[reqId].bid > 0 && a.m_currentDataStructureVector[reqId].ask > 0 && a.m_currentDataStructureVector[reqId].last > 0 && a.m_currentDataStructureVector[reqId].close > 0 && a.m_currentDataStructureVector[reqId].open > 0 && a.m_currentDataStructureVector[reqId].high > 0 && a.m_currentDataStructureVector[reqId].low > 0) { //****This gurantee that any order might be scanned once within 5 seconds even if modifiedSell is wrongly set to be false for a long time elsewhere. if ((time(0) - a.m_traderVector.longSell[reqId].lastModifiedTimeSell) > 5 && a.m_traderVector.longSell[reqId].modifiedSell == false) { a.m_traderVector.longSell[reqId].modifiedSell = true; time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << "At " << tempString << ":" << " entryPoint: modifiedSell is set to be true for symbol " << a.m_newtxtVector[reqId] << std::endl; printf("At %s, modifiedSell is set to be true for symbol %s.\n", tempString.c_str(), a.m_newtxtVector[reqId].c_str()); a.m_traderVector.longSell[reqId].lastModifiedTimeSell = time(0); } if (a.m_traderVector.longSell[reqId].modifiedSell) { if (a.m_traderVector.longSell[reqId].manualOrder == false ) //****First condition makes sure buy and sell order will never co-exist. { if (a.m_traderVector.longBuy[reqId].averageCost > 0 && a.m_traderVector.longBuy[reqId].totalPosition > 0 && a.m_newtxtVector[reqId] != "SPY") modifySellOrder(reqId, a.m_currentDataStructureVector[reqId]); } } } a.m_csCurrentDataStructureVector.LeaveCriticalSection(); } } //end of a.m_traderVector.longSell[reqId].closing else // { //**** For shoring case, I must be make sure there are no any long open order and long positions. bool b = true; //***** Note here I used nested critical sections: csTraderSTructureVector first and csCurrentDataStructureVector second. I need always keep this ordering. Also note, it is not that nested critical sections always bad. try{ a.m_csCurrentDataStructureVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_currentDataStructureVector[reqId].bid > 0 && a.m_currentDataStructureVector[reqId].ask > 0 && a.m_currentDataStructureVector[reqId].last > 0 && a.m_currentDataStructureVector[reqId].close > 0 && a.m_currentDataStructureVector[reqId].open > 0 && a.m_currentDataStructureVector[reqId].high > 0 && a.m_currentDataStructureVector[reqId].low > 0) { if (a.m_traderVector.longBuy[reqId].averageCost > 0 && a.m_traderVector.longBuy[reqId].totalPosition > 0) { if (a.m_traderVector.longSell[reqId].manualOrder == false && a.m_newtxtVector[reqId] != "SPY") //****This make sure buy and sell order will never co-exist. createSellOrder(reqId, a.m_currentDataStructureVector[reqId]); //**** There must be shares to sell because .totalPosition > 0 is checked above. } } a.m_csCurrentDataStructureVector.LeaveCriticalSection(); } } // end of // !a.m_traderVector.longSell[reqId].closing //***** Note the database query above must be within the critical section. } //End of not short-related. a.m_csTraderVector.LeaveCriticalSection(); } //end of trader critical section. } //for (int reqId = 0; reqId < a.m_newtxtVector.size(); reqId++) } //if time is within the trading session else if (time(0) < a.m_initime) { Sleep(1000); //**** Without the following sentences, then if we had an long-term internet disconnection, then the app will, e.g. requrest too many open orders when internect restored. nextHeartbeat1 = time(0); nextHeartbeat2 = time(0); nextHeartbeat3 = time(0); } else if (time(0) > (a.m_tradingEndTime + 90)) //Currently the m_endTime + 90 = 1:00pm + 75 seconds. { time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" if (remove(a.m_manuals_OLD.c_str()) != 0) { printf("Error deleting file %s.\n", a.m_manuals_OLD.c_str()); a.m_myfileLong << "At " << tempString << ":" << " Error deleting file " << a.m_manuals_OLD << std::endl; } else { printf("File %s successfully deleted", a.m_manuals_OLD.c_str()); a.m_myfileLong << "At " << tempString << ":" << " File " << a.m_manuals_OLD << " successfully deleted " << std::endl; } int file_result; file_result = rename(a.m_manuals_NEW.c_str(), a.m_manuals_OLD.c_str()); //**** rename new.txt to old.txt, but not the opposite. if (file_result == 0) { printf("File name successfully changed from %s to %s.\n", a.m_manuals_NEW.c_str(), a.m_manuals_OLD.c_str()); a.m_myfileLong << "At " << tempString << ":" << " File name sucessfully changed from " << a.m_manuals_NEW << " to " << a.m_manuals_OLD << std::endl; } else { printf("Error occured when changing file name from %s to %s.\n", a.m_manuals_NEW.c_str(), a.m_manuals_OLD.c_str()); a.m_myfileLong << "At " << tempString << ":" << " Error occured when changing file name from " << a.m_manuals_NEW << " to " << a.m_manuals_OLD << std::endl; } std::ofstream o_new(a.m_manuals_NEW.c_str(), std::ios::app); for (unsigned int reqId = 0; reqId < a.m_newtxtVector.size(); reqId++) { bool b = true; try{ a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { int totalPosition = 0; if (a.m_traderVector.longBuy[reqId].totalPosition > 0) totalPosition = a.m_traderVector.longBuy[reqId].totalPosition; else if (a.m_traderVector.shortSell[reqId].totalPosition < 0) totalPosition = a.m_traderVector.shortSell[reqId].totalPosition; if (totalPosition == 0 && a.m_traderVector.longBuy[reqId].opening == true) cancelExistingLongBuyOrder(reqId, "Cancel Long opening order before session close"); if (totalPosition != 0) { o_new << a.m_newtxtVector[reqId] << ',' << a.m_traderVector.longBuy[reqId].stopLossLong << ',' << a.m_traderVector.shortSell[reqId].stopLossShort << ',' << a.m_traderVector.longBuy[reqId].algoString << ',' << a.m_traderVector.shortSell[reqId].algoString << ',' << totalPosition << std::endl; } a.m_csTraderVector.LeaveCriticalSection(); } } o_new.close(); a.m_myfileLong << "At " << tempString << ":" << " manuals successfully written to a new file " << a.m_manuals_NEW << std::endl; Sleep(25000); //**** Wait the short client to cancel the opening order. exit(0);//***** Note I cannot have a exit(0) in the same place of short client. See the comments there. //**** Avoid using exit(0) as it may cause memory leaks if not properly used. } } //while(1) loop. } void TraderNormalLong::cancelExistingLongBuyOrder(unsigned int &reqId, std::string reasonToCancel) { if (!a.m_traderVector.longBuy[reqId].cancelling) { if (a.m_traderVector.longBuy[reqId].orderId > 0 && a.m_traderVector.longBuy[reqId].opening == true) { cancelOrder(a.m_traderVector.longBuy[reqId].orderId); //**** once arrived here, we already know that book kepts .orderId is not same as the incoming orderId. Otherwise it will be handled in the branch before. a.m_traderVector.longBuy[reqId].cancelling = true; time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << "At " << tempString << ":" << " A longBuy order is being cancelled because: " << reasonToCancel << " for symbol " << a.m_newtxtVector[reqId] << " with orderId " << a.m_traderVector.longBuy[reqId].orderId << std::endl; printf("At %s, A longBuy order is being cancelled because: %s for symbol %s.\n", tempString.c_str(), reasonToCancel.c_str(), a.m_newtxtVector[reqId].c_str()); } } } void TraderNormalLong::cancelExistingLongSellOrder(unsigned int &reqId, std::string reasonToCancel) { if (!a.m_traderVector.longSell[reqId].cancelling) { if (a.m_traderVector.longSell[reqId].orderId > 0 && a.m_traderVector.longSell[reqId].closing == true) { cancelOrder(a.m_traderVector.longSell[reqId].orderId); //**** once arrived here, we already know that book kepts .orderId is not same as the incoming orderId. Otherwise it will be handled in the branch before. a.m_traderVector.longSell[reqId].cancelling = true; time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << "At " << tempString << ":" << " A longSell order is being cancelled because: " << reasonToCancel << " for symbol " << a.m_newtxtVector[reqId] << " with orderId " << a.m_traderVector.longSell[reqId].orderId << std::endl; printf("At %s, A longSell order is being cancelled because: %s for symbol %s.\n", tempString.c_str(), reasonToCancel.c_str(), a.m_newtxtVector[reqId].c_str()); } } } void TraderNormalLong::cancelOrder(OrderId &orderId) { std::chrono::high_resolution_clock::time_point now; int counter = 0; bool done = false; while (1) { bool b = true; try{ a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_timeDeque.size() < a.m_messageLimitPerSecond) // Need a variable even thought currently it is always 50. Otherwise, hard-coding in various places is dangerous because will forget this later. { m_EC->cancelOrder(orderId); m_numModifications = m_numModifications + 1; now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); done = true; } a.m_csTimeDeque.LeaveCriticalSection(); } if (done == true) break; else { Sleep(100); counter = counter + 1; } if (counter >a.m_traderParameters.maxTimeToWaitSendingMessage) { printf("***CS*** %s %d\n", __FILE__, __LINE__); } } } void TraderNormalLong::createBuyOrder(unsigned int &reqId, CurrentDataStructure &currentDataStructure) { unsigned int i = a.m_traderParameters.i_periodIndex; a.m_traderVector.longBuy[reqId].algoString = "whiteSwanLong"; m_cfs.commonCode(reqId, i, currentDataStructure, a.m_traderVector.longBuy[reqId].algoString, "OPEN"); if (a.m_traderVector.longBuy[reqId].longHedgeOK){ if (a.m_traderVector.longBuy[reqId].basicOpen){ if (a.m_traderVector.longBuy[reqId].relevantShares > 0 && a.m_traderVector.longBuy[reqId].calculatedBid > 0){ if (a.m_traderVector.longSell[reqId].myAsk > 0) a.m_traderVector.longBuy[reqId].calculatedBid = min(a.m_traderVector.longBuy[reqId].calculatedBid, (a.m_traderVector.longSell[reqId].myAsk - 2 * a.m_traderVector.longBuy[reqId].minPriceVariation)); int lmtPrice100IntNew = int(ceil(a.m_traderVector.longBuy[reqId].calculatedBid * 100 - 0.499)); //Note the parameter 0.499 and the ceil function achieve the rounding ( using 0.5 as separating line). Here I also multiply the price by 100 so as to make the mininum 0.01 dollar to be 1 dollar and can be represented by an integer. int priceLastDigit = lmtPrice100IntNew % 10; int minPriceVariationLastDigit = (int(a.m_traderVector.longBuy[reqId].minPriceVariation * 100)) % 10; if (minPriceVariationLastDigit == 5){ if (priceLastDigit >= 5) lmtPrice100IntNew = lmtPrice100IntNew - priceLastDigit + 5; else lmtPrice100IntNew = lmtPrice100IntNew - priceLastDigit; //**** For buying, always try to lower the calcuatedBid. This is to avoid it will be bigger than .myAsk } a.m_traderVector.longBuy[reqId].calculatedBid = (double)lmtPrice100IntNew / 100; if (time(0) - a.m_traderVector.longBuy[reqId].lastFilledLongTime > a.m_traderParameters.timeBetweenReqOpenOrders){ placeOrder(reqId, i, "BUY", "LMT", a.m_traderVector.longBuy[reqId].relevantShares, a.m_traderVector.longBuy[reqId].calculatedBid); //**** The output sentence below must be after placeOrder() in order for .orderId etc. to be initialized. time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Create buy order for symbol " << a.m_newtxtVector[reqId] << " with price: shares: totalPosition " << a.m_traderVector.longBuy[reqId].myBid << ":" << a.m_traderVector.longBuy[reqId].buyingShares << ":" << a.m_traderVector.longBuy[reqId].totalPosition << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longBuy[reqId].conditions[0] << ":" << a.m_traderVector.longBuy[reqId].conditions[1] << ":" << a.m_traderVector.longBuy[reqId].conditions[2] << ":" << a.m_traderVector.longBuy[reqId].conditions[3] << ":" << a.m_traderVector.longBuy[reqId].conditions[4] << ":" << a.m_traderVector.longBuy[reqId].conditions[5] << ":" << a.m_traderVector.longBuy[reqId].conditions[6] << ":" << a.m_traderVector.longBuy[reqId].conditions[7] << ":" << a.m_traderVector.longBuy[reqId].conditions[8] << ":" << a.m_traderVector.longBuy[reqId].conditions[9] << std::endl; std::cout << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Create buy order for symbol " << a.m_newtxtVector[reqId] << " with price: shares: totalPosition " << a.m_traderVector.longBuy[reqId].myBid << ":" << a.m_traderVector.longBuy[reqId].buyingShares << ":" << a.m_traderVector.longBuy[reqId].totalPosition << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longBuy[reqId].conditions[0] << ":" << a.m_traderVector.longBuy[reqId].conditions[1] << ":" << a.m_traderVector.longBuy[reqId].conditions[2] << ":" << a.m_traderVector.longBuy[reqId].conditions[3] << ":" << a.m_traderVector.longBuy[reqId].conditions[4] << ":" << a.m_traderVector.longBuy[reqId].conditions[5] << ":" << a.m_traderVector.longBuy[reqId].conditions[6] << ":" << a.m_traderVector.longBuy[reqId].conditions[7] << ":" << a.m_traderVector.longBuy[reqId].conditions[8] << ":" << a.m_traderVector.longBuy[reqId].conditions[9] << std::endl; } } } } } void TraderNormalLong::modifyBuyOrder(unsigned int &reqId, CurrentDataStructure &currentDataStructure) { unsigned int i = a.m_traderParameters.i_periodIndex; a.m_traderVector.longBuy[reqId].algoString = "whiteSwanLong"; m_cfs.commonCode(reqId, i, currentDataStructure, a.m_traderVector.longBuy[reqId].algoString, "OPEN"); if (a.m_traderVector.longBuy[reqId].manualOrder) cancelExistingLongBuyOrder(reqId, " Long: order is cancelled because manualOrder = true. "); else{ if (!a.m_traderVector.longBuy[reqId].longHedgeOK) cancelExistingLongBuyOrder(reqId, " Long: order is cancelled because longHedgeOK = false. "); else { if (!a.m_traderVector.longBuy[reqId].basicOpen) cancelExistingLongBuyOrder(reqId, " Long: order is cancelled because basicOpen = false. "); else { if (a.m_traderVector.longBuy[reqId].calculatedBid > currentDataStructure.ask){ cancelExistingLongBuyOrder(reqId, " Long: order is cancelled because myBid is even bigger than ASK. "); if (a.m_traderVector.longBuy[reqId].relevantShares <= 0) cancelExistingLongBuyOrder(reqId, " Long: order is cancelled because relevantShares <= 0. "); else { if ((a.m_traderVector.longSell[reqId].myAsk + a.m_traderVector.longBuy[reqId].minPriceVariation) <= a.m_traderVector.longBuy[reqId].myBid && a.m_traderVector.longSell[reqId].myAsk > 0 && a.m_traderVector.longBuy[reqId].myBid > 0) if (!a.m_traderVector.longBuy[reqId].cancelling) if (a.m_traderVector.longBuy[reqId].orderId > 0) cancelExistingLongBuyOrder(reqId, " Long: I need cancel the long buy order because possible cross order "); if (a.m_traderVector.longSell[reqId].myAsk > 0) a.m_traderVector.longBuy[reqId].calculatedBid = min(a.m_traderVector.longBuy[reqId].calculatedBid, (a.m_traderVector.longSell[reqId].myAsk - 2 * a.m_traderVector.longBuy[reqId].minPriceVariation)); int lmtPrice100IntNew = int(ceil(a.m_traderVector.longBuy[reqId].calculatedBid * 100 - 0.499)); //Note the parameter 0.499 and the ceil function achieve the rounding ( using 0.5 as separating line). Here I also multiply the price by 100 so as to make the mininum 0.01 dollar to be 1 dollar and can be represented by an integer. int priceLastDigit = lmtPrice100IntNew % 10; int minPriceVariationLastDigit = (int(a.m_traderVector.longBuy[reqId].minPriceVariation * 100)) % 10; if (minPriceVariationLastDigit == 5) { if (priceLastDigit >= 5) lmtPrice100IntNew = lmtPrice100IntNew - priceLastDigit + 5; else lmtPrice100IntNew = lmtPrice100IntNew - priceLastDigit; //**** For buying, always try to lower the calcuatedBid. This is to avoid it will be bigger than .myAsk } a.m_traderVector.longBuy[reqId].calculatedBid = (double)lmtPrice100IntNew / 100; bool sharesChanged = false, priceChanged = false; if (a.m_traderVector.longBuy[reqId].buyingShares > 0) { double shareDifferenceRatio = ((double)a.m_traderVector.longBuy[reqId].relevantShares - (double)a.m_traderVector.longBuy[reqId].buyingShares) / (double)a.m_traderVector.longBuy[reqId].buyingShares; if (abs(shareDifferenceRatio) > a.m_traderParameters.sharesUncertainty) sharesChanged = true; } priceChanged = a.m_traderVector.longBuy[reqId].priceChanged && (abs(a.m_traderVector.longBuy[reqId].myBid - a.m_traderVector.longBuy[reqId].calculatedBid) >= a.m_traderVector.longBuy[reqId].minPriceVariation); if (sharesChanged || priceChanged) { int oldShares = a.m_traderVector.longBuy[reqId].buyingShares; double oldPrice = a.m_traderVector.longBuy[reqId].myBid; a.m_traderVector.longBuy[reqId].modifiedBuy = false; //**** Although it is not right to give an "advanced" value (see notes elsewhere), this one is OK. Even I cannot set it true by accknowledgement, the app will set it to true after a pre-set time duration. a.m_traderVector.longBuy[reqId].lastModifiedTimeBuy = time(0); //**** I need put one here in case there is no response. a.m_traderVector.longBuy[reqId].currentTotalBuy = a.m_traderVector.longBuy[reqId].relevantShares + a.m_traderVector.longBuy[reqId].filledBuy; a.m_traderVector.longBuy[reqId].buyingShares = a.m_traderVector.longBuy[reqId].relevantShares; if (a.m_traderVector.longBuy[reqId].currentTotalBuy > 0 && a.m_traderVector.longBuy[reqId].calculatedBid > 0) { modifyOrder_sub(reqId, "BUY", "LMT", a.m_traderVector.longBuy[reqId].currentTotalBuy, a.m_traderVector.longBuy[reqId].calculatedBid); //**** Here I change the price to calculatedBid even if the myBid price is not changed. Anyway, once arrived here, either price or shares need to change. CalculatedBid is better than .lmtPrice. a.m_traderVector.longBuy[reqId].numModifiedBuy = a.m_traderVector.longBuy[reqId].numModifiedBuy + 1; //**** The output sentence below must be after placeOrder() in order for .orderId etc. to be initialized. time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" std::cout << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Modify buy order for symbol " << a.m_newtxtVector[reqId] << " from old price:shares " << oldPrice << " : " << oldShares << " to " << a.m_traderVector.longBuy[reqId].calculatedBid << " : " << a.m_traderVector.longBuy[reqId].relevantShares << " with priceChanged:sharesChanged " << priceChanged << " : " << sharesChanged << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longBuy[reqId].conditions[0] << ":" << a.m_traderVector.longBuy[reqId].conditions[1] << ":" << a.m_traderVector.longBuy[reqId].conditions[2] << ":" << a.m_traderVector.longBuy[reqId].conditions[3] << ":" << a.m_traderVector.longBuy[reqId].conditions[4] << ":" << a.m_traderVector.longBuy[reqId].conditions[5] << ":" << a.m_traderVector.longBuy[reqId].conditions[6] << ":" << a.m_traderVector.longBuy[reqId].conditions[7] << ":" << a.m_traderVector.longBuy[reqId].conditions[8] << ":" << a.m_traderVector.longBuy[reqId].conditions[9] << std::endl; a.m_myfileLong << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Modify buy order for symbol " << a.m_newtxtVector[reqId] << " from old price:shares " << oldPrice << " : " << oldShares << " to " << a.m_traderVector.longBuy[reqId].calculatedBid << " : " << a.m_traderVector.longBuy[reqId].relevantShares << " with priceChanged:sharesChanged " << priceChanged << " : " << sharesChanged << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longBuy[reqId].conditions[0] << ":" << a.m_traderVector.longBuy[reqId].conditions[1] << ":" << a.m_traderVector.longBuy[reqId].conditions[2] << ":" << a.m_traderVector.longBuy[reqId].conditions[3] << ":" << a.m_traderVector.longBuy[reqId].conditions[4] << ":" << a.m_traderVector.longBuy[reqId].conditions[5] << ":" << a.m_traderVector.longBuy[reqId].conditions[6] << ":" << a.m_traderVector.longBuy[reqId].conditions[7] << ":" << a.m_traderVector.longBuy[reqId].conditions[8] << ":" << a.m_traderVector.longBuy[reqId].conditions[9] << std::endl; if (a.m_traderVector.longBuy[reqId].numModifiedBuy > a.m_traderParameters.maxModificationsAllowed) { a.m_traderVector.longBuy[reqId].noBuyLong = true; //**** This means I will not open a long order just after stopped out, unless I set noBuyLong to false manually during the session. a.m_myfileLong << tempString << " Long Buy: For " << a.m_newtxtVector[reqId] << " the number of modifications pass the limit and noBuyLong is set to false. " << std::endl; std::cout << tempString << " Long Buy: For " << a.m_newtxtVector[reqId] << " the number of modifications pass the limit and noBuyLong is set to false. " << std::endl; } } } // if (sharesChanged || priceChanged) } } } } } } void TraderNormalLong::createSellOrder(unsigned int &reqId, CurrentDataStructure &currentDataStructure) { unsigned int i = a.m_traderParameters.i_periodIndex; a.m_traderVector.longBuy[reqId].algoString = "whiteSwanLong"; m_cfs.commonCode(reqId, i, currentDataStructure, a.m_traderVector.longBuy[reqId].algoString, "CLOSE"); if (a.m_traderVector.longSell[reqId].basicClose) { if (a.m_traderVector.longBuy[reqId].myBid > 0) a.m_traderVector.longSell[reqId].calculatedAsk = max(a.m_traderVector.longSell[reqId].calculatedAsk, (a.m_traderVector.longBuy[reqId].myBid + 2 * a.m_traderVector.longSell[reqId].minPriceVariation)); int lmtPrice100IntNew = int(ceil(a.m_traderVector.longSell[reqId].calculatedAsk * 100 - 0.499)); //Note the parameter 0.499 and the ceil function achieve the rounding ( using 0.5 as separating line). Here I also multiply the price by 100 so as to make the mininum 0.01 dollar to be 1 dollar and can be represented by an integer. int priceLastDigit = lmtPrice100IntNew % 10; int minPriceVariationLastDigit = (int(a.m_traderVector.longSell[reqId].minPriceVariation * 100)) % 10; if (minPriceVariationLastDigit == 5) { if (priceLastDigit >= 5) lmtPrice100IntNew = lmtPrice100IntNew + (10 - priceLastDigit); else lmtPrice100IntNew = lmtPrice100IntNew - priceLastDigit + 5; //**** For buying, always try to lower the calcuatedBid. This is to avoid it will be bigger than .myAsk } a.m_traderVector.longSell[reqId].calculatedAsk = (double)lmtPrice100IntNew / 100; //**** This include the case of closeLongMid. //**** Once the final version of the following is fixed, apply it in the modifySellOrder, and also in the counterpart places in short client. if (a.m_traderParameters.dayTrading == true) { if (time(0) >= (a.m_initime + a.m_traderParameters.timeShiftToCloseOrder)) { if (currentDataStructure.ask - currentDataStructure.bid < a.m_traderVector.longSell[reqId].minPriceVariation * 1.5) a.m_traderVector.longSell[reqId].calculatedAsk = currentDataStructure.ask; else a.m_traderVector.longSell[reqId].calculatedAsk = (currentDataStructure.bid + currentDataStructure.ask) / 2; } } if (a.m_traderVector.longSell[reqId].calculatedAsk > 2 * a.m_traderVector.longSell[reqId].minPriceVariation) //**** Even .calculatedAsk is zero, the adjustment due to minPriceVariation may cause it to be a small positive number. Thus I require it to be bigger than 2*minPriceVariation. { placeOrder(reqId, i, "SELL", "LMT", a.m_traderVector.longSell[reqId].relevantShares, a.m_traderVector.longSell[reqId].calculatedAsk); //**** close when it is not good to reopen. Otherwise it will jerk away commissions. //**** The output sentence below must be after placeOrder() in order for .orderId etc. to be initialized. time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" std::cout << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Create sell order for symbol " << a.m_newtxtVector[reqId] << " with price: shares: totalPosition " << a.m_traderVector.longSell[reqId].myAsk << ":" << a.m_traderVector.longSell[reqId].sellingShares << ":" << a.m_traderVector.longBuy[reqId].totalPosition << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longSell[reqId].conditions[0] << ":" << a.m_traderVector.longSell[reqId].conditions[1] << ":" << a.m_traderVector.longSell[reqId].conditions[2] << ":" << a.m_traderVector.longSell[reqId].conditions[3] << ":" << a.m_traderVector.longSell[reqId].conditions[4] << ":" << a.m_traderVector.longSell[reqId].conditions[5] << ":" << a.m_traderVector.longSell[reqId].conditions[6] << ":" << a.m_traderVector.longSell[reqId].conditions[7] << ":" << a.m_traderVector.longSell[reqId].conditions[8] << ":" << a.m_traderVector.longSell[reqId].conditions[9] << std::endl; a.m_myfileLong << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Create sell order for symbol " << a.m_newtxtVector[reqId] << " with price: shares: totalPosition " << a.m_traderVector.longSell[reqId].myAsk << ":" << a.m_traderVector.longSell[reqId].sellingShares << ":" << a.m_traderVector.longBuy[reqId].totalPosition << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longSell[reqId].conditions[0] << ":" << a.m_traderVector.longSell[reqId].conditions[1] << ":" << a.m_traderVector.longSell[reqId].conditions[2] << ":" << a.m_traderVector.longSell[reqId].conditions[3] << ":" << a.m_traderVector.longSell[reqId].conditions[4] << ":" << a.m_traderVector.longSell[reqId].conditions[5] << ":" << a.m_traderVector.longSell[reqId].conditions[6] << ":" << a.m_traderVector.longSell[reqId].conditions[7] << ":" << a.m_traderVector.longSell[reqId].conditions[8] << ":" << a.m_traderVector.longSell[reqId].conditions[9] << std::endl; } } } void TraderNormalLong::modifySellOrder(unsigned int &reqId, CurrentDataStructure &currentDataStructure) { //**** changed to favorable, modify, change to non-favorable, not modify. unsigned int i = a.m_traderParameters.i_periodIndex; a.m_traderVector.longBuy[reqId].algoString = "whiteSwanLong"; m_cfs.commonCode(reqId, i, currentDataStructure, a.m_traderVector.longBuy[reqId].algoString, "CLOSE"); if (a.m_traderVector.longSell[reqId].manualOrder) cancelExistingLongSellOrder(reqId, " Long: modifySellOrder, manualOrder = true "); { if (a.m_traderVector.longSell[reqId].relevantShares <= 0) cancelExistingLongSellOrder(reqId, " Long: modifySellOrder, relevantShares <= 0 "); else //relevantShares > 0 { if (a.m_traderVector.longSell[reqId].basicClose == false) //**** When condition gets better, the app will cancel the order. cancelExistingLongSellOrder(reqId, " Long: modifySellOrder, a.m_traderVector.longSell[reqId].basicClos == false "); else { if ((a.m_traderVector.longSell[reqId].myAsk + a.m_traderVector.longSell[reqId].minPriceVariation) <= a.m_traderVector.longBuy[reqId].myBid && a.m_traderVector.longSell[reqId].myAsk > 0 && a.m_traderVector.longBuy[reqId].myBid > 0) if (!a.m_traderVector.longSell[reqId].cancelling) if (a.m_traderVector.longSell[reqId].orderId > 0) cancelExistingLongSellOrder(reqId, " Long: I need cancel the long sell order because possible cross order "); if (a.m_traderVector.longBuy[reqId].myBid > 0) a.m_traderVector.longSell[reqId].calculatedAsk = max(a.m_traderVector.longSell[reqId].calculatedAsk, (a.m_traderVector.longBuy[reqId].myBid + 2 * a.m_traderVector.longSell[reqId].minPriceVariation)); int lmtPrice100IntNew = int(ceil(a.m_traderVector.longSell[reqId].calculatedAsk * 100 - 0.499)); //Note the parameter 0.499 and the ceil function achieve the rounding ( using 0.5 as separating line). Here I also multiply the price by 100 so as to make the mininum 0.01 dollar to be 1 dollar and can be represented by an integer. int priceLastDigit = lmtPrice100IntNew % 10; int minPriceVariationLastDigit = (int(a.m_traderVector.longSell[reqId].minPriceVariation * 100)) % 10; if (minPriceVariationLastDigit == 5) { if (priceLastDigit >= 5) lmtPrice100IntNew = lmtPrice100IntNew + (10 - priceLastDigit); else lmtPrice100IntNew = lmtPrice100IntNew - priceLastDigit + 5; //**** For buying, always try to lower the calcuatedBid. This is to avoid it will be bigger than .myAsk } a.m_traderVector.longSell[reqId].calculatedAsk = (double)lmtPrice100IntNew / 100; //**** This include the case of closeLongMid. bool priceChanged = false, sharesChanged = false; if (a.m_traderVector.longSell[reqId].sellingShares > 0) { double shareDifferenceRatio = ((double)a.m_traderVector.longSell[reqId].relevantShares - (double)a.m_traderVector.longSell[reqId].sellingShares) / (double)a.m_traderVector.longSell[reqId].sellingShares; if (abs(shareDifferenceRatio) > a.m_traderParameters.sharesUncertainty) sharesChanged = true; } priceChanged = a.m_traderVector.longSell[reqId].priceChanged && (abs(a.m_traderVector.longSell[reqId].myAsk - a.m_traderVector.longSell[reqId].calculatedAsk) >= a.m_traderVector.longSell[reqId].minPriceVariation); if (sharesChanged || priceChanged) { if (a.m_traderVector.longSell[reqId].calculatedAsk > 2 * a.m_traderVector.longSell[reqId].minPriceVariation) { int oldShares = a.m_traderVector.longSell[reqId].sellingShares; double oldPrice = a.m_traderVector.longSell[reqId].myAsk; a.m_traderVector.longSell[reqId].modifiedSell = false; //This is fine although it is an "advanced" value, see notes in modifyBuy(). a.m_traderVector.longSell[reqId].lastModifiedTimeSell = time(0); a.m_traderVector.longSell[reqId].currentTotalSell = a.m_traderVector.longSell[reqId].relevantShares + a.m_traderVector.longSell[reqId].filledSell; a.m_traderVector.longSell[reqId].sellingShares = a.m_traderVector.longSell[reqId].relevantShares; if (a.m_traderVector.longSell[reqId].currentTotalSell > 0 && a.m_traderVector.longSell[reqId].calculatedAsk > 0) { time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" modifyOrder_sub(reqId, "SELL", "LMT", a.m_traderVector.longSell[reqId].currentTotalSell, a.m_traderVector.longSell[reqId].calculatedAsk); //****calculatedAsk is assigned a value in the beginning of this function. a.m_traderVector.longSell[reqId].numModifiedSell = a.m_traderVector.longSell[reqId].numModifiedSell + 1; //**** The output sentence below must be after placeOrder() in order for .orderId etc. to be initialized. std::cout << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Modify sell order for symbol " << a.m_newtxtVector[reqId] << " from old price:shares " << oldPrice << " : " << oldShares << " to " << a.m_traderVector.longSell[reqId].calculatedAsk << " : " << a.m_traderVector.longSell[reqId].relevantShares << " with priceChanged:sharesChanged " << priceChanged << " : " << sharesChanged << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longSell[reqId].conditions[0] << ":" << a.m_traderVector.longSell[reqId].conditions[1] << ":" << a.m_traderVector.longSell[reqId].conditions[2] << ":" << a.m_traderVector.longSell[reqId].conditions[3] << ":" << a.m_traderVector.longSell[reqId].conditions[4] << ":" << a.m_traderVector.longSell[reqId].conditions[5] << ":" << a.m_traderVector.longSell[reqId].conditions[6] << ":" << a.m_traderVector.longSell[reqId].conditions[7] << ":" << a.m_traderVector.longSell[reqId].conditions[8] << ":" << a.m_traderVector.longSell[reqId].conditions[9] << std::endl; a.m_myfileLong << tempString << ":" << a.m_traderVector.longBuy[reqId].algoString << " Long: Modify sell order for symbol " << a.m_newtxtVector[reqId] << " from old price:shares " << oldPrice << " : " << oldShares << " to " << a.m_traderVector.longSell[reqId].calculatedAsk << " : " << a.m_traderVector.longSell[reqId].relevantShares << " with priceChanged:sharesChanged " << priceChanged << " : " << sharesChanged << " and BID:ASK " << a.m_currentDataStructureVector[reqId].bid << ":" << a.m_currentDataStructureVector[reqId].ask << " and conditions: " << a.m_traderVector.longSell[reqId].conditions[0] << ":" << a.m_traderVector.longSell[reqId].conditions[1] << ":" << a.m_traderVector.longSell[reqId].conditions[2] << ":" << a.m_traderVector.longSell[reqId].conditions[3] << ":" << a.m_traderVector.longSell[reqId].conditions[4] << ":" << a.m_traderVector.longSell[reqId].conditions[5] << ":" << a.m_traderVector.longSell[reqId].conditions[6] << ":" << a.m_traderVector.longSell[reqId].conditions[7] << ":" << a.m_traderVector.longSell[reqId].conditions[8] << ":" << a.m_traderVector.longSell[reqId].conditions[9] << std::endl; if (a.m_traderVector.longSell[reqId].numModifiedSell > a.m_traderParameters.maxModificationsAllowed) { time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << tempString << " Long Sell: For " << a.m_newtxtVector[reqId] << " the number of modifications pass the limit and order will be closed with BID price. " << std::endl; std::cout << tempString << " Long Sell: For " << a.m_newtxtVector[reqId] << " the number of modifications pass the limit and order will be closed with BID price. " << std::endl; } } } } } } //relevantShares > 0 } } void TraderNormalLong::placeOrder(unsigned int &reqId, unsigned int &i, std::string action, std::string orderType, unsigned int &relevantShares, double &lmtPrice) { if (i >= 0 && i < a.m_baseNum.size() && reqId >= 0 && reqId < a.m_newtxtVector.size()) { Contract C_d; Order order_d; C_d.symbol = a.m_newtxtVector[reqId]; C_d.secType = "STK"; C_d.currency = "USD"; C_d.exchange = "SMART"; //If necessary, I may include "exchange" in the newtxtVector in the future. order_d.clientId = a.m_clientIdLong; order_d.action = action; order_d.totalQuantity = relevantShares; order_d.orderType = orderType; order_d.tif = "GTC"; order_d.transmit = true; order_d.overridePercentageConstraints = true; order_d.allOrNone = false; order_d.lmtPrice = lmtPrice; std::chrono::high_resolution_clock::time_point now; int counter = 0; bool done = false; while (1) //*******Note this condition is specially for Normal trading { bool b = true; try{ a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_timeDeque.size() < a.m_messageLimitPerSecond) // Need a variable even thought currently it is always 50. Otherwise, hard-coding in various places is dangerous because will forget this later. { bool b = true; try{ a.m_csOrderIdReadyLong.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { order_d.orderId = a.m_orderIdLong; m_EC->placeOrder(a.m_orderIdLong, C_d, order_d); m_numModifications = m_numModifications + 1; if (action == "BUY") { a.m_traderVector.longBuy[reqId].opening = true; a.m_traderVector.longBuy[reqId].orderType = order_d.orderType; a.m_traderVector.longBuy[reqId].symbol = C_d.symbol; a.m_traderVector.longBuy[reqId].orderId = order_d.orderId; a.m_traderVector.longBuy[reqId].action = action; a.m_traderVector.longBuy[reqId].myBid = order_d.lmtPrice; a.m_traderVector.longBuy[reqId].currentTotalBuy = order_d.totalQuantity; a.m_traderVector.longBuy[reqId].buyingShares = order_d.totalQuantity; } if (action == "SELL") { a.m_traderVector.longSell[reqId].closing = true; a.m_traderVector.longSell[reqId].orderType = order_d.orderType; a.m_traderVector.longSell[reqId].symbol = C_d.symbol; a.m_traderVector.longSell[reqId].orderId = order_d.orderId; a.m_traderVector.longSell[reqId].action = action; a.m_traderVector.longSell[reqId].myAsk = lmtPrice; a.m_traderVector.longSell[reqId].currentTotalSell = relevantShares; a.m_traderVector.longSell[reqId].sellingShares = relevantShares; } a.m_orderIdLong = a.m_orderIdLong + 1; done = true; a.m_csOrderIdReadyLong.LeaveCriticalSection(); } now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); } a.m_csTimeDeque.LeaveCriticalSection(); } if (done == true) break; else { Sleep(100); counter = counter + 1; } if (counter > a.m_traderParameters.maxTimeToWaitSendingMessage) { printf("***CS*** %s %d\n", __FILE__, __LINE__); } } //end of while(1) } else { time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" a.m_myfileLong << "At " << tempString << ":" << " vector out of range for reqId : i = " << reqId << " : " << i << " at file " << __FILE__ << " and line " << __LINE__ << std::endl; } } void TraderNormalLong::modifyOrder_sub(unsigned int &reqId, std::string action, std::string orderType, unsigned int &totalQuantity, double &lmtPrice) { Contract C_d; Order order_d; C_d.symbol = a.m_newtxtVector[reqId]; C_d.secType = "STK"; C_d.currency = "USD"; C_d.exchange = "SMART"; //If necessary, I may include "exchange" in the newtxtVector in the future. order_d.clientId = a.m_clientIdLong; order_d.action = action; order_d.totalQuantity = totalQuantity; order_d.orderType = orderType; order_d.tif = "GTC"; order_d.transmit = true; order_d.overridePercentageConstraints = true; order_d.allOrNone = false; order_d.lmtPrice = lmtPrice; std::chrono::high_resolution_clock::time_point now; int counter = 0; bool done = false; while (1) { bool b = true; try{ a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if (a.m_timeDeque.size() < a.m_messageLimitPerSecond) // Need a variable even thought currently it is always 50. Otherwise, hard-coding in various places is dangerous because will forget this later. { if (action == "BUY") { a.m_traderVector.longBuy[reqId].myBid = order_d.lmtPrice; order_d.orderId = a.m_traderVector.longBuy[reqId].orderId; } if (action == "SELL") { a.m_traderVector.longSell[reqId].myAsk = order_d.lmtPrice; order_d.orderId = a.m_traderVector.longSell[reqId].orderId; } m_EC->placeOrder(order_d.orderId, C_d, order_d); m_numModifications = m_numModifications + 1; now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime. a.m_timeDeque.push_back(now); //The following if-structure is redundant and is used for absolutely correct. done = true; } a.m_csTimeDeque.LeaveCriticalSection(); } if (done == true) break; else { Sleep(100); counter = counter + 1; } if (counter > a.m_traderParameters. maxTimeToWaitSendingMessage) { printf("***CS*** %s %d\n", __FILE__, __LINE__); } } } void TraderNormalLong::cleaning() { //**** NEVER DELETE the following comments //**** In the cleaning process, never automatically reset something. For example, if the app automatically reset a trader vector, it may submit infinite number of opening orders. At most I can reset once with some prescribed counter controlled. //**** The cleaning process usually should only give warnings and let developer to be aware of something wrong. //**** No longer to complicate the cleaning process by counting the number of requests of open orders etc. This cleaning() has already been put in a time-restricted place. That is, it can be run only every, say, 10 seconds. for (unsigned int reqId = 0; reqId < a.m_newtxtVector.size(); reqId++) { bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { //Part I. Warning if .opening = true but actually there are no open orders. bool noOpenOrders; noOpenOrders = ((time(0) - a.m_traderVector.longBuy[reqId].orderUpdatedTime) > 3 * a.m_traderParameters.timeBetweenReqOpenOrders); //**** if .orderUpdatedTime > time (0), it indicates it is default value time(0)*2 if (noOpenOrders && a.m_traderVector.longBuy[reqId].opening) printf("There are no opening long orders but a.m_traderVector.longBuy[reqId].opening is %d for symbol %s.\n", a.m_traderVector.longBuy[reqId].opening, a.m_newtxtVector[reqId].c_str()); noOpenOrders = ((time(0) - a.m_traderVector.longSell[reqId].orderUpdatedTime) > 3 * a.m_traderParameters.timeBetweenReqOpenOrders); //**** if .orderUpdatedTime > time (0), it indicates it is default value time(0)*2 if (noOpenOrders && a.m_traderVector.longSell[reqId].closing) printf("There are no closing long orders but a.m_traderVector.longSell[reqId].closing is %d for symbol %s.\n", a.m_traderVector.longSell[reqId].closing, a.m_newtxtVector[reqId].c_str()); noOpenOrders = ((time(0) - a.m_traderVector.shortSell[reqId].orderUpdatedTime) > 3 * a.m_traderParameters.timeBetweenReqOpenOrders); //**** if .orderUpdatedTime > time (0), it indicates it is default value time(0)*2 if (noOpenOrders && a.m_traderVector.shortSell[reqId].opening) printf("There are no opening short orders but a.m_traderVector.shortSell[reqId].opening is %d for symbol %s.\n", a.m_traderVector.shortSell[reqId].opening, a.m_newtxtVector[reqId].c_str()); noOpenOrders = ((time(0) - a.m_traderVector.shortBuy[reqId].orderUpdatedTime) > 3 * a.m_traderParameters.timeBetweenReqOpenOrders); //**** if .orderUpdatedTime > time (0), it indicates it is default value time(0)*2 if (noOpenOrders && a.m_traderVector.shortBuy[reqId].closing) printf("There are no closing short orders but a.m_traderVector.shortBuy[reqId].closing is %d for symbol %s.\n", a.m_traderVector.shortBuy[reqId].closing, a.m_newtxtVector[reqId].c_str()); if (a.m_traderVector.longBuy[reqId].totalPosition < 0 ) printf("Long position is negative %d for symbol %s.\n", a.m_traderVector.longBuy[reqId].totalPosition, a.m_newtxtVector[reqId].c_str()); if (a.m_traderVector.shortSell[reqId].totalPosition > 0) printf("Short position is positive %d for symbol %s.\n", a.m_traderVector.shortSell[reqId].totalPosition, a.m_newtxtVector[reqId].c_str()); //Part II. //**** No deletion: m_algoStringVector shares the critical section of traderVector. Thus it must always be within that critical section. if (a.m_traderVector.longBuy[reqId].totalPosition != 0 && a.m_traderVector.longBuy[reqId].algoString == "EMPTY") printf("Long position is not zero but a.m_algoStringVectorOpen is EMPTY.\n"); if (a.m_traderVector.shortSell[reqId].totalPosition != 0 && a.m_traderVector.shortSell[reqId].algoString == "EMPTY") printf("Short position is not zero but a.m_algoStringVectorOpen is EMPTY.\n"); a.m_csTraderVector.LeaveCriticalSection(); } } } void TraderNormalLong::manualReset() { double newParameter = 0; std::string tempString; std::istringstream instream; std::string String, symbol, actionString, inputFileString = "C:/symbols/Inputfile"; inputFileString.append(a.m_accountCode); inputFileString.append(".txt"); //This make sure the application calls the right file. std::ifstream i_inputFile(inputFileString, std::ios_base::in); m_inputStructureVectorLong.clear(); if (!i_inputFile.is_open()) printf("Failed in opening the InputfileLong***.txt.\n"); else { std::istringstream instream; InputStructure inputStructure; std::string wholeLineString, subString; std::vector<std::string> stringVector; std::istringstream instream0, instream1, instream2; while (getline(i_inputFile, wholeLineString, '\n')) { std::stringstream linestream(wholeLineString); stringVector.clear(); while (getline(linestream, subString, ',')) { stringVector.push_back(subString); } instream0.clear(); instream1.clear(); instream2.clear(); instream0.str(stringVector[0]); instream1.str(stringVector[1]); instream2.str(stringVector[2]); instream0 >> inputStructure.string0; instream1 >> inputStructure.string1; instream2 >> inputStructure.string2; //**** sometimes I need a number and sometimes I need a string. m_inputStructureVectorLong.push_back(inputStructure); }//while (getline(i_inputFile, wholeLineString, '\n')) i_inputFile.close(); } for (unsigned int index = 0; index < m_inputStructureVectorLong.size(); index++) //**** index = 0 is reserved for different information { symbol = m_inputStructureVectorLong[index].string0; actionString = m_inputStructureVectorLong[index].string1; std::istringstream instream(m_inputStructureVectorLong[index].string2); instream >> newParameter; //instream >> tempString; if (symbol == "ALLSYMBOLS") { if (actionString == "volatilityFactorLong") { bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { a.m_volatilityFactorLong = newParameter; //***** a.m_volatilityFactorLong must always be protected by the locks of a.m_csTraderVector a.m_volatilityFactorLong = max(a.m_volatilityFactorLong, 1.0); a.m_csTraderVector.LeaveCriticalSection(); } printf("a.m_volatilityFactorLong is set to be %f. \n", a.m_volatilityFactorLong); } else if (actionString == "volatilityFactorShort") { bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { a.m_volatilityFactorShort = newParameter; a.m_volatilityFactorShort = max(a.m_volatilityFactorShort, 1.0); a.m_csTraderVector.LeaveCriticalSection(); } printf("a.m_volatilityFactorShort is set to be %f. \n", a.m_volatilityFactorShort); } else if (actionString == "closeLongPositions") { bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { a.m_closeLongPositions = true; a.m_csTraderVector.LeaveCriticalSection(); } printf("a.m_closeLongPositions is set to be true. \n"); } else if (actionString == "closeShortPositions") { bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { a.m_closeShortPositions = true; a.m_csTraderVector.LeaveCriticalSection(); } printf("a.m_closeShortPositions is set to be true.\n"); } else if (actionString == "SHOWALLCONDITIONS") { bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { showAllTradingConditions(); a.m_csTraderVector.LeaveCriticalSection(); } } } else // for action on a specific symbol. { int reqId = -1; //**** Defined for not modifying legacy code bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { auto it = a.m_newtxtMap.find(symbol); if (it != a.m_newtxtMap.end()) reqId = it->second; a.m_csTraderVector.LeaveCriticalSection(); } if (reqId >= 0 && reqId < a.m_newtxtVector.size()) { bool b = true; try { a.m_csTraderVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { if(actionString == "SHOWSINGLECONDITIONS") { showSingleTradingConditions(reqId); } else if (actionString == "MANUALORDER") { a.m_traderVector.longBuy[reqId].manualOrder = true; a.m_traderVector.longSell[reqId].manualOrder = true; a.m_traderVector.shortSell[reqId].manualOrder = true; a.m_traderVector.shortBuy[reqId].manualOrder = true; } else if (actionString == "PRINTSTATUSLONG") { bool b = true; try { a.m_csCurrentDataStructureVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { printf("BID is %f and ASK is %f for symbol %s.\n", a.m_currentDataStructureVector[reqId].bid, a.m_currentDataStructureVector[reqId].ask, a.m_newtxtVector[reqId].c_str()); a.m_csCurrentDataStructureVector.LeaveCriticalSection(); } printf("myBid is %f buy and %f sell.\n", a.m_traderVector.longBuy[reqId].myBid, a.m_traderVector.longSell[reqId].myBid); printf("totalPosition is %d and %d.\n", a.m_traderVector.longBuy[reqId].totalPosition, a.m_traderVector.longSell[reqId].totalPosition); printf("buyingShares is %d and %d. \n", a.m_traderVector.longBuy[reqId].buyingShares, a.m_traderVector.longSell[reqId].buyingShares); printf("currentTotalBuy is %d and %d.\n", a.m_traderVector.longBuy[reqId].currentTotalBuy, a.m_traderVector.longSell[reqId].currentTotalBuy); printf("currentTotalSell is %d and %d.\n", a.m_traderVector.longBuy[reqId].currentTotalSell, a.m_traderVector.longSell[reqId].currentTotalSell); printf("averageCost is %f and %f.\n", a.m_traderVector.longBuy[reqId].averageCost, a.m_traderVector.longSell[reqId].averageCost); printf("closing is %d and %d.\n", a.m_traderVector.longBuy[reqId].closing, a.m_traderVector.longSell[reqId].closing); printf("opening is %d and %d.\n", a.m_traderVector.longBuy[reqId].opening, a.m_traderVector.longSell[reqId].opening); printf("cancelling is %d and %d.\n", a.m_traderVector.longBuy[reqId].cancelling, a.m_traderVector.longSell[reqId].cancelling); printf("orderId is %d and %d.\n", a.m_traderVector.longBuy[reqId].orderId, a.m_traderVector.longSell[reqId].orderId); printf("symbol is %s and %s.\n", a.m_traderVector.longBuy[reqId].symbol.c_str(), a.m_traderVector.longSell[reqId].symbol.c_str()); printf(".sellingShares is %d and %d.\n", a.m_traderVector.longBuy[reqId].sellingShares, a.m_traderVector.longSell[reqId].sellingShares); printf("action is %s and %s.\n", a.m_traderVector.longBuy[reqId].action.c_str(), a.m_traderVector.longSell[reqId].action.c_str()); printf("myAsk is %f and %f.\n", a.m_traderVector.longBuy[reqId].myAsk, a.m_traderVector.longSell[reqId].myAsk); printf("modifiedBuy is %d and %d.\n", a.m_traderVector.longBuy[reqId].modifiedBuy, a.m_traderVector.longSell[reqId].modifiedBuy); printf("modifiedSell is %d and %d.\n", a.m_traderVector.longBuy[reqId].modifiedSell, a.m_traderVector.longSell[reqId].modifiedSell); printf("stopLossLong is %f.\n", a.m_traderVector.longBuy[reqId].stopLossLong); printf("a.m_algoStringVectorOpen for symbol %s is %s.\n", a.m_traderVector.longBuy[reqId].symbol.c_str(), a.m_traderVector.longBuy[reqId].algoString.c_str()); } else if (actionString == "PRINTSTATUSSHORT") { bool b = true; try { a.m_csCurrentDataStructureVector.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b) { printf("BID is %f and ASK is %f for symbol %s.\n", a.m_currentDataStructureVector[reqId].bid, a.m_currentDataStructureVector[reqId].ask, a.m_newtxtVector[reqId].c_str()); a.m_csCurrentDataStructureVector.LeaveCriticalSection(); } printf("myBid is %f buy and %f sell.\n", a.m_traderVector.shortSell[reqId].myBid, a.m_traderVector.shortBuy[reqId].myBid); printf("totalPosition is %d and %d.\n", a.m_traderVector.shortSell[reqId].totalPosition, a.m_traderVector.shortBuy[reqId].totalPosition); printf("buyingShares is %d and %d. \n", a.m_traderVector.shortSell[reqId].buyingShares, a.m_traderVector.shortBuy[reqId].buyingShares); printf("currentTotalBuy is %d and %d.\n", a.m_traderVector.shortSell[reqId].currentTotalBuy, a.m_traderVector.shortBuy[reqId].currentTotalBuy); printf("currentTotalSell is %d and %d.\n", a.m_traderVector.shortSell[reqId].currentTotalSell, a.m_traderVector.shortBuy[reqId].currentTotalSell); printf("averageCost is %f and %f.\n", a.m_traderVector.shortSell[reqId].averageCost, a.m_traderVector.shortBuy[reqId].averageCost); printf("closing is %d and %d.\n", a.m_traderVector.shortSell[reqId].closing, a.m_traderVector.shortBuy[reqId].closing); printf("opening is %d and %d.\n", a.m_traderVector.shortSell[reqId].opening, a.m_traderVector.shortBuy[reqId].opening); printf("cancelling is %d and %d.\n", a.m_traderVector.shortSell[reqId].cancelling, a.m_traderVector.shortBuy[reqId].cancelling); printf("orderId is %d and %d.\n", a.m_traderVector.shortSell[reqId].orderId, a.m_traderVector.shortBuy[reqId].orderId); printf("symbol is %s and %s.\n", a.m_traderVector.shortSell[reqId].symbol.c_str(), a.m_traderVector.shortBuy[reqId].symbol.c_str()); printf(".sellingShares is %d and %d.\n", a.m_traderVector.shortSell[reqId].sellingShares, a.m_traderVector.shortBuy[reqId].sellingShares); printf("action is %s and %s.\n", a.m_traderVector.shortSell[reqId].action.c_str(), a.m_traderVector.shortBuy[reqId].action.c_str()); printf("myAsk is %f and %f.\n", a.m_traderVector.shortSell[reqId].myAsk, a.m_traderVector.shortBuy[reqId].myAsk); printf("modifiedBuy is %d and %d.\n", a.m_traderVector.shortSell[reqId].modifiedBuy, a.m_traderVector.shortBuy[reqId].modifiedBuy); printf("modifiedSell is %d and %d.\n", a.m_traderVector.shortSell[reqId].modifiedSell, a.m_traderVector.shortBuy[reqId].modifiedSell); printf("stopLossShort is %f.\n", a.m_traderVector.shortSell[reqId].stopLossShort); printf("a.m_algoStringVectorOpen for symbol %s is %s.\n", a.m_traderVector.shortSell[reqId].symbol.c_str(), a.m_traderVector.shortSell[reqId].algoString.c_str()); } a.m_csTraderVector.LeaveCriticalSection(); } } } } } void TraderNormalLong::showAllTradingConditions() { //**** Later if for several types of TFLongs for example, then we can use algoStringVector types to design vectors, but not as below where we use MrLong, TFLong..... std::vector<std::string> tempVector; tempVector.clear(); std::vector<std::vector<std::string> > longSymbolsVectorBuy;longSymbolsVectorBuy.clear(); std::vector<std::vector<std::string> > longSymbolsVectorSell; longSymbolsVectorSell.clear(); std::vector<std::vector<std::string> > shortSymbolsVectorSell; shortSymbolsVectorSell.clear(); std::vector<std::vector<std::string> > shortSymbolsVectorBuy; shortSymbolsVectorBuy.clear(); for (unsigned int j = 0; j < a.m_traderParameters.maxNumConditions; j++) { longSymbolsVectorBuy.push_back(tempVector); longSymbolsVectorSell.push_back(tempVector); shortSymbolsVectorSell.push_back(tempVector); shortSymbolsVectorBuy.push_back(tempVector); } for (unsigned int j = 0; j < a.m_traderParameters.maxNumConditions; j++) { for (unsigned int reqId = 0; reqId < a.m_newtxtVector.size(); reqId++) { if (a.m_traderVector.longBuy[reqId].conditions[j]) longSymbolsVectorBuy[j].push_back(a.m_newtxtVector[reqId]); if (a.m_traderVector.longSell[reqId].conditions[j])longSymbolsVectorSell[j].push_back(a.m_newtxtVector[reqId]); if (a.m_traderVector.shortSell[reqId].conditions[j]) shortSymbolsVectorSell[j].push_back(a.m_newtxtVector[reqId]); if (a.m_traderVector.shortBuy[reqId].conditions[j]) shortSymbolsVectorBuy[j].push_back(a.m_newtxtVector[reqId]); } } time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" for (unsigned int i = 0; i < a.m_traderParameters.maxNumConditions; i++) { if (longSymbolsVectorBuy[i].size() > 0) { printf("The number of symbols satisfying longBuy[reqId].conditions.condition %d is %d, e.g. %s.\n", i, longSymbolsVectorBuy[i].size(), longSymbolsVectorBuy[i][0].c_str()); //a.m_myfileLong << tempString << "The number of symbols satisfying longBuy[reqId].conditions.condition " << i << " is " << longSymbolsVectorBuy[i].size() << " , e.g., " << longSymbolsVectorBuy[i][0] << std::endl; } } for (unsigned int i = 0; i < a.m_traderParameters.maxNumConditions; i++) { if (longSymbolsVectorSell[i].size() > 0) { printf(" The number of symbols satisfying longSell[reqId].conditions.condition %d is %d, e.g. %s.\n", i, longSymbolsVectorSell[i].size(), longSymbolsVectorSell[i][0].c_str()); //a.m_myfileLong << tempString << "The number of symbols satisfying longSell[reqId].conditions.condition " << i << " is " << longSymbolsVectorSell[i].size() << " , e.g., " << longSymbolsVectorSell[i][0] << std::endl; } } for (unsigned int i = 0; i < a.m_traderParameters.maxNumConditions; i++) { if (shortSymbolsVectorSell[i].size() > 0) { printf(" The number of symbols satisfying shortSell[reqId].conditions.condition %d is %d, e.g. %s.\n", i, shortSymbolsVectorSell[i].size(), shortSymbolsVectorSell[i][0].c_str()); //a.m_myfileLong << tempString << "The number of symbols satisfying shortSell[reqId].conditions.condition " << i << " is " << shortSymbolsVectorSell[i].size() << " , e.g., " << shortSymbolsVectorSell[i][0] << std::endl; } } for (unsigned int i = 0; i < a.m_traderParameters.maxNumConditions; i++) { if (shortSymbolsVectorBuy[i].size() > 0) { printf(" The number of symbols satisfying shortBuy[reqId].conditions.condition %d is %d, e.g. %s.\n", i, shortSymbolsVectorBuy[i].size(), shortSymbolsVectorBuy[i][0].c_str()); //a.m_myfileLong << tempString << "The number of symbols satisfying shortBuy[reqId].conditions.condition " << i << " is " << shortSymbolsVectorBuy[i].size() << " , e.g., " << shortSymbolsVectorBuy[i][0] << std::endl; } } } void TraderNormalLong::showSingleTradingConditions(int &reqId) { time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz" for (unsigned int j = 0; j < a.m_traderParameters.maxNumConditions; j++) { if (a.m_traderVector.longBuy[reqId].conditions[j]) { printf(" symbol %s satisfies the longBuy[reqId].conditions.condition %d.\n", a.m_newtxtVector[reqId].c_str(), j); //a.m_myfileLong << tempString << " symbol " << a.m_newtxtVector[reqId] << " satisfies longBuy[reqId].conditions.condition " << j << std::endl; } } for (unsigned int j = 0; j < a.m_traderParameters.maxNumConditions; j++) { if (a.m_traderVector.longSell[reqId].conditions[j]) { printf(" symbol %s satisfies the longSell[reqId].conditions.condition %d.\n", a.m_newtxtVector[reqId].c_str(), j); //a.m_myfileLong << tempString << " symbol " << a.m_newtxtVector[reqId] << " satisfies longSell[reqId].conditions.condition " << j << std::endl; } } for (unsigned int j = 0; j < a.m_traderParameters.maxNumConditions; j++) { if (a.m_traderVector.shortSell[reqId].conditions[j]) { printf(" symbol %s satisfies the shortSell[reqId].conditions.condition %d.\n", a.m_newtxtVector[reqId].c_str(), j); //a.m_myfileLong << tempString << " symbol " << a.m_newtxtVector[reqId] << " satisfies shortSell[reqId].conditions.condition " << j << std::endl; } } for (unsigned int j = 0; j < a.m_traderParameters.maxNumConditions; j++) { if (a.m_traderVector.shortBuy[reqId].conditions[j]) { printf(" symbol %s satisfies the shortBuy[reqId].conditions.condition %d.\n", a.m_newtxtVector[reqId].c_str(), j); //a.m_myfileLong << tempString << " symbol " << a.m_newtxtVector[reqId] << " satisfies shortBuy[reqId].conditions.condition " << j << std::endl; } } printf(" a.m_traderVector.longBuy[reqId].algoString has a value of %s for symbol %s.\n", a.m_traderVector.longBuy[reqId].algoString.c_str(), a.m_newtxtVector[reqId].c_str()); //a.m_myfileLong << tempString << "a.m_traderVector.longBuy[reqId].algoString has a value of " << a.m_traderVector.longBuy[reqId].algoString << " for symbol " << a.m_newtxtVector[reqId] << std::endl; }
67.618289
537
0.690798
[ "vector" ]
f665608b77a4b4cbee1b6711247be7f28e2fccf2
2,755
cpp
C++
research&testing/EmmaTest/cube.cpp
jag-123/Amused-Anemone
e8ae090c40d3d4d97762dba834d385286e8ff21c
[ "MIT" ]
2
2019-07-25T11:46:41.000Z
2020-07-02T14:00:33.000Z
research&testing/EmmaTest/cube.cpp
jag-123/Amused-Anemone
e8ae090c40d3d4d97762dba834d385286e8ff21c
[ "MIT" ]
1
2019-04-17T17:21:49.000Z
2019-04-17T17:21:49.000Z
research&testing/EmmaTest/cube.cpp
jag-123/Amused-Anemone
e8ae090c40d3d4d97762dba834d385286e8ff21c
[ "MIT" ]
2
2021-11-29T08:13:48.000Z
2021-12-05T19:38:04.000Z
/* Copyright (c) Mark J. Kilgard, 1997. */ /* This program is freely distributable without licensing fees and is provided without guarantee or warrantee expressed or implied. This program is -not- in the public domain. */ /* This program was requested by Patrick Earl; hopefully someone else will write the equivalent Direct3D immediate mode program. */ #include <GL/glut.h> GLfloat light_diffuse[] = {1.0, 0.0, 0.0, 1.0}; /* Red diffuse light. */ GLfloat light_position[] = {1.0, 1.0, 1.0, 0.0}; /* Infinite light location. */ GLfloat n[6][3] = { /* Normals for the 6 faces of a cube. */ {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; GLint faces[6][4] = { /* Vertex indices for the 6 faces of a cube. */ {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; GLfloat v[8][3]; /* Will be filled in with X,Y,Z vertexes. */ void drawBox(void) { int i; for (i = 0; i < 7; i++) { glBegin(GL_QUADS); glNormal3fv(&n[i][0]); glVertex3fv(&v[faces[i][0]][0]); glVertex3fv(&v[faces[i][1]][0]); glVertex3fv(&v[faces[i][2]][0]); glVertex3fv(&v[faces[i][3]][0]); glEnd(); } } void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawBox(); glutSwapBuffers(); } void init(void) { /* Setup cube vertex data. */ v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1; v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1; v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1; v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1; v[0][2] = v[3][2] = v[4][2] = v[7][2] = 1; v[1][2] = v[2][2] = v[5][2] = v[6][2] = -1; /* Enable a single OpenGL light. */ glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); /* Use depth buffering for hidden surface elimination. */ glEnable(GL_DEPTH_TEST); /* Setup the view of the cube. */ glMatrixMode(GL_PROJECTION); gluPerspective( /* field of view in degree */ 40.0, /* aspect ratio */ 1.0, /* Z near */ 1.0, /* Z far */ 10.0); glMatrixMode(GL_MODELVIEW); gluLookAt(0.0, 0.0, 5.0, /* eye is at (0,0,5) */ 0.0, 0.0, 0.0, /* center is at (0,0,0) */ 0.0, 1.0, 0.); /* up is in positive Y direction */ /* Adjust cube position to be asthetic angle. */ glTranslatef(0.0, 0.0, -1.0); glRotatef(60, 1.0, 0.0, 0.0); glRotatef(-20, 0.0, 0.0, 1.0); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutCreateWindow("red 3D lighted cube"); glutDisplayFunc(display); init(); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
29.308511
80
0.575681
[ "3d" ]
f6661974405b3c2af0f1ec1a9ed1dee0da985ab0
2,016
cpp
C++
stdFunction/stdFunction.cpp
yajnas07/modernCpp
6b897831abf0b402bc8df3519e59761a338d7156
[ "CC0-1.0" ]
2
2021-12-16T15:05:41.000Z
2021-12-16T23:57:46.000Z
stdFunction/stdFunction.cpp
yajnas07/modernCpp
6b897831abf0b402bc8df3519e59761a338d7156
[ "CC0-1.0" ]
null
null
null
stdFunction/stdFunction.cpp
yajnas07/modernCpp
6b897831abf0b402bc8df3519e59761a338d7156
[ "CC0-1.0" ]
null
null
null
// stdFunction.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <algorithm> #include <vector> #include <functional> //Needed for std::function using namespace std; using namespace std::placeholders; //Need for _1 , _2 etc //Function variant bool match_substring_generic(const string& str, const string& sub) { if (str.find(sub) != string::npos) return true; return false; } //Functor variant class exact_string_matcher { string to_match_with = ""; public: exact_string_matcher(string & st):to_match_with(st){} bool operator()(const string& str) { return (to_match_with == str); } }; int counter(std::vector<string>& v, std::function< bool(const string& match_element) > predicate) { auto count = 0; for (auto element : v) { if (predicate(element)) count++; } return count; } int main() { vector<string> input{"one", "two", "onetwo", "twoonetoone", "three", "onethree", "four"}; cout << "Inputs Array is:"; for (auto s : input) { cout << s << " "; } string subs = ""; cout << "\nEnter the substring(ctrl+d or 'done' to exit):"; while ((cin >> subs) && (subs!="done")) { auto match_custom = std::bind(match_substring_generic, _1, subs); cout << "Number of string with substrigs " << subs << " = " << counter(input, match_custom) << endl; exact_string_matcher matcher(subs); auto count = counter(input,matcher); cout <<"Number of string exactly match with " << subs << " = " << count << endl; //Lambda equivalent, find string with same size auto string_withsame_size = counter(input, [value = subs](const string& str) { return str.size() == value.size(); } ); cout <<"Number of string having same length as " << subs << " = " << string_withsame_size << endl; cout << "\nEnter the substring(ctrl+d or 'done' to exit):"; } }
28.8
106
0.611111
[ "vector" ]
f666784096b8b37a7cb601f24b67bd0e7508f553
21,775
cc
C++
src/kudu/util/metrics.cc
sdreynolds/kudu
13642f60f9a6ba6dd77f97a6736467b8ab5849af
[ "Apache-2.0" ]
1
2019-09-27T10:01:52.000Z
2019-09-27T10:01:52.000Z
src/kudu/util/metrics.cc
TingyLiang/kudu
8c14875659b7edd0f4353e945351eada8d5fb9e3
[ "Apache-2.0" ]
null
null
null
src/kudu/util/metrics.cc
TingyLiang/kudu
8c14875659b7edd0f4353e945351eada8d5fb9e3
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 "kudu/util/metrics.h" #include <iostream> #include <utility> #include <gflags/gflags.h> #include <glog/logging.h> #include "kudu/gutil/map-util.h" #include "kudu/gutil/singleton.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/util/flag_tags.h" #include "kudu/util/hdr_histogram.h" #include "kudu/util/histogram.pb.h" #include "kudu/util/status.h" #include "kudu/util/string_case.h" DEFINE_int32(metrics_retirement_age_ms, 120 * 1000, "The minimum number of milliseconds a metric will be kept for after it is " "no longer active. (Advanced option)"); TAG_FLAG(metrics_retirement_age_ms, runtime); TAG_FLAG(metrics_retirement_age_ms, advanced); // Process/server-wide metrics should go into the 'server' entity. // More complex applications will define other entities. METRIC_DEFINE_entity(server); namespace kudu { using std::string; using std::vector; using strings::Substitute; // // MetricUnit // const char* MetricUnit::Name(Type unit) { switch (unit) { case kCacheHits: return "hits"; case kCacheQueries: return "queries"; case kBytes: return "bytes"; case kRequests: return "requests"; case kEntries: return "entries"; case kRows: return "rows"; case kCells: return "cells"; case kConnections: return "connections"; case kOperations: return "operations"; case kProbes: return "probes"; case kNanoseconds: return "nanoseconds"; case kMicroseconds: return "microseconds"; case kMilliseconds: return "milliseconds"; case kSeconds: return "seconds"; case kThreads: return "threads"; case kTransactions: return "transactions"; case kUnits: return "units"; case kScanners: return "scanners"; case kMaintenanceOperations: return "operations"; case kBlocks: return "blocks"; case kHoles: return "holes"; case kLogBlockContainers: return "log block containers"; case kTasks: return "tasks"; case kMessages: return "messages"; case kContextSwitches: return "context switches"; case kDataDirectories: return "data directories"; case kState: return "state"; case kSessions: return "sessions"; case kTablets: return "tablets"; default: DCHECK(false) << "Unknown unit with type = " << unit; return "UNKNOWN UNIT"; } } // // MetricType // const char* const MetricType::kGaugeType = "gauge"; const char* const MetricType::kCounterType = "counter"; const char* const MetricType::kHistogramType = "histogram"; const char* MetricType::Name(MetricType::Type type) { switch (type) { case kGauge: return kGaugeType; case kCounter: return kCounterType; case kHistogram: return kHistogramType; default: return "UNKNOWN TYPE"; } } // // MetricEntityPrototype // MetricEntityPrototype::MetricEntityPrototype(const char* name) : name_(name) { MetricPrototypeRegistry::get()->AddEntity(this); } MetricEntityPrototype::~MetricEntityPrototype() { } scoped_refptr<MetricEntity> MetricEntityPrototype::Instantiate( MetricRegistry* registry, const std::string& id, const MetricEntity::AttributeMap& initial_attrs) const { return registry->FindOrCreateEntity(this, id, initial_attrs); } // // MetricEntity // MetricEntity::MetricEntity(const MetricEntityPrototype* prototype, std::string id, AttributeMap attributes) : prototype_(prototype), id_(std::move(id)), attributes_(std::move(attributes)), published_(true) {} MetricEntity::~MetricEntity() { } void MetricEntity::CheckInstantiation(const MetricPrototype* proto) const { CHECK_STREQ(prototype_->name(), proto->entity_type()) << "Metric " << proto->name() << " may not be instantiated entity of type " << prototype_->name() << " (expected: " << proto->entity_type() << ")"; } scoped_refptr<Metric> MetricEntity::FindOrNull(const MetricPrototype& prototype) const { std::lock_guard<simple_spinlock> l(lock_); return FindPtrOrNull(metric_map_, &prototype); } namespace { bool MatchNameInList(const string& name, const vector<string>& names) { string name_uc; ToUpperCase(name, &name_uc); for (const string& e : names) { // The parameter is a case-insensitive substring match of the metric name. string e_uc; ToUpperCase(e, &e_uc); if (name_uc.find(e_uc) != string::npos) { return true; } } return false; } } // anonymous namespace Status MetricEntity::WriteAsJson(JsonWriter* writer, const MetricJsonOptions& opts) const { // Filter the 'type'. if (!opts.entity_types.empty() && !MatchNameInList(prototype_->name(), opts.entity_types)) { return Status::OK(); } // Filter the 'id'. if (!opts.entity_ids.empty() && !MatchNameInList(id_, opts.entity_ids)) { return Status::OK(); } MetricMap metrics; AttributeMap attrs; { // Snapshot the metrics in this registry (not guaranteed to be a consistent snapshot) std::lock_guard<simple_spinlock> l(lock_); attrs = attributes_; metrics = metric_map_; } // Filter the 'attributes'. if (!opts.entity_attrs.empty()) { bool match_attrs = false; DCHECK(opts.entity_attrs.size() % 2 == 0); for (int i = 0; i < opts.entity_attrs.size(); i += 2) { // The attr_key can't be found or the attr_val can't be matched. AttributeMap::const_iterator it = attrs.find(opts.entity_attrs[i]); if (it == attrs.end() || !MatchNameInList(it->second, { opts.entity_attrs[i+1] })) { continue; } match_attrs = true; break; } // None of them match. if (!match_attrs) { return Status::OK(); } } // Filter the 'metrics'. if (!opts.entity_metrics.empty()) { for (auto metric = metrics.begin(); metric != metrics.end();) { if (!MatchNameInList(metric->first->name(), opts.entity_metrics)) { metric = metrics.erase(metric); } else { ++metric; } } // None of them match. if (metrics.empty()) { return Status::OK(); } } writer->StartObject(); writer->String("type"); writer->String(prototype_->name()); writer->String("id"); writer->String(id_); if (opts.include_entity_attributes) { writer->String("attributes"); writer->StartObject(); for (const AttributeMap::value_type& val : attrs) { writer->String(val.first); writer->String(val.second); } writer->EndObject(); } writer->String("metrics"); writer->StartArray(); for (MetricMap::value_type& val : metrics) { const auto& m = val.second; if (m->ModifiedInOrAfterEpoch(opts.only_modified_in_or_after_epoch)) { if (!opts.include_untouched_metrics && m->IsUntouched()) { continue; } WARN_NOT_OK(m->WriteAsJson(writer, opts), strings::Substitute("Failed to write $0 as JSON", val.first->name())); } } writer->EndArray(); writer->EndObject(); return Status::OK(); } void MetricEntity::RetireOldMetrics() { MonoTime now(MonoTime::Now()); std::lock_guard<simple_spinlock> l(lock_); for (auto it = metric_map_.begin(); it != metric_map_.end();) { const scoped_refptr<Metric>& metric = it->second; if (PREDICT_TRUE(!metric->HasOneRef() && published_)) { // The metric is still in use. Note that, in the case of "NeverRetire()", the metric // will have a ref-count of 2 because it is reffed by the 'never_retire_metrics_' // collection. // Ensure that it is not marked for later retirement (this could happen in the case // that a metric is un-reffed and then re-reffed later by looking it up from the // registry). metric->retire_time_ = MonoTime(); ++it; continue; } if (!metric->retire_time_.Initialized()) { VLOG(3) << "Metric " << it->first << " has become un-referenced or unpublished. " << "Will retire after the retention interval"; // This is the first time we've seen this metric as retirable. metric->retire_time_ = now + MonoDelta::FromMilliseconds(FLAGS_metrics_retirement_age_ms); ++it; continue; } // If we've already seen this metric in a previous scan, check if it's // time to retire it yet. if (now < metric->retire_time_) { VLOG(3) << "Metric " << it->first << " is un-referenced, but still within " << "the retention interval"; ++it; continue; } VLOG(2) << "Retiring metric " << it->first; metric_map_.erase(it++); } } void MetricEntity::NeverRetire(const scoped_refptr<Metric>& metric) { std::lock_guard<simple_spinlock> l(lock_); never_retire_metrics_.push_back(metric); } void MetricEntity::SetAttributes(const AttributeMap& attrs) { std::lock_guard<simple_spinlock> l(lock_); attributes_ = attrs; } void MetricEntity::SetAttribute(const string& key, const string& val) { std::lock_guard<simple_spinlock> l(lock_); attributes_[key] = val; } // // MetricRegistry // MetricRegistry::MetricRegistry() { } MetricRegistry::~MetricRegistry() { } Status MetricRegistry::WriteAsJson(JsonWriter* writer, const MetricJsonOptions& opts) const { EntityMap entities; { std::lock_guard<simple_spinlock> l(lock_); entities = entities_; } writer->StartArray(); for (const auto& e : entities) { WARN_NOT_OK(e.second->WriteAsJson(writer, opts), Substitute("Failed to write entity $0 as JSON", e.second->id())); } writer->EndArray(); // Rather than having a thread poll metrics periodically to retire old ones, // we'll just retire them here. The only downside is that, if no one is polling // metrics, we may end up leaving them around indefinitely; however, metrics are // small, and one might consider it a feature: if monitoring stops polling for // metrics, we should keep them around until the next poll. entities.clear(); // necessary to deref metrics we just dumped before doing retirement scan. const_cast<MetricRegistry*>(this)->RetireOldMetrics(); return Status::OK(); } void MetricRegistry::RetireOldMetrics() { std::lock_guard<simple_spinlock> l(lock_); for (auto it = entities_.begin(); it != entities_.end();) { it->second->RetireOldMetrics(); if (it->second->num_metrics() == 0 && (it->second->HasOneRef() || !it->second->published())) { // This entity has no metrics and either has no more external references or has // been marked as unpublished, so we can remove it. // Unlike retiring the metrics themselves, we don't wait for any timeout // to retire them -- we assume that that timed retention has been satisfied // by holding onto the metrics inside the entity. entities_.erase(it++); } else { ++it; } } } // // MetricPrototypeRegistry // MetricPrototypeRegistry* MetricPrototypeRegistry::get() { return Singleton<MetricPrototypeRegistry>::get(); } void MetricPrototypeRegistry::AddMetric(const MetricPrototype* prototype) { std::lock_guard<simple_spinlock> l(lock_); metrics_.push_back(prototype); } void MetricPrototypeRegistry::AddEntity(const MetricEntityPrototype* prototype) { std::lock_guard<simple_spinlock> l(lock_); entities_.push_back(prototype); } void MetricPrototypeRegistry::WriteAsJson(JsonWriter* writer) const { std::lock_guard<simple_spinlock> l(lock_); MetricJsonOptions opts; opts.include_schema_info = true; writer->StartObject(); // Dump metric prototypes. writer->String("metrics"); writer->StartArray(); for (const MetricPrototype* p : metrics_) { writer->StartObject(); p->WriteFields(writer, opts); writer->String("entity_type"); writer->String(p->entity_type()); writer->EndObject(); } writer->EndArray(); // Dump entity prototypes. writer->String("entities"); writer->StartArray(); for (const MetricEntityPrototype* p : entities_) { writer->StartObject(); writer->String("name"); writer->String(p->name()); writer->EndObject(); } writer->EndArray(); writer->EndObject(); } void MetricPrototypeRegistry::WriteAsJson() const { std::ostringstream s; JsonWriter w(&s, JsonWriter::PRETTY); WriteAsJson(&w); std::cout << s.str() << std::endl; } // // MetricPrototype // MetricPrototype::MetricPrototype(CtorArgs args) : args_(args) { MetricPrototypeRegistry::get()->AddMetric(this); } void MetricPrototype::WriteFields(JsonWriter* writer, const MetricJsonOptions& opts) const { writer->String("name"); writer->String(name()); if (opts.include_schema_info) { writer->String("label"); writer->String(label()); writer->String("type"); writer->String(MetricType::Name(type())); writer->String("unit"); writer->String(MetricUnit::Name(unit())); writer->String("description"); writer->String(description()); } } // // FunctionGaugeDetacher // FunctionGaugeDetacher::FunctionGaugeDetacher() { } FunctionGaugeDetacher::~FunctionGaugeDetacher() { for (const Closure& c : callbacks_) { c.Run(); } } scoped_refptr<MetricEntity> MetricRegistry::FindOrCreateEntity( const MetricEntityPrototype* prototype, const std::string& id, const MetricEntity::AttributeMap& initial_attributes) { std::lock_guard<simple_spinlock> l(lock_); scoped_refptr<MetricEntity> e = FindPtrOrNull(entities_, id); if (!e) { e = new MetricEntity(prototype, id, initial_attributes); InsertOrDie(&entities_, id, e); } else if (!e->published()) { e = new MetricEntity(prototype, id, initial_attributes); entities_[id] = e; } else { e->SetAttributes(initial_attributes); } return e; } // // Metric // std::atomic<int64_t> Metric::g_epoch_; Metric::Metric(const MetricPrototype* prototype) : prototype_(prototype), m_epoch_(current_epoch()) { } Metric::~Metric() { } void Metric::IncrementEpoch() { g_epoch_++; } void Metric::UpdateModificationEpochSlowPath() { int64_t new_epoch, old_epoch; // CAS loop to ensure that we never transition a metric's epoch backwards // even if multiple threads race to update it. do { old_epoch = m_epoch_; new_epoch = g_epoch_; } while (old_epoch < new_epoch && !m_epoch_.compare_exchange_weak(old_epoch, new_epoch)); } // // Gauge // Status Gauge::WriteAsJson(JsonWriter* writer, const MetricJsonOptions& opts) const { writer->StartObject(); prototype_->WriteFields(writer, opts); writer->String("value"); WriteValue(writer); writer->EndObject(); return Status::OK(); } // // StringGauge // StringGauge::StringGauge(const GaugePrototype<string>* proto, string initial_value) : Gauge(proto), value_(std::move(initial_value)) {} std::string StringGauge::value() const { std::lock_guard<simple_spinlock> l(lock_); return value_; } void StringGauge::set_value(const std::string& value) { UpdateModificationEpoch(); std::lock_guard<simple_spinlock> l(lock_); value_ = value; } void StringGauge::WriteValue(JsonWriter* writer) const { writer->String(value()); } // // Counter // // This implementation is optimized by using a striped counter. See LongAdder for details. scoped_refptr<Counter> CounterPrototype::Instantiate(const scoped_refptr<MetricEntity>& entity) { return entity->FindOrCreateCounter(this); } Counter::Counter(const CounterPrototype* proto) : Metric(proto) { } int64_t Counter::value() const { return value_.Value(); } void Counter::Increment() { IncrementBy(1); } void Counter::IncrementBy(int64_t amount) { UpdateModificationEpoch(); value_.IncrementBy(amount); } Status Counter::WriteAsJson(JsonWriter* writer, const MetricJsonOptions& opts) const { writer->StartObject(); prototype_->WriteFields(writer, opts); writer->String("value"); writer->Int64(value()); writer->EndObject(); return Status::OK(); } ///////////////////////////////////////////////// // HistogramPrototype ///////////////////////////////////////////////// HistogramPrototype::HistogramPrototype(const MetricPrototype::CtorArgs& args, uint64_t max_trackable_value, int num_sig_digits) : MetricPrototype(args), max_trackable_value_(max_trackable_value), num_sig_digits_(num_sig_digits) { // Better to crash at definition time that at instantiation time. CHECK(HdrHistogram::IsValidHighestTrackableValue(max_trackable_value)) << Substitute("Invalid max trackable value on histogram $0: $1", args.name_, max_trackable_value); CHECK(HdrHistogram::IsValidNumSignificantDigits(num_sig_digits)) << Substitute("Invalid number of significant digits on histogram $0: $1", args.name_, num_sig_digits); } scoped_refptr<Histogram> HistogramPrototype::Instantiate( const scoped_refptr<MetricEntity>& entity) { return entity->FindOrCreateHistogram(this); } ///////////////////////////////////////////////// // Histogram ///////////////////////////////////////////////// Histogram::Histogram(const HistogramPrototype* proto) : Metric(proto), histogram_(new HdrHistogram(proto->max_trackable_value(), proto->num_sig_digits())) { } void Histogram::Increment(int64_t value) { UpdateModificationEpoch(); histogram_->Increment(value); } void Histogram::IncrementBy(int64_t value, int64_t amount) { UpdateModificationEpoch(); histogram_->IncrementBy(value, amount); } Status Histogram::WriteAsJson(JsonWriter* writer, const MetricJsonOptions& opts) const { HistogramSnapshotPB snapshot; RETURN_NOT_OK(GetHistogramSnapshotPB(&snapshot, opts)); writer->Protobuf(snapshot); return Status::OK(); } Status Histogram::GetHistogramSnapshotPB(HistogramSnapshotPB* snapshot_pb, const MetricJsonOptions& opts) const { snapshot_pb->set_name(prototype_->name()); if (opts.include_schema_info) { snapshot_pb->set_type(MetricType::Name(prototype_->type())); snapshot_pb->set_label(prototype_->label()); snapshot_pb->set_unit(MetricUnit::Name(prototype_->unit())); snapshot_pb->set_description(prototype_->description()); snapshot_pb->set_max_trackable_value(histogram_->highest_trackable_value()); snapshot_pb->set_num_significant_digits(histogram_->num_significant_digits()); } // Fast-path for a reasonably common case of an empty histogram. This occurs // when a histogram is tracking some information about a feature not in // use, for example. if (histogram_->TotalCount() == 0) { snapshot_pb->set_total_count(0); snapshot_pb->set_total_sum(0); snapshot_pb->set_min(0); snapshot_pb->set_mean(0); snapshot_pb->set_percentile_75(0); snapshot_pb->set_percentile_95(0); snapshot_pb->set_percentile_99(0); snapshot_pb->set_percentile_99_9(0); snapshot_pb->set_percentile_99_99(0); snapshot_pb->set_max(0); } else { HdrHistogram snapshot(*histogram_); snapshot_pb->set_total_count(snapshot.TotalCount()); snapshot_pb->set_total_sum(snapshot.TotalSum()); snapshot_pb->set_min(snapshot.MinValue()); snapshot_pb->set_mean(snapshot.MeanValue()); snapshot_pb->set_percentile_75(snapshot.ValueAtPercentile(75)); snapshot_pb->set_percentile_95(snapshot.ValueAtPercentile(95)); snapshot_pb->set_percentile_99(snapshot.ValueAtPercentile(99)); snapshot_pb->set_percentile_99_9(snapshot.ValueAtPercentile(99.9)); snapshot_pb->set_percentile_99_99(snapshot.ValueAtPercentile(99.99)); snapshot_pb->set_max(snapshot.MaxValue()); if (opts.include_raw_histograms) { RecordedValuesIterator iter(&snapshot); while (iter.HasNext()) { HistogramIterationValue value; RETURN_NOT_OK(iter.Next(&value)); snapshot_pb->add_values(value.value_iterated_to); snapshot_pb->add_counts(value.count_at_value_iterated_to); } } } return Status::OK(); } uint64_t Histogram::CountInBucketForValueForTests(uint64_t value) const { return histogram_->CountInBucketForValue(value); } uint64_t Histogram::TotalCount() const { return histogram_->TotalCount(); } uint64_t Histogram::MinValueForTests() const { return histogram_->MinValue(); } uint64_t Histogram::MaxValueForTests() const { return histogram_->MaxValue(); } double Histogram::MeanValueForTests() const { return histogram_->MeanValue(); } ScopedLatencyMetric::ScopedLatencyMetric(Histogram* latency_hist) : latency_hist_(latency_hist) { if (latency_hist_) { time_started_ = MonoTime::Now(); } } ScopedLatencyMetric::~ScopedLatencyMetric() { if (latency_hist_ != nullptr) { MonoTime time_now = MonoTime::Now(); latency_hist_->Increment((time_now - time_started_).ToMicroseconds()); } } } // namespace kudu
28.501309
97
0.679816
[ "vector" ]
f6712bb87bbd861ed1f523fe900822964e33f6eb
23,218
cpp
C++
nano/node/transport/udp.cpp
ez-lol/nano-node
53873a4a907e3be8b1e06f0e2e9ee59c1c81ba04
[ "BSD-2-Clause" ]
3
2020-12-24T06:32:59.000Z
2021-01-13T17:50:51.000Z
nano/node/transport/udp.cpp
ez-lol/nano-node
53873a4a907e3be8b1e06f0e2e9ee59c1c81ba04
[ "BSD-2-Clause" ]
1
2018-04-11T12:52:12.000Z
2018-04-11T12:54:26.000Z
nano/node/transport/udp.cpp
ez-lol/nano-node
53873a4a907e3be8b1e06f0e2e9ee59c1c81ba04
[ "BSD-2-Clause" ]
2
2019-06-01T06:08:44.000Z
2019-06-04T11:47:07.000Z
#include <nano/crypto_lib/random_pool.hpp> #include <nano/lib/stats.hpp> #include <nano/node/node.hpp> #include <nano/node/transport/udp.hpp> nano::transport::channel_udp::channel_udp (nano::transport::udp_channels & channels_a, nano::endpoint const & endpoint_a, uint8_t protocol_version_a) : channel (channels_a.node), endpoint (endpoint_a), channels (channels_a) { set_network_version (protocol_version_a); assert (endpoint_a.address ().is_v6 ()); } size_t nano::transport::channel_udp::hash_code () const { std::hash<::nano::endpoint> hash; return hash (endpoint); } bool nano::transport::channel_udp::operator== (nano::transport::channel const & other_a) const { bool result (false); auto other_l (dynamic_cast<nano::transport::channel_udp const *> (&other_a)); if (other_l != nullptr) { return *this == *other_l; } return result; } void nano::transport::channel_udp::send_buffer (nano::shared_const_buffer const & buffer_a, nano::stat::detail detail_a, std::function<void(boost::system::error_code const &, size_t)> const & callback_a) { set_last_packet_sent (std::chrono::steady_clock::now ()); channels.send (buffer_a, endpoint, callback (detail_a, callback_a)); } std::function<void(boost::system::error_code const &, size_t)> nano::transport::channel_udp::callback (nano::stat::detail detail_a, std::function<void(boost::system::error_code const &, size_t)> const & callback_a) const { // clang-format off return [node = std::weak_ptr<nano::node> (channels.node.shared ()), callback_a ](boost::system::error_code const & ec, size_t size_a) { if (auto node_l = node.lock ()) { if (ec == boost::system::errc::host_unreachable) { node_l->stats.inc (nano::stat::type::error, nano::stat::detail::unreachable_host, nano::stat::dir::out); } if (size_a > 0) { node_l->stats.add (nano::stat::type::traffic_udp, nano::stat::dir::out, size_a); } if (callback_a) { callback_a (ec, size_a); } } }; // clang-format on } std::string nano::transport::channel_udp::to_string () const { return boost::str (boost::format ("%1%") % endpoint); } nano::transport::udp_channels::udp_channels (nano::node & node_a, uint16_t port_a) : node (node_a), strand (node_a.io_ctx.get_executor ()), socket (node_a.io_ctx, nano::endpoint (boost::asio::ip::address_v6::any (), port_a)) { boost::system::error_code ec; auto port (socket.local_endpoint (ec).port ()); if (ec) { node.logger.try_log ("Unable to retrieve port: ", ec.message ()); } local_endpoint = nano::endpoint (boost::asio::ip::address_v6::loopback (), port); } void nano::transport::udp_channels::send (nano::shared_const_buffer const & buffer_a, nano::endpoint endpoint_a, std::function<void(boost::system::error_code const &, size_t)> const & callback_a) { boost::asio::post (strand, [this, buffer_a, endpoint_a, callback_a]() { this->socket.async_send_to (buffer_a, endpoint_a, boost::asio::bind_executor (strand, callback_a)); }); } std::shared_ptr<nano::transport::channel_udp> nano::transport::udp_channels::insert (nano::endpoint const & endpoint_a, unsigned network_version_a) { assert (endpoint_a.address ().is_v6 ()); std::shared_ptr<nano::transport::channel_udp> result; if (!node.network.not_a_peer (endpoint_a, node.config.allow_local_peers) && (node.network_params.network.is_test_network () || !max_ip_connections (endpoint_a))) { nano::unique_lock<std::mutex> lock (mutex); auto existing (channels.get<endpoint_tag> ().find (endpoint_a)); if (existing != channels.get<endpoint_tag> ().end ()) { result = existing->channel; } else { result = std::make_shared<nano::transport::channel_udp> (*this, endpoint_a, network_version_a); channels.get<endpoint_tag> ().insert ({ result }); lock.unlock (); node.network.channel_observer (result); } } return result; } void nano::transport::udp_channels::erase (nano::endpoint const & endpoint_a) { nano::lock_guard<std::mutex> lock (mutex); channels.get<endpoint_tag> ().erase (endpoint_a); } size_t nano::transport::udp_channels::size () const { nano::lock_guard<std::mutex> lock (mutex); return channels.size (); } std::shared_ptr<nano::transport::channel_udp> nano::transport::udp_channels::channel (nano::endpoint const & endpoint_a) const { nano::lock_guard<std::mutex> lock (mutex); std::shared_ptr<nano::transport::channel_udp> result; auto existing (channels.get<endpoint_tag> ().find (endpoint_a)); if (existing != channels.get<endpoint_tag> ().end ()) { result = existing->channel; } return result; } std::unordered_set<std::shared_ptr<nano::transport::channel>> nano::transport::udp_channels::random_set (size_t count_a) const { std::unordered_set<std::shared_ptr<nano::transport::channel>> result; result.reserve (count_a); nano::lock_guard<std::mutex> lock (mutex); // Stop trying to fill result with random samples after this many attempts auto random_cutoff (count_a * 2); auto peers_size (channels.size ()); // Usually count_a will be much smaller than peers.size() // Otherwise make sure we have a cutoff on attempting to randomly fill if (!channels.empty ()) { for (auto i (0); i < random_cutoff && result.size () < count_a; ++i) { auto index (nano::random_pool::generate_word32 (0, static_cast<CryptoPP::word32> (peers_size - 1))); result.insert (channels.get<random_access_tag> ()[index].channel); } } return result; } void nano::transport::udp_channels::random_fill (std::array<nano::endpoint, 8> & target_a) const { auto peers (random_set (target_a.size ())); assert (peers.size () <= target_a.size ()); auto endpoint (nano::endpoint (boost::asio::ip::address_v6{}, 0)); assert (endpoint.address ().is_v6 ()); std::fill (target_a.begin (), target_a.end (), endpoint); auto j (target_a.begin ()); for (auto i (peers.begin ()), n (peers.end ()); i != n; ++i, ++j) { assert ((*i)->get_endpoint ().address ().is_v6 ()); assert (j < target_a.end ()); *j = (*i)->get_endpoint (); } } bool nano::transport::udp_channels::store_all (bool clear_peers) { // We can't hold the mutex while starting a write transaction, so // we collect endpoints to be saved and then relase the lock. std::vector<nano::endpoint> endpoints; { nano::lock_guard<std::mutex> lock (mutex); endpoints.reserve (channels.size ()); std::transform (channels.begin (), channels.end (), std::back_inserter (endpoints), [](const auto & channel) { return channel.endpoint (); }); } bool result (false); if (!endpoints.empty ()) { // Clear all peers then refresh with the current list of peers auto transaction (node.store.tx_begin_write ({ tables::peers })); if (clear_peers) { node.store.peer_clear (transaction); } for (auto endpoint : endpoints) { nano::endpoint_key endpoint_key (endpoint.address ().to_v6 ().to_bytes (), endpoint.port ()); node.store.peer_put (transaction, std::move (endpoint_key)); } result = true; } return result; } std::shared_ptr<nano::transport::channel_udp> nano::transport::udp_channels::find_node_id (nano::account const & node_id_a) { std::shared_ptr<nano::transport::channel_udp> result; nano::lock_guard<std::mutex> lock (mutex); auto existing (channels.get<node_id_tag> ().find (node_id_a)); if (existing != channels.get<node_id_tag> ().end ()) { result = existing->channel; } return result; } void nano::transport::udp_channels::clean_node_id (nano::account const & node_id_a) { nano::lock_guard<std::mutex> lock (mutex); channels.get<node_id_tag> ().erase (node_id_a); } void nano::transport::udp_channels::clean_node_id (nano::endpoint const & endpoint_a, nano::account const & node_id_a) { nano::lock_guard<std::mutex> lock (mutex); auto existing (channels.get<node_id_tag> ().equal_range (node_id_a)); for (auto & record : boost::make_iterator_range (existing)) { // Remove duplicate node ID for same IP address if (record.endpoint ().address () == endpoint_a.address () && record.endpoint ().port () != endpoint_a.port ()) { channels.get<endpoint_tag> ().erase (record.endpoint ()); break; } } } nano::tcp_endpoint nano::transport::udp_channels::bootstrap_peer (uint8_t connection_protocol_version_min) { nano::tcp_endpoint result (boost::asio::ip::address_v6::any (), 0); nano::lock_guard<std::mutex> lock (mutex); for (auto i (channels.get<last_bootstrap_attempt_tag> ().begin ()), n (channels.get<last_bootstrap_attempt_tag> ().end ()); i != n;) { if (i->channel->get_network_version () >= connection_protocol_version_min) { result = nano::transport::map_endpoint_to_tcp (i->endpoint ()); channels.get<last_bootstrap_attempt_tag> ().modify (i, [](channel_udp_wrapper & wrapper_a) { wrapper_a.channel->set_last_bootstrap_attempt (std::chrono::steady_clock::now ()); }); i = n; } else { ++i; } } return result; } void nano::transport::udp_channels::receive () { if (node.config.logging.network_packet_logging ()) { node.logger.try_log ("Receiving packet"); } auto data (node.network.buffer_container.allocate ()); socket.async_receive_from (boost::asio::buffer (data->buffer, nano::network::buffer_size), data->endpoint, boost::asio::bind_executor (strand, [this, data](boost::system::error_code const & error, std::size_t size_a) { if (!error && !stopped) { data->size = size_a; this->node.network.buffer_container.enqueue (data); this->receive (); } else { this->node.network.buffer_container.release (data); if (error) { if (this->node.config.logging.network_logging ()) { this->node.logger.try_log (boost::str (boost::format ("UDP Receive error: %1%") % error.message ())); } } if (!stopped) { this->node.alarm.add (std::chrono::steady_clock::now () + std::chrono::seconds (5), [this]() { this->receive (); }); } } })); } void nano::transport::udp_channels::start () { for (size_t i = 0; i < node.config.io_threads; ++i) { boost::asio::post (strand, [this]() { receive (); }); } ongoing_keepalive (); } void nano::transport::udp_channels::stop () { // Stop and invalidate local endpoint stopped = true; nano::lock_guard<std::mutex> lock (mutex); local_endpoint = nano::endpoint (boost::asio::ip::address_v6::loopback (), 0); // On test-net, close directly to avoid address-reuse issues. On livenet, close // through the strand as multiple IO threads may access the socket. // clang-format off if (node.network_params.network.is_test_network ()) { this->close_socket (); } else { boost::asio::dispatch (strand, [this] { this->close_socket (); }); } // clang-format on } void nano::transport::udp_channels::close_socket () { boost::system::error_code ignored; this->socket.close (ignored); this->local_endpoint = nano::endpoint (boost::asio::ip::address_v6::loopback (), 0); } nano::endpoint nano::transport::udp_channels::get_local_endpoint () const { nano::lock_guard<std::mutex> lock (mutex); return local_endpoint; } namespace { class udp_message_visitor : public nano::message_visitor { public: udp_message_visitor (nano::node & node_a, nano::endpoint const & endpoint_a) : node (node_a), endpoint (endpoint_a) { } void keepalive (nano::keepalive const & message_a) override { if (!node.network.udp_channels.max_ip_connections (endpoint)) { auto cookie (node.network.syn_cookies.assign (endpoint)); if (cookie) { // New connection auto find_channel (node.network.udp_channels.channel (endpoint)); if (find_channel) { node.network.send_node_id_handshake (find_channel, *cookie, boost::none); node.network.send_keepalive_self (find_channel); } else if (!node.network.tcp_channels.find_channel (nano::transport::map_endpoint_to_tcp (endpoint))) { // Don't start connection if TCP channel to same IP:port exists find_channel = std::make_shared<nano::transport::channel_udp> (node.network.udp_channels, endpoint, node.network_params.protocol.protocol_version); node.network.send_node_id_handshake (find_channel, *cookie, boost::none); } } // Check for special node port data auto peer0 (message_a.peers[0]); if (peer0.address () == boost::asio::ip::address_v6{} && peer0.port () != 0) { nano::endpoint new_endpoint (endpoint.address (), peer0.port ()); node.network.merge_peer (new_endpoint); } } message (message_a); } void publish (nano::publish const & message_a) override { message (message_a); } void confirm_req (nano::confirm_req const & message_a) override { message (message_a); } void confirm_ack (nano::confirm_ack const & message_a) override { message (message_a); } void bulk_pull (nano::bulk_pull const &) override { assert (false); } void bulk_pull_account (nano::bulk_pull_account const &) override { assert (false); } void bulk_push (nano::bulk_push const &) override { assert (false); } void frontier_req (nano::frontier_req const &) override { assert (false); } void node_id_handshake (nano::node_id_handshake const & message_a) override { if (node.config.logging.network_node_id_handshake_logging ()) { node.logger.try_log (boost::str (boost::format ("Received node_id_handshake message from %1% with query %2% and response ID %3%") % endpoint % (message_a.query ? message_a.query->to_string () : std::string ("[none]")) % (message_a.response ? message_a.response->first.to_node_id () : std::string ("[none]")))); } boost::optional<nano::uint256_union> out_query; boost::optional<nano::uint256_union> out_respond_to; if (message_a.query) { out_respond_to = message_a.query; } auto validated_response (false); if (message_a.response) { if (!node.network.syn_cookies.validate (endpoint, message_a.response->first, message_a.response->second)) { validated_response = true; if (message_a.response->first != node.node_id.pub && !node.network.tcp_channels.find_node_id (message_a.response->first)) { node.network.udp_channels.clean_node_id (endpoint, message_a.response->first); auto new_channel (node.network.udp_channels.insert (endpoint, message_a.header.version_using)); if (new_channel) { node.network.udp_channels.modify (new_channel, [&message_a](std::shared_ptr<nano::transport::channel_udp> channel_a) { channel_a->set_node_id (message_a.response->first); channel_a->set_last_packet_received (std::chrono::steady_clock::now ()); }); } } } else if (node.config.logging.network_node_id_handshake_logging ()) { node.logger.try_log (boost::str (boost::format ("Failed to validate syn cookie signature %1% by %2%") % message_a.response->second.to_string () % message_a.response->first.to_account ())); } } if (!validated_response && node.network.udp_channels.channel (endpoint) == nullptr) { out_query = node.network.syn_cookies.assign (endpoint); } if (out_query || out_respond_to) { auto find_channel (node.network.udp_channels.channel (endpoint)); if (!find_channel) { find_channel = std::make_shared<nano::transport::channel_udp> (node.network.udp_channels, endpoint, node.network_params.protocol.protocol_version); } node.network.send_node_id_handshake (find_channel, out_query, out_respond_to); } message (message_a); } void message (nano::message const & message_a) { auto find_channel (node.network.udp_channels.channel (endpoint)); if (find_channel) { node.network.udp_channels.modify (find_channel, [](std::shared_ptr<nano::transport::channel_udp> channel_a) { channel_a->set_last_packet_received (std::chrono::steady_clock::now ()); }); node.network.process_message (message_a, find_channel); } } nano::node & node; nano::endpoint endpoint; }; } void nano::transport::udp_channels::receive_action (nano::message_buffer * data_a) { auto allowed_sender (true); if (data_a->endpoint == local_endpoint) { allowed_sender = false; } else if (data_a->endpoint.address ().to_v6 ().is_unspecified ()) { allowed_sender = false; } else if (nano::transport::reserved_address (data_a->endpoint, node.config.allow_local_peers)) { allowed_sender = false; } if (allowed_sender) { udp_message_visitor visitor (node, data_a->endpoint); nano::message_parser parser (node.block_uniquer, node.vote_uniquer, visitor, node.work); parser.deserialize_buffer (data_a->buffer, data_a->size); if (parser.status != nano::message_parser::parse_status::success) { node.stats.inc (nano::stat::type::error); switch (parser.status) { case nano::message_parser::parse_status::insufficient_work: // We've already increment error count, update detail only node.stats.inc_detail_only (nano::stat::type::error, nano::stat::detail::insufficient_work); break; case nano::message_parser::parse_status::invalid_magic: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_magic); break; case nano::message_parser::parse_status::invalid_network: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_network); break; case nano::message_parser::parse_status::invalid_header: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_header); break; case nano::message_parser::parse_status::invalid_message_type: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_message_type); break; case nano::message_parser::parse_status::invalid_keepalive_message: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_keepalive_message); break; case nano::message_parser::parse_status::invalid_publish_message: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_publish_message); break; case nano::message_parser::parse_status::invalid_confirm_req_message: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_confirm_req_message); break; case nano::message_parser::parse_status::invalid_confirm_ack_message: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_confirm_ack_message); break; case nano::message_parser::parse_status::invalid_node_id_handshake_message: node.stats.inc (nano::stat::type::udp, nano::stat::detail::invalid_node_id_handshake_message); break; case nano::message_parser::parse_status::outdated_version: node.stats.inc (nano::stat::type::udp, nano::stat::detail::outdated_version); break; case nano::message_parser::parse_status::success: /* Already checked, unreachable */ break; } } else { node.stats.add (nano::stat::type::traffic_udp, nano::stat::dir::in, data_a->size); } } else { if (node.config.logging.network_packet_logging ()) { node.logger.try_log (boost::str (boost::format ("Reserved sender %1%") % data_a->endpoint)); } node.stats.inc_detail_only (nano::stat::type::error, nano::stat::detail::bad_sender); } } void nano::transport::udp_channels::process_packets () { while (!stopped) { auto data (node.network.buffer_container.dequeue ()); if (data == nullptr) { break; } receive_action (data); node.network.buffer_container.release (data); } } std::shared_ptr<nano::transport::channel> nano::transport::udp_channels::create (nano::endpoint const & endpoint_a) { return std::make_shared<nano::transport::channel_udp> (*this, endpoint_a, node.network_params.protocol.protocol_version); } bool nano::transport::udp_channels::max_ip_connections (nano::endpoint const & endpoint_a) { nano::unique_lock<std::mutex> lock (mutex); bool result (channels.get<ip_address_tag> ().count (endpoint_a.address ()) >= nano::transport::max_peers_per_ip); return result; } bool nano::transport::udp_channels::reachout (nano::endpoint const & endpoint_a) { // Don't overload single IP bool error = max_ip_connections (endpoint_a); if (!error) { auto endpoint_l (nano::transport::map_endpoint_to_v6 (endpoint_a)); // Don't keepalive to nodes that already sent us something error |= channel (endpoint_l) != nullptr; nano::lock_guard<std::mutex> lock (mutex); auto existing (attempts.find (endpoint_l)); error |= existing != attempts.end (); attempts.insert ({ endpoint_l, std::chrono::steady_clock::now () }); } return error; } std::unique_ptr<nano::seq_con_info_component> nano::transport::udp_channels::collect_seq_con_info (std::string const & name) { size_t channels_count = 0; size_t attemps_count = 0; { nano::lock_guard<std::mutex> guard (mutex); channels_count = channels.size (); attemps_count = attempts.size (); } auto composite = std::make_unique<seq_con_info_composite> (name); composite->add_component (std::make_unique<seq_con_info_leaf> (seq_con_info{ "channels", channels_count, sizeof (decltype (channels)::value_type) })); composite->add_component (std::make_unique<seq_con_info_leaf> (seq_con_info{ "attempts", attemps_count, sizeof (decltype (attempts)::value_type) })); return composite; } void nano::transport::udp_channels::purge (std::chrono::steady_clock::time_point const & cutoff_a) { nano::lock_guard<std::mutex> lock (mutex); auto disconnect_cutoff (channels.get<last_packet_received_tag> ().lower_bound (cutoff_a)); channels.get<last_packet_received_tag> ().erase (channels.get<last_packet_received_tag> ().begin (), disconnect_cutoff); // Remove keepalive attempt tracking for attempts older than cutoff auto attempts_cutoff (attempts.get<1> ().lower_bound (cutoff_a)); attempts.get<1> ().erase (attempts.get<1> ().begin (), attempts_cutoff); } void nano::transport::udp_channels::ongoing_keepalive () { nano::keepalive message; node.network.random_fill (message.peers); std::vector<std::shared_ptr<nano::transport::channel_udp>> send_list; nano::unique_lock<std::mutex> lock (mutex); auto keepalive_cutoff (channels.get<last_packet_received_tag> ().lower_bound (std::chrono::steady_clock::now () - node.network_params.node.period)); for (auto i (channels.get<last_packet_received_tag> ().begin ()); i != keepalive_cutoff; ++i) { send_list.push_back (i->channel); } lock.unlock (); for (auto & channel : send_list) { channel->send (message); } std::weak_ptr<nano::node> node_w (node.shared ()); node.alarm.add (std::chrono::steady_clock::now () + node.network_params.node.period, [node_w]() { if (auto node_l = node_w.lock ()) { node_l->network.udp_channels.ongoing_keepalive (); } }); } void nano::transport::udp_channels::list (std::deque<std::shared_ptr<nano::transport::channel>> & deque_a) { nano::lock_guard<std::mutex> lock (mutex); for (auto i (channels.begin ()), j (channels.end ()); i != j; ++i) { deque_a.push_back (i->channel); } } void nano::transport::udp_channels::modify (std::shared_ptr<nano::transport::channel_udp> channel_a, std::function<void(std::shared_ptr<nano::transport::channel_udp>)> modify_callback_a) { nano::lock_guard<std::mutex> lock (mutex); auto existing (channels.get<endpoint_tag> ().find (channel_a->endpoint)); if (existing != channels.get<endpoint_tag> ().end ()) { channels.get<endpoint_tag> ().modify (existing, [modify_callback_a](channel_udp_wrapper & wrapper_a) { modify_callback_a (wrapper_a.channel); }); } }
34.346154
313
0.707727
[ "vector", "transform" ]
f67654339fc6b65a050c85a481c58974ed580d42
17,256
cc
C++
src/yb/docdb/subdocument.cc
vkulichenko/yugabyte-db
6b14282916e30afd41c8f8878fb2040449426158
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/docdb/subdocument.cc
vkulichenko/yugabyte-db
6b14282916e30afd41c8f8878fb2040449426158
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/docdb/subdocument.cc
vkulichenko/yugabyte-db
6b14282916e30afd41c8f8878fb2040449426158
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/docdb/subdocument.h" #include <map> #include <vector> #include "yb/common/ql_type.h" #include "yb/common/ql_value.h" #include "yb/docdb/value_type.h" #include "yb/gutil/casts.h" #include "yb/util/status.h" using std::endl; using std::make_pair; using std::map; using std::ostringstream; using std::shared_ptr; using std::string; using std::vector; using yb::bfql::TSOpcode; namespace yb { namespace docdb { SubDocument::SubDocument(ValueType value_type) : PrimitiveValue(value_type) { if (IsCollectionType(value_type)) { EnsureContainerAllocated(); } } SubDocument::SubDocument() : SubDocument(ValueType::kObject) {} SubDocument::SubDocument(ListExtendOrder extend_order) : SubDocument(ValueType::kArray) { extend_order_ = extend_order; } SubDocument::SubDocument( const std::vector<PrimitiveValue> &elements, ListExtendOrder extend_order) { type_ = ValueType::kArray; extend_order_ = extend_order; complex_data_structure_ = new ArrayContainer(); array_container().reserve(elements.size()); for (auto& elt : elements) { array_container().emplace_back(elt); } } SubDocument::~SubDocument() { switch (type_) { case ValueType::kObject: FALLTHROUGH_INTENDED; case ValueType::kRedisList: FALLTHROUGH_INTENDED; case ValueType::kRedisSortedSet: FALLTHROUGH_INTENDED; case ValueType::kRedisSet: FALLTHROUGH_INTENDED; case ValueType::kRedisTS: FALLTHROUGH_INTENDED; case ValueType::kSSForward: FALLTHROUGH_INTENDED; case ValueType::kSSReverse: if (has_valid_container()) { delete &object_container(); } break; case ValueType::kArray: if (has_valid_container()) { delete &array_container(); } break; default: break; } } SubDocument::SubDocument(const SubDocument& other) { if (IsPrimitiveValueType(other.type_) || other.type_ == ValueType::kInvalid || other.type_ == ValueType::kTombstone) { new(this) PrimitiveValue(other); } else { type_ = other.type_; ttl_seconds_ = other.ttl_seconds_; write_time_ = other.write_time_; complex_data_structure_ = nullptr; switch (type_) { case ValueType::kObject: if (other.has_valid_object_container()) { complex_data_structure_ = new ObjectContainer(other.object_container()); } break; case ValueType::kArray: if (other.has_valid_array_container()) { complex_data_structure_ = new ArrayContainer(other.array_container()); } break; default: LOG(FATAL) << "Trying to copy an invalid/unsupported SubDocument type: " << docdb::ToString(type_); } } } bool SubDocument::operator ==(const SubDocument& other) const { if (type_ != other.type_) { return false; } if (IsPrimitiveValueType(type_)) { return this->PrimitiveValue::operator==(other); } switch (type_) { case ValueType::kObject: if (has_valid_container() != other.has_valid_container()) { return has_valid_container() ? object_container().empty() : other.object_container().empty(); } if (has_valid_container()) { return object_container() == other.object_container(); } else { return true; // Both container pointers are nullptr. } case ValueType::kArray: if (has_valid_container() != other.has_valid_container()) { return has_valid_container() ? array_container().empty() : other.array_container().empty(); } if (has_valid_container()) { return array_container() == other.array_container(); } else { return true; } default: LOG(FATAL) << "Trying to compare SubDocuments of invalid type: " << docdb::ToString(type_); } // We'll get here if both container pointers are null. return true; } Status SubDocument::ConvertToCollection(ValueType value_type) { if (!has_valid_object_container()) { return STATUS(InvalidArgument, "Subdocument doesn't have valid object container"); } type_ = value_type; return Status::OK(); } void SubDocument::MoveFrom(SubDocument* other) { if (this == other) { return; } if (IsPrimitiveValueType(other->type_)) { new(this) PrimitiveValue(std::move(*other)); } else { // For objects/arrays the internal state is just a type and a pointer. extend_order_ = other->extend_order_; type_ = other->type_; ttl_seconds_ = other->ttl_seconds_; write_time_ = other->write_time_; complex_data_structure_ = other->complex_data_structure_; // The internal state of the other subdocument is now owned by this one. #ifndef NDEBUG // Another layer of protection against trying to use the old state in debug mode. memset(static_cast<void*>(other), 0xab, sizeof(SubDocument)); // Fill with a random value. #endif other->type_ = ValueType::kNullLow; // To avoid deallocation of the old object's memory. } } Status SubDocument::ConvertToRedisTS() { return ConvertToCollection(ValueType::kRedisTS); } Status SubDocument::ConvertToRedisSet() { return ConvertToCollection(ValueType::kRedisSet); } Status SubDocument::ConvertToRedisSortedSet() { return ConvertToCollection(ValueType::kRedisSortedSet); } Status SubDocument::ConvertToRedisList() { return ConvertToCollection(ValueType::kRedisList); } Status SubDocument::NumChildren(size_t *num_children) { if (!has_valid_object_container()) { return STATUS(IllegalState, "Not a valid object container"); } *num_children = object_container().size(); return Status::OK(); } SubDocument* SubDocument::GetChild(const PrimitiveValue& key) { if (!has_valid_object_container()) { return nullptr; } auto& obj_container = object_container(); auto iter = obj_container.find(key); if (iter == obj_container.end()) { return nullptr; } else { return &iter->second; } } const SubDocument* SubDocument::GetChild(const PrimitiveValue& key) const { if (!has_valid_object_container()) { return nullptr; } const auto& obj_container = object_container(); auto iter = obj_container.find(key); if (iter == obj_container.end()) { return nullptr; } else { return &iter->second; } } std::pair<SubDocument*, bool> SubDocument::GetOrAddChild(const PrimitiveValue& key) { DCHECK(IsObjectType(type_)); EnsureContainerAllocated(); auto& obj_container = object_container(); auto iter = obj_container.find(key); if (iter == obj_container.end()) { auto ret = obj_container.insert(make_pair(key, SubDocument())); CHECK(ret.second); return make_pair(&ret.first->second, true); // New subdocument created. } else { return make_pair(&iter->second, false); // No new subdocument created. } } void SubDocument::AddListElement(SubDocument&& value) { DCHECK_EQ(ValueType::kArray, type_); EnsureContainerAllocated(); array_container().emplace_back(std::move(value)); } void SubDocument::SetChild(const PrimitiveValue& key, SubDocument&& value) { EnsureObjectAllocated(); auto& obj_container = object_container(); auto existing_element = obj_container.find(key); if (existing_element == obj_container.end()) { const bool inserted_value = obj_container.emplace(key, std::move(value)).second; CHECK(inserted_value); } else { existing_element->second = std::move(value); } } bool SubDocument::DeleteChild(const PrimitiveValue& key) { CHECK_EQ(ValueType::kObject, type_); if (!has_valid_object_container()) return false; return object_container().erase(key) > 0; } string SubDocument::ToString() const { ostringstream ss; ss << *this; return ss.str(); } ostream& operator <<(ostream& out, const SubDocument& subdoc) { SubDocumentToStreamInternal(out, subdoc, 0); return out; } void SubDocumentToStreamInternal(ostream& out, const SubDocument& subdoc, const int indent) { if (subdoc.IsPrimitive() || subdoc.value_type() == ValueType::kInvalid || subdoc.value_type() == ValueType::kTombstone) { out << static_cast<const PrimitiveValue*>(&subdoc)->ToString(); return; } switch (subdoc.value_type()) { case ValueType::kRedisSortedSet: FALLTHROUGH_INTENDED; case ValueType::kObject: { out << "{"; if (subdoc.container_allocated()) { bool first_pair = true; for (const auto& key_value : subdoc.object_container()) { if (!first_pair) { out << ","; } first_pair = false; out << "\n" << string(indent + 2, ' ') << key_value.first.ToString() << ": "; SubDocumentToStreamInternal(out, key_value.second, indent + 2); } if (!first_pair) { out << "\n" << string(indent, ' '); } } out << "}"; break; } case ValueType::kArray: { out << "["; if (subdoc.container_allocated()) { out << (subdoc.GetExtendOrder() == ListExtendOrder::APPEND ? "APPEND" : "PREPEND") << "\n"; const auto& list = subdoc.array_container(); size_t i = 0; for (; i < list.size(); i++) { if (i != 0) { out << ","; } out << "\n" << string(indent + 2, ' ') << i << ": "; SubDocumentToStreamInternal(out, list[i], indent + 2); } if (i > 0) { out << "\n" << string(indent, ' '); } } out << "]"; break; } case ValueType::kRedisSet: { SubDocCollectionToStreamInternal(out, subdoc, indent, "(", ")"); break; } case ValueType::kRedisList: { SubDocCollectionToStreamInternal(out, subdoc, indent, "[", "]"); break; } case ValueType::kRedisTS: { SubDocCollectionToStreamInternal(out, subdoc, indent, "<", ">"); break; } default: LOG(FATAL) << "Invalid subdocument type: " << ToString(subdoc.value_type()); } } void SubDocCollectionToStreamInternal(ostream& out, const SubDocument& subdoc, const int indent, const string& begin_delim, const string& end_delim) { out << begin_delim; if (subdoc.container_allocated()) { const auto& keys = subdoc.object_container(); for (auto iter = keys.begin(); iter != keys.end(); iter++) { if (iter != keys.begin()) { out << ","; } out << "\n" << string(indent + 2, ' ') << (*iter).first.ToString(); } if (!keys.empty()) { out << "\n" << string(indent, ' '); } } out << end_delim; } void SubDocument::EnsureObjectAllocated() { type_ = ValueType::kObject; EnsureContainerAllocated(); } void SubDocument::EnsureContainerAllocated() { if (complex_data_structure_ == nullptr) { if (IsObjectType(type_)) { complex_data_structure_ = new ObjectContainer(); } else if (type_ == ValueType::kArray) { complex_data_structure_ = new ArrayContainer(); } } } SubDocument SubDocument::FromQLValuePB(const QLValuePB& value, SortingType sorting_type, TSOpcode write_instr) { switch (value.value_case()) { case QLValuePB::kMapValue: { QLMapValuePB map = value.map_value(); // this equality should be ensured by checks before getting here DCHECK_EQ(map.keys_size(), map.values_size()); SubDocument map_doc; for (int i = 0; i < map.keys_size(); i++) { PrimitiveValue pv_key = PrimitiveValue::FromQLValuePB(map.keys(i), sorting_type); SubDocument pv_val = SubDocument::FromQLValuePB(map.values(i), sorting_type, write_instr); map_doc.SetChild(pv_key, std::move(pv_val)); } // ensure container allocated even if map is empty map_doc.EnsureContainerAllocated(); return map_doc; } case QLValuePB::kSetValue: { QLSeqValuePB set = value.set_value(); SubDocument set_doc; for (auto& elem : set.elems()) { PrimitiveValue pv_key = PrimitiveValue::FromQLValuePB(elem, sorting_type); if (write_instr == TSOpcode::kSetRemove || write_instr == TSOpcode::kMapRemove) { // representing sets elems as keys pointing to tombstones to remove those entries set_doc.SetChildPrimitive(pv_key, PrimitiveValue::kTombstone); } else { // representing sets elems as keys pointing to empty (null) values set_doc.SetChildPrimitive(pv_key, PrimitiveValue()); } } // ensure container allocated even if set is empty set_doc.EnsureContainerAllocated(); return set_doc; } case QLValuePB::kListValue: { QLSeqValuePB list = value.list_value(); SubDocument list_doc(ValueType::kArray); // ensure container allocated even if list is empty list_doc.EnsureContainerAllocated(); for (int i = 0; i < list.elems_size(); i++) { SubDocument pv_val = SubDocument::FromQLValuePB(list.elems(i), sorting_type, write_instr); list_doc.AddListElement(std::move(pv_val)); } return list_doc; } default: return SubDocument(PrimitiveValue::FromQLValuePB(value, sorting_type)); } } void SubDocument::ToQLValuePB(const SubDocument& doc, const shared_ptr<QLType>& ql_type, QLValuePB* ql_value) { // interpreting empty collections as null values following Cassandra semantics if (ql_type->HasComplexValues() && (!doc.has_valid_object_container() || doc.object_num_keys() == 0)) { SetNull(ql_value); return; } switch (ql_type->main()) { case MAP: { const shared_ptr<QLType>& keys_type = ql_type->params()[0]; const shared_ptr<QLType>& values_type = ql_type->params()[1]; QLMapValuePB *value_pb = ql_value->mutable_map_value(); value_pb->clear_keys(); value_pb->clear_values(); for (auto &pair : doc.object_container()) { QLValuePB *key = value_pb->add_keys(); PrimitiveValue::ToQLValuePB(pair.first, keys_type, key); QLValuePB *value = value_pb->add_values(); SubDocument::ToQLValuePB(pair.second, values_type, value); } return; } case SET: { const shared_ptr<QLType>& elems_type = ql_type->params()[0]; QLSeqValuePB *value_pb = ql_value->mutable_set_value(); value_pb->clear_elems(); for (auto &pair : doc.object_container()) { QLValuePB *elem = value_pb->add_elems(); PrimitiveValue::ToQLValuePB(pair.first, elems_type, elem); // set elems are represented as subdocument keys so we ignore the (empty) values } return; } case LIST: { const shared_ptr<QLType>& elems_type = ql_type->params()[0]; QLSeqValuePB *value_pb = ql_value->mutable_list_value(); value_pb->clear_elems(); for (auto &pair : doc.object_container()) { // list elems are represented as subdocument values with keys only used for ordering QLValuePB *elem = value_pb->add_elems(); SubDocument::ToQLValuePB(pair.second, elems_type, elem); } return; } case USER_DEFINED_TYPE: { const shared_ptr<QLType>& keys_type = QLType::Create(INT16); QLMapValuePB *value_pb = ql_value->mutable_map_value(); value_pb->clear_keys(); value_pb->clear_values(); for (auto &pair : doc.object_container()) { QLValuePB *key = value_pb->add_keys(); PrimitiveValue::ToQLValuePB(pair.first, keys_type, key); QLValuePB *value = value_pb->add_values(); SubDocument::ToQLValuePB(pair.second, ql_type->param_type(key->int16_value()), value); } return; } case TUPLE: break; default: { return PrimitiveValue::ToQLValuePB(doc, ql_type, ql_value); } } LOG(FATAL) << "Unsupported datatype in SubDocument: " << ql_type->ToString(); } int SubDocument::object_num_keys() const { DCHECK(IsObjectType(type_)); if (!has_valid_object_container()) { return 0; } return narrow_cast<int>(object_container().size()); } bool SubDocument::container_allocated() const { CHECK(IsCollectionType(type_)); return complex_data_structure_ != nullptr; } bool SubDocument::has_valid_object_container() const { return (IsObjectType(type_)) && has_valid_container(); } bool SubDocument::has_valid_array_container() const { return type_ == ValueType::kArray && has_valid_container(); } } // namespace docdb } // namespace yb
32.497175
100
0.646094
[ "object", "vector" ]
f6771b074d4a05a2ae0f16170540bb1931925b17
5,114
cxx
C++
test/rtkdrawgeometricphantomtest.cxx
thewtex/RTK
4b762e803de6f1da11e2497158efcbd059f90a0f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
test/rtkdrawgeometricphantomtest.cxx
thewtex/RTK
4b762e803de6f1da11e2497158efcbd059f90a0f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
test/rtkdrawgeometricphantomtest.cxx
thewtex/RTK
4b762e803de6f1da11e2497158efcbd059f90a0f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
#include "rtkTest.h" #include "rtkMacro.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkConstantImageSource.h" #include "rtkGeometricPhantomFileReader.h" #include "rtkDrawGeometricPhantomImageFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkDrawCylinderImageFilter.h" #include "rtkDrawConeImageFilter.h" #include <itkRegularExpressionSeriesFileNames.h> typedef rtk::ThreeDCircularProjectionGeometry GeometryType; /** * \file rtkdrawgeometricphantomtest.cxx * * \brief Functional test for the class that creates a geometric phantom * specified in a config file. * * This test generates several phantoms with different geometrical shapes * (Cone, Cylinder, Shepp-Logan...) specified by configuration files. * The generated results are compared to the expected results, which are * created through hard-coded geometric parameters. * * \author Marc Vila */ int main(int argc, char*argv[]) { if (argc < 3) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " SheppLoganConfig.txt GeometryConfig.txt" << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 3; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New(); origin[0] = -127.; origin[1] = -127.; origin[2] = -127.; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 254.; spacing[1] = 254.; spacing[2] = 254.; #else size[0] = 128; size[1] = 128; size[2] = 128; spacing[0] = 2.; spacing[1] = 2.; spacing[2] = 2.; #endif tomographySource->SetOrigin( origin ); tomographySource->SetSpacing( spacing ); tomographySource->SetSize( size ); tomographySource->SetConstant( 0. ); ////////////////////////////////// // Part 1: Shepp Logan ////////////////////////////////// // Shepp Logan reference filter typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType; DSLType::Pointer dsl=DSLType::New(); dsl->SetInput( tomographySource->GetOutput() ); dsl->SetPhantomScale(128.); dsl->InPlaceOff(); TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() ); // Shepp Logan reference filter from Configuration File typedef rtk::DrawGeometricPhantomImageFilter<OutputImageType, OutputImageType> DGPType; DGPType::Pointer dgp=DGPType::New(); dgp->SetInput( tomographySource->GetOutput() ); dgp->InPlaceOff(); dgp->SetConfigFile(argv[1]); TRY_AND_EXIT_ON_ITK_EXCEPTION( dgp->Update() ); CheckImageQuality<OutputImageType>(dsl->GetOutput(), dgp->GetOutput(), 0.0005, 90, 255.0); std::cout << "Test PASSED! " << std::endl; ////////////////////////////////// // Part 2: other geometries than ellipsoid ////////////////////////////////// // New Geometries from Configuration File dgp->SetInput( tomographySource->GetOutput() ); dgp->SetConfigFile(argv[2]); dgp->InPlaceOff(); TRY_AND_EXIT_ON_ITK_EXCEPTION( dgp->Update() ); // // Create Reference // std::vector< double > axis; // axis.push_back(100.); // axis.push_back(0.); // axis.push_back(100.); // std::vector< double > center; // center.push_back(2.); // center.push_back(2.); // center.push_back(2.); // Draw CYLINDER typedef rtk::DrawCylinderImageFilter<OutputImageType, OutputImageType> DCType; DCType::Pointer dcl = DCType::New(); DCType::VectorType axis, center; axis[0] = 100.; axis[1] = 0.; axis[2] = 100.; center[0] = 2.; center[1] = 2.; center[2] = 2.; dcl->SetInput( tomographySource->GetOutput() ); dcl->SetAxis(axis); dcl->SetCenter(center); dcl->SetAngle(0.); dcl->SetDensity(2.); dcl->InPlaceOff(); // Draw CONE //axis.clear(); axis[0] = 25.; axis[1] = -50.; axis[2] = 25.; typedef rtk::DrawConeImageFilter<OutputImageType, OutputImageType> DCOType; DCOType::Pointer dco = DCOType::New(); dco->SetInput( tomographySource->GetOutput() ); dco->SetAxis(axis); dco->SetCenter(center); dco->SetAngle(0.); dco->SetDensity(-0.54); //Add Image Filter used to concatenate the different figures obtained on each iteration typedef itk::AddImageFilter <OutputImageType, OutputImageType, OutputImageType> AddImageFilterType; AddImageFilterType::Pointer addFilter = AddImageFilterType::New(); addFilter->SetInput1(dcl->GetOutput()); addFilter->SetInput2(dco->GetOutput()); TRY_AND_EXIT_ON_ITK_EXCEPTION( addFilter->Update() ); CheckImageQuality<OutputImageType>(dgp->GetOutput(), addFilter->GetOutput(), 0.0005, 90, 255.0); std::cout << "Test PASSED! " << std::endl; return EXIT_SUCCESS; }
31.567901
103
0.658584
[ "vector" ]
f67730e0be7419d510e1d9f77d2afcdb6e9e6093
263,212
cpp
C++
SRC/scriptCompile.cpp
CristiFati/ChatScript
1fe290ac41feb03e1859e9fa2ee0616826fa36f1
[ "MIT" ]
null
null
null
SRC/scriptCompile.cpp
CristiFati/ChatScript
1fe290ac41feb03e1859e9fa2ee0616826fa36f1
[ "MIT" ]
null
null
null
SRC/scriptCompile.cpp
CristiFati/ChatScript
1fe290ac41feb03e1859e9fa2ee0616826fa36f1
[ "MIT" ]
null
null
null
#include "common.h" //------------------------ // ALWAYS AVAILABLE //------------------------ #define PATTERNDEPTH 1000 static HEAPREF undefinedCallThreadList = NULL; static bool nospellcheck = false; bool disablePatternOptimization = true; static bool noPatternOptimization = true; static unsigned int conceptID = 0; // name of concept set static int complexity = 0; static bool livecall = false; static unsigned int priorLine = 0; static char* currentTopicBots = NULL; bool autoset = false; static char macroName[MAX_WORD_SIZE]; static uint64 macroid; char* dataBase = NULL; static char* dataChunk = NULL; static char* outputStart = NULL; static char* lineStart = NULL; static bool globalBotScope = false; static HEAPREF beenHereThreadList = NULL; char* newBuffer = NULL; char* oldBuffer = NULL; static char display[MAX_DISPLAY][100]; static int displayIndex = 0; static char* incomingPtrSys = 0; // cache AFTER token find ptr when peeking. static char lookaheadSys[MAX_WORD_SIZE]; // cache token found when peeking static unsigned int hasWarnings; // number of warnings generated unsigned int hasErrors; uint64 grade = 0; // vocabulary warning char* lastDeprecation = 0; bool compiling = false; // script compiler in progress bool patternContext = false; // current compiling a pattern unsigned int buildId; // current build static int callingSystem = 0; static bool chunking = false; static unsigned int substitutes; static unsigned int cases; static unsigned int badword; static unsigned int functionCall; static bool isDescribe = false; char* tableinput = NULL; char warnings[MAX_WARNINGS][MAX_WORD_SIZE]; unsigned int warnIndex = 0; static char baseName[SMALL_WORD_SIZE]; char errors[MAX_ERRORS][MAX_WORD_SIZE]; unsigned int errorIndex = 0; static char functionArguments[MAX_ARGUMENT_COUNT+1][500]; static int functionArgumentCount = 0; char scopeBotName[MAX_WORD_SIZE]; static bool renameInProgress = false; static bool endtopicSeen = false; // needed when ending a plan static char* nextToken; // current lookahead token unsigned int buildID = 0; static char* topicFiles[] = // files created by a topic refresh from scratch { (char*)"describe", // document variables functions concepts topics etc (char*)"facts", // hold facts (char*)"keywords", // holds topic and concepts keywords (char*)"macros", // holds macro definitions (char*)"map", // where things are defined (char*)"script", // hold topic definitions (char*)"plans", // hold plan definitions (char*)"patternWords", // things we want to detect in patterns that may not be normal words (char*)"dict", // dictionary changes (char*)"private", // private substitutions changes (char*)"canon", // private canonical values 0 }; static void WriteKey(char* word); static FILE* mapFile = NULL; // for IDE static FILE* patternFile = NULL; // where to store pattern words void InitScriptSystem() { mapFile = NULL; outputStart = NULL; } void AddWarning(char* buffer) { char c = buffer[MAX_WORD_SIZE - 300]; if (strlen(buffer) > (MAX_WORD_SIZE - 300)) buffer[MAX_WORD_SIZE - 300] = 0; sprintf(warnings[warnIndex++],(char*)"line %d of %s: %s",currentFileLine,currentFilename,buffer); buffer[MAX_WORD_SIZE - 300] = c; if (strstr(warnings[warnIndex-1],(char*)"is not a known word")) {++badword;} else if (strstr(warnings[warnIndex-1],(char*)" changes ")) {++substitutes;} else if (strstr(warnings[warnIndex-1],(char*)"is unknown as a word")) {++badword;} else if (strstr(warnings[warnIndex-1],(char*)"in opposite case")){++cases;} else if (strstr(warnings[warnIndex - 1], (char*)"multiple spellings")) { ++cases; } else if (strstr(warnings[warnIndex-1],(char*)"a function call")){++functionCall;} if (warnIndex >= MAX_WARNINGS) --warnIndex; } bool StartScriptCompiler(bool normal, bool live) { #ifndef DISCARDSCRIPTCOMPILER if (nextToken && normal) return false; if (oldBuffer) return false; // already running one disablePatternOptimization = live; // IF Pattern and match cannot safely optimize conceptID = 0; patternFile = NULL; beenHereThreadList = NULL; livecall = live; oldBuffer = newBuffer; warnIndex = errorIndex = 0; newBuffer = AllocateStack(NULL, maxBufferSize); nextToken = AllocateStack(NULL, maxBufferSize); // able to swallow big #endif return true; } void EndScriptCompiler() { #ifndef DISCARDSCRIPTCOMPILER if (newBuffer) { ReleaseStack(newBuffer); newBuffer = oldBuffer; oldBuffer = NULL; nextToken = NULL; } #endif } void ScriptError() { #ifndef DISCARDSCRIPTCOMPILER callingSystem = 0; chunking = false; outputStart = NULL; renameInProgress = false; if (compiling) { ++hasErrors; patternContext = false; if (*scopeBotName) Log(STDUSERLOG, (char*)"*** Error- line %d column %d of %s bot:%s : ", currentFileLine, currentLineColumn, currentFilename, scopeBotName); else Log(STDUSERLOG, (char*)"*** Error- line %d column %d of %s: ", currentFileLine, currentLineColumn, currentFilename); } #endif } #ifndef DISCARDSCRIPTCOMPILER void ScriptWarn() { if (compiling) { ++hasWarnings; if (*currentFilename) { if (*scopeBotName) Log(STDUSERLOG, (char*)"*** Warning- line %d column %d of %s bot:%s : ", currentFileLine, currentLineColumn,currentFilename, scopeBotName); else Log(STDUSERLOG, (char*)"*** Warning- line %d column %d of %s: ", currentFileLine, currentLineColumn,currentFilename); } else Log(STDUSERLOG, (char*)"*** Warning- "); } } static void AddBeenHere(WORDP D) { D->internalBits |= BEEN_HERE; beenHereThreadList = AllocateHeapval(beenHereThreadList, (uint64)D, NULL, NULL);// save name } void UnbindBeenHere() { while (beenHereThreadList) { uint64 D; beenHereThreadList = UnpackHeapval(beenHereThreadList, D,discard); ((WORDP)D)->internalBits &= -1 ^ BEEN_HERE; } } #endif void AddError(char* buffer) { char message[MAX_WORD_SIZE]; if (*buffer == '\r') ++buffer; if (*buffer == '\n') ++buffer; size_t len = strlen(buffer); char c = buffer[MAX_WORD_SIZE - 300]; while (buffer[len - 1] == '\n' || buffer[len - 1] == '\r') buffer[--len] = 0; if (strlen(buffer) > (MAX_WORD_SIZE - 300)) buffer[MAX_WORD_SIZE - 300] = 0; sprintf(message, "%s - line %d column %d of %s %s\r\n", buffer, currentFileLine, currentLineColumn, currentFilename, scopeBotName); buffer[MAX_WORD_SIZE - 300] = c; sprintf(errors[errorIndex++], (char*)"%s\r\n", message); if (errorIndex >= MAX_ERRORS) --errorIndex; } static char* FindComparison(char* word) { if (!*word || !word[1] || !word[2] || *word == '"') return NULL; // if token is short, we cannot do the below word+1 scans if (*word == '.') return NULL; // .<_3 is not a comparison if (*word == '\\') return NULL; // escaped is not a comparison if (*word == '!' && word[1] == '?' && word[2] == '$') return NULL; if (*word == '_' && word[1] == '?' && word[2] == '$') return NULL; if (*word == '?' && word[1] == '$') return NULL; char* at = strchr(word + 1, '!'); if (at && *word == '!') at = NULL; // ignore !! if (!at) { at = strchr(word + 1, '<'); if (at && at[1] == '<') return NULL; // << is not a comparison } if (!at) { at = strchr(word + 1, '>'); if (at && at[1] == '>') return NULL; // >> is not a comparison } if (!at) { at = strchr(word + 1, '&'); if (at && (at[1] == '_' || at[1] == ' ')) at = 0; // ignore & as part of a name } if (!at) at = strchr(word + 1, '='); if (!at) at = strchr(word + 1, '?'); // member of set if (!at) { at = strchr(word + 1, '!'); // negation if (at && (at[1] == '=' || at[1] == '?')); else at = NULL; } return at; } static void InsureAppropriateCase(char* word) { char c; char* at = FindComparison(word); // force to lower case various standard things // topcs/sets/classes/user vars/ functions and function vars are always lower case if (at) // a comparison has 2 sides { c = *at; *at = 0; InsureAppropriateCase(word); if (at[1] == '=' || at[1] == '?') InsureAppropriateCase(at + 2); // == or >= or such else InsureAppropriateCase(at + 1); *at = c; } else if (*word == '_' || *word == '\'') InsureAppropriateCase(word + 1); else if (*word == USERVAR_PREFIX) { char* dot = strchr(word, '.'); if (dot) *dot = 0; MakeLowerCase(word); if (dot) *dot = '.'; } else if ((*word == '^' && word[1] != '"') || *word == '~' || *word == SYSVAR_PREFIX || *word == '|') MakeLowerCase(word); else if (*word == '@' && IsDigit(word[1])) MakeLowerCase(word); // potential factref like @2subject } static int GetFunctionArgument(char* arg) // get index of argument (0-based) if it is value, else -1 { for (int i = 0; i < functionArgumentCount; ++i) { if (!stricmp(arg, functionArguments[i])) return i; } return -1; // failed } static void FindDeprecated(char* ptr, char* value, char* message) { char* comment = strstr(ptr, (char*)"# "); char* at = ptr; size_t len = strlen(value); while (at) { at = strstr(at, value); if (!at) break; if (*(at - 1) == USERVAR_PREFIX) // $$xxx should be ignored { at += 2; continue; } if (comment && at > comment) return; // inside a comment char word[MAX_WORD_SIZE]; ReadCompiledWord(at, word); if (!stricmp(value, word)) { lastDeprecation = at; BADSCRIPT(message); } at += len; } } static void AddDisplay(char* word) { MakeLowerCase(word); for (int i = 0; i < displayIndex; ++i) { if (!strcmp(word, display[i])) return; // no duplicates needed } strcpy(display[displayIndex], word); if (++displayIndex >= MAX_DISPLAY) BADSCRIPT("Display argument limited to %d: %s\r\n", MAX_DISPLAY, word) } static char* ReadDisplay(FILE* in, char* ptr) { char word[SMALL_WORD_SIZE]; ptr = ReadNextSystemToken(in, ptr, word, false); while (1) { ptr = ReadNextSystemToken(in, ptr, word, false); if (*word == ')') break; if (*word != USERVAR_PREFIX) BADSCRIPT("Display argument must be uservar of $$ $ or $_: %s\r\n", word) if (strchr(word, '.')) BADSCRIPT("Display argument cannot be dot-selected %s\r\n", word) AddDisplay(word); // explicit display } return ptr; } char* ReadSystemToken(char* ptr, char* word, bool separateUnderscore) // how we tokenize system stuff (rules and topic system) words -remaps & to AND { *word = 0; if (!ptr) return 0; char tmp[MAX_WORD_SIZE]; char* start = word; *start = 0; ptr = SkipWhitespace(ptr); FindDeprecated(ptr, (char*)"$bot", (char*)"Deprecated $bot needs to be $cs_bot"); FindDeprecated(ptr, (char*)"$login", (char*)"Deprecated $login needs to be $cs_login"); FindDeprecated(ptr, (char*)"$userfactlimit", (char*)"Deprecated $userfactlimit needs to be $cs_userfactlimit"); FindDeprecated(ptr, (char*)"$crashmsg", (char*)"Deprecated $crashmsg needs to be $cs_crashmsg"); FindDeprecated(ptr, (char*)"$token", (char*)"Deprecated $token needs to be $cs_token"); FindDeprecated(ptr, (char*)"$response", (char*)"Deprecated $response needs to be $cs_response"); FindDeprecated(ptr, (char*)"$randindex", (char*)"Deprecated $randindex needs to be $cs_randindex"); FindDeprecated(ptr, (char*)"$wildcardseparator", (char*)"Deprecated $wildcardseparator needs to be $cs_wildcardseparator"); FindDeprecated(ptr, (char*)"$abstract", (char*)"Deprecated $abstract needs to be $cs_abstract"); FindDeprecated(ptr, (char*)"$prepass", (char*)"Deprecated $prepass needs to be $cs_prepass"); FindDeprecated(ptr, (char*)"$control_main", (char*)"Deprecated $control_main needs to be $cs_control_main"); FindDeprecated(ptr, (char*)"$control_pre", (char*)"Deprecated $control_pre needs to be $cs_control_pre"); FindDeprecated(ptr, (char*)"$control_post", (char*)"Deprecated $control_post needs to be $cs_control_post"); #ifdef INFORMATION A token is nominally a contiguous collection of characters broken off by tab or space(since return and newline are stripped off). Tokens to include whitespace are encased in doublequotes. Characters with reserved status automatically also break into individual tokens and to include them you must put \ before them.These include : []() {} always and separate into individual tokens except for _(_[_{ < > and << >> are reserved, but only when at start or end of token.Allowed comparisons embedded.As is <= and >= Tokens ending with ' or 's break off(possessive) in patterns. Tokens starting with prefix characters ' or ! or _ keep together, except per reserved tokens. '$junk is one token. Variables ending with punctuation separate the punctuation.$hello.is two tokens as is _0. Reserved characters in a composite token with _ before or after are kept.E.g.This_(_story_is_)_done You can include a reserved tokens by putting \ in front of them. Some tokens revise their start, like the pattern tokens representing comparison.They do this in the script compiler. #endif // strings if (*ptr == '"' || (*ptr == '^' && ptr[1] == '"') || (*ptr == '^' && ptr[1] == '\'') || (*ptr == '\\' && ptr[1] == '"')) // doublequote maybe with functional heading { // simple \" if (*ptr == '\\' && (!ptr[2] || ptr[2] == ' ' || ptr[2] == '\t' || ptr[2] == ENDUNIT)) // legal { *word = '\\'; word[1] = '"'; word[2] = 0; return ptr + 2; } bool backslash = false; bool noblank = true; bool functionString = false; if (*ptr == '^') { *word++ = *ptr++; // ^"script" swallows ^ noblank = false; // allowed blanks at start or rear functionString = true; } else if (*ptr == '\\') // \"string is this" { backslash = true; ++ptr; } char* end = ReadQuote(ptr,word,backslash,noblank,MAX_WORD_SIZE); // swallow ending marker and points past if (!callingSystem && !isDescribe && !chunking && !functionString && *word == '"' && word[1] != '^' && strstr(word,"$_")) WARNSCRIPT((char*)"%s has potential local var $_ in it. This cannot be passed as argument to user macros. Is it intended to be?\r\n",word) if (end) { if (*word == '"' && word[1] != FUNCTIONSTRING && !functionString) return end; // all legal within // NOW WE SEE A FUNCTION STRING // when seeing ^, see if it remaps as a function argument // check for internal ^ also... char* hat = word - 1; if ((*word == '"' || *word == '\'') && functionString) hat = word; // came before else if (*word == '"' && word[1] == FUNCTIONSTRING) hat = word + 1; else if ((word[1] == '"' || word[1] == '\'') && *word == FUNCTIONSTRING) hat = word; // locate any local variable references in active strings char* at = word; while ((at = strchr(at,USERVAR_PREFIX))) { if (at[1] == LOCALVAR_PREFIX) { char* start = at; while (++at) { if (!IsAlphaUTF8OrDigit(*at) && *at != '_' && *at != '-') { char c = *at; *at = 0; AddDisplay(start); *at = c; break; } } } else ++at; } while ((hat = strchr(hat + 1,'^'))) // find a hat within { if (IsDigit(hat[1])) continue; // normal internal if (*(hat - 1) == '\\') continue; // escaped char* atx = hat; while (*++atx && (IsAlphaUTF8OrDigit(*atx) || *atx == '_')) { ; } char c = *atx; *atx = 0; int index = GetFunctionArgument(hat); WORDP D = FindWord(hat); // in case its a function name *atx = c; if (index >= 0) // was a function argument { strcpy(tmp,atx); // protect chunk sprintf(hat,(char*)"^%d%s",index,tmp); } else if (D && D->internalBits & FUNCTION_NAME) { ; } else if (!renameInProgress && !(hat[1] == USERVAR_PREFIX || hat[1] == '_')) { *atx = 0; WARNSCRIPT((char*)"%s is not a recognized function argument. Is it intended to be?\r\n",hat) *atx = c; } } hat = word - 1; while ((hat = strchr(hat + 1,'_'))) // rename _var? { if (IsAlphaUTF8OrDigit(*(hat - 1)) || *(hat - 1) == '_' || *(hat - 1) == '-') continue; // not a starter if (IsDigit(hat[1])) continue; // normal _ var if (*(hat - 1) == '\\' || *(hat - 1) == '"') continue; // escaped or quoted char* atx = hat; while (*++atx && (IsAlphaUTF8OrDigit(*atx))) { ; } // find end WORDP D = FindWord(hat,atx - hat,LOWERCASE_LOOKUP); if (D && D->internalBits & RENAMED) // remap matchvar inside string { strcpy(tmp,atx); // protect chunk sprintf(hat + 1,(char*)"%d%s",(unsigned int)D->properties,tmp); } } hat = word - 1; while ((hat = strchr(hat + 1,'@'))) // rename @set? { if (IsAlphaUTF8OrDigit(*(hat - 1))) continue; // not a starter if (IsDigit(hat[1]) || hat[1] == '_') continue; // normal @ var or @_marker if (*(hat - 1) == '\\') continue; // escaped char* atx = GetSetEnd(hat); WORDP D = FindWord(hat,atx - hat,LOWERCASE_LOOKUP); if (D && D->internalBits & RENAMED) // rename @set inside string { strcpy(tmp,atx); // protect chunk sprintf(hat + 1,(char*)"%d%s",(unsigned int)D->properties,tmp); } else if (!renameInProgress) // can do anything safely in a simple quoted string { char c = *at; *at = 0; WARNSCRIPT((char*)"%s is not a recognized @rename. Is it intended to be?\r\n",hat) *at = c; } } hat = word - 1; if (strstr(readBuffer, "rename:")) // accept rename of existing constant twice in a row hat = " "; while ((hat = strchr(hat + 1,'#'))) // rename #constant or ##constant { if (*(hat - 1) == '\\') continue; // escaped if (IsAlphaUTF8OrDigit(*(hat - 1)) || IsDigit(hat[1]) || *(hat - 1) == '&') continue; // not a starter, maybe #533; constant stuff char* at = hat; if (at[1] == '#') ++at; // user constant while (*++at && (IsAlphaUTF8OrDigit(*at) || *at == '_')) { ; } // find end strcpy(tmp,at); // protect chunk *at = 0; uint64 n; if (hat[1] == '#' && IsAlphaUTF8(hat[2])) // user constant { WORDP D = FindWord(hat,at - hat,LOWERCASE_LOOKUP); if (D && D->internalBits & RENAMED) // remap #constant inside string { n = D->properties; if (D->systemFlags & CONSTANT_IS_NEGATIVE) { int64 x = (int64)n; x = -x; #ifdef WIN32 sprintf(hat,(char*)"%I64d%s",(long long int) x,tmp); #else sprintf(hat,(char*)"%lld%s",(long long int) x,tmp); #endif } else { #ifdef WIN32 sprintf(hat,(char*)"%I64d%s",(long long int) n,tmp); #else sprintf(hat,(char*)"%lld%s",(long long int) n,tmp); #endif } } } else // system constant { n = FindValueByName(hat + 1); if (!n) n = FindSystemValueByName(hat + 1); if (!n) n = FindParseValueByName(hat + 1); if (!n) n = FindMiscValueByName(hat + 1); if (n) { #ifdef WIN32 sprintf(hat,(char*)"%I64d%s",(long long int) n,tmp); #else sprintf(hat,(char*)"%lld%s",(long long int) n,tmp); #endif } } if (!*hat) { *hat = '#'; BADSCRIPT((char*)"Bad # constant %s\r\n",hat) } } return end; // if we did swallow a string } if (*ptr == '\\') // was this \"xxx with NO closing { memmove(word + 1,word,strlen(word) + 1); *word = '\\'; } else { word = start; if (*start == '^') --ptr; } } // the normal composite token bool quote = false; char* xxorig = ptr; bool var = (*ptr == '$'); int brackets = 0; char quotechar = '"'; bool activestring = false; while (*ptr) { if (*ptr == ENDUNIT) break; if (patternContext && quote) {} // allow stuff in comparison quote else if (*ptr == ' ' || (*ptr == '\t' && convertTabs)) break; // legal if (patternContext && activestring == false && *ptr == '^' && (ptr[1] == '"' || ptr[1] == '\'')) { quotechar = ptr[1]; activestring = true; } if (patternContext && *ptr == quotechar) quote = !quote; char c = *ptr++; if (c == '\t' && !convertTabs && word != start) { --ptr; break; // end word with tab } *word++ = c; *word = 0; if (*start == '\t' && !convertTabs ) break; // return tab as unique word if ((word - start) > (MAX_WORD_SIZE - 2)) break; // avoid overflow if (c == '\\') *word++ = *ptr++; //escaped // want to leave array json notation alone but react to [...] touching a variable - $var] else if (var && c == '[') // ANY variable should be separated by space from a [ if not json array { ++brackets; // this MUST then be a json array and brackets will balance if (brackets > 1) BADSCRIPT("$var MUST be separated from [ unless you intend json array reference\r\n") } else if (var && c == ']') { if (--brackets < 0) // if brackets is set, we must be in json array { --ptr; --word; break; } } else if (GetNestingData(c) && !quote) // break off nesting attached to a started token unless its an escaped token { size_t len = word - start; if (len == 1) break; // automatically token by itself if (len == 2) { if ((*start == '_' || *start == '!') && (c == '[' || c == '(' || c == '{')) break; // one token as _( or !( if (*start == '\\') break; // one token escaped } // split off into two tokens --ptr; --word; break; } } *word = 0; word = start; size_t len = strlen(word); if (len == 0) return ptr; if (patternContext && word[len - 1] == '"' && word[len - 2] != '\\') { char* quote = strchr(word, '"'); if (quote == word + len - 1) BADSCRIPT("Tailing quote without start: %s\r\n", word) } if (*word == '#' && !strstr(readBuffer,"rename:")) // is this a constant from dictionary.h? or user constant { uint64 n; if (word[1] == '#' && IsAlphaUTF8(word[2])) // user constant { WORDP D = FindWord(word,0,LOWERCASE_LOOKUP); if (D && D->internalBits & RENAMED) // remap #constant { n = D->properties; if (D->systemFlags & CONSTANT_IS_NEGATIVE) { int64 x = (int64)n; x = -x; #ifdef WIN32 sprintf(word,(char*)"%I64d",(long long int) x); #else sprintf(word,(char*)"%lld",(long long int) x); #endif } else { #ifdef WIN32 sprintf(word,(char*)"%I64d",(long long int) n); #else sprintf(word,(char*)"%lld",(long long int) n); #endif } } else if (renameInProgress) { ; } // leave token alone, defining else BADSCRIPT((char*)"Bad user constant %s\r\n",word) } else // system constant { n = FindValueByName(word + 1); if (!n) n = FindSystemValueByName(word + 1); if (!n) n = FindParseValueByName(word + 1); if (!n) n = FindMiscValueByName(word + 1); if (n) { #ifdef WIN32 sprintf(word,(char*)"%I64d",(long long int) n); #else sprintf(word,(char*)"%lld",(long long int) n); #endif } else if (!IsDigit(word[1]) && word[1] != '!') //treat rest as a comment line (except if has number after it, which is user text OR internal arg reference for function { if (IsAlphaUTF8(word[1])) BADSCRIPT((char*)"Bad numeric # constant %s\r\n",word) *ptr = 0; *word = 0; } } } if (*word == '_' && (IsAlphaUTF8(word[1]))) // is this a rename _ { WORDP D = FindWord(word); if (D && D->internalBits & RENAMED) sprintf(word + 1,(char*)"%d",(unsigned int)D->properties); // remap match var convert to number // patterns can underscore ANYTING } if (*word == '\'' && word[1] == '_' && (IsAlphaUTF8(word[2]))) // is this a rename _ with ' { WORDP D = FindWord(word + 1); if (D && D->internalBits & RENAMED) sprintf(word + 2,(char*)"%d",(unsigned int)D->properties); // remap match var convert to number else if (!renameInProgress && !patternContext) // patterns can underscore ANYTING WARNSCRIPT((char*)"%s is not a recognized _rename. Should it be?\r\n",word + 1) } if (*word == '@' && IsAlphaUTF8(word[1])) // is this a rename @ { char* at = GetSetEnd(word); WORDP D = FindWord(word,at - word); if (D && D->internalBits & RENAMED) // remap @set in string { strcpy(tmp,at); // protect chunk sprintf(word + 1,(char*)"%d%s",(unsigned int)D->properties,tmp); } else if (!renameInProgress) WARNSCRIPT((char*)"%s is not a recognized @rename. Is it intended to be?\r\n",word) } if (*word == '@' && word[1] == '_' && IsAlphaUTF8(word[2])) // is this a rename @_0+ { size_t lenx = strlen(word); WORDP D = FindWord(word + 1, lenx - 1); // @_data marker char c = 0; if (!D) { c = word[lenx - 1]; word[lenx - 1] = 0; D = FindWord(word + 1, lenx - 2); word[lenx - 1] = c; } if (D && D->internalBits & RENAMED) { if (c) sprintf(word + 2,(char*)"%d%c",(unsigned int)D->properties,c); // remap @set in string else sprintf(word + 2, (char*)"%d", (unsigned int)D->properties); // remap @set in string } else if (!renameInProgress) WARNSCRIPT((char*)"%s is not a recognized @rename. Is it intended to be?\r\n",word) } // some tokens require special splitting // break off starting << from <<hello if (*word == '<' && word[1] != '=') { if (len == 3 && *word == word[1] && word[2] == '=') { ; } else if (word[1] == '<') { if (word[2]) // not assign operator { ptr -= strlen(word) - 2; // safe word[2] = 0; len -= 2; } } } // break off ending >> from hello>> if (len > 2 && word[len - 1] == '>') { if (len == 3 && *word == word[1] && word[2] == '=') { ; } else if (word[len - 2] == '>') { ptr -= 2; word[len - 2] = 0; len -= 2; } } // break off punctuation from variable end if (len > 2 && ((*word == USERVAR_PREFIX && !IsDigit(word[1])) || *word == '^' || (*word == '@' && IsDigit(word[1])) || *word == SYSVAR_PREFIX || (*word == '_' && IsDigit(word[1])) || (*word == '\'' && word[1] == '_'))) // not currency { if (!patternContext || word[len - 1] != '?') // BUT NOT $$xxx? in pattern context { while (IsRealPunctuation(word[len - 1])) // one would be enough, but $hello... needs to be addressed { --len; --ptr; } word[len] = 0; } } // break off opening < in pattern if (patternContext && *word == '<' && word[1] != '<') { ptr -= len - 1; len = 1; word[1] = 0; } // break off closing > in pattern unless escaped or notted if (len == 2 && (*word == '!' || *word == '\\')) { ; } else if (patternContext && len > 1 && word[len - 1] == '>' && word[len - 2] != '>' && word[len - 2] != '_' && word[len - 2] != '!') { ptr -= len - 1; --len; word[len - 1] = 0; } // find internal comparison op if any char* at = (patternContext) ? FindComparison(word) : 0; if (at && *word == '*' && !IsDigit(word[1])) { if (compiling) BADSCRIPT((char*)"TOKENS-1 Cannot do comparison on variable gap %s . Memorize and compare against _# instead later.\r\n",word) } if (at && *at == '!' && at[1] == '$') { ; } // allow !$xxx else if (at) // revise comparison operators { if (*at == '!') ++at; ++at; if (*at == '^' && at[1]) // remap function arg on right side. { int index = GetFunctionArgument(at); if (index >= 0) sprintf(at,(char*)"^%d",index); } if (*at == '_' && IsAlphaUTF8(word[1])) // remap rename matchvar arg on right side. { WORDP D = FindWord(at); if (D && D->internalBits & RENAMED) sprintf(at,(char*)"_%d",(unsigned int)D->properties); } if (*at == '@' && IsAlphaUTF8(word[1])) // remap @set arg on right side. { char* at1 = GetSetEnd(at); WORDP D = FindWord(at,at1 - at); if (D && D->internalBits & RENAMED) // remap @set on right side { strcpy(tmp,at1); // protect chunk sprintf(at + 1,(char*)"%d%s",(unsigned int)D->properties,tmp); } } // check for remap on LHS if (*word == '^') { char c = *--at; *at = 0; int index = GetFunctionArgument(word); *at = c; if (index >= 0) { sprintf(tmp,(char*)"^%d%s",index,at); strcpy(word,tmp); } } // check for rename on LHS if (*word == '_' && IsAlphaUTF8(word[1])) { char* atx = word; while (IsAlphaUTF8OrDigit(*++atx)) { ; } WORDP D = FindWord(word,atx - word); if (D && D->internalBits & RENAMED) // remap match var { sprintf(tmp,(char*)"%d%s",(unsigned int)D->properties,atx); strcpy(word + 1,tmp); } } // check for rename on LHS if (*word == '@' && IsAlphaUTF8(word[1])) { char* atx = GetSetEnd(word); WORDP D = FindWord(word,atx - word); if (D && D->internalBits & RENAMED) // remap @set in string { strcpy(tmp,atx); // protect chunk sprintf(word + 1,(char*)"%d%s",(unsigned int)D->properties,tmp); } } } // when seeing ^, see if it remaps as a function argument // check for internal ^ also... char* hat = word - 1; while ((hat = strchr(hat + 1,'^'))) // find a hat within { char* at = hat; while (*++at && (IsAlphaUTF8(*at) || *at == '_' || IsDigit(*at))) { ; } char c = *at; *at = 0; // terminate it so internal ^ is recognized uniquely strcpy(tmp,hat); *at = c; while (*tmp) { int index = GetFunctionArgument(tmp); if (index >= 0) { char remainder[MAX_WORD_SIZE]; strcpy(remainder,at); // protect chunk AFTER this sprintf(hat,(char*)"^%d%s",index,remainder); break; } else tmp[0] = 0; // just abort it for now shrink it smaller, to handle @9subject kinds of behaviors } } // same for quoted function arg if (*word == '\'' && word[1] == '^' && word[2]) { int index = GetFunctionArgument(word + 1); if (index >= 0) sprintf(word,(char*)"'^%d",index); } // break apart math on variables eg $value+2 as a service to the user if ((*word == '%' || *word == '$') && word[1]) // cannot use _ here as that will break memorization pattern tokens { char* atx = word + 1; if (atx[1] == '$' || atx[1] == '_') ++atx; // skip over 2ndary marker --atx; while (LegalVarChar(*++atx) || (*atx == '\\' && atx[1] == '$')); // find end of initial word - allowing \ for json $ if (*word == '$' && (*atx == '.' || *atx == '[' || *atx == ']') && (LegalVarChar(atx[1]) || atx[1] == '$' || atx[1] == '[' || atx[1] == ']' || (atx[1] == '\\' && atx[2] == '$')))// allow $x.y as a complete name { while (LegalVarChar(*++atx) || *atx == '.' || *atx == '$' || (*atx == '[' || *atx == ']' || (*atx == '\\' && atx[1] == '$'))); // find end of field name sequence if (*(atx - 1) == '.') --atx; // tailing period cannot be part of it } if (*atx && IsPunctuation(*atx) & ARITHMETICS && *atx != '=') { if (*atx == '.' && atx[1] == '_' && IsDigit(atx[2])) {} // json field reference indirection else if (*atx == '.' && atx[1] == '\'' && atx[2] == '_' && IsDigit(atx[3])) {} // json field reference indirection // - is legal in a var or word token else if (*atx != '-' || (!IsAlphaUTF8OrDigit(atx[1]) && atx[1] != '_')) { ptr -= strlen(atx); *atx = 0; len = atx - start; } } } char* tilde = (IsAlphaUTF8(*word)) ? strchr(word + 1,'~') : 0; if (tilde) // has specific meaning like African-american~1n or African-american~1 { if (IsDigit(*++tilde)) // we know the meaning, removing any POS marker since that is redundant { if (IsDigit(*++tilde)) ++tilde; if (*tilde && !tilde[1]) *tilde = 0; // trim off pos marker // now force meaning to master MEANING M = ReadMeaning(word,true,false); if (M) { M = GetMaster(M); sprintf(word,(char*)"%s~%d",Meaning2Word(M)->word,Meaning2Index(M)); } } } // universal cover of simple use - complex tokens require processing elsewhere if (*word == USERVAR_PREFIX && word[1] == LOCALVAR_PREFIX) { char* at = word + 1; while (*++at) { if (!IsAlphaUTF8OrDigit(*at) && *at != '-' && *at != '_') break; } if (*at == '.') // root of a dotted variable { *at = 0; AddDisplay(word); *at = '.'; } else if (!*at) AddDisplay(word); } InsureAppropriateCase(word); return ptr; } void EraseTopicFiles(unsigned int build, char* name) { int i = -1; while (topicFiles[++i]) { char file[SMALL_WORD_SIZE]; sprintf(file, (char*)"%s/%s%s.txt", topic, topicFiles[i], name); remove(file); sprintf(file, (char*)"%s/BUILD%s/%s%s.txt", topic, name, topicFiles[i], name); remove(file); } } #ifndef DISCARDSCRIPTCOMPILER static char* WriteDisplay(char* pack) { *pack++ = '('; *pack++ = ' '; if (displayIndex) // show and merge in the new stuff { for (int i = 0; i < displayIndex; ++i) { strcpy(pack,display[i]); pack += strlen(pack); *pack++ = ' '; } displayIndex = 0; } *pack++ = ')'; *pack++ = ' '; *pack = 0; return pack; } static char* FindAssignment(char* word) { char* assign = strchr(word + 1, ':'); if (!assign || assign[1] != '=') return NULL; return assign; } static void AddMapOutput(int line) { if (livecall) return; // if we are mapping (:build) and have started output and some data storage change has happened if (mapFile && dataBase && lineStart != dataChunk && strnicmp(macroName, "^tbl:", 5)) { *dataChunk = 0; char src[MAX_WORD_SIZE]; strncpy(src, lineStart, 30); src[30] = 0; fprintf(mapFile, (char*)" line: %d %d # %s\r\n", line, (int)(lineStart - dataBase),src); // readBuffer } lineStart = dataChunk; // used to detect new line needs tracking } char* ReadNextSystemToken(FILE* in,char* ptr, char* word, bool separateUnderscore, bool peek) { #ifdef INFORMATION The outside can ask for the next real token or merely peek ahead one token. And sometimes the outside after peeking, decides it wants to back up a real token (passing it to some other processor). To support backing up a real token, the system must keep the current readBuffer filled with the data that led to that token (to allow a ptr - strlen(word) backup). To support peeking, the system may have to read a bunch of lines in to find a token. It is going to need to track that buffer separately, so when it needs a real token which was the peek, it can both get the peek value and be using contents of the new buffer thereafter. So peeks must never touch the real readBuffer. And real reads must know whether the last token was peeked and from which buffer it was peeked. And, if someone wants to back up to allow the old token to be reread, they have to CANCEL any peek data, so the token comes from the old buffer. Meanwhile the newbuffer continues to have content for when the old buffer runs out. #endif int line = currentFileLine; // clear peek cache if (!in && !ptr) // clear cache request, next get will be from main buffer (though secondary buffer may still have peek read data) { if (word) *word = 0; incomingPtrSys = NULL; // no longer holding a PEEK value. return NULL; } char* result = NULL; if (incomingPtrSys ) // had a prior PEEK, now in cache. use up cached value, unless duplicate peeking { result = incomingPtrSys; // caller who is peeking will likely ignore this if (!peek) { currentFileLine = maxFileLine; // revert to highest read // he wants reality now... if (newBuffer && *newBuffer) // prior peek was from this buffer, make it real data in real buffer { strcpy(readBuffer,newBuffer); result = (result - newBuffer) + readBuffer; // adjust pointer to current buffer *newBuffer = 0; } strcpy(word,lookaheadSys); incomingPtrSys = 0; } else { strcpy(word,lookaheadSys); // duplicate peek result = (char*)1; // NO ONE SHOULD KEEP A PEEKed PTR } if (result == (char*)1) { currentLineColumn = 0; } else currentLineColumn = (result - readBuffer); return result; } *word = 0; if (ptr) { result = ReadSystemToken(ptr, word, separateUnderscore); } bool newln = false; while (!*word) // found no token left in existing buffer - we have to juggle buffers now unless running overwrite { if (!newln && newBuffer && *newBuffer) // use pre-read buffer per normal, it will have a token { strcpy(readBuffer,newBuffer); *newBuffer = 0; result = ReadSystemToken(readBuffer,word,separateUnderscore); break; } else // read new line into hypothetical buffer, not destroying old actual buffer yet { if (!in || ReadALine(newBuffer,in, maxBufferSize,false, convertTabs) < 0) return NULL; // end of file if (!strnicmp(newBuffer,(char*)"#ignore",7)) // hit an ignore zone { unsigned int ignoreCount = 1; while (ReadALine(newBuffer,in) >= 0) { if (!strnicmp(newBuffer,(char*)"#ignore",7)) ++ignoreCount; else if (!strnicmp(newBuffer,(char*)"#endignore",10)) { if (--ignoreCount == 0) { if (ReadALine(newBuffer,in) < 0) return NULL; // EOF break; } } } if (ignoreCount) return NULL; //EOF before finding closure } result = ReadSystemToken(newBuffer,word,separateUnderscore); // result is ptr into NEWBUFFER newln = true; } } if (peek) // save request - newBuffer has implied newln if any { incomingPtrSys = result; // next location in whatever buffer strcpy(lookaheadSys,word); // save next token peeked result = (char*)1; // NO ONE SHOULD KEEP A PEEKed PTR currentFileLine = line; // claim old value } else if (newln && newBuffer) // live token from new buffer, adjust pointers and buffers to be fully up to date { strcpy(readBuffer,newBuffer); result = (result - newBuffer) + readBuffer; // ptr into current readBuffer now *newBuffer = 0; } if (result == (char*)1 ) { currentLineColumn = 0; } else currentLineColumn = (result - readBuffer); return result; // ptr into READBUFFER or 1 if from peek zone } char* ReadDisplayOutput(char* ptr,char* buffer) // locate next output fragment to display (that will be executed) { char next[MAX_WORD_SIZE]; char* hold; *buffer = 0; char* out = buffer; while (*ptr != ENDUNIT) // not end of data { char* before = ptr; ptr = ReadCompiledWord(ptr,out); // move token if (*out && out[1] && out[2] && (out[3] == '{' || out[3] == '(') && !out[4]) // accellerator + opening? { ptr = before + ACCELLSIZE; // ignore accel continue; } if (*out && out[1] && out[2] && !out[3] && ptr[0] == '{') // accellerator + opening? { continue; // accel before else final code } if (!strnicmp(ptr, "else", 4) && !out[3]) { continue; // skip accel before else } char* copied = out; out += strlen(out); strcpy(out,(char*)" "); ++out; *out = 0; hold = ReadCompiledWord(ptr,next); // and the token after that? if (IsAlphaUTF8OrDigit(*copied) ) // simple output word was copied { if (!*next || !IsAlphaUTF8OrDigit(*next)) break; // followed by something else simple } else if (*buffer == ':' && buffer[1]) // testing command occupies the rest always { char* end = strchr(ptr,ENDUNIT); if (end) { strncpy(out,ptr,end-ptr); out += end-ptr; *out = 0; } ptr = NULL; break; } else if (*buffer == '^' && *next == '(') // function call { char* end = BalanceParen(ptr+1,true,false); // function call args strncpy(out,ptr,end-ptr); out += end-ptr; *out = 0; ptr = end; break; } else if ((*buffer == USERVAR_PREFIX && (buffer[1] == LOCALVAR_PREFIX || buffer[1] == TRANSIENTVAR_PREFIX || IsAlphaUTF8(buffer[1]) )) || (*buffer == SYSVAR_PREFIX && IsAlphaUTF8(buffer[1])) || (*buffer == '@' && IsDigit(buffer[1])) || (*buffer == '_' && IsDigit(buffer[1])) ) // user or system variable or factset or match variable { if (*next != '=' && next[1] != '=') break; // not an assignment statement while (hold) // read op, value pairs { strcpy(out,next); // transfer assignment op or arithmetic op out += strlen(out); strcpy(out,(char*)" "); ++out; ptr = ReadCompiledWord(hold,next); // read value strcpy(out,next); // transfer value out += strlen(out); // if value is a function call, get the whole call if (*next == '^' && *ptr == '(') { char* end = BalanceParen(ptr+1,true,false); // function call args strncpy(out,ptr,end-ptr); out += end-ptr; *out = 0; ptr = end; } strcpy(out,(char*)" "); ++out; if (*ptr != ENDUNIT) // more to rule { hold = ReadCompiledWord(ptr,next); // is there more to assign if (IsArithmeticOperator(next)) continue; // need to swallow op and value pair } break; } break; } else if (*buffer == '[') // choice area { // find closing ] char* end = ptr-1; while (ALWAYS) { end = strchr(end+1,']'); // find a closing ] if (!end) break; // failed if (*(end-1) != '\\') break; // ignore literal \[ } if (end) // found end of a [] pair { ++end; strncpy(out,ptr,end-ptr); out += end-ptr; *out = 0; ptr = end + 1; if (*ptr != '[') break; // end of choice zone } } else break; } if (!stricmp(buffer,(char*)"^^loop ( -1 ) ")) strcpy(buffer,(char*)"^^loop ( ) "); // shorter notation return ptr; } ////////////////// CAN BE COMPILED AWAY #ifndef DISCARDSCRIPTCOMPILER #define MAX_TOPIC_SIZE 500000 #define MAX_TOPIC_RULES 32767 #define MAX_TABLE_ARGS 20 static unsigned int hasPlans; // how many plans did we read static int missingFiles; // how many files of topics could not be found static int spellCheck = 0; // what do we spell check static int topicCount = 0; // how many topics did we compile static char duplicateTopicName[MAX_WORD_SIZE]; // potential topic name repeated static char assignKind[MAX_WORD_SIZE]; // what we are assigning from in an assignment call static char currentTopicName[MAX_WORD_SIZE]; // current topic being read static char lowercaseForm[MAX_WORD_SIZE]; // a place to put a lower case copy of a token static WORDP currentFunctionDefinition; // current macro defining or executing static char verifyLines[100][MAX_WORD_SIZE]; // verification lines for a rule to dump after seeing a rule static unsigned int verifyIndex = 0; // index of how many verify lines seen static char* ReadLoop(char* word, char* ptr, FILE* in, char* &data,char* rejoinders,bool json); #ifdef INFORMATION Script compilation validates raw topic data files amd converts them into efficient-to-execute forms. This means creating a uniform spacing of tokens and adding annotations as appropriate. Reading a topic file (on the pattern side) often has tokens jammed together. For example all grouping characters like () [ ] { } should be independent tokens. Possessive forms like cat's and cats' should return as two tokens. Just as all contractions will get expanded to the full word. Some tokens can be prefixed with ! or single-quote or _ . In order to be able to read special characters (including prefix characters) literally, one can prefix it with \ as in \[ . The token returned includes the \. \! means the exclamation mark at end of sentence. You are not required to do \? because it is directly a legal token, but you can. You CANNOT test for . because it is the default and is subsumed automatically. #endif static void AddMap(char* kind,char* msg) { if (!mapFile) return; if (kind) { char value[MAX_WORD_SIZE]; strcpy(value, kind); char* at = strchr(value, ':'); if (at) { sprintf(at + 1, " %d ", currentFileLine); at = strchr(kind, ':'); strcat(value, at + 1); } fprintf(mapFile,(char*)"%s %s",value, (msg) ? msg : ((char*)"")); if (myBot && !strstr(value,"rule:") && !strstr(value, "complexity of")) { #ifdef WIN32 fprintf(mapFile, (char*)" %I64u", (int64)myBot); #else fprintf(mapFile, (char*)" %llu", (int64)myBot); #endif } fprintf(mapFile, (char*)"\r\n"); } else fprintf(mapFile,(char*)"%s\r\n",msg); // for complexity metric } static void ClearBeenHere(WORDP D, uint64 junk) { RemoveInternalFlag(D,BEEN_HERE); // clear transient ignore spell warning flag if (D->internalBits & DO_NOISE && !(D->internalBits & HAS_SUBSTITUTE)) RemoveInternalFlag(D, DO_NOISE); } bool TopLevelUnit(char* word) // major headers (not kinds of rules) { return (!stricmp(word,(char*)":quit") || !stricmp(word,(char*)"canon:") || !stricmp(word,(char*)"replace:") || !stricmp(word, (char*)"ignorespell:") || !stricmp(word, (char*)"prefer:") || !stricmp(word,(char*)"query:") || !stricmp(word,(char*)"concept:") || !stricmp(word,(char*)"data:") || !stricmp(word,(char*)"plan:") || !stricmp(word,(char*)"outputMacro:") || !stricmp(word,(char*)"patternMacro:") || !stricmp(word,(char*)"dualMacro:") || !stricmp(word,(char*)"table:") || !stricmp(word,(char*)"tableMacro:") || !stricmp(word,(char*)"rename:") || !stricmp(word,(char*)"describe:") || !stricmp(word,(char*)"bot:") || !stricmp(word,(char*)"topic:") || (*word == ':' && IsAlphaUTF8(word[1])) ); // :xxx is a debug command } static char* FlushToTopLevel(FILE* in,unsigned int depth,char* data) { globalDepth = depth; if (data) *data = 0; // remove data char word[MAX_WORD_SIZE]; int oldindex = jumpIndex; jumpIndex = -1; // prevent ReadNextSystemToken from possibly crashing. if (newBuffer) *newBuffer = 0; ReadNextSystemToken(NULL,NULL,word,false); // clear out anything ahead char* ptr = readBuffer + strlen(readBuffer) - 1; while (ALWAYS) { char* quote = NULL; while ((quote = strchr(ptr,'"'))) ptr = quote + 1; // flush quoted things ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; MakeLowerCopy(lowercaseForm,word); if (TopLevelUnit(lowercaseForm) || TopLevelRule(lowercaseForm)) { ptr -= strlen(word); // safe break; } } jumpIndex = oldindex; return ptr; } static bool IsSet(char* word) { if (!word[1]) return true; WORDP D = FindWord(word,0,LOWERCASE_LOOKUP); return (D && D->internalBits & CONCEPT) ? true : false; } static bool IsTopic(char* word) { if (!word[1]) return true; WORDP D = FindWord(word,0,LOWERCASE_LOOKUP); return (D && D->internalBits & TOPIC) ? true : false; } static void DoubleCheckSetOrTopic() { char file[200]; sprintf(file,"%s/missingsets.txt",topic); FILE* in = FopenReadWritten(file); if (!in) return; *currentFilename = 0; // dont tell the name of the file while (ReadALine(readBuffer,in) >= 0) { char word[MAX_WORD_SIZE]; ReadCompiledWord(readBuffer,word); if (!IsSet(word) && !IsTopic(word) && !IsDigit(word[1])) WARNSCRIPT((char*)"Undefined set or topic %s\r\n",readBuffer) } FClose(in); remove(file); } static void CheckSetOrTopic(char* name) // we want to prove all references to set get defined { if (livecall) return; if (*name == '~' && !name[1]) return; // simple ~ reference char word[MAX_WORD_SIZE]; MakeLowerCopy(word,name); char* label = strchr(word,'.'); // set reference might be ~set or ~set.label if (label) *label = 0; if (IsSet(word) || IsTopic(word)) return; WORDP D = StoreWord(word); if (D->internalBits & BEEN_HERE) return; // already added to check file AddBeenHere(D); char file[200]; sprintf(file,"%s/missingsets.txt",topic); FILE* out = FopenUTF8WriteAppend(file); fprintf(out,(char*)"%s line %d column %d in %s\r\n",word,currentFileLine,currentLineColumn, currentFilename); fclose(out); // dont use FClose } static char* AddVerify(char* kind, char* sample) { char* comment = strstr(sample,(char*)"# "); // locate any comment on the line and kill it if (comment) *comment = 0; sprintf(verifyLines[verifyIndex++],(char*)"%s %s",kind,SkipWhitespace(sample)); return 0; // kill rest of line } static void WriteVerify() { if (!verifyIndex) return; char name[100]; sprintf(name,(char*)"VERIFY/%s-b%c.txt",currentTopicName+1, (buildID == BUILD0) ? '0' : '1'); FILE* valid = FopenUTF8WriteAppend(name); static bool init = true; if (!valid && init) { MakeDirectory((char*)"VERIFY"); init = false; valid = FopenUTF8WriteAppend(name); } if (valid) { char* space = ""; if (REJOINDERID(currentRuleID)) space = " "; for (unsigned int i = 0; i < verifyIndex; ++i) { fprintf(valid,(char*)"%s %s.%d.%d %s\r\n",space,currentTopicName,TOPLEVELID(currentRuleID),REJOINDERID(currentRuleID),verifyLines[i]); } fclose(valid); // dont use FClose } verifyIndex = 0; } #ifdef INFORMATION We mark words that are not normally in the dictionary as pattern words if they show up in patterns. For example, the names of synset heads are not words, but we use them in patterns. They will be marked during the scan phase of matching ONLY if some pattern "might want them". I.e., they have a pattern-word mark on them. same is true for multiword phrases we scan. Having marked words also prevents us from spell-correcting something we were expecting but which is not a legal word. #endif static void DownHierarchy(MEANING T, FILE* out, int depth) { if ( !T) return; WORDP D = Meaning2Word(T); if (D->internalBits & VAR_CHANGED) return; if (*D->word == '~') fprintf(out,(char*)"%s depth=%d\r\n",D->word,depth); else fprintf(out,(char*)" %s\r\n",D->word); D->internalBits |= VAR_CHANGED; unsigned int size = GetMeaningCount(D); if (!size) size = 1; if (*D->word == '~') // show set members { FACT* F = GetObjectNondeadHead(D); while (F) { if (ValidMemberFact(F)) DownHierarchy(F->subject,out,depth+1); F = GetObjectNondeadNext(F); } fprintf(out,(char*)". depth=%d\r\n",depth); } } static void WriteKey(char* word) { if (!compiling || spellCheck != NOTE_KEYWORDS || *word == '_' || *word == '\'' || *word == USERVAR_PREFIX || *word == SYSVAR_PREFIX || *word == '@') return; StoreWord(word); if (livecall) { return; } char file[SMALL_WORD_SIZE]; sprintf(file,(char*)"%s/keys.txt",tmp); FILE* out = FopenUTF8WriteAppend(file); if (out) { DownHierarchy(MakeMeaning(StoreWord(word)),out,0); fclose(out); // dont use Fclose } } static void WritePatternWord(char* word) { if (*word == '~' || *word == USERVAR_PREFIX || *word == '^') return; // not normal words if (IsDigit(*word)) // any non-number stuff { char* ptr = word; while (*++ptr) { if (!IsDigit(*ptr) && *ptr != '.' && *ptr != ',') break; } if (!*ptr) return; // ordinary number } if (!compiling) return; // do we want to note this word WORDP D = StoreWord(word); // if word is not resident, maybe its properties are transient so we must save pattern marker if (!livecall && !(D->properties & NORMAL_WORD)) AddSystemFlag(D,PATTERN_WORD); // case sensitivity? char tmp[MAX_WORD_SIZE]; MakeLowerCopy(tmp,word); WORDP lower = FindWord(word,0,LOWERCASE_LOOKUP); WORDP upper = FindWord(word,0,UPPERCASE_LOOKUP); char utfcharacter[10]; char* x = IsUTF8(word, utfcharacter); if (!strcmp(tmp,word) || utfcharacter[1]) {;} // came in as lower case or as UTF8 character, including ones that don't have an uppercase version? else if (nospellcheck) {;} else if (lower && lower->internalBits & DO_NOISE && !(lower->internalBits & HAS_SUBSTITUTE)) {} // told not to check else if (upper && (GetMeaningCount(upper) > 0 || upper->properties & NORMAL_WORD )){;} // clearly known as upper case else if (!livecall && !(spellCheck & NO_SPELL) && lower && lower->properties & NORMAL_WORD && !(lower->properties & (DETERMINER|AUX_VERB))) WARNSCRIPT((char*)"Keyword %s should not be uppercase - did prior rule fail to close\r\n",word) else if (!livecall && !(spellCheck & NO_SPELL) && spellCheck && lower && lower->properties & VERB && !(lower->properties & NOUN)) WARNSCRIPT((char*)"Uppercase keyword %s is usually a verb. Did prior rule fail to close\r\n",word) char* pos; if ( (pos = strchr(word,'\'')) && (pos[1] != 's' && !pos[1])) WARNSCRIPT((char*)"Contractions are always expanded - %s won't be recognized\r\n",word) if (D->properties & NORMAL_WORD) return; // already a known word if (D->internalBits & BEEN_HERE) return; // already written to pattern file or doublecheck topic ref file AddBeenHere(D); if (patternFile) fprintf(patternFile,(char*)"%s\r\n",word); else if (livecall) // has to be livecall if we dont have patternfile from build { patternwordthread = AllocateHeapval(patternwordthread, (uint64)D, NULL, NULL);// save name } } static void NoteUse(char* label,char* topicName) { char xlabel[MAX_WORD_SIZE]; char* dot = strchr(label, '.'); char* tilde = strchr(label + 1, '~'); if (tilde) { *tilde = 0; sprintf(xlabel, "%s%s", label, dot); *tilde = '~'; } else strcpy(xlabel, label); char labelx[MAX_WORD_SIZE]; char bots[MAX_WORD_SIZE]; strcpy(bots, scopeBotName); if (*bots == ' ') strcpy(bots, scopeBotName + 1); if (!*bots) strcpy(bots, "*"); int len = strlen(bots); if (bots[len - 1] == ' ') bots[len - 1] = 0; MakeUpperCase(bots); sprintf(labelx, "%s-%s", xlabel,bots); MakeUpperCase(labelx); WORDP D = FindWord(labelx); if (!D || !(D->internalBits & LABEL)) // bug doesnt look for generic if bots exists { char file[200]; sprintf(file,"%s/missingLabel.txt",topic); FILE* out = FopenUTF8WriteAppend(file); if (out) { if (scopeBotName) fprintf(out, (char*)"%s %s %s %d\r\n", xlabel, scopeBotName, currentFilename, currentFileLine); // generic else fprintf(out,(char*)"%s * %s %d\r\n",xlabel,currentFilename,currentFileLine); // specific bot fclose(out); // dont use FClose } } } static void ValidateCallArgs(WORDP D,char* arg1, char* arg2,char* argset[ARGSETLIMIT+1], bool needToField) { if (needToField) // assigning query to var, must give TO field value { if (!*argset[1] || !*argset[2] || !*argset[3] || !*argset[4] || !*argset[5] || !*argset[6]) BADSCRIPT((char*)"CALL- 62 query assignment to variable requires TO field\r\n") char* p = argset[7]; while (IsDigit(*++p)){} // skip if (!*p) WARNSCRIPT((char*)"Query assignment requires field name in %s, I don't see one.\r\n",argset[7]) } if (!stricmp(D->word,(char*)"^next")) { if (stricmp(arg1,(char*)"RESPONDER") && stricmp(arg1,(char*)"LOOP") && stricmp(arg1, (char*)"JSONLOOP") && stricmp(arg1,(char*)"REJOINDER") && stricmp(arg1,(char*)"RULE") && stricmp(arg1,(char*)"GAMBIT") && stricmp(arg1,(char*)"INPUT") && stricmp(arg1,(char*)"FACT")) BADSCRIPT((char*)"CALL- 62 1st argument to ^next must be FACT or LOOP or JSONLOOP or INPUT or RULE or GAMBIT or RESPONDER or REJOINDER - %s\r\n",arg1) } else if(!stricmp(D->word,(char*)"^jsonarraydelete")) { MakeLowerCase(arg1); if (!strstr(arg1,(char*)"index") && !strstr(arg1,(char*)"value") ) BADSCRIPT((char*)"CALL- ? 1st argument to ^jsonarraydelete must be INDEX or VALUE - %s\r\n",arg1) } else if(!stricmp(D->word,(char*)"^keephistory")) { if (stricmp(arg1,(char*)"USER") && stricmp(arg1,(char*)"BOT") ) BADSCRIPT((char*)"CALL- ? 1st argument to ^keephistory must be BOT OR USER - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^conceptlist")) { if (stricmp(arg1,(char*)"TOPIC") && stricmp(arg1,(char*)"CONCEPT") && stricmp(arg1,(char*)"BOTH")) BADSCRIPT((char*)"CALL- ? 1st argument to ^conceptlist must be CONCEPT or TOPIC or BOTH - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^field") && IsAlphaUTF8(*arg2)) { if (*arg2 != '$' && *arg2 != '^' && *arg2 != 's' && *arg2 != 'S' && *arg2 != 'v' && *arg2 != 'V' && *arg2 != 'O' && *arg2 != 'o' && *arg2 != 'F' && *arg2 != 'f' && *arg2 != 'A' && *arg2 != 'a' && *arg2 != 'R' && *arg2 != 'r') BADSCRIPT((char*)"CALL- 9 2nd argument to ^field must be SUBJECT or VERB or OBJECT or ALL or RAW or FLAG- %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^decodepos") ) { if (stricmp(arg1,(char*)"POS") && stricmp(arg1,(char*)"ROLE")) BADSCRIPT((char*)"CALL- ? 1st argument to ^decodepos must be POS or ROLE - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^position") ) { if (stricmp(arg1,(char*)"START") && stricmp(arg1,(char*)"END") && stricmp(arg1,(char*)"BOTH")) BADSCRIPT((char*)"CALL- ? 1st argument to ^position must be START, END, BOTH, - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^getparse") ) { if (stricmp(arg2,(char*)"PHRASE") && stricmp(arg2,(char*)"VERBAL") && stricmp(arg2,(char*)"CLAUSE")&& stricmp(arg2,(char*)"NOUNPHRASE")) BADSCRIPT((char*)"CALL- ? 2nd argument to ^getparse must be PHRASE, VERBAL, CLAUSE, NOUNPHRASE- %s\r\n",arg2) } else if (!stricmp(D->word, (char*)"^reset")) { if (stricmp(arg1, (char*)"history") && stricmp(arg1, (char*)"facts") && stricmp(arg1, (char*)"variables") && stricmp(arg1, (char*)"user") && stricmp(arg1, (char*)"topic") && stricmp(arg1, (char*)"output") && *arg1 != '@') BADSCRIPT((char*)"CALL- 10 1st argument to ^reset must be USER or TOPIC or OUTPUT or VARIABLES or FACTS or HISTORY or an @set- %s\r\n", arg1) } else if (!stricmp(D->word,(char*)"^substitute")) { if (stricmp(arg1,(char*)"word") && stricmp(arg1,(char*)"character") && stricmp(arg1,(char*)"insensitive") && *arg1 != '"' && *arg1 != '^') BADSCRIPT((char*)"CALL- 11 1st argument to ^substitute must be WORD or CHARACTER or INSENSITIVE- %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^setrejoinder")) { if (*arg2 && stricmp(arg1,(char*)"input") && stricmp(arg1,(char*)"output") && stricmp(arg1,(char*)"copy") ) BADSCRIPT((char*)"CALL- 63 call to ^setrejoinder requires INPUT or OUTPUT or COPY as the 1st arg.\r\n") if (!*arg2 && (!stricmp(arg1,(char*)"input") || !stricmp(arg1,(char*)"output") || !stricmp(arg1,(char*)"copy")) ) BADSCRIPT((char*)"CALL- 63 call to ^setrejoinder requires 2nd argument naming what rule to use as rejoinder\r\n") } else if (!stricmp(D->word, (char*)"^pos")) { if (stricmp(arg1, (char*)"conjugate") && stricmp(arg1, (char*)"preexists") && stricmp(arg1, (char*)"raw") && stricmp(arg1, (char*)"allupper") && stricmp(arg1, (char*)"syllable") && stricmp(arg1, (char*)"ADJECTIVE") && stricmp(arg1, (char*)"ADVERB") && stricmp(arg1, (char*)"VERB") && stricmp(arg1, (char*)"AUX") && stricmp(arg1, (char*)"PRONOUN") && stricmp(arg1, (char*)"TYPE") && stricmp(arg1, (char*)"HEX32") && stricmp(arg1, (char*)"HEX64") && stricmp(arg1, (char*)"NOUN") && stricmp(arg1, (char*)"DETERMINER") && stricmp(arg1, (char*)"PLACE") && stricmp(arg1, (char*)"common") && stricmp(arg1, (char*)"capitalize") && stricmp(arg1, (char*)"uppercase") && stricmp(arg1, (char*)"lowercase") && stricmp(arg1, (char*)"canonical") && stricmp(arg1, (char*)"integer") && stricmp(arg1, (char*)"IsModelNumber") && stricmp(arg1, (char*)"IsInteger") && stricmp(arg1, (char*)"IsUppercase") && stricmp(arg1, (char*)"IsFloat") && stricmp(arg1, (char*)"IsMixedCase")) BADSCRIPT((char*)"CALL- 12 1st argument to ^pos must be SYLLABLE or ALLUPPER or VERB or AUX or PRONOUN or NOUN or ADJECTIVE or ADVERB or DETERMINER or PLACE or COMMON or CAPITALIZE or UPPERCASE or LOWERCASE or CANONICAL or INTEGER or HEX32 or HEX64 or ISMODELNUMBER or ISINTEGER or ISUPPERCASE or ISFLOAT or ISMIXEDCASE - %s\r\n", arg1) } else if (!stricmp(D->word,(char*)"^getrule")) { if (stricmp(arg1,(char*)"TOPIC") && stricmp(arg1,(char*)"OUTPUT") && stricmp(arg1,(char*)"PATTERN") && stricmp(arg1,(char*)"LABEL") && stricmp(arg1,(char*)"TYPE") && stricmp(arg1,(char*)"TAG") && stricmp(arg1,(char*)"USABLE")) BADSCRIPT((char*)"CALL- 13 1st argument to ^getrule must be TAG or TYPE or LABEL or PATTERN or OUTPUT or TOPIC or USABLE - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^poptopic")) { if (*arg1 && *arg1 != '~' && *arg1 != USERVAR_PREFIX && *arg1 != '_' && *arg1 != SYSVAR_PREFIX && *arg1 != '^') BADSCRIPT((char*)"CALL- 61 1st argument to ^poptopic must be omitted or a topic name or variable which will return a topic name - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^nextrule")) { if (stricmp(arg1,(char*)"GAMBIT") && stricmp(arg1,(char*)"RESPONDER") && stricmp(arg1,(char*)"REJOINDER") && stricmp(arg1,(char*)"RULE")) BADSCRIPT((char*)"CALL- 14 1st argument to ^getrule must be TAG or TYPE or LABEL or PATTERN or OUTPUT - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^end")) { if (stricmp(arg1,(char*)"RULE") && stricmp(arg1,(char*)"CALL") && stricmp(arg1,(char*)"LOOP") && stricmp(arg1, (char*)"JSONLOOP") && stricmp(arg1,(char*)"TOPIC") && stricmp(arg1,(char*)"SENTENCE") && stricmp(arg1,(char*)"INPUT") && stricmp(arg1,(char*)"PLAN")) BADSCRIPT((char*)"CALL- 15 1st argument to ^end must be RULE or LOOP or JSONLOOP or TOPIC or SENTENCE or INPUT or PLAN- %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^fail")) { if (stricmp(arg1,(char*)"RULE") && stricmp(arg1,(char*)"CALL") && stricmp(arg1,(char*)"LOOP") && stricmp(arg1, (char*)"JSONLOOP") && stricmp(arg1,(char*)"TOPIC") && stricmp(arg1,(char*)"SENTENCE") && stricmp(arg1,(char*)"INPUT")) BADSCRIPT((char*)"CALL- 16 1st argument to ^fail must be RULE or LOOP or JSONLOOP or TOPIC or SENTENCE or INPUT - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^nofail")) { if (stricmp(arg1,(char*)"RULE") && stricmp(arg1,(char*)"LOOP") && stricmp(arg1, (char*)"JSONLOOP") && stricmp(arg1,(char*)"TOPIC") && stricmp(arg1,(char*)"SENTENCE") && stricmp(arg1,(char*)"INPUT")) BADSCRIPT((char*)"CALL- 16 1st argument to ^nofail must be RULE or LOOP or JSONLOOP or TOPIC or SENTENCE or INPUT - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^compute")) { char* op = arg2; if (stricmp(op,(char*)"+") && stricmp(op,(char*)"plus") && stricmp(op,(char*)"add") && stricmp(op,(char*)"and") && stricmp(op,(char*)"sub") && stricmp(op,(char*)"minus") && stricmp(op,(char*)"subtract") && stricmp(op,(char*)"deduct") && stricmp(op,(char*)"-") && stricmp(op,(char*)"x") && stricmp(op,(char*)"times") && stricmp(op,(char*)"multiply") && stricmp(op,(char*)"*") && stricmp(op,(char*)"divide") && stricmp(op,(char*)"quotient") && stricmp(op,(char*)"/") && stricmp(op,(char*)"remainder") && stricmp(op,(char*)"modulo") && stricmp(op,(char*)"mod") && stricmp(op,(char*)"%") && stricmp(op,(char*)"random") && stricmp(op,(char*)"root") && stricmp(op,(char*)"square_root") && stricmp(op,(char*)"power") && stricmp(op,(char*)"exponent") && *op != '^' && *op != '_' && *op != '$') // last covers macro args and exponents BADSCRIPT((char*)"CALL- 17 2nd argument to ^compute must be numeric operation - %s\r\n",op) } else if (!stricmp(D->word,(char*)"^counttopic") && IsAlphaUTF8(*arg1)) { if (strnicmp(arg1,(char*)"gambit",6) && stricmp(arg1,(char*)"used") && strnicmp(arg1,(char*)"rule",4) && stricmp(arg1,(char*)"available")) BADSCRIPT((char*)"CALL-20 CountTopic 1st arg must be GAMBIT or RULE or AVAILABLE or USED - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^phrase")) { if (stricmp(arg1,(char*)"adjective") && stricmp(arg1,(char*)"verbal")&& stricmp(arg1,(char*)"noun") && stricmp(arg1,(char*)"preposition")) BADSCRIPT((char*)"CALL-21 ^Phrase 1st arg must be adjective or verbal or noun or preposition - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^hasgambit") && IsAlphaUTF8(*arg2)) { if (stricmp(arg2,(char*)"last") && stricmp(arg2,(char*)"any") ) BADSCRIPT((char*)"CALL-21 HasGambit 2nd arg must be omitted or be LAST or ANY - %s\r\n",arg1) } else if (!stricmp(D->word,(char*)"^lastused" )) { if (strnicmp(arg2,(char*)"gambit",6) && strnicmp(arg2,(char*)"rejoinder",9) && strnicmp(arg2,(char*)"responder",9) && stricmp(arg2,(char*)"any")) BADSCRIPT((char*)"CALL-22 LastUsed 2nd arg must be GAMBIT or REJOINDER or RESPONDER or ANY - %s\r\n",arg2) } else if ((!stricmp(nextToken,(char*)"^first") || !stricmp(nextToken,(char*)"^last") || !stricmp(nextToken,(char*)"^random")) && *arg2) BADSCRIPT((char*)"CALL-23 Too many arguments to first/last/random - %s\r\n",arg2) else if (!stricmp(D->word,(char*)"^respond") && atoi(arg1)) BADSCRIPT((char*)"CALL-? argument to ^respond should be a topic, not a number. Did you intend ^response? - %s\r\n",arg1) else if (!stricmp(D->word,(char*)"^respond") && !stricmp(arg1,currentTopicName)) WARNSCRIPT((char*)"Recursive call to topic - possible infinite recursion danger %s\r\n",arg1) else if (!stricmp(D->word,(char*)"^gambit") && !stricmp(arg1,currentTopicName)) WARNSCRIPT((char*)"Recursive call to topic - possible infinite recursion danger %s\r\n",arg1) else if (!stricmp(D->word,(char*)"^response") && *arg1 == '~') BADSCRIPT((char*)"CALL-? argument to ^response should be a number, not a topic. Did you intend ^respond? - %s\r\n",arg1) else if (!stricmp(D->word,(char*)"^burst") && !stricmp(arg1,(char*)"wordcount")) BADSCRIPT((char*)"CALL-? argument to ^burst renamed. Use 'count' instead of 'wordcount'\r\n") // validate inference calls if we can else if (!strcmp(D->word,(char*)"^query")) { unsigned int flags = atoi(argset[9]); if (flags & (USER_FLAG1|USER_FLAG2|USER_FLAG3) && !strstr(arg1,(char*)"flag_")) BADSCRIPT((char*)"CALL-24 ^query involving USER_FLAG1 must be named xxxflag_\r\n") if (!stricmp(arg1,(char*)"direct_s") || !stricmp(arg1,(char*)"exact_s")) { if (!*arg2 || *arg2 == '?') BADSCRIPT((char*)"CALL-24 Must name subject argument to query\r\n") if (*argset[3] && *argset[3] != '?') BADSCRIPT((char*)"CALL-25 Cannot name verb argument to query %s - %s\r\n",arg1,argset[3]) if (*argset[4] && *argset[4] != '?') BADSCRIPT((char*)"CALL-26 Cannot name object argument to query %s - %s\r\n",arg1,argset[4]) if (*argset[8] && *argset[8] != '?') BADSCRIPT((char*)"CALL-27 Cannot name propgation argument to query %s - %s\r\n",arg1,argset[8]) if (*argset[9] && *argset[9] != '?') BADSCRIPT((char*)"CALL-28 Cannot name match argument to query %s - %s\r\n",arg1,argset[9]) } flags = atoi(argset[5]); if (flags & (USER_FLAG1|USER_FLAG2|USER_FLAG3) && flags < 0x00ffffff) WARNSCRIPT((char*)"Did you want a xxxflag_ query with USER_FLAG in 9th position for %s\r\n",arg1) if (!stricmp(arg1,(char*)"direct_v") || !stricmp(arg1,(char*)"exact_v")) { if (*arg2 && *arg2 != '?') BADSCRIPT((char*)"CALL-29 Cannot name subject argument to query - %s\r\n",arg2) if (!*argset[3] || *argset[3] == '?') BADSCRIPT((char*)"CALL-30 Must name verb argument to query\r\n") if (*argset[4] && *argset[4] != '?') BADSCRIPT((char*)"CALL-31 Cannot name object argument to query %s - %s\r\n",arg1,argset[4]) if (*argset[8] && *argset[8] != '?') BADSCRIPT((char*)"CALL-32 Cannot name propgation argument to query %s - %s\r\n",arg1,argset[8]) if (*argset[9] && *argset[9] != '?') BADSCRIPT((char*)"CALL-33 Cannot name match argument to query %s - %s\r\n",arg1,argset[9]) } if (!stricmp(arg1,(char*)"direct_o") || !stricmp(arg1,(char*)"exact_o")) { if (*arg2 && *arg2 != '?') BADSCRIPT((char*)"CALL-34 Cannot name subject argument to query -%s\r\n",arg2) if (*argset[3] && *argset[3] != '?') BADSCRIPT((char*)"CALL-35 Cannot name verb argument to query %s - %s\r\n",arg1,argset[3]) if (!*argset[4] || *argset[4] == '?') BADSCRIPT((char*)"CALL-36 Must name object argument to query\r\n") if (*argset[8] && *argset[8] != '?') BADSCRIPT((char*)"CALL-37 Cannot name propgation argument to query %s - %s\r\n",arg1,argset[8]) if (*argset[9] && *argset[9] != '?') BADSCRIPT((char*)"CALL-38 Cannot name match argument to query %s - %s\r\n",arg1,argset[9]) } if (!stricmp(arg1,(char*)"direct_sv") || !stricmp(arg1,(char*)"exact_sv") ) { if (!*arg2 || *arg2 == '?') BADSCRIPT((char*)"CALL-39 Must name subject argument to query\r\n") if (!*argset[3] || *argset[3] == '?') BADSCRIPT((char*)"CALL-40 Must name verb argument to query\r\n") if (*argset[4] && *argset[4] != '?') BADSCRIPT((char*)"CALL-41 Cannot name object argument to query %s - %s\r\n",arg1,argset[4]) if (*argset[8] && *argset[8] != '?') BADSCRIPT((char*)"CALL-42 Cannot name propgation argument to query %s - %s\r\n",arg1,argset[8]) if (*argset[9] && *argset[9] != '?') BADSCRIPT((char*)"CALL-43 Cannot name match argument to query %s - %s\r\n",arg1,argset[9]) } if (!stricmp(arg1,(char*)"direct_sv_member")) { if (!*arg2 || *arg2 == '?') BADSCRIPT((char*)"CALL-44 Must name subject argument to query\r\n") if (!*argset[3] || *argset[3] == '?') BADSCRIPT((char*)"CALL-45 Must name verb argument to query\r\n") if (*argset[4] && *argset[4] != '?') BADSCRIPT((char*)"CALL-46 Cannot name object argument to query %s - %s\r\n",arg1,argset[4]) if (*argset[8] && *argset[8] != '?') BADSCRIPT((char*)"CALL-47 Cannot name propgation argument to query %s - %s\r\n",arg1,argset[8]) if (*argset[9] && *argset[9] == '?') BADSCRIPT((char*)"CALL-48 Must name match argument to query %s - %s\r\n",arg1,argset[9]) } if (!stricmp(arg1,(char*)"direct_vo")|| !stricmp(arg1,(char*)"exact_vo")) { if (*arg2 && *arg2 != '?') BADSCRIPT((char*)"CALL-49 Cannot name subject argument to query -%s\r\n",arg2) if (!*argset[3] || *argset[3] == '?') BADSCRIPT((char*)"CALL-50 Must name verb argument to query\r\n") if (!*argset[4] || *argset[4] == '?') BADSCRIPT((char*)"CALL-51 Must name object argument to query\r\n") if (*argset[8] && *argset[8] != '?') BADSCRIPT((char*)"CALL-52 Cannot name propgation argument to query %s - %s\r\n",arg1,argset[8]) if (*argset[9] && *argset[9] != '?') BADSCRIPT((char*)"CALL-53 Cannot name match argument to query %s - %s\r\n",arg1,argset[9]) } if (!stricmp(arg1,(char*)"direct_svo") || !stricmp(arg1,(char*)"exact_svo") ) { if (!*arg2 || *arg2 == '?') BADSCRIPT((char*)"CALL-54 Must name subject argument to query\r\n") if (!*argset[3] || *argset[3] == '?') BADSCRIPT((char*)"CALL-55 Must name verb argument to query\r\n") if (!*argset[4] || *argset[4] == '?') BADSCRIPT((char*)"CALL-56 Must name object argument to query\r\n") if (*argset[8] && *argset[8] != '?') BADSCRIPT((char*)"CALL-57 Cannot name propgation argument to query %s - %s\r\n",arg1,argset[8]) if (*argset[9] && *argset[9] != '?') BADSCRIPT((char*)"CALL-58 Cannot name match argument to query %s - %s\r\n",arg1,argset[9]) } } } static char* ReadCall(char* name, char* ptr, FILE* in, char* &data,bool call, bool needTofield) { // returns with no space after it // ptr is just after the ^name -- user can make a call w/o ^ in name but its been patched. Or this is function argument char reuseTarget1[SMALL_WORD_SIZE]; char reuseTarget2[SMALL_WORD_SIZE]; char* xxstartit = data; int oldcallingsystem = callingSystem; *reuseTarget2 = *reuseTarget1 = 0; // in case this turns out to be a ^reuse call, we want to test for its target char* argset[ARGSETLIMIT+1]; char word[MAX_WORD_SIZE]; char* arguments = ptr; // locate the function WORDP D = FindWord(name,0,LOWERCASE_LOOKUP); if (!call || !D || !(D->internalBits & FUNCTION_NAME)) // not a function, is it a function variable? { if (IsDigit(name[1])) // function variable { *data++ = *name++; *data++ = *name++; if (IsDigit(*name)) *data++ = *name++; *data = 0; return ptr; } } SystemFunctionInfo* info = NULL; bool isStream = false; // dont check contents of stream, just format it if (D && !(D->internalBits & FUNCTION_BITS)) // system function (not pattern macro, outputmacro, dual macro, tablemacro, or plan macro) { ++callingSystem; info = &systemFunctionSet[D->x.codeIndex]; if (info->argumentCount == STREAM_ARG) isStream = true; if (!stricmp(name,"^jsonarraysize")) WARNSCRIPT((char*)"^jsonarraysize deprecated in favor of ^length\r\n") if (!stricmp(name,"^jsondelete")) WARNSCRIPT((char*)"^jsondelete deprecated in favor of ^delete\r\n") } else if (patternContext && D && (D->internalBits & IS_PLAN_MACRO) == IS_PLAN_MACRO) BADSCRIPT((char*)"CALL-2 cannot invoke plan from pattern area - %s\r\n", name) else if (patternContext && D && !(D->internalBits & (IS_PATTERN_MACRO | IS_OUTPUT_MACRO))) BADSCRIPT((char*)"CALL-2 Can only call patternmacro or dual macro from pattern area - %s\r\n",name) else if (!patternContext && D && !(D->internalBits & (IS_OUTPUT_MACRO | IS_TABLE_MACRO))) BADSCRIPT((char*)"CALL-3 Cannot call pattern or table macro from output area - %s\r\n",name) memset(argset,0,sizeof(argset)); // default EVERYTHING before we test it later if (D && !stricmp(D->word,(char*)"^debug")) DebugCode(NULL); // a place for a script compile breakpoint // write call header strcpy(data,name); data += strlen(name); *data++ = ' '; *data++ = '('; *data++ = ' '; char* strbase = AllocateStack(NULL,1); bool oldContext = patternContext; patternContext = false; priorLine = currentFileLine; // validate argument counts and stuff locally, then swallow data offically as output data int parenLevel = 1; int argumentCount = 0; ptr = ReadNextSystemToken(in,ptr,word,false); // skip ( if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } while (ALWAYS) // read as many tokens as needed to complete the call, storing them locally { ptr = ReadNextSystemToken(in,ptr,word,false); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (!*word) break; if (*word == '#' && word[1] == '!') BADSCRIPT((char*)"#! sample input seen during a call. Probably missing a closing )\r\n"); // closing paren stuck onto token like _) - break it off size_t len = strlen(word); if (word[len-1] == ')' && len > 1 && (*word != '\\' || len > 2) ) { --ptr; if (*ptr != ')') ptr -= 1; word[len-1] = 0; } MakeLowerCopy(lowercaseForm,word); // note that in making calls, [] () and {} count as a single argument with whatver they have inside switch(*word) { case '(': case '[': case '{': ++parenLevel; break; case ')': case ']': case '}': --parenLevel; if (parenLevel == 1) ++argumentCount; // completed a () argument break; case '"': if (word[1] != FUNCTIONSTRING && oldContext) // simple string is in pattern context, flip to underscore form { // convert string into its pattern form. unsigned int n = BurstWord(word,0); if (n > 1) strcpy(word,JoinWords(n)); } // DROPPING THRU case '\'': // DROPPING THRU default: if (*word == '~') CheckSetOrTopic(word); // set or topic if (!stricmp(word,(char*)"PLAN") && !stricmp(name,(char*)"^end")) endtopicSeen = true; if (parenLevel == 1) { if (*word == FUNCTIONSTRING && word[1] == '"') { word[0] = '"'; word[1] = FUNCTIONSTRING; // show we know it if (word[2] == ':') strcpy(word+3,CompileString(word+1)+2); } ReadNextSystemToken(in,ptr,nextToken,false,true); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } // argument is a function without its ^ ? // but be wary of doing this in createfact, which can have nested facts if (*word != '^' && *nextToken == '(' && stricmp(name,(char*)"^createfact")) // looks like a call, reformat it if it is { char fnname[SMALL_WORD_SIZE]; *fnname = '^'; MakeLowerCopy(fnname+1,word); WORDP DX = FindWord(fnname,0,PRIMARY_CASE_ALLOWED); if (DX && DX->internalBits & FUNCTION_NAME) strcpy(word,fnname); } if (*word == '^' && (*nextToken == '(' || IsDigit(word[1]))) // function call or function var ref { WORDP D = FindWord(word,0,LOWERCASE_LOOKUP); if (!IsDigit(word[1]) && word[1] != USERVAR_PREFIX && *nextToken == '(' && (!D || !(D->internalBits & FUNCTION_NAME))) BADSCRIPT((char*)"CALL-1 Default call to function not yet defined %s\r\n",word) if (*nextToken != '(' && !IsDigit(word[1])) BADSCRIPT((char*)"CALL-? Unknown function variable %s\r\n",word) char* arg = data; if (!stricmp(word,"^if")) { ptr = ReadIf(word,ptr,in,data,NULL); *data++ = ' '; } else if (!stricmp(word,"^loop")) { ptr = ReadLoop(word,ptr,in,data,NULL,false); } else if (!stricmp(word, "^jsonloop")) { ptr = ReadLoop(word, ptr, in, data, NULL,true); } else { ptr = ReadCall(word,ptr,in,data,*nextToken == '(',false); *data++ = ' '; } if (argumentCount < ARGSETLIMIT) { argset[++argumentCount] = AllocateStack(arg); } continue; } if (*word == '^' && word[1] == '\''){;} else if (*word == '^' && *nextToken != '(' && word[1] != '^' && word[1] != USERVAR_PREFIX && word[1] != '_' && word[1] != '"' && !IsDigit(word[1])) // ^^ indicated a deref of something BADSCRIPT((char*)"%s is either a function missing arguments or an undefined function variable.\r\n",word) // not function call or function var ref // track only initial arguments for verify. can have any number when its a stream if (argumentCount < ARGSETLIMIT) { argset[++argumentCount] = AllocateStack(word); } } else { ReadNextSystemToken(in,ptr,nextToken,false,true); if (*word == '^' && *nextToken != '(' && *nextToken != ')' && word[1] != '"' && !IsDigit(word[1])) WARNSCRIPT((char*)"Is %s intended as a function call?\r\n",word) // not function call or function var ref } } if (oldContext && IsAlphaUTF8(*word) && stricmp(name,(char*)"^incontext") && stricmp(name,(char*)"^reuse") ) { WritePatternWord(word); WriteKey(word); } // add simple item into data strcpy(data,word); data += strlen(data); if (parenLevel == 0) break; // we finished the call (no trailing space) *data++ = ' '; } *--data = 0; // remove closing paren int cntr = argumentCount; while (cntr < 15) argset[++cntr] = AllocateStack(""); char* arg1 = argset[1]; char* arg2 = argset[2]; // validate assignment calls if we can - this will be a first,last,random call if (*assignKind && (!stricmp(name,(char*)"^first") || !stricmp(name,(char*)"^last") || !stricmp(name,(char*)"^random") || !stricmp(name,(char*)"^nth") ) ) { char kind = arg1[2]; if (*arg1 == '~') {;} // get nth of a concept else if (!kind) BADSCRIPT((char*)"CALL-5 Assignment must designate how to use factset (s v or o)- %s in %s %s\r\n",assignKind,name,arguments) else if ((kind == 'a' || kind == '+' || kind == '-') && *assignKind != '_') BADSCRIPT((char*)"CALL-6 Can only spread a fact onto a match var - %s\r\n",assignKind) else if (*assignKind == SYSVAR_PREFIX && (kind == 'f' || !kind)) BADSCRIPT((char*)"CALL-7 cannot assign fact into system variable\r\n") // into system variable else if (*assignKind == '@' && kind != 'f') BADSCRIPT((char*)"CALL-8 Cannot assign fact field into fact set\r\n") // into set, but not a fact } if (D && !stricmp(D->word,(char*)"^reuse") && (IsAlphaUTF8(*arg1) || *arg1 == '~')) { MakeUpperCopy(reuseTarget1,arg1); // topic names & labels must be upper case } else if (D && !stricmp(D->word,(char*)"^enable") && IsAlphaUTF8(*arg1)) { if (stricmp(arg1,(char*)"topic") && stricmp(arg1,(char*)"write") && stricmp(arg1,(char*)"rule") && stricmp(arg1,(char*)"usedrules") ) BADSCRIPT((char*)"CALL-18 Enable 1st arg must be TOPIC or RULE or USEDRULES - %s\r\n",arg1) if (*arg2 == '@'){;} else if (*arg2 != '~' || strchr(arg2,'.')) // not a topic or uses ~topic.rulename notation { MakeUpperCopy(reuseTarget1,arg2); // topic names & labels must be upper case } } else if (D && !stricmp(D->word,(char*)"^disable") && IsAlphaUTF8(*arg1)) { if (stricmp(arg1,(char*)"topic") && stricmp(arg1,(char*)"rule") && stricmp(arg1,(char*)"write")&& stricmp(arg1,(char*)"rejoinder") && stricmp(arg1,(char*)"inputrejoinder") && stricmp(arg1,(char*)"outputrejoinder") && stricmp(arg1,(char*)"save") ) BADSCRIPT((char*)"CALL-19 Disable 1st arg must be TOPIC or RULE or INPUTREJOINDER or OUTPUTREJOINDER or SAVE - %s\r\n",arg1) if (*arg2 == '@'){;} else if (!stricmp(arg1,(char*)"rejoinder")){;} else if (*arg2 != '~' || strchr(arg2,'.')) MakeUpperCopy(reuseTarget1,arg2); // topic names & labels must be upper case } if (D) ValidateCallArgs(D,arg1,arg2,argset,needTofield); if (parenLevel != 0) { char* value = (D) ? D->word : (char*)"unknown"; BADSCRIPT((char*)"CALL-59 Failed to properly close (or [ in call to %s\r\n", value) } if (isStream){;} // no cares else if (info) // system function { if (argumentCount != (info->argumentCount & 255) && info->argumentCount != VARIABLE_ARG_COUNT && info->argumentCount != UNEVALED && info->argumentCount != STREAM_ARG) BADSCRIPT((char*)"CALL-60 Incorrect argument count to system function %s- given %d instead of required %d\r\n",name,argumentCount,info->argumentCount & 255) } else if (D && (D->internalBits & FUNCTION_BITS) == IS_PLAN_MACRO) { if (argumentCount != (int)D->w.planArgCount) BADSCRIPT((char*)"CALL-60 Incorrect argument count to plan %s- given %d instead of required %d\r\n",name,argumentCount,D->w.planArgCount) } else if (!D) { // generate crosscheck data char* nameData = AllocateHeap(NULL, strlen(name) + 2, 1); *nameData = argumentCount; strcpy(nameData + 1, name); char* filename = AllocateHeap(currentFilename, 0, 1); undefinedCallThreadList = AllocateHeapval(undefinedCallThreadList, (uint64)nameData,(uint64) filename, (uint64)currentFileLine); } else // std macro (input, output table) { unsigned char* defn = GetDefinition(D); if (defn && argumentCount != MACRO_ARGUMENT_COUNT(defn) && !(D->internalBits & VARIABLE_ARGS_TABLE)) BADSCRIPT((char*)"CALL-60 Incorrect argument count to macro %s- given %d instead of required %d\r\n",name,argumentCount,MACRO_ARGUMENT_COUNT(GetDefinition(D))) } // handle crosscheck of labels char* dot = strchr(reuseTarget1,'.'); if (!*reuseTarget1); else if (dot) // used dotted notation, split them up { strcpy(reuseTarget2,dot+1); *dot = 0; } else if (*reuseTarget1 != '~') // only had name, not topic.name, fill in { strcpy(reuseTarget2,reuseTarget1); if (currentFunctionDefinition) strcpy(reuseTarget1,currentFunctionDefinition->word); else strcpy(reuseTarget1,currentTopicName); } if (*reuseTarget1 && (*reuseTarget1 != '$' && *reuseTarget1 != '^' && *reuseTarget1 != '_' && *reuseTarget2 != USERVAR_PREFIX && *reuseTarget2 != '_')) // we cant crosscheck variable choices { if (*reuseTarget1 != '~') { memmove(reuseTarget1+1,reuseTarget1,strlen(reuseTarget1)+1); *reuseTarget1 = '~'; } strcat(reuseTarget1,(char*)"."); strcat(reuseTarget1,reuseTarget2); // compose the name NoteUse(reuseTarget1,currentFunctionDefinition ? currentFunctionDefinition->word : currentTopicName); } // now generate stuff as an output stream with its validation patternContext = oldContext; if (D && !(D->internalBits & FUNCTION_BITS)) --callingSystem; callingSystem = oldcallingsystem; *data++ = ')'; // outer layer generates trailing space *data = 0; ReleaseStack(strbase); // short term return ptr; } static void TestSubstitute(char* word,char* message) { WORDP D = FindWord(word); if (!D) return; WORDP E = GetSubstitute(D); if (E) { if (E->word[0] == '!') return; // ignore conditional char* which = "Something"; if (D->internalBits & DO_SUBSTITUTES) which = "Substitutes.txt"; if (D->internalBits & DO_CONTRACTIONS) which = "Contractions.txt"; if (D->internalBits & DO_ESSENTIALS) which = "Essentials.txt"; if (D->internalBits & DO_INTERJECTIONS) which = "Interjections.txt"; if (D->internalBits & DO_BRITISH) which = "British.txt"; if (D->internalBits & DO_SPELLING) which = "Spelling.txt"; if (D->internalBits & DO_TEXTING) which = "Texting.txt"; if (D->internalBits & DO_PRIVATE) which = "user private substitution"; if (E->word[1]) WARNSCRIPT((char*)"%s changes %s to %s %s\r\n",which,word,E->word,message) else WARNSCRIPT((char*)"%s erases %s %s\r\n",which,word,message) } } static void SpellCheckScriptWord(char* input,int startSeen,bool checkGrade) { if (!stricmp(input,(char*)"null")) return; // assignment clears if (nospellcheck) return; // remove any trailing punctuation char word[MAX_WORD_SIZE]; // see if supposed to ignore capitalization differences MakeLowerCopy(word, input); WORDP X = FindWord(word, 0, LOWERCASE_LOOKUP); if (X && X->internalBits & DO_NOISE && !(X->internalBits & HAS_SUBSTITUTE)) return; strcpy(word,input); size_t len = strlen(word); while (len > 1 && !IsAlphaUTF8(word[len-1]) && word[len-1] != '.') word[--len] = 0; WORDP set[20]; int i = GetWords(word, set, false); // words in any case and with mixed underscore and spaces char text[MAX_WORD_SIZE]; *text = 0; int nn = 0; if (i > 1) // multiple spell? { for (int x = 0; x < i; ++x) { if (GETMULTIWORDHEADER(set[x])) { if (!(set[x]->properties & TAG_TEST)) continue; // dont care } if (set[x]->properties & NOUN_FIRSTNAME) // Will, June, etc continue; strcat(text, set[x]->word); strcat(text, " "); ++nn; } } if (nn > 1) { WARNSCRIPT((char*)"Word \"%s\" known in multiple spellings %s\r\n", word, text) return; } WORDP D = FindWord(word,0,LOWERCASE_LOOKUP); WORDP entry = D; WORDP canonical = D; if (word[1] == 0 || IsUpperCase(*input) || !IsAlphaUTF8(*word) || strchr(word,'\'') || strchr(word,'.') || strchr(word,'_') || strchr(word,'-') || strchr(word,'~')) {;} // ignore proper names, sets, numbers, composite words, wordnet references, etc else if (stricmp(language,"english")) {;} // dont complain on foreign else if (!D || (!(D->properties & NORMAL_WORD) && !(D->systemFlags & PATTERN_WORD))) { // we dont know this word in lower case uint64 sysflags = 0; uint64 cansysflags = 0; wordStarts[0] = wordStarts[1] = wordStarts[2] = wordStarts[3] = AllocateHeap((char*)""); wordCount = 1; WORDP revise; uint64 flags = GetPosData(-1,word,revise,entry,canonical,sysflags,cansysflags,false,true,0); if (!flags) // try upper case { WORDP E = FindWord(word,0,SECONDARY_CASE_ALLOWED); // uppercase if (E && E != D && E->word[2]) WARNSCRIPT((char*)"Word %s only known in upper case\r\n",word) else if (E && !(E->internalBits & UPPERCASE_HASH) && !D ) WARNSCRIPT((char*)"%s is not a known word. Is it misspelled?\r\n",word) canonical = E; // the base word } } // check vocabularly limits? if (grade && checkGrade && !stricmp(language,"English")) { if (canonical && !IsUpperCase(*input) && !(canonical->systemFlags & grade) && !strchr(word,'\'')) // all contractions are legal Log(STDUSERLOG,(char*)"Grade Limit: %s\r\n",D->word); } // see if substitition will ruin this word if (!(spellCheck & NO_SUBSTITUTE_WARNING) ) { if (startSeen != -1) TestSubstitute(word,(char*)"anywhere in input"); char test[MAX_WORD_SIZE]; sprintf(test,(char*)"<%s",word); if (startSeen == 0) TestSubstitute(test,(char*)"at input start"); sprintf(test,(char*)"%s>",word); if (startSeen != -1) TestSubstitute(test,(char*)"at input end"); sprintf(test,(char*)"<%s>",word); if (startSeen == 0) TestSubstitute(test,(char*)"as entire input"); } } static char* GetRuleElipsis(char* rule) { static char value[50]; strncpy(value,rule,45); value[45] = 0; return value; } static bool PatternRelationToken(char* ptr) { if (*ptr == '!' && (ptr[1] == '=' || ptr[1] == '?')) return true; if (*ptr == '>' || *ptr == '<' || *ptr == '?' || *ptr == '&') return true; if (*ptr == '=') return true;; return false; } static bool RelationToken(char* word) { if (*word == '=') return (word[1] == '=' || !word[1]); return (*word == '<' || *word == '>' || *word == '?' || (*word == '!' && word[1] == '=') || *word == '&'); } static char* ReadDescribe(char* ptr, FILE* in,unsigned int build) { while (ALWAYS) // read as many tokens as needed to complete the definition (must be within same file) { char word[MAX_WORD_SIZE]; char description[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!stricmp(word,(char*)"describe:")) ptr = ReadNextSystemToken(in,ptr,word,false); // keep going with local loop if (!*word) break; // file ran dry size_t len = strlen(word); if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= len; // let someone else see this starter break; } if (*word != USERVAR_PREFIX && *word != '_' && *word != '^' && *word != '~') BADSCRIPT((char*)"Described entity %s is not legal to describe- must be variable or function or concept/topic\r\n", word) isDescribe = true; ptr = ReadNextSystemToken(in,ptr,description,false); isDescribe = false; char file[SMALL_WORD_SIZE]; sprintf(file,(char*)"%s/BUILD%s/describe%s.txt",topic,baseName,baseName); FILE* out = FopenUTF8WriteAppend(file); fprintf(out,(char*)" %s %s\r\n",word,description); fclose(out); // dont use Fclose } return ptr; } static void OverCover(char* laterword, STACKREF keywordList[PATTERNDEPTH], char nestKind[PATTERNDEPTH], int nestIndex) { // [ your "your own"] has your blocking detection of your_own and we want the longer match if (nestKind[nestIndex - 1] != '[' && nestKind[nestIndex - 1] != '{') return; char word1[MAX_WORD_SIZE]; strcpy(word1, laterword); char* underscore = strchr(word1, '_'); if (underscore) // see if masked by earlier word { *underscore = 0; // initial word of phrase STACKREF item = keywordList[nestIndex - 1]; while (item) { uint64 priorword; item = UnpackStackval(item, priorword); if (!strcmp((char*)priorword, word1)) BADSCRIPT((char*)"Keyword phrase %s occluded by %s. Switch their order.", laterword, priorword) } *underscore = '_'; } // add to list char* word = AllocateStack(laterword); keywordList[nestIndex - 1] = AllocateStackval(keywordList[nestIndex - 1], (uint64)word); } // never freed during compile char* ReadPattern(char* ptr, FILE* in, char* &data,bool macro, bool ifstatement) { // called from topic or patternmacro #ifdef INFORMATION // meaning of leading characters < > << >> sentence start & end boundaries, any ! NOT nul end of data from macro definition or argument substitution * *1 *~ *~2 *-1 gap (infinite, exactly 1 word, 0-2 words, 0-2 words, 1 word before) _ _2 memorize next match or refer to 3rd memorized match (0-based) @ factset references @5subject and _1 (positional set) $ user variable ^ ^1 function call or function argument (user) ()[]{} nesting of some kind (sequence AND, OR, OPTIONAL) dquote string token ? a question input ~dat ~ topic/set reference or current topic % system variable =xxx comparison test (= > < ) apostrophe and apostrophe! non-canonical meaning on next token or exclamation test \ escape next character as literal (\$ \= \~ \(etc) #xxx a constant number symbol, but only allowed on right side of comparison ------default values -1234567890 number token 12.14 number token 1435 number token a-z,A-Z,|,_ normal token , normal token (internal sentence punctuation) - period will never exist since we strip tail and cant be internal ----- these are things which must all be insured lower case (some can be on left or right side of comparison op) % system variable ~dat topic/set reference a: thru u: responder codes if/loop/jsonloop constructs ^call call function/macro calls with or without ^ ^fnvar function variables ^$glblvar global function variables $ user variable @ debug ahd factset references labels on responders responder types s: u: t: r: name of topic or concept x:=y (do assignment and do not fail) #endif char word[MAX_WORD_SIZE]; char nestKind[PATTERNDEPTH]; STACKREF keywordList[PATTERNDEPTH]; int nestLine[PATTERNDEPTH]; int nestIndex = 0; patternContext = true; unsigned int conceptIndex = 0; // id of concept set char* conceptBufferLevelStart[PATTERNDEPTH]; //start of currentConceptBuffer char* currentConceptBuffer = NULL; // movable ptr static char* conceptbase = NULL; // start of xfer buffer char* currentConceptXfer = NULL; // movable ptr char conceptStarted[PATTERNDEPTH]; // have we inited this level yet? char* stackbase = AllocateStack(NULL, 4); char* start = ptr; // if macro call, there is no opening ( or closing ) // We claim an opening and termination comes from finding a toplevel token if (macro) nestKind[nestIndex++] = '('; bool variableGapSeen = false; // wildcard pending // prefix characters bool memorizeSeen = false; // memorization pending bool quoteSeen = false; // saw ' bool notSeen = false; // saw ! bool bidirectionalSeen = false; // saw *~nb bool doubleNotSeen = false; // saw !! size_t len; bool startSeen = false; // starting token or not char* startPattern = data; char* startOrig = ptr; char* backup; // these buffer allocations must be last to balance Freebuffers in endScriptCompiler currentConceptBuffer = conceptBufferLevelStart[0] = AllocateBuffer(); conceptIndex = 0; conceptStarted[0] = 0; currentConceptXfer = conceptbase = AllocateBuffer(); while (ALWAYS) // read as many tokens as needed to complete the definition { backup = ptr; ptr = ReadNextSystemToken(in,ptr,word); if (!*word) break; // end of file if (!strcmp(word, "==") || !strcmp(word, "=")) WARNSCRIPT((char*)"== or = used standalone in pattern. Shouldn't it be attached to left and right tokens?\r\n") // we came from pattern IF and lack a ( if (ifstatement && *word != '(' && nestIndex == 0) nestKind[nestIndex++] = '('; MakeLowerCopy(lowercaseForm,word); if (TopLevelUnit(lowercaseForm) || TopLevelRule(lowercaseForm)) // end of pattern { ptr -= strlen(word); // safe break; } char c = 0; char* assignment = FindAssignment(word); if (assignment) // assignment, do normal analysis on 1st argument { c = *assignment; *assignment = 0; } char* comparison = FindComparison(word); if (comparison) // comparison, do normal analysis on 1st argument { c = *comparison; *comparison = 0; } switch(*word) // ordinary tokens, not the composite comparison blob { // token prefixes case '!': // NOT if (quoteSeen) BADSCRIPT((char*)"PATTERN-1 Cannot have ' and ! in succession\r\n") if (memorizeSeen) BADSCRIPT((char*)"PATTERN-2 Cannot use _ before _\r\n") if (notSeen) BADSCRIPT((char*)"PATTERN-3 Cannot have two ! in succession\r\n") if (!word[1]) BADSCRIPT((char*)"PATTERN-4 Must attach ! to next token. If you mean exclamation match, use escaped ! \r\n %s\r\n",ptr) notSeen = true; if (word[1] == '!') doubleNotSeen = true; if (comparison) *comparison = c; ptr -= strlen(word); // safe if (*ptr == '!') ++ptr; if (*ptr == '!') ++ptr; // possible !! allowed continue; case '_': // memorize OR var reference if (quoteSeen && !IsDigit(word[1])) BADSCRIPT((char*)"PATTERN-1 Cannot have ' and _ in succession except when quoting a match variable. Need to reverse them\r\n") if (memorizeSeen) BADSCRIPT((char*)"PATTERN-6 Cannot have two _ in succession\r\n") if (!word[1]) // allow separation which will be implied as needed { if (!ifstatement) BADSCRIPT((char*)"PATTERN-7 Must attach _ to next token. If you mean _ match, use escaped _. %s\r\n",ptr) } if (IsDigit(word[1])) // match variable { if (GetWildcardID(word) < 0) BADSCRIPT((char*)"PATTERN-8 _%d is max match reference - %s\r\n",MAX_WILDCARDS-1,word) break; } memorizeSeen = true; quoteSeen = false; if (comparison) *comparison = c; len = strlen(word) - 1 ; ptr -= len; // the remnant strncpy(ptr,word+1, len); // this allows a function parameter (originally ^word but now ^0) to properly reset continue; case '\'': // original (non-canonical) token - possessive must be \'s or \' if (quoteSeen) BADSCRIPT((char*)"PATTERN-10 Cannot have two ' in succession\r\n") if (!word[1]) BADSCRIPT((char*)"PATTERN-11 Must attach ' to next token. If you mean ' match, use \' \r\n %s\r\n",ptr) quoteSeen = true; variableGapSeen = false; if (comparison) *comparison = c; len = strlen(word) - 1 ; ptr -= len; // the remnant strncpy(ptr,word+1, len); // this allows a function parameter (originally ^word but now ^0) to properly reset continue; case '<': // sentence start < or unordered start << if (quoteSeen) BADSCRIPT((char*)"PATTERN-12 Cannot use ' before < or <<\r\n") if (memorizeSeen) BADSCRIPT((char*)"PATTERN-13 Cannot use _ before < or <<\r\n") if (word[1] == '<') // << unordered start { if (memorizeSeen) BADSCRIPT((char*)"PATTERN-14 Cannot use _ before << \r\n") if (nestKind[nestIndex-1] == '<') BADSCRIPT((char*)"PATTERN-15 << already in progress\r\n") if (variableGapSeen) BADSCRIPT((char*)"PATTERN-16 Cannot use * before <<\r\n") // close [ or { for a moment if (nestKind[nestIndex - 1] == '[' || nestKind[nestIndex - 1] == '{') { currentConceptBuffer = conceptBufferLevelStart[conceptIndex]; // resume here strcpy(currentConceptXfer, currentConceptBuffer); currentConceptXfer += strlen(currentConceptXfer); if (!livecall && *currentConceptBuffer) // we had some member { sprintf(currentConceptXfer, "%s", ")\r\n"); currentConceptXfer += 3; } *currentConceptBuffer = 0; *currentConceptXfer = 0; conceptBufferLevelStart[conceptIndex] = currentConceptBuffer; conceptStarted[conceptIndex] = 0; } nestLine[nestIndex] = currentFileLine; nestKind[nestIndex++] = '<'; } else if (word[1]) BADSCRIPT((char*)"PATTERN-17 %s cannot start with <\r\n",word) variableGapSeen = false; break; case '@': if (quoteSeen) BADSCRIPT((char*)"PATTERN-18 Quoting @ is meaningless.\r\n"); if (memorizeSeen) BADSCRIPT((char*)"PATTERN-19 Cannot use _ before @\r\n") if (word[1] == '_') // set match position @_5 { if (GetWildcardID(word+1) >= MAX_WILDCARDS) BADSCRIPT((char*)"PATTERN-? %s is not a valid positional reference - must be < %d\r\n",word,MAX_WILDCARDS) char* end = word + 3; while (IsDigit(*end)) ++end; if (*end) { if (*end == '+' && (!end[1] || end[1] == 'i')) {;} else if (*end == '-' && (!end[1] || end[1] == 'i')) {;} else BADSCRIPT((char*)"PATTERN-? %s is not a valid positional reference - @_2+ or @_2- or @_2 would be\r\n",word) } variableGapSeen = false; // no longer after anything. we are changing direction } else if (!stricmp(word, "@retry")) {} else if (GetSetID(word) < 0) BADSCRIPT((char*)"PATTERN-20 %s is not a valid factset reference\r\n",word) // factset reference else if (!GetSetMod(word)) BADSCRIPT((char*)"PATTERN-20 %s is not a valid factset reference\r\n",word) // factset reference break; case '>': // sentence end > or unordered end >> if (quoteSeen) BADSCRIPT((char*)"PATTERN-21 Cannot use ' before > or >>\r\n") if (word[1] == '>') // >> { if (memorizeSeen) BADSCRIPT((char*)"PATTERN-22 Cannot use _ before >> \r\n") if (nestKind[nestIndex - 1] != '<') BADSCRIPT((char*)"PATTERN-23 Have no << in progress\r\n"); if (variableGapSeen) BADSCRIPT((char*)"PATTERN-24 Cannot use wildcard inside >>\r\n") if (nestKind[--nestIndex] != '<') BADSCRIPT((char*)"PATTERN-24 >> should be closing %c started at line %d\r\n", nestKind[nestIndex],nestLine[nestIndex]) } variableGapSeen = false; break; // sentence end align case '(': // sequential pattern unit begin // close [ or { for a moment if (nestKind[nestIndex-1] == '[' || nestKind[nestIndex-1] == '{') { currentConceptBuffer = conceptBufferLevelStart[conceptIndex]; // resume here strcpy(currentConceptXfer, currentConceptBuffer); currentConceptXfer += strlen(currentConceptXfer); if (!livecall && *currentConceptBuffer) // we had some member { sprintf(currentConceptXfer, "%s", ")\r\n"); currentConceptXfer += 3; } *currentConceptBuffer = 0; *currentConceptXfer = 0; conceptBufferLevelStart[conceptIndex] = currentConceptBuffer; conceptStarted[conceptIndex] = 0; } if (bidirectionalSeen) BADSCRIPT((char*)"PATTERN-34 ] Cant use ( after bidirectional gap- scanning backwards is bad\r\n") if (quoteSeen) BADSCRIPT((char*)"PATTERN-25 Quoting ( is meaningless.\r\n"); nestLine[nestIndex] = currentFileLine; nestKind[nestIndex++] = '('; break; case ')': // sequential pattern unit end if (quoteSeen) BADSCRIPT((char*)"PATTERN-26 Quoting ) is meaningless.\r\n"); if (memorizeSeen && !ifstatement) BADSCRIPT((char*)"PATTERN-27 Cannot use _ before )\r\n") if (variableGapSeen && nestIndex > 1) BADSCRIPT((char*)"PATTERN-26 Cannot have wildcard followed by )\r\n") if (nestKind[--nestIndex] != '(') BADSCRIPT((char*)"PATTERN-9 ) should be closing %c started at line %d\r\n", nestKind[nestIndex], nestLine[nestIndex]) break; case '[': // list of pattern choices begin if (quoteSeen) BADSCRIPT((char*)"PATTERN-30 Quoting [ is meaningless.\r\n"); if (nestKind[nestIndex - 1] == '[' || nestKind[nestIndex - 1] == '{') { currentConceptBuffer = conceptBufferLevelStart[conceptIndex]; // resume here strcpy(currentConceptXfer, currentConceptBuffer); currentConceptXfer += strlen(currentConceptXfer); if (!livecall && *currentConceptBuffer) // we had some member { sprintf(currentConceptXfer, "%s", ")\r\n"); currentConceptXfer += 3; } *currentConceptBuffer = 0; *currentConceptXfer = 0; conceptBufferLevelStart[conceptIndex] = currentConceptBuffer; conceptStarted[conceptIndex] = 0; } nestLine[nestIndex] = currentFileLine; keywordList[nestIndex] = 0; nestKind[nestIndex++] = '['; conceptBufferLevelStart[++conceptIndex] = currentConceptBuffer; conceptStarted[conceptIndex] = 0; break; case ']': // list of pattern choices end if (quoteSeen) BADSCRIPT((char*)"PATTERN-31 Quoting ] is meaningless.\r\n"); if (memorizeSeen) BADSCRIPT((char*)"PATTERN-32 Cannot use _ before ]\r\n") if (variableGapSeen) BADSCRIPT((char*)"PATTERN-33 Cannot have wildcard followed by ]\r\n") if (nestKind[--nestIndex] != '[') BADSCRIPT((char*)"PATTERN-34 ] should be closing %c started at line %d\r\n", nestKind[nestIndex], nestLine[nestIndex]) currentConceptBuffer = conceptBufferLevelStart[conceptIndex--]; // resume here strcpy(currentConceptXfer, currentConceptBuffer); currentConceptXfer += strlen(currentConceptXfer); if (!livecall && *currentConceptBuffer) // we had some member { sprintf(currentConceptXfer,"%s",")\r\n"); currentConceptXfer += 3; } *currentConceptBuffer = 0; *currentConceptXfer = 0; break; case '{': // list of optional choices begins if (nestKind[nestIndex-1] == '[') BADSCRIPT((char*)"PATTERN-15 {} within [] is pointless because it always matches\r\n") if (nestKind[nestIndex - 1] == '<' && !memorizeSeen) WARNSCRIPT((char*)"PATTERN-15 {} within << >> is pointless unless you memorize or use ^matches because it always matches\r\n") if (bidirectionalSeen) BADSCRIPT((char*)"PATTERN-34 ] Cant use { after bidirectional gap - will always match scanning backwards\r\n") // close [ or { for a moment if (nestKind[nestIndex - 1] == '[' || nestKind[nestIndex - 1] == '{') { currentConceptBuffer = conceptBufferLevelStart[conceptIndex]; // resume here strcpy(currentConceptXfer, currentConceptBuffer); currentConceptXfer += strlen(currentConceptXfer); if (!livecall && *currentConceptBuffer) // we had some member { sprintf(currentConceptXfer, "%s", ")\r\n"); currentConceptXfer += 3; } *currentConceptBuffer = 0; *currentConceptXfer = 0; conceptBufferLevelStart[conceptIndex] = currentConceptBuffer; conceptStarted[conceptIndex] = 0; } if (variableGapSeen) { // if we can see end of } and it has a gap after it... thats a problem - two gaps in succession is the equivalent char* end = strchr(ptr,'}'); if (end) { end = SkipWhitespace(end); if (*end == '*') WARNSCRIPT((char*)"Wildcard before and after optional will probably not work since wildcards wont know where to end if optional fails. Use some other formulation\r\n") } } if (quoteSeen) BADSCRIPT((char*)"PATTERN-35 Quoting { is meaningless.\r\n"); if (notSeen) BADSCRIPT((char*)"PATTERN-36 !{ is pointless since { can fail or not anyway\r\n") if (nestIndex && nestKind[nestIndex-1] == '{') BADSCRIPT((char*)"PATTERN-37 {{ is illegal\r\n") keywordList[nestIndex] = 0; nestLine[nestIndex] = currentFileLine; nestKind[nestIndex++] = '{'; conceptBufferLevelStart[++conceptIndex] = currentConceptBuffer; conceptStarted[conceptIndex] = 0; break; case '}': // list of optional choices ends if (quoteSeen) BADSCRIPT((char*)"PATTERN-38 Quoting } is meaningless.\r\n"); if (memorizeSeen) BADSCRIPT((char*)"PATTERN-39 Cannot use _ before }\r\n") if (variableGapSeen) BADSCRIPT((char*)"PATTERN-40 Cannot have wildcard followed by }\r\n") if (nestKind[--nestIndex] != '{') BADSCRIPT((char*)"PATTERN-41 } should be closing %c started at line %d\r\n", nestKind[nestIndex], nestLine[nestIndex]) currentConceptBuffer = conceptBufferLevelStart[conceptIndex--]; // resume here strcpy(currentConceptXfer, currentConceptBuffer); currentConceptXfer += strlen(currentConceptXfer); if (!livecall && *currentConceptBuffer) // we had some member { sprintf(currentConceptXfer, "%s", ")\r\n"); currentConceptXfer += 3; } *currentConceptBuffer = 0; *currentConceptXfer = 0; break; case '\\': // literal next character if (quoteSeen) BADSCRIPT((char*)"PATTERN-42 Quoting an escape is meaningless.\r\n"); if (!word[1]) BADSCRIPT((char*)"PATTERN-43 Backslash must be joined to something to escape\r\n") variableGapSeen = false; if (word[1] && IsAlphaUTF8(word[1] )) memmove(word,word+1,strlen(word)); // escaping a real word, just use it break; case '*': // gap: * *1 *~2 (infinite, exactly 1 word, 0-2 words, 0-2 words, 1 word before) and *alpha*x* is form match if (quoteSeen) BADSCRIPT((char*)"PATTERN-44 Quoting a wildcard\r\n"); if (nestKind[nestIndex - 1] == '<') BADSCRIPT((char*)"PATTERN-45 Can not have wildcard %s inside << >>\r\n", word) if (nestKind[nestIndex-1] != '(' && (word[1] == '~' || !word[1])) BADSCRIPT((char*)"PATTERN-45 Can only have variable wildcard %s inside ( )\r\n",word) if (variableGapSeen) BADSCRIPT((char*)"PATTERN-46 Cannot have wildcard followed by %s\r\n",word) if (IsAlphaUTF8(word[1]) ) break; // find this word as fragmented spelling like sch*ding* since it will have * as a prefix // gaps of various flavors if (notSeen) BADSCRIPT((char*)"PATTERN-47 cannot have ! before gap - %s\r\n",word) if (IsDigit(word[1])) // enumerated gap size { int n = word[1] - '0'; if (n == 0) BADSCRIPT((char*)"PATTERN-48 *0 is meaningless\r\n") if (word[2]) BADSCRIPT((char*)"PATTERN-49 *9 is the largest gap allowed or bad stuff is stuck to your token- %s\r\n",word) } else if (word[1] == '-') // backwards { int n = word[2] - '0'; if (n == 0) BADSCRIPT((char*)"PATTERN-50 *-1 is the smallest backward wildcard allowed - %s\r\n",word) if (word[3]) BADSCRIPT((char*)"PATTERN-51 *-9 is the largest backward wildcard or bad stuff is stuck to your token- %s\r\n",word) } else if (word[1] == '~') // close-range gap { if (nestKind[nestIndex-1] == '{' || nestKind[nestIndex-1] == '[') BADSCRIPT((char*)"PATTERN-5? cannot stick %s wildcard inside {} or []\r\n",word) variableGapSeen = true; int n = word[2] - '0'; if (!word[2]) BADSCRIPT((char*)"PATTERN-52 *~ is not legal, you need a digit after it\r\n") else if (n == 0 && word[2] != '0') BADSCRIPT((char*)"PATTERN-53 *~1 is the smallest close-range gap - %s\r\n", word) else if (word[3] && word[3] != 'b') BADSCRIPT((char*)"PATTERN-54 *~9 is the largest close-range gap or bad stuff is stuck to your token- %s\r\n", word) } else if (word[1]) BADSCRIPT((char*)"PATTERN-55 * jammed against some other token- %s\r\n",word) else { if (nestKind[nestIndex-1] == '{' || nestKind[nestIndex-1] == '[') BADSCRIPT((char*)"PATTERN-5? cannot stick * wildcard inside {} or []\r\n") variableGapSeen = true; // std * unlimited wildcard } startSeen = true; break; case '?': // question input ? if (quoteSeen) BADSCRIPT((char*)"PATTERN-56 Quoting a ? is meaningless.\r\n"); if (memorizeSeen && word[1] != '$') BADSCRIPT((char*)"PATTERN-57 Cannot use _ before ?\r\n") if (variableGapSeen) BADSCRIPT((char*)"PATTERN-58 Cannot have wildcards before ?\r\n") break; case USERVAR_PREFIX: // user var if (quoteSeen) BADSCRIPT((char*)"PATTERN-59 Quoting a $ variable is meaningless - %s\r\n",word); variableGapSeen = false; break; case '"': // string { // you can quote a string, because you are quoting its members variableGapSeen = false; strcpy(word,JoinWords(BurstWord(word,CONTRACTIONS)));// change from string to std token WritePatternWord(word); WriteKey(word); unsigned int n = 0; char* ptr = word; while ((ptr = strchr(ptr,'_'))) { ++n; ++ptr; } if (n >= SEQUENCE_LIMIT) WARNSCRIPT((char*)"PATTERN-? Too many words in string %s, may never match\r\n",word) } goto DEFLT; case SYSVAR_PREFIX: // system data // you can quote system variables because %topic returns a topic name which can be quoted to query if (memorizeSeen) BADSCRIPT((char*)"PATTERN-60 Cannot use _ before system variable - %s\r\n",word) if (!word[1]); // simple % else if (!FindWord(word)) BADSCRIPT((char*)"PATTERN-61 %s is not a system variable\r\n",word) if (comparison) *comparison = c; variableGapSeen = false; break; case '~': variableGapSeen = false; if (quoteSeen) BADSCRIPT((char*)"PATTERN-61 cannot quote set %s because it can't be determined if set comes from original or canonical form\r\n",word) startSeen = true; WriteKey(word); CheckSetOrTopic(word); // set or topic goto DEFLT; default: // normal token ( and anon function call) DEFLT: // MERGE user pattern words into one? , e.g. drinking age == drinking_age in dictionary // only in () sequence mode. Dont merge [old age] or {old age} or << old age >> if (nestKind[nestIndex-1] == '(') // BUG- do we need to see what triples etc wordnet has { // dont want pattern may 9 to merge ReadNextSystemToken(in,ptr,nextToken,true,true); WORDP F = FindWord(word); WORDP E = FindWord(nextToken); if (E && F && E->properties & PART_OF_SPEECH && F->properties & PART_OF_SPEECH) { char join[MAX_WORD_SIZE]; sprintf(join,(char*)"%s_%s",word,nextToken); E = FindWord(join,0,PRIMARY_CASE_ALLOWED); // must be direct match if (E && E->properties & PART_OF_SPEECH && !IS_NEW_WORD(E)) // change to composite { strcpy(word,join); // joined word replaces it ptr = ReadNextSystemToken(in,ptr,nextToken,true,false); // swallow the lookahead *nextToken = 0; } } } // some token in optional or choice if (noPatternOptimization || disablePatternOptimization || assignment || comparison || *word == '^' || *word == '_' || *word == '@' || *word == '$' || *word == '%') {;} else if (strchr(word, '*') || strchr(word, '?')) { ; } // wildcard word patterns else if (nestKind[nestIndex - 1] == '[' || nestKind[nestIndex - 1] == '{') { char controls[100]; *controls = 0; if (notSeen) strcat(controls, "!"); if (*controls && memorizeSeen) BADSCRIPT((char*)"PATTERN-67 Cannot have ! and _ together\r\n") if (quoteSeen) strcat(controls, "'"); notSeen = quoteSeen = false; char name[MAX_WORD_SIZE]; if (!conceptStarted[conceptIndex ]) // not yet started { int layer = 1; if (buildId == BUILD0) layer = 0; else if (buildId == BUILD0) layer = 1; if (myBot && !livecall) { #ifdef WIN32 sprintf(name, (char*)"~%d%05d`%I64d", layer, ++conceptID, myBot); #else sprintf(name, (char*)"~%d%05d`%lld", layer, ++conceptID, myBot); #endif } else sprintf(name, "~%d%05d", layer,++conceptID); conceptStarted[conceptIndex ] = 1; if (!livecall) sprintf(currentConceptBuffer, "%s ( ", name); else sprintf(currentConceptBuffer, "%s ", name); currentConceptBuffer += strlen(currentConceptBuffer); sprintf(currentConceptBuffer, "%s%s ", controls,word); currentConceptBuffer += strlen(currentConceptBuffer); sprintf(word, "~%d%05d", layer, conceptID); // no bot id attached } else { sprintf(currentConceptBuffer, "%s%s ", controls,word); currentConceptBuffer += strlen(currentConceptBuffer); *word = 0; // dont use it } } variableGapSeen = false; startSeen = true; break; } if (assignment) { *assignment = c; if (memorizeSeen && assignment[1]) BADSCRIPT((char*)"PATTERN-57 Cannot use _ before an assignment\r\n") if (variableGapSeen) BADSCRIPT((char*)"PATTERN-16 Cannot use * before assignment since memorization will be incomplete\r\n") // rebuild token char tmp[MAX_WORD_SIZE]; *tmp = ':'; // assignment header int len = (assignment - word) + 2; // include the : and jump code in length if (len > 70) BADSCRIPT((char*)"PATTERN-65 Left side of assignment must not exceed 70 characters - %s\r\n", word) char* x = tmp + 1; Encode(len, x, 1); strcpy(tmp + 2, word); // copy left side over strcpy(word, tmp); // replace original token } else if (comparison) // is a comparison of some kind { if (memorizeSeen && comparison[1]) BADSCRIPT((char*)"PATTERN-57 Cannot use _ before a comparison\r\n") if (variableGapSeen) BADSCRIPT((char*)"PATTERN-16 Cannot use * before comparison since memorization will be incomplete\r\n") if (*word == USERVAR_PREFIX && word[1] == LOCALVAR_PREFIX) { char* dot = strchr(word,'.'); if (dot) *word = 0; AddDisplay(word); if (dot) *word = '.'; } *comparison = c; if (c == '!') // move not operator out in front of token { *data++ = '!'; *data++ = ' '; // and space it, so if we see "!=shec?~hello" we wont think != is an operator, instead = is a jump infof size_t len = strlen(comparison); memmove(comparison,comparison+1,len); } if (quoteSeen && *word == '_' && IsDigit(word[1])) // quoted match variable { quoteSeen = false; memmove(word+1,word,strlen(word)+1); *word = '\''; ++comparison; // moved over for the added ' } char* rhs = comparison+1; if (*rhs == '=' || *rhs == '?') ++rhs; if (*rhs == '^' && IsAlphaUTF8(rhs[1])) BADSCRIPT((char*)"%s is not a current function variable\r\n",rhs); if (!*rhs && *word == USERVAR_PREFIX) {} // allowed member in sentence else if (!*rhs && *word == '_' && IsDigit(word[1])); // allowed member in sentence else if (*rhs == '#') // names a constant #define to replace with number value { uint64 n = FindValueByName(rhs+1); if (!n) n = FindSystemValueByName(rhs+1); if (!n) n = FindParseValueByName(rhs+1); if (!n) n = FindMiscValueByName(rhs+1); if (!n) BADSCRIPT((char*)"PATTERN-63 No #constant recognized - %s\r\n",rhs+1) #ifdef WIN32 sprintf(rhs,(char*)"%I64d",(long long int) n); #else sprintf(rhs,(char*)"%lld",(long long int) n); #endif } else if (IsAlphaUTF8DigitNumeric(*rhs) ) // LITERAL has no constraints { // WriteKey(rhs); // WritePatternWord(rhs); // ordinary token } else if (*rhs == '~') { MakeLowerCase(rhs); CheckSetOrTopic(rhs); } else if (*rhs == '_' || *rhs == '@'); // match variable or factset variable else if (*rhs == USERVAR_PREFIX) { MakeLowerCase(rhs); // user variable if (rhs[1] == LOCALVAR_PREFIX) { char* dot = strchr(rhs,'.'); if (dot) *rhs = 0; AddDisplay(rhs); if (dot) *word = '.'; } } else if (*rhs == SYSVAR_PREFIX) MakeLowerCase(rhs); // system variable else if (*rhs == '^' && (rhs[1] == '_' || rhs[1] == USERVAR_PREFIX || IsDigit(rhs[1]))) MakeLowerCase(rhs); // indirect match variable or indirect user vaiable or function variable else if (!*rhs && *comparison == '?' && !comparison[1]); else if (*rhs == '\'' && (rhs[1] == USERVAR_PREFIX || rhs[1]== '_')); // unevaled user variable or raw match variable else if (!comparison[2] && *word == USERVAR_PREFIX); // find in sentence else if (*rhs == '"' && rhs[strlen(rhs)-1] == '"'){;} // quoted string else BADSCRIPT((char*)"PATTERN-64 Illegal comparison %s or failed to close prior rule starting at %s\r\n",word, GetRuleElipsis(start)) int len = (comparison - word) + 2; // include the = and jump code in length // rebuild token char tmp[MAX_WORD_SIZE]; *tmp = '='; // comparison header if (len > 70) BADSCRIPT((char*)"PATTERN-65 Left side of comparison must not exceed 70 characters - %s\r\n",word) char* x = tmp+1; Encode(len,x,1); strcpy(tmp+2,word); // copy left side over strcpy(word,tmp); // replace original token } else if (*word == '~') CheckSetOrTopic(word); ReadNextSystemToken(in,ptr,nextToken,true,true); // see if we have an implied call (he omitted the ^) if (false && *word != '^' && *nextToken == '(') // looks like a call, reformat it if it is - NO, require ^ in a pattern so dont collide on words with name like function { char rename[MAX_WORD_SIZE]; *rename = '^'; strcpy(rename+1,word); // in case user omitted the ^ WORDP D = FindWord(rename,0,LOWERCASE_LOOKUP); if (D && D->internalBits & FUNCTION_NAME) strcpy(word,D->word); // a recognized call } if (*word == '^') // function call or function var ref or indirect function variable assign ref like ^$$tmp = null { if (quoteSeen) BADSCRIPT((char*)"PATTERN-? Cannot use quote before ^ function call or variable\r\n") if (notSeen) { *data++ = '!'; if (doubleNotSeen) *data++ = '!'; doubleNotSeen = notSeen = false; } if (memorizeSeen) { if (!IsDigit(word[1]) && word[1] != USERVAR_PREFIX) BADSCRIPT((char*)"PATTERN-66 Cannot use _ before ^ function call\r\n") *data++ = '_'; memorizeSeen = false; } if (word[1] == USERVAR_PREFIX) { strcpy(data,word); data += strlen(data); } else { ptr = ReadCall(word,ptr,in,data,*nextToken == '(',false); if (PatternRelationToken(ptr)) // immediate relation bound to call? { ptr = ReadNextSystemToken(in,ptr,word); strcpy(data,word); data += strlen(data); } } *data++ = ' '; continue; } // put out the next token and space if (notSeen) { if (memorizeSeen) BADSCRIPT((char*)"PATTERN-67 Cannot have ! and _ together\r\n") *data++ = '!'; if (doubleNotSeen) *data++ = '!'; doubleNotSeen = notSeen = false; } if (quoteSeen) { *data++ = '\''; quoteSeen = false; } if (memorizeSeen) { *data++ = '_'; if (ifstatement) *data++ = ' '; memorizeSeen = false; } if (IsAlphaUTF8(*word) || (*word == '*' && IsAlphaUTF8(word[1])) ) { char* p; if ((p = strchr(word,'*'))) // wild word fragment? reformat to have leading * and lower case the test { char hold[MAX_WORD_SIZE]; MakeLowerCopy(hold,word); *word = '*'; strcpy(word+1,hold); } else if (IsPunctuation(*word) && !word[1]) // punctuation { WriteKey(word); WritePatternWord(word); // memorize it to know its important } else // ordinary word - break off possessives as needed { size_t lenx = strlen(word); unsigned int ignore = 0; if (lenx > 1 && word[lenx-1] == '\'' && word[lenx-2] != '_') // ending ' possessive plural { if (ifstatement && !strcmp(word,"PATTERN")) {;} // allow uppercase else { OverCover(word, keywordList,nestKind,nestIndex); WritePatternWord(word); WriteKey(word); } word[--lenx] = 0; ignore = 1; } else if (lenx > 2 && word[lenx-1] == 's' && word[lenx-2] == '\'' && word[lenx-3] != '_') // ending 's possessive singular { OverCover(word, keywordList, nestKind, nestIndex); WriteKey(word); WritePatternWord(word); lenx -= 2; word[lenx] = 0; ignore = 2; } strcpy(word,JoinWords(BurstWord(word,CONTRACTIONS))); // change to std token if (!livecall && spellCheck && !(spellCheck & NO_SPELL)) SpellCheckScriptWord(word,startSeen ? 1 : 0,false); if (strcmp(word,"PATTERN")) { OverCover(word, keywordList, nestKind, nestIndex); WriteKey(word); WritePatternWord(word); // memorize it to know its important } if (ignore) { strcpy(data,word); data += strlen(data); *data++ = '_'; if (ignore == 1) strcpy(word,(char*)"'"); else strcpy(word,(char*)"'s"); } } } strcpy(data,word); if (*word) { data += strlen(data); *data++ = ' '; } bidirectionalSeen = false; if (nestIndex == 0) break; // we completed this level if (*word == '*' && word[1] == '~' && word[3] && word[3] == 'b') bidirectionalSeen = true; } *data = 0; // leftovers? if (macro && nestIndex != 1) BADSCRIPT((char*)"PATTERN-68 Failed to balance ( or [ or { properly in macro for %s\r\n",startPattern) else if (!macro && nestIndex != 0) BADSCRIPT((char*)"PATTERN-69 Failed to close %c started at line %d : %s\r\n",nestKind[nestIndex-1],nestLine[nestIndex-1],startPattern); patternContext = false; ReleaseStack(stackbase); if (!*conceptbase) {;} // no optimization happened else if (!livecall) // not from compilepattern or dynamic testpattern { char filename[SMALL_WORD_SIZE]; int layer = 1; if (buildId == BUILD0) layer = 0; else if (buildId == BUILD0) layer = 1; sprintf(filename, (char*)"%s/BUILD%d/keywords%d.txt", topic, layer, layer); FILE* out = FopenUTF8WriteAppend(filename); fprintf(out, "%s", conceptbase); fclose(out); } else // ^compilepattern optimzation { char* revised = AllocateBuffer(); strcpy(revised, startPattern); strcpy(startPattern, conceptbase); strcat(startPattern, revised); FreeBuffer(); } FreeBuffer(); // conceptBufferLevelStart FreeBuffer(); // conceptbase return ptr; } static char* ReadChoice(char* word, char* ptr, FILE* in, char* &data,char* rejoinders) { // returns the stored data, not the ptr, starts with the [ *data++ = '['; *data++ = ' '; ReadNextSystemToken(in,ptr,word,true); // get possible rejoinder label if (word[1] == ':' && !word[2]) // is rejoinder label { if (*word < 'a' || *word >= 'q') BADSCRIPT((char*)"CHOICE-1 Bad level label %s in [ ]\r\n",word) if (rejoinders) rejoinders[(int)(*word - 'a' + 1)] = 2; // authorized level *data++ = *word; *data++ = word[1]; *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false); } ptr = ReadOutput(false,true,ptr,in,data,rejoinders,NULL,NULL,true); *data = 0; return ptr; } static bool ValidIfOperand(char c) { return (c != '<' && c != '+' && c != '-' && c != '*' && c != '/' && c != '&' && c != '|' && c != '%' && c != '=' && c != '>' && c != '^' && c != '!' && c != '?'); } char* ReadIfTest(char* ptr, FILE* in, char* &data) { priorLine = currentFileLine; char word[MAX_WORD_SIZE]; int paren = 1; // test is either a function call OR an equality comparison OR an IN relation OR an existence test // the followup will be either (or < > == or IN or ) // The function call returns a status code, you cant do comparison on it // but both function and existence can be notted- IF (!$var) or IF (!read(xx)) // You can have multiple tests, separated by AND and OR. PATTERN: ptr = ReadNextSystemToken(in,ptr,word,false,false); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (*word == '~' ) CheckSetOrTopic(word); // separate ! from things if not != and !? if (*word == '!' && word[1] && word[1] != '=' && word[1] != '?') { while (*--ptr != '!' && *ptr); ++ptr; word[1] = 0; } // actually a test joined on? char* at = word; while (*++at && ValidIfOperand(*at)) {;} // never look at first character if (*at) { size_t len = strlen(at); if (*at == '-' && *word == '$') {;} // $atat-ata could be subtract or name, but cannot be subtract in if test else if (*at == '^' && *word == '\'') {;} // '^arg is not an operator else { *at = 0; ptr -= len; // back up to rescan at = ptr; while (!ValidIfOperand(*at)) {++at;} // where does operand end? memmove(at + 1, at, strlen(at)+1); *at = ' '; // separate operand } } bool notted = false; if (*word == '!' && !word[1]) { notted = true; *data++ = '!'; *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false,false); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } } if (*word == '\'' && !word[1]) { *data++ = '\''; ptr = ReadNextSystemToken(in,ptr,word,false,false); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (*word != '_' && *word != '^') BADSCRIPT((char*)"IF-3 Can only quote _matchvar (or functionvar of one) in IF test\r\n") } if (*word == '!') BADSCRIPT((char*)"IF-4 Cannot do two ! in a row\r\n") ReadNextSystemToken(in,ptr,nextToken,false,true); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } MakeLowerCase(nextToken); if (*nextToken != '(' && *word == '^' && word[1] != '"' && IsAlphaUTF8(word[1])) BADSCRIPT((char*)"%s is not the name of a local function argument\r\n",word) if (*nextToken == '(') // function call? { if (*word != '^') // a call w/o its ^ { char rename[MAX_WORD_SIZE]; *rename = '^'; strcpy(rename+1,word); // in case user omitted the ^ strcpy(word,rename); } ptr = ReadCall(word,ptr,in,data,true,false); // read call ReadNextSystemToken(in,ptr,nextToken,false,true); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (RelationToken(nextToken)) { if (notted) BADSCRIPT((char*)"IF-5 cannot do ! in front of comparison %s\r\n",nextToken) *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow operator if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } strcpy(data,word); data += strlen(word); *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow value if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } strcpy(data,word); data += strlen(word); } } else if (*nextToken == '!' && nextToken[1] == '?') { if (notted) BADSCRIPT((char*)"IF-6 cannot do ! in front of query %s\r\n",nextToken) if (*word == '\'' && word[1] == '_') {;} else if (*word != '@' &&*word != USERVAR_PREFIX && *word != '_' && *word != '^' && *word != SYSVAR_PREFIX) BADSCRIPT((char*)"IF test query must be with $var, _# or '_#, %sysvar, @1subject or ^fnarg -%s\r\n",word) strcpy(data,word); data += strlen(word); *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow operator strcpy(data,word); data += strlen(word); *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow value if (*word == '^' && !IsDigit(word[1])) BADSCRIPT((char*)"IF-7 not allowed 2nd function call in relation - %s\r\n",word) if (*word == '~') CheckSetOrTopic(word); strcpy(data,word); data += strlen(word); } else if (RelationToken(nextToken)) { if (notted && *nextToken != '?') BADSCRIPT((char*)"IF-8 cannot do ! in front of comparison %s\r\n",nextToken) if (*word == '\'' && ((word[1] == '^' && IsDigit(word[2])) || word[1] == USERVAR_PREFIX || word[1] == '_')) {;} // quoted variable else if (*word != '@' && *word != USERVAR_PREFIX && *word != '_' && *word != '^' && *word != SYSVAR_PREFIX && !IsAlphaUTF8(*word) && !IsDigit(*word) && *word != '+' && *word != '-') BADSCRIPT((char*)"IF test comparison 1st value must be number, word, $var, _#, sysvar, @1subject or ^fnarg -%s\r\n",word) strcpy(data,word); data += strlen(word); *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow operator strcpy(data,word); data += strlen(word); *data++ = ' '; ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow value if (*word == '~') CheckSetOrTopic(word); if (*word == '^' && !IsDigit(word[1])) BADSCRIPT((char*)"IF-9 not allowed function call or active string in relation as 2nd arg - %s\r\n",word) strcpy(data,word); data += strlen(word); } else if (*nextToken == ')' || !stricmp(nextToken,(char*)"and") || !stricmp(nextToken, (char*)"&") || !stricmp(nextToken,(char*)"or")) // existence test { if (*word != USERVAR_PREFIX && *word != '_' && *word != '@' && *word != '^' && *word != SYSVAR_PREFIX && *word != '?' ) BADSCRIPT((char*)"IF-10 existence test - %s. Must be uservar or systemvar or _# or ? or @# or ~concept or ^^var \r\n",word) strcpy(data,word); data += strlen(word); } else BADSCRIPT((char*)"IF-11 illegal test %s %s . Use (X > Y) or (Foo()) or (X IN Y) or ($var) or (_3)\r\n",word,nextToken) *data++ = ' '; // check for close or more conditions ptr = ReadNextSystemToken(in,ptr,word,false,false); // ) if (*word == '~') CheckSetOrTopic(word); if (*word == ')') { *data++ = ')'; *data++ = ' '; } else if (!stricmp(word,(char*)"or") || !stricmp(word,(char*)"and") || !stricmp(word, (char*)"&")) { MakeLowerCopy(data,word); data += strlen(word); *data++ = ' '; goto PATTERN; // handle next element } else BADSCRIPT((char*)"IF-12 comparison must close with ) -%s .. Did you make a function call as 1st argument? that's illegal\r\n",word) *data = 0; return ptr; } static char* ReadBody(char* word, char* ptr, FILE* in, char* &data,char* rejoinders) { // stored data starts with the { char* start = data; ptr = ReadOutput(false,true,ptr,in,data,rejoinders,NULL,NULL); size_t len = strlen(start); if ((len + 3) >= maxBufferSize) BADSCRIPT((char*)"BODY-4 Body exceeding limit of %d bytes\r\n",maxBufferSize) return ptr; } #ifdef INFORMATION An IF consists of: if (test-condition code) xx {body code} yy else (test-condition code) xx {body code} yy else (1) xx {body code} yy spot yy is offset to end of entire if and xx if offset to next branch of if before "else". #endif char* ReadIf(char* word, char* ptr, FILE* in, char* &data,char* rejoinders) { char* bodyends[PATTERNDEPTH]; // places to patch for jumps unsigned int bodyendIndex = 0; char* original = data; strcpy(data,(char*)"^if "); data += 4; if (mapFile && dataBase && !livecall) { fprintf(mapFile, (char*)" if %d %d \r\n", currentFileLine, (int)(data - dataBase)); // readBuffer } patternContext = false; ++complexity; priorLine = currentFileLine; while (ALWAYS) { char* testbase = data; *data++ = 'a'; // reserve space for offset past pattern *data++ = 'a'; // next will be ( *data++ = 'a'; ptr = ReadNextSystemToken(in,ptr,word,false); // the '(' if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } MakeLowerCopy(lowercaseForm,word); if (!*word || TopLevelUnit(word) || TopLevelRule(lowercaseForm) || Rejoinder(lowercaseForm)) BADSCRIPT((char*)"IF-1 Incomplete IF statement - %s\r\n",word) if (*word != '(') BADSCRIPT((char*)"IF-2 Missing (for IF test - %s\r\n",word) *data++ = '('; *data++ = ' '; if (!strnicmp(ptr,(char*)"pattern ",7)) { if (livecall) BADSCRIPT((char*)"Cannot use Pattern If during live compilation\r\n") ptr = ReadNextSystemToken(in,ptr,word,false); // pattern if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } strcpy(data,word); data += strlen(data); *data++ = ' '; char* original = data; patternContext = true; // swallow pattern ptr = ReadPattern(ptr,in,data,false,true); // read ( for real in the paren for pattern if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } patternContext = false; } else { ptr = ReadIfTest(ptr, in, data); // starts by reading the ( and ends having read ) } Encode((unsigned int)(data-testbase),testbase); // offset to after pattern // Encode(xcounter,data,2); //--- format: branch to after pattern, pattern, branch around next pattern, pattern, branch around next pattern or to end of if code char* ifbase = data; *data++ = 'a'; // reserve space for offset after the closing ), which is how far to go past body *data++ = 'a'; *data++ = 'a'; // swallow body of IF after test -- must have { surrounding now ReadNextSystemToken(in,ptr,word,false,true); // { if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (*word != '{') { char hold[MAX_WORD_SIZE]; strcpy(hold,word); ptr = ReadNextSystemToken(in,ptr,word,false,false); ReadNextSystemToken(in,ptr,word,false,true); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (*word != '{') BADSCRIPT((char*)"IF-13 body must start with { instead of %s -- saw pattern %s\r\n",word,readBuffer,original) } ptr = ReadBody(word,ptr,in,data,rejoinders); // comes with space after it bodyends[bodyendIndex++] = data; // jump offset to end of if (backpatched) DummyEncode(data); // reserve space for offset after the closing ), which is how far to go past body *data++ = ' '; Encode((unsigned int)(data-ifbase),ifbase); // offset to ELSE or ELSE IF from body start // now see if ELSE branch exists ReadNextSystemToken(in,ptr,word,false,true); // else? if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (stricmp(word,(char*)"else")) break; // caller will add space after our jump index // there is either else if or else ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow the else if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } strcpy(data,(char*)"else "); data += 5; ReadNextSystemToken(in,ptr,word,false,true); // see if or { if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (mapFile && dataBase && !livecall) { if (!stricmp(word,"if")) fprintf(mapFile, (char*)" elseif %d %d \r\n", currentFileLine, (int)(data - dataBase)); // readBuffer else fprintf(mapFile, (char*)" else %d %d \r\n", currentFileLine, (int)(data - dataBase)); // readBuffer } if (*word == '{') // swallow the ELSE body now since no IF - add fake successful test { // successful test condition for else *data++ = '('; *data++ = ' '; *data++ = '1'; *data++ = ' '; *data++ = ')'; *data++ = ' '; ifbase = data; DummyEncode(data);// reserve skip data *data++ = ' '; ptr = ReadBody(word,ptr,in,data,rejoinders); bodyends[bodyendIndex++] = data; // jump offset to end of if (backpatched) DummyEncode(data);// reserve space for offset after the closing ), which is how far to go past body Encode((unsigned int)(data-ifbase),ifbase); // offset to ELSE or ELSE IF from body start (accelerator) break; } else ++complexity; ptr = ReadNextSystemToken(in,ptr,word,false,false); // eat the IF if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } } if (*(data-1) == ' ') --data; // remove excess blank patternContext = false; if (mapFile && !livecall) { fprintf(mapFile, (char*)" ifend %d %d \r\n", currentFileLine, (int)(data - dataBase)); // readBuffer } // store offsets from successful bodies to the end while (bodyendIndex != 0) { char* at = bodyends[--bodyendIndex]; Encode((unsigned int)(data-at+1),at); // accerators on completion of if to end of whole if } *data = 0; return ptr; // we return with no extra space after us, caller adds it } static char* ReadLoop(char* word, char* ptr, FILE* in, char* &data,char* rejoinders,bool json) { priorLine = currentFileLine; char* original = data; if (json) { strcpy(data, (char*)"^jsonloop "); data += 10; } else { strcpy(data, (char*)"^loop "); data += 6; } if (mapFile && dataBase) { if (json) fprintf(mapFile, (char*)" jsonloop %d %d \r\n", currentFileLine, (int)(data - dataBase)); // readBuffer else fprintf(mapFile, (char*)" loop %d %d \r\n", currentFileLine, (int)(data - dataBase)); // readBuffer } ptr = ReadNextSystemToken(in,ptr,word,false,false); // ( if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } *data++ = '('; *data++ = ' '; if (*word != '(') BADSCRIPT((char*)"LOOP-1 count must be () or (count) -%s\r\n",word) ptr = ReadNextSystemToken(in,ptr,word,false,false); // counter - if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (*word == '^' && IsAlphaUTF8(word[1])) { WORDP D = FindWord(word, 0, LOWERCASE_LOOKUP); if (!D || !(D->internalBits & FUNCTION_NAME)) BADSCRIPT((char*)"%s is not the name of a local function argument\r\n", word) ReadNextSystemToken(in, ptr, nextToken, false, true); ptr = ReadCall(word, ptr, in, data, *nextToken == '(', false); // add function call ptr = ReadNextSystemToken(in, ptr, word, false, false); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } } else if (*word == ')') { if (!json) strcpy(data, (char*)"-1"); // omitted, use -1 else BADSCRIPT("^JSONLOOP missing arguments") } else if (!stricmp(word,(char*)"-1") && !json) // precompiled previously -1 { strcpy(data,word); ptr = ReadNextSystemToken(in,ptr,word,false,false); // read closing paren if (*word != ')') BADSCRIPT((char*)"Loop counter %s was not closed by )\r\n",word); } else if (!json && !IsDigit(*word) && *word != USERVAR_PREFIX && *word != '_' && *word != SYSVAR_PREFIX && *word != '^' && *word != '@') BADSCRIPT((char*)"LOOP-2 counter must be $var, _#, %var, @factset or ^fnarg or function call -%s",word) else { strcpy(data,word); ptr = ReadNextSystemToken(in,ptr,word,false, false); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (json) // 2 more args { data += strlen(data); *data++ = ' '; if (*word != '$' && *word != '_') BADSCRIPT((char*)"LOOP-2 control must be $var or matchvar", word) strcpy(data, word); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } ptr = ReadNextSystemToken(in, ptr, word, false, false); // if (*word != '$' && *word != '_') BADSCRIPT((char*)"LOOP-2 control must be $var or matchvar", word) data += strlen(data); *data++ = ' '; strcpy(data, word); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } ptr = ReadNextSystemToken(in, ptr, word, false, false); } } data += strlen(data); *data++ = ' '; if (*word != ')' && stricmp(word,"new") && stricmp(word,"old")) BADSCRIPT((char*)"LOOP-3 control must end with ) or NEW or OLD -%s\r\n", word) if (!stricmp(word, "new") || !stricmp(word, "old")) { strcpy(data, word); data += 3; *data++ = ' '; } *data++ = ')'; *data++ = ' '; char* loopstart = data; DummyEncode(data); // reserve loop jump to end accelerator *data++ = ' '; // Encode(loopCounter,data,2); // now do body ReadNextSystemToken(in,ptr,word,false,true); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (*word != '{') // does it have precompiled accelerator { char hold[MAX_WORD_SIZE]; strcpy(hold,word); ptr = ReadNextSystemToken(in,ptr,word,false,false); ReadNextSystemToken(in,ptr,word,false,true); if (priorLine != currentFileLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (*word != '{') BADSCRIPT((char*)"LOOP-4 body must start with { -%s\r\n",hold) } char* bodystart = data; ptr = ReadBody(word,ptr,in,data,rejoinders); if (bodystart[0] == '{' && bodystart[1] == ' ' && bodystart[2] == '}') BADSCRIPT((char*)"LOOP-4 body makes no sense being empty\r\n") Encode((unsigned int)(data - loopstart),loopstart); // offset to body end from body start (accelerator) *data = 0; if (mapFile ) { fprintf(mapFile, (char*)" loopend %d %d \r\n", currentFileLine, (int)(data - dataBase)); // readBuffer } return ptr; // caller adds extra space after } static char* ReadJavaScript(FILE* in, char* &data,char* ptr) { strcpy(data,"*JavaScript"); data += strlen(data); *data++ = ' '; strcpy(data,ptr); data += strlen(data); char word[MAX_WORD_SIZE]; while (ReadALine(readBuffer,in) >= 0) { char* comment = strstr(readBuffer,"//"); if (comment) *comment = 0; // erase comments to end of line if (strstr(readBuffer,"/*")) BADSCRIPT("Cannot use /* ... */ comments in CS JavaScript: %s\r\n", readBuffer); char* ptr = SkipWhitespace(readBuffer); if (!*ptr) continue; ReadCompiledWord(ptr,word); if (TopLevelUnit(word) || !stricmp(word,(char*)"datum:")) break; *data++ = ' '; strcpy(data,ptr); data += strlen(data); } return readBuffer; } char* ReadOutput(bool optionalBrace,bool nested,char* ptr, FILE* in,char* &mydata,char* rejoinders,char* supplement,WORDP call, bool choice) { priorLine = currentFileLine; char* originalptr = ptr; char* oldOutputStart = outputStart; // does not matter if script error grabs control dataChunk = mydata; // global visible for use when changing lines for mapping if (!nested) { lineStart = dataChunk; // where line begins outputStart = dataChunk; } char* original = dataChunk; *dataChunk = 0; int bracket = 0; int paren = 0; int squiggle = 0; char* startparen = 0; char* startsquiggle = 0; char* startbracket = 0; int startpline = 0; int startbline = 0; int startsline = 0; char word[MAX_WORD_SIZE * 4]; char assignlhs[MAX_WORD_SIZE]; *assignlhs = 0; *assignKind = 0; int level = 0; int insert = 0; bool oldContext = patternContext; patternContext = false; char hold[MAX_WORD_SIZE]; *hold = 0; char startkind = 0; if (choice) { startkind = '['; ++level; startbracket = ptr; startbline = currentFileLine; } bool start = true; bool needtofield = false; bool javascript = false; while (ALWAYS) // read as many tokens as needed to complete the responder definition { if ((dataChunk-original) >= MAX_JUMP_OFFSET) BADSCRIPT((char*)"OUTPUT-1 code exceeds size limit of %d bytes\r\n",MAX_JUMP_OFFSET) if (*hold) // pending assignment code { if (*hold == '=') { strcpy(word,(char*)"="); memmove(hold,hold+1,strlen(hold)); } else { strcpy(word,hold); *hold = 0; } } else if (supplement && *supplement) { strcpy(word,supplement); supplement = NULL; } else ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; // end of file if (!strcmp(word,"==")) WARNSCRIPT((char*)"== used in output. Did you want assignment = ?\r\n") if (currentFileLine != priorLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } if (start && !stricmp(word,"javascript")) { ptr = ReadJavaScript(in,dataChunk,ptr); javascript = true; break; } if (*word == USERVAR_PREFIX) // jammed together asignment? { char* assign = strchr(word,'='); if (assign) { strcpy(hold,assign); *assign = 0; } } if (insert) --insert; MakeLowerCopy(lowercaseForm,word); if (*word == '#' && word[1] == '!') // special comment { ptr -= strlen(word); // let someone else see this also // safe break; } if (*word == 'a' && word[2] == 0 && (word[1] == ';' || word[1] == '"' || word[1] == '\'' ) ) WARNSCRIPT((char*)"Is %s supposed to be a rejoinder marker?\r\n",word,currentFilename); if ((*word == '}' && level == 0) || TopLevelUnit(word) || TopLevelRule(lowercaseForm) || Rejoinder(lowercaseForm) || !stricmp(word,(char*)"datum:")) // responder definition ends when another major unit or top level responder starts { if (*word != ':') // allow commands here { ptr -= strlen(word); // let someone else see this starter also // safe break; } else if (level >= 1) { if (startkind == '[') BADSCRIPT((char*)"CHOICE-2 Fail to close code started with %s upon seeing %s\r\n", originalptr,word) else BADSCRIPT((char*)"BODY-1 Fail to close code started with %s upon seeing %s\r\n", originalptr,word) } } ReadNextSystemToken(in,ptr,nextToken,false,true); // caching request if (!startkind) startkind = *word; // may be ( or { or [ or other switch(*word) { case '{': ++level; if (!squiggle++) { startsquiggle = ptr; startsline = currentFileLine; } break; case '(': ++level; if (!paren++) { startparen = ptr; startpline = currentFileLine; } break; case '[': startbracket = ptr; startbline = currentFileLine; ptr = ReadChoice(word,ptr,in,dataChunk,rejoinders); // but might have been json array ref continue; case ')': case ']': case '}': if (*word == '}') { --squiggle; if (!squiggle && startkind == '{') // closing level { if (paren) BADSCRIPT((char*)"BODY-3 Fail to close ( on line %d - (%s \r\n",startpline,startparen) if (bracket) BADSCRIPT((char*)"BODY-2 Fail to close [ on line %d - [%s \r\n",startbline,startbracket) } } else if (*word == ')') { --paren; if (!paren && startkind == '(') // closing level { if (squiggle) BADSCRIPT((char*)"BODY-3 Fail to close { on line %d - (%s \r\n",startsline,startsquiggle) if (bracket) BADSCRIPT((char*)"BODY-2 Fail to close [ on line %d - [%s \r\n",startbline,startbracket) } } else if (*word == ']') { --bracket; if (!bracket && startkind == '[') // closing level { if (squiggle) BADSCRIPT((char*)"BODY-3 Fail to close { on line %d - (%s \r\n",startsline,startsquiggle) if (paren) BADSCRIPT((char*)"BODY-2 Fail to close ( on line %d - [%s \r\n",startpline,startparen) } } --level; *dataChunk = 0; if (level < 0) BADSCRIPT((char*)"OUTPUT-3 Unbalanced %s in %s\r\n", word, outputStart) else if (!level && (startkind == '(' || startkind == '{' || startkind == '[')) { strcpy(dataChunk,word); dataChunk += strlen(dataChunk); *word = 0; // end loop } break; case '\'': strcpy(dataChunk,word); dataChunk += strlen(dataChunk); if (*word == '\'' && word[1] == 's' && !word[2] && IsAlphaUTF8OrDigit(*nextToken) ) *dataChunk++ = ' '; else if (word[1] == 0 && (*ptr == '_' || IsAlphaUTF8(*ptr) )) {;} // if isolated like join(' _1) then add space else *dataChunk++ = ' '; continue; case '@': // factset ref if (!IsDigit(word[1])) BADSCRIPT((char*)"OUTPUT-4 bad factset reference - %s\r\n",word) if (!stricmp(nextToken,(char*)"+=") || !stricmp(nextToken,(char*)"-=") ) insert = 2; break; } if (!*word) break; // end of body if (!stricmp("$cs_botid", assignlhs) && IsDigit(word[0])) { // bot id declaration macroid = atoi64(word); } if (*assignlhs) // during continued assignment? { if (!stricmp(word,(char*)"^") || !stricmp(word,(char*)"|") || !stricmp(word,(char*)"&") || (!stricmp(word,(char*)"+") || !stricmp(word,(char*)"-") || !stricmp(word,(char*)"*") || !stricmp(word,(char*)"/"))) { if (!stricmp(nextToken,assignlhs)) { WARNSCRIPT((char*)"Possibly faulty assignment. %s has changed value during prior assignment.\r\n",assignlhs) *assignlhs = 0; } } else if (!stricmp(nextToken,(char*)"^") || !stricmp(nextToken,(char*)"|") || !stricmp(nextToken,(char*)"&") || !stricmp(nextToken,(char*)"+") || !stricmp(nextToken,(char*)"-") || !stricmp(nextToken,(char*)"*") || !stricmp(nextToken,(char*)"/")) {} else *assignlhs = 0; } char* nakedNext = nextToken; if (*nakedNext == '^') ++nakedNext; // word w/o ^ char* nakedWord = word; if (*nakedWord == '^') ++nakedWord; // word w/o ^ if (*word == '^') { if (!stricmp(word,"^if") || !stricmp(word,"^loop") || !stricmp(word, "^jsonloop")) {;} else if (*nextToken != '(' && word[1] != '^' && word[1] != '=' && word[1] != USERVAR_PREFIX && word[1] != '_' && word[1] != '"' && word[1] != '\'' && !IsDigit(word[1])) BADSCRIPT((char*)"%s either references a function w/o arguments or names a function variable that doesn't exist\r\n",word) } // note left hand of assignment if (IsComparator(nextToken)) strcpy(assignlhs,word); if (*nextToken == '=' && !nextToken[1]) // simple assignment { *assignKind = 0; strcpy(dataChunk,word); // add simple item into data dataChunk += strlen(dataChunk); *dataChunk++ = ' '; ptr = ReadNextSystemToken(in,ptr,nextToken,false,false); // use up lookahead of = strcpy(dataChunk,(char*)"="); ++dataChunk; *dataChunk++ = ' '; ReadNextSystemToken(in,ptr,nextToken,false,true); // aim lookahead at followup if (!stricmp(nakedNext,(char*)"first") || !stricmp(nakedNext,(char*)"last") || !stricmp(nakedNext,(char*)"random") || !stricmp(nakedNext,(char*)"nth") ) strcpy(assignKind,word); // verify usage fact retrieved from set if (*nextToken == '=' || *nextToken == '<' || *nextToken == '>') { if (!IsAlphaUTF8(nextToken[1])) WARNSCRIPT((char*)"Possibly assignment followed by another binary operator") } // assigning to variable only works if tofield value is given if (*word == USERVAR_PREFIX && (!stricmp(nextToken,"^query") || !stricmp(nextToken,"query"))) needtofield = true; continue; } else if (*nextToken == '{' && !stricmp(nakedWord,(char*)"loop")) // loop missing () { ptr = ReadLoop(word,ptr,in,dataChunk,rejoinders,false); continue; } else if (*nextToken == '{' && !stricmp(nakedWord, (char*)"jsonloop")) // loop missing () { ptr = ReadLoop(word, ptr, in, dataChunk, rejoinders,true); continue; } else if (*nextToken != '(') // doesnt look like a function { } else if (!stricmp(nakedWord,(char*)"if")) // strip IF of ^ { ptr = ReadIf(word,ptr,in,dataChunk,rejoinders); *dataChunk++ = ' '; continue; } else if (!stricmp(nakedWord,(char*)"loop")) // strip LOOP of ^ { ptr = ReadLoop(word,ptr,in,dataChunk,rejoinders,false); continue; } else if (!stricmp(nakedWord, (char*)"jsonloop")) // strip LOOP of ^ { ptr = ReadLoop(word, ptr, in, dataChunk, rejoinders,true); continue; } else if (*word != '^' && (!call || stricmp(call->word,(char*)"^createfact"))) // looks like a call ... if its ALSO a normal word, presume it is not a call, like: I like (American) football { // be wary.. respond(foo) might have been text... // How does he TELL us its text? interpret normal word SPACE ( as not a function call? char rename[MAX_WORD_SIZE]; *rename = '^'; strcpy(rename+1,word); // in case user omitted the ^ MakeLowerCase(rename); WORDP D = FindWord(rename,0,PRIMARY_CASE_ALLOWED); if (D && D->internalBits & FUNCTION_NAME) // it is a function { // is it also english. If builtin function, do that for sure // if user function AND english, more problematic. maybe he forgot WORDP E = FindWord(word); if (!E || !(E->properties & PART_OF_SPEECH) || D->x.codeIndex) strcpy(word,rename); // a recognized call else if (*ptr == '(') strcpy(word,rename); // use his spacing to decide } } if (currentFileLine != priorLine) { AddMapOutput(priorLine); priorLine = currentFileLine; } // a function call, if (*word == '^' && !IsDigit(word[1]) && word[1] != '^'&& word[1] != '=' && word[1] != '"' && word[1] != '\'' && word[1] != USERVAR_PREFIX && word[1] != '_' && word[1] && *nextToken == '(' ) { ptr = ReadCall(word,ptr,in,dataChunk,*nextToken == '(',needtofield); // add function call needtofield = false; *assignKind = 0; } else if (*word == '^' && IsDigit(word[1]) ) // fn var { strcpy(dataChunk,word); // add simple item into data dataChunk += strlen(dataChunk); } else { if (*word == '~' ) CheckSetOrTopic(word); if (IsAlphaUTF8(*word) && spellCheck == OUTPUT_SPELL) SpellCheckScriptWord(word,-1,true); strcpy(dataChunk,word); // add simple item into data dataChunk += strlen(dataChunk); } *dataChunk++ = ' '; } while (*(dataChunk-1) == ' ') *--dataChunk = 0; *dataChunk++ = ' '; *dataChunk = 0; // now verify no choice block exceeds CHOICE_LIMIT and that each [ is closed with ] if (!javascript) while (*original) { original = ReadCompiledWord(original,word); if (*original != '[') continue; unsigned int count = 0; char* at = original; while (*at == '[') { // find the closing ] while (ALWAYS) { at = strchr(at+1,']'); // find closing ] - we MUST find it (check in initsql) if (!at) BADSCRIPT((char*)"OUTPUT-5 Failure to close [ choice\r\n") if (*(at-2) != '\\') break; // found if not a literal \[ } ++count; at += 2; // at next token } if (count >= (CHOICE_LIMIT - 1)) BADSCRIPT((char*)"OUTPUT-6 Max %d choices in a row\r\n",CHOICE_LIMIT) original = at; } patternContext = oldContext; outputStart = oldOutputStart; mydata = dataChunk; return ptr; } static void ReadTopLevelRule(WORDP topicName, char* typeval,char* &ptr, FILE* in,char* data,char* basedata) {// handles 1 responder/gambit + all rejoinders attached to it char type[100]; complexity = 1; strcpy(type,typeval); char info[400]; char kind[MAX_WORD_SIZE]; char tname[MAX_WORD_SIZE]; strcpy(tname, topicName->word); char* tilde = strchr(tname + 1, '~'); if (tilde) *tilde = 0; // remove dup index strcpy(kind,type); char word[MAX_WORD_SIZE]; char rejoinders[256]; // legal levels a: thru q: memset(rejoinders,0,sizeof(rejoinders)); WriteVerify(); // dump any accumulated verification data before the rule // rejoinders == 1 is normal, 2 means authorized in [] 3 means authorized and used *rejoinders = 1; // we know we have a responder. we will see about rejoinders later while (ALWAYS) // read responser + all rejoinders { MakeLowerCase(kind); char* original = data; int level = 0; // validate rejoinder is acceptable if (Rejoinder(kind)) { complexity = 1; int count = level = *kind - 'a' + 1; // 1 ... if (rejoinders[level] >= 2) rejoinders[level] = 3; // authorized by [b:] and now used else if (!rejoinders[level-1]) BADSCRIPT((char*)"RULE-1 Illegal rejoinder level %s\r\n",kind) else rejoinders[level] = 1; // we are now at this level, enables next level // levels not authorized by [b:][g:] etc are disabled while (++count < 20) { if (rejoinders[count] == 1) rejoinders[count] = 0; } currentRuleID += ONE_REJOINDER; WriteVerify(); } strcpy(data,kind); data += 2; *data++ = ' '; bool patternDone = false; #ifdef INFORMATION A responder of any kind consists of a prefix of `xx spot xx is an encoded jump offset to go the the end of the responder. Then it has the kind item (t: s: etc). Then a space. Then one of 3 kinds of character: a. a (- indicates start of a pattern b. a space - indicates no pattern exists c. a 1-byte letter jump code - indicates immediately followed by a label and the jump code takes you to the ( #endif char label[MAX_WORD_SIZE]; char labelName[MAX_WORD_SIZE]; *label = 0; *labelName = 0; while (ALWAYS) // read as many tokens as needed to complete the responder definition { ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; MakeLowerCopy(lowercaseForm,word); size_t len = strlen(word); if (TopLevelUnit(word) || TopLevelRule(lowercaseForm) || !stricmp(word,(char*)"datum:")) { *word = 0; break;// responder definition ends when another major unit or top level responder starts } if (*word == '(') // found pattern, no label { sprintf(info," rule: %s.%d.%d %s",currentTopicName,TOPLEVELID(currentRuleID),REJOINDERID(currentRuleID),kind); AddMap(info,NULL); // rule ptr = ReadPattern(ptr-1,in,data,false,false); // back up and pass in the paren for pattern patternDone = true; *word = 0; break; } else // label or start of output { ReadNextSystemToken(in,ptr,nextToken,false,true); // peek what comes after if (*nextToken == '(' && (IsAlphaUTF8(*word) ||IsDigit(*word))) // label exists { if (!IsLegalName(word,true)) BADSCRIPT((char*)"? Illegal characters in rule label %s\r\n", word) char name[MAX_WORD_SIZE]; *name = '^'; strcpy(name+1,word); WORDP D = FindWord(name,0,LOWERCASE_LOOKUP); if (D && D->internalBits & FUNCTION_NAME && (*kind == GAMBIT || *kind == RANDOM_GAMBIT)) WARNSCRIPT((char*)"label: %s is a potential macro in %s. Add ^ if you want it treated as such.\r\n",word,currentFilename) else if (!stricmp(word,(char*)"if") || !stricmp(word,(char*)"loop") || !stricmp(word, (char*)"jsonloop")) WARNSCRIPT((char*)"label: %s is a potential flow control (if/loop/jsonloop) in %s. Add ^ if you want it treated as a control word.\r\n",word,currentFilename) sprintf(info," rule: %s.%d.%d-%s %s",currentTopicName,TOPLEVELID(currentRuleID),REJOINDERID(currentRuleID),name+1, kind); AddMap(info,NULL); // rule char* bots = topicName->w.topicBots; if (!bots || !*bots) { bots = "*"; // general access } while (*bots) { char bot[MAX_WORD_SIZE]; bots = ReadCompiledWord(bots, bot); if (!*bot) break; sprintf(label, "%s.%s-%s", tname, word, bot ); MakeUpperCase(label); WORDP E = StoreWord(label, AS_IS); AddInternalFlag(E, LABEL); } MakeUpperCase(word); strcpy(labelName,word); if (strchr(word,'.')) BADSCRIPT((char*)"RULE-2 Label %s must not contain a period\r\n",word) if (len > 160) BADSCRIPT((char*)"RULE-2 Label %s must be less than 160 characters\r\n",word) int fulllen = len; if (len > 40) { int tens = len / 40; // how many 40s does it hold len -= (tens * 40); *data++ = (char) (tens + '*'); // detectable as a 2char label *data++ = (char)('0' + len + 2); // prefix attached to label } else *data++ = (char)('0' + len + 2); // prefix attached to label strcpy(data,word); data += fulllen; *data++ = ' '; ReadNextSystemToken(NULL,NULL,NULL); // drop lookahead token ptr = ReadPattern(ptr,in,data,false,false); // read ( for real in the paren for pattern patternDone = true; *word = 0; } else // we were seeing start of output (no label and no pattern) for gambit, proceed to output { sprintf(info," rule: %s.%d.%d-%s %s",currentTopicName,TOPLEVELID(currentRuleID),REJOINDERID(currentRuleID),labelName,kind); AddMap(info,NULL); // rule if (*type != GAMBIT && *type != RANDOM_GAMBIT) BADSCRIPT((char*)"RULE-3 Missing pattern for responder\r\n") *data++ = ' '; patternDone = true; // leave word intact to pass to readoutput } break; } } // END OF WHILE if (patternDone) { dataBase = data; ptr = ReadOutput(false,false,ptr,in,data,rejoinders,word,NULL); dataBase = NULL; char complex[MAX_WORD_SIZE]; sprintf(complex," Complexity of rule %s.%d.%d-%s %s %d", currentTopicName,TOPLEVELID(currentRuleID),REJOINDERID(currentRuleID),labelName,kind,complexity); AddMap(NULL, complex); // complexity // data points AFTER last char added. Back up to last char, if blank, leave it to be removed. else restore it. while (*--data == ' '); *++data = ' '; strcpy(data+1,ENDUNITTEXT); // close out last topic item+ data += strlen(data); while (ALWAYS) // read all verification comments for next rule if any, getting the next real word token { ptr = ReadNextSystemToken(in,ptr,word,false); if (*word != '#' || word[1] != '!') break; ptr = AddVerify(word,ptr); } MakeLowerCopy(lowercaseForm,word); if (!*word || TopLevelUnit(word) || TopLevelRule(lowercaseForm) || !stricmp(word,(char*)"datum:")) { ptr -= strlen(word); // safe break;// responder definition ends when another major unit or top level responder starts } // word is a rejoinder type strcpy(kind,lowercaseForm); } else ReportBug((char*)"unexpected word in ReadTopLevelRule - %s",word) } // did he forget to fill in any [] jumps for (unsigned int i = ('a'-'a'); i <= ('q'-'a'); ++i) { if (rejoinders[i] == 2) BADSCRIPT((char*)"RULE-4 Failed to define rejoinder %c: for responder just ended\r\n", i + 'a' - 1) } *data = 0; dataBase = NULL; } static char* ReadMacro(char* ptr,FILE* in,char* kind,unsigned int build) { bool table = !stricmp(kind,(char*)"table:"); // create as a transient notwrittentofile *currentTopicName = 0; displayIndex = 0; complexity = 1; uint64 typeFlags = 0; if (!stricmp(kind,(char*)"tableMacro:") || table) typeFlags = IS_TABLE_MACRO; else if (!stricmp(kind,(char*)"outputMacro:")) typeFlags = IS_OUTPUT_MACRO; else if (!stricmp(kind,(char*)"patternMacro:")) typeFlags = IS_PATTERN_MACRO; else if (!stricmp(kind,(char*)"dualMacro:")) typeFlags = IS_PATTERN_MACRO | IS_OUTPUT_MACRO; *macroName = 0; macroid = 0; functionArgumentCount = 0; char* data = AllocateBuffer(); char* d = AllocateBuffer(); char* revised = AllocateBuffer(); char* pack = data; int64 macroFlags = 0; int parenLevel = 0; WORDP D = NULL; bool gettingArguments = true; patternContext = false; char word[MAX_WORD_SIZE]; while (gettingArguments) // read as many tokens as needed to get the name and argumentList { ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; // end of file if (!*macroName) // get the macro name { if (*word == '^' || *word == '~') memmove(word,word+1,strlen(word)); // remove his ^ MakeLowerCase(word); if (!table && !IsAlphaUTF8(*word) ) BADSCRIPT((char*)"MACRO-1 Macro name must start alpha %s\r\n",word) if (table) { strcpy(macroName,(char*)"^tbl:"); strcat(macroName,word); Log(STDUSERLOG,(char*)"Reading table %s\r\n",macroName); } else { if (!IsLegalName(word)) BADSCRIPT((char*)"MACRO-2 Illegal characters in function name %s\r\n",word) *macroName = '^'; strcpy(macroName+1,word); Log(STDUSERLOG,(char*)"Reading %s %s\r\n",kind,macroName); AddMap((char*)" macro:", macroName); } D = StoreWord(macroName); if (D->w.fndefinition && D->internalBits & FUNCTION_NAME && !table) // must be different BOT ID { int64 bid; ReadInt64((char*)GetDefinition(D),bid); // have to allow multiple instances of boot bot if (bid == (int64)myBot && stricmp(D->word,"^csboot")) BADSCRIPT((char*)"MACRO-3 macro %s already defined\r\n",macroName) } continue; } if (parenLevel == 0 && !stricmp(word,(char*)"variable")) // putting "variable" before the args list paren allows you to NAME all args but get ones not supplied filled in with * (tables) or null (macros) { D->internalBits |= VARIABLE_ARGS_TABLE; continue; } if (parenLevel == 0 && !stricmp(word, (char*)"tab")) { D->internalBits |= TABBED; continue; } size_t len = strlen(word); if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= len; // let someone else see this starter also break; } char* restrict = NULL; switch(*word) { case '(': if (parenLevel++ != 0) BADSCRIPT((char*)"MACRO-4 bad paren level in macro definition %s\r\n",macroName) continue; // callArgumentList open case ')': if (--parenLevel != 0) BADSCRIPT((char*)"MACRO-5 bad closing paren in macro definition %s\r\n",macroName) gettingArguments = false; break; case '$': // declaring local restrict = strchr(word, '.'); if (restrict) { if (!stricmp(restrict + 1, (char*)"KEEP_QUOTES") && (typeFlags == IS_TABLE_MACRO || typeFlags == IS_OUTPUT_MACRO)) macroFlags |= 1ull << functionArgumentCount; // a normal string where spaces are kept instead of _ (format string) else if (!stricmp(restrict + 1, (char*)"HANDLE_QUOTES")) { if (typeFlags != IS_OUTPUT_MACRO) BADSCRIPT((char*)"MACRO-? HANDLE_QUOTES only valid with OUTPUTMACRO or DUALMACRO - %s \r\n", word) if (functionArgumentCount > 15) { int64 flag = 1ull << (functionArgumentCount - 16); // outputmacros flag <<= 32; macroFlags |= flag; } else macroFlags |= 1ull << functionArgumentCount; // outputmacros } else if (!stricmp(restrict + 1, (char*)"COMPILE") && typeFlags == IS_TABLE_MACRO) { if (functionArgumentCount > 15) { int64 flag = (1ull << 16) << (functionArgumentCount - 16); // outputmacros flag <<= 32; macroFlags |= flag; } else macroFlags |= (1ull << 16) << functionArgumentCount; // a compile string " " becomes "^:" } else if (!stricmp(restrict + 1, (char*)"UNDERSCORE") && typeFlags == IS_TABLE_MACRO) { ; } // default for quoted strings is _ else if (typeFlags != IS_TABLE_MACRO && typeFlags != IS_OUTPUT_MACRO) BADSCRIPT((char*)"Argument restrictions only available on Table Macros or OutputMacros - %s \r\n", word) else BADSCRIPT((char*)"MACRO-? Table/Tablemacro argument restriction must be KEEP_QUOTES OR COMPILE or UNDERSCORE - %s \r\n", word) *restrict = 0; } if (typeFlags & IS_PATTERN_MACRO) BADSCRIPT((char*)"MACRO-? May not use locals in a pattern/dual macro - %s\r\n",word) if (word[1] != '_') BADSCRIPT((char*)"MACRO-? Variable name as argument must be local %s\r\n",word) if (strchr(word, '.') || strchr(word, '[')) { BADSCRIPT((char*)"MACRO-? Variable name as argument must be simple, not json reference %s\r\n", word) } AddDisplay(word); strcpy(functionArguments[functionArgumentCount++],word); if (functionArgumentCount > MAX_ARG_LIMIT) BADSCRIPT((char*)"MACRO-7 Too many callArgumentList to %s - max is %d\r\n",macroName,MAX_ARG_LIMIT) continue; case '^': // declaring a new argument if (IsDigit(word[1])) BADSCRIPT((char*)"MACRO-6 Function arguments must be alpha names, not digits like %s\r\n",word) restrict = strchr(word,'.'); if (restrict) { if (!stricmp(restrict+1,(char*)"KEEP_QUOTES") && (typeFlags == IS_TABLE_MACRO || typeFlags == IS_OUTPUT_MACRO)) macroFlags |= 1ull << functionArgumentCount; // a normal string where spaces are kept instead of _ (format string) else if (!stricmp(restrict+1,(char*)"HANDLE_QUOTES")) { if (typeFlags != IS_OUTPUT_MACRO) BADSCRIPT((char*)"MACRO-? HANDLE_QUOTES only valid with OUTPUTMACRO or DUALMACRO - %s \r\n",word) if (functionArgumentCount > 15) { int64 flag = 1ull << (functionArgumentCount - 16); // outputmacros flag <<= 32; macroFlags |= flag; } else macroFlags |= 1ull << functionArgumentCount; // outputmacros } else if (!stricmp(restrict+1,(char*)"COMPILE") && typeFlags == IS_TABLE_MACRO) { if (functionArgumentCount > 15) { int64 flag = (1ull << 16) << (functionArgumentCount - 16); // outputmacros flag <<= 32; macroFlags |= flag; } else macroFlags |= (11ull << 16) << functionArgumentCount; // a compile string " " becomes "^:" } else if (!stricmp(restrict+1,(char*)"UNDERSCORE") && typeFlags == IS_TABLE_MACRO) {;} // default for quoted strings is _ else if (typeFlags != IS_TABLE_MACRO && typeFlags != IS_OUTPUT_MACRO) BADSCRIPT((char*)"Argument restrictions only available on Table Macros or OutputMacros - %s \r\n",word) else BADSCRIPT((char*)"MACRO-? Table/Tablemacro argument restriction must be KEEP_QUOTES OR COMPILE or UNDERSCORE - %s \r\n",word) *restrict = 0; } else {}// default for quoted strings on argumet is UNDERSCORE { WORDP X = FindWord(word); if (X && X->internalBits & FUNCTION_NAME) BADSCRIPT((char*)"MACRO-8 Function argument %s is also name of a function\r\n",word); } AddDisplay(word); strcpy(functionArguments[functionArgumentCount++],word); if (functionArgumentCount > MAX_ARG_LIMIT) BADSCRIPT((char*)"MACRO-7 Too many callArgumentList to %s - max is %d\r\n",macroName,MAX_ARG_LIMIT) continue; default: BADSCRIPT((char*)"MACRO-7 Bad argument %s to macro definition %s\r\n",word,macroName) } } if (!D) { dataBase = NULL; return ptr; // nothing defined } if (functionArgumentCount > ARGSETLIMIT) BADSCRIPT((char*)"MACRO-7 Argument count to macro definition %s limited to %d\r\n",macroName,ARGSETLIMIT) AddInternalFlag(D,(unsigned int)(FUNCTION_NAME|build|typeFlags)); if (functionArgumentCount > 15) *pack++ = (unsigned char)(functionArgumentCount - 15 + 'a'); else *pack++ = (unsigned char)(functionArgumentCount + 'A'); // some 10 can be had ^0..^9 bool optionalBrace = false; currentFunctionDefinition = D; dataBase = NULL; if ( (typeFlags & FUNCTION_BITS) == IS_PATTERN_MACRO) { char* at = d; ptr = ReadPattern(ptr,in,at,true,false); *at = 0; // insert display and add body back pack = WriteDisplay(pack); strcpy(pack,d); pack += at - d; } else { ReadNextSystemToken(in,ptr,word,false,true); // check for optional display variables if (*word == '(') { ptr = ReadDisplay(in,ptr); ReadNextSystemToken(in,ptr,word,false,true); } if (*word == '{') // see if he used optional { syntax { ReadNextSystemToken(in,ptr,word,false); optionalBrace = true; } dataBase = d; if ((typeFlags & FUNCTION_BITS) == IS_PATTERN_MACRO) dataBase = NULL; // now read body of macro char* at = d; // if on same line we have issue? ptr = ReadOutput(optionalBrace,false,ptr,in,at,NULL,NULL,NULL); ReadNextSystemToken(in,ptr,word,true); if (optionalBrace && *word == '}') ptr = ReadNextSystemToken(in,ptr,word,false); else if (optionalBrace) BADSCRIPT("Missing closing optional brace in reading macro %s\r\n", macroName) *at = 0; // insert display and add body back pack = WriteDisplay(pack); strcpy(pack,d); pack += at - d; } *pack++ = '`'; // add closing marker to script *pack = 0; // record that it is a macro, with appropriate validation information char botid[MAX_WORD_SIZE]; #ifdef WIN32 sprintf(botid, (char*)"%I64u", (int64)myBot); #else sprintf(botid, (char*)"%llu", (int64)myBot); #endif revised[0] = revised[1] = revised[2] = revised[3] = 0; revised += 4; #ifdef WIN32 sprintf(revised, (char*)"%s %I64d ", botid, macroFlags); #else sprintf(revised, (char*)"%s %lld ", botid, macroFlags); #endif strcat(revised, data); size_t len = strlen(revised) + 4; if (table && D->w.fndefinition) // need to link old definition to new one { unsigned int heapIndex = Heap2Index((char*)D->w.fndefinition); revised[0] = (heapIndex >> 24) & 0xff; revised[1] = (heapIndex >> 16) & 0xff; revised[2] = (heapIndex >> 8) & 0xff; revised[3] = heapIndex & 0xff; } D->w.fndefinition = (unsigned char*)AllocateHeap(revised - 4, strlen(revised) + 4); if (!table) // tables are not real macros, they are temporary { char filename[SMALL_WORD_SIZE]; sprintf(filename,(char*)"%s/BUILD%s/macros%s.txt",topic,baseName,baseName); // write out definition -- this is the real save of the data FILE* out = FopenUTF8WriteAppend(filename); if ((D->internalBits & FUNCTION_BITS) == IS_TABLE_MACRO) fprintf(out,(char*)"%s t %s\r\n",macroName,GetDefinition(D)); else if ((D->internalBits & FUNCTION_BITS) == (IS_OUTPUT_MACRO|IS_PATTERN_MACRO)) fprintf(out,(char*)"%s d %s\r\n",macroName,GetDefinition(D)); else fprintf(out,(char*)"%s %c %s\r\n",macroName,((D->internalBits & FUNCTION_BITS) == IS_OUTPUT_MACRO) ? 'o' : 'p',GetDefinition(D)); fclose(out); // dont use Fclose char complex[MAX_WORD_SIZE]; sprintf(complex, " Complexity of %s: %d", macroName, complexity); AddMap(NULL, complex); // complexity if (macroid != 0) { char name[MAX_WORD_SIZE]; #ifdef WIN32 sprintf(name, (char*)" bot: 0 %s %I64u ", macroName,macroid); #else sprintf(name, (char*)" bot: 0 %s %llu ", macroName,macroid); #endif AddMap(NULL, name); // bot macro } } *macroName = 0; dataBase = NULL; FreeBuffer(); FreeBuffer(); FreeBuffer(); return ptr; } static char* ReadTable(char* ptr, FILE* in,unsigned int build,bool fromtopic) { bool oldecho = echo; int oldtrace = trace; char name[MAX_WORD_SIZE]; char word[MAX_WORD_SIZE]; char post[MAX_WORD_SIZE]; char args[MAX_TABLE_ARGS+1][MAX_WORD_SIZE]; unsigned short quoteProcessing = 0; unsigned int indexArg = 0; char* pre = NULL; ptr = SkipWhitespace(ptr); ReadNextSystemToken(in,ptr,name,false,true); if (*name == '~') { *name = '^'; char* at = strchr(ptr, '~'); *at = '^'; } else if (*name != '^') // add function marker if it lacks one { memmove(name+1,name,strlen(name)+1); *name = '^'; } currentFunctionDefinition = FindWord(name); unsigned int sharedArgs; bool tableMacro = false; if (!currentFunctionDefinition) // go define a temporary tablemacro function since this is a spontaneous table Table: { if (fromtopic) BADSCRIPT((char*)"datum: from topic must use predefined table %s",name) ptr = ReadMacro(ptr,in,(char*)"table:",build); // defines the name,argumentList, and script ptr = ReadNextSystemToken(in,ptr,word,false,false); // the DATA: separator if (stricmp(word,(char*)"DATA:")) BADSCRIPT((char*)"TABLE-1 missing DATA: separator for table - %s\r\n",word) sharedArgs = 0; } else // this is an existing table macro being executed { tableMacro = true; ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow function name ptr = ReadNextSystemToken(in,ptr,word,false,false); // swallow ( if (*word != '(') BADSCRIPT((char*)"TABLE-2 Must have ( before arguments") while (ALWAYS) // read argument values we supply to the existing tablemacro { ptr = ReadNextSystemToken(in,ptr,args[indexArg],false,false); if (*args[indexArg] == ')') break; if (*args[indexArg] == '^' && args[indexArg][1] != '"') BADSCRIPT((char*)"TABLE-3 TableMacro %s requires real args, not redefinition args",currentFunctionDefinition->word) if (++indexArg >= MAX_TABLE_ARGS) BADSCRIPT((char*)"TABLE-4 too many table args\r\n") } sharedArgs = indexArg; } unsigned char* defn = GetDefinition(currentFunctionDefinition); unsigned int wantedArgs = MACRO_ARGUMENT_COUNT(defn); char junk[MAX_WORD_SIZE]; defn = (unsigned char*) ReadCompiledWord((char*)defn, junk); // read bot id int flags; ReadInt((char*)defn, flags); quoteProcessing = (short int) flags; // values of KEEP_QUOTES for each argument // now we have the function definition and any shared arguments. We need to read the real arguments per table line now and execute. convertTabs = (currentFunctionDefinition->internalBits & TABBED) ? false : true; char* argumentList = AllocateBuffer(); tableinput = NULL; ++jumpIndex; int holdDepth = globalDepth; char* xxbase = ptr; // debug hook tableinput = AllocateBuffer(); while (ALWAYS) { if (setjmp(scriptJump[jumpIndex])) // flush on error { ptr = FlushToTopLevel(in,holdDepth,0); break; } ptr = ReadNextSystemToken(in,ptr,word,false,false); // real token read char* original = ptr - strlen(word); if (*word == '\\' && word[1] == 'n') continue; // newline means pretend new table entry if (*word == ':' && word[1]) // debug command { ptr = original; // safe char output[MAX_WORD_SIZE]; DoCommand(ptr,output); *ptr = 0; continue; } if (!*word || TopLevelUnit(word) || TopLevelRule(word)) // end { ptr = original; // safe break; } // process a data set from the line char* systemArgumentList = argumentList; *systemArgumentList++ = '('; *systemArgumentList++ = ' '; unsigned int argCount = 0; // common arguments processing for (unsigned int i = 0; i < sharedArgs; ++i) { if (*args[i] == '^' && args[i][1] == '"') { FunctionResult result; char* oldoutputbase = currentOutputBase; currentOutputBase = systemArgumentList; ReformatString(args[i][1],args[i]+2,systemArgumentList,result); currentOutputBase = oldoutputbase; } else strcpy(systemArgumentList,args[i]); systemArgumentList += strlen(systemArgumentList); *systemArgumentList++ = ' '; ++argCount; } // now fill in args of table data from a single line char* choiceArg = NULL; // the multiple interior bool startup = true; trace = 0; strcpy(tableinput, readBuffer); while (ALWAYS) { if (!startup) ptr = ReadSystemToken(ptr,word); // next item to associate if (!stricmp(word,(char*)":debug")) { DebugCode(word); continue; } startup = false; if (!*word) break; // end of LINE of items stuff if (*word == '\t') *word = '*'; // tab forces fill with * if (!stricmp(word,(char*)"...")) break; // pad to end of arg count if (!stricmp(word,(char*)"\\n")) // fake end of line { memmove(readBuffer,ptr,strlen(ptr)+1); // erase earlier stuff we've read ptr = readBuffer; break; } if (*word == '[' ) // choice set (one per line allowed) { if (choiceArg) BADSCRIPT((char*)"TABLE-5 Only allowed 1 multiple choice [] arg\r\n") pre = systemArgumentList; // these are the fixed arguments before the multiple choice one choiceArg = ptr; // multiple choices arg char* at = strchr(ptr,']'); // find end of multiple choice if (!at) BADSCRIPT((char*)"TABLE-6 bad [ ] ending %s in table %s\r\n",readBuffer,currentFunctionDefinition->word) ptr = at + 1; // continue fixed argumentList AFTER the multiple choices set (but leave blank if there) ++argCount; continue; // skipping over this arg, move on to next arg now. } uint64 flag = 0; // how do we store string arguments - with underscores, as is, compiled, bool keepQuotes = (quoteProcessing & ( 1 << argCount)) ? 1 : 0; // want to use quotes and spaces, instead of none and convert to _ which is the default // a normal string where spaces are kept instead of _ (format string) bool xxotherNotation = (quoteProcessing & ( (1 << 16) << argCount)) ? 1 : 0; // unused at present if (*word == FUNCTIONSTRING && (word[1] == '"' || word[1] == '\'')) { strcpy(word,CompileString(word)); // no underscores in string, compiled as executable // a compile string " " becomes "^:" flag = AS_IS; } else if (*word == '"' && keepQuotes) // no underscores in string, preserve string. Quotes needed to detect as single argument for fact creation { flag = AS_IS; } else { unsigned int n = BurstWord(word,(*word == '"') ? POSSESSIVES : 0); strcpy(word,JoinWords(n)); // by default strings are stored with _, pretending they are composite words. if (n > 1) flag = AS_IS; } if ( *word == '\\') memmove(word,word+1,strlen(word)); // remove escape if (*word == '"' && !word[1]) BADSCRIPT((char*)"TABLE-? isolated doublequote argument- start of string not recognized?\r\n"); if (flag != AS_IS && *word != '"' && strstr(word,(char*)" ")) BADSCRIPT((char*)"TABLE-7 unexpected space in string %s - need to use doublequotes around string\r\n",word); WORDP baseWord = StoreWord(word,flag); strcpy(word,baseWord->word); strcpy(systemArgumentList,word); systemArgumentList += strlen(systemArgumentList); *systemArgumentList++ = ' '; ++argCount; // handle synonyms as needed MEANING base = MakeMeaning(baseWord); if (convertTabs) ptr = SkipWhitespace(ptr); if (*ptr == '(' && ++ptr) while (ALWAYS) // synonym listed, create a fact for it { ptr = ReadSystemToken(ptr,word); if (!*word || *word == '[' || *word == ']') BADSCRIPT((char*)"TABLE-8 Synomym in table %s lacks token\r\n",currentFunctionDefinition->word) if (*word == ')') break; // end of synonms strcpy(word,JoinWords(BurstWord(word,CONTRACTIONS))); if (IsUpperCase(*word)) CreateFact(MakeMeaning(StoreWord(word,NOUN|NOUN_PROPER_SINGULAR)),Mmember,base); else CreateFact(MakeMeaning(StoreWord(word,NOUN|NOUN_SINGULAR)),Mmember,base); } if ((wantedArgs - sharedArgs) == 1) { memmove(readBuffer,ptr,strlen(ptr)+1); ptr = readBuffer; break; } } while ( argCount < wantedArgs && (!stricmp(word,(char*)"...") || currentFunctionDefinition->internalBits & VARIABLE_ARGS_TABLE)) { strcpy(systemArgumentList,(char*)"*"); systemArgumentList += strlen(systemArgumentList); *systemArgumentList++ = ' '; ++argCount; } *systemArgumentList = 0; *post = 0; if (choiceArg) strcpy(post,pre); // save argumentList after the multiple choices // now we have one map of the argumentList row if (argCount && argCount != wantedArgs) BADSCRIPT((char*)"TABLE-9 Bad table %s in table %s, want %d arguments and have %d\r\n",original,currentFunctionDefinition->word, wantedArgs,argCount) // table line is read, now execute rules on it, perhaps multiple times, after stuffing in the choice if one if (argCount) // we swallowed a dataset. Process it { while (ALWAYS) { // prepare variable argumentList if (choiceArg) // do it with next multi { choiceArg = ReadSystemToken(choiceArg,word); // get choice if (!*word || *word == ']') break; // end of multiple choice unsigned int control = 0; if (*word == FUNCTIONSTRING && word[1] == '"') strcpy(word,CompileString(word)); // readtable else strcpy(word,JoinWords(BurstWord(word,CONTRACTIONS|control))); strcpy(word,StoreWord(word,(control) ? AS_IS : 0)->word); if (*word == '\'') // quoted value { choiceArg = ReadSystemToken(choiceArg,word); // get 1st of choice if (!*word || *word == ']') break; // end of LINE of items stuff ForceUnderscores(word); strcpy(pre,StoreWord(word)->word); // record the local w/o any set expansion } else { WORDP D = StoreWord(word); strcpy(pre,D->word); // record the multiple choice choiceArg = SkipWhitespace(choiceArg); if (*choiceArg == '(' && ++choiceArg) while(choiceArg) // synonym { choiceArg = ReadSystemToken(choiceArg,word); if (!*word) BADSCRIPT((char*)"TABLE-10 Failure to close synonym list in table %s\r\n",currentFunctionDefinition->word) if (*word == ')') break; // end of synonms ForceUnderscores(word); CreateFact(MakeMeaning(StoreWord(word)),Mmember,MakeMeaning(D)); } } char* at = pre + strlen(pre); *at++ = ' '; strcpy(at,post); // add rest of argumentList systemArgumentList = at + strlen(at); } *systemArgumentList++ = ')'; // end of call setup *systemArgumentList = 0; currentRule = NULL; FunctionResult result; AllocateOutputBuffer(); DoFunction(currentFunctionDefinition->word,argumentList,currentOutputBase,result); FreeOutputBuffer(); if (!choiceArg) break; } } if (fromtopic) break; // one entry only } convertTabs = true; FreeBuffer(); tableinput = NULL; FreeBuffer(); // not required to happen if error happens if (!tableMacro) // delete dynamic function { currentFunctionDefinition->internalBits &= -1LL ^ FUNCTION_NAME; currentFunctionDefinition->w.fndefinition = NULL; AddInternalFlag(currentFunctionDefinition,DELETED_MARK); } currentFunctionDefinition = NULL; --jumpIndex; echo = oldecho; trace = oldtrace; return ptr; } static void SetJumpOffsets(char* data) // store jump offset for each rule { char* at = data; char* end = data; while (*at && *++at) // find each responder end { if (*at == ENDUNIT) { int diff = (int)(at - end + 1); if (diff > MAX_JUMP_OFFSET) BADSCRIPT((char*)"TOPIC-9 Jump offset too far - %d but limit %d near %s\r\n",diff,MAX_JUMP_OFFSET,readBuffer) // limit 2 char (12 bit) Encode(diff,end); end = at + 1; } } } static char* ReadKeyword(char* word,char* ptr,bool &notted, bool &quoted, MEANING concept,uint64 type,bool ignoreSpell,unsigned int build,bool duplicate,bool startOnly,bool endOnly) { // read the keywords zone of the concept char* at; MEANING M; WORDP D; size_t len = strlen(word); switch(*word) { case '!': // excuded keyword if (len == 1) BADSCRIPT((char*)"CONCEPT-5 Must attach ! to keyword in %s\r\n",Meaning2Word(concept)->word); if (notted) BADSCRIPT((char*)"CONCEPT-5 Cannot use ! after ! in %s\r\n",Meaning2Word(concept)->word); notted = true; ptr -= len; if (*ptr == '!') ++ptr; break; case '\'': if (len == 1) BADSCRIPT((char*)"CONCEPT-6 Must attach ' to keyword in %s\r\n",Meaning2Word(concept)->word); if (quoted) BADSCRIPT((char*)"CONCEPT-5 Cannot use ' after ' in %s\r\n",Meaning2Word(concept)->word); quoted = true; // since we emitted the ', we MUST emit the next token ptr -= len; if (*ptr == '\'') ++ptr; break; default: if (*word == USERVAR_PREFIX || (*word == '_' && IsDigit(word[1])) || *word == SYSVAR_PREFIX) BADSCRIPT((char*)"CONCEPT-? Cannot use $var or _var or %var as a keyword in %s\r\n",Meaning2Word(concept)->word); if (*word == '~') MakeLowerCase(word); // sets are always lower case if (*word == '"' && word[1] == '(')// pattern word { unsigned int flags = 0; if (build & BUILD1) flags |= FACTBUILD1; // concept facts from build 1 else if (build & BUILD2) flags |= FACTBUILD2; // concept facts from build 1 MEANING conceptPattern = MakeMeaning(StoreWord("conceptPattern", AS_IS)); size_t len = strlen(word); if (word[len-1] != '"') BADSCRIPT("ConceptPattern not closing with quote") if (word[len - 2] != ')') BADSCRIPT("ConceptPattern not closing with )") word[len - 1] = 0; char* data = AllocateBuffer() ; char* startData = data++; *startData = '^'; // compiled pattern marker ReadPattern(word+1, NULL, data, false, false); // back up and pass in the paren for pattern FreeBuffer(); M = MakeMeaning(StoreWord(startData, AS_IS)); FACT* F = CreateFact(M, conceptPattern, concept, flags); return ptr; } else if ((at = strchr(word+1,'~'))) // wordnet meaning request, confirm definition exists { char level[MAX_WORD_SIZE]; strcpy(level,at); M = ReadMeaning(word); if (!M) BADSCRIPT((char*)"CONCEPT-7 WordNet word doesn't exist %s\r\n",word) WORDP D = Meaning2Word(M); int index = Meaning2Index(M); if ((GetMeaningCount(D) == 0 && !(GETTYPERESTRICTION(M) & BASIC_POS)) || (index && !strcmp(word,D->word) && index > GetMeaningCount(D))) { if (index) WARNSCRIPT((char*)"WordNet word does not have such meaning %s\r\n",word) M &= -1 ^ INDEX_BITS; } } else // ordinary word or concept-- see if it makes sense { char end = word[strlen(word)-1]; if (nospellcheck) {} else if (!IsAlphaUTF8OrDigit(end) && end != '"' && strlen(word) != 1) { if (end != '.' || strlen(word) > 6) WARNSCRIPT((char*)"last character of keyword %s is punctuation. Is this intended?\r\n", word) } else if (end == '"' && word[(strlen(word) - 2)] == ' ') BADSCRIPT((char*) "CONCEPT-? Keyword %s ends in illegal space\r\n", word) if (*word == '\\') memcpy(word,word+1,strlen(word)); // how to allow $e as a keyword M = ReadMeaning(word); D = Meaning2Word(M); uint64 type1 = type; if (type & NOUN_SINGULAR && D->internalBits & UPPERCASE_HASH) { type1 ^= NOUN_SINGULAR; type1 |= NOUN_PROPER_SINGULAR; } if (type) AddProperty(D,type1); // augment its type if (*D->word == '~') // concept { if (M == concept) BADSCRIPT((char*)"CONCEPT-8 Cannot include topic into self - %s\r\n",D->word); CheckSetOrTopic(D->word); } else if ( ignoreSpell || !spellCheck || strchr(D->word,'_') || !D->word[1] || D->internalBits & UPPERCASE_HASH) {;} // ignore spelling issues, phrases, short words && proper names else if (!(D->properties & PART_OF_SPEECH) && !(D->systemFlags & PATTERN_WORD)) { if (!(spellCheck & NO_SPELL)) SpellCheckScriptWord(D->word,-1,false); WriteKey(D->word); WritePatternWord(D->word); } } // end ordinary word unsigned int flags = quoted ? ORIGINAL_ONLY : 0; if (duplicate) flags |= FACTDUPLICATE; if (startOnly) flags |= START_ONLY; if (endOnly) flags |= END_ONLY; if (build & BUILD1) flags |= FACTBUILD1; // concept facts from build 1 else if (build & BUILD2) flags |= FACTBUILD2; // concept facts from build 1 FACT* F = CreateFact(M,(notted) ? Mexclude : Mmember,concept, flags); quoted = false; notted = false; } return ptr; } bool HasBotMember(WORDP concept, uint64 id) { FACT* F = GetObjectHead(concept); while (F) { if (F->verb == Mmember) // manual ValidMemberFact(F) because bot id is passed in { // limited to a specific bot // We ARE allowed to add to general in existing layer if (id && F->botBits & id) return true; // not allow generic fact? // we are general and it has general already if (!id) return true; } F = GetObjectNext(F); } return false; } static char* ReadBot(char* ptr) { *scopeBotName = ' '; ptr = SkipWhitespace(ptr); char* original = ptr; if (IsDigit(*ptr)) { int64 n; ptr = ReadInt64(ptr,n); // change bot id myBot = n; } MakeLowerCopy(scopeBotName+1,ptr); // presumes til end of line size_t len = strlen(scopeBotName); while (scopeBotName[len-1] == ' ') scopeBotName[--len] = 0; if (len == 0) { Log(STDUSERLOG,(char*)"Reading bot restriction: %s\r\n",original); return ""; // there is no header anymore } strcat(scopeBotName," "); // single trailing space char* x; while ((x = strchr(scopeBotName,','))) *x = ' '; // change comma to space. all bot names have spaces on both sides Log(STDUSERLOG,(char*)"Reading bot restriction: %s\r\n",original); return ""; } static char* ReadTopic(char* ptr, FILE* in,unsigned int build) { patternContext = false; displayIndex = 0; char* data = (char*) malloc(MAX_TOPIC_SIZE); // use a big chunk of memory for the data *data = 0; char* pack = data; ++topicCount; *currentTopicName = 0; unsigned int flags = 0; bool topicFlagsDone = false; bool keywordsDone = false; int parenLevel = 0; bool quoted = false; bool notted = false; MEANING topicValue = 0; int holdDepth = globalDepth; WORDP topicName = NULL; unsigned int gambits = 0; unsigned int toplevelrules = 0; // does not include rejoinders currentRuleID = 0; // reset rule notation verifyIndex = 0; bool stayRequested = false; int buffercount = bufferIndex; if (setjmp(scriptJump[++jumpIndex])) { bufferIndex = buffercount; ptr = FlushToTopLevel(in,holdDepth,data); // if error occurs lower down, flush to here } while (ALWAYS) // read as many tokens as needed to complete the definition { char word[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; if (!*currentTopicName) // get the topic name { if (*word != '~') BADSCRIPT((char*)"Topic name - %s must start with ~\r\n",word) strcpy(currentTopicName,word); Log(STDUSERLOG,(char*)"Reading topic %s\r\n",currentTopicName); topicName = FindWord(currentTopicName); if (!myBot && topicName && topicName->internalBits & CONCEPT && !(topicName->internalBits & TOPIC) && topicName->internalBits & (BUILD0 | BUILD1 | BUILD2)) WARNSCRIPT((char*)"TOPIC-1 Concept already defined with this topic name %s\r\n", currentTopicName) if (topicName && topicName->internalBits & CONCEPT && !(topicName->internalBits & TOPIC) && (topicName->internalBits & (BUILD0 | BUILD1 | BUILD2)) != build) BADSCRIPT((char*)"TOPIC-1 Concept already defined with this topic name %s in prior layer\r\n", currentTopicName) if (topicName && HasBotMember(topicName, myBot)) { BADSCRIPT((char*)"TOPIC-1 Concept already defined %s\r\n", currentTopicName) } topicName = StoreWord(currentTopicName); if (!IsLegalName(currentTopicName)) BADSCRIPT((char*)"TOPIC-2 Illegal characters in topic name %s\r\n",currentTopicName) topicValue = MakeMeaning(topicName); // handle potential multiple topics of same name duplicateCount = 0; while (topicName->internalBits & TOPIC) { ++duplicateCount; char name[MAX_WORD_SIZE]; sprintf(name,(char*)"%s%c%d",currentTopicName,DUPLICATETOPICSEPARATOR,duplicateCount); topicName = StoreWord(name); if (!*duplicateTopicName) strcpy(duplicateTopicName,currentTopicName); } strcpy(currentTopicName,topicName->word); AddMap((char*)" topic:", topicName->word); AddInternalFlag(topicName,(unsigned int)(build|CONCEPT|TOPIC)); topicName->w.topicBots = NULL; currentTopicBots = NULL; continue; } if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= strlen(word); // let someone else see this starter also // safe break; } switch(*word) { case '(': case '[': if (!keywordsDone && topicFlagsDone) BADSCRIPT((char*)"TOPIC-3 Illegal bracking in topic keywords %s\r\n",word) if (flags & TOPIC_SHARE && flags & TOPIC_SYSTEM) BADSCRIPT((char*)"TOPIC-? Don't need SHARE on SYSTEM topic %s, it is already shared via system\r\n",currentTopicName) topicFlagsDone = true; // topic flags must occur before list of keywords ++parenLevel; if (!topicName->w.topicBots && *scopeBotName) topicName->w.topicBots = AllocateHeap(scopeBotName, strlen(scopeBotName)+1); break; case ')': case ']': --parenLevel; if (parenLevel == 0) { keywordsDone = true; ReadNextSystemToken(in,ptr,word,false,true); // check for optional display variables if (*word == '(') ptr = ReadDisplay(in,ptr); } break; case '#': if (*word == '#' && word[1] == '!') ptr = AddVerify(word,ptr); continue; default: MakeLowerCopy(lowercaseForm,word); if (!topicFlagsDone) // do topic flags { if (!strnicmp(word,(char*)"bot=",4)) // bot restriction on the topic { char botlist[MAX_WORD_SIZE]; MakeLowerCopy(botlist,word+4); char* x; while ((x = strchr(botlist,','))) *x = ' '; // change comma to space. all bot names have spaces on both sides topicName->w.topicBots = AllocateHeap(botlist,strlen(botlist)); // bot=harry,georgia,roger currentTopicBots = topicName->w.topicBots; } else if (!stricmp(word,(char*)"deprioritize")) flags |= TOPIC_LOWPRIORITY; else if (!stricmp(word,(char*)"noblocking")) flags |= TOPIC_NOBLOCKING; else if (!stricmp(word,(char*)"nopatterns") || !stricmp(word,(char*)"nopattern")) flags |= TOPIC_NOPATTERNS; else if (!stricmp(word,(char*)"nogambits") || !stricmp(word,(char*)"nogambit")) flags |= TOPIC_NOGAMBITS; else if (!stricmp(word,(char*)"nosamples") || !stricmp(word,(char*)"nosample")) flags |= TOPIC_NOSAMPLES; else if (!stricmp(word,(char*)"nokeys") || !stricmp(word,(char*)"nokeywords") ) flags |= TOPIC_NOKEYS; else if (!stricmp(word,(char*)"keep")) flags |= TOPIC_KEEP; else if (!stricmp(word,(char*)"norandom")) flags &= -1 ^TOPIC_RANDOM; else if (!stricmp(word,(char*)"normal")) flags &= -1 ^TOPIC_PRIORITY; else if (!stricmp(word,(char*)"norepeat")) flags &= -1 ^TOPIC_REPEAT; else if (!stricmp(word,(char*)"nostay")) flags |= TOPIC_NOSTAY; else if (!stricmp(word,(char*)"priority")) flags |= TOPIC_PRIORITY; else if (!stricmp(word,(char*)"random")) flags |= TOPIC_RANDOM; else if (!stricmp(word,(char*)"repeat")) flags |= TOPIC_REPEAT; else if (!stricmp(word,(char*)"safe")) flags |= TOPIC_SAFE; else if (!stricmp(word,(char*)"share")) flags |= TOPIC_SHARE; else if (!stricmp(word,(char*)"stay")) { flags &= -1 ^TOPIC_NOSTAY; stayRequested = true; } else if (!stricmp(word,(char*)"erase")) flags &= -1 ^TOPIC_KEEP; else if (!stricmp(word,(char*)"system")) { flags |= TOPIC_SYSTEM | TOPIC_KEEP | TOPIC_NOSTAY; if (stayRequested) BADSCRIPT((char*)"TOPIC-4 Topic %s cannot be both STAY and SYSTEM\r\n",currentTopicName) } else if (!stricmp(word,(char*)"user")); else BADSCRIPT((char*)"Bad topic flag %s for topic %s\r\n",word,currentTopicName) } else if (!keywordsDone) ptr = ReadKeyword(word,ptr,notted,quoted,topicValue,0,false,build,false,false,false);// absorb keyword list else if (!stricmp(word,(char*)"datum:")) // absorb a top-level data table line { ptr = ReadTable(ptr,in,build,true); } else if (TopLevelRule(lowercaseForm))// absorb a responder/gambit and its rejoinders { if (IsUpperCase(*word)) BADSCRIPT((char*)"Rule ID must be lower case: %s\r\n",word); ++toplevelrules; if (TopLevelGambit(word)) ++gambits; if (pack == data) { strcpy(pack,ENDUNITTEXT+1); // init 1st rule pack += strlen(pack); } ReadTopLevelRule(topicName,lowercaseForm,ptr,in,pack,data); currentRuleID = TOPLEVELID(currentRuleID) + 1; pack += strlen(pack); if ((pack - data) > (MAX_TOPIC_SIZE - 2000)) BADSCRIPT((char*)"TOPIC-4 Topic %s data too big. Split it by calling another topic using u: () respond(~subtopic) and putting the rest of the rules in that subtopic\r\n",currentTopicName) } else BADSCRIPT((char*)"Expecting responder for topic %s, got %s",currentTopicName,word) } } --jumpIndex; if (parenLevel) BADSCRIPT((char*)"TOPIC-5 Failure to balance ( in %s\r\n",currentTopicName) if (!topicName) BADSCRIPT((char*)"TOPIC-6 No topic name?\r\n") if (toplevelrules > MAX_TOPIC_RULES) BADSCRIPT((char*)"TOPIC-8 %s has too many rules- %d must be limited to %d. Call a subtopic.\r\n",currentTopicName,toplevelrules,MAX_TOPIC_RULES) size_t len = pack-data; SetJumpOffsets(data); if (displayIndex) { char display[MAX_WORD_SIZE * 10]; char* at = WriteDisplay(display); size_t displayLen = at - display; memmove(data+displayLen,data,len+1); // shift it all down + 1 for space separator replaceing string end len += displayLen; memmove(data,display,displayLen); } bool hasUpperCharacters; bool hasUTF8Characters; unsigned int checksum = ((unsigned int) Hashit((unsigned char*) data, len,hasUpperCharacters,hasUTF8Characters)) & 0x0fffffff; // trailing blank after jump code if (len >= (MAX_TOPIC_SIZE-100)) BADSCRIPT((char*)"TOPIC-7 Too much data in one topic\r\n") char filename[SMALL_WORD_SIZE]; sprintf(filename,(char*)"%s/BUILD%s/script%s.txt",topic,baseName,baseName); FILE* out = FopenUTF8WriteAppend(filename); if (out) { // write out topic data char* restriction = (topicName->w.topicBots) ? topicName->w.topicBots : (char*)"all"; unsigned int len1 = (unsigned int)strlen(restriction); fprintf(out, (char*)"TOPIC: %s 0x%x %d %d %d %d %s\r\n", currentTopicName, (unsigned int)flags, (unsigned int)checksum, (unsigned int)toplevelrules, (unsigned int)gambits, (unsigned int)(len + len1 + 7), currentFilename); fprintf(out, (char*)"\" %s \" ", restriction); fprintf(out, (char*)"%s\r\n", data); fclose(out); // dont use FClose } free(data); return ptr; } static char* ReadRename(char* ptr, FILE* in,unsigned int build) { renameInProgress = true; while (ALWAYS) // read as many tokens as needed to complete the definition { char word[MAX_WORD_SIZE]; char basic[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; if (*word == '#' && (word[1] != '#' || !IsAlphaUTF8(word[2]))) { *ptr = 0; break; // comment ends it also } if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= strlen(word); // let someone else see this starter also // safe break; } if (*word != '_' && *word != '@' && (*word != '#' || word[1] != '#')) BADSCRIPT((char*)"Rename %s must start with _ or @ or ##\r\n",word) ptr = ReadNextSystemToken(in,ptr,basic,false); if (*word != '#' && (*basic != *word || !IsDigit(basic[1]) )) BADSCRIPT((char*)"Rename %s must start same as %s and have a number after it\r\n",basic,word) if (*word == '#' && !IsDigit(*basic) && *basic != '-' && *basic != '+') BADSCRIPT((char*)"Rename %s followed by number or sign as %s\r\n",word,basic) MakeLowerCase(word); int64 n; if (*word == '#') { ReadInt64(basic,n); if (*basic == '-') n = -n; // force positive } else ReadInt64(basic+1,n); WORDP D = FindWord(word); if (D && !myBot) WARNSCRIPT((char*)"Already have a rename for %s\r\n", word) D = StoreWord(word,n); AddInternalFlag(D,(unsigned int)(RENAMED|build)); if (*word == '#' && *basic == '-') AddSystemFlag(D,CONSTANT_IS_NEGATIVE); Log(STDUSERLOG,(char*)"Rename %s as %s\r\n",basic,word); } renameInProgress = false; return ptr; } static char* ReadPlan(char* ptr, FILE* in,unsigned int build) { if (build == BUILD2) BADSCRIPT((char*)"Not allowed plans in layer 2 at present\r\n") char planName[MAX_WORD_SIZE]; char baseName[MAX_WORD_SIZE]; displayIndex = 0; *planName = 0; functionArgumentCount = 0; int parenLevel = 0; bool gettingArguments = true; endtopicSeen = false; patternContext = false; int baseArgumentCount = 0; unsigned int duplicateCount = 0; WORDP plan = NULL; while (gettingArguments) // read as many tokens as needed to get the name and argumentList { char word[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; // end of file if (!*planName) // get the plan name { if (*word == '^') memmove(word,word+1,strlen(word)); // remove his ^ MakeLowerCase(word); if (!IsAlphaUTF8(*word) ) BADSCRIPT((char*)"PLAN-1 Plan name must start alpha %s\r\n",word) if (!IsLegalName(word)) BADSCRIPT((char*)"PLAN-2 Illegal characters in plan name %s\r\n",word) *planName = '^'; strcpy(planName+1,word); strcpy(baseName,planName); Log(STDUSERLOG,(char*)"Reading plan %s\r\n",planName); // handle potential multiple plans of same name plan = FindWord(planName); char name[MAX_WORD_SIZE]; strcpy(name,planName); if (plan) baseArgumentCount = plan->w.planArgCount; while (plan && plan->internalBits & FUNCTION_NAME) { ++duplicateCount; sprintf(name,(char*)"%s%c%d",baseName,DUPLICATETOPICSEPARATOR,duplicateCount); plan = FindWord(name); strcpy(planName,name); } plan = StoreWord(planName); continue; } size_t len = strlen(word); if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= len; // let someone else see this starter also break; } switch(*word) { case '(': if (parenLevel++ != 0) BADSCRIPT((char*)"PLAN-4 bad paren level in plan definition %s\r\n",planName) continue; // callArgumentList open case ')': if (--parenLevel != 0) BADSCRIPT((char*)"PLAN-5 bad closing paren in plan definition %s\r\n",planName) gettingArguments = false; break; case '^': // declaring a new argument if (IsDigit(word[1])) BADSCRIPT((char*)"PLAN-6 Plan arguments must be alpha names, not digits like %s\r\n",word) strcpy(functionArguments[functionArgumentCount++],word); if (functionArgumentCount > MAX_ARG_LIMIT) BADSCRIPT((char*)"PLAN-7 Too many callArgumentList to %s - max is %d\r\n",planName,MAX_ARG_LIMIT) continue; default: BADSCRIPT((char*)"PLAN-7 Bad argument to plan definition %s",planName) } } if (!plan) return ptr; // nothing defined if (parenLevel) BADSCRIPT((char*)"PLAN-5 Failure to balance ( in %s\r\n",planName) if (duplicateCount && functionArgumentCount != baseArgumentCount) BADSCRIPT((char*)"PLAN->? Additional copies of %s must have %d arguments\r\n",planName,baseArgumentCount) AddInternalFlag(plan,(unsigned int)(FUNCTION_NAME|build|IS_PLAN_MACRO)); plan->w.planArgCount = functionArgumentCount; currentFunctionDefinition = plan; char* data = (char*) malloc(MAX_TOPIC_SIZE); // use a big chunk of memory for the data *data = 0; char* pack = data; int holdDepth = globalDepth; unsigned int toplevelrules = 0; // does not include rejoinders int buffercount = bufferIndex; if (setjmp(scriptJump[++jumpIndex])) { bufferIndex = buffercount; ptr = FlushToTopLevel(in,holdDepth,data); // if error occurs lower down, flush to here } while (ALWAYS) // read as many tokens as needed to complete the definition { char word[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= strlen(word); // let someone else see this starter also // safe break; } switch(*word) { case '#': if (*word == '#' && word[1] == '!') BADSCRIPT((char*)"PLAN-? Verification not meaningful in a plan\r\n") continue; default: MakeLowerCopy(lowercaseForm,word); if (TopLevelRule(lowercaseForm))// absorb a responder/gambit and its rejoinders { ++toplevelrules; if (pack == data) { strcpy(pack,ENDUNITTEXT+1); // init 1st rule pack += strlen(pack); } ReadTopLevelRule(plan,lowercaseForm,ptr,in,pack,data); pack += strlen(pack); if ((pack - data) > (MAX_TOPIC_SIZE - 2000)) BADSCRIPT((char*)"PLAN-4 Plan %s data too big. Split it by calling another topic using u: () respond(~subtopic) and putting the rest of the rules in that subtopic\r\n",planName) } else BADSCRIPT((char*)"Expecting responder for plan %s, got %s\r\n",planName,word) } } --jumpIndex; if (toplevelrules > MAX_TOPIC_RULES) BADSCRIPT((char*)"PLAN-8 %s has too many rules- %d must be limited to %d. Call a plantopic.\r\n",planName,toplevelrules,MAX_TOPIC_RULES) size_t len = pack-data; if (!len) WARNSCRIPT((char*)"No data in plan %s\r\n",currentTopicName) if (!endtopicSeen) BADSCRIPT((char*)"PLAN-8 Plan %s cannot succeed since no ^end(plan) exists\r\n",planName) // trailing blank after jump code SetJumpOffsets(data); if (len >= (MAX_TOPIC_SIZE-100)) BADSCRIPT((char*)"PLAN-7 Too much data in one plan\r\n") *pack = 0; char file[200]; if (build == BUILD0) sprintf(file,"%s/BUILD0/plans0.txt",topic); else sprintf(file,"%s/BUILD0/plans1.txt",topic); // write how many plans were found (for when we preload during normal startups) if (hasPlans == 0) { FILE* out = FopenUTF8Write(file); fprintf(out,(char*)"%s",(char*)"0 \r\n"); // reserve 5-digit count for number of plans fclose(out); // dont use Fclose } ++hasPlans; // write out plan data FILE* out = FopenUTF8WriteAppend(file); char* restriction = (char*)"all"; unsigned int len1 = (unsigned int)strlen(restriction); fprintf(out,(char*)"PLAN: %s %d %d %d %s\r\n",planName,(unsigned int) functionArgumentCount,(unsigned int) toplevelrules,(unsigned int)(len + len1 + 7),currentFilename); fprintf(out,(char*)"\" %s \" %s\r\n",restriction,data); fclose(out); // dont use FClose free(data); return ptr; } static char* ReadQuery(char* ptr, FILE* in, unsigned int build) // readquery: name "xxxxx" text { while (ALWAYS) // read as many tokens as needed to complete the definition (must be within same file) { char word[MAX_WORD_SIZE]; char query[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); // name of query if (!*word) break; size_t len = strlen(word); if (!IsAlphaUTF8(*word)) BADSCRIPT((char*)"query label %s must be alpha\r\n",word); if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= len; // let someone else see this starter break; } ptr = ReadNextSystemToken(in,ptr,query,false); if (*query != '"') BADSCRIPT((char*)"query body %s must be in quotes\r\n",query); WORDP D = StoreWord(word); AddInternalFlag(D, (unsigned int)(QUERY_KIND|build)); char* at = strchr(query+1,'"'); if (!at) BADSCRIPT((char*)"query body %s must end in quotes\r\n", query); *at = 0; D->w.userValue = AllocateHeap(query+1); } return ptr; } static char* ReadReplace(char* ptr, FILE* in, unsigned int build) { while (ALWAYS) // read as many tokens as needed to complete the definition (must be within same file) { char word[MAX_WORD_SIZE]; char replace[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!stricmp(word,(char*)"replace:")) ptr = ReadNextSystemToken(in,ptr,word,false); // keep going with local replace loop if (!*word) break; // file ran dry if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= strlen(word); // let someone else see this starter break; } ptr = ReadNextSystemToken(in,ptr,replace,false); if (TopLevelUnit(replace)) // definition ends when another major unit starts { ptr -= strlen(replace); // let someone else see this starter break; } if (*word == '\'') { memmove(word + 1, word, strlen(word)+1); *word = '*'; } char filename[SMALL_WORD_SIZE]; sprintf(filename,(char*)"%s/BUILD%s/private%s.txt",topic,baseName,baseName); FILE* out = FopenUTF8WriteAppend(filename); fprintf(out,(char*)" %s %s\r\n",word,replace); fclose(out); // dont use FClose } return ptr; } static char* ReadIgnoreSpell(char* ptr, FILE* in, unsigned int build) { while (ALWAYS) // read as many tokens as needed to complete the definition (must be within same file) { char ignore[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in, ptr, ignore, false); if (!stricmp(ignore, (char*)"ignorespell:")) ptr = ReadNextSystemToken(in, ptr, ignore, false); // keep going with local ignore loop if (!*ignore) break; // file ran dry if (TopLevelUnit(ignore)) // definition ends when another major unit starts { ptr -= strlen(ignore); // let someone else see this starter break; } if (TopLevelUnit(ignore)) // definition ends when another major unit starts { ptr -= strlen(ignore); // let someone else see this starter break; } if (*ignore == '*' && !ignore[1]) { nospellcheck = true; continue; } if (*ignore == '!' && ignore[1] == '*' && !ignore[2]) { nospellcheck = false; continue; } WORDP D = StoreWord(ignore, 0); if (!(D->internalBits & HAS_SUBSTITUTE)) D->internalBits |= DO_NOISE; } return ptr; } static char* ReadPrefer(char* ptr, FILE* in, unsigned int build) { while (ALWAYS) // read as many tokens as needed to complete the definition (must be within same file) { char word[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in, ptr, word, false); if (!*word) break; // file ran dry if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= strlen(word); // let someone else see this starter break; } WORDP D = StoreWord(word); D->internalBits |= PREFER_THIS_UPPERCASE; } return ptr; } void SaveCanon(char* word, char* canon) { char filename[SMALL_WORD_SIZE]; sprintf(filename,(char*)"%s/BUILD%s/canon%s.txt",topic,baseName,baseName); FILE* out = FopenUTF8WriteAppend(filename); fprintf(out,(char*)" %s %s\r\n",word,canon); fclose(out); // dont use FClose WritePatternWord(word); // must recognize this word for spell check WritePatternWord(canon); // must recognize this word for spell check } static char* ReadCanon(char* ptr, FILE* in, unsigned int build) { while (ALWAYS) // read as many tokens as needed to complete the definition (must be within same file) { char word[MAX_WORD_SIZE]; char canon[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!stricmp(word,(char*)"canonical:")) ptr = ReadNextSystemToken(in,ptr,word,false); // keep going with local loop if (!*word) break; // file ran dry size_t len = strlen(word); if (TopLevelUnit(word)) // definition ends when another major unit starts { ptr -= len; // let someone else see this starter break; } ptr = ReadNextSystemToken(in,ptr,canon,false); SaveCanon(word,canon); } return ptr; } static char* ReadConcept(char* ptr, FILE* in,unsigned int build) { char conceptName[MAX_WORD_SIZE]; *conceptName = 0; MEANING concept = 0; WORDP D; bool ignoreSpell = false; patternContext = false; bool quoted = false; bool notted = false; bool more = false; bool undeclared = true; bool startOnly = false; bool endOnly = false; int parenLevel = 0; uint64 type = 0; uint64 sys; bool duplicate = false; while (ALWAYS) // read as many tokens as needed to complete the definition (must be within same file) { char word[MAX_WORD_SIZE]; ptr = ReadNextSystemToken(in,ptr,word,false); if (!*word) break; // file ran dry size_t len = strlen(word); if (TopLevelUnit(word)) // definition ends when another major unit starts { if (TopLevelUnit(word)) ptr -= len; // let someone else see this starter break; } // establish name and characteristics of the concept if (!*conceptName) // get the concept name, will be ~xxx or :xxx { if (*word != '~' ) BADSCRIPT((char*)"CONCEPT-1 Concept name must begin with ~ or : - %s\r\n",word) // Users may not create repeated user topic names. Ones already saved in dictionary are fine to overwrite MakeLowerCopy(conceptName,word); if (!IsLegalName(conceptName)) BADSCRIPT((char*)"CONCEPT-2 Illegal characters in concept name %s\r\n",conceptName) // create concept header D = StoreWord(conceptName); concept = MakeMeaning(D); sys = type = 0; parenLevel = 0; Log(STDUSERLOG,(char*)"Reading concept %s\r\n",conceptName); AddMap((char*)" concept:", conceptName); // read the control flags of the concept ptr = SkipWhitespace(ptr); while (*ptr && *ptr != '(' && *ptr != '[' && *ptr != '"') // not started and no concept comment given (concept comments come after all control flags { ptr = ReadCompiledWord(ptr,word); len = strlen(word); if (word[len-1] == '(') { word[len-1] = 0; --ptr; if (*ptr != '(') --ptr; } if (!stricmp(word,(char*)"more")) { more = true; continue; } if (!stricmp(word,(char*)"duplicate")) // allow duplicate keywords { duplicate = true; continue; } if (!stricmp(word, (char*)"INTERJECTION")) // match member as interjection { endOnly = startOnly = true; continue; } if (!stricmp(word, (char*)"START_ONLY")) // match member only at start of sentence { startOnly = true; continue; } if (!stricmp(word, (char*)"END_ONLY")) // match member only at end of sentence { endOnly = true; continue; } char* paren = strchr(word,'('); if (paren) // handle attachment of paren + stuff { while (*--ptr != '('); *paren = 0; } ptr = SkipWhitespace(ptr); uint64 bits = FindValueByName(word); type |= bits; uint64 bits1 = FindSystemValueByName(word); sys |= bits1; unsigned int bits2 = (unsigned int)FindParseValueByName(word); if (sys & NOCONCEPTLIST) { AddInternalFlag(D,FAKE_NOCONCEPTLIST); sys ^= NOCONCEPTLIST; } if (bits) AddProperty(D, bits); else if (bits1) AddSystemFlag(D, bits1); else if (bits2) AddParseBits(D,bits2); else if (!stricmp(word,(char*)"IGNORESPELLING")) ignoreSpell = true; else if (!stricmp(word,(char*)"UPPERCASE_MATCH")) AddInternalFlag(D,UPPERCASE_MATCH); else if (!stricmp(word,(char*)"ONLY_NOUNS")) AddSystemFlag(D,NOUN); else if (!stricmp(word,(char*)"ONLY_VERBS")) AddSystemFlag(D,VERB); else if (!stricmp(word,(char*)"ONLY_ADJECTIVES")) AddSystemFlag(D,ADJECTIVE); else if (!stricmp(word,(char*)"ONLY_ADVERBS")) AddSystemFlag(D,ADVERB); else if (!stricmp(word,(char*)"ONLY_NONE")) AddSystemFlag(D,ONLY_NONE); // disable ONLY here and below else BADSCRIPT((char*)"CONCEPT-4 Unknown concept property %s\r\n",word) } continue; // read more tokens now that concept has been established } if (undeclared) { undeclared = false; // dont test this again if (!more) { int buildbits = D->internalBits & (BUILD0 | BUILD1 | BUILD2); if (!myBot && D->internalBits & CONCEPT && buildbits) WARNSCRIPT((char*)"CONCEPT-3 Concept/topic already defined %s\r\n",conceptName) if (1 == 2 && (D->internalBits & CONCEPT) && buildbits != build) BADSCRIPT((char*)"CONCEPT-3 Concept/topic already defined %s in prior layer\r\n", conceptName) if (HasBotMember(D, myBot) && (D->internalBits & CONCEPT)) { BADSCRIPT((char*)"CONCEPT-3 Concept/topic already defined %s\r\n", conceptName) } } AddInternalFlag(D,(unsigned int)(build|CONCEPT)); } // read the keywords zone of the concept switch(*word) // THE MEAT OF CONCEPT DEFINITIONS { case '(': case '[': // start keyword list if (parenLevel) BADSCRIPT((char*)"CONCEPT-5 Cannot use [ or ( within a keyword list for %s\r\n",conceptName); parenLevel++; break; case ')': case ']': // end keyword list --parenLevel; if (parenLevel < 0) BADSCRIPT((char*)"CONCEPT-6 Missing ( for concept definition %s\r\n",conceptName) break; default: ptr = ReadKeyword(word,ptr,notted,quoted,concept,type,ignoreSpell,build,duplicate,startOnly,endOnly); } if (parenLevel == 0) break; } if (parenLevel) BADSCRIPT((char*)"CONCEPT-7 Failure to give closing ( in concept %s\r\n",conceptName) return ptr; } static void ReadTopicFile(char* name,uint64 buildid) // read contents of a topic file (.top or .tbl) { convertTabs = true; tableinput = NULL; callingSystem = 0; chunking = false; unsigned int build = (unsigned int) buildid; size_t len = strlen(name); if (len <= 4) return; // Check the filename is at least four characters (the ext plus one letter) // and matches either .top or .tbl char* suffix = name + len - 4; if (stricmp(suffix, (char*) ".top") && stricmp(suffix, (char*) ".tbl")) return; FILE* in = FopenReadNormal(name); if (!in) { if (strchr(name,'.') || build & FROM_FILE) // names a file, not a directory { WARNSCRIPT((char*)"Missing file %s\r\n",name) ++missingFiles; } return; } char word[MAX_WORD_SIZE]; *readBuffer = 0; // insure no carryover from elsewhere ReadNextSystemToken(NULL, NULL, word, false, false); // flush cache build &= -1 ^ FROM_FILE; // remove any flag indicating it came as a direct file, not from a directory listing Log(STDUSERLOG,(char*)"\r\n----Reading file %s\r\n",currentFilename); char map[MAX_WORD_SIZE]; char file[MAX_WORD_SIZE]; GetCurrentDir(file, MAX_WORD_SIZE); sprintf(map,"%s/%s",file,name); char* find = map; while ((find = strchr(find,'\\'))) *find = '/'; AddMap((char*)"file:", map); // if error occurs lower down, flush to here int holdDepth = globalDepth; patternContext = false; char* ptr = ""; int buffercount = bufferIndex; if (setjmp(scriptJump[++jumpIndex])) { bufferIndex = buffercount; ptr = FlushToTopLevel(in,holdDepth,0); } while (ALWAYS) { ptr = ReadNextSystemToken(in,ptr,word,false); // eat tokens (should all be top level) if (!*word) break; // no more tokens found currentFunctionDefinition = NULL; // can be set by ReadTable or ReadMacro if (!stricmp(word,(char*)":quit")) break; if (*word == ':' && word[1]) // testing command { char output[MAX_WORD_SIZE]; DoCommand(readBuffer,output); *readBuffer = 0; *ptr = 0; } else if (!stricmp(word,(char*)"concept:")) ptr = ReadConcept(ptr,in,build); else if (!stricmp(word,(char*)"query:")) ptr = ReadQuery(ptr,in,build); else if (!stricmp(word,(char*)"replace:")) ptr = ReadReplace(ptr,in,build); else if (!stricmp(word, (char*)"ignorespell:")) ptr = ReadIgnoreSpell(ptr, in, build); else if (!stricmp(word, (char*)"prefer:")) ptr = ReadPrefer(ptr, in, build); else if (!stricmp(word,(char*)"canon:")) ptr = ReadCanon(ptr,in,build); else if (!stricmp(word,(char*)"topic:")) ptr = ReadTopic(ptr,in,build); else if (!stricmp(word,(char*)"plan:")) ptr = ReadPlan(ptr,in,build); else if (!stricmp(word,(char*)"bot:")) { globalBotScope = false; // lasts for this file ptr = ReadBot(ptr); } else if (!stricmp(word,(char*)"table:")) ptr = ReadTable(ptr,in,build,false); else if (!stricmp(word,(char*)"rename:")) ptr = ReadRename(ptr,in,build); else if (!stricmp(word,(char*)"describe:")) ptr = ReadDescribe(ptr,in,build); else if (!stricmp(word,(char*)"patternMacro:") || !stricmp(word,(char*)"outputMacro:") || !stricmp(word,(char*)"dualMacro:") || !stricmp(word,(char*)"tableMacro:")) ptr = ReadMacro(ptr,in,word,build); else BADSCRIPT((char*)"FILE-1 Unknown top-level declaration %s in %s\r\n",word,name) } FClose(in); // this should be the only such, not fclose. --jumpIndex; if (hasHighChar) WARNSCRIPT((char*)"File %s has no utf8 BOM but has character>127 - extended Ansi changed to normal Ascii\r\n", name) // should have been utf 8 or have no high data. if (!globalBotScope) // restore any local change from this file { myBot = 0; *scopeBotName = 0; } } static void DoubleCheckFunctionDefinition() { HEAPREF list = undefinedCallThreadList; while (list) { uint64 functionNamex; uint64 filenamex; uint64 linex; list = UnpackHeapval(list, functionNamex, filenamex,linex); char* functionName = (char*)functionNamex; char* filename = (char*)filenamex; char* line = (char*) linex; int args = *functionName++ ; strcpy(currentFilename, filename); currentFileLine = (int)(uint64)line; WORDP D = FindWord(functionName); if (D && D->internalBits & FUNCTION_BITS) { unsigned char* defn = GetDefinition(D); int want = MACRO_ARGUMENT_COUNT(defn); if (args != want && !(D->internalBits & VARIABLE_ARGS_TABLE)) { Log(BADSCRIPTLOG, (char*)"*** Error- Function %s wrong argument count %d expected %d given \r\n", functionName,want,args); ++hasErrors; } } else if (functionName[1] != USERVAR_PREFIX) // allow function calls indirect off variables { Log(BADSCRIPTLOG, (char*)"*** Error- Undefined function %s \r\n", functionName); ++hasErrors; } } } static void DoubleCheckReuse() { char file[200]; sprintf(file,"%s/missingLabel.txt",topic); FILE* in = FopenReadWritten(file); if (!in) return; char label[MAX_WORD_SIZE]; char bothead[MAX_WORD_SIZE]; while (ReadALine(readBuffer,in) >= 0) { char *ptr = ReadCompiledWord(readBuffer, label); // topic + label ptr = ReadCompiledWord(ptr, bothead); // from file MakeUpperCase(bothead); ptr = ReadCompiledWord(ptr,tmpWord); // from file int line; ptr = ReadInt(ptr,line); // from line char labelx[MAX_WORD_SIZE]; sprintf(labelx, "%s-%s", label, bothead); WORDP D = FindWord(labelx); if (!D) // cant find as bot specific, check for general { sprintf(labelx, "%s-*", label); D = FindWord(labelx); } if (!D) WARNSCRIPT((char*)"Missing label %s for reuse in bot %s in File: %s Line: %d \r\n",label, bothead, tmpWord,line) } fclose(in); // dont use Fclose remove(file); } static void WriteCMore(FACT* F, char*&word,FILE* out,size_t& lineSize) { // write it out- this INVERTS the order now and when read back in, will be reestablished correctly // but dictionary storage locations will be inverted size_t wlen = strlen(word); if (F->botBits) // add restrictor { #ifdef WIN32 sprintf(word + wlen - 1, (char*)"`%I64u ", F->botBits); #else sprintf(word + wlen - 1, (char*)"`%llu ", F->botBits); #endif wlen = strlen(word); } fwrite(word, 1, wlen, out); lineSize += wlen; if (lineSize > 500) // avoid long lines { fprintf(out, (char*)"%s", (char*)"\r\n "); lineSize = 0; } *word = 0; } static void WriteConcepts(WORDP D, uint64 build) { seeAllFacts = true; // do for all bots at once char* name = D->word; if (*name != '~' || !(D->internalBits & build)) return; // not a topic or concept or not defined this build RemoveInternalFlag(D,(BUILD0|BUILD1)); // write out keywords FILE* out = NULL; char filename[SMALL_WORD_SIZE]; sprintf(filename,(char*)"%s/BUILD%s/keywords%s.txt",topic,baseName,baseName); out = FopenUTF8WriteAppend(filename); fprintf(out,(D->internalBits & TOPIC) ? (char*)"T%s " : (char*)"%s ", D->word); uint64 properties = D->properties; uint64 bit = START_BIT; while (properties && bit) { if (properties & bit && bit) { properties ^= bit; fprintf(out,(char*)"%s ",FindNameByValue(bit)); } bit >>= 1; } properties = D->systemFlags; bit = START_BIT; while (properties && bit) { // dont write this out in keywords see FAKE_NOCONCEPTLIST - these go in DICTn file if (properties & bit && !(bit & (PATTERN_WORD|NOCONCEPTLIST))) { char* name = FindSystemNameByValue(bit); properties ^= bit; fprintf(out,(char*)"%s ",name); } bit >>= 1; } if (D->internalBits & FAKE_NOCONCEPTLIST) fprintf(out,(char*)"%s",(char*)"NOCONCEPTLIST "); if (D->internalBits & UPPERCASE_MATCH) fprintf(out,(char*)"%s",(char*)"UPPERCASE_MATCH "); int n = 10; FACT* E = GetObjectNondeadHead(D); while (E) { if (E->verb == Mmember && E->flags & START_ONLY) { fprintf(out, (char*)"%s", (char*)"START_ONLY "); } if (E->verb == Mmember && E->flags & END_ONLY) { fprintf(out, (char*)"%s", (char*)"END_ONLY "); } if (E->verb == Mmember && E->flags & (END_ONLY | START_ONLY)) break; if (--n == 0) break; // should have found by now E = GetObjectNext(E); } fprintf(out, (char*)"%s", (char*)"( "); size_t lineSize = 0; NextInferMark(); // write out set members here, dont write out excludes here char* word = AllocateStack(NULL, maxBufferSize); FACT* F = GetObjectNondeadHead(D); if (F) { while (F) { if (build == BUILD1 && !(F->flags & FACTBUILD1)) {;} // defined by earlier level else if (build == BUILD2 && !(F->flags & FACTBUILD2)) {;} // defined by earlier level else if (F->verb == Mmember) // dont use ValidMemberFact, we want from all bots { WORDP EX = Meaning2Word(F->subject); AddBeenHere(EX); if (*EX->word == '"') // change string to std token { strcpy(word,EX->word+1); size_t len = strlen(word); word[len-1] = ' '; // remove trailing quote ForceUnderscores(word); } else if (F->flags & ORIGINAL_ONLY) sprintf(word,(char*)"'%s ",WriteMeaning(F->subject,true)); else sprintf(word,(char*)"%s ",WriteMeaning(F->subject,true)); char* dict = strchr(word+1,'~'); // has a wordnet attribute on it if (*word == '~' || dict ) // concept or full wordnet word reference { if (EX->inferMark != inferMark) SetTriedMeaning(EX,0); EX->inferMark = inferMark; if (dict) { unsigned int which = atoi(dict+1); if (which) // given a meaning index, mark it { uint64 offset = 1ull << which; SetTriedMeaning(EX,GetTriedMeaning(EX) | offset); } } } // write it out- this INVERTS the order now and when read back in, will be reestablished correctly // but dictionary storage locations will be inverted WriteCMore(F, word, out,lineSize); } F = GetObjectNondeadNext(F); } } // now do set excludes F = GetObjectNondeadHead(D); if (F) { while (F) { WORDP EX = Meaning2Word(F->subject); if (build == BUILD1 && !(F->flags & FACTBUILD1)) { ; } // defined by earlier level else if (build == BUILD2 && !(F->flags & FACTBUILD2)) { ; } // defined by earlier level else if (F->verb == Mexclude && *EX->word == '~') // the only relevant facts { sprintf(word, (char*)"!%s ", WriteMeaning(F->subject, true)); WriteCMore(F, word, out, lineSize); } F = GetObjectNondeadNext(F); } } // now write out simple excludes only MEANING MconceptPattern = MakeMeaning(FindWord("conceptpattern")); // does not have to be found F = GetObjectNondeadHead(D); if (F) { while (F) { WORDP E = Meaning2Word(F->subject); if (build == BUILD1 && !(F->flags & FACTBUILD1)) { ; } // defined by earlier level else if (build == BUILD2 && !(F->flags & FACTBUILD2)) { ; } // defined by earlier level else if (F->verb == MconceptPattern) { ; } else if (F->verb == Mexclude && *E->word != '~') // the only relevant facts { AddBeenHere(E); if (*E->word == '"') // change string to std token { strcpy(word, E->word + 1); size_t len = strlen(word); word[len - 1] = ' '; // remove trailing quote ForceUnderscores(word); } else if (F->flags & ORIGINAL_ONLY) sprintf(word, (char*)"!'%s ", WriteMeaning(F->subject, true)); else sprintf(word, (char*)"!%s ", WriteMeaning(F->subject, true)); char* dict = strchr(word + 1, '~'); // has a wordnet attribute on it if (dict) // full wordnet word reference { if (E->inferMark != inferMark) SetTriedMeaning(E, 0); E->inferMark = inferMark; if (dict) { unsigned int which = atoi(dict + 1); if (which) // given a meaning index, mark it { uint64 offset = 1ull << which; SetTriedMeaning(E, GetTriedMeaning(E) | offset); } } } // write it out- this INVERTS the order now and when read back in, will be reestablished correctly // but dictionary storage locations will be inverted WriteCMore(F, word, out, lineSize); KillFact(F); } else KillFact(F); F = GetObjectNondeadNext(F); } } ReleaseStack(word); fprintf(out,(char*)"%s",(char*)")\r\n"); fclose(out); // dont use Fclose seeAllFacts = false; } static void WriteDictionaryChange(FILE* dictout, unsigned int build) { // Note that topic labels (topic.name) and pattern words will not get written FILE* in = NULL; char file[SMALL_WORD_SIZE]; int layer = 0; if ( build == BUILD0) { sprintf(file,(char*)"%s/prebuild0.bin",tmp); in = FopenReadWritten(file); layer = 0; } else if ( build == BUILD1) { sprintf(file,(char*)"%s/prebuild1.bin",tmp); in = FopenReadWritten(file); layer = 1; } if (!in) { ReportBug((char*)"prebuild bin not found") return; } seeAllFacts = true; for (WORDP D = dictionaryBase+1; D < dictionaryFree; ++D) { uint64 oldproperties = 0; uint64 oldflags = 0; bool notPrior = false; if (D < dictionaryPreBuild[layer]) // word preexisted this level, so see if it changed { unsigned int offset = (unsigned int)(D - dictionaryBase); unsigned int xoffset; int result = fread(&xoffset,1,4,in); if (result != 4) // ran out { break; } if (xoffset != offset) (*printer)((char*)"%s",(char*)"Bad dictionary change test\r\n"); fread(&oldproperties,1,8,in); fread(&oldflags,1,8,in); fread(&xoffset,1,4,in); //old internal char junk; fread(&junk,1,1,in); // multiword header info fread(&junk,1,1,in); // 0 marker if (junk != 0) (*printer)((char*)"%s",(char*)"out of dictionary change data2?\r\n"); // multiword header } else notPrior = true; if (!D->word || *D->word == USERVAR_PREFIX) continue; // dont variables if (!strnicmp(D->word, "jo-", 3) || !strnicmp(D->word, "ja-", 3)) continue; // no need to note json composites if (*D->word == '~' && !( D->systemFlags & NOCONCEPTLIST) ) continue; // dont write topic names or concept names, let keywords do that and no variables if (D->internalBits & FUNCTION_BITS) continue; // functions written out in macros file. if (D->internalBits & QUERY_KIND && D->internalBits & build && *D->word != '@' && *D->word != '#' && *D->word != '_') { fprintf(dictout,(char*)"+query %s \"%s\" \r\n",D->word,D->w.userValue); // query defn , not a rename continue; } uint64 prop = D->properties; uint64 flags = D->systemFlags; if ((*D->word == '_' || *D->word == '@' || *D->word == '#' ) && D->internalBits & RENAMED) { if (!notPrior) continue; // written out before } else if (D->properties & AS_IS) { RemoveProperty(D,AS_IS); // fact field value uint64 prop1 = D->properties; prop1 &= -1LL ^ oldproperties; uint64 sys1 = flags; sys1 &= -1LL ^ oldflags; sys1 &= -1LL ^ (NO_EXTENDED_WRITE_FLAGS); // we dont need these- concepts will come from keywords file if ( (build == BUILD0 && D < dictionaryPreBuild[LAYER_0] ) || (build == BUILD1 && D < dictionaryPreBuild[LAYER_1]) || (build == BUILD2 && D < dictionaryPreBuild[LAYER_BOOT])) { if (!prop1 && !sys1) continue; // no need to write out, its in the prior world (though flags might be wrong) } } else if (D->systemFlags & SUBSTITUTE_RECIPIENT) continue; // ignore pattern words, etc EXCEPT when field of a fact else if (D->systemFlags & NO_EXTENDED_WRITE_FLAGS && !GetSubjectNondeadHead(D) && !GetVerbNondeadHead(D) && !GetObjectNondeadHead(D)) continue; // ignore pattern words, etc EXCEPT when field of a fact else if (D->properties & (NOUN_NUMBER|ADJECTIVE_NUMBER) && IsDigit(*D->word)) continue; // no numbers else if (!D->properties && D->internalBits & UPPERCASE_HASH && !D->systemFlags) continue; // boring uppercase pattern word, just not marked as pattern word because its uppercase char* at = D->word - 1; while (IsDigit(*++at)){;} if (*at == 0) continue; // purely a number - not allowed to write it out. not allowed to have unusual flags // only write out changes in flags and properties D->properties &= -1LL ^ oldproperties; // remove the old properties D->systemFlags &= -1 ^ oldflags; // remove the old flags // if the ONLY change is an existing word got made into a concept, dont write it out anymore if (!D->properties && !D->systemFlags && D->internalBits & CONCEPT && D <= dictionaryPreBuild[LAYER_0] ) {;} // preexisting word a concept else if (D->properties || D->systemFlags || notPrior || ((*D->word == '_' || *D->word == '@' || *D->word == '#') && D->internalBits & RENAMED)) // there were changes { fprintf(dictout,(char*)"+ %s ",D->word); if ((*D->word == '_' || (*D->word == '@')) && D->internalBits & RENAMED) fprintf(dictout,(char*)"%d",(unsigned int)D->properties); // rename value else if (*D->word == '#' && D->internalBits & RENAMED) { int64 x = (int64)D->properties; if (D->systemFlags & CONSTANT_IS_NEGATIVE) { fprintf(dictout,(char*)"%c",'-'); x = -x; } #ifdef WIN32 fprintf(dictout,(char*)"%I64d",x); #else fprintf(dictout,(char*)"%lld",x); #endif } else { char flags[MAX_WORD_SIZE]; WriteDictionaryFlags(D, flags); // write the new fprintf(dictout, "%s", flags); } fprintf(dictout,(char*)"%s",(char*)"\r\n"); } D->properties = prop; D->systemFlags = flags; } fclose(in); // dont use Fclose seeAllFacts = false; } static void WriteExtendedFacts(FILE* factout,FILE* dictout,unsigned int build) { if (!factout || !dictout) return; seeAllFacts = true; char* buffer = AllocateBuffer(); bool oldshared = shared; shared = false; char* ptr = WriteUserVariables(buffer,false,true,NULL); shared = oldshared; fwrite(buffer,ptr-buffer,1,factout); FreeBuffer(); WriteDictionaryChange(dictout,build); seeAllFacts = true; if (build == BUILD0) WriteFacts(factout,factsPreBuild[LAYER_0]); else if (build == BUILD1) WriteFacts(factout,factsPreBuild[LAYER_1]); //else if (build == BUILD2) WriteFacts(factout,factsPreBuild[LAYER_BOOT],FACTBUILD2); // factout closed by Writefacts seeAllFacts = false; } static void ClearTopicConcept(WORDP D, uint64 build) { unsigned int k = (ulong_t) build; if ((D->internalBits & (TOPIC | CONCEPT)) & k) RemoveInternalFlag(D,CONCEPT|BUILD0|BUILD1|BUILD2|TOPIC); } static void DumpErrors() { if (errorIndex) Log(ECHOSTDUSERLOG,(char*)"\r\n ERROR SUMMARY: \r\n"); for (unsigned int i = 0; i < errorIndex; ++i) Log(ECHOSTDUSERLOG,(char*)" %s",errors[i]); } static void DumpWarnings() { if (warnIndex) Log(STDUSERLOG,(char*)"\r\nWARNING SUMMARY: \r\n"); for (unsigned int i = 0; i < warnIndex; ++i) { if (strstr(warnings[i],(char*)"is not a known word")) {} else if (strstr(warnings[i],(char*)" changes ")) {} else if (strstr(warnings[i],(char*)"is unknown as a word")) {} else if (strstr(warnings[i],(char*)"in opposite case")){} else if (strstr(warnings[i],(char*)"a function call")){} else if (strstr(warnings[i], (char*)"multiple spellings")) {} else Log(STDUSERLOG,(char*)" %s",warnings[i]); } } static void EmptyVerify(char* name, uint64 junk) { char* x = strstr(name,(char*)"-b"); if (!x) return; char c = (buildID == BUILD0) ? '0' : '1'; if (x[2] == c) unlink(name); } int ReadTopicFiles(char* name,unsigned int build,int spell) { char filename[SMALL_WORD_SIZE]; int resultcode = 0; nospellcheck = false; undefinedCallThreadList = 0; isDescribe = false; *scopeBotName = 0; myBot = 0; globalBotScope = false; if (build == BUILD2) // for dynamic segment, we are allowed full names { strcpy(baseName,name+5); char* dot = strchr(baseName,'.'); *--dot = 0; // remove the 2 at the end char dir[SMALL_WORD_SIZE]; sprintf(dir,"%s/BUILD%s",topic,baseName); MakeDirectory(dir); } else if (build == BUILD1) { strcpy(baseName,(char*)"1"); char dir[200]; sprintf(dir,"%s/BUILD1",topic); MakeDirectory(dir); } else { char dir[200]; sprintf(dir,"%s/BUILD0",topic); MakeDirectory(dir); strcpy(baseName,(char*)"0"); } char* output = testOutput; testOutput = NULL; FILE* in = FopenReadNormal(name); // default was top level chatscript if (!in) { char file[SMALL_WORD_SIZE]; if (*buildfiles) { sprintf(file, (char*)"%s/%s", buildfiles, name); // 2nd default is rawdata itself in = FopenReadNormal(file); } if (!in) { sprintf(file, (char*)"RAWDATA/%s", name); // 2nd default is rawdata itself in = FopenReadNormal(file); } if (!in) { sprintf(file,(char*)"private/%s",name); // 3rd default is private in = FopenReadNormal(file); if (!in) { sprintf(file,(char*)"../%s",name); // 4th default is just above chatscript folder in = FopenReadNormal(file); if (!in) { (*printer)((char*)"%s not found\r\n",name); return 4; } } } } lastDeprecation = 0; hasPlans = 0; char word[MAX_WORD_SIZE]; buildID = build; // build 0 or build 1 *duplicateTopicName = 0; // an example of a repeated topic name found missingFiles = 0; spellCheck = spell; // what spell checking to perform // erase facts and dictionary to appropriate level ClearUserVariables(); if (build == BUILD2) ReturnToAfterLayer(2, false); // layer 2 is boot layer before a user 2 layer. rip dictionary back to start of build (but props and systemflags can be wrong) else if (build == BUILD1) ReturnToAfterLayer(0,true); // rip dictionary back to start of build (but props and systemflags can be wrong) else ReturnDictionaryToWordNet(); WalkDictionary(ClearTopicConcept,build); // remove concept/topic flags from prior defined by this build EraseTopicFiles(build,baseName); char file[SMALL_WORD_SIZE]; sprintf(file,(char*)"%s/missingLabel.txt",topic); remove(file); sprintf(file,(char*)"%s/missingSets.txt",topic); remove(file); WalkDirectory((char*)"VERIFY",EmptyVerify,0,false); // clear verification of this level compiling = true; errorIndex = warnIndex = hasWarnings = hasErrors = 0; substitutes = cases = functionCall = badword = 0; sprintf(filename,(char*)"%s/BUILD%s/map%s.txt",topic,baseName,baseName); mapFile = FopenUTF8Write(filename); fprintf(mapFile, "\r\n"); // so bytemark not with data fprintf(mapFile, "# file: 0 full_path_to_file optional_botid\r\n"); // so bytemark not with data fprintf(mapFile, "# macro: start_line_in_file name_of_macro optional_botid (definition of user function)\r\n"); // so bytemark not with data fprintf(mapFile, "# line: start_line_in_file offset_byte_in_script (action unit in output) \r\n"); // so bytemark not with data fprintf(mapFile, "# concept: start_line_in_file name_of_concept optional_botid (concept definition) \r\n"); // so bytemark not with data fprintf(mapFile, "# topic: start_line_in_file name_of_topic optional_botid (topic definition) \r\n"); // so bytemark not with data fprintf(mapFile, "# rule: start_line_in_file full_rule_tag_with_possible_label rule_kind (rule definition) \r\n"); // so bytemark not with data fprintf(mapFile, "# Complexity of name_of_macro complexity_metric (complexity metric for function) \r\n"); // so bytemark not with data fprintf(mapFile, "# Complexity of rule full_rule_tag_with_possible_label rule_kind complexity_metric (complexity metric for rule) \r\n"); // so bytemark not with data fprintf(mapFile, "# bot: name_of_macro_it_happens_in botid (possible bot macro) \r\n"); // so bytemark not with data fprintf(mapFile, "\r\n"); // so bytemark not with data AllocateOutputBuffer(); // init the script output file sprintf(filename,(char*)"%s/BUILD%s/script%s.txt",topic,baseName,baseName); FILE* out = FopenUTF8Write(filename); if (strlen(name) > 100) name[99] = 0; if (!strnicmp(name,(char*)"files",5)) name += 5; // dont need the prefix char* at = strchr(name,'.'); *at = 0; fprintf(out,(char*)"0 %s %s %s\r\n",GetMyTime(time(0)),name,version); // reserve 5-digit count for number of topics + timestamp (AFTER BOM) fclose(out); // dont use fclose uint64 oldtokenControl = tokenControl; tokenControl = 0; topicCount = 0; StartScriptCompiler(); // store known pattern words in pattern file that we want to recognize (not spellcorrect on input) sprintf(filename, (char*)"%s/BUILD%s/patternWords%s.txt", topic, baseName, baseName); patternFile = FopenUTF8Write(filename); if (!patternFile) { (*printer)((char*)"Unable to create %s? Make sure this directory exists and is writable.\r\n", filename); return 4; } // read file list to service, may also have bot: commands while (ReadALine(readBuffer,in) >= 0) { char* at = ReadCompiledWord(readBuffer,word); if (*word == '#' || !*word) continue; if (!stricmp(word,(char*)"stop") || !stricmp(word,(char*)"exit")) break; // fast abort if (!stricmp(word,"bot:")) { globalBotScope = true; // lasts til changed ReadBot(at); continue; } size_t len = strlen(word); char output[MAX_WORD_SIZE]; if (word[len-1] == '/') // directory request { Log(STDUSERLOG,(char*)"\r\n>>Reading folder %s\r\n",word); bool recurse = word[len - 2] == '/'; if (recurse) word[len - 2] = 0; WalkDirectory(word,ReadTopicFile,build,recurse); // read all files in folder (top level) Log(STDUSERLOG,(char*)"\r\n<<end folder %s\r\n",word); } else if (*word == ':' && word[1]) DoCommand(readBuffer,output); // testing command else ReadTopicFile(word,build|FROM_FILE); // was explicitly named } if (in) fclose(in); if (patternFile) { fclose(patternFile); patternFile = NULL; } fclose(mapFile); EndScriptCompiler(); StartFile((char*)"Post compilation Verification"); nospellcheck = false; // verify errors across all files DoubleCheckSetOrTopic(); // prove all sets/topics he used were defined DoubleCheckReuse(); // see if jump labels are defined DoubleCheckFunctionDefinition(); if (*duplicateTopicName) WARNSCRIPT((char*)"At least one duplicate topic name, i.e., %s, which may intended if bot restrictions differ.\r\n",duplicateTopicName) WalkDictionary(ClearBeenHere,0); // write out compiled data // write how many topics were found (for when we preload during normal startups) sprintf(filename,(char*)"%s/BUILD%s/script%s.txt",topic,baseName,baseName); out = FopenUTF8WriteAppend(filename,(char*)"rb+"); if (out) { fseek(out,0,SEEK_SET); sprintf(word,(char*)"%05d",topicCount); unsigned char bom[3]; bom[0] = 0xEF; bom[1] = 0xBB; bom[2] = 0xBF; fwrite(bom,1,3,out); fwrite(word,1,5 * sizeof(char),out); fclose(out); // dont use Fclose } if (hasPlans) { sprintf(filename,(char*)"%s/BUILD%s/plans%s.txt",topic,baseName,baseName); out = FopenUTF8WriteAppend(filename,(char*)"rb+"); if (out) { char word[MAX_WORD_SIZE]; fseek(out,0,SEEK_SET); sprintf(word,(char*)"%05d",hasPlans); fwrite(word,1,5 * sizeof(char),out); fclose(out); // dont use FClose } } // we delay writing out keywords til now, allowing multiple accumulation across tables and concepts WalkDictionary(WriteConcepts,build); WalkDictionary(ClearBeenHere,0); // dump variables, dictionary changes, topic facts sprintf(filename,(char*)"%s/BUILD%s/facts%s.txt",topic,baseName,baseName); char filename1[MAX_WORD_SIZE]; sprintf(filename1,(char*)"%s/BUILD%s/dict%s.txt",topic,baseName,baseName); FILE* dictout = FopenUTF8Write(filename1); FILE* factout = FopenUTF8Write(filename); WriteExtendedFacts(factout,dictout, build); fclose(dictout); // dont use FClose // FClose(factout); closed from within writeextendedfacts // cleanup buildID = 0; numberOfTopics = 0; tokenControl = oldtokenControl; currentRuleOutputBase = currentOutputBase = NULL; FreeOutputBuffer(); compiling = false; jumpIndex = 0; testOutput = output; // allow summary to go out the server if (hasErrors) { EraseTopicFiles(build,baseName); DumpErrors(); if (missingFiles) Log(ECHOSTDUSERLOG,(char*)"%d topic files were missing.\r\n",missingFiles); Log(ECHOSTDUSERLOG,(char*)"\r\n%d errors - press Enter to quit. Then fix and try again.\r\n",hasErrors); if (!server && !commandLineCompile) ReadALine(readBuffer,stdin); resultcode = 4; // error } else if (hasWarnings) { DumpWarnings(); if (missingFiles) Log(STDUSERLOG,(char*)"%d topic files were missing.\r\n",missingFiles); Log(STDUSERLOG,(char*)"%d serious warnings, %d function warnings, %d spelling warnings, %d case warnings, %d substitution warnings\r\n ",hasWarnings-badword-substitutes-cases,functionCall,badword,cases,substitutes); } else { if (missingFiles) Log(ECHOSTDUSERLOG,(char*)"%d topic files were missing.\r\n",missingFiles); Log(ECHOSTDUSERLOG,(char*)"No errors or warnings\r\n\r\n"); } ReturnDictionaryToWordNet(); echo = true; Log(ECHOSTDUSERLOG,(char*)"\r\n\r\nFinished compile\r\n\r\n"); return resultcode; } char* CompileString(char* ptr) // incoming is: ^"xxx" or ^'xxxx' { char tmp[MAX_WORD_SIZE * 2]; strcpy(tmp,ptr); // protect copy from multiple readcalls size_t len = strlen(tmp); if (tmp[len-1] != '"' && tmp[len-1] != '\'') BADSCRIPT((char*)"STRING-1 String not terminated with doublequote %s\r\n",tmp) tmp[len-1] = 0; // remove trailing quote // flip the FUNCTION marker inside the string static char data[MAX_WORD_SIZE * 2]; char* pack = data; *pack++ = '"'; *pack++ = FUNCTIONSTRING; *pack++ = ':'; // a internal marker that is has in fact been compiled - otherwise it is a format string whose spaces count but cant fully execute if (tmp[2] == '(') ReadPattern(tmp+2,NULL,pack,false,false); // incoming is: ^"(xxx" else ReadOutput(false,false,tmp+2,NULL,pack,NULL,NULL,NULL); TrimSpaces(data,false); len = strlen(data); data[len] = '"'; // put back closing quote data[len+1] = 0; return data; } #endif #endif
40.12378
446
0.596059
[ "object" ]
f67989b8c3e80c32ec90358bbf4ad9ac868b3d4c
1,027
cpp
C++
t1/main.cpp
vinthony/Learning-Graphics
9c20c8f1d9378a7fb2e9be7eef8042a9c6d4a2be
[ "MIT" ]
null
null
null
t1/main.cpp
vinthony/Learning-Graphics
9c20c8f1d9378a7fb2e9be7eef8042a9c6d4a2be
[ "MIT" ]
null
null
null
t1/main.cpp
vinthony/Learning-Graphics
9c20c8f1d9378a7fb2e9be7eef8042a9c6d4a2be
[ "MIT" ]
null
null
null
#include <iostream> #include <GL/glew.h> #include <GLUT/GLUT.h> #include "math_3d.h" void render(){ Vector3f Vertices[1]; Vertices[0] = Vector3f(0.0f, 0.0f, 0.0f); GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_POINTS, 0, 1); glDisableVertexAttribArray(0); glutSwapBuffers(); } int main (int argc,char ** argv) { glutInit(&argc, argv); glutInitWindowSize(800,600); glutInitWindowPosition(100, 100); glutCreateWindow("t2"); // glutDisplayFunc(void); GLenum res = glewInit(); if(res != GLEW_OK) { fprintf(stderr,"ERROR: %s\n",glewGetErrorString(res)); return 1; } glutDisplayFunc(render); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glutMainLoop(); }
22.326087
78
0.636806
[ "render" ]
f67bd84c0bd1704f047d40c1b12e78297a723da2
2,889
cpp
C++
src/xpcc/math/geometry/test/point_set_2d_test.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
5
2016-02-06T14:57:35.000Z
2018-01-02T23:34:18.000Z
src/xpcc/math/geometry/test/point_set_2d_test.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
null
null
null
src/xpcc/math/geometry/test/point_set_2d_test.cpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
1
2020-04-19T13:16:31.000Z
2020-04-19T13:16:31.000Z
// coding: utf-8 // ---------------------------------------------------------------------------- /* Copyright (c) 2009, Roboterclub Aachen e.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // ---------------------------------------------------------------------------- #include <xpcc/math/geometry/point_set_2d.hpp> #include "point_set_2d_test.hpp" void PointSet2DTest::testConstructor() { xpcc::PointSet2D<int16_t> set(5); TEST_ASSERT_EQUALS(set.getNumberOfPoints(), 0U); } void PointSet2DTest::testAppendAndAccess() { xpcc::PointSet2D<int16_t> set(5); set.append(xpcc::Vector2i(10, 20)); TEST_ASSERT_EQUALS(set.getNumberOfPoints(), 1U); TEST_ASSERT_EQUALS(set[0], xpcc::Vector2i(10, 20)); set.append(xpcc::Vector2i(30, 40)); TEST_ASSERT_EQUALS(set.getNumberOfPoints(), 2U); TEST_ASSERT_EQUALS(set[0], xpcc::Vector2i(10, 20)); TEST_ASSERT_EQUALS(set[1], xpcc::Vector2i(30, 40)); set[0] = xpcc::Vector2i(50, 60); TEST_ASSERT_EQUALS(set[0], xpcc::Vector2i(50, 60)); } void PointSet2DTest::testIterator() { xpcc::PointSet2D<int16_t> set(3); set.append(xpcc::Vector2i(10, 20)); set.append(xpcc::Vector2i(20, 30)); set.append(xpcc::Vector2i(30, 40)); xpcc::PointSet2D<int16_t>::const_iterator it; int count; for (it = set.begin(), count = 0; it != set.end(); ++it, ++count) { TEST_ASSERT_EQUALS(set[count], (*it)); } TEST_ASSERT_EQUALS(count, 3); }
35.666667
79
0.689166
[ "geometry" ]
f67ee22fe94ee780cf834879759af69eccd3f802
10,974
cc
C++
c++/src/program.cc
alexhsamuel/apsis
7a038a39e5002637b60f73147728b4cc53692da3
[ "BSD-3-Clause" ]
1
2021-06-03T15:35:31.000Z
2021-06-03T15:35:31.000Z
c++/src/program.cc
alexhsamuel/apsis
7a038a39e5002637b60f73147728b4cc53692da3
[ "BSD-3-Clause" ]
93
2018-08-17T20:32:09.000Z
2022-03-23T17:34:37.000Z
c++/src/program.cc
alexhsamuel/apsis
7a038a39e5002637b60f73147728b4cc53692da3
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <cassert> #include <iostream> #include "file.hh" #include "filename.hh" #include "json.hh" #include "program.hh" #include "xsys.hh" using namespace alxs::json; using std::string; using std::unique_ptr; namespace alxs { namespace run { //------------------------------------------------------------------------------ void Result::print( std::ostream& os) const { os << "Result["; bool first = true; for (auto iter : more_) { if (first) first = false; else os << ", "; os << iter.first << "=" << iter.second; } os << "]"; } class repeat : public Printable { public: repeat(char character, size_t num) : character_(character), num_(num) {} virtual void print( std::ostream& os) const { for (size_t i = 0; i < num_; ++i) os << character_; } private: char character_; size_t num_; }; void Result::pretty_print( std::ostream& os) const { os << "Result:\n"; for (auto i : more_) if (i.second.find('\n') == string::npos) os << "- " << i.first << " = " << i.second << '\n'; else os << "- " << i.first << ' ' << repeat('-', 77 - i.first.length()) << '\n' << i.second << '\n' << repeat('-', 80) << '\n'; } Json Result::to_json() const { using namespace json; Json json = Json::OBJ; for (auto iter : more_) json[iter.first] = iter.second; return json; } string Result::get( string const& name) const { auto iter = more_.find(name); if (iter == more_.end()) throw NameError(name); else return iter->second; } //------------------------------------------------------------------------------ EnvSpec::EnvSpec() : keep_all_(true) { } json::Json EnvSpec::to_json() const { Json json = Json::OBJ; if (keep_all_) json["keep"] = true; else if (keep_.size() == 0) json["keep"] = false; else { Json keep = Json::ARR; for (auto var : keep_) keep[keep.size()] = var; json["keep"] = std::move(keep); } Json unset = Json::ARR; for (auto var : unset_) unset[unset.size()] = var; json["unset"] = std::move(unset); Json set = Json::OBJ; for (auto var : set_) set[var.first] = var.second; json["set"] = std::move(set); return json; } EnvSpec EnvSpec::from_json( Json const& json) { EnvSpec spec; if (json.has("keep")) { Json const& keep = json["keep"]; if (keep.get_type() == Json::TRU || keep.get_type() == Json::FAL) spec.keep_all_ = keep.get_bool(); else { spec.keep_all_ = false; for (auto const& name : keep.get_arr()) spec.keep_.push_back(name.get_str()); } } if (json.has("unset")) for (auto const& name : json["unset"].get_arr()) spec.unset_.push_back(name.get_str()); if (json.has("set")) for (auto const& ent : json["set"].get_obj()) spec.set_[ent.first] = ent.second.get_str(); return spec; } unique_ptr<sys::Environment> EnvSpec::build() const { unique_ptr<sys::Environment> envp(new sys::Environment); sys::Environment& env = *envp.get(); // Possibly, keep variables from the process environment. if (keep_all_) // Keep all variables. env.get_proc_env(); else if (keep_.size() > 0) { // Keep names variables only. sys::Environment proc_env; proc_env.get_proc_env(); for (string const& name : keep_) { // Does this name exist in the process environment? auto find = proc_env.find(name); if (find != end(proc_env)) // Yes. Copy it over. env[name] = find->second; } } // Unset named variables. for (string const& name : unset_) env.erase(name); // Explicitly set variables. for (auto const& ent : set_) env[ent.first] = ent.second; return envp; } //------------------------------------------------------------------------------ FdHandlerSpec::FdHandlerSpec( string const& type) : type_(type), from_fd_(1), filename_("/dev/null"), mode_(O_RDONLY) { } Json FdHandlerSpec::to_json() const { using namespace json; Json json = Json::OBJ; json["type"] = type_; if (type_ == "dup") json["from_fd"] = from_fd_; else if (type_ == "file") { // FIXME: Stupid. string filename = filename_; json["filename"] = filename; json["mode"] = fs::mode_as_str(mode_); } return json; } unique_ptr<FdHandlerSpec> FdHandlerSpec::from_json( Json const& json) { unique_ptr<FdHandlerSpec> spec{new FdHandlerSpec}; spec->type_ = json.get_type() == Json::STR ? json.get_str() : json["type"].get_str(); if ( spec->type_ == "leave" || spec->type_ == "close" || spec->type_ == "null" || spec->type_ == "capture") ; else if (spec->type_ == "dup") spec->from_fd_ = json["from_fd"].get_int(); else if (spec->type_ == "file") { spec->filename_ = fs::Filename(json["filename"].get_str()); spec->mode_ = json.has("mode") ? fs::mode_from_str(json["mode"].get_str()) : (O_RDWR | O_CREAT); } else throw TypeError(spec->type_); return spec; } unique_ptr<FdHandler> FdHandlerSpec::build( int fd) const { if (type_ == "leave") return unique_ptr<FdHandler>(new LeaveFdHandler(fd)); else if (type_ == "close") return unique_ptr<FdHandler>(new CloseFdHandler(fd)); else if (type_ == "null") return unique_ptr<FdHandler>(new NullFdHandler(fd)); else if (type_ == "capture") return unique_ptr<FdHandler>(new CaptureFdHandler(fd)); else if (type_ == "dup") return unique_ptr<FdHandler>(new DupFdHandler(fd, from_fd_)); else if (type_ == "file") return unique_ptr<FdHandler>(new FileFdHandler(fd, filename_, mode_)); else // FIXME assert(false); } //------------------------------------------------------------------------------ unique_ptr<ProgramSpec> ProgramSpec::from_json( Json const& json) { string const type = json["type"].get_str(); if (type == ProcessProgramSpec::JSON_TYPE_NAME) { unique_ptr<ProcessProgramSpec> spec = ProcessProgramSpec::from_json(json); return unique_ptr<ProgramSpec>((ProgramSpec*) spec.release()); } else { // FIXME assert(false); return nullptr; } } //------------------------------------------------------------------------------ ProcessProgram::ProcessProgram( Spec const& spec) : waited_(false), stdin_ (spec.stdin_ .build(STDIN_FILENO)), stdout_(spec.stdout_.build(STDOUT_FILENO)), stderr_(spec.stderr_.build(STDERR_FILENO)) { pid_t const child_pid = xfork(); if (child_pid == 0) { // Child process. // Construct the argument vector. char const* argv[spec.args_.size() + 2]; size_t i = 0; // The first argument conventionally is the executable name. // FIXME: Support overriding this. argv[i++] = spec.executable_.c_str(); for (auto arg : spec.args_) argv[i++] = arg.c_str(); // NULL-terminate it. argv[i++] = nullptr; // Construct the environment. unique_ptr<sys::Environment> env = spec.env_.build(); sys::Environment::Buffer env_buffer(*env); char* const* const envp = const_cast<char* const*>(env_buffer.get()); // Start file descriptor handling. stdin_ ->start(true); stdin_ ->close(); stdout_->start(true); stdout_->close(); stderr_->start(true); stderr_->close(); // Invoke the executable. // FIXME: Handle failure. xexecve(spec.executable_.c_str(), const_cast<char* const*>(argv), envp); } else // Parent process. pid_ = child_pid; } bool ProcessProgram::is_done() const { siginfo_t siginfo; siginfo.si_pid = 0; // FIXME: Check for stopped / continued? xwaitid(P_PID, pid_, & siginfo, WEXITED | WNOHANG | WNOWAIT); return siginfo.si_pid > 0; } unique_ptr<Result> ProcessProgram::get_result() { if (! waited_) { assert(is_done()); usage_.ru_maxrss = 0; (void) xwait4(pid_, &status_, WNOHANG, &usage_); waited_ = true; } unique_ptr<Result> result(new Result); result->set("status", status_); result->set("pid", pid_); // If we captured stdout or stderr, add the captured texts. auto stdout_capture = dynamic_cast<CaptureFdHandler*>(stdout_.get()); if (stdout_capture != nullptr) result->set("stdout", stdout_capture->get()); auto stderr_capture = dynamic_cast<CaptureFdHandler*>(stderr_.get()); if (stderr_capture != nullptr) result->set("stderr", stderr_capture->get()); // Record process usage statistics. result->set("user_cpu_time", to_string(usage_.ru_utime)); result->set("system_cpu_time", to_string(usage_.ru_stime)); // FIXME: Is this right? Is this perhaps the pre-fork RSS? result->set("max_rss", to_string(usage_.ru_maxrss * 1024)); // FIXME: Add start, end time and elapsed time. return result; } ProcessProgramSpec::ProcessProgramSpec() : executable_("/bin/true"), args_(), stdin_ (), stdout_(), stderr_() { } unique_ptr<ProcessProgram> ProcessProgramSpec::start() const { return unique_ptr<ProcessProgram>(new ProcessProgram(*this)); } Json ProcessProgramSpec::to_json() const { using namespace json; Json json = Json::OBJ; json["type"] = JSON_TYPE_NAME; json["executable"] = executable_; Json arr = Json::ARR; for (auto arg : args_) arr[arr.size()] = arg; json["args"] = std::move(arr); json["env"] = env_.to_json(); json["stdin" ] = stdin_ .to_json(); json["stdout"] = stdout_.to_json(); json["stderr"] = stderr_.to_json(); return json; } string const ProcessProgramSpec::JSON_TYPE_NAME = "ProcessProgram"; unique_ptr<ProcessProgramSpec> ProcessProgramSpec::from_json( Json const& json) { using namespace json; unique_ptr<ProcessProgramSpec> spec(new ProcessProgramSpec); spec->executable_ = json["executable"].get_str(); for (auto const& arg : json["args"].get_arr()) spec->args_.emplace_back(arg.get_str()); if (json.has("env")) spec->env_ = EnvSpec::from_json(json["env"]); if (json.has("stdin")) spec->stdin_ = *FdHandlerSpec::from_json(json["stdin" ]); if (json.has("stdout")) spec->stdout_ = *FdHandlerSpec::from_json(json["stdout"]); if (json.has("stderr")) spec->stderr_ = *FdHandlerSpec::from_json(json["stderr"]); return spec; } //------------------------------------------------------------------------------ void sleep( double time) { assert(time >= 0); struct timespec ts; ts.tv_sec = (time_t) time; ts.tv_nsec = ((long) (time * 1e+9)) % 1000000000; while (true) { int const rval = nanosleep(& ts, & ts); if (rval == 0) break; else if (rval == -1) if (errno == EINTR) continue; else throw SystemError("nanosleep"); else assert(false); } } void wait( Program& prog) { // FIXME: This is stupid. double wait_time = 0.001; double const wait_time_max = 0.1; while (! prog.is_done()) sleep(wait_time = std::min(wait_time_max, wait_time * 1.01)); } } // namespace run } // namespace alxs
21.904192
100
0.597321
[ "vector" ]
f6812b0daa9348865383bd160d68d70c38a87348
3,376
cpp
C++
search/ranking_info.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
search/ranking_info.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
search/ranking_info.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
#include "search/ranking_info.hpp" #include "std/cmath.hpp" #include "std/iomanip.hpp" #include "std/limits.hpp" #include "std/sstream.hpp" namespace search { namespace { // See search/search_quality/scoring_model.py for details. In short, // these coeffs correspond to coeffs in a linear model. double const kDistanceToPivot = -1.0000000; double const kRank = 0.5238890; double const kFalseCats = -0.7319971; double const kErrorsMade = -0.0238639; double const kNameScore[NameScore::NAME_SCORE_COUNT] = { -0.1683931 /* Zero */, 0.0268117 /* Substring */, 0.0599575 /* Prefix */, 0.0816240 /* Full Match */ }; double const kType[Model::TYPE_COUNT] = { -0.4322325 /* POI */, -0.4322325 /* Building */, -0.3823704 /* Street */, -0.3747346 /* Unclassified */, -0.4453585 /* Village */, 0.3900264 /* City */, 0.5397572 /* State */, 0.7049124 /* Country */ }; double TransformDistance(double distance) { return min(distance, RankingInfo::kMaxDistMeters) / RankingInfo::kMaxDistMeters; } } // namespace // static double const RankingInfo::kMaxDistMeters = 2e6; // static void RankingInfo::PrintCSVHeader(ostream & os) { os << "DistanceToPivot" << ",Rank" << ",NameScore" << ",ErrorsMade" << ",SearchType" << ",PureCats" << ",FalseCats"; } string DebugPrint(RankingInfo const & info) { ostringstream os; os << "RankingInfo ["; os << "m_distanceToPivot:" << info.m_distanceToPivot << ","; os << "m_rank:" << static_cast<int>(info.m_rank) << ","; os << "m_nameScore:" << DebugPrint(info.m_nameScore) << ","; os << "m_errorsMade:" << DebugPrint(info.m_errorsMade) << ","; os << "m_type:" << DebugPrint(info.m_type) << ","; os << "m_pureCats:" << info.m_pureCats << ","; os << "m_falseCats:" << info.m_falseCats; os << "]"; return os.str(); } void RankingInfo::ToCSV(ostream & os) const { os << fixed; os << m_distanceToPivot << ","; os << static_cast<int>(m_rank) << ","; os << DebugPrint(m_nameScore) << ","; os << GetErrorsMade() << ","; os << DebugPrint(m_type) << ","; os << m_pureCats << ","; os << m_falseCats; } double RankingInfo::GetLinearModelRank() const { // NOTE: this code must be consistent with scoring_model.py. Keep // this in mind when you're going to change scoring_model.py or this // code. We're working on automatic rank calculation code generator // integrated in the build system. double const distanceToPivot = TransformDistance(m_distanceToPivot); double const rank = static_cast<double>(m_rank) / numeric_limits<uint8_t>::max(); auto nameScore = m_nameScore; if (m_pureCats || m_falseCats) { // If the feature was matched only by categorial tokens, it's // better for ranking to set name score to zero. For example, // when we're looking for a "cafe", cafes "Cafe Pushkin" and // "Lermontov" both match to the request, but must be ranked in // accordance to their distances to the user position or viewport, // in spite of "Cafe Pushkin" has a non-zero name rank. nameScore = NAME_SCORE_ZERO; } return kDistanceToPivot * distanceToPivot + kRank * rank + kNameScore[nameScore] + kErrorsMade * GetErrorsMade() + kType[m_type] + m_falseCats * kFalseCats; } size_t RankingInfo::GetErrorsMade() const { return m_errorsMade.IsValid() ? m_errorsMade.m_errorsMade : 0; } } // namespace search
29.876106
84
0.666765
[ "model" ]
f6836556c68fca0568cb85ccfa366a1ef4242b6d
3,517
cpp
C++
leetcode/convert_sorted_list_to_binary_search_tree/main.cpp
yylzl/CodingMyWorld
a255e5c1fe3c2c5f0ffce17539b5b5b667511448
[ "Apache-2.0" ]
null
null
null
leetcode/convert_sorted_list_to_binary_search_tree/main.cpp
yylzl/CodingMyWorld
a255e5c1fe3c2c5f0ffce17539b5b5b667511448
[ "Apache-2.0" ]
null
null
null
leetcode/convert_sorted_list_to_binary_search_tree/main.cpp
yylzl/CodingMyWorld
a255e5c1fe3c2c5f0ffce17539b5b5b667511448
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdint> #include <climits> #include <queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: #if 0 TreeNode *sortedListToBST(vector<int> &l, int start, int end) { if(start<=end) { int mid = (start+end)/2; TreeNode *node = new TreeNode(l[mid]); node->left = sortedListToBST(l, start, mid-1); node->right = sortedListToBST(l, mid+1, end); return node; } return NULL; } TreeNode* sortedListToBST(ListNode* head) { vector<int> l; while(head) { l.push_back(head->val); head = head->next; } TreeNode *r = sortedListToBST(l, 0, l.size()-1); return r; } #endif TreeNode *sortedListToBST(ListNode *head, ListNode *tail) { if(head==NULL) { return NULL; } ListNode *fast = head; ListNode *slow = head; while(fast!=tail && fast->next!=tail) { slow = slow->next; fast = fast->next->next; } TreeNode *n = new TreeNode(slow->val); if(head!=slow) { n->left = sortedListToBST(head, slow); } if(slow->next!=tail) { n->right = sortedListToBST(slow->next, tail); } return n; } TreeNode* sortedListToBST(ListNode* head) { TreeNode *r = sortedListToBST(head, NULL); return r; } }; void dumpTree(TreeNode *root) { if(root==NULL) { cout<<"null"<<endl; return; } queue<TreeNode *> q; TreeNode *sentinel = new TreeNode(0); q.push(root); q.push(sentinel); TreeNode *n; while(!q.empty()) { n = q.front(); q.pop(); if(n==sentinel) { if(!q.empty()) { q.push(sentinel); } cout<<endl; continue; } if(n) { cout<<n->val<<" "; /*if(n->left==NULL&&n->right==NULL) { continue; }*/ q.push(n->left); q.push(n->right); } else { cout<<"# "; } } } int main(int argc, char *argv[]) { Solution *S = new Solution(); TreeNode *root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->right->right = new TreeNode(4); dumpTree(root); ListNode *head = new ListNode(1); ListNode *p = head; p->next = new ListNode(2); p = p->next; p->next = new ListNode(3); p = p->next; p->next = new ListNode(4); p = p->next; p->next = new ListNode(5); p = p->next; p->next = new ListNode(6); p = p->next; p->next = new ListNode(7); p = p->next; p->next = new ListNode(8); p = p->next; p->next = new ListNode(9); p = p->next; p->next = new ListNode(10); TreeNode *ret = S->sortedListToBST(head); dumpTree(ret); return 0; }
21.98125
69
0.449531
[ "vector" ]
f686097ec3aee3604755821b76864f536627c8d4
21,055
cc
C++
chrome/browser/chromeos/dbus/bluetooth_agent_service_provider.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
chrome/browser/chromeos/dbus/bluetooth_agent_service_provider.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
chrome/browser/chromeos/dbus/bluetooth_agent_service_provider.cc
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/dbus/bluetooth_agent_service_provider.h" #include <string> #include "base/bind.h" #include "base/chromeos/chromeos_version.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/threading/platform_thread.h" #include "dbus/bus.h" #include "dbus/exported_object.h" #include "dbus/message.h" #include "dbus/object_path.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace { // Constants used by BlueZ for the ConfirmModeChange method. const char kModeOff[] = "off"; const char kModeConnectable[] = "connectable"; const char kModeDiscoverable[] = "discoverable"; } // namespace namespace chromeos { // The BluetoothAgentServiceProvider implementation used in production. class BluetoothAgentServiceProviderImpl : public BluetoothAgentServiceProvider { public: BluetoothAgentServiceProviderImpl(dbus::Bus* bus, const dbus::ObjectPath& object_path, Delegate* delegate) : weak_ptr_factory_(this), origin_thread_id_(base::PlatformThread::CurrentId()), bus_(bus), delegate_(delegate), object_path_(object_path) { DVLOG(1) << "Creating BluetoothAdapterClientImpl for " << object_path.value(); exported_object_ = bus_->GetExportedObject(object_path_); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kRelease, base::Bind(&BluetoothAgentServiceProviderImpl::Release, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAgentServiceProviderImpl::ReleaseExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kRequestPinCode, base::Bind(&BluetoothAgentServiceProviderImpl::RequestPinCode, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAgentServiceProviderImpl::RequestPinCodeExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kRequestPasskey, base::Bind(&BluetoothAgentServiceProviderImpl::RequestPasskey, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAgentServiceProviderImpl::RequestPasskeyExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kDisplayPinCode, base::Bind(&BluetoothAgentServiceProviderImpl::DisplayPinCode, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAgentServiceProviderImpl::DisplayPinCodeExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kDisplayPasskey, base::Bind(&BluetoothAgentServiceProviderImpl::DisplayPasskey, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAgentServiceProviderImpl::DisplayPasskeyExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kRequestConfirmation, base::Bind(&BluetoothAgentServiceProviderImpl::RequestConfirmation, weak_ptr_factory_.GetWeakPtr()), base::Bind( &BluetoothAgentServiceProviderImpl::RequestConfirmationExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kAuthorize, base::Bind(&BluetoothAgentServiceProviderImpl::Authorize, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAgentServiceProviderImpl::AuthorizeExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kConfirmModeChange, base::Bind(&BluetoothAgentServiceProviderImpl::ConfirmModeChange, weak_ptr_factory_.GetWeakPtr()), base::Bind( &BluetoothAgentServiceProviderImpl::ConfirmModeChangeExported, weak_ptr_factory_.GetWeakPtr())); exported_object_->ExportMethod( bluetooth_agent::kBluetoothAgentInterface, bluetooth_agent::kCancel, base::Bind(&BluetoothAgentServiceProviderImpl::Cancel, weak_ptr_factory_.GetWeakPtr()), base::Bind(&BluetoothAgentServiceProviderImpl::CancelExported, weak_ptr_factory_.GetWeakPtr())); } virtual ~BluetoothAgentServiceProviderImpl() { // Unregister the object path so we can reuse with a new agent. bus_->UnregisterExportedObject(object_path_); } private: // Returns true if the current thread is on the origin thread. bool OnOriginThread() { return base::PlatformThread::CurrentId() == origin_thread_id_; } // Called by dbus:: when the agent is unregistered from the Bluetooth // daemon, generally at the end of a pairing request. void Release(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); delegate_->Release(); dbus::Response* response = dbus::Response::FromMethodCall(method_call); response_sender.Run(response); } // Called by dbus:: when the Release method is exported. void ReleaseExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the Bluetooth daemon requires a PIN Code for // device authentication. void RequestPinCode(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; if (!reader.PopObjectPath(&device_path)) { LOG(WARNING) << "RequestPinCode called with incorrect paramters: " << method_call->ToString(); return; } Delegate::PinCodeCallback callback = base::Bind( &BluetoothAgentServiceProviderImpl::OnPinCode, weak_ptr_factory_.GetWeakPtr(), method_call, response_sender); delegate_->RequestPinCode(device_path, callback); } // Called by dbus:: when the RequestPinCode method is exported. void RequestPinCodeExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the Bluetooth daemon requires a Passkey for // device authentication. void RequestPasskey(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; if (!reader.PopObjectPath(&device_path)) { LOG(WARNING) << "RequestPasskey called with incorrect paramters: " << method_call->ToString(); return; } Delegate::PasskeyCallback callback = base::Bind( &BluetoothAgentServiceProviderImpl::OnPasskey, weak_ptr_factory_.GetWeakPtr(), method_call, response_sender); delegate_->RequestPasskey(device_path, callback); } // Called by dbus:: when the RequestPasskey method is exported. void RequestPasskeyExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the Bluetooth daemon requires that the user // enter a PIN Code into the remote device so that it may be // authenticated. void DisplayPinCode(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; std::string pincode; if (!reader.PopObjectPath(&device_path) || !reader.PopString(&pincode)) { LOG(WARNING) << "DisplayPinCode called with incorrect paramters: " << method_call->ToString(); return; } delegate_->DisplayPinCode(device_path, pincode); dbus::Response* response = dbus::Response::FromMethodCall(method_call); response_sender.Run(response); } // Called by dbus:: when the DisplayPinCode method is exported. void DisplayPinCodeExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the Bluetooth daemon requires that the user // enter a Passkey into the remote device so that it may be // authenticated. void DisplayPasskey(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; uint32 passkey; if (!reader.PopObjectPath(&device_path) || !reader.PopUint32(&passkey)) { LOG(WARNING) << "DisplayPasskey called with incorrect paramters: " << method_call->ToString(); return; } delegate_->DisplayPasskey(device_path, passkey); dbus::Response* response = dbus::Response::FromMethodCall(method_call); response_sender.Run(response); } // Called by dbus:: when the DisplayPasskey method is exported. void DisplayPasskeyExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the Bluetooth daemon requires that the user // confirm that a Passkey is displayed on the screen of the remote // device so that it may be authenticated. void RequestConfirmation( dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; uint32 passkey; if (!reader.PopObjectPath(&device_path) || !reader.PopUint32(&passkey)) { LOG(WARNING) << "RequestConfirmation called with incorrect paramters: " << method_call->ToString(); return; } Delegate::ConfirmationCallback callback = base::Bind( &BluetoothAgentServiceProviderImpl::OnConfirmation, weak_ptr_factory_.GetWeakPtr(), method_call, response_sender); delegate_->RequestConfirmation(device_path, passkey, callback); } // Called by dbus:: when the RequestConfirmation method is exported. void RequestConfirmationExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the Bluetooth daemon requires that the user // confirm that that a remote device is authorized to connect to a service // UUID. void Authorize(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); dbus::ObjectPath device_path; std::string uuid; if (!reader.PopObjectPath(&device_path) || !reader.PopString(&uuid)) { LOG(WARNING) << "Authorize called with incorrect paramters: " << method_call->ToString(); return; } Delegate::ConfirmationCallback callback = base::Bind( &BluetoothAgentServiceProviderImpl::OnConfirmation, weak_ptr_factory_.GetWeakPtr(), method_call, response_sender); delegate_->Authorize(device_path, uuid, callback); } // Called by dbus:: when the Authorize method is exported. void AuthorizeExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the Bluetooth daemon requires that the user // confirm that the adapter may change mode. void ConfirmModeChange(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); dbus::MessageReader reader(method_call); std::string mode_str; if (!reader.PopString(&mode_str)) { LOG(WARNING) << "ConfirmModeChange called with incorrect paramters: " << method_call->ToString(); return; } Delegate::Mode mode; if (mode_str == kModeOff) { mode = Delegate::OFF; } else if (mode_str == kModeConnectable) { mode = Delegate::CONNECTABLE; } else if (mode_str == kModeDiscoverable) { mode = Delegate::DISCOVERABLE; } else { LOG(WARNING) << "ConfirmModeChange called with unknown mode: " << mode_str; return; } Delegate::ConfirmationCallback callback = base::Bind( &BluetoothAgentServiceProviderImpl::OnConfirmation, weak_ptr_factory_.GetWeakPtr(), method_call, response_sender); delegate_->ConfirmModeChange(mode, callback); } // Called by dbus:: when the ConfirmModeChange method is exported. void ConfirmModeChangeExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by dbus:: when the request failed before a reply was returned // from the device. void Cancel(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender) { DCHECK(OnOriginThread()); DCHECK(delegate_); delegate_->Cancel(); dbus::Response* response = dbus::Response::FromMethodCall(method_call); response_sender.Run(response); } // Called by dbus:: when the Cancel method is exported. void CancelExported(const std::string& interface_name, const std::string& method_name, bool success) { LOG_IF(WARNING, !success) << "Failed to export " << interface_name << "." << method_name; } // Called by the Delegate to response to a method requesting a PIN code. void OnPinCode(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender, Delegate::Status status, const std::string& pincode) { DCHECK(OnOriginThread()); switch (status) { case Delegate::SUCCESS: { dbus::Response* response = dbus::Response::FromMethodCall(method_call); dbus::MessageWriter writer(response); writer.AppendString(pincode); response_sender.Run(response); break; } case Delegate::REJECTED: { dbus::ErrorResponse* response = dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_agent::kErrorRejected, "rejected"); response_sender.Run(response); break; } case Delegate::CANCELLED: { dbus::ErrorResponse* response = dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_agent::kErrorCanceled, "canceled"); response_sender.Run(response); break; } default: NOTREACHED() << "Unexpected status code from delegate: " << status; } } // Called by the Delegate to response to a method requesting a Passkey. void OnPasskey(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender, Delegate::Status status, uint32 passkey) { DCHECK(OnOriginThread()); switch (status) { case Delegate::SUCCESS: { dbus::Response* response = dbus::Response::FromMethodCall(method_call); dbus::MessageWriter writer(response); writer.AppendUint32(passkey); response_sender.Run(response); break; } case Delegate::REJECTED: { dbus::ErrorResponse* response = dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_agent::kErrorRejected, "rejected"); response_sender.Run(response); break; } case Delegate::CANCELLED: { dbus::ErrorResponse* response = dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_agent::kErrorCanceled, "canceled"); response_sender.Run(response); break; } default: NOTREACHED() << "Unexpected status code from delegate: " << status; } } // Called by the Delegate in response to a method requiring confirmation. void OnConfirmation(dbus::MethodCall* method_call, dbus::ExportedObject::ResponseSender response_sender, Delegate::Status status) { DCHECK(OnOriginThread()); switch (status) { case Delegate::SUCCESS: { dbus::Response* response = dbus::Response::FromMethodCall(method_call); response_sender.Run(response); break; } case Delegate::REJECTED: { dbus::ErrorResponse* response = dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_agent::kErrorRejected, "rejected"); response_sender.Run(response); break; } case Delegate::CANCELLED: { dbus::ErrorResponse* response = dbus::ErrorResponse::FromMethodCall( method_call, bluetooth_agent::kErrorCanceled, "canceled"); response_sender.Run(response); break; } default: NOTREACHED() << "Unexpected status code from delegate: " << status; } } // Weak pointer factory for generating 'this' pointers that might live longer // than we do. base::WeakPtrFactory<BluetoothAgentServiceProviderImpl> weak_ptr_factory_; // Origin thread (i.e. the UI thread in production). base::PlatformThreadId origin_thread_id_; // D-Bus bus object is exported on, not owned by this object and must // outlive it. dbus::Bus* bus_; // All incoming method calls are passed on to the Delegate and a callback // passed to generate the reply. |delegate_| is generally the object that // owns this one, and must outlive it. Delegate* delegate_; // D-Bus object path of object we are exporting, kept so we can unregister // again in our destructor. dbus::ObjectPath object_path_; // D-Bus object we are exporting, owned by this object. scoped_refptr<dbus::ExportedObject> exported_object_; DISALLOW_COPY_AND_ASSIGN(BluetoothAgentServiceProviderImpl); }; // The BluetoothAgentServiceProvider implementation used on Linux desktop, // which does nothing. class BluetoothAgentServiceProviderStubImpl : public BluetoothAgentServiceProvider { public: explicit BluetoothAgentServiceProviderStubImpl(Delegate* delegate_) { } virtual ~BluetoothAgentServiceProviderStubImpl() { } }; BluetoothAgentServiceProvider::BluetoothAgentServiceProvider() { } BluetoothAgentServiceProvider::~BluetoothAgentServiceProvider() { } // static BluetoothAgentServiceProvider* BluetoothAgentServiceProvider::Create( dbus::Bus* bus, const dbus::ObjectPath& object_path, Delegate* delegate) { if (base::chromeos::IsRunningOnChromeOS()) { return new BluetoothAgentServiceProviderImpl(bus, object_path, delegate); } else { return new BluetoothAgentServiceProviderStubImpl(delegate); } } } // namespace chromeos
37.003515
80
0.660128
[ "object" ]
f6870496045adb21414d5ceac99251f2cd0bccc0
2,124
cpp
C++
libs/interprocess/example/doc_anonymous_semaphoreA.cpp
mike-code/boost_1_38_0
7ff8b2069344ea6b0b757aa1f0778dfb8526df3c
[ "BSL-1.0" ]
null
null
null
libs/interprocess/example/doc_anonymous_semaphoreA.cpp
mike-code/boost_1_38_0
7ff8b2069344ea6b0b757aa1f0778dfb8526df3c
[ "BSL-1.0" ]
null
null
null
libs/interprocess/example/doc_anonymous_semaphoreA.cpp
mike-code/boost_1_38_0
7ff8b2069344ea6b0b757aa1f0778dfb8526df3c
[ "BSL-1.0" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2007. 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) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/interprocess/detail/config_begin.hpp> //[doc_anonymous_semaphoreA #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <iostream> #include "doc_anonymous_semaphore_shared_data.hpp" using namespace boost::interprocess; int main () { try{ //Erase previous shared memory shared_memory_object::remove("shared_memory"); //Create a shared memory object. shared_memory_object shm (create_only //only create ,"shared_memory" //name ,read_write //read-write mode ); //Set size shm.truncate(sizeof(shared_memory_buffer)); //Map the whole shared memory in this process mapped_region region (shm //What to map ,read_write //Map it as read-write ); //Get the address of the mapped region void * addr = region.get_address(); //Construct the shared structure in memory shared_memory_buffer * data = new (addr) shared_memory_buffer; const int NumMsg = 100; //Insert data in the array for(int i = 0; i < NumMsg; ++i){ data->nempty.wait(); data->mutex.wait(); data->items[i % shared_memory_buffer::NumItems] = i; data->mutex.post(); data->nstored.post(); } } catch(interprocess_exception &ex){ shared_memory_object::remove("shared_memory"); std::cout << ex.what() << std::endl; return 1; } //Erase shared memory shared_memory_object::remove("shared_memory"); return 0; } //] #include <boost/interprocess/detail/config_end.hpp>
29.915493
78
0.590395
[ "object" ]
f688ab7ada29607b4bf6ea2c40879ef0b664a922
17,392
cpp
C++
bob/learn/linear/cpp/bic.cpp
bioidiap/bob.learn.linear
111323c3d0a7d1f0f2249ef95c18a3c0dd52be89
[ "BSD-3-Clause" ]
4
2015-10-14T08:06:46.000Z
2021-11-15T08:02:13.000Z
bob/learn/linear/cpp/bic.cpp
bioidiap/bob.learn.linear
111323c3d0a7d1f0f2249ef95c18a3c0dd52be89
[ "BSD-3-Clause" ]
4
2015-03-18T05:27:50.000Z
2015-11-25T15:30:27.000Z
bob/learn/linear/cpp/bic.cpp
bioidiap/bob.learn.linear
111323c3d0a7d1f0f2249ef95c18a3c0dd52be89
[ "BSD-3-Clause" ]
6
2015-07-17T12:58:53.000Z
2019-01-09T14:30:27.000Z
/** * @date Tue Jun 5 16:54:27 CEST 2012 * @author Manuel Guenther <Manuel.Guenther@idiap.ch> * * A machine that implements the liner projection of input to the output using * weights, biases and sums: * output = sum(inputs * weights) + bias * It is possible to setup the machine to previously normalize the input taking * into consideration some input bias and division factor. It is also possible * to set it up to have an activation function. * A linear classifier. See C. M. Bishop, "Pattern Recognition and Machine * Learning", chapter 4 * * Copyright (C) Idiap Research Institute, Martigny, Switzerland */ #include <bob.learn.linear/bic.h> #include <bob.learn.linear/pca.h> #include <bob.math/linear.h> #include <bob.core/assert.h> #include <bob.core/check.h> /************************************************************* ************************ BIC Machine ************************* *************************************************************/ /** * Initializes an empty BIC Machine * * @param use_DFFS Add the Distance From Feature Space during score computation? */ bob::learn::linear::BICMachine::BICMachine(bool use_DFFS) : m_project_data(use_DFFS), m_use_DFFS(use_DFFS) {} /** * Assigns the other BICMachine to this, i.e., makes a deep copy of the given machine. * * @param other The other BICMachine to get a shallow copy of * @return a reference to *this */ bob::learn::linear::BICMachine::BICMachine(const BICMachine& other) : m_project_data(other.m_project_data), m_use_DFFS(other.m_use_DFFS) { if (m_project_data){ setBIC(false, other.m_mu_I, other.m_lambda_I, other.m_Phi_I, other.m_rho_I, true); setBIC(true , other.m_mu_E, other.m_lambda_E, other.m_Phi_E, other.m_rho_E, true); } else { setIEC(false, other.m_mu_I, other.m_lambda_I, true); setIEC(true , other.m_mu_E, other.m_lambda_E, true); } } /** * Assigns the other BICMachine to this, i.e., makes a deep copy of the given machine. * * @param other The other BICMachine to get a shallow copy of * @return a reference to *this */ bob::learn::linear::BICMachine::BICMachine(bob::io::base::HDF5File& hdf5) { load(hdf5); } /** * Assigns the other BICMachine to this, i.e., makes a deep copy of the given BICMachine * * @param other The other BICMachine to get a deep copy of * @return a reference to *this */ bob::learn::linear::BICMachine& bob::learn::linear::BICMachine::operator=(const BICMachine& other) { if (this != &other) { if (other.m_project_data){ m_use_DFFS = other.m_use_DFFS; setBIC(false, other.m_mu_I, other.m_lambda_I, other.m_Phi_I, other.m_rho_I, true); setBIC(true , other.m_mu_E, other.m_lambda_E, other.m_Phi_E, other.m_rho_E, true); } else { m_use_DFFS = false; setIEC(false, other.m_mu_I, other.m_lambda_I, true); setIEC(true , other.m_mu_E, other.m_lambda_E, true); } } return *this; } /** * Compares if this machine and the given one are identical * * @param other The BICMachine to compare with * @return true if both machines are identical, i.e., have exactly the same parameters, otherwise false */ bool bob::learn::linear::BICMachine::operator==(const BICMachine& other) const { return (m_project_data == other.m_project_data && (!m_project_data || m_use_DFFS == other.m_use_DFFS) && bob::core::array::isEqual(m_mu_I, other.m_mu_I) && bob::core::array::isEqual(m_mu_E, other.m_mu_E) && bob::core::array::isEqual(m_lambda_I, other.m_lambda_I) && bob::core::array::isEqual(m_lambda_E, other.m_lambda_E) && (!m_project_data || (bob::core::array::isEqual(m_Phi_I, other.m_Phi_I) && bob::core::array::isEqual(m_Phi_E, other.m_Phi_E) && (!m_use_DFFS || (m_rho_I == other.m_rho_I && m_rho_E == other.m_rho_E))))); } /** * Checks if this machine and the given one are different * * @param other The BICMachine to compare with * @return false if both machines are identical, i.e., have exactly the same parameters, otherwise true */ bool bob::learn::linear::BICMachine::operator!=(const BICMachine& other) const { return !(this->operator==(other)); } /** * Compares the given machine with this for similarity * * @param other The BICMachine to compare with * @param r_epsilon The largest value any parameter might relatively differ between the two machines * @param a_epsilon The largest value any parameter might absolutely differ between the two machines * @return true if both machines are approximately equal, otherwise false */ bool bob::learn::linear::BICMachine::is_similar_to(const BICMachine& other, const double r_epsilon, const double a_epsilon) const { if (m_project_data){ // compare data if (not bob::core::array::hasSameShape(m_Phi_I, other.m_Phi_I)) return false; if (not bob::core::array::hasSameShape(m_Phi_E, other.m_Phi_E)) return false; // check that the projection matrices are close, // but allow that eigen vectors might have opposite directions // (i.e., they are either identical -> difference is 0, or opposite -> sum is zero) for (int i = m_Phi_I.extent(1); i--;){ const blitz::Array<double,1>& sub1 = m_Phi_I(blitz::Range::all(), i); const blitz::Array<double,1>& sub2 = other.m_Phi_I(blitz::Range::all(), i); blitz::Array<double,1> sub2_negative(-sub2); if (!bob::core::array::isClose(sub1, sub2, r_epsilon, a_epsilon) && !bob::core::array::isClose(sub1, sub2_negative, r_epsilon, a_epsilon)) return false; } for (int i = m_Phi_E.shape()[1]; i--;){ const blitz::Array<double,1>& sub1 = m_Phi_E(blitz::Range::all(), i); const blitz::Array<double,1>& sub2 = other.m_Phi_E(blitz::Range::all(), i); blitz::Array<double,1> sub2_negative(-sub2); if (!bob::core::array::isClose(sub1, sub2, r_epsilon, a_epsilon) && !bob::core::array::isClose(sub1, sub2_negative, r_epsilon, a_epsilon)) return false; } } return (m_project_data == other.m_project_data && (!m_project_data || m_use_DFFS == other.m_use_DFFS) && bob::core::array::isClose(m_mu_I, other.m_mu_I, r_epsilon, a_epsilon) && bob::core::array::isClose(m_mu_E, other.m_mu_E, r_epsilon, a_epsilon) && bob::core::array::isClose(m_lambda_I, other.m_lambda_I, r_epsilon, a_epsilon) && bob::core::array::isClose(m_lambda_E, other.m_lambda_E, r_epsilon, a_epsilon) && (!m_project_data || (!m_use_DFFS || (bob::core::isClose(m_rho_I, other.m_rho_I, r_epsilon, a_epsilon) && bob::core::isClose(m_rho_E, other.m_rho_E, r_epsilon, a_epsilon))))); } void bob::learn::linear::BICMachine::initialize(bool clazz, int input_length, int projected_length){ blitz::Array<double,1>& diff = clazz ? m_diff_E : m_diff_I; blitz::Array<double,1>& proj = clazz ? m_proj_E : m_proj_I; diff.resize(input_length); proj.resize(projected_length); } /** * Sets the parameters of the given class that are required for computing the IEC scores (Guenther, Wuertz) * * @param clazz false for the intrapersonal class, true for the extrapersonal one. * @param mean The mean vector of the training data * @param variances The variances of the training data * @param copy_data If true, makes a deep copy of the matrices, otherwise it just references it (the default) */ void bob::learn::linear::BICMachine::setIEC( bool clazz, const blitz::Array<double,1>& mean, const blitz::Array<double,1>& variances, bool copy_data ){ m_project_data = false; // select the right matrices to write blitz::Array<double,1>& mu = clazz ? m_mu_E : m_mu_I; blitz::Array<double,1>& lambda = clazz ? m_lambda_E : m_lambda_I; // copy mean and variances if (copy_data){ mu.resize(mean.shape()); mu = mean; lambda.resize(variances.shape()); lambda = variances; } else { mu.reference(mean); lambda.reference(variances); } } /** * Sets the parameters of the given class that are required for computing the BIC scores (Teixeira) * * @param clazz false for the intrapersonal class, true for the extrapersonal one. * @param mean The mean vector of the training data * @param variances The eigenvalues of the training data * @param projection The PCA projection matrix * @param rho The residual eigenvalues, used for DFFS calculation * @param copy_data If true, makes a deep copy of the matrices, otherwise it just references it (the default) */ void bob::learn::linear::BICMachine::setBIC( bool clazz, const blitz::Array<double,1>& mean, const blitz::Array<double,1>& variances, const blitz::Array<double,2>& projection, const double rho, bool copy_data ){ m_project_data = true; // select the right matrices to write blitz::Array<double,1>& mu = clazz ? m_mu_E : m_mu_I; blitz::Array<double,1>& lambda = clazz ? m_lambda_E : m_lambda_I; blitz::Array<double,2>& Phi = clazz ? m_Phi_E : m_Phi_I; double& rho_ = clazz ? m_rho_E : m_rho_I; // copy information if (copy_data){ mu.resize(mean.shape()); mu = mean; lambda.resize(variances.shape()); lambda = variances; Phi.resize(projection.shape()); Phi = projection; } else { mu.reference(mean); lambda.reference(variances); Phi.reference(projection); } rho_ = rho; // check that rho has a reasonable value (if it is used) if (m_use_DFFS && rho_ < 1e-12) throw std::runtime_error("The given average eigenvalue (rho) is too close to zero"); // initialize temporaries initialize(clazz, Phi.shape()[0], Phi.shape()[1]); } /** * Set or unset the usage of the Distance From Feature Space * * @param use_DFFS The new value of use_DFFS */ void bob::learn::linear::BICMachine::use_DFFS(bool use_DFFS){ m_use_DFFS = use_DFFS; if (m_project_data && m_use_DFFS && (m_rho_E < 1e-12 || m_rho_I < 1e-12)) std::runtime_error("The average eigenvalue (rho) is too close to zero, so using DFFS will not work"); } /** * Loads the BICMachine from the given hdf5 file. * * @param config The hdf5 file containing the required information. */ void bob::learn::linear::BICMachine::load(bob::io::base::HDF5File& config){ //reads all data directly into the member variables m_project_data = config.read<bool>("project_data"); m_mu_I.reference(config.readArray<double,1>("intra_mean")); m_lambda_I.reference(config.readArray<double,1>("intra_variance")); if (m_project_data){ m_use_DFFS = config.read<bool>("use_DFFS"); m_Phi_I.reference(config.readArray<double,2>("intra_subspace")); initialize(false, m_Phi_I.shape()[0], m_Phi_I.shape()[1]); m_rho_I = config.read<double>("intra_rho"); } m_mu_E.reference(config.readArray<double,1>("extra_mean")); m_lambda_E.reference(config.readArray<double,1>("extra_variance")); if (m_project_data){ m_Phi_E.reference(config.readArray<double,2>("extra_subspace")); initialize(true, m_Phi_E.shape()[0], m_Phi_E.shape()[1]); m_rho_E = config.read<double>("extra_rho"); } // check that rho has reasonable values if (m_project_data && m_use_DFFS && (m_rho_E < 1e-12 || m_rho_I < 1e-12)) throw std::runtime_error("The loaded average eigenvalue (rho) is too close to zero"); } /** * Saves the parameters of the BICMachine to the given hdf5 file. * * @param config The hdf5 file to write the configuration into. */ void bob::learn::linear::BICMachine::save(bob::io::base::HDF5File& config) const{ config.set("project_data", m_project_data); config.setArray("intra_mean", m_mu_I); config.setArray("intra_variance", m_lambda_I); if (m_project_data){ config.set("use_DFFS", m_use_DFFS); config.setArray("intra_subspace", m_Phi_I); config.set("intra_rho", m_rho_I); } config.setArray("extra_mean", m_mu_E); config.setArray("extra_variance", m_lambda_E); if (m_project_data){ config.setArray("extra_subspace", m_Phi_E); config.set("extra_rho", m_rho_E); } } /** * Computes the BIC or IEC score for the given input vector. * The score itself is the log-likelihood score of the given input vector belonging to the intrapersonal class. * No sanity checks of input and output are performed. * * @param input A vector (of difference values) to compute the BIC or IEC score for. * @return The score. */ double bob::learn::linear::BICMachine::forward_(const blitz::Array<double,1>& input) const{ double output; if (m_project_data){ // subtract mean m_diff_I = input - m_mu_I; m_diff_E = input - m_mu_E; // project data to intrapersonal and extrapersonal subspace bob::math::prod(m_diff_I, m_Phi_I, m_proj_I); bob::math::prod(m_diff_E, m_Phi_E, m_proj_E); // compute Mahalanobis distance output = blitz::sum(blitz::pow2(m_proj_E) / m_lambda_E) - blitz::sum(blitz::pow2(m_proj_I) / m_lambda_I); // add the DFFS? if (m_use_DFFS){ output += blitz::sum(blitz::pow2(m_diff_E) - blitz::pow2(m_proj_E)) / m_rho_E; output -= blitz::sum(blitz::pow2(m_diff_I) - blitz::pow2(m_proj_I)) / m_rho_I; } output /= (m_proj_E.extent(0) + m_proj_I.extent(0)); } else { // forward without projection output = blitz::mean( blitz::pow2(input - m_mu_E) / m_lambda_E - blitz::pow2(input - m_mu_I) / m_lambda_I); } return output; } /** * Computes the BIC or IEC score for the given input vector. * The score itself is the log-likelihood score of the given input vector belonging to the intrapersonal class. * Sanity checks of input and output shape are performed. * * @param input A vector (of difference values) to compute the BIC or IEC score for. * @return The score. */ double bob::learn::linear::BICMachine::forward(const blitz::Array<double,1>& input) const{ // perform some checks bob::core::array::assertSameShape(input, m_mu_E); // call the actual method return forward_(input); } /************************************************************* ************************ BIC Trainer ************************* *************************************************************/ static double sqr(const double& x){ return x*x; } /** * This function trains one of the classes of the given machine with the given data. * It computes either BIC projection matrices, or IEC mean and variance. * * @param clazz false for the intrapersonal class, true for the extrapersonal one. * @param machine The machine to be trained. * @param differences A set of (intra/extra)-personal difference vectors that should be trained. */ void bob::learn::linear::BICTrainer::train_single(bool clazz, bob::learn::linear::BICMachine& machine, const blitz::Array<double,2>& differences) const { int subspace_dim = clazz ? m_M_E : m_M_I; int input_dim = differences.extent(1); int data_count = differences.extent(0); blitz::Range a = blitz::Range::all(); if (subspace_dim){ // train the class using BIC // Compute PCA on the given dataset bob::learn::linear::PCATrainer trainer; const int n_eigs = trainer.output_size(differences); bob::learn::linear::Machine pca(input_dim, n_eigs); blitz::Array<double,1> variances(n_eigs); trainer.train(pca, variances, differences); // compute rho double rho = 0.; int non_zero_eigenvalues = std::min(input_dim, data_count-1); // assert that the number of kept eigenvalues is not chosen to big if (subspace_dim >= non_zero_eigenvalues) throw std::runtime_error((boost::format("The chosen subspace dimension %d is larger than the theoretical number of nonzero eigenvalues %d")%subspace_dim%non_zero_eigenvalues).str()); // compute the average of the reminding eigenvalues for (int i = subspace_dim; i < non_zero_eigenvalues; ++i){ rho += variances(i); } rho /= non_zero_eigenvalues - subspace_dim; // limit dimensionalities pca.resize(input_dim, subspace_dim); variances.resizeAndPreserve(subspace_dim); // check that all variances are meaningful for (int i = 0; i < subspace_dim; ++i){ if (variances(i) < 1e-12) throw std::runtime_error((boost::format("The chosen subspace dimension is %d, but the %dth eigenvalue is already to small")%subspace_dim%i).str()); } // initialize the machine blitz::Array<double, 2> projection = pca.getWeights(); blitz::Array<double, 1> mean = pca.getInputSubtraction(); machine.setBIC(clazz, mean, variances, projection, rho); } else { // train the class using IEC // => compute mean and variance only blitz::Array<double,1> mean(input_dim), variance(input_dim); // compute mean and variance mean = 0.; variance = 0.; for (int n = data_count; n--;){ const blitz::Array<double,1>& diff = differences(n,a); for (int i = input_dim; i--;){ mean(i) += diff(i); variance(i) += sqr(diff(i)); } } // normalize mean and variances for (int i = 0; i < input_dim; ++i){ // intrapersonal variance(i) = (variance(i) - sqr(mean(i)) / data_count) / (data_count - 1.); mean(i) /= data_count; if (variance(i) < 1e-12) throw std::runtime_error((boost::format("The variance of the %dth dimension is too small. Check your data!")%i).str()); } // set the results to the machine machine.setIEC(clazz, mean, variance); } }
38.056893
188
0.671688
[ "shape", "vector" ]
f68a03f2b6fcf1c8bdb54caa6e6b762361ce93e3
14,032
cpp
C++
stage0/src/util/name.cpp
ChrisHughes24/lean4
a4de54eaf01182f91a74b54a98787239c8f836b6
[ "Apache-2.0" ]
1
2021-07-19T04:47:46.000Z
2021-07-19T04:47:46.000Z
stage0/src/util/name.cpp
ChrisHughes24/lean4
a4de54eaf01182f91a74b54a98787239c8f836b6
[ "Apache-2.0" ]
null
null
null
stage0/src/util/name.cpp
ChrisHughes24/lean4
a4de54eaf01182f91a74b54a98787239c8f836b6
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <cctype> #include <cstring> #include <vector> #include <algorithm> #include <sstream> #include <string> #include <lean/thread.h> #include <lean/debug.h> #include <lean/sstream.h> #include <lean/utf8.h> #include <lean/hash.h> #include "util/name.h" #include "util/buffer.h" #include "util/ascii.h" namespace lean { extern "C" size_t lean_name_hash_usize(b_obj_arg n) { return name::hash(n); } extern "C" obj_res lean_name_mk_string(obj_arg p, obj_arg s); extern "C" obj_res lean_name_mk_numeral(obj_arg p, obj_arg n); static inline obj_res name_mk_string_of_cstr(obj_arg p, char const * s) { return lean_name_mk_string(p, mk_string(s)); } extern "C" usize lean_name_hash(obj_arg n); usize name::hash(b_obj_arg n) { inc(n); return lean_name_hash(n); } bool name::eq_core(b_obj_arg n1, b_obj_arg n2) { while (true) { lean_assert(!is_scalar(n1)); lean_assert(!is_scalar(n2)); lean_assert(n1 && n2); lean_assert(name::hash(n1) == name::hash(n2)); if (cnstr_tag(n1) != cnstr_tag(n2)) return false; if (cnstr_tag(n1) == static_cast<unsigned>(name_kind::STRING)) { if (!string_eq(cnstr_get(n1, 1), cnstr_get(n2, 1))) return false; } else { if (!nat_eq(cnstr_get(n1, 1), cnstr_get(n1, 1))) return false; } n1 = cnstr_get(n1, 0); n2 = cnstr_get(n2, 0); if (n1 == n2) return true; if (is_scalar(n1) != is_scalar(n2)) return false; if (name::hash(n1) != name::hash(n2)) return false; } } extern "C" uint8 lean_name_eq(b_obj_arg a1, b_obj_arg a2) { return name::eq(a1, a2); } constexpr char const * anonymous_str = "[anonymous]"; bool is_greek_unicode(unsigned u) { return 0x391 <= u && u <= 0x3DD; } bool is_letter_like_unicode(unsigned u) { return (0x3b1 <= u && u <= 0x3c9 && u != 0x3bb) || // Lower greek, but lambda (0x391 <= u && u <= 0x3A9 && u != 0x3A0 && u != 0x3A3) || // Upper greek, but Pi and Sigma (0x3ca <= u && u <= 0x3fb) || // Coptic letters (0x1f00 <= u && u <= 0x1ffe) || // Polytonic Greek Extended Character Set (0x2100 <= u && u <= 0x214f) || // Letter like block (0x1d49c <= u && u <= 0x1d59f); // Latin letters, Script, Double-struck, Fractur } bool is_sub_script_alnum_unicode(unsigned u) { return (0x207f <= u && u <= 0x2089) || // n superscript and numberic subscripts (0x2090 <= u && u <= 0x209c) || // letter-like subscripts (0x1d62 <= u && u <= 0x1d6a); // letter-like subscripts } bool is_id_first(unsigned char const * begin, unsigned char const * end) { if (std::isalpha(*begin) || *begin == '_') return true; unsigned u = utf8_to_unicode(begin, end); return u == id_begin_escape || is_letter_like_unicode(u); } bool is_id_rest(unsigned char const * begin, unsigned char const * end) { if (std::isalnum(*begin) || *begin == '_' || *begin == '\'' || *begin == '?' || *begin == '!') return true; unsigned u = utf8_to_unicode(begin, end); return is_letter_like_unicode(u) || is_sub_script_alnum_unicode(u); } static void display_name_core(std::ostream & out, name const & n, bool escape, char const * sep) { lean_assert(!n.is_anonymous()); name pre = n.get_prefix(); if (pre) { display_name_core(out, pre, escape, sep); out << sep; } if (n.is_string()) { std::string str = n.get_string().to_std_string(); size_t sz = str.size(); bool must_escape = false; if (escape) { if (sz == 0) must_escape = true; if (!is_id_first(str.data(), str.data() + sz)) must_escape = true; // don't escape names produced by server::display_decl if (must_escape && str[0] == '?') // TODO(Kha, Leo): do we need this hack must_escape = false; for (size_t i = get_utf8_size(str[0]); !must_escape && i < sz; i += get_utf8_size(str[i])) { if (!is_id_rest(str.data() + i, str.data() + sz)) must_escape = true; } } if (must_escape || sz == 0) out << "«" << str << "»"; else out << str; } else { out << n.get_numeral().to_std_string(); } } static void display_name(std::ostream & out, name const & n, bool escape, char const * sep) { if (n.is_anonymous()) out << anonymous_str; else display_name_core(out, n, escape, sep); } name::name(name const & prefix, char const * n): object_ref(name_mk_string_of_cstr(prefix.raw(), n)) { inc(prefix.raw()); } name::name(name const & prefix, unsigned k): object_ref(lean_name_mk_numeral(prefix.raw(), mk_nat_obj(k))) { inc(prefix.raw()); } name::name(name const & prefix, string_ref const & s): object_ref(lean_name_mk_string(prefix.raw(), s.raw())) { inc(prefix.raw()); inc(s.raw()); } name::name(name const & prefix, nat const & k): object_ref(lean_name_mk_numeral(prefix.raw(), k.raw())) { inc(prefix.raw()); inc(k.raw()); } name::name(std::initializer_list<char const *> const & l):name() { if (l.size() == 0) { return; } else { auto it = l.begin(); *this = name(*it); ++it; for (; it != l.end(); ++it) *this = name(*this, *it); } } static name * g_anonymous = nullptr; name const & name::anonymous() { lean_assert(g_anonymous->is_anonymous()); return *g_anonymous; } static void copy_limbs(object * p, buffer<object *> & limbs) { limbs.clear(); while (!is_scalar(p)) { limbs.push_back(p); p = name::get_prefix(p); } std::reverse(limbs.begin(), limbs.end()); } bool is_prefix_of(name const & n1, name const & n2) { if (n2.is_atomic()) return n1 == n2; buffer<object*> limbs1, limbs2; object* i1 = n1.raw(); object* i2 = n2.raw(); copy_limbs(i1, limbs1); copy_limbs(i2, limbs2); unsigned sz1 = limbs1.size(); unsigned sz2 = limbs2.size(); if (sz1 > sz2) return false; else if (sz1 == sz2 && n1.hash() != n2.hash()) return false; auto it1 = limbs1.begin(); auto it2 = limbs2.begin(); for (; it1 != limbs1.end(); ++it1, ++it2) { i1 = *it1; i2 = *it2; if (cnstr_tag(i1) != cnstr_tag(i2)) return false; if (static_cast<name_kind>(cnstr_tag(i1)) == name_kind::STRING) { if (name::get_string(i1) != name::get_string(i2)) return false; } else if (name::get_numeral(i1) != name::get_numeral(i2)) { return false; } } return true; } bool operator==(name const & a, char const * b) { return a.kind() == name_kind::STRING && is_scalar(name::get_prefix(a.raw())) && name::get_string(a.raw()) == b; } int name::cmp_core(object * i1, object * i2) { buffer<object*> limbs1, limbs2; copy_limbs(i1, limbs1); copy_limbs(i2, limbs2); auto it1 = limbs1.begin(); auto it2 = limbs2.begin(); for (; it1 != limbs1.end() && it2 != limbs2.end(); ++it1, ++it2) { i1 = *it1; i2 = *it2; name_kind k1 = static_cast<name_kind>(cnstr_tag(i1)); name_kind k2 = static_cast<name_kind>(cnstr_tag(i2)); if (k1 != k2) return k1 == name_kind::STRING ? 1 : -1; if (k1 == name_kind::STRING) { if (get_string(i1) < get_string(i2)) return -1; if (get_string(i2) < get_string(i1)) return 1; } else { if (get_numeral(i1) < get_numeral(i2)) return -1; if (get_numeral(i2) < get_numeral(i1)) return 1; } } if (it1 == limbs1.end() && it2 == limbs2.end()) return 0; else return it1 == limbs1.end() ? -1 : 1; } static unsigned num_digits(nat k) { if (k == 0u) return 1; int r = 0; while (k != 0u) { k = k / nat(10); r++; } return r; } size_t name::size_core(bool unicode) const { if (is_scalar(raw())) { return strlen(anonymous_str); } else { object * i = raw(); size_t sep_sz = strlen(lean_name_separator); size_t r = 0; while (true) { lean_assert(!is_scalar(i)); if (kind(i) == name_kind::STRING) { r += unicode ? get_string(i).length() : get_string(i).num_bytes(); } else { // TODO(Leo): we are ignoring the case the numeral is not small. r += num_digits(get_numeral(i)); } i = get_prefix(i); if (is_scalar(i)) break; r += sep_sz; } return r; } } size_t name::size() const { return size_core(false); } size_t name::utf8_size() const { return size_core(true); } bool name::is_safe_ascii() const { object * i = raw(); while (!is_scalar(i)) { if (kind(i) == name_kind::STRING) { if (!::lean::is_safe_ascii(get_string(i).data(), get_string(i).num_bytes())) return false; } i = get_prefix(i); } return true; } name name::get_root() const { name n = *this; while (n.get_prefix()) { n = n.get_prefix(); } return n; } std::string name::to_string(char const * sep) const { std::ostringstream s; display_name(s, *this, false, sep); return s.str(); } std::string name::escape(char const * sep) const { std::ostringstream s; display_name(s, *this, true, sep); return s.str(); } std::ostream & operator<<(std::ostream & out, name const & n) { display_name(out, n, false, lean_name_separator); return out; } name operator+(name const & n1, name const & n2) { if (n2.is_anonymous()) { return n1; } else if (n1.is_anonymous()) { return n2; } else { name prefix; if (!n2.is_atomic()) prefix = n1 + n2.get_prefix(); else prefix = n1; if (n2.is_string()) return name(prefix, n2.get_string()); else return name(prefix, n2.get_numeral()); // <<< TODO(Leo): ignoring the case the numeral is not small. } } extern "C" obj_res lean_name_append_after(obj_arg n, obj_arg s); extern "C" obj_res lean_name_append_before(obj_arg n, obj_arg s); extern "C" obj_res lean_name_append_index_after(obj_arg n, obj_arg i); name name::append_before(char const * p) const { return name(lean_name_append_before(to_obj_arg(), lean_mk_string(p))); } name name::append_after(char const * s) const { return name(lean_name_append_after(to_obj_arg(), lean_mk_string(s))); } name name::get_subscript_base() const { if (is_string()) { return *this; } else { return name(*this, ""); } } name name::append_after(unsigned i) const { return name(lean_name_append_index_after(to_obj_arg(), lean_unsigned_to_nat(i))); } optional<pair<name, unsigned>> name::is_subscripted() const { optional<pair<name, unsigned>> none; if (!is_string()) return none; std::string s = get_string().to_std_string(); auto underscore_pos = s.find_last_of('_'); if (underscore_pos == std::string::npos) return none; std::string::iterator it = s.begin() + underscore_pos + 1; if (it == s.end() || *it == '0') return none; unsigned idx = 0; for (; it != s.end() && '0' <= *it && *it <= '9'; it++) idx = 10*idx + (*it - '0'); if (it != s.end()) return none; name prefix(get_prefix(), string_ref(s.substr(0, underscore_pos))); return optional<pair<name, unsigned>>(prefix, idx); } name name::replace_prefix(name const & prefix, name const & new_prefix) const { if (*this == prefix) return new_prefix; if (is_anonymous()) return *this; name p = get_prefix().replace_prefix(prefix, new_prefix); if (p.raw() == raw()) return *this; if (is_string()) return name(p, get_string()); else return name(p, get_numeral()); } bool is_part_of(std::string const & p, name n) { while (true) { if (n.is_string()) { std::string s = n.get_string().to_std_string(); if (s.find(p) != std::string::npos) return true; } if (n.is_atomic() || n.is_anonymous()) return false; n = n.get_prefix(); } } name string_to_name(std::string const & str) { static_assert(*(lean_name_separator+1) == 0, "this function assumes the length of lean_name_separator is 1"); name result; std::string id_part; for (unsigned i = 0; i < str.size(); i++) { if (str[i] == lean_name_separator[0]) { result = name(result, id_part.c_str()); id_part.clear(); } else { id_part.push_back(str[i]); } } return name(result, id_part.c_str()); } bool is_internal_name(name const & n) { name it = n; while (!it.is_anonymous()) { if (!it.is_anonymous() && it.is_string() && it.get_string().data() && it.get_string().data()[0] == '_') return true; it = it.get_prefix(); } return false; } static atomic<unsigned> * g_next_id = nullptr; name name::mk_internal_unique_name() { unsigned id = (*g_next_id)++; return name(name(), id); } void initialize_name() { g_anonymous = new name(); mark_persistent(g_anonymous->raw()); g_next_id = new atomic<unsigned>(0); } void finalize_name() { delete g_next_id; delete g_anonymous; } } void print(lean::name const & n) { std::cout << n << std::endl; }
29.791932
113
0.563569
[ "object", "vector" ]
f68a7a9491a001150c81f2d977b0531e1bdf2d44
2,399
cpp
C++
ngraph/core/src/op/gather.cpp
ledmonster/openvino
c1b1e2e7afc698ac82b32bb1f502ad2e90cd1419
[ "Apache-2.0" ]
null
null
null
ngraph/core/src/op/gather.cpp
ledmonster/openvino
c1b1e2e7afc698ac82b32bb1f502ad2e90cd1419
[ "Apache-2.0" ]
26
2021-01-18T16:21:41.000Z
2022-02-21T13:04:24.000Z
ngraph/core/src/op/gather.cpp
ngaloppo/openvino
7aad8827a585e2e08c5fd872bb17e40072718661
[ "Apache-2.0" ]
1
2021-08-18T14:29:37.000Z
2021-08-18T14:29:37.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/gather.hpp" #include <ngraph/validation_util.hpp> #include "itt.hpp" #include "ngraph/shape.hpp" using namespace std; using namespace ngraph; NGRAPH_RTTI_DEFINITION(op::v1::Gather, "Gather", 1, op::util::GatherBase); op::v1::Gather::Gather(const Output<Node>& params, const Output<Node>& indices, const Output<Node>& axes) : GatherBase(params, indices, axes) { constructor_validate_and_infer_types(); } bool ngraph::op::v1::Gather::visit_attributes(AttributeVisitor& visitor) { NGRAPH_OP_SCOPE(v1_Gather_visit_attributes); return true; } shared_ptr<Node> op::v1::Gather::clone_with_new_inputs(const OutputVector& new_args) const { NGRAPH_OP_SCOPE(v1_Gather_clone_with_new_inputs); check_new_args_count(this, new_args); return make_shared<v1::Gather>(new_args.at(0), new_args.at(1), new_args.at(2)); } NGRAPH_RTTI_DEFINITION(op::v7::Gather, "Gather", 7, op::util::GatherBase); op::v7::Gather::Gather(const Output<Node>& data, const Output<Node>& indices, const Output<Node>& axis, const int64_t batch_dims) : GatherBase(data, indices, axis, batch_dims) { constructor_validate_and_infer_types(); } void op::v7::Gather::validate_and_infer_types() { NGRAPH_OP_SCOPE(v7_Gather_validate_and_infer_types); NODE_VALIDATION_CHECK(this, get_input_element_type(1).is_integral_number(), "Indices element type must be of an integral number type."); NODE_VALIDATION_CHECK(this, get_input_element_type(2).is_integral_number(), "Axis element type must be of an integral number type."); op::util::GatherBase::validate_and_infer_types(); } bool ngraph::op::v7::Gather::visit_attributes(AttributeVisitor& visitor) { NGRAPH_OP_SCOPE(v7_Gather_visit_attributes); visitor.on_attribute("batch_dims", m_batch_dims); return true; } shared_ptr<Node> op::v7::Gather::clone_with_new_inputs(const OutputVector& new_args) const { NGRAPH_OP_SCOPE(v7_Gather_clone_with_new_inputs); check_new_args_count(this, new_args); return make_shared<v7::Gather>(new_args.at(0), new_args.at(1), new_args.at(2), m_batch_dims); }
32.418919
97
0.68862
[ "shape" ]
f691640148e10e44954fdb9a459cb23d42db6394
1,854
cpp
C++
collection/cp/bcw_codebook-master/Contest/Japan2014/pF.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
1
2019-03-24T13:12:01.000Z
2019-03-24T13:12:01.000Z
collection/cp/bcw_codebook-master/Contest/Japan2014/pF.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
collection/cp/bcw_codebook-master/Contest/Japan2014/pF.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> #include<unistd.h> using namespace std; #define FZ(n) memset((n),0,sizeof(n)) #define FMO(n) memset((n),-1,sizeof(n)) #define MC(n,m) memcpy((n),(m),sizeof(n)) #define F first #define S second #define MP make_pair #define PB push_back #define ALL(x) begin(x),end(x) #define SZ(x) ((int)(x).size()) #define IOS ios_base::sync_with_stdio(0); cin.tie(0) // Let's Fight! struct ed { int u, v, c, id; bool operator < (const ed &e) const { return c < e.c; } }; typedef pair<int, int> pii; const int MX = 555; const int ME = 55555; int V, E; vector<ed> edges; int djs[MX]; vector<ed> el[MX]; bool good[ME]; int ffa(int a) { return (djs[a] == a ? a : (djs[a] = ffa(djs[a]))); } stack<pii> st; bool dfs(int v, int fa, int tar, int c) { if (v == tar) { while (st.size()) { int cn, id; tie(cn, id) = st.top(); st.pop(); if (c <= cn) { good[id] = 0; } } return true; } for (auto x: el[v]) { int u = x.v; if (u == fa) continue; st.push({x.c, x.id}); if (dfs(u, v, tar, c)) return true; st.pop(); } return false; } int main() { IOS; cin >> V >> E; for (int i=0; i<=V; i++) { djs[i] = i; } for (int i=0; i<E; i++) { int a, b, c; cin >> a >> b >> c; edges.PB({a, b, c, i}); } sort(ALL(edges)); for (int i=0; i<E; i++) { int u = edges[i].u, v = edges[i].v; int id = edges[i].id; if (ffa(u) != ffa(v)) { djs[ffa(u)] = ffa(v); good[id] = true; el[u].PB({u, v, edges[i].c, id}); el[v].PB({v, u, edges[i].c, id}); } } for (int i=0; i<E; i++) { int u = edges[i].u, v = edges[i].v; int id = edges[i].id; if (not good[id]) { //cout << u << ' ' << v << endl; dfs(u, -1, v, edges[i].c); } } int a1 = 0, a2 = 0; for (int i=0; i<E; i++) { if (good[edges[i].id]) { a1 ++; a2 += edges[i].c; } } cout << a1 << ' ' << a2 << endl; return 0; }
18.356436
52
0.510248
[ "vector" ]
f69352b63e789d9629338aca9cb14a6029be91e4
23,291
cpp
C++
gdal/ogr/ogrpoint.cpp
trundev/gdal
d5777940975f2784980ef0b7561eeeb655fd0ab5
[ "MIT" ]
null
null
null
gdal/ogr/ogrpoint.cpp
trundev/gdal
d5777940975f2784980ef0b7561eeeb655fd0ab5
[ "MIT" ]
1
2015-04-14T00:19:57.000Z
2015-04-14T00:29:29.000Z
gdal/ogr/ogrpoint.cpp
trundev/gdal
d5777940975f2784980ef0b7561eeeb655fd0ab5
[ "MIT" ]
1
2015-10-05T05:19:59.000Z
2015-10-05T05:19:59.000Z
/****************************************************************************** * * Project: OpenGIS Simple Features Reference Implementation * Purpose: The Point geometry class. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * Copyright (c) 2008-2011, Even Rouault <even dot rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cpl_port.h" #include "ogr_geometry.h" #include <cmath> #include <cstdio> #include <cstring> #include <algorithm> #include <limits> #include <new> #include "cpl_conv.h" #include "ogr_core.h" #include "ogr_p.h" #include "ogr_spatialref.h" CPL_CVSID("$Id$") /************************************************************************/ /* GetEmptyNonEmptyFlag() */ /************************************************************************/ static int GetEmptyNonEmptyFlag(double x, double y) { if( std::isnan(x) || std::isnan(y) ) return 0; return OGRGeometry::OGR_G_NOT_EMPTY_POINT; } /************************************************************************/ /* OGRPoint() */ /************************************************************************/ /** * \brief Create an empty point. */ OGRPoint::OGRPoint(): x(0.0), y(0.0), z(0.0), m(0.0) { flags = 0; } /************************************************************************/ /* OGRPoint() */ /************************************************************************/ /** * \brief Create a point. * @param xIn x * @param yIn y * @param zIn z */ OGRPoint::OGRPoint( double xIn, double yIn, double zIn ) : x(xIn), y(yIn), z(zIn), m(0.0) { flags = GetEmptyNonEmptyFlag(xIn, yIn) | OGR_G_3D; } /************************************************************************/ /* OGRPoint() */ /************************************************************************/ /** * \brief Create a point. * @param xIn x * @param yIn y */ OGRPoint::OGRPoint( double xIn, double yIn ) : x(xIn), y(yIn), z(0.0), m(0.0) { flags = GetEmptyNonEmptyFlag(xIn, yIn); } /************************************************************************/ /* OGRPoint() */ /************************************************************************/ /** * \brief Create a point. * @param xIn x * @param yIn y * @param zIn z * @param mIn m */ OGRPoint::OGRPoint( double xIn, double yIn, double zIn, double mIn ) : x(xIn), y(yIn), z(zIn), m(mIn) { flags = GetEmptyNonEmptyFlag(xIn, yIn) | OGR_G_3D | OGR_G_MEASURED; } /************************************************************************/ /* createXYM() */ /************************************************************************/ /** * \brief Create a XYM point. * @param x x * @param y y * @param m m * @since GDAL 3.1 */ OGRPoint* OGRPoint::createXYM( double x, double y, double m ) { auto p = new OGRPoint(x, y, 0, m); p->flags &= ~OGR_G_3D; return p; } /************************************************************************/ /* OGRPoint( const OGRPoint& ) */ /************************************************************************/ /** * \brief Copy constructor. * * Note: before GDAL 2.1, only the default implementation of the constructor * existed, which could be unsafe to use. * * @since GDAL 2.1 */ OGRPoint::OGRPoint( const OGRPoint& ) = default; /************************************************************************/ /* ~OGRPoint() */ /************************************************************************/ OGRPoint::~OGRPoint() = default; /************************************************************************/ /* operator=( const OGRPoint& ) */ /************************************************************************/ /** * \brief Assignment operator. * * Note: before GDAL 2.1, only the default implementation of the operator * existed, which could be unsafe to use. * * @since GDAL 2.1 */ OGRPoint& OGRPoint::operator=( const OGRPoint& other ) { if( this != &other) { OGRGeometry::operator=( other ); x = other.x; y = other.y; z = other.z; m = other.m; } return *this; } /************************************************************************/ /* clone() */ /* */ /* Make a new object that is a copy of this object. */ /************************************************************************/ OGRGeometry *OGRPoint::clone() const { OGRPoint *poNewPoint = new (std::nothrow) OGRPoint( x, y, z, m ); if( poNewPoint == nullptr ) return nullptr; poNewPoint->assignSpatialReference( getSpatialReference() ); poNewPoint->flags = flags; return poNewPoint; } /************************************************************************/ /* empty() */ /************************************************************************/ void OGRPoint::empty() { x = 0.0; y = 0.0; z = 0.0; m = 0.0; flags &= ~OGR_G_NOT_EMPTY_POINT; } /************************************************************************/ /* getDimension() */ /************************************************************************/ int OGRPoint::getDimension() const { return 0; } /************************************************************************/ /* getGeometryType() */ /************************************************************************/ OGRwkbGeometryType OGRPoint::getGeometryType() const { if( (flags & OGR_G_3D) && (flags & OGR_G_MEASURED) ) return wkbPointZM; else if( flags & OGR_G_MEASURED ) return wkbPointM; else if( flags & OGR_G_3D ) return wkbPoint25D; else return wkbPoint; } /************************************************************************/ /* getGeometryName() */ /************************************************************************/ const char * OGRPoint::getGeometryName() const { return "POINT"; } /************************************************************************/ /* flattenTo2D() */ /************************************************************************/ void OGRPoint::flattenTo2D() { z = 0.0; m = 0.0; flags &= ~OGR_G_3D; setMeasured(FALSE); } /************************************************************************/ /* setCoordinateDimension() */ /************************************************************************/ void OGRPoint::setCoordinateDimension( int nNewDimension ) { if( nNewDimension == 2 ) flattenTo2D(); else if( nNewDimension == 3 ) flags |= OGR_G_3D; setMeasured(FALSE); } /************************************************************************/ /* WkbSize() */ /* */ /* Return the size of this object in well known binary */ /* representation including the byte order, and type information. */ /************************************************************************/ int OGRPoint::WkbSize() const { if( (flags & OGR_G_3D) && (flags & OGR_G_MEASURED) ) return 37; else if( (flags & OGR_G_3D) || (flags & OGR_G_MEASURED) ) return 29; else return 21; } /************************************************************************/ /* importFromWkb() */ /* */ /* Initialize from serialized stream in well known binary */ /* format. */ /************************************************************************/ OGRErr OGRPoint::importFromWkb( const unsigned char *pabyData, int nSize, OGRwkbVariant eWkbVariant, int& nBytesConsumedOut ) { nBytesConsumedOut = -1; OGRwkbByteOrder eByteOrder = wkbNDR; flags = 0; OGRErr eErr = importPreambleFromWkb( pabyData, nSize, eByteOrder, eWkbVariant ); pabyData += 5; if( eErr != OGRERR_NONE ) return eErr; if( nSize != -1 ) { if( (nSize < 37) && ((flags & OGR_G_3D) && (flags & OGR_G_MEASURED)) ) return OGRERR_NOT_ENOUGH_DATA; else if( (nSize < 29) && ((flags & OGR_G_3D) || (flags & OGR_G_MEASURED)) ) return OGRERR_NOT_ENOUGH_DATA; else if( nSize < 21 ) return OGRERR_NOT_ENOUGH_DATA; } nBytesConsumedOut = 5 + 8 * (2 + ((flags & OGR_G_3D) ? 1 : 0)+ ((flags & OGR_G_MEASURED) ? 1 : 0)); /* -------------------------------------------------------------------- */ /* Get the vertex. */ /* -------------------------------------------------------------------- */ memcpy( &x, pabyData, 8 ); pabyData += 8; memcpy( &y, pabyData, 8 ); pabyData += 8; if( OGR_SWAP( eByteOrder ) ) { CPL_SWAPDOUBLE( &x ); CPL_SWAPDOUBLE( &y ); } if( flags & OGR_G_3D ) { memcpy( &z, pabyData, 8 ); pabyData += 8; if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( &z ); } else { z = 0; } if( flags & OGR_G_MEASURED ) { memcpy( &m, pabyData, 8 ); /*pabyData += 8; */ if( OGR_SWAP( eByteOrder ) ) { CPL_SWAPDOUBLE( &m ); } } else { m = 0; } // Detect coordinates are not NaN --> NOT EMPTY. if( !(CPLIsNan(x) && CPLIsNan(y)) ) flags |= OGR_G_NOT_EMPTY_POINT; return OGRERR_NONE; } /************************************************************************/ /* exportToWkb() */ /* */ /* Build a well known binary representation of this object. */ /************************************************************************/ OGRErr OGRPoint::exportToWkb( OGRwkbByteOrder eByteOrder, unsigned char * pabyData, OGRwkbVariant eWkbVariant ) const { /* -------------------------------------------------------------------- */ /* Set the byte order. */ /* -------------------------------------------------------------------- */ pabyData[0] = DB2_V72_UNFIX_BYTE_ORDER(static_cast<unsigned char>(eByteOrder)); pabyData += 1; /* -------------------------------------------------------------------- */ /* Set the geometry feature type. */ /* -------------------------------------------------------------------- */ GUInt32 nGType = getGeometryType(); if( eWkbVariant == wkbVariantPostGIS1 ) { nGType = wkbFlatten(nGType); if( Is3D() ) // Explicitly set wkb25DBit. nGType = static_cast<OGRwkbGeometryType>(nGType | wkb25DBitInternalUse); if( IsMeasured() ) nGType = static_cast<OGRwkbGeometryType>(nGType | 0x40000000); } else if( eWkbVariant == wkbVariantIso ) { nGType = getIsoGeometryType(); } if( eByteOrder == wkbNDR ) { CPL_LSBPTR32( &nGType ); } else { CPL_MSBPTR32( &nGType ); } memcpy( pabyData, &nGType, 4 ); pabyData += 4; /* -------------------------------------------------------------------- */ /* Copy in the raw data. Swap if needed. */ /* -------------------------------------------------------------------- */ if( IsEmpty() && eWkbVariant == wkbVariantIso ) { const double dNan = std::numeric_limits<double>::quiet_NaN(); memcpy( pabyData, &dNan, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); pabyData += 8; memcpy( pabyData, &dNan, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); pabyData += 8; if( flags & OGR_G_3D ) { memcpy( pabyData, &dNan, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); pabyData += 8; } if( flags & OGR_G_MEASURED ) { memcpy( pabyData, &dNan, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); } } else { memcpy( pabyData, &x, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); pabyData += 8; memcpy( pabyData, &y, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); pabyData += 8; if( flags & OGR_G_3D ) { memcpy( pabyData, &z, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); pabyData += 8; } if( flags & OGR_G_MEASURED ) { memcpy( pabyData, &m, 8 ); if( OGR_SWAP( eByteOrder ) ) CPL_SWAPDOUBLE( pabyData ); } } return OGRERR_NONE; } /************************************************************************/ /* importFromWkt() */ /* */ /* Instantiate point from well known text format ``POINT */ /* (x,y)''. */ /************************************************************************/ OGRErr OGRPoint::importFromWkt( const char ** ppszInput ) { int bHasZ = FALSE; int bHasM = FALSE; bool bIsEmpty = false; OGRErr eErr = importPreambleFromWkt(ppszInput, &bHasZ, &bHasM, &bIsEmpty); flags = 0; if( eErr != OGRERR_NONE ) return eErr; if( bHasZ ) flags |= OGR_G_3D; if( bHasM ) flags |= OGR_G_MEASURED; if( bIsEmpty ) { return OGRERR_NONE; } else { flags |= OGR_G_NOT_EMPTY_POINT; } const char *pszInput = *ppszInput; /* -------------------------------------------------------------------- */ /* Read the point list which should consist of exactly one point. */ /* -------------------------------------------------------------------- */ OGRRawPoint *poPoints = nullptr; double *padfZ = nullptr; double *padfM = nullptr; int nMaxPoint = 0; int nPoints = 0; int flagsFromInput = flags; pszInput = OGRWktReadPointsM( pszInput, &poPoints, &padfZ, &padfM, &flagsFromInput, &nMaxPoint, &nPoints ); if( pszInput == nullptr || nPoints != 1 ) { CPLFree( poPoints ); CPLFree( padfZ ); CPLFree( padfM ); return OGRERR_CORRUPT_DATA; } if( (flagsFromInput & OGR_G_3D) && !(flags & OGR_G_3D) ) { flags |= OGR_G_3D; bHasZ = TRUE; } if( (flagsFromInput & OGR_G_MEASURED) && !(flags & OGR_G_MEASURED) ) { flags |= OGR_G_MEASURED; bHasM = TRUE; } x = poPoints[0].x; y = poPoints[0].y; CPLFree( poPoints ); if( bHasZ ) { if( padfZ != nullptr ) z = padfZ[0]; } if( bHasM ) { if( padfM != nullptr ) m = padfM[0]; } CPLFree( padfZ ); CPLFree( padfM ); *ppszInput = pszInput; return OGRERR_NONE; } /************************************************************************/ /* exportToWkt() */ /* */ /* Translate this structure into its well known text format */ /* equivalent. */ /************************************************************************/ std::string OGRPoint::exportToWkt(const OGRWktOptions& opts, OGRErr *err) const { std::string wkt = getGeometryName() + wktTypeString(opts.variant); if( IsEmpty() ) { wkt += "EMPTY"; } else { wkt += "("; bool measured = ((opts.variant == wkbVariantIso) && IsMeasured()); wkt += OGRMakeWktCoordinateM(x, y, z, m, Is3D(), measured, opts); wkt += ")"; } if (err) *err = OGRERR_NONE; return wkt; } /************************************************************************/ /* getEnvelope() */ /************************************************************************/ void OGRPoint::getEnvelope( OGREnvelope * psEnvelope ) const { psEnvelope->MinX = getX(); psEnvelope->MaxX = getX(); psEnvelope->MinY = getY(); psEnvelope->MaxY = getY(); } /************************************************************************/ /* getEnvelope() */ /************************************************************************/ void OGRPoint::getEnvelope( OGREnvelope3D * psEnvelope ) const { psEnvelope->MinX = getX(); psEnvelope->MaxX = getX(); psEnvelope->MinY = getY(); psEnvelope->MaxY = getY(); psEnvelope->MinZ = getZ(); psEnvelope->MaxZ = getZ(); } /** * \fn double OGRPoint::getX() const; * * \brief Fetch X coordinate. * * Relates to the SFCOM IPoint::get_X() method. * * @return the X coordinate of this point. */ /** * \fn double OGRPoint::getY() const; * * \brief Fetch Y coordinate. * * Relates to the SFCOM IPoint::get_Y() method. * * @return the Y coordinate of this point. */ /** * \fn double OGRPoint::getZ() const; * * \brief Fetch Z coordinate. * * Relates to the SFCOM IPoint::get_Z() method. * * @return the Z coordinate of this point, or zero if it is a 2D point. */ /** * \fn void OGRPoint::setX( double xIn ); * * \brief Assign point X coordinate. * * There is no corresponding SFCOM method. */ /** * \fn void OGRPoint::setY( double yIn ); * * \brief Assign point Y coordinate. * * There is no corresponding SFCOM method. */ /** * \fn void OGRPoint::setZ( double zIn ); * * \brief Assign point Z coordinate. * Calling this method will force the geometry * coordinate dimension to 3D (wkbPoint|wkbZ). * * There is no corresponding SFCOM method. */ /************************************************************************/ /* Equal() */ /************************************************************************/ OGRBoolean OGRPoint::Equals( const OGRGeometry * poOther ) const { if( poOther== this ) return TRUE; if( poOther->getGeometryType() != getGeometryType() ) return FALSE; const auto poOPoint = poOther->toPoint(); if( flags != poOPoint->flags ) return FALSE; if( IsEmpty() ) return TRUE; // Should eventually test the SRS. if( poOPoint->getX() != getX() || poOPoint->getY() != getY() || poOPoint->getZ() != getZ() ) return FALSE; return TRUE; } /************************************************************************/ /* transform() */ /************************************************************************/ OGRErr OGRPoint::transform( OGRCoordinateTransformation *poCT ) { if( poCT->Transform( 1, &x, &y, &z ) ) { assignSpatialReference( poCT->GetTargetCS() ); return OGRERR_NONE; } return OGRERR_FAILURE; } /************************************************************************/ /* swapXY() */ /************************************************************************/ void OGRPoint::swapXY() { std::swap(x, y); } /************************************************************************/ /* Within() */ /************************************************************************/ OGRBoolean OGRPoint::Within( const OGRGeometry *poOtherGeom ) const { if( !IsEmpty() && poOtherGeom != nullptr && wkbFlatten(poOtherGeom->getGeometryType()) == wkbCurvePolygon ) { const auto poCurve = poOtherGeom->toCurvePolygon(); return poCurve->Contains(this); } return OGRGeometry::Within(poOtherGeom); } /************************************************************************/ /* Intersects() */ /************************************************************************/ OGRBoolean OGRPoint::Intersects( const OGRGeometry *poOtherGeom ) const { if( !IsEmpty() && poOtherGeom != nullptr && wkbFlatten(poOtherGeom->getGeometryType()) == wkbCurvePolygon ) { const auto poCurve = poOtherGeom->toCurvePolygon(); return poCurve->Intersects(this); } return OGRGeometry::Intersects(poOtherGeom); }
29.594663
79
0.39277
[ "geometry", "object", "transform", "3d" ]
f693573aa9757995ed00fb6706df408dcb904dea
47,574
cpp
C++
Game_exe/release_mode/windows/obj/src/FreeplayState.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
Game_exe/release_mode/windows/obj/src/FreeplayState.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
Game_exe/release_mode/windows/obj/src/FreeplayState.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
null
null
null
#include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_Alphabet #include <Alphabet.h> #endif #ifndef INCLUDED_Controls #include <Controls.h> #endif #ifndef INCLUDED_CoolUtil #include <CoolUtil.h> #endif #ifndef INCLUDED_DiscordClient #include <DiscordClient.h> #endif #ifndef INCLUDED_FreeplayState #include <FreeplayState.h> #endif #ifndef INCLUDED_HealthIcon #include <HealthIcon.h> #endif #ifndef INCLUDED_Highscore #include <Highscore.h> #endif #ifndef INCLUDED_LoadingState #include <LoadingState.h> #endif #ifndef INCLUDED_MainMenuState #include <MainMenuState.h> #endif #ifndef INCLUDED_MusicBeatState #include <MusicBeatState.h> #endif #ifndef INCLUDED_MusicBeatSubstate #include <MusicBeatSubstate.h> #endif #ifndef INCLUDED_Paths #include <Paths.h> #endif #ifndef INCLUDED_PlayState #include <PlayState.h> #endif #ifndef INCLUDED_PlayerSettings #include <PlayerSettings.h> #endif #ifndef INCLUDED_ResetScoreSubState #include <ResetScoreSubState.h> #endif #ifndef INCLUDED_Song #include <Song.h> #endif #ifndef INCLUDED_SongMetadata #include <SongMetadata.h> #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_StoryMenuState #include <StoryMenuState.h> #endif #ifndef INCLUDED_WeekData #include <WeekData.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_FlxObject #include <flixel/FlxObject.h> #endif #ifndef INCLUDED_flixel_FlxSprite #include <flixel/FlxSprite.h> #endif #ifndef INCLUDED_flixel_FlxState #include <flixel/FlxState.h> #endif #ifndef INCLUDED_flixel_FlxSubState #include <flixel/FlxSubState.h> #endif #ifndef INCLUDED_flixel_addons_transition_FlxTransitionableState #include <flixel/addons/transition/FlxTransitionableState.h> #endif #ifndef INCLUDED_flixel_addons_transition_TransitionData #include <flixel/addons/transition/TransitionData.h> #endif #ifndef INCLUDED_flixel_addons_ui_FlxUIState #include <flixel/addons/ui/FlxUIState.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IEventGetter #include <flixel/addons/ui/interfaces/IEventGetter.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IFlxUIState #include <flixel/addons/ui/interfaces/IFlxUIState.h> #endif #ifndef INCLUDED_flixel_graphics_FlxGraphic #include <flixel/graphics/FlxGraphic.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedGroup #include <flixel/group/FlxTypedGroup.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedSpriteGroup #include <flixel/group/FlxTypedSpriteGroup.h> #endif #ifndef INCLUDED_flixel_input_FlxBaseKeyList #include <flixel/input/FlxBaseKeyList.h> #endif #ifndef INCLUDED_flixel_input_FlxKeyManager #include <flixel/input/FlxKeyManager.h> #endif #ifndef INCLUDED_flixel_input_IFlxInputManager #include <flixel/input/IFlxInputManager.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxAction #include <flixel/input/actions/FlxAction.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxActionDigital #include <flixel/input/actions/FlxActionDigital.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxActionSet #include <flixel/input/actions/FlxActionSet.h> #endif #ifndef INCLUDED_flixel_input_keyboard_FlxKeyList #include <flixel/input/keyboard/FlxKeyList.h> #endif #ifndef INCLUDED_flixel_input_keyboard_FlxKeyboard #include <flixel/input/keyboard/FlxKeyboard.h> #endif #ifndef INCLUDED_flixel_math_FlxPoint #include <flixel/math/FlxPoint.h> #endif #ifndef INCLUDED_flixel_system_FlxSound #include <flixel/system/FlxSound.h> #endif #ifndef INCLUDED_flixel_system_FlxSoundGroup #include <flixel/system/FlxSoundGroup.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_SoundFrontEnd #include <flixel/system/frontEnds/SoundFrontEnd.h> #endif #ifndef INCLUDED_flixel_text_FlxText #include <flixel/text/FlxText.h> #endif #ifndef INCLUDED_flixel_text_FlxTextBorderStyle #include <flixel/text/FlxTextBorderStyle.h> #endif #ifndef INCLUDED_flixel_tweens_FlxTween #include <flixel/tweens/FlxTween.h> #endif #ifndef INCLUDED_flixel_tweens_misc_ColorTween #include <flixel/tweens/misc/ColorTween.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif #ifndef INCLUDED_flixel_util_IFlxPooled #include <flixel/util/IFlxPooled.h> #endif #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_openfl_utils_Assets #include <openfl/utils/Assets.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_86166a84e8de7ace_22_new,"FreeplayState","new",0xc894eea3,"FreeplayState.new","FreeplayState.hx",22,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_59_create,"FreeplayState","create",0x931e5499,"FreeplayState.create","FreeplayState.hx",59,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_176_closeSubState,"FreeplayState","closeSubState",0xd27ac84c,"FreeplayState.closeSubState","FreeplayState.hx",176,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_183_addSong,"FreeplayState","addSong",0x9e966259,"FreeplayState.addSong","FreeplayState.hx",183,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_187_addWeek,"FreeplayState","addWeek",0xa1339e78,"FreeplayState.addWeek","FreeplayState.hx",187,0x0d86f62d) static const ::String _hx_array_data_b3f26131_10[] = { HX_("bf",c4,55,00,00), }; HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_204_update,"FreeplayState","update",0x9e1473a6,"FreeplayState.update","FreeplayState.hx",204,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_311_changeDiff,"FreeplayState","changeDiff",0x302511b2,"FreeplayState.changeDiff","FreeplayState.hx",311,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_330_changeSelection,"FreeplayState","changeSelection",0xbe8c8f7f,"FreeplayState.changeSelection","FreeplayState.hx",330,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_348_changeSelection,"FreeplayState","changeSelection",0xbe8c8f7f,"FreeplayState.changeSelection","FreeplayState.hx",348,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_386_positionHighscore,"FreeplayState","positionHighscore",0xe71f084a,"FreeplayState.positionHighscore","FreeplayState.hx",386,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_302_destroyFreeplayVocals,"FreeplayState","destroyFreeplayVocals",0x5af9fabb,"FreeplayState.destroyFreeplayVocals","FreeplayState.hx",302,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_25_boot,"FreeplayState","boot",0xb1d4e08f,"FreeplayState.boot","FreeplayState.hx",25,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_37_boot,"FreeplayState","boot",0xb1d4e08f,"FreeplayState.boot","FreeplayState.hx",37,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_38_boot,"FreeplayState","boot",0xb1d4e08f,"FreeplayState.boot","FreeplayState.hx",38,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_52_boot,"FreeplayState","boot",0xb1d4e08f,"FreeplayState.boot","FreeplayState.hx",52,0x0d86f62d) HX_LOCAL_STACK_FRAME(_hx_pos_86166a84e8de7ace_202_boot,"FreeplayState","boot",0xb1d4e08f,"FreeplayState.boot","FreeplayState.hx",202,0x0d86f62d) void FreeplayState_obj::__construct( ::flixel::addons::transition::TransitionData TransIn, ::flixel::addons::transition::TransitionData TransOut){ HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_22_new) HXLINE( 201) this->instPlaying = -1; HXLINE( 51) this->iconArray = ::Array_obj< ::Dynamic>::__new(0); HXLINE( 49) this->curPlaying = false; HXLINE( 46) this->intendedRating = ((Float)0); HXLINE( 45) this->intendedScore = 0; HXLINE( 44) this->lerpRating = ((Float)0); HXLINE( 43) this->lerpScore = 0; HXLINE( 34) this->songs = ::Array_obj< ::Dynamic>::__new(0); HXLINE( 22) super::__construct(TransIn,TransOut); } Dynamic FreeplayState_obj::__CreateEmpty() { return new FreeplayState_obj; } void *FreeplayState_obj::_hx_vtable = 0; Dynamic FreeplayState_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< FreeplayState_obj > _hx_result = new FreeplayState_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool FreeplayState_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x5f09868d) { if (inClassId<=(int)0x2f064378) { if (inClassId<=(int)0x23a57bae) { return inClassId==(int)0x00000001 || inClassId==(int)0x23a57bae; } else { return inClassId==(int)0x2f064378; } } else { return inClassId==(int)0x3f706236 || inClassId==(int)0x5f09868d; } } else { if (inClassId<=(int)0x7c795c9f) { return inClassId==(int)0x62817b24 || inClassId==(int)0x7c795c9f; } else { return inClassId==(int)0x7ccf8994; } } } void FreeplayState_obj::create(){ HX_GC_STACKFRAME(&_hx_pos_86166a84e8de7ace_59_create) HXLINE( 60) this->transIn = ::flixel::addons::transition::FlxTransitionableState_obj::defaultTransIn; HXLINE( 61) this->transOut = ::flixel::addons::transition::FlxTransitionableState_obj::defaultTransOut; HXLINE( 62) ::String library = null(); HXDLIN( 62) ::Array< ::String > initSonglist = ::CoolUtil_obj::coolTextFile(::Paths_obj::getPath(((HX_("data/",c5,0e,88,d4) + HX_("freeplaySonglist",73,3b,dc,de)) + HX_(".txt",02,3f,c0,1e)),HX_("TEXT",ad,94,ba,37),library)); HXLINE( 63) { HXLINE( 63) int _g = 0; HXDLIN( 63) int _g1 = initSonglist->length; HXDLIN( 63) while((_g < _g1)){ HXLINE( 63) _g = (_g + 1); HXDLIN( 63) int i = (_g - 1); HXLINE( 65) ::Array< ::String > songArray = initSonglist->__get(i).split(HX_(":",3a,00,00,00)); HXLINE( 66) this->addSong(songArray->__get(0),0,songArray->__get(1)); HXLINE( 67) this->songs->__get((this->songs->length - 1)).StaticCast< ::SongMetadata >()->color = ( (int)(::Std_obj::parseInt(songArray->__get(2))) ); } } HXLINE( 69) ::String library1 = null(); HXDLIN( 69) ::Array< ::String > colorsList = ::CoolUtil_obj::coolTextFile(::Paths_obj::getPath(((HX_("data/",c5,0e,88,d4) + HX_("freeplayColors",70,02,58,d6)) + HX_(".txt",02,3f,c0,1e)),HX_("TEXT",ad,94,ba,37),library1)); HXLINE( 70) { HXLINE( 70) int _g2 = 0; HXDLIN( 70) int _g3 = colorsList->length; HXDLIN( 70) while((_g2 < _g3)){ HXLINE( 70) _g2 = (_g2 + 1); HXDLIN( 70) int i = (_g2 - 1); HXLINE( 72) ::Array< int > _hx_tmp = ::FreeplayState_obj::coolColors; HXDLIN( 72) _hx_tmp->push(::Std_obj::parseInt(colorsList->__get(i))); } } HXLINE( 85) ::DiscordClient_obj::changePresence(HX_("In the Menus",0a,c1,ad,c6),null(),null(),null(),null()); HXLINE( 88) { HXLINE( 88) int _g4 = 1; HXDLIN( 88) int _g5 = ::WeekData_obj::songsNames->get_length(); HXDLIN( 88) while((_g4 < _g5)){ HXLINE( 88) _g4 = (_g4 + 1); HXDLIN( 88) int i = (_g4 - 1); HXLINE( 90) if (::StoryMenuState_obj::weekUnlocked->__get(i)) { HXLINE( 92) this->addWeek(( (::Array< ::String >)(::WeekData_obj::songsNames->__get(i)) ),i,( (::Array< ::String >)(::FreeplayState_obj::songsHeads->__get((i - 1))) )); } } } HXLINE( 99) ::flixel::FlxSprite _hx_tmp = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,null(),null(),null()); HXDLIN( 99) ::String library2 = null(); HXDLIN( 99) ::flixel::graphics::FlxGraphic imageToReturn = ::Paths_obj::addCustomGraphic(HX_("menuDesat",26,91,04,72)); HXDLIN( 99) ::Dynamic _hx_tmp1; HXDLIN( 99) if (::hx::IsNotNull( imageToReturn )) { HXLINE( 99) _hx_tmp1 = imageToReturn; } else { HXLINE( 99) _hx_tmp1 = ::Paths_obj::getPath(((HX_("images/",77,50,74,c1) + HX_("menuDesat",26,91,04,72)) + HX_(".png",3b,2d,bd,1e)),HX_("IMAGE",3b,57,57,3b),library2); } HXDLIN( 99) this->bg = _hx_tmp->loadGraphic(_hx_tmp1,null(),null(),null(),null(),null()); HXLINE( 100) this->add(this->bg); HXLINE( 102) this->grpSongs = ::flixel::group::FlxTypedGroup_obj::__alloc( HX_CTX ,null()); HXLINE( 103) this->add(this->grpSongs); HXLINE( 105) { HXLINE( 105) int _g6 = 0; HXDLIN( 105) int _g7 = this->songs->length; HXDLIN( 105) while((_g6 < _g7)){ HXLINE( 105) _g6 = (_g6 + 1); HXDLIN( 105) int i = (_g6 - 1); HXLINE( 107) ::Alphabet songText = ::Alphabet_obj::__alloc( HX_CTX ,( (Float)(0) ),( (Float)(((70 * i) + 30)) ),this->songs->__get(i).StaticCast< ::SongMetadata >()->songName,true,false,null(),null()); HXLINE( 108) songText->isMenuItem = true; HXLINE( 109) songText->targetY = ( (Float)(i) ); HXLINE( 110) this->grpSongs->add(songText).StaticCast< ::Alphabet >(); HXLINE( 112) ::HealthIcon icon = ::HealthIcon_obj::__alloc( HX_CTX ,this->songs->__get(i).StaticCast< ::SongMetadata >()->songCharacter,null()); HXLINE( 113) icon->sprTracker = songText; HXLINE( 116) this->iconArray->push(icon); HXLINE( 117) this->add(icon); } } HXLINE( 124) this->scoreText = ::flixel::text::FlxText_obj::__alloc( HX_CTX ,(( (Float)(::flixel::FlxG_obj::width) ) * ((Float)0.7)),5,0,HX_("",00,00,00,00),32,null()); HXLINE( 125) this->scoreText->setFormat((HX_("assets/fonts/",37,ff,a5,9c) + HX_("vcr.ttf",9d,d2,a7,82)),32,-1,HX_("right",dc,0b,64,e9),null(),null(),null()); HXLINE( 127) this->scoreBG = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,(this->scoreText->x - ( (Float)(6) )),0,null())->makeGraphic(1,66,-16777216,null(),null()); HXLINE( 128) this->scoreBG->set_alpha(((Float)0.6)); HXLINE( 129) this->add(this->scoreBG); HXLINE( 131) this->diffText = ::flixel::text::FlxText_obj::__alloc( HX_CTX ,this->scoreText->x,(this->scoreText->y + 36),0,HX_("",00,00,00,00),24,null()); HXLINE( 132) this->diffText->set_font(this->scoreText->_font); HXLINE( 133) this->add(this->diffText); HXLINE( 135) this->add(this->scoreText); HXLINE( 137) this->bg->set_color(this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->color); HXLINE( 138) this->intendedColor = this->bg->color; HXLINE( 139) this->changeSelection(null()); HXLINE( 140) this->changeDiff(null()); HXLINE( 142) ::Alphabet swag = ::Alphabet_obj::__alloc( HX_CTX ,( (Float)(1) ),( (Float)(0) ),HX_("swag",8a,2a,5e,4c),null(),null(),null(),null()); HXLINE( 161) ::flixel::FlxSprite textBG = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,0,(::flixel::FlxG_obj::height - 26),null())->makeGraphic(::flixel::FlxG_obj::width,26,-16777216,null(),null()); HXLINE( 162) textBG->set_alpha(((Float)0.6)); HXLINE( 163) this->add(textBG); HXLINE( 165) ::String leText = HX_("Press SPACE to listen to this Song / Press RESET to Reset your Score and Accuracy.",a5,1d,81,bc); HXLINE( 169) ::flixel::text::FlxText text = ::flixel::text::FlxText_obj::__alloc( HX_CTX ,textBG->x,(textBG->y + 4),::flixel::FlxG_obj::width,leText,18,null()); HXLINE( 170) text->setFormat((HX_("assets/fonts/",37,ff,a5,9c) + HX_("vcr.ttf",9d,d2,a7,82)),18,-1,HX_("right",dc,0b,64,e9),null(),null(),null()); HXLINE( 171) text->scrollFactor->set(null(),null()); HXLINE( 172) this->add(text); HXLINE( 173) this->super::create(); } void FreeplayState_obj::closeSubState(){ HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_176_closeSubState) HXLINE( 177) this->changeSelection(null()); HXLINE( 178) this->super::closeSubState(); } void FreeplayState_obj::addSong(::String songName,int weekNum,::String songCharacter){ HX_GC_STACKFRAME(&_hx_pos_86166a84e8de7ace_183_addSong) HXDLIN( 183) ::Array< ::Dynamic> _hx_tmp = this->songs; HXDLIN( 183) _hx_tmp->push( ::SongMetadata_obj::__alloc( HX_CTX ,songName,weekNum,songCharacter)); } HX_DEFINE_DYNAMIC_FUNC3(FreeplayState_obj,addSong,(void)) void FreeplayState_obj::addWeek(::Array< ::String > songs,int weekNum,::Array< ::String > songCharacters){ HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_187_addWeek) HXLINE( 188) if (::hx::IsNull( songCharacters )) { HXLINE( 189) songCharacters = ::Array_obj< ::String >::fromData( _hx_array_data_b3f26131_10,1); } HXLINE( 191) int num = 0; HXLINE( 192) { HXLINE( 192) int _g = 0; HXDLIN( 192) while((_g < songs->length)){ HXLINE( 192) ::String song = songs->__get(_g); HXDLIN( 192) _g = (_g + 1); HXLINE( 194) this->addSong(song,weekNum,songCharacters->__get(num)); HXLINE( 196) if ((songCharacters->length != 1)) { HXLINE( 197) num = (num + 1); } } } } HX_DEFINE_DYNAMIC_FUNC3(FreeplayState_obj,addWeek,(void)) void FreeplayState_obj::update(Float elapsed){ HX_GC_STACKFRAME(&_hx_pos_86166a84e8de7ace_204_update) HXLINE( 205) if ((::flixel::FlxG_obj::sound->music->_volume < ((Float)0.7))) { HXLINE( 207) ::flixel::_hx_system::FlxSound fh = ::flixel::FlxG_obj::sound->music; HXDLIN( 207) fh->set_volume((fh->_volume + (((Float)0.5) * ::flixel::FlxG_obj::elapsed))); } HXLINE( 210) Float a = ( (Float)(this->lerpScore) ); HXDLIN( 210) Float b = ( (Float)(this->intendedScore) ); HXDLIN( 210) this->lerpScore = ::Math_obj::floor((a + (::CoolUtil_obj::boundTo((elapsed * ( (Float)(24) )),( (Float)(0) ),( (Float)(1) )) * (b - a)))); HXLINE( 211) Float a1 = this->lerpRating; HXDLIN( 211) Float b1 = this->intendedRating; HXDLIN( 211) this->lerpRating = (a1 + (::CoolUtil_obj::boundTo((elapsed * ( (Float)(12) )),( (Float)(0) ),( (Float)(1) )) * (b1 - a1))); HXLINE( 213) if ((::Math_obj::abs(( (Float)((this->lerpScore - this->intendedScore)) )) <= 10)) { HXLINE( 214) this->lerpScore = this->intendedScore; } HXLINE( 215) if ((::Math_obj::abs((this->lerpRating - this->intendedRating)) <= ((Float)0.01))) { HXLINE( 216) this->lerpRating = this->intendedRating; } HXLINE( 218) this->scoreText->set_text(((((HX_("PERSONAL BEST: ",2a,a1,aa,1d) + this->lerpScore) + HX_(" (",08,1c,00,00)) + ::Math_obj::floor((this->lerpRating * ( (Float)(100) )))) + HX_("%)",64,20,00,00))); HXLINE( 219) this->positionHighscore(); HXLINE( 221) bool upP = ::PlayerSettings_obj::player1->controls->_ui_upP->check(); HXLINE( 222) bool downP = ::PlayerSettings_obj::player1->controls->_ui_downP->check(); HXLINE( 223) bool accepted = ::PlayerSettings_obj::player1->controls->_accept->check(); HXLINE( 224) ::flixel::input::keyboard::FlxKeyList _this = ( ( ::flixel::input::keyboard::FlxKeyList)(::flixel::FlxG_obj::keys->justPressed) ); HXDLIN( 224) bool space = _this->keyManager->checkStatus(32,_this->status); HXLINE( 226) if (upP) { HXLINE( 228) this->changeSelection(-1); } HXLINE( 230) if (downP) { HXLINE( 232) this->changeSelection(1); } HXLINE( 235) if (::PlayerSettings_obj::player1->controls->_ui_leftP->check()) { HXLINE( 236) this->changeDiff(-1); } HXLINE( 237) if (::PlayerSettings_obj::player1->controls->_ui_rightP->check()) { HXLINE( 238) this->changeDiff(1); } HXLINE( 240) if (::PlayerSettings_obj::player1->controls->_back->check()) { HXLINE( 242) if (::hx::IsNotNull( this->colorTween )) { HXLINE( 243) this->colorTween->cancel(); } HXLINE( 245) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 245) _hx_tmp->play(::Paths_obj::sound(HX_("cancelMenu",39,a4,43,b7),null()),null(),null(),null(),null(),null()); HXLINE( 246) ::MusicBeatState_obj::switchState( ::MainMenuState_obj::__alloc( HX_CTX ,null(),null())); } HXLINE( 250) bool _hx_tmp; HXDLIN( 250) if (space) { HXLINE( 250) _hx_tmp = (this->instPlaying != ::FreeplayState_obj::curSelected); } else { HXLINE( 250) _hx_tmp = false; } HXDLIN( 250) if (_hx_tmp) { HXLINE( 252) ::FreeplayState_obj::destroyFreeplayVocals(); HXLINE( 253) ::String poop = this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName.toLowerCase(); HXDLIN( 253) ::String poop1 = ::Highscore_obj::formatSong(poop,::FreeplayState_obj::curDifficulty); HXLINE( 254) ::PlayState_obj::SONG = ::Song_obj::loadFromJson(poop1,this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName.toLowerCase()); HXLINE( 255) if (( (bool)(::PlayState_obj::SONG->__Field(HX_("needsVoices",be,05,e9,0d),::hx::paccDynamic)) )) { HXLINE( 256) ::flixel::_hx_system::FlxSound _hx_tmp = ::flixel::_hx_system::FlxSound_obj::__alloc( HX_CTX ); HXDLIN( 256) ::FreeplayState_obj::vocals = _hx_tmp->loadEmbedded((((HX_("songs:assets/songs/",c1,ed,e6,7e) + ( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase()) + HX_("/Voices.",1e,f6,e5,90)) + HX_("ogg",4f,94,54,00)),null(),null(),null()); } else { HXLINE( 258) ::FreeplayState_obj::vocals = ::flixel::_hx_system::FlxSound_obj::__alloc( HX_CTX ); } HXLINE( 260) ::flixel::FlxG_obj::sound->list->add(::FreeplayState_obj::vocals).StaticCast< ::flixel::_hx_system::FlxSound >(); HXLINE( 261) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 261) _hx_tmp->playMusic((((HX_("songs:assets/songs/",c1,ed,e6,7e) + ( (::String)(::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic)) ).toLowerCase()) + HX_("/Inst.",f9,6e,13,1c)) + HX_("ogg",4f,94,54,00)),((Float)0.7),null(),null()); HXLINE( 262) ::FreeplayState_obj::vocals->play(null(),null(),null()); HXLINE( 263) ::FreeplayState_obj::vocals->persist = true; HXLINE( 264) ::FreeplayState_obj::vocals->looped = true; HXLINE( 265) ::FreeplayState_obj::vocals->set_volume(((Float)0.7)); HXLINE( 266) this->instPlaying = ::FreeplayState_obj::curSelected; } else { HXLINE( 268) if (accepted) { HXLINE( 270) ::String songLowercase = this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName.toLowerCase(); HXLINE( 271) ::String poop = ::Highscore_obj::formatSong(songLowercase,::FreeplayState_obj::curDifficulty); HXLINE( 272) ::String library = null(); HXDLIN( 272) if (!(::openfl::utils::Assets_obj::exists(::Paths_obj::getPath(((HX_("data/",c5,0e,88,d4) + ((songLowercase + HX_("/",2f,00,00,00)) + poop)) + HX_(".json",56,f1,d6,c2)),HX_("TEXT",ad,94,ba,37),library),null()))) { HXLINE( 273) poop = songLowercase; HXLINE( 274) ::FreeplayState_obj::curDifficulty = 1; HXLINE( 275) ::haxe::Log_obj::trace(HX_("Couldnt find file",ca,cf,b2,d5),::hx::SourceInfo(HX_("source/FreeplayState.hx",21,2d,b0,ce),275,HX_("FreeplayState",31,61,f2,b3),HX_("update",09,86,05,87))); } HXLINE( 277) ::haxe::Log_obj::trace(poop,::hx::SourceInfo(HX_("source/FreeplayState.hx",21,2d,b0,ce),277,HX_("FreeplayState",31,61,f2,b3),HX_("update",09,86,05,87))); HXLINE( 279) ::PlayState_obj::SONG = ::Song_obj::loadFromJson(poop,songLowercase); HXLINE( 280) ::PlayState_obj::isStoryMode = false; HXLINE( 281) ::PlayState_obj::storyDifficulty = ::FreeplayState_obj::curDifficulty; HXLINE( 283) ::PlayState_obj::storyWeek = this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->week; HXLINE( 284) ::Dynamic _hx_tmp = ::haxe::Log_obj::trace; HXDLIN( 284) ::String _hx_tmp1 = (HX_("CURRENT WEEK: ",c1,cc,39,35) + ::WeekData_obj::getCurrentWeekNumber()); HXDLIN( 284) _hx_tmp(_hx_tmp1,::hx::SourceInfo(HX_("source/FreeplayState.hx",21,2d,b0,ce),284,HX_("FreeplayState",31,61,f2,b3),HX_("update",09,86,05,87))); HXLINE( 285) if (::hx::IsNotNull( this->colorTween )) { HXLINE( 286) this->colorTween->cancel(); } HXLINE( 288) ::MusicBeatState_obj::switchState(::LoadingState_obj::getNextState(( ( ::flixel::FlxState)( ::PlayState_obj::__alloc( HX_CTX ,null(),null())) ),false)); HXLINE( 290) ::flixel::FlxG_obj::sound->music->set_volume(( (Float)(0) )); HXLINE( 292) ::FreeplayState_obj::destroyFreeplayVocals(); } else { HXLINE( 294) if (::PlayerSettings_obj::player1->controls->_reset->check()) { HXLINE( 296) this->openSubState( ::ResetScoreSubState_obj::__alloc( HX_CTX ,this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName,::FreeplayState_obj::curDifficulty,this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songCharacter,null())); HXLINE( 297) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 297) _hx_tmp->play(::Paths_obj::sound(HX_("scrollMenu",4c,d4,18,06),null()),null(),null(),null(),null(),null()); } } } HXLINE( 299) this->super::update(elapsed); } void FreeplayState_obj::changeDiff(::hx::Null< int > __o_change){ int change = __o_change.Default(0); HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_311_changeDiff) HXLINE( 312) ::Dynamic _hx_tmp = ::hx::ClassOf< ::FreeplayState >(); HXDLIN( 312) ::FreeplayState_obj::curDifficulty = (::FreeplayState_obj::curDifficulty + change); HXLINE( 314) if ((::FreeplayState_obj::curDifficulty < 0)) { HXLINE( 315) ::FreeplayState_obj::curDifficulty = (::CoolUtil_obj::difficultyStuff->get_length() - 1); } HXLINE( 316) if ((::FreeplayState_obj::curDifficulty >= ::CoolUtil_obj::difficultyStuff->get_length())) { HXLINE( 317) ::FreeplayState_obj::curDifficulty = 0; } HXLINE( 320) this->intendedScore = ::Highscore_obj::getScore(this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName,::FreeplayState_obj::curDifficulty); HXLINE( 321) this->intendedRating = ::Highscore_obj::getRating(this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName,::FreeplayState_obj::curDifficulty); HXLINE( 324) ::PlayState_obj::storyDifficulty = ::FreeplayState_obj::curDifficulty; HXLINE( 325) ::flixel::text::FlxText _hx_tmp1 = this->diffText; HXDLIN( 325) _hx_tmp1->set_text(((HX_("< ",64,34,00,00) + ::CoolUtil_obj::difficultyString()) + HX_(" >",1e,1c,00,00))); HXLINE( 326) this->positionHighscore(); } HX_DEFINE_DYNAMIC_FUNC1(FreeplayState_obj,changeDiff,(void)) void FreeplayState_obj::changeSelection(::hx::Null< int > __o_change){ int change = __o_change.Default(0); HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_330_changeSelection) HXDLIN( 330) ::FreeplayState _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 331) ::flixel::_hx_system::frontEnds::SoundFrontEnd _hx_tmp = ::flixel::FlxG_obj::sound; HXDLIN( 331) _hx_tmp->play(::Paths_obj::sound(HX_("scrollMenu",4c,d4,18,06),null()),((Float)0.4),null(),null(),null(),null()); HXLINE( 333) ::Dynamic _hx_tmp1 = ::hx::ClassOf< ::FreeplayState >(); HXDLIN( 333) ::FreeplayState_obj::curSelected = (::FreeplayState_obj::curSelected + change); HXLINE( 335) if ((::FreeplayState_obj::curSelected < 0)) { HXLINE( 336) ::FreeplayState_obj::curSelected = (this->songs->length - 1); } HXLINE( 337) if ((::FreeplayState_obj::curSelected >= this->songs->length)) { HXLINE( 338) ::FreeplayState_obj::curSelected = 0; } HXLINE( 340) int newColor = this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->color; HXLINE( 341) if ((newColor != this->intendedColor)) { HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::FreeplayState,_gthis) HXARGC(1) void _hx_run( ::flixel::tweens::FlxTween twn){ HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_348_changeSelection) HXLINE( 348) _gthis->colorTween = null(); } HX_END_LOCAL_FUNC1((void)) HXLINE( 342) if (::hx::IsNotNull( this->colorTween )) { HXLINE( 343) this->colorTween->cancel(); } HXLINE( 345) this->intendedColor = newColor; HXLINE( 346) this->colorTween = ::flixel::tweens::FlxTween_obj::color(this->bg,1,this->bg->color,this->intendedColor, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("onComplete",f8,d4,7e,5d), ::Dynamic(new _hx_Closure_0(_gthis))))); } HXLINE( 356) this->intendedScore = ::Highscore_obj::getScore(this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName,::FreeplayState_obj::curDifficulty); HXLINE( 357) this->intendedRating = ::Highscore_obj::getRating(this->songs->__get(::FreeplayState_obj::curSelected).StaticCast< ::SongMetadata >()->songName,::FreeplayState_obj::curDifficulty); HXLINE( 360) int bullShit = 0; HXLINE( 362) { HXLINE( 362) int _g = 0; HXDLIN( 362) int _g1 = this->iconArray->length; HXDLIN( 362) while((_g < _g1)){ HXLINE( 362) _g = (_g + 1); HXDLIN( 362) int i = (_g - 1); HXLINE( 364) this->iconArray->__get(i).StaticCast< ::HealthIcon >()->set_alpha(((Float)0.6)); } } HXLINE( 367) this->iconArray->__get(::FreeplayState_obj::curSelected).StaticCast< ::HealthIcon >()->set_alpha(( (Float)(1) )); HXLINE( 369) { HXLINE( 369) int _g2 = 0; HXDLIN( 369) ::Array< ::Dynamic> _g3 = this->grpSongs->members; HXDLIN( 369) while((_g2 < _g3->length)){ HXLINE( 369) ::Alphabet item = _g3->__get(_g2).StaticCast< ::Alphabet >(); HXDLIN( 369) _g2 = (_g2 + 1); HXLINE( 371) item->targetY = ( (Float)((bullShit - ::FreeplayState_obj::curSelected)) ); HXLINE( 372) bullShit = (bullShit + 1); HXLINE( 374) item->set_alpha(((Float)0.6)); HXLINE( 377) if ((item->targetY == 0)) { HXLINE( 379) item->set_alpha(( (Float)(1) )); } } } HXLINE( 383) this->changeDiff(null()); } HX_DEFINE_DYNAMIC_FUNC1(FreeplayState_obj,changeSelection,(void)) void FreeplayState_obj::positionHighscore(){ HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_386_positionHighscore) HXLINE( 387) ::flixel::text::FlxText _hx_tmp = this->scoreText; HXDLIN( 387) int _hx_tmp1 = ::flixel::FlxG_obj::width; HXDLIN( 387) _hx_tmp->set_x(((( (Float)(_hx_tmp1) ) - this->scoreText->get_width()) - ( (Float)(6) ))); HXLINE( 389) this->scoreBG->scale->set_x(((( (Float)(::flixel::FlxG_obj::width) ) - this->scoreText->x) + 6)); HXLINE( 390) this->scoreBG->set_x((( (Float)(::flixel::FlxG_obj::width) ) - (this->scoreBG->scale->x / ( (Float)(2) )))); HXLINE( 391) ::flixel::text::FlxText _hx_tmp2 = this->diffText; HXDLIN( 391) Float _hx_tmp3 = this->scoreBG->x; HXDLIN( 391) _hx_tmp2->set_x(( (Float)(::Std_obj::_hx_int((_hx_tmp3 + (this->scoreBG->get_width() / ( (Float)(2) ))))) )); HXLINE( 392) ::flixel::text::FlxText fh = this->diffText; HXDLIN( 392) Float fh1 = fh->x; HXDLIN( 392) fh->set_x((fh1 - (this->diffText->get_width() / ( (Float)(2) )))); } HX_DEFINE_DYNAMIC_FUNC0(FreeplayState_obj,positionHighscore,(void)) ::cpp::VirtualArray FreeplayState_obj::songsHeads; int FreeplayState_obj::curSelected; int FreeplayState_obj::curDifficulty; ::Array< int > FreeplayState_obj::coolColors; ::flixel::_hx_system::FlxSound FreeplayState_obj::vocals; void FreeplayState_obj::destroyFreeplayVocals(){ HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_302_destroyFreeplayVocals) HXLINE( 303) if (::hx::IsNotNull( ::FreeplayState_obj::vocals )) { HXLINE( 304) { HXLINE( 304) ::flixel::_hx_system::FlxSound _this = ::FreeplayState_obj::vocals; HXDLIN( 304) _this->cleanup(_this->autoDestroy,true); } HXLINE( 305) ::FreeplayState_obj::vocals->destroy(); } HXLINE( 307) ::FreeplayState_obj::vocals = null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(FreeplayState_obj,destroyFreeplayVocals,(void)) ::hx::ObjectPtr< FreeplayState_obj > FreeplayState_obj::__new( ::flixel::addons::transition::TransitionData TransIn, ::flixel::addons::transition::TransitionData TransOut) { ::hx::ObjectPtr< FreeplayState_obj > __this = new FreeplayState_obj(); __this->__construct(TransIn,TransOut); return __this; } ::hx::ObjectPtr< FreeplayState_obj > FreeplayState_obj::__alloc(::hx::Ctx *_hx_ctx, ::flixel::addons::transition::TransitionData TransIn, ::flixel::addons::transition::TransitionData TransOut) { FreeplayState_obj *__this = (FreeplayState_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(FreeplayState_obj), true, "FreeplayState")); *(void **)__this = FreeplayState_obj::_hx_vtable; __this->__construct(TransIn,TransOut); return __this; } FreeplayState_obj::FreeplayState_obj() { } void FreeplayState_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(FreeplayState); HX_MARK_MEMBER_NAME(songs,"songs"); HX_MARK_MEMBER_NAME(selector,"selector"); HX_MARK_MEMBER_NAME(scoreBG,"scoreBG"); HX_MARK_MEMBER_NAME(scoreText,"scoreText"); HX_MARK_MEMBER_NAME(diffText,"diffText"); HX_MARK_MEMBER_NAME(lerpScore,"lerpScore"); HX_MARK_MEMBER_NAME(lerpRating,"lerpRating"); HX_MARK_MEMBER_NAME(intendedScore,"intendedScore"); HX_MARK_MEMBER_NAME(intendedRating,"intendedRating"); HX_MARK_MEMBER_NAME(grpSongs,"grpSongs"); HX_MARK_MEMBER_NAME(curPlaying,"curPlaying"); HX_MARK_MEMBER_NAME(iconArray,"iconArray"); HX_MARK_MEMBER_NAME(bg,"bg"); HX_MARK_MEMBER_NAME(intendedColor,"intendedColor"); HX_MARK_MEMBER_NAME(colorTween,"colorTween"); HX_MARK_MEMBER_NAME(instPlaying,"instPlaying"); ::flixel::addons::ui::FlxUIState_obj::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } void FreeplayState_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(songs,"songs"); HX_VISIT_MEMBER_NAME(selector,"selector"); HX_VISIT_MEMBER_NAME(scoreBG,"scoreBG"); HX_VISIT_MEMBER_NAME(scoreText,"scoreText"); HX_VISIT_MEMBER_NAME(diffText,"diffText"); HX_VISIT_MEMBER_NAME(lerpScore,"lerpScore"); HX_VISIT_MEMBER_NAME(lerpRating,"lerpRating"); HX_VISIT_MEMBER_NAME(intendedScore,"intendedScore"); HX_VISIT_MEMBER_NAME(intendedRating,"intendedRating"); HX_VISIT_MEMBER_NAME(grpSongs,"grpSongs"); HX_VISIT_MEMBER_NAME(curPlaying,"curPlaying"); HX_VISIT_MEMBER_NAME(iconArray,"iconArray"); HX_VISIT_MEMBER_NAME(bg,"bg"); HX_VISIT_MEMBER_NAME(intendedColor,"intendedColor"); HX_VISIT_MEMBER_NAME(colorTween,"colorTween"); HX_VISIT_MEMBER_NAME(instPlaying,"instPlaying"); ::flixel::addons::ui::FlxUIState_obj::__Visit(HX_VISIT_ARG); } ::hx::Val FreeplayState_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"bg") ) { return ::hx::Val( bg ); } break; case 5: if (HX_FIELD_EQ(inName,"songs") ) { return ::hx::Val( songs ); } break; case 6: if (HX_FIELD_EQ(inName,"create") ) { return ::hx::Val( create_dyn() ); } if (HX_FIELD_EQ(inName,"update") ) { return ::hx::Val( update_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"scoreBG") ) { return ::hx::Val( scoreBG ); } if (HX_FIELD_EQ(inName,"addSong") ) { return ::hx::Val( addSong_dyn() ); } if (HX_FIELD_EQ(inName,"addWeek") ) { return ::hx::Val( addWeek_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"selector") ) { return ::hx::Val( selector ); } if (HX_FIELD_EQ(inName,"diffText") ) { return ::hx::Val( diffText ); } if (HX_FIELD_EQ(inName,"grpSongs") ) { return ::hx::Val( grpSongs ); } break; case 9: if (HX_FIELD_EQ(inName,"scoreText") ) { return ::hx::Val( scoreText ); } if (HX_FIELD_EQ(inName,"lerpScore") ) { return ::hx::Val( lerpScore ); } if (HX_FIELD_EQ(inName,"iconArray") ) { return ::hx::Val( iconArray ); } break; case 10: if (HX_FIELD_EQ(inName,"lerpRating") ) { return ::hx::Val( lerpRating ); } if (HX_FIELD_EQ(inName,"curPlaying") ) { return ::hx::Val( curPlaying ); } if (HX_FIELD_EQ(inName,"colorTween") ) { return ::hx::Val( colorTween ); } if (HX_FIELD_EQ(inName,"changeDiff") ) { return ::hx::Val( changeDiff_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"instPlaying") ) { return ::hx::Val( instPlaying ); } break; case 13: if (HX_FIELD_EQ(inName,"intendedScore") ) { return ::hx::Val( intendedScore ); } if (HX_FIELD_EQ(inName,"intendedColor") ) { return ::hx::Val( intendedColor ); } if (HX_FIELD_EQ(inName,"closeSubState") ) { return ::hx::Val( closeSubState_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"intendedRating") ) { return ::hx::Val( intendedRating ); } break; case 15: if (HX_FIELD_EQ(inName,"changeSelection") ) { return ::hx::Val( changeSelection_dyn() ); } break; case 17: if (HX_FIELD_EQ(inName,"positionHighscore") ) { return ::hx::Val( positionHighscore_dyn() ); } } return super::__Field(inName,inCallProp); } bool FreeplayState_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"vocals") ) { outValue = ( vocals ); return true; } break; case 10: if (HX_FIELD_EQ(inName,"songsHeads") ) { outValue = ( songsHeads ); return true; } if (HX_FIELD_EQ(inName,"coolColors") ) { outValue = ( coolColors ); return true; } break; case 11: if (HX_FIELD_EQ(inName,"curSelected") ) { outValue = ( curSelected ); return true; } break; case 13: if (HX_FIELD_EQ(inName,"curDifficulty") ) { outValue = ( curDifficulty ); return true; } break; case 21: if (HX_FIELD_EQ(inName,"destroyFreeplayVocals") ) { outValue = destroyFreeplayVocals_dyn(); return true; } } return false; } ::hx::Val FreeplayState_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"bg") ) { bg=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"songs") ) { songs=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"scoreBG") ) { scoreBG=inValue.Cast< ::flixel::FlxSprite >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"selector") ) { selector=inValue.Cast< ::flixel::text::FlxText >(); return inValue; } if (HX_FIELD_EQ(inName,"diffText") ) { diffText=inValue.Cast< ::flixel::text::FlxText >(); return inValue; } if (HX_FIELD_EQ(inName,"grpSongs") ) { grpSongs=inValue.Cast< ::flixel::group::FlxTypedGroup >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"scoreText") ) { scoreText=inValue.Cast< ::flixel::text::FlxText >(); return inValue; } if (HX_FIELD_EQ(inName,"lerpScore") ) { lerpScore=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"iconArray") ) { iconArray=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"lerpRating") ) { lerpRating=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"curPlaying") ) { curPlaying=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"colorTween") ) { colorTween=inValue.Cast< ::flixel::tweens::FlxTween >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"instPlaying") ) { instPlaying=inValue.Cast< int >(); return inValue; } break; case 13: if (HX_FIELD_EQ(inName,"intendedScore") ) { intendedScore=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"intendedColor") ) { intendedColor=inValue.Cast< int >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"intendedRating") ) { intendedRating=inValue.Cast< Float >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool FreeplayState_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"vocals") ) { vocals=ioValue.Cast< ::flixel::_hx_system::FlxSound >(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"songsHeads") ) { songsHeads=ioValue.Cast< ::cpp::VirtualArray >(); return true; } if (HX_FIELD_EQ(inName,"coolColors") ) { coolColors=ioValue.Cast< ::Array< int > >(); return true; } break; case 11: if (HX_FIELD_EQ(inName,"curSelected") ) { curSelected=ioValue.Cast< int >(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"curDifficulty") ) { curDifficulty=ioValue.Cast< int >(); return true; } } return false; } void FreeplayState_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("songs",fe,36,c7,80)); outFields->push(HX_("selector",1f,33,6d,b1)); outFields->push(HX_("scoreBG",97,a5,9a,78)); outFields->push(HX_("scoreText",1f,7d,bd,dc)); outFields->push(HX_("diffText",52,3b,1b,21)); outFields->push(HX_("lerpScore",5b,81,4d,e7)); outFields->push(HX_("lerpRating",f4,6d,a2,f2)); outFields->push(HX_("intendedScore",a7,fd,7c,89)); outFields->push(HX_("intendedRating",28,b4,ff,39)); outFields->push(HX_("grpSongs",d9,dc,c7,63)); outFields->push(HX_("curPlaying",ce,61,01,95)); outFields->push(HX_("iconArray",60,3f,53,5f)); outFields->push(HX_("bg",c5,55,00,00)); outFields->push(HX_("intendedColor",b8,fb,ff,5a)); outFields->push(HX_("colorTween",08,c2,dc,3d)); outFields->push(HX_("instPlaying",48,98,f0,7f)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo FreeplayState_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(FreeplayState_obj,songs),HX_("songs",fe,36,c7,80)}, {::hx::fsObject /* ::flixel::text::FlxText */ ,(int)offsetof(FreeplayState_obj,selector),HX_("selector",1f,33,6d,b1)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(FreeplayState_obj,scoreBG),HX_("scoreBG",97,a5,9a,78)}, {::hx::fsObject /* ::flixel::text::FlxText */ ,(int)offsetof(FreeplayState_obj,scoreText),HX_("scoreText",1f,7d,bd,dc)}, {::hx::fsObject /* ::flixel::text::FlxText */ ,(int)offsetof(FreeplayState_obj,diffText),HX_("diffText",52,3b,1b,21)}, {::hx::fsInt,(int)offsetof(FreeplayState_obj,lerpScore),HX_("lerpScore",5b,81,4d,e7)}, {::hx::fsFloat,(int)offsetof(FreeplayState_obj,lerpRating),HX_("lerpRating",f4,6d,a2,f2)}, {::hx::fsInt,(int)offsetof(FreeplayState_obj,intendedScore),HX_("intendedScore",a7,fd,7c,89)}, {::hx::fsFloat,(int)offsetof(FreeplayState_obj,intendedRating),HX_("intendedRating",28,b4,ff,39)}, {::hx::fsObject /* ::flixel::group::FlxTypedGroup */ ,(int)offsetof(FreeplayState_obj,grpSongs),HX_("grpSongs",d9,dc,c7,63)}, {::hx::fsBool,(int)offsetof(FreeplayState_obj,curPlaying),HX_("curPlaying",ce,61,01,95)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(FreeplayState_obj,iconArray),HX_("iconArray",60,3f,53,5f)}, {::hx::fsObject /* ::flixel::FlxSprite */ ,(int)offsetof(FreeplayState_obj,bg),HX_("bg",c5,55,00,00)}, {::hx::fsInt,(int)offsetof(FreeplayState_obj,intendedColor),HX_("intendedColor",b8,fb,ff,5a)}, {::hx::fsObject /* ::flixel::tweens::FlxTween */ ,(int)offsetof(FreeplayState_obj,colorTween),HX_("colorTween",08,c2,dc,3d)}, {::hx::fsInt,(int)offsetof(FreeplayState_obj,instPlaying),HX_("instPlaying",48,98,f0,7f)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo FreeplayState_obj_sStaticStorageInfo[] = { {::hx::fsObject /* ::cpp::VirtualArray */ ,(void *) &FreeplayState_obj::songsHeads,HX_("songsHeads",75,f3,e0,d9)}, {::hx::fsInt,(void *) &FreeplayState_obj::curSelected,HX_("curSelected",fb,eb,ab,32)}, {::hx::fsInt,(void *) &FreeplayState_obj::curDifficulty,HX_("curDifficulty",db,b7,38,a7)}, {::hx::fsObject /* ::Array< int > */ ,(void *) &FreeplayState_obj::coolColors,HX_("coolColors",59,b1,81,26)}, {::hx::fsObject /* ::flixel::_hx_system::FlxSound */ ,(void *) &FreeplayState_obj::vocals,HX_("vocals",5e,10,51,59)}, { ::hx::fsUnknown, 0, null()} }; #endif static ::String FreeplayState_obj_sMemberFields[] = { HX_("songs",fe,36,c7,80), HX_("selector",1f,33,6d,b1), HX_("scoreBG",97,a5,9a,78), HX_("scoreText",1f,7d,bd,dc), HX_("diffText",52,3b,1b,21), HX_("lerpScore",5b,81,4d,e7), HX_("lerpRating",f4,6d,a2,f2), HX_("intendedScore",a7,fd,7c,89), HX_("intendedRating",28,b4,ff,39), HX_("grpSongs",d9,dc,c7,63), HX_("curPlaying",ce,61,01,95), HX_("iconArray",60,3f,53,5f), HX_("bg",c5,55,00,00), HX_("intendedColor",b8,fb,ff,5a), HX_("colorTween",08,c2,dc,3d), HX_("create",fc,66,0f,7c), HX_("closeSubState",49,18,32,04), HX_("addSong",96,66,95,88), HX_("addWeek",b5,a2,32,8b), HX_("instPlaying",48,98,f0,7f), HX_("update",09,86,05,87), HX_("changeDiff",95,91,b2,1c), HX_("changeSelection",bc,98,b5,48), HX_("positionHighscore",c7,9a,8a,14), ::String(null()) }; static void FreeplayState_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(FreeplayState_obj::songsHeads,"songsHeads"); HX_MARK_MEMBER_NAME(FreeplayState_obj::curSelected,"curSelected"); HX_MARK_MEMBER_NAME(FreeplayState_obj::curDifficulty,"curDifficulty"); HX_MARK_MEMBER_NAME(FreeplayState_obj::coolColors,"coolColors"); HX_MARK_MEMBER_NAME(FreeplayState_obj::vocals,"vocals"); }; #ifdef HXCPP_VISIT_ALLOCS static void FreeplayState_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(FreeplayState_obj::songsHeads,"songsHeads"); HX_VISIT_MEMBER_NAME(FreeplayState_obj::curSelected,"curSelected"); HX_VISIT_MEMBER_NAME(FreeplayState_obj::curDifficulty,"curDifficulty"); HX_VISIT_MEMBER_NAME(FreeplayState_obj::coolColors,"coolColors"); HX_VISIT_MEMBER_NAME(FreeplayState_obj::vocals,"vocals"); }; #endif ::hx::Class FreeplayState_obj::__mClass; static ::String FreeplayState_obj_sStaticFields[] = { HX_("songsHeads",75,f3,e0,d9), HX_("curSelected",fb,eb,ab,32), HX_("curDifficulty",db,b7,38,a7), HX_("coolColors",59,b1,81,26), HX_("vocals",5e,10,51,59), HX_("destroyFreeplayVocals",b8,0f,ad,93), ::String(null()) }; void FreeplayState_obj::__register() { FreeplayState_obj _hx_dummy; FreeplayState_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("FreeplayState",31,61,f2,b3); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &FreeplayState_obj::__GetStatic; __mClass->mSetStaticField = &FreeplayState_obj::__SetStatic; __mClass->mMarkFunc = FreeplayState_obj_sMarkStatics; __mClass->mStatics = ::hx::Class_obj::dupFunctions(FreeplayState_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(FreeplayState_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< FreeplayState_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = FreeplayState_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = FreeplayState_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = FreeplayState_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void FreeplayState_obj::__boot() { { HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_25_boot) HXDLIN( 25) songsHeads = ::cpp::VirtualArray_obj::__new(6)->init(0,::cpp::VirtualArray_obj::__new(1)->init(0,HX_("dad",47,36,4c,00)))->init(1,::cpp::VirtualArray_obj::__new(3)->init(0,HX_("spooky",eb,bd,9e,c1))->init(1,HX_("spooky",eb,bd,9e,c1))->init(2,HX_("monster",1a,54,b0,b8)))->init(2,::cpp::VirtualArray_obj::__new(1)->init(0,HX_("pico",e5,e8,57,4a)))->init(3,::cpp::VirtualArray_obj::__new(1)->init(0,HX_("mom",cb,16,53,00)))->init(4,::cpp::VirtualArray_obj::__new(3)->init(0,HX_("parents",09,80,c6,e0))->init(1,HX_("parents",09,80,c6,e0))->init(2,HX_("monster",1a,54,b0,b8)))->init(5,::cpp::VirtualArray_obj::__new(3)->init(0,HX_("senpai",3c,df,8d,6b))->init(1,HX_("senpai",3c,df,8d,6b))->init(2,HX_("spirit",31,bb,a9,bd))); } { HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_37_boot) HXDLIN( 37) curSelected = 0; } { HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_38_boot) HXDLIN( 38) curDifficulty = 1; } { HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_52_boot) HXDLIN( 52) coolColors = ::Array_obj< int >::__new(0); } { HX_STACKFRAME(&_hx_pos_86166a84e8de7ace_202_boot) HXDLIN( 202) vocals = null(); } }
49.350622
735
0.700992
[ "3d" ]
f69610b36aac3f264306ebf8506d8b1833356a16
4,796
cpp
C++
src/NumericalAlgorithms/LinearAlgebra/FindGeneralizedEigenvalues.cpp
keefemitman/spectre
a8c3e387addc34d8a4544728f405991e6c9e5e38
[ "MIT" ]
null
null
null
src/NumericalAlgorithms/LinearAlgebra/FindGeneralizedEigenvalues.cpp
keefemitman/spectre
a8c3e387addc34d8a4544728f405991e6c9e5e38
[ "MIT" ]
null
null
null
src/NumericalAlgorithms/LinearAlgebra/FindGeneralizedEigenvalues.cpp
keefemitman/spectre
a8c3e387addc34d8a4544728f405991e6c9e5e38
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #include "NumericalAlgorithms/LinearAlgebra/FindGeneralizedEigenvalues.hpp" #include <cstddef> #include <ostream> #include <vector> #include "DataStructures/DataVector.hpp" #include "DataStructures/Matrix.hpp" #include "ErrorHandling/Assert.hpp" #include "ErrorHandling/Error.hpp" #include "Utilities/Gsl.hpp" // LAPACK routine to do the generalized eigenvalue problem extern "C" { extern void dggev_(char*, char*, int*, double*, int*, double*, int*, double*, double*, double*, double*, int*, double*, int*, double*, int*, int*); } void find_generalized_eigenvalues( const gsl::not_null<DataVector*> eigenvalues_real_part, const gsl::not_null<DataVector*> eigenvalues_imaginary_part, const gsl::not_null<Matrix*> eigenvectors, Matrix matrix_a, Matrix matrix_b) noexcept { // Sanity checks on the sizes of the vectors and matrices const size_t number_of_rows = matrix_a.rows(); ASSERT(number_of_rows == matrix_a.columns(), "Matrix A should be square, but A has " << matrix_a.rows() << " rows and " << matrix_a.columns() << " columns."); ASSERT(number_of_rows == matrix_b.rows() and number_of_rows == matrix_b.columns(), "Matrix A and matrix B should be the same size, but A has " << matrix_a.rows() << " rows and " << matrix_a.columns() << " columns, while B has " << matrix_b.rows() << " rows and " << matrix_b.columns() << " columns."); ASSERT(number_of_rows == eigenvectors->rows() and number_of_rows == eigenvectors->columns(), "Matrix A and matrix eigenvectors should have the same size, " "but A has " << matrix_a.rows() << " rows and " << matrix_a.columns() << " columns, while the eigenvectors matrix " << "has " << eigenvectors->rows() << " rows and " << eigenvectors->columns() << " columns."); ASSERT(number_of_rows == eigenvalues_real_part->size() and number_of_rows == eigenvalues_imaginary_part->size(), "eigenvalues DataVector sizes should equal number of columns " "in Matrix A, but A has " << matrix_a.columns() << " columns, while the real eigenvalues DataVector size is " << eigenvalues_real_part->size() << " and the imaginary eigenvalues DataVector size is " << eigenvalues_imaginary_part->size() << "."); // Set up parameters for the lapack call // Lapack uses chars to decide whether to compute the left eigenvectors, // the right eigenvectors, both, or neither. 'N' means do not compute, // 'V' means do compute. Note: not const because lapack does not want this // option const. char compute_left_eigenvectors = 'N'; char compute_right_eigenvectors = 'V'; // Lapack expects the sizes to be ints, not size_t. // NOTE: not const because lapack function dggev_() arguments // are not const. auto matrix_and_vector_size = static_cast<int>(number_of_rows); // Lapack splits the eigenvalues into unnormalized real and imaginary // parts, which it calls alphar and alphai, and a normalization, // which it calls beta. The real and imaginary parts of the eigenvalues are // found by dividing the unnormalized results by the normalization. DataVector eigenvalue_normalization(number_of_rows, 0.0); // Lapack uses a work vector, that should have a size 8N // for doing eigenvalue problems with NxN matrices // Note: a non-const int, not size_t, because lapack wants a non-const int int work_size = number_of_rows * 8; std::vector<double> lapack_work(static_cast<size_t>(work_size), 0.0); // Lapack uses an integer called info to return its status // info = 0 : success // info = -i: ith argument had bad value // info > 0: some other failure int info = 0; int matrix_a_spacing = matrix_a.spacing(); int matrix_b_spacing = matrix_b.spacing(); int eigenvectors_spacing = eigenvectors->spacing(); dggev_(&compute_left_eigenvectors, &compute_right_eigenvectors, &matrix_and_vector_size, matrix_a.data(), &matrix_a_spacing, matrix_b.data(), &matrix_b_spacing, eigenvalues_real_part->data(), eigenvalues_imaginary_part->data(), eigenvalue_normalization.data(), eigenvectors->data(), &eigenvectors_spacing, eigenvectors->data(), &eigenvectors_spacing, lapack_work.data(), &work_size, &info); if (UNLIKELY(info != 0)) { ERROR( "Lapack failed to compute generalized eigenvectors. Lapack's dggev " "INFO = " << info); } *eigenvalues_real_part /= eigenvalue_normalization; *eigenvalues_imaginary_part /= eigenvalue_normalization; }
44
80
0.673686
[ "vector" ]
f697f586a8f4fa17dd70fe194cf8df793d57d078
1,423
hpp
C++
src/rocket/parameter/interpolate_parameter.hpp
sus304/ForRocket
10fdcd0ce5a30fbbb4fec6315bcd64314bec6c12
[ "MIT" ]
21
2015-12-17T14:19:24.000Z
2021-09-09T07:17:17.000Z
src/rocket/parameter/interpolate_parameter.hpp
sus304/ForRocket
10fdcd0ce5a30fbbb4fec6315bcd64314bec6c12
[ "MIT" ]
2
2015-12-17T19:45:50.000Z
2021-02-07T05:28:34.000Z
src/rocket/parameter/interpolate_parameter.hpp
sus304/ForRocket
10fdcd0ce5a30fbbb4fec6315bcd64314bec6c12
[ "MIT" ]
10
2015-12-17T19:13:51.000Z
2021-09-27T01:14:14.000Z
// ****************************************************** // Project Name : ForRocket // File Name : interpolate_parameter.hpp // Creation Date : 2019/12/03 // // Copyright (c) 2019 Susumu Tanaka. All rights reserved. // ****************************************************** #ifndef INTERPOLATEPARAMETER_HPP_ #define INTERPOLATEPARAMETER_HPP_ #include <vector> #include "interpolate.hpp" namespace forrocket { class InterpolateParameter { public: InterpolateParameter(); InterpolateParameter(const double value); InterpolateParameter(const std::vector<double> x_axis_src, const std::vector<double> value_src, std::string fill_value); InterpolateParameter(const std::vector<double> x_axis_src, const std::vector<double> y_axis_src, const std::vector<double> value_src, std::string fill_value); InterpolateParameter(const InterpolateParameter& from); InterpolateParameter& operator=(const InterpolateParameter& from); double operator()(const double x_axis_value); double operator()(const double x_axis_value, const double y_axis_value); private: bool enable_1dlog; bool enable_2dlog; double value_const; interpolate::Interp1d polator_1d; interpolate::Interp2d polator_2d; }; } #endif
34.707317
171
0.607168
[ "vector" ]
f698b11ade6ef7e5d3b365e1274fb8d4d72db4f9
6,686
cpp
C++
1263. Minimum Moves to Move a Box to Their Target Location.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
1
2020-10-11T08:10:53.000Z
2020-10-11T08:10:53.000Z
1263. Minimum Moves to Move a Box to Their Target Location.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
1263. Minimum Moves to Move a Box to Their Target Location.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
// // Created by Yuyang Huang on 9/7/21. // /* * TODO: not completed */ /* * 1263. Minimum Moves to Move a Box to Their Target Location * Hard * * A storekeeper is a game in which the player pushes boxes around in a warehouse * trying to get them to target locations. * * The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. * Your task is to move the box 'B' to the target position 'T' under the following rules: * The character 'S' represents the player. * The player can move up, down, left, right in grid if it is a floor (empty cell). * The character '.' represents the floor which means a free cell to walk. * The character '#' represents the wall which means an obstacle (impossible to walk there). * There is only one box 'B' and one target cell 'T' in the grid. * The box can be moved to an adjacent free cell by standing next to the box * and then moving in the direction of the box. This is a push. * * The player cannot walk through the box. * Return the minimum number of pushes to move the box to the target. * If there is no way to reach the target, return -1. * * Example 1: * Input: grid = * [["#","#","#","#","#","#"], * ["#","T","#","#","#","#"], * ["#",".",".","B",".","#"], * ["#",".","#","#",".","#"], * ["#",".",".",".","S","#"], * ["#","#","#","#","#","#"]] * Output: 3 * Explanation: We return only the number of times the box is pushed. * * Example 2: * Input: grid = [["#","#","#","#","#","#"], * ["#","T","#","#","#","#"], * ["#",".",".","B",".","#"], * ["#","#","#","#",".","#"], * ["#",".",".",".","S","#"], * ["#","#","#","#","#","#"]] * Output: -1 * * Example 3: * Input: grid = [["#","#","#","#","#","#"], * ["#","T",".",".","#","#"], * ["#",".","#","B",".","#"], * ["#",".",".",".",".","#"], * ["#",".",".",".","S","#"], * ["#","#","#","#","#","#"]] * Output: 5 * Explanation: push the box down, left, left, up and up. * * Example 4: * Input: grid = * [["#","#","#","#","#","#","#"], * ["#","S","#",".","B","T","#"], * ["#","#","#","#","#","#","#"]] * Output: -1 * * Constraints: * m == grid.length * n == grid[i].length * 1 <= m, n <= 20 * grid contains only characters '.', '#', 'S', 'T', or 'B'. * There is only one character 'S', 'B', and 'T' in the grid. */ #include "LeetCodeLib.h" class Solution { public: int minPushBox(vector<vector<char>> &grid) { vector<vector<int>> dist(grid.size(), vector<int>(grid[0].size(), 100)); auto targetLoc = findTarget(grid, 'T'); dist[targetLoc.first][targetLoc.second] = 0; queue<pair<int, int>> points; points.emplace(targetLoc); queue<pair<int, int>> pushPoints; pushPoints.emplace(targetLoc); while (!points.empty()) { int x, y; auto point = points.front(); points.pop(); auto pushPoint = pushPoints.front(); pushPoints.pop(); x = point.first; y = point.second; if (grid[x][y] == 'B') { if (playerToBrick(grid, pushPoint)) { return dist[x][y]; } continue; } for (auto &move: moves) { int boxLocX, boxLocY, playerLocX, playerLocY; boxLocX = x + move[0]; boxLocY = y + move[1]; playerLocX = x + 2 * move[0]; playerLocY = y + 2 * move[1]; if (validPoint(boxLocX, boxLocY, grid.size(), grid.front().size()) && validLocation(boxLocX, boxLocY, grid) && validPoint(playerLocX, playerLocY, grid.size(), grid.front().size()) && validLocation(playerLocX, playerLocY, grid)) { if (dist[x][y] + 1 < dist[boxLocX][boxLocY]) { dist[boxLocX][boxLocY] = min(dist[x][y] + 1, dist[boxLocX][boxLocY]); points.emplace(make_pair(boxLocX, boxLocY)); pushPoints.emplace(make_pair(playerLocX, playerLocY)); } } } // PrintVectorVector(dist); // cout << endl; } return -1; } private: vector<vector<int>> moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; bool validPoint(int x, int y, int xLimit, int yLimit) { return 0 <= x && x < xLimit && 0 <= y && y < yLimit; } bool validLocation(int x, int y, vector<vector<char>> &grid) { return grid[x][y] != '#'; } pair<int, int> findTarget(vector<vector<char>> &grid, char target) { for (int row = 0; row < grid.size(); ++row) { for (int col = 0; col < grid[0].size(); ++col) { if (grid[row][col] == target) { return make_pair(row, col); } } } return make_pair(-1, -1); } bool playerToBrick(vector<vector<char>> &grid, pair<int, int> pushPos) { auto playerLoc = findTarget(grid, 'S'); queue<pair<int, int>> points; points.push(make_pair(playerLoc.first, playerLoc.second)); while (!points.empty()) { int x, y; auto point = points.front(); points.pop(); x = point.first; y = point.second; if (x == pushPos.first && y == pushPos.second) { return true; } for (auto &move: moves) { int nextX = x + move[0]; int nextY = y + move[1]; if (validPoint(nextX, nextY, grid.size(), grid.front().size()) && validLocation(nextX, nextY, grid)) { points.emplace(make_pair(nextX, nextY)); } } } return false; } }; int main() { Solution solution; vector<vector<char>> grid; grid = {{'#', '#', '#', '#', '#', '#'}, {'#', 'T', '#', '#', '#', '#'}, {'#', '.', '.', 'B', '.', '#'}, {'#', '.', '#', '#', '.', '#'}, {'#', '.', '.', '.', 'S', '#'}, {'#', '#', '#', '#', '#', '#'}}; PrintSingleResult(solution.minPushBox(grid)); grid = {{'#', '#', '#', '#', '#', '#'}, {'#', 'T', '#', '#', '#', '#'}, {'#', '.', '.', 'B', '.', '#'}, {'#', '#', '#', '#', '.', '#'}, {'#', '.', '.', '.', 'S', '#'}, {'#', '#', '#', '#', '#', '#'}}; PrintSingleResult(solution.minPushBox(grid)); grid = {{'#', '#', '#', '#', '#', '#'}, {'#', 'T', '.', '.', '#', '#'}, {'#', '.', '#', 'B', '.', '#'}, {'#', '.', '.', '.', '.', '#'}, {'#', '.', '.', '.', 'S', '#'}, {'#', '#', '#', '#', '#', '#'}}; PrintSingleResult(solution.minPushBox(grid)); grid = {{'#', '#', '#', '#', '#', '#', '#'}, {'#', 'S', '#', '.', 'B', 'T', '#'}, {'#', '#', '#', '#', '#', '#', '#'}}; PrintSingleResult(solution.minPushBox(grid)); grid = {{'#', '.', '.', '#', '#', '#', '#', '#'}, {'#', '.', '.', 'T', '#', '.', '.', '#'}, {'#', '.', '.', '.', '#', 'B', '.', '#'}, {'#', '.', '.', '.', '.', '.', '.', '#'}, {'#', '.', '.', '.', '#', '.', 'S', '#'}, {'#', '.', '.', '#', '#', '#', '#', '#'}}; }
29.453744
107
0.450045
[ "vector" ]
f69b0c1bd490439391fea8fbda5ec1db57ada289
5,101
cpp
C++
src/Transport.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
1
2017-10-13T06:00:59.000Z
2017-10-13T06:00:59.000Z
src/Transport.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
null
null
null
src/Transport.cpp
georgebrock/task
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2010 - 2014, Johannes Schlatow. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <stdlib.h> #include <util.h> #include <string.h> #include <errno.h> #include <text.h> #include <i18n.h> #include <Transport.h> #include <TransportSSH.h> #include <TransportRSYNC.h> #include <TransportCurl.h> #include <TransportShell.h> //////////////////////////////////////////////////////////////////////////////// Transport::Transport (const Uri& uri) { _executable = ""; this->_uri = uri; } //////////////////////////////////////////////////////////////////////////////// Transport::~Transport () { } //////////////////////////////////////////////////////////////////////////////// Transport* Transport::getTransport(const Uri& uri) { if (uri._protocol == "ssh") { return new TransportSSH(uri); } else if (uri._protocol == "rsync") { return new TransportRSYNC(uri); } else if ( (uri._protocol == "http") || (uri._protocol == "https") || (uri._protocol == "ftp") ) { return new TransportCurl(uri); } else if ( uri._protocol == "sh+cp") { return new TransportShell(uri); } return NULL; } //////////////////////////////////////////////////////////////////////////////// int Transport::execute() { // quote arguments std::vector<std::string>::iterator it = _arguments.begin (); for (; it != _arguments.end (); it++) { // quote until the first appearance of '{' size_t pos = it->find('{'); if (pos != 0) { // '{' is not the first character it->insert(0, "\""); if (pos != std::string::npos) it->insert(pos+1, "\""); else it->append("\""); } } int result = ::execute (_executable, _arguments); int err; switch (result) { case 127: throw format (STRING_TRANSPORT_NORUN, _executable); case -1: err = errno; throw format (STRING_TRANSPORT_NOFORK, _executable, ::strerror(err)); default: return result; } } //////////////////////////////////////////////////////////////////////////////// bool Transport::is_directory(const std::string& path) { return path[path.length()-1] == '/'; } //////////////////////////////////////////////////////////////////////////////// bool Transport::is_filelist(const std::string& path) { return (path.find ("*") != std::string::npos) || (path.find ("?") != std::string::npos) || (path.find ("{") != std::string::npos); } //////////////////////////////////////////////////////////////////////////////// void Transport::expand_braces(const std::string& path, const std::string& sourceortarget, std::vector<std::string>& paths) { // Is is_filelist appropriate here? We only care about {} if (is_filelist(path)) { std::string::size_type pos; pos = path.find("{"); if (pos == std::string::npos) throw std::string (STRING_TRANSPORT_CURL_WILDCD); if (!is_directory(sourceortarget)) throw format (STRING_TRANSPORT_URI_NODIR, sourceortarget); std::string toSplit; std::string suffix; std::string prefix = path.substr (0, pos); std::vector<std::string> splitted; toSplit = path.substr (pos+1); pos = toSplit.find ("}"); suffix = toSplit.substr (pos+1); split (splitted, toSplit.substr(0, pos), ','); std::vector <std::string>::iterator file; for (file = splitted.begin (); file != splitted.end (); ++file) { std::cout << " -- " << (prefix + *file + suffix) << "\n"; paths.push_back (prefix + *file + suffix); } } else { // Not brace expandable - use the path as is. paths.push_back (path); } } ////////////////////////////////////////////////////////////////////////////////
30.54491
80
0.538718
[ "vector" ]
f69cee0ca68cc2ef7dc310f53b7c8184bce0f176
989
hpp
C++
hiro/gtk/widget/icon-view.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
hiro/gtk/widget/icon-view.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
hiro/gtk/widget/icon-view.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#if defined(Hiro_IconView) namespace hiro { struct pIconView : pWidget { Declare(IconView, Widget) auto append(sIconViewItem item) -> void; auto remove(sIconViewItem item) -> void; auto reset() -> void override; auto setBackgroundColor(Color color) -> void; auto setBatchable(bool batchable) -> void; auto setFlow(Orientation flow) -> void; auto setForegroundColor(Color color) -> void; auto setGeometry(Geometry geometry) -> void override; auto setItemIcon(u32 position, const image& icon) -> void; auto setItemSelected(u32 position, bool selected) -> void; auto setItemSelected(const vector<s32>& selections) -> void; auto setItemSelectedAll() -> void; auto setItemSelectedNone() -> void; auto setItemText(u32 position, const string& text) -> void; auto setOrientation(Orientation orientation) -> void; auto _updateSelected() -> void; GtkWidget* subWidget = nullptr; GtkListStore* store = nullptr; vector<u32> currentSelection; }; } #endif
29.088235
62
0.728008
[ "geometry", "vector" ]
f6a3e9e01e16d1e367c8ddb20c9bffbd7c9ec250
47,912
cpp
C++
MCMCnapdev.cpp
MoisesExpositoAlonso/popgensim
44bed96e971ce058a4c6de7f351c6aad24270d18
[ "MIT" ]
null
null
null
MCMCnapdev.cpp
MoisesExpositoAlonso/popgensim
44bed96e971ce058a4c6de7f351c6aad24270d18
[ "MIT" ]
null
null
null
MCMCnapdev.cpp
MoisesExpositoAlonso/popgensim
44bed96e971ce058a4c6de7f351c6aad24270d18
[ "MIT" ]
1
2020-01-27T17:55:48.000Z
2020-01-27T17:55:48.000Z
#include <stdlib.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <random> #include <chrono> #include <ctime> #include <cstdio> #include <stdio.h> #include <math.h> #include <vector> #include <list> #include <iostream> #include <string> // when armadillo is loaded, remove this below //#include <Rcpp.h> #include <RcppArmadillo.h> #include <RcppArmadilloExtensions/sample.h> #include <RcppEigen.h> using namespace Rcpp; using namespace std; #include <bigmemory/MatrixAccessor.hpp> #include <bigmemory/isna.hpp> // [[Rcpp::depends(BH)]] // [[Rcpp::depends(bigmemory)]] // [[Rcpp::depends(Rcpp)]] // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::depends(RcppEigen)]] // Enable C++11 via this plugin (Rcpp 0.10.3 or later) // [[Rcpp::plugins(cpp11)]] //////////////////////////////////////////////////////////////////////////////// /// Profiling utilities //////////////////////////////////////////////////////////////////////////////// // RcppExport SEXP start_profiler(SEXP str) { // ProfilerStart(as<const char*>(str)); // return R_NilValue; // } // RcppExport SEXP stop_profiler() { // ProfilerStop(); // return R_NilValue; // } //////////////////////////////////////////////////////////////////////////////// /// Utilities //////////////////////////////////////////////////////////////////////////////// #define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||" #define PBWIDTH 60 void printProgress (double percentage) { int val = (int) (percentage * 100); int lpad = (int) (percentage * PBWIDTH); int rpad = PBWIDTH - lpad; printf ("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, ""); fflush (stdout); } template <typename T> Rcpp::NumericVector arma2vec(const T& x) { return Rcpp::NumericVector(x.begin(), x.end()); } template <typename T> arma::vec vec2arma(const T& x) { return Rcpp::as<arma::vec>(x); } // [[Rcpp::export]] NumericVector sample_num( NumericVector x, int size, bool replace, NumericVector prob = NumericVector::create() ) { NumericVector ret = RcppArmadillo::sample(x, size, replace, prob) ; return ret ; } // #define MIN_NUM = std::numeric_limits<float>::min(); // problem is that it does not know the type const double MIN_NUM = std::numeric_limits<float>::min(); // #define PIraw = 3.14159265358979323846; // const double PI= 3.14159265358979323846; // # define PI 3.14159265358979323846 /* pi */ //const double MAX_NUM = std::numeric_limits<float>::max(); //////////////////////////////////////////////////////////////////////////////// /// Matrix and LD utilities //////////////////////////////////////////////////////////////////////////////// // [[Rcpp::export]] arma::Mat<double> BMsubset(SEXP A, const arma::uvec & myrows, const arma::uvec & mycols ){ Rcpp::XPtr<BigMatrix> bigMat(A); arma::Mat<double> X0((double*) bigMat->matrix(), bigMat->nrow(), bigMat->ncol(), false, false); // consider saying true, perhaps is faster // Subset matrix if(myrows.n_elem == X0.n_rows){ X0=X0.cols(mycols); }else if(mycols.n_elem == X0.n_rows){ X0=X0.rows(myrows); }else{ X0=X0.submat(myrows,mycols); } return(X0); } // [[Rcpp::export]] arma::vec upperTmat(const arma::mat mat){ arma::vec output((mat.n_cols*(mat.n_cols-1))/2); arma::mat::const_iterator it = mat.begin() + mat.n_rows; //iterator at rows to skip in every step, starts at second column long toSkipInVec = 0; for(int i = 1; i < mat.n_cols; i++) //Starts with 1 to skip the diagonal { std::copy(it, it + i, output.begin() + toSkipInVec); toSkipInVec += i; it += mat.n_rows; } return output; } // [[Rcpp::export]] arma::mat Xmvcenter(arma::mat X){ arma::mat newX(X.n_rows,X.n_cols); for(int j=0; j<X.n_cols; j++){ newX.col(j) = (X.col(j) - arma::mean( X.col(j))) /arma::stddev( X.col(j)); } return(newX); } // [[Rcpp::export]] arma::mat LDrelative(SEXP A, arma::uvec m, bool debug = false){ Rcpp::XPtr<BigMatrix> bigMat(A); if(bigMat->matrix_type() !=8) stop("Big matrix is not of type double"); // Read the genome matrix from address arma::Mat<double> X((double*) bigMat->matrix(), bigMat->nrow(), bigMat->ncol(), false, false); X=X.cols(m); // mean and var center for LD calculation X=Xmvcenter(X); if(debug) cout << X << endl; // Get the relative LD for the proposals arma::mat R2 = arma::trans(X)*X ; if(debug) cout << R2 << endl; R2 = R2/ arma::sum(upperTmat(R2)); if(debug) cout << arma::sum(upperTmat(R2)) << endl; return(R2); } arma::mat LDrelative(arma::mat X, bool debug = false){ // mean and var center for LD calculation X=Xmvcenter(X); if(debug) cout << X << endl; // Get the relative LD for the proposals arma::mat R2 = arma::trans(X)*X ; if(debug) cout << R2 << endl; R2 = R2/ arma::sum(upperTmat(R2)); if(debug) cout << arma::sum(upperTmat(R2)) << endl; return(R2); } //////////////////////////////////////////////////////////////////////////////// /// Fitness functions //////////////////////////////////////////////////////////////////////////////// /// Fitness class class FITNESS{ private: int mode; public: FITNESS(int m=1){ mode=m; }; // fitness functions double w(const double &s , const int &x, const double e=2){ switch(mode){ case 1: // multiplicative return 1 + (s * x) ; break; case 2: // additive return (s * x) ; break; case 3: // inverse multiplicative // return 1 / (1 + s * x); return pow((1 + s),x); break; default: // multiplicative return 1 - (s * x) ; break; } } // void operator +*=(double w, double s,int x,int mode) // operator not needed unless class void wupdate(double &prevw, const double &s,const int &x) { switch(mode){ case 2: // additive prevw= prevw + w(s,x); break; default: // additive prevw= prevw * w(s,x); break; } } }; /// Expectation functions // [[Rcpp::export]] arma::colvec Ey_go(const arma::Mat<double> & X, // careful arma::mat default is double const arma::colvec & s, const int & mode, double epi=1, double ref=1 ){ // Initialize class and set fitness model FITNESS fit(mode); // Initialize vector of distribution means arma::colvec myprod(X.n_rows); // myprod.fill(1); myprod.fill(ref); // IMPORTANT int i,j; for (i = 0; i < X.n_cols; i ++) { for( j=0; j < X.n_rows ; j++){ fit.wupdate(myprod(j),s(i),X(j,i)); // works because these expressions generate a reference } } for( j=0; j<X.n_rows; j++) if(myprod(j)<0) myprod(j)=MIN_NUM; // **WARNING** this is necessary for non-NaN likelihood if(epi!=1) myprod=pow(myprod,epi); // probably not very efficient return(myprod); } //////////////////////////////////////////////////////////////////////////////// /// Likelihood, Probabilities, Proposals //////////////////////////////////////////////////////////////////////////////// // [[Rcpp::export]] double runif_reflect(double minhere,double maxhere,double min,double max){ // int counter=1; double newval; if( min == max){ newval= min; // if values want to be kept constant }else{ newval =Rcpp::runif(1,minhere,maxhere)(0); if(newval<min){newval = (min-newval) + min;} else if(newval>max){newval = max- (newval-max);} } if(newval < min || newval>max){ // Check if it is out of bounds newval=(max-min)/2; } return(newval); } class GPROPOSAL{ private: double b; double bmin; double bmax; double a; double amin; double amax; double p; double pmin=0; double pmax=1; double mu; double mumin; double mumax; double epi; double epimin; double epimax; double svar; double svarmin; double svarmax; double ss; double ssmin; double ssmax; int nupdates=1; bool verbose; double bw; public: GPROPOSAL( double b_=0.5,double bmin_=0,double bmax_=1, double a_=0.1,double amin_=0,double amax_=1, double p_=0.5, double mu_=1,double mumin_=0, double mumax_=50, double epi_=1,double epimin_=0, double epimax_=5, double svar_=0.5,double svarmin_=0, double svarmax_=5, double ss_=0.1,double ssmin_=0, double ssmax_=1, double bw_=0.1, bool verbose_=false ){ b=b_;bmin=bmin_;bmax=bmax_; a=a_;amin=amin_;amax=amax_; p=p_; mu=mu_;mumin=mumin_;mumax=mumax_; epi=epi_;epimin=epimin_;epimax=epimax_; svar=svar_;svarmin=svarmin_;svarmax=svarmax_; ss=ss_;ssmin=ssmin_;ssmax=ssmax_; bw=bw_; verbose=verbose_; } void setupdatesnum(int ups){nupdates=ups;} void setverbose(bool verbose_){verbose=verbose_;} void printatributes(){ cout <<"bw = " << bw << endl; cout <<"b = " << b << " [" << bmin << " " << bmax << "]" << endl; cout <<"a = " << a << " [" << amin << " " << amax << "]" << endl; cout <<"p = " << p << " [" << pmin << " " << pmax << "]" << endl; cout <<"mu = " << mu << " [" << mumin << " " << mumax << "]" << endl; cout <<"epi = " << epi << " [" << epimin << " " << epimax << "]" << endl; cout <<"svar = " << svar << " [" << svarmin << " " << svarmax << "]" << endl; cout <<"ss = " << ss << " [" << ssmin << " " << ssmax << "]" << endl; } arma::vec fn(arma::vec g){ // New proposal arma::vec news=g; // Update one position double minhere,maxhere; double newval; if(verbose) cout << "Loop to substitute position" << endl; for(int j=0; j< nupdates; j++){ int randomIndex = rand() % g.size(); switch(randomIndex){ if(verbose) cout << g(randomIndex) << endl; case 0: minhere=g(randomIndex)- (bw *(bmax-bmin)) ; maxhere=g(randomIndex)+ (bw *(bmax-bmin)); newval= runif_reflect(minhere,maxhere,bmin,bmax); break; case 1: minhere=g(randomIndex)- (bw *(amax-amin)) ; maxhere=g(randomIndex)+ (bw *(amax-amin)); newval= runif_reflect(minhere,maxhere,amin,amax); break; case 2: minhere=g(randomIndex)- (bw *(pmax-pmin)) ; maxhere=g(randomIndex)+ (bw *(pmax-pmin)); newval= runif_reflect(minhere,maxhere,pmin,pmax); break; case 3: minhere=g(randomIndex)- (bw *(mumax-mumin)) ; maxhere=g(randomIndex)+ (bw *(mumax-mumin)); newval= runif_reflect(minhere,maxhere,mumin,mumax); break; case 4: minhere=g(randomIndex)- (bw *(epimax-epimin)) ; maxhere=g(randomIndex)+ (bw *(epimax-epimin)); newval= runif_reflect(minhere,maxhere,epimin,epimax); break; case 5: minhere=g(randomIndex)- (bw *(svarmax-svarmin)) ; maxhere=g(randomIndex)+ (bw *(svarmax-svarmin)); newval= runif_reflect(minhere,maxhere,svarmin,svarmax); break; case 6: minhere=g(randomIndex)- (bw *(ssmax-ssmin)) ; maxhere=g(randomIndex)+ (bw *(ssmax-ssmin)); newval= runif_reflect(minhere,maxhere,ssmin,ssmax); break; } if(verbose) cout << newval << endl; news(randomIndex) = newval; } if(verbose) cout << "End loop" << endl; return(news); } }; // [[Rcpp::export]] arma::mat test_GPROPOSAL(double b=1, double a=1, double p=1, double mu=1, double epi=1, double svar=1, double ss=0.1, int iter=7000, bool verbose = false){ arma::vec g(7); g(0)= b; g(1)= a; g(2)= p; g(3)= mu; g(4)= epi; g(5)= svar; g(6)= ss; GPROPOSAL GProp; // mode 1 = uniform ; mode 2 = LD GProp.setverbose(verbose); GProp.printatributes(); // cout << "Original " << endl; // cout << g << endl; // cout << "Testing proposals "<< endl; arma::mat res(7,iter); res.col(0)=g; cout << "Runing several proposals "<< endl; for(int i=1; i<iter; i++){ g=GProp.fn(g); res.col(i)=g; } return(res); } ////////////////////////////////////////////////////////////////////////////// // Selection proposal with LD class PROPOSAL { private: double bw; int nupdates; double min; double max; int mode; bool verbose; arma::mat R; // for LD implementatioon public: PROPOSAL( int nupdates_, int mode_=1 ){ nupdates=nupdates_; mode=mode_; verbose=false; } PROPOSAL( double bw_, int nupdates_, double min_, double max_, int mode_=1, bool verbose_= false ){ bw=bw_;nupdates=nupdates_;min=min_;max=max_;mode=mode_;verbose=verbose_; // initialize R2 for default cases arma::mat onemat(1,1); onemat.fill(1); R=onemat; } PROPOSAL(arma::mat R2, double bw_, int nupdates_, double min_, double max_, int mode_=1, bool verbose_= false ){ bw=bw_;nupdates=nupdates_;min=min_;max=max_;mode=mode_;verbose=verbose_; // initialize R2 for default cases R=R2; } void printatributes(){ cout <<"bw = " << bw << endl; cout <<"nupdates = " <<nupdates << endl; cout <<"min = " << min << endl; cout <<"max = " <<max << endl; cout <<"mode = " <<mode << endl; cout <<"verbose = " <<verbose << endl; } arma::vec fn(arma::vec s){ switch(mode){ case 1: return update(s); break; case 2: return updateLD(s); break; default: return update(s); break; } } arma::vec fn(arma::vec s, double svar){ switch(mode){ case 1: return update(s); break; case 2: return updateLD(s); case 3: return updatelog(s,svar); break; default: return update(s); break; } } arma::vec update(arma::vec s){ /* * Make proposal change of one or more selection coefficients * from a previous vector. * Do not allow to go further thana bandwidth of 0.1 */ // New proposal arma::colvec news=s; // Update one position double minhere,maxhere,newval; if(verbose) cout << "Loop to substitute position" << endl; for(int j=0; j< nupdates; j++){ int randomIndex = rand() % s.size(); minhere=s(randomIndex)-bw; maxhere=s(randomIndex)+bw; newval = runif_reflect(minhere,maxhere,min,max); news(randomIndex) = newval; } if(verbose) cout << "End loop" << endl; return(news); } arma::vec updatelog(arma::vec s,double svar){ // New proposal arma::colvec news= s; // Update one position double meanhere,newval; if(verbose) cout << "Loop to substitute position" << endl; for(int j=0; j< nupdates; j++){ int randomIndex = rand() % s.size(); meanhere=log(1+s(randomIndex)); if(std::isinf(meanhere)){ meanhere= (max-min)/2; } newval = Rcpp::rnorm(1,0,svar)(0); news(randomIndex) = exp(newval)-1; if(verbose) cout << newval << endl; if(verbose) cout << news(randomIndex) << endl; } if(verbose) cout << "End loop" << endl; return(news); } arma::vec updateLD(arma::vec s){ // New proposal arma::colvec news=s; // Update one position double minhere,maxhere,newval; if(verbose) cout << "Loop to substitute position" << endl; int randomIndex = rand() % s.size(); minhere=s(randomIndex)-bw; maxhere=s(randomIndex)+bw; newval = runif_reflect(minhere,maxhere,min,max); news(randomIndex) = newval; double diff = news(randomIndex) - s(randomIndex); if(verbose) cout << "Difference with original value = " << diff << endl; for(int i=0; i<s.n_elem & i!= randomIndex; i++){ news(i) -= diff * R(randomIndex,i) ; if(verbose) cout << news(i) << endl; if(news(i) < min) news(i) =min+abs(news(i) -min); if(news(i) > max) news(i) =max-abs(news(i) -max); } return(news); } }; // [[Rcpp::export]] arma::vec PropoS(int nupdates,double svar = 0.5){ arma::vec s(nupdates); s.fill(0); PROPOSAL ps(nupdates,3); return(ps.fn(s,svar)); } // [[Rcpp::export]] void test_ProposalsLD( arma::mat X, double min=0, double max=1, double bw=0.1, int nupdates=1, int mode=2, int iterations=1, bool verbose=true ){ arma::vec s = Rcpp::runif(X.n_cols,0,1); PROPOSAL Prop(LDrelative(X),bw,nupdates,min,max,2,verbose); // mode 1 = uniform ; mode 2 = LD cout << "Original " << endl; // cout << s << endl; cout << "Testing proposals under mode = "<< mode << endl; for(int i=0; i<3; i++){ s=Prop.fn(s); // cout << s << endl; } } // [[Rcpp::export]] arma::vec call_Proopsals( arma::vec s, int m=10, double min=0, double max=1, double bw=0.1, int nupdates=1, int mode=1, bool verbose=true){ PROPOSAL Prop(bw,nupdates,min,max,mode,verbose); // mode 1 = uniform ; mode 2 = LD Prop.printatributes(); return Prop.fn(s); } // [[Rcpp::export]] void test_Proposals(int m=10, double min=0, double max=1, double svar=0.1, int nupdates=1, int mode=1, int iterations=3, bool verbose=true ){ arma::vec s = PropoS(m,svar); PROPOSAL Prop(svar,nupdates,min,max,mode,verbose); // mode 1 = uniform ; mode 2 = LD Prop.printatributes(); cout << "Testing proposals under mode = "<< mode << endl; for(int i=0; i<3; i++){ s=Prop.fn(s); cout << s << endl; } } //////////////////////////////////////////////////////////////////////////////// class PRIOR{ public: double min; double max; double mean; double svar; double ss; int mode; // Constructors // PRIOR(double min_=0,double max_=1, // double mean_=0,double variance_=1, // int mode_=1){ // min=min_; max=max_;mean=mean_; variance=variance_; mode=mode_; }; PRIOR(double par1=0,double par2=1, int mode_=1){ mode=mode_; switch(mode){ case 1: // moc mode, return 1 break; case 2: // true uniform min=par1; max=par2; break; case 3: // log +1 normal mean=par1; svar=par2; break; case 4: // log +1 mixture normal with sparcity svar=par1; ss=par2; break; default: min=0;max=1;mean=0,svar=0.5; break; } } void printatributes(){ cout <<"min = " << min << endl; cout <<"max = " <<max << endl; cout <<"s variance = " <<svar << endl; cout <<"mode = " <<mode << endl; } // Prior functions double uniform(const arma::colvec & s){ double L= 0; int N=s.n_elem; for(int i=0;i<N ;i++){ L+= R::dunif(s(i),min,max,true); } return L; } double loggaussian(const arma::colvec & s, double svar){ // int n=s.n_elem; arma::vec x = log(1+s); // double L = -.5*n*log(2*PI) -.5*n*log(svar) -(1/(2*svar))*sum(arma::pow((x-mean),2)); double L=0; for(int i = 0; i<s.n_elem; i++){ L+= R::dnorm(x(i),0,svar,true); } return L; } double logmixgaussian(const arma::colvec & s, double svar, double ss){ arma::vec x = log(1+s); double L=0; for(int i = 0; i<s.n_elem; i++){ // L+= R::dnorm(x(i),0,svar,true); if(x(i)==0){ L += log(ss + (1-ss) * R::dnorm(x(i),0,svar,false)) ; }else{ L += (1-ss) * R::dnorm(x(i),0,svar,true); } } return L; } // Prior distributor double fn(const arma::colvec & s){ switch(mode){ case 1: // moc mode, return 1 return 1.0; break; case 2: // true uniform return uniform(s); break; default: return 1.0; break; } } double fn(const arma::colvec & s,const double & svar,const double & ss){ switch(mode){ case 1: // moc mode, return 1 return 1.0; break; case 2: // true uniform return uniform(s); break; case 3: return loggaussian(s,svar); break; case 4: return logmixgaussian(s,svar,ss); break; default: return 1.0; break; } } }; // [[Rcpp::export]] void test_Prior(int m=10, double min=0, double max=1, double mean=0, double variance=1, double sparsity=0.1, int mode=1 ){ arma::vec s; if(mode==1){ s = exp( Rcpp::rnorm(m,0,variance) ) - 1; }else{ s = Rcpp::runif(m,0,1); } cout << s << endl; cout << "Prior mode = 1" << endl; PRIOR Pri; // mode 1 = uniform moc cout << Pri.fn(s) << endl; cout << "Prior mode = 2" << endl; PRIOR Pri2(min,max,2); // mode 1 = uniform moc cout << Pri2.fn(s) << endl; cout << "Prior mode = 3" << endl; PRIOR Pri3(mean,variance,3); // mode 1 = uniform moc cout << Pri3.fn(s,variance,sparsity) << endl; cout << "Prior mode = 4" << endl; PRIOR Pri4(mean,variance,4); // mode 1 = uniform moc cout << Pri3.fn(s,variance,sparsity) << endl; } //////////////////////////////////////////////////////////////////////////////// // [[Rcpp::export]] arma::vec hsub(const arma::vec & h){ arma::vec hunique = unique(h); arma::vec hpos(h.n_elem); for(int i=0; i<h.n_elem;i++){ for(int j=0; j< hunique.n_elem;j++){ if(h(i) == hunique(j)) hpos(i) = j; } } return(hpos); } // [[Rcpp::export]] double trialLL(double hs=10){ arma::vec e(20); e.fill(2); return e(hs); } // [[Rcpp::export]] double LLGaussMix(double y,double e,double v,double p){ double LL; if(y==0){ LL = p + (1-p) * R::pnorm(0,e,v,true,false) ; }else{ LL = (1-p) * R::dnorm(y,e,v,false); } return log(LL); } //////////////////////////////////////////////////////////////////////////////// /// Likelihood class class LIKELIHOOD{ private: int mode; bool TEST; bool verbose; arma::vec y; arma::vec h; arma::Mat<double> X; public: //Constructor LIKELIHOOD( const arma::vec y_, const arma::vec h_, const arma::Mat<double> X_, // careful the arma::mat by default is double int mode_=1, bool TEST_=false, bool verbose_=false){ y=y_; h=h_; X=X_; mode=mode_;TEST=TEST_;verbose=verbose_; } void printatributes(){ cout <<"verbose = " << verbose << endl; cout <<"TEST = " <<TEST << endl; cout <<"mode = " <<mode << endl; } // calling function double fn(const arma::vec & s, double b,double a, double p,double mu=1,double epi=1){ if(TEST) return 1.0; else return LLikfn(s,b,a,p,mu,epi); } // likelihood function double LLikfn(const arma::vec & s, double b,double a, double p,double mu=1,double epi=1){ /* * Summed log likelihood of all genotypes following each a Gammma distribution * inferred from sampling variance, mean observed genotype and selection a * set of selection coefficients */ // Precompute all expectations of mean fitness values given genotypes X and s. if(verbose) cout<< "Precompute expectations..."<< endl; arma::vec e= Ey_go(X,s,mode,epi); // cout << e<< endl; // for debugging arma::vec v= a+abs(e*b); // cout << v<< endl; // for debugging // Utilities arma::vec hs=hsub(h); // Sum likelihood over all genotypes if(verbose) cout<< "Calculating likelihood over all genotypes..."<< endl; int i; double L=0; double LL; for(i=0; i< y.n_elem ; i ++){ LL= LLGaussMix(y(i)/mu,e(hs(i)),v(hs(i)),p); if(verbose and std::isinf(LL)){ cout << "---" << endl; cout << i << endl; cout << y(i) << " "<< e(hs(i)) << " "<< v(hs(i)) <<" "<< p << endl; cout << LL << endl; } L += LL; } return(L); } }; // [[Rcpp::export]] void test_Likelihood( SEXP A, arma::vec y, arma::vec h, arma::vec s, double b, double a, double p, double mu, arma::uvec m, arma::uvec n, int Fitnessmode=1, bool TEST=false, bool verbose=true ){ arma::Mat<double> X=BMsubset(A,n,m); cout << "Selection coefficients" << endl; cout << s << endl; cout << "Likelihood" << endl; LIKELIHOOD LL(y,h,X,Fitnessmode,TEST,verbose); cout << LL.fn(s,b,a,p,mu) << endl; } // [[Rcpp::export]] void test_Likelihoodall( SEXP A, arma::vec y, arma::vec h, arma::vec s, double b, double a, double p, arma::uvec m, arma::uvec n, int mode=1, bool verbose=true ){ arma::Mat<double> X=BMsubset(A,n,m); cout << "Selection coefficients" << endl; cout << s << endl; cout << "Likelihood mode = 1 | TEST = false" << endl; LIKELIHOOD LL1(y,h,X,mode,false,verbose); cout << LL1.fn(s,b,a,p) << endl; cout << "Likelihood mode = 1 | TEST = true" << endl; LIKELIHOOD LL2(y,h,X,mode,true,verbose); cout << LL2.fn(s,b,a,p) << endl; cout << "Likelihood mode = 2 " << endl; LIKELIHOOD LL3(y,h,X,2,false,verbose); cout << LL3.fn(s,b,a,p) << endl; cout << "Likelihood mode = 3 " << endl; LIKELIHOOD LL4(y,h,X,3,false,verbose); cout << LL4.fn(s,b,a,p) << endl; } //////////////////////////////////////////////////////////////////////////////// /// MCMC //////////////////////////////////////////////////////////////////////////////// // [[Rcpp::export]] List napMCMCC( const arma::vec & y, const arma::vec & h, SEXP A, // instead of arma::mat X, const arma::colvec & s, const arma::uvec m, // the positions of SNPs const arma::uvec n , // the positions of individuals double b=0.5, double bmin=0, double bmax=1.0, // the mean variance transformation double a=0.1, double amin=0.0, double amax=1, // the intercept of variance double p=0.5, // the proportion of zero values double mu=1.0, double mumin=0,double mumax=10, double epi=1.0, double epimin=1.0,double epimax=1.0, double svar=0.1, double svarmin=0,double svarmax=1, double ss=0.1, double ssmin=0,double ssmax=1, double bw= 0.1, // the maximum size of jumps of global parameters int nupdates=1, double min=1e-6, double max=1-1e-6 , double iterations = 1e4, bool TEST =false , bool verbose=false, bool debug=false, int Fitnessmode=1, int Priormode=1, int Proposalmode=1, std::string file2sink= "output.log", bool sink2file = false ){ if(sink2file) std::freopen(file2sink.c_str(), "w", stdout); cout<< "Arguments:"<<endl; cout<< "----------"<<endl; cout<< "Range of s coefficients = ["<< min << ", " << max << "]" <<endl; cout<< "Total number of individual's observations = "<< y.n_elem <<endl; cout<< "Total number of SNPs = "<< s.n_elem <<endl; cout<< "# iterations = "<< iterations <<endl; cout<< "TEST run = "<< TEST <<endl; cout<< "Verbose = "<< verbose <<endl; cout<< "Debug = "<< debug <<endl; cout<< "----------"<<endl; cout<< "Initializing ... "<<endl; std::chrono::time_point<std::chrono::system_clock> start, end; // start chronometer values start = std::chrono::system_clock::now(); /////////////////////////////////////////////////////////////////////////// // Deal with the matrix // /////////////////////////////////////////////////////////////////////////// // arma::Mat<double> X; // // if(n.n_elem != A){ // // cout<< "Reading and subsetting genome matrix ... "<<endl; // // X=BMsubset(A,n,m); // // }else{ // // cout<< "Reading and subsetting columns ... "<<endl; // // X=BMsubset(A,m); // // } // cout<< "Reading and subsetting genome matrix ... "<<endl; // X=BMsubset(A,n,m); arma::mat X(n.n_elem,m.n_elem); if(TYPEOF(A) == EXTPTRSXP){ cout<< "Reading external pointer and subsetting genome matrix ... "<<endl; X=BMsubset(A,n,m); }else if(TYPEOF(A) == REALSXP){ cout<< "Matrix provided already subsetted "<<endl; NumericMatrix Xr(A); cout << " nrow= " << Xr.nrow() << " ncol= " << Xr.ncol() << endl; arma::mat X(Xr.begin(), Xr.nrow(), Xr.ncol(), false); } /////////////////////////////////////////////////////////////////////////// // Setup MCMC // /////////////////////////////////////////////////////////////////////////// // Counter for printing int counter = 0; double percentunit = iterations/100; // Initialize chain object arma::mat s_chain(s.n_elem,iterations+1); arma::mat par_chain(7, iterations+1); /// update when adding new par arma::vec prob(iterations+1); arma::vec paccepts(iterations+1); int naccepted=0; double prob0; double prob1; double Paccept; bool accept; double selectionpar= s.n_elem ; double globalpar= par_chain.n_rows; double totpar= selectionpar + globalpar; // CHANGE WHEN ADDING MORE PARAMETERS if(debug) cout << "Total selection parameters = " << (selectionpar) << endl; if(debug) cout << "Total global parameters = " << (globalpar) << endl; if(debug) cout << "Total # of parameters = " << (totpar) << endl; /////////////////////////////////////////////////////////////////////////// // Setup MCMC conditions // /////////////////////////////////////////////////////////////////////////// // Proposals for variables arma::vec sproposal=s; arma::vec gproposal(7); // Need to keep right order gproposal(0)=b; gproposal(1)=a; gproposal(2)=p; gproposal(3)=mu; gproposal(4)=epi; gproposal(5)=svar; gproposal(6)=ss; cout << "First proposal of global paramenters: "<< endl; cout <<"b = "<< gproposal(0)<<endl; cout <<"a = " <<gproposal(1)<<endl; cout <<"p = " <<gproposal(2)<<endl; cout <<"mu = " <<gproposal(3)<<endl; cout <<"epi = " <<gproposal(4)<<endl; cout <<"svar = " <<gproposal(5)<<endl; cout <<"ss = " <<gproposal(6)<<endl; Rcpp::StringVector parnames(gproposal.n_elem); parnames(0)="b"; parnames(1)="a"; parnames(2)="p"; parnames(3)="mu"; parnames(4)="epi"; parnames(5)="svar"; parnames(6)="ss"; // Compute prob at first step cout<< "Start chains ..."<<endl; s_chain.col(0) = s; // set start as starting value par_chain.col(0) = gproposal; // Setup probability objects LIKELIHOOD LL(y,h,X,Fitnessmode,TEST,false); PRIOR Pri(0,svar, Priormode); // loggauss // PRIOR Pri(min,max, Priormode); // uniform // Proposal Prop(R,bw,nupdates,min,max,Proposalmode); // to implement R2 PROPOSAL Prop(bw, nupdates, min, max, Proposalmode); GPROPOSAL GProp(b,bmin,bmax, a, amin,amax, p, mu,mumin,mumax, epi,epimin,epimax, svar,svarmin,svarmax); paccepts(0)=1; cout<< "Calculate posterior of starting point ..." ; prob(0) = Pri.fn(sproposal, gproposal(5),gproposal(6)) + LL.fn(sproposal, gproposal(0), gproposal(1), gproposal(2), gproposal(3), gproposal(4) ); cout << prob(0) << endl; /////////////////////////////////////////////////////////////////////////// /// Handle -inf probability starts /////////////////////////////////////////////////////////////////////////// if(std::isinf(prob(0)) || std::isnan(prob(0)) ){ cout << "Posterior is infinite!!!. Attempt changing starting values" << endl; // stop("Posterior is infinite!!!. Attempt changing stargin values"); // return List::create(Named("chain") = s_chain.t(), // Named("parchain") = par_chain.t(), // Named("parnames") = parnames, // Named("posterior") = prob, // Named("accept") = paccepts); // }else{ PROPOSAL Propattempt(bw, s.n_elem, min, max, Proposalmode); int attemptcounter=1; while((std::isinf(prob(0)) || std::isnan(prob(0)) ) && attemptcounter < 1000 ){ // cout << "attempt # " << attemptcounter << endl; sproposal = Propattempt.fn(s); gproposal=GProp.fn(par_chain.col(0)); prob(0) = Pri.fn(sproposal, gproposal(5),gproposal(6)) + LL.fn(sproposal, gproposal(0), gproposal(1), gproposal(2), gproposal(3), gproposal(4) ); attemptcounter++; } if(std::isinf(prob(0)) || std::isnan(prob(0)) ){ stop("Posterior is infinite!!!. Attempt changing stargin values"); } cout << "Successful after " << attemptcounter << " attempts " << endl; } /////////////////////////////////////////////////////////////////////////// // run MCMC // /////////////////////////////////////////////////////////////////////////// cout<< "Starting "<< iterations<< " MCMC iterations ..."<<endl; int counterupdate=0; int i; for(i=0; i<iterations;i++){ // // Propose new s and new probability if(verbose) cout<< "Generating new proposal "<<endl; if(counterupdate <= selectionpar){ sproposal=Prop.fn(s_chain.col(i),gproposal(5)); counterupdate++; }else if(counterupdate < totpar ){ gproposal=GProp.fn(par_chain.col(i)); counterupdate++; }else{ counterupdate=0; } // Probabilities if(verbose) cout<< "Calculating next posterior "<<endl; prob0= prob(i); prob1 = Pri.fn(sproposal, gproposal(5),gproposal(6))+ LL.fn(sproposal, gproposal(0), gproposal(1), gproposal(2), gproposal(3), gproposal(4) ); // if(debug) cout << prob1<< endl; // Ratio of provabilities Paccept= exp( prob1 - prob0); accept = Rcpp::runif(1)(0)<Paccept; if(verbose) cout<< "Accept proposal " << accept <<endl; if(accept){ s_chain.col(i+1) = sproposal; par_chain.col(i+1) = gproposal; prob(i+1) = prob1; paccepts(i+1) = Paccept; naccepted++; }else{ s_chain.col(i+1) = s_chain.col(i); par_chain.col(i+1) = par_chain.col(i); prob(i+1) = prob(i); paccepts(i+1) = paccepts(i); } // Print row if(counter > percentunit){ if(!debug & !sink2file) printProgress(i/iterations); counter =0; }else{ counter++; } } printProgress(1); ///////// // End // ///////// cout<< endl<< "Summary:"<<endl; cout<< "----------"<<endl; cout<< "Acceptance ratio = "<< naccepted / iterations << endl; cout<< "Final posterior = "<< prob(iterations) << endl; cout<< "----------"<<endl; cout<<endl<< "Done."<<endl; end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds1 = end-start; std::cout << "elapsed time: " << elapsed_seconds1.count() << " seconds" <<endl; return List::create(Named("chain") = s_chain.t(), Named("parchain") = par_chain.t(), Named("parnames") = parnames, Named("posterior") = prob, Named("accept") = paccepts); } // } // // [[Rcpp::export]] // List gwsMC3( // const arma::vec & y, // const arma::vec & h, // SEXP A, // instead of arma::mat X, // const arma::colvec & s, // const arma::uvec m, // the positions of SNPs // const arma::uvec n , // the positions of individuals // double b=0.5, double bmin=0, double bmax=1.0, // the mean variance transformation // double a=0.1, double amin=0.0, double amax=1, // the intercept of variance // double p=0.5, // the proportion of zero values // double mu=1.0, double mumin=0,double mumax=10, // double epi=1.0, double epimin=1.0,double epimax=1.0, // double svar=0.1, double svarmin=0,double svarmax=1, // double ss=0.1, double ssmin=0,double ssmax=1, // double bw= 0.1, // the maximum size of jumps of global parameters // int nupdates=1, // double min=1e-6, // double max=1-1e-6 , // double iterations = 1e4, // bool TEST =false , // bool verbose=false, // bool debug=false, // int Fitnessmode=1, // int Priormode=1, // int Proposalmode=1, // std::string file2sink= "output.log", // bool sink2file = false // ){ // if(sink2file) std::freopen(file2sink.c_str(), "w", stdout); // cout<< "Arguments:"<<endl; // cout<< "----------"<<endl; // cout<< "Range of s coefficients = ["<< min << ", " << max << "]" <<endl; // cout<< "Total number of individual's observations = "<< y.n_elem <<endl; // cout<< "Total number of SNPs = "<< s.n_elem <<endl; // cout<< "# iterations = "<< iterations <<endl; // cout<< "TEST run = "<< TEST <<endl; // cout<< "Verbose = "<< verbose <<endl; // cout<< "Debug = "<< debug <<endl; // cout<< "----------"<<endl; // cout<< "Initializing ... "<<endl; // std::chrono::time_point<std::chrono::system_clock> start, end; // start chronometer values // start = std::chrono::system_clock::now(); // /////////////////////////////////////////////////////////////////////////// // // Deal with the matrix // // /////////////////////////////////////////////////////////////////////////// // cout<< "Reading and subsetting genome matrix ... "<<endl; // arma::Mat<double> X=BMsubset(A,n,m); // /////////////////////////////////////////////////////////////////////////// // // Setup MCMC // // /////////////////////////////////////////////////////////////////////////// // // Counter for printing // int counter = 0; // double percentunit = iterations/100; // // Initialize chain object // arma::mat s_chain(s.n_elem,iterations+1); // arma::mat par_chain(7, iterations+1); /// update when adding new par // arma::vec prob(iterations+1); // arma::vec paccepts(iterations+1); // int naccepted=0; // double prob0; // double prob1; // double Paccept; // bool accept; // double selectionpar= s.n_elem ; // double globalpar= par_chain.n_rows; // double totpar= selectionpar + globalpar; // CHANGE WHEN ADDING MORE PARAMETERS // if(debug) cout << "Total selection parameters = " << (selectionpar) << endl; // if(debug) cout << "Total global parameters = " << (globalpar) << endl; // if(debug) cout << "Total # of parameters = " << (totpar) << endl; // /////////////////////////////////////////////////////////////////////////// // // Setup MCMC conditions // // /////////////////////////////////////////////////////////////////////////// // // Proposals for variables // arma::vec sproposal=s; // arma::vec gproposal(7); // Need to keep right order // gproposal(0)=b; // gproposal(1)=a; // gproposal(2)=p; // gproposal(3)=mu; // gproposal(4)=epi; // gproposal(5)=svar; // gproposal(6)=ss; // cout << "First proposal of global paramenters: "<< endl; // cout <<"b = "<< gproposal(0)<<endl; // cout <<"a = " <<gproposal(1)<<endl; // cout <<"p = " <<gproposal(2)<<endl; // cout <<"mu = " <<gproposal(3)<<endl; // cout <<"epi = " <<gproposal(4)<<endl; // cout <<"svar = " <<gproposal(5)<<endl; // cout <<"ss = " <<gproposal(6)<<endl; // Rcpp::StringVector parnames(gproposal.n_elem); // parnames(0)="b"; // parnames(1)="a"; // parnames(2)="p"; // parnames(3)="mu"; // parnames(4)="epi"; // parnames(5)="svar"; // parnames(6)="ss"; // // Compute prob at first step // cout<< "Start chains ..."<<endl; // s_chain.col(0) = s; // set start as starting value // par_chain.col(0) = gproposal; // // Setup probability objects // LIKELIHOOD LL(y,h,X,Fitnessmode,TEST,false); // PRIOR Pri(0,svar, Priormode); // loggauss // // PRIOR Pri(min,max, Priormode); // uniform // // Proposal Prop(R,bw,nupdates,min,max,Proposalmode); // to implement R2 // PROPOSAL Prop(bw, // nupdates, // min, // max, // Proposalmode); // GPROPOSAL GProp(b,bmin,bmax, // a, amin,amax, // p, // mu,mumin,mumax, // epi,epimin,epimax, // svar,svarmin,svarmax); // paccepts(0)=1; // cout<< "Calculate posterior of starting point ..." ; // prob(0) = Pri.fn(sproposal, gproposal(5),gproposal(6)) + // LL.fn(sproposal, // gproposal(0), // gproposal(1), // gproposal(2), // gproposal(3), // gproposal(4) // ); // cout << prob(0) << endl; // if(std::isinf(prob(0))){ // cout << "Posterior is infinite!!!. Attempting change in stargin values" << endl; // PROPOSAL Propattempt(bw, // s.n_elem, // min, // max, // Proposalmode); // while(!std::isinf(prob(0))){ // sproposal = Propattempt.fn(s); // prob(0) = // Pri.fn(sproposal, gproposal(5),gproposal(6)) + // // Pri.fn(sproposal) + // Previous implementation // LL.fn(sproposal, // gproposal(0), // gproposal(1), // gproposal(2), // gproposal(3), // gproposal(4) // ); // } // } // /////////////////////////////////////////////////////////////////////////// // // run MCMC // // /////////////////////////////////////////////////////////////////////////// // cout<< "Starting "<< iterations<< " MCMC iterations ..."<<endl; // int counterupdate=0; // int i; // for(i=0; i<iterations;i++){ // // // Propose new s and new probability // if(verbose) cout<< "Generating new proposal "<<endl; // if(counterupdate <= selectionpar){ // sproposal=Prop.fn(s_chain.col(i),gproposal(5)); // counterupdate++; // }else if(counterupdate < totpar ){ // gproposal=GProp.fn(par_chain.col(i)); // counterupdate++; // }else{ // counterupdate=0; // } // // Probabilities // if(verbose) cout<< "Calculating next posterior "<<endl; // prob0= prob(i); // prob1 = Pri.fn(sproposal, gproposal(5),gproposal(6))+ // LL.fn(sproposal, // gproposal(0), // gproposal(1), // gproposal(2), // gproposal(3), // gproposal(4) // ); // // if(debug) cout << prob1<< endl; // // Ratio of provabilities // Paccept= exp( prob1 - prob0); // accept = Rcpp::runif(1)(0)<Paccept; // if(verbose) cout<< "Accept proposal " << accept <<endl; // if(accept){ // s_chain.col(i+1) = sproposal; // par_chain.col(i+1) = gproposal; // prob(i+1) = prob1; // paccepts(i+1) = Paccept; // naccepted++; // }else{ // s_chain.col(i+1) = s_chain.col(i); // par_chain.col(i+1) = par_chain.col(i); // prob(i+1) = prob(i); // paccepts(i+1) = paccepts(i); // } // // Print row // if(counter > percentunit){ // if(!debug & !sink2file) printProgress(i/iterations); // counter =0; // }else{ // counter++; // } // } // printProgress(1); // ///////// // // End // // ///////// // cout<< endl<< "Summary:"<<endl; // cout<< "----------"<<endl; // cout<< "Acceptance ratio = "<< naccepted / iterations << endl; // cout<< "Final posterior = "<< prob(iterations) << endl; // cout<< "----------"<<endl; // cout<<endl<< "Done."<<endl; // end = std::chrono::system_clock::now(); // std::chrono::duration<double> elapsed_seconds1 = end-start; // std::cout << "elapsed time: " << elapsed_seconds1.count() << " seconds" <<endl; // return List::create(Named("chain") = s_chain.t(), // Named("parchain") = par_chain.t(), // Named("parnames") = parnames, // Named("posterior") = prob, // Named("accept") = paccepts); // } // }
30.990944
124
0.479546
[ "object", "vector", "model", "3d" ]
f6a40b75f995093140274c10842aaeca7f3e9217
4,598
cc
C++
modules/path/src/prepare/schedule/stop_positions.cc
julianharbarth/motis
d5ded8b519a85809949f084ca7983a22180deb1a
[ "MIT" ]
null
null
null
modules/path/src/prepare/schedule/stop_positions.cc
julianharbarth/motis
d5ded8b519a85809949f084ca7983a22180deb1a
[ "MIT" ]
null
null
null
modules/path/src/prepare/schedule/stop_positions.cc
julianharbarth/motis
d5ded8b519a85809949f084ca7983a22180deb1a
[ "MIT" ]
null
null
null
#include "motis/path/prepare/schedule/stop_positions.h" #include <map> #include <string> #include <vector> #include "boost/algorithm/string/predicate.hpp" #include "boost/filesystem.hpp" #include "geo/latlng.h" #include "geo/point_rtree.h" #include "utl/parser/file.h" #include "utl/to_vec.h" #include "utl/zip.h" #include "motis/core/common/logging.h" #include "motis/path/prepare/osm_util.h" #include "motis/path/fbs/StopPositionCache_generated.h" using namespace flatbuffers; namespace fs = boost::filesystem; namespace motis::path { constexpr auto kStopPositionsCacheFile = "pathcache.stop_positions.raw"; bool is_stop_positions_cache_available(std::string const& osm_file, std::string const& sched_path) { if (!fs::is_regular_file(kStopPositionsCacheFile)) { return false; } auto const buf = utl::file{kStopPositionsCacheFile, "r"}.content(); auto const* cache = GetStopPositionCache(buf.buf_); auto sched_file = fs::path(sched_path); return cache->osm_file()->mod_date() == fs::last_write_time(osm_file) && cache->osm_file()->file_size() == fs::file_size(osm_file) && cache->sched_file()->mod_date() == fs::last_write_time(sched_file) && cache->sched_file()->file_size() == fs::file_size(sched_file); } void prepare_stop_positions_cache(std::string const& osm_file, std::string const& sched_path, std::vector<station> const& stations) { if (is_stop_positions_cache_available(osm_file, sched_path)) { LOG(motis::logging::info) << "using existing stop positions"; return; } motis::logging::scoped_timer t{"parsing stop positions"}; utl::verify(std::is_sorted( begin(stations), end(stations), [](auto const& a, auto const& b) { return a.id_ < b.id_; }), "stations vector is not sorted by station id"); auto const rtree = geo::make_point_rtree(stations, [](auto const& s) { return s.pos_; }); std::vector<std::vector<geo::latlng>> positions; positions.resize(stations.size()); std::string const stop_position = "stop_position"; std::string const yes = "yes"; foreach_osm_node(osm_file, [&](auto const& node) { if (stop_position != node.get_value_by_key("public_transport", "") || yes != node.get_value_by_key("bus", "")) { return; } auto const pos = geo::latlng{node.location().lat(), node.location().lon()}; for (auto const& idx : rtree.in_radius(pos, 100)) { positions.at(idx).emplace_back(pos); break; // XXX ? } }); FlatBufferBuilder fbb; std::vector<Offset<StopPositionInfo>> infos; infos.reserve(stations.size()); for (auto const& [station, pos] : utl::zip(stations, positions)) { infos.emplace_back(CreateStopPositionInfo( fbb, fbb.CreateString(station.id_), fbb.CreateVectorOfStructs(utl::to_vec( pos, [](auto const& p) { return Position(p.lat_, p.lng_); })))); } auto sched_file = fs::path(sched_path); fbb.Finish(CreateStopPositionCache( fbb, CreateFileID(fbb, fs::last_write_time(osm_file), fs::file_size(osm_file)), CreateFileID(fbb, fs::last_write_time(sched_file), fs::file_size(sched_file)), fbb.CreateVector(infos))); utl::file{kStopPositionsCacheFile, "w+"}.write(fbb.GetBufferPointer(), fbb.GetSize()); } void annotate_stop_positions(std::vector<station>& stations) { auto const buf = utl::file{kStopPositionsCacheFile, "r"}.content(); auto const* cache = GetStopPositionCache(buf.buf_); for (auto& station : stations) { auto const it = std::lower_bound( cache->stop_positions()->begin(), cache->stop_positions()->end(), station.id_, [](auto const& lhs, auto const& rhs) { return std::strcmp(lhs->station_id()->c_str(), rhs.c_str()) < 0; }); utl::verify(it != cache->stop_positions()->end() && station.id_ == it->station_id()->c_str(), "annotate_stop_positions: station not found!"); station.stop_positions_ = utl::to_vec(*it->stop_positions(), [](auto const& p) { return geo::latlng{p->lat(), p->lng()}; }); } } void find_stop_positions(std::string const& osm_file, std::string const& sched_path, std::vector<station>& stations) { prepare_stop_positions_cache(osm_file, sched_path, stations); annotate_stop_positions(stations); } } // namespace motis::path
35.099237
80
0.639408
[ "vector" ]
f6a94a2608b25cc3715ee5823be1f42aac66145a
1,346
hpp
C++
src/ttauri/GFX/pipeline_flat_device_shared.hpp
foragerDev/ttauri
b5b5f01873adbdc2f1863eeee734fc2bdb2dac2a
[ "BSL-1.0" ]
2
2021-09-21T00:07:50.000Z
2021-09-21T22:28:28.000Z
src/ttauri/GFX/pipeline_flat_device_shared.hpp
benshurts/ttauri-gui
22eeb8f202dcfa0769653104f9b090030fbd9290
[ "BSL-1.0" ]
null
null
null
src/ttauri/GFX/pipeline_flat_device_shared.hpp
benshurts/ttauri-gui
22eeb8f202dcfa0769653104f9b090030fbd9290
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2019-2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #pragma once #include "../required.hpp" #include "../geometry/axis_aligned_rectangle.hpp" #include "../rapid/sfloat_rgba16.hpp" #include <vk_mem_alloc.h> #include <vulkan/vulkan.hpp> #include <mutex> namespace tt { class gfx_device_vulkan; } namespace tt::pipeline_flat { struct Image; struct device_shared final { gfx_device_vulkan const &device; vk::ShaderModule vertexShaderModule; vk::ShaderModule fragmentShaderModule; std::vector<vk::PipelineShaderStageCreateInfo> shaderStages; device_shared(gfx_device_vulkan const &device); ~device_shared(); device_shared(device_shared const &) = delete; device_shared &operator=(device_shared const &) = delete; device_shared(device_shared &&) = delete; device_shared &operator=(device_shared &&) = delete; /*! Deallocate vulkan resources. * This is called in the destructor of gfx_device_vulkan, therefor we can not use our `device`. */ void destroy(gfx_device_vulkan *vulkanDevice); void drawInCommandBuffer(vk::CommandBuffer &commandBuffer); private: void buildShaders(); void teardownShaders(gfx_device_vulkan *vulkanDevice); }; }
27.469388
98
0.742942
[ "geometry", "vector" ]
f6ace9adb3b433461bdcace18161aa9b0119e9c4
3,447
cpp
C++
aws-cpp-sdk-workspaces/source/model/DefaultWorkspaceCreationProperties.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-workspaces/source/model/DefaultWorkspaceCreationProperties.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-workspaces/source/model/DefaultWorkspaceCreationProperties.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/workspaces/model/DefaultWorkspaceCreationProperties.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace WorkSpaces { namespace Model { DefaultWorkspaceCreationProperties::DefaultWorkspaceCreationProperties() : m_enableWorkDocs(false), m_enableWorkDocsHasBeenSet(false), m_enableInternetAccess(false), m_enableInternetAccessHasBeenSet(false), m_defaultOuHasBeenSet(false), m_customSecurityGroupIdHasBeenSet(false), m_userEnabledAsLocalAdministrator(false), m_userEnabledAsLocalAdministratorHasBeenSet(false) { } DefaultWorkspaceCreationProperties::DefaultWorkspaceCreationProperties(JsonView jsonValue) : m_enableWorkDocs(false), m_enableWorkDocsHasBeenSet(false), m_enableInternetAccess(false), m_enableInternetAccessHasBeenSet(false), m_defaultOuHasBeenSet(false), m_customSecurityGroupIdHasBeenSet(false), m_userEnabledAsLocalAdministrator(false), m_userEnabledAsLocalAdministratorHasBeenSet(false) { *this = jsonValue; } DefaultWorkspaceCreationProperties& DefaultWorkspaceCreationProperties::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("EnableWorkDocs")) { m_enableWorkDocs = jsonValue.GetBool("EnableWorkDocs"); m_enableWorkDocsHasBeenSet = true; } if(jsonValue.ValueExists("EnableInternetAccess")) { m_enableInternetAccess = jsonValue.GetBool("EnableInternetAccess"); m_enableInternetAccessHasBeenSet = true; } if(jsonValue.ValueExists("DefaultOu")) { m_defaultOu = jsonValue.GetString("DefaultOu"); m_defaultOuHasBeenSet = true; } if(jsonValue.ValueExists("CustomSecurityGroupId")) { m_customSecurityGroupId = jsonValue.GetString("CustomSecurityGroupId"); m_customSecurityGroupIdHasBeenSet = true; } if(jsonValue.ValueExists("UserEnabledAsLocalAdministrator")) { m_userEnabledAsLocalAdministrator = jsonValue.GetBool("UserEnabledAsLocalAdministrator"); m_userEnabledAsLocalAdministratorHasBeenSet = true; } return *this; } JsonValue DefaultWorkspaceCreationProperties::Jsonize() const { JsonValue payload; if(m_enableWorkDocsHasBeenSet) { payload.WithBool("EnableWorkDocs", m_enableWorkDocs); } if(m_enableInternetAccessHasBeenSet) { payload.WithBool("EnableInternetAccess", m_enableInternetAccess); } if(m_defaultOuHasBeenSet) { payload.WithString("DefaultOu", m_defaultOu); } if(m_customSecurityGroupIdHasBeenSet) { payload.WithString("CustomSecurityGroupId", m_customSecurityGroupId); } if(m_userEnabledAsLocalAdministratorHasBeenSet) { payload.WithBool("UserEnabledAsLocalAdministrator", m_userEnabledAsLocalAdministrator); } return payload; } } // namespace Model } // namespace WorkSpaces } // namespace Aws
25.345588
102
0.775167
[ "model" ]
f6b1766411ec328913f445424a6da6636bf4d8b2
4,322
hpp
C++
addons/main/CfgMagazines.hpp
johnb432/Weapons-Balance-ACE
49d17b609b853ded7be40ed498e6d0a432e72f41
[ "MIT" ]
null
null
null
addons/main/CfgMagazines.hpp
johnb432/Weapons-Balance-ACE
49d17b609b853ded7be40ed498e6d0a432e72f41
[ "MIT" ]
null
null
null
addons/main/CfgMagazines.hpp
johnb432/Weapons-Balance-ACE
49d17b609b853ded7be40ed498e6d0a432e72f41
[ "MIT" ]
null
null
null
class CfgMagazines { class 2Rnd_12Gauge_Pellets; class 6Rnd_12Gauge_Pellets; class 30Rnd_556x45_Stanag; class 30Rnd_556x45_Stanag_Tracer_Red; class 10Rnd_762x51_Mag; class 20Rnd_762x51_Mag; class 10Rnd_762x54_Mag; class ACE_6Rnd_12Gauge_Pellets_No1_Buck; class ACE_6Rnd_12Gauge_Pellets_No2_Buck; class ACE_6Rnd_12Gauge_Pellets_No3_Buck; class ACE_6Rnd_12Gauge_Pellets_No4_Buck; class ACE_6Rnd_12Gauge_Pellets_No4_Bird; class ACE_10Rnd_762x54_Tracer_mag: 10Rnd_762x54_Mag { mass = 5.1; modelSpecial = ""; }; class ACE_30Rnd_556x45_Stanag_M995_AP_mag: 30Rnd_556x45_Stanag { mass = 9.35; }; class ACE_30Rnd_556x45_Stanag_Mk262_mag: 30Rnd_556x45_Stanag { mass = 9.35; }; class ACE_30Rnd_556x45_Stanag_Mk318_mag: 30Rnd_556x45_Stanag { mass = 9.35; }; class ACE_30Rnd_556x45_Stanag_Tracer_Dim: 30Rnd_556x45_Stanag_Tracer_Red { mass = 9.35; }; class ACE_10Rnd_762x51_M118LR_Mag: 10Rnd_762x51_Mag { mass = 8.9; }; class ACE_10Rnd_762x51_M993_AP_Mag: 10Rnd_762x51_Mag { mass = 8.9; }; class ACE_10Rnd_762x51_Mk316_Mod_0_Mag: 10Rnd_762x51_Mag { mass = 8.9; }; class ACE_10Rnd_762x51_Mk319_Mod_0_Mag: 10Rnd_762x51_Mag { mass = 8.9; }; class ACE_20Rnd_762x51_M118LR_Mag: 20Rnd_762x51_Mag { mass = 16.24; }; class ACE_20Rnd_762x51_M993_AP_Mag: 20Rnd_762x51_Mag { mass = 16.24; }; class ACE_20Rnd_762x51_Mk316_Mod_0_Mag: 20Rnd_762x51_Mag { mass = 16.24; }; class ACE_20Rnd_762x51_Mk319_Mod_0_Mag: 20Rnd_762x51_Mag { mass = 16.24; }; class ACE_20Rnd_762x51_Mag_SD: 20Rnd_762x51_Mag { mass = 16.24; }; class ACE_20Rnd_762x51_Mag_Tracer: 20Rnd_762x51_Mag { mass = 16.24; }; class ACE_2Rnd_12Gauge_Pellets_No0_Buck: 2Rnd_12Gauge_Pellets { mass = 2.2; }; class ACE_6Rnd_12Gauge_Pellets_No0_Buck: 6Rnd_12Gauge_Pellets { mass = 6.6; }; class ACE_8Rnd_12Gauge_Pellets_No00_Buck: 6Rnd_12Gauge_Pellets { author = "johnb43"; displayname = "12 Gauge 8Rnd #00 Buckshot"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; class ACE_8Rnd_12Gauge_Pellets_No0_Buck: ACE_6Rnd_12Gauge_Pellets_No0_Buck { author = "johnb43"; displayname = "12 Gauge 8Rnd #0 Buckshot"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; class ACE_8Rnd_12Gauge_Pellets_No1_Buck: ACE_6Rnd_12Gauge_Pellets_No1_Buck { author = "johnb43"; displayname = "12 Gauge 8Rnd #1 Buckshot"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; class ACE_8Rnd_12Gauge_Pellets_No2_Buck: ACE_6Rnd_12Gauge_Pellets_No2_Buck { author = "johnb43"; displayname = "12 Gauge 8Rnd #2 Buckshot"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; class ACE_8Rnd_12Gauge_Pellets_No3_Buck: ACE_6Rnd_12Gauge_Pellets_No3_Buck { author = "johnb43"; displayname = "12 Gauge 8Rnd #3 Buckshot"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; class ACE_8Rnd_12Gauge_Pellets_No4_Buck: ACE_6Rnd_12Gauge_Pellets_No4_Buck { author = "johnb43"; displayname = "12 Gauge 8Rnd #4 Buckshot"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; class ACE_8Rnd_12Gauge_Pellets_No4_Bird: ACE_6Rnd_12Gauge_Pellets_No4_Bird { author = "johnb43"; displayname = "12 Gauge 8Rnd #7 Birdshot"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; class 6Rnd_12Gauge_Slug; class ACE_8Rnd_12Gauge_Pellets_Slug_Buck: 6Rnd_12Gauge_Slug { author = "johnb43"; displayname = "12 Gauge 8Rnd Slug"; count = 8; mass = 8.8; model = "\A3\weapons_F\ammo\mag_univ.p3d"; modelSpecial = ""; }; };
30.871429
80
0.639519
[ "model" ]
f6b300f1ef468f308fc84f555557410297985cbb
7,241
cc
C++
tensorflow/core/kernels/bcast_ops.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
190,993
2015-11-09T13:17:30.000Z
2022-03-31T23:05:27.000Z
tensorflow/core/kernels/bcast_ops.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
48,461
2015-11-09T14:21:11.000Z
2022-03-31T23:17:33.000Z
tensorflow/core/kernels/bcast_ops.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
104,981
2015-11-09T13:40:17.000Z
2022-03-31T19:51:54.000Z
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/bcast.h" namespace tensorflow { // Given shapes of two tensors, computes the broadcast shape. template <typename T> class BCastArgsOp : public OpKernel { public: explicit BCastArgsOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { OP_REQUIRES( ctx, ctx->num_inputs() == 2, errors::Unimplemented("Broadcast for n-ary operations (n > 2)")); gtl::InlinedVector<BCast::Vec, 4> shapes; for (int i = 0; i < ctx->num_inputs(); ++i) { const Tensor& in = ctx->input(i); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(in.shape()), errors::InvalidArgument("In[", i, "] must be a vector.", in.shape().DebugString())); BCast::Vec vec; for (int64_t i = 0; i < in.NumElements(); ++i) { vec.push_back(in.vec<T>()(i)); } shapes.push_back(vec); } BCast bcast(shapes[0], shapes[1]); OP_REQUIRES(ctx, bcast.IsValid(), errors::InvalidArgument( "Incompatible shapes: [", absl::StrJoin(shapes[0], ","), "] vs. [", absl::StrJoin(shapes[1], ","), "]")); Output(ctx, 0, bcast.output_shape()); } bool IsExpensive() override { return false; } private: void Output(OpKernelContext* ctx, int idx, const BCast::Vec& v) { const int64_t len = v.size(); Tensor* o = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(idx, TensorShape({len}), &o)); for (int64_t i = 0; i < len; ++i) { o->flat<T>()(i) = static_cast<T>(v[i]); } } TF_DISALLOW_COPY_AND_ASSIGN(BCastArgsOp); }; // Given shapes of two tensors, computes the reduction indices for the // gradient computation. // // TODO(zhifengc): // 1. Adds support for n-ary (n >= 2). template <typename T> class BCastGradArgsOp : public OpKernel { public: explicit BCastGradArgsOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { OP_REQUIRES( ctx, ctx->num_inputs() == 2, errors::Unimplemented("Broadcast for n-ary operations (n > 2)")); gtl::InlinedVector<BCast::Vec, 4> shapes; for (int i = 0; i < ctx->num_inputs(); ++i) { const Tensor& in = ctx->input(i); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(in.shape()), errors::InvalidArgument("In[", i, "] must be a vector.", in.shape().DebugString())); BCast::Vec vec; for (int64_t i = 0; i < in.NumElements(); ++i) { vec.push_back(in.vec<T>()(i)); } shapes.push_back(vec); } BCast bcast(shapes[0], shapes[1]); OP_REQUIRES(ctx, bcast.IsValid(), errors::InvalidArgument( "Incompatible shapes: [", absl::StrJoin(shapes[0], ","), "] vs. [", absl::StrJoin(shapes[1], ","), "]")); Output(ctx, 0, bcast.grad_x_reduce_idx()); Output(ctx, 1, bcast.grad_y_reduce_idx()); } bool IsExpensive() override { return false; } private: void Output(OpKernelContext* ctx, int idx, const BCast::Vec& v) { const int64_t len = v.size(); Tensor* o = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(idx, TensorShape({len}), &o)); for (int64_t i = 0; i < len; ++i) { o->flat<T>()(i) = static_cast<T>(v[i]); } } TF_DISALLOW_COPY_AND_ASSIGN(BCastGradArgsOp); }; REGISTER_KERNEL_BUILDER(Name("BroadcastArgs") .Device(DEVICE_CPU) .TypeConstraint<int32>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0"), BCastArgsOp<int32>); REGISTER_KERNEL_BUILDER(Name("BroadcastArgs") .Device(DEVICE_CPU) .TypeConstraint<int64_t>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0"), BCastArgsOp<int64_t>); REGISTER_KERNEL_BUILDER(Name("BroadcastArgs") .Device(DEVICE_DEFAULT) .TypeConstraint<int32>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0"), BCastArgsOp<int32>); REGISTER_KERNEL_BUILDER(Name("BroadcastArgs") .Device(DEVICE_DEFAULT) .TypeConstraint<int64_t>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0"), BCastArgsOp<int64_t>); REGISTER_KERNEL_BUILDER(Name("BroadcastGradientArgs") .Device(DEVICE_CPU) .TypeConstraint<int32>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0") .HostMemory("r1"), BCastGradArgsOp<int32>); REGISTER_KERNEL_BUILDER(Name("BroadcastGradientArgs") .Device(DEVICE_CPU) .TypeConstraint<int64_t>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0") .HostMemory("r1"), BCastGradArgsOp<int64_t>); REGISTER_KERNEL_BUILDER(Name("BroadcastGradientArgs") .Device(DEVICE_DEFAULT) .TypeConstraint<int32>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0") .HostMemory("r1"), BCastGradArgsOp<int32>); REGISTER_KERNEL_BUILDER(Name("BroadcastGradientArgs") .Device(DEVICE_DEFAULT) .TypeConstraint<int64_t>("T") .HostMemory("s0") .HostMemory("s1") .HostMemory("r0") .HostMemory("r1"), BCastGradArgsOp<int64_t>); } // end namespace tensorflow
39.785714
80
0.52327
[ "shape", "vector" ]
f6b6eea11234567680eae44c6acfda5f4a04e944
10,754
cpp
C++
Seaurchin/CharacterInstance.cpp
AioiLight/Seaurchin
ac6763a51bfba09338f038ab50bdb2ebc883b114
[ "BSL-1.0", "MIT" ]
11
2018-11-11T07:44:02.000Z
2021-02-28T08:29:17.000Z
Seaurchin/CharacterInstance.cpp
amenoshita-429/Seaurchin
b9a196ffab080299132a3b2c10b7b778eda58be4
[ "BSL-1.0", "MIT" ]
null
null
null
Seaurchin/CharacterInstance.cpp
amenoshita-429/Seaurchin
b9a196ffab080299132a3b2c10b7b778eda58be4
[ "BSL-1.0", "MIT" ]
5
2020-10-12T20:09:40.000Z
2021-09-02T00:20:47.000Z
#include "CharacterInstance.h" #include "Misc.h" #include "Setting.h" #include "Config.h" #include "ScriptScene.h" using namespace std; CharacterInstance::CharacterInstance(const shared_ptr<CharacterParameter>& character, const shared_ptr<SkillParameter>& skill, const shared_ptr<AngelScript>& script, const shared_ptr<Result>& result) : scriptInterface(script) , characterSource(character) , skillSource(skill) , imageSet(nullptr) , indicators(new SkillIndicators()) , targetResult(result) , context(script->GetEngine()->CreateContext()) , judgeCallback(nullptr) {} CharacterInstance::~CharacterInstance() { if (judgeCallback) judgeCallback->Release(); context->Release(); for (const auto &t : abilityTypes) t->Release(); for (const auto &o : abilities) o->Release(); if (imageSet) imageSet->Release(); } shared_ptr<CharacterInstance> CharacterInstance::CreateInstance(shared_ptr<CharacterParameter> character, shared_ptr<SkillParameter> skill, shared_ptr<AngelScript> script, std::shared_ptr<Result> result) { auto ci = make_shared<CharacterInstance>(character, skill, script, result); ci->LoadAbilities(); ci->CreateImageSet(); ci->AddRef(); return ci; } void CharacterInstance::LoadAbilities() { using namespace boost::algorithm; using namespace boost::filesystem; auto log = spdlog::get("main"); const auto abroot = Setting::GetRootDirectory() / SU_SKILL_DIR / SU_ABILITY_DIR; const auto &abilities = skillSource->GetDetail(skillSource->CurrentLevel).Abilities; for (const auto &def : abilities) { vector<string> params; auto scrpath = abroot / ConvertUTF8ToUnicode(def.Name + ".as"); auto abo = LoadAbilityObject(scrpath); if (!abo) continue; auto abt = abo->GetObjectType(); abt->AddRef(); AbilityFunctions funcs; funcs.OnStart = abt->GetMethodByDecl("void OnStart(" SU_IF_RESULT "@)"); funcs.OnFinish = abt->GetMethodByDecl("void OnFinish(" SU_IF_RESULT "@)"); funcs.OnJusticeCritical = abt->GetMethodByDecl("void OnJusticeCritical(" SU_IF_RESULT "@, " SU_IF_JUDGE_DATA ")"); funcs.OnJustice = abt->GetMethodByDecl("void OnJustice(" SU_IF_RESULT "@, " SU_IF_JUDGE_DATA ")"); funcs.OnAttack = abt->GetMethodByDecl("void OnAttack(" SU_IF_RESULT "@, " SU_IF_JUDGE_DATA ")"); funcs.OnMiss = abt->GetMethodByDecl("void OnMiss(" SU_IF_RESULT "@, " SU_IF_JUDGE_DATA ")"); this->abilities.push_back(abo); abilityTypes.push_back(abt); abilityEvents.push_back(funcs); const auto init = abt->GetMethodByDecl("void Initialize(dictionary@, " SU_IF_SKILL_INDICATORS "@)"); if (!init) continue; auto args = CScriptDictionary::Create(scriptInterface->GetEngine()); for (const auto &arg : def.Arguments) { const auto key = arg.first; auto value = arg.second; auto &vid = value.type(); if (vid == typeid(int)) { asINT64 avalue = boost::any_cast<int>(value); args->Set(key, avalue); } else if (vid == typeid(double)) { auto avalue = boost::any_cast<double>(value); args->Set(key, avalue); } else if (vid == typeid(string)) { auto avalue = boost::any_cast<string>(value); args->Set(key, &avalue, scriptInterface->GetEngine()->GetTypeIdByDecl("string")); } } context->Prepare(init); context->SetObject(abo); context->SetArgAddress(0, args); context->SetArgAddress(1, indicators.get()); context->Execute(); context->Unprepare(); log->info(u8"アビリティー " + ConvertUnicodeToUTF8(scrpath.c_str())); } } void CharacterInstance::CreateImageSet() { imageSet = CharacterImageSet::CreateImageSet(characterSource); } asIScriptObject* CharacterInstance::LoadAbilityObject(const boost::filesystem::path& filepath) { using namespace boost::filesystem; auto log = spdlog::get("main"); auto abroot = Setting::GetRootDirectory() / SU_SKILL_DIR / SU_ABILITY_DIR; //お茶を濁せ const auto modulename = ConvertUnicodeToUTF8(filepath.c_str()); auto mod = scriptInterface->GetExistModule(modulename); if (!mod) { scriptInterface->StartBuildModule(modulename, [=](wstring inc, wstring from, CWScriptBuilder *b) { if (!exists(abroot / inc)) return false; b->AddSectionFromFile((abroot / inc).wstring().c_str()); return true; }); scriptInterface->LoadFile(filepath.wstring()); if (!scriptInterface->FinishBuildModule()) { scriptInterface->GetLastModule()->Discard(); return nullptr; } mod = scriptInterface->GetLastModule(); } //エントリポイント検索 const int cnt = mod->GetObjectTypeCount(); asITypeInfo *type = nullptr; for (auto i = 0; i < cnt; i++) { const auto cti = mod->GetObjectTypeByIndex(i); if (!(scriptInterface->CheckMetaData(cti, "EntryPoint") || cti->GetUserData(SU_UDTYPE_ENTRYPOINT))) continue; type = cti; type->SetUserData(reinterpret_cast<void*>(0xFFFFFFFF), SU_UDTYPE_ENTRYPOINT); type->AddRef(); break; } if (!type) { log->critical(u8"アビリティーにEntryPointがありません"); return nullptr; } const auto obj = scriptInterface->InstantiateObject(type); type->Release(); return obj; } void CharacterInstance::CallEventFunction(asIScriptObject *obj, asIScriptFunction *func) const { context->Prepare(func); context->SetObject(obj); context->SetArgAddress(0, targetResult.get()); context->Execute(); context->Unprepare(); } void CharacterInstance::CallEventFunction(asIScriptObject *obj, asIScriptFunction *func, const JudgeInformation &info) const { auto infoClone = info; context->Prepare(func); context->SetObject(obj); context->SetArgAddress(0, targetResult.get()); context->SetArgObject(1, static_cast<void*>(&infoClone)); context->Execute(); context->Unprepare(); } void CharacterInstance::CallJudgeCallback(const AbilityJudgeType judge, const JudgeInformation &info, const string& extra) const { if (!judgeCallback) return; if (!judgeCallback->IsExists()) { judgeCallback->Release(); judgeCallback = nullptr; return; } auto message = extra; auto infoClone = info; judgeCallback->Prepare(); judgeCallback->SetArg(0, SU_TO_INT32(judge)); judgeCallback->SetArgObject(1, &infoClone); judgeCallback->SetArgObject(2, &message); judgeCallback->Execute(); judgeCallback->Unprepare(); } void CharacterInstance::OnStart() { for (auto i = 0u; i < abilities.size(); ++i) { const auto func = abilityEvents[i].OnStart; const auto obj = abilities[i]; CallEventFunction(obj, func); } } void CharacterInstance::OnFinish() { for (auto i = 0u; i < abilities.size(); ++i) { const auto func = abilityEvents[i].OnFinish; const auto obj = abilities[i]; CallEventFunction(obj, func); } } void CharacterInstance::OnJusticeCritical(const JudgeInformation &info, const string& extra) { for (auto i = 0u; i < abilities.size(); ++i) { const auto func = abilityEvents[i].OnJusticeCritical; const auto obj = abilities[i]; CallEventFunction(obj, func, info); } CallJudgeCallback(AbilityJudgeType::JusticeCritical, info, extra); } void CharacterInstance::OnJustice(const JudgeInformation &info, const string& extra) { for (auto i = 0u; i < abilities.size(); ++i) { const auto func = abilityEvents[i].OnJustice; const auto obj = abilities[i]; CallEventFunction(obj, func, info); } CallJudgeCallback(AbilityJudgeType::Justice, info, extra); } void CharacterInstance::OnAttack(const JudgeInformation &info, const string& extra) { for (auto i = 0u; i < abilities.size(); ++i) { const auto func = abilityEvents[i].OnAttack; const auto obj = abilities[i]; CallEventFunction(obj, func, info); } CallJudgeCallback(AbilityJudgeType::Attack, info, extra); } void CharacterInstance::OnMiss(const JudgeInformation &info, const string& extra) { for (auto i = 0u; i < abilities.size(); ++i) { const auto func = abilityEvents[i].OnMiss; const auto obj = abilities[i]; CallEventFunction(obj, func, info); } CallJudgeCallback(AbilityJudgeType::Miss, info, extra); } void CharacterInstance::SetCallback(asIScriptFunction *func, ScriptScene *sceneObj) { if (!func || func->GetFuncType() != asFUNC_DELEGATE) return; if (judgeCallback) judgeCallback->Release(); func->AddRef(); judgeCallback = new CallbackObject(func); judgeCallback->SetUserData(sceneObj, SU_UDTYPE_SCENE); judgeCallback->AddRef(); sceneObj->RegisterDisposalCallback(judgeCallback); func->Release(); } CharacterParameter* CharacterInstance::GetCharacterParameter() const { return characterSource.get(); } SkillParameter* CharacterInstance::GetSkillParameter() const { return skillSource.get(); } SkillIndicators* CharacterInstance::GetSkillIndicators() const { return indicators.get(); } CharacterImageSet* CharacterInstance::GetCharacterImages() const { imageSet->AddRef(); return imageSet; } void RegisterCharacterSkillTypes(asIScriptEngine *engine) { RegisterResultTypes(engine); RegisterSkillTypes(engine); RegisterCharacterTypes(engine); engine->RegisterFuncdef("void " SU_IF_JUDGE_CALLBACK "(" SU_IF_JUDGETYPE ", " SU_IF_JUDGE_DATA ", const string &in)"); engine->RegisterObjectType(SU_IF_CHARACTER_INSTANCE, 0, asOBJ_REF); engine->RegisterObjectBehaviour(SU_IF_CHARACTER_INSTANCE, asBEHAVE_ADDREF, "void f()", asMETHOD(CharacterInstance, AddRef), asCALL_THISCALL); engine->RegisterObjectBehaviour(SU_IF_CHARACTER_INSTANCE, asBEHAVE_RELEASE, "void f()", asMETHOD(CharacterInstance, Release), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_CHARACTER_INSTANCE, SU_IF_CHARACTER_PARAM "@ GetCharacter()", asMETHOD(CharacterInstance, GetCharacterParameter), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_CHARACTER_INSTANCE, SU_IF_CHARACTER_IMAGES "@ GetCharacterImages()", asMETHOD(CharacterInstance, GetCharacterImages), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_CHARACTER_INSTANCE, SU_IF_SKILL "@ GetSkill()", asMETHOD(CharacterInstance, GetSkillParameter), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_CHARACTER_INSTANCE, SU_IF_SKILL_INDICATORS "@ GetSkillIndicators()", asMETHOD(CharacterInstance, GetSkillIndicators), asCALL_THISCALL); }
36.828767
203
0.682723
[ "vector" ]
f6b784ae5d1b9ea1ba291637fc98c9a93bdfd0ff
2,389
cpp
C++
_includes/leet353/leet353_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet353/leet353_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet353/leet353_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
struct pairhash { public: template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const { return std::hash<T>()(x.first) ^ std::hash<U>()(x.second); } }; class SnakeGame { public: /** Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ SnakeGame(int width, int height, vector<pair<int, int>> food) { i = 0; this->food = food; this->height = height; this->width = width; B.insert(make_pair(0,0)); S.push_back(make_pair(0,0)); } /** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ int move(string direction) { auto head = S.front(); switch(direction[0]){ case 'U': head.first--; if(head.first < 0 ) return -1; break; case 'L': head.second--; if(head.second < 0) return -1; break; case 'R': head.second++; if(head.second >= width) return -1; break; case 'D': head.first++; if(head.first >= height) return -1; break; default: return -1; } return move(head); } private: std::unordered_set <std::pair <int, int>,pairhash> B; vector<pair<int, int>> food; deque<pair<int, int>> S; int height; int width; int i; int move(pair<int,int>& head){ S.push_front(head); if(i<food.size()&&head == food[i]){ i++; } else{ auto tail = S.back(); B.erase(tail); S.pop_back(); } if(B.count(head)>0) return -1; else B.insert(head); return S.size()-1; } }; /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */
28.440476
105
0.494768
[ "object", "vector" ]
f6bae6db6d9f12a3683786d333ada82b1a8237b3
2,169
cc
C++
examples/http_client.cc
flusile/pistache
736f4ba8cd2f0ba54ee0daa85fa9f8beca930b00
[ "Apache-2.0" ]
null
null
null
examples/http_client.cc
flusile/pistache
736f4ba8cd2f0ba54ee0daa85fa9f8beca930b00
[ "Apache-2.0" ]
null
null
null
examples/http_client.cc
flusile/pistache
736f4ba8cd2f0ba54ee0daa85fa9f8beca930b00
[ "Apache-2.0" ]
null
null
null
/* Mathieu Stefani, 07 février 2016 * Http client example */ #include <atomic> #include <pistache/client.h> #include <pistache/http.h> #include <pistache/net.h> using namespace Pistache; int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << "Usage: http_client page [count]\n"; return 1; } std::string page = argv[1]; int count = 1; if (argc == 3) { count = std::stoi(argv[2]); } Http::Client client; auto opts = Http::Client::options().threads(1).maxConnectionsPerHost(8); client.init(opts); std::vector<Async::Promise<Http::Response>> responses; std::atomic<size_t> completedRequests(0); std::atomic<size_t> failedRequests(0); auto start = std::chrono::system_clock::now(); for (int i = 0; i < count; ++i) { auto resp = client.get(page).cookie(Http::Cookie("FOO", "bar")).send(); resp.then( [&](Http::Response response) { ++completedRequests; std::cout << "Response code = " << response.code() << std::endl; auto body = response.body(); if (!body.empty()) std::cout << "Response body = " << body << std::endl; }, [&](std::exception_ptr exc) { ++failedRequests; PrintException excPrinter; excPrinter(exc); }); responses.push_back(std::move(resp)); } auto sync = Async::whenAll(responses.begin(), responses.end()); Async::Barrier<std::vector<Http::Response>> barrier(sync); barrier.wait_for(std::chrono::seconds(5)); auto end = std::chrono::system_clock::now(); std::cout << "Summary of execution\n" << "Total number of requests sent : " << count << '\n' << "Total number of responses received: " << completedRequests.load() << '\n' << "Total number of requests failed : " << failedRequests.load() << '\n' << "Total time of execution : " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start) .count() << "ms" << std::endl; client.shutdown(); }
28.539474
78
0.550945
[ "vector" ]
f6bbc5c795af7ae546ae77eee9f5ae835e67b66c
11,877
cc
C++
src/developer/feedback/boot_log_checker/tests/reboot_log_handler_unittest.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
src/developer/feedback/boot_log_checker/tests/reboot_log_handler_unittest.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
src/developer/feedback/boot_log_checker/tests/reboot_log_handler_unittest.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/feedback/boot_log_checker/reboot_log_handler.h" #include <lib/async/cpp/executor.h> #include <lib/fit/result.h> #include <lib/zx/time.h> #include <zircon/errors.h> #include <cstdint> #include <memory> #include <optional> #include <vector> #include "src/developer/feedback/boot_log_checker/tests/stub_crash_reporter.h" #include "src/developer/feedback/boot_log_checker/tests/stub_network_reachability_provider.h" #include "src/developer/feedback/testing/cobalt_test_fixture.h" #include "src/developer/feedback/testing/gpretty_printers.h" #include "src/developer/feedback/testing/stubs/stub_cobalt_logger.h" #include "src/developer/feedback/testing/stubs/stub_cobalt_logger_factory.h" #include "src/developer/feedback/testing/unit_test_fixture.h" #include "src/developer/feedback/utils/cobalt.h" #include "src/developer/feedback/utils/cobalt_event.h" #include "src/lib/files/scoped_temp_dir.h" #include "third_party/googletest/googlemock/include/gmock/gmock.h" #include "third_party/googletest/googletest/include/gtest/gtest.h" namespace feedback { namespace { using testing::ElementsAre; using testing::IsEmpty; constexpr fit::result_state kError = fit::result_state::error; constexpr fit::result_state kOk = fit::result_state::ok; constexpr fit::result_state kPending = fit::result_state::pending; struct TestParam { std::string test_name; std::string input_reboot_log; std::string output_crash_signature; std::optional<zx::duration> output_uptime; RebootReason output_cobalt_event_code; }; class RebootLogHandlerTest : public UnitTestFixture, public CobaltTestFixture, public testing::WithParamInterface<TestParam> { public: RebootLogHandlerTest() : CobaltTestFixture(/*unit_test_fixture=*/this), executor_(dispatcher()) {} protected: void SetUpNetworkReachabilityProvider( std::unique_ptr<StubConnectivity> network_reachability_provider) { network_reachability_provider_ = std::move(network_reachability_provider); if (network_reachability_provider_) { InjectServiceProvider(network_reachability_provider_.get()); } } void SetUpCrashReporter(std::unique_ptr<StubCrashReporter> crash_reporter) { crash_reporter_ = std::move(crash_reporter); if (crash_reporter_) { InjectServiceProvider(crash_reporter_.get()); } } void WriteRebootLogContents(const std::string& contents = "ZIRCON REBOOT REASON (KERNEL PANIC)\n\nUPTIME (ms)\n74715002") { ASSERT_TRUE(tmp_dir_.NewTempFileWithData(contents, &reboot_log_path_)); } fit::result<void> HandleRebootLog() { fit::result<void> result; executor_.schedule_task( feedback::HandleRebootLog(reboot_log_path_, dispatcher(), services()) .then([&result](fit::result<void>& res) { result = std::move(res); })); RunLoopUntilIdle(); return result; } fit::result<void> HandleRebootLogTriggerOnNetworkReachable() { auto result = HandleRebootLog(); EXPECT_EQ(result.state(), kPending); network_reachability_provider_->TriggerOnNetworkReachable(true); // TODO(fxb/46216): remove delay. RunLoopFor(zx::sec(30)); return result; } private: async::Executor executor_; protected: std::unique_ptr<StubConnectivity> network_reachability_provider_; std::unique_ptr<StubCrashReporter> crash_reporter_; std::string reboot_log_path_; private: files::ScopedTempDir tmp_dir_; }; TEST_F(RebootLogHandlerTest, Succeed_NoRebootLog) { // We write nothing in |reboot_log_path_| so no file will exist at that path. EXPECT_EQ(HandleRebootLog().state(), kOk); } INSTANTIATE_TEST_SUITE_P(WithVariousRebootLogs, RebootLogHandlerTest, ::testing::ValuesIn(std::vector<TestParam>({ { "KernelPanicCrashLog", "ZIRCON REBOOT REASON (KERNEL PANIC)\n\nUPTIME (ms)\n74715002", "fuchsia-kernel-panic", zx::msec(74715002), RebootReason::kKernelPanic, }, { "KernelPanicCrashLogNoUptime", "ZIRCON REBOOT REASON (KERNEL PANIC)", "fuchsia-kernel-panic", std::nullopt, RebootReason::kKernelPanic, }, { "KernelPanicCrashLogWrongUptime", "ZIRCON REBOOT REASON (KERNEL PANIC)\n\nUNRECOGNIZED", "fuchsia-kernel-panic", std::nullopt, RebootReason::kKernelPanic, }, { "OutOfMemoryLog", "ZIRCON REBOOT REASON (OOM)\n\nUPTIME (ms)\n65487494", "fuchsia-oom", zx::msec(65487494), RebootReason::kOOM, }, { "OutOfMemoryLogNoUptime", "ZIRCON REBOOT REASON (OOM)", "fuchsia-oom", std::nullopt, RebootReason::kOOM, }, { "SoftwareWatchdogFired", "ZIRCON REBOOT REASON (SW WATCHDOG)", "fuchsia-sw-watchdog", std::nullopt, RebootReason::kSoftwareWatchdog, }, { "HardwareWatchdogFired", "ZIRCON REBOOT REASON (HW WATCHDOG)", "fuchsia-hw-watchdog", std::nullopt, RebootReason::kHardwareWatchdog, }, { "BrownoutPowerSupplyFailure", "ZIRCON REBOOT REASON (BROWNOUT)", "fuchsia-brownout", std::nullopt, RebootReason::kBrownout, }, { "UnrecognizedCrashTypeInRebootLog", "UNRECOGNIZED CRASH TYPE", "fuchsia-kernel-panic", std::nullopt, RebootReason::kKernelPanic, }, })), [](const testing::TestParamInfo<TestParam>& info) { return info.param.test_name; }); TEST_P(RebootLogHandlerTest, Succeed) { const auto param = GetParam(); WriteRebootLogContents(param.input_reboot_log); SetUpNetworkReachabilityProvider(std::make_unique<StubConnectivity>()); SetUpCrashReporter(std::make_unique<StubCrashReporter>()); SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); fit::result<void> result = HandleRebootLogTriggerOnNetworkReachable(); EXPECT_EQ(result.state(), kOk); EXPECT_STREQ(crash_reporter_->crash_signature().c_str(), param.output_crash_signature.c_str()); EXPECT_STREQ(crash_reporter_->reboot_log().c_str(), param.input_reboot_log.c_str()); EXPECT_EQ(crash_reporter_->uptime(), param.output_uptime); EXPECT_THAT(ReceivedCobaltEvents(), ElementsAre(CobaltEvent(param.output_cobalt_event_code))); } TEST_F(RebootLogHandlerTest, Pending_NetworkNotReachable) { WriteRebootLogContents(); SetUpNetworkReachabilityProvider(std::make_unique<StubConnectivity>()); SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); fit::result<void> result = HandleRebootLog(); EXPECT_EQ(result.state(), kPending); network_reachability_provider_->TriggerOnNetworkReachable(false); RunLoopUntilIdle(); EXPECT_EQ(result.state(), kPending); network_reachability_provider_->TriggerOnNetworkReachable(false); RunLoopUntilIdle(); EXPECT_EQ(result.state(), kPending); EXPECT_THAT(ReceivedCobaltEvents(), ElementsAre(CobaltEvent(RebootReason::kKernelPanic))); } TEST_F(RebootLogHandlerTest, Fail_EmptyRebootLog) { SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); WriteRebootLogContents(""); EXPECT_EQ(HandleRebootLog().state(), kError); EXPECT_THAT(ReceivedCobaltEvents(), IsEmpty()); } TEST_F(RebootLogHandlerTest, Fail_NetworkReachabilityProviderNotAvailable) { WriteRebootLogContents(); SetUpNetworkReachabilityProvider(nullptr); SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); EXPECT_EQ(HandleRebootLog().state(), kError); EXPECT_THAT(ReceivedCobaltEvents(), ElementsAre(CobaltEvent(RebootReason::kKernelPanic))); } TEST_F(RebootLogHandlerTest, Fail_NetworkReachabilityProviderClosesConnection) { WriteRebootLogContents(); SetUpNetworkReachabilityProvider(std::make_unique<StubConnectivity>()); SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); fit::result<void> result = HandleRebootLog(); EXPECT_EQ(result.state(), kPending); network_reachability_provider_->CloseConnection(); RunLoopUntilIdle(); EXPECT_EQ(result.state(), kError); EXPECT_THAT(ReceivedCobaltEvents(), ElementsAre(CobaltEvent(RebootReason::kKernelPanic))); } TEST_F(RebootLogHandlerTest, Fail_CrashReporterNotAvailable) { WriteRebootLogContents(); SetUpNetworkReachabilityProvider(std::make_unique<StubConnectivity>()); SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); fit::result<void> result = HandleRebootLogTriggerOnNetworkReachable(); EXPECT_EQ(result.state(), kError); EXPECT_THAT(ReceivedCobaltEvents(), ElementsAre(CobaltEvent(RebootReason::kKernelPanic))); } TEST_F(RebootLogHandlerTest, Fail_CrashReporterClosesConnection) { WriteRebootLogContents(); SetUpNetworkReachabilityProvider(std::make_unique<StubConnectivity>()); SetUpCrashReporter(std::make_unique<StubCrashReporterClosesConnection>()); SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); fit::result<void> result = HandleRebootLogTriggerOnNetworkReachable(); EXPECT_EQ(result.state(), kError); EXPECT_THAT(ReceivedCobaltEvents(), ElementsAre(CobaltEvent(RebootReason::kKernelPanic))); } TEST_F(RebootLogHandlerTest, Fail_CrashReporterFailsToFile) { WriteRebootLogContents(); SetUpNetworkReachabilityProvider(std::make_unique<StubConnectivity>()); SetUpCrashReporter(std::make_unique<StubCrashReporterAlwaysReturnsError>()); SetUpCobaltLoggerFactory(std::make_unique<StubCobaltLoggerFactory>()); fit::result<void> result = HandleRebootLogTriggerOnNetworkReachable(); EXPECT_EQ(result.state(), kError); EXPECT_THAT(ReceivedCobaltEvents(), ElementsAre(CobaltEvent(RebootReason::kKernelPanic))); } TEST_F(RebootLogHandlerTest, Fail_CallHandleTwice) { internal::RebootLogHandler handler(dispatcher(), services()); handler.Handle("irrelevant"); ASSERT_DEATH(handler.Handle("irrelevant"), testing::HasSubstr("Handle() is not intended to be called twice")); } } // namespace } // namespace feedback
40.397959
100
0.635935
[ "vector" ]
f6bca213e570e85cf1cfb9686ac4abc3f6fe7c0a
2,463
cxx
C++
panda/src/device/clientDevice.cxx
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/device/clientDevice.cxx
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/device/clientDevice.cxx
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file clientDevice.cxx * @author drose * @date 2001-01-25 */ #include "clientDevice.h" #include "clientBase.h" #include "indent.h" TypeHandle ClientDevice::_type_handle; /** * */ ClientDevice:: ClientDevice(ClientBase *client, TypeHandle device_type, const string &device_name) : _client(client), _device_type(device_type), _device_name(device_name) { // We have to explicitly ref the client pointer, since we can't use a // PT(ClientBase) for circular include reasons. _client->ref(); _is_connected = false; } /** * We don't actually call disconnect() at the ClientDevice level destructor, * because by the time we get here we're already partly destructed. Instead, * we should call disconnect() from each specific kind of derived class. */ ClientDevice:: ~ClientDevice() { nassertv(!_is_connected); // And now we explicitly unref the client pointer. unref_delete(_client); } /** * Disconnects the ClientDevice from its ClientBase object. The device will * stop receiving updates. * * Normally, you should not need to call this explicitly (and it is probably a * mistake to do so); it will automatically be called when the ClientDevice * object destructs. * * The lock should *not* be held while this call is made; it will explicitly * grab the lock itself. */ void ClientDevice:: disconnect() { if (_is_connected) { acquire(); bool disconnected = _client->disconnect_device(_device_type, _device_name, this); _is_connected = false; unlock(); nassertv(disconnected); } } /** * Causes the connected ClientBase to poll all of its clients, if necessary. * This will be a no-op if the client is running in forked mode, or if it has * already polled everything this frame. * * This should generally be called before accessing the data in this * ClientDevice to ensure that it is fresh. */ void ClientDevice:: poll() { _client->poll(); } /** * */ void ClientDevice:: output(ostream &out) const { out << get_type() << " " << get_device_name(); } /** * */ void ClientDevice:: write(ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; }
24.386139
78
0.702395
[ "object", "3d" ]
f6c214e2c6862de619b36251747472790ca73a3c
92,504
cpp
C++
src/backends/reference/RefLayerSupport.cpp
UberLambda/armnn
ba163f93c8a0e858c9fb1ea85e4ac34c966ef38a
[ "MIT" ]
null
null
null
src/backends/reference/RefLayerSupport.cpp
UberLambda/armnn
ba163f93c8a0e858c9fb1ea85e4ac34c966ef38a
[ "MIT" ]
null
null
null
src/backends/reference/RefLayerSupport.cpp
UberLambda/armnn
ba163f93c8a0e858c9fb1ea85e4ac34c966ef38a
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "RefLayerSupport.hpp" #include <armnn/TypesUtils.hpp> #include <armnn/Types.hpp> #include <armnn/Descriptors.hpp> #include <armnn/utility/IgnoreUnused.hpp> #include <LayerSupportCommon.hpp> #include <backendsCommon/LayerSupportRules.hpp> #include <boost/cast.hpp> #include <vector> #include <array> using namespace boost; namespace armnn { namespace { template<typename Float32Func, typename Uint8Func, typename ... Params> bool IsSupportedForDataTypeRef(Optional<std::string&> reasonIfUnsupported, DataType dataType, Float32Func floatFuncPtr, Uint8Func uint8FuncPtr, Params&&... params) { return IsSupportedForDataTypeGeneric(reasonIfUnsupported, dataType, &FalseFunc<Params...>, floatFuncPtr, uint8FuncPtr, &FalseFunc<Params...>, &FalseFunc<Params...>, std::forward<Params>(params)...); } } // anonymous namespace namespace { std::string CreateIncorrectDimensionsErrorMsg(unsigned int expected, unsigned int actual, std::string& layerStr, std::string& tensorName) { std::string errorMsg = "Reference " + layerStr + ": Expected " + std::to_string(expected) + " dimensions but got" + " " + std::to_string(actual) + " dimensions instead, for the '" + tensorName + "' tensor."; return errorMsg; } } // anonymous namespace bool RefLayerSupport::IsAbsSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { return IsElementwiseUnarySupported(input, output, ElementwiseUnaryDescriptor(UnaryOperation::Abs), reasonIfUnsupported); } bool RefLayerSupport::IsActivationSupported(const TensorInfo& input, const TensorInfo& output, const ActivationDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; // Define supported types. std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference activation: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference activation: output type not supported."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference activation: input and output types mismatched."); supported &= CheckSupportRule(ShapesAreSameRank(input, output), reasonIfUnsupported, "Reference activation: input and output shapes are of different rank."); struct ActivationFunctionSupported : public Rule { ActivationFunctionSupported(const ActivationDescriptor& desc) { switch(desc.m_Function) { case ActivationFunction::Abs: case ActivationFunction::BoundedReLu: case ActivationFunction::Elu: case ActivationFunction::HardSwish: case ActivationFunction::LeakyReLu: case ActivationFunction::Linear: case ActivationFunction::ReLu: case ActivationFunction::Sigmoid: case ActivationFunction::SoftReLu: case ActivationFunction::Sqrt: case ActivationFunction::Square: case ActivationFunction::TanH: { m_Res = true; break; } default: { m_Res = false; break; } } } }; // Function is supported supported &= CheckSupportRule(ActivationFunctionSupported(descriptor), reasonIfUnsupported, "Reference activation: function not supported."); return supported; } bool RefLayerSupport::IsAdditionSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(input0, supportedTypes), reasonIfUnsupported, "Reference addition: input 0 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(input1, supportedTypes), reasonIfUnsupported, "Reference addition: input 1 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference addition: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input0, input1), reasonIfUnsupported, "Reference addition: input 0 and Input 1 types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input0, output), reasonIfUnsupported, "Reference addition: input and output types are mismatched"); supported &= CheckSupportRule(ShapesAreBroadcastCompatible(input0, input1, output), reasonIfUnsupported, "Reference addition: shapes are not suitable for implicit broadcast."); return supported; } bool RefLayerSupport::IsArgMinMaxSupported(const armnn::TensorInfo &input, const armnn::TensorInfo &output, const armnn::ArgMinMaxDescriptor &descriptor, armnn::Optional<std::string &> reasonIfUnsupported) const { IgnoreUnused(descriptor); std::array<DataType, 7> supportedTypes = { DataType::BFloat16, DataType::Float16, DataType::Float32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference ArgMinMax: input is not a supported type."); supported &= CheckSupportRule(TypeIs(output, DataType::Signed32), reasonIfUnsupported, "Reference ArgMinMax: output type not supported"); return supported; } bool RefLayerSupport::IsBatchNormalizationSupported(const TensorInfo& input, const TensorInfo& output, const TensorInfo& mean, const TensorInfo& variance, const TensorInfo& beta, const TensorInfo& gamma, const BatchNormalizationDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); std::array<DataType, 6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference batch normalization: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference batch normalization: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference batch normalization: input and output types are mismatched"); supported &= CheckSupportRule(TypeAnyOf(mean, supportedTypes), reasonIfUnsupported, "Reference batch normalization: mean is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(variance, supportedTypes), reasonIfUnsupported, "Reference batch normalization: variance is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(beta, supportedTypes), reasonIfUnsupported, "Reference batch normalization: beta is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(gamma, supportedTypes), reasonIfUnsupported, "Reference batch normalization: gamma is not a supported type."); return supported; } bool RefLayerSupport::IsBatchToSpaceNdSupported(const TensorInfo& input, const TensorInfo& output, const BatchToSpaceNdDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::string batchToSpaceNdLayerStr = "batchToSpaceNd"; std::string inputTensorStr = "input"; std::string outputTensorStr = "output"; // Define supported types. std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference BatchToSpaceNd: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference BatchToSpaceNd: output type not supported."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference BatchToSpaceNd: input and output types mismatched."); supported &= CheckSupportRule(TensorNumDimensionsAreCorrect(output, 4), reasonIfUnsupported, CreateIncorrectDimensionsErrorMsg(4, output.GetNumDimensions(), batchToSpaceNdLayerStr, outputTensorStr).data()); supported &= CheckSupportRule(TensorNumDimensionsAreCorrect(input, 4), reasonIfUnsupported, CreateIncorrectDimensionsErrorMsg(4, input.GetNumDimensions(), batchToSpaceNdLayerStr, inputTensorStr).data()); return supported; } bool RefLayerSupport::IsComparisonSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, const ComparisonDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); std::array<DataType, 8> supportedInputTypes = { DataType::Boolean, DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input0, supportedInputTypes), reasonIfUnsupported, "Reference comparison: input 0 is not a supported type"); supported &= CheckSupportRule(TypesAreEqual(input0, input1), reasonIfUnsupported, "Reference comparison: input 0 and Input 1 types are mismatched"); supported &= CheckSupportRule(TypeIs(output, DataType::Boolean), reasonIfUnsupported, "Reference comparison: output is not of type Boolean"); return supported; } bool RefLayerSupport::IsConcatSupported(const std::vector<const TensorInfo*> inputs, const TensorInfo& output, const ConcatDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference concatenation: output type not supported"); for (const TensorInfo* input : inputs) { ARMNN_ASSERT(input != nullptr); supported &= CheckSupportRule(TypeAnyOf(*input, supportedTypes), reasonIfUnsupported, "Reference concatenation: input type not supported"); supported &= CheckSupportRule(TypesAreEqual(*input, output), reasonIfUnsupported, "Reference concatenation: input and output types mismatched."); } return supported; } bool RefLayerSupport::IsConstantSupported(const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { std::array<DataType,8> supportedTypes = { DataType::BFloat16, DataType::Float16, DataType::Float32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16, DataType::Signed32 }; return CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference constant: output is not a supported type."); } bool RefLayerSupport::IsConvertBf16ToFp32Supported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; supported &= CheckSupportRule(TypeIs(input, DataType::BFloat16), reasonIfUnsupported, "Reference for ConvertBf16ToFp32 layer: input type not supported"); supported &= CheckSupportRule(TypeIs(output, DataType::Float32), reasonIfUnsupported, "Reference for ConvertBf16ToFp32 layer: output type not supported"); return supported; } bool RefLayerSupport::IsConvertFp16ToFp32Supported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { return (IsSupportedForDataTypeGeneric(reasonIfUnsupported, input.GetDataType(), &TrueFunc<>, &FalseInputFuncF32<>, &FalseFuncU8<>, &FalseFuncI32<>, &FalseFuncU8<>) && IsSupportedForDataTypeGeneric(reasonIfUnsupported, output.GetDataType(), &FalseOutputFuncF16<>, &TrueFunc<>, &FalseFuncU8<>, &FalseFuncI32<>, &FalseFuncU8<>)); } bool RefLayerSupport::IsConvertFp32ToBf16Supported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; supported &= CheckSupportRule(TypeIs(input, DataType::Float32), reasonIfUnsupported, "Reference for ConvertFp32ToBf16 layer: input type not supported"); supported &= CheckSupportRule(TypeIs(output, DataType::BFloat16), reasonIfUnsupported, "Reference for ConvertFp32ToBf16 layer: output type not supported"); return supported; } bool RefLayerSupport::IsConvertFp32ToFp16Supported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { return (IsSupportedForDataTypeGeneric(reasonIfUnsupported, input.GetDataType(), &FalseInputFuncF16<>, &TrueFunc<>, &FalseFuncU8<>, &FalseFuncI32<>, &FalseFuncU8<>) && IsSupportedForDataTypeGeneric(reasonIfUnsupported, output.GetDataType(), &TrueFunc<>, &FalseOutputFuncF32<>, &FalseFuncU8<>, &FalseFuncI32<>, &FalseFuncU8<>)); } bool RefLayerSupport::IsConvolution2dSupported(const TensorInfo& input, const TensorInfo& output, const Convolution2dDescriptor& descriptor, const TensorInfo& weights, const Optional<TensorInfo>& biases, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; // Define supported types. std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Convolution2d: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Convolution2d: output is not a supported type."); // For Convolution2d, we allow to have BFloat16 input with Float32 output for optimization. if (input.GetDataType() == DataType::BFloat16) { if (output.GetDataType() != DataType::BFloat16 && output.GetDataType() != DataType::Float32) { reasonIfUnsupported.value() += "Output tensor type must be BFloat16 or Float32 for BFloat16 input.\n"; supported = false; } } else { supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Convolution2d: input and output types mismatched."); } const DataType inputType = input.GetDataType(); if (IsQuantized8BitType(inputType)) { ARMNN_NO_DEPRECATE_WARN_BEGIN std::array<DataType, 4> supportedWeightTypes = { DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QuantizedSymm8PerAxis // deprecated }; ARMNN_NO_DEPRECATE_WARN_END supported &= CheckSupportRule(TypeAnyOf(weights, supportedWeightTypes), reasonIfUnsupported, "Reference Convolution2d: weights type not supported for quantized input."); } else { supported &= CheckSupportRule(TypeAnyOf(weights, supportedTypes), reasonIfUnsupported, "Reference Convolution2d: weights is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, weights), reasonIfUnsupported, "Reference Convolution2d: input and weights types mismatched."); } if (biases.has_value()) { std::array<DataType,4> biasesSupportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(biases.value(), biasesSupportedTypes), reasonIfUnsupported, "Reference Convolution2d: biases is not a supported type."); } IgnoreUnused(descriptor); return supported; } bool RefLayerSupport::IsDebugSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType, 8> supportedTypes = { DataType::BFloat16, DataType::Float16, DataType::Float32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference for Debug layer: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference for Debug layer: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference for Debug layer: input and output types are mismatched"); return supported; } bool RefLayerSupport::IsDepthToSpaceSupported(const TensorInfo& input, const TensorInfo& output, const DepthToSpaceDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference DepthToSpace: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference DepthToSpace: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference DepthToSpace: input and output types are mismatched"); return supported; } bool RefLayerSupport::IsDepthwiseConvolutionSupported(const TensorInfo& input, const TensorInfo& output, const DepthwiseConvolution2dDescriptor& descriptor, const TensorInfo& weights, const Optional<TensorInfo>& biases, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; // Define supported types. std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference DepthwiseConvolution2d: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference DepthwiseConvolution2d: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference DepthwiseConvolution2d: input and output types mismatched."); const DataType inputType = input.GetDataType(); if (IsQuantized8BitType(inputType)) { ARMNN_NO_DEPRECATE_WARN_BEGIN std::array<DataType, 4> supportedWeightTypes = { DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QuantizedSymm8PerAxis // deprecated }; ARMNN_NO_DEPRECATE_WARN_END supported &= CheckSupportRule(TypeAnyOf(weights, supportedWeightTypes), reasonIfUnsupported, "Reference DepthwiseConvolution2d: weights type not supported for " "quantized input."); } else { supported &= CheckSupportRule(TypeAnyOf(weights, supportedTypes), reasonIfUnsupported, "Reference DepthwiseConvolution2d: weights is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, weights), reasonIfUnsupported, "Reference DepthwiseConvolution2d: input and weights types mismatched."); } if (biases.has_value()) { std::array<DataType,4> biasesSupportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(biases.value(), biasesSupportedTypes), reasonIfUnsupported, "Reference DepthwiseConvolution2d: biases is not a supported type."); } return supported; } bool RefLayerSupport::IsDequantizeSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,4> supportedInputTypes = { DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedInputTypes), reasonIfUnsupported, "Reference for Dequantize layer: input type not supported."); supported &= CheckSupportRule( TypeNotPerAxisQuantized(input), reasonIfUnsupported, "Reference for Dequantize layer: per-axis quantized input not support ."); supported &= CheckSupportRule(TypeNotPerAxisQuantized(input), reasonIfUnsupported, "Reference dequantize: per-axis quantized input not support ."); std::array<DataType,3> supportedOutputTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16 }; supported &= CheckSupportRule(TypeAnyOf(output, supportedOutputTypes), reasonIfUnsupported, "Reference for Dequantize layer: output type not supported."); supported &= CheckSupportRule(ShapesAreSameTotalSize(input, output), reasonIfUnsupported, "Reference for Dequantize layer: input/output shapes have different num total " "elements."); return supported; } bool RefLayerSupport::IsDetectionPostProcessSupported(const TensorInfo& boxEncodings, const TensorInfo& scores, const TensorInfo& anchors, const TensorInfo& detectionBoxes, const TensorInfo& detectionClasses, const TensorInfo& detectionScores, const TensorInfo& numDetections, const DetectionPostProcessDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(anchors, detectionBoxes, detectionClasses, detectionScores, numDetections, descriptor); bool supported = true; std::array<DataType,5> supportedInputTypes = { DataType::BFloat16, DataType::Float32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(boxEncodings, supportedInputTypes), reasonIfUnsupported, "Reference DetectionPostProcess: input 0 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(scores, supportedInputTypes), reasonIfUnsupported, "Reference DetectionPostProcess: input 1 is not a supported type."); return supported; } bool RefLayerSupport::IsDilatedDepthwiseConvolutionSupported(const TensorInfo& input, const TensorInfo& output, const DepthwiseConvolution2dDescriptor& descriptor, const TensorInfo& weights, const Optional<TensorInfo>& biases, Optional<std::string&> reasonIfUnsupported) const { return IsDepthwiseConvolutionSupported(input, output, descriptor, weights, biases, reasonIfUnsupported); } bool RefLayerSupport::IsDivisionSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(input0, supportedTypes), reasonIfUnsupported, "Reference division: input 0 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(input1, supportedTypes), reasonIfUnsupported, "Reference division: input 1 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference division: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input0, input1), reasonIfUnsupported, "Reference division: input 0 and Input 1 types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input0, output), reasonIfUnsupported, "Reference division: input and output types are mismatched"); supported &= CheckSupportRule(ShapesAreBroadcastCompatible(input0, input1, output), reasonIfUnsupported, "Reference division: shapes are not suitable for implicit broadcast."); return supported; } bool RefLayerSupport::IsElementwiseUnarySupported(const TensorInfo& input, const TensorInfo& output, const ElementwiseUnaryDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); std::array<DataType, 7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference elementwise unary: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference elementwise unary: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference elementwise unary: input and output types not matching"); supported &= CheckSupportRule(ShapesAreSameTotalSize(input, output), reasonIfUnsupported, "Reference elementwise unary: input and output shapes" "have different number of total elements"); return supported; } bool RefLayerSupport::IsEqualSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { return IsComparisonSupported(input0, input1, output, ComparisonDescriptor(ComparisonOperation::Equal), reasonIfUnsupported); } bool RefLayerSupport::IsFakeQuantizationSupported(const TensorInfo& input, const FakeQuantizationDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,1> supportedTypes = { DataType::Float32 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference fake quantization: input type not supported."); return supported; } bool RefLayerSupport::IsFillSupported(const TensorInfo& input, const TensorInfo& output, const FillDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); IgnoreUnused(output); bool supported = true; std::array<DataType,3> supportedTypes = { DataType::Float32, DataType::Float16, DataType::Signed32 }; supported &= CheckSupportRule(TypeIs(input, DataType::Signed32), reasonIfUnsupported, "Reference Fill: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Fill: output type not supported."); return supported; } bool RefLayerSupport::IsFloorSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(output); bool supported = true; std::array<DataType,3> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Floor: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Floor: output type not supported."); return supported; } bool RefLayerSupport::IsFullyConnectedSupported(const TensorInfo& input, const TensorInfo& output, const TensorInfo& weights, const TensorInfo& biases, const FullyConnectedDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; // Define supported types. std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Fully Connected: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Fully Connected: output type not supported."); supported &= CheckSupportRule(TypeAnyOf(weights, supportedTypes), reasonIfUnsupported, "Reference Fully Connected: weights type not supported."); // For FullyConnected, we allow to have BFloat16 input with Float32 output for optimization. if (input.GetDataType() == DataType::BFloat16) { if (output.GetDataType() != DataType::BFloat16 && output.GetDataType() != DataType::Float32) { reasonIfUnsupported.value() += "Output tensor type must be BFloat16 or Float32 for BFloat16 input.\n"; supported = false; } } else { supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Fully Connected: input and output types mismatched."); } supported &= CheckSupportRule(TypeAnyOf(weights, supportedTypes), reasonIfUnsupported, "Reference Fully Connected: weights is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, weights), reasonIfUnsupported, "Reference Fully Connected: input and weights types mismatched."); if (descriptor.m_BiasEnabled) { // Defined supported types for bias std::array<DataType, 5> supportedBiasTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::Signed32, DataType::QAsymmS8 }; supported &= CheckSupportRule(TypeAnyOf(biases, supportedBiasTypes), reasonIfUnsupported, "Reference Fully Connected: bias type not supported."); supported &= CheckSupportRule(BiasAndWeightsTypesMatch(biases, weights), reasonIfUnsupported, "Reference Fully Connected: bias and weight types mismatch."); supported &= CheckSupportRule(BiasAndWeightsTypesCompatible(weights, supportedBiasTypes), reasonIfUnsupported, "Reference Fully Connected: bias type inferred from weights is incompatible."); supported &= CheckSupportRule(TensorNumDimensionsAreCorrect(biases, 1U), reasonIfUnsupported, "Reference Fully Connected: bias must have 1 dimension."); } return supported; } bool RefLayerSupport::IsGatherSupported(const armnn::TensorInfo& input0, const armnn::TensorInfo& input1, const armnn::TensorInfo& output, const GatherDescriptor& descriptor, armnn::Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; if (descriptor.m_Axis != 0) { reasonIfUnsupported.value() += std::string("Reference Gather: axis not supported\n"); supported &= false; } supported &= CheckSupportRule(TypeAnyOf(input0, supportedTypes), reasonIfUnsupported, "Reference Gather: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Gather: output type not supported"); supported &= CheckSupportRule(TypeIs(input1, DataType::Signed32), reasonIfUnsupported, "Reference Gather: indices (input1) type not supported"); supported &= CheckSupportRule(TypesAreEqual(input0, output), reasonIfUnsupported, "Reference Gather: input and output types not matching"); return supported; } bool RefLayerSupport::IsGreaterSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { return IsComparisonSupported(input0, input1, output, ComparisonDescriptor(ComparisonOperation::Greater), reasonIfUnsupported); } bool RefLayerSupport::IsInputSupported(const TensorInfo& /*input*/, Optional<std::string&> /*reasonIfUnsupported*/) const { return true; } bool RefLayerSupport::IsInstanceNormalizationSupported(const TensorInfo& input, const TensorInfo& output, const InstanceNormalizationDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); // Define supported types std::array<DataType, 3> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Instance Normalization: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Instance Normalization: output type not supported."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Instance Normalization: input and output types mismatched."); supported &= CheckSupportRule(ShapesAreSameTotalSize(input, output), reasonIfUnsupported, "Reference Instance Normalization: input and output shapes have different " "num total elements."); return supported; } bool RefLayerSupport::IsL2NormalizationSupported(const TensorInfo& input, const TensorInfo& output, const L2NormalizationDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); // Define supported types std::array<DataType, 6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference L2normalization: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference L2normalization: output type not supported."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference L2normalization: input and output types mismatched."); supported &= CheckSupportRule(ShapesAreSameTotalSize(input, output), reasonIfUnsupported, "Reference L2normalization: input and output shapes have different " "num total elements."); return supported; } bool RefLayerSupport::IsLogSoftmaxSupported(const TensorInfo& input, const TensorInfo& output, const LogSoftmaxDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); std::array<DataType, 3> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference LogSoftmax: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference LogSoftmax: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference LogSoftmax: input and output types do not match"); return supported; } bool RefLayerSupport::IsLstmSupported(const TensorInfo& input, const TensorInfo& outputStateIn, const TensorInfo& cellStateIn, const TensorInfo& scratchBuffer, const TensorInfo& outputStateOut, const TensorInfo& cellStateOut, const TensorInfo& output, const LstmDescriptor& descriptor, const LstmInputParamsInfo& paramsInfo, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); IgnoreUnused(paramsInfo); bool supported = true; std::array<DataType,3> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::QSymmS16 }; // check inputs and outputs supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Lstm: input is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, outputStateIn), reasonIfUnsupported, "Reference Lstm: input and outputStateIn types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, cellStateIn), reasonIfUnsupported, "Reference Lstm: input and cellStateIn types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, scratchBuffer), reasonIfUnsupported, "Reference Lstm: input and scratchBuffer types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, outputStateOut), reasonIfUnsupported, "Reference Lstm: input and outputStateOut types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, cellStateOut), reasonIfUnsupported, "Reference Lstm: input and cellStateOut types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Lstm: input and output types are mismatched"); // check layer parameters supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetInputToForgetWeights()), reasonIfUnsupported, "Reference Lstm: input and InputToForgetWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetInputToCellWeights()), reasonIfUnsupported, "Reference Lstm: input and InputToCellWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetInputToOutputWeights()), reasonIfUnsupported, "Reference Lstm: input and InputToOutputWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetRecurrentToForgetWeights()), reasonIfUnsupported, "Reference Lstm: input and RecurrentToForgetWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetRecurrentToCellWeights()), reasonIfUnsupported, "Reference Lstm: input and RecurrentToCellWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetRecurrentToOutputWeights()), reasonIfUnsupported, "Reference Lstm: input and RecurrentToOutputWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetForgetGateBias()), reasonIfUnsupported, "Reference Lstm: input and ForgetGateBias types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetCellBias()), reasonIfUnsupported, "Reference Lstm: input and CellBias types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetOutputGateBias()), reasonIfUnsupported, "Reference Lstm: input and OutputGateBias types are mismatched"); if (!descriptor.m_CifgEnabled) { supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetInputToInputWeights()), reasonIfUnsupported, "Reference Lstm: input and InputToInputWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetRecurrentToInputWeights()), reasonIfUnsupported, "Reference Lstm: input and RecurrentToInputWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetInputGateBias()), reasonIfUnsupported, "Reference Lstm: input and InputGateBias types are mismatched"); if (descriptor.m_PeepholeEnabled) { supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetCellToInputWeights()), reasonIfUnsupported, "Reference Lstm: input and CellToInputWeights types are mismatched"); } } if (descriptor.m_PeepholeEnabled) { supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetCellToForgetWeights()), reasonIfUnsupported, "Reference Lstm: input and CellToForgetWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetCellToOutputWeights()), reasonIfUnsupported, "Reference Lstm: input and CellToOutputWeights types are mismatched"); } if (descriptor.m_ProjectionEnabled) { supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetProjectionWeights()), reasonIfUnsupported, "Reference Lstm: input and mProjectionWeights types are mismatched"); if (paramsInfo.m_ProjectionBias != nullptr) { supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetProjectionBias()), reasonIfUnsupported, "Reference Lstm: input and ProjectionBias types are mismatched"); } } if (descriptor.m_LayerNormEnabled) { if (!descriptor.m_CifgEnabled) { supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetInputLayerNormWeights()), reasonIfUnsupported, "Reference Lstm: input and InputLayerNormWeights types are mismatched"); } supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetForgetLayerNormWeights()), reasonIfUnsupported, "Reference Lstm: input and ForgetLayerNormWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetCellLayerNormWeights()), reasonIfUnsupported, "Reference Lstm: input and CellLayerNormWeights types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input, paramsInfo.GetOutputLayerNormWeights()), reasonIfUnsupported, "Reference Lstm: input and OutputLayerNormWeights types are mismatched"); } return supported; } bool RefLayerSupport::IsMaximumSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(input0, supportedTypes), reasonIfUnsupported, "Reference maximum: input 0 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(input1, supportedTypes), reasonIfUnsupported, "Reference maximum: input 1 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference maximum: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input0, input1), reasonIfUnsupported, "Reference maximum: input 0 and Input 1 types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input0, output), reasonIfUnsupported, "Reference maximum: input and output types are mismatched"); supported &= CheckSupportRule(ShapesAreBroadcastCompatible(input0, input1, output), reasonIfUnsupported, "Reference maximum: shapes are not suitable for implicit broadcast."); return supported; } bool RefLayerSupport::IsMeanSupported(const TensorInfo& input, const TensorInfo& output, const MeanDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::string meanLayerStr = "Mean"; std::string outputTensorStr = "output"; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Mean: input type not supported."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Mean: input and output types are mismatched"); if (descriptor.m_KeepDims) { supported &= CheckSupportRule(TensorNumDimensionsAreCorrect(output, input.GetNumDimensions()), reasonIfUnsupported, CreateIncorrectDimensionsErrorMsg(input.GetNumDimensions(), output.GetNumDimensions(), meanLayerStr, outputTensorStr).data()); } else if (descriptor.m_Axis.empty()) { supported &= CheckSupportRule(TensorNumDimensionsAreCorrect(output, 1), reasonIfUnsupported, CreateIncorrectDimensionsErrorMsg(1, output.GetNumDimensions(), meanLayerStr, outputTensorStr).data()); } else { auto outputDim = input.GetNumDimensions() - boost::numeric_cast<unsigned int>(descriptor.m_Axis.size()); if (outputDim > 0) { supported &= CheckSupportRule(TensorNumDimensionsAreCorrect(output, outputDim), reasonIfUnsupported, CreateIncorrectDimensionsErrorMsg(outputDim, output.GetNumDimensions(), meanLayerStr, outputTensorStr).data()); } else { supported &= CheckSupportRule(TensorNumDimensionsAreCorrect(output, 1), reasonIfUnsupported, CreateIncorrectDimensionsErrorMsg(1, output.GetNumDimensions(), meanLayerStr, outputTensorStr).data()); } } return supported; } bool RefLayerSupport::IsMergerSupported(const std::vector<const TensorInfo*> inputs, const TensorInfo& output, const MergerDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { return IsConcatSupported(inputs, output, descriptor, reasonIfUnsupported); } bool RefLayerSupport::IsMemCopySupported(const TensorInfo &input, const TensorInfo &output, Optional<std::string &> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Boolean }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference MemCopy: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference MemCopy: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference MemCopy: input and output types are mismatched"); return supported; } bool RefLayerSupport::IsMinimumSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(input0, supportedTypes), reasonIfUnsupported, "Reference minimum: input 0 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(input1, supportedTypes), reasonIfUnsupported, "Reference minimum: input 1 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference minimum: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input0, input1), reasonIfUnsupported, "Reference minimum: input 0 and Input 1 types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input0, output), reasonIfUnsupported, "Reference minimum: input and output types are mismatched"); supported &= CheckSupportRule(ShapesAreBroadcastCompatible(input0, input1, output), reasonIfUnsupported, "Reference minimum: shapes are not suitable for implicit broadcast."); return supported; } bool RefLayerSupport::IsMultiplicationSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(input0, supportedTypes), reasonIfUnsupported, "Reference multiplication: input 0 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(input1, supportedTypes), reasonIfUnsupported, "Reference multiplication: input 1 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference multiplication: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input0, input1), reasonIfUnsupported, "Reference multiplication: input 0 and Input 1 types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input0, output), reasonIfUnsupported, "Reference multiplication: input and output types are mismatched"); supported &= CheckSupportRule(ShapesAreBroadcastCompatible(input0, input1, output), reasonIfUnsupported, "Reference multiplication: shapes are not suitable for implicit broadcast."); return supported; } bool RefLayerSupport::IsNormalizationSupported(const TensorInfo& input, const TensorInfo& output, const NormalizationDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); // Define supported types std::array<DataType, 6> supportedTypes = { DataType::BFloat16, DataType::Float16, DataType::Float32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; bool supported = true; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference normalization: input type not supported."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference normalization: output type not supported."); supported &= CheckSupportRule(ShapesAreSameTotalSize(input, output), reasonIfUnsupported, "Reference normalization: input and output shapes have different " "num total elements."); return supported; } bool RefLayerSupport::IsOutputSupported(const TensorInfo& /*output*/, Optional<std::string&> /*reasonIfUnsupported*/) const { return true; } bool RefLayerSupport::IsPadSupported(const TensorInfo& input, const TensorInfo& output, const PadDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; // Define supported output and inputs types. std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference pad: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference pad: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference pad: input and output types are mismatched."); return supported; } bool RefLayerSupport::IsPermuteSupported(const TensorInfo& input, const TensorInfo& output, const PermuteDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; // Define supported output and inputs types. std::array<DataType, 6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference permute: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference permute: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference permute: input and output types are mismatched."); return supported; } bool RefLayerSupport::IsPooling2dSupported(const TensorInfo& input, const TensorInfo& output, const Pooling2dDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; // Define supported output and inputs types. std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference poolind2d: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference poolind2d: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference poolind2d: input and output types are mismatched."); return supported; } bool RefLayerSupport::IsQLstmSupported(const TensorInfo& input, const TensorInfo& previousOutputIn, const TensorInfo& previousCellStateIn, const TensorInfo& outputStateOut, const TensorInfo& cellStateOut, const TensorInfo& output, const QLstmDescriptor& descriptor, const LstmInputParamsInfo& paramsInfo, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(input); IgnoreUnused(previousOutputIn); IgnoreUnused(previousCellStateIn); IgnoreUnused(outputStateOut); IgnoreUnused(cellStateOut); IgnoreUnused(output); IgnoreUnused(descriptor); IgnoreUnused(paramsInfo); IgnoreUnused(reasonIfUnsupported); return true; } bool RefLayerSupport::IsQuantizeSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; // Define supported input types. std::array<DataType,7> supportedInputTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedInputTypes), reasonIfUnsupported, "Reference quantize: input type not supported."); // Define supported output types. std::array<DataType,4> supportedOutputTypes = { DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(output, supportedOutputTypes), reasonIfUnsupported, "Reference quantize: output type not supported."); supported &= CheckSupportRule(ShapesAreSameTotalSize(input, output), reasonIfUnsupported, "Reference quantize: input and output shapes have different num total elements."); return supported; } bool RefLayerSupport::IsRankSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(input); // Define supported output types. std::array<DataType,1> supportedOutputTypes = { DataType::Signed32, }; return CheckSupportRule(TypeAnyOf(output, supportedOutputTypes), reasonIfUnsupported, "Reference rank: input type not supported."); } bool RefLayerSupport::IsReshapeSupported(const TensorInfo& input, const TensorInfo& output, const ReshapeDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(output); IgnoreUnused(descriptor); // Define supported output types. std::array<DataType,7> supportedOutputTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::Signed32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; return CheckSupportRule(TypeAnyOf(input, supportedOutputTypes), reasonIfUnsupported, "Reference reshape: input type not supported."); } bool RefLayerSupport::IsResizeBilinearSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference ResizeBilinear: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference ResizeBilinear: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference ResizeBilinear: input and output types not matching"); return supported; } bool RefLayerSupport::IsResizeSupported(const TensorInfo& input, const TensorInfo& output, const ResizeDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Resize: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Resize: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Resize: input and output types not matching"); return supported; } bool RefLayerSupport::IsRsqrtSupported(const TensorInfo& input, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { return IsElementwiseUnarySupported(input, output, ElementwiseUnaryDescriptor(UnaryOperation::Rsqrt), reasonIfUnsupported); } bool RefLayerSupport::IsSliceSupported(const TensorInfo& input, const TensorInfo& output, const SliceDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType, 5> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Slice: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Slice: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Slice: input and output types are mismatched"); return supported; } bool RefLayerSupport::IsSoftmaxSupported(const TensorInfo& input, const TensorInfo& output, const SoftmaxDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QSymmS8, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference Softmax: output type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference Softmax: input type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference Softmax: input type not supported"); return supported; } bool RefLayerSupport::IsSpaceToBatchNdSupported(const TensorInfo& input, const TensorInfo& output, const SpaceToBatchNdDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference SpaceToBatchNd: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference SpaceToBatchNd: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference SpaceToBatchNd: input and output types are mismatched"); return supported; } bool RefLayerSupport::IsSpaceToDepthSupported(const TensorInfo& input, const TensorInfo& output, const SpaceToDepthDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference SpaceToDepth: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference SpaceToDepth: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference SpaceToDepth: input and output types are mismatched"); return supported; } bool RefLayerSupport::IsSplitterSupported(const TensorInfo& input, const ViewsDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference splitter: input type not supported"); return supported; } bool RefLayerSupport::IsSplitterSupported(const TensorInfo& input, const std::vector<std::reference_wrapper<TensorInfo>>& outputs, const ViewsDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference splitter: output type not supported"); for (const TensorInfo output : outputs) { supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference splitter: input type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference splitter: input and output types mismatched."); } return supported; } bool RefLayerSupport::IsStackSupported(const std::vector<const TensorInfo*>& inputs, const TensorInfo& output, const StackDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference stack: output type not supported"); for (const TensorInfo* input : inputs) { ARMNN_ASSERT(input != nullptr); supported &= CheckSupportRule(TypeAnyOf(*input, supportedTypes), reasonIfUnsupported, "Reference stack: input type not supported"); supported &= CheckSupportRule(TypesAreEqual(*input, output), reasonIfUnsupported, "Reference stack: input and output types mismatched."); } return supported; } bool RefLayerSupport::IsStridedSliceSupported(const TensorInfo& input, const TensorInfo& output, const StridedSliceDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,5> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference StridedSlice: input type not supported"); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference StridedSlice: output type not supported"); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference StridedSlice: input and output types are mismatched"); return supported; } bool RefLayerSupport::IsSubtractionSupported(const TensorInfo& input0, const TensorInfo& input1, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(input0, supportedTypes), reasonIfUnsupported, "Reference subtraction: input 0 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(input1, supportedTypes), reasonIfUnsupported, "Reference subtraction: input 1 is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference subtraction: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input0, input1), reasonIfUnsupported, "Reference subtraction: input 0 and Input 1 types are mismatched"); supported &= CheckSupportRule(TypesAreEqual(input0, output), reasonIfUnsupported, "Reference subtraction: input and output types are mismatched"); supported &= CheckSupportRule(ShapesAreBroadcastCompatible(input0, input1, output), reasonIfUnsupported, "Reference subtraction: shapes are not suitable for implicit broadcast."); return supported; } bool RefLayerSupport::IsPreluSupported(const TensorInfo& input, const TensorInfo& alpha, const TensorInfo& output, Optional<std::string&> reasonIfUnsupported) const { bool supported = true; std::array<DataType, 6> supportedTypes { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "PReLU: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(alpha, supportedTypes), reasonIfUnsupported, "PReLU: alpha is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "PReLU: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, alpha, output), reasonIfUnsupported, "PReLU: input, alpha and output types are mismatched"); supported &= CheckSupportRule(ShapesAreBroadcastCompatible(input, alpha, output), reasonIfUnsupported, "PReLU: shapes are not suitable for implicit broadcast"); return supported; } bool RefLayerSupport::IsTransposeConvolution2dSupported(const TensorInfo& input, const TensorInfo& output, const TransposeConvolution2dDescriptor& descriptor, const TensorInfo& weights, const Optional<TensorInfo>& biases, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; std::array<DataType,7> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference TransposeConvolution2d: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference TransposeConvolution2d: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference TransposeConvolution2d: input and output types mismatched."); const DataType inputType = input.GetDataType(); if (IsQuantized8BitType(inputType)) { ARMNN_NO_DEPRECATE_WARN_BEGIN std::array<DataType, 4> supportedWeightTypes = { DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS8, DataType::QuantizedSymm8PerAxis //Deprecated }; ARMNN_NO_DEPRECATE_WARN_END supported &= CheckSupportRule(TypeAnyOf(weights, supportedWeightTypes), reasonIfUnsupported, "Reference TransposeConvolution2d: weights type not supported for " "quantized input."); } else { supported &= CheckSupportRule(TypeAnyOf(weights, supportedTypes), reasonIfUnsupported, "Reference TransposeConvolution2d: weights is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, weights), reasonIfUnsupported, "Reference TransposeConvolution2d: input and weights types mismatched."); } if (biases.has_value()) { std::array<DataType,4> biasesSupportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::Signed32 }; supported &= CheckSupportRule(TypeAnyOf(biases.value(), biasesSupportedTypes), reasonIfUnsupported, "Reference TransposeConvolution2d: biases is not a supported type."); } return supported; } bool RefLayerSupport::IsTransposeSupported(const TensorInfo& input, const TensorInfo& output, const TransposeDescriptor& descriptor, Optional<std::string&> reasonIfUnsupported) const { IgnoreUnused(descriptor); bool supported = true; // Define supported output and inputs types. std::array<DataType, 6> supportedTypes = { DataType::BFloat16, DataType::Float32, DataType::Float16, DataType::QAsymmS8, DataType::QAsymmU8, DataType::QSymmS16 }; supported &= CheckSupportRule(TypeAnyOf(input, supportedTypes), reasonIfUnsupported, "Reference transpose: input is not a supported type."); supported &= CheckSupportRule(TypeAnyOf(output, supportedTypes), reasonIfUnsupported, "Reference transpose: output is not a supported type."); supported &= CheckSupportRule(TypesAreEqual(input, output), reasonIfUnsupported, "Reference transpose: input and output types are mismatched."); return supported; } } // namespace armnn
42.608936
119
0.574181
[ "vector" ]
f6c3c45f41d4874fdc08da679d038c60b7436a0a
32,224
cpp
C++
WhateverGreen/kern_weg.cpp
bayunr07/WhateverGreen
65fc4965c009b187bd0a7c5f83a72a2d52f6f50f
[ "BSD-3-Clause" ]
null
null
null
WhateverGreen/kern_weg.cpp
bayunr07/WhateverGreen
65fc4965c009b187bd0a7c5f83a72a2d52f6f50f
[ "BSD-3-Clause" ]
null
null
null
WhateverGreen/kern_weg.cpp
bayunr07/WhateverGreen
65fc4965c009b187bd0a7c5f83a72a2d52f6f50f
[ "BSD-3-Clause" ]
null
null
null
// // kern_weg.cpp // WhateverGreen // // Copyright © 2018 vit9696. All rights reserved. // #include <Headers/kern_api.hpp> #include <Headers/kern_devinfo.hpp> #include <Headers/kern_iokit.hpp> #include <Headers/kern_cpu.hpp> #include "kern_weg.hpp" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winconsistent-missing-override" #include <IOKit/graphics/IOFramebuffer.h> #pragma clang diagnostic pop // This is a hack to let us access protected properties. struct FramebufferViewer : public IOFramebuffer { static IOMemoryMap *&getVramMap(IOFramebuffer *fb) { // This is a hack to fix old Xcode compilation. #ifdef __MAC_10_13 return static_cast<FramebufferViewer *>(fb)->fVramMap; #else return static_cast<FramebufferViewer *>(fb)->vramMap; #endif } }; static const char *pathIOGraphics[] { "/System/Library/Extensions/IOGraphicsFamily.kext/IOGraphicsFamily" }; static const char *pathAGDPolicy[] { "/System/Library/Extensions/AppleGraphicsControl.kext/Contents/PlugIns/AppleGraphicsDevicePolicy.kext/Contents/MacOS/AppleGraphicsDevicePolicy" }; static const char *pathBacklight[] { "/System/Library/Extensions/AppleBacklight.kext/Contents/MacOS/AppleBacklight" }; static KernelPatcher::KextInfo kextIOGraphics { "com.apple.iokit.IOGraphicsFamily", pathIOGraphics, arrsize(pathIOGraphics), {true}, {}, KernelPatcher::KextInfo::Unloaded }; static KernelPatcher::KextInfo kextAGDPolicy { "com.apple.driver.AppleGraphicsDevicePolicy", pathAGDPolicy, arrsize(pathAGDPolicy), {true}, {}, KernelPatcher::KextInfo::Unloaded }; // Note: initially marked as reloadable, but I doubt it needs to be. static KernelPatcher::KextInfo kextBacklight { "com.apple.driver.AppleBacklight", pathBacklight, arrsize(pathBacklight), {true}, {}, KernelPatcher::KextInfo::Unloaded }; WEG::ApplePanelData WEG::appleBacklightData[] { { "F14Txxxx", { 0x00, 0x11, 0x00, 0x00, 0x00, 0x34, 0x00, 0x52, 0x00, 0x73, 0x00, 0x94, 0x00, 0xBE, 0x00, 0xFA, 0x01, 0x36, 0x01, 0x72, 0x01, 0xC5, 0x02, 0x2F, 0x02, 0xB9, 0x03, 0x60, 0x04, 0x1A, 0x05, 0x0A, 0x06, 0x0E, 0x07, 0x10 } }, { "F15Txxxx", { 0x00, 0x11, 0x00, 0x00, 0x00, 0x36, 0x00, 0x54, 0x00, 0x7D, 0x00, 0xB2, 0x00, 0xF5, 0x01, 0x49, 0x01, 0xB1, 0x02, 0x2B, 0x02, 0xB8, 0x03, 0x59, 0x04, 0x13, 0x04, 0xEC, 0x05, 0xF3, 0x07, 0x34, 0x08, 0xAF, 0x0A, 0xD9 } }, { "F16Txxxx", { 0x00, 0x11, 0x00, 0x00, 0x00, 0x18, 0x00, 0x27, 0x00, 0x3A, 0x00, 0x52, 0x00, 0x71, 0x00, 0x96, 0x00, 0xC4, 0x00, 0xFC, 0x01, 0x40, 0x01, 0x93, 0x01, 0xF6, 0x02, 0x6E, 0x02, 0xFE, 0x03, 0xAA, 0x04, 0x78, 0x05, 0x6C } }, { "F17Txxxx", { 0x00, 0x11, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x34, 0x00, 0x4F, 0x00, 0x71, 0x00, 0x9B, 0x00, 0xCF, 0x01, 0x0E, 0x01, 0x5D, 0x01, 0xBB, 0x02, 0x2F, 0x02, 0xB9, 0x03, 0x60, 0x04, 0x29, 0x05, 0x1E, 0x06, 0x44, 0x07, 0xA1 } }, { "F18Txxxx", { 0x00, 0x11, 0x00, 0x00, 0x00, 0x53, 0x00, 0x8C, 0x00, 0xD5, 0x01, 0x31, 0x01, 0xA2, 0x02, 0x2E, 0x02, 0xD8, 0x03, 0xAE, 0x04, 0xAC, 0x05, 0xE5, 0x07, 0x59, 0x09, 0x1C, 0x0B, 0x3B, 0x0D, 0xD0, 0x10, 0xEA, 0x14, 0x99 } }, { "F19Txxxx", { 0x00, 0x11, 0x00, 0x00, 0x02, 0x8F, 0x03, 0x53, 0x04, 0x5A, 0x05, 0xA1, 0x07, 0xAE, 0x0A, 0x3D, 0x0E, 0x14, 0x13, 0x74, 0x1A, 0x5E, 0x24, 0x18, 0x31, 0xA9, 0x44, 0x59, 0x5E, 0x76, 0x83, 0x11, 0xB6, 0xC7, 0xFF, 0x7B } }, { "F24Txxxx", { 0x00, 0x11, 0x00, 0x01, 0x00, 0x34, 0x00, 0x52, 0x00, 0x73, 0x00, 0x94, 0x00, 0xBE, 0x00, 0xFA, 0x01, 0x36, 0x01, 0x72, 0x01, 0xC5, 0x02, 0x2F, 0x02, 0xB9, 0x03, 0x60, 0x04, 0x1A, 0x05, 0x0A, 0x06, 0x0E, 0x07, 0x10 } } }; WEG *WEG::callbackWEG; void WEG::init() { callbackWEG = this; // Background init fix is only necessary on 10.10 and newer. // Former boot-arg name is igfxrst. if (getKernelVersion() >= KernelVersion::Yosemite) { PE_parse_boot_argn("gfxrst", &resetFramebuffer, sizeof(resetFramebuffer)); if (resetFramebuffer >= FB_TOTAL) { SYSLOG("weg", "invalid igfxrset value %d, falling back to autodetect", resetFramebuffer); resetFramebuffer = FB_DETECT; } } else { resetFramebuffer = FB_NONE; } // Black screen fix is needed everywhere, but the form depends on the boot-arg. // Former boot-arg name is ngfxpatch. char agdp[128]; if (PE_parse_boot_argn("agdpmod", agdp, sizeof(agdp))) processGraphicsPolicyStr(agdp); // Callback setup is only done here for compatibility. lilu.onPatcherLoadForce([](void *user, KernelPatcher &patcher) { static_cast<WEG *>(user)->processKernel(patcher); }, this); lilu.onKextLoadForce(nullptr, 0, [](void *user, KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) { static_cast<WEG *>(user)->processKext(patcher, index, address, size); }, this); // Perform a background fix. if (resetFramebuffer != FB_NONE) lilu.onKextLoadForce(&kextIOGraphics); // Perform a black screen fix. if (graphicsDisplayPolicyMod != AGDP_NONE_SET) lilu.onKextLoad(&kextAGDPolicy); // Disable backlight patches if asked specifically. PE_parse_boot_argn("applbkl", &appleBacklightPatch, sizeof(appleBacklightPatch)); if (appleBacklightPatch != APPLBKL_OFF) lilu.onKextLoad(&kextBacklight); igfx.init(); ngfx.init(); rad.init(); shiki.init(); cdf.init(); } void WEG::deinit() { igfx.deinit(); ngfx.deinit(); rad.deinit(); shiki.deinit(); cdf.deinit(); } void WEG::processKernel(KernelPatcher &patcher) { // Correct GPU properties auto devInfo = DeviceInfo::create(); if (devInfo) { if (devInfo->requestedExternalSwitchOff) { DBGLOG("weg", "disabling all external GPUs"); size_t extNum = devInfo->videoExternal.size(); for (size_t i = 0; i < extNum; i++) { auto &v = devInfo->videoExternal[i]; WIOKit::awaitPublishing(v.video); auto gpu = OSDynamicCast(IOService, v.video); auto hda = OSDynamicCast(IOService, v.audio); auto pci = OSDynamicCast(IOService, v.video->getParentEntry(gIOServicePlane)); if (gpu && pci) { if (gpu->requestTerminate(pci, 0) && gpu->terminate()) gpu->stop(pci); else SYSLOG("weg", "failed to terminate external gpu %ld", i); if (hda && hda->requestTerminate(pci, 0) && hda->terminate()) hda->stop(pci); else if (hda) SYSLOG("weg", "failed to terminate external hdau %ld", i); } else { SYSLOG("weg", "incompatible external gpu %ld discovered", i); } } devInfo->videoExternal.deinit(); } if (graphicsDisplayPolicyMod == AGDP_DETECT) { /* Default detect only */ auto getAgpdMod = [this](IORegistryEntry *device) { auto prop = device->getProperty("agdpmod"); if (prop) { DBGLOG("weg", "found agdpmod in external GPU %s", safeString(device->getName())); const char *agdp = nullptr; auto propStr = OSDynamicCast(OSString, prop); auto propData = OSDynamicCast(OSData, prop); if (propStr) { agdp = propStr->getCStringNoCopy(); } else if (propData && propData->getLength() > 0) { agdp = static_cast<const char *>(propData->getBytesNoCopy()); if (agdp && agdp[propData->getLength() - 1] != '\0') { DBGLOG("weg", "agdpmod config is not null terminated"); agdp = nullptr; } } if (agdp) { processGraphicsPolicyStr(agdp); return true; } } return false; }; size_t extNum = devInfo->videoExternal.size(); for (size_t i = 0; i < extNum; i++) { if (getAgpdMod(devInfo->videoExternal[i].video)) break; } if (devInfo->videoBuiltin != nullptr && graphicsDisplayPolicyMod == AGDP_DETECT) /* Default detect only */ getAgpdMod(devInfo->videoBuiltin); } // Do not inject properties unless non-Apple size_t extNum = devInfo->videoExternal.size(); if (devInfo->firmwareVendor != DeviceInfo::FirmwareVendor::Apple) { DBGLOG("weg", "non-apple-fw proceeding with devprops %d", graphicsDisplayPolicyMod); if (devInfo->videoBuiltin) { processBuiltinProperties(devInfo->videoBuiltin, devInfo); // Assume that enabled IGPU with connectors is the boot display. if (resetFramebuffer == FB_DETECT && !devInfo->reportedFramebufferIsConnectorLess) resetFramebuffer = FB_COPY; } if (appleBacklightPatch == APPLBKL_DETECT && devInfo->videoBuiltin != nullptr) WIOKit::getOSDataValue(devInfo->videoBuiltin, "applbkl", appleBacklightPatch); if (appleBacklightCustomName == nullptr && devInfo->videoBuiltin != nullptr) { appleBacklightCustomName = OSDynamicCast(OSData, devInfo->videoBuiltin->getProperty("applbkl-name")); appleBacklightCustomData = OSDynamicCast(OSData, devInfo->videoBuiltin->getProperty("applbkl-data")); if (appleBacklightCustomName == nullptr || appleBacklightCustomData == nullptr) appleBacklightCustomName = appleBacklightCustomData = nullptr; } for (size_t i = 0; i < extNum; i++) { auto &v = devInfo->videoExternal[i]; processExternalProperties(v.video, devInfo, v.vendor); // Assume that AMD GPU is the boot display. if (v.vendor == WIOKit::VendorID::ATIAMD && resetFramebuffer == FB_DETECT) resetFramebuffer = FB_ZEROFILL; if (appleBacklightPatch == APPLBKL_DETECT) WIOKit::getOSDataValue(v.video, "applbkl", appleBacklightPatch); if (appleBacklightCustomName == nullptr) { appleBacklightCustomName = OSDynamicCast(OSData, v.video->getProperty("applbkl-name")); appleBacklightCustomData = OSDynamicCast(OSData, v.video->getProperty("applbkl-data")); if (appleBacklightCustomName == nullptr || appleBacklightCustomData == nullptr) appleBacklightCustomName = appleBacklightCustomData = nullptr; } } // Note, disabled Optimus will make videoExternal 0, so this case checks for active IGPU only. if (appleBacklightPatch == APPLBKL_DETECT && (devInfo->videoBuiltin == nullptr || extNum > 0)) { // Either a builtin IGPU is not available, or some external GPU is available. kextBacklight.switchOff(); } if ((graphicsDisplayPolicyMod & AGDP_DETECT) && isGraphicsPolicyModRequired(devInfo)) graphicsDisplayPolicyMod = AGDP_VIT9696 | AGDP_PIKERA | AGDP_SET; if (devInfo->managementEngine) processManagementEngineProperties(devInfo->managementEngine); } else { if (appleBacklightPatch != APPLBKL_ON) { // Do not patch AppleBacklight on Apple HW, unless forced. kextBacklight.switchOff(); } // Support legacy -wegtree argument. bool rebuidTree = checkKernelArgument("-wegtree"); // Support device properties. if (!rebuidTree && devInfo->videoBuiltin) rebuidTree = devInfo->videoBuiltin->getProperty("rebuild-device-tree") != nullptr; for (size_t i = 0; !rebuidTree && i < extNum; i++) rebuidTree = devInfo->videoExternal[i].video->getProperty("rebuild-device-tree") != nullptr; // Override with modern wegtree argument. int tree; if (PE_parse_boot_argn("wegtree", &tree, sizeof(tree))) rebuidTree = tree != 0; if (rebuidTree) { DBGLOG("weg", "apple-fw proceeding with devprops by request"); if (devInfo->videoBuiltin) processBuiltinProperties(devInfo->videoBuiltin, devInfo); for (size_t i = 0; i < extNum; i++) { auto &v = devInfo->videoExternal[i]; processExternalProperties(v.video, devInfo, v.vendor); } } if (devInfo->managementEngine) processManagementEngineProperties(devInfo->managementEngine); } igfx.processKernel(patcher, devInfo); ngfx.processKernel(patcher, devInfo); rad.processKernel(patcher, devInfo); shiki.processKernel(patcher, devInfo); cdf.processKernel(patcher, devInfo); DeviceInfo::deleter(devInfo); } // Disable mods that did not find a way to function. if (resetFramebuffer == FB_DETECT) { resetFramebuffer = FB_NONE; kextIOGraphics.switchOff(); } if ((graphicsDisplayPolicyMod & AGDP_DETECT) || graphicsDisplayPolicyMod == AGDP_NONE_SET) { graphicsDisplayPolicyMod = AGDP_NONE_SET; kextAGDPolicy.switchOff(); } // We need to load vinfo for cleanup and copy. if (resetFramebuffer == FB_COPY || resetFramebuffer == FB_ZEROFILL) { auto info = reinterpret_cast<vc_info *>(patcher.solveSymbol(KernelPatcher::KernelID, "_vinfo")); if (info) { consoleVinfo = *info; DBGLOG("weg", "vinfo 1: %u:%u %u:%u:%u", consoleVinfo.v_height, consoleVinfo.v_width, consoleVinfo.v_depth, consoleVinfo.v_rowbytes, consoleVinfo.v_type); DBGLOG("weg", "vinfo 2: %s %u:%u %u:%u:%u", consoleVinfo.v_name, consoleVinfo.v_rows, consoleVinfo.v_columns, consoleVinfo.v_rowscanbytes, consoleVinfo.v_scale, consoleVinfo.v_rotate); gotConsoleVinfo = true; } else { SYSLOG("weg", "failed to obtain vcinfo"); patcher.clearError(); } } } void WEG::processKext(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) { if (kextIOGraphics.loadIndex == index) { gIOFBVerboseBootPtr = patcher.solveSymbol<uint8_t *>(index, "__ZL16gIOFBVerboseBoot", address, size); if (gIOFBVerboseBootPtr) { KernelPatcher::RouteRequest request("__ZN13IOFramebuffer6initFBEv", wrapFramebufferInit, orgFramebufferInit); patcher.routeMultiple(index, &request, 1, address, size); } else { SYSLOG("weg", "failed to resolve gIOFBVerboseBoot"); patcher.clearError(); } return; } if (kextAGDPolicy.loadIndex == index) { processGraphicsPolicyMods(patcher, address, size); return; } if (kextBacklight.loadIndex == index) { KernelPatcher::RouteRequest request("__ZN15AppleIntelPanel10setDisplayEP9IODisplay", wrapApplePanelSetDisplay, orgApplePanelSetDisplay); if (patcher.routeMultiple(kextBacklight.loadIndex, &request, 1, address, size)) { const uint8_t find[] = {"F%uT%04x"}; const uint8_t replace[] = {"F%uTxxxx"}; KernelPatcher::LookupPatch patch = {&kextBacklight, find, replace, sizeof(find), 1}; DBGLOG("weg", "applying backlight patch"); patcher.applyLookupPatch(&patch); } } if (igfx.processKext(patcher, index, address, size)) return; if (ngfx.processKext(patcher, index, address, size)) return; if (rad.processKext(patcher, index, address, size)) return; if (cdf.processKext(patcher, index, address, size)) return; } void WEG::processBuiltinProperties(IORegistryEntry *device, DeviceInfo *info) { auto name = device->getName(); // There could be only one IGPU, and it must be named IGPU for AppleGVA to function properly. if (!name || strcmp(name, "IGPU") != 0) WIOKit::renameDevice(device, "IGPU"); // Obtain the real device info, should we cast to IOPCIDevice here? auto obj = OSDynamicCast(IOService, device); if (obj) { uint32_t realDevice = WIOKit::readPCIConfigValue(obj, WIOKit::kIOPCIConfigDeviceID); uint32_t acpiDevice = 0, fakeDevice = 0; if (!WIOKit::getOSDataValue(obj, "device-id", acpiDevice)) DBGLOG("weg", "missing IGPU device-id"); // Set the right Intel model name here. auto model = getIntelModel(realDevice, fakeDevice); DBGLOG("weg", "IGPU has real %04X acpi %04X fake %04X and model %s", realDevice, acpiDevice, fakeDevice, safeString(model)); if (model && !obj->getProperty("model")) { DBGLOG("weg", "adding missing model %s from autotodetect", model); obj->setProperty("model", const_cast<char *>(model), static_cast<unsigned>(strlen(model)+1)); } // User may request to fake device-id even if it is supported. if (realDevice != acpiDevice) { DBGLOG("weg", "user requested to fake with normal device-id"); fakeDevice = acpiDevice; } // Update vtable I/O functions to ensure that a correct fake device ID is read. if (fakeDevice) { // Incorrect device-id means Intel drivers will most likely fail to do matching, error to log. if (fakeDevice != acpiDevice) { uint8_t bus = 0, dev = 0, fun = 0; WIOKit::getDeviceAddress(obj, bus, dev, fun); SYSLOG("weg", "IGPU device (%02X:%02X.%02X) has device-id 0x%04X, you should change it to 0x%04X", bus, dev, fun, acpiDevice, fakeDevice); } if (fakeDevice != realDevice) { if (KernelPatcher::routeVirtual(obj, WIOKit::PCIConfigOffset::ConfigRead16, wrapConfigRead16, &orgConfigRead16) && KernelPatcher::routeVirtual(obj, WIOKit::PCIConfigOffset::ConfigRead32, wrapConfigRead32, &orgConfigRead32)) DBGLOG("weg", "hooked configRead read methods!"); else SYSLOG("weg", "failed to hook configRead read methods!"); } } } else { SYSLOG("weg", "invalid IGPU device type"); } // Update the requested framebuffer identifier. if (info->reportedFramebufferName && BaseDeviceInfo::get().cpuGeneration >= CPUInfo::CpuGeneration::SandyBridge) device->setProperty(info->reportedFramebufferName, &info->reportedFramebufferId, sizeof(info->reportedFramebufferId)); // Set AAPL,os-info property if not present for first generation. // Default value pulled from AppleIntelHDGraphicsFB. Property is required for non-MacBookPro6,1 platforms due to a bug in AppleIntelHDGraphicsFB. if (BaseDeviceInfo::get().cpuGeneration == CPUInfo::CpuGeneration::Westmere) { if (!device->getProperty("AAPL,os-info")) { DBGLOG("weg", "fixing AAPL,os-info"); uint8_t osInfoBytes[] { 0x30, 0x49, 0x01, 0x01, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }; device->setProperty("AAPL,os-info", osInfoBytes, sizeof(osInfoBytes)); } else { DBGLOG("weg", "found existing AAPL,os-info"); } } // Ensure built-in. if (!device->getProperty("built-in")) { DBGLOG("weg", "fixing built-in"); uint8_t builtBytes[] { 0x00 }; device->setProperty("built-in", builtBytes, sizeof(builtBytes)); } else { DBGLOG("weg", "found existing built-in"); } } void WEG::processExternalProperties(IORegistryEntry *device, DeviceInfo *info, uint32_t vendor) { auto name = device->getName(); // It is unclear how to properly name the GPUs, and supposedly it does not really matter. // However, we will try to at least name them in a unique manner (GFX0, GFX1, ...) if (device->getProperty("preserve-names") == nullptr && currentExternalGfxIndex <= MaxExternalGfxIndex && (!name || strncmp(name, "GFX", strlen("GFX")) != 0)) { char name[16]; snprintf(name, sizeof(name), "GFX%u", currentExternalGfxIndex++); WIOKit::renameDevice(device, name); } // AAPL,slot-name is used to distinguish GPU slots in Mac Pro. // NVIDIA Web Drivers have a preference panel, where they read this value and allow up to 4 GPUs. // Each NVIDIA GPU is then displayed on the ECC tab. We permit more slots, since 4 is an artificial restriction. // iMac on the other side has only one GPU and is not expected to have multiple slots. // Here we pass AAPL,slot-name if the GPU is NVIDIA or we have more than one GPU. bool wantSlot = info->videoExternal.size() > 1 || vendor == WIOKit::VendorID::NVIDIA; if (wantSlot && currentExternalSlotIndex <= MaxExternalSlotIndex && !device->getProperty("AAPL,slot-name")) { char name[16]; snprintf(name, sizeof(name), "Slot-%u", currentExternalSlotIndex++); device->setProperty("AAPL,slot-name", name, sizeof("Slot-1")); } // Set the autodetected AMD GPU name here, it will later be handled by RAD to not get overridden. // This is not necessary for NVIDIA, as their drivers properly detect the name. if (vendor == WIOKit::VendorID::ATIAMD && !device->getProperty("model")) { uint32_t dev, rev, subven, sub; if (WIOKit::getOSDataValue(device, "device-id", dev) && WIOKit::getOSDataValue(device, "revision-id", rev) && WIOKit::getOSDataValue(device, "subsystem-vendor-id", subven) && WIOKit::getOSDataValue(device, "subsystem-id", sub)) { auto model = getRadeonModel(dev, rev, subven, sub); if (model) { device->setProperty("model", const_cast<char *>(model), static_cast<unsigned>(strlen(model)+1)); } } } // Ensure built-in. if (!device->getProperty("built-in")) { DBGLOG("weg", "fixing built-in"); uint8_t builtBytes[] { 0x00 }; device->setProperty("built-in", builtBytes, sizeof(builtBytes)); } else { DBGLOG("weg", "found existing built-in"); } } void WEG::processManagementEngineProperties(IORegistryEntry *imei) { auto name = imei->getName(); // Rename mislabeled IMEI device if (!name || strcmp(name, "IMEI") != 0) WIOKit::renameDevice(imei, "IMEI"); uint32_t device = 0; auto cpuGeneration = BaseDeviceInfo::get().cpuGeneration; if ((cpuGeneration == CPUInfo::CpuGeneration::SandyBridge || cpuGeneration == CPUInfo::CpuGeneration::IvyBridge) && WIOKit::getOSDataValue(imei, "device-id", device)) { // Exotic cases like SNB CPU on 7-series motherboards or IVB CPU on 6-series // require device-id faking. Unfortunately it is too late to change it at this step, // because device matching happens earlier, but we will spill a warning to make sure // one fixes them at device property or ACPI level. uint32_t suggest = 0; if (cpuGeneration == CPUInfo::CpuGeneration::SandyBridge && device != 0x1C3A) suggest = 0x1C3A; else if (cpuGeneration == CPUInfo::CpuGeneration::IvyBridge && device != 0x1E3A) suggest = 0x1E3A; if (suggest != 0) { uint8_t bus = 0, dev = 0, fun = 0; WIOKit::getDeviceAddress(imei, bus, dev, fun); SYSLOG("weg", "IMEI device (%02X:%02X.%02X) has device-id 0x%04X, you should change it to 0x%04X", bus, dev, fun, device, suggest); } } } void WEG::processGraphicsPolicyStr(const char *agdp) { DBGLOG("weg", "agdpmod using config %s", agdp); if (strstr(agdp, "detect")) { graphicsDisplayPolicyMod = AGDP_DETECT_SET; } else if (strstr(agdp, "ignore")) { graphicsDisplayPolicyMod = AGDP_NONE_SET; } else { graphicsDisplayPolicyMod = AGDP_NONE_SET; if (strstr(agdp, "vit9696")) graphicsDisplayPolicyMod |= AGDP_VIT9696; if (strstr(agdp, "pikera")) graphicsDisplayPolicyMod |= AGDP_PIKERA; if (strstr(agdp, "cfgmap")) graphicsDisplayPolicyMod |= AGDP_CFGMAP; } } void WEG::processGraphicsPolicyMods(KernelPatcher &patcher, mach_vm_address_t address, size_t size) { if (graphicsDisplayPolicyMod & AGDP_VIT9696) { uint8_t find[] = {0xBA, 0x05, 0x00, 0x00, 0x00}; uint8_t replace[] = {0xBA, 0x00, 0x00, 0x00, 0x00}; KernelPatcher::LookupPatch patch { &kextAGDPolicy, find, replace, sizeof(find), 1 }; patcher.applyLookupPatch(&patch); if (patcher.getError() != KernelPatcher::Error::NoError) { SYSLOG("weg", "failed to apply agdp vit9696's patch %d", patcher.getError()); patcher.clearError(); } } if (graphicsDisplayPolicyMod & AGDP_PIKERA) { KernelPatcher::LookupPatch patch { &kextAGDPolicy, reinterpret_cast<const uint8_t *>("board-id"), reinterpret_cast<const uint8_t *>("board-ix"), sizeof("board-id"), 1 }; patcher.applyLookupPatch(&patch); if (patcher.getError() != KernelPatcher::Error::NoError) { SYSLOG("weg", "failed to apply agdp Piker-Alpha's patch %d", patcher.getError()); patcher.clearError(); } } if (graphicsDisplayPolicyMod & AGDP_CFGMAP) { // Does not function in 10.13.x, as the symbols have been stripped. Abort on usage on 10.14 or newer. if (getKernelVersion() >= KernelVersion::Mojave) PANIC("weg", "adgpmod=cfgmap has no effect on 10.13.4, use agdpmod=ignore"); KernelPatcher::RouteRequest request("__ZN25AppleGraphicsDevicePolicy5startEP9IOService", wrapGraphicsPolicyStart, orgGraphicsPolicyStart); patcher.routeMultiple(kextAGDPolicy.loadIndex, &request, 1, address, size); } } bool WEG::isGraphicsPolicyModRequired(DeviceInfo *info) { DBGLOG("weg", "detecting policy"); // Graphics policy patches are only applicable to discrete GPUs. if (info->videoExternal.size() == 0) { DBGLOG("weg", "no external gpus"); return false; } // Graphics policy patches do harm on Apple MacBooks, see: // https://github.com/acidanthera/bugtracker/issues/260 if (info->firmwareVendor == DeviceInfo::FirmwareVendor::Apple) { DBGLOG("weg", "apple firmware"); return false; } // We do not need AGDC patches on compatible devices. auto boardId = BaseDeviceInfo::get().boardIdentifier; DBGLOG("weg", "board is %s", boardId); const char *compatibleBoards[] { "Mac-00BE6ED71E35EB86", // iMac13,1 "Mac-27ADBB7B4CEE8E61", // iMac14,2 "Mac-4B7AC7E43945597E", // MacBookPro9,1 "Mac-77EB7D7DAF985301", // iMac14,3 "Mac-C3EC7CD22292981F", // MacBookPro10,1 "Mac-C9CF552659EA9913", // ??? "Mac-F221BEC8", // MacPro5,1 (and MacPro4,1) "Mac-F221DCC8", // iMac10,1 "Mac-F42C88C8", // MacPro3,1 "Mac-FC02E91DDD3FA6A4", // iMac13,2 "Mac-2BD1B31983FE1663" // MacBookPro11,3 }; for (size_t i = 0; i < arrsize(compatibleBoards); i++) { if (!strcmp(compatibleBoards[i], boardId)) { DBGLOG("weg", "disabling nvidia patches on model %s", boardId); return false; } } return true; } void WEG::wrapFramebufferInit(IOFramebuffer *fb) { bool backCopy = callbackWEG->gotConsoleVinfo && callbackWEG->resetFramebuffer == FB_COPY; bool zeroFill = callbackWEG->gotConsoleVinfo && callbackWEG->resetFramebuffer == FB_ZEROFILL; auto &info = callbackWEG->consoleVinfo; // Copy back usually happens in a separate call to frameBufferInit // Furthermore, v_baseaddr may not be available on subsequent calls, so we have to copy if (backCopy && info.v_baseaddr) { // Note, this buffer is left allocated and never freed, yet there actually is no way to free it. callbackWEG->consoleBuffer = Buffer::create<uint8_t>(info.v_rowbytes * info.v_height); if (callbackWEG->consoleBuffer) lilu_os_memcpy(callbackWEG->consoleBuffer, reinterpret_cast<uint8_t *>(info.v_baseaddr), info.v_rowbytes * info.v_height); else SYSLOG("weg", "console buffer allocation failure"); // Even if we may succeed next time, it will be unreasonably dangerous info.v_baseaddr = 0; } uint8_t verboseBoot = *callbackWEG->gIOFBVerboseBootPtr; // For back copy we need a console buffer and no verbose backCopy = backCopy && callbackWEG->consoleBuffer && !verboseBoot; // Now check if the resolution and parameters match if (backCopy || zeroFill) { IODisplayModeID mode; IOIndex depth; IOPixelInformation pixelInfo; if (fb->getCurrentDisplayMode(&mode, &depth) == kIOReturnSuccess && fb->getPixelInformation(mode, depth, kIOFBSystemAperture, &pixelInfo) == kIOReturnSuccess) { DBGLOG("weg", "fb info 1: %d:%d %u:%u:%u", mode, depth, pixelInfo.bytesPerRow, pixelInfo.bytesPerPlane, pixelInfo.bitsPerPixel); DBGLOG("weg", "fb info 2: %u:%u %s %u:%u:%u", pixelInfo.componentCount, pixelInfo.bitsPerComponent, pixelInfo.pixelFormat, pixelInfo.flags, pixelInfo.activeWidth, pixelInfo.activeHeight); if (info.v_rowbytes != pixelInfo.bytesPerRow || info.v_width != pixelInfo.activeWidth || info.v_height != pixelInfo.activeHeight || info.v_depth != pixelInfo.bitsPerPixel) { backCopy = zeroFill = false; DBGLOG("weg", "this display has different mode"); } } else { DBGLOG("weg", "failed to obtain display mode"); backCopy = zeroFill = false; } } // For whatever reason not resetting Intel framebuffer (back copy mode) twice works better. if (!backCopy) *callbackWEG->gIOFBVerboseBootPtr = 1; FunctionCast(wrapFramebufferInit, callbackWEG->orgFramebufferInit)(fb); if (!backCopy) *callbackWEG->gIOFBVerboseBootPtr = verboseBoot; // Finish the framebuffer initialisation by filling with black or copying the image back. if (FramebufferViewer::getVramMap(fb)) { auto src = reinterpret_cast<uint8_t *>(callbackWEG->consoleBuffer); auto dst = reinterpret_cast<uint8_t *>(FramebufferViewer::getVramMap(fb)->getVirtualAddress()); if (backCopy) { DBGLOG("weg", "attempting to copy..."); // Here you can actually draw at your will, but looks like only on Intel. // On AMD you technically can draw too, but it happens for a very short while, and is not worth it. lilu_os_memcpy(dst, src, info.v_rowbytes * info.v_height); } else if (zeroFill) { // On AMD we do a zero-fill to ensure no visual glitches. DBGLOG("weg", "doing zero-fill..."); memset(dst, 0, info.v_rowbytes * info.v_height); } } } uint16_t WEG::wrapConfigRead16(IORegistryEntry *service, uint32_t space, uint8_t offset) { auto result = callbackWEG->orgConfigRead16(service, space, offset); if (offset == WIOKit::kIOPCIConfigDeviceID && service != nullptr) { auto name = service->getName(); if (name && name[0] == 'I' && name[1] == 'G' && name[2] == 'P' && name[3] == 'U') { DBGLOG("weg", "configRead16 IGPU 0x%08X at off 0x%02X, result = 0x%04x", space, offset, result); uint32_t device; if (WIOKit::getOSDataValue(service, "device-id", device) && device != result) { DBGLOG("weg", "configRead16 IGPU reported 0x%04x instead of 0x%04x", device, result); return device; } } } return result; } uint32_t WEG::wrapConfigRead32(IORegistryEntry *service, uint32_t space, uint8_t offset) { auto result = callbackWEG->orgConfigRead32(service, space, offset); // According to lvs1974 unaligned reads may actually happen! if ((offset == WIOKit::kIOPCIConfigDeviceID || offset == WIOKit::kIOPCIConfigVendorID) && service != nullptr) { auto name = service->getName(); if (name && name[0] == 'I' && name[1] == 'G' && name[2] == 'P' && name[3] == 'U') { DBGLOG("weg", "configRead32 IGPU 0x%08X at off 0x%02X, result = 0x%08X", space, offset, result); uint32_t device; if (WIOKit::getOSDataValue(service, "device-id", device) && device != (result & 0xFFFF)) { device = (result & 0xFFFF) | (device << 16); DBGLOG("weg", "configRead32 reported 0x%08x instead of 0x%08x", device, result); return device; } } } return result; } bool WEG::wrapGraphicsPolicyStart(IOService *that, IOService *provider) { auto boardIdentifier = BaseDeviceInfo::get().boardIdentifier; DBGLOG("weg", "agdp fix got board-id %s", boardIdentifier); auto oldConfigMap = OSDynamicCast(OSDictionary, that->getProperty("ConfigMap")); if (oldConfigMap) { auto rawConfigMap = oldConfigMap->copyCollection(); if (rawConfigMap) { auto newConfigMap = OSDynamicCast(OSDictionary, rawConfigMap); if (newConfigMap) { auto none = OSString::withCString("none"); if (none) { newConfigMap->setObject(boardIdentifier, none); none->release(); that->setProperty("ConfigMap", newConfigMap); } } else { SYSLOG("weg", "agdp fix failed to clone ConfigMap"); } rawConfigMap->release(); } } else { SYSLOG("weg", "agdp fix failed to obtain valid ConfigMap"); } bool result = FunctionCast(wrapGraphicsPolicyStart, callbackWEG->orgGraphicsPolicyStart)(that, provider); DBGLOG("weg", "agdp start returned %d", result); return result; } bool WEG::wrapApplePanelSetDisplay(IOService *that, IODisplay *display) { if (!callbackWEG->applePanelDisplaySet) { callbackWEG->applePanelDisplaySet = true; auto panels = OSDynamicCast(OSDictionary, that->getProperty("ApplePanels")); if (panels) { auto rawPanels = panels->copyCollection(); panels = OSDynamicCast(OSDictionary, rawPanels); if (panels) { const char *customName = nullptr; if (callbackWEG->appleBacklightCustomName != nullptr) { auto length = callbackWEG->appleBacklightCustomName->getLength(); const char *customNameBytes = static_cast<const char *>(callbackWEG->appleBacklightCustomName->getBytesNoCopy()); if (length > 0 && customNameBytes[length - 1] == '\0') customName = customNameBytes; } for (auto &entry : appleBacklightData) { if (customName != nullptr && strcmp(customName, entry.deviceName) == 0) { panels->setObject(entry.deviceName, callbackWEG->appleBacklightCustomData); DBGLOG("weg", "using custom panel data for %s device", entry.deviceName); } else { auto pd = OSData::withBytes(entry.deviceData, sizeof(entry.deviceData)); if (pd) { panels->setObject(entry.deviceName, pd); // No release required by current AppleBacklight implementation. } else { SYSLOG("weg", "panel start cannot allocate %s data", entry.deviceName); } } } that->setProperty("ApplePanels", panels); } if (rawPanels) { rawPanels->release(); } } else { SYSLOG("weg", "panel start has no panels"); } } bool result = FunctionCast(wrapApplePanelSetDisplay, callbackWEG->orgApplePanelSetDisplay)(that, display); DBGLOG("weg", "panel display set returned %d", result); return result; }
38.591617
184
0.700565
[ "model" ]
f6c6c60c5e3167eeeb4f657af0a6fd91115283c8
37,862
cpp
C++
gdal/ogr/ogrsf_frmts/oci/ogrocilayer.cpp
roman0yurin/gdal
349a0992c7ebd0c71e8014e00897b098e4ca16fb
[ "MIT" ]
2
2015-09-23T14:55:26.000Z
2018-01-10T07:09:22.000Z
gdal/ogr/ogrsf_frmts/oci/ogrocilayer.cpp
roman0yurin/gdal
349a0992c7ebd0c71e8014e00897b098e4ca16fb
[ "MIT" ]
1
2015-04-02T02:30:18.000Z
2015-04-02T08:00:13.000Z
gdal/ogr/ogrsf_frmts/oci/ogrocilayer.cpp
roman0yurin/gdal
349a0992c7ebd0c71e8014e00897b098e4ca16fb
[ "MIT" ]
5
2015-01-10T12:52:15.000Z
2020-09-04T13:47:41.000Z
/****************************************************************************** * * Project: Oracle Spatial Driver * Purpose: Implementation of the OGROCILayer class. This is layer semantics * shared between table accessors and ExecuteSQL() result * pseudo-layers. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2002, Frank Warmerdam <warmerdam@pobox.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "ogr_oci.h" #include "cpl_conv.h" CPL_CVSID("$Id$") /************************************************************************/ /* OGROCILayer() */ /************************************************************************/ OGROCILayer::OGROCILayer() { poFeatureDefn = nullptr; poDS = nullptr; poStatement = nullptr; pszQueryStatement = nullptr; nResultOffset = 0; pszGeomName = nullptr; iGeomColumn = -1; pszFIDName = nullptr; iFIDColumn = -1; hLastGeom = nullptr; hLastGeomInd = nullptr; iNextShapeId = 0; } /************************************************************************/ /* ~OGROCILayer() */ /************************************************************************/ OGROCILayer::~OGROCILayer() { if( m_nFeaturesRead > 0 && poFeatureDefn != nullptr ) { CPLDebug( "OCI", "%d features read on layer '%s'.", (int) m_nFeaturesRead, poFeatureDefn->GetName() ); } ResetReading(); CPLFree( pszGeomName ); pszGeomName = nullptr; CPLFree( pszFIDName ); pszFIDName = nullptr; CPLFree( pszQueryStatement ); pszQueryStatement = nullptr; if( poFeatureDefn != nullptr ) poFeatureDefn->Release(); } /************************************************************************/ /* ResetReading() */ /************************************************************************/ void OGROCILayer::ResetReading() { if( poStatement != nullptr ) delete poStatement; poStatement = nullptr; iNextShapeId = 0; } /************************************************************************/ /* GetNextFeature() */ /* */ /* By default we implement the full spatial and attribute query */ /* semantics manually here. The table query class will */ /* override this method and implement these inline, but the */ /* simple SELECT statement evaluator (OGROCISelectLayer) will */ /* depend us this code implementing additional spatial or */ /* attribute query semantics. */ /************************************************************************/ OGRFeature *OGROCILayer::GetNextFeature() { while( true ) { OGRFeature *poFeature; poFeature = GetNextRawFeature(); if( poFeature == nullptr ) return nullptr; if( (m_poFilterGeom == nullptr || FilterGeometry( poFeature->GetGeometryRef() ) ) && (m_poAttrQuery == nullptr || m_poAttrQuery->Evaluate( poFeature )) ) return poFeature; delete poFeature; } } /************************************************************************/ /* GetNextRawFeature() */ /************************************************************************/ OGRFeature *OGROCILayer::GetNextRawFeature() { /* -------------------------------------------------------------------- */ /* Do we need to establish an initial query? */ /* -------------------------------------------------------------------- */ if( iNextShapeId == 0 && poStatement == nullptr ) { if( !ExecuteQuery(pszQueryStatement) ) return nullptr; } /* -------------------------------------------------------------------- */ /* Have we run out of query results, such that we have no */ /* statement left? */ /* -------------------------------------------------------------------- */ if( poStatement == nullptr ) return nullptr; /* -------------------------------------------------------------------- */ /* Are we in some sort of error condition? */ /* -------------------------------------------------------------------- */ hLastGeom = nullptr; char **papszResult = poStatement->SimpleFetchRow(); if( papszResult == nullptr ) { iNextShapeId = MAX(1,iNextShapeId); delete poStatement; poStatement = nullptr; return nullptr; } /* -------------------------------------------------------------------- */ /* Create a feature from the current result. */ /* -------------------------------------------------------------------- */ int iField; OGRFeature *poFeature = new OGRFeature( poFeatureDefn ); poFeature->SetFID( iNextShapeId ); iNextShapeId++; m_nFeaturesRead++; if( iFIDColumn != -1 && papszResult[iFIDColumn] != nullptr ) poFeature->SetFID( atoi(papszResult[iFIDColumn]) ); for( iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ ) { if( papszResult[iField] != nullptr ) poFeature->SetField( iField, papszResult[iField] ); else poFeature->SetFieldNull( iField ); } /* -------------------------------------------------------------------- */ /* Translate geometry if we have it. */ /* -------------------------------------------------------------------- */ if( iGeomColumn != -1 ) { poFeature->SetGeometryDirectly( TranslateGeometry() ); OGROCISession *poSession = poDS->GetSession(); if( poFeature->GetGeometryRef() != nullptr && hLastGeom != nullptr ) poSession->Failed( OCIObjectFree(poSession->hEnv, poSession->hError, (dvoid *) hLastGeom, (ub2)OCI_OBJECTFREE_FORCE) ); hLastGeom = nullptr; hLastGeomInd = nullptr; } nResultOffset++; return poFeature; } /************************************************************************/ /* ExecuteQuery() */ /* */ /* This is invoke when the first request for a feature is */ /* made. It executes the query, and binds columns as needed. */ /* The OGROCIStatement is used for most of the work. */ /************************************************************************/ int OGROCILayer::ExecuteQuery( const char *pszReqQuery ) { OGROCISession *poSession = poDS->GetSession(); CPLAssert( pszReqQuery != nullptr ); CPLAssert( poStatement == nullptr ); /* -------------------------------------------------------------------- */ /* Execute the query. */ /* -------------------------------------------------------------------- */ poStatement = new OGROCIStatement( poSession ); if( poStatement->Execute( pszReqQuery ) != CE_None ) { delete poStatement; poStatement = nullptr; return FALSE; } nResultOffset = 0; /* -------------------------------------------------------------------- */ /* Do additional work binding the geometry column. */ /* -------------------------------------------------------------------- */ if( iGeomColumn != -1 ) { OCIDefine *hGDefine = nullptr; if( poSession->Failed( OCIDefineByPos(poStatement->GetStatement(), &hGDefine, poSession->hError, (ub4) iGeomColumn+1, (dvoid *)nullptr, (sb4)0, SQLT_NTY, (dvoid *)nullptr, (ub2 *)nullptr, (ub2 *)nullptr, (ub4)OCI_DEFAULT), "OCIDefineByPos(geometry)") ) return FALSE; if( poSession->Failed( OCIDefineObject(hGDefine, poSession->hError, poSession->hGeometryTDO, (dvoid **) &hLastGeom, (ub4 *)nullptr, (dvoid **) &hLastGeomInd, (ub4 *)nullptr ), "OCIDefineObject") ) return FALSE; } return TRUE; } /************************************************************************/ /* TranslateGeometry() */ /************************************************************************/ OGRGeometry *OGROCILayer::TranslateGeometry() { OGROCISession *poSession = poDS->GetSession(); /* -------------------------------------------------------------------- */ /* Is the geometry NULL? */ /* -------------------------------------------------------------------- */ if( hLastGeom == nullptr || hLastGeomInd == nullptr || hLastGeomInd->_atomic == OCI_IND_NULL ) return nullptr; /* -------------------------------------------------------------------- */ /* Get the size of the sdo_elem_info and sdo_ordinates arrays. */ /* -------------------------------------------------------------------- */ int nElemCount, nOrdCount; if( poSession->Failed( OCICollSize( poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_elem_info), &nElemCount), "OCICollSize(sdo_elem_info)" ) ) return nullptr; if( poSession->Failed( OCICollSize( poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_ordinates), &nOrdCount), "OCICollSize(sdo_ordinates)" ) ) return nullptr; /* -------------------------------------------------------------------- */ /* Get the GType. */ /* -------------------------------------------------------------------- */ int nGType; if( poSession->Failed( OCINumberToInt(poSession->hError, &(hLastGeom->sdo_gtype), (uword)sizeof(int), OCI_NUMBER_SIGNED, (dvoid *)&nGType), "OCINumberToInt(GType)" ) ) return nullptr; /* -------------------------------------------------------------------- */ /* Establish the dimension. */ /* -------------------------------------------------------------------- */ int nDimension = MAX(2,(nGType / 1000)); /* -------------------------------------------------------------------- */ /* Handle point data directly from built-in point info. */ /* -------------------------------------------------------------------- */ if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_POINT) && hLastGeomInd->sdo_point._atomic == OCI_IND_NOTNULL && hLastGeomInd->sdo_point.x == OCI_IND_NOTNULL && hLastGeomInd->sdo_point.y == OCI_IND_NOTNULL ) { double dfX, dfY, dfZ = 0.0; OCINumberToReal(poSession->hError, &(hLastGeom->sdo_point.x), (uword)sizeof(double), (dvoid *)&dfX); OCINumberToReal(poSession->hError, &(hLastGeom->sdo_point.y), (uword)sizeof(double), (dvoid *)&dfY); if( hLastGeomInd->sdo_point.z == OCI_IND_NOTNULL ) OCINumberToReal(poSession->hError, &(hLastGeom->sdo_point.z), (uword)sizeof(double), (dvoid *)&dfZ); if( nDimension == 3 ) return new OGRPoint( dfX, dfY, dfZ ); else return new OGRPoint( dfX, dfY ); } /* -------------------------------------------------------------------- */ /* If this is a sort of container geometry, create the */ /* container now. */ /* -------------------------------------------------------------------- */ OGRGeometryCollection *poCollection = nullptr; OGRPolygon *poPolygon = nullptr; if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_POLYGON) ) poPolygon = new OGRPolygon(); else if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_COLLECTION) ) poCollection = new OGRGeometryCollection(); else if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_MULTIPOINT) ) poCollection = new OGRMultiPoint(); else if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_MULTILINESTRING) ) poCollection = new OGRMultiLineString(); else if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_MULTIPOLYGON) ) poCollection = new OGRMultiPolygon(); /* ==================================================================== */ /* Loop over the component elements. */ /* ==================================================================== */ for( int iElement = 0; iElement < nElemCount; iElement += 3 ) { int nInterpretation, nEType; int nStartOrdinal, nElemOrdCount; LoadElementInfo( iElement, nElemCount, nOrdCount, &nEType, &nInterpretation, &nStartOrdinal, &nElemOrdCount ); /* -------------------------------------------------------------------- */ /* Translate this element. */ /* -------------------------------------------------------------------- */ OGRGeometry *poGeom; poGeom = TranslateGeometryElement( &iElement, nGType, nDimension, nEType, nInterpretation, nStartOrdinal - 1, nElemOrdCount ); if( poGeom == nullptr ) return nullptr; /* -------------------------------------------------------------------- */ /* Based on GType do what is appropriate. */ /* -------------------------------------------------------------------- */ if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_LINESTRING) ) { CPLAssert(wkbFlatten(poGeom->getGeometryType()) == wkbLineString); return poGeom; } else if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_POINT) ) { CPLAssert(wkbFlatten(poGeom->getGeometryType()) == wkbPoint); return poGeom; } else if( ORA_GTYPE_MATCH(nGType,ORA_GTYPE_POLYGON) ) { CPLAssert(wkbFlatten(poGeom->getGeometryType()) == wkbLineString ); poPolygon->addRingDirectly( (OGRLinearRing *) poGeom ); } else { CPLAssert( poCollection != nullptr ); if( wkbFlatten(poGeom->getGeometryType()) == wkbMultiPoint ) { int i; OGRMultiPoint *poMP = (OGRMultiPoint *) poGeom; for( i = 0; i < poMP->getNumGeometries(); i++ ) poCollection->addGeometry( poMP->getGeometryRef(i) ); delete poMP; } else if( nEType % 1000 == 3 ) { /* its one poly ring, create new poly or add to existing */ if( nEType == 1003 ) { if( poPolygon != nullptr && poPolygon->getExteriorRing() != nullptr ) { poCollection->addGeometryDirectly( poPolygon ); poPolygon = nullptr; } poPolygon = new OGRPolygon(); } if( poPolygon != nullptr ) poPolygon->addRingDirectly( (OGRLinearRing *) poGeom ); else { CPLAssert( poPolygon != nullptr ); } } else poCollection->addGeometryDirectly( poGeom ); } } if( poCollection != nullptr && poPolygon != nullptr ) poCollection->addGeometryDirectly( poPolygon ); /* -------------------------------------------------------------------- */ /* Return resulting collection geometry. */ /* -------------------------------------------------------------------- */ if( poCollection == nullptr ) return poPolygon; else return poCollection; } /************************************************************************/ /* LoadElementInfo() */ /* */ /* Fetch the start ordinal, count, EType and interpretation */ /* values for a particular element. */ /************************************************************************/ int OGROCILayer::LoadElementInfo( int iElement, int nElemCount, int nTotalOrdCount, int *pnEType, int *pnInterpretation, int *pnStartOrdinal, int *pnElemOrdCount ) { OGROCISession *poSession = poDS->GetSession(); boolean bExists; OCINumber *hNumber; /* -------------------------------------------------------------------- */ /* Get the details about element from the elem_info array. */ /* -------------------------------------------------------------------- */ OCICollGetElem(poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_elem_info), (sb4)(iElement+0), (boolean *)&bExists, (dvoid **)&hNumber, nullptr ); OCINumberToInt(poSession->hError, hNumber, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *) pnStartOrdinal ); OCICollGetElem(poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_elem_info), (sb4)(iElement+1), (boolean *)&bExists, (dvoid **)&hNumber, nullptr ); OCINumberToInt(poSession->hError, hNumber, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *) pnEType ); OCICollGetElem(poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_elem_info), (sb4)(iElement+2), (boolean *)&bExists, (dvoid **)&hNumber, nullptr ); OCINumberToInt(poSession->hError, hNumber, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *) pnInterpretation ); if( iElement < nElemCount-3 ) { ub4 nNextStartOrdinal; OCICollGetElem(poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_elem_info), (sb4)(iElement+3), (boolean *)&bExists, (dvoid **)&hNumber,nullptr); OCINumberToInt(poSession->hError, hNumber, (uword)sizeof(ub4), OCI_NUMBER_UNSIGNED, (dvoid *) &nNextStartOrdinal ); *pnElemOrdCount = nNextStartOrdinal - *pnStartOrdinal; } else *pnElemOrdCount = nTotalOrdCount - *pnStartOrdinal + 1; return TRUE; } /************************************************************************/ /* TranslateGeometryElement() */ /************************************************************************/ OGRGeometry * OGROCILayer::TranslateGeometryElement( int *piElement, int nGType, int nDimension, int nEType, int nInterpretation, int nStartOrdinal, int nElemOrdCount ) { /* -------------------------------------------------------------------- */ /* Handle simple point. */ /* -------------------------------------------------------------------- */ if( nEType == 1 && nInterpretation == 1 ) { OGRPoint *poPoint = new OGRPoint(); double dfX, dfY, dfZ = 0.0; GetOrdinalPoint( nStartOrdinal, nDimension, &dfX, &dfY, &dfZ ); poPoint->setX( dfX ); poPoint->setY( dfY ); if( nDimension == 3 ) poPoint->setZ( dfZ ); return poPoint; } /* -------------------------------------------------------------------- */ /* Handle multipoint. */ /* -------------------------------------------------------------------- */ else if( nEType == 1 && nInterpretation > 1 ) { OGRMultiPoint *poMP = new OGRMultiPoint(); double dfX, dfY, dfZ = 0.0; int i; CPLAssert( nInterpretation == nElemOrdCount / nDimension ); for( i = 0; i < nInterpretation; i++ ) { GetOrdinalPoint( nStartOrdinal + i*nDimension, nDimension, &dfX, &dfY, &dfZ ); OGRPoint *poPoint = (nDimension == 3) ? new OGRPoint( dfX, dfY, dfZ ): new OGRPoint( dfX, dfY ); poMP->addGeometryDirectly( poPoint ); } return poMP; } /* -------------------------------------------------------------------- */ /* Discard orientations for oriented points. */ /* -------------------------------------------------------------------- */ else if( nEType == 1 && nInterpretation == 0 ) { CPLDebug( "OCI", "Ignoring orientations for oriented points." ); return nullptr; } /* -------------------------------------------------------------------- */ /* Handle line strings consisting of straight segments. */ /* -------------------------------------------------------------------- */ else if( nEType == 2 && nInterpretation == 1 ) { OGRLineString *poLS = new OGRLineString(); int nPointCount = nElemOrdCount / nDimension, i; poLS->setNumPoints( nPointCount ); for( i = 0; i < nPointCount; i++ ) { double dfX, dfY, dfZ = 0.0; GetOrdinalPoint( i*nDimension + nStartOrdinal, nDimension, &dfX, &dfY, &dfZ ); if (nDimension == 3) poLS->setPoint( i, dfX, dfY, dfZ ); else poLS->setPoint( i, dfX, dfY ); } return poLS; } /* -------------------------------------------------------------------- */ /* Handle line strings consisting of circular arcs. */ /* -------------------------------------------------------------------- */ else if( nEType == 2 && nInterpretation == 2 ) { OGRLineString *poLS = new OGRLineString(); int nPointCount = nElemOrdCount / nDimension, i; for( i = 0; i < nPointCount-2; i += 2 ) { double dfStartX, dfStartY, dfStartZ = 0.0; double dfMidX, dfMidY, dfMidZ = 0.0; double dfEndX, dfEndY, dfEndZ = 0.0; GetOrdinalPoint( i*nDimension + nStartOrdinal, nDimension, &dfStartX, &dfStartY, &dfStartZ ); GetOrdinalPoint( (i+1)*nDimension + nStartOrdinal, nDimension, &dfMidX, &dfMidY, &dfMidZ ); GetOrdinalPoint( (i+2)*nDimension + nStartOrdinal, nDimension, &dfEndX, &dfEndY, &dfEndZ ); OGROCIStrokeArcToOGRGeometry_Points( dfStartX, dfStartY, dfMidX, dfMidY, dfEndX, dfEndY, 6.0, FALSE, poLS ); } return poLS; } /* -------------------------------------------------------------------- */ /* Handle polygon rings. Treat curves as if they were */ /* linestrings. */ /* -------------------------------------------------------------------- */ else if( nEType % 1000 == 3 && nInterpretation == 1 ) { OGRLinearRing *poLS = new OGRLinearRing(); int nPointCount = nElemOrdCount / nDimension, i; poLS->setNumPoints( nPointCount ); for( i = 0; i < nPointCount; i++ ) { double dfX, dfY, dfZ = 0.0; GetOrdinalPoint( i*nDimension + nStartOrdinal, nDimension, &dfX, &dfY, &dfZ ); if (nDimension == 3) poLS->setPoint( i, dfX, dfY, dfZ ); else poLS->setPoint( i, dfX, dfY ); } return poLS; } /* -------------------------------------------------------------------- */ /* Handle polygon rings made of circular arcs. */ /* -------------------------------------------------------------------- */ else if( nEType % 1000 == 3 && nInterpretation == 2 ) { OGRLineString *poLS = new OGRLinearRing(); int nPointCount = nElemOrdCount / nDimension, i; for( i = 0; i < nPointCount-2; i += 2 ) { double dfStartX, dfStartY, dfStartZ = 0.0; double dfMidX, dfMidY, dfMidZ = 0.0; double dfEndX, dfEndY, dfEndZ = 0.0; GetOrdinalPoint( i*nDimension + nStartOrdinal, nDimension, &dfStartX, &dfStartY, &dfStartZ ); GetOrdinalPoint( (i+1)*nDimension + nStartOrdinal, nDimension, &dfMidX, &dfMidY, &dfMidZ ); GetOrdinalPoint( (i+2)*nDimension + nStartOrdinal, nDimension, &dfEndX, &dfEndY, &dfEndZ ); OGROCIStrokeArcToOGRGeometry_Points( dfStartX, dfStartY, dfMidX, dfMidY, dfEndX, dfEndY, 6.0, FALSE, poLS ); } return poLS; } /* -------------------------------------------------------------------- */ /* Handle rectangle definitions ... translate into a linear ring. */ /* -------------------------------------------------------------------- */ else if( nEType % 1000 == 3 && nInterpretation == 3 ) { OGRLinearRing *poLS = new OGRLinearRing(); double dfX1, dfY1, dfZ1 = 0.0; double dfX2, dfY2, dfZ2 = 0.0; GetOrdinalPoint( nStartOrdinal, nDimension, &dfX1, &dfY1, &dfZ1 ); GetOrdinalPoint( nStartOrdinal + nDimension, nDimension, &dfX2, &dfY2, &dfZ2 ); poLS->setNumPoints( 5 ); poLS->setPoint( 0, dfX1, dfY1, dfZ1 ); poLS->setPoint( 1, dfX2, dfY1, dfZ1 ); poLS->setPoint( 2, dfX2, dfY2, dfZ2 ); poLS->setPoint( 3, dfX1, dfY2, dfZ2 ); poLS->setPoint( 4, dfX1, dfY1, dfZ1 ); return poLS; } /* -------------------------------------------------------------------- */ /* Handle circle definitions ... translate into a linear ring. */ /* -------------------------------------------------------------------- */ else if( nEType % 100 == 3 && nInterpretation == 4 ) { OGRLinearRing *poLS = new OGRLinearRing(); double dfX1, dfY1, dfZ1 = 0.0; double dfX2, dfY2, dfZ2 = 0.0; double dfX3, dfY3, dfZ3 = 0.0; GetOrdinalPoint( nStartOrdinal, nDimension, &dfX1, &dfY1, &dfZ1 ); GetOrdinalPoint( nStartOrdinal + nDimension, nDimension, &dfX2, &dfY2, &dfZ2 ); GetOrdinalPoint( nStartOrdinal + nDimension*2, nDimension, &dfX3, &dfY3, &dfZ3 ); OGROCIStrokeArcToOGRGeometry_Points( dfX1, dfY1, dfX2, dfY2, dfX3, dfY3, 6.0, TRUE, poLS ); return poLS; } /* -------------------------------------------------------------------- */ /* Handle compound line strings and polygon rings. */ /* */ /* This is quite complicated since we need to consume several */ /* following elements, and merge the resulting geometries. */ /* -------------------------------------------------------------------- */ else if( nEType == 4 || nEType % 100 == 5 ) { int nSubElementCount = nInterpretation; OGRLineString *poLS; int nElemCount, nTotalOrdCount; OGROCISession *poSession = poDS->GetSession(); if( poSession->Failed( OCICollSize( poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_elem_info), &nElemCount), "OCICollSize(sdo_elem_info)" ) ) return nullptr; if( poSession->Failed( OCICollSize( poSession->hEnv, poSession->hError, (OCIColl*)(hLastGeom->sdo_ordinates),&nTotalOrdCount), "OCICollSize(sdo_ordinates)" ) ) return nullptr; if( nEType == 4 ) poLS = new OGRLineString(); else poLS = new OGRLinearRing(); for( *piElement += 3; nSubElementCount-- > 0; *piElement += 3 ) { LoadElementInfo( *piElement, nElemCount, nTotalOrdCount, &nEType, &nInterpretation, &nStartOrdinal, &nElemOrdCount ); // Adjust for repeated end point except for last element. if( nSubElementCount > 0 ) nElemOrdCount += nDimension; // translate element. OGRGeometry* poGeom = TranslateGeometryElement( piElement, nGType, nDimension, nEType, nInterpretation, nStartOrdinal - 1, nElemOrdCount ); OGRLineString* poElemLS = dynamic_cast<OGRLineString *>(poGeom); // Try to append to our aggregate linestring/ring if( poElemLS ) { if( poLS->getNumPoints() > 0 ) { CPLAssert( poElemLS->getX(0) == poLS->getX(poLS->getNumPoints()-1) && poElemLS->getY(0) ==poLS->getY(poLS->getNumPoints()-1)); poLS->addSubLineString( poElemLS, 1 ); } else poLS->addSubLineString( poElemLS, 0 ); } delete poGeom; } *piElement -= 3; return poLS; } /* -------------------------------------------------------------------- */ /* Otherwise it is apparently unsupported. */ /* -------------------------------------------------------------------- */ else { CPLDebug( "OCI", "Geometry with EType=%d, Interp=%d ignored.", nEType, nInterpretation ); } return nullptr; } /************************************************************************/ /* GetOrdinalPoint() */ /************************************************************************/ int OGROCILayer::GetOrdinalPoint( int iOrdinal, int nDimension, double *pdfX, double *pdfY, double *pdfZ ) { OGROCISession *poSession = poDS->GetSession(); boolean bExists; OCINumber *hNumber; OCICollGetElem( poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_ordinates), (sb4)iOrdinal+0, (boolean *)&bExists, (dvoid **)&hNumber, nullptr ); OCINumberToReal(poSession->hError, hNumber, (uword)sizeof(double), (dvoid *)pdfX); OCICollGetElem( poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_ordinates), (sb4)iOrdinal + 1, (boolean *)&bExists, (dvoid **)&hNumber, nullptr ); OCINumberToReal(poSession->hError, hNumber, (uword)sizeof(double), (dvoid *)pdfY); if( nDimension == 3 ) { OCICollGetElem( poSession->hEnv, poSession->hError, (OCIColl *)(hLastGeom->sdo_ordinates), (sb4)iOrdinal + 2, (boolean *)&bExists, (dvoid **)&hNumber, nullptr ); OCINumberToReal(poSession->hError, hNumber, (uword)sizeof(double), (dvoid *)pdfZ); } return TRUE; } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int OGROCILayer::TestCapability( const char * pszCap ) { if( EQUAL(pszCap,OLCRandomRead) ) return TRUE; else if( EQUAL(pszCap,OLCFastFeatureCount) ) return m_poFilterGeom == nullptr; else if( EQUAL(pszCap,OLCFastSpatialFilter) ) return TRUE; else if( EQUAL(pszCap,OLCTransactions) ) return TRUE; else return FALSE; } /************************************************************************/ /* LookupTableSRID() */ /* */ /* Note that the table name may also be prefixed by the owner */ /* with a dot separator. */ /************************************************************************/ int OGROCILayer::LookupTableSRID() { /* -------------------------------------------------------------------- */ /* If we don't have a geometry column, there isn't much point */ /* in trying. */ /* -------------------------------------------------------------------- */ if( pszGeomName == nullptr ) return -1; /* -------------------------------------------------------------------- */ /* Split out the owner if available. */ /* -------------------------------------------------------------------- */ const char *pszTableName = GetLayerDefn()->GetName(); char *pszOwner = nullptr; if( strstr(pszTableName,".") != nullptr ) { pszOwner = CPLStrdup(pszTableName); pszTableName = strstr(pszTableName,".") + 1; *(strstr(pszOwner,".")) = '\0'; } /* -------------------------------------------------------------------- */ /* Build our query command. */ /* -------------------------------------------------------------------- */ OGROCIStringBuf oCommand; oCommand.Append( "SELECT SRID FROM ALL_SDO_GEOM_METADATA " "WHERE TABLE_NAME = UPPER(:table_name) AND COLUMN_NAME = UPPER(:geometry_name)" ); if( pszOwner != nullptr ) { oCommand.Append( " AND OWNER = :owner"); } /* -------------------------------------------------------------------- */ /* Execute query command. */ /* -------------------------------------------------------------------- */ OGROCIStatement oGetTables( poDS->GetSession() ); int nSRID = -1; if( oGetTables.Prepare( oCommand.GetString() ) != CE_None ) return nSRID; oGetTables.BindString(":table_name", pszTableName); oGetTables.BindString(":geometry_name", pszGeomName); if( pszOwner != nullptr ) { oGetTables.BindString(":owner", pszOwner); CPLFree( pszOwner ); } if( oGetTables.Execute( nullptr ) == CE_None ) { char **papszRow = oGetTables.SimpleFetchRow(); if( papszRow != nullptr && papszRow[0] != nullptr ) nSRID = atoi( papszRow[0] ); } return nSRID; } /************************************************************************/ /* GetFIDColumn() */ /************************************************************************/ const char *OGROCILayer::GetFIDColumn() { if( pszFIDName != nullptr ) return pszFIDName; else return ""; } /************************************************************************/ /* GetGeometryColumn() */ /************************************************************************/ const char *OGROCILayer::GetGeometryColumn() { if( pszGeomName != nullptr ) return pszGeomName; else return ""; }
38.674157
109
0.415667
[ "geometry" ]
f6c8845ab366e4d96a64da9e8483934e850d79ef
5,512
cpp
C++
chemfiles-3fc67b1/tests/files/netcdf-file.cpp
ShoubhikRaj/water-order
51626dd5755b57b38fd456c7a6be4ecd8313a69a
[ "BSD-3-Clause" ]
116
2015-11-05T01:18:13.000Z
2022-02-20T06:33:47.000Z
chemfiles-3fc67b1/tests/files/netcdf-file.cpp
ShoubhikRaj/water-order
51626dd5755b57b38fd456c7a6be4ecd8313a69a
[ "BSD-3-Clause" ]
307
2015-10-08T09:22:46.000Z
2022-03-28T13:42:51.000Z
tests/files/netcdf-file.cpp
Luthaf/chemfiles
069382c27597dc7d5bc2d72f2887d049caae2834
[ "BSD-3-Clause" ]
57
2015-10-22T06:45:40.000Z
2022-03-27T17:33:05.000Z
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include "catch.hpp" #include "chemfiles.hpp" #include "chemfiles/files/NcFile.hpp" #include "helpers.hpp" using namespace chemfiles; TEST_CASE("Read a NetCDF file") { SECTION("Float variables") { NcFile file("data/netcdf/water.nc", File::READ); CHECK(file.global_attribute("Conventions") == "AMBER"); // Usual dimmensions CHECK(file.dimension("atom") == 297); // Unlimited dimension CHECK(file.dimension("frame") == 100); CHECK(file.variable<nc::NcFloat>("cell_lengths").string_attribute("units") == "Angstrom"); auto var = file.variable<nc::NcFloat>("coordinates"); auto dims = var.dimmensions(); CHECK(dims.size() == 3); CHECK(dims[0] == 100); CHECK(dims[1] == 297); CHECK(dims[2] == 3); auto EPS = 1e-5f; auto positions = var.get({0, 0, 0}, {1, 297, 3}); CHECK(std::abs(positions[0] - 0.4172191f) < EPS); CHECK(std::abs(positions[1] - 8.303366f) < EPS); CHECK(std::abs(positions[2] - 11.73717f) < EPS); } SECTION("Double variables") { NcFile file("data/netcdf/water.ncrst", File::READ); CHECK(file.global_attribute("Conventions") == "AMBERRESTART"); // Usual dimmensions CHECK(file.dimension("atom") == 297); CHECK(file.variable<nc::NcDouble>("cell_lengths").string_attribute("units") == "angstrom"); auto var = file.variable<nc::NcDouble>("coordinates"); auto dims = var.dimmensions(); CHECK(dims.size() == 2); CHECK(dims[0] == 297); CHECK(dims[1] == 3); auto EPS = 1e-5; auto positions = var.get({0, 0}, {297, 3}); CHECK(std::abs(positions[0] - 0.4172191) < EPS); CHECK(std::abs(positions[1] - 8.303366) < EPS); CHECK(std::abs(positions[2] - 11.73717) < EPS); } } TEST_CASE("Errors in NetCDF files") { SECTION("Float variables") { NcFile file("data/netcdf/water.nc", File::READ); CHECK_THROWS_WITH(file.global_attribute("FOO"), "can not read attribute 'FOO': NetCDF: Attribute not found"); CHECK_THROWS_WITH(file.dimension("FOO"), "missing dimmension 'FOO' in NetCDF file"); CHECK_THROWS_WITH( file.variable<nc::NcFloat>("cell_lengths").string_attribute("Bar"), "can not read attribute id for attribute 'Bar': NetCDF: Attribute not found"); CHECK_THROWS_WITH(file.variable<nc::NcFloat>("FOO"), "can not get variable id for 'FOO: NetCDF: Variable not found"); } SECTION("Double variables") { NcFile file("data/netcdf/water.ncrst", File::READ); CHECK_THROWS_WITH(file.global_attribute("FOO"), "can not read attribute 'FOO': NetCDF: Attribute not found"); CHECK_THROWS_WITH(file.dimension("FOO"), "missing dimmension 'FOO' in NetCDF file"); CHECK_THROWS_WITH( file.variable<nc::NcDouble>("cell_lengths").string_attribute("Bar"), "can not read attribute id for attribute 'Bar': NetCDF: Attribute not found"); CHECK_THROWS_WITH(file.variable<nc::NcDouble>("FOO"), "can not get variable id for 'FOO: NetCDF: Variable not found"); } } TEST_CASE("Write NetCDF files") { auto tmpfile = NamedTempPath(".nc"); { NcFile file(tmpfile, File::WRITE); file.set_nc_mode(NcFile::DEFINE); file.add_global_attribute("global", "global.value"); file.add_dimension("infinite"); file.add_dimension("finite", 42); auto variable = file.add_variable<nc::NcFloat>("variable", "infinite", "finite"); variable.add_string_attribute("attribute", "hello"); auto variable_d = file.add_variable<nc::NcDouble>("variable_d", "infinite", "finite"); variable_d.add_string_attribute("attribute", "world"); file.set_nc_mode(NcFile::DATA); variable.add({0, 0}, {1, 42}, std::vector<float>(42, 38.2f)); variable_d.add({0, 0}, {1, 42}, std::vector<double>(42, 37.4)); } { NcFile file(tmpfile, File::APPEND); auto variable = file.variable<nc::NcFloat>("variable"); variable.add({1, 0}, {1, 42}, std::vector<float>(42, 55.1f)); auto variable_d = file.variable<nc::NcDouble>("variable_d"); variable_d.add({1, 0}, {1, 42}, std::vector<double>(42, 66.3)); } { NcFile file(tmpfile, File::READ); CHECK(file.global_attribute("global") == "global.value"); CHECK(file.dimension("infinite") == 2); CHECK(file.dimension("finite") == 42); CHECK(file.variable_exists("variable")); CHECK(file.variable_exists("variable_d")); CHECK_FALSE(file.variable_exists("bar")); auto variable = file.variable<nc::NcFloat>("variable"); CHECK(variable.string_attribute("attribute") == "hello"); CHECK(variable.get({0, 0}, {1, 42}) == std::vector<float>(42, 38.2f)); CHECK(variable.get({1, 0}, {1, 42}) == std::vector<float>(42, 55.1f)); auto variable_d = file.variable<nc::NcDouble>("variable_d"); CHECK(variable_d.string_attribute("attribute") == "world"); CHECK(variable_d.get({0, 0}, {1, 42}) == std::vector<double>(42, 37.4)); CHECK(variable_d.get({1, 0}, {1, 42}) == std::vector<double>(42, 66.3)); } }
40.529412
99
0.599782
[ "vector" ]
f6d2207831192c909bc52606da967436eb437ce5
2,620
cpp
C++
apps/hls_examples/camera_ready_synthesis/app_files/big_apps_8_shifts/conv2d_b2b/tb.cpp
dillonhuff/Halide-HLS
e9f4c3ac7915e5a52f211ce65004ae17890515a0
[ "MIT" ]
1
2020-06-18T16:51:39.000Z
2020-06-18T16:51:39.000Z
apps/hls_examples/camera_ready_synthesis/app_files/big_apps_8_shifts/conv2d_b2b/tb.cpp
dillonhuff/Halide-HLS
e9f4c3ac7915e5a52f211ce65004ae17890515a0
[ "MIT" ]
null
null
null
apps/hls_examples/camera_ready_synthesis/app_files/big_apps_8_shifts/conv2d_b2b/tb.cpp
dillonhuff/Halide-HLS
e9f4c3ac7915e5a52f211ce65004ae17890515a0
[ "MIT" ]
1
2020-03-18T00:43:22.000Z
2020-03-18T00:43:22.000Z
#include <iostream> #include <vector> #include <fstream> #include "json.h" #include "hls_target.h" using namespace std; using namespace nlohmann; typedef Stencil<uint8_t, 1, 1> stencil; typedef AxiPackedStencil<uint8_t, 1, 1> axi_stencil; template<typename T> vector<T> load_vals(const std::string& file) { cout << "Opening file: " << file << endl; ifstream infile(file); json j; j << infile; cout << "read in file" << endl; vector<T> vals; for (auto e : j) { vals.push_back(e); } return vals; } int main(const int argc, const char** argv) { assert(argc == 3); string in_file = argv[1]; string out_file = argv[2]; int in_rows = 1080; int in_cols = 1920; int in_pixels = in_rows*in_cols; int out_rows = in_rows - 2 - 1; int out_cols = in_cols - 2 - 1; int out_delay = in_cols*3 + 3; vector<uint8_t> vals = load_vals<uint8_t>(in_file); assert(in_pixels == vals.size()); hls::stream<axi_stencil> ins, outs; for (auto v : vals) { stencil a; a(0, 0) = v; axi_stencil as; as = a; ins.write(as); } hls_target(ins, outs); vector<uint8_t> correct_outputs = load_vals<uint8_t>(out_file); //cout << "reading dense outputs" << endl; //vector<uint8_t> dense_correct_outputs; //int ind = 0; //for (auto v : correct_outputs) { //if (v != 253) { //dense_correct_outputs.push_back(v); //cout << v << " at: " << ind << endl; //} else { //cout << "253 at: " << ind << endl; //} //ind++; //} ////for (int i = 0; i < correct_outputs.size(); i++) { ////if (correct_outputs.at(i) != 253) { ////dense_correct_outputs.push_back(correct_outputs.at(i)); //////cout << "First valid output at: " << i << " = " << correct_outputs.at(i) << endl; //////break; ////} ////} //int out_size = out_rows*out_cols; //cout << "out size = " << out_size << endl; //cout << "correct size = " << dense_correct_outputs.size() << endl; //assert(dense_correct_outputs.size() == out_size); //assert(false); for (int r = 0; r < out_rows; r++) { for (int c = 0; c < out_cols; c++) { uint8_t actual = outs.read().value; int pos = out_delay + r*in_cols + c; uint8_t expected = correct_outputs.at(pos); if (expected != 253) { cout << "r, c = " << r << ", " << c << endl; cout << "pos = " << pos << endl; cout << "actual(" << c << ", " << r << ") : " << (int) actual << endl; cout << "expected(" << c << ", " << r << ") : " << (int) expected << endl; assert(expected == actual); } } } return 0; }
23.603604
93
0.554962
[ "vector" ]
f6d3d1b1ae8970f0542e50c906c49fb85e3c0acd
7,284
cpp
C++
lib/Crypto/importkeyrequest.cpp
mkenttala/sailfish-secrets
600ca62f76a0d537e4fefa80b6e69b77f0b3dac5
[ "BSD-3-Clause" ]
27
2017-11-02T11:18:47.000Z
2021-06-29T10:40:34.000Z
lib/Crypto/importkeyrequest.cpp
mkenttala/sailfish-secrets
600ca62f76a0d537e4fefa80b6e69b77f0b3dac5
[ "BSD-3-Clause" ]
149
2017-11-09T09:31:52.000Z
2021-12-24T09:27:19.000Z
lib/Crypto/importkeyrequest.cpp
mkenttala/sailfish-secrets
600ca62f76a0d537e4fefa80b6e69b77f0b3dac5
[ "BSD-3-Clause" ]
16
2017-11-09T08:23:22.000Z
2021-06-18T06:15:48.000Z
/* * Copyright (C) 2018 Jolla Ltd. * Contact: Chris Adams <chris.adams@jollamobile.com> * All rights reserved. * BSD 3-Clause License, see LICENSE. */ #include "Crypto/importkeyrequest_p.h" #include "Crypto/cryptomanager.h" #include "Crypto/cryptomanager_p.h" #include "Crypto/serialization_p.h" #include <QtDBus/QDBusPendingReply> #include <QtDBus/QDBusPendingCallWatcher> using namespace Sailfish::Crypto; ImportKeyRequestPrivate::ImportKeyRequestPrivate() : m_status(Request::Inactive) { } /*! \class ImportKeyRequest \brief Allows a client request that the system crypto service import a key from some data. \inmodule SailfishCrypto This key will not be stored securely by the crypto daemon, but instead will be returned in its complete form to the caller. */ /*! \brief Constructs a new ImportKeyRequest object with the given \a parent. */ ImportKeyRequest::ImportKeyRequest(QObject *parent) : Request(parent) , d_ptr(new ImportKeyRequestPrivate) { } /*! \brief Destroys the ImportKeyRequest */ ImportKeyRequest::~ImportKeyRequest() { } /*! \brief Returns the name of the crypto plugin which the client wishes to perform the key import operation */ QString ImportKeyRequest::cryptoPluginName() const { Q_D(const ImportKeyRequest); return d->m_cryptoPluginName; } /*! \brief Sets the name of the crypto plugin which the client wishes to perform the key import operation to \a pluginName */ void ImportKeyRequest::setCryptoPluginName(const QString &pluginName) { Q_D(ImportKeyRequest); if (d->m_status != Request::Active && d->m_cryptoPluginName != pluginName) { d->m_cryptoPluginName = pluginName; if (d->m_status == Request::Finished) { d->m_status = Request::Inactive; emit statusChanged(); } emit cryptoPluginNameChanged(); } } /*! \brief Returns the user input parameters which should be used when requesting the input data from the user If specified, the user may be prompted to enter a pass phrase needed to decrypt the imported key. */ Sailfish::Crypto::InteractionParameters ImportKeyRequest::interactionParameters() const { Q_D(const ImportKeyRequest); return d->m_uiParams; } /*! \brief Sets the user input parameters which should be used when requesting the input data from the user to \a uiParams */ void ImportKeyRequest::setInteractionParameters( const Sailfish::Crypto::InteractionParameters &uiParams) { Q_D(ImportKeyRequest); if (d->m_status != Request::Active && d->m_uiParams != uiParams) { d->m_uiParams = uiParams; if (d->m_status == Request::Finished) { d->m_status = Request::Inactive; emit statusChanged(); } emit interactionParametersChanged(); } } /*! \brief Returns the data which should be imported as a key. */ QByteArray ImportKeyRequest::data() const { Q_D(const ImportKeyRequest); return d->m_data; } /*! \brief Sets the \a data which should be imported. */ void ImportKeyRequest::setData(const QByteArray &data) { Q_D(ImportKeyRequest); if (d->m_status != Request::Active && d->m_data != data) { d->m_data = data; if (d->m_status == Request::Finished) { d->m_status = Request::Inactive; emit statusChanged(); } emit dataChanged(); } } /*! \brief Returns the imported key Note: this value is only valid if the status of the request is Request::Finished. */ Key ImportKeyRequest::importedKey() const { Q_D(const ImportKeyRequest); return d->m_importedKey; } Request::Status ImportKeyRequest::status() const { Q_D(const ImportKeyRequest); return d->m_status; } Result ImportKeyRequest::result() const { Q_D(const ImportKeyRequest); return d->m_result; } QVariantMap ImportKeyRequest::customParameters() const { Q_D(const ImportKeyRequest); return d->m_customParameters; } void ImportKeyRequest::setCustomParameters(const QVariantMap &params) { Q_D(ImportKeyRequest); if (d->m_customParameters != params) { d->m_customParameters = params; if (d->m_status == Request::Finished) { d->m_status = Request::Inactive; emit statusChanged(); } emit customParametersChanged(); } } CryptoManager *ImportKeyRequest::manager() const { Q_D(const ImportKeyRequest); return d->m_manager.data(); } void ImportKeyRequest::setManager(CryptoManager *manager) { Q_D(ImportKeyRequest); if (d->m_manager.data() != manager) { d->m_manager = manager; emit managerChanged(); } } void ImportKeyRequest::startRequest() { Q_D(ImportKeyRequest); if (d->m_status != Request::Active && !d->m_manager.isNull()) { d->m_status = Request::Active; emit statusChanged(); if (d->m_result.code() != Result::Pending) { d->m_result = Result(Result::Pending); emit resultChanged(); } QDBusPendingReply<Result, Key> reply = d->m_manager->d_ptr->importKey(d->m_data, d->m_uiParams, d->m_customParameters, d->m_cryptoPluginName); if (reply.isError()) { d->m_status = Request::Finished; d->m_result = Result(Result::CryptoManagerNotInitializedError, reply.error().message()); emit statusChanged(); emit resultChanged(); } else if (reply.isFinished() // work around a bug in QDBusAbstractInterface / QDBusConnection... && reply.argumentAt<0>().code() != Sailfish::Crypto::Result::Succeeded) { d->m_status = Request::Finished; d->m_result = reply.argumentAt<0>(); d->m_importedKey = reply.argumentAt<1>(); emit statusChanged(); emit resultChanged(); emit importedKeyChanged(); } else { d->m_watcher.reset(new QDBusPendingCallWatcher(reply)); connect(d->m_watcher.data(), &QDBusPendingCallWatcher::finished, [this] { QDBusPendingCallWatcher *watcher = this->d_ptr->m_watcher.take(); QDBusPendingReply<Result, Key> reply = *watcher; this->d_ptr->m_status = Request::Finished; if (reply.isError()) { this->d_ptr->m_result = Result(Result::CryptoManagerNotInitializedError, reply.error().message()); this->d_ptr->m_importedKey = Key(); } else { this->d_ptr->m_result = reply.argumentAt<0>(); this->d_ptr->m_importedKey = reply.argumentAt<1>(); } watcher->deleteLater(); emit this->statusChanged(); emit this->resultChanged(); emit this->importedKeyChanged(); }); } } } void ImportKeyRequest::waitForFinished() { Q_D(ImportKeyRequest); if (d->m_status == Request::Active && !d->m_watcher.isNull()) { d->m_watcher->waitForFinished(); } }
29.370968
120
0.623421
[ "object" ]
f6d6a541d430ef83b495e8787d22f75f39db3a86
10,656
cc
C++
tensorflow/compiler/mlir/tfrt/jit/transforms/tf_cpurt_math_approximation.cc
brinkqiang/tensorflow
a9643a6a04dbc29e79f2026ec5fc501259b8c53c
[ "Apache-2.0" ]
9
2021-11-06T11:09:48.000Z
2021-12-12T04:52:29.000Z
tensorflow/compiler/mlir/tfrt/jit/transforms/tf_cpurt_math_approximation.cc
brinkqiang/tensorflow
a9643a6a04dbc29e79f2026ec5fc501259b8c53c
[ "Apache-2.0" ]
6
2019-04-13T05:50:17.000Z
2021-11-16T20:00:06.000Z
tensorflow/compiler/mlir/tfrt/jit/transforms/tf_cpurt_math_approximation.cc
brinkqiang/tensorflow
a9643a6a04dbc29e79f2026ec5fc501259b8c53c
[ "Apache-2.0" ]
1
2021-08-23T19:54:37.000Z
2021-08-23T19:54:37.000Z
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" #include "mlir/Dialect/Math/IR/Math.h" #include "mlir/Dialect/Vector/VectorOps.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "llvm/ADT/ArrayRef.h" #include "tensorflow/compiler/mlir/tfrt/jit/transforms/tf_cpurt_passes.h" namespace tensorflow { namespace { #define GEN_PASS_CLASSES #include "tensorflow/compiler/mlir/tfrt/jit/transforms/tf_cpurt_passes.h.inc" using ::llvm::ArrayRef; using ::llvm::SmallVector; using ::mlir::ImplicitLocOpBuilder; using ::mlir::LogicalResult; using ::mlir::OpRewritePattern; using ::mlir::PatternRewriter; using ::mlir::RewritePatternSet; using ::mlir::Type; using ::mlir::Value; using ::mlir::VectorType; namespace arith = ::mlir::arith; namespace math = ::mlir::math; namespace vector = ::mlir::vector; using TypePredicate = ::llvm::function_ref<bool(Type)>; // Returns vector shape if the element type is matching the predicate (scalars // that do match the predicate have shape equal to `{1}`). static llvm::Optional<SmallVector<int64_t, 2>> vectorShape(Type type, TypePredicate pred) { // If the type matches the predicate then its shape is `{1}`. if (pred(type)) return SmallVector<int64_t, 2>{1}; // Otherwise check if the type is a vector type. auto vectorType = type.dyn_cast<VectorType>(); if (vectorType && pred(vectorType.getElementType())) { return llvm::to_vector<2>(vectorType.getShape()); } return llvm::None; } // Returns vector shape of the type. If the type is a scalar returns `1`. static SmallVector<int64_t, 2> vectorShape(Type type) { auto vectorType = type.dyn_cast<VectorType>(); return vectorType ? llvm::to_vector<2>(vectorType.getShape()) : SmallVector<int64_t, 2>{1}; } // Returns vector element type. If the type is a scalar returns the argument. static Type elementType(Type type) { auto vectorType = type.dyn_cast<VectorType>(); return vectorType ? vectorType.getElementType() : type; } static bool isF32(Type type) { return type.isF32(); } //----------------------------------------------------------------------------// // Broadcast scalar types and values into vector types and values. //----------------------------------------------------------------------------// // Returns true if shape != {1}. static bool isNonScalarShape(ArrayRef<int64_t> shape) { return shape.size() > 1 || shape[0] > 1; } // Broadcasts scalar type into vector type (iff shape is non-scalar). static Type broadcast(Type type, ArrayRef<int64_t> shape) { assert(!type.isa<VectorType>() && "must be scalar type"); return isNonScalarShape(shape) ? VectorType::get(shape, type) : type; } // Broadcasts scalar value into vector (iff shape is non-scalar). static Value broadcast(ImplicitLocOpBuilder &builder, Value value, ArrayRef<int64_t> shape) { assert(!value.getType().isa<VectorType>() && "must be scalar value"); auto type = broadcast(value.getType(), shape); return isNonScalarShape(shape) ? builder.create<vector::BroadcastOp>(type, value) : value; } //----------------------------------------------------------------------------// // Helper functions to create constants. //----------------------------------------------------------------------------// static Value f32Cst(ImplicitLocOpBuilder &builder, float value) { return builder.create<arith::ConstantOp>(builder.getF32FloatAttr(value)); } static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) { return builder.create<arith::ConstantOp>(builder.getI32IntegerAttr(value)); } //----------------------------------------------------------------------------// // Helper functions to build math function approximations. //----------------------------------------------------------------------------// static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) { return builder.create<mlir::SelectOp>( builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, a, b), a, b); } static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) { return builder.create<mlir::SelectOp>( builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, a, b), a, b); } static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, Value upperBound) { return max(builder, min(builder, value, upperBound), lowerBound); } // Eigen's implementation of ldexp. // ldexp(x, exp) = x * 2^exp // Set e = min(max(exp, -278), 278) // b = floor(e/4) // Then out = ((((x * 2^(b)) * 2^(b)) * 2^(b)) * 2^(e-3*b)) static Value ldexp(ImplicitLocOpBuilder &builder, Value x, Value exp) { assert(isF32(elementType(x.getType())) && "argument x must be f32 type"); assert(isF32(elementType(exp.getType())) && "argument exp must be f32 type"); auto shape = vectorShape(x.getType()); auto exp_shape = vectorShape(exp.getType()); assert(shape == exp_shape && "x and exp must be of equal shape"); auto f32Vec = broadcast(builder.getF32Type(), shape); auto i32Vec = broadcast(builder.getI32Type(), shape); auto bcast = [&](Value value) -> Value { return broadcast(builder, value, shape); }; auto mulf = [&](Value a, Value b) -> Value { return builder.create<arith::MulFOp>(a, b); }; auto subi = [&](Value a, Value b) -> Value { return builder.create<arith::SubIOp>(a, b); }; auto shli = [&](Value a, Value pos) -> Value { return builder.create<arith::ShLIOp>(a, pos); }; Value cstMantBitsI = bcast(i32Cst(builder, 23)); Value cstMaxExponent = bcast(f32Cst(builder, 278.0f)); Value cstMinExponent = bcast(f32Cst(builder, -278.0f)); Value cstBiasI = bcast(i32Cst(builder, 127)); Value cst2I = bcast(i32Cst(builder, 2)); Value e = clamp(builder, exp, cstMinExponent, cstMaxExponent); Value eI = builder.create<arith::FPToSIOp>(i32Vec, e); Value bI = builder.create<arith::ShRSIOp>(eI, cst2I); Value biasedBI = builder.create<arith::AddIOp>(bI, cstBiasI); Value c = builder.create<arith::BitcastOp>( f32Vec, shli(biasedBI, cstMantBitsI)); // 2^b Value out = mulf(mulf(mulf(x, c), c), c); // x * 2^(3b) bI = subi(subi(subi(eI, bI), bI), bI); // e - 3b biasedBI = builder.create<arith::AddIOp>(bI, cstBiasI); // 2^(e - 3b) c = builder.create<arith::BitcastOp>(f32Vec, shli(biasedBI, cstMantBitsI)); out = mulf(out, c); return out; } struct EigenExpApproximation : public OpRewritePattern<math::ExpOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(math::ExpOp op, PatternRewriter &rewriter) const final; }; LogicalResult EigenExpApproximation::matchAndRewrite( math::ExpOp op, PatternRewriter &rewriter) const { auto shape = vectorShape(op.operand().getType(), isF32); if (!shape.hasValue()) return rewriter.notifyMatchFailure(op, "unsupported operand type"); ImplicitLocOpBuilder builder(op->getLoc(), rewriter); auto addf = [&](Value a, Value b) -> Value { return builder.create<arith::AddFOp>(a, b); }; auto bcast = [&](Value value) -> Value { return broadcast(builder, value, *shape); }; auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); }; auto fma = [&](Value a, Value b, Value c) { return builder.create<math::FmaOp>(a, b, c); }; auto mulf = [&](Value a, Value b) -> Value { return builder.create<arith::MulFOp>(a, b); }; Value cstOne = bcast(f32Cst(builder, 1.0f)); Value cstHalf = bcast(f32Cst(builder, 0.5f)); Value cstExpHi = bcast(f32Cst(builder, 88.723f)); Value cstExpLo = bcast(f32Cst(builder, -88.723f)); Value cstCephesLog2E = bcast(f32Cst(builder, 1.44269504088896341f)); Value cstCephesExpP0 = bcast(f32Cst(builder, 1.9875691500E-4f)); Value cstCephesExpP1 = bcast(f32Cst(builder, 1.3981999507E-3f)); Value cstCephesExpP2 = bcast(f32Cst(builder, 8.3334519073E-3f)); Value cstCephesExpP3 = bcast(f32Cst(builder, 4.1665795894E-2f)); Value cstCephesExpP4 = bcast(f32Cst(builder, 1.6666665459E-1f)); Value cstCephesExpP5 = bcast(f32Cst(builder, 5.0000001201E-1f)); Value x = clamp(builder, op.operand(), cstExpLo, cstExpHi); Value m = floor(fma(x, cstCephesLog2E, cstHalf)); Value cstCephesExpC1 = bcast(f32Cst(builder, -0.693359375f)); Value cstCephesExpC2 = bcast(f32Cst(builder, 2.12194440e-4f)); Value r = fma(m, cstCephesExpC1, x); r = fma(m, cstCephesExpC2, r); Value r2 = mulf(r, r); Value r3 = mulf(r2, r); Value y = fma(cstCephesExpP0, r, cstCephesExpP1); Value y1 = fma(cstCephesExpP3, r, cstCephesExpP4); Value y2 = addf(r, cstOne); y = fma(y, r, cstCephesExpP2); y1 = fma(y1, r, cstCephesExpP5); y = fma(y, r3, y1); y = fma(y, r2, y2); Value ret = max(builder, ldexp(builder, y, m), op.operand()); rewriter.replaceOp(op, ret); return mlir::success(); } static void populateMathApproximationPatterns(RewritePatternSet &patterns, ArrayRef<std::string> oplist) { for (const std::string &op : oplist) { if (op == "exp" || op == "all") patterns.add<EigenExpApproximation>(patterns.getContext()); } } struct MathApproximationPass : public MathApproximationBase<MathApproximationPass> { explicit MathApproximationPass(ArrayRef<std::string> approx_oplist) { this->oplist = approx_oplist; } void runOnFunction() override; }; void MathApproximationPass::runOnFunction() { mlir::OwningRewritePatternList patterns(&getContext()); populateMathApproximationPatterns(patterns, oplist); if (failed(mlir::applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) signalPassFailure(); } } // namespace std::unique_ptr<mlir::FunctionPass> CreateMathApproximationPass( ArrayRef<std::string> oplist) { return std::make_unique<MathApproximationPass>(oplist); } } // namespace tensorflow
38.057143
80
0.653622
[ "shape", "vector" ]
f6d79dc0348c558f0278d3763e45bf6b92dabba2
656
cpp
C++
coding/codeforces/721_A.cpp
aguilarpgc/coding-preparation
00547d499adda5a6cdbe90acae8a0e88a2d8d69e
[ "MIT" ]
4
2021-04-11T23:55:54.000Z
2022-03-07T20:06:33.000Z
coding/codeforces/721_A.cpp
aguilarpgc/coding-preparation
00547d499adda5a6cdbe90acae8a0e88a2d8d69e
[ "MIT" ]
null
null
null
coding/codeforces/721_A.cpp
aguilarpgc/coding-preparation
00547d499adda5a6cdbe90acae8a0e88a2d8d69e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> int main() { int n; scanf("%d", &n); char s[n]; scanf("%s",s); std::vector<int> v; int count = 0; for (int i=0; i<n; i++) { if(s[i] == 'B') { count++; } else { if (count > 0) { v.push_back(count); } count = 0; } } if (count > 0) { v.push_back(count); } if(v.empty()) { printf("0\n"); } else { printf("%lu\n", v.size()); for(auto g: v) { printf("%d\n", g); } } return 0; }
15.255814
35
0.330793
[ "vector" ]
f6d9e780b63d20de7fe864a1de0213e9ed55c3f9
23,516
cpp
C++
SpatialGDK/Source/SpatialGDKEditor/Private/SchemaGenerator/SchemaGenerator.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
363
2018-07-30T12:57:42.000Z
2022-03-25T14:30:28.000Z
SpatialGDK/Source/SpatialGDKEditor/Private/SchemaGenerator/SchemaGenerator.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
1,634
2018-07-30T14:30:25.000Z
2022-03-03T01:55:15.000Z
SpatialGDK/Source/SpatialGDKEditor/Private/SchemaGenerator/SchemaGenerator.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
153
2018-07-31T13:45:02.000Z
2022-03-03T05:20:24.000Z
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "SchemaGenerator.h" #include "Algo/Reverse.h" #include "Engine/BlueprintGeneratedClass.h" #include "Engine/SCS_Node.h" #include "UObject/TextProperty.h" #include "Interop/SpatialClassInfoManager.h" #include "SpatialGDKSettings.h" #include "Utils/CodeWriter.h" #include "Utils/ComponentIdGenerator.h" #include "Utils/DataTypeUtilities.h" #include "Utils/GDKPropertyMacros.h" #include "SpatialGDKEditorSchemaGenerator.h" using namespace SpatialGDKEditor::Schema; DEFINE_LOG_CATEGORY(LogSchemaGenerator); namespace { ESchemaComponentType PropertyGroupToSchemaComponentType(EReplicatedPropertyGroup Group) { if (Group == REP_MultiClient) { return SCHEMA_Data; } else if (Group == REP_SingleClient) { return SCHEMA_OwnerOnly; } else { checkNoEntry(); return SCHEMA_Invalid; } } // Given a RepLayout cmd type (a data type supported by the replication system). Generates the corresponding // type used in schema. FString PropertyToSchemaType(GDK_PROPERTY(Property)* Property) { FString DataType; if (Property->IsA(GDK_PROPERTY(StructProperty)::StaticClass())) { GDK_PROPERTY(StructProperty)* StructProp = GDK_CASTFIELD<GDK_PROPERTY(StructProperty)>(Property); UScriptStruct* Struct = StructProp->Struct; DataType = TEXT("bytes"); } else if (Property->IsA(GDK_PROPERTY(BoolProperty)::StaticClass())) { DataType = TEXT("bool"); } else if (Property->IsA(GDK_PROPERTY(FloatProperty)::StaticClass())) { DataType = TEXT("float"); } else if (Property->IsA(GDK_PROPERTY(DoubleProperty)::StaticClass())) { DataType = TEXT("double"); } else if (Property->IsA(GDK_PROPERTY(Int8Property)::StaticClass())) { DataType = TEXT("int32"); } else if (Property->IsA(GDK_PROPERTY(Int16Property)::StaticClass())) { DataType = TEXT("int32"); } else if (Property->IsA(GDK_PROPERTY(IntProperty)::StaticClass())) { DataType = TEXT("int32"); } else if (Property->IsA(GDK_PROPERTY(Int64Property)::StaticClass())) { DataType = TEXT("int64"); } else if (Property->IsA(GDK_PROPERTY(ByteProperty)::StaticClass())) { DataType = TEXT("uint32"); // uint8 not supported in schema. } else if (Property->IsA(GDK_PROPERTY(UInt16Property)::StaticClass())) { DataType = TEXT("uint32"); } else if (Property->IsA(GDK_PROPERTY(UInt32Property)::StaticClass())) { DataType = TEXT("uint32"); } else if (Property->IsA(GDK_PROPERTY(UInt64Property)::StaticClass())) { DataType = TEXT("uint64"); } else if (Property->IsA(GDK_PROPERTY(NameProperty)::StaticClass()) || Property->IsA(GDK_PROPERTY(StrProperty)::StaticClass()) || Property->IsA(GDK_PROPERTY(TextProperty)::StaticClass())) { DataType = TEXT("string"); } else if (Property->IsA(GDK_PROPERTY(ObjectPropertyBase)::StaticClass())) { DataType = TEXT("UnrealObjectRef"); } else if (Property->IsA(GDK_PROPERTY(ArrayProperty)::StaticClass())) { DataType = PropertyToSchemaType(GDK_CASTFIELD<GDK_PROPERTY(ArrayProperty)>(Property)->Inner); DataType = FString::Printf(TEXT("list<%s>"), *DataType); } else if (Property->IsA(GDK_PROPERTY(EnumProperty)::StaticClass())) { DataType = GetEnumDataType(GDK_CASTFIELD<GDK_PROPERTY(EnumProperty)>(Property)); } else { DataType = TEXT("bytes"); } return DataType; } void WriteSchemaRepField(FCodeWriter& Writer, const TSharedPtr<FUnrealProperty> RepProp, const int FieldCounter) { Writer.Printf("{0} {1} = {2};", *PropertyToSchemaType(RepProp->Property), *SchemaFieldName(RepProp), FieldCounter ); } void WriteSchemaHandoverField(FCodeWriter& Writer, const TSharedPtr<FUnrealProperty> HandoverProp, const int FieldCounter) { Writer.Printf("{0} {1} = {2};", *PropertyToSchemaType(HandoverProp->Property), *SchemaFieldName(HandoverProp), FieldCounter ); } // Generates schema for a statically attached subobject on an Actor. FActorSpecificSubobjectSchemaData GenerateSchemaForStaticallyAttachedSubobject(FCodeWriter& Writer, FComponentIdGenerator& IdGenerator, FString PropertyName, TSharedPtr<FUnrealType>& TypeInfo, UClass* ComponentClass, UClass* ActorClass, int MapIndex, const FActorSpecificSubobjectSchemaData* ExistingSchemaData) { FUnrealFlatRepData RepData = GetFlatRepData(TypeInfo); FActorSpecificSubobjectSchemaData SubobjectData; SubobjectData.ClassPath = ComponentClass->GetPathName(); for (EReplicatedPropertyGroup Group : GetAllReplicatedPropertyGroups()) { // Since it is possible to replicate subobjects which have no replicated properties. // We need to generate a schema component for every subobject. So if we have no replicated // properties, we only don't generate a schema component if we are REP_SingleClient if (RepData[Group].Num() == 0 && Group == REP_SingleClient) { continue; } Worker_ComponentId ComponentId = 0; if (ExistingSchemaData != nullptr && ExistingSchemaData->SchemaComponents[PropertyGroupToSchemaComponentType(Group)] != 0) { ComponentId = ExistingSchemaData->SchemaComponents[PropertyGroupToSchemaComponentType(Group)]; } else { ComponentId = IdGenerator.Next(); } Writer.PrintNewLine(); FString ComponentName = PropertyName + GetReplicatedPropertyGroupName(Group); Writer.Printf("component {0} {", *ComponentName); Writer.Indent(); Writer.Printf("id = {0};", ComponentId); Writer.Printf("data unreal.generated.{0};", *SchemaReplicatedDataName(Group, ComponentClass)); Writer.Outdent().Print("}"); AddComponentId(ComponentId, SubobjectData.SchemaComponents, PropertyGroupToSchemaComponentType(Group)); } FCmdHandlePropertyMap HandoverData = GetFlatHandoverData(TypeInfo); if (HandoverData.Num() > 0) { Worker_ComponentId ComponentId = 0; if (ExistingSchemaData != nullptr && ExistingSchemaData->SchemaComponents[ESchemaComponentType::SCHEMA_Handover] != 0) { ComponentId = ExistingSchemaData->SchemaComponents[ESchemaComponentType::SCHEMA_Handover]; } else { ComponentId = IdGenerator.Next(); } Writer.PrintNewLine(); // Handover (server to server) replicated properties. Writer.Printf("component {0} {", *(PropertyName + TEXT("Handover"))); Writer.Indent(); Writer.Printf("id = {0};", ComponentId); Writer.Printf("data unreal.generated.{0};", *SchemaHandoverDataName(ComponentClass)); Writer.Outdent().Print("}"); AddComponentId(ComponentId, SubobjectData.SchemaComponents, ESchemaComponentType::SCHEMA_Handover); } return SubobjectData; } // Output the includes required by this schema file. void GenerateSubobjectSchemaForActorIncludes(FCodeWriter& Writer, TSharedPtr<FUnrealType>& TypeInfo) { TSet<UStruct*> AlreadyImported; for (auto& PropertyPair : TypeInfo->Properties) { GDK_PROPERTY(Property)* Property = PropertyPair.Key; GDK_PROPERTY(ObjectProperty)* ObjectProperty = GDK_CASTFIELD<GDK_PROPERTY(ObjectProperty)>(Property); TSharedPtr<FUnrealType>& PropertyTypeInfo = PropertyPair.Value->Type; if (ObjectProperty && PropertyTypeInfo.IsValid()) { UObject* Value = PropertyTypeInfo->Object; if (Value != nullptr && IsSupportedClass(Value->GetClass())) { UClass* Class = Value->GetClass(); if (!AlreadyImported.Contains(Class) && SchemaGeneratedClasses.Contains(Class)) { Writer.Printf("import \"unreal/generated/Subobjects/{0}.schema\";", *ClassPathToSchemaName[Class->GetPathName()]); AlreadyImported.Add(Class); } } } } } // Generates schema for all statically attached subobjects on an Actor. void GenerateSubobjectSchemaForActor(FComponentIdGenerator& IdGenerator, UClass* ActorClass, TSharedPtr<FUnrealType> TypeInfo, FString SchemaPath, FActorSchemaData& ActorSchemaData, const FActorSchemaData* ExistingSchemaData) { FCodeWriter Writer; Writer.Printf(R"""( // Copyright (c) Improbable Worlds Ltd, All Rights Reserved // Note that this file has been generated automatically package unreal.generated.{0}.subobjects;)""", *ClassPathToSchemaName[ActorClass->GetPathName()].ToLower()); Writer.PrintNewLine(); GenerateSubobjectSchemaForActorIncludes(Writer, TypeInfo); FSubobjectMap Subobjects = GetAllSubobjects(TypeInfo); bool bHasComponents = false; for (auto& It : Subobjects) { TSharedPtr<FUnrealType>& SubobjectTypeInfo = It.Value; UClass* SubobjectClass = Cast<UClass>(SubobjectTypeInfo->Type); FActorSpecificSubobjectSchemaData SubobjectData; if (SchemaGeneratedClasses.Contains(SubobjectClass)) { bHasComponents = true; const FActorSpecificSubobjectSchemaData* ExistingSubobjectSchemaData = nullptr; if (ExistingSchemaData != nullptr) { for (auto& SubobjectIt : ExistingSchemaData->SubobjectData) { if (SubobjectIt.Value.Name == SubobjectTypeInfo->Name) { ExistingSubobjectSchemaData = &SubobjectIt.Value; break; } } } SubobjectData = GenerateSchemaForStaticallyAttachedSubobject(Writer, IdGenerator, UnrealNameToSchemaComponentName(SubobjectTypeInfo->Name.ToString()), SubobjectTypeInfo, SubobjectClass, ActorClass, 0, ExistingSubobjectSchemaData); } else { continue; } SubobjectData.Name = SubobjectTypeInfo->Name; uint32 SubobjectOffset = SubobjectData.SchemaComponents[SCHEMA_Data]; check(SubobjectOffset != 0); ActorSchemaData.SubobjectData.Add(SubobjectOffset, SubobjectData); } if (bHasComponents) { Writer.WriteToFile(FString::Printf(TEXT("%s%sComponents.schema"), *SchemaPath, *ClassPathToSchemaName[ActorClass->GetPathName()])); } } FString GetRPCFieldPrefix(ERPCType RPCType) { switch (RPCType) { case ERPCType::ClientReliable: return TEXT("server_to_client_reliable"); case ERPCType::ClientUnreliable: return TEXT("server_to_client_unreliable"); case ERPCType::ServerReliable: return TEXT("client_to_server_reliable"); case ERPCType::ServerUnreliable: return TEXT("client_to_server_unreliable"); case ERPCType::NetMulticast: return TEXT("multicast"); default: checkNoEntry(); } return FString(); } void GenerateRPCEndpoint(FCodeWriter& Writer, FString EndpointName, Worker_ComponentId ComponentId, TArray<ERPCType> SentRPCTypes, TArray<ERPCType> AckedRPCTypes) { Writer.PrintNewLine(); Writer.Printf("component Unreal{0} {", *EndpointName).Indent(); Writer.Printf("id = {0};", ComponentId); Schema_FieldId FieldId = 1; for (ERPCType SentRPCType : SentRPCTypes) { uint32 RingBufferSize = GetDefault<USpatialGDKSettings>()->MaxRPCRingBufferSize; for (uint32 RingBufferIndex = 0; RingBufferIndex < RingBufferSize; RingBufferIndex++) { Writer.Printf("option<UnrealRPCPayload> {0}_rpc_{1} = {2};", GetRPCFieldPrefix(SentRPCType), RingBufferIndex, FieldId++); } Writer.Printf("uint64 last_sent_{0}_rpc_id = {1};", GetRPCFieldPrefix(SentRPCType), FieldId++); } for (ERPCType AckedRPCType : AckedRPCTypes) { Writer.Printf("uint64 last_acked_{0}_rpc_id = {1};", GetRPCFieldPrefix(AckedRPCType), FieldId++); } if (ComponentId == SpatialConstants::MULTICAST_RPCS_COMPONENT_ID) { // This counter is used to let clients execute initial multicast RPCs when entity is just getting created, // while ignoring existing multicast RPCs when an entity enters the interest range. Writer.Printf("uint32 initially_present_multicast_rpc_count = {0};", FieldId++); } Writer.Outdent().Print("}"); } } // anonymous namespace void GenerateSubobjectSchema(FComponentIdGenerator& IdGenerator, UClass* Class, TSharedPtr<FUnrealType> TypeInfo, FString SchemaPath) { FCodeWriter Writer; Writer.Printf(R"""( // Copyright (c) Improbable Worlds Ltd, All Rights Reserved // Note that this file has been generated automatically package unreal.generated;)"""); bool bShouldIncludeCoreTypes = false; // Only include core types if the subobject has replicated references to other UObjects FUnrealFlatRepData RepData = GetFlatRepData(TypeInfo); for (auto& PropertyGroup : RepData) { for (auto& PropertyPair : PropertyGroup.Value) { GDK_PROPERTY(Property)* Property = PropertyPair.Value->Property; if (Property->IsA<GDK_PROPERTY(ObjectPropertyBase)>()) { bShouldIncludeCoreTypes = true; } if (Property->IsA<GDK_PROPERTY(ArrayProperty)>()) { if (GDK_CASTFIELD<GDK_PROPERTY(ArrayProperty)>(Property)->Inner->IsA<GDK_PROPERTY(ObjectPropertyBase)>()) { bShouldIncludeCoreTypes = true; } } } } if (bShouldIncludeCoreTypes) { Writer.PrintNewLine(); Writer.Printf("import \"unreal/gdk/core_types.schema\";"); } for (EReplicatedPropertyGroup Group : GetAllReplicatedPropertyGroups()) { // Since it is possible to replicate subobjects which have no replicated properties. // We need to generate a schema component for every subobject. So if we have no replicated // properties, we only don't generate a schema component if we are REP_SingleClient if (RepData[Group].Num() == 0 && Group == REP_SingleClient) { continue; } // If this class is an Actor Component, it MUST have bReplicates at field ID 1. if (Group == REP_MultiClient && Class->IsChildOf<UActorComponent>()) { TSharedPtr<FUnrealProperty> ExpectedReplicatesPropData = RepData[Group].FindRef(SpatialConstants::ACTOR_COMPONENT_REPLICATES_ID); const GDK_PROPERTY(Property)* ReplicatesProp = UActorComponent::StaticClass()->FindPropertyByName("bReplicates"); if (!(ExpectedReplicatesPropData.IsValid() && ExpectedReplicatesPropData->Property == ReplicatesProp)) { UE_LOG(LogSchemaGenerator, Error, TEXT("Did not find ActorComponent->bReplicates at field %d for class %s. Modifying the base Actor Component class is currently not supported."), SpatialConstants::ACTOR_COMPONENT_REPLICATES_ID, *Class->GetName()); } } Writer.PrintNewLine(); Writer.Printf("type {0} {", *SchemaReplicatedDataName(Group, Class)); Writer.Indent(); for (auto& RepProp : RepData[Group]) { WriteSchemaRepField(Writer, RepProp.Value, RepProp.Value->ReplicationData->Handle); } Writer.Outdent().Print("}"); } FCmdHandlePropertyMap HandoverData = GetFlatHandoverData(TypeInfo); if (HandoverData.Num() > 0) { Writer.PrintNewLine(); Writer.Printf("type {0} {", *SchemaHandoverDataName(Class)); Writer.Indent(); int FieldCounter = 0; for (auto& Prop : HandoverData) { FieldCounter++; WriteSchemaHandoverField(Writer, Prop.Value, FieldCounter); } Writer.Outdent().Print("}"); } // Use the max number of dynamically attached subobjects per class to generate // that many schema components for this subobject. const uint32 DynamicComponentsPerClass = GetDefault<USpatialGDKSettings>()->MaxDynamicallyAttachedSubobjectsPerClass; FSubobjectSchemaData SubobjectSchemaData; // Use previously generated component IDs when possible. const FSubobjectSchemaData* const ExistingSchemaData = SubobjectClassPathToSchema.Find(Class->GetPathName()); if (ExistingSchemaData != nullptr && !ExistingSchemaData->GeneratedSchemaName.IsEmpty() && ExistingSchemaData->GeneratedSchemaName != ClassPathToSchemaName[Class->GetPathName()]) { UE_LOG(LogSchemaGenerator, Error, TEXT("Saved generated schema name does not match in-memory version for class %s - schema %s : %s"), *Class->GetPathName(), *ExistingSchemaData->GeneratedSchemaName, *ClassPathToSchemaName[Class->GetPathName()]); UE_LOG(LogSchemaGenerator, Error, TEXT("Schema generation may have resulted in component name clash, recommend you perform a full schema generation")); } for (uint32 i = 1; i <= DynamicComponentsPerClass; i++) { FDynamicSubobjectSchemaData DynamicSubobjectComponents; for (EReplicatedPropertyGroup Group : GetAllReplicatedPropertyGroups()) { // Since it is possible to replicate subobjects which have no replicated properties. // We need to generate a schema component for every subobject. So if we have no replicated // properties, we only don't generate a schema component if we are REP_SingleClient if (RepData[Group].Num() == 0 && Group == REP_SingleClient) { continue; } Writer.PrintNewLine(); Worker_ComponentId ComponentId = 0; if (ExistingSchemaData != nullptr) { ComponentId = ExistingSchemaData->GetDynamicSubobjectComponentId(i - 1, PropertyGroupToSchemaComponentType(Group)); } if (ComponentId == 0) { ComponentId = IdGenerator.Next(); } FString ComponentName = SchemaReplicatedDataName(Group, Class) + TEXT("Dynamic") + FString::FromInt(i); Writer.Printf("component {0} {", *ComponentName); Writer.Indent(); Writer.Printf("id = {0};", ComponentId); Writer.Printf("data {0};", *SchemaReplicatedDataName(Group, Class)); Writer.Outdent().Print("}"); AddComponentId(ComponentId, DynamicSubobjectComponents.SchemaComponents, PropertyGroupToSchemaComponentType(Group)); } if (HandoverData.Num() > 0) { Writer.PrintNewLine(); Worker_ComponentId ComponentId = 0; if (ExistingSchemaData != nullptr) { ComponentId = ExistingSchemaData->GetDynamicSubobjectComponentId(i - 1, SCHEMA_Handover); } if (ComponentId == 0) { ComponentId = IdGenerator.Next(); } FString ComponentName = SchemaHandoverDataName(Class) + TEXT("Dynamic") + FString::FromInt(i); Writer.Printf("component {0} {", *ComponentName); Writer.Indent(); Writer.Printf("id = {0};", ComponentId); Writer.Printf("data {0};", *SchemaHandoverDataName(Class)); Writer.Outdent().Print("}"); AddComponentId(ComponentId, DynamicSubobjectComponents.SchemaComponents, ESchemaComponentType::SCHEMA_Handover); } SubobjectSchemaData.DynamicSubobjectComponents.Add(MoveTemp(DynamicSubobjectComponents)); } Writer.WriteToFile(FString::Printf(TEXT("%s%s.schema"), *SchemaPath, *ClassPathToSchemaName[Class->GetPathName()])); SubobjectSchemaData.GeneratedSchemaName = ClassPathToSchemaName[Class->GetPathName()]; SubobjectClassPathToSchema.Add(Class->GetPathName(), SubobjectSchemaData); } void GenerateActorSchema(FComponentIdGenerator& IdGenerator, UClass* Class, TSharedPtr<FUnrealType> TypeInfo, FString SchemaPath) { const FActorSchemaData* const SchemaData = ActorClassPathToSchema.Find(Class->GetPathName()); FCodeWriter Writer; Writer.Printf(R"""( // Copyright (c) Improbable Worlds Ltd, All Rights Reserved // Note that this file has been generated automatically package unreal.generated.{0};)""", *ClassPathToSchemaName[Class->GetPathName()].ToLower()); // Will always be included since AActor has replicated pointers to other actors Writer.PrintNewLine(); Writer.Printf("import \"unreal/gdk/core_types.schema\";"); FActorSchemaData ActorSchemaData; ActorSchemaData.GeneratedSchemaName = ClassPathToSchemaName[Class->GetPathName()]; FUnrealFlatRepData RepData = GetFlatRepData(TypeInfo); // Client-server replicated properties. for (EReplicatedPropertyGroup Group : GetAllReplicatedPropertyGroups()) { if (RepData[Group].Num() == 0) { continue; } // If this class is an Actor, it MUST have bTearOff at field ID 3. if (Group == REP_MultiClient && Class->IsChildOf<AActor>()) { TSharedPtr<FUnrealProperty> ExpectedReplicatesPropData = RepData[Group].FindRef(SpatialConstants::ACTOR_TEAROFF_ID); const GDK_PROPERTY(Property)* ReplicatesProp = AActor::StaticClass()->FindPropertyByName("bTearOff"); if (!(ExpectedReplicatesPropData.IsValid() && ExpectedReplicatesPropData->Property == ReplicatesProp)) { UE_LOG(LogSchemaGenerator, Error, TEXT("Did not find Actor->bTearOff at field %d for class %s. Modifying the base Actor class is currently not supported."), SpatialConstants::ACTOR_TEAROFF_ID, *Class->GetName()); } } Worker_ComponentId ComponentId = 0; if (SchemaData != nullptr && SchemaData->SchemaComponents[PropertyGroupToSchemaComponentType(Group)] != 0) { ComponentId = SchemaData->SchemaComponents[PropertyGroupToSchemaComponentType(Group)]; } else { ComponentId = IdGenerator.Next(); } Writer.PrintNewLine(); Writer.Printf("component {0} {", *SchemaReplicatedDataName(Group, Class)); Writer.Indent(); Writer.Printf("id = {0};", ComponentId); AddComponentId(ComponentId, ActorSchemaData.SchemaComponents, PropertyGroupToSchemaComponentType(Group)); int FieldCounter = 0; for (auto& RepProp : RepData[Group]) { FieldCounter++; WriteSchemaRepField(Writer, RepProp.Value, RepProp.Value->ReplicationData->Handle); } Writer.Outdent().Print("}"); } FCmdHandlePropertyMap HandoverData = GetFlatHandoverData(TypeInfo); if (HandoverData.Num() > 0) { Worker_ComponentId ComponentId = 0; if (SchemaData != nullptr && SchemaData->SchemaComponents[ESchemaComponentType::SCHEMA_Handover] != 0) { ComponentId = SchemaData->SchemaComponents[ESchemaComponentType::SCHEMA_Handover]; } else { ComponentId = IdGenerator.Next(); } Writer.PrintNewLine(); // Handover (server to server) replicated properties. Writer.Printf("component {0} {", *SchemaHandoverDataName(Class)); Writer.Indent(); Writer.Printf("id = {0};", ComponentId); AddComponentId(ComponentId, ActorSchemaData.SchemaComponents, ESchemaComponentType::SCHEMA_Handover); int FieldCounter = 0; for (auto& Prop : HandoverData) { FieldCounter++; WriteSchemaHandoverField(Writer, Prop.Value, FieldCounter); } Writer.Outdent().Print("}"); } GenerateSubobjectSchemaForActor(IdGenerator, Class, TypeInfo, SchemaPath, ActorSchemaData, ActorClassPathToSchema.Find(Class->GetPathName())); ActorClassPathToSchema.Add(Class->GetPathName(), ActorSchemaData); // Cache the NCD for this Actor if (AActor* CDO = Class->GetDefaultObject<AActor>()) { const float NCD = CDO->NetCullDistanceSquared; if (NetCullDistanceToComponentId.Find(NCD) == nullptr) { if (FMath::FloorToFloat(NCD) != NCD) { UE_LOG(LogSchemaGenerator, Warning, TEXT("Fractional Net Cull Distance values are not supported and may result in incorrect behaviour. " "Please modify class's (%s) Net Cull Distance Squared value (%f)"), *Class->GetPathName(), NCD); } NetCullDistanceToComponentId.Add(NCD, 0); } } Writer.WriteToFile(FString::Printf(TEXT("%s%s.schema"), *SchemaPath, *ClassPathToSchemaName[Class->GetPathName()])); } void GenerateRPCEndpointsSchema(FString SchemaPath) { FCodeWriter Writer; Writer.Print(R"""( // Copyright (c) Improbable Worlds Ltd, All Rights Reserved // Note that this file has been generated automatically package unreal.generated;)"""); Writer.PrintNewLine(); Writer.Print("import \"unreal/gdk/core_types.schema\";"); Writer.Print("import \"unreal/gdk/rpc_payload.schema\";"); GenerateRPCEndpoint(Writer, TEXT("ClientEndpoint"), SpatialConstants::CLIENT_ENDPOINT_COMPONENT_ID, { ERPCType::ServerReliable, ERPCType::ServerUnreliable }, { ERPCType::ClientReliable, ERPCType::ClientUnreliable }); GenerateRPCEndpoint(Writer, TEXT("ServerEndpoint"), SpatialConstants::SERVER_ENDPOINT_COMPONENT_ID, { ERPCType::ClientReliable, ERPCType::ClientUnreliable }, { ERPCType::ServerReliable, ERPCType::ServerUnreliable }); GenerateRPCEndpoint(Writer, TEXT("MulticastRPCs"), SpatialConstants::MULTICAST_RPCS_COMPONENT_ID, { ERPCType::NetMulticast }, {}); Writer.WriteToFile(FString::Printf(TEXT("%srpc_endpoints.schema"), *SchemaPath)); } // Add the component ID to the passed schema components array and the set of components of that type. void AddComponentId(const Worker_ComponentId ComponentId, ComponentIdPerType& SchemaComponents, const ESchemaComponentType ComponentType) { SchemaComponents[ComponentType] = ComponentId; SchemaComponentTypeToComponents[ComponentType].Add(ComponentId); }
34.180233
311
0.749064
[ "object" ]
f6da875ab916f9754130d7df39f92d2af702cc6e
10,921
cpp
C++
OgreMain/src/OgreColourValue.cpp
VonChenPlus/ogre
5a709466b9b4617e83a9bd1512233148223107bc
[ "MIT" ]
158
2016-11-17T19:37:51.000Z
2022-03-21T19:57:55.000Z
OgreMain/src/OgreColourValue.cpp
VonChenPlus/ogre
5a709466b9b4617e83a9bd1512233148223107bc
[ "MIT" ]
94
2016-11-18T09:55:57.000Z
2021-01-14T08:50:40.000Z
OgreMain/src/OgreColourValue.cpp
VonChenPlus/ogre
5a709466b9b4617e83a9bd1512233148223107bc
[ "MIT" ]
51
2017-05-24T10:20:25.000Z
2022-03-17T15:07:02.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2016 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreColourValue.h" #include "OgreMath.h" namespace Ogre { const ColourValue ColourValue::ZERO = ColourValue(0.0,0.0,0.0,0.0); const ColourValue ColourValue::Black = ColourValue(0.0,0.0,0.0); const ColourValue ColourValue::White = ColourValue(1.0,1.0,1.0); const ColourValue ColourValue::Red = ColourValue(1.0,0.0,0.0); const ColourValue ColourValue::Green = ColourValue(0.0,1.0,0.0); const ColourValue ColourValue::Blue = ColourValue(0.0,0.0,1.0); //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG ABGR ColourValue::getAsABGR(void) const #else RGBA ColourValue::getAsRGBA(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (RGBA = 8888) // Red val8 = static_cast<uint8>(r * 255); val32 = val8 << 24; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 16; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8 << 8; // Alpha val8 = static_cast<uint8>(a * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG BGRA ColourValue::getAsBGRA(void) const #else ARGB ColourValue::getAsARGB(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ARGB = 8888) // Alpha val8 = static_cast<uint8>(a * 255); val32 = val8 << 24; // Red val8 = static_cast<uint8>(r * 255); val32 += val8 << 16; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 8; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG ARGB ColourValue::getAsARGB(void) const #else BGRA ColourValue::getAsBGRA(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ARGB = 8888) // Blue val8 = static_cast<uint8>(b * 255); val32 = val8 << 24; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 16; // Red val8 = static_cast<uint8>(r * 255); val32 += val8 << 8; // Alpha val8 = static_cast<uint8>(a * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG RGBA ColourValue::getAsRGBA(void) const #else ABGR ColourValue::getAsABGR(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ABRG = 8888) // Alpha val8 = static_cast<uint8>(a * 255); val32 = val8 << 24; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8 << 16; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 8; // Red val8 = static_cast<uint8>(r * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsABGR(const ABGR val) #else void ColourValue::setAsRGBA(const RGBA val) #endif { uint32 val32 = val; // Convert from 32bit pattern // (RGBA = 8888) // Red r = ((val32 >> 24) & 0xFF) / 255.0f; // Green g = ((val32 >> 16) & 0xFF) / 255.0f; // Blue b = ((val32 >> 8) & 0xFF) / 255.0f; // Alpha a = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsBGRA(const BGRA val) #else void ColourValue::setAsARGB(const ARGB val) #endif { uint32 val32 = val; // Convert from 32bit pattern // (ARGB = 8888) // Alpha a = ((val32 >> 24) & 0xFF) / 255.0f; // Red r = ((val32 >> 16) & 0xFF) / 255.0f; // Green g = ((val32 >> 8) & 0xFF) / 255.0f; // Blue b = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsARGB(const ARGB val) #else void ColourValue::setAsBGRA(const BGRA val) #endif { uint32 val32 = val; // Convert from 32bit pattern // (ARGB = 8888) // Blue b = ((val32 >> 24) & 0xFF) / 255.0f; // Green g = ((val32 >> 16) & 0xFF) / 255.0f; // Red r = ((val32 >> 8) & 0xFF) / 255.0f; // Alpha a = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsRGBA(const RGBA val) #else void ColourValue::setAsABGR(const ABGR val) #endif { uint32 val32 = val; // Convert from 32bit pattern // (ABGR = 8888) // Alpha a = ((val32 >> 24) & 0xFF) / 255.0f; // Blue b = ((val32 >> 16) & 0xFF) / 255.0f; // Green g = ((val32 >> 8) & 0xFF) / 255.0f; // Red r = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- bool ColourValue::operator==(const ColourValue& rhs) const { return (r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a); } //--------------------------------------------------------------------- bool ColourValue::operator!=(const ColourValue& rhs) const { return !(*this == rhs); } //--------------------------------------------------------------------- void ColourValue::setHSB(Real hue, Real saturation, Real brightness) { // wrap hue if (hue > 1.0f) { hue -= (int)hue; } else if (hue < 0.0f) { hue += (int)hue + 1; } // clamp saturation / brightness saturation = std::min(saturation, (Real)1.0); saturation = std::max(saturation, (Real)0.0); brightness = std::min(brightness, (Real)1.0); brightness = std::max(brightness, (Real)0.0); if (brightness == 0.0f) { // early exit, this has to be black r = g = b = 0.0f; return; } if (saturation == 0.0f) { // early exit, this has to be grey r = g = b = brightness; return; } Real hueDomain = hue * 6.0f; if (hueDomain >= 6.0f) { // wrap around, and allow mathematical errors hueDomain = 0.0f; } unsigned short domain = (unsigned short)hueDomain; Real f1 = brightness * (1 - saturation); Real f2 = brightness * (1 - saturation * (hueDomain - domain)); Real f3 = brightness * (1 - saturation * (1 - (hueDomain - domain))); switch (domain) { case 0: // red domain; green ascends r = brightness; g = f3; b = f1; break; case 1: // yellow domain; red descends r = f2; g = brightness; b = f1; break; case 2: // green domain; blue ascends r = f1; g = brightness; b = f3; break; case 3: // cyan domain; green descends r = f1; g = f2; b = brightness; break; case 4: // blue domain; red ascends r = f3; g = f1; b = brightness; break; case 5: // magenta domain; blue descends r = brightness; g = f1; b = f2; break; } } //--------------------------------------------------------------------- void ColourValue::getHSB(Real* hue, Real* saturation, Real* brightness) const { Real vMin = std::min(r, std::min(g, b)); Real vMax = std::max(r, std::max(g, b)); Real delta = vMax - vMin; *brightness = vMax; if (Math::RealEqual(delta, 0.0f, 1e-6)) { // grey *hue = 0; *saturation = 0; } else { // a colour *saturation = delta / vMax; Real deltaR = (((vMax - r) / 6.0f) + (delta / 2.0f)) / delta; Real deltaG = (((vMax - g) / 6.0f) + (delta / 2.0f)) / delta; Real deltaB = (((vMax - b) / 6.0f) + (delta / 2.0f)) / delta; if (Math::RealEqual(r, vMax)) *hue = deltaB - deltaG; else if (Math::RealEqual(g, vMax)) *hue = 0.3333333f + deltaR - deltaB; else if (Math::RealEqual(b, vMax)) *hue = 0.6666667f + deltaG - deltaR; if (*hue < 0.0f) *hue += 1.0f; if (*hue > 1.0f) *hue -= 1.0f; } } }
26.832924
81
0.462595
[ "object" ]
f6df7c228a4d827ca8a035ee36fed3b3fe2d5741
5,224
cpp
C++
src/slg/textures/fresnel/fresnelsopra.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/textures/fresnel/fresnelsopra.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
src/slg/textures/fresnel/fresnelsopra.cpp
DavidBluecame/LuxRays
be0f5228b8b65268278a6c6a1c98564ebdc27c05
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 1998-2015 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * 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 <fstream> #include <boost/lexical_cast.hpp> #include <boost/regex.hpp> #include "luxrays/core/color/spds/irregular.h" #include "slg/textures/fresnel/fresnelsopra.h" #include "slg/textures/fresnel/fresnelconst.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // Fresnel Sopra texture //------------------------------------------------------------------------------ // Converts photon energy (in eV) to wavelength (in nm) static float eVtolambda(const float eV) { // lambda = hc / E, where // h is planck's constant in eV*s // c is speed of light in m/s return (4.13566733e-15f * 299792458.f * 1e9f) / eV; } // Converts wavelength (in micrometer) to wavelength (in nm) static float umtolambda(const float um) { return um * 1000.f; } // Converts wavelength (in cm-1) to wavelength (in nm) static float invcmtolambda(const float invcm) { return 1e7f / invcm; } // Converts wavelength (in nm) to wavelength (in nm) static float nmtolambda(const float nm) { return nm; } FresnelTexture *slg::AllocFresnelSopraTex(const Properties &props, const string &propName) { const string fileName = props.Get(Property(propName + ".file")("sopra.nk")).Get<string>(); ifstream fs; fs.open(fileName.c_str()); string line; if (!getline(fs, line).good()) throw runtime_error("Unable to read sopra file: " + fileName); boost::smatch m; // Read initial line, containing metadata boost::regex header_expr("(\\d+)[^\\.[:digit:]]+(\\d*\\.?\\d+(?:[eE]-?\\d+)?)[^\\.[:digit:]]+(\\d*\\.?\\d+(?:[eE]-?\\d+)?)[^\\.[:digit:]]+(\\d+)"); if (!boost::regex_search(line, m, header_expr)) throw runtime_error("Bad sopra header in: " + fileName); // Used to convert file units to wavelength in nm float (*tolambda)(float) = NULL; float lambda_first, lambda_last; if (m[1] == "1") { // lambda in eV // low eV -> high lambda lambda_first = boost::lexical_cast<float>(m[3]); lambda_last = boost::lexical_cast<float>(m[2]); tolambda = &eVtolambda; } else if (m[1] == "2") { // lambda in um lambda_first = boost::lexical_cast<float>(m[2]); lambda_last = boost::lexical_cast<float>(m[3]); tolambda = &umtolambda; } else if (m[1] == "3") { // lambda in cm-1 lambda_first = boost::lexical_cast<float>(m[3]); lambda_last = boost::lexical_cast<float>(m[2]); tolambda = &invcmtolambda; } else if (m[1] == "4") { // lambda in nm lambda_first = boost::lexical_cast<float>(m[2]); lambda_last = boost::lexical_cast<float>(m[3]); tolambda = &nmtolambda; } else throw runtime_error("Unknown sopra unit code '" + m[1] + "' in: " + fileName); // Number of lines of nk data const int count = boost::lexical_cast<int>(m[4]); // Read nk data boost::regex sample_expr("(\\d*\\.?\\d+(?:[eE]-?\\d+)?)[^\\.[:digit:]]+(\\d*\\.?\\d+(?:[eE]-?\\d+)?)"); vector<float> wl(count + 1); vector<float> n(count + 1); vector<float> k(count + 1); // We want lambda to go from low to high // so reverse direction const float delta = (lambda_last - lambda_first) / count; for (int i = count; i >= 0; --i) { if (getline(fs, line).bad()) throw runtime_error("Not enough sopra data in: " + fileName); if (!boost::regex_search(line, m, sample_expr)) throw runtime_error("Unparseable sopra data at data line " + ToString(count - i) + "' in: " + fileName); // Linearly interpolate units in file // then convert to wavelength in nm wl[i] = tolambda(lambda_first + delta * i); n[i] = boost::lexical_cast<float>(m[1]); k[i] = boost::lexical_cast<float>(m[2]); } IrregularSPD N(&wl[0], &n[0], wl.size()); IrregularSPD K(&wl[0], &k[0], wl.size()); ColorSystem colorSpace; const RGBColor Nrgb = colorSpace.ToRGBConstrained(N.ToNormalizedXYZ()); const RGBColor Krgb = colorSpace.ToRGBConstrained(K.ToNormalizedXYZ()); return new FresnelConstTexture(Nrgb, Krgb); }
37.582734
148
0.565276
[ "vector" ]
f6e1fcd31e3fc516296d6ceec268f6a51a194bd7
17,829
cpp
C++
TestsValidation/TVRenderer/SceneDecals.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
TestsValidation/TVRenderer/SceneDecals.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
TestsValidation/TVRenderer/SceneDecals.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Core/Logger.h> #include <Workflow/ModelImporterX.h> #include <Workflow/ModelOptimize.h> #include <Workflow/TexCompression.h> #include <Workflow/PicBankGeneration.h> #include "SceneDecals.h" SceneDecals::SceneDecals(const TestSceneData & data) : ITestScene(data) { _prevCameraWorld.setZero(); updateCamera(); _alpha = 0.0; _beta = 0.0; } bool SceneDecals::initialise(const Ptr<Core::VirtualFileSystem> & pVFS, const Ptr<Window::Window> & pRenderWindow) { bool result = true; try { _pScene = _pRenderer->createScene(); _pHUD = _pRenderer->createHUD(); // Textes Ptr<Renderer::IFont> pFont1 = _pRenderer->createFont(L"Arial", 20); Ptr<Renderer::IFont> pFont2 = _pRenderer->createFont(L"Segoe Script", 20); Ptr<Renderer::IText> pText1 = _pHUD->createText(pFont1, L"This is a test."); Ptr<Renderer::IText> pText2 = _pHUD->createText(pFont1, L"This is a bold test."); Ptr<Renderer::IText> pText3 = _pHUD->createText(pFont1, L"This is an italic test."); Ptr<Renderer::IText> pText4 = _pHUD->createText(pFont1, L"This is a bold italic test."); Ptr<Renderer::IText> pText5 = _pHUD->createText(pFont2, L"Yet another test."); Ptr<Renderer::IText> pText6 = _pHUD->createText(pFont2, L"It fucking works guys."); pText1->setPosition(Core::Vector2f(20.0f, 40.0f)); pText2->setPosition(Core::Vector2f(20.0f, 65.0f)); pText3->setPosition(Core::Vector2f(20.0f, 90.0f)); pText4->setPosition(Core::Vector2f(20.0f, 115.0f)); pText5->setPosition(Core::Vector2f(20.0f, 160.0f)); pText6->setPosition(Core::Vector2f(20.0f, 185.0f)); pText2->setBold(true); pText3->setItalic(true); pText4->setBold(true); pText4->setItalic(true); pText2->setColor(Core::Vector4f(1.00f, 0.25f, 0.25f, 1.00f)); pText3->setColor(Core::Vector4f(0.25f, 1.00f, 0.25f, 0.50f)); pText4->setColor(Core::Vector4f(0.75f, 0.75f, 1.00f, 0.25f)); pText5->setColor(Core::Vector4f(0.75f, 0.75f, 1.00f, 1.00f)); pText6->setColor(Core::Vector4f(0.75f, 1.00f, 1.00f, 0.25f)); pText1->setPriority(1); pText2->setPriority(1); pText3->setPriority(1); pText4->setPriority(1); pText5->setPriority(1); pText6->setPriority(1); // Images Ptr<Assets::PictureBank> pPBKData = Workflow::generatePictureBank(L"Data/TUData/Pictures/Bank00", 256, Assets::TEX_FORMAT_ARGB8); Ptr<Renderer::IPictureBank> pPBK = _pRenderer->uploadPictureBank(pPBKData); const Renderer::PictureInfos & pic1 = pPBK->getPictureInfos(L"source-normmap.jpg"); Ptr<Renderer::IRectangle> pRect1 = _pHUD->createRectangle(pic1); Ptr<Renderer::IRectangle> pRect2 = _pHUD->createRectangle(pic1); Ptr<Renderer::IRectangle> pRect3 = _pHUD->createRectangle(Renderer::PictureInfos::PLAIN_COLOR); pRect1->setPosition(Core::Vector2f(100.0f, 50.0f)); pRect2->setPosition(Core::Vector2f(170.0f, 50.0f)); pRect3->setPosition(Core::Vector2f(100.0f, 120.0f)); pRect1->setSize(Core::Vector2f(float(pic1.width), float(pic1.height))); pRect2->setSize(Core::Vector2f(float(pic1.width), float(pic1.height))); pRect3->setSize(Core::Vector2f(float(pic1.width), float(pic1.height))); pRect1->setPriority(0); pRect2->setPriority(2); pRect3->setPriority(0); pRect3->setColor(Core::Vector4f(1.0f, 0.0f, 0.0f, 0.5f)); // Fog Renderer::FogSettings fog(Core::Vector4f(0.3f, 0.1f, 0.1f, 1.0f), 300.0f, 1500.0f, 0.0f); _pScene->setFogSettings(fog); // Modèle Workflow::ModelImporterX importX; Ptr<Core::InputStream> pInputModel(pVFS->readFile(L"/Data/TUData/Modeles/teapot.x")); Ptr<Assets::Model> pModelTeapot(importX.importModel(*pInputModel)); Workflow::ModelPackingOptions modelOptions; Workflow::packModel(modelOptions, *pModelTeapot); int32 idTeapotMesh = pModelTeapot->getMeshId(L"Teapot01"); if(idTeapotMesh == Assets::UNDEFINED_NODE_ID) throw Core::Exception(L"Model does not contain objet 'Teapot01'"); TextureGrabber texGrabber(pVFS, _pRenderer); Ptr<Renderer::IMesh> pRenderMesh = _pRenderer->uploadMesh(pModelTeapot->getMeshPtr(idTeapotMesh), texGrabber); Renderer::Material mat1; mat1.diffuse = Core::Vector4f(0.42f, 0.64f, 0.87f, 1.00f); mat1.specular = Core::Vector4f(0.40f, 0.40f, 0.40f, 1.00f); mat1.shininess = 45.0; _pScene2 = _pRenderer->createScene(); Ptr<Renderer::IMeshInstance> pTeapot(_pScene2->createMeshInstance(pRenderMesh)); pTeapot->setMaterial(mat1); pTeapot->setWorldMatrix(Core::Matrix4f(Core::TRANSLATION, 0.0f, -30.0f, 0.0f)); // Texture Ptr<Renderer::ITextureMap> pTexMap00(loadTexture(pVFS, L"/Data/TUData/Textures/decal00.tga", Workflow::TEXTURE_COLORMAP)); Ptr<Renderer::ITextureMap> pTexMap01(loadTexture(pVFS, L"/Data/TUData/Textures/decal01.tga", Workflow::TEXTURE_COLORMAP)); Ptr<Renderer::ITextureMap> pTexMap02(loadTexture(pVFS, L"/Data/TUData/Textures/decal02.tga", Workflow::TEXTURE_COLORMAP)); //Ptr<Renderer::ITextureMap> pTexMap03(loadTexture(pVFS, L"/Data/TUData/Textures/stones01-normal.jpg", Workflow::TEXTURE_NORMALMAP)); Ptr<Renderer::ITextureMap> pTexMap03(loadTexture(pVFS, L"/Data/TUData/Textures/Water0.jpg", Workflow::TEXTURE_NORMALMAP)); Ptr<Renderer::ITextureMap> pTexMap04(loadTexture(pVFS, L"/Data/TUData/Textures/refrac00.jpg", Workflow::TEXTURE_NORMALMAP)); // Texture animée 0 Workflow::TextureOptions options; Core::List<Ptr<Images::Image> > images; images.push_back(Ptr<Images::Image>(new Images::Image())); images.push_back(Ptr<Images::Image>(new Images::Image())); images.push_back(Ptr<Images::Image>(new Images::Image())); images.push_back(Ptr<Images::Image>(new Images::Image())); Ptr<Core::InputStream> pInputAnim00(pVFS->readFile(L"/Data/TUData/Textures/Anim00/00.jpg")); Ptr<Core::InputStream> pInputAnim01(pVFS->readFile(L"/Data/TUData/Textures/Anim00/01.jpg")); Ptr<Core::InputStream> pInputAnim02(pVFS->readFile(L"/Data/TUData/Textures/Anim00/02.jpg")); Ptr<Core::InputStream> pInputAnim03(pVFS->readFile(L"/Data/TUData/Textures/Anim00/03.jpg")); images[0]->load((Core::SeekableInputStream &)*pInputAnim00); images[1]->load((Core::SeekableInputStream &)*pInputAnim01); images[2]->load((Core::SeekableInputStream &)*pInputAnim02); images[3]->load((Core::SeekableInputStream &)*pInputAnim03); Ptr<Assets::Texture> pTexAnim00(Workflow::generateTexture3D(options, images)); Ptr<Renderer::ITextureMap> pTexMapAnim00(_pRenderer->uploadTexture(pTexAnim00)); Ptr<Renderer::ITextureMap> pTexMapAnim01(loadTexture(pVFS, L"/Data/TUData/Textures/fire-sprite2.jpg", Workflow::TEXTURE_COLORMAP)); // Instances Ptr<Renderer::IDecal> decal00(_pScene->createDecal(pTexMap00, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal01(_pScene->createDecal(pTexMap00, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal02(_pScene->createDecal(pTexMap00, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal03(_pScene->createDecal(pTexMap00, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal04(_pScene->createDecal(pTexMap00, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal05(_pScene->createDecal(pTexMap00, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal06(_pScene->createDecal(pTexMap01, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal07(_pScene->createDecal(pTexMap01, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal08(_pScene->createDecal(pTexMap02, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal09(_pScene->createDecal(pTexMap02, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal10(_pScene->createDecal(pTexMapAnim00, Renderer::DECAL_LERP)); Ptr<Renderer::IDecal> decal11(_pScene->createDecal(pTexMapAnim01, Renderer::DECAL_ADD)); Ptr<Renderer::IDecal> decal12(_pScene->createDecal(pTexMap03, Renderer::DECAL_REFRAC)); _pDecalRefrac = decal12; decal11->setSpriteLayout(4, 4); decal00->setSize(40.0f); decal01->setSize(40.0f, 30.0f); decal02->setSize(30.0f, 40.0f); decal03->setSize(40.0f); decal04->setSize(40.0f, 30.0f); decal05->setSize(30.0f, 40.0f); decal06->setSize(60.0f); decal07->setSize(60.0f); decal08->setSize(60.0f); decal09->setSize(60.0f); decal10->setSize(60.0f); decal11->setSize(60.0f); decal12->setSize(100.0f); decal00->setColor(Core::Vector4f(1.0f, 0.0f, 0.0f, 1.00f)); decal01->setColor(Core::Vector4f(0.0f, 1.0f, 0.0f, 1.00f)); decal02->setColor(Core::Vector4f(0.0f, 0.0f, 1.0f, 1.00f)); decal03->setColor(Core::Vector4f(1.0f, 0.0f, 0.0f, 0.10f)); decal04->setColor(Core::Vector4f(0.0f, 1.0f, 0.0f, 0.25f)); decal05->setColor(Core::Vector4f(0.0f, 0.0f, 1.0f, 0.50f)); decal06->setColor(Core::Vector4f(0.5f, 0.8f, 0.9f, 1.00f)); decal07->setColor(Core::Vector4f(0.5f, 0.8f, 0.9f, 1.00f)); decal07->setGlow(Core::Vector4f(0.5f, 0.8f, 0.9f, 1.00f)); decal08->setColor(Core::Vector4f(0.5f, 0.2f, 0.2f, 1.00f)); decal09->setColor(Core::Vector4f(0.5f, 0.2f, 0.2f, 1.00f)); decal09->setGlow(Core::Vector4f(0.5f, 0.2f, 0.2f, 1.00f)); decal08->setMode(Renderer::DECAL_ADD); decal09->setMode(Renderer::DECAL_ADD); decal10->setColor(Core::Vector4f(1.0f, 1.0f, 1.0f, 0.75f)); decal11->setColor(Core::Vector4f(1.0f, 1.0f, 1.0f, 0.75f)); decal12->setColor(Core::Vector4f(1.0f, 1.0f, 1.0f, 1.0f)); Core::Matrix4f world00(Core::TRANSLATION, -50.0, 20.0, -50.0); Core::Matrix4f world01(Core::TRANSLATION, 0.0, 20.0, -50.0); Core::Matrix4f world02(Core::TRANSLATION, 50.0, 20.0, -50.0); Core::Matrix4f world03(Core::TRANSLATION, -50.0, -20.0, -50.0); Core::Matrix4f world04(Core::TRANSLATION, 0.0, -20.0, -50.0); Core::Matrix4f world05(Core::TRANSLATION, 50.0, -20.0, -50.0); Core::Matrix4f rotX(Core::ROTATION, f_PI_DIV_2, Core::ROT_X_PITCH); Core::Matrix4f rotY(Core::ROTATION, f_PI_DIV_2, Core::ROT_Y_YAW); Core::Matrix4f world06(Core::TRANSLATION, 100.0, -60.0, 0.0); world06.postMultiply(rotY); Core::Matrix4f world07(Core::TRANSLATION, 120.0, -45.0, 25.0); world07.postMultiply(rotY); Core::Matrix4f world08(Core::TRANSLATION, 100.0, 40.0, 0.0); world08.postMultiply(rotY); Core::Matrix4f world09(Core::TRANSLATION, 120.0, 65.0, 25.0); world09.postMultiply(rotY); Core::Matrix4f world10(Core::TRANSLATION, -120.0, 65.0, 25.0); world10.postMultiply(rotY); Core::Matrix4f world11(Core::TRANSLATION, -120.0, -45.0, 25.0); world11.postMultiply(rotY); Core::Matrix4f world12(Core::TRANSLATION, 50.0, 85.0, 25.0); world12.postMultiply(rotX); decal00->setWorldMatrix(world00); decal01->setWorldMatrix(world01); decal02->setWorldMatrix(world02); decal03->setWorldMatrix(world03); decal04->setWorldMatrix(world04); decal05->setWorldMatrix(world05); decal06->setWorldMatrix(world06); decal07->setWorldMatrix(world07); decal08->setWorldMatrix(world08); decal09->setWorldMatrix(world09); decal10->setWorldMatrix(world10); decal11->setWorldMatrix(world11); decal12->setWorldMatrix(world12); for(int32 ii=0; ii < 11; ii++) _boxes.push_back(_pScene->createAABox()); _boxes[ 0]->setBox(decal00->getBoundingBox()); _boxes[ 1]->setBox(decal01->getBoundingBox()); _boxes[ 2]->setBox(decal02->getBoundingBox()); _boxes[ 3]->setBox(decal03->getBoundingBox()); _boxes[ 4]->setBox(decal04->getBoundingBox()); _boxes[ 5]->setBox(decal05->getBoundingBox()); _boxes[ 6]->setBox(decal06->getBoundingBox()); _boxes[ 7]->setBox(decal07->getBoundingBox()); _boxes[ 8]->setBox(decal08->getBoundingBox()); _boxes[ 9]->setBox(decal09->getBoundingBox()); _boxes[10]->setBox(pTeapot->getBoundingBox()); _pDecalAnim01 = decal10; _pDecalAnim02 = decal11; setBoxesVisible(false); _pCamera = _pScene->createPerspectiveCamera(f_PI_DIV_4, pRenderWindow->getWidth() / (float) pRenderWindow->getHeight(), 10.0, 10000.0); } catch(Core::Exception & exception) { ERR << L"Error initialising teapot scene : " << exception.getMessage() << L"\n"; ERR << exception.getCallStack(); result = false; } return result; } void SceneDecals::update(double elapsed) { ITestScene::update(elapsed); _alpha = float(fmod(_alpha + 1.0 * elapsed, double(f_PI))); _beta = float(fmod(_beta + 1.0 * elapsed, double(f_PI_MUL_2))); float cb = float(Core::L_cos(_beta)); float sb = float(Core::L_sin(_beta)); float sa = float(Core::L_sin(_alpha)); Renderer::PostFX fx = _pCamera->getPostFX(); Core::Matrix4f view; Core::Matrix4f world; _pCamera->getViewMatrix(view); _pCamera->getWorldMatrix(world); if(!_prevCameraWorld.isZero()) { Core::Vector3f camMove = world.getTVector() - _prevCameraWorld.getTVector(); Core::Vector3f viewMove = view.apply3x3(camMove); //viewMove *= 0.10f; static const float MM = 2.0f; viewMove.clamp(Core::Vector3f(-MM), Core::Vector3f(MM)); _moveBuffer.push_back(viewMove); } if(_moveBuffer.size() >= 50) { Core::Vector3f viewMove(Core::Vector3f::ZERO); for(int32 ii=0; ii < _moveBuffer.size(); ii++) viewMove += _moveBuffer[ii]; viewMove /= float(_moveBuffer.size()); //fx.blurDir1 = Core::Vector2f(viewMove.x, -viewMove.y); //fx.radialBlurFactor = std::max(0.0f, std::min(1.0f, abs(0.75f * viewMove.z))); _moveBuffer.erase(_moveBuffer.begin()); } //fx.fadeColor = Core::Vector4f(0.0f, 0.0f, 1.0f, sa); //fx.saturation = sa; //fx.blurDir1 = Core::Vector2f(0.5f + 0.25f * cb, 0.0f); //fx.blurDir2 = Core::Vector2f(0.0f, 0.5f + 0.25f * sb); //fx.radialBlurFactor = sa; //fx.radialBlurCenter = Core::Vector2f(0.5f + 0.25f * cb, 0.5f + 0.25f * sb); fx.timeBlurOn = true; fx.timeBlurFactor = 0.001f;//float(1.0 - 5.0 * elapsed); _pCamera->setPostFX(fx); _prevCameraWorld = world; if(_pInput->isKeyDown('L')) { Core::Vector4f c = _pDecalRefrac->getColor(); c.a -= 1.0f * float(elapsed); INF << Core::toString(c.a) << L"\n"; _pDecalRefrac->setColor(c); } if(_pInput->isKeyDown('M')) { Core::Vector4f c = _pDecalRefrac->getColor(); c.a += 1.0f * float(elapsed); INF << Core::toString(c.a) << L"\n"; _pDecalRefrac->setColor(c); } _pDecalAnim01->setTimeKey(float(fmod(_pDecalAnim01->getTimeKey() + elapsed * 0.25, 1.0))); _pDecalAnim02->setTimeKey(float(fmod(_pDecalAnim02->getTimeKey() + elapsed * 0.25, 1.0))); } void SceneDecals::render() { _pCamera->setWorldMatrix(_matWorldCamera); Core::List<Ptr<Renderer::IScene> > scenes; scenes.push_back(_pScene); scenes.push_back(_pScene2); _pRenderer->renderScenes(_pRenderer->getDefaultView(), scenes, _pCamera); _pRenderer->renderHUD(_pRenderer->getDefaultView(), _pHUD); }
44.461347
144
0.644063
[ "render", "model" ]
f6e32169c35845df0066b7fc36796529b9eaaa96
27,470
cpp
C++
src/video_capture/testcard.cpp
Martin-Bela/UltraGrid
bbaa729aa8c156d2cf6d2f4ec247889b93a5b6f3
[ "BSD-3-Clause" ]
370
2016-10-05T15:19:00.000Z
2022-03-29T22:12:28.000Z
src/video_capture/testcard.cpp
Martin-Bela/UltraGrid
bbaa729aa8c156d2cf6d2f4ec247889b93a5b6f3
[ "BSD-3-Clause" ]
165
2016-11-21T13:01:36.000Z
2022-03-31T20:01:20.000Z
src/video_capture/testcard.cpp
Martin-Bela/UltraGrid
bbaa729aa8c156d2cf6d2f4ec247889b93a5b6f3
[ "BSD-3-Clause" ]
63
2016-10-13T12:07:45.000Z
2022-03-23T19:46:10.000Z
/** * @file video_capture/testcard.cpp * @author Colin Perkins <csp@csperkins.org * @author Alvaro Saurin <saurin@dcs.gla.ac.uk> * @author Martin Benes <martinbenesh@gmail.com> * @author Lukas Hejtmanek <xhejtman@ics.muni.cz> * @author Petr Holub <hopet@ics.muni.cz> * @author Milos Liska <xliska@fi.muni.cz> * @author Jiri Matela <matela@ics.muni.cz> * @author Dalibor Matura <255899@mail.muni.cz> * @author Ian Wesley-Smith <iwsmith@cct.lsu.edu> */ /* * Copyright (c) 2005-2006 University of Glasgow * Copyright (c) 2005-2021 CESNET z.s.p.o. * * Redistribution and use in source and binary forms, with or without * modification, is permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * * This product includes software developed by the University of Southern * California Information Sciences Institute. This product also includes * software developed by CESNET z.s.p.o. * * 4. Neither the name of the University, Institute, CESNET 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 AUTHORS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @todo * Do the rendering in 16 bits */ #include "config.h" #include "config_unix.h" #include "config_win32.h" #include "debug.h" #include "host.h" #include "lib_common.h" #include "tv.h" #include "video.h" #include "video_capture.h" #include "song1.h" #include "utils/color_out.h" #include "utils/ring_buffer.h" #include "utils/vf_split.h" #include <stdio.h> #include <stdlib.h> #include <chrono> #ifdef HAVE_LIBSDL_MIXER #ifdef HAVE_SDL2 #include <SDL2/SDL.h> #include <SDL2/SDL_mixer.h> #else #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #endif // defined HAVE_SDL2 #endif /* HAVE_LIBSDL_MIXER */ #include <vector> #include "audio/types.h" #include "utils/video_pattern_generator.hpp" #define AUDIO_SAMPLE_RATE 48000 #define AUDIO_BPS 2 #define BUFFER_SEC 1 constexpr int AUDIO_BUFFER_SIZE(int ch_count) { return AUDIO_SAMPLE_RATE * AUDIO_BPS * ch_count * BUFFER_SEC; } #define MOD_NAME "[testcard] " constexpr video_desc default_format = { 1920, 1080, UYVY, 25.0, INTERLACED_MERGED, 1 }; using rang::fg; using rang::style; using namespace std; struct testcard_state { std::chrono::steady_clock::time_point last_frame_time; int pan; char *data {nullptr}; std::chrono::steady_clock::time_point t0; struct video_frame *frame{nullptr}; int frame_linesize; struct video_frame *tiled; struct audio_frame audio; char **tiles_data; int tiles_cnt_horizontal; int tiles_cnt_vertical; vector <char> audio_data; struct ring_buffer *midi_buf{}; enum class grab_audio_t { NONE, ANY, MIDI, SINE, } grab_audio = grab_audio_t::NONE; unsigned int still_image; string pattern{"bars"}; }; #if defined HAVE_LIBSDL_MIXER && ! defined HAVE_MACOSX static void midi_audio_callback(int chan, void *stream, int len, void *udata) { UNUSED(chan); struct testcard_state *s = (struct testcard_state *) udata; ring_buffer_write(s->midi_buf, static_cast<const char *>(stream), len); } #endif static auto configure_sdl_mixer_audio(struct testcard_state *s) { #if defined HAVE_LIBSDL_MIXER && ! defined HAVE_MACOSX char filename[1024] = ""; int fd; Mix_Music *music; ssize_t bytes_written = 0l; SDL_Init(SDL_INIT_AUDIO); if( Mix_OpenAudio( AUDIO_SAMPLE_RATE, AUDIO_S16LSB, s->audio.ch_count, 4096 ) == -1 ) { fprintf(stderr,"[testcard] error initalizing sound\n"); return false; } strncpy(filename, "/tmp/uv.midiXXXXXX", sizeof filename - 1); fd = mkstemp(filename); if (fd < 0) { perror("mkstemp"); return false; } do { ssize_t ret; ret = write(fd, song1 + bytes_written, sizeof(song1) - bytes_written); if(ret < 0) return false; bytes_written += ret; } while (bytes_written < (ssize_t) sizeof(song1)); close(fd); music = Mix_LoadMUS(filename); // register grab as a postmix processor if (!Mix_RegisterEffect(MIX_CHANNEL_POST, midi_audio_callback, nullptr, s)) { printf("[testcard] Mix_RegisterEffect: %s\n", Mix_GetError()); return false; } if(Mix_PlayMusic(music,-1)==-1){ fprintf(stderr, "[testcard] error playing midi\n"); return false; } Mix_Volume(-1, 0); s->midi_buf = ring_buffer_init(AUDIO_BUFFER_SIZE(s->audio.ch_count) /* 1 sec */); cout << MOD_NAME << "Initialized MIDI\n"; return true; #else UNUSED(s); return false; #endif } static void configure_fallback_audio(struct testcard_state *s) { static_assert(AUDIO_BPS == sizeof(int16_t), "Only 2-byte audio is supported for testcard audio at the moment"); const int frequency = 1000; const double scale = 0.1; for (int i = 0; i < AUDIO_BUFFER_SIZE(s->audio.ch_count) / AUDIO_BPS; i += 1) { *(reinterpret_cast<int16_t*>(&s->audio_data[i * AUDIO_BPS])) = round(sin((static_cast<double>(i) / (static_cast<double>(AUDIO_SAMPLE_RATE) / frequency)) * M_PI * 2. ) * ((1LL << (AUDIO_BPS * 8)) / 2 - 1) * scale); } } static auto configure_audio(struct testcard_state *s) { s->audio.bps = AUDIO_BPS; s->audio.ch_count = audio_capture_channels > 0 ? audio_capture_channels : DEFAULT_AUDIO_CAPTURE_CHANNELS; s->audio.sample_rate = AUDIO_SAMPLE_RATE; s->audio.max_size = AUDIO_BUFFER_SIZE(s->audio.ch_count); s->audio_data.resize(s->audio.max_size); s->audio.data = s->audio_data.data(); if (s->grab_audio != testcard_state::grab_audio_t::SINE) { if (configure_sdl_mixer_audio(s)) { s->grab_audio = testcard_state::grab_audio_t::MIDI; return true; } if (s->grab_audio == testcard_state::grab_audio_t::MIDI) { return false; } } LOG(LOG_LEVEL_WARNING) << MOD_NAME "SDL-mixer missing, running on Mac or other problem - using fallback audio.\n"; configure_fallback_audio(s); s->grab_audio = testcard_state::grab_audio_t::SINE; return true; } static int configure_tiling(struct testcard_state *s, const char *fmt) { char *tmp, *token, *saveptr = NULL; int tile_cnt; int x; int grid_w, grid_h; if(fmt[1] != '=') return 1; tmp = strdup(&fmt[2]); token = strtok_r(tmp, "x", &saveptr); grid_w = atoi(token); token = strtok_r(NULL, "x", &saveptr); grid_h = atoi(token); free(tmp); s->tiled = vf_alloc(grid_w * grid_h); s->tiles_cnt_horizontal = grid_w; s->tiles_cnt_vertical = grid_h; s->tiled->color_spec = s->frame->color_spec; s->tiled->fps = s->frame->fps; s->tiled->interlacing = s->frame->interlacing; tile_cnt = grid_w * grid_h; assert(tile_cnt >= 1); s->tiles_data = (char **) malloc(tile_cnt * sizeof(char *)); /* split only horizontally!!!!!! */ vf_split(s->tiled, s->frame, grid_w, 1, 1 /*prealloc*/); /* for each row, make the tile data correct. * .data pointers of same row point to same block, * but different row */ for(x = 0; x < grid_w; ++x) { int y; s->tiles_data[x] = s->tiled->tiles[x].data; s->tiled->tiles[x].width = s->frame->tiles[0].width/ grid_w; s->tiled->tiles[x].height = s->frame->tiles[0].height / grid_h; s->tiled->tiles[x].data_len = s->frame->tiles[0].data_len / (grid_w * grid_h); s->tiled->tiles[x].data = s->tiles_data[x] = (char *) realloc(s->tiled->tiles[x].data, s->tiled->tiles[x].data_len * grid_h * 2); memcpy(s->tiled->tiles[x].data + s->tiled->tiles[x].data_len * grid_h, s->tiled->tiles[x].data, s->tiled->tiles[x].data_len * grid_h); /* recopy tiles vertically */ for(y = 1; y < grid_h; ++y) { memcpy(&s->tiled->tiles[y * grid_w + x], &s->tiled->tiles[x], sizeof(struct tile)); /* make the pointers correct */ s->tiles_data[y * grid_w + x] = s->tiles_data[x] + y * s->tiled->tiles[x].height * vc_get_linesize(s->tiled->tiles[x].width, s->tiled->color_spec); s->tiled->tiles[y * grid_w + x].data = s->tiles_data[x] + y * s->tiled->tiles[x].height * vc_get_linesize(s->tiled->tiles[x].width, s->tiled->color_spec); } } return 0; } static const codec_t codecs_8b[] = {I420, RGBA, RGB, UYVY, YUYV, VIDEO_CODEC_NONE}; static const codec_t codecs_10b[] = {R10k, v210, VIDEO_CODEC_NONE}; static const codec_t codecs_12b[] = {Y216, RG48, R12L, VIDEO_CODEC_NONE}; static auto parse_format(char **fmt, char **save_ptr) { struct video_desc desc{}; desc.tile_count = 1; desc.interlacing = PROGRESSIVE; char *tmp = strtok_r(*fmt, ":", save_ptr); if (!tmp) { LOG(LOG_LEVEL_ERROR) << MOD_NAME << "Missing width!\n"; return video_desc{}; } desc.width = max<long long>(strtol(tmp, nullptr, 0), 0); if ((tmp = strtok_r(nullptr, ":", save_ptr)) == nullptr) { LOG(LOG_LEVEL_ERROR) << MOD_NAME << "Missing height!\n"; return video_desc{}; } desc.height = max<long long>(strtol(tmp, nullptr, 0), 0); if (desc.width * desc.height == 0) { fprintf(stderr, "Wrong dimensions for testcard.\n"); return video_desc{}; } if ((tmp = strtok_r(nullptr, ":", save_ptr)) == nullptr) { LOG(LOG_LEVEL_ERROR) << MOD_NAME << "Missing FPS!\n"; return video_desc{}; } char *endptr; desc.fps = strtod(tmp, &endptr); if (strlen(endptr) != 0) { // optional interlacing suffix desc.interlacing = get_interlacing_from_suffix(endptr); if (desc.interlacing != PROGRESSIVE && desc.interlacing != SEGMENTED_FRAME && desc.interlacing != INTERLACED_MERGED) { // tff or bff log_msg(LOG_LEVEL_ERROR, "Unsuppored interlacing format!\n"); return video_desc{}; } if (desc.interlacing == INTERLACED_MERGED) { desc.fps /= 2; } } if ((tmp = strtok_r(nullptr, ":", save_ptr)) == nullptr) { LOG(LOG_LEVEL_ERROR) << MOD_NAME << "Missing pixel format!\n"; return video_desc{}; } desc.color_spec = get_codec_from_name(tmp); if (desc.color_spec == VIDEO_CODEC_NONE) { LOG(LOG_LEVEL_ERROR) << MOD_NAME << "Unknown codec '" << tmp << "'\n"; return video_desc{}; } { const codec_t *sets[] = {codecs_8b, codecs_10b, codecs_12b}; bool supported = false; for (int i = 0; i < (int) (sizeof sets / sizeof sets[0]); ++i) { const codec_t *it = sets[i]; while (*it != VIDEO_CODEC_NONE) { if (desc.color_spec == *it++) { supported = true; } } } if (!supported) { LOG(LOG_LEVEL_ERROR) << MOD_NAME << "Unsupported codec '" << tmp << "'\n"; return video_desc{}; } } *fmt = nullptr; return desc; } static int vidcap_testcard_init(struct vidcap_params *params, void **state) { struct testcard_state *s = nullptr; char *filename; const char *strip_fmt = NULL; FILE *in = NULL; char *save_ptr = NULL; char *tmp; if (vidcap_params_get_fmt(params) == NULL || strcmp(vidcap_params_get_fmt(params), "help") == 0) { printf("testcard options:\n"); cout << BOLD(RED("\t-t testcard") << ":<width>:<height>:<fps>:<codec>[:filename=<filename>][:p][:s=<X>x<Y>][:i|:sf][:still][:pattern=<pattern>][:apattern=sine|midi]\n"); cout << "where\n"; cout << BOLD("\t<filename>") << " - use file named filename instead of default bars\n"; cout << BOLD("\tp") << " - pan with frame\n"; cout << BOLD("\ts") << " - split the frames into XxY separate tiles\n"; cout << BOLD("\ti|sf") << " - send as interlaced or segmented frame (if none of those is set, progressive is assumed)\n"; cout << BOLD("\tstill") << " - send still image\n"; cout << BOLD("\tpattern") << " - pattern to use, use \"" << BOLD("pattern=help") << "\" for options\n"; cout << BOLD("\tapattern") << " - audio pattern to use - \"sine\" or an included \"midi\"\n"; show_codec_help("testcard", codecs_8b, codecs_10b, codecs_12b); return VIDCAP_INIT_NOERR; } s = new testcard_state(); if (!s) return VIDCAP_INIT_FAIL; char *fmt = strdup(vidcap_params_get_fmt(params)); char *ptr = fmt; struct video_desc desc = [&]{ return strlen(ptr) == 0 || !isdigit(ptr[0]) ? default_format : parse_format(&ptr, &save_ptr);}(); if (!desc) { goto error; } s->still_image = FALSE; s->frame = vf_alloc_desc(desc); vf_get_tile(s->frame, 0)->data = static_cast<char *>(malloc(s->frame->tiles[0].data_len * 2)); s->frame_linesize = vc_get_linesize(desc.width, desc.color_spec); filename = NULL; tmp = strtok_r(ptr, ":", &save_ptr); while (tmp) { if (strcmp(tmp, "p") == 0) { s->pan = 48; } else if (strncmp(tmp, "filename=", strlen("filename=")) == 0) { filename = tmp + strlen("filename="); in = fopen(filename, "r"); if (!in) { perror("fopen"); goto error; } fseek(in, 0L, SEEK_END); long filesize = ftell(in); assert(filesize >= 0); fseek(in, 0L, SEEK_SET); if (s->frame->tiles[0].data_len != static_cast<unsigned>(filesize)) { int level = s->frame->tiles[0].data_len < static_cast<unsigned>(filesize) ? LOG_LEVEL_WARNING : LOG_LEVEL_ERROR; LOG(level) << MOD_NAME << "Wrong file size for selected " "resolution and codec. File size " << filesize << ", " "computed size " << s->frame->tiles[0].data_len << "\n"; filesize = s->frame->tiles[0].data_len; if (level == LOG_LEVEL_ERROR) { goto error; } } if (in == nullptr || fread(vf_get_tile(s->frame, 0)->data, filesize, 1, in) != 1) { log_msg(LOG_LEVEL_ERROR, "Cannot read file %s\n", filename); goto error; } fclose(in); in = NULL; } else if (strncmp(tmp, "s=", 2) == 0) { strip_fmt = tmp; } else if (strcmp(tmp, "i") == 0) { s->frame->interlacing = INTERLACED_MERGED; log_msg(LOG_LEVEL_WARNING, "[testcard] Deprecated 'i' option. Use format testcard:1920:1080:50i:UYVY instead!\n"); } else if (strcmp(tmp, "sf") == 0) { s->frame->interlacing = SEGMENTED_FRAME; log_msg(LOG_LEVEL_WARNING, "[testcard] Deprecated 'sf' option. Use format testcard:1920:1080:25sf:UYVY instead!\n"); } else if (strcmp(tmp, "still") == 0) { s->still_image = TRUE; } else if (strncmp(tmp, "pattern=", strlen("pattern=")) == 0) { const char *pattern = tmp + strlen("pattern="); s->pattern = pattern; } else if (strstr(tmp, "apattern=") == tmp) { s->grab_audio = strcasecmp(tmp + strlen("apattern="), "sine") == 0 ? testcard_state::grab_audio_t::SINE : testcard_state::grab_audio_t::MIDI; } else { fprintf(stderr, "[testcard] Unknown option: %s\n", tmp); goto error; } tmp = strtok_r(NULL, ":", &save_ptr); } if (!filename) { auto data = video_pattern_generate(s->pattern.c_str(), s->frame->tiles[0].width, s->frame->tiles[0].height, s->frame->color_spec); if (!data) { goto error; } memcpy(vf_get_tile(s->frame, 0)->data, data.get(), s->frame->tiles[0].data_len); } // duplicate the image to allow scrolling memcpy(vf_get_tile(s->frame, 0)->data + vf_get_tile(s->frame, 0)->data_len, vf_get_tile(s->frame, 0)->data, vf_get_tile(s->frame, 0)->data_len); if (!s->still_image && codec_is_planar(s->frame->color_spec)) { log_msg(LOG_LEVEL_WARNING, MOD_NAME "Planar pixel format '%s', using still picture.\n", get_codec_name(s->frame->color_spec)); s->still_image = true; } s->last_frame_time = std::chrono::steady_clock::now(); printf("Testcard capture set to %dx%d, bpp %f\n", vf_get_tile(s->frame, 0)->width, vf_get_tile(s->frame, 0)->height, get_bpp(s->frame->color_spec)); if(strip_fmt != NULL) { if(configure_tiling(s, strip_fmt) != 0) { goto error; } } if(vidcap_params_get_flags(params) & VIDCAP_FLAG_AUDIO_EMBEDDED) { if (s->grab_audio == testcard_state::grab_audio_t::NONE) { s->grab_audio = testcard_state::grab_audio_t::ANY; } if (!configure_audio(s)) { LOG(LOG_LEVEL_ERROR) << "Cannot initialize audio!\n"; goto error; } } else { s->grab_audio = testcard_state::grab_audio_t::NONE; } free(fmt); s->data = s->frame->tiles[0].data; *state = s; return VIDCAP_INIT_OK; error: free(fmt); free(s->data); vf_free(s->frame); if (in) fclose(in); delete s; return VIDCAP_INIT_FAIL; } static void vidcap_testcard_done(void *state) { struct testcard_state *s = (struct testcard_state *) state; free(s->data); if (s->tiled) { int i; for (i = 0; i < s->tiles_cnt_horizontal; ++i) { free(s->tiles_data[i]); } vf_free(s->tiled); } vf_free(s->frame); ring_buffer_destroy(s->midi_buf); delete s; } static struct video_frame *vidcap_testcard_grab(void *arg, struct audio_frame **audio) { struct testcard_state *state; state = (struct testcard_state *)arg; std::chrono::steady_clock::time_point curr_time = std::chrono::steady_clock::now(); if (std::chrono::duration_cast<std::chrono::duration<double>>(curr_time - state->last_frame_time).count() < 1.0 / state->frame->fps) { return NULL; } state->last_frame_time = curr_time; if (state->grab_audio != testcard_state::grab_audio_t::NONE) { if (state->grab_audio == testcard_state::grab_audio_t::MIDI) { state->audio.data_len = ring_buffer_read(state->midi_buf, state->audio.data, state->audio.max_size); } else if (state->grab_audio == testcard_state::grab_audio_t::SINE) { state->audio.data_len = state->audio.ch_count * state->audio.bps * AUDIO_SAMPLE_RATE / state->frame->fps; state->audio.data += state->audio.data_len; if (state->audio.data + state->audio.data_len > state->audio_data.data() + AUDIO_BUFFER_SIZE(state->audio.ch_count)) { state->audio.data = state->audio_data.data(); } } else { abort(); } if(state->audio.data_len > 0) *audio = &state->audio; else *audio = NULL; } else { *audio = NULL; } if(!state->still_image) { vf_get_tile(state->frame, 0)->data += state->frame_linesize + state->pan; } if (vf_get_tile(state->frame, 0)->data > state->data + state->frame->tiles[0].data_len) { vf_get_tile(state->frame, 0)->data = state->data; } if (state->tiled) { /* update tile data instead */ int i; int count = state->tiled->tile_count; for (i = 0; i < count; ++i) { /* shift - for semantics of vars refer to configure_tiling*/ state->tiled->tiles[i].data += vc_get_linesize( state->tiled->tiles[i].width, state->tiled->color_spec); /* if out of data, move to beginning * keep in mind that we have two "pictures" for * every tile stored sequentially */ if(state->tiled->tiles[i].data >= state->tiles_data[i] + state->tiled->tiles[i].data_len * state->tiles_cnt_vertical) { state->tiled->tiles[i].data = state->tiles_data[i]; } } return state->tiled; } return state->frame; } static struct vidcap_type *vidcap_testcard_probe(bool verbose, void (**deleter)(void *)) { struct vidcap_type *vt; *deleter = free; vt = (struct vidcap_type *) calloc(1, sizeof(struct vidcap_type)); if (vt == NULL) { return NULL; } vt->name = "testcard"; vt->description = "Video testcard"; if (!verbose) { return vt; } vt->card_count = 1; vt->cards = (struct device_info *) calloc(vt->card_count, sizeof(struct device_info)); snprintf(vt->cards[0].name, sizeof vt->cards[0].name, "Testing signal"); struct { int width; int height; } sizes[] = { {1280, 720}, {1920, 1080}, {3840, 2160}, }; int framerates[] = {24, 30, 60}; const char * const pix_fmts[] = {"UYVY", "RGB"}; snprintf(vt->cards[0].modes[0].name, sizeof vt->cards[0].modes[0].name, "Default"); snprintf(vt->cards[0].modes[0].id, sizeof vt->cards[0].modes[0].id, "{\"width\":\"\", " "\"height\":\"\", " "\"format\":\"\", " "\"fps\":\"\"}"); int i = 1; for(const auto &pix_fmt : pix_fmts){ for(const auto &size : sizes){ for(const auto &fps : framerates){ snprintf(vt->cards[0].modes[i].name, sizeof vt->cards[0].name, "%dx%d@%d %s", size.width, size.height, fps, pix_fmt); snprintf(vt->cards[0].modes[i].id, sizeof vt->cards[0].modes[0].id, "{\"width\":\"%d\", " "\"height\":\"%d\", " "\"format\":\"%s\", " "\"fps\":\"%d\"}", size.width, size.height, pix_fmt, fps); i++; } } } return vt; } static const struct video_capture_info vidcap_testcard_info = { vidcap_testcard_probe, vidcap_testcard_init, vidcap_testcard_done, vidcap_testcard_grab, true }; REGISTER_MODULE(testcard, &vidcap_testcard_info, LIBRARY_CLASS_VIDEO_CAPTURE, VIDEO_CAPTURE_ABI_VERSION); /* vim: set expandtab sw=8: */
39.985444
229
0.514998
[ "vector" ]
f6eab3b6c5f1b500ebeb6b82de0bb81df365575d
19,574
cpp
C++
App/App/examples/053_lab1_Third/053_enviroment.cpp
hyunjun529/Simple-Character-Animation-Reinforce-Learninng
2150bc894b2c7aac2b7a2c24b3dc95bcb0dc3658
[ "MIT" ]
8
2017-02-20T09:15:46.000Z
2021-01-08T04:30:23.000Z
App/App/examples/053_lab1_Third/053_enviroment.cpp
hyunjun529/Simple-Character-Animation-Reinforce-Learninng
2150bc894b2c7aac2b7a2c24b3dc95bcb0dc3658
[ "MIT" ]
null
null
null
App/App/examples/053_lab1_Third/053_enviroment.cpp
hyunjun529/Simple-Character-Animation-Reinforce-Learninng
2150bc894b2c7aac2b7a2c24b3dc95bcb0dc3658
[ "MIT" ]
3
2019-03-03T17:52:31.000Z
2021-12-01T00:49:40.000Z
#include "053_enviroment.h" #include "../CommonEnviroment.h" #include "btBulletDynamicsCommon.h" #include "LinearMath/btVector3.h" #include "LinearMath/btAlignedObjectArray.h" #include "CommonInterfaces/CommonRigidBodyBase.h" #include <iostream> #include "Actions.h" #include "Targets.h" #include "Logger.h" #include "Lab1ReinforcementLearning.h" struct lab1Example3 : public CommonRigidBodyBase { float Capsule_Width = 0.5f; float Capsule_Radius = 0.12f; bool m_once; btAlignedObjectArray<btJointFeedback*> m_jointFeedback; btHingeConstraint* hinge_shoulder; btHingeConstraint* hinge_elbow; btRigidBody* linkBody[3]; btVector3 groundOrigin_target; btRigidBody* body; short collisionFilterGroup = short(btBroadphaseProxy::CharacterFilter); short collisionFilterMask = short(btBroadphaseProxy::AllFilter ^ (btBroadphaseProxy::CharacterFilter)); int selected_target = 0; float target_height[TARGET_SIZE] = { TARGET_0_HEIGHT, TARGET_1_HEIGHT, TARGET_2_HEIGHT, TARGET_3_HEIGHT, TARGET_4_HEIGHT, TARGET_5_HEIGHT, }; float Fist_velocity; float F2T_distance_; float F2T_angle_; float sd_angle_; float sd_angular_velocity; float eb_angle_; float eb_angular_velocity; Lab1ReinforcementLearning rl_; Logger lg_; const int initStep = 100; const int maxStep = 500 + initStep; int cntStep; bool chkStudying; bool chkPrinting; lab1Example3(struct GUIHelperInterface* helper); virtual ~lab1Example3(); virtual void initPhysics(); virtual void stepSimulation(float deltaTime); void lockLiftHinge(btHingeConstraint* hinge); virtual bool keyboardCallback(int key, int state); virtual void resetCamera() { float dist = 5; float pitch = 270; float yaw = 21; float targetPos[3] = { -1.34,3.4,-0.44 }; m_guiHelper->resetCamera(dist, pitch, yaw, targetPos[0], targetPos[1], targetPos[2]); } // Controller evnets void initState(lab1Example3* target) { selected_target = (int)rand() % 6; target->m_guiHelper->removeAllGraphicsInstances(); target->initPhysics(); } void moveEbAngleUp(btHingeConstraint *target) { target->setLimit(M_PI / 360.0f, M_PI / 1.2f); target->enableAngularMotor(true, 6.0, 4000.f); } void moveEbAngleDown(btHingeConstraint *target) { target->setLimit(M_PI / 360.0f, M_PI / 1.2f); target->enableAngularMotor(true, -6.0, 4000.f); } void moveEbAngleStay(btHingeConstraint *target) { lockLiftHinge(target); } void moveSdAngleUp(btHingeConstraint *target) { target->setLimit(M_PI / 360.0f, M_PI / 1.2f); target->enableAngularMotor(true, 6.0, 4000.f); } void moveSdAngleDown(btHingeConstraint *target) { target->setLimit(M_PI / 360.0f, M_PI / 1.2f); target->enableAngularMotor(true, -6.0, 4000.f); } void moveSdAngleStay(btHingeConstraint *target) { lockLiftHinge(target); } // get States float getF2TDistance() { return sqrt(pow((body->getCenterOfMassPosition().getZ() - linkBody[2]->getCenterOfMassPosition().getZ()), 2) + pow((body->getCenterOfMassPosition().getY() - linkBody[2]->getCenterOfMassPosition().getY()), 2)) - 0.225; } float getF2TAngle() { return (atan((linkBody[2]->getCenterOfMassPosition().getZ() - body->getCenterOfMassPosition().getZ()) / (linkBody[2]->getCenterOfMassPosition().getY() - body->getCenterOfMassPosition().getY()))) * 180 / M_PI; } float getFistVelocity() { return abs(linkBody[2]->getVelocityInLocalPoint(linkBody[2]->getCenterOfMassPosition()).getZ()); } float getSdAngle() { return hinge_shoulder->getHingeAngle() / M_PI * 180; } float getSdAngularVelocity() { return abs(linkBody[0]->getAngularVelocity().getX()); } float getEbAngle() { return hinge_elbow->getHingeAngle() / M_PI * 180; } float getEbAngularVelocity() { return abs(linkBody[1]->getAngularVelocity().getX()); } }; lab1Example3::lab1Example3(struct GUIHelperInterface* helper) :CommonRigidBodyBase(helper), m_once(true) { std::cout.precision(5); cntStep = 0; chkStudying = true; chkPrinting = true; lg_.fs_open("053_log.csv"); /******************************************************************************************** * start init rl_ *********************************************************************************************/ // h529 : 이전 게임의 기억을 가져감 rl_.num_input_histories_ = 1; // h529 : 기억을 재생함, pool로 사용 중 rl_.num_exp_replay_ = 0; // h529 : 현재 총 7개 rl_.num_state_variables_ = 7; // h529 : 행동할 수 있는 Action의 개수, 현재 총 9개 rl_.num_game_actions_ = 9; rl_.initialize(); for (int h = 0; h < rl_.num_input_histories_; h++) { rl_.recordHistory(VectorND<float>(rl_.num_state_variables_), 0.0f, 2, VectorND<float>(rl_.num_game_actions_)); // choice 2 is stay } /******************************************************************************************** * end init rl_ *********************************************************************************************/ } lab1Example3::~lab1Example3() { for (int i = 0; i<m_jointFeedback.size(); i++) { delete m_jointFeedback[i]; } } void lab1Example3::lockLiftHinge(btHingeConstraint* hinge) { btScalar hingeAngle = hinge->getHingeAngle(); btScalar lowLim = hinge->getLowerLimit(); btScalar hiLim = hinge->getUpperLimit(); hinge->enableAngularMotor(false, 0, 0); if (hingeAngle < lowLim) { hinge->setLimit(lowLim, lowLim); } else if (hingeAngle > hiLim) { hinge->setLimit(hiLim, hiLim); } else { hinge->setLimit(hingeAngle, hingeAngle); } return; } void lab1Example3::stepSimulation(float deltaTime) { if (cntStep < initStep) { cntStep++; m_dynamicsWorld->stepSimulation(1. / 240, 0); static int count = 0; return; } /******************************************************************************************** * start set Action *********************************************************************************************/ // set Vector rl_.forward(); VectorND<float> output_vector_temp; rl_.nn_.copyOutputVectorTo(false, output_vector_temp); VectorND<float> output_target_temp; // set Action float dice = (chkStudying) ? (0.3f) : (0.0f); int action_ = rl_.nn_.getOutputIXEpsilonGreedy(dice); switch (action_) { case ACTION_SD_UP_EB_UP: { moveSdAngleUp(hinge_shoulder); moveEbAngleUp(hinge_elbow); break; } case ACTION_SD_UP_EB_DN: { moveSdAngleUp(hinge_shoulder); moveEbAngleDown(hinge_elbow); break; } case ACTION_SD_UP_EB_ST: { moveSdAngleUp(hinge_shoulder); moveEbAngleStay(hinge_elbow); break; } case ACTION_SD_DN_EB_UP: { moveSdAngleDown(hinge_shoulder); moveEbAngleUp(hinge_elbow); break; } case ACTION_SD_DN_EB_DN: { moveSdAngleDown(hinge_shoulder); moveEbAngleDown(hinge_elbow); break; } case ACTION_SD_DN_EB_ST: { moveSdAngleDown(hinge_shoulder); moveEbAngleStay(hinge_elbow); break; } case ACTION_SD_ST_EB_UP: { moveSdAngleStay(hinge_shoulder); moveEbAngleUp(hinge_elbow); break; } case ACTION_SD_ST_EB_DN: { moveSdAngleStay(hinge_shoulder); moveEbAngleDown(hinge_elbow); break; } case ACTION_SD_ST_EB_ST: { moveSdAngleStay(hinge_shoulder); moveEbAngleStay(hinge_elbow); break; } default: {} } /******************************************************************************************** * end set Action *********************************************************************************************/ /******************************************************************************************** * start get State *********************************************************************************************/ // get about Fist to Target F2T_distance_ = getF2TDistance(); F2T_angle_ = getF2TAngle() / 180; // get Fist Velocity Fist_velocity = getFistVelocity(); // get Shoulder states sd_angle_ = getSdAngle() / 180; sd_angular_velocity = getSdAngularVelocity(); // get Elbow states eb_angle_ = getEbAngle() / 180; eb_angular_velocity = getEbAngularVelocity(); //collison check bool chkCollision = false; int numManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { if (m_dynamicsWorld->getDispatcher()->getNumManifolds() == 0) continue; btPersistentManifold* contactManifold = m_dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); const btCollisionObject* obA = contactManifold->getBody0(); const btCollisionObject* obB = contactManifold->getBody1(); int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& pt = contactManifold->getContactPoint(j); if (pt.getDistance() < 0.f) { const btVector3& ptA = pt.getPositionWorldOnA(); const btVector3& ptB = pt.getPositionWorldOnB(); const btVector3& normalOnB = pt.m_normalWorldOnB; //check the head or body chkCollision = true; } } } // calc Reward float weightStepEarly = (1 - ((float)cntStep / ((float)maxStep * 1.25f))); float weightDistance = (1 - (F2T_distance_ / 2.5f)); float weightAngle = (abs(F2T_angle_) * 2.0f); float weight_sd_Angle = (1 - ((abs(sd_angle_ * 180 - 90))) / 150); float weight_eb_Angle = (1 - (eb_angle_ * 180) / 150); float weight_fist_vel = (1 - (Fist_velocity / 60)); float reward_ = weightDistance * weightAngle * weight_sd_Angle * weight_eb_Angle; // set state VectorND VectorND<float> state_; state_.initialize(rl_.num_state_variables_, true); state_[0] = sd_angle_; state_[1] = sd_angular_velocity; state_[2] = eb_angle_; state_[3] = eb_angular_velocity; state_[4] = F2T_distance_; state_[5] = F2T_angle_; state_[6] = Fist_velocity; // Print current state if (chkPrinting) { std::cout << std::fixed << "selcted_action : " << action_ << "\t"; //std::cout << std::fixed << "sd_ang : " << sd_angle_ << "\t" << "sd_ang_vel : " << sd_angular_velocity << "\t"; //std::cout << std::fixed << "eb_ang : " << eb_angle_ << "\t" << "eb_ang_vel : " << eb_angular_velocity << "\t"; std::cout << std::fixed << "F2T_dis : " << F2T_distance_ << "\t"; std::cout << std::fixed << "F2T_ang : " << F2T_angle_ << "\t"; std::cout << std::fixed << "Fist_vel : " << Fist_velocity << "\t"; //std::cout << std::fixed << "weight_Fist_vel : " << weight_fist_vel << "\t"; //std::cout << std::fixed << "weight_F2T_Distance : " << weightDistance << "\t"; //std::cout << std::fixed << "weight_F2T_angle : " << weightAngle << "\t"; std::cout << std::fixed << "reward : " << reward_ << "\t"; std::cout << std::fixed << "current_step : " << cntStep << "\t"; if (chkCollision) std::cout << "Collision !!!!!!!!!!!!\t"; std::cout << std::endl; } // record history rl_.recordHistory(state_, reward_, action_, output_vector_temp); /******************************************************************************************** * end get State *********************************************************************************************/ /******************************************************************************************** * start Training *********************************************************************************************/ if ((chkCollision || cntStep > maxStep) && chkStudying) { // logging lg_.fout << sd_angle_ << ", " << eb_angle_ << ", " << F2T_angle_ << ", " << F2T_distance_ << ", " << selected_target << ", " << reward_ << ", " << cntStep << std::endl; // number of training int tr_num = (chkCollision) ? (100) : (10); // sd for (int tr = 0; tr < tr_num; tr++) for (int m_tr = rl_.memory_.num_elements_ - 2; m_tr >= rl_.num_input_histories_; m_tr--) { // h529 : 방학숙제에서 발췌 // stochastic training // h529 : 전체를 요약한 부분을 확률적으로 선택해서 학습하는 방법론 // h529 : http://sanghyukchun.github.io/74/ int m = rand() % (rl_.memory_.num_elements_ - 1 - rl_.num_input_histories_) + rl_.num_input_histories_; // memory index from end const int inv_m = m - (rl_.memory_.num_elements_ - 1); float Q_next = 0.0f; if (m != rl_.memory_.num_elements_ - 2) // if next is not the terminal state { // Q_next = ...; Q_next = rl_.memory_.q_values_array_[m + 1].getMaxValue(); } float Q_target; // Q_target = ...; Q_target = Q_next + rl_.memory_.reward_array_[m]; // forward propagation from previous inputs rl_.makeInputVectorFromHistory(inv_m - 1, rl_.old_input_vector_); rl_.nn_.setInputVector(rl_.old_input_vector_); for (int i = 0; i < 100; i++) { rl_.nn_.feedForward(); rl_.nn_.copyOutputVectorTo(false, output_target_temp); // output_target_temp[...] = ...; output_target_temp[rl_.memory_.selected_array_[m]] = Q_target; rl_.nn_.propBackward(output_target_temp); } rl_.nn_.check(); } // reset rl_.memory_.reset(); // is really need? for (int h = 0; h < rl_.num_input_histories_; h++) { rl_.recordHistory(VectorND<float>(rl_.num_state_variables_), 0.0f, 2, VectorND<float>(rl_.num_game_actions_)); // choice 2 is stay } cntStep = 0; initState(this); } if (chkCollision && chkStudying) { // reset rl_.memory_.reset(); // is really need? for (int h = 0; h < rl_.num_input_histories_; h++) { rl_.recordHistory(VectorND<float>(rl_.num_state_variables_), 0.0f, 2, VectorND<float>(rl_.num_game_actions_)); // choice 2 is stay } cntStep = 0; initState(this); } /******************************************************************************************** * end Training *********************************************************************************************/ cntStep++; m_dynamicsWorld->stepSimulation(1. / 240, 0); static int count = 0; } void lab1Example3::initPhysics() { int upAxis = 1; m_guiHelper->setUpAxis(upAxis); createEmptyDynamicsWorld(); m_dynamicsWorld->getSolverInfo().m_splitImpulse = false; m_dynamicsWorld->setGravity(btVector3(0, 0, -10)); m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld); int mode = btIDebugDraw::DBG_DrawWireframe + btIDebugDraw::DBG_DrawConstraints + btIDebugDraw::DBG_DrawConstraintLimits; m_dynamicsWorld->getDebugDrawer()->setDebugMode(mode); int numLinks = 3; bool spherical = false; bool canSleep = false; bool selfCollide = false; btVector3 baseHalfExtents(0.4f, 0.7f, 0.1f); btVector3 linkHalfExtents(0.05f, 0.37f, 0.1f); btBoxShape* baseBox = new btBoxShape(baseHalfExtents); btVector3 basePosition = btVector3(-0.9f, 3.0f, 0.f); btTransform baseWorldTrans; baseWorldTrans.setIdentity(); baseWorldTrans.setOrigin(basePosition); btVector3 basePosition_origen = btVector3(-0.4f, 4.f, 0.f); btTransform baseWorldTrans_origen; baseWorldTrans_origen.setIdentity(); baseWorldTrans_origen.setOrigin(basePosition_origen); //init the base btVector3 baseInertiaDiag(0.f, 0.f, 0.f); float baseMass = 0.f; float linkMass = 1.f; btRigidBody* base = createRigidBody(baseMass, baseWorldTrans, baseBox); m_dynamicsWorld->removeRigidBody(base); base->setDamping(0, 0); m_dynamicsWorld->addRigidBody(base, collisionFilterGroup, collisionFilterMask); /* btBoxShape* linkBox1 = new btBoxShape(linkHalfExtents); btBoxShape* linkBox2 = new btBoxShape(linkHalfExtents);*/ btCollisionShape* linkBox1 = new btCapsuleShape(Capsule_Radius, Capsule_Width); btCollisionShape* linkBox2 = new btCapsuleShape(Capsule_Radius, Capsule_Width); btSphereShape* linkSphere = new btSphereShape(radius); btRigidBody* prevBody = base; btQuaternion orn[3]; orn[0] = btQuaternion(btVector3(1, 0, 0), 0.25*3.1415926538); orn[1] = btQuaternion(btVector3(1, 0, 0), 0.75*3.1415926538); orn[2] = btQuaternion(btVector3(1, 0, 0), 0.25*3.1415926538); for (int i = 0; i<numLinks; i++) { btTransform linkTrans; linkTrans = baseWorldTrans_origen; linkTrans.setOrigin(basePosition_origen - btVector3(0, linkHalfExtents[1] * 2.f*(i / 4 + 1) - 0.1, i*0.5 + 0.2)); linkTrans.setRotation(orn[i]); btCollisionShape* colOb = 0; if (i == 0) { colOb = linkBox1; } else if (i == 1) { colOb = linkBox2; } else { colOb = linkSphere; } linkBody[i] = createRigidBody(linkMass, linkTrans, colOb); m_dynamicsWorld->removeRigidBody(linkBody[i]); m_dynamicsWorld->addRigidBody(linkBody[i], collisionFilterGroup, collisionFilterMask); linkBody[i]->setDamping(0, 0); btTypedConstraint* con = 0; if (i == 0) { //create a hinge constraint btVector3 pivotInA(0.5, -linkHalfExtents[1] + 1.0f, 0); btVector3 pivotInB(0, linkHalfExtents[1], 0); btVector3 axisInA(1, 0, 0); btVector3 axisInB(1, 0, 0); bool useReferenceA = true; hinge_shoulder = new btHingeConstraint(*prevBody, *linkBody[i], pivotInA, pivotInB, axisInA, axisInB, useReferenceA); hinge_shoulder->setLimit(M_PI / 0.24f, M_PI / 0.24f); m_dynamicsWorld->addConstraint(hinge_shoulder, true); con = hinge_shoulder; } else if (i == 1) { //create a hinge constraint btVector3 pivotInA(0, -linkHalfExtents[1], 0); btVector3 pivotInB(0, linkHalfExtents[1], 0); btVector3 axisInA(1, 0, 0); btVector3 axisInB(1, 0, 0); bool useReferenceA = true; hinge_elbow = new btHingeConstraint(*prevBody, *linkBody[i], pivotInA, pivotInB, axisInA, axisInB, useReferenceA); hinge_elbow->setLimit(M_PI / 1.92f, M_PI / 1.92f); m_dynamicsWorld->addConstraint(hinge_elbow, true); con = hinge_elbow; } else { btTransform pivotInA(btQuaternion::getIdentity(), btVector3(0, -radius, 0)); //par body's COM to cur body's COM offset btTransform pivotInB(btQuaternion::getIdentity(), btVector3(0, radius, 0)); //cur body's COM to cur body's PIV offset btGeneric6DofSpring2Constraint* fixed = new btGeneric6DofSpring2Constraint(*prevBody, *linkBody[i], pivotInA, pivotInB); fixed->setLinearLowerLimit(btVector3(0, 0, 0)); fixed->setLinearUpperLimit(btVector3(0, 0, 0)); fixed->setAngularLowerLimit(btVector3(0, 0, 0)); fixed->setAngularUpperLimit(btVector3(0, 0, 0)); con = fixed; } btAssert(con); if (con) { btJointFeedback* fb = new btJointFeedback(); m_jointFeedback.push_back(fb); con->setJointFeedback(fb); m_dynamicsWorld->addConstraint(con, true); } prevBody = linkBody[i]; } // Target Position btSphereShape* linkSphere_1 = new btSphereShape(radius); btTransform start; start.setIdentity(); groundOrigin_target = btVector3(-0.4f, target_height[selected_target], -1.6f); start.setOrigin(groundOrigin_target); body = createRigidBody(0, start, linkSphere_1); body->setFriction(0); m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); } bool lab1Example3::keyboardCallback(int key, int state) { bool handled = true; if (state) { switch (key) { case B3G_INSERT: { chkPrinting = (chkPrinting) ? (false) : (true); break; } case B3G_END: { chkStudying = (chkStudying) ? (false) : (true); break; } case B3G_HOME: { initState(this); break; } case B3G_LEFT_ARROW: { moveEbAngleUp(hinge_elbow); handled = true; break; } case B3G_RIGHT_ARROW: { moveEbAngleDown(hinge_elbow); handled = true; break; } case B3G_UP_ARROW: { moveSdAngleUp(hinge_shoulder); handled = true; break; } case B3G_DOWN_ARROW: { moveSdAngleDown(hinge_shoulder); handled = true; break; } } } else { switch (key) { case B3G_LEFT_ARROW: case B3G_RIGHT_ARROW: { lockLiftHinge(hinge_elbow); handled = true; break; } case B3G_UP_ARROW: case B3G_DOWN_ARROW: { lockLiftHinge(hinge_shoulder); handled = true; break; } default: break; } } return handled; } CommonExampleInterface* env_053(CommonExampleOptions& options) { return new lab1Example3(options.m_guiHelper); }
27.337989
219
0.641668
[ "vector" ]
f6f067ec74d33c28b051b65c3cad55dd24f166f9
14,008
cpp
C++
libminifi/src/c2/C2Client.cpp
tomhollingworth/nifi-minifi-cpp
65fad0d02d04463181470b21c8ea290ddd61c52a
[ "Apache-2.0" ]
null
null
null
libminifi/src/c2/C2Client.cpp
tomhollingworth/nifi-minifi-cpp
65fad0d02d04463181470b21c8ea290ddd61c52a
[ "Apache-2.0" ]
null
null
null
libminifi/src/c2/C2Client.cpp
tomhollingworth/nifi-minifi-cpp
65fad0d02d04463181470b21c8ea290ddd61c52a
[ "Apache-2.0" ]
null
null
null
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 <memory> #include <map> #include "c2/C2Client.h" #include "core/state/nodes/MetricsBase.h" #include "core/state/nodes/QueueMetrics.h" #include "core/state/nodes/AgentInformation.h" #include "core/state/nodes/ConfigurationChecksums.h" #include "core/state/nodes/RepositoryMetrics.h" #include "properties/Configure.h" #include "core/state/UpdateController.h" #include "core/controller/ControllerServiceProvider.h" #include "c2/C2Agent.h" #include "core/state/nodes/FlowInformation.h" #include "utils/file/FileSystem.h" namespace org { namespace apache { namespace nifi { namespace minifi { namespace c2 { C2Client::C2Client( std::shared_ptr<Configure> configuration, std::shared_ptr<core::Repository> provenance_repo, std::shared_ptr<core::Repository> flow_file_repo, std::shared_ptr<core::ContentRepository> content_repo, std::unique_ptr<core::FlowConfiguration> flow_configuration, std::shared_ptr<utils::file::FileSystem> filesystem, std::shared_ptr<core::logging::Logger> logger) : core::Flow(std::move(provenance_repo), std::move(flow_file_repo), std::move(content_repo), std::move(flow_configuration)), configuration_(std::move(configuration)), filesystem_(std::move(filesystem)), logger_(std::move(logger)) {} void C2Client::stopC2() { if (c2_agent_) { c2_agent_->stop(); } } bool C2Client::isC2Enabled() const { std::string c2_enable_str; configuration_->get(minifi::Configuration::nifi_c2_enable, "c2.enable", c2_enable_str); return utils::StringUtils::toBool(c2_enable_str).value_or(false); } void C2Client::initialize(core::controller::ControllerServiceProvider *controller, state::Pausable *pause_handler, state::StateMonitor* update_sink) { if (!isC2Enabled()) { return; } if (!configuration_->getAgentClass()) { logger_->log_info("Agent class is not predefined"); } configuration_->setFallbackAgentIdentifier(getControllerUUID().to_string()); { std::lock_guard<std::mutex> lock(initialization_mutex_); if (initialized_ && !flow_update_) { return; } } // root_response_nodes_ was not cleared before, it is unclear if that was intentional std::map<std::string, Connection*> connections; if (root_ != nullptr) { root_->getConnections(connections); } std::string class_csv; if (configuration_->get(minifi::Configuration::nifi_c2_root_classes, class_csv)) { std::vector<std::string> classes = utils::StringUtils::split(class_csv, ","); for (const std::string& clazz : classes) { auto instance = core::ClassLoader::getDefaultClassLoader().instantiate(clazz, clazz); auto response_node = utils::dynamic_unique_cast<state::response::ResponseNode>(std::move(instance)); if (nullptr == response_node) { logger_->log_error("No metric defined for %s", clazz); continue; } auto identifier = dynamic_cast<state::response::AgentIdentifier*>(response_node.get()); if (identifier != nullptr) { identifier->setAgentIdentificationProvider(configuration_); } auto monitor = dynamic_cast<state::response::AgentMonitor*>(response_node.get()); if (monitor != nullptr) { monitor->addRepository(provenance_repo_); monitor->addRepository(flow_file_repo_); monitor->setStateMonitor(update_sink); } auto agent_node = dynamic_cast<state::response::AgentNode*>(response_node.get()); if (agent_node != nullptr && controller != nullptr) { agent_node->setUpdatePolicyController(std::static_pointer_cast<controllers::UpdatePolicyControllerService>(controller->getControllerService(C2Agent::UPDATE_NAME)).get()); } if (agent_node != nullptr) { agent_node->setConfigurationReader([this](const std::string& key){ return configuration_->getString(key); }); } auto configuration_checksums = dynamic_cast<state::response::ConfigurationChecksums*>(response_node.get()); if (configuration_checksums) { configuration_checksums->addChecksumCalculator(configuration_->getChecksumCalculator()); configuration_checksums->addChecksumCalculator(flow_configuration_->getChecksumCalculator()); } auto flowMonitor = dynamic_cast<state::response::FlowMonitor*>(response_node.get()); if (flowMonitor != nullptr) { for (auto &con : connections) { flowMonitor->updateConnection(con.second); } flowMonitor->setStateMonitor(update_sink); flowMonitor->setFlowVersion(flow_configuration_->getFlowVersion()); } const auto responseNodeName = response_node->getName(); std::lock_guard<std::mutex> guard(metrics_mutex_); root_response_nodes_[responseNodeName] = std::move(response_node); } } initializeComponentMetrics(); loadC2ResponseConfiguration("nifi.c2.root.class.definitions"); std::lock_guard<std::mutex> lock(initialization_mutex_); if (!initialized_) { // C2Agent is initialized once, meaning that a C2-triggered flow/configuration update // might not be equal to a fresh restart c2_agent_ = std::make_unique<c2::C2Agent>(controller, pause_handler, update_sink, configuration_, filesystem_); c2_agent_->start(); initialized_ = true; } } std::optional<std::string> C2Client::fetchFlow(const std::string& uri) const { if (!c2_agent_) { return {}; } return c2_agent_->fetchFlow(uri); } void C2Client::initializeComponentMetrics() { { std::lock_guard<std::mutex> guard(metrics_mutex_); component_metrics_.clear(); } if (root_ == nullptr) { return; } std::vector<core::Processor*> processors; root_->getAllProcessors(processors); for (const auto processor : processors) { auto rep = dynamic_cast<state::response::ResponseNodeSource*>(processor); if (rep == nullptr) { continue; } // we have a metrics source. std::vector<std::shared_ptr<state::response::ResponseNode>> metric_vector; rep->getResponseNodes(metric_vector); std::lock_guard<std::mutex> guard(metrics_mutex_); for (auto& metric : metric_vector) { component_metrics_[metric->getName()] = metric; } } } void C2Client::loadC2ResponseConfiguration(const std::string &prefix) { std::string class_definitions; if (!configuration_->get(prefix, class_definitions)) { return; } std::vector<std::string> classes = utils::StringUtils::split(class_definitions, ","); for (const std::string& metricsClass : classes) { try { std::string option = prefix + "." + metricsClass; std::string classOption = option + ".classes"; std::string nameOption = option + ".name"; std::string name; if (!configuration_->get(nameOption, name)) { continue; } std::shared_ptr<state::response::ResponseNode> new_node = std::make_shared<state::response::ObjectNode>(name); if (configuration_->get(classOption, class_definitions)) { std::vector<std::string> classes = utils::StringUtils::split(class_definitions, ","); for (const std::string& clazz : classes) { // instantiate the object std::shared_ptr<core::CoreComponent> ptr = core::ClassLoader::getDefaultClassLoader().instantiate(clazz, clazz); if (nullptr == ptr) { const bool found_metric = [&] { std::lock_guard<std::mutex> guard{metrics_mutex_}; auto metric = component_metrics_.find(clazz); if (metric != component_metrics_.end()) { ptr = metric->second; return true; } return false; }(); if (!found_metric) { logger_->log_error("No metric defined for %s", clazz); continue; } } auto node = std::dynamic_pointer_cast<state::response::ResponseNode>(ptr); std::static_pointer_cast<state::response::ObjectNode>(new_node)->add_node(node); } } else { std::string optionName = option + "." + name; auto node = loadC2ResponseConfiguration(optionName, new_node); } std::lock_guard<std::mutex> guard{metrics_mutex_}; root_response_nodes_[name] = new_node; } catch (...) { logger_->log_error("Could not create metrics class %s", metricsClass); } } } std::shared_ptr<state::response::ResponseNode> C2Client::loadC2ResponseConfiguration(const std::string &prefix, std::shared_ptr<state::response::ResponseNode> prev_node) { std::string class_definitions; if (!configuration_->get(prefix, class_definitions)) { return prev_node; } std::vector<std::string> classes = utils::StringUtils::split(class_definitions, ","); for (const std::string& metricsClass : classes) { try { std::string option = prefix + "." + metricsClass; std::string classOption = option + ".classes"; std::string nameOption = option + ".name"; std::string name; if (!configuration_->get(nameOption, name)) { continue; } std::shared_ptr<state::response::ResponseNode> new_node = std::make_shared<state::response::ObjectNode>(name); if (name.find(',') != std::string::npos) { std::vector<std::string> sub_classes = utils::StringUtils::split(name, ","); for (const std::string& subClassStr : classes) { auto node = loadC2ResponseConfiguration(subClassStr, prev_node); if (node != nullptr) std::static_pointer_cast<state::response::ObjectNode>(prev_node)->add_node(node); } } else { if (configuration_->get(classOption, class_definitions)) { std::vector<std::string> classes = utils::StringUtils::split(class_definitions, ","); for (const std::string& clazz : classes) { // instantiate the object std::shared_ptr<core::CoreComponent> ptr = core::ClassLoader::getDefaultClassLoader().instantiate(clazz, clazz); if (nullptr == ptr) { const bool found_metric = [&] { std::lock_guard<std::mutex> guard{metrics_mutex_}; auto metric = component_metrics_.find(clazz); if (metric != component_metrics_.end()) { ptr = metric->second; return true; } return false; }(); if (!found_metric) { logger_->log_error("No metric defined for %s", clazz); continue; } } auto node = std::dynamic_pointer_cast<state::response::ResponseNode>(ptr); std::static_pointer_cast<state::response::ObjectNode>(new_node)->add_node(node); } if (!new_node->isEmpty()) std::static_pointer_cast<state::response::ObjectNode>(prev_node)->add_node(new_node); } else { std::string optionName = option + "." + name; auto sub_node = loadC2ResponseConfiguration(optionName, new_node); std::static_pointer_cast<state::response::ObjectNode>(prev_node)->add_node(sub_node); } } } catch (...) { logger_->log_error("Could not create metrics class %s", metricsClass); } } return prev_node; } std::shared_ptr<state::response::ResponseNode> C2Client::getMetricsNode(const std::string& metrics_class) const { if (!metrics_class.empty()) { std::lock_guard<std::mutex> lock(metrics_mutex_); const auto citer = component_metrics_.find(metrics_class); if (citer != component_metrics_.end()) { return citer->second; } } else { std::lock_guard<std::mutex> lock(metrics_mutex_); const auto iter = root_response_nodes_.find("metrics"); if (iter != root_response_nodes_.end()) { return iter->second; } } return nullptr; } std::vector<std::shared_ptr<state::response::ResponseNode>> C2Client::getHeartbeatNodes(bool include_manifest) const { std::string fullHb{"true"}; configuration_->get(minifi::Configuration::nifi_c2_full_heartbeat, fullHb); const bool include = include_manifest || fullHb == "true"; std::vector<std::shared_ptr<state::response::ResponseNode>> nodes; nodes.reserve(root_response_nodes_.size()); std::lock_guard<std::mutex> lock(metrics_mutex_); for (const auto &entry : root_response_nodes_) { auto identifier = std::dynamic_pointer_cast<state::response::AgentIdentifier>(entry.second); if (identifier) { identifier->includeAgentManifest(include); } nodes.push_back(entry.second); } return nodes; } void C2Client::updateResponseNodeConnections() { std::map<std::string, Connection*> connections; if (root_ != nullptr) { root_->getConnections(connections); } std::lock_guard<std::mutex> lock(metrics_mutex_); for (auto& [_, responseNode] : root_response_nodes_) { auto flowMonitor = dynamic_cast<state::response::FlowMonitor*>(responseNode.get()); if (flowMonitor != nullptr) { flowMonitor->clearConnections(); for (const auto &con: connections) { flowMonitor->updateConnection(con.second); } } } } } // namespace c2 } // namespace minifi } // namespace nifi } // namespace apache } // namespace org
38.589532
178
0.672401
[ "object", "vector" ]
f6f12b974e1f4e8a612f8249d4b6142af8cced5e
55,242
cpp
C++
mps_voxels/src/tracker.cpp
UM-ARM-Lab/multihypothesis_segmentation_tracking
801d460afbf028100374c880bc684187ec8b909f
[ "MIT" ]
3
2020-10-31T21:42:36.000Z
2021-12-16T12:56:02.000Z
mps_voxels/src/tracker.cpp
UM-ARM-Lab/multihypothesis_segmentation_tracking
801d460afbf028100374c880bc684187ec8b909f
[ "MIT" ]
1
2020-11-11T03:46:08.000Z
2020-11-11T03:46:08.000Z
mps_voxels/src/tracker.cpp
UM-ARM-Lab/multihypothesis_segmentation_tracking
801d460afbf028100374c880bc684187ec8b909f
[ "MIT" ]
1
2022-03-02T12:32:21.000Z
2022-03-02T12:32:21.000Z
/* * Copyright (c) 2020 Andrew Price * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ //#include <opencv2/imgproc.hpp> //#include <opencv2/optflow.hpp> #include <opencv2/highgui.hpp> //#include <opencv2/features2d.hpp> //#include <opencv2/xfeatures2d.hpp> // //#include <cv_bridge/cv_bridge.h> //#include <sensor_msgs/image_encodings.h> //#include <image_transport/image_transport.h> //#include <image_transport/subscriber_filter.h> //#include <depth_image_proc/depth_conversions.h> //#include <message_filters/subscriber.h> //#include <message_filters/time_synchronizer.h> #include "mps_voxels/util/assert.h" #include "mps_voxels/CudaTracker.h" #include "mps_voxels/Scene.h" #include "mps_voxels/image_utils.h" #include "mps_voxels/segmentation_utils.h" #include "mps_voxels/video_graph.h" #include "mps_voxels/Ultrametric.h" #include "mps_voxels/graph_matrix_utils.h" #include "mps_voxels/LocalOctreeServer.h" #include "mps_voxels/OctreeMotionModel.h" #include <mps_msgs/SegmentGraph.h> #include <mps_msgs/ClusterRigidMotionsAction.h> #include <mps_msgs/MatchFrameSegmentsAction.h> #include <actionlib/client/simple_action_client.h> #include <visualization_msgs/MarkerArray.h> #include <depth_image_proc/depth_traits.h> #include <image_geometry/pinhole_camera_model.h> #include <moveit/robot_model_loader/robot_model_loader.h> #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit/robot_state/conversions.h> #include <boost/graph/filtered_graph.hpp> #include <boost/graph/connected_components.hpp> #include <Eigen/Eigenvalues> #include <Eigen/SparseCore> #include <ros/ros.h> using RigidClusterClient = actionlib::SimpleActionClient<mps_msgs::ClusterRigidMotionsAction>; using FrameMatchClient = actionlib::SimpleActionClient<mps_msgs::MatchFrameSegmentsAction>; std::unique_ptr<Tracker> tracker; std::shared_ptr<RGBDSegmenter> segmentationClient; std::unique_ptr<image_transport::Publisher> segmentationPub; double SIFT_MATCH_WEIGHT = 1.0/5.0; double RIGID_MATCH_WEIGHT = 1.0/5.0; int NUM_OUTPUT_LABELS = 15; //int pyrScale = 2; mps_msgs::Segmentation toSegmentationMsg(const SegmentationInfo& si) { mps_msgs::Segmentation s; sensor_msgs::CameraInfo info = tracker->cameraModel.cameraInfo(); info.header.stamp = si.t; s.camera_info = info; s.rgb = *cv_bridge::CvImage(info.header, sensor_msgs::image_encodings::BGR8, si.rgb).toImageMsg(); s.depth = *cv_bridge::CvImage(info.header, sensor_msgs::image_encodings::TYPE_16UC1, si.depth).toImageMsg(); // s.segments = *cv_bridge::CvImage(info.header, sensor_msgs::image_encodings::MONO16, si.labels).toImageMsg(); s.segments = *cv_bridge::CvImage(info.header, sensor_msgs::image_encodings::MONO16, si.objectness_segmentation->image).toImageMsg(); // s.ucm = *cv_bridge::CvImage(info.header, sensor_msgs::image_encodings::TYPE_64FC1, si.ucm).toImageMsg(); return s; } template <typename T> void getSetIfMissing(ros::NodeHandle& nh, const std::string& param_name, T& param_val) { if (!nh.hasParam(param_name)) { nh.setParam(param_name, param_val); } else { nh.getParam(param_name, param_val); } } /* static void drawOptFlowMap(const cv::Mat& flow, cv::Mat& cflowmap, int step, double, const cv::Scalar& color) { for(int y = 0; y < cflowmap.rows; y += step) for(int x = 0; x < cflowmap.cols; x += step) { const cv::Point2f& fxy = flow.at<cv::Point2f>(y, x); cv::line(cflowmap, cv::Point(x,y), cv::Point(cvRound(x+fxy.x), cvRound(y+fxy.y)), color); cv::circle(cflowmap, cv::Point(x,y), 2, color, -1); } } */ /* void track() { cv::Mat flow, cflow, display; cv::UMat gray1, gray2, uflow; // Possibly CPU or GPU image matrix cv::cvtColor(rgb_buffer.front()->image, gray1, cv::COLOR_BGR2GRAY); for (int i = 1; i < static_cast<int>(rgb_buffer.size()) && ros::ok(); ++i) { rgb_buffer[i-1]->image.copyTo(display); cv::cvtColor(rgb_buffer[i]->image, gray2, cv::COLOR_BGR2GRAY); // cv::calcOpticalFlowFarneback(gray1, gray2, uflow, 0.4, 3, 12, 5, 7, 1.5, cv::OPTFLOW_FARNEBACK_GAUSSIAN); // cv::calcOpticalFlowFarneback(gray1, gray2, uflow, 0.4, 1, 12, 5, 7, 1.5, cv::OPTFLOW_FARNEBACK_GAUSSIAN); // uflow.copyTo(flow); cv::calcOpticalFlowFarneback(gray1, gray2, uflow, 0.3, 4, 5, 15, 5, 1.2, cv::OPTFLOW_FARNEBACK_GAUSSIAN); const int GRID_STEP = 15; cv::cvtColor(gray1, cflow, cv::COLOR_GRAY2BGR); uflow.copyTo(flow); drawOptFlowMap(flow, cflow, 16, 1.5, cv::Scalar(0, 255, 0)); // // By y += 5, x += 5 you can specify the grid // for (int y = 0; y < display.rows; y += GRID_STEP) // { // for (int x = 0; x < display.cols; x += GRID_STEP) // { // // get the flow from y, x position * 10 for better visibility // const cv::Point2f flowatxy = flow.at<cv::Point2f>(y, x) * 10; // // draw line at flow direction // cv::line(display, cv::Point(x, y), cv::Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), cv::Scalar(255,0,0)); // // draw initial point // cv::circle(display, cv::Point(x, y), 1, cv::Scalar(0, 0, 0), -1); // } // } // cv::imshow("prev", display); cv::imshow("prev", cflow); cv::waitKey(100); std::swap(gray1, gray2); } } */ void decomposeAdjoint(const Eigen::MatrixXd& M, Eigen::VectorXd& eigenvalues, Eigen::MatrixXd& eigenvectors) { Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver; solver.compute(M, Eigen::ComputeEigenvectors); eigenvalues = solver.eigenvalues(); eigenvectors = solver.eigenvectors(); } // Signum function template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } //void cutGraph(VideoSegmentationGraph& graph, const std::vector<size_t>& cuts, const Eigen::MatrixXd& eigenvectors) //{ // std::set<VideoSegmentationGraph::edge_descriptor> cutEdges; // for (VideoSegmentationGraph::edge_descriptor ed : make_range(boost::edges(graph))) // { // VideoSegmentationGraph::vertex_descriptor u = boost::source(ed, graph); // VideoSegmentationGraph::vertex_descriptor v = boost::target(ed, graph); // // for (const size_t c : cuts) // { // if (sgn(eigenvectors.col(c)[u]) != sgn(eigenvectors.col(c)[v])) // { // cutEdges.insert(ed); // break; // } // } // } // // for (VideoSegmentationGraph::edge_descriptor ed : cutEdges) // { // boost::remove_edge(ed, graph); // } //} std::vector<cv::Point2i> getNeighbors(const int row, const int col, const cv::Mat& img) { std::vector<cv::Point2i> neighbors; neighbors.reserve(8); std::vector<int> rows, cols; rows.reserve(3); cols.reserve(3); // Enumerate rows to search if (row > 0) { rows.push_back(row-1); } rows.push_back(row); if (row < img.rows-1) { rows.push_back(row+1); } // Enumerate cols to search if (col > 0) { cols.push_back(col-1); } cols.push_back(col); if (col < img.cols-1) { cols.push_back(col+1); } for (const int r : rows) { for (const int c : cols) { if (r == row && c == col) { continue; } neighbors.emplace_back(cv::Point2i(c, r)); } } return neighbors; } std::set<std::pair<uint16_t, uint16_t>> computeNeighbors(const cv::Mat& labels) { std::set<std::pair<uint16_t, uint16_t>> neighbors; for(int i = 0; i < labels.rows; i++) { for(int j = 0; j < labels.cols; j++) { const uint16_t val = labels.at<uint16_t>(i, j); if (0 == val) { std::set<uint16_t> neighborhood; for (const auto& pt : getNeighbors(i, j, labels)) { const uint16_t nval = labels.at<uint16_t>(pt); if (0 != nval) { neighborhood.insert(nval); } } for (const auto a : neighborhood) { for (const auto b : neighborhood) { if (a != b) { neighbors.insert({a, b}); } } } } } } return neighbors; } std::map<std::pair<uint16_t, uint16_t>, double> computeUcmDual(const cv::Mat& labels, const cv::Mat& ucm) { MPS_ASSERT(labels.size == ucm.size); std::map<std::pair<uint16_t, uint16_t>, double> neighbors; for(int i = 0; i < labels.rows; i++) { for(int j = 0; j < labels.cols; j++) { const uint16_t val = labels.at<uint16_t>(i, j); if (0 == val) { if (0 < i && i < labels.rows-1) { const uint16_t llabel = labels.at<uint16_t>(i-1, j); const uint16_t rlabel = labels.at<uint16_t>(i+1, j); if (llabel != 0 && rlabel != 0 && llabel != rlabel) { std::pair<uint16_t, uint16_t> p(std::min(llabel, rlabel), std::max(llabel, rlabel)); double edge_val = ucm.at<double>(i, j); edge_val = edge_val * edge_val; auto iter = neighbors.find(p); if (iter == neighbors.end()) { neighbors.emplace(p, edge_val); } else { iter->second = std::min(edge_val, iter->second); } } } if (0 < j && j < labels.cols-1) { const uint16_t blabel = labels.at<uint16_t>(i, j-1); const uint16_t tlabel = labels.at<uint16_t>(i, j+1); if (blabel != 0 && tlabel != 0 && blabel != tlabel) { std::pair<uint16_t, uint16_t> p(std::min(blabel, tlabel), std::max(blabel, tlabel)); double edge_val = ucm.at<double>(i, j); edge_val = edge_val * edge_val; auto iter = neighbors.find(p); if (iter == neighbors.end()) { neighbors.emplace(p, edge_val); } else { iter->second = std::min(edge_val, iter->second); } } } } } } return neighbors; } #define REQUIRE_OBJECTNESS_IN_GRAPH true void addToGraph(VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G, const SegmentationInfo& si) { const cv::Mat& ucm = si.ucm2; const cv::Mat& full_labels = si.labels2; const ros::Time k = si.t; // Frame index, label value SegmentLookup<SEGMENT_TYPE::UCM> segmentToNode; for (const auto lbl : unique(full_labels)) { if (0 == lbl) { continue; } #if REQUIRE_OBJECTNESS_IN_GRAPH if (cv::countNonZero((0 != si.objectness_segmentation->image) & (lbl == si.labels)) < cv::countNonZero(lbl == si.labels)/4) { continue; } #endif VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor v = boost::add_vertex(NodeProperties<SEGMENT_TYPE::UCM>({k, lbl}), G); segmentToNode.insert({{k, lbl}, v}); } auto neighbor_pairs = computeUcmDual(full_labels, ucm); for (const auto edge : neighbor_pairs) { label_type p = edge.first.first; label_type q = edge.first.second; double dist = edge.second; if (dist <= 0 || 1.0 < dist) { throw std::runtime_error("Ultrametric max distance should be <= 1.0"); } VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor s, t; const auto a = segmentToNode.find({k, p}); const auto b = segmentToNode.find({k, q}); #if REQUIRE_OBJECTNESS_IN_GRAPH if (a == segmentToNode.end() || b == segmentToNode.end()) { continue; } #else MPS_ASSERT(a != segmentToNode.end()); MPS_ASSERT(b != segmentToNode.end()); #endif s = a->second; t = b->second; boost::add_edge(s, t, {1.0/(dist+1e-4)}, G); } #if !REQUIRE_OBJECTNESS_IN_GRAPH for (VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor vd : make_range(boost::vertices(G))) { MPS_ASSERT(boost::out_degree(vd, G) > 0); } #endif } void joinFrameGraphs(VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G, const SegmentationInfo& iInfo, const SegmentationInfo& jInfo, const Tracker::Flow2D& flow) { SegmentLookup<SEGMENT_TYPE::UCM> segmentToNode; for (VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor vd : make_range(boost::vertices(G))) { const NodeProperties<SEGMENT_TYPE::UCM>& np = G[vd]; segmentToNode[{np.t, np.leafID}] = vd; } const ros::Time& i = iInfo.t; const ros::Time& j = jInfo.t; if (i == j) throw std::logic_error("Sad!"); const cv::Mat& iLabels = iInfo.labels; const cv::Mat& jLabels = jInfo.labels; for (std::pair<cv::Point2f, cv::Point2f> flowVec : flow) { // NB: Flow may be computed for the full image, so flow points may be outside the ROI if (!iInfo.roi.contains(cv::Point2i(flowVec.first.x, flowVec.first.y))) { continue; } if (!jInfo.roi.contains(cv::Point2i(flowVec.second.x, flowVec.second.y))) { continue; } flowVec.first.x -= iInfo.roi.x; flowVec.first.y -= iInfo.roi.y; flowVec.second.x -= jInfo.roi.x; flowVec.second.y -= jInfo.roi.y; cv::Point2i iPt(flowVec.first.x, flowVec.first.y); cv::Point2i jPt(flowVec.second.x, flowVec.second.y); // if (iPt.x < 0 || iPt.y < 0) { continue; } // if (iPt.x >= iLabels.cols || iPt.y >= iLabels.rows) { continue; } // if (jPt.x < 0 || jPt.y < 0) { continue; } // if (jPt.x >= jLabels.cols || jPt.y >= jLabels.rows) { continue; } int iLabel = iLabels.at<uint16_t>(iPt); int jLabel = jLabels.at<uint16_t>(jPt); if (iLabel == 0 || jLabel == 0) { continue; } auto a = segmentToNode.find({i, iLabel}); auto b = segmentToNode.find({j, jLabel}); #if REQUIRE_OBJECTNESS_IN_GRAPH if (a == segmentToNode.end() || b == segmentToNode.end()) { continue; } #else MPS_ASSERT(a != segmentToNode.end()); MPS_ASSERT(b != segmentToNode.end()); #endif auto res = boost::add_edge(a->second, b->second, G); EdgeProperties& eProps = G[res.first]; if (eProps.affinity == 0) { eProps.affinity = 1.0; } eProps.affinity += SIFT_MATCH_WEIGHT; } } void joinMotionCliques(VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G, const SegmentationInfo& iInfo, const SegmentationInfo& jInfo, const Tracker::Flow2D& flow) { SegmentLookup<SEGMENT_TYPE::UCM> segmentToNode; for (VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor vd : make_range(boost::vertices(G))) { const NodeProperties<SEGMENT_TYPE::UCM>& np = G[vd]; segmentToNode[{np.t, np.leafID}] = vd; } const ros::Time& i = iInfo.t; const ros::Time& j = jInfo.t; const cv::Mat& iLabels = iInfo.labels; const cv::Mat& jLabels = jInfo.labels; std::set<uint16_t> iSet, jSet; for (std::pair<cv::Point2f, cv::Point2f> flowVec : flow) { // NB: Flow may be computed for the full image, so flow points may be outside the ROI if (!iInfo.roi.contains(cv::Point2i(flowVec.first.x, flowVec.first.y))) { continue; } if (!jInfo.roi.contains(cv::Point2i(flowVec.second.x, flowVec.second.y))) { continue; } flowVec.first.x -= iInfo.roi.x; flowVec.first.y -= iInfo.roi.y; flowVec.second.x -= jInfo.roi.x; flowVec.second.y -= jInfo.roi.y; cv::Point2i iPt(flowVec.first.x, flowVec.first.y); cv::Point2i jPt(flowVec.second.x, flowVec.second.y); uint16_t iLabel = iLabels.at<uint16_t>(iPt); uint16_t jLabel = jLabels.at<uint16_t>(jPt); if (iLabel == 0 || jLabel == 0) { continue; } iSet.insert(iLabel); jSet.insert(jLabel); } for (const auto iLabel : iSet) { for (const auto jLabel : jSet) { auto res = boost::add_edge(segmentToNode.at({i, iLabel}), segmentToNode.at({j, jLabel}), G); EdgeProperties& eProps = G[res.first]; if (eProps.affinity == 0) { eProps.affinity = 1.0; } eProps.affinity += RIGID_MATCH_WEIGHT; } } } void reinforceObjectEdges(VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G, const std::map<ros::Time, std::shared_ptr<SegmentationInfo>>& segmentations) { using Vertex = VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor; using Edge = VideoSegmentationGraph<SEGMENT_TYPE::UCM>::edge_descriptor; for (Edge ed : make_range(boost::edges(G))) { Vertex u = boost::source(ed, G); Vertex v = boost::target(ed, G); EdgeProperties& ep = G[ed]; const NodeProperties<SEGMENT_TYPE::UCM>& Gu = G[u]; const NodeProperties<SEGMENT_TYPE::UCM>& Gv = G[v]; if (Gu.t != Gv.t) { continue; } const std::shared_ptr<SegmentationInfo>& si = segmentations.at(Gu.t); const cv::Mat& C = si->centroids2; cv::Point2f cu(C.at<double>(Gu.leafID, 0)/2.0, C.at<double>(Gu.leafID, 1)/2.0); cv::Point2f cv(C.at<double>(Gv.leafID, 0)/2.0, C.at<double>(Gv.leafID, 1)/2.0); if (si->objectness_segmentation->image.at<uint16_t>(cu) == si->objectness_segmentation->image.at<uint16_t>(cv)) { ep.affinity += SIFT_MATCH_WEIGHT / 5.0; } } } #include <pcl_ros/point_cloud.h> void visualizeVideoGraph(const VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G, const std::map<ros::Time, std::shared_ptr<SegmentationInfo>>& segmentations)//const std::vector<cv::Mat>& imgs, const std::vector<cv::Mat>& centroids) { using Vertex = VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor; using Edge = VideoSegmentationGraph<SEGMENT_TYPE::UCM>::edge_descriptor; static ros::NodeHandle nh; static ros::Publisher pcPub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("video_points", 1, true); static ros::Publisher edgePub = nh.advertise<visualization_msgs::Marker>("video_edges", 1, true); const float UV_SCALE = 0.001; const float T_SCALE = 0.3; const int IMAGE_SCALE = 2; // SEGMENT_TYPE::UCM is at double the resolution normal const ros::Time& startTime = segmentations.begin()->first; pcl::PointCloud<pcl::PointXYZRGB> pc; // size_t k = 0; for (const auto& pair : segmentations) { const cv::Mat& img = pair.second->display_contours; for (int u = 1; u < img.cols; ++u) { for (int v = 1; v < img.rows; ++v) { auto color = img.at<cv::Vec3b>(v, u); pcl::PointXYZRGB pt(color[2], color[1], color[0]); pt.x = UV_SCALE * (u + IMAGE_SCALE*pair.second->roi.x); pt.y = -UV_SCALE * (v + IMAGE_SCALE*pair.second->roi.y); pt.z = -T_SCALE * (pair.first-startTime).toSec(); pc.points.push_back(pt); } } // ++k; } pc.header.frame_id = "video"; pcl_conversions::toPCL(ros::Time::now(), pc.header.stamp); pcPub.publish(pc); ros::spinOnce(); visualization_msgs::Marker m; m.action = visualization_msgs::Marker::ADD; m.type = visualization_msgs::Marker::LINE_LIST; m.color.a = 1.0f; m.color.r = 1.0f; m.color.g = 1.0f; m.color.b = 1.0f; m.pose.orientation.w = 1; m.frame_locked = true; m.id = 1; m.scale.x = 1.1*UV_SCALE; double minAffinity = std::numeric_limits<double>::infinity(); double maxAffinity = -std::numeric_limits<double>::infinity(); for (Edge ed : make_range(boost::edges(G))) { const EdgeProperties& ep = G[ed]; minAffinity = std::min(ep.affinity, minAffinity); maxAffinity = std::max(ep.affinity, maxAffinity); } geometry_msgs::Point pt; std_msgs::ColorRGBA color; for (Edge ed : make_range(boost::edges(G))) { Vertex u = boost::source(ed, G); Vertex v = boost::target(ed, G); const EdgeProperties& ep = G[ed]; const NodeProperties<SEGMENT_TYPE::UCM>& Gu = G[u]; const NodeProperties<SEGMENT_TYPE::UCM>& Gv = G[v]; const std::shared_ptr<SegmentationInfo>& Su = segmentations.at(Gu.t); const std::shared_ptr<SegmentationInfo>& Sv = segmentations.at(Gv.t); const cv::Mat& Cu = Su->centroids2; const cv::Mat& Cv = Sv->centroids2; cv::Point2f cu(Cu.at<double>(Gu.leafID, 0), Cu.at<double>(Gu.leafID, 1)); cv::Point2f cv(Cv.at<double>(Gv.leafID, 0), Cv.at<double>(Gv.leafID, 1)); pt.x = UV_SCALE * (cu.x + IMAGE_SCALE*Su->roi.x); pt.y = -UV_SCALE * (cu.y + IMAGE_SCALE*Su->roi.y); pt.z = -T_SCALE * (Gu.t-startTime).toSec(); m.points.push_back(pt); // colormap(igl::viridis_cm, (float)(ep.affinity-minAffinity)/(maxAffinity-minAffinity)), color.r, color.g, color.b); colormap(igl::viridis_cm, (float)tanh(10.0*(ep.affinity-minAffinity)/(maxAffinity-minAffinity)), color.r, color.g, color.b); m.colors.push_back(color); pt.x = UV_SCALE * (cv.x + IMAGE_SCALE*Sv->roi.x); pt.y = -UV_SCALE * (cv.y + IMAGE_SCALE*Sv->roi.y); pt.z = -T_SCALE * (Gv.t-startTime).toSec(); m.points.push_back(pt); m.colors.push_back(color); } m.header.frame_id = pc.header.frame_id; m.header.stamp = ros::Time::now(); edgePub.publish(m); } void visualizeObjectBundles(const VideoSegmentationGraph<SEGMENT_TYPE::BODY>& G, std::map<ros::Time, std::shared_ptr<SegmentationInfo>> segmentations, std::map<SegmentIndex<SEGMENT_TYPE::BODY>, BundleIndex> segmentToBundle, std::map<BundleIndex, cv::Scalar> bundleColors)//const std::vector<cv::Mat>& imgs, const std::vector<cv::Mat>& centroids) { using Vertex = VideoSegmentationGraph<SEGMENT_TYPE::BODY>::vertex_descriptor; using Edge = VideoSegmentationGraph<SEGMENT_TYPE::BODY>::edge_descriptor; static ros::NodeHandle nh; static ros::Publisher pcPub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("video_color", 1, true); static ros::Publisher edgePub = nh.advertise<visualization_msgs::Marker>("video_edge_colors", 1, true); const float UV_SCALE = 0.001; const float T_SCALE = 0.3; const ros::Time& startTime = segmentations.begin()->first; pcl::PointCloud<pcl::PointXYZRGB> pc; size_t k = 0; for (const auto& pair : segmentations) { // const cv::Mat& img = pair.second->labels; const cv::Mat& img = pair.second->objectness_segmentation->image; for (int u = 1; u < img.cols; ++u) { for (int v = 1; v < img.rows; ++v) { int label = img.at<uint16_t>(v, u); auto iter = segmentToBundle.find({pair.first, label}); if (iter == segmentToBundle.end()) { // std::cerr << "??" << std::endl; ++k; continue; } BundleIndex bundle = iter->second; auto color = bundleColors.at(bundle); pcl::PointXYZRGB pt(color[2], color[1], color[0]); pt.x = UV_SCALE * (u+pair.second->roi.x); pt.y = -UV_SCALE * (v+pair.second->roi.y); pt.z = -T_SCALE * (pair.first-startTime).toSec(); pc.points.push_back(pt); } } // ++k; } std::cerr << "Unmatched pixels: " << k << std::endl; pc.header.frame_id = "video"; pcl_conversions::toPCL(ros::Time::now(), pc.header.stamp); pcPub.publish(pc); ros::spinOnce(); visualization_msgs::Marker m; m.action = visualization_msgs::Marker::ADD; m.type = visualization_msgs::Marker::LINE_LIST; m.color.a = 1.0f; m.color.r = 1.0f; m.color.g = 1.0f; m.color.b = 1.0f; m.pose.orientation.w = 1; m.frame_locked = true; m.id = 1; m.scale.x = 1.1*UV_SCALE; double minAffinity = std::numeric_limits<double>::infinity(); double maxAffinity = -std::numeric_limits<double>::infinity(); for (Edge ed : make_range(boost::edges(G))) { const EdgeProperties& ep = G[ed]; minAffinity = std::min(ep.affinity, minAffinity); maxAffinity = std::max(ep.affinity, maxAffinity); } geometry_msgs::Point pt; std_msgs::ColorRGBA color; for (Edge ed : make_range(boost::edges(G))) { Vertex u = boost::source(ed, G); Vertex v = boost::target(ed, G); if (u == v) {throw std::logic_error("Graph has self-loops.");} const EdgeProperties& ep = G[ed]; const NodeProperties<SEGMENT_TYPE::BODY>& Gu = G[u]; const NodeProperties<SEGMENT_TYPE::BODY>& Gv = G[v]; const std::shared_ptr<SegmentationInfo>& Su = segmentations.at(Gu.t); const std::shared_ptr<SegmentationInfo>& Sv = segmentations.at(Gv.t); cv::Moments mu = cv::moments(Su->objectness_segmentation->image == Gu.leafID); cv::Moments mv = cv::moments(Sv->objectness_segmentation->image == Gv.leafID); if (mu.m00 == 0.0) {throw std::runtime_error("");} if (mv.m00 == 0.0) {throw std::runtime_error("");} cv::Point2f cu(mu.m10/mu.m00, mu.m01/mu.m00); cv::Point2f cv(mv.m10/mv.m00, mv.m01/mv.m00); pt.x = UV_SCALE * (cu.x+Su->roi.x); pt.y = -UV_SCALE * (cu.y+Su->roi.y); pt.z = -T_SCALE * (Gu.t-startTime).toSec(); m.points.push_back(pt); colormap(igl::viridis_cm, (float)((ep.affinity-minAffinity)/(maxAffinity-minAffinity)), color.r, color.g, color.b); m.colors.push_back(color); pt.x = UV_SCALE * (cv.x+Sv->roi.x); pt.y = -UV_SCALE * (cv.y+Sv->roi.y); pt.z = -T_SCALE * (Gv.t-startTime).toSec(); m.points.push_back(pt); m.colors.push_back(color); } m.header.frame_id = pc.header.frame_id; m.header.stamp = ros::Time::now(); edgePub.publish(m); ros::spinOnce(); usleep(100000); } VideoSegmentationGraph<SEGMENT_TYPE::UCM> subgraph(const VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G1, const std::vector<int>& labels, const int label) { using Vertex = VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor; using Edge = VideoSegmentationGraph<SEGMENT_TYPE::UCM>::edge_descriptor; VideoSegmentationGraph<SEGMENT_TYPE::UCM> G2; SegmentLookup<SEGMENT_TYPE::UCM> segmentToNode; for (Vertex vd : make_range(boost::vertices(G1))) { if (labels[vd] == label) { const NodeProperties<SEGMENT_TYPE::UCM>& np = G1[vd]; Vertex vd2 = boost::add_vertex(np, G2); auto r = segmentToNode.insert({{np.t, np.leafID}, vd2}); MPS_ASSERT(r.second); } } for (const Edge ed : make_range(boost::edges(G1))) { Vertex u = boost::source(ed, G1); Vertex v = boost::target(ed, G1); const EdgeProperties& ep = G1[ed]; const NodeProperties<SEGMENT_TYPE::UCM>& Gu = G1[u]; const NodeProperties<SEGMENT_TYPE::UCM>& Gv = G1[v]; VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor s, t; const auto a = segmentToNode.find({Gu.t, Gu.leafID}); const auto b = segmentToNode.find({Gv.t, Gv.leafID}); if (a == segmentToNode.end() || b == segmentToNode.end()) { continue; } s = a->second; t = b->second; boost::add_edge(s, t, ep, G2); } return G2; } void getUcmObjectMappings(const SegmentationInfo& si, std::map<uint16_t, uint16_t>& ucmLabelsToObjectLabel, std::map<uint16_t, std::set<uint16_t> >& objectLabelToUcmLabels) { MPS_ASSERT(si.labels.size() == si.objectness_segmentation->image.size()); const auto objectLabelIDs = unique(si.objectness_segmentation->image); for (const uint16_t objID : objectLabelIDs) { cv::Mat labelMask = (si.objectness_segmentation->image == objID); cv::Mat matches = cv::Mat::zeros(si.labels.size(), CV_16U); si.labels.copyTo(matches, labelMask); auto ucmLabelIDs = unique(matches); ucmLabelIDs.erase(0); objectLabelToUcmLabels[objID] = ucmLabelIDs; for (const uint16_t ucmID : ucmLabelIDs) { ucmLabelsToObjectLabel.insert({ucmID, objID}); } } } VideoSegmentationGraph<SEGMENT_TYPE::BODY> compressGraph(const VideoSegmentationGraph<SEGMENT_TYPE::UCM>& G1, std::map<ros::Time, std::map<uint16_t, uint16_t>>& ucmLabelsToObjectLabel) { VideoSegmentationGraph<SEGMENT_TYPE::BODY> G2; SegmentLookup<SEGMENT_TYPE::BODY> segmentToNodeG2; for (const auto& p : ucmLabelsToObjectLabel) { const ros::Time& t = p.first; for (const auto& p2 : p.second) { if (0 == p2.first) { continue; } if (segmentToNodeG2.find({t, p2.second}) != segmentToNodeG2.end()) { continue; } VideoSegmentationGraph<SEGMENT_TYPE::BODY>::vertex_descriptor v = boost::add_vertex(NodeProperties<SEGMENT_TYPE::BODY>({t, p2.second}), G2); segmentToNodeG2.insert({{t, p2.second}, v}); } } for (VideoSegmentationGraph<SEGMENT_TYPE::UCM>::edge_descriptor ed : make_range(boost::edges(G1))) { VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor u1 = boost::source(ed, G1); VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor v1 = boost::target(ed, G1); const EdgeProperties& ep = G1[ed]; const NodeProperties<SEGMENT_TYPE::UCM>& Gu = G1[u1]; const NodeProperties<SEGMENT_TYPE::UCM>& Gv = G1[v1]; const ros::Time& i = Gu.t; const ros::Time& j = Gv.t; int iNewLabel = ucmLabelsToObjectLabel.at(i).at(Gu.leafID); int jNewLabel = ucmLabelsToObjectLabel.at(j).at(Gv.leafID); VideoSegmentationGraph<SEGMENT_TYPE::BODY>::vertex_descriptor u2 = segmentToNodeG2.at({i, iNewLabel}); VideoSegmentationGraph<SEGMENT_TYPE::BODY>::vertex_descriptor v2 = segmentToNodeG2.at({j, jNewLabel}); if (u2==v2) { continue; } auto res = boost::add_edge(u2, v2, G2); EdgeProperties& eProps = G2[res.first]; eProps.affinity = std::max(eProps.affinity, ep.affinity); } typedef std::map<VideoSegmentationGraph<SEGMENT_TYPE::BODY>::vertex_descriptor, unsigned long> mapping_t; typedef boost::shared_ptr<mapping_t> vertex_component_map; vertex_component_map mapping = boost::make_shared<mapping_t>(); size_t num_components = boost::connected_components(G2, boost::associative_property_map<mapping_t>(*mapping)); if (num_components > 1) { // throw std::logic_error("Graph is disconnected."); } else if (num_components == 0) { throw std::logic_error("Graph is empty."); } else { std::cerr << "Compressed graph is connected." << std::endl; } return G2; } #include "mps_voxels/octree_utils.h" #include <tf_conversions/tf_eigen.h> //#include <rosgraph_msgs/Clock.h> void visualize(const OctreeMotionModel& omm, tf::TransformBroadcaster* tb, const std::string& globalFrame, const std::string& frame) { static ros::NodeHandle nh; static ros::Publisher pub = nh.advertise<visualization_msgs::MarkerArray>("object_memory", 1, true); // static ros::Publisher clockPub = nh.advertise<rosgraph_msgs::Clock>("/clock", 1, false); // static int clock_count = 0; ros::Time fakeNow = ros::Time::now();// + ros::Duration(++clock_count); // rosgraph_msgs::Clock clk; // clk.clock = fakeNow; // clockPub.publish(clk); tf::Transform T; tf::poseEigenToTF(omm.localTglobal.inverse(Eigen::Isometry), T); tb->sendTransform(tf::StampedTransform(T, fakeNow, globalFrame, frame)); visualization_msgs::MarkerArray occupiedNodesVis = visualizeOctree(omm.octree.get(), frame); for (visualization_msgs::Marker& m : occupiedNodesVis.markers) { m.ns = frame; m.header.stamp = fakeNow; } pub.publish(occupiedNodesVis); } int main(int argc, char* argv[]) { ros::init(argc, argv, "flow"); ros::NodeHandle nh, pnh("~"); setIfMissing(pnh, "frame_id", "table_surface"); setIfMissing(pnh, "resolution", 0.010); auto listener = std::make_shared<tf::TransformListener>(ros::Duration(60.0)); image_transport::ImageTransport it(nh); // image_transport::TransportHints hints("compressed", ros::TransportHints(), pnh); ros::Publisher pcPub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("pile_points", 1, true); std::shared_ptr<robot_model_loader::RobotModelLoader> mpLoader = std::make_shared<robot_model_loader::RobotModelLoader>(); robot_model::RobotModelPtr pModel = mpLoader->getModel(); MPS_ASSERT(!pModel->getJointModelGroupNames().empty()); std::map<std::string, std::shared_ptr<MotionModel>> selfModels; if (!loadLinkMotionModels(pModel.get(), selfModels)) { ROS_ERROR("Model loading failed."); } selfModels.erase("victor_base_plate"); // HACK: camera always collides selfModels.erase("victor_pedestal"); selfModels.erase("victor_left_arm_mount"); selfModels.erase("victor_right_arm_mount"); ros::ServiceClient segmentClient = nh.serviceClient<mps_msgs::SegmentGraph>("/segment_graph"); if (!segmentClient.waitForExistence(ros::Duration(3))) { ROS_ERROR("Graph segmentation server not connected."); return -1; } // RigidClusterClient motionClient("/cluster_flow", true); // if (!motionClient.waitForServer(ros::Duration(3))) // { // ROS_ERROR("Flow segmentation server not connected."); // } // // FrameMatchClient matchClient("/histogram_matcher", true); // if (!matchClient.waitForServer(ros::Duration(3))) // { // ROS_ERROR("Frame match server not connected."); // } std::shared_ptr<Scenario> scenario = std::make_shared<Scenario>(); scenario->mapServer = std::make_shared<LocalOctreeServer>(pnh); scenario->listener = listener; scenario->broadcaster = std::make_shared<tf::TransformBroadcaster>(); scenario->segmentationClient = std::make_shared<CachingRGBDSegmenter>(nh); scenario->robotModel = pModel; // scenario->loadManipulators(pModel); // std::unique_ptr<Scene> scene = std::make_unique<Scene>(); std::map<ros::Time, std::shared_ptr<Scene>> scenes; segmentationPub = std::make_unique<image_transport::Publisher>(it.advertise("segmentation", 1)); cv::namedWindow("segmentation", CV_WINDOW_NORMAL); cv::namedWindow("contours", CV_WINDOW_NORMAL); cv::namedWindow("labels", CV_WINDOW_NORMAL); const int step = 8;//3; tracker = std::make_unique<CudaTracker>(25*step, listener); // tracker = std::make_unique<Tracker>(5*step, listener); std::map<BundleIndex, std::shared_ptr<OctreeMotionModel>> omms; // OctreeMotionModel omm; // omm.localTglobal = MotionModel::Pose::Identity(); // omm.octree = std::make_shared<octomap::OcTree>(scenario->mapServer->m_res); // TODO: Make step size variable based on average flow CachingRGBDSegmenter::SegmentationCache& segmentations = std::dynamic_pointer_cast<CachingRGBDSegmenter>(scenario->segmentationClient)->cache; while (ros::ok()) { if (tracker->rgb_buffer.size() == tracker->MAX_BUFFER_LEN) { // Load tracking graph weights std::string param_ns = "/video_graph/"; getSetIfMissing(nh, param_ns+"sift_weight", SIFT_MATCH_WEIGHT); getSetIfMissing(nh, param_ns+"rigid_weight", RIGID_MATCH_WEIGHT); pnh.param("num_labels", NUM_OUTPUT_LABELS, NUM_OUTPUT_LABELS); std::cerr << "Sift weight: " << SIFT_MATCH_WEIGHT << std::endl; cv::Size nativeSize = tracker->rgb_buffer.begin()->second->image.size(); VideoSegmentationGraph<SEGMENT_TYPE::UCM> G; std::vector<ros::Time> steps; for (auto iter = tracker->rgb_buffer.begin(); iter != tracker->rgb_buffer.end(); std::advance(iter, step)) { steps.push_back(iter->first); } tracker->track(steps); for (int i = 0; i < static_cast<int>(steps.size()) && ros::ok(); ++i) { const ros::Time& tCurr = steps[i]; std::shared_ptr<Scene> scene = std::make_shared<Scene>(); scenes.insert({tCurr, scene}); scene->scenario = scenario; scene->selfModels = selfModels; scene->visualize = true; // NB: We do this every loop because we shrink the box during the crop/filter process scene->minExtent = Eigen::Vector4f(-0.4f, -0.6f, -0.020f, 1); scene->maxExtent = Eigen::Vector4f(0.4f, 0.6f, 0.5f, 1); scene->cv_rgb_ptr = tracker->rgb_buffer[tCurr]; scene->cv_depth_ptr = tracker->depth_buffer[tCurr]; sensor_msgs::CameraInfo cam_info = tracker->cameraModel.cameraInfo(); cam_info.header.stamp = scene->cv_rgb_ptr->header.stamp; scene->cameraModel.fromCameraInfo(cam_info); bool sceneSuccess; sceneSuccess = scene->loadAndFilterScene(); if (!sceneSuccess) { throw std::runtime_error(":("); } sceneSuccess = scene->performSegmentation(); if (!sceneSuccess) { throw std::runtime_error(":("); } const SegmentationInfo& si = *segmentations.at(tCurr); double alpha = 0.75; cv::Mat labelColorsMap = colorByLabel(si.objectness_segmentation->image); labelColorsMap.setTo(0, 0 == si.objectness_segmentation->image); labelColorsMap = alpha*labelColorsMap + (1.0-alpha)*si.rgb; cv::imshow("segmentation", labelColorsMap); cv::waitKey(1); cv::Mat displayLabels; si.labels.convertTo(displayLabels, CV_8UC1); cv::imshow("labels", displayLabels); cv::imshow("contours", si.display_contours); cv::waitKey(1); if (segmentationPub->getNumSubscribers() > 0) { segmentationPub->publish(cv_bridge::CvImage(tracker->cameraModel.cameraInfo().header, "bgr8", labelColorsMap).toImageMsg()); } scene->pile_cloud->header.frame_id = scene->cameraFrame; pcl_conversions::toPCL(ros::Time::now(), scene->pile_cloud->header.stamp); pcPub.publish(scene->pile_cloud); ros::spinOnce(); addToGraph(G, si);//.ucm2, si.labels2, tCurr); if (i >= 1) { const ros::Time& tPrev = steps[i-1]; // const cv::Mat prevLabels = segmentations[tPrev]->labels; joinFrameGraphs(G, *segmentations[tPrev], si, tracker->flows2.at({tPrev, tCurr})); // Add rigid motion cliques /* if (motionClient.isServerConnected()) { mps_msgs::ClusterRigidMotionsGoal req; req.flow_field.reserve(tracker->flows3.at({tPrev, tCurr}).size()); std::vector<size_t> valid_flow_to_all_flow_lookup; for (size_t f = 0; f<tracker->flows3[{tPrev, tCurr}].size(); ++f) { const auto& flow = tracker->flows3[{tPrev, tCurr}][f]; std::cerr << flow.second.norm() << std::endl; if (flow.second.norm()<0.01) { continue; } if (0.1>flow.first.z() || flow.first.z()>2.0) { continue; } mps_msgs::FlowVector flowVector; flowVector.pos.x = flow.first.x(); flowVector.pos.y = flow.first.y(); flowVector.pos.z = flow.first.z(); flowVector.vel.x = flow.second.x(); flowVector.vel.y = flow.second.y(); flowVector.vel.z = flow.second.z(); req.flow_field.push_back(flowVector); valid_flow_to_all_flow_lookup.push_back(f); } std::cerr << tracker->flows3[{tPrev, tCurr}].size() << "->" << req.flow_field.size() << std::endl; auto success = motionClient.sendGoalAndWait(req); if (!success.isDone()) { continue; } mps_msgs::ClusterRigidMotionsResultConstPtr resp = motionClient.getResult(); if (resp) { MPS_ASSERT(resp->labels.size()==req.flow_field.size()); // for (const auto l : resp->labels) { std::cerr << l << "\t"; } std::cerr << std::endl; std::map<int, std::vector<size_t>> flow_clusters; for (size_t f = 0; f<req.flow_field.size(); ++f) { flow_clusters[resp->labels[f]].push_back(f); } for (const auto& cluster : flow_clusters) { if (cluster.second.size()>10) { Tracker::Flow2D flows2; for (size_t iter = 0; iter<cluster.second.size(); ++iter) { // We skipped a bunch of flows, so we need to find our original position in the list size_t f = valid_flow_to_all_flow_lookup[iter]; flows2.push_back(tracker->flows2[{tPrev, tCurr}][f]); } // joinMotionCliques(G, *segmentations[tPrev], si, flows2); } } } } */ } visualizeVideoGraph(G, segmentations); } std::map<ros::Time, std::map<uint16_t, uint16_t>> ucmLabelsToObjectLabelWithTime; for (int i = 0; i < static_cast<int>(steps.size()) && ros::ok(); ++i) { const ros::Time& t = steps[i]; const SegmentationInfo& si = *segmentations[t]; std::map<uint16_t, uint16_t> ucmLabelsToObjectLabel; std::map<uint16_t, std::set<uint16_t> > objectLabelToUcmLabels; getUcmObjectMappings(si, ucmLabelsToObjectLabel, objectLabelToUcmLabels); ucmLabelsToObjectLabelWithTime.insert({t, ucmLabelsToObjectLabel}); } VideoSegmentationGraph<SEGMENT_TYPE::BODY> objectG = compressGraph(G, ucmLabelsToObjectLabelWithTime); // Filter for segments that have objects // { // boost::graph_traits<VideoSegmentationGraph<SEGMENT_TYPE::BODY>>::vertex_iterator vi, vi_end, next; // boost::tie(vi, vi_end) = boost::vertices(objectG); // for (next = vi; vi != vi_end; vi = next) // { // ++next; // const auto seg = objectG[*vi]; // const auto& lookup = scenes.at(seg.t)->labelToIndexLookup; // if (lookup.find(seg.leafID) == lookup.end()) // { // std::cerr << "Rejected: <" << seg.t << "," << seg.leafID << ">." << std::endl; // boost::clear_vertex(*vi, objectG); // boost::remove_vertex(*vi, objectG); // // Remove invalidates iterators, start over // boost::tie(vi, vi_end) = boost::vertices(objectG); // next = vi; // } // } // MPS_ASSERT(boost::num_vertices(objectG) > 0); // } std::map<BundleIndex, cv::Scalar> bundle_colors; cv::RNG rng(0); MPS_ASSERT(segmentations.find(segmentations.rbegin()->first) != segmentations.end()); MPS_ASSERT(segmentations.rbegin()->first == segmentations.rbegin()->second->t); // mps_msgs::MatchFrameSegmentsGoal g; // g.frames.emplace_back(toSegmentationMsg(*segmentations.begin()->second)); // g.frames.emplace_back(toSegmentationMsg(*segmentations.rbegin()->second)); // auto res = matchClient.sendGoalAndWait(g); // if (!res.isDone() || res.state_ != actionlib::SimpleClientGoalState::SUCCEEDED) { throw std::runtime_error("Matching failed."); } // // mps_msgs::MatchFrameSegmentsResultConstPtr frameMatchResult = matchClient.getResult(); // if (!frameMatchResult) { continue; } // for (const auto& b : frameMatchResult->segments_to_bundles) // { // for (const auto v : b.values) // { // bundle_colors[BundleIndex{v}] = randomColor(rng); // } // } // std::map<SegmentIndex, int> segmentToBundle; // { // std::map<ros::Time, cv::Mat> video; // for (const ros::Time& t : frameMatchResult->stamps) // { // video.insert({t, cv::Mat::zeros(nativeSize, CV_8UC3)}); // } // // for (size_t i = 0; i < frameMatchResult->segments_to_bundles.size(); ++i) // { // const ros::Time& t = frameMatchResult->stamps[i]; // const mps_msgs::IndexMap& b = frameMatchResult->segments_to_bundles[i]; // for (size_t j = 0; j < b.keys.size(); ++j) // { // const auto& si = segmentations.at(t); // const int k = b.keys[j]; // const BundleIndex v{b.values[j]}; //// segmentToBundle.insert({{t, k}, v}); // cv::Mat active(video.at(t), si->roi); // MPS_ASSERT(active.size == segmentations.at(t)->labels.size); // active.setTo(bundle_colors.at(v), si->objectness_segmentation->image == k); // // cv::imshow("source", si->rgb); // cv::imshow("mask", si->objectness_segmentation->image == k); // cv::imshow("video", video.at(t)); // // cv::waitKey(0); // } // } // // for (const auto& pair : video) // { // cv::imshow("video", pair.second); // cv::waitKey(1); // } // // cv::VideoWriter tracking("bundled_pair.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 1, nativeSize, true); // for (const auto& pair : video) // tracking.write(pair.second); // tracking.release(); // } {/* // Maps from bundle ID (id) to all segments contained in that "object". Reverse lookup of segments_to_bundles std::map<BundleIndex, std::set<SegmentIndex<SEGMENT_TYPE::BODY>> > bundleMembership; for (size_t t = 0; t < frameMatchResult->stamps.size(); ++t) { const auto& lookup = scenes.at(frameMatchResult->stamps[t])->labelToIndexLookup; MPS_ASSERT(!lookup.empty()); for (size_t i = 0; i < frameMatchResult->segments_to_bundles[t].keys.size(); ++i) { // Not all segments wind up in our final structure, due to being background, or too small, etc if (lookup.find(frameMatchResult->segments_to_bundles[t].keys[i]) == lookup.end()) { std::cerr << "SegmentID <" << frameMatchResult->stamps[t] << "," << frameMatchResult->segments_to_bundles[t].keys[i] << "> was rejected." << std::endl; continue; } else { std::cerr << "SegmentID <" << frameMatchResult->stamps[t] << "," << frameMatchResult->segments_to_bundles[t].keys[i] << "> was located." << std::endl; } bundleMembership[BundleIndex{frameMatchResult->segments_to_bundles[t].values[i]}].insert({frameMatchResult->stamps[t], frameMatchResult->segments_to_bundles[t].keys[i]}); // TODO: Problem here??? } } for (auto& bundle : bundleMembership) { std::shared_ptr<OctreeMotionModel> omm = std::make_shared<OctreeMotionModel>(); omm->localTglobal = MotionModel::Pose::Identity(); omm->octree = std::make_shared<octomap::OcTree>(scenario->mapServer->m_res); omms.insert({bundle.first, omm}); } // Map from a segment ID to a vertex ID in the graph SegmentLookup<SEGMENT_TYPE::BODY> objectSegmentToNode; for (VideoSegmentationGraph<SEGMENT_TYPE::BODY>::vertex_descriptor vd : make_range(boost::vertices(objectG)))//objectG { const NodeProperties<SEGMENT_TYPE::BODY>& np = objectG[vd]; auto r = objectSegmentToNode.insert({{np.t, np.leafID}, vd}); MPS_ASSERT(r.second); } std::map<SegmentIndex<SEGMENT_TYPE::BODY>, BundleIndex> segmentToBundle; visualizeObjectBundles(objectG, segmentations, segmentToBundle, bundle_colors); // Eventually the matcher should handle this part... // Connect from start frame to final frame for (auto& bundle : bundleMembership) { std::deque<SegmentIndex<SEGMENT_TYPE::BODY>> path = getObjectPath(objectG, objectSegmentToNode, *bundle.second.begin(), *bundle.second.rbegin()); for (const auto& seg : path) { bundle.second.insert(seg); segmentToBundle[seg] = bundle.first; } visualizeObjectBundles(objectG, segmentations, segmentToBundle, bundle_colors); } for (const auto& bundle : bundleMembership) { std::map<ros::Time, cv::Mat> bundleMasks; ///< Collection of frames where this bundle was observed for (const auto& seg : bundle.second) { const auto& si = segmentations.at(seg.first); bundleMasks.insert({seg.first, cv::Mat::zeros(si->objectness_segmentation->image.size(), CV_8UC1)}); } for (const auto& seg : bundle.second) { const auto& si = segmentations.at(seg.first); bundleMasks.at(seg.first).setTo(255, si->objectness_segmentation->image == seg.second); } // Step through pairs of masks and look for tracks auto iter1 = bundleMasks.begin(); auto iter2 = ++bundleMasks.begin(); for (; iter2 != bundleMasks.end(); ++iter1, ++iter2) { const auto& si1 = segmentations.at(iter1->first); const auto& si2 = segmentations.at(iter2->first); const auto& flow2 = tracker->flows2[{si1->t, si2->t}]; const auto& flow3 = tracker->flows3[{si1->t, si2->t}]; Tracker::Flow3D bundleFlow3; for (size_t f = 0; f < flow2.size(); ++f) { auto flowVec = flow2[f]; if (!si1->roi.contains(cv::Point2i(flowVec.first.x, flowVec.first.y))) { continue; } if (!si2->roi.contains(cv::Point2i(flowVec.second.x, flowVec.second.y))) { continue; } flowVec.first.x -= si1->roi.x; flowVec.first.y -= si1->roi.y; flowVec.second.x -= si2->roi.x; flowVec.second.y -= si2->roi.y; cv::Point2i iPt(flowVec.first.x, flowVec.first.y); cv::Point2i jPt(flowVec.second.x, flowVec.second.y); // If flow2d @ time t1 in mask1 and flow2d in mask2 @ time t2, add to list if (iter1->second.at<uint8_t>(iPt) > 0 && iter2->second.at<uint8_t>(jPt) > 0) { bundleFlow3.push_back(flow3[f]); } } if (bundleFlow3.size() < 3) { std::cerr << "Insufficient matches (" << bundleFlow3.size() << ") for bundle '" << bundle.first.id << "' between " << si1->t << " and " << si2->t << std::endl; continue; } Eigen::Isometry3d bTa; if (estimateRigidTransform(bundleFlow3, bTa)) { std::cerr << "Got one: " << std::endl; std::cerr << bTa.matrix() << std::endl; const auto& scene1 = scenes.at(si1->t); const auto& scene2 = scenes.at(si2->t); for (const auto& seg : bundle.second) { if (seg.first == si1->t) { // NB: objectID may be missing if it took a stupid path through the inner frames const auto& iter = scene1->labelToIndexLookup.find(seg.second); if (iter == scene1->labelToIndexLookup.end()) { continue; } ObjectIndex obj = iter->second; std::shared_ptr<OctreeMotionModel>& omm = omms.at(bundle.first); // omm.localTglobal *= bTa; omm->observe(scene1->segments.at(obj), scene1->worldTcamera); visualize(*omm, scenario->broadcaster.get(), scene1->worldFrame, "1"); // sleep(2); } } // omm.localTglobal.translation().x() += 0.1; // visualize(omm, scenario->broadcaster.get(), scene1->worldFrame, "1"); // TODO: Draw the frame-frame connection here! } else { std::cerr << "RANSAC failed for bundle '" << bundle.first.id << "' between " << si1->t << " and " << si2->t << std::endl; } } } for (const auto& bundle : bundleMembership) { for (const auto& seg : bundle.second) { segmentToBundle[seg] = bundle.first; } } visualizeObjectBundles(objectG, segmentations, segmentToBundle, bundle_colors); for (int i = 0; i < static_cast<int>(steps.size()) && ros::ok(); ++i) { // const ros::Time& tCurr = steps[i]; // const ros::Time& tPrev = steps[i-1]; // // const std::shared_ptr<Scene>& sceneCurr = scenes.at(tCurr); // const std::shared_ptr<Scene>& scenePrev = scenes.at(tPrev); // omm.observe(scene->segments.front(), scene->worldTcamera); // visualize(omm, scenario->broadcaster.get(), scene->worldFrame, "1"); // sleep(2); // omm.localTglobal.translation().x() += 0.1; // visualize(omm, scenario->broadcaster.get(), scene->worldFrame, "1"); } */} // std::vector<ComponentGraph> component_graphs; // // for (size_t i = 0; i < num_components; i++) // component_graphs.emplace_back(G, // [mapping,i,&G](VideoSegmentationGraph::edge_descriptor e) { // return mapping->at(boost::source(e,G))==i // || mapping->at(boost::target(e,G))==i; // }, // [mapping,i](VideoSegmentationGraph::vertex_descriptor v) { // return mapping->at(v)==i; // }); // // for (const auto& g : component_graphs) { // Eigen::MatrixXd laplacian = getLaplacianNormalized(G); // const int numCells = laplacian.rows(); // std::cerr << "Segmenting subgraph with " << numCells << " vertices (out of " << boost::num_vertices(G) << ")." << std::endl; // Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver; // solver.compute(laplacian, Eigen::ComputeEigenvectors); // Eigen::VectorXd eigenvalues = solver.eigenvalues(); // Eigen::MatrixXd eigenvectors = solver.eigenvectors(); } // for (size_t node = 0; node < componentLookup.size(); ++node) // { // int seg = componentLookup[node]; // // } { reinforceObjectEdges(G, segmentations); visualizeVideoGraph(G, segmentations); } int maxObjs = std::numeric_limits<int>::lowest(); for (const auto& scene : scenes) { maxObjs = std::max(maxObjs, static_cast<int>(scene.second->segments.size())); } std::vector<int> componentLookup(boost::num_vertices(G)); int num_components = boost::connected_components(G, &componentLookup[0]); std::vector<VideoSegmentationGraph<SEGMENT_TYPE::UCM>> Gs; for (int component = 0; component < num_components; ++component) { const auto Gprime = subgraph(G, componentLookup, component); if (static_cast<int>(boost::num_vertices(Gprime)) > maxObjs * 2) { Gs.push_back(Gprime); } } SegmentLookup<SEGMENT_TYPE::UCM> segmentToNode; for (VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor vd : make_range(boost::vertices(G))) { const NodeProperties<SEGMENT_TYPE::UCM>& np = G[vd]; segmentToNode[{np.t, np.leafID}] = vd; } for (int numObjs = maxObjs - 2; numObjs < maxObjs + 4; ++numObjs) { bundle_colors.clear(); std::map<VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor, int> objectClusters; int total_num_labels = 0; for (const auto& Gprime : Gs) { Eigen::SparseMatrix<double> adj = getAdjacencySparse(Gprime); mps_msgs::SegmentGraphRequest req; for (const auto& triplet : to_triplets(adj)) { req.adjacency.row_index.push_back(triplet.row()); req.adjacency.col_index.push_back(triplet.col()); req.adjacency.value.push_back(triplet.value()); } req.num_labels = numObjs; req.algorithm = "spectral"; //"affinity"; //dbscan mps_msgs::SegmentGraphResponse resp; bool success = segmentClient.call(req, resp); if (!success) { ROS_ERROR_STREAM("Graph segmentation call failed."); break; } for (VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor vd : make_range(boost::vertices(Gprime))) { const NodeProperties<SEGMENT_TYPE::UCM>& np = Gprime[vd]; objectClusters.insert({segmentToNode.at({np.t, np.leafID}), resp.labels[vd]+total_num_labels}); } total_num_labels += resp.num_labels; } for (const auto& oc : objectClusters) { bundle_colors[BundleIndex{oc.second}] = randomColor(rng); } // Recolor image based on segments std::map<ros::Time, cv::Mat> video; for (const ros::Time& t : steps) { video.insert({t, cv::Mat::zeros(nativeSize, CV_8UC3)}); } for (VideoSegmentationGraph<SEGMENT_TYPE::UCM>::vertex_descriptor vd : make_range(boost::vertices(G))) { const NodeProperties<SEGMENT_TYPE::UCM>& np = G[vd]; const auto& segmentation = segmentations.at(np.t); cv::Mat ucmLabelMask = segmentation->labels==np.leafID; // ucmLabelMask.setTo(0, segmentation->objectness_segmentation->image == 0); const auto iter = objectClusters.find(vd); if (iter != objectClusters.end()) { cv::Mat(video.at(np.t), segmentation->roi).setTo(bundle_colors.at(BundleIndex{iter->second}), ucmLabelMask); } } const double alpha = 0.75; cv::VideoWriter tracking("clustered_"+std::to_string(numObjs)+".avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 1, nativeSize, true); for (const auto& pair : video) { tracking.write(alpha*pair.second+(1.0-alpha)*scenes.at(pair.first)->cv_rgb_ptr->image); } tracking.release(); } // { // Eigen::SparseMatrix<double> laplacian = getLaplacianSparseNormalized(G); // using SparseMatProd = Spectra::SparseSymMatProd<double>; // Spectra::SparseGenMatProd<double> // SparseMatProd op(laplacian); // Spectra::SymEigsSolver<double, Spectra::LARGEST_MAGN, SparseMatProd> eigs(&op, 5, 5*30+1); // eigs.init(); // int nconv = eigs.compute(); // if (eigs.info()==Spectra::SUCCESSFUL) // { // std::cerr << nconv << "\n" << eigs.eigenvectors().real() << std::endl; // } // else // { // ROS_WARN("Failed to compute eigenvectors. Clusterign aborted."); // // tracker->reset(); // continue; // } // } while (ros::ok() && cv::waitKeyEx(10) < 0) { } tracker->reset(); std::cerr << "Tracker reset." << std::endl; tracker->startCapture(); } cv::waitKey(1); sleep(1); cv::waitKey(1); } tracker.reset(); segmentationClient.reset(); segmentationPub.reset(); return 0; }
34.699749
345
0.66511
[ "object", "vector", "model", "transform" ]
f6f142b8b1212aca887766f32fc46a404542335e
16,899
cpp
C++
qt/interface/ReportUserInterface_Qt.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
3
2021-06-28T21:07:58.000Z
2021-07-02T11:21:49.000Z
qt/interface/ReportUserInterface_Qt.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
null
null
null
qt/interface/ReportUserInterface_Qt.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
null
null
null
/**************************************************************************/ /*Copyright 2002-2014 e-foto team (UERJ) This file is part of e-foto. e-foto 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. e-foto 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 e-foto. If not, see <http://www.gnu.org/licenses/>. */ #include "ReportUserInterface_Qt.h" #include "ReportManager.h" #include "ETableWidget.h" #include "LoadingScreen.h" #include <qapplication.h> #include <qvariant.h> #include <qimage.h> #include <qpixmap.h> #include <qaction.h> #include <qstring.h> #include <QtWidgets> #include <QDebug> namespace br { namespace uerj { namespace eng { namespace efoto { ReportUserInterface_Qt* ReportUserInterface_Qt::ReportInst = NULL; ReportUserInterface_Qt* ReportUserInterface_Qt::instance(ReportManager* manager) { if (ReportInst == NULL) { delete ReportInst; ReportInst = NULL; } if (ReportInst == NULL) { ReportInst = new ReportUserInterface_Qt(manager); } return ReportInst; } ReportUserInterface_Qt::ReportUserInterface_Qt(ReportManager* manager, QWidget* parent, Qt::WindowFlags fl) : QMainWindow(parent, fl) { setupUi(this); this->manager = manager; //setWindowState(this->windowState() | Qt::WindowMaximized); qApp->processEvents(); init(); } ReportUserInterface_Qt::~ReportUserInterface_Qt() { // no need to delete child widgets, Qt does it all for us } void ReportUserInterface_Qt::languageChange() { retranslateUi(this); } void ReportUserInterface_Qt::init() { newTree(); connect(generateButton,SIGNAL(clicked()),this,SLOT(saveEPR())); } void ReportUserInterface_Qt::closeEvent(QCloseEvent *e) { LoadingScreen::instance().show(); qApp->processEvents(); manager->returnProject(); QMainWindow::closeEvent(e); } void ReportUserInterface_Qt::newTree() { QTreeWidget *treeWidget = new QTreeWidget(this); connect(treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(selectAllChildren(QTreeWidgetItem*))); connect(treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(unselectFatherByKid(QTreeWidgetItem*))); treeWidget->clear(); treeItems.clear(); QTreeWidgetItem* item = new QTreeWidgetItem(treeWidget); item->setCheckState(0,Qt::Checked); item->setText(0, "Select All"); item->setExpanded(true); treeItems.push_back(item); QTreeWidgetItem* fatherTree = item; item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Header"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Terrain"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Sensors"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Flights"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Images"); treeItems.push_back(item); QTreeWidgetItem* n1RootItem = item; item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Metadata"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Orientation parameters"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Points"); treeItems.push_back(item); n1RootItem = item; item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Coordinates in Object Space Frame"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Coordinates in Image Space Frame"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Affine Transformation"); treeItems.push_back(item); n1RootItem = item; item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Initialization data"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Quality data"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Spatial Resection"); treeItems.push_back(item); n1RootItem = item; item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Initialization data"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Quality data"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Values at each iteration"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Photogrammetric Block"); treeItems.push_back(item); n1RootItem = item; item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Initialization data"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Values at each iteration"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Interior Orientation"); treeItems.push_back(item); n1RootItem = item; item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Xa"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Matrix V"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "SigmaXa"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Exterior Orientation"); treeItems.push_back(item); n1RootItem = item; item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "EO Type"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Number of Iterations for Convergence"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Xa"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "Matrix V"); treeItems.push_back(item); item = new QTreeWidgetItem(n1RootItem); item->setCheckState(0,Qt::Checked); item->setText(0, "SigmaXa"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Stereo Pairs"); treeItems.push_back(item); /* item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Stereo Plotting"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "DSM"); treeItems.push_back(item); item = new QTreeWidgetItem(fatherTree); item->setCheckState(0,Qt::Checked); item->setText(0, "Orthorectification"); treeItems.push_back(item);*/ manager->checkTree(treeItems); treeWidget->setCurrentItem(treeItems.at(0)); treeWidget->header()->hide(); treeArea->setLayout(new QVBoxLayout()); treeArea->layout()->addWidget(treeWidget); //processTreeClick(treeWidget->currentIndex()); } bool ReportUserInterface_Qt::exec() { this->show(); LoadingScreen::instance().close(); qApp->processEvents(); return true; } void ReportUserInterface_Qt::selectAllChildren(QTreeWidgetItem* father) { int numChild= father->childCount(); if (father->checkState(0)==Qt::Checked) { for (int i=0;i<numChild;i++) { QTreeWidgetItem *aux=father->child(i); if(!aux->isDisabled()) aux->setCheckState(0,Qt::Checked); if (aux->childCount()!=0) { selectAllChildren(aux); } } } else if (father->checkState(0)==Qt::Unchecked) { for (int i=0;i<numChild;i++) { QTreeWidgetItem *aux=father->child(i); aux->setCheckState(0,Qt::Unchecked); if (aux->childCount()!=0) { selectAllChildren(aux); } } } } void ReportUserInterface_Qt::unselectFatherByKid(QTreeWidgetItem* kid) { QTreeWidgetItem* father = kid->parent(); if (father==NULL) return; int numChild = father->childCount(); int count_uncheck = 0; int count_check = 0; for (int i=0;i<numChild;i++) { if(!father->child(i)->isDisabled()) { if(father->child(i)->checkState(0)==Qt::Unchecked) { ++count_uncheck; } else if(father->child(i)->checkState(0)==Qt::Checked) { ++count_check; } else if(father->child(i)->checkState(0)==Qt::PartiallyChecked) { father->setCheckState(0,Qt::PartiallyChecked); } } } if(count_uncheck > 0) { if(count_uncheck==numChild) { father->setCheckState(0,Qt::Unchecked); } else { father->setCheckState(0,Qt::PartiallyChecked); } } if(count_check > 0) { if(count_check==numChild) { father->setCheckState(0,Qt::Checked); } } unselectFatherByKid(father); } bool ReportUserInterface_Qt::saveEPR() { QFileDialog salvar(this, tr("Save File As"), ".",tr("*.xml;;*.txt;;*.html")); salvar.setAcceptMode(QFileDialog::AcceptSave); #ifdef Q_OS_WIN64 QSettings binSettings("uerj","efoto"); QString binPath = QString::fromLocal8Bit(binSettings.value("binPath").toByteArray().constData()); #endif if(salvar.exec()) { QString filename = salvar.selectedFiles()[0]; //QString chosenExtension = new QString(); QString chosenExtension = salvar.selectedNameFilter(); QString filenameOriginal,filenameOriginalMask,filePathMask; int idExt = 0; if (filename.isEmpty()) { return false; } else { int j=filename.lastIndexOf("/"); filenameOriginal = filename.right(filename.length()-j-1); if(!filename.endsWith(".xml")) filename.append(".xml"); //chosenExtension->remove('*'); chosenExtension.remove('*'); //if (chosenExtension->toStdString() == ".xml"){ if (chosenExtension.toStdString() == ".xml"){ idExt = XMLTYPE; } else { //if (chosenExtension->toStdString() == ".txt"){ if (chosenExtension.toStdString() == ".txt"){ idExt = TXTTYPE; filenameOriginalMask = filenameOriginal; filenameOriginalMask.prepend("~"); filePathMask = filename.left(j); filename = filePathMask + "/" + filenameOriginalMask; } else { //if (chosenExtension->toStdString() == ".html"){ if (chosenExtension.toStdString() == ".html"){ idExt = HTMTYPE; filenameOriginalMask = filenameOriginal; filenameOriginalMask.prepend("~"); filePathMask = filename.left(j); filename = filePathMask + "/" + filenameOriginalMask; } } } } int i=filename.lastIndexOf("/"); QString filePath = filename.left(i); //bool done = manager->makeFile(filename.toStdString(),idExt,treeItems); bool done = manager->makeFile(filename.toLocal8Bit().constData(),idExt,treeItems); bool doneXslt = false; if(idExt == TXTTYPE) { //doneXslt = manager->makeXslt(TXTTYPE,filePath.toStdString()); doneXslt = manager->makeXslt(TXTTYPE,filePath.toLocal8Bit().constData()); } else { if(idExt == HTMTYPE) { //doneXslt = manager->makeXslt(HTMTYPE,filePath.toStdString()); doneXslt = manager->makeXslt(HTMTYPE,filePath.toLocal8Bit().constData()); } else { doneXslt = true; } } if(done == true && doneXslt == true) { QProcess *pro = new QProcess(); if(idExt == TXTTYPE) { QString output; if(filenameOriginal.endsWith(".txt")) output = filePath + "/" + filenameOriginal; else output = filePath + "/" + filenameOriginal + ".txt"; QString outxsl; outxsl = filePath + "/" + "epr_txt.xsl"; QString outcmd; #ifdef unix //LINUX outcmd = "xsltproc -o " + output + " " + filename + " " + outxsl; pro->start(outcmd); pro->waitForFinished(1000); pro->start("rm " + outxsl); pro->waitForFinished(1000); pro->start("rm " + filename); pro->waitForFinished(1000); #endif #ifdef Q_OS_WIN64 //WINDOWS outcmd = binPath + "/" + "xsltproc -o \"" + output + "\" \"" + filename + "\" \"" + outxsl + "\""; pro->start(outcmd); pro->waitForFinished(1000); outxsl.replace("/","\\"); filename.replace("/","\\"); pro->start("cmd /C del \""+outxsl+"\""); pro->waitForFinished(1000); pro->start("cmd /C del \""+filename+"\""); pro->waitForFinished(1000); #endif } else { if(idExt == HTMTYPE){ QString output; if(filenameOriginal.endsWith(".html")) output = filePath + "/" + filenameOriginal; else output = filePath + "/" + filenameOriginal + ".html"; QString outxsl; outxsl = filePath + "/" + "epr_html.xsl"; QString outcmd; #ifdef unix //LINUX outcmd = "xsltproc -o " + output + " " + filename + " " + outxsl; pro->start(outcmd); pro->waitForFinished(1000); pro->start("rm " + outxsl); pro->waitForFinished(1000); pro->start("rm " + filename); pro->waitForFinished(1000); #endif #ifdef Q_OS_WIN64 //WINDOWS outcmd = binPath + "/" + "xsltproc -o \"" + output + "\" \"" + filename + "\" \"" + outxsl + "\""; pro->start(outcmd); pro->waitForFinished(1000); outxsl.replace("/","\\"); filename.replace("/","\\"); pro->start("cmd /C del \""+outxsl+"\""); pro->waitForFinished(1000); pro->start("cmd /C del \""+filename+"\""); pro->waitForFinished(1000); #endif } } pro->kill(); return true; } else { return false; } } return false; } } // namespace efoto } // namespace eng } // namespace uerj } // namespace br
30.61413
118
0.583644
[ "object" ]
f6f233453582171e10a52705e3f98ff9dea29565
3,295
cc
C++
atom/browser/web_dialog_helper.cc
gitter-badger/atom-shell
8947d54cc9eb8f5bd5305805d5b4856939a07ecd
[ "MIT" ]
4
2016-04-02T14:53:54.000Z
2017-07-26T05:47:43.000Z
atom/browser/web_dialog_helper.cc
cocos-creator/atom-shell
d229338e40058a9b4323b2544f62818a3c55748c
[ "MIT" ]
null
null
null
atom/browser/web_dialog_helper.cc
cocos-creator/atom-shell
d229338e40058a9b4323b2544f62818a3c55748c
[ "MIT" ]
2
2015-07-18T09:31:03.000Z
2019-12-24T09:55:03.000Z
// Copyright (c) 2014 GitHub, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/web_dialog_helper.h" #include <vector> #include "atom/browser/ui/file_dialog.h" #include "base/bind.h" #include "base/files/file_enumerator.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/file_chooser_file_info.h" #include "ui/shell_dialogs/selected_file_info.h" namespace atom { WebDialogHelper::WebDialogHelper(NativeWindow* window) : window_(window), weak_factory_(this) { } WebDialogHelper::~WebDialogHelper() { } void WebDialogHelper::RunFileChooser(content::WebContents* web_contents, const content::FileChooserParams& params) { std::vector<content::FileChooserFileInfo> result; if (params.mode == content::FileChooserParams::Save) { base::FilePath path; if (file_dialog::ShowSaveDialog(window_, base::UTF16ToUTF8(params.title), params.default_file_name, file_dialog::Filters(), &path)) { content::FileChooserFileInfo info; info.file_path = path; info.display_name = path.BaseName().value(); result.push_back(info); } } else { int flags = file_dialog::FILE_DIALOG_CREATE_DIRECTORY; switch (params.mode) { case content::FileChooserParams::OpenMultiple: flags |= file_dialog::FILE_DIALOG_MULTI_SELECTIONS; case content::FileChooserParams::Open: flags |= file_dialog::FILE_DIALOG_OPEN_FILE; break; case content::FileChooserParams::UploadFolder: flags |= file_dialog::FILE_DIALOG_OPEN_DIRECTORY; break; default: NOTREACHED(); } std::vector<base::FilePath> paths; if (file_dialog::ShowOpenDialog(window_, base::UTF16ToUTF8(params.title), params.default_file_name, file_dialog::Filters(), flags, &paths)) { for (auto& path : paths) { content::FileChooserFileInfo info; info.file_path = path; info.display_name = path.BaseName().value(); result.push_back(info); } } } web_contents->GetRenderViewHost()->FilesSelectedInChooser( result, params.mode); } void WebDialogHelper::EnumerateDirectory(content::WebContents* web_contents, int request_id, const base::FilePath& dir) { int types = base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES | base::FileEnumerator::INCLUDE_DOT_DOT; base::FileEnumerator file_enum(dir, false, types); base::FilePath path; std::vector<base::FilePath> paths; while (!(path = file_enum.Next()).empty()) paths.push_back(path); web_contents->GetRenderViewHost()->DirectoryEnumerationFinished( request_id, paths); } } // namespace atom
34.322917
80
0.616388
[ "vector" ]
f6f7c01aee4af591c77f4bc87b011cf698ed1a6d
6,878
cpp
C++
src/socials.cpp
Kvitrafn/Aspen
0c98633d3d0fbe21e0bbb14edd7d19203711a3a2
[ "MIT" ]
null
null
null
src/socials.cpp
Kvitrafn/Aspen
0c98633d3d0fbe21e0bbb14edd7d19203711a3a2
[ "MIT" ]
null
null
null
src/socials.cpp
Kvitrafn/Aspen
0c98633d3d0fbe21e0bbb14edd7d19203711a3a2
[ "MIT" ]
null
null
null
#include <tinyxml2.h> #include <string> #include <map> #include "socials.h" #include "world.h" #include "living.h" #include "command.h" #include "utils.h" Socials* Socials::_ptr; Socials* Socials::GetPtr() { if (!Socials::_ptr) { Socials::_ptr = new Socials(); Socials::_ptr->Initialize(); } return Socials::_ptr; } void Socials::Initialize() { _socid = 1; } Socials::~Socials() { for (auto it:_slist) { delete it.second; } } void Socials::Save() { tinyxml2::XMLDocument doc; tinyxml2::XMLElement* socials = doc.NewElement("socials"); tinyxml2::XMLElement* social = nullptr; SOCIAL_DATA* sdata = NULL; doc.InsertEndChild(doc.NewDeclaration()); for (auto it: _slist) { sdata = it.second; social = doc.NewElement("social"); social->SetAttribute("id", sdata->id); social->SetAttribute("name", sdata->name.c_str()); social->SetAttribute("ynotarg", sdata->ynotarg.c_str()); social->SetAttribute("rnotarg", sdata->rnotarg.c_str()); social->SetAttribute("ttarg", sdata->ttarg.c_str()); social->SetAttribute("rtarg", sdata->rtarg.c_str()); social->SetAttribute("ytarg", sdata->ytarg.c_str()); socials->InsertEndChild(social); } doc.InsertEndChild(socials); doc.SaveFile(SOCIALS_FILE); } void Socials::Load() { World* world = World::GetPtr(); int id = 0; tinyxml2::XMLDocument doc; tinyxml2::XMLElement* socials = nullptr; tinyxml2::XMLElement* social = nullptr; SOCIAL_DATA* data = nullptr; if (!FileExists(SOCIALS_FILE)) { #ifdef NO_INIT_DEFAULTS world->WriteLog("No socials file exists, and NO_INIT_DEFAULTS was enabled.", CRIT); #else InitializeDefaultSocials(); #endif return; } if (doc.LoadFile(SOCIALS_FILE) != tinyxml2::XML_NO_ERROR) { world->WriteLog("Could not load XML socials file."); return; } socials = doc.FirstChildElement("socials"); if (socials) { for (social = socials->FirstChildElement(); social; social = social->NextSiblingElement()) { data = new SOCIAL_DATA(); data->id = social->IntAttribute("id"); data->name = social->Attribute("name"); data->ynotarg = social->Attribute("ynotarg"); data->rnotarg = social->Attribute("rnotarg"); data->ttarg = social->Attribute("ttarg"); data->rtarg = social->Attribute("rtarg"); data->ytarg = social->Attribute("ytarg"); if (id > _socid) { _socid = id+1; } _slist[data->name] = data; } } } BOOL Socials::SocialExists(const std::string &name) const { return (_slist.count(name) == 0? false:true); } BOOL Socials::AddSocial(const std::string &name, const std::string &ynotarg, const std::string &rnotarg, const std::string &ytarg, const std::string &rtarg, const std::string &ttarg) { if (SocialExists(name)) { return false; } SOCIAL_DATA* data = new SOCIAL_DATA(); data->name = name; data->ynotarg = ynotarg; data->rnotarg = rnotarg; data->ttarg = ttarg; data->rtarg = rtarg; data->ytarg = ytarg; data->id = _socid; _socid++; _slist[name] = data; return true; } SOCIAL_DATA* Socials::GetSocial(const std::string &name) { if (!SocialExists(name)) { return NULL; } return _slist[name]; } void Socials::InitializeDefaultSocials() { #ifndef NO_INIT_DEFAULTS AddSocial("smile", "You %a %v.", "%N %a %vs.", "You %a %v at %T.", "%N %a %vs at %T.", "%N %a %vs at you."); AddSocial("grin", "You %v %a.", "%N %vs %a.", "You %v %a at %T.", "%N %vs %a at %T.", "%N %vs %a at you."); AddSocial("nod", "You %v %a.", "%N %vs %a.", "You %v %a at %T.", "%N %vs %a at %T.", "%N %vs %a at you."); AddSocial("frown", "You %v %a.", "%N %vs %a.", "You %v %a at %T.", "%N %vs %a at %T.", "%N %vs %a at you."); AddSocial("wave", "You %a %v.", "%N %a %vs.", "You %a %v to %T.", "%N %a %vs to %T.", "%N %a %vs to you."); AddSocial("agree", "You %a %v.", "%N %a %vs.", "You %a %v with %T.", "%N %a %vs with %T.", "%N %a %vs with you."); AddSocial("chuckle", "You %v %a.", "%N %vs %a.", "You %v %a at %T.", "%N %vs %a at %T.", "%N %vs %a at you."); AddSocial("cower", "You %v in a corner.", "%N %vs in a corner.", "You %v in fear from %T.", "%N %vs in fear from %T.", "%N %vs in fear from you."); AddSocial("cry", "You %v.", "%N %vs.", "You %v on %T's shoulder.", "%N %vs on %T's shoulder.", "%N %vs on your shoulder."); AddSocial("wink", "you %v suggestively", "%N %vs suggestively", "You %v suggestively at %T.", "%N %vs suggestively at %T.", "%N %vs suggestively at you."); AddSocial("addict", "You stand and proclaim, \"I am %N, and I am a mud addict.\"", "%N stands and proclaims, \"I am %N, and I am a mud addict.\"", "You stand and proclaim to %T, \"I am %N, and I am a mud addict.\"", "%N stands and proclaims to %T, \"I am %N, and I am a mud addict.\"", "%N proclaims to you, \"I am %N, and I am a mud addict.\""); AddSocial("aargh", "You shout, %v!", "%N shouts, %v!", "You shout, %v at %T.", "%N shouts, %v at %T.", "%N shouts, %v at you."); Save(); #endif } void Socials::AddCommands() { World* world = World::GetPtr(); world->WriteLog("Adding social commands."); for (auto it: _slist) { CMDSocials*com = new CMDSocials(); com->SetName(it.second->name); com->SetType(CommandType::Social); com->SetSubcmd(it.second->id); world->commands.AddCommand(com); } } EVENT(socials_shutdown) { World* world = World::GetPtr(); world->WriteLog("Cleaning up socials."); Socials* soc = Socials::GetPtr(); soc->Save(); delete soc; } CMDSocials::CMDSocials() { } BOOL CMDSocials::Execute(const std::string &verb, Player* mobile,std::vector<std::string> &args,int subcmd) { Socials* soc = Socials::GetPtr(); SOCIAL_DATA* data = soc->GetSocial(verb); if (data == NULL) { mobile->Message(MSG_ERROR, "That social doesn't exist."); return false; } return true; } BOOL InitializeSocials() { World* world = World::GetPtr(); world->WriteLog("Initializing socials."); Socials* soc = Socials::GetPtr(); soc->Load(); soc->AddCommands(); world->events.AddCallback("Shutdown", socials_shutdown); world->events.AddCallback("Copyover", socials_shutdown); return true; }
32.597156
350
0.553068
[ "vector" ]
f6fb3e58280ea1247e832f05bd8f7064dfc72262
12,067
cpp
C++
Server/Shared/NGP/src/NavPacket.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Shared/NGP/src/NavPacket.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Shared/NGP/src/NavPacket.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd 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. */ #include "NavPacket.h" #include "MC2CRC32.h" byte NavPacket::MAX_PROTOVER = 0x0c; uint8 NavPacket::magicBytes[256] = { 0x37, 0x77, 0x89, 0x05, 0x28, 0x72, 0x5b, 0x2a, 0xce, 0xe4, 0x44, 0x1a, 0x28, 0x72, 0x5b, 0x2a, 0xce, 0xe4, 0x44, 0x1a, 0x79, 0x8a, 0xdb, 0x90, 0xce, 0xe4, 0x44, 0x1a, 0x79, 0x8a, 0xdb, 0x90, 0x2f, 0x5b, 0xcc, 0xd1, 0x79, 0x8a, 0xdb, 0x90, 0x2f, 0x5b, 0xcc, 0xd1, 0x6e, 0x72, 0xb4, 0x9a, 0x2f, 0x5b, 0xcc, 0xd1, 0x6e, 0x72, 0xb4, 0x9a, 0x79, 0x9b, 0xa5, 0x2b, 0x6e, 0x72, 0xb4, 0x9a, 0x79, 0x9b, 0xa5, 0x2b, 0x45, 0x6a, 0xc1, 0x7c, 0x79, 0x9b, 0xa5, 0x2b, 0x45, 0x6a, 0xc1, 0x7c, 0xe0, 0x4a, 0x81, 0x08, 0x45, 0x6a, 0xc1, 0x7c, 0xe0, 0x4a, 0x81, 0x08, 0xbc, 0xdb, 0x31, 0x8a, 0xe0, 0x4a, 0x81, 0x08, 0xbc, 0xdb, 0x31, 0x8a, 0xbe, 0x75, 0xa3, 0x36, 0xbc, 0xdb, 0x31, 0x8a, 0xbe, 0x75, 0xa3, 0x36, 0xfe, 0x7d, 0xc6, 0x2c, 0xbe, 0x75, 0xa3, 0x36, 0xfe, 0x7d, 0xc6, 0x2c, 0xd8, 0x91, 0xfc, 0x45, 0xfe, 0x7d, 0xc6, 0x2c, 0xd8, 0x91, 0xfc, 0x45, 0x03, 0xb0, 0xde, 0x7b, 0xd8, 0x91, 0xfc, 0x45, 0x03, 0xb0, 0xde, 0x7b, 0x4b, 0x82, 0xa6, 0x90, 0x03, 0xb0, 0xde, 0x7b, 0x4b, 0x82, 0xa6, 0x90, 0xeb, 0x67, 0x0c, 0xcb, 0x4b, 0x82, 0xa6, 0x90, 0xeb, 0x67, 0x0c, 0xcb, 0xb0, 0x8c, 0xd2, 0x6c, 0xeb, 0x67, 0x0c, 0xcb, 0xb0, 0x8c, 0xd2, 0x6c, 0x67, 0x03, 0xf5, 0x24, 0xb0, 0x8c, 0xd2, 0x6c, 0x67, 0x03, 0xf5, 0x24, 0x77, 0x98, 0x5a, 0x74, 0x67, 0x03, 0xf5, 0x24, 0x77, 0x98, 0x5a, 0x74, 0x14, 0x1f, 0x9f, 0xec, 0x77, 0x98, 0x5a, 0x74, 0x14, 0x1f, 0x9f, 0xec, 0xb0, 0x9b, 0x30, 0xb2, 0x14, 0x1f, 0x9f, 0xec, 0xb0, 0x9b, 0x30, 0xb2, 0x4b, 0x0e, 0x2d, 0x95, 0xb0, 0x9b, 0x30, 0xb2, 0x4b, 0x0e, 0x2d, 0x95, 0x90, 0xd3, 0x25, 0x7a, 0x4b, 0x0e, 0x2d, 0x95, }; NavPacket::NavPacket( byte protoVer, uint16 type, byte reqID, byte reqVer ) : m_protoVer( protoVer ), m_type( type ), m_reqID( reqID ), m_reqVer( reqVer ) { } NavPacket::NavPacket( byte protoVer, uint16 type, byte reqID, byte reqVer, const byte* buff, uint32 buffLen, uint32* uncompressedSize ) : m_protoVer( protoVer ), m_type( type ), m_reqID( reqID ), m_reqVer( reqVer ), m_params( buff, buffLen, protoVer, uncompressedSize ) { } const char* NavPacket::requestTypeAsString( uint16 type ) { switch( type ) { case NAV_INVALID : return "INVALID"; case NAV_ROUTE_REQ : return "Route"; case NAV_ROUTE_REPLY : return "Route Reply"; case NAV_SEARCH_REQ : return "Search"; case NAV_SEARCH_REPLY : return "Search Reply"; case NAV_REV_GEOCODING_REQ : return "ReverseGeocoding"; case NAV_REV_GEOCODING_REPLY : return "ReverseGeocoding Reply"; case NAV_MAP_REQ : return "Map"; case NAV_MAP_REPLY : return "Map Reply"; case NAV_FAV_REQ : return "Fav"; case NAV_FAV_REPLY : return "Fav Reply"; case NAV_INFO_REQ : return "Info"; case NAV_INFO_REPLY : return "Info Reply"; case NAV_DETAIL_REQ : return "Detail"; case NAV_DETAIL_REPLY : return "Detail Reply"; case NAV_MESSAGE_REQ : return "Message"; case NAV_MESSAGE_REPLY : return "Message Reply"; case NAV_UPGRADE_REQ : return "Upgrade"; case NAV_UPGRADE_REPLY : return "Upgrade Reply"; case NAV_VECTOR_MAP_REQ : return "VectorMap"; case NAV_VECTOR_MAP_REPLY : return "VectorMap Reply"; case NAV_MULTI_VECTOR_MAP_REQ : return "MultiVectorMap"; case NAV_MULTI_VECTOR_MAP_REPLY : return "MultiVectorMap Reply"; case NAV_CELL_REPORT : return "CellReport"; case NAV_CELL_CONFIRM : return "CellConfirm"; case NAV_TOP_REGION_REQ : return "TopRegion"; case NAV_TOP_REGION_REPLY : return "TopRegion Reply"; case NAV_LATEST_NEWS_REQ : return "LatestNews"; case NAV_LATEST_NEWS_REPLY : return "LatestNews Reply"; case NAV_CATEGORIES_REQ : return "Categories"; case NAV_CATEGORIES_REPLY : return "Categories Reply"; case NAV_CALLCENTER_LIST_REQ : return "CallcenterList"; case NAV_CALLCENTER_LIST_REPLY : return "CallcenterList Reply"; case NAV_SERVER_LIST_REQ : return "ServerList"; case NAV_SERVER_LIST_REPLY : return "ServerList Reply"; case NAV_NEW_PASSWORD_REQ : return "NewPassword"; case NAV_NEW_PASSWORD_REPLY : return "NewPassword Reply"; case NAV_SERVER_INFO_REQ : return "ServerInfo"; case NAV_SERVER_INFO_REPLY : return "ServerInfo Reply"; case NAV_WHOAMI_REQ : return "WhoAmI"; case NAV_WHOAMI_REPLY : return "WhoAmI Reply"; case NAV_BINARY_TRANSFER_REQ : return "BinaryTransfer"; case NAV_BINARY_TRANSFER_REPLY : return "BinaryTransfer Reply"; case NAV_NOP_REQ : return "NOP"; case NAV_NOP_REPLY : return "NOP Reply"; case NAV_CHANGED_LICENCE_REQ : return "ChangedLicence"; case NAV_CHANGED_LICENCE_REPLY : return "ChangedLicence Reply"; case NAV_SERVER_AUTH_BOB_REQ : return "ServerAuthBob"; case NAV_SERVER_AUTH_BOB_REPLY : return "ServerAuthBob Reply"; case NAV_TRACK_REQ : return "Tracking"; case NAV_TUNNEL_DATA_REQ : return "Tunnel"; case NAV_COMBINED_SEARCH_REQ : return "CombinedSearch"; case NAV_COMBINED_SEARCH_REPLY : return "CombinedSearch Reply"; case NAV_SEARCH_DESC_REQ : return "SearchDesc"; case NAV_SEARCH_DESC_REPLY : return "SearchDesc Reply"; case NAV_CELLID_LOOKUP_REQ: return "CellIDLookup"; case NAV_CELLID_LOOKUP_REPLY: return "CellIDLookup Reply"; case NAV_GET_KEYED_DATA_REQ: return "GetKeyedData"; case NAV_GET_KEYED_DATA_REPLY: return "GetKeyedData Reply"; case NAV_ECHO_REQ : return "Echo"; case NAV_ECHO_REPLY : return "Echo Reply"; case NAV_VERIFY_THIRD_PARTY_TRANSACTION_REQ : return "VerifyThirdPartyTransaction"; case NAV_VERIFY_THIRD_PARTY_TRANSACTION_REPLY : return "VerifyThirdPartyTransaction Reply"; case NAV_LOCAL_CATEGORY_TREE_REQ : return "LocalCategoryTree"; case NAV_LOCAL_CATEGORY_TREE_REPLY : return "LocalCategoryTree Reply"; case NAV_ONE_SEARCH_REQ : return "OneSearch"; case NAV_ONE_SEARCH_REPLY : return "OneSearch Reply"; }; return "UNKNOWN"; } void NavPacket::writeHeader( vector< byte >& buff ) const { // STX 1 buff.push_back( 0x02 ); // Length 4 (Real value written last) buff.push_back( 0 ); buff.push_back( 0 ); buff.push_back( 0 ); buff.push_back( 0 ); // protover 1 buff.push_back( m_protoVer ); // type 2 buff.push_back( ( m_type ) >> 8 ); buff.push_back( ( m_type ) & 0xff ); // req_id 1 buff.push_back( m_reqID ); // req_ver 1 buff.push_back( m_reqVer ); } void NavPacket::writeLengthAndParams( vector< byte >& buff, bool mayUseGzip, uint32* uncompressedSize ) const { // ParamBlock m_params.writeParams( buff, m_protoVer, mayUseGzip, uncompressedSize ); if ( uncompressedSize ) { *uncompressedSize += 4; // crc } // Write length // Length 1-4 buff[ 1 ] = (( buff.size() + 4 ) >> 24 ) & 0xff; buff[ 2 ] = (( buff.size() + 4 ) >> 16 ) & 0xff; buff[ 3 ] = (( buff.size() + 4 ) >> 8 ) & 0xff; buff[ 4 ] = (( buff.size() + 4 ) ) & 0xff; // CRC 4 uint32 crc = MC2CRC32::crc32( &buff.front(), buff.size() ); buff.push_back( (( crc ) >> 24 ) & 0xff ); buff.push_back( (( crc ) >> 16 ) & 0xff ); buff.push_back( (( crc ) >> 8 ) & 0xff ); buff.push_back( (( crc ) ) & 0xff ); } void NavPacket::dump( ostream& out, const char* prefix, bool dumpValues, bool singleLine, uint32 maxLen, uint32 maxSame ) const { out << prefix << " protoVer " << MC2HEX( int(m_protoVer) ); if ( !singleLine ) out << endl; out << " type " << MC2HEX( int(m_type) ); if ( !singleLine ) out << endl; out << " reqID " << MC2HEX( int(m_reqID) ); if ( !singleLine ) out << endl; out << " reqVer " << MC2HEX( int(m_reqVer) ); if ( !singleLine ) out << endl; if ( singleLine ) out << " "; m_params.dump( out, dumpValues, singleLine, maxLen, maxSame ); } NavRequestPacket::NavRequestPacket( byte protoVer, uint16 type, byte reqID, byte reqVer, const byte* buff, uint32 buffLen, uint32* uncompressedSize ) : NavPacket( protoVer, type, reqID, reqVer, buff, buffLen, uncompressedSize ) { } void NavRequestPacket::writeTo( vector< byte >& buff, bool mayUseGzip, uint32* uncompressedSize ) const { writeHeader( buff ); writeLengthAndParams( buff, mayUseGzip, uncompressedSize ); } NavReplyPacket::NavReplyPacket( byte protoVer, uint16 type, byte reqID, byte reqVer, byte statusCode, const char* statusMessage ) : NavPacket( protoVer, type, reqID, reqVer ), m_statusCode( statusCode ), m_statusMessage( statusMessage ) { } NavReplyPacket::NavReplyPacket( byte protoVer, uint16 type, byte reqID, byte reqVer, byte statusCode, const char* statusMessage, const byte* buff, uint32 buffLen, uint32* uncompressedSize ) : NavPacket( protoVer, type, reqID, reqVer, buff, buffLen, uncompressedSize ), m_statusCode( statusCode ), m_statusMessage( statusMessage ) { } void NavReplyPacket::writeTo( vector< byte >& buff, bool mayUseGzip, uint32* uncompressedSize ) const { // Header writeHeader( buff ); // status_code 1 buff.push_back( m_statusCode ); // status_message string for ( uint32 i = 0 ; i < m_statusMessage.size() ; ++i ) { buff.push_back( m_statusMessage[ i ] ); } buff.push_back( '\0' ); // Null byte writeLengthAndParams( buff, mayUseGzip, uncompressedSize ); }
36.677812
755
0.632137
[ "vector" ]
f6fd4cad317449e9cb7f79f46366798765afaa67
8,355
cpp
C++
realtime_obj_detect_cpp.cpp
YaserMarey/realtime_obj_detect_cpp
e5b750d9b5993c3ba338819d16ddbb1b50770e30
[ "MIT" ]
null
null
null
realtime_obj_detect_cpp.cpp
YaserMarey/realtime_obj_detect_cpp
e5b750d9b5993c3ba338819d16ddbb1b50770e30
[ "MIT" ]
null
null
null
realtime_obj_detect_cpp.cpp
YaserMarey/realtime_obj_detect_cpp
e5b750d9b5993c3ba338819d16ddbb1b50770e30
[ "MIT" ]
null
null
null
#include <fstream> #include <sstream> #include <opencv2/dnn.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> using namespace cv; using namespace dnn; using namespace std; float confThreshold, nmsThreshold; vector<string> classes; inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale, const Scalar& mean, bool swapRB); void postprocess(Mat& frame, const std::vector<Mat>& out, Net& net); void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame); int main(int argc, char** argv) { confThreshold = 0.4; nmsThreshold = 0.2; float scale = 1.0; Scalar mean = Scalar(0, 0, 0); bool swapRB = true; int inpWidth = 416; int inpHeight = 416; size_t asyncNumReq = 0; string modelPath = "yolov3.weights"; string configPath = "yolov3.cfg"; ifstream ifs("coco.names"); if (!ifs.is_open()) CV_Error(Error::StsError, "File coco.names not found"); string line; while (getline(ifs, line)) { classes.push_back(line); } // Load a model. Net net = readNet("yolov3.weights", "yolov3.cfg"); vector<String> outNames = net.getUnconnectedOutLayersNames(); // Create a window namedWindow("", WINDOW_NORMAL); // Open a video file or an image file or a camera stream. VideoCapture cap; //cap.open("traffic1.mp4"); cap.open(1); // Process frames. Mat frame, blob; while (waitKey(1) < 0) { cap >> frame; if (frame.empty()) { waitKey(); break; } preprocess(frame, net, Size(416, 416), 1.0, Scalar(0, 0, 0), true); vector<Mat> outs; net.forward(outs, outNames); postprocess(frame, outs, net); imshow("", frame); //if (waitKey(1) < 0) // break; } return 0; } inline void preprocess(const Mat& frame, Net& net, Size inpSize, float scale, const Scalar& mean, bool swapRB) { static Mat blob; blobFromImage(frame, blob, 1.0, inpSize, Scalar(), swapRB, false, CV_8U); // Run a model. net.setInput(blob, "", scale, mean); } void postprocess(Mat& frame, const std::vector<Mat>& outs, Net& net) { static vector<int> outLayers = net.getUnconnectedOutLayers(); static string outLayerType = net.getLayer(outLayers[0])->type; vector<int> classIds; vector<float> confidences; vector<Rect> boxes; if (outLayerType == "DetectionOutput") { // Network produces output blob with a shape 1x1xNx7 where N is a number of // detections and an every detection is a vector of values // [batchId, classId, confidence, left, top, right, bottom] CV_Assert(outs.size() > 0); for (size_t k = 0; k < outs.size(); k++) { float* data = (float*)outs[k].data; for (size_t i = 0; i < outs[k].total(); i += 7) { float confidence = data[i + 2]; if (confidence > confThreshold) { int left = (int)data[i + 3]; int top = (int)data[i + 4]; int right = (int)data[i + 5]; int bottom = (int)data[i + 6]; int width = right - left + 1; int height = bottom - top + 1; if (width <= 2 || height <= 2) { left = (int)(data[i + 3] * frame.cols); top = (int)(data[i + 4] * frame.rows); right = (int)(data[i + 5] * frame.cols); bottom = (int)(data[i + 6] * frame.rows); width = right - left + 1; height = bottom - top + 1; } classIds.push_back((int)(data[i + 1]) - 1); // Skip 0th background class id. boxes.push_back(Rect(left, top, width, height)); confidences.push_back(confidence); } } } } else if (outLayerType == "Region") { for (size_t i = 0; i < outs.size(); ++i) { // Network produces output blob with a shape NxC where N is a number of // detected objects and C is a number of classes + 4 where the first 4 // numbers are [center_x, center_y, width, height] float* data = (float*)outs[i].data; for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols) { Mat scores = outs[i].row(j).colRange(5, outs[i].cols); Point classIdPoint; double confidence; minMaxLoc(scores, 0, &confidence, 0, &classIdPoint); if (confidence > confThreshold) { int centerX = (int)(data[0] * frame.cols); int centerY = (int)(data[1] * frame.rows); int width = (int)(data[2] * frame.cols); int height = (int)(data[3] * frame.rows); int left = centerX - width / 2; int top = centerY - height / 2; classIds.push_back(classIdPoint.x); confidences.push_back((float)confidence); boxes.push_back(Rect(left, top, width, height)); } } } } else CV_Error(Error::StsNotImplemented, "Unknown output layer type: " + outLayerType); // NMS is used inside Region layer only on DNN_BACKEND_OPENCV for another backends we need NMS in sample // or NMS is required if number of outputs > 1 if (outLayers.size() > 1 || (outLayerType == "Region")) { std::map<int, std::vector<size_t> > class2indices; for (size_t i = 0; i < classIds.size(); i++) { if (confidences[i] >= confThreshold) { class2indices[classIds[i]].push_back(i); } } std::vector<Rect> nmsBoxes; std::vector<float> nmsConfidences; std::vector<int> nmsClassIds; for (std::map<int, std::vector<size_t> >::iterator it = class2indices.begin(); it != class2indices.end(); ++it) { std::vector<Rect> localBoxes; std::vector<float> localConfidences; std::vector<size_t> classIndices = it->second; for (size_t i = 0; i < classIndices.size(); i++) { localBoxes.push_back(boxes[classIndices[i]]); localConfidences.push_back(confidences[classIndices[i]]); } std::vector<int> nmsIndices; NMSBoxes(localBoxes, localConfidences, confThreshold, nmsThreshold, nmsIndices); for (size_t i = 0; i < nmsIndices.size(); i++) { size_t idx = nmsIndices[i]; nmsBoxes.push_back(localBoxes[idx]); nmsConfidences.push_back(localConfidences[idx]); nmsClassIds.push_back(it->first); } } boxes = nmsBoxes; classIds = nmsClassIds; confidences = nmsConfidences; } for (size_t idx = 0; idx < boxes.size(); ++idx) { Rect box = boxes[idx]; drawPred(classIds[idx], confidences[idx], box.x, box.y, box.x + box.width, box.y + box.height, frame); } } void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0)); string label = format("%.2f", conf); if (!classes.empty()) { CV_Assert(classId < (int)classes.size()); label = classes[classId] + ": " + label; } int baseLine; Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); top = max(top, labelSize.height); rectangle(frame, Point(left, top - labelSize.height), Point(left + labelSize.width, top + baseLine), Scalar::all(255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar()); }
34.958159
120
0.52304
[ "shape", "vector", "model" ]