repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
lnarolski/PLCino
moje_klasy.h
#ifndef MOJE_KLASY_H #define MOJE_KLASY_H class moje_klasy { public: moje_klasy(); }; #endif // MOJE_KLASY_H
lnarolski/PLCino
zmienna_w_arduino.h
#ifndef ZMIENNA_W_ARDUINO_H #define ZMIENNA_W_ARDUINO_H struct zmienna_w_arduino { QString numer_pinu; quint32 typ_zmiennej; // analogowa/dyskretna quint32 rodzaj_pinu; // wejscie/wyjscie }; #endif // ZMIENNA_W_ARDUINO_H
lnarolski/PLCino
ui_uzywane_zmienne.h
<reponame>lnarolski/PLCino<filename>ui_uzywane_zmienne.h<gh_stars>0 /******************************************************************************** ** Form generated from reading UI file 'uzywane_zmienne.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_UZYWANE_ZMIENNE_H #define UI_UZYWANE_ZMIENNE_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QPushButton> #include <QtWidgets/QTableView> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_uzywane_zmienne { public: QGridLayout *gridLayout; QHBoxLayout *horizontalLayout; QVBoxLayout *verticalLayout; QPushButton *nowa; QPushButton *usun; QTableView *tableView; void setupUi(QDialog *uzywane_zmienne) { if (uzywane_zmienne->objectName().isEmpty()) uzywane_zmienne->setObjectName(QStringLiteral("uzywane_zmienne")); uzywane_zmienne->setWindowModality(Qt::WindowModal); uzywane_zmienne->resize(622, 300); gridLayout = new QGridLayout(uzywane_zmienne); gridLayout->setObjectName(QStringLiteral("gridLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); nowa = new QPushButton(uzywane_zmienne); nowa->setObjectName(QStringLiteral("nowa")); verticalLayout->addWidget(nowa); usun = new QPushButton(uzywane_zmienne); usun->setObjectName(QStringLiteral("usun")); verticalLayout->addWidget(usun); horizontalLayout->addLayout(verticalLayout); gridLayout->addLayout(horizontalLayout, 0, 1, 1, 1); tableView = new QTableView(uzywane_zmienne); tableView->setObjectName(QStringLiteral("tableView")); gridLayout->addWidget(tableView, 0, 0, 1, 1); retranslateUi(uzywane_zmienne); QMetaObject::connectSlotsByName(uzywane_zmienne); } // setupUi void retranslateUi(QDialog *uzywane_zmienne) { uzywane_zmienne->setWindowTitle(QApplication::translate("uzywane_zmienne", "U\305\274ywane zmienne", Q_NULLPTR)); nowa->setText(QApplication::translate("uzywane_zmienne", "Nowa", Q_NULLPTR)); usun->setText(QApplication::translate("uzywane_zmienne", "Usu\305\204", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class uzywane_zmienne: public Ui_uzywane_zmienne {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_UZYWANE_ZMIENNE_H
lnarolski/PLCino
plcino.h
#ifndef PLCINO_H #define PLCINO_H #include <QDesktopWidget> #include <QTableWidget> #include <QStandardItemModel> #include <QSizePolicy> #include <QtDebug> #include <QMessageBox> #include <QInputDialog> #include <QMainWindow> #include <QHBoxLayout> #include <QVBoxLayout> #include <QList> #include <QTableView> #include <QStandardItemModel> #include <QMap> #include <QString> #include <QFileDialog> #include <QDir> #include <QWizard> #include <QLabel> #include <QLineEdit> #include <QProcess> #include <QSerialPort> #include <QThread> #include <QSerialPortInfo> #include <uzywane_zmienne.h> #include <model_drabinka.h> #include <wybor_portu.h> #include <zmienna_w_arduino.h> #include <edycja_specjalna.h> #include "elementy_schematu.h" enum rodzaje_obslugiwanych_plytek { leonardo, nano, mega, brak }; namespace Ui { class PLCino; } class PLCino : public QMainWindow //główna klasa programu { Q_OBJECT public: explicit PLCino(QWidget *parent = 0); ~PLCino(); private slots: void on_actionNowa_linia_triggered(); void on_actionUsun_linie_triggered(); void on_actionDodaj_kolumne_triggered(); void on_actionUsun_kolumne_triggered(); void on_actionDodaj_wiersz_triggered(); void on_actionUsun_wiersz_triggered(); void on_actionUzywane_zmienne_triggered(); void on_actionPort_triggered(); void edycja_wlasciwosci(const QModelIndex ModelIndex); void on_actionLeonadro_triggered(); void on_actionMega_triggered(); void on_actionNano_triggered(); void on_actionNowy_triggered(); void on_actionZamknij_triggered(); void on_actionKompiluj_do_C_triggered(); void on_actionKompiluj_i_wgraj_do_Arduino_triggered(); void on_actionZapisz_triggered(); void on_actionOtworz_triggered(); void on_actionEdycja_wlasciwosci_triggered(); void on_actionUsun_element_triggered(); void on_actionWgraj_plik_C_do_Arduino_triggered(); public: Ui::PLCino *ui; QList<QTableView*> lista_linii; //lista graficznych linii(tabel) QList<model_drabinka*> lista_modeli; //lista modeli danych dla każdej graficznej linii QMap<QString, zmienna_w_arduino> lista_uzywanych_zmiennych; //lista używanych zmiennych z nazwami w środowisku graficznym oraz odpowiadającymi im nazwami w programie Arduino uzywane_zmienne* okno_edycji_zmiennych; //okno służące do edycji listy używanych zmiennych QDialog* okno_wyboru_portu; //okno używane do wyboru portu COM, do którego podłączona jest płytka Arduino dodawanie_zmiennej *okno_dodawanie_zmiennej; //okno pojawiające się, gdy użytkownik chce ustawić zmienną do elementu, która jeszcze nie istnieje edycja_specjalna *okno_edycji_specjalnej; struct { QString nazwa_wybranego_portu; rodzaje_obslugiwanych_plytek wybrana_plytka; QString sciezka_zapisu_projektu; QString sciezka_zapisu_kompilacja; } konfiguracja; //struktura z konfiguracją programu private: int kompilator(); int wybranie_sciezki_zapisu(int); //ELEMENTY WYKORZYSTYWANE NA POTRZEBY KOMPILACJI QString warunek; bool sprawdz_czy_jest_na_liscie(elementy_drabinki* a, QList<elementy_schematu*>* b); bool sprawdz_czy_jest_na_liscie(elementy_schematu* a, QList<elementy_schematu*> b); bool sprawdz_czy_jest_na_wejsciu_lub_wyjsciu(elementy_drabinki* a, elementy_schematu* b); elementy_schematu* znajdz_element_drabinki(QList <elementy_schematu*> lista, elementy_drabinki* a); bool czy_styk_nalezy_do_bloku_funkcyjnego(QString nazwa_zmiennej, QList<elementy_schematu*> liczniki, QList<elementy_schematu*> timery); void tworzenie_warunkow(QTextStream &out, elementy_schematu* element, QString string, QList<elementy_schematu*> liczniki, QList<elementy_schematu*> timery); QString poszukiwanie_portu_bootloadera(QList<QSerialPortInfo> *przed_resetem, QList<QSerialPortInfo> *po_resecie); }; #endif // PLCINO_H
lnarolski/PLCino
ui_plcino.h
<reponame>lnarolski/PLCino /******************************************************************************** ** Form generated from reading UI file 'plcino.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_PLCINO_H #define UI_PLCINO_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenu> #include <QtWidgets/QMenuBar> #include <QtWidgets/QScrollArea> #include <QtWidgets/QStatusBar> #include <QtWidgets/QToolBar> #include <QtWidgets/QTreeWidget> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_PLCino { public: QAction *actionOtworz; QAction *actionZamknij; QAction *actionKompiluj_do_C; QAction *actionKompiluj_i_wgraj_do_Arduino; QAction *actionPort; QAction *actionZapisz; QAction *actionUzywane_zmienne; QAction *actionNowa_linia; QAction *actionUsun_linie; QAction *actionDodaj_kolumne; QAction *actionUsun_kolumne; QAction *actionDodaj_wiersz; QAction *actionUsun_wiersz; QAction *actionLeonadro; QAction *actionMega; QAction *actionNano; QAction *actionZapisz_jako; QAction *actionNowy; QAction *actionEdycja_wlasciwosci; QAction *actionUsun_element; QAction *actionWgraj_plik_C_do_Arduino; QWidget *centralWidget; QGridLayout *gridLayout; QHBoxLayout *horizontalLayout; QScrollArea *scrollArea; QWidget *scrollAreaWidgetContents; QGridLayout *gridLayout_2; QVBoxLayout *verticalLayout; QTreeWidget *treeWidget; QMenuBar *menuBar; QMenu *menuPlik; QMenu *menuKompilacja; QMenu *menuUstawienia; QMenu *menuRodzaj_p_ytki; QMenu *menuEdytuj; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *PLCino) { if (PLCino->objectName().isEmpty()) PLCino->setObjectName(QStringLiteral("PLCino")); PLCino->setWindowModality(Qt::WindowModal); PLCino->resize(1188, 631); actionOtworz = new QAction(PLCino); actionOtworz->setObjectName(QStringLiteral("actionOtworz")); actionZamknij = new QAction(PLCino); actionZamknij->setObjectName(QStringLiteral("actionZamknij")); actionKompiluj_do_C = new QAction(PLCino); actionKompiluj_do_C->setObjectName(QStringLiteral("actionKompiluj_do_C")); actionKompiluj_i_wgraj_do_Arduino = new QAction(PLCino); actionKompiluj_i_wgraj_do_Arduino->setObjectName(QStringLiteral("actionKompiluj_i_wgraj_do_Arduino")); actionPort = new QAction(PLCino); actionPort->setObjectName(QStringLiteral("actionPort")); actionZapisz = new QAction(PLCino); actionZapisz->setObjectName(QStringLiteral("actionZapisz")); actionUzywane_zmienne = new QAction(PLCino); actionUzywane_zmienne->setObjectName(QStringLiteral("actionUzywane_zmienne")); actionNowa_linia = new QAction(PLCino); actionNowa_linia->setObjectName(QStringLiteral("actionNowa_linia")); QIcon icon; icon.addFile(QStringLiteral("Ikony/nowa_linia.png"), QSize(), QIcon::Normal, QIcon::Off); actionNowa_linia->setIcon(icon); actionUsun_linie = new QAction(PLCino); actionUsun_linie->setObjectName(QStringLiteral("actionUsun_linie")); QIcon icon1; icon1.addFile(QStringLiteral("Ikony/usun_linie.png"), QSize(), QIcon::Normal, QIcon::Off); actionUsun_linie->setIcon(icon1); actionDodaj_kolumne = new QAction(PLCino); actionDodaj_kolumne->setObjectName(QStringLiteral("actionDodaj_kolumne")); QIcon icon2; icon2.addFile(QStringLiteral("Ikony/dodaj_kolumne.png"), QSize(), QIcon::Normal, QIcon::Off); actionDodaj_kolumne->setIcon(icon2); actionUsun_kolumne = new QAction(PLCino); actionUsun_kolumne->setObjectName(QStringLiteral("actionUsun_kolumne")); QIcon icon3; icon3.addFile(QStringLiteral("Ikony/usun_kolumne.png"), QSize(), QIcon::Normal, QIcon::Off); actionUsun_kolumne->setIcon(icon3); actionDodaj_wiersz = new QAction(PLCino); actionDodaj_wiersz->setObjectName(QStringLiteral("actionDodaj_wiersz")); QIcon icon4; icon4.addFile(QStringLiteral("Ikony/dodaj_wiersz.png"), QSize(), QIcon::Normal, QIcon::Off); actionDodaj_wiersz->setIcon(icon4); actionUsun_wiersz = new QAction(PLCino); actionUsun_wiersz->setObjectName(QStringLiteral("actionUsun_wiersz")); QIcon icon5; icon5.addFile(QStringLiteral("Ikony/usun_wiersz.png"), QSize(), QIcon::Normal, QIcon::Off); actionUsun_wiersz->setIcon(icon5); actionLeonadro = new QAction(PLCino); actionLeonadro->setObjectName(QStringLiteral("actionLeonadro")); actionLeonadro->setCheckable(true); actionMega = new QAction(PLCino); actionMega->setObjectName(QStringLiteral("actionMega")); actionMega->setCheckable(true); actionNano = new QAction(PLCino); actionNano->setObjectName(QStringLiteral("actionNano")); actionNano->setCheckable(true); actionNano->setChecked(false); actionZapisz_jako = new QAction(PLCino); actionZapisz_jako->setObjectName(QStringLiteral("actionZapisz_jako")); actionNowy = new QAction(PLCino); actionNowy->setObjectName(QStringLiteral("actionNowy")); actionEdycja_wlasciwosci = new QAction(PLCino); actionEdycja_wlasciwosci->setObjectName(QStringLiteral("actionEdycja_wlasciwosci")); actionUsun_element = new QAction(PLCino); actionUsun_element->setObjectName(QStringLiteral("actionUsun_element")); actionWgraj_plik_C_do_Arduino = new QAction(PLCino); actionWgraj_plik_C_do_Arduino->setObjectName(QStringLiteral("actionWgraj_plik_C_do_Arduino")); centralWidget = new QWidget(PLCino); centralWidget->setObjectName(QStringLiteral("centralWidget")); gridLayout = new QGridLayout(centralWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(6); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); scrollArea = new QScrollArea(centralWidget); scrollArea->setObjectName(QStringLiteral("scrollArea")); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); scrollArea->setWidgetResizable(true); scrollArea->setAlignment(Qt::AlignHCenter|Qt::AlignTop); scrollAreaWidgetContents = new QWidget(); scrollAreaWidgetContents->setObjectName(QStringLiteral("scrollAreaWidgetContents")); scrollAreaWidgetContents->setGeometry(QRect(0, 0, 906, 536)); gridLayout_2 = new QGridLayout(scrollAreaWidgetContents); gridLayout_2->setSpacing(6); gridLayout_2->setContentsMargins(11, 11, 11, 11); gridLayout_2->setObjectName(QStringLiteral("gridLayout_2")); gridLayout_2->setSizeConstraint(QLayout::SetMaximumSize); verticalLayout = new QVBoxLayout(); verticalLayout->setSpacing(6); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setSizeConstraint(QLayout::SetDefaultConstraint); gridLayout_2->addLayout(verticalLayout, 0, 0, 1, 1); scrollArea->setWidget(scrollAreaWidgetContents); horizontalLayout->addWidget(scrollArea); treeWidget = new QTreeWidget(centralWidget); QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem(treeWidget); __qtreewidgetitem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); new QTreeWidgetItem(__qtreewidgetitem); new QTreeWidgetItem(__qtreewidgetitem); QTreeWidgetItem *__qtreewidgetitem1 = new QTreeWidgetItem(treeWidget); __qtreewidgetitem1->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); new QTreeWidgetItem(__qtreewidgetitem1); new QTreeWidgetItem(__qtreewidgetitem1); QTreeWidgetItem *__qtreewidgetitem2 = new QTreeWidgetItem(treeWidget); __qtreewidgetitem2->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); new QTreeWidgetItem(__qtreewidgetitem2); new QTreeWidgetItem(__qtreewidgetitem2); QTreeWidgetItem *__qtreewidgetitem3 = new QTreeWidgetItem(treeWidget); __qtreewidgetitem3->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); new QTreeWidgetItem(__qtreewidgetitem3); new QTreeWidgetItem(__qtreewidgetitem3); new QTreeWidgetItem(__qtreewidgetitem3); new QTreeWidgetItem(__qtreewidgetitem3); new QTreeWidgetItem(__qtreewidgetitem3); new QTreeWidgetItem(__qtreewidgetitem3); QTreeWidgetItem *__qtreewidgetitem4 = new QTreeWidgetItem(treeWidget); __qtreewidgetitem4->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); new QTreeWidgetItem(__qtreewidgetitem4); treeWidget->setObjectName(QStringLiteral("treeWidget")); treeWidget->setDragEnabled(true); treeWidget->setAnimated(true); horizontalLayout->addWidget(treeWidget); horizontalLayout->setStretch(0, 9); gridLayout->addLayout(horizontalLayout, 0, 1, 1, 1); PLCino->setCentralWidget(centralWidget); menuBar = new QMenuBar(PLCino); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 1188, 21)); menuPlik = new QMenu(menuBar); menuPlik->setObjectName(QStringLiteral("menuPlik")); menuKompilacja = new QMenu(menuBar); menuKompilacja->setObjectName(QStringLiteral("menuKompilacja")); menuUstawienia = new QMenu(menuBar); menuUstawienia->setObjectName(QStringLiteral("menuUstawienia")); menuRodzaj_p_ytki = new QMenu(menuUstawienia); menuRodzaj_p_ytki->setObjectName(QStringLiteral("menuRodzaj_p_ytki")); menuEdytuj = new QMenu(menuBar); menuEdytuj->setObjectName(QStringLiteral("menuEdytuj")); PLCino->setMenuBar(menuBar); mainToolBar = new QToolBar(PLCino); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); mainToolBar->setMovable(false); PLCino->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(PLCino); statusBar->setObjectName(QStringLiteral("statusBar")); statusBar->setSizeGripEnabled(false); PLCino->setStatusBar(statusBar); menuBar->addAction(menuPlik->menuAction()); menuBar->addAction(menuEdytuj->menuAction()); menuBar->addAction(menuKompilacja->menuAction()); menuBar->addAction(menuUstawienia->menuAction()); menuPlik->addAction(actionNowy); menuPlik->addAction(actionOtworz); menuPlik->addAction(actionZapisz); menuPlik->addAction(actionZamknij); menuKompilacja->addAction(actionKompiluj_do_C); menuKompilacja->addAction(actionWgraj_plik_C_do_Arduino); menuKompilacja->addAction(actionKompiluj_i_wgraj_do_Arduino); menuUstawienia->addAction(menuRodzaj_p_ytki->menuAction()); menuUstawienia->addAction(actionPort); menuUstawienia->addAction(actionUzywane_zmienne); menuRodzaj_p_ytki->addAction(actionLeonadro); menuRodzaj_p_ytki->addAction(actionMega); menuRodzaj_p_ytki->addAction(actionNano); menuEdytuj->addAction(actionEdycja_wlasciwosci); menuEdytuj->addAction(actionUsun_element); mainToolBar->addAction(actionZapisz); mainToolBar->addAction(actionOtworz); mainToolBar->addSeparator(); mainToolBar->addAction(actionNowa_linia); mainToolBar->addAction(actionUsun_linie); mainToolBar->addSeparator(); mainToolBar->addAction(actionDodaj_kolumne); mainToolBar->addAction(actionUsun_kolumne); mainToolBar->addAction(actionDodaj_wiersz); mainToolBar->addAction(actionUsun_wiersz); retranslateUi(PLCino); QMetaObject::connectSlotsByName(PLCino); } // setupUi void retranslateUi(QMainWindow *PLCino) { PLCino->setWindowTitle(QApplication::translate("PLCino", "PLCino", Q_NULLPTR)); actionOtworz->setText(QApplication::translate("PLCino", "Otw\303\263rz", Q_NULLPTR)); #ifndef QT_NO_SHORTCUT actionOtworz->setShortcut(QApplication::translate("PLCino", "Ctrl+O", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionZamknij->setText(QApplication::translate("PLCino", "Zamknij", Q_NULLPTR)); actionKompiluj_do_C->setText(QApplication::translate("PLCino", "Kompiluj do C++", Q_NULLPTR)); #ifndef QT_NO_SHORTCUT actionKompiluj_do_C->setShortcut(QApplication::translate("PLCino", "F5", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionKompiluj_i_wgraj_do_Arduino->setText(QApplication::translate("PLCino", "Kompiluj i wgraj do Arduino", Q_NULLPTR)); #ifndef QT_NO_SHORTCUT actionKompiluj_i_wgraj_do_Arduino->setShortcut(QApplication::translate("PLCino", "F9", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionPort->setText(QApplication::translate("PLCino", "Port", Q_NULLPTR)); actionZapisz->setText(QApplication::translate("PLCino", "Zapisz", Q_NULLPTR)); #ifndef QT_NO_SHORTCUT actionZapisz->setShortcut(QApplication::translate("PLCino", "Ctrl+S", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionUzywane_zmienne->setText(QApplication::translate("PLCino", "U\305\274ywane zmienne", Q_NULLPTR)); actionNowa_linia->setText(QApplication::translate("PLCino", "Nowa linia", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP actionNowa_linia->setToolTip(QApplication::translate("PLCino", "Utw\303\263rz now\304\205 lini\304\231 z drabink\304\205", Q_NULLPTR)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_SHORTCUT actionNowa_linia->setShortcut(QApplication::translate("PLCino", "Ctrl+T", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionUsun_linie->setText(QApplication::translate("PLCino", "Usu\305\204 lini\304\231", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP actionUsun_linie->setToolTip(QApplication::translate("PLCino", "Usuwa aktualnie wybran\304\205 lini\304\231 z drabink\304\205", Q_NULLPTR)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_SHORTCUT actionUsun_linie->setShortcut(QApplication::translate("PLCino", "Ctrl+W", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionDodaj_kolumne->setText(QApplication::translate("PLCino", "Dodaj kolumn\304\231", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP actionDodaj_kolumne->setToolTip(QApplication::translate("PLCino", "Dodaje kolumn\304\231 do aktualnie wybranej linii", Q_NULLPTR)); #endif // QT_NO_TOOLTIP actionUsun_kolumne->setText(QApplication::translate("PLCino", "Usu\305\204 kolumn\304\231", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP actionUsun_kolumne->setToolTip(QApplication::translate("PLCino", "Usuwa kolumn\304\231 z aktualnie wybranej linii", Q_NULLPTR)); #endif // QT_NO_TOOLTIP actionDodaj_wiersz->setText(QApplication::translate("PLCino", "Dodaj wiersz", Q_NULLPTR)); actionUsun_wiersz->setText(QApplication::translate("PLCino", "Usu\305\204 wiersz", Q_NULLPTR)); actionLeonadro->setText(QApplication::translate("PLCino", "Leonadro", Q_NULLPTR)); actionMega->setText(QApplication::translate("PLCino", "Mega", Q_NULLPTR)); actionNano->setText(QApplication::translate("PLCino", "Nano", Q_NULLPTR)); actionZapisz_jako->setText(QApplication::translate("PLCino", "Zapisz jako", Q_NULLPTR)); actionNowy->setText(QApplication::translate("PLCino", "Nowy", Q_NULLPTR)); #ifndef QT_NO_SHORTCUT actionNowy->setShortcut(QApplication::translate("PLCino", "Ctrl+N", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionEdycja_wlasciwosci->setText(QApplication::translate("PLCino", "Edycja w\305\202a\305\233ciwo\305\233ci", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP actionEdycja_wlasciwosci->setToolTip(QApplication::translate("PLCino", "Edycja w\305\202a\305\233ciwo\305\233ci wybranego elementu", Q_NULLPTR)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_SHORTCUT actionEdycja_wlasciwosci->setShortcut(QApplication::translate("PLCino", "Return", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionUsun_element->setText(QApplication::translate("PLCino", "Usu\305\204 element", Q_NULLPTR)); #ifndef QT_NO_TOOLTIP actionUsun_element->setToolTip(QApplication::translate("PLCino", "Usuwa zaznaczony element", Q_NULLPTR)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_SHORTCUT actionUsun_element->setShortcut(QApplication::translate("PLCino", "Del", Q_NULLPTR)); #endif // QT_NO_SHORTCUT actionWgraj_plik_C_do_Arduino->setText(QApplication::translate("PLCino", "Wgraj plik C++ do Arduino", Q_NULLPTR)); #ifndef QT_NO_SHORTCUT actionWgraj_plik_C_do_Arduino->setShortcut(QApplication::translate("PLCino", "F7", Q_NULLPTR)); #endif // QT_NO_SHORTCUT QTreeWidgetItem *___qtreewidgetitem = treeWidget->headerItem(); ___qtreewidgetitem->setText(0, QApplication::translate("PLCino", "Elementy drabinki", Q_NULLPTR)); const bool __sortingEnabled = treeWidget->isSortingEnabled(); treeWidget->setSortingEnabled(false); QTreeWidgetItem *___qtreewidgetitem1 = treeWidget->topLevelItem(0); ___qtreewidgetitem1->setText(0, QApplication::translate("PLCino", "Cewka", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem2 = ___qtreewidgetitem1->child(0); ___qtreewidgetitem2->setText(0, QApplication::translate("PLCino", "Zwyk\305\202a -( )-", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem3 = ___qtreewidgetitem1->child(1); ___qtreewidgetitem3->setText(0, QApplication::translate("PLCino", "Zanegowana -(/)-", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem4 = treeWidget->topLevelItem(1); ___qtreewidgetitem4->setText(0, QApplication::translate("PLCino", "Styk", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem5 = ___qtreewidgetitem4->child(0); ___qtreewidgetitem5->setText(0, QApplication::translate("PLCino", "Zwyk\305\202y -| |-", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem6 = ___qtreewidgetitem4->child(1); ___qtreewidgetitem6->setText(0, QApplication::translate("PLCino", "Zanegowany -|/|-", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem7 = treeWidget->topLevelItem(2); ___qtreewidgetitem7->setText(0, QApplication::translate("PLCino", "Blok funkcyjny", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem8 = ___qtreewidgetitem7->child(0); ___qtreewidgetitem8->setText(0, QApplication::translate("PLCino", "Licznik CTU", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem9 = ___qtreewidgetitem7->child(1); ___qtreewidgetitem9->setText(0, QApplication::translate("PLCino", "Timer TON", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem10 = treeWidget->topLevelItem(3); ___qtreewidgetitem10->setText(0, QApplication::translate("PLCino", "Operator por\303\263wnania", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem11 = ___qtreewidgetitem10->child(0); ___qtreewidgetitem11->setText(0, QApplication::translate("PLCino", "Wi\304\231ksze >", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem12 = ___qtreewidgetitem10->child(1); ___qtreewidgetitem12->setText(0, QApplication::translate("PLCino", "Wi\304\231ksze b\304\205d\305\272 r\303\263wne >=", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem13 = ___qtreewidgetitem10->child(2); ___qtreewidgetitem13->setText(0, QApplication::translate("PLCino", "Mniejsze <", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem14 = ___qtreewidgetitem10->child(3); ___qtreewidgetitem14->setText(0, QApplication::translate("PLCino", "Mniejsze b\304\205d\305\272 r\303\263wne <=", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem15 = ___qtreewidgetitem10->child(4); ___qtreewidgetitem15->setText(0, QApplication::translate("PLCino", "R\303\263wne ==", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem16 = ___qtreewidgetitem10->child(5); ___qtreewidgetitem16->setText(0, QApplication::translate("PLCino", "R\303\263\305\274ne !=", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem17 = treeWidget->topLevelItem(4); ___qtreewidgetitem17->setText(0, QApplication::translate("PLCino", "\305\201\304\205czniki", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem18 = ___qtreewidgetitem17->child(0); ___qtreewidgetitem18->setText(0, QApplication::translate("PLCino", "\342\224\200", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem19 = ___qtreewidgetitem17->child(1); ___qtreewidgetitem19->setText(0, QApplication::translate("PLCino", "\342\224\202", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem20 = ___qtreewidgetitem17->child(2); ___qtreewidgetitem20->setText(0, QApplication::translate("PLCino", "\342\224\214", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem21 = ___qtreewidgetitem17->child(3); ___qtreewidgetitem21->setText(0, QApplication::translate("PLCino", "\342\224\220", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem22 = ___qtreewidgetitem17->child(4); ___qtreewidgetitem22->setText(0, QApplication::translate("PLCino", "\342\224\224", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem23 = ___qtreewidgetitem17->child(5); ___qtreewidgetitem23->setText(0, QApplication::translate("PLCino", "\342\224\230", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem24 = ___qtreewidgetitem17->child(6); ___qtreewidgetitem24->setText(0, QApplication::translate("PLCino", "\342\224\234", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem25 = ___qtreewidgetitem17->child(7); ___qtreewidgetitem25->setText(0, QApplication::translate("PLCino", "\342\224\244", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem26 = ___qtreewidgetitem17->child(8); ___qtreewidgetitem26->setText(0, QApplication::translate("PLCino", "\342\224\254", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem27 = ___qtreewidgetitem17->child(9); ___qtreewidgetitem27->setText(0, QApplication::translate("PLCino", "\342\224\264", Q_NULLPTR)); QTreeWidgetItem *___qtreewidgetitem28 = ___qtreewidgetitem17->child(10); ___qtreewidgetitem28->setText(0, QApplication::translate("PLCino", "\342\224\274", Q_NULLPTR)); treeWidget->setSortingEnabled(__sortingEnabled); menuPlik->setTitle(QApplication::translate("PLCino", "Plik", Q_NULLPTR)); menuKompilacja->setTitle(QApplication::translate("PLCino", "Kompilacja", Q_NULLPTR)); menuUstawienia->setTitle(QApplication::translate("PLCino", "Ustawienia", Q_NULLPTR)); menuRodzaj_p_ytki->setTitle(QApplication::translate("PLCino", "Rodzaj p\305\202ytki", Q_NULLPTR)); menuEdytuj->setTitle(QApplication::translate("PLCino", "Edycja", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class PLCino: public Ui_PLCino {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_PLCINO_H
lnarolski/PLCino
elementy_drabinki.h
#ifndef ELEMENTY_DRABINKI_H #define ELEMENTY_DRABINKI_H #include <typy_wyliczeniowe.h> #include <QString> #include <QImage> #include <QDataStream> #include <QMap> class elementy_drabinki { public: elementy rodzaj; //rodzaj na podstawie typu wyliczeniowego quint32 rodzaj2; //"podrodzaj" elementu - na podstawie stałych preprocesora QString zmienna; //nazwa zmiennej do ktorej obiekt sie odwoluje QString nazwa; //symboliczna nazwa elementu elementy_drabinki(elementy rodzaj = pusty, quint32 rodzaj2 = 0); //konstruktor QMap<quint32, QString> parametry; }; #endif // ELEMENTY_DRABINKI_H
lnarolski/PLCino
okno_edycji_wlasciwosci.h
#ifndef OKNO_EDYCJI_WLASCIWOSCI_H #define OKNO_EDYCJI_WLASCIWOSCI_H #include <QDialog> namespace Ui { class okno_edycji_wlasciwosci; } class okno_edycji_wlasciwosci : public QDialog { Q_OBJECT public: explicit okno_edycji_wlasciwosci(QWidget *parent = 0, QVariant* data = NULL); ~okno_edycji_wlasciwosci(); QVariant* edytowana_komorka; private: Ui::okno_edycji_wlasciwosci *ui; }; #endif // OKNO_EDYCJI_WLASCIWOSCI_H
lnarolski/PLCino
ui_wybor_portu.h
/******************************************************************************** ** Form generated from reading UI file 'wybor_portu.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_WYBOR_PORTU_H #define UI_WYBOR_PORTU_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QListWidget> QT_BEGIN_NAMESPACE class Ui_Wybor_portu { public: QGridLayout *gridLayout_3; QGridLayout *gridLayout_2; QListWidget *listWidget; QDialogButtonBox *buttonBox; void setupUi(QDialog *Wybor_portu) { if (Wybor_portu->objectName().isEmpty()) Wybor_portu->setObjectName(QStringLiteral("Wybor_portu")); Wybor_portu->setWindowModality(Qt::WindowModal); Wybor_portu->resize(402, 275); gridLayout_3 = new QGridLayout(Wybor_portu); gridLayout_3->setObjectName(QStringLiteral("gridLayout_3")); gridLayout_2 = new QGridLayout(); gridLayout_2->setObjectName(QStringLiteral("gridLayout_2")); listWidget = new QListWidget(Wybor_portu); listWidget->setObjectName(QStringLiteral("listWidget")); listWidget->setViewMode(QListView::ListMode); listWidget->setSortingEnabled(true); gridLayout_2->addWidget(listWidget, 0, 0, 1, 1); buttonBox = new QDialogButtonBox(Wybor_portu); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setOrientation(Qt::Vertical); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok|QDialogButtonBox::Reset); gridLayout_2->addWidget(buttonBox, 0, 1, 1, 1); gridLayout_3->addLayout(gridLayout_2, 0, 0, 1, 1); retranslateUi(Wybor_portu); QMetaObject::connectSlotsByName(Wybor_portu); } // setupUi void retranslateUi(QDialog *Wybor_portu) { Wybor_portu->setWindowTitle(QApplication::translate("Wybor_portu", "Dialog", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Wybor_portu: public Ui_Wybor_portu {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_WYBOR_PORTU_H
lnarolski/PLCino
uzywane_zmienne.h
#ifndef UZYWANE_ZMIENNE_H #define UZYWANE_ZMIENNE_H #include <QDialog> #include "dodawanie_zmiennej.h" #include "model_uzywane_zmienne.h" #include "zmienna_w_arduino.h" namespace Ui { class uzywane_zmienne; } class uzywane_zmienne : public QDialog { Q_OBJECT public: explicit uzywane_zmienne(QMap<QString, zmienna_w_arduino> *lista, QWidget *parent = 0); ~uzywane_zmienne(); private slots: void on_nowa_clicked(); void on_usun_clicked(); void edycja_zmiennej(const QModelIndex ModelIndex); private: Ui::uzywane_zmienne *ui; dodawanie_zmiennej* dialog; //okno odpowiedzialne za dodawanie nowych zmiennych QMap<QString, zmienna_w_arduino> *lista_uzywanych_zmiennych; //adres do listy używanych zmiennych model_uzywane_zmienne model; //model danych używany przez listę używanych zmiennych(zrobiony tylko po to, żeby móc ustawić nagłówki kolumn) dodawanie_zmiennej* okno_edycji_zmiennej; }; #endif // UZYWANE_ZMIENNE_H
lnarolski/PLCino
model_drabinka.h
<filename>model_drabinka.h #ifndef MODEL_DRABINKA_H #define MODEL_DRABINKA_H #include <QAbstractTableModel> #include <QList> #include <elementy_drabinki.h> #include <QPixmap> #include <QPainter> class model_drabinka : public QAbstractTableModel { Q_OBJECT public: explicit model_drabinka(QObject *parent = 0, int x = 2, int y = 2); //konstruktor z początkową liczbą kolumn(x) i wierszy(y) int rowCount(const QModelIndex &parent = QModelIndex()) const ; int columnCount(const QModelIndex &parent = QModelIndex()) const; bool insertRow(int row, const QModelIndex & parent = QModelIndex()); bool insertColumn(int column, const QModelIndex & parent = QModelIndex()); bool removeRow(int row, const QModelIndex & parent = QModelIndex()); bool removeColumn(int column, const QModelIndex & parent = QModelIndex()); bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); //reakcja modelu na upuszczenie elementu podczas drag&drop Qt::DropActions supportedDropActions() const; //obługiwane akcje w tabeli związane z drag&drop Qt::ItemFlags flags(const QModelIndex &index) const; //flagi dla każdej komórki w tabeli QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; //sposób prezentacji danych w każdej z komórek int kolumny_temp; //tymczasowa liczba kolumn używana, gdy usuwany jest ostatni wiersz(bo wtedy się bugowało) QList<QList<elementy_drabinki*>*> model_dane; //model danych z obiektami z elementy_drabinki.h w postaci tabeli(lista list) QPixmap generowanie_grafik(elementy_drabinki* element) const; }; #endif // MODEL_DRABINKA_H
HuanDay/XTYMapView
MapView/XTYMapView.h
// // XTYMapView.h // XTYMapView // // Created by Michael on 16/8/21. // Copyright © 2016年 Michael. All rights reserved. // #import <UIKit/UIKit.h> #import <MapKit/Mapkit.h> #import "XTYMapAnnotationItem.h" typedef NSInteger XTYMapAnnIndex; typedef NSInteger XTYMapOverIndex; /************************************************/ @interface CurrentAnnotation : NSObject<MKAnnotation> - (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate; @end /************************************************/ @interface XTYMapView : UIView @property (nonatomic, readonly) MKMapView *mapView; @property (nonatomic, readonly) CurrentAnnotation *currentAnnotation; /** * set annotation item list manually * * @param arr XTYMapAnnotationItem item list */ - (void)setUpAnnotationItemList:(NSArray<XTYMapAnnotationItem *> *)arr; /** * delete annotation item list * * @param arr XTYMapAnnotationItem item list */ - (void)deleteAnnotationItems:(NSArray<XTYMapAnnotationItem *> *)arr; /** * creat new annotation item list and add to MapView * * @param arr XTYMapAnnotationItem item list */ - (void)addAnnotationItems:(NSArray<XTYMapAnnotationItem *> *)arr; /** * delete and add the new item list to annotation * * @param arr the new annotation item list */ - (void)reloadAnnotationItems:(NSArray<XTYMapAnnotationItem *> *)arr; /** * delete all annotation item */ - (void)deleteAllAnnotationItems; /** * get annotation information with index * * @param index the index in annotation item list * * @return annotation information item */ - (id<MKAnnotation>)getAnnotationWithAnnIndex:(XTYMapAnnIndex)index; /** * get overlay information with index * * @param index the index in annotation item list * * @return overlay information item */ - (id<MKOverlay>)getOverlayWithAnnIndex:(XTYMapOverIndex)index; /** * set the annotation view with index selected status * * @param index the index of annotation view */ - (void)selectAnnWithIndex:(XTYMapAnnIndex)index; /** * set the current annotation View selected status * * @param animated with animation or not */ - (void)selectCurrentAnnAnimated:(BOOL)animated; /** * cancle the selected status of current annotation view * * @param animated with animation or not */ - (void)deselectCurrentAnnAnimated:(BOOL)animated; /** * show all annotation view * * @param animated with animation or not */ - (void)showAllAnnotationAnimated:(BOOL)animated; /** * set current annotation information * * @param coordinate CLLocationCoordinate2D lat and lng */ - (void)setCurrentAnn:(CLLocationCoordinate2D)coordinate; /** * change the map center to specified coordinate * * @param coordinate center coordinate */ - (void)changeMapViewCenterWith:(CLLocationCoordinate2D)coordinate; /** * change the map center to specified coordinate * * @param coordinate center coordinate * @param animated set the tranform with animation or not */ - (void)changeMapViewCenterWith:(CLLocationCoordinate2D)coordinate andAnimated:(BOOL)animated; /** * change the map center to specified coordinate and scale to specified span * * @param coordinate center coordinate * @param delta span parameter * @param compel set span automatic or use the specified span * @param animated set the tranform with animation or not */ - (void)changeMapViewCenterWith:(CLLocationCoordinate2D)coordinate andSpan:(CLLocationDegrees)delta andCompel:(BOOL)compel andAnimated:(BOOL)animated; @end
HuanDay/XTYMapView
MapView/CLLocation+XTYAddition.h
<reponame>HuanDay/XTYMapView // // CLLocation+XTYAddition.h // XTYMapView // // Created by Michael on 16/8/21. // Copyright © 2016 Michael. All rights reserved. // #import <CoreLocation/CoreLocation.h> @interface CLLocation (XTYAddition) /** * determine whether lat value is correct * * @param lat -90 =< lat <= 90 * * @return YES or NO */ + (BOOL)isValidLatitude:(double)lat; /** * determine whether lng value is correct * * @param lng -180 =< lng <= 180 * * @return YES or NO */ + (BOOL)isValidLongitude:(double)lng; /** * determine whether ther location value is correct * * @return YES or NO */ - (BOOL)isValidCLLocation; /** * get CLLocation instance through location information * * @param d_lat latitude value * @param d_lng longitude value * * @return CLLocation instance */ + (CLLocation *)validLocationFromLat:(CLLocationDegrees)d_lat lng:(CLLocationDegrees)d_lng; /** * get CLLocation instance through location information with string format * * @param lat latitude value with string format * @param lng longitude value with string format * * @return CLLocation instance */ + (CLLocation *)validLocationFromLatString:(NSString *)lat lngString:(NSString *)lng; /** * format loacation information <N:north,S:South,W:west,E:east> * * @return location information such as: N35.1°,W80° */ - (NSString *)coordinateStringVeryShort; @end
HuanDay/XTYMapView
XTYMapDemo/XTYModel/XTYModelItem.h
<filename>XTYMapDemo/XTYModel/XTYModelItem.h // // XTYModelItem.h // XTYModel // // Created by Michael on 16/8/19. // Copyright © 2016 Michael. All rights reserved. // #import <Foundation/Foundation.h> #import "XTYJson.h" @interface XTYModelItem : NSObject <NSCopying> /** * the raw data properties, readonly. When we parse the properties, the item retains the original data, this data can use to upload to the server or anyother uses. */ @property (nonatomic, readonly) NSDictionary* originDict; @property (nonatomic, readonly) XTYJson *json; /** * init method, the input data is a XTYJson instance, if your original data is a dictionary, just use the XTYJson init method to get a instance with your dictionary. We do not encourage to use original data class, like NSDictionary or NSArray to init item. */ - (instancetype)initWithJson:(XTYJson*)json; - (instancetype)initwithDictionary:(NSDictionary *)dictionary; /** * follow methods use to parse list data structure, they are class method and should be used with subClass */ + (NSArray<__kindof XTYModelItem *> *)arrayWithArrayDictionary:(NSArray<NSDictionary *>*)arrayDict; + (NSMutableArray<__kindof XTYModelItem *> *)mutableArrayWithArrayDictionary:(NSArray<NSDictionary *>*)arrayDict; #pragma mark - config methods,rewrite them in the subClass if you need /** * the map between json key and property key <NSString* -> NSString*>, if the key return from the server is not same as the property name, you can rewrite this method to make the properties parse correctly */ + (NSDictionary *)JSONKeyMapForProperties; /** * returen a dictionary, if the property is kind of NSArray instance or inherite from it, the key is the property name<NSString *>, the value is the Class <like [NSString class]> */ + (NSDictionary *)elementClassMapForNSArrayProperties; /** * rewrite this method to set a list which includes the properties you do not want to parse */ + (NSArray *)ignoredProperties; /** parse method*/ - (void)parseProperties; - (void)rebuildJsonFromProperties; @end
HuanDay/XTYMapView
XTYMapDemo/XTYMapDemo/ViewController.h
// // ViewController.h // XTYMapDemo // // Created by Michael on 16/8/27. // Copyright © 2016年 Michael. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
HuanDay/XTYMapView
XTYMapDemo/XTYScrollView/XTYCycleCollectionViewCell.h
// // XTYCycleCollectionViewCell.h // XTYCycleScrollView // // Created by Mr.Sunday on 16/8/13. // Copyright © 2016年 Sunday. All rights reserved. // #import <UIKit/UIKit.h> @interface XTYCycleCollectionViewCell : UICollectionViewCell @property (nonatomic, strong) UIView *view; @property (nonatomic, weak) UIImageView *imgView; @property (nonatomic, strong) UIImage *bgImage; @property (nonatomic, strong) UIImage *shadowImage; @property (nonatomic, copy) NSString *title; @property (nonatomic, strong) UIColor *titleLabelTextColor; @property (nonatomic, strong) UIFont *titleLabelTextFont; @property (nonatomic, strong) UIColor *titleLabelBackgroundColor; @property (nonatomic, assign) CGFloat titleLabelHeight; @property (nonatomic, assign) BOOL hasConfigured; - (void)setImageView:(id)imageSource; @end
HuanDay/XTYMapView
XTYMapDemo/XTYMapDemo/DemoAnnotationView.h
<gh_stars>1-10 // // DemoAnnotationView.h // XTYMapViewDemo // // Created by Michael on 16/8/27. // Copyright © 2016年 Michael. All rights reserved. // #import <MapKit/MapKit.h> #import "DemoAnnotationItem.h" @interface DemoAnnotation : NSObject<MKAnnotation> @property (nonatomic, strong) DemoAnnotationItem *info; @end @interface DemoAnnotationView : MKAnnotationView @end
HuanDay/XTYMapView
MapView/XTYCoordinateItem.h
// // XTYCoordinateItem.h // XTYMapView // // Created by Michael on 16/8/21. // Copyright © 2016年 Michael. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> /*************** coordinate item *****************/ @interface XTYCoordinateItem : NSObject @property (nonatomic, assign) CLLocationDegrees lat; @property (nonatomic, assign) CLLocationDegrees lng; @end /*************** list item *****************/ @interface XTYCoordinateListItem : NSObject @property (nonatomic, strong) NSArray<XTYCoordinateItem *> * itemList; @end
HuanDay/XTYMapView
XTYMapDemo/XTYMapDemo/DemoAnnotationItem.h
<gh_stars>1-10 // // DemoAnnotationItem.h // XTYMapViewDemo // // Created by Michael on 16/8/27. // Copyright © 2016年 Michael. All rights reserved. // #import "XTYModelItem.h" #import <CoreLocation/CoreLocation.h> @interface DemoAnnotationItem : XTYModelItem @property (nonatomic, strong) NSString *title; @property (nonatomic, strong) NSString *imageName; @property (nonatomic, assign) CLLocationDegrees lat; @property (nonatomic, assign) CLLocationDegrees lng; @end
HuanDay/XTYMapView
XTYMapDemo/XTYModel/XTYJson.h
// // XTYJson.h // XTYModel // // Created by Michael on 16/8/19. // Copyright © 2016 Michael. All rights reserved. // #import <Foundation/Foundation.h> @interface XTYJson : NSObject <NSCopying> /** jsonObj is NSDictionary or NSArray*/ @property(nonatomic, readonly) id jsonObj; /** * init method */ - (instancetype)initWithObject:(id)object; + (XTYJson *)jsonWithObject:(id)obj; + (XTYJson *)jsonWithData:(NSData*)jsonData; + (XTYJson *)jsonWithString:(NSString*)jsonStr; /** * return json raw string */ - (NSString*)stringJson; /** * count of jsonObj */ - (NSUInteger)count; /** * return NSDictionary or NSArray */ - (instancetype)jsonObj; - (void)setJsonObject:(id)jsonObj; /** * search wether exist value at key */ - (BOOL)hasValueForKey:(NSString*)key; - (BOOL)hasValueAtIndex:(NSUInteger)index; /** * get json value with key */ - (XTYJson*)jsonForKey:(NSString*)key; - (instancetype)originValueForKey:(NSString *)key; /** * get json value with index */ - (XTYJson*)jsonAtIndex:(NSUInteger)index; /** * return string value for key */ - (NSString*)stringValueForKey:(NSString*)key; /** * if jsonObj does't contain the key or the value of the key is NSNull, return the default Sring */ - (NSString*)stringValueForKey:(NSString*)key defaultValue:(NSString*)defaultStr; /** * return NSInteger value for key */ - (NSInteger)integerValueForKey:(NSString*)key; /** * if jsonObj does't contain the key or the value of the key is NSNull, return the default int value */ - (NSInteger)integerValueForKey:(NSString*)key defaultValue:(NSInteger)defaultInt; /** * other getter method of base data type with key or index */ - (int)intValueForKey:(NSString *)key; - (int)intValueForKey:(NSString *)key defaultValue:(int)defaultInt; - (char)charValueForKey:(NSString*)key; - (NSInteger)charValueForKey:(NSString*)key defaultValue:(int)defaultChar; - (char)charValueAtIndex:(NSUInteger)index; - (char)charValueAtIndex:(NSUInteger)index defaultValue:(char)defaultChar; - (long)longValueForKey:(NSString*)key; - (long)longValueForKey:(NSString*)key defaultValue:(long)defaultLong; - (long long)longlongValueForKey:(NSString*)key; - (long long)longlongValueForKey:(NSString*)key defaultValue:(long long)defaultLonglong; - (double)doubleValueForKey:(NSString*)key; - (double)doubleValueForKey:(NSString*)key defaultValue:(double)defaultDouble; - (float)floatValueForKey:(NSString*)key; - (float)floatValueForKey:(NSString*)key defaultValue:(float)defaultFloat; - (BOOL)booleanValueForKey:(NSString*)key; - (BOOL)booleanValueForKey:(NSString*)key defaultValue:(BOOL)defaultBoolean; - (id)originValueAtIndex:(NSUInteger)index; - (NSString*)stringValueAtIndex:(NSUInteger)index; - (NSString*)stringValueAtIndex:(NSUInteger)index defaultValue:(NSString*)defaultStr; - (NSInteger)integerValueAtIndex:(NSUInteger)index; - (NSInteger)integerValueAtIndex:(NSUInteger)index defaultValue:(NSInteger)defaultInt; - (int)intValueAtIndex:(NSUInteger)index; - (int)intValueAtIndex:(NSUInteger)index defaultValue:(int)defaultInt; - (long)longValueAtIndex:(NSUInteger)index; - (long)longValueAtIndex:(NSUInteger)index defaultValue:(long)defaultLong; - (long long)longlongValueAtIndex:(NSUInteger)index; - (long long)longlongValueAtIndex:(NSUInteger)index defaultValue:(long long)defaultLonglong; - (double)doubleValueAtIndex:(NSUInteger)index; - (double)doubleValueAtIndex:(NSUInteger)index defaultValue:(double)defaultDouble; - (float)floatValueAtIndex:(NSUInteger)index; - (float)floatValueAtIndex:(NSUInteger)index defaultValue:(float)defaultFloat; @end
HuanDay/XTYMapView
MapView/XTYMapAnnotationItem.h
// // XTYMapAnnotationItem.h // XTYMapView // // Created by Michael on 16/8/21. // Copyright © 2016年 Michael. All rights reserved. // #import <Foundation/Foundation.h> typedef void(^FinishLoadAnnotationViewCallback)(id annotationView); typedef void(^DidSelectCallback)(id annotationView); typedef void(^DidDeselectCallback)(id annotationView); typedef void(^WillAddInMapViewCallback)(id annotationView,id annotation); @protocol XTYMapAnnotationItemProtocol <NSObject> - (void)setInfo:(id)info; - (void)setIndex:(NSInteger)index; @end @interface XTYMapAnnotationItem : NSObject @property (nonatomic, strong) Class annotationViewClass; @property (nonatomic, strong) Class annotationClass; @property (nonatomic, strong) NSString *reusableIdentifier; @property (nonatomic, copy) DidSelectCallback didSelectCallback; @property (nonatomic, copy) DidDeselectCallback didDeselectCallback; @property (nonatomic, copy) FinishLoadAnnotationViewCallback loadCallback; @property (nonatomic, copy) WillAddInMapViewCallback willAddInMapViewCallback; @property (nonatomic, strong) id annotationInfo; @property (nonatomic, assign) BOOL isOverlay; @property (nonatomic, assign) NSInteger index; @end
HuanDay/XTYMapView
XTYMapDemo/XTYScrollView/XTYCycleScrollView.h
<reponame>HuanDay/XTYMapView // // XTYCycleScrollView.h // XTYCycleScrollView // // Created by Mr.Sunday on 16/8/13. // Copyright © 2016年 Sunday. All rights reserved. // #import <UIKit/UIKit.h> #pragma mark - stype ENUM typedef NS_ENUM(NSInteger,XTYCycleScrollViewPageContolAliment) { XTYCycleScrollViewPageContolAlimentRight, XTYCycleScrollViewPageContolAlimentCenter }; typedef NS_ENUM(NSInteger,XTYCycleScrollViewPageContolStyle) { XTYCycleScrollViewPageContolStyleClassic, // system default style XTYCycleScrollViewPageContolStyleAnimated, // animation pagecontrol XTYCycleScrollViewPageContolStyleNone // do not show pagecontrol }; #pragma mark - select protocol @class XTYCycleScrollView; @protocol XTYCycleScrollViewDelegate <NSObject> @optional /** * tells the delegate the view scroll to the specific index * * @param cycleScrollView the scroll view * @param index next index */ - (void)cycleScrollView:(XTYCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index; /** * tells the delegate the item at specific index was selected * * @param cycleScrollView the scroll view * @param index the index of selected view */ - (void)cycleScrollView:(XTYCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index; @end #pragma mark - scrollView class @interface XTYCycleScrollView : UIView /** * init method with config parameters * * @param frame scroll view frame * @param target delegate target * @param dotColor page control dot color * @param infiniteLoop whether infinite loop automaitically * * @return scroll View instance */ - (instancetype)initWithFrame:(CGRect)frame target:(id)target dotColor:(UIColor *)dotColor infiniteLoop:(BOOL)infiniteLoop; #pragma mark - data source /** * config method with data source * * @param itemList element of item list can be image url<string>, image<UIImage> or view<UIView> */ - (void)configScrollViewWithItemList:(NSArray *)itemList; /** properties which can config*/ @property (nonatomic, readonly) UIScrollView *scrollView; /** local images data list*/ @property (nonatomic, strong) NSArray<NSString *> *localImagesGroup; /** web image data list*/ @property (nonatomic, strong) NSArray<NSString *> *imageURLStringsGroup; /** title for each image data list*/ @property (nonatomic, strong) NSArray<NSString *> *titlesGroup; /** views list*/ @property (nonatomic, strong) NSArray<UIView *> *viewsGroup; #pragma mark - scroll control properties /** croll time interval, default 2s*/ @property (nonatomic, assign) CGFloat autoScrollTimeInterval; /** can infinite loop, default Yes*/ @property(nonatomic,assign) BOOL infiniteLoop; /** automatic scroll, default Yes*/ @property(nonatomic,assign) BOOL autoScroll; /** the delegate of touch inside event*/ @property (nonatomic, weak) id<XTYCycleScrollViewDelegate> delegate; #pragma mark - customize style /** show the pageControl, default Yes*/ @property (nonatomic, assign) BOOL showPageControl; /** if only one page, hiden pageControl, default Yes*/ @property (nonatomic, assign) BOOL hidesForSinglePage; /** pagecontrol style,default XTYCycleScrollViewPageContolStyleAnimated*/ @property (nonatomic, assign) XTYCycleScrollViewPageContolStyle pageControlStyle; /** placeholder image*/ @property (nonatomic, strong) UIImage *placeholderImage; /** the shadow image*/ @property (nonatomic, strong) UIImage *shadowImage; /** the aliment of pageControl*/ @property (nonatomic, assign) XTYCycleScrollViewPageContolAliment pageControlAliment; /** pageControl frame, use center to ajust it's frame*/ @property (nonatomic, assign) CGPoint pageControlCenter; /** the dot size of pageControl*/ @property (nonatomic, assign) CGSize pageControlDotSize; /** the color of pageControl dot*/ @property (nonatomic, strong) UIColor *dotColor; /** the highlight color of pageContril dot*/ @property (nonatomic, strong) UIColor *dotHightlightColor; /** the image of dot*/ @property (nonatomic, strong) UIImage *dotImage; /** the highlight image of dot*/ @property (nonatomic, strong) UIImage *dotHightLightImage; /** the properties of title Label*/ @property (nonatomic, strong) UIColor *titleLabelTextColor; @property (nonatomic, strong) UIFont *titleLabelTextFont; @property (nonatomic, strong) UIColor *titleLabelBackgroundColor; @property (nonatomic, assign) CGFloat titleLabelHeight; /** scroll deriction vertical or horizontal*/ @property (nonatomic, assign) UICollectionViewScrollDirection scrollDirection; /** class method to init instance*/ + (instancetype)cycleScrollViewWithFrame:(CGRect)frame; /** * init instance * * @param frame scroll view frame * @param imagesGroup image list @[(UIImage),...] * * @return scroll view instance */ + (instancetype)cycleScrollViewWithFrame:(CGRect)frame imagesGroup:(NSArray<UIImage *> *)imagesGroup; /** * init instance * * @param frame <#frame description#> * @param imageURLStringsGroup <#imageURLStringsGroup description#> * * @return <#return value description#> */ + (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageURLStringsGroup:(NSArray<NSString *> *)imageURLStringsGroup; @end
dmitry42nd/trikRuntime
trikControl/src/eventDevice.h
<reponame>dmitry42nd/trikRuntime<gh_stars>0 /* Copyright 2016 CyberTech Labs 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. */ #pragma once #include <QtCore/QSharedPointer> #include "eventDeviceInterface.h" #include "deviceState.h" namespace trikHal { class HardwareAbstractionInterface; } namespace trikControl { class EventDeviceWorker; /// Implementation of generic event device that uses HAL device file to provide events. class EventDevice : public EventDeviceInterface { Q_OBJECT public: /// Constructor. /// @param eventFile - path to event file that this object needs to watch. /// @param hardwareAbstraction - interface to underlying hardware or operating system capabilities of a robot. EventDevice(const QString &eventFile, const trikHal::HardwareAbstractionInterface &hardwareAbstraction); ~EventDevice() override; EventInterface *onEvent(int eventType) override; Status status() const override; private: /// Actual implementation of event device watcher in separate thread (in case there are too many events). QScopedPointer<EventDeviceWorker> mWorker; /// Thread for event file watcher. QThread mWorkerThread; /// State of event device. DeviceState mState; /// A storage for created event objects. They will listen to the events from the moment of first reference /// until event device is shut down. QHash<int, QSharedPointer<EventInterface>> mEvents; }; }
dmitry42nd/trikRuntime
trikControl/src/audioSynthDevices.h
<gh_stars>0 /* Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QtCore/QByteArray> #include <QtCore/QIODevice> #include <QtMultimedia/QAudioFormat> /// QIODevice that synthesize sine wave values class AudioSynthDevice : public QIODevice { Q_OBJECT public: /// Constructor AudioSynthDevice(QObject *parent, int sampleRate, int sampleSize); ~AudioSynthDevice(); /// Provides reading from device qint64 readData(char *data, qint64 maxlen); /// Opens device, run generation in buffered mode void start(int hzFreq); /// Close device and reset pose void stop(); /// Stub, because readonly device qint64 writeData(const char *data, qint64 len); /// Returns amount of available bytes qint64 bytesAvailable() const; private: /// Sythesize sine wave values int generate(char *data, int length, int hzFreq); private: /// Internal buffer, used in buffered mode QByteArray mBuffer; qint64 mPos; int mHzFreq; const int mSampleRate; const int mSampleSize; /// Mode of device bool mBuffered = false; /// New call of playTone(...), not readData(...) call bool newCall = true; };
dmitry42nd/trikRuntime
trikControl/src/vectorSensorWorker.h
/* Copyright 2014 - 2015 CyberTech Labs 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. */ #pragma once #include <QtCore/QObject> #include <QtCore/QScopedPointer> #include <QtCore/QVector> #include <QtCore/QTimer> #include <QtCore/QReadWriteLock> #include <trikHal/hardwareAbstractionInterface.h> #include "deviceState.h" namespace trikKernel { class TimeVal; } namespace trikControl { /// Handles events from sensor, intended to work in separate thread. class VectorSensorWorker : public QObject { Q_OBJECT public: /// Constructor. /// @param eventFile - device file for this sensor. /// @param state - state of a device. /// @param thread - background thread where all socket events will be processed. VectorSensorWorker(const QString &eventFile, DeviceState &state , const trikHal::HardwareAbstractionInterface &hardwareAbstraction , QThread &thread); signals: /// Emitted when new sensor reading is ready. void newData(QVector<int> reading, const trikKernel::TimeVal &eventTime); public slots: /// Returns current raw reading of a sensor. QVector<int> read(); /// Shuts down sensor. void deinitialize(); private slots: /// Updates current reading when new value is ready in event file. void onNewEvent(int eventType, int code, int value, const trikKernel::TimeVal &eventTime); /// Called when there are no events from event file for too long (1 second hardcoded). Attempts to reopen /// event file. void onSensorHanged(); /// Called when timeout for another try to reestablish connection with a device is expired. Tries to reopen /// event file. void onTryReopen(); private: /// Event file for that sensor. QScopedPointer<trikHal::EventFileInterface> mEventFile; /// Current reading that will be returned on read() call. QVector<int> mReading; /// Current partial reading, will be copied to mReading on SYNC signal. QVector<int> mReadingUnsynced; /// Device state, shared between worker and proxy. DeviceState &mState; /// Timer that reopens event file when there are no events for too long (1 second hardcoded). QTimer mLastEventTimer; /// Timer that initiates attempts to reopen device file if there is a hangup. QTimer mTryReopenTimer; }; }
dmitry42nd/trikRuntime
trikGui/batteryIndicator.h
/* Copyright 2014 CyberTech Labs 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. */ #pragma once #include <QtCore/qglobal.h> #include <QtCore/QTimer> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QLabel> #else #include <QtWidgets/QLabel> #endif #include <trikControl/brickInterface.h> namespace trikGui { /// Label showing battery voltage. class BatteryIndicator : public QLabel { Q_OBJECT public: /// Constructor. /// @param brick - object that provides interface to a hardware. /// @param parent - parent of this widget in terms of Qt parent-child widget relations. explicit BatteryIndicator(trikControl::BrickInterface &brick, QWidget *parent = 0); private slots: void renew(); private: trikControl::BrickInterface &mBrick; QTimer mRenewTimer; const int mRenewInterval = 60*1000; const float mWarningThreshold = 11.2; const float mShutdownThreshold = 10.5; const float mSanityThreshold = 1.0; }; }
dmitry42nd/trikRuntime
trikNetwork/src/gamepadConnection.h
<filename>trikNetwork/src/gamepadConnection.h /* Copyright 2015 CyberTech Labs 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. */ #pragma once #include "connection.h" namespace trikNetwork { /// Connection object for android gamepad. class GamepadConnection : public Connection { Q_OBJECT public: GamepadConnection(); signals: /// Emitted when user pulls finger off a pad. /// @param pad - id of a pad on which the event occurs. void padUp(int pad); /// Emitted when user tilts his Android device with "wheel" turned on. /// @param percent - percent of a tilt angle. void wheel(int percent); /// Emitted when user pushes or moves his finger on a pad. /// @param pad - id of a pad on which the event occurs. /// @param x - x coordinate of an event. /// @param y - y coordinate of an event. void pad(int pad, int x, int y); /// Emitted when user pushes a button on gamepad. /// @param button - button number. /// @param pressed - 1 if button was pressed, 0 if it was released. void button(int button, int pressed); private: void processData(const QByteArray &data) override; }; }
dmitry42nd/trikRuntime
trikControl/src/exceptions/incorrectStateChangeException.h
<reponame>dmitry42nd/trikRuntime /* Copyright 2015 CyberTech Labs 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. */ #pragma once #include <trikKernel/exceptions/trikRuntimeException.h> #include "deviceInterface.h" #include <QsLog.h> namespace trikControl { /// Exception for incorrect device state change, for example, from "off" to "stopping". class IncorrectStateChangeException : public trikKernel::TrikRuntimeException { public: /// Constructor. /// @param deviceName - name of the device. /// @param from - status from which we tried to change. /// @param to - status to which we tried to change. IncorrectStateChangeException(const QString &deviceName, DeviceInterface::Status from, DeviceInterface::Status to) { QLOG_ERROR() << deviceName << QString(": incorrect device state change from \"%1\" to \"%2\"") .arg(statusToString(from)).arg(statusToString(to)); } /// Constructor, used to report incorrect resetting of failure state. /// @param deviceName - name of the device. /// @param from - status from which we tried to change. IncorrectStateChangeException(const QString &deviceName, DeviceInterface::Status from) { QLOG_ERROR() << deviceName << QString(": incorrect attempt to reset failure from \"%1\"") .arg(statusToString(from)); } private: /// Helper method to convert status enum value to string. static QString statusToString(DeviceInterface::Status status) { switch (status) { case DeviceInterface::Status::failure: return "failure"; case DeviceInterface::Status::off: return "off"; case DeviceInterface::Status::ready: return "ready"; case DeviceInterface::Status::starting: return "starting"; case DeviceInterface::Status::stopping: return "stopping"; } return ""; } }; }
dmitry42nd/trikRuntime
trikNetwork/include/trikNetwork/gamepadFactory.h
/* Copyright 2015 CyberTech Labs 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. */ #pragma once #include <QtCore/QThread> #include <QtCore/QString> #include "declSpec.h" namespace trikKernel { class Configurer; } namespace trikNetwork { class GamepadInterface; /// Factory that creates real gamepad receiver object. class TRIKNETWORK_EXPORT GamepadFactory { public: /// Method that creates gamepad object. /// Transfers ownership over GamepadInterface object to caller. /// @param port - TCP port of a gamepad server. static GamepadInterface *create(int port); /// Method that creates gamepad object. /// Transfers ownership over GamepadInterface object to caller. /// @param configurer - configurer object that contains preparsed XML config. If gamepad is not enabled, nullptr /// will be returned. static GamepadInterface *create(const trikKernel::Configurer &configurer); }; }
dmitry42nd/trikRuntime
trikGui/controller.h
/* Copyright 2013 - 2015 <NAME> and CyberTech Labs 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. */ #pragma once #include <trikCommunicator/trikCommunicator.h> #include <trikControl/brickInterface.h> #include <trikNetwork/gamepadInterface.h> #include <trikNetwork/mailboxInterface.h> #include <trikScriptRunner/trikScriptRunner.h> #include <trikTelemetry/trikTelemetry.h> #include "lazyMainWidget.h" namespace trikWiFi { class TrikWiFi; } namespace trikGui { class RunningWidget; class AutoRunner; /// Provides backend features like Qt Script runner for frontend. class Controller : public QObject { Q_OBJECT public: /// Constructor. /// @param configPath - path to config file for trikControl, for example, /home/root/trik/. explicit Controller(const QString &configPath); ~Controller() override; /// Executes specified file as Qt Script, if it has .qts extension, or as a program otherwise. void runFile(const QString &filePath); /// Executes given script. void runScript(const QString &script); /// Returns reference to Brick object, which provides access to robot hardware. trikControl::BrickInterface &brick(); /// Returns reference to Mailbox object, which provides access to robot-to-robot communications. /// Does not pass ownership to the caller. trikNetwork::MailboxInterface *mailbox(); /// Reference to WiFi manager. trikWiFi::TrikWiFi &wiFi(); /// Asks controller to correctly close given running widget. void doCloseRunningWidget(MainWidget &widget); /// Returns communicator connection status (whether or not both Telemetry and Communicator servers are connected). bool communicatorConnectionStatus(); /// Returns gamepad connection status. bool gamepadConnectionStatus() const; public slots: /// Cancels execution of current program. void abortExecution(); signals: /// Emitted when a new script starts and therefore a running widget must be shown with the script's name. void showRunningWidget(const QString &fileName, int scriptId); /// Emitted when running widget for a script with a given id must be closed. void hideRunningWidget(int scriptId); /// Emitted when a script stops due to an error. void showError(const QString &error, int scriptId); /// Emitted when a graphics widget must be closed. void hideGraphicsWidget(); /// Emitted when both graphics and running widget must be closed. void hideScriptWidgets(); /// Emitted when brick has finished deferred deinitialization so we need to refresh display to clear possible /// clutter from videosensors. void brickStopped(); /// Emitted when a robot is disconnected from a gamepad. void gamepadDisconnected(); /// Emitted when a robot is connected to a gamepad. void gamepadConnected(); /// Emitted when a robot is connected to a network. void wiFiConnected(); /// Emitted when a robot is disconnected from a network. void wiFiDisconnected(); /// Emitted when Telemetry and Communicator servers' status changes. /// @param status - true if both servers are connected. void communicatorStatusChanged(bool status); /// Emitted when Mailbox server's status changes. void mailboxStatusChanged(bool connected); private slots: void scriptExecutionCompleted(const QString &error, int scriptId); void scriptExecutionFromFileStarted(const QString &fileName, int scriptId); void directScriptExecutionStarted(int scriptId); void updateCommunicatorStatus(); private: QScopedPointer<trikControl::BrickInterface> mBrick; QScopedPointer<trikNetwork::GamepadInterface> mGamepad; QScopedPointer<trikNetwork::MailboxInterface> mMailbox; QScopedPointer<trikScriptRunner::TrikScriptRunner> mScriptRunner; QScopedPointer<trikCommunicator::TrikCommunicator> mCommunicator; QScopedPointer<trikTelemetry::TrikTelemetry> mTelemetry; QScopedPointer<trikWiFi::TrikWiFi> mWiFi; QScopedPointer<AutoRunner> mAutoRunner; QHash<int, RunningWidget *> mRunningWidgets; // Has ownership. }; }
dmitry42nd/trikRuntime
trikKernel/include/trikKernel/timeVal.h
/* Copyright 2015 - 2016 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once namespace trikKernel { /// Structure of a time value in a convenient format. class TimeVal { public: /// Constructor. TimeVal() = default; /// Copy constructor. /// @param timeVal - an object, a copy of which is created. TimeVal(const TimeVal &timeVal); /// Constructor. Parameters represent time in the format - (sec * 10^6 + mcsec) msces. /// Constructor translates this value to the new format - 1 unit of a new value(mTime) is equal to 256 mcsec. /// Note that after these conversions value in microseconds becomes rounded, but we can neglect this fact /// in most cases. /// Formula for translation : mTime = (sec * 10^6 + mcsec) << 8 = sec * 10^6 << mShift + mcsec << mShift = /// = sec * mSecConst << (mShift - 6) + mcsec << mShift TimeVal(int sec, int mcsec); /// Translates an interior format to mcsec. int toMcSec() const; /// Overloaded "minus" operator. /// @param left - a value before sign. /// @param right - a value after sign. friend const TimeVal operator-(const TimeVal &left, const TimeVal &right); /// Overloaded "is equal" operator. /// @param timeVal - a value, which is assigned to a variable. TimeVal &operator=(const TimeVal &timeVal); private: int mTime = 0; static const int mSecConst = 15625; static const int mShift = 8; }; /// Overloaded "minus" operator. /// @param left - a value before sign. /// @param right - a value after sign. inline const TimeVal operator-(const TimeVal &left, const TimeVal &right) { TimeVal deltaTime; deltaTime.mTime = left.mTime - right.mTime; return deltaTime; } }
dmitry42nd/trikRuntime
trikNetwork/src/gamepad.h
<gh_stars>0 /* Copyright 2013 - 2015 <NAME>, <NAME> and CyberTech Labs 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. */ #pragma once #include <QtCore/QScopedPointer> #include <QtCore/QThread> #include <QtCore/QHash> #include <QtCore/QSet> #include <QtCore/QTimer> #include <trikKernel/configurer.h> #include "include/trikNetwork/gamepadInterface.h" namespace trikNetwork { class GamepadServer; /// Implementation of remote control interface. class Gamepad : public GamepadInterface { Q_OBJECT public: /// Constructor. /// @param port - TCP port of a gamepad server. Gamepad(int port); /// Constructor. /// @param configurer - configurer object that contains preparsed XML config. Gamepad(const trikKernel::Configurer &configurer); /// Destructor declared here for QScopedPointer to be able to clean up forward-declared TcpConnector. ~Gamepad() override; public slots: void reset() override; bool buttonWasPressed(int buttonNumber) override; bool buttonIsPressed(int buttonNumber) override; bool isPadPressed(int pad) const override; int padX(int pad) const override; int padY(int pad) const override; int wheel() const override; bool isConnected() const override; private slots: void onPadUp(int padId); void onWheel(int percent); void onPad(int padId, int x, int y); void onButton(int button, int pressed); void onButtonStateClearTimerTimeout(); private: Q_DISABLE_COPY(Gamepad) /// Does object initialization. void init(int port); struct PadStatus { int x; int y; bool isPressed; }; QSet<int> mButtonWasPressed; QHash<int, bool> mButtonState; /// Hack for the fact that gamepad does not send button press events, only releases. We count button as "pressed" /// if it was released within 500 milliseconds from this moment. So actually button becomes "pressed" when it is /// released and stays pressed for 500 milliseconds. QHash<int, QTimer *> mButtonStateClearTimers; QHash<int, PadStatus> mPads; int mWheelPercent = -101; /// Server that works in separate thread. QScopedPointer<GamepadServer> mWorker; /// Worker thread. QThread mWorkerThread; }; }
dmitry42nd/trikRuntime
trikGui/motorLever.h
/* Copyright 2014 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <QtCore/qglobal.h> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QWidget> #include <QtGui/QHBoxLayout> #include <QtGui/QLabel> #include <QtGui/QProgressBar> #else #include <QtWidgets/QWidget> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QProgressBar> #endif #include <QtCore/QString> namespace trikControl { class MotorInterface; } namespace trikGui { /// Widget that allows to set power value of a motor and turn it on and off. /// It is designed to use as a part of MotorsWidget. class MotorLever : public QWidget { Q_OBJECT public: /// Constructor. /// @param port - name of a port which the motor is connected to. /// @param motor - pointer to an instance representing the motor. /// @param parent - pointer to a parent widget. MotorLever(const QString &port, trikControl::MotorInterface &motor, QWidget *parent = 0); /// Destructor. ~MotorLever() override; protected: void keyPressEvent(QKeyEvent *event) override; void paintEvent(QPaintEvent *) override; private: void setPower(int power); void turnOnOff(); trikControl::MotorInterface &mMotor; bool mIsOn; const int mMaxPower; const int mMinPower; const int mPowerStep; int mPower; QHBoxLayout mLayout; QLabel mNameLabel; QProgressBar mPowerBar; QLabel mOnOffLabel; }; }
dmitry42nd/trikRuntime
trikNetwork/src/gamepadServer.h
<gh_stars>0 /* Copyright 2015 CyberTech Labs 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. */ #pragma once #include <QtCore/QObject> #include <QtCore/QMultiHash> #include <QtCore/QReadWriteLock> #include <QtCore/QQueue> #include <QtNetwork/QHostAddress> #include "trikServer.h" namespace trikNetwork { /// Worker object for android gamepad. It is a server that is supposed to be run in a separate thread. class GamepadServer : public TrikServer { Q_OBJECT public: /// Constructor. /// @param port - a port for gamepad server. GamepadServer(); signals: /// Emitted when user pulls finger off a pad. /// @param pad - id of a pad on which the event occurs. void padUp(int pad); /// Emitted when user tilts his Android device with "wheel" turned on. /// @param percent - percent of a tilt angle. void wheel(int percent); /// Emitted when user pushes or moves his finger on a pad. /// @param pad - id of a pad on which the event occurs. /// @param x - x coordinate of an event. /// @param y - y coordinate of an event. void pad(int pad, int x, int y); /// Emitted when user pushes a button on gamepad. /// @param button - button number. /// @param pressed - 1 if button was pressed, 0 if it was released. void button(int button, int pressed); /// Emitted when gamepad disconnect from robot. If there are several gamepads connected simultaneously, signal is /// emitted when all gamepads become disconnected. void disconnect(); private slots: void onGamepadConnectionClosed(); private: Connection *connectionFactory(); }; }
dmitry42nd/trikRuntime
trikCommunicator/include/trikCommunicator/trikCommunicator.h
/* Copyright 2013 - 2015 <NAME>, CyberTech Labs 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. */ #pragma once #include <QtCore/QString> #include <QtCore/QScopedPointer> #include <trikKernel/differentOwnerPointer.h> #include <trikNetwork/trikServer.h> namespace trikScriptRunner { class TrikScriptRunner; } namespace trikControl { class BrickInterface; } namespace trikNetwork { class MailboxInterface; class GamepadInterface; } namespace trikCommunicator { class Connection; /// Class that enables connection with a client running on computer (TRIKStudio or remote control). /// Communication subsystem consists of TrikCommunicator object which runs in main thread and listens for incoming /// connections, Connection objects --- one for every connected client, they run in separate threads each, and /// ScriptRunnerWrapper object in main thread which processes signals from Connections. class TrikCommunicator : public trikNetwork::TrikServer { Q_OBJECT public: /// Constructor that creates its own instance of a script runner. /// @param brick - reference to robot brick. /// @param mailbox - mailbox object used to communicate with other robots. /// @param gamepad - gamepad object used to interact with TRIK Gamepad on Android device. /// @param startDirPath - path to the directory from which the application was executed. TrikCommunicator(trikControl::BrickInterface &brick , trikNetwork::MailboxInterface * const mailbox , trikNetwork::GamepadInterface * const gamepad ); /// Constructor that accepts external script runner and issues commands to it. /// @param runner - script runner that shall be used to execute commands. /// @param configVersion - version of system config file that can be used to check that client and runtime configs /// match. explicit TrikCommunicator(trikScriptRunner::TrikScriptRunner &runner, const QString &configVersion); ~TrikCommunicator() override; public slots: /// Broadcasts given text as a message to be printed. void sendPrintMessage(const QString &text); signals: /// Emitted when stop command received from a computer. void stopCommandReceived(); private: TrikCommunicator(const trikKernel::DifferentOwnerPointer<trikScriptRunner::TrikScriptRunner> &runner , const QString &configVersion); Connection *connectionFactory(); /// Script runner object common to all connections. trikKernel::DifferentOwnerPointer<trikScriptRunner::TrikScriptRunner> mTrikScriptRunner; /// Version of system configuration file. Must correspond to casing model, used to allow clients to check that /// their expectations of configuration match actual one. const QString mConfigVersion; }; }
dmitry42nd/trikRuntime
trikControl/src/shapes/rectangle.h
<reponame>dmitry42nd/trikRuntime<gh_stars>0 /* Copyright 2015 CyberTech Labs 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. */ #pragma once #include "shape.h" namespace trikControl { /// Presents a rectangle to draw on display. class Rectangle : public Shape { public: /// Rectangle defined by top left corner (x,y), width and height. Rectangle(int x, int y, int width, int height, QColor color, int penWidth); void draw(QPainter *painter) override; bool equals(const Shape *other) const override; private: QRect mRect; }; }
ben-mkiv/unreal-sqlite3
Source/CISQLite3/Public/SQLiteDatabase.h
<filename>Source/CISQLite3/Public/SQLiteDatabase.h<gh_stars>0 #pragma once #include "sqlite3.h" #include "SQLiteBlueprintNodes.h" #include "SQLiteDatabaseStructs.h" #include "SQLiteDatabase.generated.h" USTRUCT(BlueprintType) struct CISQLITE3_API FSQLiteDatabaseReference { GENERATED_USTRUCT_BODY() /** The database name (not the filename) */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Database Reference") FString DatabaseName; /** The database tables we want to get data from */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Database Reference") TArray<FString> Tables; }; USTRUCT(BlueprintType) struct CISQLITE3_API FSQLiteKeyValuePair { GENERATED_USTRUCT_BODY() /** The database table field name */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Key Value Pair") FString Key; /** The value of the field */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Key Value Pair") FString Value; }; USTRUCT(BlueprintType) struct CISQLITE3_API FSQLiteQueryResultRow { GENERATED_USTRUCT_BODY() /** A list of field name, field value pairs */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Query Result") TArray<FSQLiteKeyValuePair> Fields; }; USTRUCT(BlueprintType) struct CISQLITE3_API FSQLiteQueryResult { GENERATED_USTRUCT_BODY() /** The resulting rows from the query */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Query Result") TArray<FSQLiteQueryResultRow> ResultRows; /** Was the query successful or not */ UPROPERTY(BlueprintReadOnly, Category = "SQLite Query Result") bool Success; /** If the query was unsuccessful a human readable error message will be populated here */ UPROPERTY(BlueprintReadOnly, Category = "SQLite Query Result") FString ErrorMessage; }; // A few things for internal use here. namespace SQLiteResultValueTypes { enum SQLiteResultValType { Integer, Float, Text, UnsupportedValueType }; } // Result field, used as an intermediary when collecting results from // an SQLITE3 query. struct SQLiteResultField { FString StringValue; double DoubleValue; int64 IntValue; FString Name; SQLiteResultValueTypes::SQLiteResultValType Type; FString ToString() { if (Type == SQLiteResultValueTypes::Text) return StringValue; else if (Type == SQLiteResultValueTypes::Integer) return FString::Printf(TEXT("%i"), IntValue); else if (Type == SQLiteResultValueTypes::Float) return FString::Printf(TEXT("%f"), DoubleValue); return StringValue; } }; // Represents a single row in the result. struct SQLiteResultValue { TArray<SQLiteResultField> Fields; }; // The internal result object. struct SQLiteQueryResult { bool Success; FString ErrorMessage; TArray<SQLiteResultValue> Results; }; /** * SQLite main database class. */ UCLASS() class CISQLITE3_API USQLiteDatabase : public UObject { GENERATED_UCLASS_BODY() public: /** Create a sqlite database file if it doesn't exist already. Does nothing if already exists. * Returns false if the file couldn't be created */ UFUNCTION(BlueprintCallable, Category = "SQLite") static bool CreateDatabase(const FString& Filename, bool RelativeToGameContentDirectory); /** Checks if the database is registered, ie. that it can be found in Databases. */ /** Add a database to the list of databases. It will be checked that it's valid (will try to open it) */ UFUNCTION(BlueprintCallable, Category = "SQLite") static bool RegisterDatabase(const FString& Name, const FString& Filename, bool RelativeToGameContentDirectory, bool KeepOpen=false); /** Remove a database from the list of databases. Closes the database in case KeepOpen flag was set during @ref RegisterDatabase */ UFUNCTION(BlueprintCallable, Category = "SQLite") static void UnregisterDatabase(const FString& Name); /** Checks if the database is registered, ie. that it can be found in Databases. */ UFUNCTION(BlueprintCallable, Category = "SQLite") static bool IsDatabaseRegistered(const FString& DatabaseName); /** Get data from the database using a select statement straight into an UObject, ie. populates its properties. */ UFUNCTION(BlueprintCallable, Category = "SQLite", meta = (DisplayName = "Get Data Into Object (manual query)")) static bool GetDataIntoObject(const FString& DatabaseName, const FString& Query, UObject* ObjectToPopulate); /** Blueprint: Gets data from the database using a select statement straight into an UObject, ie. populates its properties. * Note: Does not create a new object. ObjectToPopulate is the reference to the object you want to populate. */ UFUNCTION(BlueprintCallable, Category = "SQLite", meta = (DisplayName = "Get Data Into Object")) static bool GetDataIntoObjectBP(const FSQLiteDatabaseReference& DataSource, TArray<FString> Fields, FSQLiteQueryFinalizedQuery Query, UObject* ObjectToPopulate); /** Get data from the database using a select statement and return the rows. */ UFUNCTION(BlueprintCallable, Category = "SQLite", meta = (DisplayName = "Get Data From Table(s) (manual query)")) static FSQLiteQueryResult GetData(const FString& DatabaseName, const FString& Query); /** Blueprint: Get data from the database. Returns the resulting rows. */ UFUNCTION(BlueprintCallable, Category = "SQLite", meta = (DisplayName = "Get Data From Table(s)")) static FSQLiteQueryResult GetDataBP(const FSQLiteDatabaseReference& DataSource, TArray<FString> Fields, FSQLiteQueryFinalizedQuery Query, int32 MaxResults = -1, int32 ResultOffset = 0); /** Create table in the database. */ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Create Table")) static FSQLiteTable CreateTable(const FString& DatabaseName, const FString& TableName, const TArray<FSQLiteTableField> Fields, const FSQLitePrimaryKey PK); /** Create indexes for table */ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Create Indexes")) static bool CreateIndexes(const FString& DatabaseName, const FString& TableName, const TArray<FSQLiteIndex> Indexes); /** Create index for table */ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Create Index")) static bool CreateIndex(const FString& DatabaseName, const FString& TableName, const FSQLiteIndex Index); /** Drop index*/ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Drop Index")) static bool DropIndex(const FString& DatabaseName, const FString& IndexName); /** Drop Table*/ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Drop Table")) static bool DropTable(const FString& DatabaseName, const FString& TableName); /** Truncate Table*/ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Truncate Table")) static bool TruncateTable(const FString& DatabaseName, const FString& TableName); /** Is table exists?*/ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Is table exists?")) static bool IsTableExists(const FString& DatabaseName, const FString& TableName); /** Insert rows into table */ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Insert Rows Into Table")) static void InsertRowsIntoTable(const FString& DatabaseName, const FString& TableName, TArray<FSQLiteTableRowSimulator> rowsOfFields); /** Compact database*/ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Compact database")) static bool Vacuum(const FString& DatabaseName); /** Execute SQL (can be used for insert statement)*/ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Execute SQL")) static bool ExecSql(const FString& DatabaseName, const FString& Query); /** Checks database validity (if the file exists and/or if it can be opened). */ UFUNCTION(BlueprintCallable, Category = "SQLite|Query", meta = (DisplayName = "Is Valid Database")) static bool IsValidDatabase(const FString& DatabaseFilename, bool TestByOpening); static TArray<uint8> Dump(const FString& DatabaseFilename); static bool Restore(const FString& DatabaseFilename, const TArray<uint8>& data); /** Runs a query and returns fetched rows. */ static TUniquePtr<SQLiteQueryResult> RunQueryAndGetResults(const FString& DatabaseName, const FString& Query); private: /** Tries to open a database. */ static bool CanOpenDatabase(const FString& DatabaseFilename); /** Collects all properties from an UObject and maps them by the property name. */ static TMap<FString, FProperty*> CollectProperties(UObject* SourceObject); /** Constructs an SQL query from the blueprint fed data. */ static FString ConstructQuery(TArray<FString> Tables, TArray<FString> Fields, FSQLiteQueryFinalizedQuery QueryObject, int32 MaxResults = -1, int32 ResultOffset = 0); /** Assigns a result row's fields' values to an UObject, ie. assigns them to the properties that have the same name. */ static void AssignResultsToObjectProperties(const SQLiteResultValue& ResultValue, UObject* ObjectToPopulate); /** @brief Prepare given statement, returns whether to keep the database open */ static bool PrepareStatement(const FString& DatabaseName, const FString& Query, sqlite3** Db, int32** SqlReturnCode, sqlite3_stmt** PreparedStatement); private: /** A list of the databases for convenience, easier to refer to them by name rather than a long filename. */ static TMap<FString, FString> Databases; static TMap<FString, sqlite3*> SQLite3Databases; };
ben-mkiv/unreal-sqlite3
Source/CISQLite3/Public/SQLiteBlueprintNodes.h
#pragma once #include "SQLiteBlueprintNodes.generated.h" USTRUCT(BlueprintType) struct CISQLITE3_API FSQLiteQueryLogicExpectedNode { GENERATED_USTRUCT_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Database Query") FString Query; FSQLiteQueryLogicExpectedNode(){} FSQLiteQueryLogicExpectedNode(FString LHSQuery, FString Append) : Query(LHSQuery) { Query += Append; } }; USTRUCT(BlueprintType) struct CISQLITE3_API FSQLiteQueryTermExpectedNode { GENERATED_USTRUCT_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Database Query") FString Query; FSQLiteQueryTermExpectedNode(){} FSQLiteQueryTermExpectedNode(FString LHSQuery, FString Append) : Query(LHSQuery) { Query += Append; } }; USTRUCT(BlueprintType) struct CISQLITE3_API FSQLiteQueryFinalizedQuery { GENERATED_USTRUCT_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SQLite Database Query") FString Query; FSQLiteQueryFinalizedQuery(){} FSQLiteQueryFinalizedQuery(FString Query) : Query(Query){} };
plushmonkey/Terracotta
terracotta/block/BlockFace.h
<filename>terracotta/block/BlockFace.h #ifndef TERRACOTTA_BLOCK_BLOCKFACE_H_ #define TERRACOTTA_BLOCK_BLOCKFACE_H_ #include <string> namespace terra { namespace block { enum class BlockFace { North, East, South, West, Up, Down, None }; const std::string& to_string(BlockFace face); BlockFace face_from_string(const std::string& str); BlockFace get_opposite_face(BlockFace face); } // ns block } // ns terra #endif
plushmonkey/Terracotta
terracotta/math/Plane.h
#ifndef TERRACOTTA_MATH_PLANE_H_ #define TERRACOTTA_MATH_PLANE_H_ #include <glm/glm.hpp> #include <mclib/common/Vector.h> namespace terra { namespace math { class Plane { public: Plane() { } Plane(glm::vec3 normal, float distance); // Construct plane from three noncollinear points Plane(glm::vec3 p1, glm::vec3 p2, glm::vec3 p3); const glm::vec3& GetNormal() const { return m_Normal; } float GetDistance() const { return m_Distance; } float PointDistance(const glm::vec3& q) const; float PointDistance(mc::Vector3i q) const; float PointDistance(mc::Vector3d q) const; private: glm::vec3 m_Normal; float m_Distance; }; } // ns math } // ns terra #endif
plushmonkey/Terracotta
terracotta/block/BlockElement.h
<reponame>plushmonkey/Terracotta #pragma once #ifndef TERRACOTTA_BLOCK_BLOCKELEMENT_H_ #define TERRACOTTA_BLOCK_BLOCKELEMENT_H_ #include "BlockFace.h" #include <vector> #include <glm/glm.hpp> #include "../assets/TextureArray.h" namespace terra { namespace block { struct RenderableFace { assets::TextureHandle texture; int tint_index; BlockFace face; BlockFace cull_face; glm::vec2 uv_from; glm::vec2 uv_to; }; struct ElementRotation { glm::vec3 origin; glm::vec3 axis; float angle; bool rescale; ElementRotation() : origin(0, 0, 0), axis(0, 0, 0), angle(0), rescale(false) { } }; class BlockElement { public: BlockElement(glm::vec3 from, glm::vec3 to) : m_From(from), m_To(to), m_Shade(true) { m_Faces.resize(6); for (RenderableFace& renderable : m_Faces) { renderable.face = BlockFace::None; } m_FullExtent = m_From == glm::vec3(0, 0, 0) && m_To == glm::vec3(1, 1, 1); } std::vector<RenderableFace>& GetFaces() { return m_Faces; } const RenderableFace& GetFace(BlockFace face) const { return m_Faces[static_cast<std::size_t>(face)]; } void AddFace(RenderableFace face) { m_Faces[static_cast<std::size_t>(face.face)] = face; } const glm::vec3& GetFrom() const { return m_From; } const glm::vec3& GetTo() const { return m_To; } bool IsFullExtent() const { return m_FullExtent; } void SetShouldShade(bool shade) { m_Shade = shade; } bool ShouldShade() const { return m_Shade; } ElementRotation& GetRotation() { return m_Rotation; } const ElementRotation& GetRotation() const { return m_Rotation; } private: std::vector<RenderableFace> m_Faces; glm::vec3 m_From; glm::vec3 m_To; bool m_FullExtent; bool m_Shade; ElementRotation m_Rotation; }; } // ns block } // ns terra #endif
plushmonkey/Terracotta
terracotta/render/ChunkMesh.h
<reponame>plushmonkey/Terracotta #ifndef TERRACOTTA_RENDER_CHUNKMESH_H_ #define TERRACOTTA_RENDER_CHUNKMESH_H_ #include "Shader.h" #include <cstddef> namespace terra { namespace render { class ChunkMesh { public: ChunkMesh(unsigned int vao, unsigned int vbo, GLsizei vertex_count); ChunkMesh(const ChunkMesh& other); ChunkMesh& operator=(const ChunkMesh& other); void Render(unsigned int model_uniform); void Destroy(); private: unsigned int m_VAO; unsigned int m_VBO; GLsizei m_VertexCount; }; } // ns render } // ns terra #endif
plushmonkey/Terracotta
terracotta/Transform.h
<reponame>plushmonkey/Terracotta #pragma once #ifndef TERRACOTTA_TRANSFORM_H_ #define TERRACOTTA_TRANSFORM_H_ #include <mclib/common/Vector.h> #include <mclib/common/AABB.h> namespace terra { struct Transform { mc::Vector3d position; mc::Vector3d velocity; mc::Vector3d input_velocity; mc::Vector3d acceleration; mc::Vector3d input_acceleration; float max_speed; float orientation; float rotation; mc::AABB bounding_box; }; } // namespace terra #endif
plushmonkey/Terracotta
terracotta/block/BlockVariant.h
<filename>terracotta/block/BlockVariant.h #pragma once #ifndef TERRACOTTA_BLOCK_BLOCKVARIANT_H_ #define TERRACOTTA_BLOCK_BLOCKVARIANT_H_ #include "BlockModel.h" #include <mclib/block/Block.h> #include <glm/glm.hpp> namespace terra { namespace block { class BlockVariant { public: BlockVariant(BlockModel* model, const std::string& properties, mc::block::BlockPtr block) : m_Model(model), m_Properties(properties), m_Block(block), m_Rotations(0, 0, 0), m_LockUV(true), m_HasRotation(false) { } BlockModel* GetModel() { return m_Model; } mc::block::BlockPtr GetBlock() { return m_Block; } const std::string& GetProperties() const { return m_Properties; } const glm::vec3& GetRotations() const { return m_Rotations; } void SetRotation(const glm::vec3& rotations) { m_Rotations = rotations; m_HasRotation = m_Rotations.x != 0 || m_Rotations.y != 0 || m_Rotations.z != 0; } bool HasRotation() { return m_HasRotation; } private: std::string m_Properties; BlockModel* m_Model; mc::block::BlockPtr m_Block; glm::vec3 m_Rotations; bool m_LockUV; bool m_HasRotation; }; } // ns block } // ns terra #endif
plushmonkey/Terracotta
terracotta/PriorityQueue.h
#ifndef TERRACOTTA_PRIORITY_QUEUE_H_ #define TERRACOTTA_PRIORITY_QUEUE_H_ #include <algorithm> #include <vector> namespace terra { template <typename T, typename Comparator, typename Container = std::vector<T>> class PriorityQueue { private: Container m_Container; Comparator m_Comp; public: PriorityQueue() = default; PriorityQueue(const Comparator& cmp) : m_Comp(cmp) { } void Push(T item) { m_Container.push_back(item); std::push_heap(m_Container.begin(), m_Container.end(), m_Comp); } T Pop() { T item = m_Container.front(); std::pop_heap(m_Container.begin(), m_Container.end(), m_Comp); m_Container.pop_back(); return item; } void Update() { std::make_heap(m_Container.begin(), m_Container.end(), m_Comp); } bool Empty() const { return m_Container.empty(); } Container& GetData() { return m_Container; } }; } // ns terra #endif
plushmonkey/Terracotta
terracotta/assets/AssetCache.h
#ifndef TERRACOTTA_ASSETS_ASSETCACHE_H_ #define TERRACOTTA_ASSETS_ASSETCACHE_H_ #include "TextureArray.h" #include <unordered_map> #include <string> #include <memory> #include "../block/BlockState.h" #include "../block/BlockModel.h" #include "../block/BlockVariant.h" #include <mclib/block/Block.h> namespace terra { namespace assets { class ZipArchive; class AssetCache { public: AssetCache() { } ~AssetCache() { } block::BlockState* GetBlockState(u32 block_id) const; void AddBlockState(std::unique_ptr<terra::block::BlockState> state); void SetMaxBlockId(std::size_t id); TextureArray& GetTextures() { return m_TextureArray; } TextureHandle AddTexture(const std::string& path, const std::string& data); void AddVariantModel(std::unique_ptr<block::BlockVariant> variant); block::BlockVariant* GetVariant(mc::block::BlockPtr block); std::vector<block::BlockModel*> GetBlockModels(const std::string& find); block::BlockModel* GetBlockModel(const std::string& path); void AddBlockModel(const std::string& path, std::unique_ptr<block::BlockModel> model); private: block::BlockVariant* GetVariantFromProperties(const std::string& block_name, const std::string& properties); // Maps block id to the BlockState std::vector<std::unique_ptr<terra::block::BlockState>> m_BlockStates; std::vector<terra::block::BlockVariant*> m_VariantCache; // Maps model path to a BlockModel std::unordered_map<std::string, std::unique_ptr<terra::block::BlockModel>> m_BlockModels; // Block name -> (list of Variants) std::unordered_map<std::string, std::vector<std::unique_ptr<block::BlockVariant>>> m_BlockVariants; TextureArray m_TextureArray; }; } // assets } // terra extern std::unique_ptr<terra::assets::AssetCache> g_AssetCache; #endif
plushmonkey/Terracotta
terracotta/assets/TextureArray.h
#ifndef TERRACOTTA_ASSETS_TEXTUREARRAY_H_ #define TERRACOTTA_ASSETS_TEXTUREARRAY_H_ #include <cstddef> #include <vector> #include <string> #include <unordered_map> #include <cstdint> namespace terra { namespace assets { using TextureHandle = uint32_t; class TextureArray { public: TextureArray(); TextureHandle Append(const std::string& filename, const std::string& texture); bool GetTexture(const std::string& filename, TextureHandle* handle); bool IsTransparent(TextureHandle handle) const; void Generate(); void Bind(); private: unsigned int m_TextureId; std::vector<unsigned char> m_TextureData; std::unordered_map<std::string, TextureHandle> m_Textures; bool m_Transparency[2048]; }; } // ns assets } // ns terra #endif
plushmonkey/Terracotta
terracotta/assets/AssetLoader.h
#pragma once #ifndef TERRACOTTA_ASSETS_ASSETLOADER_H_ #define TERRACOTTA_ASSETS_ASSETLOADER_H_ #include <memory> #include <string> #include <unordered_map> #include <glm/glm.hpp> #include "TextureArray.h" #include "../block/BlockFace.h" #include "../block/BlockElement.h" namespace terra { namespace block { class BlockModel; } // ns block namespace assets { // Stores the intermediate faces of a block. The textures are resolved later and stored into a final RenderableFace. struct IntermediateFace { block::BlockFace face; block::BlockFace cull_face; std::string texture; int tint_index; glm::vec2 uv_from; glm::vec2 uv_to; }; // Stores the intermediate element for a BlockModel. The faces are resolved later and stored in a final BlockElement. struct IntermediateElement { glm::vec3 from; glm::vec3 to; bool shade; block::ElementRotation rotation; std::vector<IntermediateFace> faces; }; class ZipArchive; class AssetCache; class AssetLoader { public: AssetLoader(AssetCache& cache); bool LoadArchive(const std::string& archive_path, const std::string& blocks_path); private: using TextureMap = std::unordered_map<std::string, std::string>; bool LoadBlockStates(const std::string& filename); std::size_t LoadBlockModels(terra::assets::ZipArchive& archive); void LoadBlockVariants(terra::assets::ZipArchive& archive); bool LoadTexture(terra::assets::ZipArchive& archive, const std::string& path, TextureHandle* handle); std::unique_ptr<block::BlockModel> LoadBlockModel(terra::assets::ZipArchive& archive, const std::string& path, TextureMap& texture_map, std::vector<IntermediateElement>& intermediates); AssetCache& m_Cache; }; } // ns assets } // ns terra #endif
plushmonkey/Terracotta
terracotta/ChatWindow.h
#ifndef TERRACOTTA_CHAT_WINDOW_H_ #define TERRACOTTA_CHAT_WINDOW_H_ #include <mclib/protocol/packets/PacketDispatcher.h> #include <mclib/protocol/packets/PacketHandler.h> #include <string> #include <deque> namespace terra { class ChatWindow : public mc::protocol::packets::PacketHandler { public: ChatWindow(mc::protocol::packets::PacketDispatcher* dispatcher, mc::core::Connection* connection); ~ChatWindow(); void HandlePacket(mc::protocol::packets::in::ChatPacket* packet); void Render(); private: mc::core::Connection* m_Connection; char m_InputText[256]; std::deque<std::string> m_ChatBuffer; }; } // ns terra #endif
plushmonkey/Terracotta
terracotta/block/BlockModel.h
#ifndef TERRACOTTA_BLOCK_BLOCKMODEL_H_ #define TERRACOTTA_BLOCK_BLOCKMODEL_H_ #include <string> #include <memory> #include <unordered_map> #include <mclib/common/JsonFwd.h> #include "BlockFace.h" #include "BlockElement.h" namespace terra { namespace block { class BlockModel { public: std::vector<BlockElement>& GetElements() { return m_Elements; } void AddElement(BlockElement element) { m_Elements.push_back(element); } private: std::vector<BlockElement> m_Elements; }; } // ns block } // ns terra #endif
plushmonkey/Terracotta
terracotta/math/volumes/Frustum.h
<reponame>plushmonkey/Terracotta #ifndef TERRACOTTA_MATH_VOLUMES_FRUSTUM_H_ #define TERRACOTTA_MATH_VOLUMES_FRUSTUM_H_ #include <glm/glm.hpp> #include <mclib/common/AABB.h> #include "../Plane.h" namespace terra { namespace math { namespace volumes { class Frustum { public: Frustum(glm::vec3 position, glm::vec3 forward, float near, float far, float fov, float ratio, glm::vec3 up, glm::vec3 right); bool Intersects(const mc::AABB& aabb) const; bool Intersects(glm::vec3 v) const; bool Intersects(mc::Vector3i v) const; bool Intersects(mc::Vector3d v) const; private: glm::vec3 m_Position; glm::vec3 m_Forward; float m_Near; float m_Far; float m_NearWidth; float m_NearHeight; float m_FarWidth; float m_FarHeight; Plane m_Planes[6]; }; } // ns volumes } // ns math } // ns terra #endif
plushmonkey/Terracotta
terracotta/render/Shader.h
<gh_stars>10-100 #ifndef TERRACOTTA_RENDER_SHADER_H_ #define TERRACOTTA_RENDER_SHADER_H_ #include <GL/glew.h> namespace terra { namespace render { class Shader { public: Shader(); Shader(const Shader& other) = delete; Shader(Shader&& other) = delete; Shader& operator=(const Shader& other) = delete; Shader& operator=(Shader&& other) = delete; bool Initialize(const char* vertexPath, const char* fragmentPath); void Use(); void Stop(); GLuint GetUniform(const char* name); private: GLuint m_Program; }; } // ns render } // ns terra #endif
plushmonkey/Terracotta
terracotta/block/BlockState.h
<reponame>plushmonkey/Terracotta<gh_stars>10-100 #ifndef TERRACOTTA_BLOCK_BLOCKSTATE_H_ #define TERRACOTTA_BLOCK_BLOCKSTATE_H_ #include <mclib/common/Types.h> #include <mclib/common/JsonFwd.h> #include <memory> #include <string> #include <unordered_map> namespace terra { namespace block { class BlockState { public: BlockState(u32 id) : m_Id(id) { } u32 GetId() const { return m_Id; } const std::string& GetProperty(const std::string& property) const; const std::string& GetVariant() const { return m_Variant; } static std::unique_ptr<BlockState> FromJSON(const mc::json& json); private: u32 m_Id; std::string m_Variant; std::unordered_map<std::string, std::string> m_Properties; }; } // ns block } // ns terra #endif
plushmonkey/Terracotta
terracotta/render/ChunkMeshGenerator.h
#ifndef TERRACOTTA_RENDER_CHUNKMESHGENERATOR_H_ #define TERRACOTTA_RENDER_CHUNKMESHGENERATOR_H_ #include "ChunkMesh.h" #include <unordered_map> #include <memory> #include <vector> #include <utility> #include <mclib/common/Vector.h> #include <glm/glm.hpp> #include "../World.h" #include "../PriorityQueue.h" #include "../block/BlockFace.h" #include "../block/BlockVariant.h" #include <mutex> #include <thread> #include <condition_variable> #include <deque> namespace std { template <> struct hash<mc::Vector3i> { std::size_t operator()(const mc::Vector3i& s) const noexcept { std::size_t seed = 3; for (int i = 0; i < 3; ++i) { seed ^= s[i] + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } }; } namespace terra { namespace block { class BlockModel; } // ns block namespace render { struct Vertex { glm::vec3 position; glm::vec2 uv; u32 texture_index; glm::vec3 tint; unsigned char ambient_occlusion; Vertex(glm::vec3 pos, glm::vec2 uv, u32 tex_index, glm::vec3 tint, int ambient_occlusion) : position(pos), uv(uv), texture_index(tex_index), tint(tint), ambient_occlusion(static_cast<unsigned char>(ambient_occlusion)) { } }; struct ChunkMeshBuildContext { // Store the chunk data and a border around the chunk mc::block::BlockPtr chunk_data[18 * 18 * 18]; mc::Vector3i world_position; mc::block::BlockPtr GetBlock(const mc::Vector3i& world_pos) { mc::Vector3i::value_type x = world_pos.x - world_position.x + 1; mc::Vector3i::value_type y = world_pos.y - world_position.y + 1; mc::Vector3i::value_type z = world_pos.z - world_position.z + 1; return chunk_data[y * 18 * 18 + z * 18 + x]; } }; class ChunkMeshGenerator : public terra::WorldListener { public: using iterator = std::unordered_map<mc::Vector3i, std::unique_ptr<terra::render::ChunkMesh>>::iterator; ChunkMeshGenerator(terra::World* world, const glm::vec3& camera_position); ~ChunkMeshGenerator(); void OnBlockChange(mc::Vector3i position, mc::block::BlockPtr newBlock, mc::block::BlockPtr oldBlock) override; void OnChunkLoad(terra::ChunkPtr chunk, const terra::ChunkColumnMetadata& meta, u16 index_y) override; void OnChunkUnload(terra::ChunkColumnPtr chunk) override; void GenerateMesh(s64 chunk_x, s64 chunk_y, s64 chunk_z); void GenerateMesh(ChunkMeshBuildContext& context); void DestroyChunk(s64 chunk_x, s64 chunk_y, s64 chunk_z); iterator begin() { return m_ChunkMeshes.begin(); } iterator end() { return m_ChunkMeshes.end(); } void ProcessChunks(); private: struct ChunkMeshBuildComparator { const glm::vec3& position; ChunkMeshBuildComparator(const glm::vec3& position) : position(position) { } bool operator()(const std::shared_ptr<ChunkMeshBuildContext>& first_ctx, const std::shared_ptr<ChunkMeshBuildContext>& second_ctx) { mc::Vector3i first = first_ctx->world_position; mc::Vector3i second = second_ctx->world_position; glm::vec3 f(first.x, 0, first.z); glm::vec3 s(second.x, 0, second.z); glm::vec3 a = f - position; glm::vec3 b = s - position; return glm::dot(a, a) > glm::dot(b, b); } }; struct VertexPush { mc::Vector3i pos; std::unique_ptr<std::vector<Vertex>> vertices; VertexPush(const mc::Vector3i& pos, std::unique_ptr<std::vector<Vertex>> vertices) : pos(pos), vertices(std::move(vertices)) { } }; int GetAmbientOcclusion(ChunkMeshBuildContext& context, const mc::Vector3i& side1, const mc::Vector3i& side2, const mc::Vector3i& corner); bool IsOccluding(terra::block::BlockVariant* from_variant, terra::block::BlockFace face, mc::block::BlockPtr test_block); void WorkerUpdate(); void EnqueueBuildWork(long chunk_x, int chunk_y, long chunk_z); std::mutex m_QueueMutex; PriorityQueue<std::shared_ptr<ChunkMeshBuildContext>, ChunkMeshBuildComparator> m_ChunkBuildQueue; std::deque<mc::Vector3i> m_ChunkPushQueue; std::condition_variable m_BuildCV; terra::World* m_World; std::mutex m_PushMutex; std::vector<std::unique_ptr<VertexPush>> m_VertexPushes; std::unordered_map<mc::Vector3i, std::unique_ptr<terra::render::ChunkMesh>> m_ChunkMeshes; bool m_Working; std::vector<std::thread> m_Workers; }; } // ns render } // ns terra #endif
plushmonkey/Terracotta
terracotta/Collision.h
#pragma once #ifndef TERRACOTTA_COLLISION_H_ #define TERRACOTTA_COLLISION_H_ #include "Transform.h" #include "World.h" namespace terra { class Collision { private: mc::Vector3d m_Position; mc::Vector3d m_Normal; public: Collision() noexcept { } Collision(mc::Vector3d position, mc::Vector3d normal) noexcept : m_Position(position), m_Normal(normal) { } mc::Vector3d GetPosition() const noexcept { return m_Position; } mc::Vector3d GetNormal() const noexcept { return m_Normal; } }; class CollisionDetector { private: terra::World* m_World; std::vector<mc::Vector3i> GetSurroundingLocations(mc::AABB bounds); public: CollisionDetector(terra::World* world) noexcept : m_World(world) { } bool DetectCollision(mc::Vector3d from, mc::Vector3d rayVector, Collision* collision) const; void ResolveCollisions(Transform* transform, double dt, bool* onGround); }; } // namespace terra #endif
plushmonkey/Terracotta
terracotta/math/TypeUtil.h
<filename>terracotta/math/TypeUtil.h<gh_stars>10-100 #ifndef TERRACOTTA_MATH_TYPEUTIL_H_ #define TERRACOTTA_MATH_TYPEUTIL_H_ #include <glm/glm.hpp> #include <mclib/common/Vector.h> namespace terra { namespace math { inline glm::vec3 VecToGLM(mc::Vector3d v) { return glm::vec3(v.x, v.y, v.z); } inline glm::vec3 VecToGLM(mc::Vector3i v) { return glm::vec3(v.x, v.y, v.z); } } // ns math } // ns terra #endif
plushmonkey/Terracotta
terracotta/Game.h
#ifndef TERRACOTTA_GAME_H_ #define TERRACOTTA_GAME_H_ #include <mclib/core/Client.h> #include "Camera.h" #include "GameWindow.h" #include "Transform.h" #include "Collision.h" #include <mclib/protocol/packets/PacketHandler.h> #include <mclib/protocol/packets/Packet.h> #include <memory> namespace terra { class World; class Player { public: Player(terra::World* world); void Update(float dt); Transform& GetTransform() noexcept { return m_Transform; } bool OnGround(); bool IsSneaking() const { return m_Sneaking; } void SetSneaking(bool sneaking) { m_Sneaking = sneaking; } CollisionDetector& GetCollisionDetector() { return m_CollisionDetector; } private: bool m_OnGround; bool m_Sneaking; Transform m_Transform; CollisionDetector m_CollisionDetector; }; class Game : public mc::protocol::packets::PacketHandler, mc::core::PlayerListener { public: Game(mc::protocol::packets::PacketDispatcher* dispatcher, GameWindow& window, const Camera& camera); void OnMouseChange(double x, double y); void OnMouseScroll(double offset_x, double offset_y); void OnMousePress(int button, int action, int mods); void OnClientSpawn(mc::core::PlayerPtr player); void HandlePacket(mc::protocol::packets::in::UpdateHealthPacket* packet); void HandlePacket(mc::protocol::packets::in::EntityVelocityPacket* packet); void HandlePacket(mc::protocol::packets::in::SpawnPositionPacket* packet); void Update(); void UpdateClient(); void CreatePlayer(terra::World* world); Camera& GetCamera() { return m_Camera; } mc::Vector3d GetPosition(); mc::core::Client& GetNetworkClient() { return m_NetworkClient; } private: mc::core::Client m_NetworkClient; GameWindow& m_Window; std::unique_ptr<Player> m_Player; Camera m_Camera; float m_DeltaTime; float m_LastFrame; float m_LastPositionTime; bool m_Sprinting; }; } // ns terra #endif
plushmonkey/Terracotta
terracotta/Chunk.h
#ifndef TERRACOTTA_CHUNK_H_ #define TERRACOTTA_CHUNK_H_ #include <mclib/block/Block.h> #include <mclib/block/BlockEntity.h> #include <mclib/common/Types.h> #include <mclib/nbt/NBT.h> #include <mclib/world/Chunk.h> #include <array> #include <map> #include <memory> namespace terra { struct ChunkColumnMetadata { s32 x; s32 z; u16 sectionmask; bool continuous; bool skylight; ChunkColumnMetadata(const mc::world::ChunkColumnMetadata& metadata) : x(metadata.x), z(metadata.z), sectionmask(metadata.sectionmask), continuous(metadata.continuous), skylight(metadata.skylight) { } }; /** * A 16x16x16 area. A ChunkColumn is made up of 16 of these */ class Chunk { private: std::array<mc::block::BlockPtr, 16 * 16 * 16> m_Blocks; public: Chunk(); Chunk(const Chunk& other) = delete; Chunk& operator=(const Chunk& other) = delete; Chunk(const mc::world::Chunk& other); /** * Position is relative to this chunk position */ mc::block::BlockPtr GetBlock(const mc::Vector3i& chunkPosition) const; /** * Position is relative to this chunk position */ void SetBlock(mc::Vector3i chunkPosition, mc::block::BlockPtr block); }; typedef std::shared_ptr<Chunk> ChunkPtr; /** * Stores a 16x256x16 area. Uses chunks (16x16x16) to store the data vertically. * A null chunk is fully air. */ class ChunkColumn { public: enum { ChunksPerColumn = 16 }; typedef std::array<ChunkPtr, ChunksPerColumn>::iterator iterator; typedef std::array<ChunkPtr, ChunksPerColumn>::reference reference; typedef std::array<ChunkPtr, ChunksPerColumn>::const_iterator const_iterator; typedef std::array<ChunkPtr, ChunksPerColumn>::const_reference const_reference; private: std::array<ChunkPtr, ChunksPerColumn> m_Chunks; ChunkColumnMetadata m_Metadata; std::map<mc::Vector3i, mc::block::BlockEntityPtr> m_BlockEntities; public: ChunkColumn(ChunkColumnMetadata metadata); ChunkColumn(const ChunkColumn& rhs) = default; ChunkColumn& operator=(const ChunkColumn& rhs) = default; ChunkColumn(ChunkColumn&& rhs) = default; ChunkColumn& operator=(ChunkColumn&& rhs) = default; ChunkColumn(const mc::world::ChunkColumn& rhs); iterator begin() { return m_Chunks.begin(); } iterator end() { return m_Chunks.end(); } reference operator[](std::size_t index) { return m_Chunks[index]; } const_iterator begin() const { return m_Chunks.begin(); } const_iterator end() const { return m_Chunks.end(); } const_reference operator[](std::size_t index) const { return m_Chunks[index]; } void AddBlockEntity(mc::block::BlockEntityPtr blockEntity) { m_BlockEntities.insert(std::make_pair(blockEntity->GetPosition(), blockEntity)); } void RemoveBlockEntity(mc::Vector3i pos) { m_BlockEntities.erase(pos); } /** * Position is relative to this ChunkColumn position. */ mc::block::BlockPtr GetBlock(const mc::Vector3i& position); const ChunkColumnMetadata& GetMetadata() const { return m_Metadata; } mc::block::BlockEntityPtr GetBlockEntity(mc::Vector3i worldPos); std::vector<mc::block::BlockEntityPtr> GetBlockEntities(); }; typedef std::shared_ptr<ChunkColumn> ChunkColumnPtr; } // ns terra #endif
plushmonkey/Terracotta
terracotta/assets/zip/ZipArchive.h
<filename>terracotta/assets/zip/ZipArchive.h #ifndef TERRACOTTA_UTIL_ZIPARCHIVE_H_ #define TERRACOTTA_UTIL_ZIPARCHIVE_H_ #include <string> #include <vector> #include "miniz.h" namespace terra { namespace assets { class ZipArchive { public: ZipArchive(); bool Open(const char *archivePath); void Close(); // Reads a file from the archive into the heap. char* ReadFile(const char* filename, size_t* size); void FreeFileData(char* data); // Lists all of the files in the archive that contain search in their name. std::vector<std::string> ListFiles(const char* search); private: mz_zip_archive m_Archive; }; } // ns assets } // ns terra #endif
plushmonkey/Terracotta
terracotta/World.h
<reponame>plushmonkey/Terracotta #ifndef TERRACOTTA_WORLD_H_ #define TERRACOTTA_WORLD_H_ #include <mclib/protocol/packets/PacketHandler.h> #include <mclib/protocol/packets/PacketDispatcher.h> #include <mclib/util/ObserverSubject.h> #include "Chunk.h" #include <unordered_map> namespace terra { using ChunkCoord = std::pair<s32, s32>; } // ns terra namespace std { template <> struct hash<terra::ChunkCoord> { std::size_t operator()(const terra::ChunkCoord& s) const noexcept { std::size_t seed = 3; seed ^= s.first + 0x9e3779b9 + (seed << 6) + (seed >> 2); seed ^= s.second + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } }; } // ns std namespace terra { class WorldListener { public: // yIndex is the chunk section index of the column, 0 means bottom chunk, 15 means top virtual void OnChunkLoad(ChunkPtr chunk, const ChunkColumnMetadata& meta, u16 yIndex) { } virtual void OnChunkUnload(ChunkColumnPtr chunk) { } virtual void OnBlockChange(mc::Vector3i position, mc::block::BlockPtr newBlock, mc::block::BlockPtr oldBlock) { } }; class World : public mc::protocol::packets::PacketHandler, public mc::util::ObserverSubject<WorldListener> { public: World(mc::protocol::packets::PacketDispatcher* dispatcher); ~World(); World(const World& rhs) = delete; World& operator=(const World& rhs) = delete; World(World&& rhs) = delete; World& operator=(World&& rhs) = delete; void HandlePacket(mc::protocol::packets::in::ChunkDataPacket* packet); void HandlePacket(mc::protocol::packets::in::UnloadChunkPacket* packet); void HandlePacket(mc::protocol::packets::in::MultiBlockChangePacket* packet); void HandlePacket(mc::protocol::packets::in::BlockChangePacket* packet); void HandlePacket(mc::protocol::packets::in::ExplosionPacket* packet); void HandlePacket(mc::protocol::packets::in::UpdateBlockEntityPacket* packet); void HandlePacket(mc::protocol::packets::in::RespawnPacket* packet); /** * Pos can be any world position inside of the chunk */ ChunkColumnPtr GetChunk(const mc::Vector3i& pos) const; mc::block::BlockPtr GetBlock(const mc::Vector3i& pos) const; mc::block::BlockEntityPtr GetBlockEntity(mc::Vector3i pos) const; // Gets all of the known block entities in loaded chunks std::vector<mc::block::BlockEntityPtr> GetBlockEntities() const; const std::unordered_map<ChunkCoord, ChunkColumnPtr>::const_iterator begin() const { return m_Chunks.begin(); } const std::unordered_map<ChunkCoord, ChunkColumnPtr>::const_iterator end() const { return m_Chunks.end(); } private: std::unordered_map<ChunkCoord, ChunkColumnPtr> m_Chunks; bool SetBlock(mc::Vector3i position, u32 blockData); }; } // ns terra #endif
plushmonkey/Terracotta
terracotta/GameWindow.h
<reponame>plushmonkey/Terracotta #ifndef TERRACOTTA_GAME_WINDOW_H_ #define TERRACOTTA_GAME_WINDOW_H_ #include <GLFW/glfw3.h> #include <vector> #include <functional> namespace terra { using MouseSetCallback = std::function<void(double, double)>; using MouseChangeCallback = std::function<void(double, double)>; using MouseButtonCallback = std::function<void(int, int, int)>; using MouseScrollCallback = std::function<void(double, double)>; class GameWindow { public: GameWindow(GLFWwindow* window); void OnKeyChange(int key, int code, int action, int mode); void OnMouseMove(double x, double y); void OnMouseButton(int button, int action, int mods); void OnMouseScroll(double offset_x, double offset_y); void RegisterMouseSet(MouseSetCallback callback) { m_MouseSetCallbacks.push_back(callback); } void RegisterMouseChange(MouseChangeCallback callback) { m_MouseChangeCallbacks.push_back(callback); } void RegisterMouseButton(MouseButtonCallback callback) { m_MouseButtonCallbacks.push_back(callback); } void RegisterMouseScroll(MouseScrollCallback callback) { m_MouseScrollCallbacks.push_back(callback); } bool IsKeyDown(int code); private: GLFWwindow* m_Window; std::vector<MouseSetCallback> m_MouseSetCallbacks; std::vector<MouseChangeCallback> m_MouseChangeCallbacks; std::vector<MouseButtonCallback> m_MouseButtonCallbacks; std::vector<MouseScrollCallback> m_MouseScrollCallbacks; bool m_Keys[1024]; float m_LastMouseX; float m_LastMouseY; bool m_FirstMouse; bool m_UpdateMouse; }; } // ns terra #endif
plushmonkey/Terracotta
terracotta/Camera.h
#ifndef TERRACOTTA_CAMERA_H_ #define TERRACOTTA_CAMERA_H_ #include <GL/glew.h> #include <glm/glm.hpp> #include "math/volumes/Frustum.h" #undef near #undef far namespace terra { enum class CameraMovement { Forward, Backward, Left, Right, Raise, Lower }; class Camera { public: Camera(glm::vec3 position, float fov, float ratio, float near, float far, glm::vec3 worldUp = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = -1.5708, float pitch = 0.0f); void ProcessMovement(CameraMovement direction, float dt); void ProcessRotation(float xoffset, float yoffset); void ProcessZoom(float yoffset); const glm::vec3& GetPosition() const { return m_Position; } glm::vec3 GetFront() const { return m_Front; } glm::vec3 GetRight() const { return m_Right; } float GetZoom() const { return m_Zoom; } glm::mat4 GetViewMatrix() const; glm::mat4 GetPerspectiveMatrix() const; void SetPosition(glm::vec3 pos) { m_Position = pos; } float GetYaw() const { return m_Yaw; } float GetPitch() const { return m_Pitch; } math::volumes::Frustum GetFrustum() const; void SetMouseSensitivity(float sensitivity) { m_MouseSensitivity = sensitivity; } void SetFov(float fov) { m_Fov = fov; } private: glm::vec3 m_Position; glm::vec3 m_Front; glm::vec3 m_WorldUp; glm::vec3 m_Up; glm::vec3 m_Right; float m_Yaw; float m_Pitch; float m_Near; float m_Far; float m_Fov; float m_AspectRatio; float m_MovementSpeed; float m_MouseSensitivity; float m_Zoom; void UpdateVectors(); }; } // ns terra #endif
AITT-VN/xcontroller_arduino_lib
src/Mini_Fan.h
#ifndef MINIFAN_H #define MINIFAN_H #include <Arduino.h> class MiniFan { private: uint8_t _pin; public: MiniFan(uint8_t pin); void on(); void off(); }; #endif
AITT-VN/xcontroller_arduino_lib
src/Tone32.h
<gh_stars>0 #ifndef _TONE32_h #define _TONE32_h #define TONE_CHANNEL 15 #include "Arduino.h" #include "pitches.h" void tone32(uint8_t pin, unsigned int frequency, unsigned long duration = 0, uint8_t channel = TONE_CHANNEL); void noTone32(uint8_t pin, uint8_t channel = TONE_CHANNEL); #endif
AITT-VN/xcontroller_arduino_lib
src/Servos.h
<reponame>AITT-VN/xcontroller_arduino_lib #ifndef SERVOS_H #define SERVOS_H #include "Adafruit_PWMServoDriver.h" class Servos{ private: Adafruit_PWMServoDriver pca9685 = Adafruit_PWMServoDriver(); int pos[8] = {0 ,0, 0, 0, 0, 0, 0, 0}; int _angleToPulse(int ang); public: Servos(); void init(); void position(int index, int degrees); void rotate(int index, int change, int sleep); void release(int index); void spin(int index, int direction, int speed); }; #endif
AITT-VN/xcontroller_arduino_lib
src/mpu6050.h
<gh_stars>0 #ifndef _MPU6050_H #define _MPU6050_H #include "Arduino.h" #include <Wire.h> #define ACCEL_XOUT_H 0x3B #define ACCEL_XOUT_L 0x3C #define ACCEL_YOUT_H 0x3D #define ACCEL_YOUT_L 0x3E #define ACCEL_ZOUT_H 0x3F #define ACCEL_ZOUT_L 0x40 #define TEMP_OUT_H 0x41 #define TEMP_OUT_L 0x42 #define GYRO_XOUT_H 0x43 #define GYRO_XOUT_L 0x44 #define GYRO_YOUT_H 0x45 #define GYRO_YOUT_L 0x46 #define GYRO_ZOUT_H 0x47 #define GYRO_ZOUT_L 0x48 #define ADDR_MPU6050 0x68 class MPU6050 { public: void begin(); int16_t getData(int8_t address); int16_t getAccX(void); int16_t getAccY(void); int16_t getAccZ(void); int16_t getGyroX(void); int16_t getGyroY(void); int16_t getGyroZ(void); } ; #endif
AITT-VN/xcontroller_arduino_lib
src/Ultrasonic.h
<reponame>AITT-VN/xcontroller_arduino_lib /* HCSR04 - Library for arduino, for HC-SR04 ultrasonic distance sensor. Created by <NAME>, June 11, 2016. */ #ifndef ULTRASONIC_H #define ULTRASONIC_H #include "Arduino.h" class Ultrasonic{ public: /** * @param triggerPin Digital pin that is used for controlling sensor (output). * @param echoPin Digital pin that is used to get information from sensor (input). */ Ultrasonic(int triggerPin, int echoPin); double measureDistanceCm(); double measureDistanceMm(); private: int triggerPin, echoPin; }; #endif // ULTRASONIC_H
AITT-VN/xcontroller_arduino_lib
src/LineArray.h
<reponame>AITT-VN/xcontroller_arduino_lib /* LineArray.h */ #ifndef LINEARRAY_h #define LINEARRAY_h #include "Arduino.h" #include "PCF8574.h" #include "Wire.h" #define LINE_1 0 #define LINE_2 1 #define LINE_3 2 #define LINE_4 3 class LineArray { public: LineArray(int sda, int scl); int* read(); int read(uint8_t index); private: PCF8574 _pcf8574 = PCF8574(0x23, &Wire1); }; #endif
AITT-VN/xcontroller_arduino_lib
src/LCD_1602.h
/* LCD_I2C - Arduino library to control a 16x2 LCD via an I2C adapter based on PCF8574 Copyright(C) 2020 Blackhack <<EMAIL>> This program is free software : you can redistribute it and /or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program.If not, see < https://www.gnu.org/licenses/>. */ #ifndef _LCD_1602_h #define _LCD_1602_h #include "Arduino.h" /* This struct helps us constructing the I2C output based on data and control outputs. Because the LCD is set to 4-bit mode, 4 bits of the I2C output are for the control outputs while the other 4 bits are for the 8 bits of data which are send in parts using the enable output.*/ struct OutputState { uint8_t rs = 0; uint8_t rw = 0; uint8_t E = 0; uint8_t Led = 0; uint8_t data = 0; uint8_t GetLowData() { uint8_t buffer = rs; buffer |= rw << 1; buffer |= E << 2; buffer |= Led << 3; buffer |= (data & 0x0F) << 4; return buffer; } uint8_t GetHighData() { uint8_t buffer = rs; buffer |= rw << 1; buffer |= E << 2; buffer |= Led << 3; buffer |= (data & 0xF0); return buffer; } }; class LCD_1602 : public Print { public: LCD_1602(uint8_t address) { _address = address; } void begin(int8_t scl, int8_t sda); void backlight(); void noBacklight(); void clear(); void home(); void leftToRight(); void rightToLeft(); void autoscroll(); void noAutoscroll(); void display(); void noDisplay(); void cursor(); void noCursor(); void blink(); void noBlink(); void scrollDisplayLeft(); void scrollDisplayRight(); void createChar(uint8_t location, uint8_t charmap[]); void setCursor(uint8_t col, uint8_t row); // Method used by the Arduino class "Print" which is the one that provides the .print(string) method virtual size_t write(uint8_t character); private: void InitializeLCD(); void I2C_Write(uint8_t output); void LCD_Write(uint8_t output, bool initialization = false); private: uint8_t _address; OutputState _output; uint8_t _displayState = 0x00; uint8_t _entryState = 0x00; }; #endif
AITT-VN/xcontroller_arduino_lib
src/Adafruit_NeoPixel.h
<gh_stars>0 #ifndef Adafruit_NEOPIXEL_H #define Adafruit_NEOPIXEL_H #ifdef ARDUINO #if (ARDUINO >= 100) #include <Arduino.h> #else #include <WProgram.h> #include <pins_arduino.h> #endif #endif #ifdef TARGET_LPC1768 #include <Arduino.h> #endif // The order of primary colors in the NeoPixel data stream can vary among // device types, manufacturers and even different revisions of the same // item. The third parameter to the Adafruit_NeoPixel constructor encodes // the per-pixel byte offsets of the red, green and blue primaries (plus // white, if present) in the data stream -- the following #defines provide // an easier-to-use named version for each permutation. e.g. NEO_GRB // indicates a NeoPixel-compatible device expecting three bytes per pixel, // with the first byte transmitted containing the green value, second // containing red and third containing blue. The in-memory representation // of a chain of NeoPixels is the same as the data-stream order; no // re-ordering of bytes is required when issuing data to the chain. // Most of these values won't exist in real-world devices, but it's done // this way so we're ready for it (also, if using the WS2811 driver IC, // one might have their pixels set up in any weird permutation). // Bits 5,4 of this value are the offset (0-3) from the first byte of a // pixel to the location of the red color byte. Bits 3,2 are the green // offset and 1,0 are the blue offset. If it is an RGBW-type device // (supporting a white primary in addition to R,G,B), bits 7,6 are the // offset to the white byte...otherwise, bits 7,6 are set to the same value // as 5,4 (red) to indicate an RGB (not RGBW) device. // i.e. binary representation: // 0bWWRRGGBB for RGBW devices // 0bRRRRGGBB for RGB // RGB NeoPixel permutations; white and red offsets are always same // Offset: W R G B #define NEO_RGB ((0<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B #define NEO_RBG ((0<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G #define NEO_GRB ((1<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B #define NEO_GBR ((2<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R #define NEO_BRG ((1<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G #define NEO_BGR ((2<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R // RGBW NeoPixel permutations; all 4 offsets are distinct // Offset: W R G B #define NEO_WRGB ((0<<6) | (1<<4) | (2<<2) | (3)) ///< Transmit as W,R,G,B #define NEO_WRBG ((0<<6) | (1<<4) | (3<<2) | (2)) ///< Transmit as W,R,B,G #define NEO_WGRB ((0<<6) | (2<<4) | (1<<2) | (3)) ///< Transmit as W,G,R,B #define NEO_WGBR ((0<<6) | (3<<4) | (1<<2) | (2)) ///< Transmit as W,G,B,R #define NEO_WBRG ((0<<6) | (2<<4) | (3<<2) | (1)) ///< Transmit as W,B,R,G #define NEO_WBGR ((0<<6) | (3<<4) | (2<<2) | (1)) ///< Transmit as W,B,G,R #define NEO_RWGB ((1<<6) | (0<<4) | (2<<2) | (3)) ///< Transmit as R,W,G,B #define NEO_RWBG ((1<<6) | (0<<4) | (3<<2) | (2)) ///< Transmit as R,W,B,G #define NEO_RGWB ((2<<6) | (0<<4) | (1<<2) | (3)) ///< Transmit as R,G,W,B #define NEO_RGBW ((3<<6) | (0<<4) | (1<<2) | (2)) ///< Transmit as R,G,B,W #define NEO_RBWG ((2<<6) | (0<<4) | (3<<2) | (1)) ///< Transmit as R,B,W,G #define NEO_RBGW ((3<<6) | (0<<4) | (2<<2) | (1)) ///< Transmit as R,B,G,W #define NEO_GWRB ((1<<6) | (2<<4) | (0<<2) | (3)) ///< Transmit as G,W,R,B #define NEO_GWBR ((1<<6) | (3<<4) | (0<<2) | (2)) ///< Transmit as G,W,B,R #define NEO_GRWB ((2<<6) | (1<<4) | (0<<2) | (3)) ///< Transmit as G,R,W,B #define NEO_GRBW ((3<<6) | (1<<4) | (0<<2) | (2)) ///< Transmit as G,R,B,W #define NEO_GBWR ((2<<6) | (3<<4) | (0<<2) | (1)) ///< Transmit as G,B,W,R #define NEO_GBRW ((3<<6) | (2<<4) | (0<<2) | (1)) ///< Transmit as G,B,R,W #define NEO_BWRG ((1<<6) | (2<<4) | (3<<2) | (0)) ///< Transmit as B,W,R,G #define NEO_BWGR ((1<<6) | (3<<4) | (2<<2) | (0)) ///< Transmit as B,W,G,R #define NEO_BRWG ((2<<6) | (1<<4) | (3<<2) | (0)) ///< Transmit as B,R,W,G #define NEO_BRGW ((3<<6) | (1<<4) | (2<<2) | (0)) ///< Transmit as B,R,G,W #define NEO_BGWR ((2<<6) | (3<<4) | (1<<2) | (0)) ///< Transmit as B,G,W,R #define NEO_BGRW ((3<<6) | (2<<4) | (1<<2) | (0)) ///< Transmit as B,G,R,W // Add NEO_KHZ400 to the color order value to indicate a 400 KHz device. // All but the earliest v1 NeoPixels expect an 800 KHz data stream, this is // the default if unspecified. Because flash space is very limited on ATtiny // devices (e.g. Trinket, Gemma), v1 NeoPixels aren't handled by default on // those chips, though it can be enabled by removing the ifndef/endif below, // but code will be bigger. Conversely, can disable the NEO_KHZ400 line on // other MCUs to remove v1 support and save a little space. #define NEO_KHZ800 0x0000 ///< 800 KHz data transmission #ifndef __AVR_ATtiny85__ #define NEO_KHZ400 0x0100 ///< 400 KHz data transmission #endif // If 400 KHz support is enabled, the third parameter to the constructor // requires a 16-bit value (in order to select 400 vs 800 KHz speed). // If only 800 KHz is enabled (as is default on ATtiny), an 8-bit value // is sufficient to encode pixel color order, saving some space. #ifdef NEO_KHZ400 typedef uint16_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor #else typedef uint8_t neoPixelType; ///< 3rd arg to Adafruit_NeoPixel constructor #endif // These two tables are declared outside the Adafruit_NeoPixel class // because some boards may require oldschool compilers that don't // handle the C++11 constexpr keyword. /* A PROGMEM (flash mem) table containing 8-bit unsigned sine wave (0-255). Copy & paste this snippet into a Python REPL to regenerate: import math for x in range(256): print("{:3},".format(int((math.sin(x/128.0*math.pi)+1.0)*127.5+0.5))), if x&15 == 15: print */ static const uint8_t PROGMEM _NeoPixelSineTable[256] = { 128,131,134,137,140,143,146,149,152,155,158,162,165,167,170,173, 176,179,182,185,188,190,193,196,198,201,203,206,208,211,213,215, 218,220,222,224,226,228,230,232,234,235,237,238,240,241,243,244, 245,246,248,249,250,250,251,252,253,253,254,254,254,255,255,255, 255,255,255,255,254,254,254,253,253,252,251,250,250,249,248,246, 245,244,243,241,240,238,237,235,234,232,230,228,226,224,222,220, 218,215,213,211,208,206,203,201,198,196,193,190,188,185,182,179, 176,173,170,167,165,162,158,155,152,149,146,143,140,137,134,131, 128,124,121,118,115,112,109,106,103,100, 97, 93, 90, 88, 85, 82, 79, 76, 73, 70, 67, 65, 62, 59, 57, 54, 52, 49, 47, 44, 42, 40, 37, 35, 33, 31, 29, 27, 25, 23, 21, 20, 18, 17, 15, 14, 12, 11, 10, 9, 7, 6, 5, 5, 4, 3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 9, 10, 11, 12, 14, 15, 17, 18, 20, 21, 23, 25, 27, 29, 31, 33, 35, 37, 40, 42, 44, 47, 49, 52, 54, 57, 59, 62, 65, 67, 70, 73, 76, 79, 82, 85, 88, 90, 93, 97,100,103,106,109,112,115,118,121,124}; /* Similar to above, but for an 8-bit gamma-correction table. Copy & paste this snippet into a Python REPL to regenerate: import math gamma=2.6 for x in range(256): print("{:3},".format(int(math.pow((x)/255.0,gamma)*255.0+0.5))), if x&15 == 15: print */ static const uint8_t PROGMEM _NeoPixelGammaTable[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96, 97, 99,100,102,103,105,106,108,109,111,112,114,115,117,119,120, 122,124,125,127,129,130,132,134,136,137,139,141,143,145,146,148, 150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180, 182,184,186,188,191,193,195,197,199,202,204,206,209,211,213,215, 218,220,223,225,227,230,232,235,237,240,242,245,247,250,252,255}; /*! @brief Class that stores state and functions for interacting with Adafruit NeoPixels and compatible devices. */ class Adafruit_NeoPixel { public: // Constructor: number of LEDs, pin number, LED type Adafruit_NeoPixel(uint16_t n, uint16_t pin=6, neoPixelType type=NEO_GRB + NEO_KHZ800); Adafruit_NeoPixel(void); ~Adafruit_NeoPixel(); void begin(void); void show(void); void setPin(uint16_t p); void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b); void setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w); void setPixelColor(uint16_t n, uint32_t c); void fill(uint32_t c=0, uint16_t first=0, uint16_t count=0); void setBrightness(uint8_t); void clear(void); void updateLength(uint16_t n); void updateType(neoPixelType t); /*! @brief Check whether a call to show() will start sending data immediately or will 'block' for a required interval. NeoPixels require a short quiet time (about 300 microseconds) after the last bit is received before the data 'latches' and new data can start being received. Usually one's sketch is implicitly using this time to generate a new frame of animation...but if it finishes very quickly, this function could be used to see if there's some idle time available for some low-priority concurrent task. @return 1 or true if show() will start sending immediately, 0 or false if show() would block (meaning some idle time is available). */ bool canShow(void) { if (endTime > micros()) { endTime = micros(); } return (micros() - endTime) >= 300L; } /*! @brief Get a pointer directly to the NeoPixel data buffer in RAM. Pixel data is stored in a device-native format (a la the NEO_* constants) and is not translated here. Applications that access this buffer will need to be aware of the specific data format and handle colors appropriately. @return Pointer to NeoPixel buffer (uint8_t* array). @note This is for high-performance applications where calling setPixelColor() on every single pixel would be too slow (e.g. POV or light-painting projects). There is no bounds checking on the array, creating tremendous potential for mayhem if one writes past the ends of the buffer. Great power, great responsibility and all that. */ uint8_t *getPixels(void) const { return pixels; }; uint8_t getBrightness(void) const; /*! @brief Retrieve the pin number used for NeoPixel data output. @return Arduino pin number (-1 if not set). */ int16_t getPin(void) const { return pin; }; /*! @brief Return the number of pixels in an Adafruit_NeoPixel strip object. @return Pixel count (0 if not set). */ uint16_t numPixels(void) const { return numLEDs; } uint32_t getPixelColor(uint16_t n) const; /*! @brief An 8-bit integer sine wave function, not directly compatible with standard trigonometric units like radians or degrees. @param x Input angle, 0-255; 256 would loop back to zero, completing the circle (equivalent to 360 degrees or 2 pi radians). One can therefore use an unsigned 8-bit variable and simply add or subtract, allowing it to overflow/underflow and it still does the expected contiguous thing. @return Sine result, 0 to 255, or -128 to +127 if type-converted to a signed int8_t, but you'll most likely want unsigned as this output is often used for pixel brightness in animation effects. */ static uint8_t sine8(uint8_t x) { return pgm_read_byte(&_NeoPixelSineTable[x]); // 0-255 in, 0-255 out } /*! @brief An 8-bit gamma-correction function for basic pixel brightness adjustment. Makes color transitions appear more perceptially correct. @param x Input brightness, 0 (minimum or off/black) to 255 (maximum). @return Gamma-adjusted brightness, can then be passed to one of the setPixelColor() functions. This uses a fixed gamma correction exponent of 2.6, which seems reasonably okay for average NeoPixels in average tasks. If you need finer control you'll need to provide your own gamma-correction function instead. */ static uint8_t gamma8(uint8_t x) { return pgm_read_byte(&_NeoPixelGammaTable[x]); // 0-255 in, 0-255 out } /*! @brief Convert separate red, green and blue values into a single "packed" 32-bit RGB color. @param r Red brightness, 0 to 255. @param g Green brightness, 0 to 255. @param b Blue brightness, 0 to 255. @return 32-bit packed RGB value, which can then be assigned to a variable for later use or passed to the setPixelColor() function. Packed RGB format is predictable, regardless of LED strand color order. */ static uint32_t Color(uint8_t r, uint8_t g, uint8_t b) { return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; } /*! @brief Convert separate red, green, blue and white values into a single "packed" 32-bit WRGB color. @param r Red brightness, 0 to 255. @param g Green brightness, 0 to 255. @param b Blue brightness, 0 to 255. @param w White brightness, 0 to 255. @return 32-bit packed WRGB value, which can then be assigned to a variable for later use or passed to the setPixelColor() function. Packed WRGB format is predictable, regardless of LED strand color order. */ static uint32_t Color(uint8_t r, uint8_t g, uint8_t b, uint8_t w) { return ((uint32_t)w << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; } static uint32_t ColorHSV(uint16_t hue, uint8_t sat=255, uint8_t val=255); /*! @brief A gamma-correction function for 32-bit packed RGB or WRGB colors. Makes color transitions appear more perceptially correct. @param x 32-bit packed RGB or WRGB color. @return Gamma-adjusted packed color, can then be passed in one of the setPixelColor() functions. Like gamma8(), this uses a fixed gamma correction exponent of 2.6, which seems reasonably okay for average NeoPixels in average tasks. If you need finer control you'll need to provide your own gamma-correction function instead. */ static uint32_t gamma32(uint32_t x); protected: #ifdef NEO_KHZ400 // If 400 KHz NeoPixel support enabled... bool is800KHz; ///< true if 800 KHz pixels #endif bool begun; ///< true if begin() previously called uint16_t numLEDs; ///< Number of RGB LEDs in strip uint16_t numBytes; ///< Size of 'pixels' buffer below int16_t pin; ///< Output pin number (-1 if not yet set) uint8_t brightness; ///< Strip brightness 0-255 (stored as +1) uint8_t *pixels; ///< Holds LED color values (3 or 4 bytes each) uint8_t rOffset; ///< Red index within each 3- or 4-byte pixel uint8_t gOffset; ///< Index of green byte uint8_t bOffset; ///< Index of blue byte uint8_t wOffset; ///< Index of white (==rOffset if no white) uint32_t endTime; ///< Latch timing reference #ifdef __AVR__ volatile uint8_t *port; ///< Output PORT register uint8_t pinMask; ///< Output PORT bitmask #endif #if defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_ARDUINO_CORE_STM32) GPIO_TypeDef *gpioPort; ///< Output GPIO PORT uint32_t gpioPin; ///< Output GPIO PIN #endif }; #endif // Adafruit_NEOPIXEL_H
AITT-VN/xcontroller_arduino_lib
src/xcontroller.h
#include "Arduino.h" #include <Adafruit_NeoPixel.h> #include "Tone32.h" //#include "Motors.h" //#include "Servos.h" //#include "mpu6050.h" //#include "esp32BLEUtilities.h" #ifndef XCONTROLLER_H #define XCONTROLLER_H #define NUMPIXELS_ONBOARD 2 //#include "Wire.h" //#include "esp32BLEUtilities.h" //#include "pca9685.h" //#include "mpu6050.h" //#include <utility/TM1640.h> //#include <utility/TM16xxMatrix.h> class XController { private: Adafruit_NeoPixel ledOnboard = Adafruit_NeoPixel(NUMPIXELS_ONBOARD, RGB_LED, NEO_GRB + NEO_KHZ800); public: XController(void); void showLed(uint8_t index, uint8_t r, uint8_t g, uint8_t b); void tone(unsigned int frequency, unsigned long duration, uint8_t channel); void noTone(uint8_t channel); }; #endif
AITT-VN/xcontroller_arduino_lib
src/Motors.h
#ifndef MOTORS_H #define MOTORS_H #include "Adafruit_PWMServoDriver.h" #define MAX_PWM 3000 #define M1_PWM 10 #define M1_IN2 11 #define M1_IN1 12 #define M2_IN1 13 #define M2_IN2 14 #define M2_PWM 15 class Motors{ private: Adafruit_PWMServoDriver pca9685 = Adafruit_PWMServoDriver(); int DCMotors[2][3] = {{M1_PWM, M1_IN2, M1_IN1}, {M2_PWM, M2_IN2, M2_IN1}}; void _pin(int pin, int value); void _speed(int index, int value); public: Motors(); void init(); void speed(int m1, int m2); void move(int dir, int speed); void stop(); }; #endif
AITT-VN/xcontroller_arduino_lib
src/IR/private/IRTimer.cpp.h
/** * @file IRTimer.cpp.h * * @brief All timer specific definitions are contained in this file. * * This file is part of Arduino-IRremote https://github.com/Arduino-IRremote/Arduino-IRremote. * ************************************************************************************* * MIT License * * Copyright (c) 2021 <NAME> * * 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 "IR/IRremoteInt.h" /** \addtogroup HardwareDependencies CPU / board dependent definitions * @{ */ /** \addtogroup Timer Usage of timers for the different CPU / boards * @{ */ #if defined(SEND_PWM_BY_TIMER) && !defined(ESP32) #undef IR_SEND_PIN // send pin is determined by timer except for ESP32 #endif /* * For backwards compatibility */ #if defined(SYSCLOCK) // allow for processor specific code to define F_CPU #undef F_CPU /** * Clock frequency to be used for timing. */ #define F_CPU SYSCLOCK #endif #if defined(PARTICLE) #define F_CPU 16000000 #endif #if defined (DOXYGEN) /** * Hardware / timer dependent pin number for sending IR if SEND_PWM_BY_TIMER is defined. Otherwise used as default for IrSender.sendPin. */ #define IR_SEND_PIN #elif defined(__AVR__) /********************************************************************************************************************** * Mapping of AVR boards to AVR timers * For some CPU's you have the option to switch the timer and the hardware send pin **********************************************************************************************************************/ /*************************************** * Plain AVR CPU's, no boards ***************************************/ // Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc // ATmega48, ATmega88, ATmega168, ATmega328 #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328PB__) || defined(__AVR_ATmega168__) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER2) //#define IR_USE_AVR_TIMER1 // send pin = pin 9 #define IR_USE_AVR_TIMER2 // send pin = pin 3 # endif // Arduino Mega #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER2) && !defined(IR_USE_AVR_TIMER3) && !defined(IR_USE_AVR_TIMER4) && !defined(IR_USE_AVR_TIMER5) //#define IR_USE_AVR_TIMER1 // send pin = pin 11 #define IR_USE_AVR_TIMER2 // send pin = pin 9 //#define IR_USE_AVR_TIMER3 // send pin = pin 5 //#define IR_USE_AVR_TIMER4 // send pin = pin 6 //#define IR_USE_AVR_TIMER5 // send pin = pin 46 # endif // Leonardo #elif defined(__AVR_ATmega32U4__) && ! defined(TEENSYDUINO) && ! defined(ARDUINO_AVR_PROMICRO) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER3) && !defined(IR_USE_AVR_TIMER4_HS) //#define IR_USE_AVR_TIMER1 // send pin = pin 9 #define IR_USE_AVR_TIMER3 // send pin = pin 5 //#define IR_USE_AVR_TIMER4_HS // send pin = pin 13 # endif // Nano Every, Uno WiFi Rev2 and similar #elif defined(__AVR_ATmega808__) || defined(__AVR_ATmega809__) || defined(__AVR_ATmega3208__) || defined(__AVR_ATmega3209__) \ || defined(__AVR_ATmega1608__) || defined(__AVR_ATmega1609__) || defined(__AVR_ATmega4808__) || defined(__AVR_ATmega4809__) || defined(__AVR_ATtiny1604__) # if !defined(IR_USE_AVR_TIMER_B) #define IR_USE_AVR_TIMER_B // send pin = pin 6 # endif // ATmega8u2, ATmega16U2, ATmega32U2 #elif defined(__AVR_ATmega8U2__) || defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega32U2__) # if !defined(IR_USE_AVR_TIMER1) #define IR_USE_AVR_TIMER1 // send pin = pin C6 # endif // Atmega8 #elif defined(__AVR_ATmega8__) # if !defined(IR_USE_AVR_TIMER1) #define IR_USE_AVR_TIMER1 // send pin = pin 9 # endif // ATtiny84 #elif defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny88__) # if !defined(IR_USE_AVR_TIMER1) #define IR_USE_AVR_TIMER1 // send pin = pin 6 # endif #elif defined(__AVR_ATtiny87__) || defined(__AVR_ATtiny167__) # if !defined(IR_USE_AVR_TIMER1) #define IR_USE_AVR_TIMER1 # endif #define USE_TIMER_CHANNEL_B // send pin = pin PB1 //ATtiny85 #elif defined(__AVR_ATtiny85__) # if !defined(IR_USE_AVR_TIMER_TINY0) && !defined(IR_USE_AVR_TIMER_TINY1) # if defined(ARDUINO_AVR_DIGISPARK) // tested with 16 and 8 MHz #define IR_USE_AVR_TIMER_TINY0 // send pin = pin 1 // standard Digispark settings use timer 1 for millis() and micros() # else // standard ATTinyCore settings use timer 0 for millis() and micros() #define IR_USE_AVR_TIMER_TINY1 // send pin = pin 4 # endif # endif /*************************************** * SPARKFUN Pro Micro board ***************************************/ #elif defined(ARDUINO_AVR_PROMICRO) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER3) && !defined(IR_USE_AVR_TIMER4_HS) //#define IR_USE_AVR_TIMER1 // send pin = pin 9 #define IR_USE_AVR_TIMER3 // send pin = pin 5 //#define IR_USE_AVR_TIMER4_HS // send pin = pin 13 # endif /*************************************** * TEENSY Boards ***************************************/ // Teensy 1.0 #elif defined(__AVR_AT90USB162__) # if !defined(IR_USE_AVR_TIMER1) #define IR_USE_AVR_TIMER1 // send pin = pin 17 # endif // Teensy++ 1.0 & 2.0 #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER2) && !defined(IR_USE_AVR_TIMER3) //#define IR_USE_AVR_TIMER1 // send pin = pin 25 #define IR_USE_AVR_TIMER2 // send pin = pin 1 //#define IR_USE_AVR_TIMER3 // send pin = pin 16 # endif // Teensy 2.0 #elif defined(__AVR_ATmega32U4__) && defined(TEENSYDUINO) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER3) && !defined(IR_USE_AVR_TIMER4_HS) //#define IR_USE_AVR_TIMER1 // send pin = pin 14 (Teensy 2.0 - physical pin: B5) #define IR_USE_AVR_TIMER3 // send pin = pin 9 (Teensy 2.0 - physical pin: C6) //#define IR_USE_AVR_TIMER4_HS // send pin = pin 10 (Teensy 2.0 - physical pin: C7) # endif /*************************************** * CPU's with MegaCore ***************************************/ // MegaCore - ATmega64, ATmega128 #elif defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2560__) # if !defined(IR_USE_AVR_TIMER1) #define IR_USE_AVR_TIMER1 // send pin = pin 13 # endif /*************************************** * CPU's with MajorCore ***************************************/ #elif defined(__AVR_ATmega8515__) || defined(__AVR_ATmega162__) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER3) #define IR_USE_AVR_TIMER1 // send pin = pin 13 //#define IR_USE_AVR_TIMER3 // send pin = pin 12 - ATmega162 only # endif /*************************************** * CPU's with MightyCore ***************************************/ // MightyCore - ATmega1284 #elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER2) && !defined(IR_USE_AVR_TIMER3) //#define IR_USE_AVR_TIMER1 // send pin = pin 13 #define IR_USE_AVR_TIMER2 // send pin = pin 14 //#define IR_USE_AVR_TIMER3 // send pin = pin 6 # endif // MightyCore - ATmega164, ATmega324, ATmega644 #elif defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \ || defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \ || defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \ || defined(__AVR_ATmega164P__) # if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER2) //#define IR_USE_AVR_TIMER1 // send pin = pin 13 #define IR_USE_AVR_TIMER2 // send pin = pin 14 # endif // MightyCore - ATmega8535, ATmega16, ATmega32 #elif defined(__AVR_ATmega8535__) || defined(__AVR_ATmega16__) || defined(__AVR_ATmega32__) # if !defined(IR_USE_AVR_TIMER1) #define IR_USE_AVR_TIMER1 // send pin = pin 13 # endif /*************************************** * CPU's with TinyCore ***************************************/ #elif defined(__AVR_ATtiny1616__) || defined(__AVR_ATtiny3216__) || defined(__AVR_ATtiny3217__) // TinyCore boards #define IR_USE_AVR_TIMER_D #endif // AVR CPU's /********************************************************************************************************************** * End of AVR mapping, start of AVR timers **********************************************************************************************************************/ /* * AVR Timer1 (16 bits) */ #if defined(IR_USE_AVR_TIMER1) # if defined(SEND_PWM_BY_TIMER) # if defined(CORE_OC1A_PIN) #define IR_SEND_PIN CORE_OC1A_PIN // Teensy # elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define IR_SEND_PIN 11 // Arduino Mega // MightyCore, MegaCore, MajorCore # elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \ || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \ || defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \ || defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \ || defined(__AVR_ATmega164P__) || defined(__AVR_ATmega32__) \ || defined(__AVR_ATmega16__) || defined(__AVR_ATmega8535__) \ || defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__) \ || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__) \ || defined(__AVR_ATmega8515__) || defined(__AVR_ATmega162__) #define IR_SEND_PIN 13 # elif defined(__AVR_ATtiny84__) #define IR_SEND_PIN 6 # elif defined(__AVR_ATtiny87__) || defined(__AVR_ATtiny167__) #define IR_SEND_PIN PIN_PB1 // OC1BU at ATTinyCore (BU/PB1, BV/PB3, BW/PB5 and BX/PB7 are available) see ENABLE_SEND_PWM_BY_TIMER # else #define IR_SEND_PIN 9 // OC1A Arduino Duemilanove, Diecimila, LilyPad, Sparkfun Pro Micro, Leonardo, MH-ET Tiny88 etc. # endif // defined(CORE_OC1A_PIN) # if defined(__AVR_ATtiny87__) || defined(__AVR_ATtiny167__) // Clear OC1A/OC1B on Compare Match when up-counting. Set OC1A/OC1B on Compare Match when downcounting. #define ENABLE_SEND_PWM_BY_TIMER TCNT1 = 0; (TCCR1A |= _BV(COM1A1); (TCCR1D |= _BV(OC1BU)) // + enable OC1BU as output #define DISABLE_SEND_PWM_BY_TIMER (TCCR1D = 0) # else #define ENABLE_SEND_PWM_BY_TIMER TCNT1 = 0; (TCCR1A |= _BV(COM1A1)) // Clear OC1A/OC1B on Compare Match when up-counting. Set OC1A/OC1B on Compare Match when downcounting. #define DISABLE_SEND_PWM_BY_TIMER (TCCR1A &= ~(_BV(COM1A1))) # endif # endif // defined(SEND_PWM_BY_TIMER) #define TIMER_RESET_INTR_PENDING # if defined(__AVR_ATmega8__) || defined(__AVR_ATmega8515__) \ || defined(__AVR_ATmega8535__) || defined(__AVR_ATmega16__) \ || defined(__AVR_ATmega32__) || defined(__AVR_ATmega64__) \ || defined(__AVR_ATmega128__) || defined(__AVR_ATmega162__) #define TIMER_ENABLE_RECEIVE_INTR (TIMSK |= _BV(OCIE1A)) #define TIMER_DISABLE_RECEIVE_INTR (TIMSK &= ~_BV(OCIE1A)) # else #define TIMER_ENABLE_RECEIVE_INTR (TIMSK1 = _BV(OCIE1A)) // Timer/Counter1, Output Compare A Match Interrupt Enable #define TIMER_DISABLE_RECEIVE_INTR (TIMSK1 = 0) # endif # if defined(USE_TIMER_CHANNEL_B) # if defined(TIMER1_COMPB_vect) #define TIMER_INTR_NAME TIMER1_COMPB_vect # elif defined(TIM1_COMPB_vect) #define TIMER_INTR_NAME TIM1_COMPB_vect # endif #else # if defined(TIMER1_COMPA_vect) #define TIMER_INTR_NAME TIMER1_COMPA_vect # elif defined(TIM1_COMPA_vect) #define TIMER_INTR_NAME TIM1_COMPA_vect # endif # endif void timerConfigForSend(uint8_t aFrequencyKHz) { # if (((F_CPU / 2000) / 38) < 256) const uint16_t pwmval = (F_CPU / 2000) / (aFrequencyKHz); // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of Phase Correct PWM TCCR1A = _BV(WGM11);// PWM, Phase Correct, Top is ICR1 TCCR1B = _BV(WGM13) | _BV(CS10);// CS10 -> no prescaling ICR1 = pwmval - 1; # if defined(USE_TIMER_CHANNEL_B) OCR1A = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; # else OCR1A = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; # endif TCNT1 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible # else const uint16_t pwmval = ((F_CPU / 8) / 2000) / (aFrequencyKHz); // 2000 instead of 1000 because of Phase Correct PWM TCCR1A = _BV(WGM11);// PWM, Phase Correct, Top is ICR1 TCCR1B = _BV(WGM13) | _BV(CS11);// CS11 -> Prescaling by 8 ICR1 = pwmval - 1; # if defined(USE_TIMER_CHANNEL_B) OCR1A = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; # else OCR1A = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; # endif TCNT1 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible # endif } void timerConfigForReceive() { TCCR1A = 0; TCCR1B = _BV(WGM12) | _BV(CS10); OCR1A = F_CPU * MICROS_PER_TICK / 1000000; TCNT1 = 0; } /* * AVR Timer2 (8 bits) */ #elif defined(IR_USE_AVR_TIMER2) # if defined(SEND_PWM_BY_TIMER) # if defined(CORE_OC2B_PIN) #define IR_SEND_PIN CORE_OC2B_PIN // Teensy # elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define IR_SEND_PIN 9 // Arduino Mega # elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \ || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \ || defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \ || defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \ || defined(__AVR_ATmega164P__) #define IR_SEND_PIN 14 // MightyCore, MegaCore # else #define IR_SEND_PIN 3 // Arduino Duemilanove, Diecimila, LilyPad, etc # endif // defined(CORE_OC2B_PIN) #define ENABLE_SEND_PWM_BY_TIMER TCNT2 = 0; (TCCR2A |= _BV(COM2B1)) // Clear OC2B on Compare Match #define DISABLE_SEND_PWM_BY_TIMER (TCCR2A &= ~(_BV(COM2B1))) // Normal port operation, OC2B disconnected. # endif // defined(SEND_PWM_BY_TIMER) #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR (TIMSK2 = _BV(OCIE2B)) // Output Compare Match A Interrupt Enable #define TIMER_DISABLE_RECEIVE_INTR (TIMSK2 = 0) #define TIMER_INTR_NAME TIMER2_COMPB_vect // We use TIMER2_COMPB_vect to be compatible with tone() library // The top value for the timer. The modulation frequency will be F_CPU / 2 / OCR2A. #pragma GCC diagnostic ignored "-Wunused-function" /* * timerConfigForSend() is used exclusively by IRsend::enableIROut() */ void timerConfigForSend(uint8_t aFrequencyKHz) { # if (((F_CPU / 2000) / 38) < 256) const uint16_t pwmval = (F_CPU / 2000) / (aFrequencyKHz); // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of Phase Correct PWM TCCR2A = _BV(WGM20);// PWM, Phase Correct, Top is OCR2A TCCR2B = _BV(WGM22) | _BV(CS20);// CS20 -> no prescaling OCR2A = pwmval - 1; OCR2B = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT2 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible # else const uint16_t pwmval = ((F_CPU / 8) / 2000) / (aFrequencyKHz); // 2000 instead of 1000 because of Phase Correct PWM TCCR2A = _BV(WGM20);// PWM, Phase Correct, Top is OCR2A TCCR2B = _BV(WGM22) | _BV(CS21);// CS21 -> Prescaling by 8 OCR2A = pwmval - 1; OCR2B = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT2 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible # endif } #define TIMER_COUNT_TOP (F_CPU * MICROS_PER_TICK / 1000000) /* * timerConfigForReceive() is used exclusively by IRrecv::enableIRIn() * It generates an interrupt each 50 (MICROS_PER_TICK) us. */ void timerConfigForReceive() { # if (TIMER_COUNT_TOP < 256) TCCR2A = _BV(WGM21); TCCR2B = _BV(CS20); OCR2A = TIMER_COUNT_TOP; OCR2B = TIMER_COUNT_TOP; TCNT2 = 0; # else TCCR2A = _BV(WGM21); TCCR2B = _BV(CS21); OCR2A = TIMER_COUNT_TOP / 8; OCR2B = TIMER_COUNT_TOP / 8; TCNT2 = 0; # endif } /* * AVR Timer3 (16 bits) */ #elif defined(IR_USE_AVR_TIMER3) # if defined(SEND_PWM_BY_TIMER) # if defined(CORE_OC3A_PIN) #define IR_SEND_PIN CORE_OC3A_PIN // Teensy # elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) \ || defined(__AVR_ATmega32U4__) || defined(ARDUINO_AVR_PROMICRO) #define IR_SEND_PIN 5 // Arduino Mega, Arduino Leonardo, Sparkfun Pro Micro # elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) #define IR_SEND_PIN 6 // MightyCore, MegaCore # else #error Please add OC3A pin number here # endif #define ENABLE_SEND_PWM_BY_TIMER TCNT3 = 0; (TCCR3A |= _BV(COM3A1)) #define DISABLE_SEND_PWM_BY_TIMER (TCCR3A &= ~(_BV(COM3A1))) # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR (TIMSK3 = _BV(OCIE3B)) #define TIMER_DISABLE_RECEIVE_INTR (TIMSK3 = 0) #define TIMER_INTR_NAME TIMER3_COMPB_vect void timerConfigForSend(uint8_t aFrequencyKHz) { #if defined(SEND_PWM_BY_TIMER) && F_CPU > 16000000 #error "Creating timer PWM with timer 3 is not supported for F_CPU > 16 MHz" #endif const uint16_t pwmval = (F_CPU / 2000) / (aFrequencyKHz); // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of Phase Correct PWM TCCR3A = _BV(WGM31); TCCR3B = _BV(WGM33) | _BV(CS30);// PWM, Phase Correct, ICRn as TOP, complete period is double of pwmval ICR3 = pwmval - 1; OCR3A = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT3 = 0;// required, since we have an 16 bit counter } void timerConfigForReceive() { TCCR3A = 0; TCCR3B = _BV(WGM32) | _BV(CS30); OCR3A = F_CPU * MICROS_PER_TICK / 1000000; OCR3B = F_CPU * MICROS_PER_TICK / 1000000; TCNT3 = 0; } /* * AVR Timer4 (16 bits) */ #elif defined(IR_USE_AVR_TIMER4) # if defined(SEND_PWM_BY_TIMER) # if defined(CORE_OC4A_PIN) #define IR_SEND_PIN CORE_OC4A_PIN # elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define IR_SEND_PIN 6 // Arduino Mega # else #error Please add OC4A pin number here # endif #define ENABLE_SEND_PWM_BY_TIMER TCNT4 = 0; (TCCR4A |= _BV(COM4A1)) #define DISABLE_SEND_PWM_BY_TIMER (TCCR4A &= ~(_BV(COM4A1))) # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR (TIMSK4 = _BV(OCIE4A)) #define TIMER_DISABLE_RECEIVE_INTR (TIMSK4 = 0) #define TIMER_INTR_NAME TIMER4_COMPA_vect void timerConfigForSend(uint8_t aFrequencyKHz) { #if defined(SEND_PWM_BY_TIMER) && F_CPU > 16000000 #error "Creating timer PWM with timer 4 is not supported for F_CPU > 16 MHz" #endif const uint16_t pwmval = (F_CPU / 2000) / (aFrequencyKHz); // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of Phase Correct PWM TCCR4A = _BV(WGM41); TCCR4B = _BV(WGM43) | _BV(CS40); ICR4 = pwmval - 1; OCR4A = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT4 = 0;// required, since we have an 16 bit counter } void timerConfigForReceive() { TCCR4A = 0; TCCR4B = _BV(WGM42) | _BV(CS40); OCR4A = F_CPU * MICROS_PER_TICK / 1000000; TCNT4 = 0; } /* * AVR Timer4 (10 bits, high speed option) */ #elif defined(IR_USE_AVR_TIMER4_HS) # if defined(SEND_PWM_BY_TIMER) # if defined(CORE_OC4A_PIN) #define IR_SEND_PIN CORE_OC4A_PIN // Teensy # elif defined(ARDUINO_AVR_PROMICRO) #define IR_SEND_PIN 5 // Sparkfun Pro Micro # elif defined(__AVR_ATmega32U4__) #define IR_SEND_PIN 13 // Leonardo # else #error Please add OC4A pin number here # endif # if defined(ARDUINO_AVR_PROMICRO) // Sparkfun Pro Micro #define ENABLE_SEND_PWM_BY_TIMER TCNT4 = 0; (TCCR4A |= _BV(COM4A0)) // Use complementary OC4A output on pin 5 #define DISABLE_SEND_PWM_BY_TIMER (TCCR4A &= ~(_BV(COM4A0))) // (Pro Micro does not map PC7 (32/ICP3/CLK0/OC4A) // of ATmega32U4 ) # else #define ENABLE_SEND_PWM_BY_TIMER TCNT4 = 0; (TCCR4A |= _BV(COM4A1)) #define DISABLE_SEND_PWM_BY_TIMER (TCCR4A &= ~(_BV(COM4A1))) # endif # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR (TIMSK4 = _BV(TOIE4)) #define TIMER_DISABLE_RECEIVE_INTR (TIMSK4 = 0) #define TIMER_INTR_NAME TIMER4_OVF_vect void timerConfigForSend(uint8_t aFrequencyKHz) { #if defined(SEND_PWM_BY_TIMER) && F_CPU > 16000000 #error "Creating timer PWM with timer 4 HS is not supported for F_CPU > 16 MHz" #endif const uint16_t pwmval = ((F_CPU / 2000) / (aFrequencyKHz)) - 1; // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of Phase Correct PWM TCCR4A = (1 << PWM4A); TCCR4B = _BV(CS40); TCCR4C = 0; TCCR4D = (1 << WGM40); TCCR4E = 0; TC4H = pwmval >> 8; OCR4C = pwmval; TC4H = (pwmval * IR_SEND_DUTY_CYCLE / 100) >> 8; OCR4A = (pwmval * IR_SEND_DUTY_CYCLE / 100) & 255; TCNT4 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible } void timerConfigForReceive() { TCCR4A = 0; TCCR4B = _BV(CS40); TCCR4C = 0; TCCR4D = 0; TCCR4E = 0; TC4H = (F_CPU * MICROS_PER_TICK / 1000000) >> 8; OCR4C = (F_CPU * MICROS_PER_TICK / 1000000) & 255; TC4H = 0; TCNT4 = 0; } /* * AVR Timer5 (16 bits) */ #elif defined(IR_USE_AVR_TIMER5) # if defined(SEND_PWM_BY_TIMER) # if defined(CORE_OC5A_PIN) #define IR_SEND_PIN CORE_OC5A_PIN # elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #define IR_SEND_PIN 46 // Arduino Mega # else #error Please add OC5A pin number here # endif #define ENABLE_SEND_PWM_BY_TIMER TCNT5 = 0; (TCCR5A |= _BV(COM5A1)) #define DISABLE_SEND_PWM_BY_TIMER (TCCR5A &= ~(_BV(COM5A1))) # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR (TIMSK5 = _BV(OCIE5A)) #define TIMER_DISABLE_RECEIVE_INTR (TIMSK5 = 0) #define TIMER_INTR_NAME TIMER5_COMPA_vect void timerConfigForSend(uint8_t aFrequencyKHz) { #if defined(SEND_PWM_BY_TIMER) && F_CPU > 16000000 #error "Creating timer PWM with timer 5 is not supported for F_CPU > 16 MHz" #endif const uint16_t pwmval = (F_CPU / 2000) / (aFrequencyKHz); // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of Phase Correct PWM TCCR5A = _BV(WGM51); TCCR5B = _BV(WGM53) | _BV(CS50); ICR5 = pwmval - 1; OCR5A = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT5 = 0;// required, since we have an 16 bit counter } void timerConfigForReceive() { TCCR5A = 0; TCCR5B = _BV(WGM52) | _BV(CS50); OCR5A = F_CPU * MICROS_PER_TICK / 1000000; TCNT5 = 0; } /* * AVR Timer0 for ATtinies (8 bits) */ #elif defined(IR_USE_AVR_TIMER_TINY0) # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN 1 #define ENABLE_SEND_PWM_BY_TIMER TCNT0 = 0; (TCCR0A |= _BV(COM0B1)) #define DISABLE_SEND_PWM_BY_TIMER (TCCR0A &= ~(_BV(COM0B1))) # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR (TIMSK |= _BV(OCIE0A)) #define TIMER_DISABLE_RECEIVE_INTR (TIMSK &= ~(_BV(OCIE0A))) #define TIMER_INTR_NAME TIMER0_COMPA_vect void timerConfigForSend(uint8_t aFrequencyKHz) { #if defined(SEND_PWM_BY_TIMER) && F_CPU > 16000000 #error "Creating timer PWM with timer TINY0 is not supported for F_CPU > 16 MHz" #endif const uint16_t pwmval = (F_CPU / 2000) / (aFrequencyKHz); // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of Phase Correct PWM TCCR0A = _BV(WGM00);// PWM, Phase Correct, Top is OCR0A TCCR0B = _BV(WGM02) | _BV(CS00);// CS00 -> no prescaling OCR0A = pwmval - 1; OCR0B = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT0 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible } #define TIMER_COUNT_TOP (F_CPU * MICROS_PER_TICK / 1000000) void timerConfigForReceive() { # if (TIMER_COUNT_TOP < 256) TCCR0A = _BV(WGM01); // CTC, Top is OCR0A TCCR0B = _BV(CS00);// No prescaling OCR0A = TIMER_COUNT_TOP; TCNT0 = 0; # else TCCR0A = _BV(WGM01); TCCR0B = _BV(CS01); // prescaling by 8 OCR0A = TIMER_COUNT_TOP / 8; TCNT0 = 0; # endif } /* * AVR Timer1 for ATtinies (8 bits) */ #elif defined(IR_USE_AVR_TIMER_TINY1) # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN 4 #define ENABLE_SEND_PWM_BY_TIMER TCNT1 = 0; GTCCR |= _BV(PWM1B) | _BV(COM1B0) // Enable pin 4 PWM output (PB4 - Arduino D4) #define DISABLE_SEND_PWM_BY_TIMER (GTCCR &= ~(_BV(PWM1B) | _BV(COM1B0))) # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR (TIMSK |= _BV(OCIE1B)) #define TIMER_DISABLE_RECEIVE_INTR (TIMSK &= ~(_BV(OCIE1B))) #define TIMER_INTR_NAME TIMER1_COMPB_vect void timerConfigForSend(uint8_t aFrequencyKHz) { # if (((F_CPU / 1000) / 38) < 256) const uint16_t pwmval = (F_CPU / 1000) / (aFrequencyKHz); // 421 @16 MHz, 26 @1 MHz and 38 kHz TCCR1 = _BV(CTC1) | _BV(CS10);// CTC1 = 1: TOP value set to OCR1C, CS10 No Prescaling OCR1C = pwmval - 1; OCR1B = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT1 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible GTCCR = _BV(PWM1B) | _BV(COM1B0);// PWM1B = 1: Enable PWM for OCR1B, COM1B0 Clear on compare match # else const uint16_t pwmval = ((F_CPU / 2) / 1000) / (aFrequencyKHz); // 210 for 16 MHz and 38 kHz TCCR1 = _BV(CTC1) | _BV(CS11);// CTC1 = 1: TOP value set to OCR1C, CS11 Prescaling by 2 OCR1C = pwmval - 1; OCR1B = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; TCNT1 = 0;// not really required, since we have an 8 bit counter, but makes the signal more reproducible GTCCR = _BV(PWM1B) | _BV(COM1B0);// PWM1B = 1: Enable PWM for OCR1B, COM1B0 Clear on compare match # endif } #define TIMER_COUNT_TOP (F_CPU * MICROS_PER_TICK / 1000000) void timerConfigForReceive() { # if (TIMER_COUNT_TOP < 256) TCCR1 = _BV(CTC1) | _BV(CS10); // Clear Timer/Counter on Compare Match, Top is OCR1C, No prescaling GTCCR = 0; // normal, non-PWM mode OCR1C = TIMER_COUNT_TOP; TCNT1 = 0; # else TCCR1 = _BV(CTC1) | _BV(CS12); // Clear Timer/Counter on Compare Match, Top is OCR1C, prescaling by 8 GTCCR = 0; // normal, non-PWM mode OCR1C = TIMER_COUNT_TOP / 8; TCNT1 = 0; # endif } /* * AVR TimerB for Nano Every, Uno WiFi Rev2 (8 bits) */ #elif defined(IR_USE_AVR_TIMER_B) # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN A4 // PA2 - A4 on Nano Every, PA5 on ATtiny1604 #define ENABLE_SEND_PWM_BY_TIMER TCB0.CNT = 0; (TCB0.CTRLB |= TCB_CCMPEN_bm) #define DISABLE_SEND_PWM_BY_TIMER (TCB0.CTRLB &= ~(TCB_CCMPEN_bm)) # endif // ATmega4809 TCB0 #define TIMER_RESET_INTR_PENDING TCB0.INTFLAGS = TCB_CAPT_bm #define TIMER_ENABLE_RECEIVE_INTR (TCB0.INTCTRL = TCB_CAPT_bm) #define TIMER_DISABLE_RECEIVE_INTR (TCB0.INTCTRL &= ~(TCB_CAPT_bm)) #define TIMER_INTR_NAME TCB0_INT_vect void timerConfigForSend(uint8_t aFrequencyKHz) { #if defined(SEND_PWM_BY_TIMER) && F_CPU > 16000000 // we have only prescaler 2 or must take clock of timer A (which is non deterministic) #error "Creating timer PWM with timer TCB0 is not possible for F_CPU > 16 MHz" #endif const uint16_t pwmval = (F_CPU / 2000) / (aFrequencyKHz); // 210,52 for 38 kHz @16 MHz clock, 2000 instead of 1000 because of using CLK / 2 TCB0.CTRLB = TCB_CNTMODE_PWM8_gc; // 8 bit PWM mode TCB0.CCMPL = pwmval - 1; // Period of 8 bit PWM TCB0.CCMPH = ((pwmval * IR_SEND_DUTY_CYCLE) / 100) - 1; // Duty cycle of waveform of 8 bit PWM TCB0.CTRLA = (TCB_CLKSEL_CLKDIV2_gc) | (TCB_ENABLE_bm); // use CLK / 2 TCB0.CNT = 0; // not really required, since we have an 8 bit counter, but makes the signal more reproducible } void timerConfigForReceive() { TCB0.CTRLB = (TCB_CNTMODE_INT_gc); // Periodic interrupt mode TCB0.CCMP = ((F_CPU * MICROS_PER_TICK) / 1000000); TCB0.INTFLAGS = TCB_CAPT_bm; // reset interrupt flags TCB0.CTRLA = (TCB_CLKSEL_CLKDIV1_gc) | (TCB_ENABLE_bm); } /* * AVR TimerD for TinyCore 32 (16 bits) */ #elif defined(IR_USE_AVR_TIMER_D) # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN 13 #define ENABLE_SEND_PWM_BY_TIMER (timerEnablSendPWM()) #define DISABLE_SEND_PWM_BY_TIMER (TCD0.CTRLA = 0) // do not disable output, disable complete timer # endif #define TIMER_RESET_INTR_PENDING (TCD0.INTFLAGS = TCD_OVF_bm) #define TIMER_ENABLE_RECEIVE_INTR (TCD0.INTCTRL = TCD_OVF_bm) #define TIMER_DISABLE_RECEIVE_INTR (TCD0.INTCTRL = 0) #define TIMER_INTR_NAME TCD0_OVF_vect void timerEnablSendPWM() { TCD0.CTRLA = 0; // reset enable bit in order to unprotect the other bits _PROTECTED_WRITE(TCD0.FAULTCTRL, FUSE_CMPAEN_bm);// enable WOA output at pin 13/PA4 // _PROTECTED_WRITE(TCD0.FAULTCTRL, FUSE_CMPAEN_bm | FUSE_CMPBEN_bm); // enable WOA + WOB output pins at 13/PA4 + 14/PA5 TCD0.CTRLA = TCD_ENABLE_bm | TCD_CLKSEL_SYSCLK_gc| TCD_CNTPRES_DIV1_gc;// System clock, no prescale, no synchronization prescaler } void timerConfigForSend(uint8_t aFrequencyKHz) { const uint16_t pwmval = (F_CPU / 1000) / (aFrequencyKHz); // 526,31 for 38 kHz @20 MHz clock // use one ramp mode and overflow interrupt TCD0.CTRLA = 0;// reset enable bit in order to unprotect the other bits // while ((TCD0.STATUS & TCD_ENRDY_bm) == 0); // Wait for Enable Ready to be high - I guess it is not required TCD0.CTRLB = TCD_WGMODE_ONERAMP_gc;// must be set since it is used by PWM TCD0.CTRLC = 0;// reset WOx output settings // TCD0.CMPBSET = 80; TCD0.CMPBCLR = pwmval - 1; // Generate duty cycle signal for debugging etc. TCD0.CMPASET = 0; TCD0.CMPACLR = (pwmval * IR_SEND_DUTY_CYCLE / 100) - 1;// duty cycle for WOA TCD0.INTFLAGS = TCD_OVF_bm;// reset interrupt flags TCD0.INTCTRL = TCD_OVF_bm;// overflow interrupt // Do not enable timer, this is done at timerEnablSendPWM() } void timerConfigForReceive() { TCD0.CTRLA = 0; // reset enable bit in order to unprotect the other bits TCD0.CTRLB = TCD_WGMODE_ONERAMP_gc;// must be set since it is used by PWM // TCD0.CMPBSET = 80; TCD0.CMPBCLR = ((F_CPU * MICROS_PER_TICK) / 1000000) - 1; _PROTECTED_WRITE(TCD0.FAULTCTRL, 0);// must disable WOA output at pin 13/PA4 TCD0.INTFLAGS = TCD_OVF_bm; // reset interrupt flags // TCD0.INTCTRL = TCD_OVF_bm; // overflow interrupt // check enable ready // while ((TCD0.STATUS & TCD_ENRDY_bm) == 0); // Wait for Enable Ready to be high - I guess it is not required // enable timer - this locks the other bits and static registers and activates values in double buffered registers TCD0.CTRLA = TCD_ENABLE_bm | TCD_CLKSEL_SYSCLK_gc| TCD_CNTPRES_DIV1_gc;// System clock, no prescale, no synchronization prescaler } #else #error Internal code configuration error, no timer functions implemented for this AVR CPU / board #endif //defined(IR_USE_AVR_TIMER*) /********************************************************************************************************************** * End of AVR timers **********************************************************************************************************************/ /*************************************** * Teensy 3.0 / Teensy 3.1 boards ***************************************/ #elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN 5 #define ENABLE_SEND_PWM_BY_TIMER do { CORE_PIN5_CONFIG = PORT_PCR_MUX(2) | PORT_PCR_DSE | PORT_PCR_SRE; } while(0) #define DISABLE_SEND_PWM_BY_TIMER do { CORE_PIN5_CONFIG = PORT_PCR_MUX(1) | PORT_PCR_DSE | PORT_PCR_SRE; } while(0) # endif // Special carrier modulator timer for Teensy 3.0 / Teensy 3.1 #define TIMER_RESET_INTR_PENDING uint8_t tmp __attribute__((unused)) = CMT_MSC; CMT_CMD2 = 30 #define TIMER_ENABLE_RECEIVE_INTR NVIC_ENABLE_IRQ(IRQ_CMT) #define TIMER_DISABLE_RECEIVE_INTR NVIC_DISABLE_IRQ(IRQ_CMT) #define TIMER_INTR_NAME cmt_isr # ifdef ISR #undef ISR # endif #define ISR(f) void do_not_use__(void) #define CMT_PPS_DIV ((F_BUS + 7999999) / 8000000) # if F_BUS < 8000000 #error IRremote requires at least 8 MHz on Teensy 3.x # endif void timerConfigForSend(uint8_t aFrequencyKHz) { SIM_SCGC4 |= SIM_SCGC4_CMT; SIM_SOPT2 |= SIM_SOPT2_PTD7PAD; CMT_PPS = CMT_PPS_DIV - 1; CMT_CGH1 = ((F_BUS / CMT_PPS_DIV / 3000) + ((aFrequencyKHz) / 2)) / (aFrequencyKHz); CMT_CGL1 = ((F_BUS / CMT_PPS_DIV / 1500) + ((aFrequencyKHz) / 2)) / (aFrequencyKHz); CMT_CMD1 = 0; CMT_CMD2 = 30; CMT_CMD3 = 0; CMT_CMD4 = 0; CMT_OC = 0x60; CMT_MSC = 0x01; } void timerConfigForReceive() { SIM_SCGC4 |= SIM_SCGC4_CMT; CMT_PPS = CMT_PPS_DIV - 1; CMT_CGH1 = 1; CMT_CGL1 = 1; CMT_CMD1 = 0; CMT_CMD2 = 30; CMT_CMD3 = 0; CMT_CMD4 = (F_BUS / 160000 + CMT_PPS_DIV / 2) / CMT_PPS_DIV - 31; CMT_OC = 0; CMT_MSC = 0x03; } /*************************************** * Teensy-LC board ***************************************/ #elif defined(__MKL26Z64__) # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN 16 #define ENABLE_SEND_PWM_BY_TIMER FTM1_CNT = 0; CORE_PIN16_CONFIG = PORT_PCR_MUX(3)|PORT_PCR_DSE|PORT_PCR_SRE #define DISABLE_SEND_PWM_BY_TIMER CORE_PIN16_CONFIG = PORT_PCR_MUX(1)|PORT_PCR_SRE # endif // defines for TPM1 timer on Teensy-LC #define TIMER_RESET_INTR_PENDING FTM1_SC |= FTM_SC_TOF; #define TIMER_ENABLE_RECEIVE_INTR NVIC_ENABLE_IRQ(IRQ_FTM1) #define TIMER_DISABLE_RECEIVE_INTR NVIC_DISABLE_IRQ(IRQ_FTM1) #define TIMER_INTR_NAME ftm1_isr # ifdef ISR #undef ISR # endif #define ISR(f) void do_not_use__(void) void timerConfigForSend(uint8_t aFrequencyKHz) { SIM_SCGC6 |= SIM_SCGC6_TPM1; FTM1_SC = 0; FTM1_CNT = 0; FTM1_MOD = ((F_PLL / 2000) / aFrequencyKHz) - 1; FTM1_C0V = ((F_PLL / 6000) / aFrequencyKHz) - 1; FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(0); } void timerConfigForReceive() { SIM_SCGC6 |= SIM_SCGC6_TPM1; FTM1_SC = 0; FTM1_CNT = 0; FTM1_MOD = (F_PLL / 40000) - 1; FTM1_C0V = 0; FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(0) | FTM_SC_TOF | FTM_SC_TOIE; } #elif defined(ESP8266) #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR timer1_attachInterrupt(&IRTimerInterruptHandler) // enables interrupt too #define TIMER_DISABLE_RECEIVE_INTR timer1_detachInterrupt() // disables interrupt too // Redefinition of ISR macro which creates a plain function now # ifdef ISR #undef ISR # endif #define ISR() ICACHE_RAM_ATTR void IRTimerInterruptHandler() ICACHE_RAM_ATTR void IRTimerInterruptHandler(); #ifdef SEND_PWM_BY_TIMER #error "No support for hardware PWM generation for ESP8266" #endif void timerConfigForSend(uint8_t aFrequencyKHz) { (void) aFrequencyKHz; } /* * Set timer for interrupts every MICROS_PER_TICK (50 us) */ void timerConfigForReceive() { timer1_isr_init(); /* * TIM_DIV1 = 0, //80MHz (80 ticks/us - 104857.588 us max) * TIM_DIV16 = 1, //5MHz (5 ticks/us - 1677721.4 us max) * TIM_DIV256 = 3 //312.5Khz (1 tick = 3.2us - 26843542.4 us max) */ timer1_enable(TIM_DIV16, TIM_EDGE, TIM_LOOP); timer1_write((80 / 16) * MICROS_PER_TICK); // 80 for 80 and 160! MHz clock, 16 for TIM_DIV16 above } /*************************************** * ESP32 boards - can use any pin for timer ***************************************/ #elif defined(ESP32) //# if defined(SEND_PWM_BY_TIMER) #if !defined(IR_SEND_PIN) #define IR_SEND_PIN IR_TX // can use any pin, no timer restrictions #endif #define ENABLE_SEND_PWM_BY_TIMER ledcWrite(LED_CHANNEL, IR_SEND_DUTY_CYCLE) // we must use channel here not pin number #define DISABLE_SEND_PWM_BY_TIMER ledcWrite(LED_CHANNEL, 0) //# endif # if ! defined(LED_CHANNEL) #define LED_CHANNEL 0 // The channel used for PWM 0 to 7 are high speed PWM channels # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR timerAlarmEnable(timer) #define TIMER_DISABLE_RECEIVE_INTR timerEnd(timer); timerDetachInterrupt(timer) // Redefinition of ISR macro which creates a plain function now # ifdef ISR #undef ISR # endif #define ISR() IRAM_ATTR void IRTimerInterruptHandler() IRAM_ATTR void IRTimerInterruptHandler(); // Variables specific to the ESP32. // the ledc functions behave like hardware timers for us :-), so we do not require our own soft PWM generation code. hw_timer_t *timer; void timerConfigForSend(uint8_t aFrequencyKHz) { ledcSetup(LED_CHANNEL, aFrequencyKHz * 1000, 8); // 8 bit PWM resolution ledcAttachPin(IrSender.sendPin, LED_CHANNEL);// bind pin to channel } /* * Set timer for interrupts every MICROS_PER_TICK (50 us) */ void timerConfigForReceive() { // ESP32 has a proper API to setup timers, no weird chip macros needed // simply call the readable API versions :) // 3 timers, choose #1, 80 divider for microsecond precision @80MHz clock, count_up = true timer = timerBegin(1, 80, true); timerAttachInterrupt(timer, &IRTimerInterruptHandler, 1); // every 50 us, autoreload = true timerAlarmWrite(timer, MICROS_PER_TICK, true); } /*************************************** * SAMD boards like DUE and Zero ***************************************/ #elif defined(ARDUINO_ARCH_SAMD) # if defined(SEND_PWM_BY_TIMER) #error PWM generation by hardware not implemented for SAMD # endif # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN 9 # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR NVIC_EnableIRQ(TC3_IRQn) #define TIMER_DISABLE_RECEIVE_INTR NVIC_DisableIRQ(TC3_IRQn) // or TC3->COUNT16.CTRLA.reg &= ~TC_CTRLA_ENABLE; // Redefinition of ISR macro which creates a plain function now # ifdef ISR #undef ISR # endif #define ISR(f) void IRTimerInterruptHandler(void) // ATSAMD Timer IRQ functions void IRTimerInterruptHandler(); #define TIMER_PRESCALER_DIV 64 // use timer 3 hard coded here // functions based on setup from GitHub jdneo/timerInterrupt.ino void setTimerFrequency(unsigned int aFrequencyHz) { int compareValue = (F_CPU / (TIMER_PRESCALER_DIV * aFrequencyHz)) - 1; //Serial.println(compareValue); TcCount16 *TC = (TcCount16*) TC3; // Make sure the count is in a proportional position to where it was // to prevent any jitter or disconnect when changing the compare value. TC->COUNT.reg = map(TC->COUNT.reg, 0, TC->CC[0].reg, 0, compareValue); TC->CC[0].reg = compareValue; //Serial.print("COUNT.reg "); //Serial.println(TC->COUNT.reg); //Serial.print("CC[0].reg "); //Serial.println(TC->CC[0].reg); while (TC->STATUS.bit.SYNCBUSY == 1) { } } /* * Set timer for interrupts every MICROS_PER_TICK (50 us) */ void timerConfigForReceive() { REG_GCLK_CLKCTRL = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_TCC2_TC3); while (GCLK->STATUS.bit.SYNCBUSY == 1) { } TcCount16 *TC = (TcCount16*) TC3; // The TC should be disabled before the TC is reset in order to avoid undefined behavior. TC->CTRLA.reg &= ~TC_CTRLA_ENABLE; // When write-synchronization is ongoing for a register, any subsequent write attempts to this register will be discarded, and an error will be reported. while (TC->STATUS.bit.SYNCBUSY == 1) { } // wait for sync // Reset TCx TC->CTRLA.reg = TC_CTRLA_SWRST; // When writing a �1� to the CTRLA.SWRST bit it will immediately read as �1�. // CTRL.SWRST will be cleared by hardware when the peripheral has been reset. while (TC->CTRLA.bit.SWRST) { } // Use the 16-bit timer // Use match mode so that the timer counter resets when the count matches the compare register // Set prescaler to 64 TC->CTRLA.reg |= TC_CTRLA_MODE_COUNT16 | TC_CTRLA_WAVEGEN_MFRQ | TC_CTRLA_PRESCALER_DIV64 | TC_CTRLA_ENABLE; setTimerFrequency(1000000 / MICROS_PER_TICK); // Enable the compare interrupt TC->INTENSET.reg = 0; TC->INTENSET.bit.MC0 = 1; } void TC3_Handler(void) { TcCount16 *TC = (TcCount16*) TC3; // If this interrupt is due to the compare register matching the timer count // we toggle the LED. if (TC->INTFLAG.bit.MC0 == 1) { TC->INTFLAG.bit.MC0 = 1; IRTimerInterruptHandler(); } } /*************************************** * NRF5 boards like the BBC:Micro ***************************************/ #elif defined(NRF5) || defined(ARDUINO_ARCH_NRF52840) # if defined(SEND_PWM_BY_TIMER) #error PWM generation by hardware not implemented for NRF5 # endif # if defined(SEND_PWM_BY_TIMER) // The default pin used used for sending. 3, A0 - left pad #define IR_SEND_PIN 3 // dummy since sending not yet supported # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR NVIC_EnableIRQ(TIMER2_IRQn); #define TIMER_DISABLE_RECEIVE_INTR NVIC_DisableIRQ(TIMER2_IRQn); # ifdef ISR #undef ISR # endif #define ISR(f) void IRTimerInterruptHandler(void) void IRTimerInterruptHandler(); /* * Set timer for interrupts every MICROS_PER_TICK (50 us) */ void timerConfigForReceive() { NRF_TIMER2->MODE = TIMER_MODE_MODE_Timer; // Set the timer in Timer Mode NRF_TIMER2->TASKS_CLEAR = 1;// clear the task first to be usable for later NRF_TIMER2->PRESCALER = 4;// f TIMER = 16 MHz / (2 ^ PRESCALER ) : 4 -> 1 MHz, 1 uS NRF_TIMER2->BITMODE = TIMER_BITMODE_BITMODE_16Bit;//Set counter to 16 bit resolution NRF_TIMER2->CC[0] = MICROS_PER_TICK;//Set value for TIMER2 compare register 0, to trigger every 50 uS NRF_TIMER2->CC[1] = 0;//Set value for TIMER2 compare register 1 // Enable interrupt on Timer 2, for CC[0] compare match events NRF_TIMER2->INTENSET = (TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos); NRF_TIMER2->TASKS_START = 1;// Start TIMER2 // timerAttachInterrupt(timer, &IRTimerInterruptHandler, 1); } /** TIMTER2 peripheral interrupt handler. This interrupt handler is called whenever there it a TIMER2 interrupt * Don't mess with this line. really. */ extern "C" { void TIMER2_IRQHandler(void) { // Interrupt Service Routine - Fires every 50uS if ((NRF_TIMER2->EVENTS_COMPARE[0] != 0) && ((NRF_TIMER2->INTENSET & TIMER_INTENSET_COMPARE0_Msk) != 0)) { NRF_TIMER2->EVENTS_COMPARE[0] = 0; //Clear compare register 0 event IRTimerInterruptHandler();// call the IR-receive function NRF_TIMER2->CC[0] += 50; } } } /********************************************************************************************************************** * BluePill in 2 flavors see https://samuelpinches.com.au/3d-printer/cutting-through-some-confusion-on-stm32-and-arduino/ * * Recommended original Arduino_STM32 by <NAME>. * http://dan.drown.org/stm32duino/package_STM32duino_index.json * STM32F1 architecture for "Generic STM32F103C series" from "STM32F1 Boards (Arduino_STM32)" of Arduino Board manager **********************************************************************************************************************/ #elif defined(__STM32F1__) || defined(ARDUINO_ARCH_STM32F1) #include <HardwareTimer.h> // 4 timers and 4. timer (4.channel) is used for tone() # if defined(SEND_PWM_BY_TIMER) #error PWM generation by hardware not implemented for STM32 # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR sSTM32Timer.resume() #define TIMER_DISABLE_RECEIVE_INTR sSTM32Timer.pause() // Redefinition of ISR macro which creates a plain function now # ifdef ISR #undef ISR # endif #define ISR() void IRTimerInterruptHandler(void) void IRTimerInterruptHandler(); /* * Use timer 3 as IRMP timer. * Timer 3 blocks PA6, PA7, PB0, PB1, so if you require one of them as tone() or Servo output, you must choose another timer. */ HardwareTimer sSTM32Timer(3); /* * Set timer for interrupts every MICROS_PER_TICK (50 us) */ void timerConfigForReceive() { sSTM32Timer.setMode(TIMER_CH1, TIMER_OUTPUT_COMPARE); sSTM32Timer.setPrescaleFactor(1); sSTM32Timer.setOverflow((F_CPU / 1000000) * MICROS_PER_TICK); sSTM32Timer.attachInterrupt(TIMER_CH1, IRTimerInterruptHandler); sSTM32Timer.refresh(); } /********************************************************************************************************************** * STM32duino by ST Microsystems. * https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json * stm32 architecture for "Generic STM32F1 series" from "STM32 Boards (selected from submenu)" of Arduino Board manager **********************************************************************************************************************/ #elif defined(STM32F1xx) || defined(ARDUINO_ARCH_STM32) #include <HardwareTimer.h> // 4 timers and 3. timer is used for tone(), 2. for Servo # if defined(SEND_PWM_BY_TIMER) #error PWM generation by hardware not implemented for STM32 # endif #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR sSTM32Timer.resume() #define TIMER_DISABLE_RECEIVE_INTR sSTM32Timer.pause() // Redefinition of ISR macro which creates a plain function now # ifdef ISR #undef ISR # endif #define ISR() void IRTimerInterruptHandler(void) void IRTimerInterruptHandler(); /* * Use timer 4 as IRMP timer. * Timer 4 blocks PB6, PB7, PB8, PB9, so if you need one them as tone() or Servo output, you must choose another timer. */ # if defined(TIM4) HardwareTimer sSTM32Timer(TIM4); # else HardwareTimer sSTM32Timer(TIM2); # endif /* * Set timer for interrupts every MICROS_PER_TICK (50 us) */ void timerConfigForReceive() { sSTM32Timer.setOverflow(MICROS_PER_TICK, MICROSEC_FORMAT); // 50 uS sSTM32Timer.attachInterrupt(IRTimerInterruptHandler); sSTM32Timer.resume(); } /*************************************** * Particle special IntervalTimer * !!!UNTESTED!!! ***************************************/ #elif defined(PARTICLE) # ifndef __INTERVALTIMER_H__ #include "SparkIntervalTimer.h" // SparkIntervalTimer.h is required if PARTICLE is defined. # endif # if defined(SEND_PWM_BY_TIMER) #define IR_SEND_PIN A5 // Particle supports multiple pins #define ENABLE_SEND_PWM_BY_TIMER analogWrite(IrSender.sendPin, 128, ir_out_kHz*1000) #define DISABLE_SEND_PWM_BY_TIMER analogWrite(IrSender.sendPin, 0, ir_out_kHz*1000) # endif # ifndef IR_OUT_KHZ #define IR_OUT_KHZ 38 // default set to 38 KHz # endif extern IntervalTimer timer; extern int ir_out_kHz; //void IRTimerInterruptHandler(); #define TIMER_RESET_INTR_PENDING #define TIMER_ENABLE_RECEIVE_INTR timer.begin(IRTimerInterruptHandler, MICROS_PER_TICK, uSec) #define TIMER_DISABLE_RECEIVE_INTR timer.end() // Redefinition of ISR macro which creates a plain function now # ifdef ISR #undef ISR # endif #define ISR() void IRTimerInterruptHandler(void) void timerConfigForSend(uint8_t aFrequencyKHz) { ir_out_kHz = aFrequencyKHz; } void timerConfigForReceive() { } /*************************************** * Unknown CPU coard ***************************************/ #else #error Internal code configuration error, no timer functions implemented for this CPU / board /* * Dummy definitions to avoid more irritating compile errors */ #define TIMER_RESET_INTR_PENDING #define ENABLE_SEND_PWM_BY_TIMER #define DISABLE_SEND_PWM_BY_TIMER #define TIMER_ENABLE_RECEIVE_INTR #define TIMER_DISABLE_RECEIVE_INTR # ifdef ISR #undef ISR # endif #define ISR() void notImplemented(void) void timerConfigForSend(uint8_t aFrequencyKHz) { (void) aFrequencyKHz; } void timerConfigForReceive() { } #endif // defined(DOXYGEN / CPU_TYPES) /** @}*/ /** @}*/
Bungarch/meta
include/meta/classify/classifier/one_vs_one.h
/** * @file one_vs_one.h * @author <NAME> * * All files in META are released under the MIT license. For more details, * consult the file LICENSE in the root of the project. */ #ifndef META_CLASSIFY_ONE_VS_ONE_H_ #define META_CLASSIFY_ONE_VS_ONE_H_ #include "meta/classify/classifier/binary_classifier.h" #include "meta/classify/classifier/online_classifier.h" #include "meta/classify/classifier_factory.h" #include "meta/hashing/hash.h" #include "meta/meta.h" #include "meta/parallel/parallel_for.h" #include "meta/util/traits.h" namespace meta { namespace classify { /** * Ensemble method adaptor for extending binary_classifiers to the * multi-class classification case by using a one-vs-one strategy. This * entails creating a classifier for each pair of classes, and assigning * the label which gets the most "votes" from each individual * binary_classifier as the label for a given document. * * Required config parameters: * ~~~toml * [classifier] * method = "one-vs-one" * [classifier.base] * method = "sgd" # for example * loss = "hinge" # for example * prefix = "sgd-model" # for example * ~~~ */ class one_vs_one : public online_classifier { public: /** * Constructs a new one_vs_one classifier over the given training set * by using the creation function specified for creating * binary_classifiers. The creation function shall take one parameter * (a binary_dataset_view for training) and shall return a unique_ptr * to a binary_classifer. * * @param docs The training data * @param creator The function to create and train binary_classifiers */ template <class Creator, class = typename std:: enable_if<util::is_callable<Creator>::value>::type> one_vs_one(multiclass_dataset_view docs, Creator&& creator) { // for deterministic results, we create a list of the possible class // labels and sort them so that we always create the same pairs for the // one-vs-one reduction. This matters when using e.g. SGD where the // termination depends on the loss, which depends on which class we // treat as positive in the reduction. { std::vector<class_label> labels; labels.reserve(docs.total_labels()); for (auto it = docs.labels_begin(); it != docs.labels_end(); ++it) labels.push_back(it->first); std::sort(labels.begin(), labels.end()); for (auto outer = labels.begin(), end = labels.end(); outer != end; ++outer) { for (auto inner = outer; ++inner != end;) { classifiers_.emplace(problem_type{*outer, *inner}, nullptr); } } } using size_type = multiclass_dataset_view::size_type; using indices_type = std::vector<size_type>; // partition by class label std::unordered_map<class_label, indices_type> partitions; for (auto it = docs.begin(), end = docs.end(); it != end; ++it) partitions[docs.label(*it)].push_back(it.index()); parallel::parallel_for( classifiers_.begin(), classifiers_.end(), [&](classifier_map_type::value_type& problem) { const auto& pos = partitions[problem.first.positive]; const auto& neg = partitions[problem.first.negative]; indices_type indices; indices.reserve(pos.size() + neg.size()); std::copy(pos.begin(), pos.end(), std::back_inserter(indices)); std::copy(neg.begin(), neg.end(), std::back_inserter(indices)); binary_dataset_view bdv{docs, std::move(indices), [&](const instance_type& instance) { return docs.label(instance) == problem.first.positive; }}; problem.second = creator(bdv); }); #ifndef NDEBUG for (const auto& pr : classifiers_) assert(pr.second != nullptr); #endif } /** * Constructs a new one_vs_one classifier using the given * training data and a configuration group to create the internal * binary_classifiers. * * @param docs The documents to train with * @param base The configuration for the individual * binary_classifiers */ one_vs_one(multiclass_dataset_view docs, const cpptoml::table& base); /** * Loads a one_vs_one classifier from a stream. * @param in The stream to read from */ one_vs_one(std::istream& in); void save(std::ostream& out) const override; class_label classify(const feature_vector& instance) const override; void train(dataset_view_type docs) override; void train_one(const feature_vector& doc, const class_label& label) override; /** * The identifier for this classifier. */ const static util::string_view id; private: struct problem_type { class_label positive; class_label negative; template <class HashAlgorithm> friend void hash_append(HashAlgorithm& h, const problem_type& prob) { hash_append(h, prob.positive); hash_append(h, prob.negative); } friend bool operator==(const problem_type& a, const problem_type& b) { return std::tie(a.positive, a.negative) == std::tie(b.positive, b.negative); } friend bool operator!=(const problem_type& a, const problem_type& b) { return !(a == b); } }; using classifier_map_type = std::unordered_map<problem_type, std::unique_ptr<binary_classifier>, hashing::hash<>>; /** * the set of classifiers used in the ensemble, indexed by their * positive/negative class pair */ classifier_map_type classifiers_; }; /** * Specialization of the factory method used to create one_vs_all * classifiers. */ template <> std::unique_ptr<classifier> make_classifier<one_vs_one>(const cpptoml::table&, multiclass_dataset_view training); } } #endif
Bungarch/meta
include/meta/io/gzstream.h
/** * @file gzstream.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_UTIL_GZSTREAM_H_ #define META_UTIL_GZSTREAM_H_ #include <zlib.h> #include <streambuf> #include <vector> #include "meta/config.h" #include "meta/io/zstream.h" namespace meta { namespace io { class gzstreambuf : public std::streambuf { public: gzstreambuf(const char* filename, const char* openmode, size_t buffer_size = 512); ~gzstreambuf(); int_type underflow() override; int_type overflow(int_type ch) override; int sync() override; bool is_open() const; private: std::vector<char> buffer_; gzFile file_; }; /** * An ifstream that can read gz compressed files. */ using gzifstream = zifstream<gzstreambuf>; /** * An ofstream that can write gz compressed files. */ using gzofstream = zofstream<gzstreambuf>; } } #endif
Bungarch/meta
include/meta/topics/lda_cvb.h
<reponame>Bungarch/meta /** * @file lda_cvb.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_TOPICS_LDA_CVB_H_ #define META_TOPICS_LDA_CVB_H_ #include "meta/config.h" #include "meta/stats/multinomial.h" #include "meta/topics/lda_model.h" namespace meta { namespace topics { /** * lda_cvb: An implementation of LDA that uses collapsed variational bayes * for inference. Specifically, it uses the CVB0 algorithm detailed in * Asuncion et. al. * * @see http://www.ics.uci.edu/~asuncion/pubs/UAI_09.pdf */ class lda_cvb : public lda_model { public: class inferencer; /** * Constructs the lda model over the given documents, with the * given number of topics, and hyperparameters \f$\alpha\f$ and * \f$\beta\f$ for the priors on \f$\phi\f$ (topic distributions) * and \f$\theta\f$ (topic proportions), respectively. * * @param docs Documents to model * @param num_topics The number of topics to infer * @param alpha The hyperparameter for the Dirichlet prior over * \f$\phi\f$ * @param beta The hyperparameter for the Dirichlet prior over * \f$\theta\f$ */ lda_cvb(const learn::dataset& docs, std::size_t num_topics, double alpha, double beta); /** * Destructor: virtual for potential subclassing. */ virtual ~lda_cvb() = default; /** * Runs the variational inference algorithm for a maximum number of * iterations, or until the given convergence criterion is met. The * convergence criterion is determined as the maximum difference in * any of the variational parameters \f$\gamma_{dij}\f$ in a given * iteration. * * @param num_iters The maximum number of iterations to run the * sampler for * @param convergence The lowest maximum difference in any * \f$\gamma_{dij}\f$ to be allowed before considering the * inference to have converged */ void run(uint64_t num_iters, double convergence = 1e-3) override; virtual double compute_term_topic_probability(term_id term, topic_id topic) const override; virtual double compute_doc_topic_probability(learn::instance_id doc, topic_id topic) const override; virtual stats::multinomial<topic_id> topic_distribution(doc_id doc) const override; virtual stats::multinomial<term_id> term_distribution(topic_id k) const override; protected: /** * Initializes the parameters randomly. */ void initialize(); /** * Performs one iteration of the inference algorithm. * * @param iter The current iteration number * @return the maximum change in any of the \f$\gamma_{dij}\f$s */ double perform_iteration(uint64_t iter); /** * Variational distributions \f$\gamma_{ij}\f$, which represent the soft * topic assignments for each word occurrence \f$i\f$ in document * \f$j\f$. * * Indexed as gamma_[doc.id][i] */ std::vector<std::vector<stats::multinomial<topic_id>>> gamma_; /** * The word distributions for each topic, \f$\phi_t\f$. */ std::vector<stats::multinomial<term_id>> phi_; /** * The topic distributions for each document, \f$\theta_d\f$. */ std::vector<stats::multinomial<topic_id>> theta_; }; namespace detail { template <class DecreaseCounts, class UpdateWeight, class IncreaseCounts> double update_gamma(const learn::feature_vector& doc, std::size_t num_topics, std::vector<stats::multinomial<topic_id>>& gammas, DecreaseCounts&& decrease_counts, UpdateWeight&& update_weight, IncreaseCounts&& increase_counts) { double max_change = 0; uint64_t n = 0; for (const auto& freq : doc) { const auto& term = freq.first; for (uint64_t j = 0; j < freq.second; ++j) { const auto old_gamma = gammas[n]; // remove current word's expected counts for (topic_id k{0}; k < num_topics; ++k) decrease_counts(k, term, old_gamma.probability(k)); // recompute gamma distribution gammas[n].clear(); for (topic_id k{0}; k < num_topics; ++k) gammas[n].increment(k, update_weight(k, term)); // redistribute expected counts and compute L1 change in gamma double delta = 0; for (topic_id k{0}; k < num_topics; ++k) { auto prob = gammas[n].probability(k); increase_counts(k, term, prob); delta += std::abs(prob - old_gamma.probability(k)); } max_change = std::max(max_change, delta); n += 1; } } return max_change; } } } } #endif
Bungarch/meta
include/meta/topics/lda_gibbs.h
<filename>include/meta/topics/lda_gibbs.h /** * @file topics/lda_gibbs.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_LDA_GIBBS_H_ #define META_LDA_GIBBS_H_ #include <random> #include "meta/config.h" #include "meta/stats/multinomial.h" #include "meta/topics/lda_model.h" #include "meta/util/dense_matrix.h" namespace meta { namespace topics { /** * A LDA topic model implemented using a collapsed gibbs sampler. * * @see http://www.pnas.org/content/101/suppl.1/5228.full.pdf */ class lda_gibbs : public lda_model { public: class inferencer; /** * Constructs the lda model over the given documents, with the * given number of topics, and hyperparameters \f$\alpha\f$ and * \f$\beta\f$ for the priors on \f$\phi\f$ (topic distributions) * and \f$\theta\f$ (topic proportions), respectively. * * @param docs Documents to model * @param num_topics The number of topics to infer * @param alpha The hyperparameter for the Dirichlet prior over * \f$\phi\f$ * @param beta The hyperparameter for the Dirichlet prior over * \f$\theta\f$ */ lda_gibbs(const learn::dataset& docs, std::size_t num_topics, double alpha, double beta); /** * Destructor: virtual for potential subclassing. */ virtual ~lda_gibbs() = default; /** * Runs the sampler for a maximum number of iterations, or until * the given convergence criterion is met. The convergence * criterion is determined as the relative difference in log * corpus likelihood between two iterations. * * @param num_iters The maximum number of iterations to run the * sampler for * @param convergence The lowest relative difference in \f$\log * P(\mathbf{w} \mid \mathbf{z})\f$ to be allowed before considering * the sampler to have converged */ virtual void run(uint64_t num_iters, double convergence = 1e-6) override; /** * @return the probability that the given term appears in the given * topic * * @param term The term we are concerned with. * @param topic The topic we are concerned with. */ virtual double compute_term_topic_probability(term_id term, topic_id topic) const override; /** * @return the probability that the given topic is picked for the given * document * * @param doc The document we are concerned with. * @param topic The topic we are concerned with. */ virtual double compute_doc_topic_probability(learn::instance_id doc, topic_id topic) const override; virtual stats::multinomial<topic_id> topic_distribution(doc_id doc) const override; virtual stats::multinomial<term_id> term_distribution(topic_id k) const override; protected: /** * Initializes the first set of topic assignments for inference. * Employs an online application of the sampler where counts are * only considered for the words observed so far through the loop. */ virtual void initialize(); /** * Performs a sampling iteration. * * @param iter The iteration number * @param init Whether or not to employ the online method (defaults to * `false`) */ virtual void perform_iteration(uint64_t iter, bool init = false); /** * @return \f$\log P(\mathbf{w} \mid \mathbf{z})\f$ */ double corpus_log_likelihood() const; /** * lda_gibbs cannot be copy assigned. */ lda_gibbs& operator=(const lda_gibbs&) = delete; /** * lda_gibbs cannot be copy constructed. */ lda_gibbs(const lda_gibbs& other) = delete; /** * The topic assignment for every word in every document. Note that * the same word occurring multiple times in one document could * potentially have many different topics assigned to it, so we are * not using term_ids here, but our own contrived intra document term id. * * Indexed as [instance_id][position]. */ std::vector<std::vector<topic_id>> doc_word_topic_; /** * The word distributions for each topic, \f$\phi_t\f$. */ std::vector<stats::multinomial<term_id>> phi_; /** * The topic distributions for each document, \f$\theta_d\f$. */ std::vector<stats::multinomial<topic_id>> theta_; /** * The random number generator for the sampler. */ std::mt19937_64 rng_; }; namespace detail { template <class SampleWeight, class RandomNumberGenerator> topic_id sample_topic(term_id term, SampleWeight&& sample_weight, std::size_t num_topics, stats::multinomial<topic_id>& full_conditional, RandomNumberGenerator&& rng) { full_conditional.clear(); for (topic_id topic{0}; topic < num_topics; ++topic) full_conditional.increment(topic, sample_weight(topic, term)); return full_conditional(std::forward<RandomNumberGenerator>(rng)); } template <class DecreaseCounts, class SampleWeight, class IncreaseCounts, class RandomNumberGenerator> void sample_document(const learn::feature_vector& doc, std::size_t num_topics, std::vector<topic_id>& assignments, DecreaseCounts&& decrease_counts, SampleWeight&& sample_weight, IncreaseCounts&& increase_counts, RandomNumberGenerator&& rng) { // cached scratch space per-document to reduce allocations stats::multinomial<topic_id> full_conditional; uint64_t n = 0; // term number within document---constructed // so that each occurrence of the same term // can still be assigned a different topic for (const auto& freq : doc) { const auto& term = freq.first; for (uint64_t j = 0; j < freq.second; ++j) { auto old_topic = assignments[n]; // don't include current topic assignment in // probability calculation decrease_counts(old_topic, term); // sample a new topic assignment auto topic = sample_topic( term, std::forward<SampleWeight>(sample_weight), num_topics, full_conditional, std::forward<RandomNumberGenerator>(rng)); assignments[n] = topic; // increase counts increase_counts(topic, term); n += 1; } } } } } } #endif
Bungarch/meta
include/meta/analyzers/analyzer.h
<gh_stars>0 /** * @file analyzer.h * @author <NAME> * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_ANALYZER_H_ #define META_ANALYZER_H_ #include <memory> #include <stdexcept> #include "meta/analyzers/featurizer.h" #include "meta/config.h" #include "meta/util/clonable.h" namespace cpptoml { class table; } namespace meta { namespace corpus { class document; } namespace analyzers { class token_stream; class multi_analyzer; /** * An class that provides a framework to produce token counts from documents. * All analyzers inherit from this class and (possibly) implement tokenize(). * * The template argument for an analyzer indicates the supported feature * value for the analyzer, which is either uint64_t for inverted_index or * double for forward_index. * * When defining your own sublcass of analyzer, you should ensure to * subclass from the appropriate type. */ class analyzer : public util::clonable<analyzer> { public: /** * A default virtual destructor. */ virtual ~analyzer() = default; /** * Tokenizes a document. * @param doc The document to be tokenized * @return a feature_map that maps the observed features to their * counts in the document */ template <class T> feature_map<T> analyze(const corpus::document& doc) { feature_map<T> counts; featurizer feats{counts}; tokenize(doc, feats); return counts; } friend multi_analyzer; private: /** * The tokenization function that actually does the heavy lifting. This * should be overridden in derived classes. * * @param doc The document to be tokenized * @param counts The featurizer to record feature values with */ virtual void tokenize(const corpus::document& doc, featurizer& counts) = 0; }; /** * Basic exception for analyzer interactions. */ class analyzer_exception : public std::runtime_error { public: using std::runtime_error::runtime_error; }; /** * @param config The config group used to create the analyzer from * @return an analyzer as specified by a config object */ std::unique_ptr<analyzer> load(const cpptoml::table& config); /** * @param config The config group used to create the analyzer from * @return the default filter chain for this version of MeTA, * based on a config object */ std::unique_ptr<token_stream> default_filter_chain(const cpptoml::table& config); /** * @param config The config group used to create the analyzer from * @return the default filter chain for unigram words for this version * of MeTA, based on a config object */ std::unique_ptr<token_stream> default_unigram_chain(const cpptoml::table& config); /** * @param global The original config object with all parameters * @param config The config group used to create the filters from * @return a filter chain as specified by a config object */ std::unique_ptr<token_stream> load_filters(const cpptoml::table& global, const cpptoml::table& config); /** * @param src The token stream that will feed into this filter * @param config The config group used to create the filter from * @return a single filter specified by a config object */ std::unique_ptr<token_stream> load_filter(std::unique_ptr<token_stream> src, const cpptoml::table& config); /** * @param doc The document to get content for * @return the contents of the document, as a string */ std::string get_content(const corpus::document& doc); } } #endif
Bungarch/meta
include/meta/classify/classifier/sgd.h
<filename>include/meta/classify/classifier/sgd.h /** * @file sgd.h * @author <NAME> * * All files in META are released under the MIT license. For more details, * consult the file LICENSE in the root of the project. */ #ifndef META_CLASSIFY_SGD_H_ #define META_CLASSIFY_SGD_H_ #include "meta/classify/binary_classifier_factory.h" #include "meta/classify/classifier/binary_classifier.h" #include "meta/classify/classifier/online_binary_classifier.h" #include "meta/learn/loss/loss_function.h" #include "meta/learn/sgd.h" #include "meta/util/disk_vector.h" #include "meta/meta.h" namespace meta { namespace classify { /** * Implements stochastic gradient descent for learning binary linear * classifiers. These may be extended to multiclass classification using * the one_vs_all or all_vs_all adapters. * * Required config parameters: * ~~~toml * [classifier] * method = "sgd" * prefix = "path-to-model" * loss = "hinge" # or "huber", "least-squares", "logistic", etc * ~~~ * * Optional config parameters: * ~~~toml * [classifier] * learning-rate = 0.5 * convergence-threshold = 1e-3 * l2-regularization = 1e-7 * l1-regularization = 0 * max-iter = 5 * calibrate = false * ~~~ */ class sgd : public online_binary_classifier { public: /// The default \f$\gamma\f$ parameter. const static constexpr double default_gamma = 1e-3; /// The default number of allowed iterations. const static constexpr size_t default_max_iter = 1000; /** * @param docs The training documents * @param alpha \f$alpha\f$, the learning rate * @param gamma \f$gamma\f$, the error threshold * @param bias \f$b\f$, the bias * @param lambda \f$\lambda\f$, the regularization constant * @param max_iter The maximum number of iterations for training. */ sgd(binary_dataset_view docs, std::unique_ptr<learn::loss::loss_function> loss, learn::sgd_model::options_type options, double gamma = default_gamma, size_t max_iter = default_max_iter, bool calibrate = false); /** * Loads an sgd classifier from a stream. * @param in The stream to read from */ sgd(std::istream& in); void save(std::ostream& out) const override; void train(binary_dataset_view docs) override; void train_one(const feature_vector& doc, bool label) override; /** * Returns the dot product with the current weight vector. Used * mainly for generalization of a binary decision problem to a * multiclass decision problem. * * @param doc The document to compute the dot product with * @return the dot product with the current weight vector */ double predict(const feature_vector& doc) const override; /** * The identifier for this classifier. */ const static util::string_view id; private: /** * Internal version of train_one that returns the loss. */ double train_instance(const feature_vector& doc, bool label); /// The model learn::sgd_model model_; /// \f$\gamma\f$, the error threshold. const double gamma_; /// The maximum number of iterations for training. const size_t max_iter_; /// The loss function to be used for the update. std::unique_ptr<learn::loss::loss_function> loss_; }; /** * Specialization of the factory method used to create sgd classifiers. */ template <> std::unique_ptr<binary_classifier> make_binary_classifier<sgd>(const cpptoml::table& config, binary_dataset_view training); } } #endif
Bungarch/meta
include/meta/util/sparse_vector.h
<gh_stars>0 /** * @file sparse_vector.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_UTIL_SPARSE_VECTOR_H_ #define META_UTIL_SPARSE_VECTOR_H_ #include <cstdint> #include <utility> #include <vector> #include "meta/config.h" #include "meta/io/packed.h" namespace meta { namespace util { /** * Represents a sparse vector, indexed by type Index and storing values of * type Value. This stores the elements in the vector in sorted order by * the Index type. */ template <class Index, class Value> class sparse_vector { public: using pair_type = std::pair<Index, Value>; using container_type = std::vector<pair_type>; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator; /** * Creates an empty sparse_vector. */ sparse_vector() = default; /** * Creates a sparse vector with size elements. * @param size The number of elements in the new sparse vector. */ sparse_vector(uint64_t size); /** * Creates a sparse vector from a pair of iterators of pairs. * @param begin The iterator to the beginning of the sequence * @param end The iterator to the end of the sequence */ template <class Iter> sparse_vector(Iter begin, Iter end); /** * Gets the value associated with a given index in the vector, adding * it with a value-initialized Value if not present. * * @param index The index of the sparse vector to access * @return a reference to the value associated with that index into * the vector */ Value& operator[](const Index& index); /** * Gets the value associated with a given index in the vector. If not * present, this will return a value-initialized Value and will NOT * modify the vector. * * @param index The index of the sparse vector to access * @return the value associated with that index into the vector, or a * value-initialized Value if there is none */ Value at(const Index& index) const; /** * @param index The index of the sparse vector to search for * @return an iterator to that position, or the end iterator if it * does not exist */ const_iterator find(const Index& index) const; /** * Adds a new element to the vector, placing it at the back. * * This assumes that you are adding elements in sorted order by * Index---otherwise, the behavior of the vector afterwards is * undefined. * * @param ts The arguments to forward to the pair constructor of the * new element */ template <class... Ts> void emplace_back(Ts&&... ts); /** * Reserves space for elements * @param size The number of elements to reserve space for */ void reserve(uint64_t size); /** * Empties the vector. */ void clear(); /** * Optimises the memory usage of the vector. */ void shrink_to_fit(); /** * Condenses the vector to include only non-zero (value initialized) * entries. */ void condense(); /** * @return the number of non-zero elements in the vector */ uint64_t size() const; /** * @return the total capacity of the underlying storage */ uint64_t capacity() const; /** * @return whether the vector is empty */ bool empty() const; /** * @return the contents of the vector */ const container_type& contents() const; /** * @param cont The new contents of the vector */ void contents(container_type cont); /** * @return an iterator to the beginning of the vector */ iterator begin(); /** * @return a const_iterator to the beginning of the vector */ const_iterator begin() const; /** * @return a const_iterator to the beginning of the vector */ const_iterator cbegin() const; /** * @return an iterator to the end of the vector */ iterator end(); /** * @return a const_iterator to the end of the vector */ const_iterator end() const; /** * @return a const_iterator to the end of the vector */ const_iterator cend() const; /** * Removes an element. */ iterator erase(iterator pos); /** * Removes elements in an iterator range. */ iterator erase(iterator first, iterator last); sparse_vector& operator+=(const sparse_vector& rhs); sparse_vector& operator-=(const sparse_vector& rhs); template <class OutputSteam> friend uint64_t packed_write(OutputSteam& os, const sparse_vector& sv) { return io::packed::write(os, sv.storage_); } template <class InputStream> friend uint64_t packed_read(InputStream& is, sparse_vector& sv) { return io::packed::read(is, sv.storage_); } private: /** * Internal storage for the sparse vector: a sorted vector of pairs. */ container_type storage_; }; template <class Index, class Value> sparse_vector<Index, Value> operator+(const sparse_vector<Index, Value>& lhs, const sparse_vector<Index, Value>& rhs) { return sparse_vector<Index, Value>(lhs) += rhs; } template <class Index, class Value> sparse_vector<Index, Value> operator+(sparse_vector<Index, Value>&& lhs, const sparse_vector<Index, Value>& rhs) { return lhs += rhs; } template <class Index, class Value> sparse_vector<Index, Value> operator+(const sparse_vector<Index, Value>& lhs, sparse_vector<Index, Value>&& rhs) { return rhs += lhs; } template <class Index, class Value> sparse_vector<Index, Value> operator+(sparse_vector<Index, Value>&& lhs, sparse_vector<Index, Value>&& rhs) { return lhs += rhs; } template <class Index, class Value> sparse_vector<Index, Value> operator-(const sparse_vector<Index, Value>& lhs, const sparse_vector<Index, Value>& rhs) { return sparse_vector<Index, Value>(lhs) -= rhs; } template <class Index, class Value> sparse_vector<Index, Value> operator-(sparse_vector<Index, Value>&& lhs, const sparse_vector<Index, Value>& rhs) { return lhs -= rhs; } template <class Index, class Value> sparse_vector<Index, Value> operator-(sparse_vector<Index, Value>&& lhs, sparse_vector<Index, Value>&& rhs) { return lhs -= rhs; } template <class Index, class Value> double l2norm(const sparse_vector<Index, Value>& vec) { return std::sqrt(std::accumulate( std::begin(vec), std::end(vec), 0.0, [](double accum, const typename sparse_vector<Index, Value>::pair_type& pr) { return accum + pr.second * pr.second; })); } template <class SparseVector1, class SparseVector2> double dot_product(SparseVector1&& first, SparseVector2&& second) { auto first_it = std::begin(first); auto first_end = std::end(first); auto second_it = std::begin(second); auto second_end = std::end(second); auto dot = 0.0; while (first_it != first_end && second_it != second_end) { if (first_it->first == second_it->first) { dot += first_it->second * second_it->second; ++first_it; ++second_it; } else if (first_it->first < second_it->first) { ++first_it; } else { ++second_it; } } return dot; } template <class SparseVector1, class SparseVector2> double cosine_sim(SparseVector1&& first, SparseVector2&& second) { return dot_product(first, second) / (l2norm(first) * l2norm(second)); } } } #include "meta/util/sparse_vector.tcc" #endif
Bungarch/meta
include/meta/io/filedes.h
/** * @file filedes.h * @author <NAME> * * All files in MeTA are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_IO_FILEDES_H_ #define META_IO_FILEDES_H_ #include <cstdint> #include <fcntl.h> #include <stdexcept> #include <string> #include <sys/stat.h> #include <type_traits> #if _MSC_VER #include <io.h> #include <share.h> #else #include <unistd.h> #endif #include "meta/config.h" namespace meta { namespace io { /** * Represents the open mode for a file descriptor. Bitwise | can be applied * to create a mix of flags, and bitwise & can be performed to check for * the presence of a flag. */ enum class open_mode : uint8_t { READ = 1, WRITE = 1 << 1, READ_WRITE = 1 << 2, CREATE = 1 << 3 }; inline open_mode& operator|=(open_mode& a, open_mode b) { using T = std::underlying_type<open_mode>::type; return a = static_cast<open_mode>(static_cast<T>(a) | static_cast<T>(b)); } inline open_mode operator|(open_mode a, open_mode b) { return a |= b; } inline bool operator&(open_mode a, open_mode b) { using T = std::underlying_type<open_mode>::type; return static_cast<bool>(static_cast<T>(a) & static_cast<T>(b)); } namespace detail { #if _MSC_VER inline int to_flags(open_mode mode) { int flags = 0; flags |= (mode & open_mode::READ) ? _O_RDONLY : 0; flags |= (mode & open_mode::WRITE) ? _O_WRONLY : 0; flags |= (mode & open_mode::READ_WRITE) ? _O_RDWR : 0; flags |= (mode & open_mode::CREATE) ? _O_CREAT : 0; return flags; } inline int to_share(open_mode mode) { if (mode & open_mode::READ) return _SH_DENYWR; return _SH_DENYRW; } #else inline int to_flags(open_mode mode) { int flags = 0; flags |= (mode & open_mode::READ) ? O_RDONLY : 0; flags |= (mode & open_mode::WRITE) ? O_WRONLY : 0; flags |= (mode & open_mode::READ_WRITE) ? O_RDWR : 0; flags |= (mode & open_mode::CREATE) ? O_CREAT : 0; return flags; } #endif } class file_descriptor_exception : public std::runtime_error { public: using std::runtime_error::runtime_error; }; /** * RAII wrapper class for a system file descriptor. * * This class is not very full featured; it mainly serves as a porting * class for supporting Unix vs Windows. */ class file_descriptor { public: file_descriptor() : fd_{-1} { // nothing } file_descriptor(const char* path, open_mode mode) { using detail::to_flags; #ifndef _MSC_VER fd_ = ::open(path, to_flags(mode), S_IRUSR | S_IWUSR); if (fd_ < 0) { throw file_descriptor_exception{ "error obtaining file descriptor for " + std::string(path)}; } #else using detail::to_share; auto err = ::_sopen_s(&fd_, path, to_flags(mode), to_share(mode), _S_IREAD | _S_IWRITE); if (fd_ < 0) { throw file_descriptor_exception{ "error obtaining file descriptor for " + std::string(path)}; } #endif } file_descriptor(file_descriptor&& other) : fd_{other.fd_} { other.fd_ = -1; } file_descriptor& operator=(file_descriptor&& rhs) { close(); fd_ = rhs.fd_; rhs.fd_ = -1; return *this; } ~file_descriptor() { close(); } void close() { if (fd_ < 0) return; #ifndef _MSC_VER ::close(fd_); #else ::_close(fd_); #endif fd_ = -1; } long lseek(long offset) { #ifndef _MSC_VER return ::lseek(fd_, offset, SEEK_SET); #else return ::_lseek(fd_, offset, SEEK_SET); #endif } long write(const void* buffer, unsigned int count) { #ifndef _MSC_VER return ::write(fd_, buffer, count); #else return ::_write(fd_, buffer, count); #endif } operator int() const { return fd_; } private: int fd_; }; } } #endif
Bungarch/meta
include/meta/util/disk_vector.h
<gh_stars>0 /** * @file disk_vector.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_DISK_VECTOR_H_ #define META_DISK_VECTOR_H_ #include <fcntl.h> #include <stdio.h> #include <string> #include <type_traits> #ifndef _WIN32 #include <sys/mman.h> #include <unistd.h> #else #include "meta/io/mman-win32/mman.h" #endif #include "meta/config.h" #include "meta/io/filedes.h" #include "meta/meta.h" namespace meta { namespace util { /** * Basic exception for disk_vector. */ class disk_vector_exception : public std::runtime_error { public: using std::runtime_error::runtime_error; }; /** * disk_vector represents a large constant-size vector that does not necessarily * fit in memory. */ template <class T> class disk_vector { static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value || std::is_base_of<util::numeric, T>::value, "disk_vector templated types must be integral types"); public: /** * @param path The path to save this vector as. If the file * exists, it is treated as disk_vector. If the file doesn't exist, a * new one is created. * @param size The number of elements that will be in this vector. If not * specified, the disk_vector assumes that the file already exists. */ disk_vector(const std::string& path, uint64_t size = 0); /** * Move constructor. */ disk_vector(disk_vector&&); /** * Move assignment operator. */ disk_vector& operator=(disk_vector&&); /** * Destructor. */ ~disk_vector(); /** * @param idx The index of the vector to retrieve * @return a reference to the element at position idx in the vector * container */ template <class U = T, class = typename std::enable_if<!std::is_const<U>::value>::type> T& operator[](uint64_t idx) { return start_[idx]; } /** * @param idx The index of the vector to retrieve * @return a reference to the element at position idx in the vector * container */ const T& operator[](uint64_t idx) const; /** * @param idx The index of the vector to retrieve * @return a reference to the element at position idx in the vector * * The function automatically checks whether idx is within the bounds of * valid elements in the vector, throwing an exception if it is not * (i.e., if idx is greater or equal than its size). This is in contrast * with member operator[], that does not check against bounds. */ template <class U = T, class = typename std::enable_if<!std::is_const<U>::value>::type> T& at(uint64_t idx) { if (idx >= size_) throw disk_vector_exception{"index " + std::to_string(idx) + " out of range [0, " + std::to_string(size_) + ")"}; return start_[idx]; } /** * @param idx The index of the vector to retrieve * @return a reference to the element at position idx in the vector * * The function automatically checks whether idx is within the bounds of * valid elements in the vector, throwing an exception if it is not * (i.e., if idx is greater or equal than its size). This is in contrast * with member operator[], that does not check against bounds. */ const T& at(uint64_t idx) const; /** * @return the number of elements this vector stores */ uint64_t size() const; using iterator = T*; using const_iterator = const T*; /** * @return an iterator to the beginning of this container */ template <class U = T, class = typename std::enable_if<!std::is_const<U>::value>::type> iterator begin() { return start_; } /** * @return an iterator to the beginning of this container (const * version) */ const_iterator begin() const; /** * @return an iterator to the end of this container */ template <class U = T, class = typename std::enable_if<!std::is_const<U>::value>::type> iterator end() { return start_ + size_; } /** * @return an iterator to the end of this container (const version) */ const_iterator end() const; private: /// the path to the file this disk_vector uses for storage std::string path_; /// the beginning of where the storage file is memory mapped T* start_; /// this size of the memory-mapped file (in regards to T objects) uint64_t size_; /// the file descriptor used to open and close the mmap file io::file_descriptor file_desc_; }; } } #include "meta/util/disk_vector.tcc" #endif
Bungarch/meta
include/meta/util/clonable.h
<reponame>Bungarch/meta /** * @file clonable.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_UTIL_CLONABLE_H_ #define META_UTIL_CLONABLE_H_ #include <memory> #include "meta/config.h" #include "meta/util/shim.h" namespace meta { namespace util { /** * Template class to facilitate polymorphic cloning. Use in place of an * ordinary base class, with first parameter being the root of the * inheritance hierarchy, the second being the desired base class, and the * third being the current class (CRTP style). */ template <class Root, class Base, class Derived> class multilevel_clonable : public Base { public: /// Inherit the constructors from the base class using Base::Base; /** * Clones the given object. This requires that the Derived class be * capable of being copy-constructed. * * @return a unique_ptr to the Root type object. */ std::unique_ptr<Root> clone() const override { return make_unique<Derived>(static_cast<const Derived&>(*this)); } }; /** * Template class to facilitate polymorphic cloning. Used in the base class * to ensure that the clone() virtual function is provided and is pure * abstract. */ template <class Root> class multilevel_clonable<Root, Root, Root> { public: /** * Clones the given object. This requires that the Derived class be * capable of being copy-constructed. * * @return a unique_ptr to the Root type object. */ virtual std::unique_ptr<Root> clone() const = 0; }; /** * Template alias to facilitate polymorphic cloning. Use in place of an * ordinary base class, with first parameter being the base class and the * second parameter being the current class (CRTP style). */ template <class Base, class Derived = Base> using clonable = multilevel_clonable<Base, Base, Derived>; } } #endif
Bungarch/meta
include/meta/topics/bl_term_scorer.h
<filename>include/meta/topics/bl_term_scorer.h<gh_stars>0 /** * @file topic_model.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_TOPICS_DEFAULT_TERM_SCORER_H_ #define META_TOPICS_DEFAULT_TERM_SCORER_H_ #include "meta/index/forward_index.h" #include "meta/meta.h" #include "meta/topics/topic_model.h" namespace meta { namespace topics { /** * Scores terms according to a tfidf - like weighting by Blei and Lafferty. * @see http://www.cs.columbia.edu/~blei/papers/BleiLafferty2009.pdf */ class bl_term_scorer { public: /** * @param model The topic model to score */ bl_term_scorer(const topics::topic_model& model); /** * @param k The topic id * @param v The term id */ double operator()(topic_id k, term_id v) const; private: /** * The topic model */ const topics::topic_model& model_; /** * The sums */ std::vector<double> sums_; }; } } #endif
Bungarch/meta
include/meta/topics/lda_cvb_inferencer.h
<gh_stars>0 /** * @file topics/lda_cvb_inferencer.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_LDA_CVB_INFERENCER_H_ #define META_LDA_CVB_INFERENCER_H_ #include "meta/config.h" #include "meta/topics/inferencer.h" #include "meta/topics/lda_cvb.h" namespace meta { namespace topics { /** * An inferencer for topic proportions for unseen documents that uses * collapsed variational Bayes inference. */ class lda_cvb::inferencer : public meta::topics::inferencer { public: using meta::topics::inferencer::inferencer; /** * Performs inference using the CVB0 algorithm to determine the topic * proportions for the supplied document. The topics themselves are * held fixed and are not modified by this function. * * @param doc the document to be analyzed * @param max_iters the maximum number of inference iterations * @param convergence convergence threshold (maximum L1 change in * word-topic distribution vectors) */ stats::multinomial<topic_id> operator()(const learn::feature_vector& doc, std::size_t max_iters, double convergence) const; }; } } #endif
Bungarch/meta
include/meta/io/binary.h
/** * @file binary.h * @author <NAME> * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_IO_BINARY_H_ #define META_IO_BINARY_H_ #include <array> #include <cmath> #include <istream> #include <limits> #include <ostream> #include <string> #include "meta/config.h" namespace meta { namespace io { /** * Writes an object in binary format to a stream. * @param out The stream to write to * @param elem The element to write */ template <class T> uint64_t write_binary(std::ostream& out, const T& elem) { out.write(reinterpret_cast<const char*>(&elem), sizeof(T)); return sizeof(T); } /** * Writes a std::string object in binary format to a stream. * @param out The stream to write to * @param str the string to write */ inline uint64_t write_binary(std::ostream& out, const std::string& str) { out.write(str.c_str(), static_cast<std::streamsize>(str.size() + 1)); return str.size() + 1; } /** * Reads an object in binary from a stream. * @param in The stream to read from * @param elem The element to read */ template <class T> void read_binary(std::istream& in, T& elem) { in.read(reinterpret_cast<char*>(&elem), sizeof(T)); } /** * Reads a string in binary from a stream. * @param in The stream to read from * @param str The string to read */ inline void read_binary(std::istream& in, std::string& str) { std::getline(in, str, '\0'); } } } #endif
Bungarch/meta
include/meta/learn/transform.h
/** * @file dataset.h * @author <NAME> * * All files in META are released under the MIT license. For more details, * consult the file LICENSE in the root of the project. */ #ifndef META_LEARN_TRANSFORM_H_ #define META_LEARN_TRANSFORM_H_ #include "meta/index/ranker/ranker.h" #include "meta/index/score_data.h" #include "meta/learn/dataset.h" namespace meta { namespace learn { /** * Transformer for converting term frequency vectors into tf-idf weight * vectors. This transformation is performed with respect to a specific * index::inverted_index that defines the term statistics, and with respect * to an index::ranking_function that defines the "tf-idf" weight (via its * score_one() function). * * For example, one can construct a tfidf_transformer with an * inverted index and an okapi_bm25 ranker to get tf-idf vectors using * Okapi BM25's definitions of tf and idf. * * Some caveats to be aware of: * * 1. if your ranker uses extra information that isn't present in score_data * (e.g. by using score_data.d_id and querying something), this will only * work if your instance ids directly correspond to doc ids in the * inverted index * * 2. tf-idf values are computed using statistics from the inverted_index. * If this index contains your test set, the statistics are going to be * computed including documents in your test set. If this is * undesirable, create an inverted_index on just your training data and * use that instead of one created on both the training and testing * data. * * 3. This transformation only makes sense if your instances' weight * vectors are actually term frequency vectors. If they aren't, the * assumptions here that every entry in every weight vector can be * safely converted to an integral value without rounding is violated. */ class tfidf_transformer { public: /** * @param idx The index to use for term statistics * @param r The ranker to use for defining the weights */ tfidf_transformer(index::inverted_index& idx, index::ranking_function& r) : idx_(idx), rnk_(r), sdata_(idx, idx.avg_doc_length(), idx.num_docs(), idx.total_corpus_terms(), 1) { sdata_.query_term_weight = 1.0f; } /** * @param inst The instance to transform */ void operator()(learn::instance& inst) { sdata_.d_id = doc_id{inst.id}; sdata_.doc_size = static_cast<uint64_t>(std::accumulate( inst.weights.begin(), inst.weights.end(), 0.0, [](double accum, const std::pair<feature_id, double>& val) { return accum + val.second; })); sdata_.doc_unique_terms = inst.weights.size(); for (auto& pr : inst.weights) { sdata_.t_id = term_id{pr.first}; sdata_.doc_count = idx_.doc_freq(sdata_.t_id); sdata_.corpus_term_count = idx_.total_num_occurences(sdata_.t_id); sdata_.doc_term_count = static_cast<uint64_t>(pr.second); pr.second = rnk_.score_one(sdata_); } } private: index::inverted_index& idx_; index::ranking_function& rnk_; index::score_data sdata_; }; /** * Transformer to normalize all unit vectors to unit length. */ class l2norm_transformer { public: void operator()(learn::instance& inst) const { auto norm = std::sqrt(std::accumulate( inst.weights.begin(), inst.weights.end(), 0.0, [](double accum, const std::pair<feature_id, double>& val) { return accum + val.second * val.second; })); for (auto& pr : inst.weights) pr.second /= norm; } }; /** * Transformer to scale all features by their maximum absolute value. */ class max_abs_transformer { public: max_abs_transformer(const learn::dataset& dset) : max_abs_(dset.total_features()) { for (const auto& inst : dset) { for (const auto& pr : inst.weights) { max_abs_[pr.first] = std::max(max_abs_[pr.first], std::abs(pr.second)); } } } void operator()(learn::instance& inst) const { for (auto& pr : inst.weights) pr.second /= max_abs_[pr.first]; } private: std::vector<double> max_abs_; }; /** * Transforms the feature vectors of a dataset **in place** using the given * transformation function. TransformFunction must have an operator() that * takes a learn::instance by mutable reference and changes its * feature values in-place. For example, a simple TransformFunction might * be one that normalizes all of the feature vectors to be unit length. * * @param dset The dataset to be transformed * @param trans The transformation function to be applied to all * feature_vectors in dset */ template <class TransformFunction> void transform(dataset& dset, TransformFunction&& trans) { for (auto& inst : dset) trans(inst); } /** * Transforms the feature vectors of a dataset **in place** to be tf-idf * features using the given index for term statistics and ranker for * tf-idf weight definitions. * * @param dset The dataset to be transformed * @param idx The inverted_index to use for term statistics like df * @param rnk The ranker to use to define tf-idf weights (via its * score_one()) */ inline void tfidf_transform(dataset& dset, index::inverted_index& idx, index::ranking_function& rnk) { tfidf_transformer transformer{idx, rnk}; transform(dset, transformer); } /** * Transforms the feature vectors of a dataset **in place** to be unit * length according to their L2 norm. * * @param dset The dataset to be transformed */ inline void l2norm_transform(dataset& dset) { return transform(dset, l2norm_transformer{}); } /** * Transforms the feature vectors of a dataset **in place** to have their * feature values scaled by the maximum absolute value for that feature. * * @param dset The dataset to be transformed. */ inline void max_abs_transform(dataset& dset) { return transform(dset, max_abs_transformer{dset}); } } } #endif
Bungarch/meta
include/meta/io/xzstream.h
/** * @file xzstream.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_UTIL_XZSTREAM_H_ #define META_UTIL_XZSTREAM_H_ #include <lzma.h> #include <cstdio> #include <stdexcept> #include <streambuf> #include <vector> #include "meta/config.h" #include "meta/io/zstream.h" namespace meta { namespace io { class xz_exception : public std::runtime_error { public: xz_exception(const std::string& msg, lzma_ret code) : std::runtime_error{msg}, code_{code} { // nothing } explicit operator lzma_ret() const { return code_; } private: lzma_ret code_; }; class xzstreambuf : public std::streambuf { public: xzstreambuf(const char* filename, const char* openmode, std::size_t buffer_size = 128 * 1024); ~xzstreambuf(); int_type underflow() override; int_type overflow(int_type ch) override; int sync() override; bool is_open() const; uint64_t bytes_read() const; private: bool reading_; std::vector<char> in_buffer_; std::vector<char> out_buffer_; FILE* file_; uint64_t bytes_read_; lzma_stream stream_; lzma_action action_; }; /** * An ifstream that can read xz compressed files. */ using xzifstream = zifstream<xzstreambuf>; /** * An ofstream that can write xz compressed files. */ using xzofstream = zofstream<xzstreambuf>; } } #endif
Bungarch/meta
include/meta/regression/models/sgd.h
/** * @file sgd.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_REGRESSION_SGD_H_ #define META_REGRESSION_SGD_H_ #include "meta/learn/sgd.h" #include "meta/regression/models/regressor.h" #include "meta/regression/regressor_factory.h" namespace meta { namespace regression { /** * Implements stochastic gradient descent for learning regression models. * * Required config parameters: * ~~~toml * [regressor] * method = "sgd" * loss = "least-squares" # or huber * ~~~ * * Optional config parameters: * ~~~toml * [regressor] * learning-rate = 0.5 * convergence-threshold = 1e-3 * l2-regularization = 1e-7 * l1-regularization = 0 * max-iter = 5 * calibrate = true * ~~~ */ class sgd : public regressor { public: /// The default convergence threshold const static constexpr double default_gamma = 1e-3; /// The default number of allowed iterations const static constexpr size_t default_max_iter = 1000; /** * @param docs The training documents * @param loss The loss function * @param options The options for the SGD learner * @param gamma The convergence threshold * @param max_iter The maximum allowed iterations */ sgd(dataset_view_type docs, std::unique_ptr<learn::loss::loss_function> loss, learn::sgd_model::options_type options, double gamma = default_gamma, size_t max_iter = default_max_iter, bool calibrate = true); /** * Loads an sgd regressor from a stream. * @param in The stream to read from */ sgd(std::istream& in); void save(std::ostream& out) const override; /** * Trains the model on an additional set of documents. * @param docs The document collection to update the model with */ void train(dataset_view_type docs); /** * Trains the model on a single instance. * @param doc The document to learn from * @param label The actual label of the document */ void train_one(const feature_vector& doc, double label); double predict(const feature_vector& doc) const override; /** * The identifier for this regressor */ const static util::string_view id; private: /// The model learn::sgd_model model_; /// \f$\gamma\f$, the error threshold. const double gamma_; /// The maximum number of iterations for training. const size_t max_iter_; /// The loss function to be used for the update. std::unique_ptr<learn::loss::loss_function> loss_; }; /** * Specialization of the factory method used to create sgd regressors. */ template <> std::unique_ptr<regressor> make_regressor<sgd>(const cpptoml::table& config, regression_dataset_view training); } } #endif
Bungarch/meta
include/meta/topics/inferencer.h
/** * @file topics/inferencer.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_TOPICS_INFERENCER_H_ #define META_TOPICS_INFERENCER_H_ #include "meta/config.h" #include "meta/topics/topic_model.h" #include "meta/util/progress.h" namespace meta { namespace topics { /** * A base class for topic model inference methods to be run on unseen (new) * documents. This class is useless on its own, but provides a unified * interface for loading in topic model output from disk and provides the * necessary information for specific inferencers to be built. */ class inferencer { public: /** * Constructs an inferencer by consulting the [lda] configuration * group of the supplied config. * * @param config a cpptoml::table that contains an [lda] subtable. */ inferencer(const cpptoml::table& config); /** * Constructs an inferencer from an input stream representing the * topics file from a topic model (.phi.bin) and the desired * (symmetric) Dirichlet prior parameter. * * @param topic_stream an istream reading the .phi.bin file from a * topic model * @param alpha the parameter for a symmetric Dirichlet prior for the * proportions to be inferred */ inferencer(std::istream& topic_stream, double alpha); /** * @param k the topic identifier * @return the term distribution for the given topic */ const stats::multinomial<term_id>& term_distribution(topic_id k) const; /** * @return the number of topics */ std::size_t num_topics() const; /** * @return the Dirichlet prior to use for inferred topic proportions * for new documents */ const stats::dirichlet<topic_id>& proportions_prior() const; private: void load_from_stream(std::istream& topic_stream); /// The topics, indexed by topic_id std::vector<stats::multinomial<term_id>> topics_; /// The prior distribution to use for inferred topic proportions stats::dirichlet<topic_id> prior_; }; class inferencer_exception : public std::runtime_error { public: using std::runtime_error::runtime_error; }; } } #endif
Bungarch/meta
include/meta/io/libsvm_parser.h
<filename>include/meta/io/libsvm_parser.h /** * @file libsvm_parser.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_LIBSVM_PARSER_H_ #define META_LIBSVM_PARSER_H_ #include <string> #include <utility> #include <vector> #include <stdexcept> #include "meta/config.h" #include "meta/meta.h" namespace meta { namespace io { namespace libsvm_parser { /// Collection of (term_id, double) using counts_t = const std::vector<std::pair<term_id, double>>; /** * Extracts a class_label from a string in libsvm format * @param text A libsvm-formatted string; throws an exception if it can't * be parsed correctly * @return the class_label */ class_label label(const std::string& text); /** * @param text A libsvm-formatted string; throws an exception if it can't * be parsed correctly * @param contains_label Whether this string's first token is the * class_label * @return (feature, count) pairs of the libsvm data */ counts_t counts(const std::string& text, bool contains_label = true); /** * Exception class for this parser. */ class libsvm_parser_exception : public std::runtime_error { public: using std::runtime_error::runtime_error; }; } } } #endif
Bungarch/meta
include/meta/classify/binary_dataset_view.h
<filename>include/meta/classify/binary_dataset_view.h /** * @file binary_dataset_view.h * @author <NAME> * * All files in META are released under the MIT license. For more details, * consult the file LICENSE in the root of the project. */ #ifndef META_CLASSIFY_BINARY_DATASET_VIEW_H_ #define META_CLASSIFY_BINARY_DATASET_VIEW_H_ #include "meta/classify/multiclass_dataset_view.h" #include "meta/config.h" #include "meta/learn/dataset_view.h" namespace meta { namespace classify { using binary_dataset = learn::labeled_dataset<bool>; /** * A non-owning view of a dataset with binary class labels. This is * designed to be used with binary classifiers. */ class binary_dataset_view : public learn::dataset_view { public: binary_dataset_view(const binary_dataset& dset) : dataset_view{dset}, label_fn_{[&](const instance_type& instance) { return dset.label(instance); }} { // nothing } template <class RandomEngine> binary_dataset_view(const binary_dataset& dset, RandomEngine&& rng) : dataset_view{dset, std::forward<RandomEngine>(rng)}, label_fn_{[&](const instance_type& instance) { return dset.label(instance); }} { // nothing } binary_dataset_view(const binary_dataset_view& bdv, iterator begin, iterator end) : dataset_view{bdv, begin, end}, label_fn_{bdv.label_fn_} { // nothing } binary_dataset_view(const binary_dataset& dset, binary_dataset::const_iterator begin, binary_dataset::const_iterator end) : dataset_view{dset, begin, end}, label_fn_{[&](const instance_type& instance) { return dset.label(instance); }} { // nothing } template <class RandomEngine> binary_dataset_view(const binary_dataset& dset, binary_dataset::const_iterator begin, binary_dataset::const_iterator end, RandomEngine&& rng) : dataset_view{dset, begin, end, std::forward<RandomEngine>(rng)}, label_fn_{[&](const instance_type& instance) { return dset.label(instance); }} { // nothing } binary_dataset_view(const binary_dataset_view& bdv, std::vector<size_type>&& indices) : dataset_view{bdv, std::move(indices)}, label_fn_{bdv.label_fn_} { // nothing } template <class LabelFunction> binary_dataset_view(const multiclass_dataset_view& mdv, LabelFunction&& fn) : dataset_view{mdv}, label_fn_(std::forward<LabelFunction>(fn)) { // nothing } template <class LabelFunction> binary_dataset_view(const multiclass_dataset_view& mdv, std::vector<size_type>&& indices, LabelFunction&& fn) : dataset_view{mdv, std::move(indices)}, label_fn_(std::forward<LabelFunction>(fn)) { // nothing } bool label(const instance_type& instance) const { return label_fn_(instance); } size_type total_labels() const { return 2; } friend binary_dataset_view operator-(const binary_dataset_view& lhs, const binary_dataset_view& rhs) { auto lhs_indices = lhs.indices(); auto rhs_indices = rhs.indices(); std::sort(std::begin(lhs_indices), std::end(lhs_indices)); std::sort(std::begin(rhs_indices), std::end(rhs_indices)); std::vector<size_type> diff_indices; std::set_difference(std::begin(lhs_indices), std::end(lhs_indices), std::begin(rhs_indices), std::end(rhs_indices), std::back_inserter(diff_indices)); return {lhs, std::move(diff_indices)}; } private: /// function to obtain the labels for instances std::function<bool(const instance_type&)> label_fn_; }; } } #endif
Bungarch/meta
include/meta/util/traits.h
/** * @file traits.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_UTIL_TRAITS_H_ #define META_UTIL_TRAITS_H_ #include <type_traits> namespace meta { namespace util { template <class A, class B> using disable_if_same_or_derived_t = typename std:: enable_if<!std::is_base_of<A, typename std::remove_reference<B>::type>:: value>::type; // @see http://stackoverflow.com/a/15394527 template <class T, class = void> struct is_callable : std::is_function<T> { // nothing }; template <class T> struct is_callable<T, typename std:: enable_if<std::is_same<decltype(void(&T::operator())), void>::value>::type> : std::true_type { // nothing }; } } #endif
Bungarch/meta
include/meta/learn/sgd.h
/** * @file sgd.h * @author <NAME> * * All files in META are released under the MIT license. For more details, * consult the file LICENSE in the root of the project. */ #ifndef META_LEARN_SGD_H_ #define META_LEARN_SGD_H_ #include <vector> #include "meta/config.h" #include "meta/learn/dataset.h" #include "meta/learn/loss/loss_function.h" namespace meta { namespace learn { /** * A generic stochastic gradient descent learner for binary classification * or regression. It implements AdaGrad (Duchi, Hazan, and Singer) and * supports calibrating a learning rate from a subset of training data, * which should reduce the need to fiddle with the learning rate as much. * * It supports both L1 and L2 regularization, which may be used at the same * time. L2 regularization uses the "scalar-times-a-vector" trick for * efficient shrinking during training, and L1 regularization is performed * using the cumulative penalty method of Tsuruoka, Tsujii, and Ananiadou. * * @see http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf * @see http://www.aclweb.org/anthology/P09-1054 */ class sgd_model { public: /// The default initial learning rate const static constexpr double default_learning_rate = 0.001; /// The default l2 regularization parameter const static constexpr double default_l2_regularizer = 1e-7; /// The default l1 regularization parameter (defaults to off) const static constexpr double default_l1_regularizer = 0; /** * Construction options for the model, specifying the learning rate * and the regularizer values. */ struct options_type { double learning_rate = default_learning_rate; double l2_regularizer = default_l2_regularizer; double l1_regularizer = default_l1_regularizer; options_type() { // nothing; workaround for clang not liking the default // initialized argument below without an explicit default // constructor definition, and gcc 4.8 not being happy with a // braced init list to set the values to work around clang... } }; /** * Constructs a new model with the specified number of features, * learning rate, and regularization. */ sgd_model(std::size_t num_features, options_type options = {}); /** * Loads a model from a stream (so that one could continue training). */ sgd_model(std::istream& in); /** * Saves the current model state to a stream. */ void save(std::ostream& out) const; /** * Calibrates the learning rate for the model based on sample data. * Search strategy inspired by <NAME>'s SGD package. * * @see http://leon.bottou.org/projects/sgd * * @param view The dataset_view that represents the sample * @param loss The loss function used to calculate the training loss * @param labeler A unary function object to convert an instance -> * double label * @param calibration_rate How much to scale the learning rate by for * each subsequent trial */ template <class SampleView, class LabelFunction> void calibrate(SampleView view, const loss::loss_function& loss, LabelFunction&& labeler, double calibration_rate = 2, std::size_t calibration_samples = 1000) { using diff_type = typename decltype(view.begin())::difference_type; // we can't calibrate properly if we get 0 loss from a null // prediction as we'll just end up setting the learning rate to 0 // to keep the loss minimized. This happens when we're passed the // Perceptron loss. if (loss.loss(0, 1) == 0 && loss.loss(0, -1) == 0) return; view.shuffle(); auto samples = std::min(calibration_samples, view.size()); SampleView calib_view{view, view.begin(), view.begin() + static_cast<diff_type>(samples)}; lr_ *= calibration_rate; reset(); auto hi_loss = avg_loss_on_sample(view, calibration_samples, loss, std::forward<LabelFunction>(labeler)); lr_ /= calibration_rate; reset(); auto lo_loss = avg_loss_on_sample(view, calibration_samples, loss, std::forward<LabelFunction>(labeler)); if (lo_loss < hi_loss) { while (lo_loss < hi_loss) { lr_ /= calibration_rate; hi_loss = lo_loss; reset(); lo_loss = avg_loss_on_sample(view, calibration_samples, loss, std::forward<LabelFunction>(labeler)); } lr_ *= calibration_rate; } else if (hi_loss < lo_loss) { lr_ *= calibration_rate; while (hi_loss < lo_loss) { lr_ *= calibration_rate; lo_loss = hi_loss; reset(); hi_loss = avg_loss_on_sample(view, calibration_samples, loss, std::forward<LabelFunction>(labeler)); } lr_ /= calibration_rate; } // sometimes calibration gets out of control, so tame it a bit here // just in case. If you need a learning rate out of this range, you // hopefully know it. lr_ = std::max(std::min(lr_, 2.0), 1e-6); reset(); } /** * Gives a prediction for an input vector. This is simply \f$w^T x\f$. * @return the prediction */ double predict(const feature_vector& x) const; /** * Updates the model for a specific instance. * * @param x The instance to update with * @param expected_label The ground truth label * @param loss The loss function to use for the update * * @return the loss incurred for this example */ double train_one(const feature_vector& x, double expected_label, const loss::loss_function& loss); private: /** * Per-feature representation of the weight vector. * * This stores four values: the actual weight, the current scale * factor, and the running sum of squared gradients in order to * implement the normalized adaptive gradient algorithm from Ross, * Mineiro, and Langford, as well as the total cumulative L1 penalty to * implement the L1 regularization proposed by Tsuruoka, Tsujii, and * Ananiadou. */ struct weight_type { double weight = 0; double grad_squared = 0; double cumulative_penalty = 0; }; template <class SampleView, class LabelFunction> double avg_loss_on_sample(const SampleView& sample, std::size_t calibration_samples, const loss::loss_function& loss, LabelFunction&& labeler) { auto avg_loss = 0.0; auto it = sample.begin(); for (std::size_t i = 0; i < calibration_samples; ++i) { if (it == sample.end()) it = sample.begin(); avg_loss += train_one(it->weights, labeler(*it), loss); } avg_loss /= calibration_samples; if (l2_regularization_ > 0) avg_loss += 0.5 * l2_regularization_ * std::pow(l2norm(), 2); if (l1_regularization_ > 0) avg_loss += l1_regularization_ * l1norm(); return avg_loss; } void penalize(weight_type& weight_val); void reset(); double l2norm() const; double l1norm() const; /// The per-feature weight information std::vector<weight_type> weights_; /// The weight information for the bias term weight_type bias_; /// The current scalar to multiply weights in the weight vector by double scale_; /// The update scale factor (\f$N\f$ in Ross et. al.) double update_scale_; /// The learning rate (\f$\eta\f$ in Ross et. al.) double lr_; /// The l2 regularization constant double l2_regularization_; /// The l1 regularization constant double l1_regularization_; /// The total number of observed examples std::size_t t_; }; } } #endif
Bungarch/meta
include/meta/util/identifiers.h
/** * @file identifiers.h * @author <NAME> * Defines CRTP base classes that allow for the creation of type-safe * "typedef" classes that serve as identifiers in the project. * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_NUMERIC_IDENTIFIER_H_ #define META_NUMERIC_IDENTIFIER_H_ #include <functional> // for std::hash #include "meta/config.h" #include "meta/hashing/hash.h" #include "meta/util/comparable.h" #include "meta/util/string_view.h" #if _MSC_VER #define META_EMPTY_BASES __declspec(empty_bases) #else #define META_EMPTY_BASES #endif namespace meta { namespace util { /** * Empty helper class to denote that something is numeric. */ struct numeric { }; /** * Type trait for numeric. */ template <class T> struct is_numeric { const static constexpr bool value = std::is_integral<T>::value || std::is_base_of<numeric, T>::value; }; /** * Base template that denotes an identifier. identifiers are comparable * through normal relational operators defined on the underlying type T. */ template <class Tag, class T> struct META_EMPTY_BASES identifier : public comparable<identifier<Tag, T>> { using underlying_type = T; /** * The underlying id for the identifier. */ T id_; /** * identifiers must be explicitly constructed from their base * type---they *cannot* be implicitly converted from them! * * @param t the underlying type to convert into an identifier */ explicit constexpr identifier(const T& t) : id_{t} { // nothing } /** * identifier has a default constructor. */ identifier() = default; /** * identifiers may be copy constructed. */ identifier(const identifier&) = default; /** * identifiers may be move constructed. */ identifier(identifier&&) = default; /** * identifiers may be copy assigned. */ identifier& operator=(const identifier&) = default; /** * identifiers may be move assigned. */ identifier& operator=(identifier&&) = default; /** * identifiers may be converted into their base type. This is the const * version. * * @return the base type representation for this identifier */ constexpr operator const T&() const { return id_; } /** * identifiers may be converted into their base type. This is the * non-const version. * * @return the base type representation for this identifier */ operator T&() { return id_; } /** * Conversion to string_view. Enabled only if T is a std::string. * @return the base type representation of this identifier, converted * to a string_view */ template < typename U = T, typename = typename std::enable_if<std::is_same<U, std::string>::value>::type> constexpr operator util::string_view() const { return id_; } /** * identifiers may be printed to output streams. * @param stream The stream to write to * @param ident The identifier to write to the stream * @return `stream` */ inline friend std::ostream& operator<<(std::ostream& stream, const identifier& ident) { return stream << static_cast<const T&>(ident); } /** * identifiers may be read from input streams. * @param stream The stream to read from * @param ident The identifier to read into * @return `stream` */ inline friend std::istream& operator>>(std::istream& stream, identifier& ident) { return stream >> ident.id_; } }; /** * identifiers are comparable by their base types. This allows for * storage in comparison-based containers like std::map or std::set. * * @param lhs * @param rhs * @return whether lhs < rhs based on T::operator<. */ template <class Tag, class T> inline constexpr bool operator<(const identifier<Tag, T>& lhs, const identifier<Tag, T>& rhs) { return static_cast<const T&>(lhs) < static_cast<const T&>(rhs); } template <class HashAlgorithm, class Tag, class T> void hash_append(HashAlgorithm& h, const identifier<Tag, T>& id) { using hashing::hash_append; hash_append(h, static_cast<const T&>(id)); } /** * A CRTP template base that adds numeric functionality to the identifier * type. numerical_identifiers support typical integer math functions on * top of the things supported by identifiers. */ template <class Tag, class T> struct META_EMPTY_BASES numerical_identifier : public identifier<Tag, T>, numeric { using identifier<Tag, T>::identifier; using identifier<Tag, T>::id_; using identifier<Tag, T>::operator=; // these shouldn't be needed, but GCC 7.1.1 is doing weird things when // using MAKE_NUMERIC_IDENTIFIER instead of MAKE_NUMERIC_IDENTIFIER_UDL // and explicitly defaulting these ctors/operators makes it go away... numerical_identifier() = default; numerical_identifier(const numerical_identifier&) = default; numerical_identifier(numerical_identifier&&) = default; numerical_identifier& operator=(const numerical_identifier&) = default; numerical_identifier& operator=(numerical_identifier&&) = default; /** * Prefix-increment. * @return the current identifier after being incremented */ numerical_identifier& operator++() { ++id_; return *this; } /** * Postifx-increment. * @return the old value of the identifier */ numerical_identifier operator++(int) { auto t = *this; ++(*this); return t; } /** * Prefix-decrement. * @return the current identifier after being decremented */ numerical_identifier& operator--() { --id_; return *this; } /** * Postfix-decrement. * @return the old value of the identifier */ numerical_identifier operator--(int) { auto t = *this; --(*this); return t; } /** * @param step How much to increase the current identifier by * @return the current identifier */ template <class U, class = typename std:: enable_if<std::is_convertible<U, T>::value>::type> numerical_identifier& operator+=(const T& step) { id_ += step; return *this; } /** * @param step How much to decrease the current identifier by * @return the current identifier */ template <class U, class = typename std:: enable_if<std::is_convertible<U, T>::value>::type> numerical_identifier& operator-=(const T& step) { id_ -= step; return *this; } /** * @param lhs * @param rhs * @return lhs + rhs, defined in terms of * numerical_identifier::operator+=. */ friend inline numerical_identifier operator+(numerical_identifier lhs, const numerical_identifier& rhs) { lhs += static_cast<T>(rhs); return lhs; } /** * @param lhs * @param rhs * @return lhs - rhs, defined in terms of * numerical_identifier::operator-=. */ friend inline numerical_identifier operator-(numerical_identifier lhs, const numerical_identifier& rhs) { lhs -= static_cast<T>(rhs); return lhs; } }; } } namespace std { /** * A partial specialization that allows for hashing of identifier types * based on their base type. */ template <class Tag, class T> struct hash<meta::util::identifier<Tag, T>> { /** * @param to_hash The identifier to be hashed * @return the hash code for the given identifier, defined in terms of * std::hash of its underlying type */ size_t operator()(const meta::util::identifier<Tag, T>& to_hash) const { return hash<T>{}(static_cast<T>(to_hash)); } }; /** * A partial specialization that allows for hashing of * numerical_identifier types based on their base type. */ template <class Tag, class T> struct hash<meta::util::numerical_identifier<Tag, T>> { /** * @param to_hash The identifier to be hashed * @return the hash code for the given identifier, defined in terms of * std::hash of its underlying type */ size_t operator()(const meta::util::numerical_identifier<Tag, T>& to_hash) const { return hash<T>{}(static_cast<T>(to_hash)); } }; } #define MAKE_USER_DEFINED_LITERAL(ident_name, base_type, suffix) \ inline ident_name operator"" suffix(const char* str, std::size_t len) \ { \ return ident_name{base_type{str, len}}; \ } #define MAKE_USER_DEFINED_NUMERIC_LITERAL(ident_name, base_type, suffix) \ inline ident_name operator"" suffix(unsigned long long int val) \ { \ return ident_name{base_type(val)}; \ } #define MAKE_OPAQUE_IDENTIFIER(ident_name, base_type) \ struct ident_name##_tag \ { \ }; \ using ident_name = meta::util::identifier<ident_name##_tag, base_type>; #define MAKE_OPAQUE_NUMERIC_IDENTIFIER(ident_name, base_type) \ struct ident_name##_tag \ { \ }; \ using ident_name \ = meta::util::numerical_identifier<ident_name##_tag, base_type>; #define MAKE_IDENTIFIER(ident_name, base_type) \ MAKE_OPAQUE_IDENTIFIER(ident_name, base_type) #define MAKE_NUMERIC_IDENTIFIER(ident_name, base_type) \ MAKE_OPAQUE_NUMERIC_IDENTIFIER(ident_name, base_type) #define MAKE_IDENTIFIER_UDL(ident_name, base_type, suffix) \ MAKE_OPAQUE_IDENTIFIER(ident_name, base_type) \ MAKE_USER_DEFINED_LITERAL(ident_name, base_type, suffix) #define MAKE_NUMERIC_IDENTIFIER_UDL(ident_name, base_type, suffix) \ MAKE_OPAQUE_NUMERIC_IDENTIFIER(ident_name, base_type) \ MAKE_USER_DEFINED_NUMERIC_LITERAL(ident_name, base_type, suffix) #endif
Bungarch/meta
include/meta/io/zstream.h
<gh_stars>0 /** * @file zstream.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_IO_ZSTREAM_H_ #define META_IO_ZSTREAM_H_ #include <istream> #include <ostream> #include <type_traits> #include "meta/config.h" namespace meta { namespace io { namespace detail { template <class StreamBuf> struct has_bytes_read { template <class T> static constexpr auto check(T*) -> typename std::is_same<decltype(std::declval<T>().bytes_read()), uint64_t>::type; template <class> static constexpr auto check(...) -> std::false_type; using type = decltype(check<StreamBuf>(nullptr)); const static constexpr bool value = type::value; }; } template <class StreamBase, class ZStreamBuf> class zfstream : public StreamBase { public: using streambuf_type = ZStreamBuf; explicit zfstream(const std::string& name, const char* openmode) : StreamBase{&buffer_}, buffer_{name.c_str(), openmode} { if (buffer_.is_open()) this->clear(); else this->setstate(std::ios::badbit); } streambuf_type* rdbuf() const { return const_cast<streambuf_type*>(&buffer_); } void flush() { buffer_.sync(); } template <class T = ZStreamBuf> typename std::enable_if<detail::has_bytes_read<T>::value && std::is_same<StreamBase, std::istream>::value, uint64_t>::type bytes_read() const { return buffer_.bytes_read(); } private: streambuf_type buffer_; }; /** * A base class for an input stream that reads from a compressed streambuf * object. */ template <class ZStreamBuf> class zifstream : public zfstream<std::istream, ZStreamBuf> { public: explicit zifstream(const std::string& name) : zfstream<std::istream, ZStreamBuf>(name, "rb") { // nothing } }; /** * A base class for an output stream that writes to a compressed streambuf * object. */ template <class ZStreamBuf> class zofstream : public zfstream<std::ostream, ZStreamBuf> { public: explicit zofstream(const std::string& name) : zfstream<std::ostream, ZStreamBuf>(name, "wb") { // nothing } }; } } #endif
Bungarch/meta
tests/farm_hash_test.h
/** * @file farm_hash_test.h * @author <NAME> * * This file contains the test vectors for our farmhashna implementation. * These are ported directly from the MIT Licensed test code on the * google/farmhash repository. * * @see https://github.com/google/farmhash/blob/master/src/farmhash.cc#L4491-L5728 */ #include <vector> #include "bandit/bandit.h" #include "meta/hashing/hashes/farm_hash.h" using namespace snowhouse; namespace { uint32_t create_seed(int offset, int salt) { using namespace meta::hashing::farm; uint32_t h = static_cast<uint32_t>(static_cast<unsigned>(salt) & 0xffffffff); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); h += static_cast<uint32_t>(static_cast<unsigned>(offset) & 0xffffffff); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); h = h * c1; h ^= (h >> 17); return h; } uint32_t expected[] = { 1140953930u, 861465670u, 3277735313u, 2681724312u, 2598464059u, 797982799u, 890626835u, 800175912u, 2603993599u, 921001710u, 1410420968u, 2134990486u, 3283896453u, 1867689945u, 2914424215u, 2244477846u, 255297188u, 2992121793u, 1110588164u, 4186314283u, 161451183u, 3943596029u, 4019337850u, 452431531u, 283198166u, 2741341286u, 3379021470u, 2557197665u, 299850021u, 2532580744u, 452473466u, 1706958772u, 1298374911u, 3099673830u, 2199864459u, 3696623795u, 236935126u, 2976578695u, 4055299123u, 3281581178u, 1053458494u, 1882212500u, 2305012065u, 2169731866u, 3456121707u, 275903667u, 458884671u, 3033004529u, 3058973506u, 2379411653u, 1898235244u, 1402319660u, 2700149065u, 2699376854u, 147814787u, 720739346u, 2433714046u, 4222949502u, 4220361840u, 1712034059u, 3425469811u, 3690733394u, 4148372108u, 1330324210u, 594028478u, 2921867846u, 1635026870u, 192883107u, 780716741u, 1728752234u, 3280331829u, 326029180u, 3969463346u, 1436364519u, 393215742u, 3349570000u, 3824583307u, 1612122221u, 2859809759u, 3808705738u, 1379537552u, 1646032583u, 2233466664u, 1432476832u, 4023053163u, 2650381482u, 2052294713u, 3552092450u, 1628777059u, 1499109081u, 3476440786u, 3829307897u, 2960536756u, 1554038301u, 1145519619u, 3190844552u, 2902102606u, 3600725550u, 237495366u, 540224401u, 65721842u, 489963606u, 1448662590u, 397635823u, 1596489240u, 1562872448u, 1790705123u, 2128624475u, 180854224u, 2604346966u, 1435705557u, 1262831810u, 155445229u, 1672724608u, 1669465176u, 1341975128u, 663607706u, 2077310004u, 3610042449u, 1911523866u, 1043692997u, 1454396064u, 2563776023u, 294527927u, 1099072299u, 1389770549u, 703505868u, 678706990u, 2952353448u, 2026137563u, 3603803785u, 629449419u, 1933894405u, 3043213226u, 226132789u, 2489287368u, 1552847036u, 645684964u, 3828089804u, 3632594520u, 187883449u, 230403464u, 3151491850u, 3272648435u, 3729087873u, 1303930448u, 2002861219u, 165370827u, 916494250u, 1230085527u, 3103338579u, 3064290191u, 3807265751u, 3628174014u, 231181488u, 851743255u, 2295806711u, 1781190011u, 2988893883u, 1554380634u, 1142264800u, 3667013118u, 1968445277u, 315203929u, 2638023604u, 2290487377u, 732137533u, 1909203251u, 440398219u, 1891630171u, 1380301172u, 1498556724u, 4072067757u, 4165088768u, 4204318635u, 441430649u, 3931792696u, 197618179u, 956300927u, 914413116u, 3010839769u, 2837339569u, 2148126371u, 1913303225u, 3074915312u, 3117299654u, 4139181436u, 2993479124u, 3178848746u, 1357272220u, 1438494951u, 507436733u, 667183474u, 2084369203u, 3854939912u, 1413396341u, 126024219u, 146044391u, 1016656857u, 3022024459u, 3254014218u, 429095991u, 165589978u, 1578546616u, 985653208u, 1718653828u, 623071693u, 366414107u, 249776086u, 1207522198u, 3047342438u, 2991127487u, 3120876698u, 1684583131u, 46987739u, 1157614300u, 863214540u, 1087193030u, 199124911u, 520792961u, 3614377032u, 586863115u, 3331828431u, 1013201099u, 1716848157u, 4033596884u, 1164298657u, 4140791139u, 1146169032u, 1434258493u, 3824360466u, 3242407770u, 3725511003u, 232064808u, 872586426u, 762243036u, 2736953692u, 816692935u, 512845449u, 3748861010u, 2266795890u, 3781899767u, 4290630595u, 517646945u, 22638523u, 648000590u, 959214578u, 558910384u, 1283799121u, 3047062993u, 1024246061u, 4027776454u, 3544509313u, 622325861u, 834785312u, 382936554u, 411505255u, 1973395102u, 1825135056u, 2725923798u, 580988377u, 2826990641u, 3474970689u, 1029055034u, 812546227u, 2506885666u, 2584372201u, 1758123094u, 589567754u, 325737734u, 345313518u, 2022370576u, 3886113119u, 3338548567u, 257578986u, 3698087965u, 1776047957u, 1771384107u, 3604937815u, 3198590202u, 2305332220u, 191910725u, 4232136669u, 427759438u, 4244322689u, 542201663u, 3315355162u, 2135941665u, 556609672u, 45845311u, 1175961330u, 3948351189u, 23075771u, 3252374102u, 1634635545u, 4151937410u, 713127376u, 1467786451u, 663013031u, 3444053918u, 2638154051u, 810082938u, 3077742128u, 1062268187u, 2115441882u, 4081398201u, 3735739145u, 2794294783u, 2335576331u, 2560479831u, 1379288194u, 4225182569u, 2442302747u, 3948961926u, 3958366652u, 3067277639u, 3667516477u, 1709989541u, 1516711748u, 2339636583u, 4188504038u, 59581167u, 2725013602u, 3639843023u, 2658147000u, 2643979752u, 3758739543u, 4189944477u, 2470483982u, 877580602u, 2995362413u, 118817200u, 3252925478u, 2062343506u, 3981838403u, 3762572073u, 1231633714u, 4168280671u, 2931588131u, 3284356565u, 1129162571u, 732225574u, 4173605289u, 1407328702u, 1677744031u, 3532596884u, 3232041815u, 1652884780u, 2256541290u, 3459463480u, 3740979556u, 259034107u, 2227121257u, 1426140634u, 3606709555u, 3424793077u, 315836068u, 3200749877u, 1386256573u, 24035717u, 2982018998u, 1811050648u, 234531934u, 1115203611u, 1598686658u, 3146815575u, 1603559457u, 323296368u, 2632963283u, 1778459926u, 739944537u, 579625482u, 3486330348u, 492621815u, 1231665285u, 2457048126u, 3903349120u, 389846205u, 3355404249u, 3275550588u, 1052645068u, 862072556u, 2834153464u, 1481069623u, 2657392572u, 4279236653u, 1688445808u, 701920051u, 3740748788u, 3388062747u, 1873358321u, 2152785640u, 883382081u, 1005815394u, 1020177209u, 734239551u, 2371453141u, 100326520u, 3488500412u, 1279682138u, 2610427744u, 49703572u, 3026361211u, 605900428u, 302392721u, 2509302188u, 1416453607u, 2815915291u, 1862819968u, 519710058u, 2450888314u, 4017598378u, 937074653u, 3035635454u, 1590230729u, 3268013438u, 2710029305u, 12886044u, 3711259084u, 2627383582u, 3895772404u, 648534979u, 260307902u, 855990313u, 3669691805u, 263366740u, 2938543471u, 414331688u, 3080542944u, 3405007814u, 3565059103u, 1190977418u, 390836981u, 1606450012u, 2649808239u, 2514169310u, 2747519432u, 4129538640u, 1721522849u, 492099164u, 792990594u, 3625507637u, 2271095827u, 2993032712u, 2302363854u, 4013112951u, 1111617969u, 2183845740u, 795918276u, 1116991810u, 3110898804u, 3963062126u, 2737064702u, 462795667u, 937372240u, 1343017609u, 1091041189u, 2790555455u, 277024217u, 25485284u, 1166522068u, 1623631848u, 241727183u, 2836158787u, 3112996740u, 573836428u, 2721658101u, 1937681565u, 4175169209u, 3190765433u, 1970000788u, 1668258120u, 114616703u, 954762543u, 199237753u, 4094644498u, 2522281978u, 732086117u, 1756889687u, 2936126607u, 2437031370u, 4103143808u, 3883389541u, 3171090854u, 2483004780u, 1927385370u, 2360538162u, 2740855009u, 4241185118u, 1492209542u, 1672737098u, 2148675559u, 1789864670u, 2434313103u, 2319172611u, 2760941207u, 2636210123u, 1338083267u, 1128080590u, 822806371u, 1199583556u, 314727461u, 1335160250u, 2084630531u, 1156261526u, 316766066u, 112090465u, 3129033323u, 2746885618u, 636616055u, 2582210744u, 1721064910u, 3468394263u, 470463518u, 2076016059u, 408721884u, 2121041886u, 378460278u, 1915948002u, 357324860u, 2301682622u, 2691859523u, 1869756364u, 2429314418u, 2193146527u, 1185564327u, 2614088922u, 1975527044u, 919067651u, 2855948894u, 3662539576u, 1943802836u, 3529473373u, 1490330107u, 366036094u, 3384241033u, 4276268604u, 448403661u, 4271796078u, 1910401882u, 3077107698u, 299427366u, 2035665349u, 3201262636u, 3738454258u, 2554452696u, 3588997135u, 3363895827u, 1267505995u, 1852004679u, 2237827073u, 2803250686u, 3468044908u, 2143572850u, 1728158656u, 1022551180u, 1996680960u, 839529273u, 2400647871u, 2201096054u, 3606433628u, 2597259793u, 3544595875u, 3909443124u, 819278607u, 3447346709u, 806136613u, 2711436388u, 3656063205u, 837475154u, 694525336u, 4070212073u, 4011303412u, 1068395209u, 438095290u, 484603494u, 2673730227u, 737767009u, 642310823u, 3914002299u, 308425103u, 268427550u, 1334387085u, 4069797497u, 4280783219u, 2914011058u, 4243643405u, 2849988118u, 2504230175u, 1817156623u, 2804200483u, 3406991497u, 2948254999u, 2102063419u, 1071272117u, 514889942u, 571972433u, 1246595599u, 1735616066u, 1539151988u, 1230831543u, 277987182u, 4269526481u, 991511607u, 95237878u, 2005032160u, 1291113144u, 626619670u, 3560835907u, 164940926u, 1433635018u, 116647396u, 3039097112u, 2868163232u, 1141645918u, 1764165478u, 881378302u, 2159170082u, 2953647681u, 1011320066u, 184856151u, 1723308975u, 336034862u, 2017579106u, 1476681709u, 147523618u, 3896252223u, 2264728166u, 944743644u, 1694443528u, 2690700128u, 1947321519u, 735478508u, 4058183171u, 260177668u, 505662155u, 2391691262u, 1920739747u, 3216960415u, 1898176786u, 3722741628u, 1511077569u, 449636564u, 983350414u, 2580237367u, 2055059789u, 1103819072u, 2089123665u, 3873755579u, 2718467458u, 3124338704u, 3204250304u, 2475035432u, 1120017626u, 3873758287u, 1982999824u, 2950794582u, 780634378u, 2842141483u, 4029205195u, 1656892865u, 3330993377u, 80890710u, 1953796601u, 3873078673u, 136118734u, 2317676604u, 4199091610u, 1864448181u, 3063437608u, 1699452298u, 1403506686u, 1513069466u, 2348491299u, 4273657745u, 4055855649u, 1805475756u, 2562064338u, 973124563u, 4197091358u, 172861513u, 2858726767u, 4271866024u, 3071338162u, 3590386266u, 2328277259u, 1096050703u, 1189614342u, 459509140u, 771592405u, 817999971u, 3740825152u, 520400189u, 1941874618u, 185232757u, 4032960199u, 3928245258u, 3527721294u, 1301118856u, 752188080u, 3512945009u, 308584855u, 2105373972u, 752872278u, 3823368815u, 3760952096u, 4250142168u, 2565680167u, 3646354146u, 1259957455u, 1085857127u, 3471066607u, 38924274u, 3770488806u, 1083869477u, 3312508103u, 71956383u, 3738784936u, 3099963860u, 1255084262u, 4286969992u, 3621849251u, 1190908967u, 1831557743u, 2363435042u, 54945052u, 4059585566u, 4023974274u, 1788578453u, 3442180039u, 2534883189u, 2432427547u, 3909757989u, 731996369u, 4168347425u, 1356028512u, 2741583197u, 1280920000u, 312887059u, 3259015297u, 3946278527u, 4135481831u, 1281043691u, 1121403845u, 3312292477u, 1819941269u, 1741932545u, 3293015483u, 2127558730u, 713121337u, 2635469238u, 486003418u, 4015067527u, 2976737859u, 2108187161u, 927011680u, 1970188338u, 4177613234u, 1799789551u, 2118505126u, 4134691985u, 1958963937u, 1929210029u, 2555835851u, 2768832862u, 910892050u, 2567532373u, 4075249328u, 86689814u, 3726640307u, 1392137718u, 1240000030u, 4104757832u, 3026358429u, 313797689u, 1435798509u, 3101500919u, 1241665335u, 3573008472u, 3615577014u, 3767659003u, 3134294021u, 4063565523u, 2296824134u, 1541946015u, 3087190425u, 2693152531u, 2199672572u, 2123763822u, 1034244398u, 857839960u, 2515339233u, 2228007483u, 1628096047u, 2116502287u, 2502657424u, 2809830736u, 460237542u, 450205998u, 3646921704u, 3818199357u, 1808504491u, 1950698961u, 2069753399u, 3657033172u, 3734547671u, 4067859590u, 3292597295u, 1106466069u, 356742959u, 2469567432u, 3495418823u, 183440071u, 3248055817u, 3662626864u, 1750561299u, 3926138664u, 4088592524u, 567122118u, 3810297651u, 992181339u, 3384018814u, 3272124369u, 3177596743u, 320086295u, 2316548367u, 100741310u, 451656820u, 4086604273u, 3759628395u, 2553391092u, 1745659881u, 3650357479u, 2390172694u, 330172533u, 767377322u, 526742034u, 4102497288u, 2088767754u, 164402616u, 2482632320u, 2352347393u, 1873658044u, 3861555476u, 2751052984u, 1767810825u, 20037241u, 545143220u, 2594532522u, 472304191u, 3441135892u, 3323383489u, 258785117u, 2977745165u, 2781737565u, 2963590112u, 2756998822u, 207428029u, 2581558559u, 3824717027u, 1258619503u, 3472047571u, 2648427775u, 2360400900u, 2393763818u, 2332399088u, 3932701729u, 884421165u, 1396468647u, 1377764574u, 4061795938u, 1559119087u, 3343596838u, 3604258095u, 1435134775u, 1099809675u, 908163739u, 1418405656u, 368446627u, 3741651161u, 3374512975u, 3542220540u, 3244772570u, 200009340u, 3198975081u, 2521038253u, 4081637863u, 337070226u, 3235259030u, 3897262827u, 736956644u, 641040550u, 644850146u, 1306761320u, 4219448634u, 193750500u, 3293278106u, 1383997679u, 1242645122u, 4109252858u, 450747727u, 3716617561u, 362725793u, 2252520167u, 3377483696u, 1788337208u, 8130777u, 3226734120u, 759239140u, 1012411364u, 1658628529u, 2911512007u, 1002580201u, 1681898320u, 3039016929u, 4294520281u, 367022558u, 3071359622u, 3205848570u, 152989999u, 3839042136u, 2357687350u, 4273132307u, 3898950547u, 1176841812u, 1314157485u, 75443951u, 1027027239u, 1858986613u, 2040551642u, 36574105u, 2603059541u, 3456147251u, 2137668425u, 4077477194u, 3565689036u, 491832241u, 363703593u, 2579177168u, 3589545214u, 265993036u, 1864569342u, 4149035573u, 3189253455u, 1072259310u, 3153745937u, 923017956u, 490608221u, 855846773u, 845706553u, 1018226240u, 1604548872u, 3833372385u, 3287246572u, 2757959551u, 2452872151u, 1553870564u, 1713154780u, 2649450292u, 500120236u, 84251717u, 661869670u, 1444911517u, 2489716881u, 2810524030u, 1561519055u, 3884088359u, 2509890699u, 4247155916u, 1005636939u, 3224066062u, 2774151984u, 2035978240u, 2514910366u, 1478837908u, 3144450144u, 2107011431u, 96459446u, 3587732908u, 2389230590u, 3287635953u, 250533792u, 1235983679u, 4237425634u, 3704645833u, 3882376657u, 2976369049u, 1187061987u, 276949224u, 4100839753u, 1698347543u, 1629662314u, 1556151829u, 3784939568u, 427484362u, 4246879223u, 3155311770u, 4285163791u, 1693376813u, 124492786u, 1858777639u, 3476334357u, 1941442701u, 1121980173u, 3485932087u, 820852908u, 358032121u, 2511026735u, 1873607283u, 2556067450u, 2248275536u, 1528632094u, 1535473864u, 556796152u, 1499201704u, 1472623890u, 1526518503u, 3692729434u, 1476438092u, 2913077464u, 335109599u, 2167614601u, 4121131078u, 3158127917u, 3051522276u, 4046477658u, 2857717851u, 1863977403u, 1341023343u, 692059110u, 1802040304u, 990407433u, 3285847572u, 319814144u, 561105582u, 1540183799u, 4052924496u, 2926590471u, 2244539806u, 439121871u, 3317903224u, 3178387550u, 4265214507u, 82077489u, 1978918971u, 4279668976u, 128732476u, 2853224222u, 464407878u, 4190838199u, 997819001u, 3250520802u, 2330081301u, 4095846095u, 733509243u, 1583801700u, 722314527u, 3552883023u, 1403784280u, 432327540u, 1877837196u, 3912423882u, 505219998u, 696031431u, 908238873u, 4189387259u, 8759461u, 2540185277u, 3385159748u, 381355877u, 2519951681u, 1679786240u, 2019419351u, 4051584612u, 1933923923u, 3768201861u, 1670133081u, 3454981037u, 700836153u, 1675560450u, 371560700u, 338262316u, 847351840u, 2222395828u, 3130433948u, 405251683u, 3037574880u, 184098830u, 453340528u, 1385561439u, 2224044848u, 4071581802u, 1431235296u, 5570097u, 570114376u, 2287305551u, 2272418128u, 803575837u, 3943113491u, 414959787u, 708083137u, 2452657767u, 4019147902u, 3841480082u, 3791794715u, 2965956183u, 2763690963u, 2350937598u, 3424361375u, 779434428u, 1274947212u, 686105485u, 3426668051u, 3692865672u, 3057021940u, 2285701422u, 349809124u, 1379278508u, 3623750518u, 215970497u, 1783152480u, 823305654u, 216118434u, 1787189830u, 3692048450u, 2272612521u, 3032187389u, 4159715581u, 1388133148u, 1611772864u, 2544383526u, 552925303u, 3420960112u, 3198900547u, 3503230228u, 2603352423u, 2318375898u, 4064071435u, 3006227299u, 4194096960u, 1283392422u, 1510460996u, 174272138u, 3671038966u, 1775955687u, 1719108984u, 1763892006u, 1385029063u, 4083790740u, 406757708u, 684087286u, 531310503u, 3329923157u, 3492083607u, 1059031410u, 3037314475u, 3105682208u, 3382290593u, 2292208503u, 426380557u, 97373678u, 3842309471u, 777173623u, 3241407531u, 303065016u, 1477104583u, 4234905200u, 2512514774u, 2649684057u, 1397502982u, 1802596032u, 3973022223u, 2543566442u, 3139578968u, 3193669211u, 811750340u, 4013496209u, 567361887u, 4169410406u, 3622282782u, 3403136990u, 2540585554u, 895210040u, 3862229802u, 1145435213u, 4146963980u, 784952939u, 943914610u, 573034522u, 464420660u, 2356867109u, 3054347639u, 3985088434u, 1911188923u, 583391304u, 176468511u, 2990150068u, 2338031599u, 519948041u, 3181425568u, 496106033u, 4110294665u, 2736756930u, 1196757691u, 1089679033u, 240953857u, 3399092928u, 4040779538u, 2843673626u, 240495962u, 3017658263u, 3828377737u, 4243717901u, 2448373688u, 2759616657u, 2246245780u, 308018483u, 4262383425u, 2731780771u, 328023017u, 2884443148u, 841480070u, 3188015819u, 4051263539u, 2298178908u, 2944209234u, 1372958390u, 4164532914u, 4074952232u, 1683612329u, 2155036654u, 1872815858u, 2041174279u, 2368092311u, 206775997u, 2283918569u, 645945606u, 115406202u, 4206471368u, 3923500892u, 2217060665u, 350160869u, 706531239u, 2824302286u, 509981657u, 1469342315u, 140980u, 1891558063u, 164887091u, 3094962711u, 3437115622u, 13327420u, 422986366u, 330624974u, 3630863408u, 2425505046u, 824008515u, 3543885677u, 918718096u, 376390582u, 3224043675u, 3724791476u, 1837192976u, 2968738516u, 3424344721u, 3187805406u, 1550978788u, 1743089918u, 4251270061u, 645016762u, 3855037968u, 1928519266u, 1373803416u, 2289007286u, 1889218686u, 1610271373u, 3059200728u, 2108753646u, 582042641u, 812347242u, 3188172418u, 191994904u, 1343511943u, 2247006571u, 463291708u, 2697254095u, 1534175504u, 1106275740u, 622521957u, 917121602u, 4095777215u, 3955972648u, 3852234638u, 2845309942u, 3299763344u, 2864033668u, 2554947496u, 799569078u, 2551629074u, 1102873346u, 2661022773u, 2006922227u, 2900438444u, 1448194126u, 1321567432u, 1983773590u, 1237256330u, 3449066284u, 1691553115u, 3274671549u, 4271625619u, 2741371614u, 3285899651u, 786322314u, 1586632825u, 564385522u, 2530557509u, 2974240289u, 1244759631u, 3263135197u, 3592389776u, 3570296884u, 2749873561u, 521432811u, 987586766u, 3206261120u, 1327840078u, 4078716491u, 1753812954u, 976892272u, 1827135136u, 1781944746u, 1328622957u, 1015377974u, 3439601008u, 2209584557u, 2482286699u, 1109175923u, 874877499u, 2036083451u, 483570344u, 1091877599u, 4190721328u, 1129462471u, 640035849u, 1867372700u, 920761165u, 3273688770u, 1623777358u, 3389003793u, 3241132743u, 2734783008u, 696674661u, 2502161880u, 1646071378u, 1164309901u, 350411888u, 1978005963u, 2253937037u, 7371540u, 989577914u, 3626554867u, 3214796883u, 531343826u, 398899695u, 1145247203u, 1516846461u, 3656006011u, 529303412u, 3318455811u, 3062828129u, 1696355359u, 3698796465u, 3155218919u, 1457595996u, 3191404246u, 1395609912u, 2917345728u, 1237411891u, 1854985978u, 1091884675u, 3504488111u, 3109924189u, 1628881950u, 3939149151u, 878608872u, 778235395u, 1052990614u, 903730231u, 2069566979u, 2437686324u, 3163786257u, 2257884264u, 2123173186u, 939764916u, 2933010098u, 1235300371u, 1256485167u, 1950274665u, 2180372319u, 2648400302u, 122035049u, 1883344352u, 2083771672u, 3712110541u, 321199441u, 1896357377u, 508560958u, 3066325351u, 2770847216u, 3177982504u, 296902736u, 1486926688u, 456842861u, 601221482u, 3992583643u, 2794121515u, 1533934172u, 1706465470u, 4281971893u, 2557027816u, 900741486u, 227175484u, 550595824u, 690918144u, 2825943628u, 90375300u, 300318232u, 1985329734u, 1440763373u, 3670603707u, 2533900859u, 3253901179u, 542270815u, 3677388841u, 307706478u, 2570910669u, 3320103693u, 1273768482u, 1216399252u, 1652924805u, 1043647584u, 1120323676u, 639941430u, 325675502u, 3652676161u, 4241680335u, 1545838362u, 1991398008u, 4100211814u, 1097584090u, 3262252593u, 2254324292u, 1765019121u, 4060211241u, 2315856188u, 3704419305u, 411263051u, 238929055u, 3540688404u, 3094544537u, 3250435765u, 3460621305u, 1967599860u, 2016157366u, 847389916u, 1659615591u, 4020453639u, 901109753u, 2682611693u, 1661364280u, 177155177u, 3210561911u, 3802058181u, 797089608u, 3286110054u, 2110358240u, 1353279028u, 2479975820u, 471725410u, 2219863904u, 3623364733u, 3167128228u, 1052188336u, 3656587111u, 721788662u, 3061255808u, 1615375832u, 924941453u, 2547780700u, 3328169224u, 1310964134u, 2701956286u, 4145497671u, 1421461094u, 1221397398u, 1589183618u, 1492533854u, 449740816u, 2686506989u, 3035198924u, 1682886232u, 2529760244u, 3342031659u, 1235084019u, 2151665147u, 2315686577u, 3282027660u, 1140138691u, 2754346599u, 2091754612u, 1178454681u, 4226896579u, 2942520471u, 2122168506u, 3751680858u, 3213794286u, 2601416506u, 4142747914u, 3951404257u, 4243249649u, 748595836u, 4004834921u, 238887261u, 1927321047u, 2217148444u, 205977665u, 1885975275u, 186020771u, 2367569534u, 2941662631u, 2608559272u, 3342096731u, 741809437u, 1962659444u, 3539886328u, 3036596491u, 2282550094u, 2366462727u, 2748286642u, 2144472852u, 1390394371u, 1257385924u, 2205425874u, 2119055686u, 46865323u, 3597555910u, 3188438773u, 2372320753u, 3641116924u, 3116286108u, 2680722658u, 3371014971u, 2058751609u, 2966943726u, 2345078707u, 2330535244u, 4013841927u, 1169588594u, 857915866u, 1875260989u, 3175831309u, 3193475664u, 1955181430u, 923161569u, 4068653043u, 776445899u, 954196929u, 61509556u, 4248237857u, 3808667664u, 581227317u, 2893240187u, 4159497403u, 4212264930u, 3973886195u, 2077539039u, 851579036u, 2957587591u, 772351886u, 1173659554u, 946748363u, 2794103714u, 2094375930u, 4234750213u, 3671645488u, 2614250782u, 2620465358u, 3122317317u, 2365436865u, 3393973390u, 523513960u, 3645735309u, 2766686992u, 2023960931u, 2312244996u, 1875932218u, 3253711056u, 3622416881u, 3274929205u, 612094988u, 1555465129u, 2114270406u, 3553762793u, 1832633644u, 1087551556u, 3306195841u, 1702313921u, 3675066046u, 1735998785u, 1690923980u, 1482649756u, 1171351291u, 2043136409u, 1962596992u, 461214626u, 3278253346u, 1392428048u, 3744621107u, 1028502697u, 3991171462u, 1014064003u, 3642345425u, 3186995039u, 6114625u, 3359104346u, 414856965u, 2814387514u, 3583605071u, 2497896367u, 1024572712u, 1927582962u, 2892797583u, 845302635u, 328548052u, 1523379748u, 3392622118u, 1347167673u, 1012316581u, 37767602u, 2647726017u, 1070326065u, 2075035198u, 4202817168u, 2502924707u, 2612406822u, 2187115553u, 1180137213u, 701024148u, 1481965992u, 3223787553u, 2083541843u, 203230202u, 3876887380u, 1334816273u, 2870251538u, 2186205850u, 3985213979u, 333533378u, 806507642u, 1010064531u, 713520765u, 3084131515u, 2637421459u, 1703168933u, 1517562266u, 4089081247u, 3231042924u, 3079916123u, 3154574447u, 2253948262u, 1725190035u, 2452539325u, 1343734533u, 213706059u, 2519409656u, 108055211u, 2916327746u, 587001593u, 1917607088u, 4202913084u, 926304016u, 469255411u, 4042080256u, 3498936874u, 246692543u, 495780578u, 438717281u, 2259272650u, 4011324645u, 2836854664u, 2317249321u, 946828752u, 1280403658u, 1905648354u, 2034241661u, 774652981u, 1285694082u, 2200307766u, 2158671727u, 1135162148u, 232040752u, 397012087u, 1717527689u, 1720414106u, 918797022u, 2580119304u, 3568069742u, 2904461070u, 3893453420u, 973817938u, 667499332u, 3785870412u, 2088861715u, 1565179401u, 600903026u, 591806775u, 3512242245u, 997964515u, 2339605347u, 1134342772u, 3234226304u, 4084179455u, 302315791u, 2445626811u, 2590372496u, 345572299u, 2274770442u, 3600587867u, 3706939009u, 1430507980u, 2656330434u, 1079209397u, 2122849632u, 1423705223u, 3826321888u, 3683385276u, 1057038163u, 1242840526u, 3987000643u, 2398253089u, 1538190921u, 1295898647u, 3570196893u, 3065138774u, 3111336863u, 2524949549u, 4203895425u, 3025864372u, 968800353u, 1023721001u, 3763083325u, 526350786u, 635552097u, 2308118370u, 2166472723u, 2196937373u, 2643841788u, 3040011470u, 4010301879u, 2782379560u, 3474682856u, 4201389782u, 4223278891u, 1457302296u, 2251842132u, 1090062008u, 3188219189u, 292733931u, 1424229089u, 1590782640u, 1365212370u, 3975957073u, 3982969588u, 2927147928u, 1048291071u, 2766680094u, 884908196u, 35237839u, 2221180633u, 2490333812u, 4098360768u, 4029081103u, 3490831871u, 2392516272u, 3455379186u, 3948800722u, 335456628u, 2105117968u, 4181629008u, 1044201772u, 3335754111u, 540133451u, 3313113759u, 3786107905u, 2627207327u, 3540337875u, 3473113388u, 3430536378u, 2514123129u, 2124531276u, 3872633376u, 3272957388u, 3501994650u, 2418881542u, 487365389u, 3877672368u, 1512866656u, 3486531087u, 2102955203u, 1136054817u, 3004241477u, 1549075351u, 1302002008u, 3936430045u, 2258587644u, 4109233936u, 3679809321u, 3467083076u, 2484463221u, 1594979755u, 529218470u, 3527024461u, 1147434678u, 106799023u, 1823161970u, 1704656738u, 1675883700u, 3308746763u, 1875093248u, 1352868568u, 1898561846u, 2508994984u, 3177750780u, 4217929592u, 400784472u, 80090315u, 3564414786u, 3841585648u, 3379293868u, 160353261u, 2413172925u, 2378499279u, 673436726u, 1505702418u, 1330977363u, 1853298225u, 3201741245u, 2135714208u, 4069554166u, 3715612384u, 3692488887u, 3680311316u, 4274382900u, 914186796u, 2264886523u, 3869634032u, 1254199592u, 1131020455u, 194781179u, 429923922u, 2763792336u, 2052895198u, 3997373194u, 3440090658u, 2165746386u, 1575500242u, 3463310191u, 2064974716u, 3779513671u, 3106421434u, 880320527u, 3281914119u, 286569042u, 3909096631u, 122359727u, 1429837716u, 252230074u, 4111461225u, 762273136u, 93658514u, 2766407143u, 3623657004u, 3869801679u, 3925695921u, 2390397316u, 2499025338u, 2741806539u, 2507199021u, 1659221866u, 361292116u, 4048761557u, 3797133396u, 1517903247u, 3121647246u, 3884308578u, 1697201500u, 1558800262u, 4150812360u, 3161302278u, 2610217849u, 641564641u, 183814518u, 2075245419u, 611996508u, 2223461433u, 329123979u, 121860586u, 860985829u, 1137889144u, 4018949439u, 2904348960u, 947795261u, 1992594155u, 4255427501u, 2281583851u, 2892637604u, 1478186924u, 3050771207u, 2767035539u, 373510582u, 1963520320u, 3763848370u, 3756817798u, 627269409u, 1806905031u, 1814444610u, 3646665053u, 1822693920u, 278515794u, 584050483u, 4142579188u, 2149745808u, 3193071606u, 1179706341u, 2693495182u, 3259749808u, 644172091u, 880509048u, 3340630542u, 3365160815u, 2384445068u, 3053081915u, 2840648309u, 1986990122u, 1084703471u, 2370410550u, 1627743573u, 2244943480u, 4057483496u, 2611595995u, 2470013639u, 4024732359u, 3987190386u, 873421687u, 2447660175u, 3226583022u, 767655877u, 2528024413u, 1962070688u, 1233635843u, 2163464207u, 659054446u, 854207134u, 258410943u, 4197831420u, 2515400215u, 3100476924u, 1961549594u, 2219491151u, 3997658851u, 163850514u, 470325051u, 2598261204u, 3052145580u, 59836528u, 1376188597u, 966733415u, 850667549u, 3622479237u, 1083731990u, 1525777459u, 4005126532u, 1428155540u, 2781907007u, 943739431u, 1493961005u, 2839096988u, 2000057832u, 1941829603u, 1901484772u, 939810041u, 3377407371u, 3090115837u, 3310840540u, 2068409688u, 3261383939u, 2212130277u, 2594774045u, 2912652418u, 4179816101u, 3534504531u, 3349254805u, 2796552902u, 1385421283u, 4259908631u, 3714780837u, 3070073945u, 3372846298u, 3835884044u, 3047965714u, 3009018735u, 744091167u, 1861124263u, 2764936304u, 1338171648u, 4222019554u, 1395200692u, 1371426007u, 3338031581u, 2525665319u, 4196233786u, 2332743921u, 1474702008u, 2274266301u, 4255175517u, 2290169528u, 1793910997u, 2188254024u, 354202001u, 3864458796u, 4280290498u, 1554419340u, 1733094688u, 2010552302u, 1561807039u, 664313606u, 2548990879u, 1084699349u, 3233936866u, 973895284u, 2386881969u, 1831995860u, 2961465052u, 1428704144u, 3269904970u, 231648253u, 2602483763u, 4125013173u, 3319187387u, 3347011944u, 1892898231u, 4019114049u, 868879116u, 4085937045u, 2378411019u, 1072588531u, 3547435717u, 2208070766u, 1069899078u, 3142980597u, 2337088907u, 1593338562u, 919414554u, 688077849u, 3625708135u, 1472447348u, 1947711896u, 3953006207u, 877438080u, 845995820u, 3150361443u, 3053496713u, 2484577841u, 224271045u, 2914958001u, 2682612949u, 806655563u, 2436224507u, 1907729235u, 2920583824u, 1251814062u, 2070814520u, 4034325578u, 497847539u, 2714317144u, 385182008u, 640855184u, 1327075087u, 1062468773u, 1757405994u, 1374270191u, 4263183176u, 3041193150u, 1037871524u, 3633173991u, 4231821821u, 2830131945u, 3505072908u, 2830570613u, 4195208715u, 575398021u, 3992840257u, 3691788221u, 1949847968u, 2999344380u, 3183782163u, 3723754342u, 759716128u, 3284107364u, 1714496583u, 15918244u, 820509475u, 2553936299u, 2201876606u, 4237151697u, 2605688266u, 3253705097u, 1008333207u, 712158730u, 1722280252u, 1933868287u, 4152736859u, 2097020806u, 584426382u, 2836501956u, 2522777566u, 1996172430u, 2122199776u, 1069285218u, 1474209360u, 690831894u, 107482532u, 3695525410u, 670591796u, 768977505u, 2412057331u, 3647886687u, 3110327607u, 1072658422u, 379861934u, 1557579480u, 4124127129u, 2271365865u, 3880613089u, 739218494u, 547346027u, 388559045u, 3147335977u, 176230425u, 3094853730u, 2554321205u, 1495176194u, 4093461535u, 3521297827u, 4108148413u, 1913727929u, 1177947623u, 1911655402u, 1053371241u, 3265708874u, 1266515850u, 1045540427u, 3194420196u, 3717104621u, 1144474110u, 1464392345u, 52070157u, 4144237690u, 3350490823u, 4166253320u, 2747410691u, }; bool test(uint8_t* data, int offset, int len = 0) { using meta::hashing::farm_hash; using meta::hashing::farm_hash_seeded; using result_type = farm_hash::result_type; static int index = 0; auto check = [&](uint32_t actual) { uint32_t e = expected[index++]; AssertThat(actual, Equals(e)); }; if (offset == -1) { int alive = 0; { farm_hash_seeded hasher{create_seed(offset, 0), create_seed(offset, 1)}; hasher(data, static_cast<std::size_t>(len++)); auto h = static_cast<result_type>(hasher); alive += (h >> 32) > 0; alive += ((h << 32) >> 32) > 0; } { farm_hash_seeded hasher{create_seed(offset, -1)}; hasher(data, static_cast<std::size_t>(len++)); auto h = static_cast<result_type>(hasher); alive += (h >> 32) > 0; alive += ((h << 32) >> 32) > 0; } { farm_hash hasher; hasher(data, static_cast<std::size_t>(len++)); auto h = static_cast<result_type>(hasher); alive += (h >> 32) > 0; alive += ((h << 32) >> 32) > 0; } len -= 3; return alive > 0; } { farm_hash_seeded hasher{create_seed(offset, 0), create_seed(offset, 1)}; hasher(data + offset, static_cast<std::size_t>(len)); auto h = static_cast<result_type>(hasher); check(h >> 32); check((h << 32) >> 32); } { farm_hash_seeded hasher{create_seed(offset, -1)}; hasher(data + offset, static_cast<std::size_t>(len)); auto h = static_cast<result_type>(hasher); check(h >> 32); check((h << 32) >> 32); } { farm_hash hasher; hasher(data + offset, static_cast<std::size_t>(len)); auto h = static_cast<result_type>(hasher); check(h >> 32); check((h << 32) >> 32); } return true; } void farm_hash_self_test() { const static constexpr int data_size = 1 << 20; const static constexpr int test_size = 300; std::vector<uint8_t> data(data_size); // initialize data to pseudorandom values uint64_t a = 9; uint64_t b = 777; for (std::size_t i = 0; i < data_size; ++i) { a += b; b += a; a = (a ^ (a >> 41)) * meta::hashing::farm::k0; b = (b ^ (b >> 41)) * meta::hashing::farm::k0 + static_cast<uint64_t>(i); data[i] = static_cast<uint8_t>(b >> 37); } AssertThat(test(data.data(), -1), Equals(true)); int i = 0; for (; i < test_size - 1; ++i) test(data.data(), i * i, i); for (; i < data_size; i += i / 7) test(data.data(), 0, i); test(data.data(), 0, data_size); } }
Bungarch/meta
include/meta/parser/trees/visitors/visitor.h
/** * @file tree_visitor.h * @author <NAME> * * All files in META are released under the MIT license. For more details, * consult the file LICENSE in the root of the project. */ #ifndef META_PARSE_TREE_VISITOR_H_ #define META_PARSE_TREE_VISITOR_H_ namespace meta { namespace parser { class leaf_node; class internal_node; /** * Abstract base class for visitors over parse trees that do not modify * the underlying tree. */ template <class T> class const_visitor { public: /** * The result of running the visitor over the tree. */ using result_type = T; /** * @return the result of running the visitor on the supplied leaf node */ virtual result_type operator()(const leaf_node&) = 0; /** * @return the result of running the visitor on the supplied internal * node */ virtual result_type operator()(const internal_node&) = 0; virtual ~const_visitor() = default; }; /** * Abstract base class for visitors over parse trees that are allowed to * modify the underlying tree. */ template <class T> class visitor { public: /** * The result of running the visitor over the tree. */ using result_type = T; /** * @return the result of running the visitor on the supplied leaf node */ virtual result_type operator()(leaf_node&) = 0; /** * @return the result of running the visitor on the supplied internal * node */ virtual result_type operator()(internal_node&) = 0; virtual ~visitor() = default; }; } } #endif
Bungarch/meta
include/meta/util/iterator.h
<reponame>Bungarch/meta /** * @file iterator.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_UTIL_ITERATOR_H_ #define META_UTIL_ITERATOR_H_ #include <iterator> #include <type_traits> #include "meta/config.h" namespace meta { namespace util { /** * Wrapper around an Iterator that, when dereferenced, returns f(*it) * where `it` is the wrapped Iterator and `f` is a UnaryFunction. */ template <class Iterator, class UnaryFunction> class transform_iterator { public: using traits_type = std::iterator_traits<Iterator>; using difference_type = typename traits_type::difference_type; using value_type = typename std::result_of<UnaryFunction( typename traits_type::reference)>::type; using pointer = typename std::add_pointer<value_type>::type; using reference = typename std::add_lvalue_reference<const value_type>::type; using iterator_category = typename traits_type::iterator_category; transform_iterator(Iterator it, UnaryFunction fun) : it_{it}, fun_(fun) { // nothing } transform_iterator& operator++() { ++it_; return *this; } transform_iterator operator++(int) { auto tmp = *this; ++it_; return tmp; } transform_iterator& operator--() { --it_; return *this; } transform_iterator operator--(int) { auto tmp = *this; --it_; return *tmp; } transform_iterator& operator+=(difference_type diff) { it_ += diff; return *this; } transform_iterator operator+(difference_type diff) const { auto tmp = *this; tmp += diff; return tmp; } transform_iterator& operator-=(difference_type diff) { it_ -= diff; return *this; } transform_iterator operator-(difference_type diff) const { auto tmp = *this; tmp -= diff; return tmp; } difference_type operator-(const transform_iterator& other) const { return it_ - other.it_; } reference operator[](difference_type diff) const { return fun_(it_[diff]); } bool operator<(const transform_iterator& other) const { return it_ < other.it_; } bool operator<=(const transform_iterator& other) const { return it_ <= other.it_; } bool operator>(const transform_iterator& other) const { return it_ > other.it_; } bool operator>=(const transform_iterator& other) const { return it_ >= other.it_; } bool operator==(const transform_iterator& other) const { return it_ == other.it_; } bool operator!=(const transform_iterator& other) const { return it_ != other.it_; } value_type operator*() const { return fun_(*it_); } private: Iterator it_; UnaryFunction fun_; }; /** * Helper function to construct a transform_iterator from an Iterator and * a UnaryFunction to transform the values of that Iterator. */ template <class Iterator, class UnaryFunction> transform_iterator<Iterator, UnaryFunction> make_transform_iterator(Iterator it, UnaryFunction&& fun) { return transform_iterator<Iterator, UnaryFunction>( it, std::forward<UnaryFunction>(fun)); } } } #endif
Bungarch/meta
include/meta/topics/lda_gibbs_inferencer.h
<gh_stars>0 /** * @file topics/lda_gibbs_inferencer.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_LDA_GIBBS_INFERENCER_H_ #define META_LDA_GIBBS_INFERENCER_H_ #include "meta/config.h" #include "meta/topics/inferencer.h" #include "meta/topics/lda_gibbs.h" namespace meta { namespace topics { /** * An inferencer for topic proportions for unseen documents that uses * collapsed Gibbs sampling for inference. */ class lda_gibbs::inferencer : public meta::topics::inferencer { public: using meta::topics::inferencer::inferencer; /** * Performs inference using collapsed Gibbs sampling to determine the * topic proportions for the supplied document. The topics themselves * are held fixed and are not modified by this function. * * @param doc the document to be analyzed * @param iters the number of iterations of sampling to apply * @param rng the random number generator to use during sampling */ template <class RandomNumberGenerator> stats::multinomial<topic_id> operator()(const learn::feature_vector& doc, std::size_t iters, RandomNumberGenerator&& rng) const { auto doc_size = std::accumulate( doc.begin(), doc.end(), 0.0, [](double accum, const std::pair<learn::feature_id, double>& weight) { return accum + weight.second; }); std::vector<topic_id> assignments(static_cast<std::size_t>(doc_size)); stats::multinomial<topic_id> proportions{proportions_prior()}; for (std::size_t i = 0; i < iters; ++i) { detail::sample_document( doc, num_topics(), assignments, // decrease counts [&](topic_id old_topic, term_id) { if (i > 0) proportions.decrement(old_topic, 1); }, // sample weight [&](topic_id topic, term_id term) { return proportions.probability(topic) * term_distribution(topic).probability(term); }, // increase counts [&](topic_id new_topic, term_id) { proportions.increment(new_topic, 1); }, std::forward<RandomNumberGenerator>(rng)); } return proportions; } }; } } #endif
Bungarch/meta
include/meta/succinct/broadword.h
/** * @file broadword.h * @author <NAME> * * All files in META are dual-licensed under the MIT and NCSA licenses. For more * details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the * project. */ #ifndef META_SUCCINCT_BROADWORD_H_ #define META_SUCCINCT_BROADWORD_H_ #include <cstdint> #if _MSC_VER #include <intrin.h> #endif #include "meta/config.h" namespace meta { namespace succinct { /** * A collection of functions for "broadword" bit operations like * selection, msb and lsb finding, etc. * * Most of the code here is taken from code by <NAME> and * released under the Apache 2.0 license. * * @see https://github.com/ot/succinct/blob/master/broadword.hpp * @see https://github.com/ot/succinct/blob/master/tables.hpp * @see https://github.com/ot/succinct/blob/master/LICENSE */ namespace broadword { const uint8_t select_in_byte[2048] = { 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 8, 8, 8, 1, 8, 2, 2, 1, 8, 3, 3, 1, 3, 2, 2, 1, 8, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 5, 5, 1, 5, 2, 2, 1, 5, 3, 3, 1, 3, 2, 2, 1, 5, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 6, 6, 1, 6, 2, 2, 1, 6, 3, 3, 1, 3, 2, 2, 1, 6, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 6, 5, 5, 1, 5, 2, 2, 1, 5, 3, 3, 1, 3, 2, 2, 1, 5, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 7, 7, 1, 7, 2, 2, 1, 7, 3, 3, 1, 3, 2, 2, 1, 7, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 7, 5, 5, 1, 5, 2, 2, 1, 5, 3, 3, 1, 3, 2, 2, 1, 5, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 7, 6, 6, 1, 6, 2, 2, 1, 6, 3, 3, 1, 3, 2, 2, 1, 6, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 6, 5, 5, 1, 5, 2, 2, 1, 5, 3, 3, 1, 3, 2, 2, 1, 5, 4, 4, 1, 4, 2, 2, 1, 4, 3, 3, 1, 3, 2, 2, 1, 8, 8, 8, 8, 8, 8, 8, 2, 8, 8, 8, 3, 8, 3, 3, 2, 8, 8, 8, 4, 8, 4, 4, 2, 8, 4, 4, 3, 4, 3, 3, 2, 8, 8, 8, 5, 8, 5, 5, 2, 8, 5, 5, 3, 5, 3, 3, 2, 8, 5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3, 4, 3, 3, 2, 8, 8, 8, 6, 8, 6, 6, 2, 8, 6, 6, 3, 6, 3, 3, 2, 8, 6, 6, 4, 6, 4, 4, 2, 6, 4, 4, 3, 4, 3, 3, 2, 8, 6, 6, 5, 6, 5, 5, 2, 6, 5, 5, 3, 5, 3, 3, 2, 6, 5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3, 4, 3, 3, 2, 8, 8, 8, 7, 8, 7, 7, 2, 8, 7, 7, 3, 7, 3, 3, 2, 8, 7, 7, 4, 7, 4, 4, 2, 7, 4, 4, 3, 4, 3, 3, 2, 8, 7, 7, 5, 7, 5, 5, 2, 7, 5, 5, 3, 5, 3, 3, 2, 7, 5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3, 4, 3, 3, 2, 8, 7, 7, 6, 7, 6, 6, 2, 7, 6, 6, 3, 6, 3, 3, 2, 7, 6, 6, 4, 6, 4, 4, 2, 6, 4, 4, 3, 4, 3, 3, 2, 7, 6, 6, 5, 6, 5, 5, 2, 6, 5, 5, 3, 5, 3, 3, 2, 6, 5, 5, 4, 5, 4, 4, 2, 5, 4, 4, 3, 4, 3, 3, 2, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 3, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 4, 8, 4, 4, 3, 8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8, 5, 8, 5, 5, 3, 8, 8, 8, 5, 8, 5, 5, 4, 8, 5, 5, 4, 5, 4, 4, 3, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 6, 8, 6, 6, 3, 8, 8, 8, 6, 8, 6, 6, 4, 8, 6, 6, 4, 6, 4, 4, 3, 8, 8, 8, 6, 8, 6, 6, 5, 8, 6, 6, 5, 6, 5, 5, 3, 8, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 3, 8, 8, 8, 7, 8, 7, 7, 4, 8, 7, 7, 4, 7, 4, 4, 3, 8, 8, 8, 7, 8, 7, 7, 5, 8, 7, 7, 5, 7, 5, 5, 3, 8, 7, 7, 5, 7, 5, 5, 4, 7, 5, 5, 4, 5, 4, 4, 3, 8, 8, 8, 7, 8, 7, 7, 6, 8, 7, 7, 6, 7, 6, 6, 3, 8, 7, 7, 6, 7, 6, 6, 4, 7, 6, 6, 4, 6, 4, 4, 3, 8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6, 5, 5, 3, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8, 5, 8, 5, 5, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 6, 8, 6, 6, 4, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 6, 8, 6, 6, 5, 8, 8, 8, 6, 8, 6, 6, 5, 8, 6, 6, 5, 6, 5, 5, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 4, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 5, 8, 8, 8, 7, 8, 7, 7, 5, 8, 7, 7, 5, 7, 5, 5, 4, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 6, 8, 8, 8, 7, 8, 7, 7, 6, 8, 7, 7, 6, 7, 6, 6, 4, 8, 8, 8, 7, 8, 7, 7, 6, 8, 7, 7, 6, 7, 6, 6, 5, 8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6, 5, 5, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 6, 8, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 6, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 6, 8, 8, 8, 7, 8, 7, 7, 6, 8, 7, 7, 6, 7, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 7, 8, 7, 7, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7}; const static constexpr uint64_t ones_step_4 = 0x1111111111111111ULL; const static constexpr uint64_t ones_step_8 = 0x0101010101010101ULL; const static constexpr uint64_t msbs_step_8 = 0x80ULL * ones_step_8; inline uint64_t byte_counts(uint64_t word) { word = word - ((word & 0xa * ones_step_4) >> 1); word = (word & 3 * ones_step_4) + ((word >> 2) & 3 * ones_step_4); word = (word + (word >> 4)) & 0x0f * ones_step_8; return word; } inline uint64_t bytes_sum(uint64_t word) { return word * ones_step_8 >> 56; } inline uint64_t popcount(uint64_t word) { #if META_HAS_BUILTIN_POPCOUNTLL return static_cast<uint64_t>(__builtin_popcountll(word)); #elif META_HAS_POPCOUNT64 return static_cast<uint64_t>(__popcnt64(word)); #else return bytes_sum(byte_counts(word)); #endif } inline uint64_t lsb(uint64_t word) { // TODO: how good is the builtin here when it's not a single instruction? #if META_HAS_BUILTIN_CTZLL return static_cast<uint64_t>(__builtin_ctzll(word)); #elif META_HAS_BITSCANFORWARD64 unsigned long val; if (_BitScanForward64(&val, word)) return static_cast<uint64_t>(val); #else unsigned long val; if (_BitScanForward(&val, static_cast<unsigned long>(word))) return static_cast<uint64_t>(val); if (_BitScanForward(&val, static_cast<unsigned long>(word >> 32))) return 32 + static_cast<uint64_t>(val); #endif return 64; } inline uint64_t msb(uint64_t word) { return 63 - lsb(word); } inline uint64_t select_in_word(uint64_t word, uint64_t k) { uint64_t byte_sums = byte_counts(word) * ones_step_8; const uint64_t k_step_8 = k * ones_step_8; const uint64_t geq_k_step_8 = (((k_step_8 | msbs_step_8) - byte_sums) & msbs_step_8); #if META_HAS_BUILTIN_POPCOUNTLL || META_HAS_POPCOUNT64 const uint64_t place = popcount(geq_k_step_8) * 8; #else const uint64_t place = ((geq_k_step_8 >> 7) * ones_step_8 >> 53) & ~uint64_t(0x7); #endif const uint64_t byte_rank = k - (((byte_sums << 8) >> place) & uint64_t(0xFF)); return place + select_in_byte[((word >> place) & 0xFF) | (byte_rank << 8)]; } } } } #endif