hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dae53245f62fea7a54ed6926505324621f29f39b | 1,056 | cpp | C++ | roman-to-integer.cpp | isanchez-aguilar/LeetCode-Solutions | 094c15b672efa6ca2581f187579303c8b94390a3 | [
"MIT"
] | null | null | null | roman-to-integer.cpp | isanchez-aguilar/LeetCode-Solutions | 094c15b672efa6ca2581f187579303c8b94390a3 | [
"MIT"
] | null | null | null | roman-to-integer.cpp | isanchez-aguilar/LeetCode-Solutions | 094c15b672efa6ca2581f187579303c8b94390a3 | [
"MIT"
] | null | null | null | class Solution {
public:
static int getValueOfChar(char c) {
if (c == 'I')
return 1;
if (c == 'V')
return 5;
if (c == 'X')
return 10;
if (c == 'L')
return 50;
if (c == 'C')
return 100;
if (c == 'D')
return 500;
return 1000;
}
/*
** Time complexity: O(|s|)
** Space complexity: O(1)
*/
int romanToInt(string s) {
int answer = 0;
int currentSum = getValueOfChar(s[0]);
int prevVal = currentSum;
const int size = s.size();
for (int i = 1; i < size; ++i) {
const int symbolValue = getValueOfChar(s[i]);
if (symbolValue == prevVal) {
currentSum += symbolValue;
}
if (symbolValue < prevVal) {
answer += currentSum;
currentSum = symbolValue;
}
if (prevVal < symbolValue) {
answer += symbolValue - currentSum;
currentSum = 0;
}
prevVal = symbolValue;
}
answer += currentSum;
return answer;
}
};
| 17.311475 | 51 | 0.482008 |
daea7fa9d026ab64bc6657d418427ad9b130ff80 | 1,291 | cpp | C++ | src/modelFactory/FindSCMain.cpp | toebs88/SCAM | 0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca | [
"MIT"
] | 3 | 2018-08-31T21:35:27.000Z | 2018-10-29T04:06:46.000Z | src/modelFactory/FindSCMain.cpp | toebs88/SCAM | 0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca | [
"MIT"
] | 1 | 2018-04-20T12:38:22.000Z | 2018-04-20T12:38:55.000Z | src/modelFactory/FindSCMain.cpp | toebs88/SCAM | 0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca | [
"MIT"
] | null | null | null | #include <iostream>
#include "FindSCMain.h"
namespace SCAM {
FindSCMain::FindSCMain(clang::TranslationUnitDecl *tuDecl):
pass(0),
scMainFound(false),
_scmainFunctionDecl(NULL){
assert (!(tuDecl == NULL));
//Find sc_main
TraverseDecl(tuDecl);
//Is found
}
bool FindSCMain::VisitFunctionDecl(clang::FunctionDecl *functionDecl) {
/// Find sc_main.
/// There are three conditions to satisfy this:
/// 1. Must have sc_main in its name.
/// 2. Must have a body
/// 3. Must *not* be a first declaration. (This is becuase systemc.h includes a null definition of sc_main.
if ((functionDecl->getNameInfo().getAsString() == "sc_main") && (functionDecl->hasBody())) {
//Pass the null definition of main
if(pass == 1){
_scmainFunctionDecl = functionDecl;
scMainFound = true;
return false;
}
pass = 1;
}
return true;
}
clang::FunctionDecl *FindSCMain::getSCMainFunctionDecl() {
assert (!(_scmainFunctionDecl == NULL));
return _scmainFunctionDecl;
}
bool FindSCMain::isScMainFound() const {
return scMainFound;
}
} | 28.688889 | 115 | 0.570875 |
daf21b6cc2dad19ff68ccdb7b99cafead549e91a | 8,908 | cpp | C++ | modules/xfeatures2d/src/pct_signatures_sqfd.cpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 7,158 | 2016-07-04T22:19:27.000Z | 2022-03-31T07:54:32.000Z | modules/xfeatures2d/src/pct_signatures_sqfd.cpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 2,184 | 2016-07-05T12:04:14.000Z | 2022-03-30T19:10:12.000Z | modules/xfeatures2d/src/pct_signatures_sqfd.cpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 5,535 | 2016-07-06T12:01:10.000Z | 2022-03-31T03:13:24.000Z | /*
By downloading, copying, installing or using the software you agree to this license.
If you do not agree to this license, do not download, install,
copy or use the software.
License Agreement
For Open Source Computer Vision Library
(3-clause BSD License)
Copyright (C) 2000-2016, Intel Corporation, all rights reserved.
Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved.
Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved.
Copyright (C) 2015-2016, Itseez Inc., all rights reserved.
Third party copyrights are property of their respective owners.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the copyright holders nor the names of the contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are disclaimed.
In no event shall copyright holders or contributors be liable for any direct,
indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused
and on any theory of liability, whether in contract, strict liability,
or tort (including negligence or otherwise) arising in any way out of
the use of this software, even if advised of the possibility of such damage.
*/
/*
Contributed by Gregor Kovalcik <gregor dot kovalcik at gmail dot com>
based on code provided by Martin Krulis, Jakub Lokoc and Tomas Skopal.
References:
Martin Krulis, Jakub Lokoc, Tomas Skopal.
Efficient Extraction of Clustering-Based Feature Signatures Using GPU Architectures.
Multimedia tools and applications, 75(13), pp.: 8071�8103, Springer, ISSN: 1380-7501, 2016
Christian Beecks, Merih Seran Uysal, Thomas Seidl.
Signature quadratic form distance.
In Proceedings of the ACM International Conference on Image and Video Retrieval, pages 438-445.
ACM, 2010.
*/
#include "precomp.hpp"
#include "pct_signatures/constants.hpp"
#include "pct_signatures/similarity.hpp"
namespace cv
{
namespace xfeatures2d
{
namespace pct_signatures
{
class PCTSignaturesSQFD_Impl : public PCTSignaturesSQFD
{
public:
PCTSignaturesSQFD_Impl(
const int distanceFunction,
const int similarityFunction,
const float similarityParameter)
: mDistanceFunction(distanceFunction),
mSimilarityFunction(similarityFunction),
mSimilarityParameter(similarityParameter)
{
}
float computeQuadraticFormDistance(
InputArray _signature0,
InputArray _signature1) const CV_OVERRIDE;
void computeQuadraticFormDistances(
const Mat& sourceSignature,
const std::vector<Mat>& imageSignatures,
std::vector<float>& distances) const CV_OVERRIDE;
private:
int mDistanceFunction;
int mSimilarityFunction;
float mSimilarityParameter;
float computePartialSQFD(
const Mat& signature0,
const Mat& signature1) const;
};
/**
* @brief Class implementing parallel computing of SQFD distance for multiple images.
*/
class Parallel_computeSQFDs : public ParallelLoopBody
{
private:
const PCTSignaturesSQFD* mPctSignaturesSQFDAlgorithm;
const Mat* mSourceSignature;
const std::vector<Mat>* mImageSignatures;
std::vector<float>* mDistances;
public:
Parallel_computeSQFDs(
const PCTSignaturesSQFD* pctSignaturesSQFDAlgorithm,
const Mat* sourceSignature,
const std::vector<Mat>* imageSignatures,
std::vector<float>* distances)
: mPctSignaturesSQFDAlgorithm(pctSignaturesSQFDAlgorithm),
mSourceSignature(sourceSignature),
mImageSignatures(imageSignatures),
mDistances(distances)
{
mDistances->resize(imageSignatures->size());
}
void operator()(const Range& range) const CV_OVERRIDE
{
if (mSourceSignature->empty())
{
CV_Error(Error::StsBadArg, "Source signature is empty!");
}
for (int i = range.start; i < range.end; i++)
{
if (mImageSignatures[i].empty())
{
CV_Error_(Error::StsBadArg, ("Signature ID: %d is empty!", i));
}
(*mDistances)[i] = mPctSignaturesSQFDAlgorithm->computeQuadraticFormDistance(
*mSourceSignature, (*mImageSignatures)[i]);
}
}
};
float PCTSignaturesSQFD_Impl::computeQuadraticFormDistance(
InputArray _signature0,
InputArray _signature1) const
{
// check input
if (_signature0.empty() || _signature1.empty())
{
CV_Error(Error::StsBadArg, "Empty signature!");
}
Mat signature0 = _signature0.getMat();
Mat signature1 = _signature1.getMat();
if (signature0.cols != SIGNATURE_DIMENSION || signature1.cols != SIGNATURE_DIMENSION)
{
CV_Error_(Error::StsBadArg, ("Signature dimension must be %d!", SIGNATURE_DIMENSION));
}
if (signature0.rows <= 0 || signature1.rows <= 0)
{
CV_Error(Error::StsBadArg, "Signature count must be greater than 0!");
}
// compute sqfd
float result = 0;
result += computePartialSQFD(signature0, signature0);
result += computePartialSQFD(signature1, signature1);
result -= computePartialSQFD(signature0, signature1) * 2;
return sqrt(result);
}
void PCTSignaturesSQFD_Impl::computeQuadraticFormDistances(
const Mat& sourceSignature,
const std::vector<Mat>& imageSignatures,
std::vector<float>& distances) const
{
parallel_for_(Range(0, (int)imageSignatures.size()),
Parallel_computeSQFDs(this, &sourceSignature, &imageSignatures, &distances));
}
float PCTSignaturesSQFD_Impl::computePartialSQFD(
const Mat& signature0,
const Mat& signature1) const
{
float result = 0;
for (int i = 0; i < signature0.rows; i++)
{
for (int j = 0; j < signature1.rows; j++)
{
result += signature0.at<float>(i, WEIGHT_IDX) * signature1.at<float>(j, WEIGHT_IDX)
* computeSimilarity(mDistanceFunction, mSimilarityFunction, mSimilarityParameter, signature0, i, signature1, j);
}
}
return result;
}
}// end of namespace pct_signatures
Ptr<PCTSignaturesSQFD> PCTSignaturesSQFD::create(
const int distanceFunction,
const int similarityFunction,
const float similarityParameter)
{
return makePtr<pct_signatures::PCTSignaturesSQFD_Impl>(distanceFunction, similarityFunction, similarityParameter);
}
}
}
| 39.591111 | 140 | 0.591828 |
daf3166dce0501452596e89e418449bde63c9607 | 5,965 | cpp | C++ | StartDialog.cpp | KaikiasVind/CellBadger | c21adf5feec7766decfd4d89a110364d4bdfbc46 | [
"MIT"
] | null | null | null | StartDialog.cpp | KaikiasVind/CellBadger | c21adf5feec7766decfd4d89a110364d4bdfbc46 | [
"MIT"
] | null | null | null | StartDialog.cpp | KaikiasVind/CellBadger | c21adf5feec7766decfd4d89a110364d4bdfbc46 | [
"MIT"
] | null | null | null | #include "StartDialog.h"
#include "ui_StartDialog.h"
#include <QStringList>
#include <QFileDialog>
#include <QDir>
#include <QDebug>
#include <QPushButton>
#include <QLabel>
#include <QObject>
#include <QAction>
#include <QMouseEvent>
#include "Utils/Helper.h"
using Helper::chopFileName;
using Helper::openFileDialog;
/**
* @brief StartDialog::StartDialog
* @param parent
*/
StartDialog::StartDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::StartDialog)
{
ui->setupUi(this);
this->setWindowFlags(Qt::FramelessWindowHint);
ui->stackedWidget->setCurrentIndex(0);
ui->buttonRun->setDisabled(true);
}
/**
* @brief StartDialog::~StartDialog
*/
StartDialog::~StartDialog() { /*REMEMBER: What should be done here?*/ }
/**
* @brief StartDialog::createPushButton
* @return
*/
QPushButton * StartDialog::createPushButton() {
QPushButton * button = new QPushButton();
button->setText("+");
return button;
}
/**
* @brief StartDialog::addDatasetToLayout
* @param name
*/
void StartDialog::addDatasetToLayout(const QString filePath) {
QString fileName = chopFileName(filePath);
QListWidgetItem * item = new QListWidgetItem(fileName);
ui->listDatasets->addItem(item);
}
/**
* @brief StartDialog::enableRunButtonIfReady - If every requirement is set, enable the run button
*/
void StartDialog::enableRunButtonIfReady() {
bool isUploadedDataset = !uploadedDatasets.isEmpty();
bool isUseDefaultSelected = ui->checkBoxUseDefault->isChecked();
bool isCustomMarkerFileUploaded = !uploadedMarkerFile.isNull();
if (isUploadedDataset && (isUseDefaultSelected || isCustomMarkerFileUploaded)) {
ui->buttonRun->setEnabled(true);
}
}
/**
* @brief StartDialog::disableUseDefaultButton - Disables the default button (in case no valid default file was found)
*/
void StartDialog::disableUseDefaultButton() {
this->ui->checkBoxUseDefault->setDisabled(true);
}
// ++++++++++++++++++++++++++++++++ SLOTS ++++++++++++++++++++++++++++++++
// STACKED WIDGET PAGE ONE
/**
* @brief StartDialog::on_buttonMenuBarExit_clicked
*/
__attribute__((noreturn)) void StartDialog::on_buttonMenuBarExit_clicked() {
exit(0);
}
/**
* @brief StartDialog::on_buttonExit_clicked
*/
__attribute__((noreturn)) void StartDialog::on_buttonExit_clicked() {
exit(0);
}
/**
* @brief StartDialog::on_buttonLoadProject_clicked
*/
void StartDialog::on_buttonLoadProject_clicked() {
QStringList csvMimeTypes = { "text/plain" };
QStringList fileNames = openFileDialog(this, csvMimeTypes, false);
if (fileNames.empty())
return;
qDebug() << "Sent project file name.";
}
/**
* @brief StartDialog::on_buttonNewProject_clicked
*/
void StartDialog::on_buttonNewProject_clicked() {
ui->stackedWidget->setCurrentIndex(1);
}
// STACKED WIDGET PAGE TWO
/**
* @brief StartDialog::on_buttonMenuBarBack_clicked
*/
void StartDialog::on_buttonMenuBarBack_clicked() {
ui->stackedWidget->setCurrentIndex(0);
}
/**
* @brief StartDialog::on_checkBoxUseDefault_stateChanged
* @param state
*/
void StartDialog::on_checkBoxUseDefault_stateChanged(int state) {
if (state == Qt::CheckState::Checked) {
ui->buttonLoadCustom->setDisabled(true);
// REMEMBER: This should be done differently
uploadedMarkerFile = "nAn";
enableRunButtonIfReady();
} else {
ui->buttonLoadCustom->setDisabled(false);
ui->buttonRun->setDisabled(true);
}
}
/**
* @brief StartDialog::on_buttonMenuBarExit_2_clicked
*/
__attribute__((noreturn)) void StartDialog::on_buttonMenuBarExit_2_clicked() {
exit(0);
}
/**
* @brief StartDialog::on_buttonLoadCustom_clicked
*/
void StartDialog::on_buttonLoadCustom_clicked() {
QStringList csvMimeTypes = { "text/csv" };
QStringList fileNames = openFileDialog(this, csvMimeTypes, false);
if (fileNames.empty())
return;
uploadedMarkerFile = fileNames.first();
enableRunButtonIfReady();
qDebug() << "Uploaded" << fileNames[0];
}
/**
* @brief StartDialog::on_buttonAddDataset_clicked
*/
void StartDialog::on_buttonAddDataset_clicked() {
QStringList csvMimeTypes = { "text/csv" };
QStringList filePaths = openFileDialog(this, csvMimeTypes, true);
if (filePaths.empty())
return;
for (int i = 0; i < filePaths.length(); i++) {
QString filePath = filePaths[i];
QString fileName = chopFileName(filePath);
// If file has already been uploaded, skip it
if (uploadedDatasets.contains(fileName)) {
continue;
}
uploadedDatasets.insert(fileName, filePath);
addDatasetToLayout(fileName);
qDebug() << "Uploaded" << fileName;
}
enableRunButtonIfReady();
}
/**
* @brief StartDialog::on_buttonRemoveDataset_clicked
*/
void StartDialog::on_buttonRemoveDataset_clicked() {
qDebug() << uploadedDatasets;
for (QListWidgetItem * item : ui->listDatasets->selectedItems()) {
uploadedDatasets.remove(item->text());
delete ui->listDatasets->takeItem(ui->listDatasets->row(item));
}
qDebug() << uploadedDatasets;
}
/**
* @brief StartDialog::on_buttonRun_clicked
*/
void StartDialog::on_buttonRun_clicked() {
emit runNewProject(uploadedMarkerFile, uploadedDatasets.values());
this->close();
//REMEMBER: How to delete this the right way?
// this->deleteLater(); ?!
// this->~StartDialog();
}
// ++++++++++++++++++++++++++++++++ SLOTS ++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++ MOUSE ++++++++++++++++++++++++++++++++
void StartDialog::mousePressEvent(QMouseEvent * mousePressEvent) {
this->mouseClickXCoordinate = mousePressEvent->x();
this->mouseClickYCoordinate = mousePressEvent->y();
}
void StartDialog::mouseMoveEvent(QMouseEvent * mouseMoveEvent) {
this->move(mouseMoveEvent->globalX() - this->mouseClickXCoordinate, mouseMoveEvent->globalY() - this->mouseClickYCoordinate);
}
| 25.063025 | 125 | 0.677284 |
daf428e5daade87c6e23122d7d74215de7f98183 | 719 | cpp | C++ | Rogue.cpp | Kahsyaj/TacticalRPGProject | 689c2131e4ec0e5ccc272e630b9483880ecbafc3 | [
"MIT"
] | null | null | null | Rogue.cpp | Kahsyaj/TacticalRPGProject | 689c2131e4ec0e5ccc272e630b9483880ecbafc3 | [
"MIT"
] | null | null | null | Rogue.cpp | Kahsyaj/TacticalRPGProject | 689c2131e4ec0e5ccc272e630b9483880ecbafc3 | [
"MIT"
] | null | null | null | #include "Rogue.h"
#include "IronArmor.h"
#include "SilverDagger.h"
#include "SilverSword.h"
#include "YewStick.h"
#include "Inventory.h"
//Constructor
//No drop defined
Rogue::Rogue(int lvl) : Monster("Rogue", new int[2]{HP*lvl, HP*lvl}, new int[2]{MANA*lvl, MANA*lvl},
lvl, GOLD*lvl, STRENGTH*lvl, AGILITY*lvl, WISDOM*lvl)
{
IronArmor *sArmor = new IronArmor(level);
YewStick *yStick = new YewStick(level);
SilverDagger *sDagger = new SilverDagger(level);
SilverSword *sSword = new SilverSword(level);
this->drop->getStock().push_back(sArmor);
this->drop->getStock().push_back(yStick);
this->drop->getStock().push_back(sDagger);
this->drop->getStock().push_back(sSword);
}
| 29.958333 | 101 | 0.687065 |
dafab4061e8226c67f81de72b61f295ce44a5a1f | 185 | cc | C++ | labs/12-verilog-blink/code/empty/sim.cc | dddrrreee/cs240lx-22spr | 7cab61cbe2ff7779ca414ca7ff64ea00914bf362 | [
"MIT"
] | 2 | 2022-03-29T03:59:29.000Z | 2022-03-29T04:27:26.000Z | labs/12-verilog-blink/code/empty/sim.cc | dddrrreee/cs240lx-22spr | 7cab61cbe2ff7779ca414ca7ff64ea00914bf362 | [
"MIT"
] | null | null | null | labs/12-verilog-blink/code/empty/sim.cc | dddrrreee/cs240lx-22spr | 7cab61cbe2ff7779ca414ca7ff64ea00914bf362 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include "Vled_top.h"
#include "verilated.h"
int main() {
Vled_top* dut = new Vled_top;
dut->eval();
printf("led=%d\n", dut->led_r);
return 0;
}
| 13.214286 | 35 | 0.589189 |
dafb238d7c9ae5709f90ff437c60dd5c5e2410bd | 309 | hpp | C++ | firmware/VersickerungsSensor/src/Display/Pages/Elements/Mixins/FilteredDistanceMixin.hpp | Finomnis/VersickerungsSensor | 90b02acc9c57b71c38a874760008780dce1abc8f | [
"MIT"
] | null | null | null | firmware/VersickerungsSensor/src/Display/Pages/Elements/Mixins/FilteredDistanceMixin.hpp | Finomnis/VersickerungsSensor | 90b02acc9c57b71c38a874760008780dce1abc8f | [
"MIT"
] | null | null | null | firmware/VersickerungsSensor/src/Display/Pages/Elements/Mixins/FilteredDistanceMixin.hpp | Finomnis/VersickerungsSensor | 90b02acc9c57b71c38a874760008780dce1abc8f | [
"MIT"
] | null | null | null | #pragma once
#include "../../../../utils/ValueWatcher.hpp"
namespace Pages::Elements::Mixins
{
class FilteredDistanceMixin
{
protected:
FilteredDistanceMixin();
ValueWatcher<float> &filtered_distance();
private:
ValueWatcher<float> filtered_distance_value;
};
}
| 18.176471 | 52 | 0.653722 |
daff34c6e49f7ce10c7b45518a1edd7a3d66be09 | 5,256 | cpp | C++ | traj_visualization_plugin/src/trajectory_display.cpp | YanzhouWang/rsp_final_project | c58c3efbf507cdd54abf860f7519006bc077c9f0 | [
"MIT"
] | null | null | null | traj_visualization_plugin/src/trajectory_display.cpp | YanzhouWang/rsp_final_project | c58c3efbf507cdd54abf860f7519006bc077c9f0 | [
"MIT"
] | null | null | null | traj_visualization_plugin/src/trajectory_display.cpp | YanzhouWang/rsp_final_project | c58c3efbf507cdd54abf860f7519006bc077c9f0 | [
"MIT"
] | null | null | null | #include <traj_visualization_plugin/trajectory_display.hpp>
namespace trajectory_display_ns{
trajectory_display::trajectory_display(){
description_property_=new rviz::StringProperty("Robot Description","robot_description",
"The name of the ROS parameter where the URDF for the robot is loaded",
this, SLOT (updateRobotDescription()));
target_property_=new rviz::StringProperty("Target link", " ",
"Target link of the robot",
this, SLOT (updateLinkChoice()));
color_property_=new rviz::ColorProperty("Line color",QColor(204,51,204),
"Color of the path",
this, SLOT (updateLineColorandAlpha()));
alpha_property_=new rviz::FloatProperty("Line alpha",1,
"Line alpha, 1 is opaque, 0 is transparent",
this, SLOT (updateLineColorandAlpha()));
width_property_=new rviz::FloatProperty("Line width",0.003,
"Line width",
this, SLOT(updateLineWidth()));
plugin_status_=new rviz::StatusProperty("Plugin status","plugin status",rviz::StatusProperty::Level(0) , this);
plugin_status_->hide();
}
trajectory_display::~trajectory_display(){
delete target_property_;
delete description_property_;
delete color_property_;
delete alpha_property_;
delete width_property_;
delete plugin_status_;
delete kdlfk_r2t_;
}
void trajectory_display::onInitialize(){
MFDClass::onInitialize();
std::string robot_description_string;
ros::param::get(description_property_->getStdString(),robot_description_string);
if(!kdl_parser::treeFromString(robot_description_string, tree_)){
ROS_ERROR("Cannot build tree.");
setStatus(rviz::StatusProperty::Level(2),"Robot state","Cannot get robot model from parameter server.");
plugin_status_->setLevel(rviz::StatusProperty::Level(2));
}
else{
ROS_INFO("Retrieved tree from parameter server.");
setStatus(rviz::StatusProperty::Level(0),"Robot state","OK");
plugin_status_->setLevel(rviz::StatusProperty::Level(0));
}
path_line_=new rviz::BillboardLine(scene_manager_, scene_node_);
}
void trajectory_display::reset(){
MFDClass::reset();
updateLinkChoice();
path_line_->clear();
}
void trajectory_display::updateLinkChoice(){
std::map<std::string, KDL::TreeElement>::const_iterator root;
root=tree_.getRootSegment();
std::string root_link=root->first;
std::string target_link=target_property_->getStdString();
//Setting up for chain from root to target link
if(!tree_.getChain(root_link,target_link,chain_r2t_)){
ROS_ERROR("Cannot get chain from %s to %s.", root_link.c_str(),target_link.c_str());
setStatus(rviz::StatusProperty::Level(2),"Target link","Cannot get chain.");
plugin_status_->setLevel(rviz::StatusProperty::Level(2));
}
else
{
ROS_INFO("To-target chain updated from %s to %s.",root_link.c_str(),target_link.c_str());
kdlfk_r2t_=new KDL::ChainFkSolverPos_recursive(chain_r2t_);
setStatus(rviz::StatusProperty::Level(0),"Target link","OK");
plugin_status_->setLevel(rviz::StatusProperty::Level(0));
}
}
void trajectory_display::updateRobotDescription(){
onInitialize();
}
void trajectory_display::updateLineColorandAlpha(){
Ogre::ColourValue new_color=color_property_->getOgreColor();
new_color.a=alpha_property_->getFloat();
path_line_->setColor(new_color.r, new_color.g, new_color.b, new_color.a);
context_->queueRender();
}
void trajectory_display::updateLineWidth(){
float new_width=width_property_->getFloat();
path_line_->setLineWidth(new_width);
context_->queueRender();
}
void trajectory_display::processMessage(const display_trajectory_msgs::DisplayTrajectoryStamped::ConstPtr& msg){
path_line_->clear();
Ogre::Quaternion orientation;
Ogre::Vector3 position;
if( !context_->getFrameManager()->getTransform( msg->header.frame_id,
msg->header.stamp,
position, orientation ))
{
ROS_DEBUG( "Error transforming from frame '%s' to frame '%s'",
msg->header.frame_id.c_str(), qPrintable( fixed_frame_ ));
return;
}
path_line_->setPosition(position);
path_line_->setOrientation(orientation);
//Proceed only when status is OK
if(plugin_status_->getLevel()==0){
int num_wayPoints=msg->moveit_display_trajectory.trajectory[0].joint_trajectory.points.size();
int num_joints_to_target=chain_r2t_.getNrOfJoints();
updateLineWidth();
updateLineColorandAlpha();
//Here is the tricky part and will need more work into this.
KDL::JntArray q_in_target;
q_in_target.resize(num_joints_to_target);
for(size_t i=0; i<num_wayPoints; i++){
for(size_t k=0; k<num_joints_to_target; k++){
q_in_target(k)=msg->moveit_display_trajectory.trajectory[0].joint_trajectory.points[i].positions[k];
}
KDL::Frame p_out_target;
kdlfk_r2t_->JntToCart(q_in_target, p_out_target);
KDL::Vector V=p_out_target.p;
Ogre::Vector3 new_point{(double)V.x(), (double)V.y(), (double)V.z()};
path_line_->addPoint(new_point);
}
}
}
}
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(trajectory_display_ns::trajectory_display, rviz::Display)
| 38.364964 | 115 | 0.709285 |
97020a69bca2dd711dad18ef03e181da5e4693af | 4,535 | hpp | C++ | Source/src/ezcard/io/scribe/list_property_scribe.hpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 5 | 2019-10-30T06:10:10.000Z | 2020-04-25T16:52:06.000Z | Source/src/ezcard/io/scribe/list_property_scribe.hpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | null | null | null | Source/src/ezcard/io/scribe/list_property_scribe.hpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 2 | 2019-11-27T23:47:54.000Z | 2020-01-13T16:36:03.000Z | //
// list_property_scribe.hpp
// OpenPGP
//
// Created by Yanfeng Zhang on 6/23/17.
//
// The MIT License
//
// Copyright (c) 2019 Proton Technologies AG
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef list_property_scribe_hpp
#define list_property_scribe_hpp
#include <stdio.h>
#include "vcard_property_scribe.hpp"
#include "vobject_property_values.hpp"
namespace ezvcard {
/**
* Marshals properties that contain a list of values.
* @param <T> the property class
* @author Michael Angstadt
*/
template <class T>
class ListPropertyScribe : public VCardPropertyScribeWrapper<T> {
static_assert(std::is_base_of<TextListProperty, T>::value, "ListPropertyScribe<T>: T must be extent of TextListProperty type :-(");
public:
ListPropertyScribe(const std::string& propertyName) : VCardPropertyScribeWrapper<T>(propertyName) {
}
protected:
virtual std::shared_ptr<T> _newInstance() = 0;
VCardDataType::Ptr _defaultDataType(const VCardVersion::Ptr& version) {
return VCardDataType::TEXT;
}
std::string _writeText(const std::shared_ptr<T>& property, const WriteContext::Ptr& context) {
return VObjectPropertyValues::writeList(property->getValues());
}
std::shared_ptr<T> _parseText(const std::string& value,
const VCardDataType::Ptr& dataType,
const VCardVersion::Ptr& version,
const VCardParameters::Ptr& parameters,
std::list<std::string> warnings) {
auto values = VObjectPropertyValues::parseList(value);
return parse(values);
}
// @Override
// protected void _writeXml(T property, XCardElement parent) {
// parent.append(VCardDataType.TEXT.getName().toLowerCase(), property.getValues());
// }
//
// @Override
// protected T _parseXml(XCardElement element, VCardParameters parameters, ParseContext context) {
// List<String> values = element.all(VCardDataType.TEXT);
// if (!values.isEmpty()) {
// return parse(values);
// }
//
// throw missingXmlElements(VCardDataType.TEXT);
// }
//
// @Override
// protected JCardValue _writeJson(T property) {
// List<String> values = property.getValues();
// if (values.isEmpty()) {
// return JCardValue.single("");
// }
//
// return JCardValue.multi(values);
// }
//
// @Override
// protected T _parseJson(JCardValue value, VCardDataType dataType, VCardParameters parameters, ParseContext context) {
// List<String> values = value.asMulti();
// return parse(values);
// }
private:
std::shared_ptr<T> parse(const std::vector<std::string>& values) {
auto property = _newInstance();
property->addValues(values);
return property;
}
};
}
#endif /* list_property_scribe_hpp */
| 37.479339 | 139 | 0.587872 |
9704beb9c7e8f67345dac4235bdce1d99220ae3a | 173 | hpp | C++ | include/Game/Entities/Treats/MultiballTreat.hpp | FoxelCode/Barkanoid | 3e582cbfb4bf13aa522d344489c8b0bac77fa8c5 | [
"Unlicense"
] | null | null | null | include/Game/Entities/Treats/MultiballTreat.hpp | FoxelCode/Barkanoid | 3e582cbfb4bf13aa522d344489c8b0bac77fa8c5 | [
"Unlicense"
] | null | null | null | include/Game/Entities/Treats/MultiballTreat.hpp | FoxelCode/Barkanoid | 3e582cbfb4bf13aa522d344489c8b0bac77fa8c5 | [
"Unlicense"
] | null | null | null | #pragma once
#include "Treat.hpp"
class MultiballTreat : public Treat
{
public:
MultiballTreat(sf::Vector2f pos, float launchAngle);
void AddAward(PlayState* state);
}; | 15.727273 | 53 | 0.751445 |
9704e258106af9ac50f95c6e1251955b8cb30194 | 544 | hpp | C++ | include/executor_exam/throw_message_node.hpp | hsgwa/executer_exam | 083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24 | [
"Apache-2.0"
] | null | null | null | include/executor_exam/throw_message_node.hpp | hsgwa/executer_exam | 083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24 | [
"Apache-2.0"
] | null | null | null | include/executor_exam/throw_message_node.hpp | hsgwa/executer_exam | 083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24 | [
"Apache-2.0"
] | 1 | 2021-11-11T12:35:09.000Z | 2021-11-11T12:35:09.000Z | #ifndef __THROW_MESSAGE_NODE_HPP__
#define __THROW_MESSAGE_NODE_HPP__
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/string.hpp>
namespace executor_test
{
class ThrowMessageNode : public rclcpp::Node
{
public:
explicit ThrowMessageNode(const rclcpp::NodeOptions &options);
private:
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr msg_pub_;
uint64_t publish_count_;
void cyclic_send_message();
};
}
#endif | 22.666667 | 74 | 0.674632 |
970700f6e7502b8d1f5d358af3d6242ee8392dcc | 2,608 | cpp | C++ | src/aten/src/ATen/native/npu/AddmmKernelNpu.cpp | Ascend/pytorch | 39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc | [
"BSD-3-Clause"
] | 1 | 2021-12-02T03:07:35.000Z | 2021-12-02T03:07:35.000Z | src/aten/src/ATen/native/npu/AddmmKernelNpu.cpp | Ascend/pytorch | 39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc | [
"BSD-3-Clause"
] | 1 | 2021-11-12T07:23:03.000Z | 2021-11-12T08:28:13.000Z | src/aten/src/ATen/native/npu/AddmmKernelNpu.cpp | Ascend/pytorch | 39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ATen/native/npu/utils/CalcuOpUtil.h"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/NpuUtils.h"
#include "ATen/native/npu/utils/OpAdapter.h"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor& addmm_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& mat1,
const Tensor& mat2,
Scalar beta,
Scalar alpha) {
// mat1*alpha
Tensor mulResult = at::mul(mat1, alpha);
// mulmat1 mm mat2
Tensor mmResult = at::mm(mulResult, mat2);
// matmul*alpha+self*beta
at::add_out(result, mmResult, self, beta);
return result;
}
Tensor addmm_npu(
const Tensor& self,
const Tensor& mat1,
const Tensor& mat2,
Scalar beta,
Scalar alpha) {
// calculate the output size
auto outputSize = addmm_npu_output_size(self, mat1, mat2, beta, alpha);
// add算子支持NZ与1维且该轴能被16整除的ND相加,直接得到NZ result
int64_t resFormat = (self.dim() == 1 && self.size(0) % 16 == 0 && self.scalar_type() == at::kHalf) ?
ACL_FORMAT_FRACTAL_NZ :
ACL_FORMAT_ND;
Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, self.options(), resFormat);
// calculate the output result of the NPU
addmm_out_npu(result, self, mat1, mat2, beta, alpha);
return result;
}
Tensor& addmm_npu_(
Tensor& self,
const Tensor& mat1,
const Tensor& mat2,
Scalar beta,
Scalar alpha) {
SmallVector<Tensor, N> inputs = {self, mat1, mat2};
SmallVector<Tensor, N> outputs = {self};
CalcuOpUtil::check_memory_over_laps(inputs, outputs);
if (!NpuUtils::check_match(&self)) {
Tensor contiguousSelf = NpuUtils::format_contiguous(self);
Tensor result =
addmm_out_npu(contiguousSelf, contiguousSelf, mat1, mat2, beta, alpha);
NpuUtils::format_fresh_view(self, result);
} else {
addmm_out_npu(self, self, mat1, mat2, beta, alpha);
}
return self;
}
} // namespace native
} // namespace at
| 29.303371 | 103 | 0.704755 |
8ccbe8b685149a575057a1fe2341f07029c38dec | 4,255 | cpp | C++ | src/shared/ai/RandomIA.cpp | StevenEnsea/plt | f36edc064c375b58b4add9de1caa56ee3fc41fce | [
"Apache-2.0"
] | null | null | null | src/shared/ai/RandomIA.cpp | StevenEnsea/plt | f36edc064c375b58b4add9de1caa56ee3fc41fce | [
"Apache-2.0"
] | null | null | null | src/shared/ai/RandomIA.cpp | StevenEnsea/plt | f36edc064c375b58b4add9de1caa56ee3fc41fce | [
"Apache-2.0"
] | null | null | null | #include "ai.h"
#include "engine.h"
#include "state.h"
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
using namespace ai;
using namespace engine;
using namespace state;
using namespace std;
int RandomIA::run (engine::Engine& engine){
// L'IA effectue ces actions uniquement si c'est son tour
//sleep(5);
State state = engine.getState();
if(state.getPlaying()->getIa()==true){
int randomAction;
std::pair<int,int> randomPosition;
int randomAttaque;
bool premierEssai = true;
bool actionPossible=true;
bool attaquePossible=true;
Player* bot =state.getPlaying();
int randomDirection;
int X, Y, range;
std::vector<int> attaquesValides;
srand(time(NULL));
while ((bot->getHp() > 0) && actionPossible){
clock_t start_time = clock();
while(clock()<start_time+100000);
//sleep(1);
if(premierEssai == true){
cout<< "\t [Controle par le CPU] " << endl;
premierEssai = false;
}
/*
* randomAction: 0 = deplacemnt
* 1 = attaque
* 2 = fin de tour
* */
//to do augementer proba d'action en fct des pm pa restant
if (bot->getMovement()==0 && (bot->getSkillCount()==0 || !attaquePossible)){
randomAction = 2;
}
else if (bot->getMovement()==0 && bot->getSkillCount()>0 && attaquePossible){
randomAction = rand()%2+1 ;
}
else if (bot->getMovement()>0 && (bot->getSkillCount()==0 || !attaquePossible)){
randomAction = rand()%2;
if(randomAction == 1){
randomAction = 2;
}
}
else{randomAction = rand()%3;}
//cout<<"Action selectionné :";
// 0 : Cas du deplacement
if (randomAction == 0){
//cout<<" déplacement"<<endl;
randomDirection=rand()%4;
if(randomDirection==0){
randomPosition = {bot->getX(),bot->getY()-1};
}else
if(randomDirection==1){
randomPosition = {bot->getX()+1,bot->getY()};
}else
if(randomDirection==2){
randomPosition = {bot->getX(),bot->getY()+1};
}else
if(randomDirection==3){
randomPosition = {bot->getX()-1,bot->getY()};
}
Move* move = new Move(randomPosition);
engine.executeCommand(move);
}
// 1 : Cas de l'attaque
else if (randomAction == 1){
//cout<<" attaque"<<endl;
std::vector<Skill*> listeAttaques = bot-> getSkills();
for(size_t a=0;a<listeAttaques.size();a++){
if(listeAttaques[a]->getCooldown()<=0){
attaquesValides.push_back(a);
}
}
if (attaquesValides.size() !=0){
//cout<<"attaques valides"<<endl;
//choix aléatoire de l'attaque parmi les attaques possibles
randomAttaque = attaquesValides[rand()%attaquesValides.size()];
//cout<<"attaque selectionné :"<<listeAttaques[randomAttaque]->getName()<<endl;
//choix de la direction aléatoire
randomDirection=rand()%4;
if(randomDirection==0){
X=0;
Y=-1;
//cout<<"Direction : Nord"<<endl;
}else
if(randomDirection==1){
X=1;
Y=0;
//cout<<"Direction : Est"<<endl;
}else
if(randomDirection==2){
X=0;
Y=1;
//cout<<"Direction : Sud"<<endl;
}else
if(randomDirection==3){
X=-1;
Y=0;
//cout<<"Direction : Ouest"<<endl;
}
//choix de la case attaqué (range) aléatoire
range=rand()%(listeAttaques[randomAttaque]->getRange().second -listeAttaques[randomAttaque]->getRange().first+1)+listeAttaques[randomAttaque]->getRange().first;
randomPosition={bot->getX()+X*range,bot->getY()+Y*range};
// Commande d'attaque
Attack* attack = new Attack(randomPosition , randomAttaque);
engine.executeCommand(attack);
}else{
cout<<"Le CPU n'a pas d'attaque possible"<<endl;
attaquePossible=false;
}
}
// 2 : Cas de fin d'actions
else if (randomAction == 2){
//cout<<" fin de tour"<<endl;
EndActions* endactions = new EndActions();
engine.executeCommand(endactions);
actionPossible=false;
return 0;
}
engine.getState().notifyObservers(engine.getState());
}
//test verification hors boucle
if(actionPossible == false){
cout<< "\t\t-> Action impossible pour le CPU " << bot->getName() << " <-" << endl;
}
}
return 0;
}
| 26.93038 | 165 | 0.602115 |
8ccc20dd11a86c904eb27573405378b304d03922 | 1,915 | cpp | C++ | Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2022-03-16T14:31:36.000Z | 2022-03-16T14:31:36.000Z | Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | null | null | null | Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2020-07-01T01:26:17.000Z | 2020-07-01T01:26:17.000Z | /*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference
when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using https://forum.aspose.com/c/tasks
*/
#include "WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.h"
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object.h>
#include <system/collections/list.h>
#include <PrimaveraXmlReader.h>
#include <cstdint>
#include "RunExamples.h"
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace WorkingWithProjects {
namespace ImportingAndExporting {
RTTI_INFO_IMPL_HASH(681918485u, ::Aspose::Tasks::Examples::CPP::WorkingWithProjects::ImportingAndExporting::ReadProjectUIDsFromXMLFile, ThisTypeBaseTypesInfo);
void ReadProjectUIDsFromXMLFile::Run()
{
// The path to the documents directory.
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
// ExStart:ReadProjectUIDsFromXMLFile
System::SharedPtr<PrimaveraXmlReader> reader = System::MakeObject<PrimaveraXmlReader>(dataDir + u"Project.xml");
System::SharedPtr<System::Collections::Generic::List<int32_t>> listOpProjectUids = reader->GetProjectUids();
// ExEnd:ReadProjectUIDsFromXMLFile
}
} // namespace ImportingAndExporting
} // namespace WorkingWithProjects
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
| 36.826923 | 164 | 0.784856 |
8ccd54ac424e188603837c89770c80d54353d660 | 1,638 | cpp | C++ | Uncategorized/bts16p6.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/bts16p6.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/bts16p6.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;
using ll = long long;
using stt = pair<pair<int, ll>, pair<int, int>>;
const ll mod = 1e9+7;
const int MM = 505;
int n, m, qt;
ll v[MM][MM];
pair<int, ll> dis[MM][MM], ans;
array<int, 2> mv[] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
priority_queue<stt> q;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n>>m>>qt;
while(qt--){
ll a, b, c, d, k;
cin>>a>>b>>c>>d>>k;
v[a][b] += k;
v[a][b+d] -= k*(d+1);
v[a][b+d+1] += k*(d);
v[a+c][b] -= k*(c+1);
v[a+c+1][b] += k*(c);
v[a+c][b+d] += k*(c+1)*(d+1);
v[a+c+1][b+d] -= k*(c)*(d+1);
v[a+c][b+d+1] -= k*(c+1)*(d);
v[a+c+1][b+d+1] += k*(c)*(d);
}
for(int t = 0; t < 2; t++){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
v[i][j] += v[i-1][j] + v[i][j-1] - v[i-1][j-1];
}
}
}
memset(dis, -0x3f, sizeof dis);
int sx, sy; cin>>sx>>sy;
q.push({dis[sx][sy] = {1, v[sx][sy]}, {sx, sy}});
while(size(q)){
auto [curd, p] = q.top(); q.pop();
auto [a, b] = p;
if(curd < dis[a][b])
continue;
ans = max(ans, curd);
for(auto [x, y]: mv){
x += a, y += b;
if(x and x <= n and y and y <= m and v[x][y] > v[a][b]){
auto nx = curd;
nx.first++;
nx.second += v[x][y];
if(nx > dis[x][y]){
q.push({dis[x][y] = nx, {x, y}});
}
}
}
}
cout<<ans.second%mod<<'\n';
}
/*
1 0 0 -4 0
0 0 0 0 0
-3 0 0 12 0
0 0 0 0 0
1 1 1 -3 0
1 1 1 -3 0
-2 -2 -2 -6 0
0 0 0 0 0
1 2 3 0 0
2 4 6 0 0
0 0 0 0 0
0 0 0 0 0
*/ | 18.827586 | 60 | 0.413919 |
8ccd7e504d55323da82c84b9662b782c3e668742 | 2,526 | hpp | C++ | include/oglplus/object/bound.hpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 459 | 2016-03-16T04:11:37.000Z | 2022-03-31T08:05:21.000Z | include/oglplus/object/bound.hpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 2 | 2016-08-08T18:26:27.000Z | 2017-05-08T23:42:22.000Z | include/oglplus/object/bound.hpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 47 | 2016-05-31T15:55:52.000Z | 2022-03-28T14:49:40.000Z | /**
* @file oglplus/object/bound.hpp
* @brief Operations on currently bound objects
*
* @author Matus Chochlik
*
* Copyright 2010-2015 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_OBJECT_BOUND_1405011014_HPP
#define OGLPLUS_OBJECT_BOUND_1405011014_HPP
#include <oglplus/object/name.hpp>
namespace oglplus {
template <typename ObjTag>
class BoundObjOps
{
public:
BoundObjOps(void)
OGLPLUS_NOEXCEPT(true)
{ }
template <typename X>
BoundObjOps(X)
OGLPLUS_NOEXCEPT(true)
{ }
};
template <typename ObjTag>
class ObjectOps<tag::CurrentBound, ObjTag>
: public ObjZeroOps<tag::CurrentBound, ObjTag>
, public BoundObjOps<ObjTag>
{
protected:
ObjectOps(ObjectName<ObjTag> name)
OGLPLUS_NOEXCEPT(true)
: ObjZeroOps<tag::CurrentBound, ObjTag>(name)
{ }
public:
typedef typename BoundObjOps<ObjTag>::Target Target;
#if !OGLPLUS_NO_DEFAULTED_FUNCTIONS
ObjectOps(ObjectOps&&) = default;
ObjectOps(const ObjectOps&) = default;
ObjectOps& operator = (ObjectOps&&) = default;
ObjectOps& operator = (const ObjectOps&) = default;
#else
typedef ObjZeroOps<tag::CurrentBound, ObjTag> _base1;
typedef BoundObjOps<ObjTag> _base2;
ObjectOps(ObjectOps&& temp)
OGLPLUS_NOEXCEPT(true)
: _base1(static_cast<_base1&&>(temp))
, _base2(static_cast<_base2&&>(temp))
{ }
ObjectOps(const ObjectOps& that)
OGLPLUS_NOEXCEPT(true)
: _base1(static_cast<const _base1&>(that))
, _base2(static_cast<const _base2&>(that))
{ }
ObjectOps& operator = (ObjectOps&& temp)
OGLPLUS_NOEXCEPT(true)
{
_base1::operator = (static_cast<_base1&&>(temp));
_base2::operator = (static_cast<_base2&&>(temp));
return *this;
}
ObjectOps& operator = (const ObjectOps& that)
OGLPLUS_NOEXCEPT(true)
{
_base1::operator = (static_cast<const _base1&>(that));
_base2::operator = (static_cast<const _base2&>(that));
return *this;
}
#endif
};
template <typename ObjTag>
class Reference<ObjectOps<tag::CurrentBound, ObjTag>>
: public ObjectOps<tag::CurrentBound, ObjTag>
{
private:
typedef ObjectOps<tag::CurrentBound, ObjTag> Base;
public:
Reference(void)
: ObjectOps<tag::CurrentBound, ObjTag>(
ObjBindingOps<ObjTag>::Binding()
)
{ }
Reference(typename Base::Target init_tgt)
: ObjectOps<tag::CurrentBound, ObjTag>(
ObjBindingOps<ObjTag>::Binding(init_tgt)
)
{
this->target = init_tgt;
}
};
} // namespace oglplus
#endif // include guard
| 22.756757 | 68 | 0.732779 |
8ccdc0abe43785e2014d73e8172ed2189027dbe4 | 4,964 | cpp | C++ | brickstone/src/math/vec3.cpp | GenTexX/brickstone | b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b | [
"MIT"
] | 1 | 2019-10-10T12:30:14.000Z | 2019-10-10T12:30:14.000Z | brickstone/src/math/vec3.cpp | GenTexX/brickstone | b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b | [
"MIT"
] | null | null | null | brickstone/src/math/vec3.cpp | GenTexX/brickstone | b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b | [
"MIT"
] | 1 | 2019-10-10T12:52:08.000Z | 2019-10-10T12:52:08.000Z | #include <bspch.h>
#include "Vec3.h"
namespace bs {
const vec3 vec3::up(0.0f, 1.0f, 0.0f);
const vec3 vec3::down(0.0f, -1.0f, 0.0f);
const vec3 vec3::right(1.0f, 0.0f, 0.0f);
const vec3 vec3::left(-1.0f, 0.0f, 0.0f);
const vec3 vec3::back(0.0f, 0.0f, -1.0f);
const vec3 vec3::forward(0.0f, 0.0f, 1.0f);
const vec3 vec3::one(1.0f, 1.0f, 1.0f);
const vec3 vec3::zero(0.0f, 0.0f, 0.0f);
vec3::vec3(const float &x, const float &y, const float &z) : x(x), y(y), z(z) {
}
vec3::vec3() : x(0), y(0), z(0) {
}
vec3::~vec3() {
}
float vec3::magnitude() {
return (float)sqrt(this->x * this->x + this->y * this->y + this->z * this->z);
}
float vec3::sqrMagnitude() {
return (float) (this->x * this->x + this->y * this->y + this->z * this->z);
}
vec3 vec3::normalized() {
return *this /= this->magnitude();
}
bool vec3::equals(vec3& other) {
return *this == other;
}
vec3& vec3::add(const vec3& other) {
this->x += other.x;
this->y += other.y;
this->z += other.z;
return *this;
}
vec3& vec3::sub(const vec3& other) {
this->x -= other.x;
this->y -= other.y;
this->z -= other.z;
return *this;
}
vec3& vec3::mult(const vec3& other) {
this->x *= other.x;
this->y *= other.y;
this->z *= other.z;
return *this;
}
vec3& vec3::div(const vec3& other) {
this->x /= other.x;
this->y /= other.y;
this->z /= other.z;
return *this;
}
vec3& vec3::add(const float& other) {
this->x += other;
this->y += other;
this->z += other;
return *this;
}
vec3& vec3::sub(const float& other) {
this->x -= other;
this->y -= other;
this->z -= other;
return *this;
}
vec3& vec3::mult(const float& other) {
this->x *= other;
this->y *= other;
this->z *= other;
return *this;
}
vec3& vec3::div(const float& other) {
this->x /= other;
this->y /= other;
this->z /= other;
return *this;
}
vec3& vec3::operator+=(const vec3& other) {
return this->add(other);
}
vec3& vec3::operator-=(const vec3& other) {
return this->sub(other);
}
vec3& vec3::operator*=(const vec3& other) {
return this->mult(other);
}
vec3& vec3::operator/=(const vec3& other) {
return this->div(other);
}
vec3& vec3::operator+=(const float& other) {
return this->add(other);
}
vec3& vec3::operator-=(const float& other) {
return this->sub(other);
}
vec3& vec3::operator*=(const float& other) {
return this->mult(other);
}
vec3& vec3::operator/=(const float& other) {
return this->div(other);
}
bool vec3::operator==(const vec3& other) {
return (this->x == other.x && this->y == other.y && this->z == other.z);
}
bool vec3::operator!=(const vec3& other) {
return !(this->x == other.x && this->y == other.y && this->z == other.z);
}
bool vec3::operator>(vec3& other) {
return (this->sqrMagnitude() > other.sqrMagnitude());
}
bool vec3::operator<(vec3& other) {
return (this->sqrMagnitude() < other.sqrMagnitude());
}
bool vec3::operator>=(vec3& other) {
return (this->sqrMagnitude() >= other.sqrMagnitude());
}
bool vec3::operator<=(vec3& other) {
return (this->sqrMagnitude() <= other.sqrMagnitude());
}
vec3 operator+(vec3 left, const vec3& right) {
return left.add(right);
}
vec3 operator-(vec3 left, const vec3& right) {
return left.sub(right);
}
vec3 operator*(vec3 left, const vec3& right) {
return left.mult(right);;
}
vec3 operator/(vec3 left, const vec3& right) {
return left.div(right);;
}
vec3 operator+(vec3 left, const float& right) {
left.add(right);
return left;
}
vec3 operator-(vec3 left, const float& right) {
left.sub(right);
return left;
}
vec3 operator*(vec3 left, const float& right) {
left.mult(right);
return left;
}
vec3 operator/(vec3 left, const float& right) {
left.div(right);
return left;
}
vec3 operator+(const float& left, vec3 right) {
right.add(left);
return right;
}
vec3 operator*(const float& left, vec3 right) {
right.mult(left);
return right;
}
std::ostream& operator<<(std::ostream& stream, vec3& vector) {
stream << vector.toString();
return stream;
}
float vec3::dot(const vec3& left, const vec3& right) {
return left.x * right.x + left.y * right.y + left.z * left.z;
}
vec3 vec3::cross(const vec3& left, const vec3& right) {
return vec3(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x);
}
float vec3::distance(const vec3& left, const vec3& right) {
return (left - right).magnitude();
}
float vec3::sqrDistance(const vec3& left, const vec3& right) {
return (left - right).sqrMagnitude();
}
vec3 vec3::lerp(const vec3& left, const vec3& right, const float& t) {
return ((right - left) * t) + left;
}
std::string vec3::toString() {
return "(" + std::to_string(this->x) + " | " + std::to_string(this->y) + " | " + std::to_string(this->z) + ")";
}
} | 15.368421 | 125 | 0.595085 |
8ccfbe147c1ddb00c6b36131edb47a96d2caf253 | 16,631 | cp | C++ | Std/Mod/Stamps.cp | romiras/Blackbox-fw-playground | 6de94dc65513e657a9b86c1772e2c07742b608a8 | [
"BSD-2-Clause"
] | 1 | 2016-03-17T08:27:05.000Z | 2016-03-17T08:27:05.000Z | Std/Mod/Stamps.cps | Spirit-of-Oberon/LightBox | 8a45ed11dcc02ae97e86f264dcee3e07c910ff9d | [
"BSD-2-Clause"
] | null | null | null | Std/Mod/Stamps.cps | Spirit-of-Oberon/LightBox | 8a45ed11dcc02ae97e86f264dcee3e07c910ff9d | [
"BSD-2-Clause"
] | 1 | 2018-03-14T17:53:27.000Z | 2018-03-14T17:53:27.000Z | MODULE StdStamps;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = ""
issues = ""
**)
(*
StdStamps are used to keep track of document changes, in particular program texts.
StdStamps carry a sequence number and a fingerprint of the document with them.
Each time the document (and therefore its fingerprint) is changed and stored,
the sequence number is incremented. (When determining the fingerprint of the
document, whitespace is ignored, except in string literals.)
Each StdStamp also keeps track of the history of most recent changes.
For the last maxHistoryEntries sequence numbers, the date and time,
and an optional one-line comment is stored. To avoid too many entries in the history
while working on a module, the most recent history entry is overwritten upon the
generation of a new sequence number if the current date is the same as the date in
the history entry.
*)
IMPORT
SYSTEM, (* SYSTEM.ROT only, for fingerprint calculation *)
Strings, Dates, StdCmds,
Ports, Models, Stores, Containers, Properties, Views, Controllers, Fonts,
TextModels, TextSetters, TextMappers, TextViews, TextRulers;
CONST
setCommentKey = "#Std:Set Comment";
maxHistoryEntries = 25;
minVersion = 0; origStampVersion = 0; thisVersion = 2;
TYPE
History = ARRAY maxHistoryEntries OF RECORD
fprint, snr: INTEGER; (* fingerprint, sequence number *)
date: INTEGER; (* days since 1/1/1 *)
time: INTEGER; (* min + 64 * hour *)
comment: POINTER TO ARRAY OF CHAR; (* nil if no comment *)
END;
StdView = POINTER TO RECORD (Views.View)
(*--snr: LONGINT;*)
nentries: INTEGER; (* number of entries in history *)
history: History; (* newest entry in history[0] *)
cache: ARRAY 64 OF CHAR;
END;
SetCmtOp = POINTER TO RECORD (Stores.Operation)
stamp: StdView;
oldcomment: POINTER TO ARRAY OF CHAR;
END;
VAR
comment*: RECORD
s*: ARRAY 64 OF CHAR;
END;
PROCEDURE (op: SetCmtOp) Do;
VAR temp: POINTER TO ARRAY OF CHAR;
BEGIN
temp := op.stamp.history[0].comment;
op.stamp.history[0].comment := op.oldcomment;
op.oldcomment := temp;
END Do;
PROCEDURE Format (v: StdView);
VAR s: ARRAY 64 OF CHAR; d: Dates.Date; t: INTEGER;
BEGIN
t := v.history[0].time;
Dates.DayToDate(v.history[0].date, d);
Dates.DateToString(d, Dates.plainAbbreviated, s); v.cache := s$;
Strings.IntToStringForm(v.history[0].snr, Strings.decimal, 4, "0", FALSE, s);
v.cache := v.cache + " (" + s + ")"
END Format;
PROCEDURE FontContext (v: StdView): Fonts.Font;
VAR c: Models.Context;
BEGIN
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
RETURN c(TextModels.Context).Attr().font;
ELSE
RETURN Fonts.dir.Default()
END;
END FontContext;
PROCEDURE CalcFP (t: TextModels.Model): INTEGER;
CONST sglQuote = "'"; dblQuote = '"';
VAR fp: INTEGER; rd: TextModels.Reader; ch, quoteChar: CHAR;
BEGIN
quoteChar := 0X; fp := 0;
rd := t.NewReader(NIL); rd.ReadChar(ch);
WHILE ~rd.eot DO
IF ch = quoteChar THEN quoteChar := 0X;
ELSIF (quoteChar = 0X) & ((ch = dblQuote) OR (ch = sglQuote)) THEN quoteChar := ch;
END;
IF (quoteChar = 0X) & (21X <= ch) & (ch # 8BX) & (ch # 8FX) & (ch # 0A0X) (* not in string literal *)
OR (quoteChar # 0X) & (20X <= ch) (* within string literal *)
THEN
fp := SYSTEM.ROT(fp, 1) + 13 * ORD(ch);
END;
rd.ReadChar(ch);
END;
RETURN fp;
END CalcFP;
PROCEDURE Update (v: StdView; forcenew: BOOLEAN);
VAR fp: INTEGER; i: INTEGER; ndays: INTEGER; d: Dates.Date; t: Dates.Time;
BEGIN
IF (v.context # NIL) & (v.context IS TextModels.Context) THEN
fp := CalcFP(v.context(TextModels.Context).ThisModel());
IF (fp # v.history[0].fprint) OR forcenew THEN
Dates.GetDate(d); Dates.GetTime(t);
ndays := Dates.Day(d);
IF (ndays # v.history[0].date) OR forcenew THEN
(* move down entries in history list *)
i := maxHistoryEntries-1;
WHILE i > 0 DO
v.history[i] := v.history[i-1];
DEC(i);
END;
v.history[0].comment := NIL;
END;
IF v.nentries < maxHistoryEntries THEN INC(v.nentries) END;
INC(v.history[0].snr);
v.history[0].fprint := fp;
v.history[0].date := ndays;
v.history[0].time := t.minute + t.hour*64;
Format(v);
Views.Update(v, Views.keepFrames);
END;
END;
END Update;
PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer);
VAR i, len: INTEGER;
BEGIN
Update(v, FALSE);
v.Externalize^(wr);
wr.WriteVersion(thisVersion);
(*--wr.WriteLInt(v.snr);*)
wr.WriteXInt(v.nentries);
FOR i := 0 TO v.nentries-1 DO
wr.WriteInt(v.history[i].fprint);
wr.WriteInt(v.history[i].snr);
wr.WriteInt(v.history[i].date);
wr.WriteXInt(v.history[i].time);
IF v.history[i].comment # NIL THEN
len := LEN(v.history[i].comment$);
wr.WriteXInt(len);
wr.WriteXString(v.history[i].comment^);
ELSE wr.WriteXInt(0);
END
END;
END Externalize;
PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER; format: BYTE; i, len: INTEGER;
d: Dates.Date; t: Dates.Time;
BEGIN
v.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(minVersion, thisVersion, version);
IF ~rd.cancelled THEN
IF version = origStampVersion THEN (* deal with old StdStamp format *)
(* would like to calculate fingerprint, but hosting model not available at this time *)
v.history[0].fprint := 0;
v.history[0].snr := 1; v.nentries := 1;
rd.ReadXInt(d.year); rd.ReadXInt(d.month); rd.ReadXInt(d.day);
rd.ReadXInt(t.hour); rd.ReadXInt(t.minute); rd.ReadXInt(t.second);
rd.ReadByte(format); (* format not used anymore *)
v.history[0].date := Dates.Day(d);
v.history[0].time := t.minute + t.hour*64;
ELSE
IF version = 1 THEN rd.ReadInt(v.history[0].snr) END; (* red text: to be removed soon *)
rd.ReadXInt(v.nentries);
FOR i := 0 TO v.nentries-1 DO
rd.ReadInt(v.history[i].fprint);
IF version > 1 THEN rd.ReadInt(v.history[i].snr)
ELSIF (* (version = 1) & *) i > 0 THEN v.history[i].snr := v.history[i-1].snr - 1;
END; (* red text: to be removed soon *)
rd.ReadInt(v.history[i].date);
rd.ReadXInt(v.history[i].time);
rd.ReadXInt(len);
IF len > 0 THEN
NEW(v.history[i].comment, len + 1);
rd.ReadXString(v.history[i].comment^);
ELSE v.history[i].comment := NIL;
END
END;
END;
Format(v);
END
END
END Internalize;
PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View);
VAR i: INTEGER;
BEGIN
(* v.CopyFrom^(source); *)
WITH source: StdView DO
(*--v.snr := source.snr;*)
v.nentries := source.nentries;
v.history := source.history;
v.cache := source.cache;
FOR i := 0 TO v.nentries - 1 DO
IF source.history[i].comment # NIL THEN
NEW(v.history[i].comment, LEN(source.history[i].comment$) + 1);
v.history[i].comment^ := source.history[i].comment^$;
END
END
END
END CopyFromSimpleView;
PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR a: TextModels.Attributes; color: Ports.Color; c: Models.Context; font: Fonts.Font;
asc, dsc, fw: INTEGER;
BEGIN
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := v.context(TextModels.Context).Attr();
font := a.font;
color := a.color;
ELSE font := Fonts.dir.Default(); color := Ports.black;
END;
font.GetBounds(asc, dsc, fw);
f.DrawLine(f.l, asc + f.dot, f.r, asc + f.dot, 1, Ports.grey25 );
f.DrawString(0, asc, color, v.cache, font);
END Restore;
PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref);
VAR font: Fonts.Font; asc, dsc, w: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR;
BEGIN
font := FontContext(v);
font.GetBounds(asc, dsc, w);
d.day := 28; d.month := 1; d.year := 2222; p.w := 0;
WHILE d.month <= 12 DO
Dates.DateToString(d, Dates.plainAbbreviated, s);
s := s + " (0000)";
w := font.StringWidth(s);
IF w > p.w THEN p.w := w END;
INC(d.month)
END;
p.h := asc + dsc;
END SizePref;
PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message);
VAR font: Fonts.Font; asc, w: INTEGER;
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.SizePref DO
SizePref(v, msg)
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: Properties.FocusPref DO
msg.hotFocus := TRUE
| msg: TextSetters.Pref DO
font := FontContext(v);
font.GetBounds(asc, msg.dsc, w);
ELSE
END
ELSE
END
END HandlePropMsg;
PROCEDURE NewRuler (): TextRulers.Ruler;
CONST mm = Ports.mm;
VAR r: TextRulers.Ruler;
BEGIN
r := TextRulers.dir.New(NIL);
TextRulers.SetRight(r, 140 * mm);
TextRulers.AddTab(r, 15 * mm); TextRulers.AddTab(r, 35 * mm); TextRulers.AddTab(r, 75 * mm);
RETURN r
END NewRuler;
PROCEDURE ShowHistory (v: StdView);
VAR text: TextModels.Model; f: TextMappers.Formatter;
i: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR;
tv: TextViews.View; attr: TextModels.Attributes;
BEGIN
text := TextModels.dir.New();
f.ConnectTo(text);
attr := f.rider.attr;
f.rider.SetAttr(TextModels.NewStyle(attr, {Fonts.italic}));
f.WriteString("seq nr."); f.WriteTab;
f.WriteString("fingerprint"); f.WriteTab;
f.WriteString("date and time"); f.WriteTab;
f.WriteString("comment"); f.WriteLn;
f.rider.SetAttr(attr); f.WriteLn;
(*--n := v.snr;*)
FOR i := 0 TO v.nentries-1 DO
f.WriteIntForm(v.history[i].snr, 10, 4, "0", FALSE);
(*--DEC(n);*)
f.WriteTab;
f.WriteIntForm(v.history[i].fprint, TextMappers.hexadecimal, 8, "0", FALSE);
f.WriteTab;
Dates.DayToDate(v.history[i].date, d);
Dates.DateToString(d, Dates.plainAbbreviated, s);
f.WriteString(s);
f.WriteString(" ");
f.WriteIntForm(v.history[i].time DIV 64, 10, 2, "0", FALSE);
f.WriteString(":");
f.WriteIntForm(v.history[i].time MOD 64, 10, 2, "0", FALSE);
IF v.history[i].comment # NIL THEN
f.WriteTab;
f.WriteString( v.history[i].comment^);
END;
f.WriteLn;
END;
tv := TextViews.dir.New(text);
tv.SetDefaults(NewRuler(), TextViews.dir.defAttr);
tv.ThisController().SetOpts({Containers.noFocus, Containers.noCaret});
Views.OpenAux(tv, "History");
END ShowHistory;
PROCEDURE Track (v: StdView; f: Views.Frame; x, y: INTEGER; buttons: SET);
VAR c: Models.Context; w, h: INTEGER; isDown, in, in0: BOOLEAN; m: SET;
BEGIN
c := v.context; c.GetSize(w, h); in0 := FALSE; in := TRUE;
REPEAT
IF in # in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.show); in0 := in
END;
f.Input(x, y, m, isDown);
in := (0 <= x) & (x < w) & (0 <= y) & (y < h)
UNTIL ~isDown;
IF in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.hide);
IF Controllers.modify IN m THEN
IF v.history[0].comment # NIL THEN comment.s := v.history[0].comment^$;
ELSE comment.s := "";
END;
StdCmds.OpenToolDialog("Std/Rsrc/Stamps", "Comment");
ELSE ShowHistory(v);
END
END
END Track;
PROCEDURE (v: StdView) HandleCtrlMsg (
f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN
WITH msg: Controllers.TrackMsg DO
Track(v, f, msg.x, msg.y, msg.modifiers)
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor
ELSE
END
END HandleCtrlMsg;
(* ------------ programming interface: ---------------------- *)
PROCEDURE GetFirstInText* (t: TextModels.Model): Views.View;
VAR r: TextModels.Reader; v: Views.View;
BEGIN
IF t # NIL THEN
r := t.NewReader(NIL);
REPEAT r.ReadView(v) UNTIL (v = NIL) OR (v IS StdView);
RETURN v;
ELSE RETURN NIL;
END;
END GetFirstInText;
PROCEDURE IsStamp* (v: Views.View): BOOLEAN;
BEGIN
RETURN v IS StdView;
END IsStamp;
PROCEDURE GetInfo* (v: Views.View; VAR snr, historylen: INTEGER);
BEGIN
ASSERT(v IS StdView, 20);
WITH v: StdView DO
snr := v.history[0].snr; historylen := v.nentries;
END
END GetInfo;
PROCEDURE GetData* (v: Views.View; entryno: INTEGER;
VAR fprint: INTEGER; VAR date: Dates.Date; VAR time: Dates.Time);
BEGIN
ASSERT(v IS StdView, 20);
WITH v: StdView DO
IF entryno <= v.nentries THEN
fprint := v.history[entryno].fprint;
Dates.DayToDate(v.history[entryno].date, date);
time.minute := v.history[entryno].time MOD 64;
time.minute := v.history[entryno].time DIV 64;
time.second := 0;
END
END
END GetData;
(** Insert new history entry with comment in v. *)
PROCEDURE Stamp* (v: Views.View; comment: ARRAY OF CHAR);
BEGIN
ASSERT(v IS StdView, 20);
WITH v: StdView DO
Update(v, TRUE);
NEW(v.history[0].comment, LEN(comment$) + 1);
v.history[0].comment^ := comment$;
END
END Stamp;
PROCEDURE New* (): Views.View;
VAR v: StdView; d: Dates.Date; t: Dates.Time;
BEGIN
NEW(v); v.history[0].snr := 0; v.nentries := 0;
v.history[0].fprint := 0;
Dates.GetDate(d); Dates.GetTime(t);
v.history[0].date := Dates.Day(d);
v.history[0].time := t.minute + t.hour*64;
Format(v);
RETURN v;
END New;
PROCEDURE SetComment*;
VAR v: Views.View; op: SetCmtOp;
BEGIN
v := GetFirstInText(TextViews.FocusText());
IF v # NIL THEN
WITH v: StdView DO
NEW(op); op.stamp := v;
NEW(op.oldcomment, LEN(comment.s$) + 1);
op.oldcomment^ := comment.s$;
Views.Do(v, setCommentKey, op);
END
END
END SetComment;
PROCEDURE Deposit*;
BEGIN
Views.Deposit(New())
END Deposit;
END StdStamps.
| 37.373034 | 113 | 0.52793 |
8cd19462045c53dbfb213caad447eb6ab19d1fa9 | 305 | hpp | C++ | include/properties/properties.hpp | Voltra/CppProperties | fe63c7394d764ecafea17c570185139f5cb69a78 | [
"MIT"
] | null | null | null | include/properties/properties.hpp | Voltra/CppProperties | fe63c7394d764ecafea17c570185139f5cb69a78 | [
"MIT"
] | null | null | null | include/properties/properties.hpp | Voltra/CppProperties | fe63c7394d764ecafea17c570185139f5cb69a78 | [
"MIT"
] | null | null | null | #pragma once
/**
* @namespace props
* @brief Root namespace containing property classes
*/
namespace props{}
#include <properties/property.h>
#include <properties/readonly.h>
#include <properties/Prop.h>
#include <properties/ReadProp.h>
#include <properties/WriteProp.h>
#include <properties/utils.h> | 21.785714 | 52 | 0.757377 |
8cd1a5a4bf62b3720695a9a12beaaee08decda9d | 1,357 | cpp | C++ | emulator/src/mame/video/tutankhm.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/video/tutankhm.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/video/tutankhm.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Mirko Buffoni
/***************************************************************************
video.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "emu.h"
#include "includes/tutankhm.h"
/*************************************
*
* Write handlers
*
*************************************/
WRITE_LINE_MEMBER(tutankhm_state::flip_screen_x_w)
{
m_flip_x = state;
}
WRITE_LINE_MEMBER(tutankhm_state::flip_screen_y_w)
{
m_flip_y = state;
}
/*************************************
*
* Video update
*
*************************************/
uint32_t tutankhm_state::screen_update_tutankhm(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
int xorx = m_flip_x ? 255 : 0;
int xory = m_flip_y ? 255 : 0;
for (int y = cliprect.min_y; y <= cliprect.max_y; y++)
{
uint32_t *dst = &bitmap.pix32(y);
for (int x = cliprect.min_x; x <= cliprect.max_x; x++)
{
uint8_t effx = x ^ xorx;
uint8_t yscroll = (effx < 192 && m_scroll.found()) ? *m_scroll : 0;
uint8_t effy = (y ^ xory) + yscroll;
uint8_t vrambyte = m_videoram[effy * 128 + effx / 2];
uint8_t shifted = vrambyte >> (4 * (effx % 2));
dst[x] = m_palette->pen_color(shifted & 0x0f);
}
}
return 0;
}
| 22.245902 | 119 | 0.512159 |
8cd42c8bf8be13c37152815eca3a7b1e728c26c3 | 282 | cpp | C++ | bitwise is power of 2.cpp | asadd007/beginners-C-program-examples | 5402774a9554feea958907481af3a47d7d6060b7 | [
"MIT"
] | null | null | null | bitwise is power of 2.cpp | asadd007/beginners-C-program-examples | 5402774a9554feea958907481af3a47d7d6060b7 | [
"MIT"
] | null | null | null | bitwise is power of 2.cpp | asadd007/beginners-C-program-examples | 5402774a9554feea958907481af3a47d7d6060b7 | [
"MIT"
] | null | null | null | #include<stdio.h>
int main()
{
int n;//take n=8;
printf("Enter the number to check it is power of 2 or not :\n");
scanf("%d",&n);
if((n&(n-1))==0)//8=1000,7=0111 when we take and of (8 & 7)=0;
printf("%d is power of 2",n);
else
printf("%d is not power of 2",n);
}
| 23.5 | 66 | 0.56383 |
8cd4fd710f3c18a8622b605dc0e595f513b4ca51 | 354 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 3,294 | 2016-10-30T05:27:20.000Z | 2022-03-31T15:59:30.000Z | samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 16,739 | 2016-10-28T19:41:29.000Z | 2022-03-31T22:38:48.000Z | samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp | BaruaSourav/docs | c288ed777de6b091f5e074d3488f7934683f3eb5 | [
"CC-BY-4.0",
"MIT"
] | 6,701 | 2016-10-29T20:56:11.000Z | 2022-03-31T12:32:26.000Z |
#using <System.Xml.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Xml::Serialization;
// <Snippet1>
public ref class Car
{
public:
[XmlAttributeAttribute(Namespace="Make")]
String^ MakerName;
[XmlAttributeAttribute(Namespace="Model")]
String^ ModelName;
};
// </Snippet1>
| 15.391304 | 45 | 0.723164 |
8cd69161a48a2981e3173a0b39c7f7fce5fbda19 | 28 | cpp | C++ | FootCommander.cpp | amit1021/wargame-a | d46702bf56aff054469eae864fbb59cb87728065 | [
"MIT"
] | null | null | null | FootCommander.cpp | amit1021/wargame-a | d46702bf56aff054469eae864fbb59cb87728065 | [
"MIT"
] | null | null | null | FootCommander.cpp | amit1021/wargame-a | d46702bf56aff054469eae864fbb59cb87728065 | [
"MIT"
] | null | null | null | #include "FootCommander.hpp" | 28 | 28 | 0.821429 |
8cda95fd83e580f2cd1abf917f21598d4332a6a2 | 1,589 | hpp | C++ | src/config.hpp | tpruzina/dvc-toggler-linux | ccd70fedfdc47172e876c04357b863bb758bd304 | [
"BSD-3-Clause"
] | null | null | null | src/config.hpp | tpruzina/dvc-toggler-linux | ccd70fedfdc47172e876c04357b863bb758bd304 | [
"BSD-3-Clause"
] | 1 | 2019-05-20T16:47:28.000Z | 2019-05-20T16:47:28.000Z | src/config.hpp | tpruzina/dvc-toggler-linux | ccd70fedfdc47172e876c04357b863bb758bd304 | [
"BSD-3-Clause"
] | null | null | null | #ifndef CONFIG_HPP
#define CONFIG_HPP
#include <QSettings>
#include <QMap>
#define CONFIG_SLEEP_STR "watcher_sleep_ms"
#define CONFIG_START_MIN_STR "start_minimized"
#define CONFIG_ENABLED_STR "enabled"
#define CONFIG_AUTOHIDE_STR "autohide"
#define CONFIG_TRAY_INFO_SHOWN "tray_icon_warning_shown"
#define CONFIG_DEFAULT_PROFILE_STR "default"
using DVC_map = QMap<int,int>;
class Config : public QSettings
{
public:
Config() noexcept;
QVariant getValue(const QString &key, const QVariant &defaultValue = QVariant()) const noexcept;
void setValue(const QString &key, const QVariant &value) noexcept;
QStringList queryProfiles() noexcept;
bool get_bool(const QString &attribute)
{
return getValue(attribute).toBool();
}
bool set_bool(const QString &attribute, bool val)
{
setValue(attribute, val);
return val;
}
bool toggle_bool(const QString &attribute)
{
return set_bool(attribute, !get_bool(attribute));
}
QString queryIconPath(const QString &profile_name) noexcept;
void setIconPath(const QString &profile_name, const QString &path) noexcept;
DVC_map queryDVC(const QString &profile_name) noexcept;
void setDVC(const QString &profile_name, DVC_map &map) noexcept;
unsigned querySleepTime_ms(void) noexcept;
void setSleepTime_ms(unsigned ms) noexcept;
void removeProfile(const QString &key) noexcept;
};
#endif // CONFIG_HPP
| 29.425926 | 104 | 0.674638 |
8cdb79234c0934d62035d0a852b2e11fc2917b3e | 3,019 | hpp | C++ | include/message.hpp | astuff/can_dbc_loader | ce97f5cf7b002e5faca367c50f33fff2dcde2c43 | [
"MIT"
] | 9 | 2019-10-23T15:00:06.000Z | 2021-04-02T01:45:26.000Z | include/message.hpp | astuff/can_dbc_loader | ce97f5cf7b002e5faca367c50f33fff2dcde2c43 | [
"MIT"
] | null | null | null | include/message.hpp | astuff/can_dbc_loader | ce97f5cf7b002e5faca367c50f33fff2dcde2c43 | [
"MIT"
] | 5 | 2020-04-30T03:45:13.000Z | 2021-11-25T05:28:16.000Z | // Copyright (c) 2019 AutonomouStuff, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef MESSAGE_HPP_
#define MESSAGE_HPP_
#include "common_defs.hpp"
#include "bus_node.hpp"
#include "comment.hpp"
#include "signal.hpp"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace AS
{
namespace CAN
{
namespace DbcLoader
{
class Message
: public DbcObj, public AttrObj
{
public:
Message(std::string && dbc_text);
Message(
unsigned int id,
std::string && name,
unsigned char dlc,
BusNode && transmitting_node,
std::vector<Signal> && signals);
~Message() = default;
Message(const Message & other);
Message(Message && other) = default;
Message & operator=(const Message & other);
Message & operator=(Message && other) = default;
unsigned int getId() const;
std::string getName() const;
unsigned char getDlc() const;
unsigned char getLength() const;
BusNode getTransmittingNode() const;
std::unordered_map<std::string, const Signal *> getSignals() const;
const std::string * getComment() const;
static unsigned char dlcToLength(const unsigned char & dlc);
friend class Database;
friend class MessageTranscoder;
private:
unsigned int id_;
std::string name_;
unsigned char dlc_;
BusNode transmitting_node_;
std::unordered_map<std::string, Signal> signals_;
std::unique_ptr<std::string> comment_;
void generateText() override;
void parse() override;
};
class MessageTranscoder
{
public:
MessageTranscoder(Message * dbc_msg);
const Message * getMessageDef();
void decode(std::vector<uint8_t> && raw_data, TranscodeError * err = nullptr);
std::vector<uint8_t> encode(TranscodeError * err = nullptr);
private:
void decodeRawData(TranscodeError * err);
Message * msg_def_;
std::vector<uint8_t> data_;
std::unordered_map<std::string, SignalTranscoder> signal_xcoders_;
};
} // namespace DbcLoader
} // namespace CAN
} // namespace AS
#endif // MESSAGE_HPP_
| 28.752381 | 80 | 0.735012 |
8cdfcc00eb84c51cc43aa66fa173361f95dbb15a | 1,057 | cpp | C++ | src/ConeClassifier.cpp | BakrN/ImageProcessingFEB | ea4d813de7f2901c44aad369bdbc38d5dbc01d9a | [
"MIT"
] | null | null | null | src/ConeClassifier.cpp | BakrN/ImageProcessingFEB | ea4d813de7f2901c44aad369bdbc38d5dbc01d9a | [
"MIT"
] | null | null | null | src/ConeClassifier.cpp | BakrN/ImageProcessingFEB | ea4d813de7f2901c44aad369bdbc38d5dbc01d9a | [
"MIT"
] | null | null | null | #include "ConeClassifier.h"
vn::ConeClassifier::ConeClassifier(){
}
vn::ConeClassifier::ConeClassifier(const std::shared_ptr<StereoCamera>& Camera){
m_Camera = Camera;
}
vn::ConeClassifier::~ConeClassifier(){
}
void vn::ConeClassifier::Detect(){
//preprocess image to do undermine illumination effects
cv::Mat pre_image;
//process output
cv::Mat detections;
// a mat with rows of all detections
for (int i = 0 ; i < detections.rows; i++){
if(detections.at<float>(i , 1)>= CONFIDENCE_THRESHOLD){ // confidence
// add bounding box to vector
// calculate color by doing some image processing
}
}
}
void vn::ConeClassifier::Detect(const std::shared_ptr<StereoCamera>& Camera){
m_Camera = Camera;
Detect();
}
// simple canny edge detector with threshhold
cv::Mat& EdgeDetect(const cv::Mat& ConeImage){
cv::Mat edge_image;
edge_image.create(ConeImage.size(), CV_8UC1);
return edge_image;
}
// Hough transform
// look for line within range | 24.581395 | 80 | 0.659413 |
8ce13ff806babb1ef5d71e52db54a76d89500c3b | 1,373 | cpp | C++ | matrix/module/DropoutLayer.cpp | xiaohuihuichao/matrix | 1500b398fe96ee308990dd14590df2b76aba3dad | [
"ICU"
] | 6 | 2019-02-11T09:50:45.000Z | 2021-07-31T03:27:11.000Z | matrix/module/DropoutLayer.cpp | xiaohuihuichao/matrix | 1500b398fe96ee308990dd14590df2b76aba3dad | [
"ICU"
] | null | null | null | matrix/module/DropoutLayer.cpp | xiaohuihuichao/matrix | 1500b398fe96ee308990dd14590df2b76aba3dad | [
"ICU"
] | 1 | 2021-04-25T12:31:03.000Z | 2021-04-25T12:31:03.000Z | #include "DropoutLayer.hpp"
namespace mario
{
DropoutLayer::DropoutLayer(const int &_lastNeuronNum, const double &_p)
{
m_p = _p;
m_in = matrix(1, _lastNeuronNum, 0);
m_mul = matrix(1, _lastNeuronNum, 0);
m_out = matrix(1, _lastNeuronNum, 0);
m_dx = matrix(1, _lastNeuronNum, 0);
}
const matrix& DropoutLayer::forward(const matrix &_lastOut)
{
if (_lastOut.cols() != m_in.cols())
{
throw "Error in DropoutLayer::forward(): _lastOut.cols() != m_in.cols().";
}
m_in.release();
m_in = _lastOut;
#if 1==TRAIN
matrix deleteMul(1, m_in.cols(), 0);
for (int c = 0; c < deleteMul.cols(); ++c)
{
if (isDelete())
{
deleteMul.set(0, c, 0);
}
else
{
deleteMul.set(0, c, 1);
}
}
#endif // 1==TRAIN
#if 0==TRAIN
matrix deleteMul(1, m_in.cols(), 1);
#endif // 0==TRAIN
m_mul.release();
m_mul = copyRow(deleteMul, _lastOut.rows());
m_out.release();
m_out = m_mul.mul(_lastOut);
return m_out;
}
const matrix& DropoutLayer::backward(const matrix &_nextDerr)
{
if (m_dx.cols() != _nextDerr.cols())
{
throw "Error in DropoutLayer::backward(): m_dx.cols() != _nextDerr.cols().\n";
}
m_dx.release();
m_dx = m_mul.mul(_nextDerr);
return m_dx;
}
bool DropoutLayer::isDelete()
{
double p = rand() / double(RAND_MAX);
if (p < m_p)
{
return true;
}
return false;
}
}
| 16.152941 | 81 | 0.612527 |
8ce148dd152c96d19575fb5d72ab2552238fa455 | 3,835 | cpp | C++ | src/inference/src/check_network_batchable.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/inference/src/check_network_batchable.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/inference/src/check_network_batchable.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | #include "check_network_batchable.hpp"
#include "dimension_tracker.hpp"
#include "ie_ngraph_utils.hpp"
#include "ngraph/opsets/opset.hpp"
#include "openvino/op/detection_output.hpp"
#include "openvino/op/ops.hpp"
#include "openvino/pass/manager.hpp"
#include "transformations/common_optimizations/dimension_tracking.hpp"
#include "transformations/init_node_info.hpp"
namespace InferenceEngine {
namespace details {
NetworkBatchAbility isNetworkBatchable(const CNNNetwork& orig_network,
const std::string& deviceNameWithoutBatch,
bool strictly_track_dims) {
CNNNetwork clonedNetwork(cloneNetwork(orig_network));
auto function = clonedNetwork.getFunction();
// find the batch dim
ov::pass::Manager m;
m.register_pass<ngraph::pass::InitNodeInfo>();
m.register_pass<ov::pass::FindBatch>(true, strictly_track_dims);
m.run_passes(function);
bool any_batched_inputs = false;
// do not reshape/re-batch originally batched networks and when there are no inputs with the N* layouts
// input(s) should have the batch dim as the first dim or none (current limitation of the auto-batching impl)
const auto& params = function->get_parameters();
for (size_t input_id = 0; input_id < params.size(); input_id++) {
const auto& input = params[input_id];
const auto& shape = input->get_partial_shape();
// currently no plugin support batched execution for dynamic networks
if (shape.is_dynamic())
return NetworkBatchAbility::NO;
// check the batch dim: either 0th (and the original batch size of 1) or none
if (shape.size() && ov::DimensionTracker::get_label(shape[0])) {
const auto& static_shape = input->get_shape();
if (static_shape[0] != 1)
return NetworkBatchAbility::NO;
else
any_batched_inputs = true;
} else {
// if the 0-th dim is not for the batch, then we support only the case when NONE dimension is batch
for (size_t s = 1; s < shape.size(); s++)
if (ov::DimensionTracker::get_label(shape[s]))
return NetworkBatchAbility::NO;
}
}
if (!any_batched_inputs)
return NetworkBatchAbility::NO;
for (auto&& node : orig_network.getFunction()->get_ops())
node->get_rt_info()["affinity"] = "BATCH"; // default affinity (ignored if HETERO is not triggered)
// have to execute the DetectionOutput separately (without batching)
// as this layer does mix-in the values from the different inputs (batch id)
bool bDetectionOutput = false;
for (auto& result_node : orig_network.getFunction()->get_results()) {
auto do_node = result_node->input_value(0).get_node_shared_ptr();
std::shared_ptr<ov::Node> convert_node;
if (ov::is_type<ov::opset1::Convert>(do_node)) { // cases with do->convert->result
convert_node = do_node;
do_node = convert_node->get_input_node_shared_ptr(0);
}
// the code below doesn't need to separate the versions (opsets) of the DetectionOutput
// so base class check is enough
auto detectionOutputBase = std::dynamic_pointer_cast<ov::op::util::DetectionOutputBase>(do_node);
if (detectionOutputBase) {
result_node->get_rt_info()["affinity"] = deviceNameWithoutBatch;
do_node->get_rt_info()["affinity"] = deviceNameWithoutBatch;
if (convert_node)
convert_node->get_rt_info()["affinity"] = deviceNameWithoutBatch;
bDetectionOutput = true;
}
}
return bDetectionOutput ? NetworkBatchAbility::WITH_HETERO : NetworkBatchAbility::AS_IS;
}
} // namespace details
} // namespace InferenceEngine | 48.544304 | 113 | 0.663625 |
8ce6ba6e115cf9ff1876a9f7781287efc9c78fdc | 7,398 | cpp | C++ | Labs/Puppeteer/src/main.cpp | jadnohra/jad-pre-2015-dabblings | 368cbd39c6371b3e48b0c67d9a83fc20eee41346 | [
"MIT"
] | null | null | null | Labs/Puppeteer/src/main.cpp | jadnohra/jad-pre-2015-dabblings | 368cbd39c6371b3e48b0c67d9a83fc20eee41346 | [
"MIT"
] | null | null | null | Labs/Puppeteer/src/main.cpp | jadnohra/jad-pre-2015-dabblings | 368cbd39c6371b3e48b0c67d9a83fc20eee41346 | [
"MIT"
] | null | null | null | #include "NeheGL.h"
#include "app.h"
#define WM_TOGGLEFULLSCREEN (WM_USER+1) // Application Define Message For Toggling
static BOOL g_isProgramLooping; // Window Creation Loop, For FullScreen/Windowed Toggle // Between Fullscreen / Windowed Mode
static BOOL g_createFullScreen; // If TRUE, Then Create Fullscreen
App* g_App = NULL;
LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg)
{
case WM_DROPFILES:
{
if (g_App)
{
HDROP fDrop = (HDROP) wParam;
int dropped_file_count = DragQueryFileA(fDrop, 0xFFFFFFFF, NULL, 0);
char* fName = NULL;
int buffer_size = 0;
g_App->OnFilesDropped(dropped_file_count);
for (int i=0; i<dropped_file_count; ++i)
{
UINT nBufSize = 1 + DragQueryFileA(fDrop, i, NULL, 0);
if (nBufSize > buffer_size)
{
buffer_size = nBufSize;
delete fName;
fName = new char[buffer_size];
}
DragQueryFileA(fDrop, i, fName, buffer_size);
g_App->OnFileDropped(fName);
}
delete fName;
DragFinish(fDrop);
}
return 0;
}
break;
}
return NeheGLWindowProc(hWnd,uMsg,wParam,lParam);
}
BOOL RegisterWindowClass (Application* application) // Register A Window Class For This Application.
{ // TRUE If Successful
// Register A Window Class
WNDCLASSEXA windowClass; // Window Class
ZeroMemory (&windowClass, sizeof (WNDCLASSEXA)); // Make Sure Memory Is Cleared
windowClass.cbSize = sizeof (WNDCLASSEXA); // Size Of The windowClass Structure
windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraws The Window For Any Movement / Resizing
windowClass.lpfnWndProc = (WNDPROC)(WndProc); // WindowProc Handles Messages
windowClass.hInstance = application->hInstance; // Set The Instance
windowClass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE); // Class Background Brush Color
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
windowClass.lpszClassName = application->className; // Sets The Applications Classname
if (RegisterClassExA (&windowClass) == 0) // Did Registering The Class Fail?
{
// NOTE: Failure, Should Never Happen
MessageBoxA (HWND_DESKTOP, "RegisterClassEx Failed!", "Error", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return False (Failure)
}
return TRUE; // Return True (Success)
}
int main()
{
Application application; // Application Structure
GL_Window window; // Window Structure
Keys keys; // Key Structure
BOOL isMessagePumpActive; // Message Pump Active?
MSG msg; // Window Message Structure
DWORD tickCount; // Used For The Tick Counter
// Fill Out Application Data
application.className = "Puppeteer"; // Application Class Name
application.hInstance = GetModuleHandle(NULL); // Application Instance
// Fill Out Window
ZeroMemory (&window, sizeof (GL_Window)); // Make Sure Memory Is Zeroed
window.keys = &keys; // Window Key Structure
window.init.application = &application; // Window Application
window.init.title = "Puppeteer"; // Window Title
window.init.width = 800; // Window Width
window.init.height = 600; // Window Height
window.init.bitsPerPixel = 32; // Bits Per Pixel
window.init.isFullScreen = FALSE; // Fullscreen? (Set To TRUE)
ZeroMemory (&keys, sizeof (Keys)); // Zero keys Structure
// Ask The User If They Want To Start In FullScreen Mode?
//if (MessageBoxA (HWND_DESKTOP, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MB_YESNO | MB_ICONQUESTION) == IDNO)
//{
// window.init.isFullScreen = FALSE; // If Not, Run In Windowed Mode
//}
// Register A Class For Our Window To Use
if (RegisterWindowClass (&application) == FALSE) // Did Registering A Class Fail?
{
// Failure
MessageBoxA (HWND_DESKTOP, "Error Registering Window Class!", "Error", MB_OK | MB_ICONEXCLAMATION);
return -1; // Terminate Application
}
g_isProgramLooping = TRUE; // Program Looping Is Set To TRUE
g_createFullScreen = window.init.isFullScreen; // g_createFullScreen Is Set To User Default
App app;
//while (g_isProgramLooping) // Loop Until WM_QUIT Is Received
{
// Create A Window
window.init.isFullScreen = g_createFullScreen; // Set Init Param Of Window Creation To Fullscreen?
if (CreateWindowGL (&window) == TRUE) // Was Window Creation Successful?
{
// At This Point We Should Have A Window That Is Setup To Render OpenGL
if (!app.Load(&window)) // Call User Intialization
{
// Failure
TerminateApplication (&window); // Close Window, This Will Handle The Shutdown
}
else // Otherwise (Start The Message Pump)
{
g_App = &app;
DragAcceptFiles(window.hWnd, TRUE);
// Initialize was a success
isMessagePumpActive = TRUE; // Set isMessagePumpActive To TRUE
while (isMessagePumpActive == TRUE) // While The Message Pump Is Active
{
// Success Creating Window. Check For Window Messages
if (PeekMessage (&msg, window.hWnd, 0, 0, PM_REMOVE) != 0)
{
// Check For WM_QUIT Message
if (msg.message != WM_QUIT) // Is The Message A WM_QUIT Message?
{
DispatchMessage (&msg); // If Not, Dispatch The Message
}
else // Otherwise (If Message Is WM_QUIT)
{
isMessagePumpActive = FALSE; // Terminate The Message Pump
}
}
else // If There Are No Messages
{
//if (window.isVisible == FALSE) // If Window Is Not Visible
//{
// WaitMessage (); // Application Is Minimized Wait For A Message
//}
//else // If Window Is Visible
{
// Process Application Loop
tickCount = GetTickCount (); // Get The Tick Count
app.Update (tickCount - window.lastTickCount); // Update The Counter
window.lastTickCount = tickCount; // Set Last Count To Current Count
app.Draw(); // Draw Our Scene
SwapBuffers (window.hDC); // Swap Buffers (Double Buffering)
}
}
} // Loop While isMessagePumpActive == TRUE
} // If (Initialize (...
// Application Is Finished
app.End();
//Deinitialize (); // User Defined DeInitialization
g_App = NULL;
DestroyWindowGL (&window); // Destroy The Active Window
}
else // If Window Creation Failed
{
// Error Creating Window
MessageBoxA (HWND_DESKTOP, "Error Creating OpenGL Window", "Error", MB_OK | MB_ICONEXCLAMATION);
g_isProgramLooping = FALSE; // Terminate The Loop
}
} // While (isProgramLooping)
UnregisterClassA (application.className, application.hInstance); // UnRegister Window Class
return 0;
} | 37.744898 | 153 | 0.620843 |
8ce85cbe115c3eaf335aec9520d6771c5923f882 | 2,306 | cpp | C++ | examples/Scrolling/Scrolling.cpp | picrap/vaca | 377070c2124bb71649313f6a144c6bd40fdee723 | [
"MIT"
] | null | null | null | examples/Scrolling/Scrolling.cpp | picrap/vaca | 377070c2124bb71649313f6a144c6bd40fdee723 | [
"MIT"
] | null | null | null | examples/Scrolling/Scrolling.cpp | picrap/vaca | 377070c2124bb71649313f6a144c6bd40fdee723 | [
"MIT"
] | null | null | null | // Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
//
// This file is distributed under the terms of the MIT license,
// please read LICENSE.txt for more information.
#include <vaca/vaca.h>
#include "../resource.h"
using namespace vaca;
//////////////////////////////////////////////////////////////////////
class ScrollableTest : public ScrollableWidget
{
// true if we have to wait some milliseconds after update the
// invalidated area
bool m_sleep;
public:
ScrollableTest(Widget* parent)
: ScrollableWidget(parent)
, m_sleep(false)
{
setFullSize(Size(2000, 1500));
// the red color will be used to erase the background of
// invalidated area, but in onPaint the red will be re-erased with
// a white brush
setBgColor(Color::Red);
}
void setSleep(bool sleep)
{
m_sleep = sleep;
}
protected:
virtual void onPaint(PaintEvent& ev)
{
Graphics& g = ev.getGraphics();
// this sleep have the purpose to show the invalidated areas 100
// milliseconds (the background filled by default with the
// getBgColor, that in this case is Color::Red)
if (m_sleep)
CurrentThread::sleep(100);
// draw the (white) background
Brush brush(Color::White);
g.fillRect(brush, getClientBounds());
// draw the shapes (ellipses and round-rectangles)
Pen pen(Color::Blue);
Point offset = -getScrollPoint();
for (int r=0; r<10; ++r) {
Rect rc(offset, getFullSize());
rc.shrink(50 * r);
g.drawEllipse(pen, rc);
g.drawRoundRect(pen, rc, Size(32, 32));
}
}
};
//////////////////////////////////////////////////////////////////////
void updateSleep(ScrollableTest* s, CheckBox* cb)
{
s->setSleep(cb->isSelected());
}
int VACA_MAIN()
{
Application app;
Frame frm(L"Scrolling");
ScrollableTest wgt(&frm);
CheckBox sleep(L"Show invalidated areas for some milliseconds", &frm);
sleep.Click.connect(Bind<void>(&updateSleep, &wgt, &sleep));
wgt.setConstraint(new BoxConstraint(true));
frm.setLayout(new BoxLayout(Orientation::Vertical, false));
frm.setIcon(ResourceId(IDI_VACA));
frm.setVisible(true);
app.run();
return 0;
}
| 24.531915 | 73 | 0.606678 |
8ce922f71f5ddd81ed293609b080050c360b16e3 | 708 | cpp | C++ | 1100/90/1196a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 1 | 2020-07-03T15:55:52.000Z | 2020-07-03T15:55:52.000Z | 1100/90/1196a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | null | null | null | 1100/90/1196a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 3 | 2020-10-01T14:55:28.000Z | 2021-07-11T11:33:58.000Z | #include <algorithm>
#include <array>
#include <iostream>
using integer = long long;
template <typename T, size_t N>
std::istream& operator >>(std::istream& input, std::array<T, N>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(integer v)
{
std::cout << v << '\n';
}
void solve(std::array<integer, 3>& v)
{
std::sort(v.begin(), v.end());
const integer d = std::min(v[1] - v[0], v[2]);
v[0] += d;
v[2] -= d;
answer(v[0] < v[1] ? v[0] : v[0] + v[2] / 2);
}
void test_case()
{
std::array<integer, 3> v;
std::cin >> v;
solve(v);
}
int main()
{
size_t t;
std::cin >> t;
while (t-- > 0)
test_case();
return 0;
}
| 14.16 | 67 | 0.507062 |
8ce9b13579ba3a267f73417c070ea22855259089 | 19,164 | cpp | C++ | plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 5 | 2016-04-18T23:12:51.000Z | 2022-03-06T05:12:07.000Z | plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 2 | 2015-10-09T19:13:25.000Z | 2018-12-25T17:16:54.000Z | plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 15 | 2015-02-23T16:35:28.000Z | 2022-03-25T13:40:33.000Z | /*
* vfspluginVP: Generic GUCEF VFS plugin for "Violation Pack" archives
* Copyright (C) 2002 - 2008. Dinand Vanvelzen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#include <string.h>
#ifndef GUCEF_CORE_DVMD5UTILS_H
#include "dvmd5utils.h"
#define GUCEF_CORE_DVMD5UTILS_H
#endif /* GUCEF_CORE_DVMD5UTILS_H ? */
#ifndef GUCEF_CORE_CDYNAMICBUFFER_H
#include "CDynamicBuffer.h"
#define GUCEF_CORE_CDYNAMICBUFFER_H
#endif /* GUCEF_CORE_CDYNAMICBUFFER_H ? */
#ifndef GUCEF_CORE_CDYNAMICBUFFERACCESS_H
#include "CDynamicBufferAccess.h"
#define GUCEF_CORE_CDYNAMICBUFFERACCESS_H
#endif /* GUCEF_CORE_CDYNAMICBUFFERACCESS_H ? */
#ifndef GUCEF_CORE_CSUBFILEACCESS_H
#include "gucefCORE_CSubFileAccess.h"
#define GUCEF_CORE_CSUBFILEACCESS_H
#endif /* GUCEF_CORE_CSUBFILEACCESS_H ? */
#ifndef GUCEF_CORE_DVCPPSTRINGUTILS_H
#include "dvcppstringutils.h"
#define GUCEF_CORE_DVCPPSTRINGUTILS_H
#endif /* GUCEF_CORE_DVCPPSTRINGUTILS_H ? */
#include "vfspluginVP_CVPArchive.h"
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GUCEF {
namespace VFSPLUGIN {
namespace VP {
/*-------------------------------------------------------------------------//
// //
// TYPES //
// //
//-------------------------------------------------------------------------*/
struct SVPFileIndexEntry
{
VFS::UInt32 offset;
VFS::UInt32 size;
char filename[ 32 ];
VFS::Int32 timestamp;
};
typedef struct SVPFileIndexEntry TVPFileIndexEntry;
/*-------------------------------------------------------------------------//
// //
// CONSTANTS //
// //
//-------------------------------------------------------------------------*/
#define VP_HEADER_SIZE 16
#define VP_INDEX_ENTRY_SIZE 44
/*-------------------------------------------------------------------------//
// //
// GLOBAL VARS //
// //
//-------------------------------------------------------------------------*/
const VFS::CString CVPArchive::VPArchiveTypeName = "vp";
/*-------------------------------------------------------------------------//
// //
// UTILITIES //
// //
//-------------------------------------------------------------------------*/
CVPArchive::CVPArchive( void )
: CArchive() ,
m_header() ,
m_index() ,
m_archiveName() ,
m_archivePath()
{GUCEF_TRACE;
}
/*-------------------------------------------------------------------------*/
CVPArchive::~CVPArchive()
{GUCEF_TRACE;
UnloadArchive();
}
/*-------------------------------------------------------------------------*/
VFS::CArchive::CVFSHandlePtr
CVPArchive::GetFile( const VFS::CString& file ,
const char* mode ,
const VFS::UInt32 memLoadSize ,
const bool overwrite )
{GUCEF_TRACE;
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: request to get file: " + file );
// We only support read only modes
if ( *mode != 'r' )
{
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: Unable to support requested file access mode for file: " + file );
return CVFSHandlePtr();
}
// load the file
CORE::CIOAccess* fileAccess = LoadFile( file, memLoadSize );
if ( NULL != fileAccess )
{
// create a handle for the file
VFS::CString filePath = m_archivePath;
CORE::AppendToPath( filePath, file );
VFS::CVFSHandle* fileHandle = new VFS::CVFSHandle( fileAccess ,
file ,
filePath );
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: providing access to file: " + file );
return CVFSHandlePtr( fileHandle, this );
}
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: Unable to provide access to file: " + file );
return CVFSHandlePtr();
}
/*-------------------------------------------------------------------------*/
bool
CVPArchive::DeleteFile( const VFS::CString& filePath )
{GUCEF_TRACE;
// Not implemented / supported at this time
return false;
}
/*-------------------------------------------------------------------------*/
bool
CVPArchive::StoreAsFile( const CORE::CString& filepath ,
const CORE::CDynamicBuffer& data ,
const CORE::UInt64 offset ,
const bool overwrite )
{GUCEF_TRACE;
// Not implemented / supported at this time
return false;
}
/*-------------------------------------------------------------------------*/
void
CVPArchive::GetList( TStringSet& outputList ,
const VFS::CString& mountLocation ,
const VFS::CString& archiveLocation ,
bool recursive ,
bool includePathInFilename ,
const VFS::CString& filter ,
bool addFiles ,
bool addDirs ) const
{GUCEF_TRACE;
TFileIndexMap::const_iterator i = m_index.begin();
while ( i != m_index.end() )
{
// Check if the starting path matches
const VFS::CString& filePath = (*i).first;
if ( filePath == archiveLocation )
{
// Don't add the location itself to the list
++i;
continue;
}
if ( 0 == filePath.HasSubstr( archiveLocation, true ) )
{
const TVPIndexEntry& indexEntry = (*i).second;
// Check if the entry is a directory
if ( indexEntry.size == 0 || indexEntry.offset == 0 )
{
if ( !addDirs )
{
// Skip this item
++i;
continue;
}
}
else
{
if ( !addFiles )
{
// Skip this item
++i;
continue;
}
}
if ( !recursive )
{
// Check if we have multiple subdirs beyond the "location" to get to
// the archive. If so then we cannot add this archive because recursive
// searching is not allowed.
if ( !CORE::IsFileInDir( archiveLocation, filePath ) )
{
// The directory seperator was not the last character so we have multiple
// sub-dirs which is not allowed, we cannot add this item
++i;
continue;
}
}
VFS::CString filename = CORE::ExtractFilename( filePath );
if ( filename != ".." )
{
if ( includePathInFilename )
{
outputList.insert( filePath );
}
else
{
outputList.insert( filename );
}
}
}
++i;
}
}
/*-------------------------------------------------------------------------*/
bool
CVPArchive::FileExists( const VFS::CString& filePath ) const
{GUCEF_TRACE;
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: request to check if file exists: " + filePath );
return m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) ) != m_index.end();
}
/*-------------------------------------------------------------------------*/
VFS::UInt32
CVPArchive::GetFileSize( const VFS::CString& filePath ) const
{GUCEF_TRACE;
TFileIndexMap::const_iterator i = m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) );
if ( i != m_index.end() )
{
return (*i).second.size;
}
return 0;
}
/*-------------------------------------------------------------------------*/
CORE::CIOAccess*
CVPArchive::LoadFile( const VFS::CString& file ,
const VFS::UInt32 memLoadSize ) const
{GUCEF_TRACE;
TFileIndexMap::const_iterator i = m_index.find( file.Lowercase().ReplaceChar( '/', '\\' ) );
if ( i != m_index.end() )
{
const TVPIndexEntry& entry = (*i).second;
if ( memLoadSize >= entry.size )
{
FILE* fptr = fopen( m_archivePath.C_String(), "rb" );
if ( NULL == fptr ) return NULL;
if ( 0 == fseek( fptr, entry.offset, SEEK_CUR ) )
{
// prepare a memory buffer for the file
CORE::CDynamicBuffer* fileBuffer = new CORE::CDynamicBuffer();
fileBuffer->SetDataSize( entry.size );
if ( 1 == fread( fileBuffer->GetBufferPtr(), entry.size, 1, fptr ) )
{
// Successfully read file into memory
fclose( fptr );
return new CORE::CDynamicBufferAccess( fileBuffer, true );
}
// unable to read entire file
delete fileBuffer;
}
fclose( fptr );
}
else
{
CORE::CSubFileAccess* fileAccess = new CORE::CSubFileAccess();
if ( fileAccess->Load( m_archivePath ,
entry.offset ,
entry.size ) )
{
return fileAccess;
}
delete fileAccess;
}
}
return NULL;
}
/*-------------------------------------------------------------------------*/
VFS::CString
CVPArchive::GetFileHash( const VFS::CString& file ) const
{GUCEF_TRACE;
CORE::CIOAccess* fileAccess = LoadFile( file.Lowercase().ReplaceChar( '/', '\\' ), 102400 );
if ( NULL != fileAccess )
{
VFS::UInt8 digest[ 16 ];
if ( 0 != CORE::md5fromfile( fileAccess->CStyleAccess() ,
digest ) )
{
delete fileAccess;
char md5_str[ 48 ];
CORE::md5tostring( digest, md5_str );
VFS::CString md5Str;
md5Str.Set( md5_str, 48 );
return md5Str;
}
delete fileAccess;
}
return VFS::CString();
}
/*-------------------------------------------------------------------------*/
CORE::CDateTime
CVPArchive::GetFileModificationTime( const VFS::CString& filePath ) const
{GUCEF_TRACE;
TFileIndexMap::const_iterator i = m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) );
if ( i != m_index.end() )
{
return CORE::CDateTime( (time_t) (*i).second.timestamp, true );
}
return CORE::CDateTime();
}
/*-------------------------------------------------------------------------*/
const VFS::CString&
CVPArchive::GetArchiveName( void ) const
{GUCEF_TRACE;
return m_archiveName;
}
/*-------------------------------------------------------------------------*/
bool
CVPArchive::IsWriteable( void ) const
{GUCEF_TRACE;
return false;
}
/*-------------------------------------------------------------------------*/
bool
CVPArchive::LoadArchive( const VFS::CArchiveSettings& settings )
{GUCEF_TRACE;
// We do not support writable VP archives
if ( settings.GetWriteableRequested() )
return false;
FILE* fptr = fopen( settings.GetActualArchivePath().C_String(), "rb" );
if ( NULL == fptr ) return false;
if ( fread( &m_header, VP_HEADER_SIZE, 1, fptr ) == 1 )
{
if ( ( memcmp( m_header.sig, "VPVP", 4 ) == 0 ) &&
( m_header.version == 2 ) )
{
// Move to the index location at the end of the file
if ( 0 != fseek( fptr, m_header.indexoffset, SEEK_SET ) )
{
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: unable to archive header" );
fclose( fptr );
return false;
}
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Successfully read the archive header" );
// read the index
VFS::CString path;
TVPFileIndexEntry fileEntry;
for ( VFS::UInt32 i=0; i<m_header.idxentries; ++i )
{
if ( fread( &fileEntry, VP_INDEX_ENTRY_SIZE, 1, fptr ) != 1 )
{
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: unable to read index entry" );
m_header.idxentries = i;
break;
}
if ( fileEntry.offset == 0 || fileEntry.size == 0 )
{
// directory entry
VFS::CString dirName;
dirName.Scan( fileEntry.filename, 32 );
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Found directory entry: " + dirName);
if ( dirName == ".." )
{
path = CORE::StripLastSubDir( path );
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Going up to directory: " + path );
}
else
{
CORE::AppendToPath( path, dirName );
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Entering directory: " + dirName );
}
// Add the entry for the directory to our index
TVPIndexEntry entry;
entry.offset = 0;
entry.size = 0;
entry.timestamp = 0;
m_index[ path.Lowercase().ReplaceChar( '/', '\\' ) ] = entry;
}
else
{
// file entry
TVPIndexEntry entry;
entry.offset = fileEntry.offset;
entry.size = fileEntry.size;
entry.timestamp = fileEntry.timestamp;
VFS::CString filenameBuffer;
filenameBuffer.Scan( fileEntry.filename, 32 );
VFS::CString filename = path;
CORE::AppendToPath( filename, filenameBuffer );
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Found file entry: " + filenameBuffer );
m_index[ filename.Lowercase().ReplaceChar( '/', '\\' ) ] = entry;
}
}
fclose( fptr );
m_archiveName = settings.GetArchiveName();
m_archivePath = settings.GetArchivePath();
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Successfully finished reading the index" );
return true;
}
else
{
GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: Archive header not recognized" );
fclose( fptr );
}
}
return false;
}
/*-------------------------------------------------------------------------*/
bool
CVPArchive::LoadArchive( const VFS::CString& archiveName ,
CVFSHandlePtr vfsResource ,
const bool writeableRequest )
{GUCEF_TRACE;
return false;
}
/*-------------------------------------------------------------------------*/
bool
CVPArchive::UnloadArchive( void )
{GUCEF_TRACE;
m_index.clear();
m_archiveName = NULL;
m_archivePath = NULL;
return true;
}
/*-------------------------------------------------------------------------*/
const VFS::CString&
CVPArchive::GetType( void ) const
{GUCEF_TRACE;
return VPArchiveTypeName;
}
/*-------------------------------------------------------------------------*/
void
CVPArchive::DestroyObject( VFS::CVFSHandle* objectToBeDestroyed )
{GUCEF_TRACE;
delete objectToBeDestroyed;
}
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace VP */
}; /* namespace VFSPLUGIN */
}; /* namespace GUCEF */
/*-------------------------------------------------------------------------*/
| 34.717391 | 128 | 0.412283 |
8cecb7820b8d7d4b2a52d3e4487f4d641983d2c9 | 3,356 | cpp | C++ | common_alg/src/surface_cps3_reader.cpp | bs-eagle/bs-eagle | b1017a4f6ac2dcafba2deafec84052ddde792671 | [
"BSD-3-Clause"
] | 7 | 2015-07-16T22:30:36.000Z | 2020-02-06T10:16:42.000Z | common_alg/src/surface_cps3_reader.cpp | bs-eagle/bs-eagle | b1017a4f6ac2dcafba2deafec84052ddde792671 | [
"BSD-3-Clause"
] | null | null | null | common_alg/src/surface_cps3_reader.cpp | bs-eagle/bs-eagle | b1017a4f6ac2dcafba2deafec84052ddde792671 | [
"BSD-3-Clause"
] | 3 | 2017-01-05T20:06:28.000Z | 2021-12-20T16:19:10.000Z | /// @file surface_cps3_reader.cpp
/// @brief Read surface in CPS-3 ASCII format
/// @author uentity
/// @version 1.0
/// @date 30.09.2015
/// @copyright This source code is released under the terms of
/// the BSD License. See LICENSE for more details.
#include "bs_kernel.h"
#include "conf.h"
#include <fstream>
#include <sstream>
#include <limits>
namespace blue_sky {
using namespace std;
// hidden namespace
namespace {
/*-----------------------------------------------------------------
* helper structure to get dx[i] when dim is given by one number
*----------------------------------------------------------------*/
struct dim_subscript {
dim_subscript(const double dim, const double offset = .0)
: dim_(dim), offset_(offset), sum_(offset)
{}
void reset() { sum_ = offset_; }
double operator[](t_ulong idx) {
return offset_ + dim_ * idx;
}
private:
const double dim_;
const double offset_;
double sum_;
};
} /* eof hidden namespace */
ulong read_cps3_grid(std::ifstream& f, ulong* dims, spv_float& databuf) {
std::string linebuf;
std::istringstream line_s;
// [x_min, x_max, y_min, y_max, z_min, z_max]
t_float bounds[] = {0., 0., 0., 0., 0., 0.};
// increment in X and Y directions
t_float D[] = {0., 0.};
// actually read file
ulong n_points = 0;
bool data_started = false, overflow = false;
ulong i = 0, j = 0;
while(std::getline(f, linebuf)) {
line_s.clear();
// parse header
if(!data_started) {
size_t pos = linebuf.find("FSLIMI");
if(pos != string::npos) {
line_s.str(linebuf.substr(pos + 6));
if(!(line_s >> bounds[0] >> bounds[1] >> bounds[2] >> bounds[3] >> bounds[4] >> bounds[5])) {
BSERR << "Error reading limits from CPS-3 FSLIMI keyword" << bs_end;
return 0;
}
}
pos = linebuf.find("FSNROW");
if(pos != string::npos) {
line_s.str(linebuf.substr(pos + 6));
if(!(line_s >> dims[1] >> dims[0])) {
BSERR << "Error reading dimensions from CPS-3 FSNROW keyword" << bs_end;
return 0;
}
// resize Z data buffer
databuf->resize(dims[0] * dims[1] * 3);
// TODO: enable NaN when GUI part will be fixed to support it
//fill(databuf->begin(), databuf->end(), std::numeric_limits< double >::quiet_NaN());
fill(databuf->begin(), databuf->end(), 1e30);
// data is read from upper left corner, i = 0, j = max
i = 0;
j = dims[1] - 1;
}
pos = linebuf.find("FSXINC");
if(pos != string::npos) {
line_s.str(linebuf.substr(pos + 6));
if(!(line_s >> D[1] >> D[0])) {
BSERR << "Error reading deltas from CPS-3 FSXINC keyword" << bs_end;
return 0;
}
}
// check if we reached actual data
if(linebuf.find("->MSMODL") != string::npos) {
data_started = true;
}
continue;
}
// if we are here, then we're in data section
line_s.str(linebuf);
t_float val;
while(line_s >> val) {
// store x, y, z surface value
const v_float::iterator dest = databuf->begin() + (dims[1] * i + j) * 3;
if(dest > databuf->end() - 3) {
overflow = true;
break;
}
dest[0] = bounds[0] + D[0] * i;
dest[1] = bounds[2] + D[1] * j;
if(val >= bounds[4] && val <= bounds[5])
dest[2] = val;
// step to next surface point
if(--j > dims[1]) {
++i;
j = dims[1] - 1;
}
++n_points;
}
}
return n_points;
}
} /* namespace blue_sky */
| 25.424242 | 97 | 0.578069 |
8cecd67c9170c77a95ca5206dfc6beeb4ff50153 | 46,408 | cpp | C++ | Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp | danielholanda/Tactile-Glove | 837b5868afe1e567299e78b4c9cf7b5c93f126b5 | [
"MIT"
] | 14 | 2016-11-08T19:06:52.000Z | 2022-03-15T13:20:50.000Z | Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp | danielholanda/Tactile-Glove | 837b5868afe1e567299e78b4c9cf7b5c93f126b5 | [
"MIT"
] | null | null | null | Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp | danielholanda/Tactile-Glove | 837b5868afe1e567299e78b4c9cf7b5c93f126b5 | [
"MIT"
] | null | null | null | /*
* MPU6050_Axis_MotionApps20.cpp
*
* Created on: 2016年1月10日
* Author: qq95538
*/
// I2Cdev library collection - MPU6050 I2C device class, 6-axis MotionApps 2.0 implementation
// Based on InvenSense MPU-6050 register map document rev. 2.0, 5/19/2011 (RM-MPU-6000A-00)
// 6/18/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
// ... - ongoing debug release
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg
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 <iostream>
#include <typeinfo>
#include <math.h>
#include <sys/time.h>
#include "helper_3dmath4Edison.hpp"
#include "MPU6050_4Edison.hpp"
/* Source is from the InvenSense MotionApps v2 demo code. Original source is
* unavailable, unless you happen to be amazing as decompiling binary by
* hand (in which case, please contact me, and I'm totally serious).
*
* Also, I'd like to offer many, many thanks to Noah Zerkin for all of the
* DMP reverse-engineering he did to help make this bit of wizardry
* possible.
*/
#define MPU6050_DMP_CODE_SIZE 1929 // dmpMemory[]
#define MPU6050_DMP_CONFIG_SIZE 192 // dmpConfig[]
#define MPU6050_DMP_UPDATES_SIZE 47 // dmpUpdates[]
/* ================================================================================================ *
| Default MotionApps v2.0 42-byte FIFO packet structure: |
| |
| [QUAT W][ ][QUAT X][ ][QUAT Y][ ][QUAT Z][ ][GYRO X][ ][GYRO Y][ ] |
| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
| |
| [GYRO Z][ ][ACC X ][ ][ACC Y ][ ][ACC Z ][ ][ ] |
| 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
* ================================================================================================ */
#define prog_uchar uint8_t
#define PROGMEM
/**
* Instance DMP variables
*/
bool dmpDebug = true;
bool dmpReady = false; // set true if DMP init was successful
uint8_t dmpIntStatus = false; // holds actual interrupt status byte from MPU
uint8_t dmpStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t dmpPacketSize; // expected DMP packet size (default is 42 bytes)
uint16_t dmpFifoCount; // count of all bytes currently in FIFO
uint8_t dmpFifoBuffer[64]; // FIFO storage buffer
// orientation/motion vars
Quaternion dmpQuat; // [w, x, y, z] quaternion container
VectorInt16 dmpAccel; // [x, y, z] accel sensor measurements
VectorInt16 dmpAccelReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 dmpAccelWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat dmpGravity; // [x, y, z] gravity vector
float dmpEuler[3]; // [psi, theta, phi] Euler angle container
float dmpYawPitchRoll[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
//#define OUTPUT_READABLE_QUATERNION
#define OUTPUT_READABLE_EULER
#define OUTPUT_READABLE_YAWPITCHROLL
//#define OUTPUT_READABLE_REALACCEL
#define OUTPUT_READABLE_WORLDACCEL
//#define OUTPUT_TEAPOT
uint8_t dmpTeapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
// this block of memory gets written to the MPU on start-up, and it seems
// to be volatile memory, so it has to be done each time (it only takes ~1
// second though)
const prog_uchar dmpMemory[MPU6050_DMP_CODE_SIZE] PROGMEM = {
// bank 0, 256 bytes
0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00,
0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82,
0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC,
0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4,
0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10,
// bank 1, 256 bytes
0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8,
0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C,
0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C,
0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0,
// bank 2, 256 bytes
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// bank 3, 256 bytes
0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F,
0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2,
0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF,
0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C,
0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1,
0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01,
0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80,
0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C,
0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80,
0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E,
0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9,
0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24,
0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0,
0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86,
0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1,
0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86,
// bank 4, 256 bytes
0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA,
0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C,
0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8,
0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3,
0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84,
0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5,
0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3,
0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1,
0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5,
0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A,
0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8,
0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87,
// bank 5, 256 bytes
0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8,
0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68,
0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D,
0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94,
0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA,
0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56,
0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9,
0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA,
0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A,
0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60,
0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97,
0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04,
0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78,
0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79,
0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68,
0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68,
// bank 6, 256 bytes
0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04,
0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66,
0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31,
0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60,
0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76,
0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56,
0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD,
0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91,
0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8,
0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE,
0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9,
0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD,
0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E,
0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8,
0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89,
0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79,
// bank 7, 138 bytes (remainder)
0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8,
0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA,
0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB,
0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3,
0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3,
0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3,
0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3,
0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC,
0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF
};
// DMP FIFO update rate: 0x09 drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz,
// 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very
// noisy data. DMP output frequency is calculated easily using this equation:
// (200Hz / (1 + value))
// It is important to make sure the host processor can keep up with reading and
// processing the FIFO output at the desired rate. Handling FIFO overflow
// cleanly is also a good idea. thanks to Noah Zerkin for piecing this stuff
// together!
#ifndef DMP_FIFO_RATE
#define DMP_FIFO_RATE 1
#endif
const prog_uchar dmpConfig[MPU6050_DMP_CONFIG_SIZE] PROGMEM = {
// BANK OFFSET LENGTH [DATA]
0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration
0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration
0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration
0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration
0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration
0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration
0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration
0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration
0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01
0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02
0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10
0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11
0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12
0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20
0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21
0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22
0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors
0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion
0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update
0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone
// SPECIAL 0x01 = enable interrupts
0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION
0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt
0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion
0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer
0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro
0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo
0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo
0x02, 0x16, 0x02, 0x00, DMP_FIFO_RATE // D_0_22 inv_set_fifo_rate
};
const prog_uchar dmpUpdates[MPU6050_DMP_UPDATES_SIZE] PROGMEM = {
0x01, 0xB2, 0x02, 0xFF, 0xFF,
0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35,
0x01, 0x6A, 0x02, 0x06, 0x00,
0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00,
0x01, 0x62, 0x02, 0x00, 0x00,
0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00
};
long long timeLastCatch = 0;
int timeAvg = 0;
int timeAvgMax = 30;
int timeCountTarget = 10; // Minimal measurement
int timeCountCatch = 0; // Number of catching data
double timeBalance = 0.9999;
/**
* Return the current time as milliseconds
* @param print
* @return
*/
long long MPU6050::getMilliTime(bool print) {
timeval millitime;
long long mtime, seconds, useconds;
gettimeofday(&millitime, NULL);
seconds = millitime.tv_sec;
useconds = millitime.tv_usec;
mtime = (seconds * 1000) + (useconds / 1000.0) + 0.5;
if(print) printf("Seconds: %lld, Micro: %lld, Milli: %lld\n", seconds, useconds, mtime);
return mtime;
}
/**
* Check if is time to do a new request
* @return
*/
long long MPU6050::timeCheck()
{
long long cur = getMilliTime(false);
int interval = cur - timeLastCatch;
if (interval >= timeAvg)
{
if(dmpDebug) printf("Interval\n");
return cur;
}/*
else if (timeCountCatch < timeCountTarget)
{
printf("Count\n");
return cur;
}*/
else if(dmpDebug) printf("Pass %d >= %d and %d < %d - %lld\n", interval, timeAvg, timeCountCatch, timeCountTarget, cur);
return 0;
}
/**
* Recalculate average time with new time
* @param time
*/
void MPU6050::timeCount(long long time)
{
// Balance use a range of tolerance to avoid fifo overflow and request overflow
timeAvg = ((time - timeLastCatch + timeAvg) / 2) * timeBalance;
if (timeAvg > timeAvgMax) timeAvg = timeAvgMax;
timeLastCatch = time;
timeCountCatch += 1;
}
/**
* Reset average time measurement for interval of request data from MPU unit
*/
void MPU6050::timeReset()
{
timeAvg = 0;
timeCountCatch = 0;
timeLastCatch = getMilliTime(false);
}
/**
* Start the device through address with offset's informed
* @param address
* @param xGyroOffset
* @param yGyroOffset
* @param zGyroOffset
* @return boolean
*/
bool MPU6050::dmpStartDevice(uint8_t address, int xGyroOffset, int yGyroOffset, int zGyroOffset) {
setAddress(address);
initialize();
setXGyroOffset(xGyroOffset);
setYGyroOffset(yGyroOffset);
setZGyroOffset(zGyroOffset);
if (testConnection())
{
if(dmpDebug) printf("Connection OK\n");
// load and configure the DMP
if (dmpInitialize() == 0)
{
if(dmpDebug) printf("DMP initialized\n");
// turn on the DMP, now that it's ready
setDMPEnabled(true);
dmpStatus = getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
dmpReady = true;
// get expected DMP packet size for later comparison
dmpPacketSize = dmpGetFIFOPacketSize();
timeReset();
resetFIFO();
return true;
}
}
return false;
}
/**
* Collect and process data from MPU unit, if this data is available
* @return boolean
*/
bool MPU6050::dmpGetData()
{
long long time = timeCheck();
if(dmpDebug) printf("%lld ", time);
if(dmpReady && time > 0)
{
if(dmpDebug) printf("\n %lld \n", time);
// get current FIFO count
dmpFifoCount = getFIFOCount();
if (dmpFifoCount == 1024) {
// reset so we can continue cleanly
resetFIFO();
timeReset();
if(dmpDebug) printf("FIFO overflow!\n");
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (dmpFifoCount >= 42) {
timeCount(time);
// read a packet from FIFO
getFIFOBytes(dmpFifoBuffer, dmpPacketSize);
// display quaternion values in easy matrix form: w x y z
dmpGetQuaternion(&dmpQuat, dmpFifoBuffer);
if(dmpDebug) printf("quat %7.2f %7.2f %7.2f %7.2f ", dmpQuat.w,dmpQuat.x,dmpQuat.y,dmpQuat.z);
#ifdef OUTPUT_READABLE_EULER
// display Euler angles in degrees
dmpGetEuler(dmpEuler, &dmpQuat);
dmpEuler[0] = dmpEuler[0] * 180/M_PI;
dmpEuler[1] = dmpEuler[1] * 180/M_PI;
dmpEuler[2] = dmpEuler[2] * 180/M_PI;
if(dmpDebug) printf("euler %7.2f %7.2f %7.2f ", dmpEuler[0], dmpEuler[1], dmpEuler[2]);
#endif
#ifdef OUTPUT_READABLE_YAWPITCHROLL
// display Euler angles in degrees
dmpGetGravity(&dmpGravity, &dmpQuat);
dmpGetYawPitchRoll(dmpYawPitchRoll, &dmpQuat, &dmpGravity);
dmpYawPitchRoll[0] = dmpYawPitchRoll[0] * 180/M_PI;
dmpYawPitchRoll[1] = dmpYawPitchRoll[1] * 180/M_PI;
dmpYawPitchRoll[2] = dmpYawPitchRoll[2] * 180/M_PI;
if(dmpDebug) printf("ypr %7.2f %7.2f %7.2f ", dmpYawPitchRoll[0], dmpYawPitchRoll[1], dmpYawPitchRoll[2]);
#endif
#ifdef OUTPUT_READABLE_REALACCEL
// display real acceleration, adjusted to remove gravity
dmpGetAccel(&dmpAccel, dmpFifoBuffer);
dmpGetGravity(&dmpGravity, &dmpQuat);
dmpGetLinearAccel(&dmpAccelReal, &dmpAccel, &dmpGravity);
if(dmpDebug) printf("areal %6d %6d %6d ", dmpAccelReal.x, dmpAccelReal.y, dmpAccelReal.z);
#endif
#ifdef OUTPUT_READABLE_WORLDACCEL
// display initial world-frame acceleration, adjusted to remove gravity
// and rotated based on known orientation from quaternion
dmpGetAccel(&dmpAccel, dmpFifoBuffer);
dmpGetGravity(&dmpGravity, &dmpQuat);
dmpGetLinearAccelInWorld(&dmpAccelWorld, &dmpAccelReal, &dmpQuat);
if(dmpDebug) printf("aworld %6d %6d %6d ", dmpAccelWorld.x, dmpAccelWorld.y, dmpAccelWorld.z);
#endif
#ifdef OUTPUT_TEAPOT
// display quaternion values in InvenSense Teapot demo format:
dmpTeapotPacket[2] = dmpFifoBuffer[0];
dmpTeapotPacket[3] = dmpFifoBuffer[1];
dmpTeapotPacket[4] = dmpFifoBuffer[4];
dmpTeapotPacket[5] = dmpFifoBuffer[5];
dmpTeapotPacket[6] = dmpFifoBuffer[8];
dmpTeapotPacket[7] = dmpFifoBuffer[9];
dmpTeapotPacket[8] = dmpFifoBuffer[12];
dmpTeapotPacket[9] = dmpFifoBuffer[13];
//Serial.write(dmpTeapotPacket, 14);
dmpTeapotPacket[11]++; // packetCount, loops at 0xFF on purpose
#endif
printf("\n");
return true;
}
}
return false;
}
/**
* Quaternion
* @return Quaternion[w, x, y, z]
*/
Quaternion getDmpQuaternion()
{
return dmpQuat;
}
/**
* Accel Sensor Measurements
* @return VectorInt16[x, y, z]
*/
VectorInt16 getDmpAccel()
{
return dmpAccel;
}
/**
* Gravity-free Accel Sensor Measurements
* @return VectorInt16[x, y, z]
*/
VectorInt16 getDmpAccelReal()
{
return dmpAccelReal;
}
/**
* World-frame Accel Sensor Measurements
* @return VectorInt16[x, y, z]
*/
VectorInt16 getDmpAccelWorld()
{
return dmpAccelWorld;
}
/**
* Gravity Vector
* @return VectorFloat[x, y, z]
*/
VectorFloat getDmpGravity()
{
return dmpGravity;
}
/**
* Euler Angle Container
* @return Float[psi, theta, phi]
*/
float* getDmpEuler()
{
return dmpEuler;
}
/**
* Yaw/Pitch/Roll container and gravity vector
* @return Float[yaw, pitch, roll]
*/
float* getDmpYawPitchRoll()
{
return dmpYawPitchRoll;
}
/**
* Initialize DMP inside MPU6050
* @return boolean
*/
uint8_t MPU6050::dmpInitialize() {
//Resetting MPU6050...
reset();
usleep(30000); // wait after reset
//Disabling sleep mode...
setSleepEnabled(false);
// get MPU hardware revision
//Selecting user bank 16...
setMemoryBank(0x10, true, true);
//Selecting memory byte 6...
setMemoryStartAddress(0x06);
//Checking hardware revision...
uint8_t hwRevision __attribute__((__unused__)) = readMemoryByte();
//Revision @ user[16][6] =
//hwRevision, HEX);
//Resetting memory bank selection to 0...
setMemoryBank(0, false, false);
// check OTP bank valid
//Reading OTP bank valid flag...
uint8_t otpValid __attribute__((__unused__)) = getOTPBankValid();
//OTP bank is
//otpValid ? F("valid!") : F("invalid!
// get X/Y/Z gyro offsets
//Reading gyro offset values...
/*
int8_t xgOffset = getXGyroOffset();
int8_t ygOffset = getYGyroOffset();
int8_t zgOffset = getZGyroOffset();
sleep(5);
for(int cnt = 0; cnt < 1000; cnt = cnt + 1)
{
std::cout << "X: " << typeid(xgOffset).name() << "Y: " << typeid(ygOffset).name() << "Z: " << typeid(zgOffset).name() << "\n";
sleep(1);
//xgOffset = (getXGyroOffset() + xgOffset)/2;
//ygOffset = (getYGyroOffset() + ygOffset)/2;
//zgOffset = (getZGyroOffset() + zgOffset)/2;
}
*/
//X gyro offset =
//xgOffset);
//Y gyro offset =
//ygOffset);
//Z gyro offset =
//zgOffset);
// setup weird slave stuff (?)
//Setting slave 0 address to 0x7F...
setSlaveAddress(0, 0x7F);
//Disabling I2C Master mode...
setI2CMasterModeEnabled(false);
//Setting slave 0 address to 0x68 (self)...
setSlaveAddress(0, 0x68);
/*
if (addr == 104)
{
std::cout << "Address: 104";
setSlaveAddress(0, 0x68);
}
else
{
std::cout << "Address: 105";
setSlaveAddress(0, 0x69);
}
* */
//Resetting I2C Master control...
resetI2CMaster();
usleep(20000);
// load DMP code into memory banks
//Writing DMP code to MPU memory banks (
// bytes)
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
printf("Success! DMP code written and verified.\n");
// write DMP configuration
//Writing DMP configuration to MPU memory banks (
// bytes in config def)
if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
printf("Success! DMP configuration written and verified.\n");
//Setting clock source to Z Gyro...
setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
//Setting DMP and FIFO_OFLOW interrupts enabled...
setIntEnabled(0x12);
//Setting sample rate to 200Hz...
setRate(4); // 1khz / (1 + 4) = 200 Hz
//Setting external frame sync to TEMP_OUT_L[0]...
setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);
//Setting DLPF bandwidth to 42Hz...
setDLPFMode(MPU6050_DLPF_BW_42);
//Setting gyro sensitivity to +/- 2000 deg/sec...
setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
//Setting DMP configuration bytes (function unknown)...
setDMPConfig1(0x03);
setDMPConfig2(0x00);
//Clearing OTP Bank flag...
setOTPBankValid(false);
/*
//Setting X/Y/Z gyro offsets to previous values...
setXGyroOffset(xgOffset);
setYGyroOffset(ygOffset);
setZGyroOffset(zgOffset);
//Setting X/Y/Z gyro user offsets to zero...
setXGyroOffsetUser(0);
setYGyroOffsetUser(0);
setZGyroOffsetUser(0);
*/
//Writing final memory update 1/7 (function unknown)...
uint8_t dmpUpdate[16], j;
uint16_t pos = 0;
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//Writing final memory update 2/7 (function unknown)...
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//Resetting FIFO...
resetFIFO();
//Reading FIFO count...
uint8_t fifoCount = getFIFOCount();
uint8_t fifoBuffer[128];
printf("Current FIFO count=%d\n", fifoCount);
//fifoCount);
if (fifoCount > 0)
getFIFOBytes(fifoBuffer, fifoCount);
//Setting motion detection threshold to 2...
setMotionDetectionThreshold(2);
//Setting zero-motion detection threshold to 156...
setZeroMotionDetectionThreshold(156);
//Setting motion detection duration to 80...
setMotionDetectionDuration(80);
//Setting zero-motion detection duration to 0...
setZeroMotionDetectionDuration(0);
//Resetting FIFO...
resetFIFO();
//Enabling FIFO...
setFIFOEnabled(true);
//Enabling DMP...
setDMPEnabled(true);
//Resetting DMP...
resetDMP();
//Writing final memory update 3/7 (function unknown)...
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//Writing final memory update 4/7 (function unknown)...
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//Writing final memory update 5/7 (function unknown)...
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
printf("Waiting for FIFO count > 2...\n");
while ((fifoCount = getFIFOCount()) < 3);
printf("Current FIFO count=%d",fifoCount);
//Reading FIFO data...
getFIFOBytes(fifoBuffer, fifoCount);
//Reading interrupt status...
uint8_t mpuIntStatus __attribute__((__unused__)) = getIntStatus();
//Current interrupt status= mpuIntStatus, HEX
//Reading final memory update 6/7 (function unknown)...
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//Waiting for FIFO count > 2...
while ((fifoCount = getFIFOCount()) < 3);
//Current FIFO count=
//fifoCount);
//Reading FIFO data...
getFIFOBytes(fifoBuffer, fifoCount);
//Reading interrupt status...
mpuIntStatus = getIntStatus();
//Current interrupt status=
//mpuIntStatus, HEX
//Writing final memory update 7/7 (function unknown)...
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
//DMP is good to go! Finally.
//Disabling DMP (you turn it on later)...
setDMPEnabled(false);
//Setting up internal 42-byte (default) DMP packet buffer...
dmpPacketSize = 42;
/*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) {
return 3; // TODO: proper error code for no memory
}*/
//Resetting FIFO and clearing INT status one last time...
resetFIFO();
getIntStatus();
} else {
//ERROR! DMP configuration verification failed.
return 2; // configuration block loading failed
}
} else {
//ERROR! DMP code verification failed.
return 1; // main binary block loading failed
}
return 0; // success
}
bool MPU6050::dmpPacketAvailable() {
return getFIFOCount() >= dmpGetFIFOPacketSize();
}
// uint8_t MPU6050::dmpSetFIFORate(uint8_t fifoRate);
// uint8_t MPU6050::dmpGetFIFORate();
// uint8_t MPU6050::dmpGetSampleStepSizeMS();
// uint8_t MPU6050::dmpGetSampleFrequency();
// int32_t MPU6050::dmpDecodeTemperature(int8_t tempReg);
//uint8_t MPU6050::dmpRegisterFIFORateProcess(inv_obj_func func, int16_t priority);
//uint8_t MPU6050::dmpUnregisterFIFORateProcess(inv_obj_func func);
//uint8_t MPU6050::dmpRunFIFORateProcesses();
// uint8_t MPU6050::dmpSendQuaternion(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGyro(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccelInWorld(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendControlData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendExternalSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGravity(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendPacketNumber(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendQuantizedAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendEIS(uint_fast16_t elements, uint_fast16_t accuracy);
uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[28] << 24) + (packet[29] << 16) + (packet[30] << 8) + packet[31]);
data[1] = ((packet[32] << 24) + (packet[33] << 16) + (packet[34] << 8) + packet[35]);
data[2] = ((packet[36] << 24) + (packet[37] << 16) + (packet[38] << 8) + packet[39]);
return 0;
}
uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[28] << 8) + packet[29];
data[1] = (packet[32] << 8) + packet[33];
data[2] = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
v -> x = (packet[28] << 8) + packet[29];
v -> y = (packet[32] << 8) + packet[33];
v -> z = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 24) + (packet[1] << 16) + (packet[2] << 8) + packet[3]);
data[1] = ((packet[4] << 24) + (packet[5] << 16) + (packet[6] << 8) + packet[7]);
data[2] = ((packet[8] << 24) + (packet[9] << 16) + (packet[10] << 8) + packet[11]);
data[3] = ((packet[12] << 24) + (packet[13] << 16) + (packet[14] << 8) + packet[15]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 8) + packet[1]);
data[1] = ((packet[4] << 8) + packet[5]);
data[2] = ((packet[8] << 8) + packet[9]);
data[3] = ((packet[12] << 8) + packet[13]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
int16_t qI[4];
uint8_t status = dmpGetQuaternion(qI, packet);
if (status == 0) {
q -> w = (float)qI[0] / 16384.0f;
q -> x = (float)qI[1] / 16384.0f;
q -> y = (float)qI[2] / 16384.0f;
q -> z = (float)qI[3] / 16384.0f;
return 0;
}
return status; // int16 return value, indicates error if this line is reached
}
// uint8_t MPU6050::dmpGet6AxisQuaternion(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetRelativeQuaternion(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[16] << 24) + (packet[17] << 16) + (packet[18] << 8) + packet[19]);
data[1] = ((packet[20] << 24) + (packet[21] << 16) + (packet[22] << 8) + packet[23]);
data[2] = ((packet[24] << 24) + (packet[25] << 16) + (packet[26] << 8) + packet[27]);
return 0;
}
uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[16] << 8) + packet[17];
data[1] = (packet[20] << 8) + packet[21];
data[2] = (packet[24] << 8) + packet[25];
return 0;
}
// uint8_t MPU6050::dmpSetLinearAccelFilterCoefficient(float coef);
// uint8_t MPU6050::dmpGetLinearAccel(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
// get rid of the gravity component (+1g = +4096 in standard DMP FIFO packet)
v -> x = vRaw -> x - gravity -> x*4096;
v -> y = vRaw -> y - gravity -> y*4096;
v -> z = vRaw -> z - gravity -> z*4096;
return 0;
}
// uint8_t MPU6050::dmpGetLinearAccelInWorld(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
// rotate measured 3D acceleration vector into original state
// frame of reference based on orientation quaternion
memcpy(v, vReal, sizeof(VectorInt16));
v -> rotate(q);
return 0;
}
// uint8_t MPU6050::dmpGetGyroAndAccelSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGyroSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetControlData(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetTemperature(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGravity(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) {
v -> x = 2 * (q -> x*q -> z - q -> w*q -> y);
v -> y = 2 * (q -> w*q -> x + q -> y*q -> z);
v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z;
return 0;
}
// uint8_t MPU6050::dmpGetUnquantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetExternalSensorData(long *data, int size, const uint8_t* packet);
// uint8_t MPU6050::dmpGetEIS(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) {
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // psi
data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y); // theta
data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1); // phi
return 0;
}
uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
// yaw: (about Z axis)
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
// pitch: (nose up/down, about Y axis)
data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
// roll: (tilt left/right, about X axis)
data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
return 0;
}
// uint8_t MPU6050::dmpGetAccelFloat(float *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuaternionFloat(float *data, const uint8_t* packet);
uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) {
/*for (uint8_t k = 0; k < dmpPacketSize; k++) {
if (dmpData[k] < 0x10) Serial.print("0");
Serial.print(dmpData[k], HEX);
Serial.print(" ");
}
Serial.print("\n");*/
//Serial.println((uint16_t)dmpPacketBuffer);
return 0;
}
uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) {
uint8_t status;
uint8_t buf[dmpPacketSize];
for (uint8_t i = 0; i < numPackets; i++) {
// read packet from FIFO
getFIFOBytes(buf, dmpPacketSize);
// process packet
if ((status = dmpProcessFIFOPacket(buf)) > 0) return status;
// increment external process count variable, if supplied
if (processed != 0) (*processed)++;
}
return 0;
}
// uint8_t MPU6050::dmpSetFIFOProcessedCallback(void (*func) (void));
// uint8_t MPU6050::dmpInitFIFOParam();
// uint8_t MPU6050::dmpCloseFIFO();
// uint8_t MPU6050::dmpSetGyroDataSource(uint_fast8_t source);
// uint8_t MPU6050::dmpDecodeQuantizedAccel();
// uint32_t MPU6050::dmpGetGyroSumOfSquare();
// uint32_t MPU6050::dmpGetAccelSumOfSquare();
// void MPU6050::dmpOverrideQuaternion(long *q);
uint16_t MPU6050::dmpGetFIFOPacketSize() {
return dmpPacketSize;
}
| 45.453477 | 134 | 0.618471 |
8cf02ef30bf559dd11e9df2d3d58fb0a749eac70 | 6,428 | hpp | C++ | State/code/StateMachine.hpp | HONGYU-LEE/DesignPatterns | b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918 | [
"MIT"
] | null | null | null | State/code/StateMachine.hpp | HONGYU-LEE/DesignPatterns | b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918 | [
"MIT"
] | null | null | null | State/code/StateMachine.hpp | HONGYU-LEE/DesignPatterns | b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918 | [
"MIT"
] | null | null | null | #pragma once
#include"State.hpp"
class MarioStateMachine
{
public:
MarioStateMachine()
: _score(0)
{
//提前缓存各种状态
_normalMario = new NormalMario(this);
_superMario = new SuperMario(this);
_fireMario = new FireMario(this);
_deadMario = new DeadMario(this);
_state = _normalMario;
}
~MarioStateMachine()
{
delete _normalMario, _superMario, _fireMario, _deadMario;
}
void getRevive(); //复活
void getMushroom(); //获得蘑菇
void getSunFlower(); //获得太阳花
void getHurt(); //受到伤害
int getScore() const; //获取当前分数
MarioState* getState() const; //获取当前状态
void setScore(int score); //获取当前分数
void setState(MarioState* state); //获取当前状态
MarioState* getNormalMario(); //获取缓存的状态
MarioState* getSuperMario();
MarioState* getFireMario();
MarioState* getDeadMario();
private:
int _score; //当前分数
MarioState* _state; //当前状态
MarioState* _superMario; //缓存所有的状态
MarioState* _normalMario;
MarioState* _fireMario;
MarioState* _deadMario;
private:
class NormalMario : public MarioState
{
public:
NormalMario(MarioStateMachine* stateMachine)
: _stateMachine(stateMachine)
{}
void getRevive() override
{
std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl;
}
void getMushroom() override
{
_stateMachine->setScore(_stateMachine->getScore() + 100);
_stateMachine->setState(_stateMachine->getSuperMario());
std::cout << "获得蘑菇,由普通马里奥变为超级马里奥,增加一百分" << std::endl;
}
void getSunFlower() override
{
_stateMachine->setScore(_stateMachine->getScore() + 200);
_stateMachine->setState(_stateMachine->getFireMario());
std::cout << "获得太阳花,由普通马里奥变为火焰马里奥,增加两百分" << std::endl;
}
void getHurt() override
{
_stateMachine->setScore(0);
_stateMachine->setState(_stateMachine->getDeadMario());
std::cout << "受到伤害,马里奥死亡,分数清空" << std::endl;
}
std::string getStateName() override
{
return "普通马里奥";
}
private:
MarioStateMachine* _stateMachine; //状态机
};
class SuperMario : public MarioState
{
public:
SuperMario(MarioStateMachine* stateMachine)
: _stateMachine(stateMachine)
{}
void getRevive() override
{
std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl;
}
void getMushroom() override
{
_stateMachine->setScore(_stateMachine->getScore() + 100);
std::cout << "获得蘑菇,增加一百分" << std::endl;
}
void getSunFlower() override
{
_stateMachine->setScore(_stateMachine->getScore() + 200);
_stateMachine->setState(_stateMachine->getFireMario());
std::cout << "获得太阳花,由超级马里奥变为火焰马里奥,增加两百分" << std::endl;
}
void getHurt() override
{
_stateMachine->setScore(_stateMachine->getScore() - 100);
_stateMachine->setState(_stateMachine->getNormalMario());
std::cout << "受到伤害,由超级马里奥变为普通马里奥,扣一百分" << std::endl;
}
std::string getStateName() override
{
return "超级马里奥";
}
private:
MarioStateMachine* _stateMachine; //状态机
};
class FireMario : public MarioState
{
public:
FireMario(MarioStateMachine* stateMachine)
: _stateMachine(stateMachine)
{}
void getRevive() override
{
std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl;
}
void getMushroom() override
{
_stateMachine->setScore(_stateMachine->getScore() + 100);
std::cout << "获得蘑菇,增加一百分" << std::endl;
}
void getSunFlower() override
{
_stateMachine->setScore(_stateMachine->getScore() + 200);
std::cout << "获得太阳花,增加两百分" << std::endl;
}
void getHurt() override
{
_stateMachine->setScore(_stateMachine->getScore() - 100);
_stateMachine->setState(_stateMachine->getSuperMario());
std::cout << "受到伤害,由火焰马里奥变为超级马里奥,扣一百分" << std::endl;
}
std::string getStateName() override
{
return "火焰马里奥";
}
private:
MarioStateMachine* _stateMachine; //状态机
};
class DeadMario : public MarioState
{
public:
DeadMario(MarioStateMachine* stateMachine)
: _stateMachine(stateMachine)
{}
void getRevive() override
{
_stateMachine->setScore(0);
_stateMachine->setState(_stateMachine->getNormalMario());
std::cout << "复活马里奥,会到普通状态,分数重新计算" << std::endl;
}
void getMushroom() override
{
std::cout << "死亡后不能获取道具,不存在该逻辑" << std::endl;
}
void getSunFlower() override
{
std::cout << "死亡后不能获取道具,不存在该逻辑" << std::endl;
}
void getHurt() override
{
std::cout << "死亡后不能受到伤害,不存在该逻辑" << std::endl;
}
std::string getStateName() override
{
return "死亡";
}
private:
MarioStateMachine* _stateMachine; //状态机
};
};
void MarioStateMachine::getRevive()
{
_state->getRevive();
}
void MarioStateMachine::getMushroom()
{
_state->getMushroom();
}
void MarioStateMachine::getSunFlower()
{
_state->getSunFlower();
}
void MarioStateMachine::getHurt()
{
_state->getHurt();
}
int MarioStateMachine::getScore() const
{
return _score;
}
MarioState* MarioStateMachine::getState() const
{
return _state;
}
void MarioStateMachine::setScore(int score)
{
_score = score;
}
void MarioStateMachine::setState(MarioState* state)
{
_state = state;
}
MarioState* MarioStateMachine::getNormalMario()
{
return _normalMario;
}
MarioState* MarioStateMachine::getSuperMario()
{
return _superMario;
}
MarioState* MarioStateMachine::getFireMario()
{
return _fireMario;
}
MarioState* MarioStateMachine::getDeadMario()
{
return _deadMario;
}
| 23.807407 | 71 | 0.558027 |
8cf1cca6709f496c90b1ffcf3cbaa568ef803876 | 3,128 | cpp | C++ | 301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | 1 | 2018-10-02T22:44:52.000Z | 2018-10-02T22:44:52.000Z | 301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | 301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp | ysmiles/leetcode-cpp | e7e6ef11224c7383071ed8efbe2feac313824a71 | [
"BSD-3-Clause"
] | null | null | null | // Say you have an array for which the ith element is the price of a given stock
// on day i.
// Design an algorithm to find the maximum profit. You may complete as many
// transactions as you like (ie, buy one and sell one share of the stock
// multiple times) with the following restrictions:
// You may not engage in multiple transactions at the same time (ie, you
// must sell the stock before you buy again). After you sell your stock, you
// cannot buy stock on next day. (ie, cooldown 1 day)
// Example:
// prices = [1, 2, 3, 0, 2]
// maxProfit = 3
// transactions = [buy, sell, cooldown, buy, sell]
// correct thinking direction
// finite state machine
// ref:
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking)
// 3 states (indicate net money we have, start at 0):
// s0: can stay at s0, or buy and go to s1
// s1: can stay at s1, or sell and go to s2 (cooldown state, cannot buy)
// s2: cannot stay at s2, after 1 day cooldown, go to s1
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() < 2)
return 0;
int n = prices.size();
vector<int> s0(n), s1(n), s2(n);
s0[0] = 0;
s1[0] = -prices[0];
s2[0] = INT_MIN; // impossible to sell at first day
for (int i = 1; i < n; ++i) {
s0[i] = max(s0[i - 1], s2[i - 1]);
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]);
s2[i] = s1[i - 1] + prices[i];
}
return max(s0[n - 1], s2[n - 1]);
}
};
// further optimized to O(1) space
class Solution {
public:
int maxProfit(vector<int> &prices) {
int s0 = 0, s1 = INT_MIN, s2 = 0;
for (auto &&p : prices) {
int pre_s2 = s2;
s2 = s1 + p;
s1 = max(s1, s0 - p);
s0 = max(s0, pre_s2);
}
return max(s0, s2);
}
};
// my own analysis, seems to be wrong way
// analysis
// vector input, return a int
// conditions
// => dp
// let dp[n] represents the max profit after the end of day n
// not day n price is price[n-1]
// if day n-1 must be selling transaction
// i.e. dp[n-1] != dp[n-2]
// dp[n] = max(dp[n-1], dp[n-1] + price[n-1] - price[n-2])
// if day n-1 can be a non-selling transaction
// if day n-1 can be cooldown window
// i.e. dp[n-1] == dp[n-2]
// dp[n] = dp[n-1]
// if day n-1 is not cooldown (n-2 is not selling)
// i.e. dp[n-2] == dp[n-3]
// dp[n] = dp[n-2] + max(0, price[n-1] - price[n-2])
// beginning cases:
// dp[0] = 0, dp[1] = 0, dp[2] = max(0, price[1] - price[0])
//
// code:
// int n = prices.size();
// vector<int> dp(n + 1); // all 0s
// dp[2] = max(0, prices[1] - prices[0]);
// for (int i = 3; i <= n; ++i) {
// if (dp[i - 1] != dp[i - 2])
// dp[i] = dp[i - 1] + max(0, prices[i - 1] - prices[i - 2]);
// else {
// // n-1 is cooldown
// dp[i] = dp[i - 1];
// if (dp[i - 2] == dp[i - 3])
// dp[i] += max(0, prices[i - 1] - prices[i - 2]);
// }
// }
// return dp[n]; | 31.59596 | 141 | 0.538683 |
8cf76e3a2f55f04ec658adbbce9fe0ea6b6b9d73 | 1,412 | cpp | C++ | resources.cpp | 5cript/minide | 0964ae51512eb7ba1ee44d828d27e5b73da32245 | [
"MIT"
] | null | null | null | resources.cpp | 5cript/minide | 0964ae51512eb7ba1ee44d828d27e5b73da32245 | [
"MIT"
] | 1 | 2018-01-26T00:06:19.000Z | 2018-01-26T00:06:54.000Z | resources.cpp | 5cript/minide | 0964ae51512eb7ba1ee44d828d27e5b73da32245 | [
"MIT"
] | null | null | null | #include "resources.hpp"
#include <boost/dll/runtime_symbol_info.hpp>
#include <fstream>
#include <sstream>
namespace MinIDE
{
//#####################################################################################################################
path getResourcesDirectory()
{
auto program_path = boost::dll::program_location();
program_path = program_path.parent_path();
// for dev:
auto fname = program_path.filename().string();
if (fname == "Debug" || fname == "Release")
program_path = program_path.parent_path();
auto res = program_path.parent_path() / "resources";
return res;
}
//---------------------------------------------------------------------------------------------------------------------
path resource(path const& file)
{
return getResourcesDirectory() / file;
}
//---------------------------------------------------------------------------------------------------------------------
std::string loadResource(path const& file)
{
auto res = resource(file);
std::ifstream reader{res, std::ios_base::binary};
std::stringstream buffer;
buffer << reader.rdbuf();
return buffer.str();
}
//#####################################################################################################################
}
| 33.619048 | 120 | 0.386686 |
8cf8c764d68f0576d49cf9bbb33bd30b7e6a0e51 | 1,927 | cc | C++ | fibonacci_sum/fibonacci_sum.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | fibonacci_sum/fibonacci_sum.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | fibonacci_sum/fibonacci_sum.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | 2 | 2020-12-02T13:04:29.000Z | 2020-12-07T00:17:01.000Z | /**
* Universidad de La Laguna
* Escuela Superior de Ingeniería y Tecnología
* Grado en Ingeniería Informática
* Informática Básica
*
* @author F. de Sande
* @date 7.nov.2020
* @brief Cada nuevo término de la serie de Fibonacci se genera sumando los dos anteriores.
* Comenzando con 0 y 1, los primeros 10 términos serán: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
* Desarrolle en C++ un programa que calcule la suma de todos los términos de valor par
* de la serie que sean menores que 1000.
* @see https://docs.google.com/document/d/1-3hTIVf8tPrbn9u0vs0Cm2IGyX1XBgv8hReVU0KOSUQ/edit?usp=sharing
* @see stoi http://www.cplusplus.com/reference/string/stoi/
* An Object Oriented Version of the program:
* @see https://stackoverflow.com/questions/21360694/sum-of-even-fibonacci-numbers-under-1000
*
*/
#include <iostream>
#include <cstdlib> // exit
#include "fibonacci_sum.h"
// Usage: the program requires a single numeric parameter
void Usage(int argc, char *argv[]) {
if (argc != 2) {
std::cout << argv[0] << ": Falta un número natural como parámetro" << std::endl;
std::cout << "Pruebe " << argv[0] << " --help para más información" << std::endl;
exit(EXIT_SUCCESS);
}
std::string parameter{argv[1]};
if (parameter == "--help") {
std::cout << kHelpText << std::endl;
exit(EXIT_SUCCESS);
}
}
size_t fibonacci_sum(const size_t kLimit) {
size_t second_to_last{0}, // Second to last term
last{1}, // Last term generated
new_term; // New term of the serie
size_t long sum{0}; // Accumulated sum of the terms
do {
new_term = last + second_to_last;
if (new_term % 2 == 0) {
sum += new_term;
}
// Uncomment for debug: print each new term
// std::cout << "Term: " << new_term << std::endl;
second_to_last = last;
last = new_term;
} while (new_term < kLimit);
return sum;
}
| 33.807018 | 104 | 0.646082 |
8cf90e7707c1f12d35fcd1633760e24ff715f571 | 3,984 | cpp | C++ | src/GameClient/MapView/ResourcesBar.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T13:44:49.000Z | 2021-01-19T10:39:48.000Z | src/GameClient/MapView/ResourcesBar.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | null | null | null | src/GameClient/MapView/ResourcesBar.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T16:03:20.000Z | 2020-02-15T09:14:30.000Z | // ResourcesBar.cpp: implementation of the CResourcesBar class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ResourcesBar.h"
#include "..\GameClientGlobal.h"
#include "..\DataObjects\CMap.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define RESOURCEBAR_ITEM_WIDTH 55
#define RESOURCEBAR_LINE_HEIGHT 18
#define RESOURCEBAR_TEXT_COLOR RGB32(255, 255, 255)
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
IMPLEMENT_DYNAMIC(CResourcesBar, CWindow)
BEGIN_OBSERVER_MAP(CResourcesBar, CWindow)
case -1:
break;
END_OBSERVER_MAP(CResourcesBar, CWindow)
CResourcesBar::CResourcesBar()
{
m_pFont = NULL;
memset(m_aResources, 0, sizeof(int) * RESOURCE_COUNT);
}
CResourcesBar::~CResourcesBar()
{
ASSERT(m_pFont == NULL);
}
#ifdef _DEBUG
void CResourcesBar::AssertValid() const
{
CWindow::AssertValid();
ASSERT(m_pFont != NULL);
}
void CResourcesBar::Dump(CDumpContext &dc) const
{
CWindow::Dump(dc);
}
#endif
void CResourcesBar::Create(CWindow *pParent, CFontObject *pFont)
{
ASSERT(pParent != NULL);
ASSERT(pFont != NULL);
m_pFont = pFont;
// First determine count of used resources
DWORD dwCount = 0, i;
for(i = 0; i < RESOURCE_COUNT; i++){
if(!g_pMap->GetResource(i)->GetName().IsEmpty()){
dwCount ++;
}
}
// Compute the positioning
CRect rcParent;
rcParent = pParent->GetWindowPosition();
int nStartPosition, nRowCount = 1;
while((int)((dwCount / nRowCount) * RESOURCEBAR_ITEM_WIDTH) > rcParent.Width())
nRowCount++;
nStartPosition = rcParent.Width() - ((dwCount + (nRowCount / 2)) / nRowCount) * RESOURCEBAR_ITEM_WIDTH;
int nPos = nStartPosition, nRow = 0;
for(i = 0; i < RESOURCE_COUNT; i++){
if(g_pMap->GetResource(i)->GetName().IsEmpty()){
m_aPositions[i].x = -1;
}
else{
m_aPositions[i].x = nPos - nStartPosition;
m_aPositions[i].y = nRow * RESOURCEBAR_LINE_HEIGHT;
nPos += RESOURCEBAR_ITEM_WIDTH;
if(nPos >= rcParent.Width()){
nPos = nStartPosition;
nRow++;
}
}
}
// Comptute the position of the window
CRect rcWnd;
rcWnd.left = nStartPosition;
rcWnd.right = rcParent.Width();
rcWnd.top = 0;
rcWnd.bottom = nRowCount * RESOURCEBAR_LINE_HEIGHT;
m_bTransparent = TRUE;
CWindow::Create(&rcWnd, pParent);
}
void CResourcesBar::Delete()
{
CWindow::Delete();
m_pFont = NULL;
}
void CResourcesBar::SetResource(DWORD dwIndex, int nNewValue)
{
ASSERT(dwIndex < RESOURCE_COUNT);
m_aResources[dwIndex] = nNewValue;
CRect rc;
rc.left = m_aPositions[dwIndex].x;
if(rc.left == -1) return;
rc.top = m_aPositions[dwIndex].y;
rc.right = rc.left + RESOURCEBAR_ITEM_WIDTH;
rc.bottom = rc.top + RESOURCEBAR_LINE_HEIGHT;
UpdateRect(&rc);
}
void CResourcesBar::Draw(CDDrawSurface *pSurface, CRect *pRect)
{
DWORD i;
CString str;
int nVal;
for(i = 0; i < RESOURCE_COUNT; i++){
if(m_aPositions[i].x == -1) continue;
pSurface->Paste(m_aPositions[i], g_pMap->GetResource(i)->GetIcon());
nVal = m_aResources[i];
if(abs(nVal) > 99999){ // nVal / 1000 k
if(abs(nVal) > 9999999){ // nVal / 1000000 M
if(abs(nVal) > 9999999999){ // nVal / 1000000000 G
str.Format("%dG", nVal / 1000000000);
}
else{
str.Format("%dM", nVal / 1000000);
}
}
else{
str.Format("%dk", nVal / 1000);
}
}
else{
str.Format("%d", nVal);
}
m_pFont->PaintText(m_aPositions[i].x + 17, m_aPositions[i].y + (RESOURCEBAR_LINE_HEIGHT - m_pFont->GetCharSize('A').cy) / 2,
str, pSurface, RESOURCEBAR_TEXT_COLOR);
}
}
// Returns the window from givven screen point
// works only on subtree of windows
CWindow * CResourcesBar::WindowFromPoint(CPoint &pt)
{
return NULL;
}
| 23.298246 | 128 | 0.626255 |
8cf9baba50c162a61a817c1d88bfc08028f7fe46 | 417 | cpp | C++ | BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | //
// Created by rahul on 21/7/19.
//
#include <iostream>
#include <cmath>
#define ACCURACY 0.001
int main()
{
int n;
float sum,n1,m;
n=1;sum=0;
for(int i=1;;i++) {
n1 = float(1) / n;
m = pow(n1, i);
std::cout<<m<<'\n';
sum +=m;
std::cout<<"sum"<<sum<<'\n';
if (m <= ACCURACY)
break;
n++;
}
std::cout<<sum<<"\n";
return 0;
} | 16.68 | 36 | 0.434053 |
8cfcd4b41e0a05d8a7421905aaa8d3713f9c4f17 | 1,151 | hpp | C++ | Project/RSA_Input.hpp | elie-wanko/RSA-in-Optical-Networks | a23e4525b865826aca8e2d5b6ce55d7b3fc20528 | [
"MIT"
] | null | null | null | Project/RSA_Input.hpp | elie-wanko/RSA-in-Optical-Networks | a23e4525b865826aca8e2d5b6ce55d7b3fc20528 | [
"MIT"
] | null | null | null | Project/RSA_Input.hpp | elie-wanko/RSA-in-Optical-Networks | a23e4525b865826aca8e2d5b6ce55d7b3fc20528 | [
"MIT"
] | null | null | null | #ifndef RSA_INPUT_HPP
#define RSA_INPUT_HPP
#include <vector>
#include <string>
//Forward declaration
class Demand;
class Vertex;
class Edge;
class RSA_Input {
private:
std::string file_Outputplacement_;
std::vector<Demand *> requests_;
std::vector<Vertex *> nodes_;
std::vector<Edge *> edges_;
public:
//Constructors
RSA_Input() {}
//Getters
const std::vector<Demand *> &getRequests() const { return requests_; }
const std::vector<Vertex *> &getNodes() const { return nodes_; }
const std::vector<Edge *> &getEdges() const { return edges_; }
std::vector<Demand *> &getRequests() { return requests_; }
std::vector<Vertex *> &getNodes() { return nodes_; }
std::vector<Edge *> &getEdges() { return edges_; }
//Functions
void data_load_demand(const std::string filename);
void data_load_edge(const std::string filename);
void data_load_node(const std::string filename);
//Shows
void showRequests() const;
//Destructors
~RSA_Input() {}
};
#endif // RSA_INPUT_HPP | 22.134615 | 78 | 0.612511 |
8cfce37bdb0ee0541268171e2dad940d44557d5c | 2,508 | cpp | C++ | frameworks-ext/av/media/libstagefright/wifi-display-mediatek/sink/LinearRegression.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | frameworks-ext/av/media/libstagefright/wifi-display-mediatek/sink/LinearRegression.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | frameworks-ext/av/media/libstagefright/wifi-display-mediatek/sink/LinearRegression.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | /*
* Copyright 2012, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "LinearRegression"
#include <utils/Log.h>
#include "LinearRegression.h"
#include <math.h>
#include <string.h>
namespace android {
LinearRegression::LinearRegression(size_t historySize)
: mHistorySize(historySize),
mCount(0),
mHistory(new Point[mHistorySize]),
mSumX(0.0),
mSumY(0.0) {
}
LinearRegression::~LinearRegression() {
delete[] mHistory;
mHistory = NULL;
}
void LinearRegression::addPoint(float x, float y) {
if (mCount == mHistorySize) {
const Point &oldest = mHistory[0];
mSumX -= oldest.mX;
mSumY -= oldest.mY;
memmove(&mHistory[0], &mHistory[1], (mHistorySize - 1) * sizeof(Point));
--mCount;
}
Point *newest = &mHistory[mCount++];
newest->mX = x;
newest->mY = y;
mSumX += x;
mSumY += y;
}
bool LinearRegression::approxLine(float *n1, float *n2, float *b) const {
static const float kEpsilon = 1.0E-4;
if (mCount < 2) {
return false;
}
float sumX2 = 0.0f;
float sumY2 = 0.0f;
float sumXY = 0.0f;
float meanX = mSumX / (float)mCount;
float meanY = mSumY / (float)mCount;
for (size_t i = 0; i < mCount; ++i) {
const Point &p = mHistory[i];
float x = p.mX - meanX;
float y = p.mY - meanY;
sumX2 += x * x;
sumY2 += y * y;
sumXY += x * y;
}
float T = sumX2 + sumY2;
float D = sumX2 * sumY2 - sumXY * sumXY;
float root = sqrt(T * T * 0.25 - D);
float L1 = T * 0.5 - root;
if (fabs(sumXY) > kEpsilon) {
*n1 = 1.0;
*n2 = (2.0 * L1 - sumX2) / sumXY;
float mag = sqrt((*n1) * (*n1) + (*n2) * (*n2));
*n1 /= mag;
*n2 /= mag;
} else {
*n1 = 0.0;
*n2 = 1.0;
}
*b = (*n1) * meanX + (*n2) * meanY;
return true;
}
} // namespace android
| 22.594595 | 80 | 0.583333 |
ea0058484aadc9a76c9fa0d2bd09d9540088fd77 | 2,254 | cpp | C++ | cores/n64/GLideN64/src/GLideNHQ/txWidestringWrapper.cpp | wulfebw/retro | dad4b509e99e729e39a2f27e9ee4120e3b607f58 | [
"MIT-0",
"MIT"
] | 7 | 2020-07-20T12:11:35.000Z | 2021-12-23T02:09:19.000Z | cores/n64/GLideN64/src/GLideNHQ/txWidestringWrapper.cpp | wulfebw/retro | dad4b509e99e729e39a2f27e9ee4120e3b607f58 | [
"MIT-0",
"MIT"
] | null | null | null | cores/n64/GLideN64/src/GLideNHQ/txWidestringWrapper.cpp | wulfebw/retro | dad4b509e99e729e39a2f27e9ee4120e3b607f58 | [
"MIT-0",
"MIT"
] | 1 | 2020-08-29T16:36:48.000Z | 2020-08-29T16:36:48.000Z | #ifdef OS_ANDROID
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include "txWidestringWrapper.h"
tx_wstring::tx_wstring(const wchar_t * wstr) : _wstring(wstr)
{
wcstombs(cbuf, wstr, BUF_SIZE);
_astring.assign(cbuf);
}
tx_wstring::tx_wstring(const tx_wstring & other) : _wstring(other.c_str())
{
wcstombs(cbuf, other.c_str(), BUF_SIZE);
_astring.assign(cbuf);
}
void tx_wstring::assign(const wchar_t * wstr)
{
_wstring.assign(wstr);
wcstombs(cbuf, wstr, BUF_SIZE);
_astring.assign(cbuf);
}
void tx_wstring::assign(const tx_wstring & wstr)
{
_wstring.assign(wstr.c_str());
wcstombs(cbuf, wstr.c_str(), BUF_SIZE);
_astring.assign(cbuf);
}
void tx_wstring::append(const tx_wstring & wstr)
{
wcstombs(cbuf, wstr.c_str(), BUF_SIZE);
_astring.append(cbuf);
mbstowcs(wbuf, _astring.c_str(), BUF_SIZE);
_wstring.assign(wbuf);
}
tx_wstring & tx_wstring::operator=(const tx_wstring & other)
{
assign(other);
return *this;
}
tx_wstring & tx_wstring::operator+=(const tx_wstring & other)
{
append(other);
return *this;
}
tx_wstring & tx_wstring::operator+=(const wchar_t * wstr)
{
append(wstr);
return *this;
}
tx_wstring tx_wstring::operator+(const tx_wstring & wstr) const
{
tx_wstring ans(_wstring.c_str());
ans.append(wstr);
return ans;
}
tx_wstring tx_wstring::operator+(const wchar_t * wstr) const
{
tx_wstring ans(_wstring.c_str());
ans.append(wstr);
return ans;
}
const wchar_t * tx_wstring::c_str() const
{
return _wstring.c_str();
}
bool tx_wstring::empty() const
{
return _astring.empty();
}
int tx_wstring::compare(const wchar_t * wstr)
{
wcstombs(cbuf, wstr, BUF_SIZE);
return _astring.compare(cbuf);
}
dummyWString::dummyWString(const char * _str)
{
wchar_t buf[BUF_SIZE];
mbstowcs(buf, _str, BUF_SIZE);
_wstr.assign(buf);
}
int tx_swprintf(wchar_t* ws, size_t len, const wchar_t* format, ...)
{
char cbuf[BUF_SIZE];
char fmt[BUF_SIZE];
wcstombs(fmt, format, BUF_SIZE);
va_list ap;
va_start(ap, format);
int res = vsprintf(cbuf, fmt, ap);
va_end(ap);
mbstowcs(ws, cbuf, len);
return res;
}
bool wccmp(const wchar_t* w1, const wchar_t* w2)
{
char cbuf1[16];
wcstombs(cbuf1, w1, 16);
char cbuf2[16];
wcstombs(cbuf2, w2, 16);
return cbuf1[0] == cbuf2[0];
}
#endif // OS_ANDROID
| 18.783333 | 74 | 0.712067 |
ea017d4ceeb555ab858a441fe7c08b6fab504293 | 6,173 | cpp | C++ | WaterEveryDay/third_party/GdiOle/GDIImageOLE.cpp | achellies/WaterEveryDay | 376b8a22b288a2b275861363a731a5054c43bf0a | [
"MIT"
] | 5 | 2016-03-11T08:49:04.000Z | 2019-07-19T02:18:02.000Z | WaterEveryDay/third_party/GdiOle/GDIImageOLE.cpp | achellies/WaterEveryDay | 376b8a22b288a2b275861363a731a5054c43bf0a | [
"MIT"
] | null | null | null | WaterEveryDay/third_party/GdiOle/GDIImageOLE.cpp | achellies/WaterEveryDay | 376b8a22b288a2b275861363a731a5054c43bf0a | [
"MIT"
] | 4 | 2015-07-01T03:34:51.000Z | 2019-12-25T18:21:38.000Z | // GDIImage.cpp : Implementation of CGDIImageOle
#include "stdafx.h"
#include "GDIImageOle.h"
// CGDIImageOle
//using namespace Gdiplus;
const IID IID_IGDIImageDeleteNotify = {0xa991582, 0x6f1a, 0x4150, 0xbd, 0xcd, 0x25, 0x3b, 0xb7, 0x8c, 0xf9, 0xf};
CGDIImageOle::CGDIImageOle():
m_pImage(NULL),
m_FrameCount(0),
m_hCallbackWnd(NULL),
m_dwUpdateMsg(WM_USER),
m_bIsDeleting(false),
m_bRegistered(false)
{
//m_bWindowOnly = TRUE;
//CalcExtent(m_sizeExtent);
}
HRESULT CGDIImageOle::FinalConstruct()
{
//InitializeCriticalSection(&m_csAdviseSink);
return S_OK;
}
void CGDIImageOle::FinalRelease()
{
if (m_pImage)
{
if (m_bRegistered)
{
m_pImage->UnregisterCallback(OnFrameChanged, (LPARAM)this);
m_bRegistered = false;
}
m_pImage->Release();
}
//DeleteCriticalSection(&m_csAdviseSink);
}
enum DefinedTestRectValue {TR_NOOVERLAP, TR_INTERSECT, TR_CONTAIN};
static DefinedTestRectValue TestRectInRect(RECT *pRect1, RECT *pRect2)
{
RECT rcIntersect;
DefinedTestRectValue ret = TR_NOOVERLAP;
if (IntersectRect(&rcIntersect, pRect1, pRect2))
{
if (EqualRect(&rcIntersect, pRect2))
ret = TR_CONTAIN;
else
ret = TR_INTERSECT;
}
return ret;
}
HRESULT CGDIImageOle::FireViewChangeEx(BOOL bEraseBackground)
{
HRESULT Res = S_OK;
if (m_bInPlaceActive)
{
// Active
if (m_hWndCD != NULL)
::InvalidateRect(m_hWndCD, NULL, bEraseBackground); // Window based
else if (m_bWndLess && m_spInPlaceSite != NULL)
m_spInPlaceSite->InvalidateRect(NULL, bEraseBackground); // Windowless
}
else // Inactive
{
/*
if (CComCompositeControl<CGDIImageOle>::m_hWnd)
::InvalidateRect(CComCompositeControl<CGDIImageOle>::m_hWnd, NULL, FALSE);
else if (m_hCallbackWnd)
{
::PostMessage(m_hCallbackWnd, m_dwUpdateMsg, 0, (LPARAM)this);
}
else
{
SendOnViewChange(DVASPECT_CONTENT);
}
*/
if (m_spClientSite && !m_bIsDeleting)
{
/*
IOleClientSite *pClientSite = m_spClientSite;
pClientSite->AddRef();
::PostMessage(m_hCallbackWnd, m_dwUpdateMsg, 0, (LPARAM)pClientSite);
*/
CComPtr<IOleInPlaceSite> spInPlaceSite;
m_spClientSite->QueryInterface(__uuidof(IOleInPlaceSite), (void **)&spInPlaceSite);
HWND hwndParent = NULL;
if (spInPlaceSite && spInPlaceSite->GetWindow(&hwndParent) == S_OK && hwndParent && ::IsWindowVisible(hwndParent))
{
OLEINPLACEFRAMEINFO frameInfo;
IOleInPlaceFrame *pInPlaceFrame = NULL;
IOleInPlaceUIWindow *pInPlaceUIWindow = NULL;
RECT rcPos, rcClip;
frameInfo.cb = sizeof(OLEINPLACEFRAMEINFO);
if (spInPlaceSite->GetWindowContext(&pInPlaceFrame,
&pInPlaceUIWindow, &rcPos, &rcClip, &frameInfo) == S_OK)
{
if (pInPlaceFrame)
pInPlaceFrame->Release();
if (pInPlaceUIWindow)
pInPlaceUIWindow->Release();
DefinedTestRectValue TestRect = TestRectInRect(&rcClip, &rcPos);
if (TestRect == TR_CONTAIN)
{
// Object fully visible
SendOnViewChange(DVASPECT_CONTENT);
}
else if (TestRect == TR_INTERSECT)
{
// Object partially visible
// [!] brain-ripper
// this implementation flickers smiles
::InvalidateRect(hwndParent, &rcPos, FALSE);
/*
// [!] brain-ripper
// this implementation doesn't respect selection color
HDC hDC = ::GetDC(hwndParent);
m_pImage->Draw(hDC,
rcPos.left,
rcPos.top,
min(m_dwW, DWORD(rcPos.right - rcPos.left)),
min(m_dwH, DWORD(rcPos.bottom - rcPos.top)), 0, 0, m_hBackDC, 0, 0,
min(m_dwW, DWORD(rcPos.right - rcPos.left)),
min(m_dwH, DWORD(rcPos.bottom - rcPos.top)));
::ReleaseDC(hwndParent, hDC);
//*/
}
else
{
// Object hidden
if (m_bRegistered)
{
// Returning S_FALSE on callback makes
// pImage to unregister callback function.
// This mechanism used because it is not allowed Register/Unregister
// callback functions from inside callback functions
Res = S_FALSE;
m_bRegistered = false;
}
}
}
}
}
}
return Res;
}
STDMETHODIMP CGDIImageOle::put_SetImage(CGDIImage *pImage, LPCWSTR pStrData, HWND hCallbackWnd, DWORD dwUpdateMsg)
{
if (m_pImage)
return S_FALSE;
m_pImage = pImage;
if (!m_pImage)
return S_FALSE;
m_pImage->AddRef();
m_dwW = m_pImage->GetWidth();
m_dwH = m_pImage->GetHeight();
SIZEL szPix = {m_dwW, m_dwH};
SIZEL szHi;
AtlPixelToHiMetric(&szPix, &szHi);
m_sizeExtent.cx = szHi.cx;
m_sizeExtent.cy = szHi.cy;
m_hCallbackWnd = hCallbackWnd;
m_dwUpdateMsg = dwUpdateMsg;
m_pImage->RegisterCallback(OnFrameChanged, (LPARAM)this);
m_bRegistered = true;
SetUnicodeTextData(pStrData);
return S_OK;
}
bool CGDIImageOle::OnFrameChanged(CGDIImage *pImage, LPARAM lParam)
{
CGDIImageOle *pGDIImage = (CGDIImageOle *)lParam;
return pGDIImage->FireViewChangeEx(FALSE) == S_OK;
}
LRESULT CGDIImageOle::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
return S_OK;
}
HRESULT CGDIImageOle::IDataObject_GetData(FORMATETC* pFormatEtc, STGMEDIUM* pStgMedium)
{
ATLASSERT(pFormatEtc);
ATLASSERT(pStgMedium);
int iIndex = _FindFormat(pFormatEtc);
if( iIndex < 0 ) return DV_E_FORMATETC;
return _AddRefStgMedium(pStgMedium, &m_aObjects[iIndex].StgMed, &m_aObjects[iIndex].FmtEtc);
}
HRESULT CGDIImageOle::SetGlobalData(CLIPFORMAT cf, LPCVOID pData, DWORD dwSize)
{
FORMATETC fmtetc = { cf, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
STGMEDIUM stgmed = { TYMED_HGLOBAL, { 0 }, 0 };
stgmed.hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T) dwSize);
if( stgmed.hGlobal == NULL ) return E_OUTOFMEMORY;
memcpy(GlobalLock(stgmed.hGlobal), pData, (size_t) dwSize);
GlobalUnlock(stgmed.hGlobal);
return SetData(&fmtetc, &stgmed, TRUE);
}
HRESULT CGDIImageOle::SetUnicodeTextData(LPCWSTR pstrData)
{
return SetGlobalData(CF_UNICODETEXT, pstrData, (::lstrlenW(pstrData) + 1) * sizeof(WCHAR));
}
| 26.493562 | 118 | 0.672607 |
ea0208315cc3df4de2ecf683063501a8fc659c8f | 6,987 | hpp | C++ | MsgWnd.hpp | chrisoldwood/WCL | 608a83f9e41f4c1d2a7ac6991abbcf264d5924e0 | [
"MIT"
] | 5 | 2017-10-02T04:10:35.000Z | 2021-07-26T04:45:35.000Z | MsgWnd.hpp | chrisoldwood/WCL | 608a83f9e41f4c1d2a7ac6991abbcf264d5924e0 | [
"MIT"
] | null | null | null | MsgWnd.hpp | chrisoldwood/WCL | 608a83f9e41f4c1d2a7ac6991abbcf264d5924e0 | [
"MIT"
] | null | null | null | /******************************************************************************
** (C) Chris Oldwood
**
** MODULE: MSGWND.HPP
** COMPONENT: Windows C++ Library.
** DESCRIPTION: The CMsgWnd class declaration.
**
*******************************************************************************
*/
// Check for previous inclusion
#ifndef MSGWND_HPP
#define MSGWND_HPP
#if _MSC_VER > 1000
#pragma once
#endif
#include "Wnd.hpp"
// Forward declarations.
class CPoint;
class CDC;
/******************************************************************************
**
** This is a Wnd derived class that provides a base class for all message
** based windows. It provides the default handlers for all messages common to
** all windows.
**
*******************************************************************************
*/
class CMsgWnd : public CWnd /*, private NotCopyable*/
{
public:
//
// Constructors/Destructor.
//
CMsgWnd();
//
// Scroll bar methods.
//
int HorzScrollPos(int iPos, bool bRepaint = true);
int VertScrollPos(int iPos, bool bRepaint = true);
int HorzScrollPos();
int VertScrollPos();
void HorzScrollRange(int iMin, int iMax, bool bRepaint = true);
void VertScrollRange(int iMin, int iMax, bool bRepaint = true);
protected:
/////////////////////////////////////////////////////////////////
// Structure to define an entry in the control message table.
/////////////////////////////////////////////////////////////////
// Pointer to generic message handler.
typedef LRESULT (CMsgWnd::*PFNMSGHANDLER)(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
// Pointer to WM_COMMAND style control message handler.
typedef void (CMsgWnd::*PFNCMDMSGHANDLER)();
// Pointer to WM_NOTIFY style control message handler.
typedef LRESULT (CMsgWnd::*PFNNFYMSGHANDLER)(NMHDR& rMsgHdr);
struct CTRLMSG
{
uint m_iMsgType; // WM_COMMAND or WM_NOTIFY.
uint m_iCtrlID; // ID of control.
uint m_iMsgID; // Event message ID.
PFNMSGHANDLER m_pfnMsgHandler; // Message handler method.
};
//
// Members.
//
CTRLMSG* m_pCtrlMsgTable;
//
// General message handlers.
//
virtual LRESULT WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
virtual LRESULT DefaultWndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam) = 0;
//
// Message processors.
//
virtual void OnCreate(const CRect& rcClient);
virtual void OnActivate(bool bActivating);
virtual void OnEraseBackground(CDC& rDC);
virtual void OnPaint(CDC& rDC);
virtual void OnResize(WCL::ResizeFlags iFlag, const CSize& NewSize);
virtual void OnTimer(WCL::TimerID iTimerID);
virtual void OnShow(bool bShowing);
virtual void OnDestroy();
virtual void OnNCDestroy();
virtual void OnHorizScroll(WCL::ScrollbarFlags iCode, uint iPos);
virtual void OnVertScroll(WCL::ScrollbarFlags iCode, uint iPos);
virtual void OnCmdMsg(uint iID);
virtual void OnCtrlMsg(uint iID, uint iMsg, HWND hControl);
virtual LRESULT OnCtrlMsg(NMHDR& rMsgHdr);
virtual void OnReflectedCtrlMsg(uint iMsg);
virtual void OnReflectedCtrlMsg(NMHDR& rMsgHdr);
virtual void OnMeasureItem(uint iID, uint iItem, uint& iWidth, uint& iHeight);
virtual void OnDrawItem(uint iID, uint iAction, uint iState, CDC& rDC, uint iItem, const CRect& rcItem);
virtual void OnSetCursor(HWND hWnd, uint nHitCode, uint nMouseMsg);
virtual void OnCtlColour(uint nCtlClrMsg, HDC hDC, HWND hCtlWnd);
virtual HBRUSH OnReflectedCtlClr(uint nCtlClrMsg, HDC hDC);
virtual void OnHelp(HELPINFO& oInfo);
virtual void OnUserMsg(uint nMsg, WPARAM wParam, LPARAM lParam);
virtual void OnAppMsg(uint nMsg, WPARAM wParam, LPARAM lParam);
virtual void OnRegisteredMsg(uint nMsg, WPARAM wParam, LPARAM lParam);
virtual void OnHitTest(const CPoint& ptCursor);
//
// Access to window data.
//
WNDPROC WindowProc(WNDPROC lpfnWndProc);
//
// Access to message result members.
//
void MsgHandled(BOOL bHandled);
void MsgResult (LRESULT lResult);
//! Set the result for the message.
void SetMsgResult(BOOL bHandled, LRESULT lResult);
BOOL* MsgHandledBuffer(BOOL* pbBuffer);
LRESULT* MsgResultBuffer (LRESULT* plBuffer);
private:
//
// Members.
//
BOOL* m_pbMsgHandled; // Was message handled?
LRESULT* m_plMsgResult; // Message result code.
// NotCopyable.
CMsgWnd(const CMsgWnd&);
CMsgWnd& operator=(const CMsgWnd&);
};
/******************************************************************************
**
** Macros used to ease the definition of the control message table.
**
*******************************************************************************
*/
#define DEFINE_CTRLMSG_TABLE static CTRLMSG CtrlMsgs[] = {
#define CMD_CTRLMSG(id, msgid, fn) { (WM_COMMAND), (id), (msgid), (PFNMSGHANDLER) (fn) },
#define NFY_CTRLMSG(id, msgid, fn) { (WM_NOTIFY), (id), (msgid), (PFNMSGHANDLER) (fn) },
#define END_CTRLMSG_TABLE { 0, 0, 0, (PFNMSGHANDLER) (NULL) } }; \
m_pCtrlMsgTable = CtrlMsgs;
/******************************************************************************
**
** Implementation of inline functions.
**
*******************************************************************************
*/
inline int CMsgWnd::HorzScrollPos(int iPos, bool bRepaint)
{
return ::SetScrollPos(m_hWnd, SB_HORZ, iPos, bRepaint);
}
inline int CMsgWnd::VertScrollPos(int iPos, bool bRepaint)
{
return ::SetScrollPos(m_hWnd, SB_VERT, iPos, bRepaint);
}
inline int CMsgWnd::HorzScrollPos()
{
return ::GetScrollPos(m_hWnd, SB_HORZ);
}
inline int CMsgWnd::VertScrollPos()
{
return ::GetScrollPos(m_hWnd, SB_VERT);
}
inline void CMsgWnd::HorzScrollRange(int iMin, int iMax, bool bRepaint)
{
::SetScrollRange(m_hWnd, SB_HORZ, iMin, iMax, bRepaint);
}
inline void CMsgWnd::VertScrollRange(int iMin, int iMax, bool bRepaint)
{
::SetScrollRange(m_hWnd, SB_VERT, iMin, iMax, bRepaint);
}
inline WNDPROC CMsgWnd::WindowProc(WNDPROC lpfnWndProc)
{
return reinterpret_cast<WNDPROC>(::SetWindowLongPtr(m_hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(lpfnWndProc)));
}
inline void CMsgWnd::MsgHandled(BOOL bHandled)
{
ASSERT(m_pbMsgHandled != NULL);
*m_pbMsgHandled = bHandled;
}
inline void CMsgWnd::MsgResult(LRESULT lResult)
{
ASSERT(m_plMsgResult != NULL);
*m_plMsgResult = lResult;
}
////////////////////////////////////////////////////////////////////////////////
//! Set the result for the message. This method replaces the need to make two
//! calls - one to MsgHandled() and one to MsgResult() - with a single call.
inline void CMsgWnd::SetMsgResult(BOOL bHandled, LRESULT lResult)
{
ASSERT(m_pbMsgHandled != NULL);
ASSERT(m_plMsgResult != NULL);
*m_pbMsgHandled = bHandled;
*m_plMsgResult = lResult;
}
inline BOOL* CMsgWnd::MsgHandledBuffer(BOOL* pbBuffer)
{
BOOL* pbOldBuffer = m_pbMsgHandled;
m_pbMsgHandled = pbBuffer;
return pbOldBuffer;
}
inline LRESULT* CMsgWnd::MsgResultBuffer (LRESULT* plBuffer)
{
LRESULT* plOldBuffer = m_plMsgResult;
m_plMsgResult = plBuffer;
return plOldBuffer;
}
#endif //MSGWND_HPP
| 28.173387 | 117 | 0.642765 |
ea038c5120b075ddc7600e85808666bc4aaee631 | 552 | cc | C++ | Semestre_5/IN505/TD/C++/td1/tdexo5/point.cc | abedeltawil/Licence3_Informatique | 892b7b2cd74778539b534b57026bf8b4a3453c4f | [
"MIT"
] | 1 | 2019-11-28T22:41:57.000Z | 2019-11-28T22:41:57.000Z | Semestre_5/IN505/TD/C++/td1/tdexo5/point.cc | abedeltawil/Licence3_Informatique | 892b7b2cd74778539b534b57026bf8b4a3453c4f | [
"MIT"
] | null | null | null | Semestre_5/IN505/TD/C++/td1/tdexo5/point.cc | abedeltawil/Licence3_Informatique | 892b7b2cd74778539b534b57026bf8b4a3453c4f | [
"MIT"
] | 7 | 2019-10-23T16:11:58.000Z | 2019-12-14T12:27:27.000Z | #include "point.h"
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
Point::Point(){
this->x=0;
this->y=0;
}
Point::Point(double x,double y){
this->x=x;
this->y=y;
}
Point::Point(Point& p){
this->x=p.getX();
this->y=p.getY();
}
double Point::getX(){
return this->x;
}
double Point::getY(){
return this->y;
}
void Point::affiche(){
cout<<"POINT ("<<this->x<<","<<this->y<<")"<<endl;
}
void Point::clone(const Point& p){
this->x=p.x;
this->y=p.y;
}
Point::~Point(){
cout << "appel au destructeur Point"<<endl;
}
| 15.333333 | 51 | 0.608696 |
ea03b84ece42767e529e38791be6276b07e3c621 | 1,544 | cpp | C++ | src/gradient_descent.cpp | dsherma7/LinearRegression | ce0827bfe7b98cfaf1d6df3c736694ae7ea3a8c3 | [
"MIT"
] | null | null | null | src/gradient_descent.cpp | dsherma7/LinearRegression | ce0827bfe7b98cfaf1d6df3c736694ae7ea3a8c3 | [
"MIT"
] | null | null | null | src/gradient_descent.cpp | dsherma7/LinearRegression | ce0827bfe7b98cfaf1d6df3c736694ae7ea3a8c3 | [
"MIT"
] | null | null | null | #include <Eigen/Dense>
double mse(Eigen::MatrixXd X, Eigen::VectorXd W, Eigen::VectorXd Y);
Eigen::VectorXd _derivative(Eigen::MatrixXd X, Eigen::VectorXd W,
Eigen::VectorXd Y) {
/*
Computes the jth derivative given W, X, Y
by following gradient descent where
D_j J(W,X) = (Y - X * W) * X_j
*/
return -1 * X.transpose() * (Y - X * W);
}
Eigen::VectorXd _gradient_descent_step(Eigen::MatrixXd X, Eigen::VectorXd W,
Eigen::VectorXd Y, double alpha) {
/*
Runs gradient descent for each row in the dataset X
*/
Eigen::VectorXd W_temp = W;
for (int j = 0; j < X.rows(); j++) {
W_temp -= alpha * _derivative(X, W, Y);
}
return W_temp;
}
Eigen::VectorXd gradient_descent(Eigen::MatrixXd X, Eigen::MatrixXd Y,
int *iter, bool *converged,
int max_iterations, double threshold,
double learning_rate) {
Eigen::VectorXd W;
/*
Starting from a random set of weights W, use
gradient descent to determine the optimal W. Stop
when either the max iterations (not converged)
or the error threshold (converged) is reached.
*/
*converged = true;
W = Eigen::MatrixXd::Random(X.cols(), 1);
for (*iter = 0; *iter < max_iterations; *iter = *iter + 1) {
W = _gradient_descent_step(X, W, Y, learning_rate);
double error = mse(X, W, Y);
if (error < threshold) {
*converged = true;
break;
}
}
return W;
} | 29.132075 | 76 | 0.579663 |
ea06bb35c1378bea013384c842221ae36d28d4c3 | 1,121 | cpp | C++ | src/dng_engine/XMLHelper.cpp | szczypiorofix/dungeon_engine | dd1db1c22a73eabd9ea18d44a133d71427957180 | [
"MIT"
] | null | null | null | src/dng_engine/XMLHelper.cpp | szczypiorofix/dungeon_engine | dd1db1c22a73eabd9ea18d44a133d71427957180 | [
"MIT"
] | null | null | null | src/dng_engine/XMLHelper.cpp | szczypiorofix/dungeon_engine | dd1db1c22a73eabd9ea18d44a133d71427957180 | [
"MIT"
] | null | null | null | /*
* Dungeon Engine
* Copyright (C) 2020 szczypiorofix <szczypiorofix@o2.pl>
*/
#include "XMLHelper.h"
int XMLHelper::xmlCharToInt(const xmlChar* a) {
int c = 0, sign = 0, offset = 0, n = 0;
if (a[0] == '-') {
sign = -1;
}
if (sign == -1) {
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
short XMLHelper::xmlCharToShort(const xmlChar* a) {
short c = 0, sign = 0, offset = 0, n = 0;
if (a[0] == '-') {
sign = -1;
}
if (sign == -1) {
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
int XMLHelper::readPropInt(xmlNodePtr node, const xmlChar* prop) {
xmlChar* c = xmlGetProp(node, prop);
int s = 0;
if (c != NULL) {
s = xmlCharToInt(c);
xmlFree(c);
}
return s;
}
short XMLHelper::readPropShort(xmlNodePtr node, const xmlChar* prop) {
xmlChar* c = xmlGetProp(node, prop);
short s = 0;
if (c != NULL) {
s = xmlCharToShort(c);
xmlFree(c);
}
return s;
}
| 15.356164 | 70 | 0.522748 |
ea09432aabad0fc4950466ce982930d98fb37c09 | 5,518 | cpp | C++ | HedgeLib/src/io/hl_stream.cpp | Radfordhound/HedgeLib | e59f875bb7feba37bc5a373a50ae5af8874cd1e2 | [
"BSD-2-Clause"
] | 56 | 2017-02-14T13:19:52.000Z | 2022-03-26T03:59:07.000Z | HedgeLib/src/io/hl_stream.cpp | Radfordhound/HedgeLib | e59f875bb7feba37bc5a373a50ae5af8874cd1e2 | [
"BSD-2-Clause"
] | 66 | 2017-04-22T01:02:04.000Z | 2021-08-18T00:41:04.000Z | HedgeLib/src/io/hl_stream.cpp | Radfordhound/HedgeLib | e59f875bb7feba37bc5a373a50ae5af8874cd1e2 | [
"BSD-2-Clause"
] | 30 | 2017-02-16T09:07:31.000Z | 2022-01-20T23:48:22.000Z | #include "hedgelib/io/hl_stream.h"
#include <memory>
namespace hl
{
stream::~stream() {}
void stream::read_all(std::size_t size, void* buf)
{
const std::size_t readByteCount = read(size, buf);
if (readByteCount != size)
{
// TODO: Throw a better error?
HL_ERROR(error_type::unknown);
}
}
void stream::write_all(std::size_t size, const void* buf)
{
const std::size_t writtenByteCount = write(size, buf);
if (writtenByteCount != size)
{
// TODO: Throw a better error?
HL_ERROR(error_type::unknown);
}
}
static const u8 in_stream_nulls_static_buffer[1024] = { 0 };
void stream::write_nulls(std::size_t amount)
{
if (amount > sizeof(in_stream_nulls_static_buffer))
{
// Allocate a buffer large enough to hold all of the nulls we want to write.
std::unique_ptr<u8[]> nulls(new u8[amount]());
// Write the nulls to the stream.
write_arr(amount, nulls.get());
}
else
{
// Write the given amount of nulls to the stream using our static nulls buffer.
write_arr(amount, in_stream_nulls_static_buffer);
}
}
void stream::write_off32(std::size_t basePos, std::size_t offVal,
bool doSwap, off_table& offTable)
{
// Compute offset.
u32 off = static_cast<u32>(offVal - basePos);
// Swap offset if necessary.
if (doSwap) endian_swap(off);
// Add offset position to offset table.
offTable.push_back(tell());
// Write offset to stream.
write_obj(off);
}
void stream::write_off64(std::size_t basePos, std::size_t offVal,
bool doSwap, off_table& offTable)
{
// Compute offset.
u64 off = static_cast<u64>(offVal - basePos);
// Swap offset if necessary.
if (doSwap) endian_swap(off);
// Add offset position to offset table.
offTable.push_back(tell());
// Write offset to stream.
write_obj(off);
}
void stream::fix_off32(std::size_t basePos, std::size_t offPos,
bool doSwap, off_table& offTable)
{
// Get end of stream position.
const std::size_t endPos = tell();
// Jump to the given offset position.
jump_to(offPos);
// Fix the offset.
write_off32(basePos, endPos, doSwap, offTable);
// Jump back to end of stream.
jump_to(endPos);
}
void stream::fix_off64(std::size_t basePos, std::size_t offPos,
bool doSwap, off_table& offTable)
{
// Get end of stream position.
const std::size_t endPos = tell();
// Jump to the given offset position.
jump_to(offPos);
// Fix the offset.
write_off64(basePos, endPos, doSwap, offTable);
// Jump back to end of stream.
jump_to(endPos);
}
bool stream::read_str(std::size_t bufSize, char* buf)
{
constexpr std::size_t tmpBufSize = 20;
char tmpBuf[tmpBufSize];
// Return early if bufSize == 0
if (!bufSize) return true;
// Read string into buffer.
while (true)
{
const std::size_t readByteCount = read(tmpBufSize, tmpBuf);
const std::size_t safeWriteCount = std::min(readByteCount, bufSize);
// Append a null terminator and return failure
// if we've reached the end of the stream.
if (readByteCount == 0)
{
*(buf++) = '\0';
return false;
}
// Otherwise, append all of the bytes we just read into the temporary buffer.
for (std::size_t i = 0; i < safeWriteCount; ++i)
{
*(buf++) = tmpBuf[i];
// Jump to end of string and return success if we read a null terminator.
if (tmpBuf[i] == '\0')
{
jump_behind(static_cast<long>(readByteCount - (i + 1)));
return true;
}
}
// Decrease writable buffer size.
bufSize -= safeWriteCount;
// Raise an error if we've exceeded the buffer size.
if (!bufSize)
{
HL_ERROR(error_type::out_of_range);
}
}
}
std::string stream::read_str()
{
constexpr std::size_t tmpBufSize = 20;
std::string str;
char tmpBuf[tmpBufSize];
while (true)
{
const std::size_t readByteCount = read(tmpBufSize, tmpBuf);
// Return if we've reached the end of the stream.
if (readByteCount == 0) return str;
// Otherwise, append all of the bytes we just read into the temporary buffer.
for (std::size_t i = 0; i < readByteCount; ++i)
{
// Jump to end of string and return if we read a null terminator.
if (tmpBuf[i] == '\0')
{
jump_behind(static_cast<long>(readByteCount - (i + 1)));
return str;
}
// Append characters.
str += tmpBuf[i];
}
}
}
void stream::align(std::size_t stride)
{
std::size_t pos;
// If stride is < 2, we don't need to align.
if (stride-- < 2) return;
/* Get the current stream position. */
pos = tell();
// Compute the closest position in the stream that's aligned
// by the given stride, and jump to that position.
jump_to(((pos + stride) & ~stride));
}
void stream::pad(std::size_t stride)
{
std::size_t pos;
// If stride is < 2, we don't need to pad.
if (stride-- < 2) return;
// Get the current stream position.
pos = tell();
// Compute the amount of nulls we need to write to align the
// stream with the given stride, and write that many nulls.
write_nulls(((pos + stride) & ~stride) - pos);
}
} // hl
| 25.546296 | 87 | 0.600942 |
ea0dfab3accb98ecb414c3727797d1580fc51380 | 1,529 | cpp | C++ | source/MaterialXTest/MaterialXFormat/XmlExport.cpp | jerrans/MaterialX | 8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6 | [
"BSD-3-Clause"
] | 101 | 2017-08-08T12:08:01.000Z | 2022-03-17T06:37:58.000Z | source/MaterialXTest/MaterialXFormat/XmlExport.cpp | jerrans/MaterialX | 8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6 | [
"BSD-3-Clause"
] | 1,002 | 2018-01-09T10:33:07.000Z | 2022-03-31T18:35:04.000Z | source/MaterialXTest/MaterialXFormat/XmlExport.cpp | jerrans/MaterialX | 8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6 | [
"BSD-3-Clause"
] | 24 | 2018-01-05T20:16:36.000Z | 2022-02-03T15:40:14.000Z | //
// TM & (c) 2021 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXTest/Catch/catch.hpp>
#include <MaterialXFormat/XmlExport.h>
namespace mx = MaterialX;
TEST_CASE("File Path Predicate", "[xmlexport]")
{
mx::FileSearchPath searchPath("libraries/stdlib");
mx::DocumentPtr doc = mx::createDocument();
mx::readFromXmlFile(doc, "resources/Materials/TestSuite/stdlib/export/export.mtlx", searchPath);
mx::XmlExportOptions exportOptions;
exportOptions.flattenFilenames = true;
exportOptions.resolvedTexturePath = mx::FileSearchPath(mx::FilePath::getCurrentPath() /
"resources" /
"Materials" /
"TestSuite" /
"stdlib" /
"export" );
mx::FileSearchPath textureSearchPath("resources");
exportOptions.skipFlattening = [textureSearchPath](const mx::FilePath& filePath) -> bool
{
return textureSearchPath.find(filePath) != filePath;
};
std::stringstream ss;
mx::exportToXmlStream(doc, ss, &exportOptions);
mx::NodePtr node = doc->getNode("image_color3");
mx::NodePtr node2 = doc->getNode("image_color3_2");
REQUIRE(node);
REQUIRE(node2);
mx::InputPtr input = node->getInput("file");
mx::InputPtr input2 = node2->getInput("file");
REQUIRE(input->getValueString() == "Images/grid.png");
REQUIRE(mx::FileSearchPath(input2->getValueString()).asString() == exportOptions.resolvedTexturePath.find("black_image.png").asString());
}
| 36.404762 | 141 | 0.69261 |
ea0f1967721cd8d30cf9086331dd8fd119eb2d3d | 394 | cpp | C++ | solved/0-b/arrange-the-numbers/gen.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/0-b/arrange-the-numbers/gen.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/0-b/arrange-the-numbers/gen.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <cstdio>
#include <cstdlib>
#include <ctime>
#if 0
#define MAXT 1000
#define MAXN 1000
#endif
#if 1
#define MAXT 20
#define MAXN 1000
#endif
int T;
void gen()
{
int N = rand() % MAXN + 1;
int M = rand() % N + 1;
int K = rand() % M + 1;
printf("%d %d %d\n", N, M, K);
--T;
}
int main()
{
srand(time(NULL));
T = MAXT;
printf("%d\n", T);
while (T) gen();
return 0;
}
| 9.85 | 31 | 0.550761 |
ea157f15576755de1efd6ebc866056f8a9983480 | 111,373 | cpp | C++ | Code/Projects/Rosa/src/Components/wbcomprosaplayer.cpp | dphrygian/zeta | 2b32760558cf2b20c626cf46fcf2a382924988fe | [
"Zlib",
"Unlicense"
] | 6 | 2022-01-22T02:18:07.000Z | 2022-02-14T09:30:53.000Z | Code/Projects/Rosa/src/Components/wbcomprosaplayer.cpp | dphrygian/zeta | 2b32760558cf2b20c626cf46fcf2a382924988fe | [
"Zlib",
"Unlicense"
] | null | null | null | Code/Projects/Rosa/src/Components/wbcomprosaplayer.cpp | dphrygian/zeta | 2b32760558cf2b20c626cf46fcf2a382924988fe | [
"Zlib",
"Unlicense"
] | null | null | null | #include "core.h"
#include "wbcomprosaplayer.h"
#include "keyboard.h"
#include "rosaworld.h"
#include "rosaframework.h"
#include "wbeventmanager.h"
#include "wbcomprosatransform.h"
#include "wbcomprosacollision.h"
#include "wbcomprosacamera.h"
#include "wbcomprosafootsteps.h"
#include "wbcomprosahealth.h"
#include "wbcomprosainventory.h"
#include "wbcomprosaweapon.h"
#include "wbcomprosafrobber.h"
#include "wbcomprosafrobbable.h"
#include "wbcomprosamesh.h"
#include "Components/wbcompstatmod.h"
#include "Components/wbcomplabel.h"
#include "configmanager.h"
#include "idatastream.h"
#include "ray.h"
#include "collisioninfo.h"
#include "wbscene.h"
#include "inputsystem.h"
#include "configmanager.h"
#include "mathcore.h"
#include "rosagame.h"
#include "rosasaveload.h"
#include "reversehash.h"
#include "matrix.h"
#include "irenderer.h"
#include "Common/uimanagercommon.h"
#include "noise.h"
#include "rosadifficulty.h"
#include "rosacampaign.h"
#if BUILD_DEV
#if BUILD_WINDOWS
#include "console.h"
#endif
#include "wbcomprosainventory.h"
#include "wbcomprosarope.h"
#include "wbcomprosavisible.h"
#include "wbcomprosawallet.h"
#include "wbcomprosakeyring.h"
#include "wbcomprosalinkedentities.h"
#include "wbcomponentarrays.h"
#include "wbcomprosafaction.h"
#include "fontmanager.h"
#endif
#define CAMERA_RELATIVE_CLIMBING 1
#define CAMERA_RELATIVE_CLIMBING_BIAS 1
WBCompRosaPlayer::WBCompRosaPlayer()
: m_DeferMusic( false )
, m_InitialMusicTrackBits( 0 )
, m_RollingAutosaveDelay( 0.0f )
, m_RetryAutosaveDelay( 0.0f )
, m_AutosaveSuppRefsSerialized( 0 )
, m_AutosaveSuppRefsTransient( 0 )
, m_UnlandedForceFootstepWindow( 0.0f )
, m_UnlandedJumpWindow( 0.0f )
, m_UnlandedLeanWindow( 0.0f )
, m_LandAcceleration( 0.0f )
, m_AirAcceleration( 0.0f )
, m_TurnSpeed( 0.0f )
, m_JumpHeight( 0.0f )
, m_BackpedalScalar( 0.0f )
, m_UncrouchOnSprint( false )
, m_IsCrouched( false )
, m_IsUncrouching( false )
, m_IsForceCrouched( false )
, m_StandExtentsZ( 0.0f )
, m_CrouchExtentsZ( 0.0f )
, m_StandViewOffsetZ( 0.0f )
, m_CrouchViewOffsetZ( 0.0f )
, m_CrouchViewInterpTime( 0.0f )
, m_ViewOffsetZInterpolator()
, m_PowerSlideRollInterpolator()
, m_StepUpZInterpolator()
, m_ViewBobOffsetInterpolator()
, m_ViewBobAngleOffsetInterpolator()
, m_ViewSwayOffsetInterpolator()
, m_ViewSwayAngleOffsetInterpolator()
, m_ViewHandsAcceleration()
, m_ViewHandsVelocity()
, m_ViewHandsRotationalAcceleration()
, m_ViewHandsRotationalVelocity()
, m_KickSpringK( 0.0f )
, m_KickDamperC( 0.0f )
, m_KickVelocity()
, m_KickPosition()
, m_ViewHandsSpringK( 0.0f )
, m_ViewHandsDamperC( 0.0f )
, m_PushToSprint( false )
, m_IsSprinting( false )
, m_IsSprintingWithMovement( false )
, m_SprintStartTime( 0.0f )
, m_SprintFOVScale( 0.0f )
, m_SprintFOVTime( 0.0f )
, m_DoubleJumpHeight( 0.0f )
, m_HasDoubleJumped( false )
, m_PowerJumpRatio( 0.0f )
, m_IsPowerSliding( false )
, m_PowerSlideDuration( 0.0f )
, m_PowerSlideEndTime( 0.0f )
, m_PowerSlideY()
, m_PowerSlideInputContext()
, m_PowerSlideReqVelocitySq( 0.0f )
, m_PowerSlideRoll( 0.0f )
, m_PowerSlideRollInterpTime( 0.0f )
, m_IsDragging( false )
, m_DragInputContext()
, m_DragDropOffset()
, m_DragDropOrientation()
, m_DragDropSpawnImpulse( 0.0f )
, m_DragDropSpawnImpulseZ( 0.0f )
, m_DraggedEntity()
, m_ClimbRefs( 0 )
, m_IsClimbing( false )
, m_ClimbInputContext()
, m_ClimbOffImpulse( 0.0f )
, m_ClimbFacingBiasAngle( 0.0f )
, m_ClimbFacingBiasScale( 0.0f )
, m_IsMantling( false )
, m_MantleInputContext()
, m_MantleVelocity( 0.0f )
, m_MantleVector()
, m_MantleDestination()
, m_CanMantle( false )
, m_AutoAimEnabled( false )
, m_AutoAimMaxTurn( 0.0f )
, m_SprintFOVEnabled( false )
, m_CurrentFOV()
, m_CurrentFGFOV()
, m_IsDisablingPause( false )
, m_HasSetSpawnPoint( false )
, m_SpawnLocation()
, m_SpawnOrientation()
, m_IsFlying( false )
, m_MaxViewBobOffset()
, m_MaxViewBobAngleOffset()
, m_UnlandedViewBobWindow( 0.0f )
, m_ViewBobAngleExponent( 0.0f )
, m_ViewBobInterpolateTime( 0.0f )
, m_MaxViewSwayOffset()
, m_MaxViewSwayAngleOffset()
, m_ViewSwayInterpolateTime( 0.0f )
, m_ViewSwayNoiseOctaves( 0 )
, m_ViewSwayNoiseScalars()
, m_ViewSwayNoiseAngleScalars()
#if BUILD_DEV
, m_DEVHACKDebugTarget()
, m_DEVHACKClockMultiplier( NULL )
, m_CAMHACKPathData()
, m_CAMHACKCamActive( false )
, m_CAMHACKCamVelocity( 1.0f )
, m_CAMHACKCamLocation()
, m_CAMHACKCamOrientation()
, m_CAMHACKCamStartLocation()
, m_CAMHACKCamEndLocation()
, m_CAMHACKCamStartOrientation()
, m_CAMHACKCamEndOrientation()
, m_DebugSpawners()
, m_DebugSpawnerIndex( 0 )
, m_CACHED_LastAINoiseSourceLocation()
, m_CACHED_LastAINoiseRadius( 0.0f )
#endif
{
STATIC_HASHED_STRING( PreLevelTransition );
GetEventManager()->AddObserver( sPreLevelTransition, this );
STATIC_HASHED_STRING( PostLevelTransition );
GetEventManager()->AddObserver( sPostLevelTransition, this );
STATIC_HASHED_STRING( OnAINoise );
GetEventManager()->AddObserver( sOnAINoise, this );
GetFramework()->GetInputSystem()->AddInputSystemObserver( this );
}
WBCompRosaPlayer::~WBCompRosaPlayer()
{
WBEventManager* const pEventManager = GetEventManager();
if( pEventManager )
{
STATIC_HASHED_STRING( PreLevelTransition );
pEventManager->RemoveObserver( sPreLevelTransition, this );
STATIC_HASHED_STRING( PostLevelTransition );
pEventManager->RemoveObserver( sPostLevelTransition, this );
STATIC_HASHED_STRING( OnAINoise );
pEventManager->RemoveObserver( sOnAINoise, this );
}
InputSystem* const pInputSystem = GetFramework()->GetInputSystem();
if( pInputSystem )
{
pInputSystem->RemoveInputSystemObserver( this );
}
}
/*virtual*/ void WBCompRosaPlayer::InitializeFromDefinition( const SimpleString& DefinitionName )
{
RosaCampaign* const pCampaign = RosaCampaign::GetCampaign();
Super::InitializeFromDefinition( DefinitionName );
MAKEHASH( DefinitionName );
STATICHASH( DeferMusic );
m_DeferMusic = ConfigManager::GetInheritedBool( sDeferMusic, false, sDefinitionName );
STATICHASH( InitialMusicTrackBits );
m_InitialMusicTrackBits = pCampaign->OverrideInt( sInitialMusicTrackBits, ConfigManager::GetInheritedInt( sInitialMusicTrackBits, 0, sDefinitionName ) );
STATICHASH( RollingAutosaveDelay );
m_RollingAutosaveDelay = ConfigManager::GetInheritedFloat( sRollingAutosaveDelay, 0.0f, sDefinitionName );
STATICHASH( RetryAutosaveDelay );
m_RetryAutosaveDelay = ConfigManager::GetInheritedFloat( sRetryAutosaveDelay, 0.0f, sDefinitionName );
STATICHASH( UnlandedForceFootstepWindow );
m_UnlandedForceFootstepWindow = ConfigManager::GetInheritedFloat( sUnlandedForceFootstepWindow, 0.0f, sDefinitionName );
STATICHASH( UnlandedJumpWindow );
m_UnlandedJumpWindow = ConfigManager::GetInheritedFloat( sUnlandedJumpWindow, 0.0f, sDefinitionName );
STATICHASH( UnlandedLeanWindow );
m_UnlandedLeanWindow = ConfigManager::GetInheritedFloat( sUnlandedLeanWindow, 0.0f, sDefinitionName );
STATICHASH( LandAcceleration );
m_LandAcceleration = ConfigManager::GetInheritedFloat( sLandAcceleration, 0.0f, sDefinitionName );
STATICHASH( AirAcceleration );
m_AirAcceleration = ConfigManager::GetInheritedFloat( sAirAcceleration, 0.0f, sDefinitionName );
STATICHASH( TurnSpeed );
m_TurnSpeed = ConfigManager::GetInheritedFloat( sTurnSpeed, 0.0f, sDefinitionName );
STATICHASH( JumpHeight );
m_JumpHeight = ConfigManager::GetInheritedFloat( sJumpHeight, 0.0f, sDefinitionName );
STATICHASH( BackpedalScalar );
m_BackpedalScalar = ConfigManager::GetInheritedFloat( sBackpedalScalar, 1.0f, sDefinitionName );
STATICHASH( DoubleJumpHeight );
m_DoubleJumpHeight = ConfigManager::GetInheritedFloat( sDoubleJumpHeight, 0.0f, sDefinitionName );
STATICHASH( PowerJumpRatio );
m_PowerJumpRatio = ConfigManager::GetInheritedFloat( sPowerJumpRatio, 0.0f, sDefinitionName );
STATICHASH( UncrouchOnSprint );
m_UncrouchOnSprint = ConfigManager::GetInheritedBool( sUncrouchOnSprint, false, sDefinitionName );
STATICHASH( SprintFOVScale );
m_SprintFOVScale = ConfigManager::GetInheritedFloat( sSprintFOVScale, 1.0f, sDefinitionName );
STATICHASH( SprintFOVTime );
m_SprintFOVTime = ConfigManager::GetInheritedFloat( sSprintFOVTime, 0.0f, sDefinitionName );
STATICHASH( StandExtentsZ );
m_StandExtentsZ = ConfigManager::GetInheritedFloat( sStandExtentsZ, 0.0f, sDefinitionName );
STATICHASH( CrouchExtentsZ );
m_CrouchExtentsZ = ConfigManager::GetInheritedFloat( sCrouchExtentsZ, 0.0f, sDefinitionName );
STATICHASH( StandViewOffsetZ );
m_StandViewOffsetZ = ConfigManager::GetInheritedFloat( sStandViewOffsetZ, 0.0f, sDefinitionName );
m_ViewOffsetZInterpolator.Reset( m_StandViewOffsetZ );
STATICHASH( CrouchViewOffsetZ );
m_CrouchViewOffsetZ = ConfigManager::GetInheritedFloat( sCrouchViewOffsetZ, 0.0f, sDefinitionName );
STATICHASH( CrouchViewInterpTime );
m_CrouchViewInterpTime = ConfigManager::GetInheritedFloat( sCrouchViewInterpTime, 0.0f, sDefinitionName );
STATICHASH( PushToSprint );
m_PushToSprint = ConfigManager::GetInheritedBool( sPushToSprint, false, sDefinitionName );
STATICHASH( PowerSlideDuration );
m_PowerSlideDuration = ConfigManager::GetInheritedFloat( sPowerSlideDuration, 0.0f, sDefinitionName );
STATICHASH( PowerSlideInputContext );
m_PowerSlideInputContext = ConfigManager::GetInheritedHash( sPowerSlideInputContext, HashedString::NullString, sDefinitionName );
STATICHASH( PowerSlideReqVelocity );
m_PowerSlideReqVelocitySq = Square( ConfigManager::GetInheritedFloat( sPowerSlideReqVelocity, 0.0f, sDefinitionName ) );
STATICHASH( PowerSlideRoll );
m_PowerSlideRoll = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sPowerSlideRoll, 0.0f, sDefinitionName ) );
STATICHASH( PowerSlideRollInterpTime );
m_PowerSlideRollInterpTime = ConfigManager::GetInheritedFloat( sPowerSlideRollInterpTime, 0.0f, sDefinitionName );
STATICHASH( DragInputContext );
m_DragInputContext = ConfigManager::GetInheritedHash( sDragInputContext, HashedString::NullString, sDefinitionName );
STATICHASH( DragDropOffsetZ );
m_DragDropOffset.z = ConfigManager::GetInheritedFloat( sDragDropOffsetZ, 0.0f, sDefinitionName );
STATICHASH( DragDropOrientationYaw );
m_DragDropOrientation.Yaw = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sDragDropOrientationYaw, 0.0f, sDefinitionName ) );
STATICHASH( DragDropSpawnImpulse );
m_DragDropSpawnImpulse = ConfigManager::GetInheritedFloat( sDragDropSpawnImpulse, 0.0f, sDefinitionName );
STATICHASH( DragDropSpawnImpulseZ );
m_DragDropSpawnImpulseZ = ConfigManager::GetInheritedFloat( sDragDropSpawnImpulseZ, 0.0f, sDefinitionName );
STATICHASH( ClimbInputContext );
m_ClimbInputContext = ConfigManager::GetInheritedHash( sClimbInputContext, HashedString::NullString, sDefinitionName );
STATICHASH( ClimbOffImpulse );
m_ClimbOffImpulse = ConfigManager::GetInheritedFloat( sClimbOffImpulse, 0.0f, sDefinitionName );
STATICHASH( ClimbFacingBiasAngle );
m_ClimbFacingBiasAngle = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sClimbFacingBiasAngle, 0.0f, sDefinitionName ) );
STATICHASH( ClimbFacingBiasScale );
m_ClimbFacingBiasScale = ConfigManager::GetInheritedFloat( sClimbFacingBiasScale, 0.0f, sDefinitionName );
STATICHASH( MantleInputContext );
m_MantleInputContext = ConfigManager::GetInheritedHash( sMantleInputContext, HashedString::NullString, sDefinitionName );
STATICHASH( MantleVelocity );
m_MantleVelocity = ConfigManager::GetInheritedFloat( sMantleVelocity, 0.0f, sDefinitionName );
// Not a config var of the component!
STATICHASH( AutoAim );
m_AutoAimEnabled = ConfigManager::GetBool( sAutoAim );
STATICHASH( AutoAimMaxTurn );
m_AutoAimMaxTurn = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sAutoAimMaxTurn, 0.0f, sDefinitionName ) );
// Not a config var of the component!
STATICHASH( SprintFOV );
m_SprintFOVEnabled = ConfigManager::GetBool( sSprintFOV );
STATICHASH( MaxViewBobOffsetX );
m_MaxViewBobOffset.x = ConfigManager::GetInheritedFloat( sMaxViewBobOffsetX, 0.0f, sDefinitionName );
STATICHASH( MaxViewBobOffsetY );
m_MaxViewBobOffset.y = ConfigManager::GetInheritedFloat( sMaxViewBobOffsetY, 0.0f, sDefinitionName );
STATICHASH( MaxViewBobOffsetZ );
m_MaxViewBobOffset.z = ConfigManager::GetInheritedFloat( sMaxViewBobOffsetZ, 0.0f, sDefinitionName );
STATICHASH( MaxViewBobAngleOffsetPitch );
m_MaxViewBobAngleOffset.Pitch = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewBobAngleOffsetPitch, 0.0f, sDefinitionName ) );
STATICHASH( MaxViewBobAngleOffsetRoll );
m_MaxViewBobAngleOffset.Roll = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewBobAngleOffsetRoll, 0.0f, sDefinitionName ) );
STATICHASH( MaxViewBobAngleOffsetYaw );
m_MaxViewBobAngleOffset.Yaw = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewBobAngleOffsetYaw, 0.0f, sDefinitionName ) );
STATICHASH( UnlandedViewBobWindow );
m_UnlandedViewBobWindow = ConfigManager::GetInheritedFloat( sUnlandedViewBobWindow, 0.0f, sDefinitionName );
STATICHASH( ViewBobAngleExponent );
m_ViewBobAngleExponent = ConfigManager::GetInheritedFloat( sViewBobAngleExponent, 0.0f, sDefinitionName );
STATICHASH( ViewBobInterpolateTime );
m_ViewBobInterpolateTime = ConfigManager::GetInheritedFloat( sViewBobInterpolateTime, 0.0f, sDefinitionName );
STATICHASH( MaxViewSwayOffsetX );
m_MaxViewSwayOffset.x = ConfigManager::GetInheritedFloat( sMaxViewSwayOffsetX, 0.0f, sDefinitionName );
STATICHASH( MaxViewSwayOffsetY );
m_MaxViewSwayOffset.y = ConfigManager::GetInheritedFloat( sMaxViewSwayOffsetY, 0.0f, sDefinitionName );
STATICHASH( MaxViewSwayOffsetZ );
m_MaxViewSwayOffset.z = ConfigManager::GetInheritedFloat( sMaxViewSwayOffsetZ, 0.0f, sDefinitionName );
STATICHASH( MaxViewSwayAngleOffsetPitch );
m_MaxViewSwayAngleOffset.Pitch = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewSwayAngleOffsetPitch, 0.0f, sDefinitionName ) );
STATICHASH( MaxViewSwayAngleOffsetRoll );
m_MaxViewSwayAngleOffset.Roll = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewSwayAngleOffsetRoll, 0.0f, sDefinitionName ) );
STATICHASH( MaxViewSwayAngleOffsetYaw );
m_MaxViewSwayAngleOffset.Yaw = DEGREES_TO_RADIANS( ConfigManager::GetInheritedFloat( sMaxViewSwayAngleOffsetYaw, 0.0f, sDefinitionName ) );
STATICHASH( ViewSwayInterpolateTime );
m_ViewSwayInterpolateTime = ConfigManager::GetInheritedFloat( sViewSwayInterpolateTime, 0.0f, sDefinitionName );
STATICHASH( ViewSwayNoiseOctaves );
m_ViewSwayNoiseOctaves = ConfigManager::GetInheritedInt( sViewSwayNoiseOctaves, 0, sDefinitionName );
STATICHASH( ViewSwayNoiseScalarsX );
m_ViewSwayNoiseScalars.x = ConfigManager::GetInheritedFloat( sViewSwayNoiseScalarsX, 0.0f, sDefinitionName );
STATICHASH( ViewSwayNoiseScalarsY );
m_ViewSwayNoiseScalars.y = ConfigManager::GetInheritedFloat( sViewSwayNoiseScalarsY, 0.0f, sDefinitionName );
STATICHASH( ViewSwayNoiseScalarsZ );
m_ViewSwayNoiseScalars.z = ConfigManager::GetInheritedFloat( sViewSwayNoiseScalarsZ, 0.0f, sDefinitionName );
STATICHASH( ViewSwayNoiseAngleScalarsPitch );
m_ViewSwayNoiseAngleScalars.x = ConfigManager::GetInheritedFloat( sViewSwayNoiseAngleScalarsPitch, 0.0f, sDefinitionName );
STATICHASH( ViewSwayNoiseAngleScalarsRoll );
m_ViewSwayNoiseAngleScalars.y = ConfigManager::GetInheritedFloat( sViewSwayNoiseAngleScalarsRoll, 0.0f, sDefinitionName );
STATICHASH( ViewSwayNoiseAngleScalarsYaw );
m_ViewSwayNoiseAngleScalars.z = ConfigManager::GetInheritedFloat( sViewSwayNoiseAngleScalarsYaw, 0.0f, sDefinitionName );
STATICHASH( KickSpringK );
m_KickSpringK = ConfigManager::GetInheritedFloat( sKickSpringK, 0.0f, sDefinitionName );
STATICHASH( KickDamperC );
m_KickDamperC = ConfigManager::GetInheritedFloat( sKickDamperC, 0.0f, sDefinitionName );
STATICHASH( ViewHandsSpringK );
m_ViewHandsSpringK = ConfigManager::GetInheritedFloat( sViewHandsSpringK, 0.0f, sDefinitionName );
STATICHASH( ViewHandsDamperC );
m_ViewHandsDamperC = ConfigManager::GetInheritedFloat( sViewHandsDamperC, 0.0f, sDefinitionName );
#if BUILD_DEV
const uint NumActiveContexts = GetFramework()->GetInputSystem()->GetNumActiveContexts();
const bool IsInTitleScreen = GetGame()->IsInTitleScreen();
// This isn't really the player component's domain, it's just a convenient place to validate this.
// Title screen has a null input context, so it is excepted.
DEVASSERT( NumActiveContexts == 0 || IsInTitleScreen );
#endif // BUILD_DEV
#if BUILD_DEV
STATICHASH( RosaPlayer_DebugSpawner );
STATICHASH( NumEntities );
const uint NumEntities = ConfigManager::GetInt( sNumEntities, 0, sRosaPlayer_DebugSpawner );
for( uint EntityIndex = 0; EntityIndex < NumEntities; ++EntityIndex )
{
SDebugSpawner& Spawner = m_DebugSpawners.PushBack();
Spawner.m_Entity = ConfigManager::GetSequenceString( "Entity%d", EntityIndex, "", sRosaPlayer_DebugSpawner );
Spawner.m_Offset.x = ConfigManager::GetSequenceFloat( "Entity%dX", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner );
Spawner.m_Offset.y = ConfigManager::GetSequenceFloat( "Entity%dY", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner );
Spawner.m_Offset.z = ConfigManager::GetSequenceFloat( "Entity%dZ", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner );
Spawner.m_NormalDistance = ConfigManager::GetSequenceFloat( "Entity%dN", EntityIndex, 0.0f, sRosaPlayer_DebugSpawner );
}
#endif
}
void WBCompRosaPlayer::TickViewBobAndSway()
{
XTRACE_FUNCTION;
PROFILE_FUNCTION;
WBEntity* const pEntity = GetEntity();
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
WBCompRosaHealth* const pHealth = WB_GETCOMP( pEntity, RosaHealth );
WBCompRosaFootsteps* const pFootsteps = WB_GETCOMP( pEntity, RosaFootsteps );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
// NOTE: This uses the transform's *default* speed limit, not the modded speed limit.
// Which is what I want here, because then it saturates while running even if speed limit is increased.
const bool DoViewBob = pHealth->IsAlive() && pCollision->IsRecentlyLanded( m_UnlandedViewBobWindow ) && !m_IsPowerSliding && !m_IsClimbing && !m_IsMantling;
const float ViewBobScalar = Saturate( pTransform->GetVelocity().Length2D() / pTransform->GetSpeedLimit() );
const float ViewBobAngleScalar = Pow( ViewBobScalar, m_ViewBobAngleExponent );
const float ViewBobAlphaX = pFootsteps ? pFootsteps->GetStepPhaseSignedAlpha() : 0.0f; // [-1, 1]
const float ViewBobAlphaYZ = Abs( ViewBobAlphaX ); // [0, 1]
const Vector ViewBobAlpha = Vector( ViewBobAlphaX, ViewBobAlphaYZ, ViewBobAlphaYZ );
const Angles ViewBobAngleAlpha = Angles( ViewBobAlphaYZ, ViewBobAlphaX, ViewBobAlphaX );
const Vector ViewBobOffset = ( ViewBobScalar * ViewBobAlpha * m_MaxViewBobOffset ) * pTransform->GetOrientation().ToMatrix();
const Angles ViewBobAngleOffset = ( ViewBobAngleScalar * ViewBobAngleAlpha * m_MaxViewBobAngleOffset );
const bool DoViewSway = true;
const Vector ViewSwayAlpha = Vector(
Noise::SumNoise1( GetTime() * m_ViewSwayNoiseScalars.x, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ),
Noise::SumNoise1( GetTime() * m_ViewSwayNoiseScalars.y, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ),
Noise::SumNoise1( GetTime() * m_ViewSwayNoiseScalars.z, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ) );
const Angles ViewSwayAngleAlpha = Angles(
Noise::SumNoise1( GetTime() * m_ViewSwayNoiseAngleScalars.x, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ),
Noise::SumNoise1( GetTime() * m_ViewSwayNoiseAngleScalars.y, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ),
Noise::SumNoise1( GetTime() * m_ViewSwayNoiseAngleScalars.z, m_ViewSwayNoiseOctaves, Noise::CubicNoise1 ) );
WB_MODIFY_FLOAT( ViewSwayOffsetScalar, 1.0f, pStatMod );
const float ViewSwayOffsetScalar = WB_MODDED( ViewSwayOffsetScalar );
WB_MODIFY_FLOAT( ViewSwayAngleOffsetScalar, 1.0f, pStatMod );
const float ViewSwayAngleOffsetScalar = WB_MODDED( ViewSwayAngleOffsetScalar );
const Vector ViewSwayOffset = ViewSwayOffsetScalar * ( ( ViewSwayAlpha * m_MaxViewSwayOffset ) * pTransform->GetOrientation().ToMatrix() );
const Angles ViewSwayAngleOffset = ViewSwayAngleOffsetScalar * ( ViewSwayAngleAlpha * m_MaxViewSwayAngleOffset );
// Constantly resetting from current value produces an ease-out effect
m_ViewBobOffsetInterpolator.Reset(
Interpolator<Vector>::EIT_Linear,
m_ViewBobOffsetInterpolator.GetValue(),
DoViewBob ? ViewBobOffset : Vector(),
m_ViewBobInterpolateTime );
m_ViewBobAngleOffsetInterpolator.Reset(
Interpolator<Angles>::EIT_Linear,
m_ViewBobAngleOffsetInterpolator.GetValue(),
DoViewBob ? ViewBobAngleOffset : Angles(),
m_ViewBobInterpolateTime );
m_ViewSwayOffsetInterpolator.Reset(
Interpolator<Vector>::EIT_Linear,
m_ViewSwayOffsetInterpolator.GetValue(),
DoViewSway ? ViewSwayOffset : Vector(),
m_ViewSwayInterpolateTime );
m_ViewSwayAngleOffsetInterpolator.Reset(
Interpolator<Angles>::EIT_Linear,
m_ViewSwayAngleOffsetInterpolator.GetValue(),
DoViewSway ? ViewSwayAngleOffset : Angles(),
m_ViewSwayInterpolateTime );
}
WBCompRosaWeapon* WBCompRosaPlayer::GetWeapon() const
{
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaInventory* const pInventory = WB_GETCOMP( pEntity, RosaInventory );
DEVASSERT( pInventory );
WBEntity* const pWeaponEntity = pInventory->GetCycleItem();
WBCompRosaWeapon* const pWeapon = WB_GETCOMP_SAFE( pWeaponEntity, RosaWeapon );
return pWeapon;
}
void WBCompRosaPlayer::TickKick( const float DeltaTime )
{
WBCompRosaWeapon* const pWeapon = GetWeapon();
const float SpringK = ( pWeapon && pWeapon->GetKickSpringK() > 0.0f ) ? pWeapon->GetKickSpringK() : m_KickSpringK;
const float DamperC = ( pWeapon && pWeapon->GetKickDamperC() > 0.0f ) ? pWeapon->GetKickDamperC() : m_KickDamperC;
// Spring-damping system (ignoring mass because it's just a multiple of this equation)
const Angles KickAcceleration = ( -SpringK * m_KickPosition ) + ( -DamperC * m_KickVelocity );
m_KickVelocity += KickAcceleration * DeltaTime;
m_KickPosition += m_KickVelocity * DeltaTime;
}
void WBCompRosaPlayer::TickHandsVelocity( const float DeltaTime, const Vector& TargetVelocity, const Angles& TargetRotationalVelocity )
{
// Here, the velocity *is* the position for the spring system; so "velocity" becomes acceleration, and "acceleration" becomes jerk.
// This system typically tries to center at the origin instead of a target;
// so subtract to get our "position" (velocity).
const Vector CurrentVelocity = m_ViewHandsVelocity - TargetVelocity;
const Angles CurrentRotationalVelocity = m_ViewHandsRotationalVelocity - TargetRotationalVelocity;
const Vector ViewHandsJerk = ( -m_ViewHandsSpringK * CurrentVelocity ) + ( -m_ViewHandsDamperC * m_ViewHandsAcceleration );
const Angles ViewHandsRotationalJerk = ( -m_ViewHandsSpringK * CurrentRotationalVelocity ) + ( -m_ViewHandsDamperC * m_ViewHandsRotationalAcceleration );
m_ViewHandsAcceleration += ViewHandsJerk * DeltaTime;
m_ViewHandsRotationalAcceleration += ViewHandsRotationalJerk * DeltaTime;
m_ViewHandsVelocity += m_ViewHandsAcceleration * DeltaTime;
m_ViewHandsRotationalVelocity += m_ViewHandsRotationalAcceleration * DeltaTime;
}
// Sticky targeting (lock-on, auto aim, aim assist, whatever)
// Orient to face aim target, if any; only if we're using the controller.
// This isn't dependent on input per se, but it's probably best
// if we only do it in cases where turning isn't suppressed.
// ROSATODO: This should probably still be an option, even if it's controller-only.
void WBCompRosaPlayer::TickAutoAim( const float DeltaTime )
{
if( !m_AutoAimEnabled )
{
return;
}
STATIC_HASHED_STRING( TurnX );
STATIC_HASHED_STRING( TurnY );
InputSystem* const pInputSystem = GetFramework()->GetInputSystem();
if( !pInputSystem->IsUsingControllerExclusively() ||
pInputSystem->IsSuppressed( sTurnX ) ||
pInputSystem->IsSuppressed( sTurnY ) )
{
return;
}
WBCompRosaWeapon* const pWeapon = GetWeapon();
if( !pWeapon || !pWeapon->CanAutoAim() )
{
return;
}
WBEntity* const pEntity = GetEntity();
WBCompRosaFrobber* const pFrobber = WB_GETCOMP( pEntity, RosaFrobber );
WBEntity* pAimTarget;
HashedString AimTargetBone;
pFrobber->GetAimTarget( pAimTarget, AimTargetBone );
if( !pAimTarget )
{
return;
}
WBCompRosaFrobbable* const pFrobbable = WB_GETCOMP( pAimTarget, RosaFrobbable );
DEVASSERT( pFrobbable );
if( !pFrobbable->CanBeAutoAimedAt() )
{
return;
}
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera );
WBCompRosaMesh* const pAimTargetMesh = WB_GETCOMP( pAimTarget, RosaMesh );
const Vector BoneLocation = pAimTargetMesh->GetBoneLocation( pAimTargetMesh->GetBoneIndex( AimTargetBone ) );
const Vector CameraLocation = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() );
const Angles OldOrientation = pTransform->GetOrientation();
const Vector AimOffset = BoneLocation - CameraLocation;
const Angles AimOrientation = AimOffset.ToAngles();
Angles TurnOffset = ( AimOrientation - pTransform->GetOrientation() ).GetShortestRotation();
const float MaxTurn = DeltaTime * m_AutoAimMaxTurn;
TurnOffset.Yaw = Clamp( TurnOffset.Yaw, -MaxTurn, MaxTurn );
TurnOffset.Pitch = Clamp( TurnOffset.Pitch, -MaxTurn, MaxTurn );
const Angles NewOrientation = WBCompRosaTransform::ClampPitch( OldOrientation + TurnOffset );
pTransform->SetOrientation( NewOrientation );
}
/*virtual*/ void WBCompRosaPlayer::Tick( const float DeltaTime )
{
XTRACE_FUNCTION;
PROFILE_FUNCTION;
WBEntity* const pEntity = GetEntity();
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera );
WBCompRosaHealth* const pHealth = WB_GETCOMP( pEntity, RosaHealth );
WBCompRosaInventory* const pInventory = WB_GETCOMP( pEntity, RosaInventory );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
WBCompRosaWeapon* const pWeapon = GetWeapon();
WBEventManager* const pEventManager = GetEventManager();
InputSystem* const pInputSystem = GetFramework()->GetInputSystem();
#if BUILD_DEV
if( m_CAMHACKCamActive )
{
m_CAMHACKCamLocation.Tick( DeltaTime );
m_CAMHACKCamOrientation.Tick( DeltaTime );
WBCompRosaFootsteps* const pFootsteps = WB_GETCOMP( pEntity, RosaFootsteps );
pTransform->SetLocation( m_CAMHACKCamLocation.GetValue() );
pTransform->SetOrientation( m_CAMHACKCamOrientation.GetValue() );
if( m_CAMHACKCamLocation.GetT() == 1.0f )
{
m_CAMHACKCamActive = false;
pCollision->ResetCollisionFlags();
pTransform->SetDefaultGravity();
if( pFootsteps )
{
pFootsteps->SetFootstepsDisabled( false );
}
WB_MAKE_EVENT( ShowHands, GetEntity() );
WB_DISPATCH_EVENT( pEventManager, ShowHands, GetEntity() );
STATIC_HASHED_STRING( HUD );
WB_MAKE_EVENT( RepushUIScreen, NULL );
WB_SET_AUTO( RepushUIScreen, Hash, Screen, sHUD );
WB_DISPATCH_EVENT( GetEventManager(), RepushUIScreen, NULL );
}
}
#endif // BUILD_DEV
TickViewBobAndSway();
TickKick( DeltaTime );
TickHandsVelocity( DeltaTime, pTransform->GetVelocity(), pTransform->GetRotationalVelocity() );
if( pHealth->IsAlive() )
{
m_ViewOffsetZInterpolator.Tick( DeltaTime );
pCamera->SetViewOffsetZ( m_ViewOffsetZInterpolator.GetValue() );
m_PowerSlideRollInterpolator.Tick( DeltaTime );
pCamera->SetSlideRoll( m_PowerSlideRollInterpolator.GetValue() );
m_StepUpZInterpolator.Tick( DeltaTime );
pCamera->SetStepUpZ( m_StepUpZInterpolator.GetValue() );
// Stat mod kick at the last minute instead of for each impulse
WB_MODIFY_FLOAT( KickScalar, 1.0f, pStatMod );
pCamera->SetKickAngleOffset( m_KickPosition * WB_MODDED( KickScalar ) );
}
else
{
pCamera->SetKickAngleOffset( Angles() );
}
// Do this part regardless of being alive, I guess
{
m_ViewBobOffsetInterpolator.Tick( DeltaTime );
pCamera->SetViewBobOffset( m_ViewBobOffsetInterpolator.GetValue() );
m_ViewBobAngleOffsetInterpolator.Tick( DeltaTime );
pCamera->SetViewBobAngleOffset( m_ViewBobAngleOffsetInterpolator.GetValue() );
m_ViewSwayOffsetInterpolator.Tick( DeltaTime );
pCamera->SetViewSwayOffset( m_ViewSwayOffsetInterpolator.GetValue() );
m_ViewSwayAngleOffsetInterpolator.Tick( DeltaTime );
pCamera->SetViewSwayAngleOffset( m_ViewSwayAngleOffsetInterpolator.GetValue() );
pCamera->SetHandsVelocity( m_ViewHandsVelocity, m_ViewHandsRotationalVelocity );
}
// Update FOVs, factoring in weapon aim and any other stat mods
// Weapon aim FOV takes priority, then fall back to sprint/normal, then apply stat mods
const bool UseSprintFOV = m_SprintFOVEnabled && ( m_IsSprintingWithMovement || m_IsPowerSliding );
const float BaseFOVScale = ( pWeapon && pWeapon->IsAiming() ) ? pWeapon->GetAimZoom() : ( UseSprintFOV ? m_SprintFOVScale : 1.0f );
const float BaseFGFOVScale = ( pWeapon && pWeapon->IsAiming() ) ? pWeapon->GetAimZoomFG() : 1.0f;
const float BaseFOVTime = ( pWeapon && pWeapon->IsAimChanging() ) ? pWeapon->GetAimTime() : m_SprintFOVTime;
WB_MODIFY_FLOAT( FOVScale, BaseFOVScale, pStatMod );
WB_MODIFY_FLOAT( FGFOVScale, BaseFGFOVScale, pStatMod );
WB_MODIFY_FLOAT( FOVTime, BaseFOVTime, pStatMod );
STATICHASH( FOV );
STATICHASH( ForegroundFOV );
TickScaleFOV( m_CurrentFOV, ConfigManager::GetFloat( sFOV ), WB_MODDED( FOVScale ), WB_MODDED( FOVTime ), DeltaTime );
TickScaleFOV( m_CurrentFGFOV, ConfigManager::GetFloat( sForegroundFOV ), WB_MODDED( FGFOVScale ), WB_MODDED( FOVTime ), DeltaTime );
GetFramework()->SetFOV( m_CurrentFOV.GetValue() );
GetFramework()->SetFGFOV( m_CurrentFGFOV.GetValue() );
if( m_IsUncrouching )
{
TryUncrouch();
}
if( m_IsPowerSliding )
{
if( GetTime() >= m_PowerSlideEndTime )
{
EndPowerSlide();
}
}
// *********************************************************************************************
// *********************************************************************************************
// *********************************************************************************************
//
// Everything before this point is independent of current input and must be done every tick.
// Everything after this point is dependent on input and should be done only when we have focus.
//
// *********************************************************************************************
// *********************************************************************************************
// *********************************************************************************************
if( !GetFramework()->HasFocus() )
{
return;
}
TickAutoAim( DeltaTime );
DEVASSERT( pTransform );
DEVASSERT( pCollision );
DEVASSERT( pCamera );
DEVASSERT( pStatMod );
// Get 2D orientation; we don't want to move as if we're flying.
Angles PlayerOrientation;
Vector X, Y, Z;
const Vector UpVector = Vector( 0.0f, 0.0f, 1.0f );
const Vector PlayerFacing = pTransform->GetOrientation().ToVector();
const Vector PlayerRight = PlayerFacing.Cross( UpVector ).GetNormalized(); // DLP 8 Nov 2019: This didn't used to be normalized, not sure if it could've been a problem
if( m_IsFlying )
{
PlayerOrientation = pTransform->GetOrientation();
}
else
{
PlayerOrientation.Yaw = pTransform->GetOrientation().Yaw;
}
PlayerOrientation.GetAxes( X, Y, Z );
Vector MovementVector;
Angles TurnAngles;
Vector ImpulseVector;
STATIC_HASHED_STRING( Right );
STATIC_HASHED_STRING( Left );
STATIC_HASHED_STRING( Forward );
STATIC_HASHED_STRING( Back );
STATIC_HASHED_STRING( MoveX );
STATIC_HASHED_STRING( MoveY );
STATIC_HASHED_STRING( Jump );
STATIC_HASHED_STRING( Heal );
STATIC_HASHED_STRING( UseWeapon );
STATIC_HASHED_STRING( Shove );
STATIC_HASHED_STRING( Reload );
STATIC_HASHED_STRING( Zoom );
STATIC_HASHED_STRING( Light );
STATIC_HASHED_STRING( CycleMag );
STATIC_HASHED_STRING( Radial );
STATIC_HASHED_STRING( CycleSlot0 );
STATIC_HASHED_STRING( CycleSlot1 );
STATIC_HASHED_STRING( CycleSlot2 );
STATIC_HASHED_STRING( CycleSlot3 );
STATIC_HASHED_STRING( CyclePrev );
STATIC_HASHED_STRING( CycleNext );
STATIC_HASHED_STRING( Frob );
STATIC_HASHED_STRING( LeanLeft );
STATIC_HASHED_STRING( LeanRight );
STATIC_HASHED_STRING( TurnX );
STATIC_HASHED_STRING( TurnY );
STATIC_HASHED_STRING( Run );
STATIC_HASHED_STRING( Crouch );
STATIC_HASHED_STRING( ClimbForward );
STATIC_HASHED_STRING( ClimbBack );
STATIC_HASHED_STRING( ClimbDown );
STATIC_HASHED_STRING( ClimbY );
STATIC_HASHED_STRING( ClimbJump );
STATIC_HASHED_STRING( Mantle );
if( pInputSystem->IsHigh( sRight ) ) { MovementVector += X; }
if( pInputSystem->IsHigh( sLeft ) ) { MovementVector -= X; }
if( pInputSystem->IsHigh( sForward ) ) { MovementVector += Y; }
if( pInputSystem->IsHigh( sBack ) ) { MovementVector -= Y * m_BackpedalScalar; }
if( m_IsFlying )
{
// TODO: Maybe do this with an input context? It's really just a borrowed hack from Acid for ghosting right now, whatever.
if( pInputSystem->IsHigh( sJump ) )
{
MovementVector += UpVector;
}
if( pInputSystem->IsHigh( sCrouch ) )
{
MovementVector -= UpVector;
}
}
const float MoveX = pInputSystem->GetPosition( sMoveX );
const float MoveY = pInputSystem->GetPosition( sMoveY );
MovementVector += X * MoveX;
MovementVector += Y * MoveY * ( ( MoveY < 0.0f ) ? m_BackpedalScalar : 1.0f );
const bool HasMovementInput = MovementVector.LengthSquared() >= 0.1f || pInputSystem->IsHigh( sMantle ); // HACKHACK to keep spring on during mantle, since the input context disabled MoveX/Y
const bool WasSprinting = m_IsSprinting;
if( m_PushToSprint )
{
// In this mode, latch the sprinting flag until movement stops.
if( pInputSystem->IsHigh( sRun ) )
{
m_IsSprinting = true;
}
else if( !HasMovementInput )
{
m_IsSprinting = false;
}
}
else
{
m_IsSprinting = pInputSystem->IsHigh( sRun );
}
m_IsSprintingWithMovement = m_IsSprinting && HasMovementInput;
if( !WasSprinting && m_IsSprinting )
{
m_SprintStartTime = GetTime();
}
// If we're crouched and we start sprinting, even if we don't have any movement input, then uncrouch.
// (Surprisingly, this feels more correct than requiring movement input. Feels weird to be crouched,
// press shift, start moving, and not be sprinting.)
// Note: This behavior doesn't change for push-to-sprint.
if( m_UncrouchOnSprint && m_IsCrouched && pInputSystem->OnRise( sRun ) )
{
BeginUncrouch();
}
if( m_IsPowerSliding )
{
MovementVector += m_PowerSlideY;
}
float LeanTarget = 0.0f;
const bool CanLean = pCollision->IsRecentlyLanded( m_UnlandedLeanWindow );
if( m_IsFlying )
{
// Don't lean
}
else if( CanLean )
{
if( pInputSystem->IsHigh( sLeanLeft ) ) { LeanTarget -= 1.0f; }
if( pInputSystem->IsHigh( sLeanRight ) ) { LeanTarget += 1.0f; }
}
float StrafeRollTarget = 0.0f;
if( pInputSystem->IsHigh( sLeft ) ) { StrafeRollTarget -= 1.0f; }
if( pInputSystem->IsHigh( sRight ) ) { StrafeRollTarget += 1.0f; }
StrafeRollTarget += pInputSystem->GetPosition( sMoveX );
if( pInputSystem->OnRise( sHeal ) )
{
WB_MAKE_EVENT( TryUseBandage, pEntity );
WB_DISPATCH_EVENT( pEventManager, TryUseBandage, pEntity );
}
// NOTE: Always send weapon input, even when it's low. This way, we
// untrigger automatic weapons even if the OnFall edge is missed.
const uint UseWeaponInput = pInputSystem->OnInput( sUseWeapon );
{
WB_MAKE_EVENT( UseWeapon, pEntity );
WB_SET_AUTO( UseWeapon, Int, Input, UseWeaponInput );
WB_DISPATCH_EVENT( pEventManager, UseWeapon, pEntity );
}
if( pInputSystem->OnRise( sShove ) )
{
WB_MAKE_EVENT( TryShove, pEntity );
WB_DISPATCH_EVENT( pEventManager, TryShove, pEntity );
}
if( pInputSystem->OnRise( sReload ) )
{
WB_MAKE_EVENT( TryReload, pEntity );
WB_DISPATCH_EVENT( pEventManager, TryReload, pEntity );
}
if( pInputSystem->OnRise( sLight ) )
{
WB_MAKE_EVENT( ToggleFlashlight, NULL );
WB_DISPATCH_EVENT( pEventManager, ToggleFlashlight, NULL );
}
if( pInputSystem->OnRise( sCycleMag ) )
{
WB_MAKE_EVENT( TryCycleMagazine, pEntity );
WB_DISPATCH_EVENT( pEventManager, TryCycleMagazine, pEntity );
}
// NOTE: TryAim/TryUnAim are sent continuously, to make sure they aren't missed
// during weapon transitional states and stuff.
if( pInputSystem->IsHigh( sZoom ) )
{
WB_MAKE_EVENT( TryAim, pEntity );
WB_SET_AUTO( TryAim, Float, ZoomTime, WB_MODDED( FOVTime ) );
WB_DISPATCH_EVENT( pEventManager, TryAim, pEntity );
}
else
{
WB_MAKE_EVENT( TryUnAim, pEntity );
WB_SET_AUTO( TryUnAim, Float, ZoomTime, WB_MODDED( FOVTime ) );
WB_DISPATCH_EVENT( pEventManager, TryUnAim, pEntity );
}
// Only accept radial input if we have any cycle items
if( pInputSystem->OnRise( sRadial ) && pInventory->GetNumCycleItems() > 0 )
{
STATIC_HASHED_STRING( RadialScreen );
WB_MAKE_EVENT( PushUIScreen, NULL );
WB_SET_AUTO( PushUIScreen, Hash, Screen, sRadialScreen );
WB_DISPATCH_EVENT( GetEventManager(), PushUIScreen, NULL );
}
#define HANDLE_CYCLESLOT_INPUT( slot ) \
if( pInputSystem->OnRise( sCycleSlot##slot ) ) \
{ \
STATIC_HASHED_STRING( WeaponSlot##slot ); \
WB_MAKE_EVENT( RequestCycleToSlot, pEntity ); \
WB_SET_AUTO( RequestCycleToSlot, Hash, Slot, sWeaponSlot##slot ); \
WB_DISPATCH_EVENT( pEventManager, RequestCycleToSlot, pEntity ); \
}
HANDLE_CYCLESLOT_INPUT( 0 );
HANDLE_CYCLESLOT_INPUT( 1 );
HANDLE_CYCLESLOT_INPUT( 2 );
HANDLE_CYCLESLOT_INPUT( 3 );
#undef HANDLE_CYCLESLOT_INPUT
if( pInputSystem->OnRise( sCyclePrev ) )
{
WB_MAKE_EVENT( RequestCyclePrev, pEntity );
WB_DISPATCH_EVENT( pEventManager, RequestCyclePrev, pEntity );
}
if( pInputSystem->OnRise( sCycleNext ) )
{
WB_MAKE_EVENT( RequestCycleNext, pEntity );
WB_DISPATCH_EVENT( pEventManager, RequestCycleNext, pEntity );
}
const uint FrobInput = pInputSystem->OnInput( sFrob );
if( FrobInput )
{
WB_MAKE_EVENT( OnFrob, pEntity );
WB_SET_AUTO( OnFrob, Int, Input, FrobInput );
WB_DISPATCH_EVENT( pEventManager, OnFrob, pEntity );
}
bool IsDoubleJumping = false;
const bool IsRecentlyLanded = pCollision->IsRecentlyLanded( m_UnlandedJumpWindow );
const bool ShouldDoubleJump = !IsRecentlyLanded && CanDoubleJump();
if( m_IsFlying )
{
// Don't jump
}
else if(
( pInputSystem->OnRise( sJump ) && IsRecentlyLanded ) ||
( pInputSystem->OnRise( sJump ) && ShouldDoubleJump ) ||
( pInputSystem->IsHigh( sJump ) && ShouldDoubleJump && pTransform->GetVelocity().z < 0.0f ) )
{
if( ShouldDoubleJump )
{
IsDoubleJumping = true;
m_HasDoubleJumped = true;
}
WB_MAKE_EVENT( OnJumped, pEntity );
WB_SET_AUTO( OnJumped, Bool, DoubleJump, IsDoubleJumping );
WB_DISPATCH_EVENT( pEventManager, OnJumped, pEntity );
ImpulseVector.z += 1.0f;
if( CanPowerJump() )
{
ImpulseVector += ( Y * m_PowerJumpRatio );
// HACKHACK: Power jump should always uncrouch you
if( m_IsCrouched )
{
BeginUncrouch();
}
// HACKHACK: Land out of the jump in a sprint (for push-to-sprint mode)
m_IsSprinting = true;
m_IsSprintingWithMovement = true;
}
if( m_IsPowerSliding )
{
EndPowerSlide();
}
}
if( m_IsMantling && pInputSystem->IsLow( sMantle ) )
{
EndMantle( false );
}
if( m_IsFlying )
{
// Don't crouch, and uncrouch if we are
if( m_IsCrouched )
{
BeginUncrouch();
}
}
else if( pInputSystem->OnRise( sCrouch ) )
{
if( m_IsUncrouching )
{
CancelUncrouch();
}
else if( m_IsCrouched )
{
BeginUncrouch();
}
else
{
if( CanCrouch() )
{
Crouch();
if( CanPowerSlide() &&
( pInputSystem->IsHigh( sForward ) || pInputSystem->GetPosition( sMoveY ) > 0.0f ) )
{
BeginPowerSlide( Y );
}
}
}
}
// CAMTODO: Is this still something we want? How will missions in Zeta end? Going to an exit might make more sense...
// Send the Return to Hub message if we've completed the mission
if( pInputSystem->OnHold( sHeal ) &&
RosaCampaign::GetCampaign()->IsScenarioCompleted() )
{
WB_MAKE_EVENT( ActiveReturnToHub, GetEntity() );
WB_DISPATCH_EVENT( GetEventManager(), ActiveReturnToHub, GetEntity() );
}
const bool IsClimbForward = pInputSystem->IsHigh( sClimbForward );
const bool IsClimbBack = pInputSystem->IsHigh( sClimbBack );
const bool IsClimbDown = pInputSystem->IsHigh( sClimbDown );
const float ClimbY = pInputSystem->GetPosition( sClimbY );
const bool IsClimbY = Abs( ClimbY ) > EPSILON;
#if CAMERA_RELATIVE_CLIMBING
// Camera-relative climbing motion (how I prefer).
if( IsClimbForward || IsClimbBack || IsClimbDown || IsClimbY )
{
#if CAMERA_RELATIVE_CLIMBING_BIAS
const Matrix ClimbFacingMatrix = Matrix::CreateRotation( PlayerRight, m_ClimbFacingBiasAngle );
const Vector ClimbFacing = PlayerFacing * ClimbFacingMatrix;
const float ClimbMagnitude = ClimbFacing.z;
const float ScaledClimbMagnitude = Clamp( ClimbMagnitude * m_ClimbFacingBiasScale, -1.0f, 1.0f );
const Vector ClimbVector = UpVector * ScaledClimbMagnitude;
#else
const Vector ClimbVector = PlayerFacing.ProjectionOnto( UpVector );
#endif
ASSERT( ClimbVector.x == 0.0f && ClimbVector.y == 0.0f );
if( IsClimbForward ) { MovementVector += ClimbVector; }
if( IsClimbBack ) { MovementVector -= ClimbVector; }
if( IsClimbDown ) { MovementVector -= UpVector; }
if( IsClimbY ) { MovementVector += ClimbVector * ClimbY; }
}
#else
if( IsClimbForward || IsClimbBack || IsClimbDown || IsClimbY )
{
if( IsClimbForward ) { MovementVector += UpVector; }
if( IsClimbBack ) { MovementVector -= UpVector; }
if( IsClimbDown ) { MovementVector -= UpVector; }
if( IsClimbY ) { MovementVector += UpVector * ClimbY; }
}
#endif
if( pInputSystem->OnRise( sClimbJump ) &&
!pInputSystem->OnFall( sJump ) ) // This prevents jumping off when we've just switched to the climb context
{
ZeroClimbRefs();
WB_MAKE_EVENT( OnJumped, pEntity );
WB_DISPATCH_EVENT( pEventManager, OnJumped, pEntity );
ImpulseVector.z += 1.0f;
MovementVector = Vector();
if( IsClimbForward ) { ImpulseVector += Y; }
if( IsClimbBack ) { ImpulseVector -= Y; }
if( IsClimbY ) { ImpulseVector += Y * ClimbY; }
}
ConditionalApplyRunningStatMods();
TurnAngles.Yaw -= pInputSystem->GetPosition( sTurnX );
TurnAngles.Pitch -= pInputSystem->GetPosition( sTurnY );
float MoveSpeed = 0.0f;
if( m_IsClimbing || pCollision->IsLanded() || m_IsFlying ) // ACIDHACK: Use land acceleration in the air if we're flying, because that's how it's tuned
{
WB_MODIFY_FLOAT( LandAcceleration, m_LandAcceleration, pStatMod );
MoveSpeed = WB_MODDED( LandAcceleration );
}
else
{
MoveSpeed = m_AirAcceleration;
}
if( m_IsClimbing )
{
const float Mu = pCollision->GetFrictionCoefficient();
pTransform->SetVelocity( pTransform->GetVelocity() * Mu );
}
// Don't let movement input exceed 1.0 (run + strafe doesn't double speed!),
// but do allow it to be less than 1.0 for camera-relative climbing or analog input.
Vector MovementVectorDirection;
float MovementVectorLength;
float MovementVectorLengthOverOne;
MovementVector.GetNormalized( MovementVectorDirection, MovementVectorLength, MovementVectorLengthOverOne );
const float AppliedMovementLength = Min( MovementVectorLength, 1.0f );
MovementVector = MovementVectorDirection * AppliedMovementLength * MoveSpeed;
TurnAngles *= m_TurnSpeed * WB_MODDED( FOVScale ); // Apply FOV scale here so zoomed view has slower turn speed
if( m_IsMantling )
{
// Check if we're past the destination and end the mantle if so
const Vector CurrentLocation = pTransform->GetLocation();
const Vector ToDestination = ( m_MantleDestination - CurrentLocation );
const float CosAngle = ToDestination.Dot( m_MantleVector );
if( CosAngle < 0.0f )
{
EndMantle( true );
}
else
{
const Vector MantleVelocity = m_MantleVector * m_MantleVelocity;
pTransform->SetVelocity( MantleVelocity );
}
}
pTransform->SetAcceleration( MovementVector );
pTransform->SetRotationalVelocity( TurnAngles );
if( !ImpulseVector.IsZero() )
{
const float BaseJumpHeight = IsDoubleJumping ? m_DoubleJumpHeight : m_JumpHeight;
WB_MODIFY_FLOAT( JumpHeight, BaseJumpHeight, pStatMod );
const float JumpImpulse = SqRt( -2.0f * pTransform->GetGravity() * WB_MODDED( JumpHeight ) );
ImpulseVector = ImpulseVector.GetFastNormalized() * JumpImpulse;
// HACKHACK: Negate velocity along impulse vector, so double jumps work as expected.
// DLP 29 Dec 2018: For power jumps, I've realized I only want to negate velocity in Z.
//const Vector ImpulseDirectionVelocity = pTransform->GetVelocity().ProjectionOnto( ImpulseVector );
const Vector ImpulseDirectionVelocity = pTransform->GetVelocity().ProjectionOnto( Vector::Up );
pTransform->ApplyImpulse( -ImpulseDirectionVelocity );
pTransform->ApplyImpulse( ImpulseVector );
}
pCamera->SetLeanPosition( LeanTarget );
pCamera->SetStrafeRollPosition( StrafeRollTarget );
if( m_IsSprintingWithMovement || m_IsPowerSliding )
{
pCamera->ZoomMinimapOut();
}
else
{
pCamera->ZoomMinimapIn();
}
#if BUILD_DEV
DEVHACKInput();
#endif
}
void WBCompRosaPlayer::SetCrouchOverlayHidden( const bool Hidden )
{
STATIC_HASHED_STRING( HUD );
STATIC_HASHED_STRING( CrouchOverlay );
WB_MAKE_EVENT( SetWidgetHidden, GetEntity() );
WB_SET_AUTO( SetWidgetHidden, Hash, Screen, sHUD );
WB_SET_AUTO( SetWidgetHidden, Hash, Widget, sCrouchOverlay );
WB_SET_AUTO( SetWidgetHidden, Bool, Hidden, Hidden );
WB_DISPATCH_EVENT( GetEventManager(), SetWidgetHidden, GetFramework()->GetUIManager() );
}
void WBCompRosaPlayer::Crouch()
{
ASSERT( !m_IsCrouched );
ASSERT( !m_IsUncrouching );
DEBUGASSERT( CanCrouch() );
m_IsCrouched = true;
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
ASSERT( pCollision );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
Vector Extents = pCollision->GetExtents();
ASSERT( m_CrouchExtentsZ < Extents.z );
Extents.z = m_CrouchExtentsZ;
pCollision->SetExtents( Extents );
// DLP 22 Dec 2020: If we're on the ground, immediately assume the crouched height location.
// This fixes the long standing issue of falling to the ground which I'd papered over with
// view interpolation and stuff. It was revealed again with the view hands velocity stuff,
// so I'm finally just doing the thing I should've always done and setting the location
// (after setting the smaller extents). I don't do this in the air because it jerks the
// camera and might affect the ability to reach high ledges during crouch jumps.
if( pCollision->IsLanded() )
{
Vector CrouchLocation = pTransform->GetLocation();
CrouchLocation.z = ( CrouchLocation.z - m_StandExtentsZ ) + m_CrouchExtentsZ + EPSILON; // ROSAHACK: Add an epsilon to fix getting stuck in ground
pTransform->SetLocation( CrouchLocation );
}
m_ViewOffsetZInterpolator.Reset( Interpolator<float>::EIT_EaseOut, m_StandViewOffsetZ, m_CrouchViewOffsetZ, m_CrouchViewInterpTime );
SetCrouchOverlayHidden( false );
STATIC_HASHED_STRING( Crouching );
pStatMod->TriggerEvent( sCrouching );
}
void WBCompRosaPlayer::BeginUncrouch()
{
ASSERT( m_IsCrouched );
m_IsUncrouching = true;
m_IsForceCrouched = false;
if( m_IsPowerSliding )
{
EndPowerSlide();
}
}
void WBCompRosaPlayer::CancelUncrouch()
{
ASSERT( m_IsCrouched );
ASSERT( m_IsUncrouching );
m_IsUncrouching = false;
}
void WBCompRosaPlayer::TryUncrouch()
{
ASSERT( m_IsCrouched );
ASSERT( m_IsUncrouching );
if( CanUncrouch() )
{
Uncrouch();
}
}
bool WBCompRosaPlayer::CanCrouch()
{
DEVASSERT( !m_IsCrouched );
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
ASSERT( pCollision );
RosaWorld* const pWorld = GetWorld();
ASSERT( pWorld );
CollisionInfo Info;
Info.m_In_CollideWorld = true;
Info.m_In_CollideEntities = true;
Info.m_In_CollidingEntity = GetEntity();
Info.m_In_UserFlags = EECF_BlockerCollision;
if( pWorld->CheckClearance( pTransform->GetLocation(), pCollision->GetExtents(), Info ) )
{
// We're inside collision (a valid case when seated at a table, for example); don't crouch
return false;
}
else
{
return true;
}
}
bool WBCompRosaPlayer::CanUncrouch()
{
ASSERT( m_IsCrouched );
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
ASSERT( pCollision );
RosaWorld* const pWorld = GetWorld();
ASSERT( pWorld );
Vector StandLocation = pTransform->GetLocation();
// DLP 22 Dec 2020: I used to always check the standing location because I was always
// moving the location on Uncrouch. Not anymore, this corresponds to what Uncrouch does.
if( pCollision->IsLanded() )
{
StandLocation.z = ( StandLocation.z - m_CrouchExtentsZ ) + m_StandExtentsZ + EPSILON; // ROSAHACK: Add an epsilon to fix getting stuck in ground
}
Vector CheckExtents = pCollision->GetExtents();
CheckExtents.z = m_StandExtentsZ;
CollisionInfo Info;
Info.m_In_CollideWorld = true;
Info.m_In_CollideEntities = true;
Info.m_In_CollidingEntity = GetEntity();
Info.m_In_UserFlags = EECF_BlockerCollision;
if( pWorld->CheckClearance( StandLocation, CheckExtents, Info ) )
{
// Something is blocking the uncrouch
return false;
}
else
{
return true;
}
}
void WBCompRosaPlayer::Uncrouch()
{
ASSERT( m_IsCrouched );
ASSERT( m_IsUncrouching );
DEBUGASSERT( CanUncrouch() );
m_IsUncrouching = false;
m_IsCrouched = false;
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
ASSERT( pCollision );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
// If we're on land, transform back up.
// DLP 22 Dec 2020: I used to always do this, which could be used to boost higher during a jump.
// This introduces the possibility that you won't be able to uncrouch if you're airborne
// just above the ground (a case I'm handling in CanUncrouch), but that's probably fine.
if( pCollision->IsLanded() )
{
Vector StandLocation = pTransform->GetLocation();
StandLocation.z = ( StandLocation.z - m_CrouchExtentsZ ) + m_StandExtentsZ + EPSILON; // ROSAHACK: Add an epsilon to fix getting stuck in ground
pTransform->SetLocation( StandLocation );
}
Vector Extents = pCollision->GetExtents();
ASSERT( m_StandExtentsZ > Extents.z );
Extents.z = m_StandExtentsZ;
pCollision->SetExtents( Extents );
m_ViewOffsetZInterpolator.Reset( Interpolator<float>::EIT_EaseOut, m_CrouchViewOffsetZ, m_StandViewOffsetZ, m_CrouchViewInterpTime );
SetCrouchOverlayHidden( true );
STATIC_HASHED_STRING( Crouching );
pStatMod->UnTriggerEvent( sCrouching );
}
void WBCompRosaPlayer::RestoreCrouch()
{
// Fix up view offset and stat mod from state.
// Other crouch properties (collision extents, transform location) are serialized.
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera );
ASSERT( pCamera );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
const float ViewOffsetZ = m_IsCrouched ? m_CrouchViewOffsetZ : m_StandViewOffsetZ;
m_ViewOffsetZInterpolator.Reset( ViewOffsetZ );
pCamera->SetViewOffsetZ( ViewOffsetZ );
SetCrouchOverlayHidden( !m_IsCrouched );
STATIC_HASHED_STRING( Crouching );
pStatMod->SetEventActive( sCrouching, m_IsCrouched );
}
void WBCompRosaPlayer::OnSteppedUp( const float StepHeight )
{
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera );
ASSERT( pCamera );
const float NewViewOffsetZ = m_StepUpZInterpolator.GetEndValue();
const float OldViewOffsetZ = NewViewOffsetZ - StepHeight;
m_StepUpZInterpolator.Reset( Interpolator<float>::EIT_EaseOut, OldViewOffsetZ, NewViewOffsetZ, m_CrouchViewInterpTime );
pCamera->SetStepUpZ( OldViewOffsetZ );
}
bool WBCompRosaPlayer::CanPowerJump() const
{
if( !m_IsPowerSliding )
{
return false;
}
WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod );
WB_MODIFY_FLOAT( PowerJump, 0.0f, pStatMod );
const bool PowerJump = ( WB_MODDED( PowerJump ) != 0.0f );
return PowerJump;
}
bool WBCompRosaPlayer::CanPowerSlide() const
{
if( !m_IsSprinting )
{
return false;
}
WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>();
if( pTransform->GetVelocity().LengthSquared2D() < m_PowerSlideReqVelocitySq )
{
return false;
}
WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod );
WB_MODIFY_FLOAT( PowerSlide, 0.0f, pStatMod );
const bool PowerSlide = ( WB_MODDED( PowerSlide ) != 0.0f );
return PowerSlide;
}
bool WBCompRosaPlayer::CanDoubleJump() const
{
if( m_HasDoubleJumped )
{
return false;
}
if( m_IsMantling )
{
return false;
}
WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod );
WB_MODIFY_FLOAT( DoubleJump, 0.0f, pStatMod );
const bool DoubleJump = ( WB_MODDED( DoubleJump ) != 0.0f );
return DoubleJump;
}
void WBCompRosaPlayer::BeginPowerSlide( const Vector& PowerSlideY )
{
ASSERT( !m_IsPowerSliding );
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
DEVASSERT( pStatMod );
WB_MODIFY_FLOAT( PowerSlideDuration, m_PowerSlideDuration, pStatMod );
m_IsPowerSliding = true;
m_PowerSlideEndTime = GetTime() + WB_MODDED( PowerSlideDuration );
m_PowerSlideY = PowerSlideY;
m_PowerSlideRollInterpolator.Reset( Interpolator<float>::EIT_Linear, 0.0f, m_PowerSlideRoll, m_PowerSlideRollInterpTime );
STATIC_HASHED_STRING( PowerSliding );
pStatMod->TriggerEvent( sPowerSliding );
GetFramework()->GetInputSystem()->PushContext( m_PowerSlideInputContext );
WB_MAKE_EVENT( OnBeginPowerSlide, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), OnBeginPowerSlide, pEntity );
}
void WBCompRosaPlayer::EndPowerSlide()
{
ASSERT( m_IsPowerSliding );
m_IsPowerSliding = false;
InputSystem* const pInputSystem = GetFramework()->GetInputSystem();
ASSERT( pInputSystem );
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
// DLP 13 Oct 2021: This used to use m_PowerSlideRoll as the StartValue, but it seems better to blend back
// from whatever it was at, in case the roll hadn't finished interpolating when the player stopped sliding?
m_PowerSlideRollInterpolator.Reset( Interpolator<float>::EIT_Linear, m_PowerSlideRollInterpolator.GetValue(), 0.0f, m_PowerSlideRollInterpTime );
STATIC_HASHED_STRING( PowerSliding );
pStatMod->UnTriggerEvent( sPowerSliding );
pInputSystem->PopContext( m_PowerSlideInputContext );
STATIC_HASHED_STRING( Run );
if( pInputSystem->IsHigh( sRun ) )
{
BeginUncrouch();
}
}
void WBCompRosaPlayer::RestorePowerSlide()
{
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
const float ViewAngleOffsetRoll = m_IsPowerSliding ? m_PowerSlideRoll : 0.0f;
m_PowerSlideRollInterpolator.Reset( ViewAngleOffsetRoll );
STATIC_HASHED_STRING( PowerSliding );
pStatMod->SetEventActive( sPowerSliding, m_IsPowerSliding );
if( m_IsPowerSliding )
{
GetFramework()->GetInputSystem()->PushContext( m_PowerSlideInputContext );
}
}
void WBCompRosaPlayer::BeginDrag( WBEntity* const pDraggedEntity )
{
DEVASSERT( !m_IsDragging );
m_IsDragging = true;
m_DraggedEntity = pDraggedEntity;
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
DEVASSERT( pStatMod );
STATIC_HASHED_STRING( Dragging );
pStatMod->TriggerEvent( sDragging );
GetFramework()->GetInputSystem()->PushContext( m_DragInputContext );
}
// HACKHACK: Move the dragged entity and give it an impulse.
// I'm calling this a hack because all the other behavior (e.g., showing/hiding it) is scripted.
void WBCompRosaPlayer::DropDraggedEntity()
{
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBEntity* const pDraggedEntity = m_DraggedEntity.Get();
DEVASSERT( pDraggedEntity );
WBCompRosaTransform* const pDraggedTransform = pDraggedEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pDraggedTransform );
WBCompRosaCollision* const pDraggedCollision = WB_GETCOMP( pDraggedEntity, RosaCollision );
DEVASSERT( pDraggedCollision );
Vector DropLocation = pTransform->GetLocation() + m_DragDropOffset;
const Angles Orientation = pTransform->GetOrientation().Get2D();
const Angles DropOrientation = Orientation + m_DragDropOrientation;
Vector DropImpulse = Orientation.ToVector();
DropImpulse.z += m_DragDropSpawnImpulseZ;
DropImpulse.FastNormalize();
DropImpulse *= m_DragDropSpawnImpulse;
CollisionInfo Info;
Info.m_In_CollideWorld = true;
Info.m_In_CollideEntities = true;
Info.m_In_CollidingEntity = pEntity; // Using the player, not the dragged entity
Info.m_In_UserFlags = EECF_EntityCollision;
const bool FoundSpot = GetWorld()->FindSpot( DropLocation, pDraggedCollision->GetExtents(), Info );
Unused( FoundSpot );
DEVASSERT( FoundSpot );
pDraggedTransform->SetLocation( DropLocation );
pDraggedTransform->SetVelocity( pTransform->GetVelocity() );
pDraggedTransform->SetOrientation( DropOrientation );
pDraggedTransform->ApplyImpulse( DropImpulse );
pDraggedTransform->OnTeleport();
}
void WBCompRosaPlayer::EndDrag()
{
DEVASSERT( m_IsDragging );
DropDraggedEntity();
m_IsDragging = false;
m_DraggedEntity = static_cast<WBEntity*>( NULL );
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
DEVASSERT( pStatMod );
STATIC_HASHED_STRING( Dragging );
pStatMod->UnTriggerEvent( sDragging );
GetFramework()->GetInputSystem()->PopContext( m_DragInputContext );
}
void WBCompRosaPlayer::RestoreDrag()
{
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
DEVASSERT( pStatMod );
STATIC_HASHED_STRING( Dragging );
pStatMod->SetEventActive( sDragging, m_IsDragging );
if( m_IsDragging )
{
GetFramework()->GetInputSystem()->PushContext( m_DragInputContext );
}
}
bool WBCompRosaPlayer::ShouldAttachToClimbable( const WBEvent& ClimbEvent )
{
if( m_ClimbRefs > 0 )
{
// If we're already climbing, always attach to any further climbables.
return true;
}
STATIC_HASHED_STRING( UseSnapPlane );
const bool UseSnapPlane = ClimbEvent.GetBool( sUseSnapPlane );
if( !UseSnapPlane )
{
// We have no snap plane, always attach.
return true;
}
WBEntity* const pEntity = GetEntity();
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
ASSERT( pCollision );
if( !pCollision->IsLanded() )
{
// Always attach if jumping or falling.
return true;
}
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
const Vector Orientation = pTransform->GetOrientation().ToVector();
const Vector VelocityNormal = pTransform->GetVelocity().GetFastNormalized();
STATIC_HASHED_STRING( SnapPlaneNormal );
const Vector SnapPlaneNormal = ClimbEvent.GetVector( sSnapPlaneNormal );
// Cheap 90 degree rotation to get facing plane from snap plane
ASSERT( SnapPlaneNormal.z == 0.0f );
const Vector FacingPlaneNormal = Vector( -SnapPlaneNormal.y, SnapPlaneNormal.x, 0.0f );
// TODO: Configurate if needed.
static const float kCos90 = 0.0f; // Climbing angle
const float FacingDot = Orientation.Dot( FacingPlaneNormal );
const float MovingDot = VelocityNormal.Dot( FacingPlaneNormal );
if( FacingDot < kCos90 &&
MovingDot < kCos90 )
{
// We're facing the snap plane and moving toward the snap plane, so we should attach.
return true;
}
// All cases failed, don't attach.
return false;
}
void WBCompRosaPlayer::IncrementClimbRefs( const WBEvent& ClimbEvent )
{
if( ++m_ClimbRefs == 1 )
{
if( !m_IsMantling && !m_IsDragging )
{
BeginClimb( ClimbEvent );
}
}
}
void WBCompRosaPlayer::DecrementClimbRefs( const bool AddClimbOffImpulse )
{
if( m_ClimbRefs > 0 )
{
if( --m_ClimbRefs == 0 )
{
if( m_IsClimbing )
{
EndClimb( AddClimbOffImpulse );
}
}
}
}
void WBCompRosaPlayer::ZeroClimbRefs()
{
if( m_ClimbRefs > 0 )
{
m_ClimbRefs = 0;
if( m_IsClimbing )
{
EndClimb( false );
}
}
}
void WBCompRosaPlayer::BeginClimb( const WBEvent& ClimbEvent )
{
if( m_IsPowerSliding )
{
EndPowerSlide();
}
if( m_IsCrouched )
{
BeginUncrouch();
}
ASSERT( !m_IsClimbing );
m_HasDoubleJumped = false;
m_IsClimbing = true;
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
STATIC_HASHED_STRING( UseSnapPlane );
const bool UseSnapPlane = ClimbEvent.GetBool( sUseSnapPlane );
if( UseSnapPlane )
{
STATIC_HASHED_STRING( SnapPlaneDistance );
const float SnapPlaneDistance = ClimbEvent.GetFloat( sSnapPlaneDistance );
STATIC_HASHED_STRING( SnapPlaneNormal );
const Vector SnapPlaneNormal = ClimbEvent.GetVector( sSnapPlaneNormal );
const Plane SnapPlane = Plane( SnapPlaneNormal, SnapPlaneDistance );
const Vector Location = pTransform->GetLocation();
const Vector SnappedLocation = SnapPlane.ProjectPoint( Location );
pTransform->SetLocation( SnappedLocation );
}
pTransform->SetGravity( 0.0f );
pTransform->SetVelocity( Vector() );
pTransform->SetAcceleration( Vector() );
pTransform->SetRotationalVelocity( Angles() );
STATIC_HASHED_STRING( Climbing );
pStatMod->TriggerEvent( sClimbing );
GetFramework()->GetInputSystem()->PushContext( m_ClimbInputContext );
WB_MAKE_EVENT( HideHands, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), HideHands, pEntity );
}
void WBCompRosaPlayer::EndClimb( const bool AddClimbOffImpulse )
{
ASSERT( m_IsClimbing );
m_IsClimbing = false;
GetFramework()->GetInputSystem()->PopContext( m_ClimbInputContext );
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
pTransform->SetDefaultGravity();
if( AddClimbOffImpulse )
{
pTransform->ApplyImpulse( Vector( 0.0f, 0.0f, m_ClimbOffImpulse ) );
}
STATIC_HASHED_STRING( Climbing );
pStatMod->UnTriggerEvent( sClimbing );
WB_MAKE_EVENT( ShowHands, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), ShowHands, pEntity );
}
void WBCompRosaPlayer::RestoreClimb()
{
m_IsClimbing = ( m_ClimbRefs > 0 );
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
ASSERT( pStatMod );
STATIC_HASHED_STRING( Climbing );
pStatMod->SetEventActive( sClimbing, m_IsClimbing );
if( m_IsClimbing )
{
GetFramework()->GetInputSystem()->PushContext( m_ClimbInputContext );
}
}
void WBCompRosaPlayer::TryBeginMantle( const Vector& CollisionNormal )
{
if( m_IsMantling || !m_CanMantle || m_ClimbRefs > 0 )
{
return;
}
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
ASSERT( pCollision );
InputSystem* const pInputSystem = GetFramework()->GetInputSystem();
ASSERT( pInputSystem );
STATIC_HASHED_STRING( Jump );
// TODO: Configurate if needed.
static const float kCos45 = 0.707107f; // Mantle angle
const Vector Facing = pTransform->GetOrientation().ToVector2D();
// If we're facing the collision surface and falling and holding the jump button, try to mantle.
if( pCollision->IsRecentlyLanded( 0.0f ) ||
pTransform->GetVelocity().z >= 0.0f ||
Facing.Dot( CollisionNormal ) >= -kCos45 ||
!pInputSystem->IsHigh( sJump ) )
{
return;
}
RosaWorld* const pWorld = GetWorld();
DEVASSERT( pWorld );
const Vector MantleDestination = GetMantleDestination( CollisionNormal, pTransform->GetLocation(), pCollision->GetExtents() );
CollisionInfo ClearanceInfo;
ClearanceInfo.m_In_CollideWorld = true;
ClearanceInfo.m_In_CollideEntities = true;
ClearanceInfo.m_In_CollidingEntity = pEntity;
// Historically, this was always EECF_BlockerCollision (same as below but also colliding with dynamic entities);
// now I'm choosing to not collide with dynamic entities so the player can smash through windows. Potentially
// this means it could try to mantel the player up into an enemy or something, but that won't cause stuck bugs.
ClearanceInfo.m_In_UserFlags = EECF_CollideAsBlocker | EECF_CollideStaticEntities;
// Check that we still have room at our destination.
if( !pWorld->CheckClearance( MantleDestination, pCollision->GetExtents(), ClearanceInfo ) )
{
BeginMantle( MantleDestination );
return;
}
// Something is blocking the mantle; crouch and retry
if( m_IsCrouched || !CanCrouch() )
{
return;
}
Vector CrouchExtents = pCollision->GetExtents();
CrouchExtents.z = m_CrouchExtentsZ;
const Vector CrouchMantleDestination = GetMantleDestination( CollisionNormal, pTransform->GetLocation(), CrouchExtents );
if( !pWorld->CheckClearance( CrouchMantleDestination, CrouchExtents, ClearanceInfo ) )
{
Crouch();
m_IsForceCrouched = true;
BeginMantle( CrouchMantleDestination );
return;
}
}
Vector WBCompRosaPlayer::GetMantleDestination( const Vector& CollisionNormal, const Vector& Location, const Vector& Extents ) const
{
const float MantleDestinationZ = Location.z + ( Extents.z * 1.5f ); // We can climb up to 1.5x our height (TODO: configurate? might require a sweep down to be sure we don't overshoot)
const Vector MantleDestinationXY = Location - ( CollisionNormal * Extents.x * 1.414f ); // Multiply by 1.414 to be sure we'll have clearance on any angle
const Vector MantleDestination = Vector( MantleDestinationXY.x, MantleDestinationXY.y, MantleDestinationZ );
return MantleDestination;
}
void WBCompRosaPlayer::BeginMantle( const Vector& MantleDestination )
{
ASSERT( !m_IsMantling );
m_IsMantling = true;
m_HasDoubleJumped = true; // HACKHACK: We don't want to double jump during the pop off a mantel
WBEntity* const pEntity = GetEntity();
DEVASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
GetFramework()->GetInputSystem()->PushContext( m_MantleInputContext );
m_MantleDestination = MantleDestination;
// Make sure m_MantleVector has a significant component in both X/Y and Z.
// As such, it does *not* indicate the actual direction to the mantle point.
m_MantleVector = ( MantleDestination - pTransform->GetLocation() ).GetNormalized().Get2D();
m_MantleVector.z = 1.0f;
m_MantleVector.FastNormalize();
m_CanMantle = false;
WB_MAKE_EVENT( OnBeginMantle, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), OnBeginMantle, pEntity );
}
void WBCompRosaPlayer::EndMantle( const bool AllowMantle )
{
ASSERT( m_IsMantling );
m_IsMantling = false;
// DLP 18 May 2020: This used to only become true on landing;
// I'm now making it so you can continue to mantle into any
// other surface you encounter before landing, which feels
// a lot better because you keep holding the inputs and keep
// mantling as long as there's space to do so. I haven't seen
// any issues with it yet, just leaving this note here as a
// reminder in case anything wonky happens later.
// (Addendum: I added the AllowMantle flag so this does *not*
// get enabled if EndMantle is called because the input was
// released during mantling; this fixes odd repeat mantling
// if spamming the space bar to bunny hop.)
m_CanMantle = AllowMantle;
GetFramework()->GetInputSystem()->PopContext( m_MantleInputContext );
if( m_IsForceCrouched )
{
BeginUncrouch();
}
}
void WBCompRosaPlayer::TickScaleFOV( Interpolator<float>& FOVInterpolator, const float BaseFOVDegrees, const float Scale, const float Time, const float DeltaTime )
{
const float HalfFOVRadians = DEGREES_TO_RADIANS( 0.5f * BaseFOVDegrees );
const float HalfScaledFOVRadians = ATan( Scale * Tan( HalfFOVRadians ) );
const float ScaledFOVDegrees = 2.0f * RADIANS_TO_DEGREES( HalfScaledFOVRadians );
if( FOVInterpolator.GetValue() == 0.0f )
{
// Instantly reset FOV to the target if we don't have a valid current value.
FOVInterpolator.Reset( ScaledFOVDegrees );
}
if( FOVInterpolator.GetEndValue() != ScaledFOVDegrees )
{
// If the target FOV changes, restart the lerp.
FOVInterpolator.Reset( Interpolator<float>::EIT_Linear, FOVInterpolator.GetValue(), ScaledFOVDegrees, Time );
}
FOVInterpolator.Tick( DeltaTime );
}
void WBCompRosaPlayer::SetSpawnPoint()
{
ASSERT( !m_HasSetSpawnPoint );
WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
m_SpawnLocation = pTransform->GetLocation();
m_SpawnOrientation = pTransform->GetOrientation();
m_HasSetSpawnPoint = true;
}
void WBCompRosaPlayer::RestoreSpawnPoint()
{
ASSERT( m_HasSetSpawnPoint );
WBEntity* const pEntity = GetEntity();
ASSERT( pEntity );
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
ASSERT( pTransform );
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
ASSERT( pCollision );
RosaWorld* const pWorld = GetWorld();
DEVASSERT( pWorld );
CollisionInfo Info;
Info.m_In_CollideWorld = true;
Info.m_In_CollideEntities = true;
Info.m_In_CollidingEntity = pEntity;
Info.m_In_UserFlags = EECF_BlockerCollision;
Vector SpawnLocation = m_SpawnLocation;
const bool FoundSpot = pWorld->FindSpot( SpawnLocation, pCollision->GetExtents(), Info );
ASSERT( FoundSpot );
pTransform->SetLocation( SpawnLocation );
pTransform->SetVelocity( Vector() );
pTransform->SetAcceleration( Vector() );
pTransform->SetOrientation( m_SpawnOrientation );
if( m_IsCrouched )
{
BeginUncrouch();
}
}
void WBCompRosaPlayer::TeleportTo( const HashedString& TeleportLabel )
{
if( TeleportLabel == HashedString::NullString )
{
return;
}
WBEntity* const pTeleportTarget = WBCompLabel::GetEntityByLabel( TeleportLabel );
if( !pTeleportTarget )
{
return;
}
WBCompRosaTransform* pTeleportTransform = pTeleportTarget->GetTransformComponent<WBCompRosaTransform>();
if( !pTeleportTransform )
{
return;
}
WBCompRosaTransform* pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>();
ASSERT( pTransform );
pTransform->SetLocation( pTeleportTransform->GetLocation() );
pTransform->SetVelocity( Vector() );
pTransform->SetAcceleration( Vector() );
pTransform->SetOrientation( pTeleportTransform->GetOrientation() );
}
#if BUILD_DEV
/*virtual*/ void WBCompRosaPlayer::Report() const
{
Super::Report();
PRINTF( WBPROPERTY_REPORT_PREFIX "Autosave Suppression Refcount: %d/%d\n", m_AutosaveSuppRefsSerialized, m_AutosaveSuppRefsTransient );
}
/*virtual*/ void WBCompRosaPlayer::DebugRender( const bool GroupedRender ) const
{
Super::DebugRender( GroupedRender );
RosaFramework* const pFramework = GetFramework();
IRenderer* const pRenderer = pFramework->GetRenderer();
View* const pView = pFramework->GetMainView();
Display* const pDisplay = pFramework->GetDisplay();
WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>();
DEVASSERT( pTransform );
const Vector Location = pTransform->GetLocation();
const float ClockMultiplier = m_DEVHACKClockMultiplier ? m_DEVHACKClockMultiplier->m_Multiplier : 1.0f;
pRenderer->DEBUGPrint( SimpleString::PrintF( "%s Clock multiplier: %.2f", DebugRenderLineFeed().CStr(), ClockMultiplier ), Location, pView, pDisplay, DEFAULT_FONT_TAG, ARGB_TO_COLOR( 255, 255, 255, 255 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) );
pRenderer->DEBUGPrint( SimpleString::PrintF( "%s Fixed time scalar: %.2f", DebugRenderLineFeed().CStr(), pFramework->DEV_GetFixedTimeScalar() ), Location, pView, pDisplay, DEFAULT_FONT_TAG, ARGB_TO_COLOR( 255, 255, 255, 255 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) );
// (These are going to be the previous frame's stats, obviously.)
const IRenderer::SDEV_RenderStats& RenderStats = pRenderer->DEV_GetStats();
// Print renderer stats in the top left, not on the player entity.
// TODO: I don't feel like writing a whole system to display real-time stats from multiple sources right now. But I should.
pRenderer->DEBUGPrint( SimpleString::PrintF(
"Avg FPS: %d\nAvg frame time: %.3fms\nRender time: %.3fms\nRendered meshes: %d\nRendered draw calls: %d\n"
"Rendered shadow lights: %d\nRendered shadow meshes: %d\nShadow time: %.3fms\n"
"TickSim time: %.3fms (min %.3fms / max %.3fms)\n"
"TickRender time: %.3fms (min %.3fms / max %.3fms)",
RoundToUInt( RenderStats.m_AvgFPS ), 1000.0f / RenderStats.m_AvgFPS, GET_CLOCK_MS( RenderStats.m_RenderTime ), RenderStats.m_NumMeshes, RenderStats.m_NumDrawCalls,
RenderStats.m_NumShadowLights, RenderStats.m_NumShadowMeshes, GET_CLOCK_MS( RenderStats.m_ShadowTime ),
GET_CLOCK_MS( pFramework->DEV_GetSimTime() ), GET_CLOCK_MS( pFramework->DEV_GetSimTimeMin() ), GET_CLOCK_MS( pFramework->DEV_GetSimTimeMax() ),
GET_CLOCK_MS( pFramework->DEV_GetRenderTime() ), GET_CLOCK_MS( pFramework->DEV_GetRenderTimeMin() ), GET_CLOCK_MS( pFramework->DEV_GetRenderTimeMax() ) ),
SRect( 100.0f, 100.0f, 0.0f, 0.0f ), DEFAULT_MONOSPACED_FONT_TAG, ARGB_TO_COLOR( 255, 255, 255, 255 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) );
// Display relevant shadow-casting lights and the number of meshes drawn for each.
// It makes sense to do this here instead of a debug display on the light component,
// because we want to see all lights, and also we don't have rendered numbers on the
// light components. I might comment this out too.
FOR_EACH_ARRAY( ShadowLightIter, RenderStats.m_ShadowLights, IRenderer::SDEV_RenderStats::SDEV_ShadowLight )
{
const IRenderer::SDEV_RenderStats::SDEV_ShadowLight& ShadowLight = ShadowLightIter.GetValue();
//pRenderer->DEBUGDrawSphere( ShadowLight.m_Location, ShadowLight.m_Radius, ARGB_TO_COLOR( 255, 255, 255, 255 ), false );
pRenderer->DEBUGDrawCross( ShadowLight.m_Location, 1.0f, ARGB_TO_COLOR( 255, 255, 255, 255 ), false );
pRenderer->DEBUGPrint(
SimpleString::PrintF( "%d", ShadowLight.m_NumMeshes ),
ShadowLight.m_Location,
pView,
pDisplay,
DEFAULT_FONT_TAG,
ARGB_TO_COLOR( 255, 255, 255, 0 ),
ARGB_TO_COLOR( 255, 0, 0, 0 ) );
}
const uint NumPathSteps = m_CAMHACKPathData.m_Path.Size();
for( uint PathIndex = 1; PathIndex < NumPathSteps; ++PathIndex )
{
const Vector& PrevStep = m_CAMHACKPathData.m_Path[ PathIndex - 1 ];
const Vector& NextStep = m_CAMHACKPathData.m_Path[ PathIndex ];
pRenderer->DEBUGDrawLine( PrevStep, NextStep, ARGB_TO_COLOR( 255, 255, 0, 0 ) );
}
uint NavNodeIndex;
if( GetWorld()->FindNavNodeUnder( Location, NavNodeIndex ) )
{
static const Vector skNavNodeOffset = Vector( 0.0f, 0.0f, 0.01f );
const SNavNode& NavNode = GetWorld()->GetNavNode( NavNodeIndex );
// Draw the tri raised slightly and with each vert moved slightly toward centroid so it doesn't z-fight geo
pRenderer->DEBUGDrawTriangle(
NavNode.m_Tri.m_Vec1 + skNavNodeOffset + 0.01f * ( NavNode.m_Centroid - NavNode.m_Tri.m_Vec1 ).GetFastNormalized(),
NavNode.m_Tri.m_Vec2 + skNavNodeOffset + 0.01f * ( NavNode.m_Centroid - NavNode.m_Tri.m_Vec2 ).GetFastNormalized(),
NavNode.m_Tri.m_Vec3 + skNavNodeOffset + 0.01f * ( NavNode.m_Centroid - NavNode.m_Tri.m_Vec3 ).GetFastNormalized(),
ARGB_TO_COLOR( 255, 255, 128, 0 ) );
if( NavNode.m_Props != ENP_None )
{
pRenderer->DEBUGPrint( SimpleString::PrintF( "%sNav node props: 0x%08X", DebugRenderLineFeed().CStr(), NavNode.m_Props ), Location, pView, pDisplay, DEFAULT_FONT_TAG, ARGB_TO_COLOR( 255, 255, 128, 0 ), ARGB_TO_COLOR( 255, 0, 0, 0 ) );
}
}
for( float Radius = m_CACHED_LastAINoiseRadius; Radius > 0.0f; Radius -= 1.0f )
{
pRenderer->DEBUGDrawCircleXY( m_CACHED_LastAINoiseSourceLocation, Radius, ARGB_TO_COLOR( 255, 255, 255, 0 ) );
}
}
#endif // BUILD_DEV
#if BUILD_DEV
void WBCompRosaPlayer::DEVHACKInput()
{
WBEntity* const pEntity = GetEntity();
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
WBCompRosaCamera* const pCamera = WB_GETCOMP( pEntity, RosaCamera );
WBCompRosaKeyRing* const pKeyRing = WB_GETCOMP( pEntity, RosaKeyRing );
WBCompRosaVisible* const pVisible = WB_GETCOMP( pEntity, RosaVisible );
WBCompRosaFootsteps* const pFootsteps = WB_GETCOMP( pEntity, RosaFootsteps );
RosaWorld* const pWorld = GetWorld();
RosaFramework* const pFramework = GetFramework();
Keyboard* const pKeyboard = pFramework->GetKeyboard();
// G (no Alt): Hide hands and HUD, Shift + G: re-show
if( pKeyboard->IsLow( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_G ) )
{
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) )
{
WB_MAKE_EVENT( ForceShowHands, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), ForceShowHands, pEntity );
STATIC_HASHED_STRING( HUD );
WB_MAKE_EVENT( RepushUIScreen, NULL );
WB_SET_AUTO( RepushUIScreen, Hash, Screen, sHUD );
WB_DISPATCH_EVENT( GetEventManager(), RepushUIScreen, NULL );
}
else
{
WB_MAKE_EVENT( HideHands, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), HideHands, pEntity );
STATIC_HASHED_STRING( HUD );
WB_MAKE_EVENT( RemoveUIScreen, NULL );
WB_SET_AUTO( RemoveUIScreen, Hash, Screen, sHUD );
WB_DISPATCH_EVENT( GetEventManager(), RemoveUIScreen, NULL );
}
}
#if BUILD_WINDOWS
if( pKeyboard->OnRise( Keyboard::EB_Grave ) )
{
Console::Toggle();
}
#endif
if( pKeyboard->OnRise( Keyboard::EB_LeftBrace ) )
{
m_DebugSpawnerIndex = ( m_DebugSpawnerIndex + m_DebugSpawners.Size() - 1 ) % m_DebugSpawners.Size();
PRINTF( "Next entity: %s\n", m_DebugSpawners[ m_DebugSpawnerIndex ].m_Entity.CStr() );
}
if( pKeyboard->OnRise( Keyboard::EB_RightBrace ) )
{
m_DebugSpawnerIndex = ( m_DebugSpawnerIndex + 1 ) % m_DebugSpawners.Size();
PRINTF( "Next entity: %s\n", m_DebugSpawners[ m_DebugSpawnerIndex ].m_Entity.CStr() );
}
// Numpad +/-: time dilation (use Ctrl to test clock multiplier instead of fixed frame time hack; ideal for slowing the game instead of speeding it up)
if( pKeyboard->OnRise( Keyboard::EB_NumAdd ) || pKeyboard->OnRise( Keyboard::EB_NumSubtract ) )
{
const float Scalar = pKeyboard->OnRise( Keyboard::EB_NumAdd ) ? 2.0f : 0.5f;
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Control ) )
{
const float NewMultiplier = m_DEVHACKClockMultiplier ? ( Scalar * m_DEVHACKClockMultiplier->m_Multiplier ) : Scalar;
if( m_DEVHACKClockMultiplier )
{
pFramework->GetClock()->RemoveMultiplierRequest( &m_DEVHACKClockMultiplier );
}
if( NewMultiplier != 1.0f )
{
m_DEVHACKClockMultiplier = pFramework->GetClock()->AddMultiplierRequest( 0.0f, NewMultiplier );
}
}
else
{
pFramework->DEV_SetFixedTimeScalar( Scalar * pFramework->DEV_GetFixedTimeScalar() );
}
}
// Right shift: debug render targeted entity
// (This is pretty basic, but it works to debug enemies, which is the main purpose)
if( pKeyboard->OnRise( Keyboard::EB_RightShift ) )
{
WBEntityRef OldTarget = m_DEVHACKDebugTarget;
m_DEVHACKDebugTarget = NULL;
// DLP 5 Dec 2021: First try the frob and aim targets, then trace if needed
WBCompRosaFrobber* const pFrobber = WB_GETCOMP( pEntity, RosaFrobber );
DEVASSERT( pFrobber );
m_DEVHACKDebugTarget = pFrobber->GetFrobTarget();
if( !m_DEVHACKDebugTarget )
{
m_DEVHACKDebugTarget = pFrobber->GetAimTarget();
}
if( !m_DEVHACKDebugTarget )
{
const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() );
const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector();
const Ray TraceRay = Ray( EyeLoc, EyeDir );
CollisionInfo Info;
Info.m_In_CollideWorld = true;
Info.m_In_CollideEntities = true;
Info.m_In_CollidingEntity = GetEntity();
Info.m_In_UserFlags = EECF_Trace | EECF_CollideBones;
if( pWorld->Trace( TraceRay, Info ) )
{
WBEntity* const pHitEntity = static_cast<WBEntity*>( Info.m_Out_HitEntity );
m_DEVHACKDebugTarget = pHitEntity;
}
}
// Targeting nothing; focus on self, then unfocus
if( !m_DEVHACKDebugTarget )
{
if( OldTarget == GetEntity() )
{
// Do nothing (unfocus)
}
else
{
m_DEVHACKDebugTarget = GetEntity();
}
}
if( OldTarget != m_DEVHACKDebugTarget )
{
if( OldTarget.Get() )
{
OldTarget.Get()->SetShouldDebugRender( false );
}
if( m_DEVHACKDebugTarget )
{
m_DEVHACKDebugTarget.Get()->SetShouldDebugRender( true );
}
}
}
if( pKeyboard->OnRise( Keyboard::EB_PageDown ) )
{
if( m_DEVHACKDebugTarget )
{
m_DEVHACKDebugTarget.Get()->GoToNextDebugRenderComponent();
}
else
{
m_DEVHACKDebugTarget = GetEntity();
m_DEVHACKDebugTarget.Get()->SetShouldDebugRender( true );
}
}
if( pKeyboard->OnRise( Keyboard::EB_PageUp ) )
{
if( m_DEVHACKDebugTarget )
{
m_DEVHACKDebugTarget.Get()->GoToPrevDebugRenderComponent();
}
else
{
m_DEVHACKDebugTarget = GetEntity();
m_DEVHACKDebugTarget.Get()->SetShouldDebugRender( true );
m_DEVHACKDebugTarget.Get()->GoToPrevDebugRenderComponent();
}
}
// X: Teleport to trace destination
if( pKeyboard->OnRise( Keyboard::EB_X ) )
{
const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() );
const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector();
const Ray TraceRay = Ray( EyeLoc, EyeDir );
CollisionInfo Info;
Info.m_In_CollideWorld = true;
Info.m_In_CollideEntities = true;
Info.m_In_CollidingEntity = GetEntity();
Info.m_In_UserFlags = EECF_BlockerCollision;
if( pWorld->Trace( TraceRay, Info ) )
{
Vector Destination = Info.m_Out_Intersection + Info.m_Out_Plane.m_Normal * 0.1f;
if( pWorld->FindSpot( Destination, pCollision->GetExtents(), Info ) )
{
pTransform->SetLocation( Destination );
}
}
}
// Alt + K: Kill all enemies
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) &&
pKeyboard->OnRise( Keyboard::EB_K ) &&
!pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) &&
!pKeyboard->IsHigh( Keyboard::EB_V ) )
{
Array<WBEntity*> AllEntities;
WBScene::GetDefault()->GetAllEntities( AllEntities );
FOR_EACH_ARRAY( EntityIter, AllEntities, WBEntity* )
{
WBEntity* const pIterEntity = EntityIter.GetValue();
if( pIterEntity == pEntity )
{
continue;
}
if( WBCompRosaFaction::GetCon( pEntity, pIterEntity ) != RosaFactions::EFR_Hostile )
{
continue;
}
WB_MAKE_EVENT( Kill, pIterEntity );
WB_SET_AUTO( Kill, Entity, Damager, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), Kill, pIterEntity );
}
}
// Alt + L: Print player location and heading to log
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_L ) && !pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) )
{
PRINTF( "Player location: %s\n", pTransform->GetLocation().GetString().CStr() );
PRINTF( "Player direction: %s\n", pTransform->GetOrientation().ToVector().GetString().CStr() );
}
// Alt + M: Give master key
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_M ) )
{
STATIC_HASHED_STRING( Keycard_MASTER );
pKeyRing->AddKeycard( sKeycard_MASTER, true );
}
// Alt + O: Toggle invisible, silent, noclip
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_O ) )
{
const bool CheatOn = pVisible->IsVisible();
pVisible->SetVisible( !CheatOn );
if( pFootsteps )
{
pFootsteps->SetFootstepsDisabled( CheatOn );
}
}
// V: Spawn entity
if( !pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_V ) )
{
const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() );
const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector();
const Ray TraceRay( EyeLoc, EyeDir );
CollisionInfo TraceInfo;
TraceInfo.m_In_CollideWorld = true;
TraceInfo.m_In_UserFlags = EECF_CollideAsEntity;
if( pWorld->Trace( TraceRay, TraceInfo ) )
{
const SDebugSpawner& Spawner = m_DebugSpawners[ m_DebugSpawnerIndex ];
WBEntity* pSpawnedEntity = WBWorld::GetInstance()->CreateEntity( Spawner.m_Entity );
WBCompRosaTransform* pSpawnedTransform = pSpawnedEntity->GetTransformComponent<WBCompRosaTransform>();
if( pSpawnedTransform )
{
Vector SpawnLocation = TraceInfo.m_Out_Intersection + TraceInfo.m_Out_Plane.m_Normal * Spawner.m_NormalDistance * pSpawnedTransform->GetScale() + Spawner.m_Offset;
WBCompRosaCollision* pSpawnedCollision = WB_GETCOMP( pSpawnedEntity, RosaCollision );
if( pSpawnedCollision )
{
CollisionInfo FindSpotInfo;
FindSpotInfo.m_In_CollideWorld = true;
FindSpotInfo.m_In_CollideEntities = true;
FindSpotInfo.m_In_CollidingEntity = pSpawnedEntity;
FindSpotInfo.m_In_UserFlags = EECF_EntityCollision;
pWorld->FindSpot( SpawnLocation, pSpawnedCollision->GetExtents(), FindSpotInfo );
}
pSpawnedTransform->SetInitialTransform( SpawnLocation, Angles() );
}
}
}
// Alt+LMB: Test pathfinding from current loc to wherever we're aiming
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_Mouse_Left ) )
{
const Vector EyeLoc = pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() );
const Vector EyeDir = pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ).ToVector();
const Ray TraceRay( EyeLoc, EyeDir );
CollisionInfo Info;
Info.m_In_CollideWorld = true;
Info.m_In_UserFlags = EECF_CollideAsEntity;
if( pWorld->Trace( TraceRay, Info ) )
{
const Vector HitLoc = Info.m_Out_Intersection + Info.m_Out_Plane.m_Normal * 0.1f;
m_CAMHACKPathData.m_Params.m_PathMode = RosaNav::EPM_Search;
m_CAMHACKPathData.m_Params.m_Start = pTransform->GetLocation();
m_CAMHACKPathData.m_Params.m_Destination = HitLoc;
m_CAMHACKPathData.m_Params.m_AgentHeight = pCollision->GetExtents().z * 2.0f;
m_CAMHACKPathData.m_Params.m_AgentRadius = pCollision->GetExtents().x * 1.414f;
m_CAMHACKPathData.m_Params.m_MotionType = RosaNav::EMT_Walking;
m_CAMHACKPathData.m_Params.m_CanOpenDoors = true;
m_CAMHACKPathData.m_Params.m_MaxSteps = 1000;
m_CAMHACKPathData.m_Params.m_UsePartialPath = true;
#if BUILD_DEBUG
m_CAMHACKPathData.m_Params.m_Verbose = true;
#endif
RosaNav::GetInstance()->FindPath( m_CAMHACKPathData );
}
}
// Alt + G: ghost (no collision, no gravity), Shift + Alt + G: disable ghost
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->OnRise( Keyboard::EB_G ) )
{
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Shift ) )
{
pCollision->ResetCollisionFlags();
WB_MAKE_EVENT( StopFlying, GetEntity() );
WB_DISPATCH_EVENT( GetEventManager(), StopFlying, GetEntity() );
}
else
{
pCollision->SetCollisionFlags( 0 );
WB_MAKE_EVENT( StartFlying, GetEntity() );
WB_DISPATCH_EVENT( GetEventManager(), StartFlying, GetEntity() );
}
}
// Camera hacks: Alt + V + ... (Used to be Shift + C + ...)
if( pKeyboard->IsHigh( Keyboard::EB_Virtual_Alt ) && pKeyboard->IsHigh( Keyboard::EB_V ) )
{
//WBCompRosaTransform* const pTransform = GetEntity()->GetTransformComponent<WBCompRosaTransform>();
//WBCompRosaCollision* const pCollision = WB_GETCOMP( GetEntity(), RosaCollision );
//WBCompRosaHealth* const pHealth = WB_GETCOMP( GetEntity(), RosaHealth );
//WBCompRosaWallet* const pWallet = WB_GETCOMP( GetEntity(), RosaWallet );
//WBCompRosaKeyRing* const pKeyRing = WB_GETCOMP( GetEntity(), RosaKeyRing );
if( pKeyboard->OnRise( Keyboard::EB_U ) )
{
m_CAMHACKCamVelocity *= 0.8f;
PRINTF( "m_CAMHACKCamVelocity: %f\n", m_CAMHACKCamVelocity );
}
if( pKeyboard->OnRise( Keyboard::EB_P ) )
{
m_CAMHACKCamVelocity *= 1.25f;
PRINTF( "m_CAMHACKCamVelocity: %f\n", m_CAMHACKCamVelocity );
}
if( pKeyboard->OnRise( Keyboard::EB_J ) )
{
m_CAMHACKCamStartLocation = pTransform->GetLocation();
m_CAMHACKCamStartOrientation = pTransform->GetOrientation();
PRINTF( "Start point set\n" );
}
if( pKeyboard->OnRise( Keyboard::EB_K ) )
{
m_CAMHACKCamEndLocation = pTransform->GetLocation();
m_CAMHACKCamEndOrientation = pTransform->GetOrientation();
PRINTF( "End point set\n" );
}
if( pKeyboard->OnRise( Keyboard::EB_L ) )
{
PRINTF( "Toggled\n" );
m_CAMHACKCamActive = !m_CAMHACKCamActive;
if( m_CAMHACKCamActive )
{
if( m_CAMHACKCamStartLocation.IsZero() || m_CAMHACKCamEndLocation.IsZero() )
{
// Don't interpolate, it will cause problems.
m_CAMHACKCamActive = false;
}
else
{
pCollision->SetCollisionFlags( 0 );
pTransform->SetGravity( 0.0f );
if( pFootsteps )
{
pFootsteps->SetFootstepsDisabled( true );
}
WB_MAKE_EVENT( HideHands, GetEntity() );
WB_DISPATCH_EVENT( GetEventManager(), HideHands, GetEntity() );
const float Distance = ( m_CAMHACKCamStartLocation - m_CAMHACKCamEndLocation ).Length();
const float Duration = Distance / m_CAMHACKCamVelocity;
m_CAMHACKCamLocation.Reset( Interpolator<Vector>::EIT_Linear, m_CAMHACKCamStartLocation, m_CAMHACKCamEndLocation, Duration );
m_CAMHACKCamOrientation.Reset( Interpolator<Angles>::EIT_Linear, m_CAMHACKCamStartOrientation, m_CAMHACKCamEndOrientation, Duration );
STATIC_HASHED_STRING( HUD );
WB_MAKE_EVENT( RemoveUIScreen, NULL );
WB_SET_AUTO( RemoveUIScreen, Hash, Screen, sHUD );
WB_DISPATCH_EVENT( GetEventManager(), RemoveUIScreen, NULL );
}
}
else
{
pCollision->ResetCollisionFlags();
pTransform->SetDefaultGravity();
if( pFootsteps )
{
pFootsteps->SetFootstepsDisabled( false );
}
WB_MAKE_EVENT( ShowHands, GetEntity() );
WB_DISPATCH_EVENT( GetEventManager(), ShowHands, GetEntity() );
STATIC_HASHED_STRING( HUD );
WB_MAKE_EVENT( RepushUIScreen, NULL );
WB_SET_AUTO( RepushUIScreen, Hash, Screen, sHUD );
WB_DISPATCH_EVENT( GetEventManager(), RepushUIScreen, NULL );
}
}
}
}
#endif // BUILD_DEV
/*virtual*/ void WBCompRosaPlayer::HandleEvent( const WBEvent& Event )
{
XTRACE_FUNCTION;
Super::HandleEvent( Event );
// Forward all events the player receives to the game and world
GetGame()->HandleEvent( Event );
GetWorld()->HandleEvent( Event );
STATIC_HASHED_STRING( OnSpawned );
STATIC_HASHED_STRING( OnLoaded );
STATIC_HASHED_STRING( CycleMenuDifficulty );
STATIC_HASHED_STRING( SetMenuDifficulty );
STATIC_HASHED_STRING( OnInitialized );
STATIC_HASHED_STRING( OnAutosave );
STATIC_HASHED_STRING( AddAutosaveSuppression );
STATIC_HASHED_STRING( RemoveAutosaveSuppression );
STATIC_HASHED_STRING( StartDrag );
STATIC_HASHED_STRING( StopDrag );
STATIC_HASHED_STRING( OnTouchedClimbable );
STATIC_HASHED_STRING( OnUntouchedClimbable );
STATIC_HASHED_STRING( OnJumped );
STATIC_HASHED_STRING( OnLanded );
STATIC_HASHED_STRING( OnCollided );
STATIC_HASHED_STRING( OnSteppedUp );
STATIC_HASHED_STRING( OnKickImpulse );
STATIC_HASHED_STRING( PreLevelTransition );
STATIC_HASHED_STRING( PostLevelTransition );
STATIC_HASHED_STRING( PushInputContext );
STATIC_HASHED_STRING( PopInputContext );
STATIC_HASHED_STRING( DisablePause );
STATIC_HASHED_STRING( EnablePause );
STATIC_HASHED_STRING( PushPersistence );
STATIC_HASHED_STRING( PullPersistence );
STATIC_HASHED_STRING( OnAINoise );
STATIC_HASHED_STRING( OnFOVChanged );
STATIC_HASHED_STRING( SlamFOVScale );
STATIC_HASHED_STRING( SetInitialMusicTrackBits );
STATIC_HASHED_STRING( StartFlying );
STATIC_HASHED_STRING( StopFlying );
STATIC_HASHED_STRING( OnDied );
const HashedString EventName = Event.GetEventName();
if( EventName == sOnSpawned )
{
SetCrouchOverlayHidden( true );
QueueAutosave( m_RollingAutosaveDelay );
// Update from difficulty system
RosaDifficulty::PushMenuToGame();
}
else if( EventName == sOnLoaded )
{
RestoreCrouch();
RestorePowerSlide();
RestoreDrag();
RestoreClimb();
// Notify difficulty system (if we're traveling with persistence, we pull that later)
RosaDifficulty::PushGameToMenu();
}
else if( EventName == sCycleMenuDifficulty || EventName == sSetMenuDifficulty )
{
// Update from difficulty system
RosaDifficulty::PushMenuToGame();
}
else if( EventName == sOnInitialized )
{
// In case user switches away from game and we end up paused
// before playing new music, stop the old music (and ambience!) immediately.
WB_MAKE_EVENT( StopMusicAndAmbience, NULL );
WB_DISPATCH_EVENT( GetEventManager(), StopMusicAndAmbience, GetGame() );
// HACKHACK: The grossest hack. Since I'm (currently!) only using this to defer
// music in RosaIntro, ignore it on subsequent initializations so returning to
// the title will play music the usual way. Gross!
static bool CanDeferMusic = true;
if( m_DeferMusic && CanDeferMusic )
{
CanDeferMusic = false;
// Do nothing, something else will play music later
}
else
{
WB_MAKE_EVENT( PlayMusicAndAmbience, NULL );
WB_SET_AUTO( PlayMusicAndAmbience, Int, TrackBits, m_InitialMusicTrackBits );
WB_DISPATCH_EVENT( GetEventManager(), PlayMusicAndAmbience, GetGame() ); // ROSANOTE: Since Eldritch, this had always been delayed by one tick. Can't remember why.
}
}
else if( EventName == sOnAutosave )
{
if( CanAutosave() )
{
// Queue the next one *before* autosaving so the queued event gets saved.
QueueAutosave( m_RollingAutosaveDelay );
GetGame()->Autosave();
}
else
{
QueueAutosave( m_RetryAutosaveDelay );
}
}
else if( EventName == sAddAutosaveSuppression )
{
STATIC_HASHED_STRING( Serialize );
const bool Serialize = Event.GetBool( sSerialize );
AddAutosaveSuppression( Serialize );
}
else if( EventName == sRemoveAutosaveSuppression )
{
STATIC_HASHED_STRING( Serialize );
const bool Serialize = Event.GetBool( sSerialize );
RemoveAutosaveSuppression( Serialize );
}
else if( EventName == sStartDrag )
{
STATIC_HASHED_STRING( DraggedEntity );
WBEntity* const pDraggedEntity = Event.GetEntity( sDraggedEntity );
DEVASSERT( pDraggedEntity );
BeginDrag( pDraggedEntity );
}
else if( EventName == sStopDrag )
{
#if BUILD_DEV
// Validate that we're stopping the actual dragged entity
STATIC_HASHED_STRING( DraggedEntity );
WBEntity* const pDraggedEntity = Event.GetEntity( sDraggedEntity );
DEVASSERT( pDraggedEntity );
DEVASSERT( pDraggedEntity == m_DraggedEntity.Get() );
#endif
EndDrag();
}
else if( EventName == sOnTouchedClimbable )
{
if( ShouldAttachToClimbable( Event ) )
{
IncrementClimbRefs( Event );
}
}
else if( EventName == sOnUntouchedClimbable )
{
const bool AddClimbOffImpulse = true;
DecrementClimbRefs( AddClimbOffImpulse );
}
else if( EventName == sOnLanded )
{
if( !m_HasSetSpawnPoint )
{
SetSpawnPoint();
}
m_HasDoubleJumped = false;
m_CanMantle = true;
ZeroClimbRefs();
// Force a footstep on landed, with a timeout to prevent relanded events from making more footsteps
WBEntity* const pEntity = GetEntity();
WBCompRosaCollision* const pCollision = WB_GETCOMP( pEntity, RosaCollision );
if( !pCollision->IsRecentlyLanded( m_UnlandedForceFootstepWindow ) )
{
// Pass landed magnitude through as additional speed
STATIC_HASHED_STRING( LandedMagnitude );
const float LandedMagnitude = Event.GetFloat( sLandedMagnitude );
WB_MAKE_EVENT( ForceFootstep, GetEntity() );
WB_SET_AUTO( ForceFootstep, Float, AdditionalSpeed, LandedMagnitude );
WB_DISPATCH_EVENT( GetEventManager(), ForceFootstep, GetEntity() );
}
if( m_IsForceCrouched )
{
BeginUncrouch();
}
}
else if( EventName == sOnCollided )
{
if( m_IsPowerSliding )
{
EndPowerSlide();
}
STATIC_HASHED_STRING( CollidedEntity );
WBEntity* const pCollidedEntity = Event.GetEntity( sCollidedEntity );
WBCompRosaCollision* const pCollidedCollision = WB_GETCOMP_SAFE( pCollidedEntity, RosaCollision );
if( pCollidedCollision && pCollidedCollision->IsDynamicBlocker() )
{
// Collided entity is a blocker (a dynamic entity that blocks other entities). Do not attempt to mantle onto it.
}
else
{
STATIC_HASHED_STRING( CollisionNormal );
const Vector CollisionNormal = Event.GetVector( sCollisionNormal );
TryBeginMantle( CollisionNormal );
}
}
else if( EventName == sOnSteppedUp )
{
STATIC_HASHED_STRING( StepHeight );
const float StepHeight = Event.GetFloat( sStepHeight );
OnSteppedUp( StepHeight );
}
else if( EventName == sOnKickImpulse )
{
STATIC_HASHED_STRING( KickImpulse );
const Angles KickImpulse = Event.GetAngles( sKickImpulse );
m_KickVelocity += KickImpulse;
}
else if( EventName == sPreLevelTransition )
{
WB_MAKE_EVENT( PushPersistence, GetEntity() );
WB_DISPATCH_EVENT( GetEventManager(), PushPersistence, GetEntity() );
}
else if( EventName == sPostLevelTransition )
{
const TPersistence& Persistence = RosaGame::StaticGetTravelPersistence();
if( Persistence.Size() )
{
WB_MAKE_EVENT( PullPersistence, GetEntity() );
WB_DISPATCH_EVENT( GetEventManager(), PullPersistence, GetEntity() );
}
STATIC_HASHED_STRING( RestoreSpawnPoint );
const bool ShouldRestoreSpawnPoint = Event.GetBool( sRestoreSpawnPoint );
STATIC_HASHED_STRING( TeleportLabel );
const HashedString TeleportLabel = Event.GetHash( sTeleportLabel );
if( TeleportLabel != HashedString::NullString )
{
TeleportTo( TeleportLabel );
}
else if( ShouldRestoreSpawnPoint && m_HasSetSpawnPoint )
{
RestoreSpawnPoint();
}
}
else if( EventName == sPushInputContext )
{
STATIC_HASHED_STRING( InputContext );
const HashedString InputContext = Event.GetHash( sInputContext );
GetFramework()->GetInputSystem()->PushContext( InputContext );
}
else if( EventName == sPopInputContext )
{
STATIC_HASHED_STRING( InputContext );
const HashedString InputContext = Event.GetHash( sInputContext );
GetFramework()->GetInputSystem()->PopContext( InputContext );
}
else if( EventName == sDisablePause )
{
m_IsDisablingPause = true;
}
else if( EventName == sEnablePause )
{
m_IsDisablingPause = false;
}
else if( EventName == sPushPersistence )
{
PushPersistence();
}
else if( EventName == sPullPersistence )
{
PullPersistence();
}
else if( EventName == sOnAINoise )
{
#if BUILD_DEV
STATIC_HASHED_STRING( EventOwner );
WBEntity* const pEventOwner = Event.GetEntity( sEventOwner );
ASSERT( pEventOwner );
STATIC_HASHED_STRING( NoiseEntity );
WBEntity* const pNoiseEntity = Event.GetEntity( sNoiseEntity, pEventOwner );
if( pNoiseEntity == GetEntity() )
{
STATIC_HASHED_STRING( NoiseLocation );
const Vector NoiseEntityLocation = pEventOwner->GetTransformComponent<WBCompRosaTransform>()->GetLocation();
const Vector NoiseLocation = Event.GetVector( sNoiseLocation, NoiseEntityLocation );
DEVASSERT( !NoiseLocation.IsZero() );
STATIC_HASHED_STRING( NoiseSourceLocation );
const Vector NoiseSourceLocation = Event.GetVector( sNoiseSourceLocation );
m_CACHED_LastAINoiseSourceLocation = NoiseSourceLocation.IsZero() ? NoiseLocation : NoiseSourceLocation;
STATIC_HASHED_STRING( NoiseRadius );
m_CACHED_LastAINoiseRadius = Event.GetFloat( sNoiseRadius );
}
#endif
}
else if( EventName == sOnFOVChanged )
{
STATICHASH( FOV );
m_CurrentFOV.Reset( ConfigManager::GetFloat( sFOV ) );
}
else if( EventName == sSlamFOVScale )
{
// HACKHACK for Intro hub wake-up moment, mainly
STATICHASH( FOVScale );
const float FOVScale = Event.GetFloat( sFOVScale );
STATICHASH( FOV );
STATICHASH( ForegroundFOV );
TickScaleFOV( m_CurrentFOV, ConfigManager::GetFloat( sFOV ), FOVScale, 0.0f, 0.0f );
TickScaleFOV( m_CurrentFGFOV, ConfigManager::GetFloat( sForegroundFOV ), FOVScale, 0.0f, 0.0f );
GetFramework()->SetFOV( m_CurrentFOV.GetValue() );
GetFramework()->SetFGFOV( m_CurrentFGFOV.GetValue() );
}
else if( EventName == sSetInitialMusicTrackBits )
{
STATIC_HASHED_STRING( InitialMusicTrackBits );
const uint InitialMusicTrackBits = Event.GetInt( sInitialMusicTrackBits );
m_InitialMusicTrackBits = InitialMusicTrackBits;
}
else if( EventName == sStartFlying )
{
// Adapted from Acid flying scripts
m_IsFlying = true;
WBEntity* const pEntity = GetEntity();
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
pTransform->SetGravity( 0.0f );
WB_MAKE_EVENT( EnableAirFriction, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), EnableAirFriction, pEntity );
WB_MAKE_EVENT( DisableFootsteps, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), DisableFootsteps, pEntity );
}
else if( EventName == sStopFlying )
{
// Adapted from Acid flying scripts
m_IsFlying = false;
WBEntity* const pEntity = GetEntity();
WBCompRosaTransform* const pTransform = pEntity->GetTransformComponent<WBCompRosaTransform>();
pTransform->SetDefaultGravity();
WB_MAKE_EVENT( DisableAirFraction, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), DisableAirFraction, pEntity );
WB_MAKE_EVENT( EnableFootsteps, pEntity );
WB_DISPATCH_EVENT( GetEventManager(), EnableFootsteps, pEntity );
}
else if( EventName == sOnDied )
{
if( m_IsCrouched )
{
BeginUncrouch();
}
}
}
/*virtual*/ void WBCompRosaPlayer::AddContextToEvent( WBEvent& Event ) const
{
Super::AddContextToEvent( Event );
WBCompRosaWeapon* const pWeapon = GetWeapon();
const bool IsAiming = pWeapon && pWeapon->IsAiming();
WBCompStatMod* const pStatMod = WB_GETCOMP( GetEntity(), StatMod );
WB_MODIFY_FLOAT( CanUnlockDoors, 0.0f, pStatMod );
const bool CanUnlockDoors = ( WB_MODDED( CanUnlockDoors ) != 0.0f );
{
WB_SET_CONTEXT( Event, Bool, CanOpenDoors, true );
WB_SET_CONTEXT( Event, Bool, CanUnlockDoors, CanUnlockDoors );
WB_SET_CONTEXT( Event, Bool, IsSprinting, m_IsSprinting && !m_IsCrouched );
WB_SET_CONTEXT( Event, Float, SprintTime, GetTime() - m_SprintStartTime );
WB_SET_CONTEXT( Event, Bool, IsPowerSliding, m_IsPowerSliding );
WB_SET_CONTEXT( Event, Bool, IsMantling, m_IsMantling );
WB_SET_CONTEXT( Event, Bool, IsAiming, IsAiming );
}
// OLDVAMP: Replace with an equivalent for Zeta campaign?
//// Add some campaign context so we can easily query this stuff without special PEs
//// (as long as we're querying it *after* the player has spawned!)
//RosaCampaign* const pCampaign = RosaCampaign::GetCampaign();
//if( pCampaign )
//{
// WB_SET_CONTEXT( Event, Int, Campaign_Legacy, pCampaign->GetLegacy() );
// WB_SET_CONTEXT( Event, Int, Campaign_Season, pCampaign->GetSeason() );
// WB_SET_CONTEXT( Event, Int, Campaign_Episode, pCampaign->GetEpisode() );
//}
}
// Manage difficulty persistence here, since there's no difficulty component
void WBCompRosaPlayer::PushPersistence() const
{
TPersistence& Persistence = RosaGame::StaticGetTravelPersistence();
const uint GameDifficulty = RosaDifficulty::GetGameDifficulty();
STATIC_HASHED_STRING( GameDifficulty );
Persistence.SetInt( sGameDifficulty, GameDifficulty );
}
void WBCompRosaPlayer::PullPersistence()
{
TPersistence& Persistence = RosaGame::StaticGetTravelPersistence();
STATIC_HASHED_STRING( GameDifficulty );
const uint GameDifficulty = Persistence.GetInt( sGameDifficulty );
RosaDifficulty::SetGameDifficulty( GameDifficulty );
RosaDifficulty::PushGameToMenu();
}
void WBCompRosaPlayer::AddAutosaveSuppression( const bool Serialize )
{
if( Serialize )
{
++m_AutosaveSuppRefsSerialized;
}
else
{
++m_AutosaveSuppRefsTransient;
}
}
void WBCompRosaPlayer::RemoveAutosaveSuppression( const bool Serialize )
{
if( Serialize )
{
if( m_AutosaveSuppRefsSerialized > 0 )
{
--m_AutosaveSuppRefsSerialized;
}
#if BUILD_DEV
else
{
WARNDESC( "Autosave: Suppression refcount mismatch, trying to decrement past zero." );
}
#endif
}
else
{
if( m_AutosaveSuppRefsTransient > 0 )
{
--m_AutosaveSuppRefsTransient;
}
#if BUILD_DEV
else
{
WARNDESC( "Autosave: Transient suppression refcount mismatch, trying to decrement past zero." );
}
#endif
}
}
bool WBCompRosaPlayer::CanAutosave()
{
if( m_AutosaveSuppRefsSerialized > 0 || m_AutosaveSuppRefsTransient > 0 )
{
DEVPRINTF( "CanAutosave: false because suppression refcount is %d/%d\n", m_AutosaveSuppRefsSerialized, m_AutosaveSuppRefsTransient );
return false;
}
WBCompRosaCollision* const pCollision = WB_GETCOMP( GetEntity(), RosaCollision );
if( !pCollision->IsLanded() )
{
DEVPRINTF( "CanAutosave: false because player is unlanded\n" );
return false;
}
DEVPRINTF( "CanAutosave: true\n" );
return true;
}
void WBCompRosaPlayer::QueueAutosave( const float AutosaveDelay )
{
WB_MAKE_EVENT( OnAutosave, NULL );
WB_QUEUE_EVENT_DELAY( GetEventManager(), OnAutosave, GetEntity(), AutosaveDelay );
}
/*virtual*/ void WBCompRosaPlayer::OnInputContextsChanged()
{
ConditionalApplyRunningStatMods();
}
void WBCompRosaPlayer::ConditionalApplyRunningStatMods()
{
WBEntity* const pEntity = GetEntity();
WBCompStatMod* const pStatMod = WB_GETCOMP( pEntity, StatMod );
STATIC_HASHED_STRING( Running );
if( m_IsSprinting && !m_IsCrouched )
{
pStatMod->SetEventActive( sRunning, true );
}
else
{
pStatMod->SetEventActive( sRunning, false );
}
}
#define VERSION_EMPTY 0
#define VERSION_CROUCHING 1
#define VERSION_CLIMBING 2
#define VERSION_UNCLIMBINGGRAVITY 3
#define VERSION_SPAWNPOINT 4
#define VERSION_POWERSLIDE 5
#define VERSION_POWERSLIDEY 6
#define VERSION_ISDISABLINGPAUSE 7
#define VERSION_DRAG 8
#define VERSION_AUTOSAVESUPPRESSION 9
#define VERSION_HASDOUBLEJUMPED 10
#define VERSION_INITIALMUSICTRACKBITS 11
#define VERSION_ISFORCEDCROUCHED 12
#define VERSION_UNCLIMBINGGRAVITY_DEPR 13
#define VERSION_ISFLYING 14
#define VERSION_CURRENT 14
uint WBCompRosaPlayer::GetSerializationSize()
{
uint Size = 0;
Size += 4; // Version
Size += 1; // m_IsCrouched
Size += 1; // m_IsUncrouching
Size += 1; // m_IsForceCrouched
Size += 4; // m_ClimbRefs
Size += 1; // m_HasSetSpawnPoint
Size += sizeof( Vector ); // m_SpawnLocation
Size += sizeof( Angles ); // m_SpawnOrientation
Size += 1; // m_HasDoubleJumped
Size += 1; // m_IsPowerSliding
Size += 4; // Power slide time remaining
Size += sizeof( Vector ); // m_PowerSlideY
Size += 1; // m_IsDisablingPause
Size += 1; // m_IsDragging
Size += sizeof( WBEntityRef ); // m_DraggedEntity
Size += 4; // m_AutosaveSuppRefsSerialized
Size += 4; // m_InitialMusicTrackBits
Size += 1; // m_IsFlying
return Size;
}
void WBCompRosaPlayer::Save( const IDataStream& Stream )
{
Stream.WriteUInt32( VERSION_CURRENT );
Stream.WriteBool( m_IsCrouched );
Stream.WriteBool( m_IsUncrouching );
Stream.WriteBool( m_IsForceCrouched );
Stream.WriteInt32( m_ClimbRefs );
Stream.WriteBool( m_HasSetSpawnPoint );
Stream.Write( sizeof( Vector ), &m_SpawnLocation );
Stream.Write( sizeof( Angles ), &m_SpawnOrientation );
Stream.WriteBool( m_HasDoubleJumped );
Stream.WriteBool( m_IsPowerSliding );
Stream.WriteFloat( m_PowerSlideEndTime - GetTime() );
Stream.Write( sizeof( Vector ), &m_PowerSlideY );
Stream.WriteBool( m_IsDisablingPause );
Stream.WriteBool( m_IsDragging );
Stream.Write( sizeof( WBEntityRef ), &m_DraggedEntity );
Stream.WriteUInt32( m_AutosaveSuppRefsSerialized );
Stream.WriteUInt32( m_InitialMusicTrackBits );
Stream.WriteBool( m_IsFlying );
}
void WBCompRosaPlayer::Load( const IDataStream& Stream )
{
XTRACE_FUNCTION;
const uint Version = Stream.ReadUInt32();
if( Version >= VERSION_CROUCHING )
{
m_IsCrouched = Stream.ReadBool();
m_IsUncrouching = Stream.ReadBool();
}
if( Version >= VERSION_ISFORCEDCROUCHED )
{
m_IsForceCrouched = Stream.ReadBool();
}
if( Version >= VERSION_CLIMBING )
{
m_ClimbRefs = Stream.ReadInt32();
}
if( Version >= VERSION_UNCLIMBINGGRAVITY && Version < VERSION_UNCLIMBINGGRAVITY_DEPR )
{
Stream.ReadFloat();
}
if( Version >= VERSION_SPAWNPOINT )
{
m_HasSetSpawnPoint = Stream.ReadBool();
Stream.Read( sizeof( Vector ), &m_SpawnLocation );
Stream.Read( sizeof( Angles ), &m_SpawnOrientation );
}
if( Version >= VERSION_HASDOUBLEJUMPED )
{
m_HasDoubleJumped = Stream.ReadBool();
}
if( Version >= VERSION_POWERSLIDE )
{
m_IsPowerSliding = Stream.ReadBool();
m_PowerSlideEndTime = GetTime() + Stream.ReadFloat();
}
if( Version >= VERSION_POWERSLIDEY )
{
Stream.Read( sizeof( Vector ), &m_PowerSlideY );
}
if( Version >= VERSION_ISDISABLINGPAUSE )
{
m_IsDisablingPause = Stream.ReadBool();
}
if( Version >= VERSION_DRAG )
{
m_IsDragging = Stream.ReadBool();
Stream.Read( sizeof( WBEntityRef ), &m_DraggedEntity );
}
if( Version >= VERSION_AUTOSAVESUPPRESSION )
{
m_AutosaveSuppRefsSerialized = Stream.ReadUInt32();
}
if( Version >= VERSION_INITIALMUSICTRACKBITS )
{
m_InitialMusicTrackBits = Stream.ReadUInt32();
}
if( Version >= VERSION_ISFLYING )
{
m_IsFlying = Stream.ReadBool();
}
}
| 33.375187 | 261 | 0.743044 |
ea1661eda603cd1b755ed6abeda67e0793b7072c | 3,283 | hpp | C++ | third_party/xsimd/types/xsimd_common_math.hpp | jeanlaroche/pythran | 6a2452e8588390bbb20575f580dba11b0037962b | [
"BSD-3-Clause"
] | 1 | 2019-11-09T07:12:56.000Z | 2019-11-09T07:12:56.000Z | third_party/xsimd/types/xsimd_common_math.hpp | jeanlaroche/pythran | 6a2452e8588390bbb20575f580dba11b0037962b | [
"BSD-3-Clause"
] | 1 | 2015-12-19T10:53:53.000Z | 2015-12-19T17:58:20.000Z | third_party/xsimd/types/xsimd_common_math.hpp | jeanlaroche/pythran | 6a2452e8588390bbb20575f580dba11b0037962b | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_COMMON_MATH_HPP
#define XSIMD_COMMON_MATH_HPP
#include <limits>
#include <type_traits>
namespace xsimd
{
/*********************************************
* Some utility math operations shared *
* across scalar versio and fallback *
* versions *
*********************************************/
namespace detail
{
template <class T0, class T1>
inline T0
ipow(const T0& t0, const T1& t1)
{
static_assert(std::is_integral<T1>::value, "second argument must be an integer");
T0 a = t0;
T1 b = t1;
bool const recip = b < 0;
T0 r{static_cast<T0>(1)};
while (1)
{
if (b & 1)
{
r *= a;
}
b /= 2;
if (b == 0)
{
break;
}
a *= a;
}
return recip ? 1 / r : r;
}
template<typename T, class = typename std::enable_if<std::is_scalar<T>::value>::type>
T sadd(const T& lhs, const T& rhs)
{
if (std::numeric_limits<T>::is_signed)
{
if ((lhs > 0) && (rhs > std::numeric_limits<T>::max() - lhs))
{
return std::numeric_limits<T>::max();
}
else if ((lhs < 0) && (rhs < std::numeric_limits<T>::lowest() - lhs))
{
return std::numeric_limits<T>::lowest();
}
else {
return lhs + rhs;
}
}
else
{
if (rhs > std::numeric_limits<T>::max() - lhs)
{
return std::numeric_limits<T>::max();
}
else
{
return lhs + rhs;
}
}
}
template<typename T, class = typename std::enable_if<std::is_scalar<T>::value>::type>
T ssub(const T& lhs, const T& rhs)
{
if (std::numeric_limits<T>::is_signed)
{
return sadd(lhs, (T)-rhs);
}
else
{
if (lhs < rhs)
{
return std::numeric_limits<T>::lowest();
}
else
{
return lhs - rhs;
}
}
}
}
}
#endif
| 31.266667 | 93 | 0.335364 |
ea1a1a4ad651a8413789e171ef860cd2d745c0e6 | 107 | cpp | C++ | LiberoEngine/src/Libero/Components/InputComponent.cpp | Kair0z/LiberoEngine3D | 84c5f75251f19330da9a490587bbf0911bdb681a | [
"MIT"
] | null | null | null | LiberoEngine/src/Libero/Components/InputComponent.cpp | Kair0z/LiberoEngine3D | 84c5f75251f19330da9a490587bbf0911bdb681a | [
"MIT"
] | null | null | null | LiberoEngine/src/Libero/Components/InputComponent.cpp | Kair0z/LiberoEngine3D | 84c5f75251f19330da9a490587bbf0911bdb681a | [
"MIT"
] | null | null | null | #include "Liber_pch.h"
#include "InputComponent.h"
void Libero::InputComponent::HandleEvent(IEvent& )
{
}
| 15.285714 | 50 | 0.747664 |
ea1e97576f585169d98fd8f01f696db032199934 | 10,874 | cpp | C++ | src/plugins/vtyulc/vlcplayer.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/vtyulc/vlcplayer.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/plugins/vtyulc/vlcplayer.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2013 Vladislav Tyulbashev
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include <QVBoxLayout>
#include <QPushButton>
#include <QTime>
#include <QMouseEvent>
#include <QWidget>
#include <QTime>
#include <QTimer>
#include <QSizePolicy>
#include <QEventLoop>
#include <QTimeLine>
#include <QDir>
#include <QDebug>
#include "vlcplayer.h"
namespace
{
QTime convertTime (libvlc_time_t t)
{
return QTime (t / 1000 / 60 / 60, t / 1000 / 60 % 60, t / 1000 % 60, t % 1000);
}
void sleep (int ms)
{
QEventLoop loop;
QTimer::singleShot (ms, &loop, SLOT (quit ()));
loop.exec ();
}
const int DVD_IS_MORE_THAN = 10 * 60 * 1000; // in ms
const int MAX_TIMEOUT = 1000; // in ms
}
namespace LeechCraft
{
namespace vlc
{
VlcPlayer::VlcPlayer (QWidget *parent)
: QObject (parent)
, M_ (nullptr)
, Parent_ (parent)
, DVD_ (false)
{
VlcInstance_ = std::shared_ptr<libvlc_instance_t> (libvlc_new (0, nullptr), libvlc_release);
Mp_ = std::shared_ptr<libvlc_media_player_t> (libvlc_media_player_new (VlcInstance_.get ()), libvlc_media_player_release);
libvlc_media_player_set_xwindow (Mp_.get (), parent->winId ());
}
VlcPlayer::~VlcPlayer()
{
libvlc_media_player_stop (Mp_.get ());
}
void VlcPlayer::Init (QWidget *parent)
{
libvlc_media_player_set_xwindow (Mp_.get (), parent->winId ());
Parent_ = parent;
}
void VlcPlayer::setUrl (const QUrl& url)
{
Subtitles_.clear ();
libvlc_media_player_stop (Mp_.get ());
DVD_ = url.scheme () == "dvd";
M_.reset (libvlc_media_new_location (VlcInstance_.get (), url.toEncoded ()), libvlc_media_release);
libvlc_media_player_set_media (Mp_.get (), M_.get ());
libvlc_media_player_play (Mp_.get ());
}
void VlcPlayer::addUrl (const QUrl& url)
{
const QUrl &lastMedia = QUrl::fromEncoded (libvlc_media_get_meta (libvlc_media_player_get_media (Mp_.get ()), libvlc_meta_URL));
Freeze ();
M_.reset (libvlc_media_new_location (VlcInstance_.get (), lastMedia.toEncoded ()), libvlc_media_release);
libvlc_media_add_option (M_.get (), ":input-slave=" + url.toEncoded ());
libvlc_media_player_set_media (Mp_.get (), M_.get ());
UnFreeze ();
}
bool VlcPlayer::NowPlaying () const
{
return libvlc_media_player_is_playing (Mp_.get ());
}
double VlcPlayer::GetPosition () const
{
return libvlc_media_player_get_position (Mp_.get ());
}
void VlcPlayer::togglePlay ()
{
bool subtitlesRequired = false;
if (libvlc_media_player_get_state (Mp_.get ()) == libvlc_Stopped ||
libvlc_media_player_get_state (Mp_.get ()) == libvlc_Ended)
subtitlesRequired = true;
if (NowPlaying ())
libvlc_media_player_pause (Mp_.get ());
else
libvlc_media_player_play (Mp_.get ());
if (subtitlesRequired)
ReloadSubtitles ();
}
void VlcPlayer::stop ()
{
libvlc_media_player_stop (Mp_.get ());
}
void VlcPlayer::pause ()
{
libvlc_media_player_pause (Mp_.get ());
}
void VlcPlayer::changePosition (double pos)
{
if (libvlc_media_player_get_media (Mp_.get ()))
libvlc_media_player_set_position (Mp_.get (), pos);
}
QTime VlcPlayer::GetFullTime () const
{
if (libvlc_media_player_get_media (Mp_.get ()))
return convertTime (libvlc_media_player_get_length (Mp_.get ()));
else
return convertTime (0);
}
QTime VlcPlayer::GetCurrentTime () const
{
if (libvlc_media_player_get_media (Mp_.get ()))
return convertTime (libvlc_media_player_get_time (Mp_.get ()));
else
return convertTime (0);
}
void VlcPlayer::SetCurrentTime (libvlc_time_t time)
{
if (libvlc_media_player_is_playing (Mp_.get ()))
libvlc_media_player_set_time (Mp_.get (), time);
else
{
libvlc_media_player_play (Mp_.get ());
WaitForPlaying ();
libvlc_media_player_set_time (Mp_.get (), time);
libvlc_media_player_pause (Mp_.get ());
}
}
void VlcPlayer::Freeze ()
{
emit unstable ();
FreezePlayingMedia_ = libvlc_media_player_get_media (Mp_.get ());
if (FreezePlayingMedia_)
{
FreezeCur_ = libvlc_media_player_get_time (Mp_.get ());
FreezeAudio_ = GetCurrentAudioTrack ();
FreezeSubtitle_ = GetCurrentSubtitle ();
}
FreezeIsPlaying_ = libvlc_media_player_is_playing (Mp_.get ());
FreezeDVD_ = DVD_ && libvlc_media_player_get_length (Mp_.get ()) > DVD_IS_MORE_THAN;
libvlc_media_player_stop (Mp_.get ());
}
void VlcPlayer::switchWidget (QWidget *widget)
{
Freeze ();
libvlc_media_player_set_xwindow (Mp_.get (), widget->winId ());
UnFreeze ();
}
void VlcPlayer::UnFreeze ()
{
libvlc_media_player_play (Mp_.get ());
WaitForPlaying ();
if (FreezeDVD_)
{
libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_activate);
WaitForDVDPlaying ();
}
if (FreezePlayingMedia_ && (!DVD_ || FreezeDVD_))
{
libvlc_media_player_set_time (Mp_.get (), FreezeCur_);
setAudioTrack (FreezeAudio_);
setSubtitle (FreezeSubtitle_);
}
if (!FreezeIsPlaying_)
libvlc_media_player_pause (Mp_.get ());
ReloadSubtitles ();
emit stable ();
}
void VlcPlayer::ReloadSubtitles ()
{
for (int i = 0; i < Subtitles_.size (); i++)
libvlc_video_set_subtitle_file (Mp_.get (), Subtitles_ [i].toUtf8 ());
}
QWidget* VlcPlayer::GetParent () const
{
return Parent_;
}
std::shared_ptr<libvlc_media_player_t> VlcPlayer::GetPlayer () const
{
return Mp_;
}
int VlcPlayer::GetAudioTracksNumber () const
{
return libvlc_audio_get_track_count (Mp_.get ());
}
int VlcPlayer::GetCurrentAudioTrack () const
{
return libvlc_audio_get_track (Mp_.get ());
}
void VlcPlayer::setAudioTrack (int track)
{
libvlc_audio_set_track (Mp_.get (), track);
}
QString VlcPlayer::GetAudioTrackDescription (int track) const
{
libvlc_track_description_t *t = GetTrack (libvlc_audio_get_track_description (Mp_.get ()), track);
return QString (t->psz_name);
}
int VlcPlayer::GetAudioTrackId(int track) const
{
libvlc_track_description_t *t = GetTrack (libvlc_audio_get_track_description (Mp_.get ()), track);
return t->i_id;
}
int VlcPlayer::GetSubtitlesNumber () const
{
return libvlc_video_get_spu_count (Mp_.get ());
}
void VlcPlayer::AddSubtitles (const QString& file)
{
libvlc_video_set_subtitle_file (Mp_.get (), file.toUtf8 ());
Subtitles_ << file;
}
int VlcPlayer::GetCurrentSubtitle () const
{
return libvlc_video_get_spu (Mp_.get ());
}
QString VlcPlayer::GetSubtitleDescription (int track) const
{
libvlc_track_description_t *t = GetTrack (libvlc_video_get_spu_description (Mp_.get ()), track);
return QString (t->psz_name);
}
int VlcPlayer::GetSubtitleId(int track) const
{
libvlc_track_description_t *t = GetTrack (libvlc_video_get_spu_description (Mp_.get ()), track);
return t->i_id;
}
void VlcPlayer::setSubtitle (int track)
{
libvlc_video_set_spu (Mp_.get (), track);
}
libvlc_track_description_t* VlcPlayer::GetTrack(libvlc_track_description_t *t, int track) const
{
for (int i = 0; i < track; i++)
t = t->p_next;
return t;
}
void VlcPlayer::DVDNavigate (unsigned nav)
{
libvlc_media_player_navigate (Mp_.get (), nav);
}
void VlcPlayer::dvdNavigateDown ()
{
libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_down);
}
void VlcPlayer::dvdNavigateUp ()
{
libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_up);
}
void VlcPlayer::dvdNavigateRight ()
{
libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_right);
}
void VlcPlayer::dvdNavigateLeft ()
{
libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_left);
}
void VlcPlayer::dvdNavigateEnter ()
{
libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_activate);
}
void VlcPlayer::WaitForPlaying () const
{
QTimeLine line;
line.start ();
while (!NowPlaying ())
{
sleep (5);
if (line.currentTime () > MAX_TIMEOUT)
{
qWarning () << Q_FUNC_INFO << "timeout";
break;
}
}
}
void VlcPlayer::WaitForDVDPlaying () const
{
QTimeLine line;
line.start ();
while (libvlc_media_player_get_length (Mp_.get ()) < DVD_IS_MORE_THAN)
{
sleep (5);
if (line.currentTime () > MAX_TIMEOUT)
{
qWarning () << Q_FUNC_INFO << "timeout";
break;
}
}
WaitForPlaying ();
}
libvlc_instance_t* VlcPlayer::GetInstance () const
{
return VlcInstance_.get ();
}
void VlcPlayer::plus3percent ()
{
libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) + libvlc_media_player_get_length (Mp_.get ()) * 0.03);
}
void VlcPlayer::minus3percent ()
{
libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) - libvlc_media_player_get_length (Mp_.get ()) * 0.03);
}
void VlcPlayer::plus10seconds ()
{
libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) + 10 * 1000);
}
void VlcPlayer::minus10seconds ()
{
libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) - 10 * 1000);
}
void VlcPlayer::setAspectRatio (const QByteArray& ratio)
{
libvlc_video_set_aspect_ratio (Mp_.get (), ratio);
}
void VlcPlayer::setRealZoom (const QByteArray& zoom)
{
libvlc_video_set_crop_geometry (Mp_.get (), zoom.constData ());
}
QString VlcPlayer::GetAspectRatio () const
{
return libvlc_video_get_aspect_ratio (Mp_.get ());
}
}
}
| 26.014354 | 140 | 0.697995 |
ea1facd474872ae296f836d868e0b674e4ccedc0 | 787 | hpp | C++ | src/CacheClient.hpp | mostynb/tundra | 4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1 | [
"MIT"
] | null | null | null | src/CacheClient.hpp | mostynb/tundra | 4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1 | [
"MIT"
] | null | null | null | src/CacheClient.hpp | mostynb/tundra | 4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1 | [
"MIT"
] | null | null | null | #pragma once
#include "Hash.hpp"
namespace Frozen { struct DagNode; struct Dag; }
struct StatCache;
struct Mutex;
struct ThreadState;
namespace CacheResult
{
enum Enum
{
DidNotTry,
Failure,
CacheMiss,
Success,
};
}
struct CacheClient
{
static CacheResult::Enum AttemptRead(const Frozen::Dag* dag, const Frozen::DagNode* dagNode, HashDigest signature, StatCache* stat_cache, Mutex* queue_lock, ThreadState* thread_state);
static CacheResult::Enum AttemptWrite(const Frozen::Dag* dag, const Frozen::DagNode* dagNode, HashDigest signature, StatCache* stat_cache, Mutex* queue_lock, ThreadState* thread_state, const char* ingredients_file);
};
void GetCachingBehaviourSettingsFromEnvironment(bool* attemptReads, bool* attemptWrites);
| 28.107143 | 219 | 0.7446 |
ea221a48a43ed4ee332d6f60ac6fd941bf9321f2 | 5,515 | cpp | C++ | server.cpp | Stykk-Gruppen/qTracker-Server | 4abf1a6a583c9681481e7fd678aa31a467f8040f | [
"MIT"
] | null | null | null | server.cpp | Stykk-Gruppen/qTracker-Server | 4abf1a6a583c9681481e7fd678aa31a467f8040f | [
"MIT"
] | 2 | 2020-06-03T10:03:48.000Z | 2020-08-24T13:58:34.000Z | server.cpp | Feqzz/qTracker-Server | 4abf1a6a583c9681481e7fd678aa31a467f8040f | [
"MIT"
] | null | null | null | #include "server.h"
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <iostream>
/**
* Initializes the openssl library, creates SSL context, configures it
* and creates a socket using the portnumber supplied
* @param int port
* @return Server object
*/
Server::Server(int port)
{
initOpenSSL();
ctx = createContext();
configureContect(ctx);
sock = createSocket(port);
}
/**
* Creates a Secure TCP socket server and starts listening.
* It does not very if the certificate is valid only that is exists.
* The function also creates a new thread for each incoming request.
*/
void Server::start()
{
/* Handle connections */
while(1) {
struct sockaddr_in addr;
uint len = sizeof(addr);
SSL *ssl;
int client = accept(sock, (struct sockaddr*)&addr, &len);
if (client < 0)
{
perror("Unable to accept");
exit(EXIT_FAILURE);
}
pid=fork();
if(pid==0)
{
ssl = SSL_new(ctx);
SSL_set_fd(ssl, client);
if (SSL_accept(ssl) <= 0)
{
ERR_print_errors_fp(stderr);
}
else
{
handleClient(ssl);
/*const char reply[] = "1";
char readBuffer[10];
SSL_read(ssl,readBuffer,10);
SSL_write(ssl, reply, strlen(reply));*/
signal(SIGCHLD,SIG_IGN);
SSL_shutdown(ssl);
SSL_free(ssl);
exit(0);
}
}
else
{
close(client);
}
}
close(sock);
SSL_CTX_free(ctx);
cleanupSSL();
}
/**
* Read and parses the buffer from the socket connection and creates a Email object.
* Depending on the email sending success, a 0 or 1 is returned back to the TCP connection.
* @param ssl Secure Socket connection pointer
*/
void Server::handleClient(SSL* ssl)
{
//buffer size can be changed to whatever
int bufferSize = 255;
std::string reply = "";
char readBuffer[bufferSize];
SSL_read(ssl,readBuffer,bufferSize);
std::vector<std::string> variables;
variables = parseBuffer(readBuffer,bufferSize);
Email email(variables);
int emailSuccess = email.send();
//emailSuccess = -1 means the system call failed
if(emailSuccess >= 0)
{
reply = "1";
}
else
{
reply = "0";
}
SSL_write(ssl,&reply[0],1);
/*const char asd[] = "1";
int test = SSL_write(ssl, asd, strlen(asd));
std::cout << test << "\n";*/
}
/**
* Iterates through the buffer to build strings, if a '\n' char is found a variable is finished
* and added to the return vector.
* @param buffer
* @param length
* @return std::vector<std::string> parsed data from buffer
*/
std::vector<std::string> Server::parseBuffer(char* buffer,int length)
{
std::vector<std::string> stringVector;
std::string tempString = "";
//0 is invite, 1 is forgotten password
//int code = (int)buffer[0]-48;
for(int i=0;i<length;i++)
{
char tempChar = buffer[i];
if(tempChar=='\n')
{
stringVector.push_back(tempString);
tempString = "";
}
else
{
tempString += tempChar;
}
}
return stringVector;
}
/**
* Creates a TCP socket with the port number 'port'
* @param port
* @return int socket
*/
int Server::createSocket(int port)
{
int s;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0)
{
perror("Unable to create socket");
exit(EXIT_FAILURE);
}
if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0)
{
perror("Unable to bind");
exit(EXIT_FAILURE);
}
if (listen(s, 1) < 0)
{
perror("Unable to listen");
exit(EXIT_FAILURE);
}
return s;
}
/**
* @brief Server::initOpenSSL
*/
void Server::initOpenSSL()
{
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
}
/**
* @brief Server::cleanupSSL
*/
void Server::cleanupSSL()
{
EVP_cleanup();
}
/**
* @brief Server::createContext
* @return SSL_CTX*
*/
SSL_CTX* Server::createContext()
{
const SSL_METHOD *method;
SSL_CTX *ctx;
method = SSLv23_server_method();
ctx = SSL_CTX_new(method);
if (!ctx)
{
perror("Unable to create SSL context");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
return ctx;
}
/**
* @brief Server::configureContect
* @param SSL_CTX*
*/
void Server::configureContect(SSL_CTX *ctx)
{
SSL_CTX_set_ecdh_auto(ctx, 1);
/* Set the key and cert */
if (SSL_CTX_use_certificate_file(ctx, "cert.pem", SSL_FILETYPE_PEM) <= 0)
{
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
if (SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
} | 22.789256 | 96 | 0.553218 |
ea2948783dfe546548f7937329adac5262413e9c | 550 | cpp | C++ | Sail/src/Sail/entities/components/RagdollComponent.cpp | BTH-StoraSpel-DXR/SPLASH | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 12 | 2019-09-11T15:52:31.000Z | 2021-11-14T20:33:35.000Z | Sail/src/Sail/entities/components/RagdollComponent.cpp | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 227 | 2019-09-11T08:40:24.000Z | 2020-06-26T14:12:07.000Z | Sail/src/Sail/entities/components/RagdollComponent.cpp | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 2 | 2020-10-26T02:35:18.000Z | 2020-10-26T02:36:01.000Z | #include "pch.h"
#include "RagdollComponent.h"
RagdollComponent::RagdollComponent() {
localCenterOfMass = {0.f, 0.f, 0.f};
wireframeModel = nullptr;
}
RagdollComponent::RagdollComponent(Model* wireframe) {
localCenterOfMass = { 0.f, 0.f, 0.f };
wireframeModel = wireframe;
}
RagdollComponent::~RagdollComponent() {
}
void RagdollComponent::addContactPoint(glm::vec3 localOffset, glm::vec3 halfSize) {
contactPoints.emplace_back();
contactPoints.back().boundingBox.setHalfSize(halfSize);
contactPoints.back().localOffSet = localOffset;
}
| 22.916667 | 83 | 0.752727 |
ea2a6ec0c8c1518fd2627ff467f0bcd2f715cfd0 | 572 | cc | C++ | zircon/kernel/phys/panic.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | zircon/kernel/phys/panic.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | zircon/kernel/phys/panic.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#include <zircon/assert.h>
#include "main.h"
// This is what ZX_ASSERT calls.
// TODO(mcgrathr): print message, backtrace
PHYS_SINGLETHREAD void __zx_panic(const char* format, ...) { __builtin_trap(); }
// The compiler generates calls to this for -fstack-protector.
extern "C" [[noreturn]] PHYS_SINGLETHREAD void __stack_chk_fail() {
__zx_panic("stack canary corrupted!\n");
}
| 30.105263 | 80 | 0.736014 |
ea2c4a8b11b218b908d90e5bb9c606fab4a98ba6 | 996 | cpp | C++ | PID Controller implementation/blocks/differentiator.cpp | SokratALDARMINI/Implementation-of-PID-controller-using-Qt-creator | 9281560aae98c5142dcc4428ce39fbd1b8bb2b28 | [
"MIT"
] | null | null | null | PID Controller implementation/blocks/differentiator.cpp | SokratALDARMINI/Implementation-of-PID-controller-using-Qt-creator | 9281560aae98c5142dcc4428ce39fbd1b8bb2b28 | [
"MIT"
] | null | null | null | PID Controller implementation/blocks/differentiator.cpp | SokratALDARMINI/Implementation-of-PID-controller-using-Qt-creator | 9281560aae98c5142dcc4428ce39fbd1b8bb2b28 | [
"MIT"
] | null | null | null | #include "differentiator.h"
Differentiator::Differentiator(double n)
{// the value of coefficient (N) is set as needed when the differentiator is created the integrator (I) is created with inital output equal zero
N=n; I=new Integrator(0); }
Differentiator::~Differentiator()
{ //the integrator (I) is deleted
delete I; }
double Differentiator::update(double input, double dt)
{ //update with integrator value with (input-integrator_output)*N
//then the integrator input is used as the output of the differentiator
value=(input-I->getValue())*N;
I->update(value,dt);
return value; }
void Differentiator::setValue(double V)
{ //the integrator output is set to V and the differentiator output is set to zero
value = 0; I->setValue(V);}
double Differentiator::getValue() const
{ //return the output of the differentiator
return value;}
void Differentiator::setN(double value)
{ // set the coefficient (N)
N = value;}
| 34.344828 | 145 | 0.695783 |
ea2ca5a2a95fc6632a25d457d167b0d36980f8f3 | 5,820 | cpp | C++ | bitbots_navigation/bitbots_local_planner/src/bitbots_local_planner.cpp | MosHumanoid/bitbots_thmos_meta | f45ccc362dc689b69027be5b0d000d2a08580de4 | [
"MIT"
] | null | null | null | bitbots_navigation/bitbots_local_planner/src/bitbots_local_planner.cpp | MosHumanoid/bitbots_thmos_meta | f45ccc362dc689b69027be5b0d000d2a08580de4 | [
"MIT"
] | null | null | null | bitbots_navigation/bitbots_local_planner/src/bitbots_local_planner.cpp | MosHumanoid/bitbots_thmos_meta | f45ccc362dc689b69027be5b0d000d2a08580de4 | [
"MIT"
] | null | null | null | #include <bitbots_local_planner/bitbots_local_planner.h>
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(bitbots_local_planner::BBPlanner, nav_core::BaseLocalPlanner)
namespace bitbots_local_planner
{
BBPlanner::BBPlanner()
{
}
void BBPlanner::initialize(std::string name, tf2_ros::Buffer *tf_buffer, costmap_2d::Costmap2DROS *costmap_ros)
{
ros::NodeHandle private_nh("~/" + name);
local_plan_publisher_ = private_nh.advertise<nav_msgs::Path>("local_plan", 1);
tf_buffer_ = tf_buffer;
goal_reached_ = false;
costmap_ros_ = costmap_ros;
//Parameter for dynamic reconfigure
dsrv_ = new dynamic_reconfigure::Server<BBPlannerConfig>(private_nh);
dynamic_reconfigure::Server<BBPlannerConfig>::CallbackType cb = boost::bind(&BBPlanner::reconfigureCB, this, _1, _2);
dsrv_->setCallback(cb);
ROS_DEBUG("BBPlanner: Version 2 Init.");
}
void BBPlanner::reconfigureCB(BBPlannerConfig &config, uint32_t level)
{
config_ = config;
}
bool BBPlanner::setPlan(const std::vector<geometry_msgs::PoseStamped> &plan) {
global_plan_ = plan;
int carrot_distance = 10;
if (global_plan_.size() > 10)
{
carrot_distance = 10;
}
else
{
carrot_distance = global_plan_.size() - 1;
}
// Querys the pose of our carrot which we want to follow
bitbots_local_planner::getXPose(
*tf_buffer_,
global_plan_,
costmap_ros_->getGlobalFrameID(),
goal_pose_,
carrot_distance);
// Query the final pose of our robot at the end of the global plan
bitbots_local_planner::getXPose(
*tf_buffer_, global_plan_,
costmap_ros_->getGlobalFrameID(),
end_pose_,
global_plan_.size() - 1);
old_goal_pose_ = goal_pose_;
goal_reached_ = false;
return true;
}
bool BBPlanner::computeVelocityCommands(geometry_msgs::Twist &cmd_vel)
{
ros::Time begin = ros::Time::now();
tf2::Stamped<tf2::Transform> current_pose;
geometry_msgs::PoseStamped msg;
costmap_ros_->getRobotPose(msg);
current_pose.setData(
tf2::Transform(
tf2::Quaternion(
msg.pose.orientation.x,
msg.pose.orientation.y,
msg.pose.orientation.z,
msg.pose.orientation.w),
tf2::Vector3(
msg.pose.position.x,
msg.pose.position.y,
msg.pose.position.z)));
double walk_angle = std::fmod(
std::atan2(
goal_pose_.getOrigin().y() - current_pose.getOrigin().y(),
goal_pose_.getOrigin().x() - current_pose.getOrigin().x()),
2 * M_PI);
double final_walk_angle = std::fmod(
std::atan2(
end_pose_.getOrigin().y() - current_pose.getOrigin().y(),
end_pose_.getOrigin().x() - current_pose.getOrigin().x()),
2 * M_PI);
double distance = sqrt(
pow(end_pose_.getOrigin().y() - current_pose.getOrigin().y(), 2) +
pow(end_pose_.getOrigin().x() - current_pose.getOrigin().x(), 2));
double walk_vel = std::min(distance * config_.translation_slow_down_factor, config_.max_vel_x);
double diff = 0;
if (distance > config_.orient_to_goal_distance)
{
diff = final_walk_angle - tf2::getYaw(current_pose.getRotation());
}
else
{
diff = tf2::getYaw(end_pose_.getRotation()) - tf2::getYaw(current_pose.getRotation());
}
double min_angle = (std::fmod(diff + M_PI, 2 * M_PI) - M_PI);
double vel = std::max(std::min(
config_.rotation_slow_down_factor * min_angle,
config_.max_rotation_vel),
-config_.max_rotation_vel);
if (distance < config_.position_accuracy && abs(min_angle) < config_.rotation_accuracy)
{
cmd_vel.linear.x = 0;
cmd_vel.linear.y = 0;
cmd_vel.angular.z = 0;
goal_reached_ = true;
}
else
{
cmd_vel.linear.x = std::cos(walk_angle - tf2::getYaw(current_pose.getRotation())) * walk_vel;
cmd_vel.linear.y = std::sin(walk_angle - tf2::getYaw(current_pose.getRotation())) * walk_vel;
cmd_vel.angular.z = vel;
goal_reached_ = false;
}
publishPlan(0);
ros::Time end = ros::Time::now();
ros::Duration duration = end - begin;
ROS_DEBUG("BBPlanner: Calculation time: %f seconds", duration.toSec());
return true;
}
bool BBPlanner::isGoalReached()
{
if (goal_reached_)
{
ROS_DEBUG("BBPlanner: Goal reached.");
}
return goal_reached_;
}
void BBPlanner::publishPlan(int max_point)
{
std::vector<geometry_msgs::PoseStamped> path;
path = transformed_global_plan_;
//given an empty path we won't do anything
if (path.empty())
return;
//create a path message
nav_msgs::Path gui_path;
gui_path.poses.resize(path.size());
gui_path.header.frame_id = path[0].header.frame_id;
gui_path.header.stamp = path[0].header.stamp;
// Extract the plan in world co-ordinates, we assume the path is all in the same frame
for (unsigned int i = 0; i < path.size(); i++)
{
gui_path.poses[i] = path[i];
}
local_plan_publisher_.publish(gui_path);
}
BBPlanner::~BBPlanner()
{
}
}
| 31.290323 | 125 | 0.576632 |
ea2e5481716ce5e091b30ed5aee0bd5819816eaf | 5,691 | hpp | C++ | Wp81Wol/Generated Files/MainPage.g.hpp | fredericGette/Wp81Wol | d2a10e64bdba71353720fcb38ac7230c3d9dd0e2 | [
"MIT"
] | null | null | null | Wp81Wol/Generated Files/MainPage.g.hpp | fredericGette/Wp81Wol | d2a10e64bdba71353720fcb38ac7230c3d9dd0e2 | [
"MIT"
] | null | null | null | Wp81Wol/Generated Files/MainPage.g.hpp | fredericGette/Wp81Wol | d2a10e64bdba71353720fcb38ac7230c3d9dd0e2 | [
"MIT"
] | null | null | null |
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
#include "pch.h"
#include "MainPage.xaml.h"
void ::Wp81Wol::MainPage::InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
// Call LoadComponent on ms-appx:///MainPage.xaml
::Windows::UI::Xaml::Application::LoadComponent(this, ref new ::Windows::Foundation::Uri(L"ms-appx:///MainPage.xaml"), ::Windows::UI::Xaml::Controls::Primitives::ComponentResourceLocation::Application);
// Get the StackPanel named 'PanelListComputerItem'
PanelListComputerItem = safe_cast<::Windows::UI::Xaml::Controls::StackPanel^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"PanelListComputerItem"));
// Get the StackPanel named 'PanelEditComputerItem'
PanelEditComputerItem = safe_cast<::Windows::UI::Xaml::Controls::StackPanel^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"PanelEditComputerItem"));
// Get the StackPanel named 'PanelHelp'
PanelHelp = safe_cast<::Windows::UI::Xaml::Controls::StackPanel^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"PanelHelp"));
// Get the TextBox named 'TextBoxName'
TextBoxName = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"TextBoxName"));
// Get the TextBox named 'TextBoxMacAddress'
TextBoxMacAddress = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"TextBoxMacAddress"));
// Get the TextBlock named 'ListViewIsEmpty'
ListViewIsEmpty = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"ListViewIsEmpty"));
// Get the ListView named 'ListViewComputerItem'
ListViewComputerItem = safe_cast<::Windows::UI::Xaml::Controls::ListView^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"ListViewComputerItem"));
// Get the Flyout named 'FlyoutNotification'
FlyoutNotification = safe_cast<::Windows::UI::Xaml::Controls::Flyout^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"FlyoutNotification"));
// Get the TextBlock named 'FlyoutNotificationText'
FlyoutNotificationText = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"FlyoutNotificationText"));
// Get the AppBarButton named 'AddAppBarButton'
AddAppBarButton = safe_cast<::Windows::UI::Xaml::Controls::AppBarButton^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"AddAppBarButton"));
// Get the AppBarButton named 'SaveAppBarButton'
SaveAppBarButton = safe_cast<::Windows::UI::Xaml::Controls::AppBarButton^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"SaveAppBarButton"));
// Get the AppBarButton named 'DeleteAppBarButton'
DeleteAppBarButton = safe_cast<::Windows::UI::Xaml::Controls::AppBarButton^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"DeleteAppBarButton"));
// Get the AppBarButton named 'HelpAppBarButton'
HelpAppBarButton = safe_cast<::Windows::UI::Xaml::Controls::AppBarButton^>(static_cast<Windows::UI::Xaml::IFrameworkElement^>(this)->FindName(L"HelpAppBarButton"));
}
void ::Wp81Wol::MainPage::Connect(int connectionId, Platform::Object^ target)
{
switch (connectionId)
{
case 1:
(safe_cast<::Windows::UI::Xaml::Controls::ListViewBase^>(target))->ItemClick +=
ref new ::Windows::UI::Xaml::Controls::ItemClickEventHandler(this, (void (::Wp81Wol::MainPage::*)(Platform::Object^, Windows::UI::Xaml::Controls::ItemClickEventArgs^))&MainPage::ItemView_ItemClick);
break;
case 2:
(safe_cast<::Windows::UI::Xaml::UIElement^>(target))->Holding +=
ref new ::Windows::UI::Xaml::Input::HoldingEventHandler(this, (void (::Wp81Wol::MainPage::*)(Platform::Object^, Windows::UI::Xaml::Input::HoldingRoutedEventArgs^))&MainPage::ItemView_Holding);
break;
case 3:
(safe_cast<::Windows::UI::Xaml::Controls::Primitives::ButtonBase^>(target))->Click +=
ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Wp81Wol::MainPage::*)(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^))&MainPage::AppBarButton_Click);
break;
case 4:
(safe_cast<::Windows::UI::Xaml::Controls::Primitives::ButtonBase^>(target))->Click +=
ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Wp81Wol::MainPage::*)(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^))&MainPage::AppBarButton_Click);
break;
case 5:
(safe_cast<::Windows::UI::Xaml::Controls::Primitives::ButtonBase^>(target))->Click +=
ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Wp81Wol::MainPage::*)(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^))&MainPage::AppBarButton_Click);
break;
case 6:
(safe_cast<::Windows::UI::Xaml::Controls::Primitives::ButtonBase^>(target))->Click +=
ref new ::Windows::UI::Xaml::RoutedEventHandler(this, (void (::Wp81Wol::MainPage::*)(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^))&MainPage::AppBarButton_Click);
break;
}
(void)connectionId; // Unused parameter
(void)target; // Unused parameter
_contentLoaded = true;
}
| 65.413793 | 210 | 0.686523 |
ea2f9e99d5b76a029fb58104b9313e546e674578 | 576 | hpp | C++ | hw3/src/object/geometry.hpp | xupei0610/ComputerGraphics-HW | 299416c0d75db17f6490bbab95a3561210a6277e | [
"MIT"
] | 2 | 2017-10-11T13:48:30.000Z | 2020-06-04T05:30:13.000Z | hw3/src/object/geometry.hpp | xupei0610/ComputerGraphics-HW | 299416c0d75db17f6490bbab95a3561210a6277e | [
"MIT"
] | null | null | null | hw3/src/object/geometry.hpp | xupei0610/ComputerGraphics-HW | 299416c0d75db17f6490bbab95a3561210a6277e | [
"MIT"
] | 2 | 2018-10-05T15:37:29.000Z | 2021-12-20T15:25:48.000Z | #ifndef PX_CG_OBJECT_GEOMETRY_HPP
#define PX_CG_OBJECT_GEOMETRY_HPP
#include "object/geometry/base_geometry.hpp"
#include "object/geometry/box.hpp"
#include "object/geometry/cone.hpp"
#include "object/geometry/cylinder.hpp"
#include "object/geometry/disk.hpp"
#include "object/geometry/ellipsoid.hpp"
#include "object/geometry/normal_triangle.hpp"
#include "object/geometry/plane.hpp"
#include "object/geometry/quadric.hpp"
#include "object/geometry/ring.hpp"
#include "object/geometry/sphere.hpp"
#include "object/geometry/triangle.hpp"
#endif // PX_CG_OBJECT_GEOMETRY_HPP
| 32 | 46 | 0.809028 |
ea317fbca3e28c10b4b0e577e351cf6a6bbd06c9 | 6,197 | cpp | C++ | src/Framework/Utility.cpp | Belfer/SFMLTemplate | 7dcf4aa26239252597d681ca72888463cd4a54b0 | [
"MIT"
] | null | null | null | src/Framework/Utility.cpp | Belfer/SFMLTemplate | 7dcf4aa26239252597d681ca72888463cd4a54b0 | [
"MIT"
] | null | null | null | src/Framework/Utility.cpp | Belfer/SFMLTemplate | 7dcf4aa26239252597d681ca72888463cd4a54b0 | [
"MIT"
] | null | null | null | #include "Utility.hpp"
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include <fstream>
#include <streambuf>
#define ASSERT(expr) assert(expr)
std::string Utility::LoadTextFile(const std::string& filepath)
{
std::ifstream t(filepath);
return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
}
bool LoadObj(const std::string& directory, const std::string& filename, tinyobj::attrib_t& attrib, std::vector<tinyobj::shape_t>& shapes, std::vector<tinyobj::material_t>& materials)
{
std::string warn;
std::string err;
std::string& filepath = directory.size() > 0 ? directory + "/" + filename : filename;
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filepath.c_str(), directory.c_str());
if (!warn.empty())
std::cout << warn << std::endl;
if (!err.empty())
std::cerr << err << std::endl;
return ret;
}
void ParseVertex(VertexPNCT& vertex, const tinyobj::index_t& idx, const tinyobj::attrib_t& attrib)
{
// access to vertex
vertex.position.x = attrib.vertices[(3 * idx.vertex_index) + 0];
vertex.position.y = attrib.vertices[(3 * idx.vertex_index) + 1];
vertex.position.z = attrib.vertices[(3 * idx.vertex_index) + 2];
vertex.normal.x = attrib.normals[(3 * idx.normal_index) + 0];
vertex.normal.y = attrib.normals[(3 * idx.normal_index) + 1];
vertex.normal.z = attrib.normals[(3 * idx.normal_index) + 2];
vertex.texcoord.x = attrib.texcoords[(2 * idx.texcoord_index) + 0];
vertex.texcoord.y = attrib.texcoords[(2 * idx.texcoord_index) + 1];
vertex.color.r = attrib.colors[3 * idx.vertex_index + 0];
vertex.color.g = attrib.colors[3 * idx.vertex_index + 1];
vertex.color.b = attrib.colors[3 * idx.vertex_index + 2];
vertex.color.a = 1.0f;
}
Model Utility::LoadModel(const std::string& directory, const std::string& filename)
{
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
if (!LoadObj(directory, filename, attrib, shapes, materials))
throw;
Model model;
if (materials.size() > 0)
{
Material& material = model.material;
material.diffuse = glm::vec3(materials[0].diffuse[0], materials[0].diffuse[1], materials[0].diffuse[2]);
sf::Image image;
if (image.loadFromFile((directory + "/" + materials[0].diffuse_texname).c_str()))
{
sf::Vector2u imageSize = image.getSize();
material.albedo = Graphics::CreateTexture(TextureFormat::RBGA32, 1, imageSize.x, imageSize.y, image.getPixelsPtr(), true);
Graphics::FilterTexture(material.albedo, TextureWrap::REPEAT, TextureWrap::REPEAT, TextureFilter::LINEAR_LINEAR, TextureFilter::LINEAR);
}
material.attributeFormat = VertexPNCT::format;
}
std::vector<VertexPNCT> meshData;
// Loop over shapes
for (size_t s = 0; s < shapes.size(); s++)
{
// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++)
{
int fv = shapes[s].mesh.num_face_vertices[f];
// Loop over vertices in the face.
for (size_t v = 0; v < fv; v++)
{
VertexPNCT vertex;
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
ParseVertex(vertex, idx, attrib);
meshData.emplace_back(vertex);
}
index_offset += fv;
}
}
Mesh& mesh = model.mesh;
mesh.vBuffer = Graphics::CreateBuffer(1, meshData.size() * (sizeof(VertexPNCT) / sizeof(float)), &meshData[0], false, false);
mesh.count = meshData.size();
return model;
}
std::vector<Model> Utility::LoadScene(const std::string& directory, const std::string& filename)
{
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
if (!LoadObj(directory, filename, attrib, shapes, materials))
throw;
std::vector<Model> models(materials.size());
for (size_t i = 0; i < materials.size(); i++)
{
Material& material = models[i].material;
material.diffuse = glm::vec3(materials[i].diffuse[0], materials[i].diffuse[1], materials[i].diffuse[2]);
sf::Image image;
if (image.loadFromFile((directory + "/" + materials[i].diffuse_texname).c_str()))
{
sf::Vector2u imageSize = image.getSize();
material.albedo = Graphics::CreateTexture(TextureFormat::RBGA32, 1, imageSize.x, imageSize.y, image.getPixelsPtr(), true);
Graphics::FilterTexture(material.albedo, TextureWrap::REPEAT, TextureWrap::REPEAT, TextureFilter::LINEAR_LINEAR, TextureFilter::LINEAR);
}
material.attributeFormat = VertexPNCT::format;
}
std::vector<std::vector<VertexPNCT>> meshData(materials.size());
// Loop over shapes
for (size_t s = 0; s < shapes.size(); s++)
{
// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++)
{
// per-face material
int matId = shapes[s].mesh.material_ids[f];
std::vector<VertexPNCT>& data = meshData[matId];
int fv = shapes[s].mesh.num_face_vertices[f];
// Loop over vertices in the face.
for (size_t v = 0; v < fv; v++)
{
VertexPNCT vertex;
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
ParseVertex(vertex, idx, attrib);
data.emplace_back(vertex);
}
index_offset += fv;
}
}
for (size_t i = 0; i < materials.size(); i++)
{
std::vector<VertexPNCT>& data = meshData[i];
Mesh& mesh = models[i].mesh;
mesh.vBuffer = Graphics::CreateBuffer(1, data.size() * (sizeof(VertexPNCT) / sizeof(float)), &data[0], false, false);
mesh.count = data.size();
}
return models;
} | 35.210227 | 182 | 0.616589 |
ea31ecc3290c6e3646cb56c0b0742d4a0f278456 | 83 | hpp | C++ | Safety/Inc/RSSI.hpp | YashrajN/ZeroPilot-SW | 3418f7050443af86bc0e7cc8e58177a95adc40eb | [
"BSD-4-Clause"
] | 15 | 2017-09-12T14:54:16.000Z | 2021-09-21T23:28:57.000Z | Safety/Inc/RSSI.hpp | YashrajN/ZeroPilot-SW | 3418f7050443af86bc0e7cc8e58177a95adc40eb | [
"BSD-4-Clause"
] | 67 | 2017-10-31T02:04:44.000Z | 2022-03-28T01:02:25.000Z | Safety/Inc/RSSI.hpp | YashrajN/ZeroPilot-SW | 3418f7050443af86bc0e7cc8e58177a95adc40eb | [
"BSD-4-Clause"
] | 48 | 2017-09-28T23:47:17.000Z | 2022-01-08T18:30:40.000Z | #ifndef RSSI_HPP
#define RSSI_HPP
bool CommsFailed();
void RSSI_Check();
#endif
| 9.222222 | 19 | 0.746988 |
ea32bfeb3470f003807075e55be23f2238848833 | 2,542 | cpp | C++ | src/capi/impl/capi_initialization.cpp | meiwanlanjun/turicreate | acd1422e82e4dabd6da7a3f82771dbf2f0474b1b | [
"BSD-3-Clause"
] | null | null | null | src/capi/impl/capi_initialization.cpp | meiwanlanjun/turicreate | acd1422e82e4dabd6da7a3f82771dbf2f0474b1b | [
"BSD-3-Clause"
] | null | null | null | src/capi/impl/capi_initialization.cpp | meiwanlanjun/turicreate | acd1422e82e4dabd6da7a3f82771dbf2f0474b1b | [
"BSD-3-Clause"
] | null | null | null | /* Copyright © 2018 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include <unity/server/unity_server_control.hpp>
#include <unity/server/unity_server_options.hpp>
#include <unity/server/unity_server.hpp>
#include <capi/impl/capi_initialization.hpp>
#include <capi/impl/capi_initialization_internal.hpp>
#include <capi/impl/capi_error_handling.hpp>
// All the functions related to the initialization of the server.
namespace turi {
// Create and return the server options.
static unity_server_options& _get_server_options() {
static std::unique_ptr<turi::unity_server_options> _server_options;
if (_server_options == nullptr) {
_server_options.reset(new unity_server_options);
_server_options->log_file = "/var/log/";
_server_options->root_path = "";
_server_options->daemon = false;
_server_options->log_rotation_interval = 0;
_server_options->log_rotation_truncate = 0;
}
return *_server_options;
}
///////////////////////////////////////////////////////////////////////////////
//
// The server is initialized on demand.
bool capi_server_initialized = false;
static std::mutex _capi_server_initializer_lock;
EXPORT void _tc_initialize() {
std::lock_guard<std::mutex> lg(_capi_server_initializer_lock);
if (capi_server_initialized) {
return;
}
turi::start_server(_get_server_options(), *capi_server_initializer());
capi_server_initialized = true;
// Set up the progress logger to log progress to stdout.
global_logger().add_observer(LOG_PROGRESS,
[](int, const char* buf, size_t len) {
for (; len != 0; --len) {
std::cout << *buf;
++buf;
}
std::cout << std::flush;
});
}
} // namespace turi
// The user facing components of the server initialization
extern "C" {
EXPORT void tc_setup_log_location(const char* log_file, tc_error** error) {
ERROR_HANDLE_START();
std::lock_guard<std::mutex> lg(turi::_capi_server_initializer_lock);
if (turi::capi_server_initialized) {
set_error(error, "CAPI server is already initialized; call setup functions before all other functions.");
return;
}
turi::_get_server_options().log_file = log_file;
ERROR_HANDLE_END(error);
}
}
| 29.905882 | 109 | 0.651849 |
ea3498abc15747fdba49966c1e4ee69294837816 | 22,249 | cpp | C++ | Engine/Source/Runtime/CoreUObject/Private/Serialization/PropertyLocalizationDataGathering.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/CoreUObject/Private/Serialization/PropertyLocalizationDataGathering.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/CoreUObject/Private/Serialization/PropertyLocalizationDataGathering.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Serialization/PropertyLocalizationDataGathering.h"
#include "UObject/Script.h"
#include "UObject/ObjectMacros.h"
#include "UObject/UObjectHash.h"
#include "UObject/Class.h"
#include "UObject/Package.h"
#include "UObject/UnrealType.h"
#include "UObject/TextProperty.h"
#include "UObject/PropertyPortFlags.h"
#include "HAL/UnrealMemory.h"
#include "Internationalization/TextNamespaceUtil.h"
#include "Internationalization/TextPackageNamespaceUtil.h"
FPropertyLocalizationDataGatherer::FPropertyLocalizationDataGatherer(TArray<FGatherableTextData>& InOutGatherableTextDataArray, const UPackage* const InPackage, EPropertyLocalizationGathererResultFlags& OutResultFlags)
: GatherableTextDataArray(InOutGatherableTextDataArray)
, Package(InPackage)
, ResultFlags(OutResultFlags)
, AllObjectsInPackage()
{
// Build up the list of objects that are within our package - we won't follow object references to things outside of our package
{
TArray<UObject*> AllObjectsInPackageArray;
GetObjectsWithOuter(Package, AllObjectsInPackageArray, true, RF_Transient, EInternalObjectFlags::PendingKill);
AllObjectsInPackage.Reserve(AllObjectsInPackageArray.Num());
for (UObject* Object : AllObjectsInPackageArray)
{
AllObjectsInPackage.Add(Object);
}
}
TArray<UObject*> RootObjectsInPackage;
GetObjectsWithOuter(Package, RootObjectsInPackage, false, RF_Transient, EInternalObjectFlags::PendingKill);
// Iterate over each root object in the package
for (const UObject* Object : RootObjectsInPackage)
{
GatherLocalizationDataFromObjectWithCallbacks(Object, EPropertyLocalizationGathererTextFlags::None);
}
}
bool FPropertyLocalizationDataGatherer::ShouldProcessObject(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags) const
{
if (Object->HasAnyFlags(RF_Transient))
{
// Transient objects aren't saved, so skip them as part of the gather
return false;
}
// Skip objects that we've already processed to avoid repeated work and cyclic chains
const bool bAlreadyProcessed = ProcessedObjects.Contains(FObjectAndGatherFlags(Object, GatherTextFlags));
return !bAlreadyProcessed;
}
void FPropertyLocalizationDataGatherer::MarkObjectProcessed(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags)
{
ProcessedObjects.Add(FObjectAndGatherFlags(Object, GatherTextFlags));
}
void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromObjectWithCallbacks(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags)
{
// See if we have a custom handler for this type
FLocalizationDataGatheringCallback* CustomCallback = nullptr;
for (const UClass* Class = Object->GetClass(); Class != nullptr; Class = Class->GetSuperClass())
{
CustomCallback = GetTypeSpecificLocalizationDataGatheringCallbacks().Find(Class);
if (CustomCallback)
{
break;
}
}
if (CustomCallback)
{
checkf(IsObjectValidForGather(Object), TEXT("Cannot gather for objects outside of the current package! Package: '%s'. Object: '%s'."), *Package->GetFullName(), *Object->GetFullName());
if (ShouldProcessObject(Object, GatherTextFlags))
{
MarkObjectProcessed(Object, GatherTextFlags);
(*CustomCallback)(Object, *this, GatherTextFlags);
}
}
else if (ShouldProcessObject(Object, GatherTextFlags))
{
MarkObjectProcessed(Object, GatherTextFlags);
GatherLocalizationDataFromObject(Object, GatherTextFlags);
}
}
void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromObject(const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags)
{
checkf(IsObjectValidForGather(Object), TEXT("Cannot gather for objects outside of the current package! Package: '%s'. Object: '%s'."), *Package->GetFullName(), *Object->GetFullName());
const FString Path = Object->GetPathName();
// Gather text from our fields.
GatherLocalizationDataFromObjectFields(Path, Object, GatherTextFlags);
// Also gather from the script data on UStruct types.
{
if (!!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::ForceHasScript))
{
ResultFlags |= EPropertyLocalizationGathererResultFlags::HasScript;
}
const UStruct* Struct = Cast<UStruct>(Object);
if (Struct)
{
GatherScriptBytecode(Path, Struct->Script, !!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::ForceEditorOnlyScriptData));
}
}
// Gather from anything that has us as their outer, as not all objects are reachable via a property pointer.
if (!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::SkipSubObjects))
{
TArray<UObject*> ChildObjects;
GetObjectsWithOuter(Object, ChildObjects, false, RF_Transient, EInternalObjectFlags::PendingKill);
for (const UObject* ChildObject : ChildObjects)
{
GatherLocalizationDataFromObjectWithCallbacks(ChildObject, GatherTextFlags);
}
}
}
void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromObjectFields(const FString& PathToParent, const UObject* Object, const EPropertyLocalizationGathererTextFlags GatherTextFlags)
{
const UObject* ArchetypeObject = Object->GetArchetype();
for (TFieldIterator<const UField> FieldIt(Object->GetClass(), EFieldIteratorFlags::IncludeSuper, EFieldIteratorFlags::ExcludeDeprecated, EFieldIteratorFlags::IncludeInterfaces); FieldIt; ++FieldIt)
{
// Gather text from the property data
{
const UProperty* PropertyField = Cast<UProperty>(*FieldIt);
if (PropertyField)
{
const void* ValueAddress = PropertyField->ContainerPtrToValuePtr<void>(Object);
const void* DefaultValueAddress = nullptr;
if (ArchetypeObject)
{
const UProperty* ArchetypePropertyField = FindField<UProperty>(ArchetypeObject->GetClass(), *PropertyField->GetName());
if (ArchetypePropertyField && ArchetypePropertyField->IsA(PropertyField->GetClass()))
{
DefaultValueAddress = ArchetypePropertyField->ContainerPtrToValuePtr<void>(ArchetypeObject);
}
}
GatherLocalizationDataFromChildTextProperties(PathToParent, PropertyField, ValueAddress, DefaultValueAddress, GatherTextFlags | (PropertyField->HasAnyPropertyFlags(CPF_EditorOnly) ? EPropertyLocalizationGathererTextFlags::ForceEditorOnly : EPropertyLocalizationGathererTextFlags::None));
}
}
// Gather text from the script bytecode
{
const UStruct* StructField = Cast<UStruct>(*FieldIt);
if (StructField && IsObjectValidForGather(StructField) && ShouldProcessObject(StructField, GatherTextFlags))
{
MarkObjectProcessed(StructField, GatherTextFlags);
GatherLocalizationDataFromObject(StructField, GatherTextFlags);
}
}
}
}
void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromStructFields(const FString& PathToParent, const UStruct* Struct, const void* StructData, const void* DefaultStructData, const EPropertyLocalizationGathererTextFlags GatherTextFlags)
{
const UStruct* ArchetypeStruct = Cast<UStruct>(Struct->GetArchetype());
for (TFieldIterator<const UField> FieldIt(Struct, EFieldIteratorFlags::IncludeSuper, EFieldIteratorFlags::ExcludeDeprecated, EFieldIteratorFlags::IncludeInterfaces); FieldIt; ++FieldIt)
{
// Gather text from the property data
{
const UProperty* PropertyField = Cast<UProperty>(*FieldIt);
if (PropertyField)
{
const void* ValueAddress = PropertyField->ContainerPtrToValuePtr<void>(StructData);
const void* DefaultValueAddress = nullptr;
if (ArchetypeStruct && DefaultStructData)
{
const UProperty* ArchetypePropertyField = FindField<UProperty>(ArchetypeStruct, *PropertyField->GetName());
if (ArchetypePropertyField && ArchetypePropertyField->IsA(PropertyField->GetClass()))
{
DefaultValueAddress = ArchetypePropertyField->ContainerPtrToValuePtr<void>(DefaultStructData);
}
}
GatherLocalizationDataFromChildTextProperties(PathToParent, PropertyField, ValueAddress, DefaultValueAddress, GatherTextFlags | (PropertyField->HasAnyPropertyFlags(CPF_EditorOnly) ? EPropertyLocalizationGathererTextFlags::ForceEditorOnly : EPropertyLocalizationGathererTextFlags::None));
}
}
// Gather text from the script bytecode
{
const UStruct* StructField = Cast<UStruct>(*FieldIt);
if (StructField && IsObjectValidForGather(StructField) && ShouldProcessObject(StructField, GatherTextFlags))
{
MarkObjectProcessed(StructField, GatherTextFlags);
GatherLocalizationDataFromObject(StructField, GatherTextFlags);
}
}
}
}
void FPropertyLocalizationDataGatherer::GatherLocalizationDataFromChildTextProperties(const FString& PathToParent, const UProperty* const Property, const void* const ValueAddress, const void* const DefaultValueAddress, const EPropertyLocalizationGathererTextFlags GatherTextFlags)
{
if (Property->HasAnyPropertyFlags(CPF_Transient))
{
// Transient properties aren't saved, so skip them as part of the gather
return;
}
const UTextProperty* const TextProperty = Cast<const UTextProperty>(Property);
const UArrayProperty* const ArrayProperty = Cast<const UArrayProperty>(Property);
const UMapProperty* const MapProperty = Cast<const UMapProperty>(Property);
const USetProperty* const SetProperty = Cast<const USetProperty>(Property);
const UStructProperty* const StructProperty = Cast<const UStructProperty>(Property);
const UObjectPropertyBase* const ObjectProperty = Cast<const UObjectPropertyBase>(Property);
const EPropertyLocalizationGathererTextFlags ChildPropertyGatherTextFlags = GatherTextFlags | (Property->HasAnyPropertyFlags(CPF_EditorOnly) ? EPropertyLocalizationGathererTextFlags::ForceEditorOnly : EPropertyLocalizationGathererTextFlags::None);
// Handles both native, fixed-size arrays and plain old non-array properties.
const bool IsFixedSizeArray = Property->ArrayDim > 1;
for(int32 i = 0; i < Property->ArrayDim; ++i)
{
const FString PathToElement = FString(PathToParent.IsEmpty() ? TEXT("") : PathToParent + TEXT(".")) + (IsFixedSizeArray ? Property->GetName() + FString::Printf(TEXT("[%d]"), i) : Property->GetName());
const void* const ElementValueAddress = reinterpret_cast<const uint8*>(ValueAddress) + Property->ElementSize * i;
const void* const DefaultElementValueAddress = DefaultValueAddress ? (reinterpret_cast<const uint8*>(DefaultValueAddress) + Property->ElementSize * i) : nullptr;
const bool bIsDefaultValue = DefaultElementValueAddress && Property->Identical(ElementValueAddress, DefaultElementValueAddress, PPF_None);
if (bIsDefaultValue)
{
// Skip any properties that have the default value, as those will be gathered from the default instance
continue;
}
// Property is a text property.
if (TextProperty)
{
const FText* const TextElementValueAddress = static_cast<const FText*>(ElementValueAddress);
UPackage* const PropertyPackage = TextProperty->GetOutermost();
if (FTextInspector::GetFlags(*TextElementValueAddress) & ETextFlag::ConvertedProperty)
{
PropertyPackage->MarkPackageDirty();
}
GatherTextInstance(*TextElementValueAddress, PathToElement, !!(GatherTextFlags & EPropertyLocalizationGathererTextFlags::ForceEditorOnlyProperties) || TextProperty->HasAnyPropertyFlags(CPF_EditorOnly));
}
// Property is a DYNAMIC array property.
else if (ArrayProperty)
{
// Iterate over all elements of the array.
FScriptArrayHelper ScriptArrayHelper(ArrayProperty, ElementValueAddress);
const int32 ElementCount = ScriptArrayHelper.Num();
for(int32 j = 0; j < ElementCount; ++j)
{
GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d)"), j), ArrayProperty->Inner, ScriptArrayHelper.GetRawPtr(j), nullptr, ChildPropertyGatherTextFlags);
}
}
// Property is a map property.
else if (MapProperty)
{
// Iterate over all elements of the map.
FScriptMapHelper ScriptMapHelper(MapProperty, ElementValueAddress);
const int32 ElementCount = ScriptMapHelper.Num();
for(int32 j = 0, ElementIndex = 0; ElementIndex < ElementCount; ++j)
{
if (!ScriptMapHelper.IsValidIndex(j))
{
continue;
}
const uint8* MapPairPtr = ScriptMapHelper.GetPairPtr(j);
GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d - Key)"), ElementIndex), MapProperty->KeyProp, MapPairPtr + MapProperty->MapLayout.KeyOffset, nullptr, ChildPropertyGatherTextFlags);
GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d - Value)"), ElementIndex), MapProperty->ValueProp, MapPairPtr + MapProperty->MapLayout.ValueOffset, nullptr, ChildPropertyGatherTextFlags);
++ElementIndex;
}
}
// Property is a set property.
else if (SetProperty)
{
// Iterate over all elements of the Set.
FScriptSetHelper ScriptSetHelper(SetProperty, ElementValueAddress);
const int32 ElementCount = ScriptSetHelper.Num();
for(int32 j = 0, ElementIndex = 0; ElementIndex < ElementCount; ++j)
{
if (!ScriptSetHelper.IsValidIndex(j))
{
continue;
}
const uint8* ElementPtr = ScriptSetHelper.GetElementPtr(j);
GatherLocalizationDataFromChildTextProperties(PathToElement + FString::Printf(TEXT("(%d)"), ElementIndex), SetProperty->ElementProp, ElementPtr + SetProperty->SetLayout.ElementOffset, nullptr, ChildPropertyGatherTextFlags);
++ElementIndex;
}
}
// Property is a struct property.
else if (StructProperty)
{
GatherLocalizationDataFromStructFields(PathToElement, StructProperty->Struct, ElementValueAddress, DefaultElementValueAddress, ChildPropertyGatherTextFlags);
}
// Property is an object property.
else if (ObjectProperty && !(GatherTextFlags & EPropertyLocalizationGathererTextFlags::SkipSubObjects))
{
const UObject* InnerObject = ObjectProperty->GetObjectPropertyValue(ElementValueAddress);
if (InnerObject && IsObjectValidForGather(InnerObject))
{
GatherLocalizationDataFromObjectWithCallbacks(InnerObject, ChildPropertyGatherTextFlags);
}
}
}
}
void FPropertyLocalizationDataGatherer::GatherTextInstance(const FText& Text, const FString& Description, const bool bIsEditorOnly)
{
auto AddGatheredText = [this, &Description](const FString& InNamespace, const FString& InKey, const FTextSourceData& InSourceData, const bool InIsEditorOnly)
{
FGatherableTextData* GatherableTextData = GatherableTextDataArray.FindByPredicate([&](const FGatherableTextData& Candidate)
{
return Candidate.NamespaceName.Equals(InNamespace, ESearchCase::CaseSensitive)
&& Candidate.SourceData.SourceString.Equals(InSourceData.SourceString, ESearchCase::CaseSensitive)
&& Candidate.SourceData.SourceStringMetaData == InSourceData.SourceStringMetaData;
});
if (!GatherableTextData)
{
GatherableTextData = &GatherableTextDataArray[GatherableTextDataArray.AddDefaulted()];
GatherableTextData->NamespaceName = InNamespace;
GatherableTextData->SourceData = InSourceData;
}
// We might attempt to add the same text multiple times if we process the same object with slightly different flags - only add this source site once though.
{
static const FLocMetadataObject DefaultMetadataObject;
const bool bFoundSourceSiteContext = GatherableTextData->SourceSiteContexts.ContainsByPredicate([&](const FTextSourceSiteContext& InSourceSiteContext) -> bool
{
return InSourceSiteContext.KeyName.Equals(InKey, ESearchCase::CaseSensitive)
&& InSourceSiteContext.SiteDescription.Equals(Description, ESearchCase::CaseSensitive)
&& InSourceSiteContext.IsEditorOnly == InIsEditorOnly
&& InSourceSiteContext.IsOptional == false
&& InSourceSiteContext.InfoMetaData == DefaultMetadataObject
&& InSourceSiteContext.KeyMetaData == DefaultMetadataObject;
});
if (!bFoundSourceSiteContext)
{
FTextSourceSiteContext& SourceSiteContext = GatherableTextData->SourceSiteContexts[GatherableTextData->SourceSiteContexts.AddDefaulted()];
SourceSiteContext.KeyName = InKey;
SourceSiteContext.SiteDescription = Description;
SourceSiteContext.IsEditorOnly = InIsEditorOnly;
SourceSiteContext.IsOptional = false;
}
}
};
FString Namespace;
FString Key;
const FTextDisplayStringRef DisplayString = FTextInspector::GetSharedDisplayString(Text);
const bool bFoundNamespaceAndKey = FTextLocalizationManager::Get().FindNamespaceAndKeyFromDisplayString(DisplayString, Namespace, Key);
if (!bFoundNamespaceAndKey || !Text.ShouldGatherForLocalization())
{
return;
}
ResultFlags |= EPropertyLocalizationGathererResultFlags::HasText;
FTextSourceData SourceData;
{
const FString* SourceString = FTextInspector::GetSourceString(Text);
SourceData.SourceString = SourceString ? *SourceString : FString();
}
#if USE_STABLE_LOCALIZATION_KEYS
// Make sure the namespace is what we expect for this package
// This would usually be done when the text is loaded, but we also gather text when saving packages so we need to make sure things are consistent
{
const FString PackageNamespace = TextNamespaceUtil::GetPackageNamespace(Package);
if (!PackageNamespace.IsEmpty())
{
Namespace = TextNamespaceUtil::BuildFullNamespace(Namespace, PackageNamespace);
}
}
#endif // USE_STABLE_LOCALIZATION_KEYS
// Always include the text without its package localization ID
const FString CleanNamespace = TextNamespaceUtil::StripPackageNamespace(Namespace);
AddGatheredText(CleanNamespace, Key, SourceData, bIsEditorOnly);
}
struct FGatherTextFromScriptBytecode
{
public:
FGatherTextFromScriptBytecode(const TCHAR* InSourceDescription, const TArray<uint8>& InScript, FPropertyLocalizationDataGatherer& InPropertyLocalizationDataGatherer, const bool InTreatAsEditorOnlyData)
: SourceDescription(InSourceDescription)
, Script(const_cast<TArray<uint8>&>(InScript)) // We won't change the script, but we have to lie so that the code in ScriptSerialization.h will compile :(
, PropertyLocalizationDataGatherer(InPropertyLocalizationDataGatherer)
, bTreatAsEditorOnlyData(InTreatAsEditorOnlyData)
, bIsParsingText(false)
{
const int32 ScriptSizeBytes = Script.Num();
int32 iCode = 0;
while (iCode < ScriptSizeBytes)
{
SerializeExpr(iCode, DummyArchive);
}
}
private:
FLinker* GetLinker()
{
return nullptr;
}
EExprToken SerializeExpr(int32& iCode, FArchive& Ar)
{
#define XFERSTRING() SerializeString(iCode, Ar)
#define XFERUNICODESTRING() SerializeUnicodeString(iCode, Ar)
#define XFERTEXT() SerializeText(iCode, Ar)
#define SERIALIZEEXPR_INC
#define SERIALIZEEXPR_AUTO_UNDEF_XFER_MACROS
#include "ScriptSerialization.h"
return Expr;
#undef SERIALIZEEXPR_INC
#undef SERIALIZEEXPR_AUTO_UNDEF_XFER_MACROS
}
void SerializeString(int32& iCode, FArchive& Ar)
{
if (bIsParsingText)
{
LastParsedString.Reset();
do
{
LastParsedString += (char)(Script[iCode]);
iCode += sizeof(uint8);
}
while (Script[iCode-1]);
}
else
{
do
{
iCode += sizeof(uint8);
}
while (Script[iCode-1]);
}
}
void SerializeUnicodeString(int32& iCode, FArchive& Ar)
{
if (bIsParsingText)
{
LastParsedString.Reset();
do
{
uint16 UnicodeChar = 0;
#ifdef REQUIRES_ALIGNED_INT_ACCESS
FMemory::Memcpy(&UnicodeChar, &Script[iCode], sizeof(uint16));
#else
UnicodeChar = *((uint16*)(&Script[iCode]));
#endif
LastParsedString += (TCHAR)UnicodeChar;
iCode += sizeof(uint16);
}
while (Script[iCode-1] || Script[iCode-2]);
}
else
{
do
{
iCode += sizeof(uint16);
}
while (Script[iCode-1] || Script[iCode-2]);
}
}
void SerializeText(int32& iCode, FArchive& Ar)
{
// What kind of text are we dealing with?
const EBlueprintTextLiteralType TextLiteralType = (EBlueprintTextLiteralType)Script[iCode++];
switch (TextLiteralType)
{
case EBlueprintTextLiteralType::Empty:
// Don't need to gather empty text
break;
case EBlueprintTextLiteralType::LocalizedText:
{
bIsParsingText = true;
SerializeExpr(iCode, Ar);
const FString SourceString = MoveTemp(LastParsedString);
SerializeExpr(iCode, Ar);
const FString TextKey = MoveTemp(LastParsedString);
SerializeExpr(iCode, Ar);
const FString TextNamespace = MoveTemp(LastParsedString);
bIsParsingText = false;
const FText TextInstance = FInternationalization::ForUseOnlyByLocMacroAndGraphNodeTextLiterals_CreateText(*SourceString, *TextNamespace, *TextKey);
PropertyLocalizationDataGatherer.GatherTextInstance(TextInstance, FString::Printf(TEXT("%s [Script Bytecode]"), SourceDescription), bTreatAsEditorOnlyData);
}
break;
case EBlueprintTextLiteralType::InvariantText:
// Don't need to gather invariant text, but we do need to walk over the string in the buffer
SerializeExpr(iCode, Ar);
break;
case EBlueprintTextLiteralType::LiteralString:
// Don't need to gather literal strings, but we do need to walk over the string in the buffer
SerializeExpr(iCode, Ar);
break;
case EBlueprintTextLiteralType::StringTableEntry:
// Don't need to gather string table entries, but we do need to walk over the strings in the buffer
iCode += sizeof(ScriptPointerType); // String Table asset (if any)
SerializeExpr(iCode, Ar);
SerializeExpr(iCode, Ar);
break;
default:
checkf(false, TEXT("Unknown EBlueprintTextLiteralType! Please update FGatherTextFromScriptBytecode::SerializeText to handle this type of text."));
break;
}
}
const TCHAR* SourceDescription;
TArray<uint8>& Script;
FPropertyLocalizationDataGatherer& PropertyLocalizationDataGatherer;
bool bTreatAsEditorOnlyData;
FArchive DummyArchive;
bool bIsParsingText;
FString LastParsedString;
};
void FPropertyLocalizationDataGatherer::GatherScriptBytecode(const FString& PathToScript, const TArray<uint8>& ScriptData, const bool bIsEditorOnly)
{
if (ScriptData.Num() > 0)
{
ResultFlags |= EPropertyLocalizationGathererResultFlags::HasScript;
}
FGatherTextFromScriptBytecode(*PathToScript, ScriptData, *this, bIsEditorOnly);
}
FPropertyLocalizationDataGatherer::FLocalizationDataGatheringCallbackMap& FPropertyLocalizationDataGatherer::GetTypeSpecificLocalizationDataGatheringCallbacks()
{
static FLocalizationDataGatheringCallbackMap TypeSpecificLocalizationDataGatheringCallbacks;
return TypeSpecificLocalizationDataGatheringCallbacks;
}
| 39.378761 | 291 | 0.779046 |
ea3b9a0fde1686640ccbd54de121d3eef0fca70c | 23,497 | cpp | C++ | pepnovo/src/main.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | pepnovo/src/main.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | pepnovo/src/main.cpp | compomics/jwrapper-pepnovo | 1bd21a4910d7515dfab7747711917176a6b5ce99 | [
"Apache-2.0"
] | null | null | null | #include "AdvancedScoreModel.h"
#include "FileManagement.h"
#include "Fragmentation.h"
#include "DeNovoDp.h"
#include "QuickClustering.h"
#include "EdgeModel.h"
#include "FragmentSelection.h"
#include "MSBlast.h"
#include "PMCSQS.h"
#include "PeakRankStats.h"
#include "PeptideRankScorer.h"
#include "DeNovoSolutions.h"
#include "auxfun.h"
#include "includes.h"
int main()
{
Config *config=NULL;
FileManager fm;
FileSet fs;
AdvancedScoreModel model;
EdgeModel edge_model;
PeptideRankScorer drs;
rand_seed(112233);
// train_all();
model.read_model("CID_IT_TRYP");
config = model.get_config();
config->apply_selected_PTMs("C+57:M+16:Q-17");
// fm.init_from_file(config,"C:\\Work\\msms5\\DnvScore\\all_ds\\HEK_98_3_unique_30.mgf");
fs.select_files_in_mz_range(fm,300,2000,3);
fs.randomly_reduce_ssfs(100);
vector<int> cc(4,0);
cc[3]=100;
fs.create_mgf_file(fm,config,"HEK_4_30e.mgf",cc);
exit(0);
// model.get_config()->apply_selected_PTMs("C+57:M+16:Q-17");
PMCSQS_Scorer *pmcsqs = (PMCSQS_Scorer *)model.get_pmcsqs_ptr();
fm.init_from_list_file(config,"C:\\Work\\msms5\\PepNovoHQ\\train3.txt");
pmcsqs->benchmark_pm_selection(config,fm,0.3);
exit(0);
/* benchmark_shew(model,"C:\\Work\\msms5\\PepNovoHQ\\Shew_test_10.mgf");
exit(0);
drs.set_model_type(0);
drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DBSCORE\\DBSCORE_rank_model.txt");
drs.give_de_novo_and_peak_match_examples("C:\\Work\\msms5\\DnvScore\\all_db_hits",
"C:\\Work\\msms5\\DnvScore\\seq_freqs\\sequences",
"C:\\Work\\msms5\\DnvScore\\dnv_full_parts",
"C:\\Work\\msms5\\DnvScore\\dicty2_all.txt",
2,2);
exit(0);
drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DBSCORE\\DBSCORE_rank_model.txt");
drs.rescore_inspect_results("C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08.mzXML",
"C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08.txt",
"C:\\Work\\msms5\\DnvScore\\inspect_res\\H293-40ul-08_new.txt");
exit(0);
// test_denovo_integrity(model,"C:\\Work\\msms5\\DnvScore\\all_ds\\Dicty_98_2_unique_8.mgf", 20000, 8);
// benchmark_ranking_on_denovo("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVSCORE5\\DNVSCORE5_rank_model.txt",
// "C:\\Work\\msms5\\DnvScore\\test\\DNVSCORE4_test_10.mgf",400,10); //
// benchmark_ranking_on_full_denovo("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVFULL\\DNVFULL_rank_model.txt",
// "C:\\Work\\msms5\\DnvScore\\test\\FULL_test_10.mgf",1000);
// exit(0);
fm.init_from_list_file(config,//"C:\\Work\\msms5\\DnvScore\\short2_train_mgf_list.txt");
"C:\\Work\\msms5\\DnvScore\\comp2_train_mgf_list.txt");
// "C:\\Work\\msms5\\NewScore\\lists\\Shew_98_3_unique_mgf_list.txt");
fs.select_files(fm,0,2500,-1,-1,2);
find_special_PTM_frags_using_offset_counts("S",fm,fs.get_ssf_pointers(),&model,2);
exit(0);
drs.read_denovo_rank_scorer_model("C:\\Work\\msms5\\PepNovoHQ\\Models\\DNVSC_RANK\\LTQ_DNVRANK_model.txt");
drs.test_model("C:\\Work\\msms5\\DnvScore\\test_sets\\LTQ_DNVRANK_test_10.mgf",2000);
drs.train_denovo_partition_model("C:\\Work\\msms5\\DnvScore\\all_db_hits",
"C:\\Work\\msms5\\DnvScore\\seq_freqs\\sequences",
"C:\\Work\\msms5\\DnvScore\\comp_all_parts",
// "C:\\Work\\msms5\\DnvScore\\short2_train_mgf_list.txt",
"C:\\Work\\msms5\\DnvScore\\comp2_train_mgf_list.txt",
2,
1,
30000,
5);
// model.read_model("ETD");
// config = model.get_config();
// config->apply_selected_PTMs("M+16:Q-17:N+1:C+57");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\PepNovoHQ\\ETD2\\ETD_unique_train.txt");
// model.full_train_model("ETD",fm,0.5);
// model.train_pmc_rank_models("C:\\Work\\msms5\\PepNovoHQ\\ETD2\\ETD_all_train.txt");
// model.write_model();
exit(0);
// train_all();
// create_training_sets();
// exit(0);
// generate_size_reports();
// test_sims();
// data_set_stats();
// convert_list_to_trianing_peptide_file(
// "C:\\Work\\msms5\\NewScore\\lists\\Dicty_98_3_unique_mgf_list.txt",
// "C:\\Work\\msms5\\NewScore\\tps\\Dicty_98_3_unique_tps.txt");
// proline_cleavage_reports("b",2);
// exit(0);
// center_cleavage_reports("y",3);
// n_terminal_cleavage_reports("y",2);
// c_terminal_cleavage_reports("y",-2);
// find_best_similar_pairs("LTQ_LOW_TRYP",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf",8);
// find_self_similarity("LTQ_LOW_TRYP",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");
// find_similar_pairs_ditrib("LTQ_LOW_TRYP",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");
// find_homeometric_similarity_distrib("LTQ_LOW_TRYP",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");
// find_self_similarity_ranges("LTQ_LOW_TRYP",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\SHEW18.mgf");
// peptide_distances();
// find_matches_similarity_distrib("LTQ_LOW_TRYP",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\HEK_pos2.mgf",
// "C:\\Work\\msms5\\PepNovoHQ\\pairs\\Shew_pos2.mgf");
// match_sim_exp();
// exit(0);
// edge_model.train_all_edge_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2);
// saa.train_saa_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2);
// saa.train_saancd_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2);
// daa.train_daa_models("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2,0.25);
// daa.train_daancd_model("C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt","LTQ",2);
// dot_prod_exp();
// qc_exp();
// qc_ann_exp("64068",true);
// exit(0);
config = model.get_config();
config->init_with_defaults();
config->apply_selected_PTMs("M+16:Q-17:N+1:C+57");
fm.init_from_file(config,"C:\\Work\\msms5\\PepNovoHQ\\ETD\\train_etd.mgf");
model.full_train_model("ETD",fm,0.5);
exit(0);
if (1)
{
model.read_model("LTQ_LOW_TRYP");
// model.get_config()->apply_selected_PTMs("C+57:M+16");
// model.get_config()->init_with_defaults();
model.get_config()->apply_selected_PTMs("M+16:C+57:Q-17");
// model.test_pmc("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\sqs_train_1.mgf",1);
// model.compute_sqs_cum_stats_for_ided("C:\\Work\\msms5\\NewScore\\lists\\all_HEK_mgf_list.txt");
// model.compute_sqs_cum_stats_for_crap("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\crap_list.txt");
// model.write_model();
model.compute_sqs_cum_stats_for_ided("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40good\\H40good_mgf_list.txt");
/// model.benchmark_sqs("C:\\Work\\msms5\\PepNovoHQ\\small_list.txt",
// "C:\\Work\\msms5\\PepNovoHQ\\small_anns.txt");
// model.benchmark_sqs("C:\\Work\\msms5\\PepNovoHQ\\tmp\\H40ul_0_list.txt",
// "C:\\Work\\msms5\\PepNovoHQ\\H40ul55_missed.txt");
// "C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40ul98_anns.txt");
exit(0);
DAT_Converter dat;
dat.create_dat_files_for_anns(model.get_config(),
"C:\\Work\\Data\\Briggs\\HEK293\\40ul_list.txt",
// "C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\H40ul98_anns.txt",
"C:\\Work\\msms5\\PepNovoHQ\\H40ul55_missed.txt",
"C:\\Work\\msms5\\PepNovoHQ\\tmp\\",
"H4055");
//
// model.train_pmc_rank_models(
// "C:\\Work\\msms5\\NewScore\\lists\\HEK_98_1_unique_mgf_list.txt",0);
// "C:\\Work\\msms5\\NewScore\\lists\\all_unique_mgf_list.txt",0);
// "C:\\Work\\msms5\\NewScore\\lists\\all_HEK_mgf_list.txt",0);
// model.write_model();
// make_before_and_after_matrices(model.get_config(),"C:\\Work\\msms5\\lists\\mgf10.txt",3,"y");
exit(0);
FileManager fm;
fm.init_from_list_file(model.get_config(),"C:\\Work\\msms5\\lists\\LTQ_train_list.txt");
model.full_train_model("LTQ_IT_TRYP",fm,0.45);
model.write_model();
// model.train_pmc("C:\\Work\\msms5\\lists\\pos_sqs_list.txt");
vector< vector<float> > weights;
weights.resize(4);
weights[1].resize(3,0);
weights[2].resize(3,0);
weights[3].resize(3,0);
weights[1][0] = 0.1; weights[1][1] = 0.1; weights[1][2] = 0.4;
weights[2][0] = 0.6; weights[2][1] = 0.75; weights[2][2] = 0.5;
weights[3][0] = 0.3; weights[3][1] = 0.15; weights[3][2] = 0.1;
// model.train_sqs("C:\\Work\\msms5\\lists\\pos_sqs_list.txt",
// "C:\\Work\\msms5\\lists\\neg_sqs_list.txt",&weights);
// model.train_sqs("C:\\Work\\msms5\\NewScore\\lists\\all_unique_mgf_list.txt",
// "C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\crap_list.txt",&weights);
// config = model.get_config();
// config->set_tolerance(0.5);
//
// find_pair_similarities(config,"C:/Work/clust_exp/Results/Shew_bm/ShewBM40_0_1.mgf",
// "C:/Work/clust_exp/Results/Shew_bm/ShewBM40_pairs.txt");
exit(0);
}
// make_y_vectors("C:\\Work\\msms5\\PepNovoHQ\\pmcsqs\\sqs10_train_2.mgf",&model);
// create_training_files(config);
// exit(0);
if (0)
{
PMCSQS_Scorer sqs;
// exit(0);
// create_training_files(config);
exit(0);
}
if (1)
{
// fm.init_from_file(model.get_config(),"C:\\Work\\msms5\\PepNovoHQ\\orbi_ann.mgf");
// create_MSB_query_for_file_list(fm,&model);
vector< vector<int> > annotation_idxs;
vector<mzXML_annotation> annotations;
read_mzXML_annotations("C:/Work/Data/Briggs/HEK293_mzxml_list.txt",
"C:/Work/ClusterAnn/mzxml_anns3.txt", annotation_idxs, annotations, 35000);
// read_mzXML_annotations("C:/Work/ClusterAnn/H40ul_mgf_list.txt",
// "C:/Work/ClusterAnn/mgf_anns.txt", annotation_idxs, annotations, 35000);
cout << "Read annotations: " << annotations.size() << endl;
fm.init_from_list_file_and_add_annotations(config,"C:/Work/Data/Briggs/HEK293_mzxml_list.txt",
annotation_idxs, annotations,true);
// fm.init_from_list_file_and_add_annotations(config,"C:/Work/ClusterAnn/H40ul_mgf_list.txt",annotation_idxs,
// annotations,true);
FileSet all_spec_fs;
all_spec_fs.select_all_files(fm,true);
// config->set_need_to_normalize(0);
// all_spec_fs.create_MGF_file(fm,config,"C:/Work/ClusterAnn/mgf_spectra.mgf");
// exit(0);
ofstream mgf_stream("C:/Work/ClusterAnn/mzxml_spectra3.mgf",ios::out);
BasicSpecReader bsr;
const vector<SingleSpectrumFile *>& ssfs = all_spec_fs.get_ssf_pointers();
int i;
for (i=0; i<ssfs.size(); i++)
{
static QCPeak peaks[5000];
BasicSpectrum bs;
MZXML_single *ssf = (MZXML_single *)ssfs[i];
bs.peaks = peaks;
bs.ssf = ssf;
ostringstream oss;
oss << ssf->file_idx << " " << ssf->scan_number;
ssf->single_name = oss.str();
bs.num_peaks = bsr.read_basic_spec(config,fm,ssf,peaks);
if (ssf->scan_number<0)
{
cout << "Error: no scan number read from mzXML!!!" << endl;
exit(1);
}
cout << "scan: " << ssf->scan_number << " " << bs.num_peaks << endl;
bs.output_to_mgf(mgf_stream,config);
// bs.output_to_mgf(cout,&config);
}
//all_spec_fs.create_MGF_file(fm,config,"C:/Work/ClusterAnn/mzxml_spectra.mgf");
// extractMZFromFiles(model.get_config(),,"C:/Work/Data/Briggs/HEK293/H29340ul_mz.txt");
//
exit(0);
}
if (1)
{
model.read_model("LTQ_LOW_TRYP");
config = model.get_config();
config->apply_selected_PTMs("C+57 M+16");
config->set_tolerances(0.5);
config->set_pm_tolerance(2.5);
config->set_digest_type(TRYPSIN_DIGEST);
config->set_max_number_peaks_per_local_window(15);
// fm.init_from_list_file(config,"C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\LTQ_train_list.txt");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\orbi_train.txt");
// edge_model.train_all_edge_models(fm,&model);
// tm.train_models(fm,&model);
// fm.init_from_list_file(config,"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt");
// make_frag_rank_histogram(fm,config);
// exit(0);
// benchmark_k_value(config,"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt");
// make_benchmark_clustering_dataset(config, "C:\\Work\\clust_exp\\ShewMGF\\AnnsPlus_ann_list.txt",
// 600, 750, false, "C:\\Work\\clust_exp\\ShewMGF\\", "BMNEW");
// exit(0);
benchmark_clustering_performance(config,
"C:\\Work\\clust_exp\\ShewMGF\\BM2000_ann_list.txt",15);
// print_dataset_spectra_by_stats(config,"C:\\Work\\clust_exp\\ann_mgf\\Sings_1.mgf");
// benchmark_top7_and_sim_thresh(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt",
// "C:\\Work\\clust_exp\\Results\\BM40ul\\BM40ul_anns.txt");
// benchmark_heuristic_filtering(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt");
// benchmark_retention_thresh(config,"C:\\Work\\clust_exp\\tmp\\H293_40ul_list.txt",
// "C:\\Work\\clust_exp\\Results\\BM40ul\\BM40ul_anns.txt");
exit(0);
FileManager fm;
// fm.init_from_mgf(config,"C:\\Work\\clust_exp\\ShewMGF\\OnlyAnn_1.mgf");
// make_specified_benchmark_clustering_dataset(config,"C:\\Work\\clust_exp\\ShewMGF\\both_list.txt",400,1000,
// "C:\\Work\\clust_exp\\ShewMGF\\","BM3000",3000,10,0);
make_benchmark_clustering_dataset(config, "C:\\Work\\clust_exp\\ShewMGF\\AnnsPlus_ann_list.txt",
800, 1200, true, "C:\\Work\\clust_exp\\ShewMGF\\", "AnnOnly");
exit(0);
ann_mgf_and_create_mgf_with_sim_masses(config,"K:\\Work\\Data\\Shewenella\\FT_anns.txt",
"K:\\Work\\Data\\Shewenella\\FT_mgf_list.txt",
"K:\\Work\\Data\\Shewenella\\FT_peptides.txt",
"C:\\Work\\clust_exp\\ShewMGF\\",
"AnnsPlus");
exit(0);
ann_mgf_and_create_mgf(config,"C:\\Work\\Data\\FT_mgf\\FT_single_anns.txt",
"C:\\Work\\Data\\FT_mgf\\FT_single_mgf.txt",
"C:\\Work\\clust_exp\\ShewMGF\\",
"Single",true);
exit(0);
ann_mgf_and_create_mgf(config,"C:\\Work\\Data\\FT_mgf\\FT_anns.txt",
"C:\\Work\\Data\\FT_mgf\\FT_mgf_list.txt",
"C:\\Work\\clust_exp\\ShewMGF\\",
"OnlyAnn",true);
exit(0);
// create_16O_18O_dataset("C:\\Work\\msms5\\lists\\p19_list.txt",config);
// exit(0);
// config->set_need_to_estimate_pm(0);
model.clone_charge_model(2,1);
model.clone_charge_model(2,3);
model.clone_charge_model(2,4);
model.clone_charge_model(2,5);
// dataset_eval(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.05);
// dataset_eval(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1);
// dataset_eval(&model,"C:\\Work\\msms5\\lists\\list280_mgf.txt",0.6);
vector<int> set_sizes;
vector<float> probs;
denovo_sequencing_and_aa_probs(&model,"C:\\Work\\msms5\\lists\\m280_list.txt",
set_sizes,probs,2);
// denovo_sequencing_and_aa_probs(&model,"C:\\Work\\clust_exp\\LTQ_train2_ann_list.txt",
// set_sizes,probs,2);
//
// output_denovo_results(&model,"C:\\Work\\msms5\\lists\\LTQ-FT_mgf_list.txt");
// denovo_sequencing_and_aa_probs(&model,"C:\\Work\\msms5\\lists\\LTQ-FT_mgf_list.txt",
// set_sizes,probs, 2);
exit(0);
// print_specs(model.get_config(), "C:\\Work\\msms5\\lists\\one_mzxml.txt");
// check_m_over_z(&model,"C:\\Work\\msms5\\lists\\CoCl345sann_ann_list.txt");
// calc_parent_mass_tolerance_distribution(&model, "C:\\Work\\msms5\\lists\\ann_mgf_list.txt" , 0.6, 0.98);
// calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_mgf_list.txt", 0.6, 0.95);
// perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_mgf_list.txt",0.5,2,0.05);
// denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt" ,0.0075);
// denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1);
// denovo_sequencing_results(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.008);
// perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.2,2,0.05);
// perfrom_inital_evalutation("C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.025,2,0.05);
// calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1,0.95);
// calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.1,0.95);
// calc_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.1,0.95);
// calc_tolerance_distribution(&model,"C:\\Work\\Data\\Omics04\\omics_ann_list.txt",0.75,0.95);
// calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_qtof_list.txt",0.1,0.975);
// calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\ann_orbi_list.txt",0.1,0.975);
// calc_parent_mass_tolerance_distribution(&model,"C:\\Work\\msms5\\lists\\CAD_376.txt",0.1,0.975);
exit(0);
// fm.init_from_mgf(config,"C:\\Work\\msms4\\PepNovo\\test\\m280.mgf");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\good_list2.txt");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\p215.txt");
// fm.init_from_list_file(config,"C:\\Work\\Data\\Omics04\\omics_ann_list.txt");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\omics_mgf_list.txt");
// fm.init_from_mgf(config,"C:\\Work\\msms5\\PepNovoHQ\\Omics04Spectra.mgf");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\omics02_dta.txt");
// FileSet fs;
// fs.select_all_files(fm);
// fs.sort_according_to_m_over_z();
// fs.create_MGF_file(fm,config,"Omics02Spectra.mgf");
// exit(0);
// collect_denovo_statistics(fm,&model);
// denovo_histograms(fm,&model);
// config->set_tolerance(0.0075);
// random_check_homemorphic(config,50000,25);
// create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\Drosophila_list.txt",".","cc",0,5E6,0,1E6);
// create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\Dros_short.txt",".","cc",0,1E6,0,1E6);
// create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\all_clust.txt","clust_out","ikkb",0,5E6,0,1E6);
// create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\omics_mgf_list.txt","clust_out",
// "Omics04b",0,5E6,0,1E6);
// create_spectrum_clusters(config,"C:\\Work\\msms5\\lists\\omics02_mgf_list.txt","clust_out",
// "Omics02",0,5E6,0,1E6);
// create_spectrum_clusters(config,"C:\\Work\\msms5\\PepNovoHQ\\clust_out2\\h293_dat_list.txt",
// "clust_out2","H293b_2nd_digest_abd3",0,5E6,1938.76,1E6,2);
// create_spectrum_clusters(config,"C:\\Work\\msms5\\PepNovoHQ\\clust_out\\h29s_list.txt","clust_out",
// "xxxx",0,5E6,835.397,1E6,2);
exit(0);
DAT_Converter dat;
dat.init_DAT_Converter(2000,25,1048576);
exit(0);
}
// config->add_selected_PTMs("C+57 M+16 S+80 T+80 Y+80 N+1 Q+1 K+42 D+16 K+16 P+16 N+16");
// config->set_tolerances(0.0075);
// config->set_pm_tolerance(0.011);
// fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\contaminants.fasta",config);
// fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\Homo_sapiens.NCBI35.dec.pep.fa",config);
// fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa50mb.fa",config,true,5,6);
// fdb.create_db_from_fasta("C:\\Work\\msms5\\PepNovoHQ\\DB\\homo_pos.fa",config);
// fdb.print_protein_names();
// fdb.write_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\homo.dat");
// fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\homo.dat",config);
// fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\qqq.dat",config);
// fdb.read_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa500k.dat",config);
// fdb.print_protein_names();
// fdb.write_FastaDB("C:\\Work\\msms5\\PepNovoHQ\\DB\\fa5--0mb.dat");
// exit(0);
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_seq_list.txt");
// fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_u_list.txt");
fm.init_from_list_file(config,"C:\\Work\\msms5\\lists\\CAD_376.txt");
// make_bin_histograms(fm,config);
// calc_avg_rand(fm,config);
// explore_fragment_set(fm,config);
// show_occurences(fm,config,"p-25.0");
// find_internal_offset_counts(fm,config);
// make_frag_rank_histogram(fm,config);
// exit(0);
// internal_fragment_annotation(fm,model.get_config());
// find_internal_offset_counts(fm,model.get_config());
// exit(0);
FileSet fs;
fs.select_all_files(fm);
fstream ofs("true_seq.txt",ios::out);
fs.make_fasta_from_file_seqs(fm,config,45,ofs);
// dbsm.train_regression_models(fm,fdb,12,&model);
// analyze_cad_spec(fm,config);
// make_rank_histograms(fm,&model);
// dbsm.read_model("DBS.txt");
// CAD_histograms(fm,&model,fdb,&dbsm);
// rand_db_stats(fm,&model,&dbsm);
// db_search_stats(fm,&model,&dbsm);
// neg_db_search_stats(fm,&model,&dbsm);
// CAD_edge_stats(fm,&model);
// CAD_denovo_histograms(fm,&model,fdb);
// CAD_edge_stats(fm,&model);
// collect_denovo_statistics(fm,&model);
exit(0);
// int *arr;
// int t_size;
// read_fasta("cshort.fasta",&arr,&t_size,&config);
// read_fasta("C:\\Work\\msms4\\PepNovo\\Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,config);
read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
read_fasta("Homo_sapiens.NCBI35.dec.pep.fa",&arr,&t_size,&config);
// homeomorphic_levels(&config,arr,t_size,1000.0,1001,"hp_res.txt");
config->set_tolerance(0.0075);
// full_exp(config,0,arr,t_size,"hp_res_dis_a0.txt");
// full_exp(config,1,arr,t_size,"hp_res_dis_a1.txt");
// full_exp(config,2,arr,t_size,"hp_res_dis_a2.txt");
// full_exp(config,3,arr,t_size,"hp_res_dis_a3.txt");
// full_exp(config,4,arr,t_size,"hp_res_dis_a4.txt");
// homeomorphic_exp3(&config,100);
// exit(0);
// config.print_supported_PTMs();
// config.print_session_aas();
string p;
// ifstream fs("D:\\msms4\\PepNovo\\test\\C25A19_IP_01.mgf",ios::in);
// ifstream fs("D:\\msms4\\PepNovo\\test\\m280.mgf",ios::in);
// fm.init_from_mgf(&config,"D:\\msms4\\PepNovo\\test\\m280.mgf");
// fm.init_from_mgf(&config,"D:\\msms4\\PepNovo\\mgf_2600.2.mgf");
// fm.init_from_list_file(&config,"D:\\msms4\\lists\\unique_good2.txt");
// fm.init_from_list_file(&config,"D:\\msms4\\lists\\short2.txt");
// fm.init_from_list_file(&config,"D:\\Data2\\ikkb_unmod_list.txt");
// rand_seed(1111);
rand_seed(1426347);
// model.read_model("ESI_RANKS");
// model.get_config()->add_selected_PTMs("C+57");
// SpectrumScore sqs;
// sqs.learn_score_params(&model,"D:\\msms4\\lists\\sqs2_short.txt",
// "D:\\msms4\\lists\\sqs_neg1.txt");
// exit(0);
// model.set_model_name(string("ESI2"));
// random_peak_match_exp(model.get_config(),fm,800,1200,10000000);
// model.print_joint_scores();
// me_reg_exp();
// me_exp();
// exit(0);
// fm.init_from_mgf(model.get_config(),"c:\\work\\msms4\\PepNovo\\test\\m280.mgf");
// fm.init_from_mgf(model.get_config(),"c:\\work\\msms4\\PepNovo\\hpep.mgf");
fm.init_from_list_file(config,"c:\\Work\\msms4\\lists\\efast2.txt");
// fm.init_from_list_file(&config,"D:\\msms4\\lists\\charge2.txt");
//m.init_from_list_file(model.get_config(),"C:\\Work\\msms4\\PepNovo\\lll.txt");
//m.init_from_list_file(model.get_config(),"D:\\msms4\\lists\\l1.txt");
*/
return 0;
} | 35.122571 | 111 | 0.675831 |
ea3bf7111be855d397152194b602065d6a61b0b0 | 107 | hpp | C++ | tests/export.hpp | RealKC/Reiji | 69a8b50c5e1e997fb90652d5b263c27f75e4e0ea | [
"BSL-1.0"
] | null | null | null | tests/export.hpp | RealKC/Reiji | 69a8b50c5e1e997fb90652d5b263c27f75e4e0ea | [
"BSL-1.0"
] | 4 | 2020-08-09T20:33:04.000Z | 2021-02-07T04:02:39.000Z | tests/export.hpp | RealKC/Reiji | 69a8b50c5e1e997fb90652d5b263c27f75e4e0ea | [
"BSL-1.0"
] | null | null | null | #pragma once
#if defined(_WIN32)
# define EXPORT __declspec(dllexport)
#else
# define EXPORT
#endif
| 13.375 | 40 | 0.719626 |
ea3e8e08258da66f0239cb386b3739ca4257eb64 | 721 | cpp | C++ | Observer/Subject.cpp | wolf9970/CST276SRS01 | f4e0a339e19fba1c10f831e8618b91f755cf02f7 | [
"MIT"
] | null | null | null | Observer/Subject.cpp | wolf9970/CST276SRS01 | f4e0a339e19fba1c10f831e8618b91f755cf02f7 | [
"MIT"
] | null | null | null | Observer/Subject.cpp | wolf9970/CST276SRS01 | f4e0a339e19fba1c10f831e8618b91f755cf02f7 | [
"MIT"
] | null | null | null | //
// Created by wolf on 7/9/18.
//
#include "Subject.h"
void Subject::Attach(Observer* observer)
{
observers_.emplace_back(observer);
}
// code from Mitch's in-class slide on erase-remove idiom
void Subject::Detach(Observer* observer)
{
observers_.erase(std::remove_if(observers_.begin(), observers_.end(),
[&observer](Observer const &value) {
auto const result = &value == &observer;
return result;
}),
observers_.end()
);
}
void Subject::Notify()
{
for (Observer* observer : observers_)
observer->Update();
}
}
| 22.53125 | 80 | 0.510402 |
ea3edce689c621c537745fbce640c7806ef286c5 | 457 | cc | C++ | ast/location.cc | asilha/hilti | ebfffc7dad31059b43a02eb26abcf7a25f742eb8 | [
"BSD-3-Clause"
] | 46 | 2015-01-21T13:31:25.000Z | 2020-10-27T10:18:03.000Z | ast/location.cc | jjchromik/hilti-104-total | 0f9e0cb7114acc157211af24f8254e4b23bd78a5 | [
"BSD-3-Clause"
] | 29 | 2015-03-30T08:23:04.000Z | 2019-05-03T13:11:35.000Z | ast/location.cc | jjchromik/hilti-104-total | 0f9e0cb7114acc157211af24f8254e4b23bd78a5 | [
"BSD-3-Clause"
] | 20 | 2015-01-27T12:59:38.000Z | 2020-10-28T21:40:47.000Z |
#include <util/util.h>
#include "location.h"
using namespace ast;
const Location Location::None("<no location>");
Location::operator string() const
{
if ( this == &None )
return "<no location>";
string s = _file.size() ? _file : "<no filename>";
s += ":";
if ( _from >= 0 ) {
if ( _to >= 0 )
s += util::fmt("%d-%d", _from, _to);
else
s += util::fmt("%d", _from);
}
return s;
}
| 16.925926 | 54 | 0.49453 |
ea3f18a9f2941f8de6e6ad85de09584ffa021e61 | 3,040 | cpp | C++ | Engine/Source/GEOGL/Rendering/SubTexture2D.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | Engine/Source/GEOGL/Rendering/SubTexture2D.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | Engine/Source/GEOGL/Rendering/SubTexture2D.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2020 Matthew Krueger *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgment in the product documentation would *
* be appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not *
* be misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source *
* distribution. *
* *
*******************************************************************************/
#include "SubTexture2D.hpp"
namespace GEOGL{
SubTexture2D::SubTexture2D(const Ref <Texture2D> &textureAtlas, const glm::vec2 &minBound,
const glm::vec2 &maxBound) : m_Texture(textureAtlas){
m_TextureCoords[0] = {minBound.x, minBound.y};
m_TextureCoords[1] = {maxBound.x, minBound.y};
m_TextureCoords[2] = {maxBound.x, maxBound.y};
m_TextureCoords[3] = {minBound.x, maxBound.y};
}
Ref <SubTexture2D> SubTexture2D::createFromCoords(const Ref<Texture2D>& textureAtlas, const glm::vec2 &spritePosition, const glm::vec2& cellSize, const glm::vec2& spriteDimensions) {
glm::vec2 minBounds = {
(spritePosition.x * cellSize.x)/(float)textureAtlas->getWidth(),
(spritePosition.y * cellSize.y)/(float)textureAtlas->getHeight()};
glm::vec2 maxBounds = {
((spritePosition.x + spriteDimensions.x) * cellSize.x) / (float)textureAtlas->getWidth(),
((spritePosition.y + spriteDimensions.y) * cellSize.y) / (float)textureAtlas->getHeight()};
return createRef<SubTexture2D>(textureAtlas, minBounds, maxBounds);
}
} | 55.272727 | 186 | 0.471382 |
ea405f6f53b65abdb821e58f9bf4bb40b9deefa4 | 1,715 | cpp | C++ | src/Cameras/PerspectiveCamera.cpp | drobnik/raytracing-engine | ae4add6e59e2f80c794e13edc6f6fe65ea5615f6 | [
"MIT"
] | 1 | 2018-01-16T18:55:31.000Z | 2018-01-16T18:55:31.000Z | src/Cameras/PerspectiveCamera.cpp | drobnik/raytracing-engine | ae4add6e59e2f80c794e13edc6f6fe65ea5615f6 | [
"MIT"
] | null | null | null | src/Cameras/PerspectiveCamera.cpp | drobnik/raytracing-engine | ae4add6e59e2f80c794e13edc6f6fe65ea5615f6 | [
"MIT"
] | null | null | null | #include "PerspectiveCamera.h"
PerspectiveCamera::PerspectiveCamera(const Vector3& e, const Vector3& look, const Vector3& u,
unsigned int height, unsigned int width, float pixSize,
const std::shared_ptr<AdaptiveSampler>& sampler, float field)
: Camera(e, look, u, height, width, pixSize, sampler) {
fieldOfView = field;
// if distance is default -> calculate from field(ofView)
calculateViewDistance();
zoom = 4.0f;
}
EngineImage PerspectiveCamera::RenderScene(LightIntensity &background, std::unique_ptr<Tracer> const &tracer) {
LightIntensity color;
std::string name = tracer->sceneName();
EngineImage image = EngineImage(viewHeight, viewWidth, background, name);
image.resetPixels(background);
float x, y;
float d;
Ray ray;
Vector3 vo;
ray.setOrigin(eye);
for(unsigned int r = 0; r < viewHeight; r++){ //up
for(unsigned int c = 0; c < viewWidth; c++){ //horizontal
x = pixelSize * (c - 0.5f *(viewWidth - 1.0f));
y = pixelSize * (r - 0.5f *(viewHeight - 1.0f));
vo = Vector3(x, y, viewDistance) - eye;
d = vo.length();
ray.setDirection(Vector3(x, y, d));
color = sampler->AdaptiveSampling(ray, tracer, pixelSize, 0, false);
image.setPixel((int)r, (int)c, color);
}
}
return image;
}
PerspectiveCamera::PerspectiveCamera(const PerspectiveCamera& cam) :
Camera(cam),
fieldOfView(cam.fieldOfView){ }
void PerspectiveCamera::calculateViewDistance(){
viewDistance = 400.0f;//viewWidth / (2.0f * tanf(Utility::degToRad(fieldOfView) * 0.5f));
} | 36.489362 | 111 | 0.61516 |
ea423eb3e36b05cb5a4e48631ce07d29b8cf4308 | 3,091 | cpp | C++ | src/api/button/b_skill.cpp | geoo89/Lix | 47dfd2317509ed5cb39b7b230b2de138dc613a6d | [
"CC0-1.0"
] | 1 | 2015-08-29T05:22:40.000Z | 2015-08-29T05:22:40.000Z | src/api/button/b_skill.cpp | carvalhomb/AdaptiveLix | d7054c5f96fae54dccef23e48760851b4981a109 | [
"CC0-1.0"
] | null | null | null | src/api/button/b_skill.cpp | carvalhomb/AdaptiveLix | d7054c5f96fae54dccef23e48760851b4981a109 | [
"CC0-1.0"
] | null | null | null | #include <sstream>
#include "b_skill.h"
#include "../../graphic/gra_lib.h"
#include "../../other/help.h"
#include "../../other/language.h" // Lix-Bildname
namespace Api {
SkillButton::SkillButton(const int nx, const int ny, const int nxl)
:
Button (nx, ny, nxl, 60),
icon(GraLib::get_lix(LixEn::GARDEN), get_ground(),
get_x_here() + get_xl()/2 - 17, get_y_here() + 23)
{
set_skill(LixEn::NOTHING);
}
SkillButton::~SkillButton()
{
}
void SkillButton::set_skill(const LixEn::Ac ac)
{
set_draw_required();
skill = ac;
icon.set_y_frame(skill - 1);
if (skill == LixEn::NOTHING) set_number(0);
}
void SkillButton::set_number(const int nr)
{
set_draw_required();
number = (skill != LixEn::NOTHING ? nr : 0);
if (number != 0 ) {
icon.set_x_frame(0);
}
else {
set_off();
icon.set_x_frame(1);
}
}
void SkillButton::set_style(const LixEn::Style st)
{
set_draw_required();
icon.set_cutbit(GraLib::get_lix(st));
}
void SkillButton::set_hotkey_label(const std::string& s)
{
hotkey_label = s;
if (ustrlen(hotkey_label.c_str()) > 3) {
hotkey_label.resize(uoffset(hotkey_label.c_str(), 3));
}
// note: if the hotkey label text has an initial non-ASCII
// character we won't be able to capitalize it. Oh well.
// Not sure that ever happens for real?
// Anyway, this allows us to work below as if the first
// character only takes one byte.
if (hotkey_label.size() > 0) {
int c = hotkey_label[0];
if (c >= 'a' && c <= 'z') hotkey_label[0] = c + 'A' - 'a';
}
set_draw_required();
}
void SkillButton::draw_self()
{
Button::draw_self();
if (skill != LixEn::NOTHING) {
icon.set_x(get_x_here() + get_xl()/2 - 17);
icon.set_y(get_y_here() + 23);
icon.draw();
// draw the number
// note: some calculations below assume all chars in s
// are ASCII which is currently the case.
std::ostringstream s;
if (number == LixEn::infinity) s << "*";
else if (number == 0); // write nothing
else if (number >= 0 && number <= LixEn::skill_nr_max) s << number;
else s << "?";
// for the horizontal position, we subtract 1 in case of 3 digits
// because they weren't properly centered otherwise.
Help::draw_shadow_centered_text(get_ground(),
(s.str().size() > 2 ? font_nar : font_big),
s.str().c_str(), get_x_here() + get_xl()/2 + (s.str().size()>2?-1:0),
get_y_here() + 4,
color[COL_TEXT_ON], color[COL_API_SHADOW]);
// draw the hotkey
if (! hotkey_label.empty() && ! s.str().empty()) {
Help::draw_shadow_text(get_ground(), font_sml,
hotkey_label.c_str(), get_x_here() + get_xl() - 3
- ::text_length(font_sml, hotkey_label.c_str()),
get_y_here() + get_yl() - 15,
color[COL_TEXT], color[COL_API_SHADOW]
);
}
// end drawing hotkey
}
}
} // Ende Namensraum
| 25.758333 | 78 | 0.57813 |
ea45370865a076b0520fb580ba48176e80bfcee7 | 5,629 | cc | C++ | easyeye/tests/FilesTest.cc | mike10004/easyeye | d9996cab2edcedbc1eb78ab6366866423c6be023 | [
"MIT"
] | 4 | 2017-01-27T16:38:53.000Z | 2018-09-07T14:02:39.000Z | easyeye/tests/FilesTest.cc | superchao1982/easyeye | d9996cab2edcedbc1eb78ab6366866423c6be023 | [
"MIT"
] | 1 | 2018-07-25T18:19:43.000Z | 2018-07-25T18:19:43.000Z | easyeye/tests/FilesTest.cc | superchao1982/easyeye | d9996cab2edcedbc1eb78ab6366866423c6be023 | [
"MIT"
] | 11 | 2015-02-20T05:28:22.000Z | 2021-07-27T03:57:27.000Z | /*
* File: FilesTest.cc
* Author: mike
*
* Created on Jan 31, 2014, 10:25:33 AM
*/
#include "FilesTest.h"
#include <vector>
#include <string>
#include "../src/easyeye/common/easyeye_utils.h"
using namespace easyeye;
using namespace std;
CPPUNIT_TEST_SUITE_REGISTRATION(FilesTest);
static bool Eq(const string& a, const string& b)
{
return a.compare(b) == 0;
}
// format:
// {"path", "dirname", "basename", "extension", "nameWithoutExtension"},
//vector< vector<string> > get_test_cases() {
//
// {"/usr/lib", "/usr", "lib", "", ""},
// {"/usr/", "/", "usr", "", ""},
// {"usr", ".", "usr", "", ""},
// {"/", "/", "/", "", ""},
// {".", ".", ".", "", ""},
// {"..", ".", "..", "", ""},
// {0, 0, 0, 0, 0, 0}
//};
static vector<PathInfo> GetTestCases()
{
// format: path, dirname, basename, stem, extension
PathInfo a("/usr/lib", "/usr", "lib", "lib", "");
PathInfo b("/usr/", "/", "usr", "usr", "");
PathInfo c("usr", ".", "usr", "usr", "");
PathInfo d("/", "/", "/", "/", "");
PathInfo e("a/b/c.txt", "a/b", "c.txt", "c", "txt");
PathInfo f("a.txt", ".", "a.txt", "a", "txt");
PathInfo g("a/b/c", "a/b", "c", "c", "");
PathInfo h("a/b/c/", "a/b", "c", "c", "");
PathInfo l("a/b/c.jpg", "a/b", "c.jpg", "c", "jpg");
PathInfo m("a/b.txt/c", "a/b.txt", "c", "c", "");
PathInfo n("/a/b/c.txt", "/a/b", "c.txt", "c", "txt");
PathInfo q("a/b/.c", "a/b", ".c", ".c", "");
PathInfo r("a/b/c.", "a/b", "c.", "c", "");
PathInfo s(".", ".", ".", ".", "");
PathInfo t("..", ".", "..", "..", "");
PathInfo u("........", ".", "........", "........", "");
// {".", ".", ".", "", ""},
// {"..", ".", "..", "", ""},
vector<PathInfo> test_cases;
test_cases.push_back(a);
test_cases.push_back(b);
test_cases.push_back(c);
test_cases.push_back(d);
test_cases.push_back(e);
test_cases.push_back(f);
test_cases.push_back(g);
test_cases.push_back(h);
test_cases.push_back(l);
test_cases.push_back(m);
test_cases.push_back(n);
test_cases.push_back(q);
test_cases.push_back(r);
test_cases.push_back(s);
test_cases.push_back(t);
test_cases.push_back(u);
return test_cases;
}
//Filename
//a/b/c.txt --> c.txt
// a.txt --> a.txt
// a/b/c --> c
// a/b/c/ --> ""
// Name without extension
//a/b/c.txt --> c
// a.txt --> a
// a/b/c --> c
// a/b/c/ --> ""
//foo.txt --> "txt"
// a/b/c.jpg --> "jpg"
// a/b.txt/c --> ""
// a/b/c --> ""
FilesTest::FilesTest() {
}
FilesTest::~FilesTest() {
}
void FilesTest::setUp() {
}
void FilesTest::tearDown() {
}
void FilesTest::testExtension() {
vector<PathInfo> test_cases = GetTestCases();
int num_diff = 0;
for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) {
PathInfo& expected = *it;
cerr << endl << "filename_extension of \"" << expected.path << "\"" << endl;
cerr << "expected: " << expected.filename_extension << endl;
PathInfo actual;
Files::ParsePathInfo(expected.path, actual);
cerr << " actual: " << actual.filename_extension << endl;
bool equiv = Eq(expected.filename_extension, actual.filename_extension);
cerr << " equal: " << equiv << endl;
if (!equiv) num_diff++;
}
CPPUNIT_ASSERT_EQUAL(0, num_diff);
}
void FilesTest::testNameWithoutExtension() {
vector<PathInfo> test_cases = GetTestCases();
int num_diff = 0;
for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) {
PathInfo& expected = *it;
cerr << endl << "filename_stem of \"" << expected.path << "\"" << endl;
cerr << "expected: " << expected.filename_stem << endl;
PathInfo actual;
Files::ParsePathInfo(expected.path, actual);
cerr << " actual: " << actual.filename_stem << endl;
bool equiv = Eq(expected.filename_stem, actual.filename_stem);
cerr << " equal: " << equiv << endl;
if (!equiv) num_diff++;
}
CPPUNIT_ASSERT_EQUAL(0, num_diff);
}
void FilesTest::testAbsolute() {
CPPUNIT_ASSERT(true);
}
void FilesTest::testDirname() {
vector<PathInfo> test_cases = GetTestCases();
int num_diff = 0;
for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) {
PathInfo& expected = *it;
cerr << endl << "dirname of \"" << expected.path << "\"" << endl;
cerr << "expected: " << expected.dirname << endl;
PathInfo actual;
Files::ParsePathInfo(expected.path, actual);
cerr << " actual: " << actual.dirname << endl;
bool equiv = Eq(expected.dirname, actual.dirname);
cerr << " equal: " << equiv << endl;
if (!equiv) num_diff++;
}
CPPUNIT_ASSERT_EQUAL(0, num_diff);
}
void FilesTest::testBasename() {
vector<PathInfo> test_cases = GetTestCases();
int num_diff = 0;
for (vector<PathInfo>::iterator it = test_cases.begin(); it != test_cases.end(); ++it) {
PathInfo& expected = *it;
cerr << endl << "filename of \"" << expected.path << "\"" << endl;
cerr << "expected: " << expected.filename << endl;
PathInfo actual;
Files::ParsePathInfo(expected.path, actual);
cerr << " actual: " << actual.filename << endl;
bool equiv = Eq(expected.filename, actual.filename);
cerr << " equal: " << equiv << endl;
if (!equiv) num_diff++;
}
CPPUNIT_ASSERT_EQUAL(0, num_diff);
}
| 30.101604 | 92 | 0.52798 |
3569f3f4b1ed81bd76a4a9f74daff5d730c69b77 | 748 | cpp | C++ | December-25/day25_rohithmsr_trappingrainwater.cpp | rohith-bare-on/A-December-of-Algorithms-2020 | aadc6fc59c9e2046a2803d42466991b7357e64dc | [
"MIT"
] | 1 | 2020-12-09T06:12:43.000Z | 2020-12-09T06:12:43.000Z | December-25/day25_rohithmsr_trappingrainwater.cpp | rohith-bare-on/A-December-of-Algorithms-2020 | aadc6fc59c9e2046a2803d42466991b7357e64dc | [
"MIT"
] | null | null | null | December-25/day25_rohithmsr_trappingrainwater.cpp | rohith-bare-on/A-December-of-Algorithms-2020 | aadc6fc59c9e2046a2803d42466991b7357e64dc | [
"MIT"
] | null | null | null | /*
Runtime: 4 ms, faster than 98.81% of C++ online submissions for Trapping Rain Water.
Memory Usage: 14.4 MB, less than 96.32% of C++ online submissions for Trapping Rain Water.
*/
class Solution
{
public:
int trap(vector<int> &height)
{
int i = 0;
int j = height.size() - 1;
int vol = 0;
int lmax = 0;
int rmax = 0;
while (i < j)
{
lmax = max(lmax, height[i]);
rmax = max(rmax, height[j]);
if (lmax < rmax)
{
vol += lmax - height[i];
i++;
}
else
{
vol += rmax - height[j];
j--;
}
}
return vol;
}
}; | 20.777778 | 90 | 0.417112 |
356e66a8717a03e14994d0f5362993c17eab363d | 918 | cpp | C++ | Homeworks/1_MiniDraw/project/src/App/Curve.cpp | Chaphlagical/USTC_CG | 9f8b0321e09e5a05afb1c93303e3c736f78503fa | [
"MIT"
] | 13 | 2020-05-21T03:12:48.000Z | 2022-01-20T01:25:02.000Z | Homeworks/1_MiniDraw/project/src/App/Curve.cpp | lyf7115/USTC_CG | 9f8b0321e09e5a05afb1c93303e3c736f78503fa | [
"MIT"
] | null | null | null | Homeworks/1_MiniDraw/project/src/App/Curve.cpp | lyf7115/USTC_CG | 9f8b0321e09e5a05afb1c93303e3c736f78503fa | [
"MIT"
] | 4 | 2020-06-13T13:14:14.000Z | 2021-12-15T07:36:05.000Z | #include "Curve.h"
using namespace minidraw;
Curve::Curve()
{
type_ = kCurve;
finish = false;
polygon.push_back(start);
}
Curve::~Curve()
{
}
void Curve::update(int mode)
{
switch (mode)
{
case 0:
finish = true;
break;
case 1:
if (polygon.size() > 0)
{
polygon.back() = end;
points.push_back(end);
}
polygon.push_back(polygon.back());
break;
default:
break;
}
}
void Curve::Draw(QPainter& painter)
{
if (finish)
{
QPainterPath path(points[0]);
for (int i = 0; i < points.size() - 1; i++)
{
QPoint sp = points[i];
QPoint ep = points[i + 1];
QPoint c1 = QPoint((sp.x() + ep.x()) / 2, sp.y());
QPoint c2 = QPoint((sp.x() + ep.x()) / 2, ep.y());
//QPoint c2 = QPoint(ep.x(), (sp.y() + ep.y()) / 2);
path.cubicTo(c1, c2, ep);
//path.quadTo(c1, ep);
}
painter.drawPath(path);
}
//painter.drawPolygon(polygon);
else
painter.drawPolyline(polygon);
}
| 15.827586 | 55 | 0.58061 |
356fe67569b3e8efd7d30b4e41ead2f716705f08 | 24,565 | cpp | C++ | inetsrv/iis/svcs/smtp/adminsso/admin.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/svcs/smtp/adminsso/admin.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/svcs/smtp/adminsso/admin.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // admin.cpp : Implementation of CsmtpadmApp and DLL registration.
#include "stdafx.h"
#include "metautil.h"
#include "smtpadm.h"
#include "smtpcmn.h"
#include "smtpprop.h"
#include "admin.h"
#include "version.h"
#include "oleutil.h"
#include "metakey.h"
#define SMTP_DEF_SERVICE_VERSION ( 0 ) // MCIS
// Must define THIS_FILE_* macros to use NntpCreateException()
#define THIS_FILE_HELP_CONTEXT 0
#define THIS_FILE_PROG_ID _T("Smtpadm.Admin.1")
#define THIS_FILE_IID IID_ISmtpAdmin
/////////////////////////////////////////////////////////////////////////////
//
CSmtpAdmin::CSmtpAdmin () :
m_dwServiceInstance ( 0 )
// CComBSTR's are initialized to NULL by default.
{
m_dwServiceVersion = SMTP_DEF_SERVICE_VERSION;
}
CSmtpAdmin::~CSmtpAdmin ()
{
// All CComBSTR's are freed automatically.
}
STDMETHODIMP CSmtpAdmin::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_ISmtpAdmin,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
STDMETHODIMP CSmtpAdmin::get_ServiceAdmin ( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminService> pISmtpAdminService;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminService,
IID_ISmtpAdminService,
&pISmtpAdminService,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminService->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminService
}
STDMETHODIMP CSmtpAdmin::get_VirtualServerAdmin ( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminVirtualServer> pISmtpAdminVirtualServer;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminVirtualServer,
IID_ISmtpAdminVirtualServer,
&pISmtpAdminVirtualServer,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminVirtualServer->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
hr = pISmtpAdminVirtualServer->put_ServiceInstance ( m_dwServiceInstance );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminVirtualServer
}
STDMETHODIMP CSmtpAdmin::get_SessionsAdmin ( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminSessions> pISmtpAdminSessions;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminSessions,
IID_ISmtpAdminSessions,
&pISmtpAdminSessions,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminSessions->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
hr = pISmtpAdminSessions->put_ServiceInstance ( m_dwServiceInstance );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminSessions
}
STDMETHODIMP CSmtpAdmin::get_AliasAdmin( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminAlias> pISmtpAdminAlias;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminAlias,
IID_ISmtpAdminAlias,
&pISmtpAdminAlias,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminAlias->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
hr = pISmtpAdminAlias->put_ServiceInstance ( m_dwServiceInstance );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminAlias
}
STDMETHODIMP CSmtpAdmin::get_UserAdmin( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminUser> pISmtpAdminUser;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminUser,
IID_ISmtpAdminUser,
&pISmtpAdminUser,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminUser->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
hr = pISmtpAdminUser->put_ServiceInstance ( m_dwServiceInstance );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminUser
}
STDMETHODIMP CSmtpAdmin::get_DLAdmin( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminDL> pISmtpAdminDL;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminDL,
IID_ISmtpAdminDL,
&pISmtpAdminDL,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminDL->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
hr = pISmtpAdminDL->put_ServiceInstance ( m_dwServiceInstance );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminDL
}
STDMETHODIMP CSmtpAdmin::get_DomainAdmin( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminDomain> pISmtpAdminDomain;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminDomain,
IID_ISmtpAdminDomain,
&pISmtpAdminDomain,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminDomain->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
hr = pISmtpAdminDomain->put_ServiceInstance ( m_dwServiceInstance );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminDomain
}
STDMETHODIMP CSmtpAdmin::get_VirtualDirectoryAdmin( IDispatch ** ppIDispatch )
{
HRESULT hr = NOERROR;
CComBSTR bstrT = _T("");
CComPtr<ISmtpAdminVirtualDirectory> pISmtpAdminVirtualDirectory;
if (!bstrT)
{
hr = E_OUTOFMEMORY;
goto Error;
}
hr = StdPropertyHandoffIDispatch (
CLSID_CSmtpAdminVirtualDirectory,
IID_ISmtpAdminVirtualDirectory,
&pISmtpAdminVirtualDirectory,
ppIDispatch
);
if ( FAILED(hr) ) {
goto Error;
}
// Set default properties:
hr = pISmtpAdminVirtualDirectory->put_Server ( m_strServer ? m_strServer : bstrT );
if ( FAILED (hr) ) {
goto Error;
}
hr = pISmtpAdminVirtualDirectory->put_ServiceInstance ( m_dwServiceInstance );
if ( FAILED (hr) ) {
goto Error;
}
return hr;
Error:
SAFE_RELEASE ( *ppIDispatch );
*ppIDispatch = NULL;
return hr;
// Destructor releases pISmtpAdminVirtualDirectory
}
// Which service to configure:
STDMETHODIMP CSmtpAdmin::get_Server ( BSTR * pstrServer )
{
return StdPropertyGet ( m_strServer, pstrServer );
}
STDMETHODIMP CSmtpAdmin::put_Server ( BSTR strServer )
{
return StdPropertyPutServerName ( &m_strServer, strServer );
}
STDMETHODIMP CSmtpAdmin::get_ServiceInstance ( long * plServiceInstance )
{
return StdPropertyGet ( m_dwServiceInstance, plServiceInstance );
}
STDMETHODIMP CSmtpAdmin::put_ServiceInstance ( long lServiceInstance )
{
return StdPropertyPut ( &m_dwServiceInstance, lServiceInstance );
}
// Versioning:
STDMETHODIMP CSmtpAdmin::get_HighVersion ( long * plHighVersion )
{
*plHighVersion = HIGH_VERSION;
return NOERROR;
}
STDMETHODIMP CSmtpAdmin::get_LowVersion ( long * plLowVersion )
{
*plLowVersion = LOW_VERSION;
return NOERROR;
}
STDMETHODIMP CSmtpAdmin::get_BuildNum ( long * plBuildNumber )
{
*plBuildNumber = BUILD_NUM;
return NOERROR;
}
STDMETHODIMP CSmtpAdmin::get_ServiceVersion ( long * plServiceVersion )
{
*plServiceVersion = m_dwServiceVersion;
return NOERROR;
}
//////////////////////////////////////////////////////////////////////
// Methods:
//////////////////////////////////////////////////////////////////////
//$-------------------------------------------------------------------
//
// CSmtpAdmin::EnumerateInstances
//
// Description:
//
// Returns a list of the virtual servers on the given machine.
//
// Parameters:
//
// ppsaInstances - Returned SAFEARRAY of instance IDs.
// Must be freed by caller.
//
// Returns:
//
//
//--------------------------------------------------------------------
STDMETHODIMP CSmtpAdmin::EnumerateInstances ( SAFEARRAY ** ppsaInstances )
{
TraceFunctEnter ( "CSmtpAdmin::EnumerateInstances" );
HRESULT hr = NOERROR;
CComPtr<IMSAdminBase> pMetabase;
SAFEARRAY * psaEmpty = NULL;
SAFEARRAYBOUND sabound[1];
// Check parameters:
_ASSERT ( ppsaInstances != NULL );
_ASSERT ( IS_VALID_OUT_PARAM ( ppsaInstances ) );
if ( ppsaInstances == NULL ) {
FatalTrace ( 0, "Bad return pointer" );
hr = E_POINTER;
goto Exit;
}
// Zero the out parameters:
*ppsaInstances = NULL;
// Set the return array to an empty array:
sabound[0].lLbound = 0;
sabound[0].cElements = 0;
psaEmpty = SafeArrayCreate ( VT_I4, 1, sabound );
if ( psaEmpty == NULL ) {
FatalTrace ( (LPARAM) this, "Out of memory" );
hr = E_OUTOFMEMORY;
goto Exit;
}
*ppsaInstances = psaEmpty;
// Get the metabase pointer:
hr = m_mbFactory.GetMetabaseObject ( m_strServer, &pMetabase );
BAIL_ON_FAILURE(hr);
// Enumerate the instances:
hr = QueryMetabaseInstances ( pMetabase, ppsaInstances );
Exit:
if ( FAILED(hr) ) {
_VERIFY ( SUCCEEDED (SafeArrayDestroy ( psaEmpty )) );
if (ppsaInstances)
*ppsaInstances = NULL;
}
TraceFunctLeave ();
return hr;
}
STDMETHODIMP CSmtpAdmin::EnumerateInstancesVariant ( SAFEARRAY ** ppsaInstances )
{
TraceFunctEnter ( "CSmtpAdmin::EnumerateInstancesVariant" );
HRESULT hr;
SAFEARRAY * psaInstances = NULL;
hr = EnumerateInstances ( &psaInstances );
BAIL_ON_FAILURE(hr);
hr = LongArrayToVariantArray ( psaInstances, ppsaInstances );
BAIL_ON_FAILURE(hr);
Exit:
TraceFunctLeave ();
return hr;
}
//$-------------------------------------------------------------------
//
// CSmtpAdmin::CreateInstance
//
// Description:
//
// Creates a new SMTP virtual server on the given machine.
//
// Parameters:
//
// plInstanceId - The new virtual server ID.
//
// Returns:
//
//
//--------------------------------------------------------------------
STDMETHODIMP CSmtpAdmin::CreateInstance ( BSTR pstrMailRoot, long * plInstanceId )
{
TraceFunctEnter ( "CSmtpAdmin::CreateInstance" );
HRESULT hr = NOERROR;
CComPtr<IMSAdminBase> pMetabase;
// Check parameters:
_ASSERT ( plInstanceId != NULL );
_ASSERT ( IS_VALID_OUT_PARAM ( plInstanceId ) );
if ( plInstanceId == NULL ) {
FatalTrace ( 0, "Bad return pointer" );
hr = E_POINTER;
goto Exit;
}
// Zero the out parameter:
*plInstanceId = 0;
// Get the metabase pointer:
hr = m_mbFactory.GetMetabaseObject ( m_strServer, &pMetabase );
if ( FAILED(hr) ) {
goto Exit;
}
// Create a new instance:
hr = CreateNewInstance ( pMetabase, plInstanceId, pstrMailRoot );
Exit:
TraceFunctLeave ();
return hr;
}
//$-------------------------------------------------------------------
//
// CSmtpAdmin::DestroyInstance
//
// Description:
//
// Removes the given virtual server.
//
// Parameters:
//
// lInstanceId - The ID of the virtual server to delete.
//
// Returns:
//
//
//--------------------------------------------------------------------
STDMETHODIMP CSmtpAdmin::DestroyInstance ( long lInstanceId )
{
TraceFunctEnter ( "CSmtpAdmin::DestroyInstance" );
HRESULT hr = NOERROR;
CComPtr<IMSAdminBase> pMetabase;
// Get the metabase pointer:
hr = m_mbFactory.GetMetabaseObject ( m_strServer, &pMetabase );
if ( FAILED(hr) ) {
goto Exit;
}
// Delete the instance:
hr = DeleteInstance ( pMetabase, lInstanceId );
Exit:
TraceFunctLeave ();
return hr;
}
//$-------------------------------------------------------------------
//
// CSmtpAdmin::ErrorToString
//
// Description:
//
// Translates an SMTP_ERROR_CODE to a readable string.
//
// Parameters:
//
// lErrorCode - Win32 error code.
// pstrError - the readable error string.
//
// Returns:
//
// The error string in *pstrError.
//
//--------------------------------------------------------------------
STDMETHODIMP CSmtpAdmin::ErrorToString ( DWORD lErrorCode, BSTR * pstrError )
{
TraceFunctEnter ( "CSmtpAdmin::ErrorToString" );
_ASSERT ( IS_VALID_OUT_PARAM ( pstrError ) );
HRESULT hr = NOERROR;
DWORD dwFormatFlags;
WCHAR wszError [ 1024 ];
if ( pstrError == NULL ) {
FatalTrace ( (LPARAM) this, "Bad return pointer" );
TraceFunctLeave ();
return E_POINTER;
}
//----------------------------------------------------------------
//
// Map error codes here:
//
//
//----------------------------------------------------------------
dwFormatFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
if ( !FormatMessage ( dwFormatFlags, NULL, lErrorCode, 0, // Lang ID - Should be nonzero?
wszError, 1024, NULL ) ) {
// Didn't work, so put in a default message:
WCHAR wszFormat [ 256 ];
wszFormat[0] = L'\0';
if ( !LoadStringW ( _Module.GetResourceInstance (), IDS_UNKNOWN_ERROR, wszFormat, 256 ) ||
!*wszFormat ) {
wcscpy ( wszFormat, L"Unknown Error (%1!d!)" );
}
FormatMessage (
FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY,
wszFormat,
IDS_UNKNOWN_ERROR,
0,
wszError,
1024,
(va_list *) &lErrorCode
);
}
//
// We need to strip out any " from the string, because
// Javascript will barf.
//
LPWSTR pch;
for ( pch = wszError; *pch; pch++ ) {
if ( *pch == L'\"' ) {
*pch = L'\'';
}
}
//
// Strip off any trailing control characters.
//
for (pch = &wszError[wcslen(wszError) - 1];
pch >= wszError && iswcntrl(*pch);
pch --) {
*pch = 0;
}
*pstrError = ::SysAllocString( wszError );
if ( *pstrError == NULL ) {
hr = E_OUTOFMEMORY;
goto Exit;
}
Exit:
TraceFunctLeave ();
return hr;
}
//$-------------------------------------------------------------------
//
// CSmtpAdmin::Tokenize
//
// Description:
//
// Makes the given string safe for HTML & Javascript
//
// Parameters:
//
// strIn - the input string
// strOut - the resulting string with appropriate escape sequences.
//
//--------------------------------------------------------------------
STDMETHODIMP CSmtpAdmin::Tokenize ( BSTR strIn, BSTR * pstrOut )
{
TraceFunctEnter ( "CSmtpAdmin::Tokenize" );
_ASSERT ( IS_VALID_STRING ( strIn ) );
_ASSERT ( IS_VALID_OUT_PARAM ( pstrOut ) );
HRESULT hr = NOERROR;
PWCHAR pSrc = strIn;
PWCHAR pSrcCur = NULL;
PWCHAR pDstCur = NULL;
PWCHAR pDst = NULL;
*pstrOut = NULL;
pDst = new WCHAR [ 3 * lstrlen ( strIn ) + 1 ];
if ( pDst == NULL ) {
FatalTrace ( (LPARAM) this, "Out of memory" );
hr = E_OUTOFMEMORY;
goto Exit;
}
for ( pSrcCur = pSrc, pDstCur = pDst; *pSrcCur; pSrcCur++ ) {
switch ( *pSrcCur ) {
case L'\\':
*(pDstCur++) = L'%';
*(pDstCur++) = L'5';
*(pDstCur++) = L'c';
break;
case L' ':
*(pDstCur++) = L'+';
break;
case L':':
*(pDstCur++) = L'%';
*(pDstCur++) = L'3';
*(pDstCur++) = L'a';
break;
case L'/':
*(pDstCur++) = L'%';
*(pDstCur++) = L'2';
*(pDstCur++) = L'f';
break;
default:
*(pDstCur++) = *pSrcCur;
}
}
*pDstCur = L'\0';
*pstrOut = ::SysAllocString ( pDst );
if ( *pstrOut == NULL ) {
FatalTrace ( (LPARAM) this, "Out of memory" );
hr = E_OUTOFMEMORY;
goto Exit;
}
Exit:
delete pDst;
if ( FAILED(hr) && hr != DISP_E_EXCEPTION ) {
hr = SmtpCreateExceptionFromHresult ( hr );
}
TraceFunctLeave ();
return hr;
}
//$-------------------------------------------------------------------
//
// CSmtpAdmin::QueryMetabaseInstances
//
// Description:
//
// Retrieves the list of virtual servers from the metabase
//
// Parameters:
//
// pMetabase - the metabase object
// ppsaInstances - resulting array of instance ids.
//
// Returns:
//
//
//--------------------------------------------------------------------
HRESULT CSmtpAdmin::QueryMetabaseInstances ( IMSAdminBase * pMetabase, SAFEARRAY ** ppsaInstances )
{
TraceFunctEnter ( "CSmtpAdmin::QueryMetabaseInstances" );
_ASSERT ( IS_VALID_IN_PARAM ( pMetabase ) );
_ASSERT ( IS_VALID_OUT_PARAM ( ppsaInstances ) );
HRESULT hr = NOERROR;
CMetabaseKey mkeySmtp ( pMetabase );
SAFEARRAY * psaResult = NULL;
DWORD cValidInstances = 0;
SAFEARRAYBOUND rgsaBound[1];
DWORD i;
TCHAR szName[ METADATA_MAX_NAME_LEN ];
long index[1];
DWORD dwInstance;
hr = mkeySmtp.Open ( SMTP_MD_ROOT_PATH );
if ( FAILED(hr) ) {
goto Exit;
}
// pickup the service version number:
hr = mkeySmtp.GetDword ( _T(""), MD_SMTP_SERVICE_VERSION, &m_dwServiceVersion );
if ( FAILED(hr) ) {
m_dwServiceVersion = SMTP_DEF_SERVICE_VERSION;
}
hr = mkeySmtp.GetIntegerChildCount ( &cValidInstances );
if ( FAILED(hr) ) {
goto Exit;
}
// Allocate the array:
rgsaBound[0].lLbound = 0;
rgsaBound[0].cElements = cValidInstances;
psaResult = SafeArrayCreate ( VT_I4, 1, rgsaBound );
if ( psaResult == NULL ) {
FatalTrace ( 0, "Out of memory" );
hr = E_OUTOFMEMORY;
goto Exit;
}
mkeySmtp.BeginChildEnumeration ();
for ( i = 0; i < cValidInstances; i++ ) {
hr = mkeySmtp.NextIntegerChild ( &dwInstance, szName );
_ASSERT ( SUCCEEDED(hr) );
index[0] = i;
hr = SafeArrayPutElement ( psaResult, index, &dwInstance );
_ASSERT ( SUCCEEDED(hr) );
}
*ppsaInstances = psaResult;
_ASSERT ( SUCCEEDED(hr) );
Exit:
if ( FAILED (hr) ) {
SafeArrayDestroy ( psaResult );
}
TraceFunctLeave ();
return hr;
}
//$-------------------------------------------------------------------
//
// CSmtpAdmin::CreateNewInstance
//
// Description:
//
// Creates a new virtual server in the metabase.
//
// Parameters:
//
// pMetabase - The metabase object
// plInstanceId - The new instance ID.
//
// Returns:
//
//
//--------------------------------------------------------------------
HRESULT CSmtpAdmin::CreateNewInstance (
IMSAdminBase * pMetabase,
long * plInstanceId,
BSTR bstrMailRoot
)
{
TraceFunctEnter ( "CSmtpAdmin::CreateNewInstance" );
_ASSERT ( IS_VALID_IN_PARAM ( pMetabase ) );
_ASSERT ( IS_VALID_OUT_PARAM ( plInstanceId ) );
HRESULT hr = NOERROR;
CMetabaseKey mkeySmtp ( pMetabase );
DWORD dwInstance;
TCHAR szInstance [ METADATA_MAX_NAME_LEN ];
TCHAR szPath [ METADATA_MAX_NAME_LEN ];
TCHAR szDir [512];
DWORD cb;
// Zero the out parameters:
*plInstanceId = NULL;
hr = mkeySmtp.Open ( SMTP_MD_ROOT_PATH, METADATA_PERMISSION_WRITE );
if ( FAILED(hr) ) {
ErrorTraceX ( (LPARAM) this, "Failed to open SmtpSvc key, %x", GetLastError() );
goto Exit;
}
hr = mkeySmtp.CreateIntegerChild ( &dwInstance, szInstance );
if ( FAILED (hr) ) {
goto Exit;
}
wsprintf( szPath, _T("%s/Root"), szInstance );
hr = mkeySmtp.CreateChild( szPath );
if ( FAILED (hr) ) {
goto Exit;
}
wsprintf( szPath, _T("%s/Root/MailRoot"), szInstance );
hr = mkeySmtp.CreateChild( szPath );
if ( FAILED (hr) ) {
goto Exit;
}
// create mail root virtual directory
if( bstrMailRoot && bstrMailRoot[0] )
{
// get rid of '\' at the end
cb = lstrlen( bstrMailRoot );
if( cb > 0 && bstrMailRoot[cb-1] == _T('\\') )
bstrMailRoot[cb-1] = _T('\0');
wsprintf( szPath, _T("%s/Root/MailRoot"), szInstance );
cb = wsprintf( szDir, _T("%s\\Mailbox"), bstrMailRoot );
mkeySmtp.SetString( szPath, MD_VR_PATH, szDir);
// set badmail, drop, pickup, queue keys
wsprintf( szPath, _T("%s"), szInstance );
cb = wsprintf( szDir, _T("%s\\Badmail"), bstrMailRoot );
mkeySmtp.SetString( szPath, MD_BAD_MAIL_DIR, szDir);
// K2 only has drop doamin
if( SERVICE_IS_K2(m_dwServiceVersion) )
{
cb = wsprintf( szDir, _T("%s\\Drop"), bstrMailRoot );
mkeySmtp.SetString( szPath, MD_MAIL_DROP_DIR, szDir );
}
cb = wsprintf( szDir, _T("%s\\Pickup"), bstrMailRoot );
mkeySmtp.SetString( szPath, MD_MAIL_PICKUP_DIR, szDir );
cb = wsprintf( szDir, _T("%s\\Queue"), bstrMailRoot );
mkeySmtp.SetString( szPath, MD_MAIL_QUEUE_DIR, szDir );
// set the routing sources, it's MultiSZ
cb = wsprintf( szDir, _T("szDataDirectory=%s\\Route"), bstrMailRoot );
szDir[cb] = szDir[cb+1] = _T('\0');
mkeySmtp.SetMultiSz( szPath, MD_ROUTING_SOURCES, szDir, (cb+2) * sizeof(TCHAR) );
// MCIS needs SendNDRTo and SendBadTo as "Postmaster", setup should set it on service level
if( SERVICE_IS_MCIS(m_dwServiceVersion) )
{
mkeySmtp.SetString( szPath, MD_SEND_NDR_TO, TSTR_POSTMASTR_NAME );
mkeySmtp.SetString( szPath, MD_SEND_BAD_TO, TSTR_POSTMASTR_NAME );
}
}
//
// Initialize the server state:
//
mkeySmtp.SetDword ( szInstance, MD_SERVER_COMMAND, MD_SERVER_COMMAND_STOP );
mkeySmtp.SetDword ( szInstance, MD_SERVER_STATE, MD_SERVER_STATE_STOPPED );
mkeySmtp.SetDword ( szInstance, MD_SERVER_AUTOSTART, FALSE );
// hr = mkeySmtp.Close();
// BAIL_ON_FAILURE(hr);
mkeySmtp.Close();
hr = pMetabase->SaveData ( );
if ( FAILED (hr) ) {
goto Exit;
}
*plInstanceId = dwInstance;
Exit:
TraceFunctLeave ();
return hr;
}
//$-------------------------------------------------------------------
//
// CSmtpAdmin::DeleteInstance
//
// Description:
//
// Removes a virtual server from the metabase
//
// Parameters:
//
// pMetabase - The metabase object
// lInstanceId - The ID of the virtual server to delete.
//
// Returns:
//
//
//--------------------------------------------------------------------
HRESULT CSmtpAdmin::DeleteInstance ( IMSAdminBase * pMetabase, long lInstanceId )
{
TraceFunctEnter ( "CSmtpAdmin::CreateNewInstance" );
_ASSERT ( IS_VALID_IN_PARAM ( pMetabase ) );
HRESULT hr = NOERROR;
CMetabaseKey mkeySmtp ( pMetabase );
//
// Tell U2 to delete any mappings associated with this virtual server:
//
::DeleteMapping ( m_strServer, (BSTR) MD_SERVICE_NAME, lInstanceId );
//
// Delete the virtual server from the metabase:
//
hr = mkeySmtp.Open ( SMTP_MD_ROOT_PATH, METADATA_PERMISSION_WRITE );
if ( FAILED(hr) ) {
ErrorTraceX ( (LPARAM) this, "Failed to open SmtpSvc key, %x", GetLastError() );
goto Exit;
}
hr = mkeySmtp.DestroyIntegerChild ( (DWORD) lInstanceId );
if ( FAILED (hr) ) {
goto Exit;
}
// hr = mkeySmtp.Close();
// BAIL_ON_FAILURE(hr);
mkeySmtp.Close();
hr = pMetabase->SaveData ( );
if ( FAILED (hr) ) {
goto Exit;
}
Exit:
TraceFunctLeave ();
return hr;
}
| 21.91347 | 100 | 0.596173 |
3573fb7d5e9ca7e52ba4fdd797c30dc406b3ff22 | 1,402 | hpp | C++ | modules/sdk/include/nt2/sdk/dsl/proto/extends.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | 1 | 2022-03-24T03:35:10.000Z | 2022-03-24T03:35:10.000Z | modules/sdk/include/nt2/sdk/dsl/proto/extends.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | null | null | null | modules/sdk/include/nt2/sdk/dsl/proto/extends.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | null | null | null | /*******************************************************************************
* Copyright 2003-2010 LASMEA UMR 6602 CNRS/U.B.P
* Copyright 2009-2010 LRI UMR 8623 CNRS/Univ Paris Sud XI
*
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt
******************************************************************************/
#ifndef NT2_SDK_DSL_PROTO_EXTENDS_HPP
#define NT2_SDK_DSL_PROTO_EXTENDS_HPP
#include <nt2/sdk/details/preprocessor.hpp>
////////////////////////////////////////////////////////////////////////////////
// BOOST_PROTO_BASIC_EXTENDS working with template Domain
////////////////////////////////////////////////////////////////////////////////
#define BOOST_PROTO_BASIC_EXTENDS_TPL(Expr, Derived, Domain) \
BOOST_PROTO_BASIC_EXTENDS_( NT2_PP_STRIP(Expr) \
, NT2_PP_STRIP(Derived) \
, NT2_PP_STRIP(Domain) \
) \
typedef void proto_is_aggregate_; \
typedef typename NT2_PP_STRIP(Domain)::proto_generator proto_generator; \
/**/
#endif
| 53.923077 | 80 | 0.413695 |
35740d60fbccfa21c6ab923e38c28c5debb9e38d | 940 | cpp | C++ | third_party/mexconv3d/mex_maxpool3d.cpp | janelia-flyem/flymatlib | 63fab6b2deca8996d31b379a38a860ef3e751466 | [
"BSD-3-Clause"
] | 4 | 2016-04-02T17:58:47.000Z | 2020-02-13T18:19:31.000Z | third_party/mexconv3d/mex_maxpool3d.cpp | janelia-flyem/flymatlib | 63fab6b2deca8996d31b379a38a860ef3e751466 | [
"BSD-3-Clause"
] | null | null | null | third_party/mexconv3d/mex_maxpool3d.cpp | janelia-flyem/flymatlib | 63fab6b2deca8996d31b379a38a860ef3e751466 | [
"BSD-3-Clause"
] | 2 | 2019-12-19T01:09:53.000Z | 2022-01-03T21:17:48.000Z | #include "mex.h"
#include "src/maxpool3d.h"
#include "src/wrapperMx.h"
// [Y,ind] = MEX_MAXPOOL3D(X); forward pass
// dZdX = MEX_MAXPOOL3D(dZdY, ind); backward pass
// MEX_MAXPOOL3D(..., 'pool',pool, 'stride',s, 'pad',pad); options
void mexFunction(int no, mxArray *vo[],
int ni, mxArray const *vi[])
{
#ifdef WITHCUDNN
factory_mp3d_withcudnn factory;
#else
factory_mp3d_homebrew factory;
#endif
maxpool3d* h = 0; // TODO: consider unique_ptr?
try {
h = factory.parse_and_create(no, vo, ni, vi);
assert( h != 0 );
// do the job and set output
if (h->ct == maxpool3d::FPROP) {
h->fprop();
vo[0] = h->Y.getMxArray();
vo[1] = h->ind.getMxArray();
}
if (h->ct == maxpool3d::BPROP) {
h->bprop();
vo[0] = h->dX.getMxArray();
}
// done: cleanup
safe_delete(h);
}
catch (const mp3d_ex e) {
safe_delete(h);
mexErrMsgTxt(e.what());
}
} | 23.5 | 66 | 0.584043 |
35751cf78578591ccfa8a90510839623b78c9628 | 493 | hpp | C++ | platform/platform.hpp | Peefy/ArkLightCpp | d2ebda501bed1fd9d7780c9ae9f1cdeedf42fff5 | [
"Apache-2.0"
] | 1 | 2018-05-03T14:12:17.000Z | 2018-05-03T14:12:17.000Z | platform/platform.hpp | Peefy/ArkLightCpp | d2ebda501bed1fd9d7780c9ae9f1cdeedf42fff5 | [
"Apache-2.0"
] | null | null | null | platform/platform.hpp | Peefy/ArkLightCpp | d2ebda501bed1fd9d7780c9ae9f1cdeedf42fff5 | [
"Apache-2.0"
] | null | null | null |
#include <string>
#include "../core/basic.h"
#include "./osplatformutil.h"
enum class Platform
{
Unknown = 0,
Windows = 1,
Linux = 2,
MacOS = 3,
Android = 4,
iOS = 5,
FreeBSD = 6,
OpenBSD = 7,
Sun = 8
};
inline Platform GetPlatfom() {
#if defined ARK_MSVC
return Platform::Windows;
#elif defined ARK_GCC
return Platform::Linux;
#elif defined ARK_APPLE
return Platform::MacOS;
#else
return Platform::Unknown;
#endif
}
| 16.433333 | 30 | 0.602434 |
3576d34fd65a8bcf6ffb78c50761890d9945b668 | 10,370 | cpp | C++ | silkopter/rc/src/main.cpp | jeanleflambeur/silkopter | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | [
"BSD-3-Clause"
] | 36 | 2015-03-09T16:47:14.000Z | 2021-02-04T08:32:04.000Z | silkopter/rc/src/main.cpp | jeanlemotan/silkopter | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | [
"BSD-3-Clause"
] | 42 | 2017-02-11T11:15:51.000Z | 2019-12-28T16:00:44.000Z | silkopter/rc/src/main.cpp | jeanleflambeur/silkopter | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | [
"BSD-3-Clause"
] | 5 | 2015-10-15T05:46:48.000Z | 2020-05-11T17:40:36.000Z | #include "Comms.h"
#include "Video_Decoder.h"
//#include "Menu_System.h"
//#include "Splash_Menu_Page.h"
//#include "Main_Menu_Page.h"
#include "utils/Clock.h"
#include "IHAL.h"
#ifdef RASPBERRY_PI
# include "PI_HAL.h"
#else
# include "GLFW_HAL.h"
#endif
#include "imgui.h"
#include "HUD.h"
namespace silk
{
int s_version_major = 1;
int s_version_minor = 0;
std::string s_program_path;
std::unique_ptr<silk::IHAL> s_hal;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//This prints an "Assertion failed" message and aborts.
void __assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function)
{
QASSERT_MSG(false, "assert: {}:{}: {}: {}", __file, __line, __function, __assertion);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void signal_callback_handler(int signum)
{
printf("Caught signal %d\n", signum);
if (silk::s_hal)
{
silk::s_hal->shutdown();
}
exit(signum);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger()));
q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC));
// boost::shared_ptr<asio::io_service::work> work(new asio::io_service::work(s_async_io_service));
// std::thread_group worker_threads;
// for(int x = 0; x < 4; ++x)
// {
// worker_threads.create_thread(boost::bind(&asio::io_service::run, &s_async_io_service));
// }
signal(SIGHUP, signal_callback_handler);
signal(SIGINT, signal_callback_handler);
signal(SIGCONT, signal_callback_handler);
signal(SIGTERM, signal_callback_handler);
silk::s_program_path = argv[0];
size_t off = silk::s_program_path.find_last_of('/');
if (off != std::string::npos)
{
silk::s_program_path = silk::s_program_path.substr(0, off);
}
QLOGI("Program path: {}.", silk::s_program_path);
#ifdef RASPBERRY_PI
silk::s_hal.reset(new silk::PI_HAL());
#else
silk::s_hal.reset(new silk::GLFW_HAL());
#endif
silk::IHAL& hal = *silk::s_hal;
ts::Result<void> result = hal.init();
if (result != ts::success)
{
QLOGE("Cannot init hal: {}.", result.error().what());
exit(1);
}
silk::HUD hud(hal);
math::vec2u32 display_size = hal.get_display_size();
ImGuiStyle& style = ImGui::GetStyle();
style.ScrollbarSize = display_size.x / 80.f;
style.TouchExtraPadding = ImVec2(style.ScrollbarSize * 2.f, style.ScrollbarSize * 2.f);
//style.ItemSpacing = ImVec2(size.x / 200, size.x / 200);
//style.ItemInnerSpacing = ImVec2(style.ItemSpacing.x / 2, style.ItemSpacing.y / 2);
ImGuiIO& io = ImGui::GetIO();
io.FontGlobalScale = 2.f;
Video_Decoder decoder;
decoder.init();
Clock::time_point last_tp = Clock::now();
hal.get_comms().on_video_data_received = [&decoder](void const* data, size_t size, math::vec2u16 const& res)
{
decoder.decode_data(data, size, res);
};
float temperature = 0.f;
Clock::time_point last_comms_history_tp = Clock::now();
std::vector<float> tx_rssi_history;
std::vector<float> rx_rssi_history;
std::vector<float> packets_dropped_history;
std::vector<float> packets_received_history;
std::vector<float> packets_sent_history;
float brightness = 80.f;
float fan_speed = 100.f;
hal.set_backlight(brightness / 100.f);
hal.set_fan_speed(fan_speed / 100.f);
bool single_phy = false;
silk::stream::ICamera_Commands::Value camera_commands;
while (hal.process())
{
decoder.release_buffers();
Clock::time_point now = Clock::now();
Clock::duration dt = now - last_tp;
last_tp = now;
io.DeltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(dt).count();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImVec2(display_size.x, display_size.y));
ImGui::SetNextWindowBgAlpha(0);
ImGui::Begin("", nullptr, ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoInputs);
ImGui::Image((void*)(decoder.get_video_texture_id() | 0x80000000),
ImVec2(display_size.x, display_size.y),
ImVec2(0, 1),
ImVec2(1, 0));
hud.draw();
ImGui::Begin("HAL");
{
static int counter = 0;
ImGui::Text("Hello, world!"); // Display some text (you can use a format string too)
if (ImGui::SliderFloat("Brightness", &brightness, 10.f, 100.f, "%.0f%%"))
{
hal.set_backlight(brightness / 100.f);
}
if (ImGui::SliderFloat("Fan", &fan_speed, 10.f, 100.f, "%.0f%%"))
{
hal.set_fan_speed(fan_speed / 100.f);
}
temperature = hal.get_temperature();
ImGui::Text("Temperature = %.2f'C", temperature);
if (now - last_comms_history_tp >= std::chrono::milliseconds(100))
{
last_comms_history_tp = now;
silk::Comms::Stats stats = hal.get_comms().get_stats();
tx_rssi_history.push_back(stats.tx_rssi);
while (tx_rssi_history.size() > 10 * 5) { tx_rssi_history.erase(tx_rssi_history.begin()); }
rx_rssi_history.push_back(stats.rx_rssi);
while (rx_rssi_history.size() > 10 * 5) { rx_rssi_history.erase(rx_rssi_history.begin()); }
packets_dropped_history.push_back(stats.packets_dropped_per_second);
while (packets_dropped_history.size() > 10 * 5) { packets_dropped_history.erase(packets_dropped_history.begin()); }
packets_received_history.push_back(stats.packets_received_per_second);
while (packets_received_history.size() > 10 * 5) { packets_received_history.erase(packets_received_history.begin()); }
packets_sent_history.push_back(stats.packets_sent_per_second);
while (packets_sent_history.size() > 10 * 5) { packets_sent_history.erase(packets_sent_history.begin()); }
}
if (!tx_rssi_history.empty())
{
ImGui::Text("TX = %ddBm", (int)tx_rssi_history.back());
ImGui::PlotLines("History",
tx_rssi_history.data(), tx_rssi_history.size(),
0, NULL,
-128.f, 128.f,
ImVec2(0, display_size.y / 20));
}
if (!rx_rssi_history.empty())
{
ImGui::Text("RX = %ddBm", (int)rx_rssi_history.back());
ImGui::PlotLines("History",
rx_rssi_history.data(), rx_rssi_history.size(),
0, NULL,
-128.f, 128.f,
ImVec2(0, display_size.y / 20));
}
if (!packets_dropped_history.empty())
{
ImGui::Text("Dropped = %.2f", packets_dropped_history.back());
auto minmax = std::minmax_element(packets_dropped_history.begin(), packets_dropped_history.end());
ImGui::PlotLines("History",
packets_dropped_history.data(), packets_dropped_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
if (!packets_received_history.empty())
{
ImGui::Text("Received = %.2f", packets_received_history.back());
auto minmax = std::minmax_element(packets_received_history.begin(), packets_received_history.end());
ImGui::PlotLines("History",
packets_received_history.data(), packets_received_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
if (!packets_sent_history.empty())
{
ImGui::Text("Sent = %.2f", packets_sent_history.back());
auto minmax = std::minmax_element(packets_sent_history.begin(), packets_sent_history.end());
ImGui::PlotLines("History",
packets_sent_history.data(), packets_sent_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
bool hq = camera_commands.quality == silk::stream::ICamera_Commands::Quality::HIGH;
ImGui::Checkbox("HQ Video", &hq);
camera_commands.quality = hq ? silk::stream::ICamera_Commands::Quality::HIGH : silk::stream::ICamera_Commands::Quality::LOW;
ImGui::SameLine();
ImGui::Checkbox("Record Video", &camera_commands.recording);
hal.get_comms().send_camera_commands_value(camera_commands);
ImGui::Checkbox("Single Phy", &single_phy);
hal.get_comms().set_single_phy(single_phy);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
ImGui::End();
ImGui::End();
//std::this_thread::sleep_for(std::chrono::microseconds(1));
ImGui::Render();
}
hal.shutdown();
return 0;
}
| 39.429658 | 155 | 0.542816 |
35780e67403f1502578682eb387b94c80863e5cd | 3,850 | cpp | C++ | src/libs/opengl/src/gl_buffers.cpp | zZnghialamZz/Ethan | e841b0a07f75022fab6634d53827c64dd1a466de | [
"Apache-2.0"
] | 2 | 2020-07-29T04:27:22.000Z | 2021-10-11T01:27:43.000Z | src/libs/opengl/src/gl_buffers.cpp | zZnghialamZz/Ethan | e841b0a07f75022fab6634d53827c64dd1a466de | [
"Apache-2.0"
] | null | null | null | src/libs/opengl/src/gl_buffers.cpp | zZnghialamZz/Ethan | e841b0a07f75022fab6634d53827c64dd1a466de | [
"Apache-2.0"
] | 2 | 2020-08-03T03:29:28.000Z | 2020-08-03T08:01:14.000Z | /**
* ==================================================
* _____
* __|___ |__ __ __ _ ____ ____ _
* | ___| | _| |_ | |_| || \ | \ | |
* | ___| ||_ _|| _ || \ | \| |
* |______| __| |__| |__| |_||__|\__\|__/\____|
* |_____|
*
* Game Engine
* ==================================================
*
* @file gl_buffers.cpp
* @author Nghia Lam <nghialam12795@gmail.com>
*
* @brief
*
* @license Copyright 2020 Nghia Lam
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ethan/opengl/gl_buffers.h"
#include "ethan/opengl/gl_assert.h"
#include <glad/glad.h>
namespace Ethan {
static unsigned int BufferDataUsageToOpenGL(BufferDataUsage usage) {
switch(usage) {
case BufferDataUsage::STATIC: return GL_STATIC_DRAW;
case BufferDataUsage::DYNAMIC: return GL_DYNAMIC_DRAW;
}
}
/// --- GLVertexBuffer
GLVertexBuffer::GLVertexBuffer(BufferDataUsage usage)
: data_usage_(usage) {
// TODO(Nghia Lam): Profile Here
GLCALL(glGenBuffers(1, &vertexbufferID_));
}
GLVertexBuffer::GLVertexBuffer(uint32_t size, BufferDataUsage usage)
: data_usage_(usage) {
// TODO(Nghia Lam): Profile Here
GLCALL(glGenBuffers(1, &vertexbufferID_));
GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_));
GLCALL(glBufferData(GL_ARRAY_BUFFER, size, nullptr, BufferDataUsageToOpenGL(usage)));
}
GLVertexBuffer::GLVertexBuffer(const void* data, uint32_t size, BufferDataUsage usage)
: data_usage_(usage) {
// TODO(Nghia Lam): Profile here
GLCALL(glGenBuffers(1, &vertexbufferID_));
GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_));
GLCALL(glBufferData(GL_ARRAY_BUFFER, size, data, BufferDataUsageToOpenGL(usage)));
}
GLVertexBuffer::~GLVertexBuffer() {
GLCALL(glDeleteBuffers(1, &vertexbufferID_));
}
void GLVertexBuffer::Bind() const {
GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_));
}
void GLVertexBuffer::UnBind() const {
GLCALL(glBindBuffer(GL_ARRAY_BUFFER, 0));
}
void GLVertexBuffer::SetData(const void* data, uint32_t size) {
// NOTE(Nghia Lam): Bind Buffer to make sure we set data to the right vertex buffer
// Will this impact the performace ?
GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_));
GLCALL(glBufferData(GL_ARRAY_BUFFER, size, data, BufferDataUsageToOpenGL(data_usage_)));
}
void GLVertexBuffer::SetSubData(const void* data, uint32_t size, uint32_t offset) {
GLCALL(glBindBuffer(GL_ARRAY_BUFFER, vertexbufferID_));
GLCALL(glBufferSubData(GL_ARRAY_BUFFER, offset, size, data));
}
/// --- GLIndexBuffer
GLIndexBuffer::GLIndexBuffer(uint32_t* indices, uint32_t &count)
: count_(count) {
GLCALL(glGenBuffers(1, &indexbufferID_));
GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbufferID_));
GLCALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(uint32_t), indices, GL_STATIC_DRAW));
}
GLIndexBuffer::~GLIndexBuffer() {
GLCALL(glDeleteBuffers(1, &indexbufferID_));
}
void GLIndexBuffer::Bind() const {
GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexbufferID_));
}
void GLIndexBuffer::UnBind() const {
GLCALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
}
} // namespace Ethan | 32.627119 | 101 | 0.670909 |
357aacf63c7d9f507c2fc9dfb197f5d474f336a4 | 351 | cpp | C++ | CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp | alaxion/Learning | 4b12b1603419252103cd933fdbfc4b2faffb6d00 | [
"MIT"
] | null | null | null | CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp | alaxion/Learning | 4b12b1603419252103cd933fdbfc4b2faffb6d00 | [
"MIT"
] | null | null | null | CppPrimer/CppPrimer-Exercises/CppPrimer-Ch05/Exercise5.22.cpp | alaxion/Learning | 4b12b1603419252103cd933fdbfc4b2faffb6d00 | [
"MIT"
] | null | null | null | // Exercise5.22.cpp
// Ad
// Rewrite the last example in this section using a loop.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int get_size();
int main()
{
int sz = get_size();
while (sz <= 0)
{
sz = get_size();
}
// pause
cin.get();
return 0;
}
int get_size()
{
return -1;
} | 12.535714 | 58 | 0.555556 |
357e438ac93c4bb905bdeb3833a77bd60233f590 | 2,788 | cpp | C++ | containers/list/c++/list.cpp | nonkr/cat | 754372d0f1a20de5d88aa54f489034478ab61444 | [
"MIT"
] | null | null | null | containers/list/c++/list.cpp | nonkr/cat | 754372d0f1a20de5d88aa54f489034478ab61444 | [
"MIT"
] | null | null | null | containers/list/c++/list.cpp | nonkr/cat | 754372d0f1a20de5d88aa54f489034478ab61444 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018, Billie Soong <nonkr@hotmail.com>
* All rights reserved.
*
* This file is under MIT, see LICENSE for details.
*
* Author: Billie Soong <nonkr@hotmail.com>
* Datetime: 2018/3/9 15:11
*
*/
#include <string>
#include <list>
#include <iostream>
#include <algorithm>
using namespace std;
void PrintIt(string &StringToPrint)
{
cout << StringToPrint << endl;
}
int main()
{
list<string> lst;
if (lst.empty())
{
cout << "empty list" << endl;
}
lst.push_back("b");
lst.push_back("c");
lst.push_front("a");
cout << "list size: " << lst.size() << endl;
cout << "list max_size: " << lst.max_size() << endl;
cout << "========" << endl;
// 遍历方式一
for (auto n : lst)
{
cout << n << endl;
}
cout << "========" << endl;
// 遍历方式二
list<string>::iterator lstIterator;
for (lstIterator = lst.begin(); lstIterator != lst.end(); lstIterator++)
{
cout << *lstIterator << endl;
}
cout << "========" << endl;
string s = lst.front();
cout << "first: " << s << endl;
cout << "========" << endl;
lst.pop_front();
string s2 = lst.front();
cout << "first after pop_front: " << s2 << endl;
cout << "========" << endl;
// 把list的元素倒转
lst.reverse();
// 遍历方式三
for_each(lst.begin(), lst.end(), PrintIt);
cout << "========" << endl;
list<int> Scores;
Scores.push_back(15);
Scores.push_back(100);
Scores.push_back(5);
Scores.push_back(25);
Scores.push_back(10);
Scores.push_back(100);
Scores.push_back(25);
Scores.push_back(30);
Scores.push_back(20);
cout << count(Scores.begin(), Scores.end(), 100) << endl;
cout << count_if(Scores.begin(), Scores.end(), [](int i) { return i % 10 == 0; }) << endl;
cout << "========" << endl;
for (auto n : Scores)
{
cout << n << endl;
}
Scores.sort();
cout << "==== after sort() ====" << endl;
for (auto n : Scores)
{
cout << n << endl;
}
Scores.erase(Scores.begin());
cout << "==== after erase(Scores.begin()) ====" << endl;
for (auto n : Scores)
{
cout << n << endl;
}
cout << "========" << endl;
Scores.remove(25);
cout << "==== after remove(25) ====" << endl;
for (auto n : Scores)
{
cout << n << endl;
}
cout << "========" << endl;
Scores.unique();
cout << "==== after unique() ====" << endl;
for (auto n : Scores)
{
cout << n << endl;
}
cout << "========" << endl;
Scores.erase(Scores.begin(), Scores.end());
cout << "==== after erase() ====" << endl;
for (auto n : Scores)
{
cout << n << endl;
}
cout << "========" << endl;
return 0;
}
| 20.651852 | 94 | 0.48637 |
357f2fc5c895bbe88e01755584290087338ea20c | 3,816 | cpp | C++ | src/armed/FilePickerDialog.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/armed/FilePickerDialog.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/armed/FilePickerDialog.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | // This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
#include "StdAfx.h"
#include "FilePickerDialog.h"
#include "QtUtil.h"
#include "Project.h"
#include "QtUtil.h"
namespace Armed
{
//////////////////////////////////////////////////////////////////////////
FilePickerDialog::FilePickerDialog(QWidget* parent) : QDialog(parent)
{
m_Ui.setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
connect(m_Ui.OkButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(m_Ui.CancelButton, SIGNAL(clicked()), this, SLOT(reject()));
connect(this, SIGNAL(finished(int)), this, SLOT(OnFinished()));
connect(m_Ui.ProjectTree, SIGNAL(PathSelected(QString)), this, SLOT(OnPathSelected(QString)));
connect(m_Ui.ProjectTree, SIGNAL(doubleClicked(QModelIndex)), m_Ui.OkButton, SLOT(click()));
connect(m_Ui.FileName, SIGNAL(textChanged(QString)), this, SLOT(OnPathEdited(QString)));
OnPathEdited("");
QSettings settings;
settings.beginGroup("FilePickerDialog");
restoreGeometry(settings.value("Geometry").toByteArray());
m_Ui.MainSplitter->restoreState(settings.value("MainSplitter").toByteArray());
settings.endGroup();
}
//////////////////////////////////////////////////////////////////////////
FilePickerDialog::~FilePickerDialog()
{
}
//////////////////////////////////////////////////////////////////////////
void FilePickerDialog::OnFinished()
{
QSettings settings;
settings.beginGroup("FilePickerDialog");
settings.setValue("Geometry", saveGeometry());
settings.setValue("MainSplitter", m_Ui.MainSplitter->saveState());
settings.endGroup();
}
//////////////////////////////////////////////////////////////////////////
void FilePickerDialog::OnPathSelected(const QString& path)
{
if (QtUtil::NormalizeFileName(path) != QtUtil::NormalizeFileName(m_Ui.FileName->text()))
m_Ui.FileName->setText(QDir::toNativeSeparators(path));
}
//////////////////////////////////////////////////////////////////////////
void FilePickerDialog::OnPathEdited(const QString& path)
{
bool isValid = false;
bool isFile = false;
bool isAbs = false;
if (!path.isEmpty())
{
QString absPath = Project::GetInstance()->GetAbsoluteFileName(path.trimmed());
QFileInfo fileInfo(absPath);
if (fileInfo.exists())
{
m_Ui.ProjectTree->SetCurrentFile(Project::GetInstance()->GetRelativeFileName(absPath));
isValid = true;
isFile = fileInfo.isFile() && m_FilterExtensions.contains(fileInfo.suffix().toLower());
isAbs = QDir::isAbsolutePath(path);
}
}
m_Ui.OkButton->setEnabled(isFile);
QPalette palette = m_Ui.FileName->palette();
QColor textColor = Qt::black;
if (isValid)
{
if (isAbs) textColor = Qt::red;
}
else textColor = Qt::darkGray;
palette.setColor(QPalette::Active, QPalette::Text, textColor);
m_Ui.FileName->setPalette(palette);
}
//////////////////////////////////////////////////////////////////////////
QString FilePickerDialog::GetCurrentFile() const
{
return QDir::fromNativeSeparators(m_Ui.FileName->text().trimmed());
}
//////////////////////////////////////////////////////////////////////////
void FilePickerDialog::SetCurrentFile(const QString& fileName)
{
m_Ui.FileName->setText(QDir::fromNativeSeparators(fileName));
}
//////////////////////////////////////////////////////////////////////////
void FilePickerDialog::SetFilterTypes(const QString& types)
{
m_FilterTypes = types.split(";", QString::SkipEmptyParts);
QtUtil::FileTypeListToExtList(types, m_FilterExtensions);
QStringList masks;
qforeach (const QString& ext, m_FilterExtensions)
{
masks << "*." + ext;
}
m_Ui.ProjectTree->SetFilters(masks);
}
} // namespace Armed | 30.774194 | 96 | 0.604036 |
35815d9343ab23878ef8569e186361f1efda9a3b | 4,293 | cpp | C++ | src/ReconstructionModules/NeutrinoReconstructionByApproximation.cpp | jjacob/AnalysisSoftware | 670513bcde9c3df46077f906246e912627ee251a | [
"Apache-2.0"
] | null | null | null | src/ReconstructionModules/NeutrinoReconstructionByApproximation.cpp | jjacob/AnalysisSoftware | 670513bcde9c3df46077f906246e912627ee251a | [
"Apache-2.0"
] | null | null | null | src/ReconstructionModules/NeutrinoReconstructionByApproximation.cpp | jjacob/AnalysisSoftware | 670513bcde9c3df46077f906246e912627ee251a | [
"Apache-2.0"
] | null | null | null | /*
* NeutrinoReconstructionByApproximation.cpp
*
* Created on: Apr 2, 2012
* Author: lkreczko
*/
#include "../../interface/ReconstructionModules/NeutrinoReconstructionByApproximation.h"
namespace BAT {
const double initialBigValue = 123456789;
boost::array<ParticlePointer, 2> NeutrinoReconstructionByApproximation::getNeutrinos(unsigned int approximation) {
ParticlePointer neutrino(new Particle(initialBigValue, initialBigValue, initialBigValue, initialBigValue));
switch (approximation) {
case NeutrinoApproximation::ScalingMETApproximation:
neutrino = scalingMETApproximation();
break;
case NeutrinoApproximation::SameEtaApproximation:
neutrino = sameEtaApproximation();
break;
case NeutrinoApproximation::ColinearApproximation:
neutrino = colinearApproximation();
break;
case NeutrinoApproximation::NullDeltaApproximation:
neutrino = nullDeltaApproximation();
break;
}
boost::array<ParticlePointer, 2> neutrinos;
neutrinos.at(0) = neutrino;
neutrinos.at(1) = neutrino;
return neutrinos;
}
ParticlePointer NeutrinoReconstructionByApproximation::scalingMETApproximation() {
const double WMass(BasicNeutrinoReconstruction::W_mass);
double MissingPx(met->px()), MissingPy(met->py());
double MissingPt = met->pt();
double SumPt = MissingPt + leptonFromW->pt();
double SumPx = MissingPx + leptonFromW->px();
double SumPy = MissingPy + leptonFromW->py();
double WTransverseMass = sqrt(SumPt * SumPt - SumPx * SumPx - SumPy * SumPy);
double factor = WMass / WTransverseMass;
double NewMissingPx = MissingPx * (factor * factor);
double NewMissingPy = MissingPy * (factor * factor);
MissingPt = sqrt(NewMissingPx * NewMissingPx + NewMissingPy * NewMissingPy);
SumPx = NewMissingPx + leptonFromW->px();
SumPy = NewMissingPy + leptonFromW->py();
double alpha = WMass * WMass + SumPx * SumPx + SumPy * SumPy - leptonFromW->energy() * leptonFromW->energy();
double beta = 0.5 * (alpha - MissingPt * MissingPt + leptonFromW->pz() * leptonFromW->pz());
double lambda = 2. * beta * leptonFromW->pz() / (leptonFromW->energy() * leptonFromW->energy() - leptonFromW->pz()
* leptonFromW->pz());
double Pz = lambda / 2.;
double energy = sqrt(MissingPt * MissingPt + Pz * Pz);
ParticlePointer neutrino(new Particle(energy, NewMissingPx, NewMissingPy, Pz));
return neutrino;
}
ParticlePointer NeutrinoReconstructionByApproximation::sameEtaApproximation() {
double Theta = leptonFromW->theta();
double MissingPt(met->pt());
double Phi = met->phi();
//calculate the neutrino momentum based on it's transverse momentum and the leptons theta angle(z, xy-plane)
double momentum = MissingPt / sin(Theta);
TVector3 Vector;
Vector.SetMagThetaPhi(momentum, Theta, Phi);
ParticlePointer neutrino(new Particle(momentum, Vector.Px(), Vector.Py(), Vector.Pz()));
return neutrino;
}
ParticlePointer NeutrinoReconstructionByApproximation::colinearApproximation() {
double MissingPx(met->px()), MissingPy(met->py());
double leptonPz(leptonFromW->pz());
double energy = sqrt(MissingPx * MissingPx + MissingPy * MissingPy + leptonPz * leptonPz);
ParticlePointer neutrino(new Particle(energy, MissingPx, MissingPy, leptonPz));
return neutrino;
}
ParticlePointer NeutrinoReconstructionByApproximation::nullDeltaApproximation() {
const double WMass(BasicNeutrinoReconstruction::W_mass);
double MissingPx(met->px()), MissingPy(met->py()), MissingPt(met->pt());
double leptonPz(leptonFromW->pz()), leptonEnergy(leptonFromW->energy());
double SumPx = MissingPx + leptonFromW->px();
double SumPy = MissingPy + leptonFromW->py();
double alpha = WMass * WMass + SumPx * SumPx + SumPy * SumPy - leptonEnergy * leptonEnergy;
double beta = 0.5 * (alpha - MissingPt * MissingPt + leptonPz * leptonPz);
double lambda = 2. * beta * leptonPz / (leptonEnergy * leptonEnergy - leptonPz * leptonPz);
double Pz = lambda / 2.;
double energy = sqrt(MissingPt * MissingPt + Pz * Pz);
ParticlePointer neutrino(new Particle(energy, MissingPx, MissingPy, Pz));
return neutrino;
}
NeutrinoReconstructionByApproximation::NeutrinoReconstructionByApproximation(const LeptonPointer lepton,
const METPointer met) :
BasicNeutrinoReconstruction(lepton, met) {
}
NeutrinoReconstructionByApproximation::~NeutrinoReconstructionByApproximation() {
}
}
| 36.07563 | 115 | 0.752853 |
3584bcbedc417d2b523b3629db28d225be9ba9bf | 3,579 | cpp | C++ | src/util/runnable_console_listener.cpp | MelbourneSpaceProgram/msp_flight_software_public | de290a2e7181ac43af1232b2ffbca2db8ec4ecd2 | [
"MIT"
] | 10 | 2018-04-28T04:44:56.000Z | 2022-02-06T21:12:13.000Z | src/util/runnable_console_listener.cpp | MelbourneSpaceProgram/msp_flight_software_public | de290a2e7181ac43af1232b2ffbca2db8ec4ecd2 | [
"MIT"
] | null | null | null | src/util/runnable_console_listener.cpp | MelbourneSpaceProgram/msp_flight_software_public | de290a2e7181ac43af1232b2ffbca2db8ec4ecd2 | [
"MIT"
] | 3 | 2019-02-16T03:22:26.000Z | 2022-02-03T14:54:22.000Z | #include <src/payload_processor/runnable_payload_processor.h>
#include <src/sensors/runnable_system_health_check.h>
#include <src/telecomms/lithium.h>
#include <src/util/message_codes.h>
#include <src/util/msp_exception.h>
#include <src/util/runnable_console_listener.h>
#include <src/util/runnable_console_logger.h>
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Mailbox.h>
Uart* RunnableConsoleListener::debug_uart = NULL;
RunnableConsoleListener::RunnableConsoleListener(Uart* debug_uart) {
if (RunnableConsoleListener::debug_uart == NULL) {
// WARNING: This task should only ever READ from the debug UART
RunnableConsoleListener::debug_uart = debug_uart;
} else {
throw MspException(
"Only one instance of RunnableConsoleListener should ever be "
"instantiated",
kConsoleListenerMultipleFail, __FILE__, __LINE__);
}
}
fnptr RunnableConsoleListener::GetRunnablePointer() {
return &RunnableConsoleListener::Listen;
}
bool RunnableConsoleListener::ReadUart(byte* read_buffer, uint8_t size) {
return size == debug_uart->PerformReadTransaction(read_buffer, size);
}
void RunnableConsoleListener::Listen() {
while (1) {
try {
byte header_buffer[5];
byte payload_buffer[Lithium::kMaxReceivedUplinkSize -
RunnablePayloadProcessor::kUplinkAx25Length];
// Grab sync characters (first two bytes of header/packet) one char
// at a time. Not two at a time so we can 'burn off' additional
// characters and regain sync
if (!ReadUart(header_buffer, 1)) continue;
if (header_buffer[0] !=
RunnableConsoleLogger::kMeasurableLoggerSyncChar1) {
continue;
}
if (!ReadUart(header_buffer + 1, 1)) continue;
if (header_buffer[1] !=
RunnableConsoleLogger::kMeasurableLoggerSyncChar2) {
continue;
}
if (!ReadUart(header_buffer + 2, 1)) continue; // size
if (header_buffer[2] == 0) continue;
if (!ReadUart(header_buffer + 3, 1)) continue; // id
if (!ReadUart(header_buffer + 4, 1))
continue; // TODO(dingbenjamin): Implement checksum
if (!ReadUart(payload_buffer, header_buffer[2])) continue;
// TODO(dingbenjamin): Do something with the size byte:
// header_buffer[2]
switch (header_buffer[3]) {
case kPayloadProcessorInjection:
// Create fake AX.25 bytes for the payload processor to
// throw away
byte fake_ax25_payload
[sizeof(payload_buffer) +
RunnablePayloadProcessor::kUplinkAx25Length];
memset(fake_ax25_payload, 0x00,
RunnablePayloadProcessor::kUplinkAx25Length);
memcpy(fake_ax25_payload +
RunnablePayloadProcessor::kUplinkAx25Length,
payload_buffer,
Lithium::kMaxReceivedUplinkSize -
RunnablePayloadProcessor::kUplinkAx25Length);
Mailbox_post(Lithium::GetInstance()->GetUplinkMailbox(),
fake_ax25_payload, BIOS_WAIT_FOREVER);
}
} catch (MspException& e) {
MspException::LogTopLevelException(e, kRunnableConsoleLoggerCatch);
}
}
}
| 39.32967 | 79 | 0.605197 |
3585618ed34f4961ccc77b2e7dd5e0f6ecb06a89 | 885 | cpp | C++ | SPOJ/FENCE1 - Build a Fence.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 6 | 2018-11-26T02:38:07.000Z | 2021-07-28T00:16:41.000Z | SPOJ/FENCE1 - Build a Fence.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 1 | 2021-05-30T09:25:53.000Z | 2021-06-05T08:33:56.000Z | SPOJ/FENCE1 - Build a Fence.cpp | ravirathee/Competitive-Programming | 20a0bfda9f04ed186e2f475644e44f14f934b533 | [
"Unlicense"
] | 4 | 2020-04-16T07:15:01.000Z | 2020-12-04T06:26:07.000Z | /*FENCE1 - Build a Fence
#math
There is a wall in your backyard. It is so long that you can’t see its endpoints. You want to build a fence of length L such that the area enclosed between the wall and the fence is maximized. The fence can be of arbitrary shape, but only its two endpoints may touch the wall.
Input
The input consists of several test cases.
For every test case, there is only one integer L (1<=L<=100), indicating the length of the fence.
The input ends with L=0.
Output
For each test case, output one line containing the largest area. Your answer should be rounded to 2 digits after the decimal point.
Example
Input:
1
0
Output:
0.16
*/
#include <cmath>
#include <iomanip>
#include <iostream>
int main()
{
for (int l; std::cin >> l && l !=0;)
{
std::cout << std::setprecision(2) << std::fixed << l*l / (std::atan(1) * 8) << std::endl;
}
}
| 23.918919 | 276 | 0.693785 |
358565336bad30a16789c0389cdf37d969dfd7d7 | 478 | hpp | C++ | include/SSVOpenHexagon/Data/PackData.hpp | mehlon/SSVOpenHexagon | a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad | [
"AFL-3.0"
] | null | null | null | include/SSVOpenHexagon/Data/PackData.hpp | mehlon/SSVOpenHexagon | a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad | [
"AFL-3.0"
] | null | null | null | include/SSVOpenHexagon/Data/PackData.hpp | mehlon/SSVOpenHexagon | a6abf3bcf41b4f6821c53f92a86f9b8c00ecbaad | [
"AFL-3.0"
] | null | null | null | // Copyright (c) 2013-2015 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#ifndef HG_PACKDATA
#define HG_PACKDATA
namespace hg
{
struct PackData
{
std::string id, name;
float priority;
PackData(
const std::string& mId, const std::string& mName, float mPriority)
: id{mId}, name{mName}, priority{mPriority}
{
}
};
}
#endif
| 20.782609 | 78 | 0.60251 |
3586b02ccae01f85d6954123e95c028070b1f195 | 4,407 | cpp | C++ | MyThirthyHomeWork/for.1/for.1.cpp | pashak14/CppHomeWork | 861bf1241800f2c6a0fb782738554d617de89599 | [
"MIT"
] | null | null | null | MyThirthyHomeWork/for.1/for.1.cpp | pashak14/CppHomeWork | 861bf1241800f2c6a0fb782738554d617de89599 | [
"MIT"
] | null | null | null | MyThirthyHomeWork/for.1/for.1.cpp | pashak14/CppHomeWork | 861bf1241800f2c6a0fb782738554d617de89599 | [
"MIT"
] | 1 | 2020-12-14T11:52:04.000Z | 2020-12-14T11:52:04.000Z | #include <iostream>
using namespace std;
void variant1(),
variant2(),
variant3(),
variant4(),
variant5(),
variant6(),
variant7(),
variant8(),
variant9(),
variant10();
int main() {
int numEx;
setlocale(0, "");
while (true) {
cout << "\nВведите вариант узора (0 - 10): " << endl;
cin >> numEx;
switch (numEx) {
case 1:
variant1();
break;
case 2:
variant2();
break;
case 3:
variant3();
break;
case 4:
variant4();
break;
case 5:
variant5();
break;
case 6:
variant6();
break;
case 7:
variant7();
break;
case 8:
variant8();
break;
case 9:
variant9();
break;
case 10:
variant10();
break;
}
}
}
void variant1() {
int i = 0, j = 0, k = 0, col = 10;
while (0 < col) {
i++;
col -= 1;
j = 0;
while (j <= col) {
j++;
cout << " * ";
}
cout << endl;
k = 0;
while (k < i) {
cout << " ";
k++;
}
}
}
void variant2() {
int i = 0, j, col = 10;
while (i < col) {
i++;
j = 0;
while (j < i) {
j++;
cout << " * ";
}
cout << endl;
}
}
void variant3() {
int i = 0, j, k, b, col = 10;
while (0 <= col ) {
i++;
col -= 2;
j = 0;
while (j <= col) {
j++;
cout << " * ";
}
cout << endl;
k = 0;
while (k < i) {
cout << " ";
k++;
}
}
}
void variant4() {
int n = 0, i = 0, col = 10;
n = 1;
while (n <= col) {
i = 1;
while (i <= col) {
if ((!(i >= n) && !(i + n <= col))) {
cout << " * ";
}
else {
cout << " ";
}
i++;
}
cout << endl;
n++;
}
}
void variant5() {
int n = 0, i = 0, col = 10;
n = 1;
while (n <= col) {
i = 1;
while (i <= col) {
if ((!(i >= n) && !(i + n <= col)) || ((i >= n) && (i + n <= col))) {
cout << " * ";
}
else {
cout << " ";
}
i++;
}
cout << endl;
n++;
}
}
void variant7() {
int n = 0, i = 0, col = 10;
n = 1;
while (n <= col) {
i = 1;
while (i <= col) {
if (i <= n && (i + n ) <= col) {
cout << " * ";
}
else {
cout << " ";
}
i++;
}
cout << endl;
n++;
}
}
void variant6() {
int n = 0, i = 0, col = 9;
n = 1;
while (n <= col) {
i = 1;
while (i <= col) {
if ((i <= n && (i + n - 1) <= col) || (i >= n && !(i + n <= col))) {
cout << " * ";
}
else {
cout << " ";
}
i++;
}
cout << endl;
n++;
}
}
void variant8() {
int n = 0, i = 0, col = 10;
n = 1;
while (n <= col) {
i = 1;
while (i <= col) {
if ((i >= n && !(i + n - 1 <= col))) {
cout << " * ";
}
else {
cout << " ";
}
i++;
}
cout << endl;
n++;
}
}
void variant10() {
int i = 0, j = 0, k = 0, col = 10;
while (0 < col) {
i++;
col -= 1;
k = 0;
while (k < i - 1) {
k++;
cout << " * ";
}
cout << endl;
j = 0;
while (j <= col) {
cout << " ";
j++;
}
}
}
void variant9() {
int i = 0, j, k, col = 10;
while (i < col) {
i++;
k = i;
while (k <= col) {
k++;
cout << " * ";
}
cout << endl;
}
}
| 17.557769 | 81 | 0.256637 |
3587c88b7d11dc508d9a24ec8758b390be867c65 | 20,157 | cc | C++ | src/core/rnn/CustomLayers.cc | arjun-k-r/Sibyl | ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb | [
"Apache-2.0"
] | 34 | 2017-03-01T05:49:17.000Z | 2022-01-01T15:30:06.000Z | src/core/rnn/CustomLayers.cc | arjun-k-r/Sibyl | ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb | [
"Apache-2.0"
] | 1 | 2018-12-19T17:02:52.000Z | 2018-12-19T17:02:52.000Z | src/core/rnn/CustomLayers.cc | junosan/Sibyl | ae2edbb09f58e8b1cef79470e8ca9c02c244fdcb | [
"Apache-2.0"
] | 24 | 2017-09-19T01:51:50.000Z | 2022-02-04T19:53:16.000Z | /*
Copyright 2017 Hosang Yoon
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "CustomLayers.h"
#include <string>
namespace fractal
{
void AddLstmLayer_ForgetOneInit(Rnn &rnn,
const std::string &name,
const std::string &biasLayer,
const unsigned long delayAmount,
const unsigned long size,
const bool selfLoop,
const InitWeightParam &initWeightParam)
{
const std::string prefix = name + ".";
rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size);
rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size);
rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size);
rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_SQUASH", ACT_TANH, AGG_SUM, size);
rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size);
ConnParam connParam(CONN_IDENTITY);
connParam.srcRangeFrom = 0;
connParam.srcRangeTo = size - 1;
rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam);
rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL.DELAYED", {CONN_IDENTITY, delayAmount});
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SQUASH", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_SQUASH", prefix + "OUTPUT", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY);
/* Bias */
ConnParam initParam(initWeightParam);
initParam.dstRangeFrom = 0;
initParam.dstRangeTo = size - 1;
rnn.AddConnection(biasLayer, prefix + "INPUT", initParam);
initParam.dstRangeFrom += size;
initParam.dstRangeTo += size;
rnn.AddConnection(biasLayer, prefix + "INPUT", initParam);
InitWeightParamUniform oneInitParam;
oneInitParam.a = 1.0;
oneInitParam.b = 1.0;
oneInitParam.isValid = true;
ConnParam oneParam(oneInitParam);
oneParam.dstRangeFrom = 2 * size;
oneParam.dstRangeTo = 3 * size - 1;
rnn.AddConnection(biasLayer, prefix + "INPUT", oneParam);
initParam.dstRangeFrom += 2 * size;
initParam.dstRangeTo += 2 * size;
rnn.AddConnection(biasLayer, prefix + "INPUT", initParam);
/* Peephole connections */
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam);
rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam);
rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam);
rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY);
if(selfLoop == true)
{
rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size);
rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount});
rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam);
}
}
void AddResGateLayer(Rnn &rnn,
const std::string &name,
const std::string &biasLayer,
const unsigned long size)
{
// out = in_r * sig(k) + in_1 * (1 - sig(k))
// in_r : residual (output of layer just below)
// in_1 : identity (input of layer just below)
// assumes in_r.size == in_1.size
const std::string prefix = name + ".";
rnn.AddLayer(prefix + "INPUT_R" , ACT_LINEAR , AGG_MULT, size);
rnn.AddLayer(prefix + "INPUT_1" , ACT_LINEAR , AGG_MULT, size);
rnn.AddLayer(prefix + "SWITCH_R", ACT_SIGMOID , AGG_SUM , size);
rnn.AddLayer(prefix + "SWITCH_1", ACT_ONE_MINUS_LINEAR, AGG_SUM , size);
rnn.AddLayer(prefix + "OUTPUT" , ACT_LINEAR , AGG_SUM , size);
InitWeightParamUniform minusOne; // biased towards identity initially
minusOne.a = -1.0;
minusOne.b = -1.0;
minusOne.isValid = true;
rnn.AddConnection(biasLayer , prefix + "SWITCH_R", minusOne);
rnn.AddConnection(prefix + "SWITCH_R", prefix + "SWITCH_1", CONN_IDENTITY);
rnn.AddConnection(prefix + "SWITCH_R", prefix + "INPUT_R", CONN_IDENTITY);
rnn.AddConnection(prefix + "SWITCH_1", prefix + "INPUT_1", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_R", prefix + "OUTPUT", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_1", prefix + "OUTPUT", CONN_IDENTITY);
}
void AddLstmLayer_LearnInit(Rnn &rnn,
const std::string &name,
const std::string &biasLayer,
const unsigned long delayAmount,
const unsigned long size,
const InitWeightParam &initWeightParam)
{
const std::string prefix = name + ".";
rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size);
rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size);
rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size);
rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_SUM, size); // mult -> sum
rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_SQUASH", ACT_TANH, AGG_SUM, size);
rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_SUM, size); // mult -> sum
// switch between init & prev states
// reset = 1. (use init states) or 0. (use prev states)
{
rnn.AddLayer(prefix + "RESET", ACT_LINEAR , AGG_SUM, 1);
rnn.AddLayer(prefix + "CARRY", ACT_ONE_MINUS_LINEAR, AGG_SUM, 1);
rnn.AddConnection(prefix + "RESET", prefix + "CARRY", CONN_IDENTITY);
rnn.AddLayer(prefix + "MEMORY_CELL_INIT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "MEMORY_CELL_PREV", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_INIT" , ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_PREV" , ACT_LINEAR, AGG_MULT, size);
rnn.AddConnection(biasLayer, prefix + "MEMORY_CELL_INIT", initWeightParam);
rnn.AddConnection(biasLayer, prefix + "OUTPUT_INIT" , initWeightParam);
rnn.AddConnection(prefix + "RESET", prefix + "MEMORY_CELL_INIT", CONN_BROADCAST);
rnn.AddConnection(prefix + "CARRY", prefix + "MEMORY_CELL_PREV", CONN_BROADCAST);
rnn.AddConnection(prefix + "RESET", prefix + "OUTPUT_INIT" , CONN_BROADCAST);
rnn.AddConnection(prefix + "CARRY", prefix + "OUTPUT_PREV" , CONN_BROADCAST);
rnn.AddConnection(prefix + "MEMORY_CELL_INIT", prefix + "MEMORY_CELL.DELAYED", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL_PREV", prefix + "MEMORY_CELL.DELAYED", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_INIT" , prefix + "OUTPUT.DELAYED" , CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_PREV" , prefix + "OUTPUT.DELAYED" , CONN_IDENTITY);
}
ConnParam connParam(CONN_IDENTITY);
connParam.srcRangeFrom = 0;
connParam.srcRangeTo = size - 1;
rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam);
rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL_PREV", {CONN_IDENTITY, delayAmount}); // .DELAYED -> _PREV
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SQUASH", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_SQUASH", prefix + "OUTPUT", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY);
/* Bias */
rnn.AddConnection(biasLayer, prefix + "INPUT", initWeightParam);
/* Peephole connections */
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam);
rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam);
rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam);
rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY);
// selfLoop
{
rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT_PREV", {CONN_IDENTITY, delayAmount}); // .DELAYED -> _PREV
rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam);
}
}
void AddLstmLayer_DSigmoidOut(Rnn &rnn,
const std::string &name,
const std::string &biasLayer,
const unsigned long delayAmount,
const unsigned long size,
const bool selfLoop,
const InitWeightParam &initWeightParam)
{
const std::string prefix = name + ".";
rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size);
rnn.AddLayer(prefix + "INPUT_SQUASH", ACT_TANH, AGG_SUM, size);
rnn.AddLayer(prefix + "INPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "FORGET_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_GATE_PEEP", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "INPUT_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "INPUT_GATE_MULT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "MEMORY_CELL", ACT_LINEAR, AGG_SUM, size);
rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "FORGET_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "FORGET_GATE_MULT", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_SIGMOID", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "OUTPUT_ONE_MINUS_SIGMOID", ACT_ONE_MINUS_LINEAR, AGG_SUM, size);
rnn.AddLayer(prefix + "OUTPUT_DSIGMOID", ACT_LINEAR, AGG_MULT, size);
rnn.AddLayer(prefix + "OUTPUT_GATE", ACT_SIGMOID, AGG_SUM, size);
rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_MULT, size);
ConnParam connParam(CONN_IDENTITY);
connParam.srcRangeFrom = 0;
connParam.srcRangeTo = size - 1;
rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_SQUASH", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "INPUT_GATE", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "FORGET_GATE", connParam);
connParam.srcRangeFrom += size;
connParam.srcRangeTo += size;
rnn.AddConnection(prefix + "INPUT", prefix + "OUTPUT_GATE", connParam);
rnn.AddConnection(prefix + "INPUT_SQUASH", prefix + "INPUT_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_GATE", prefix + "INPUT_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "INPUT_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "MEMORY_CELL.DELAYED", {CONN_IDENTITY, delayAmount});
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE", prefix + "FORGET_GATE_MULT", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE_MULT", prefix + "MEMORY_CELL", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_SIGMOID", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_SIGMOID", prefix + "OUTPUT_ONE_MINUS_SIGMOID", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_SIGMOID", prefix + "OUTPUT_DSIGMOID", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_ONE_MINUS_SIGMOID", prefix + "OUTPUT_DSIGMOID", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_DSIGMOID", prefix + "OUTPUT", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_GATE", prefix + "OUTPUT", CONN_IDENTITY);
/* Bias */
rnn.AddConnection(biasLayer, prefix + "INPUT", initWeightParam);
/* Peephole connections */
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "INPUT_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED", prefix + "FORGET_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(prefix + "MEMORY_CELL", prefix + "OUTPUT_GATE_PEEP", CONN_IDENTITY);
rnn.AddConnection(biasLayer, prefix + "INPUT_GATE_PEEP", initWeightParam);
rnn.AddConnection(biasLayer, prefix + "FORGET_GATE_PEEP", initWeightParam);
rnn.AddConnection(biasLayer, prefix + "OUTPUT_GATE_PEEP", initWeightParam);
rnn.AddConnection(prefix + "INPUT_GATE_PEEP", prefix + "INPUT_GATE", CONN_IDENTITY);
rnn.AddConnection(prefix + "FORGET_GATE_PEEP", prefix + "FORGET_GATE", CONN_IDENTITY);
rnn.AddConnection(prefix + "OUTPUT_GATE_PEEP", prefix + "OUTPUT_GATE", CONN_IDENTITY);
if(selfLoop == true)
{
rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size);
rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount});
rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam);
}
}
void AddOELstmLayer(Rnn &rnn,
const std::string &name,
const std::string &biasLayer,
const unsigned long delayAmount,
const unsigned long size,
const bool selfLoop,
const InitWeightParam &initWeightParam)
{
const std::string prefix = name + ".";
verify(size % 2 == 0);
rnn.AddLayer(prefix + "INPUT", ACT_LINEAR, AGG_SUM, 4 * size);
// 1D weights (input bias & peephole) are added by the internal layers
// 2D weights (below-to-input & feedback) are added outside
basicLayers::AddFastLstmLayer(rnn, prefix + "OLSTM", biasLayer, 1,
size / 2, false, initWeightParam);
AddLstmLayer_DSigmoidOut (rnn, prefix + "ELSTM", biasLayer, 1,
size / 2, false, initWeightParam);
/* Connect "RESET" to
* "OLSTM.MEMORY_CELL.DELAYED" and "ELSTM.MEMORY_CELL.DELAYED" directly
*
* Otherwise, cannot function with "RESET" removed for inference
*/
rnn.AddLayer(prefix + "OUTPUT", ACT_LINEAR, AGG_SUM, size);
ConnParam srcParam(CONN_IDENTITY);
srcParam.srcRangeFrom = 0;
srcParam.srcRangeTo = 2 * size - 1;
rnn.AddConnection(prefix + "INPUT", prefix + "OLSTM.INPUT", srcParam);
srcParam.srcRangeFrom += 2 * size;
srcParam.srcRangeTo += 2 * size;
rnn.AddConnection(prefix + "INPUT", prefix + "ELSTM.INPUT", srcParam);
// // relay reset signal
// rnn.AddLayer(prefix + "MEMORY_CELL.DELAYED", ACT_LINEAR, AGG_SUM, size);
//
// srcParam.srcRangeFrom = 0;
// srcParam.srcRangeTo = size / 2 - 1;
// rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED",
// prefix + "OLSTM.MEMORY_CELL.DELAYED", srcParam);
//
// srcParam.srcRangeFrom += size / 2;
// srcParam.srcRangeTo += size / 2;
// rnn.AddConnection(prefix + "MEMORY_CELL.DELAYED",
// prefix + "ELSTM.MEMORY_CELL.DELAYED", srcParam);
ConnParam dstParam(CONN_IDENTITY);
dstParam.dstRangeFrom = 0;
dstParam.dstRangeTo = size / 2 - 1;
rnn.AddConnection(prefix + "OLSTM.OUTPUT", prefix + "OUTPUT", dstParam);
dstParam.dstRangeFrom += size / 2;
dstParam.dstRangeTo += size / 2;
rnn.AddConnection(prefix + "ELSTM.OUTPUT", prefix + "OUTPUT", dstParam);
if(selfLoop == true)
{
rnn.AddLayer(prefix + "OUTPUT.DELAYED", ACT_LINEAR, AGG_MULT, size);
rnn.AddConnection(prefix + "OUTPUT", prefix + "OUTPUT.DELAYED", {CONN_IDENTITY, delayAmount});
rnn.AddConnection(prefix + "OUTPUT.DELAYED", prefix + "INPUT", initWeightParam);
}
}
} | 49.283619 | 126 | 0.674406 |
358c3223168f206b6db3f4686d2072394f2d571e | 648 | cpp | C++ | PAT/B1011.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | PAT/B1011.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | PAT/B1011.cpp | iphelf/Programming-Practice | 2a95bb7153957b035427046b250bf7ffc6b00906 | [
"WTFPL"
] | null | null | null | #include<stdio.h>
using namespace std;
long long A,B,C;
bool check(){
if(A>0 && B>0 && C>0) return A>C-B;
if(A<0 && B<0 && C<0) return A>C-B;
if(A>0 && B>0 && C<0) return true;
if(A<0 && B<0 && C>0) return false;
return A+B>C;
}
int main(void) {
// freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
for(int I=1;I<=T;I++){
printf("Case #%d: ",I);
scanf("%lld%lld%lld",&A,&B,&C);
if(check()) puts("true");
else puts("false");
}
return 0;
}
/*
4
1 2 3
2 3 4
2147483647 0 2147483646
0 -2147483648 -2147483647
Case #1: false
Case #2: true
Case #3: true
Case #4: false
*/
| 16.615385 | 39 | 0.512346 |
358d183c0e807d86a5d58dda48fdd53de75f73d3 | 11,928 | cpp | C++ | src/kernel.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | src/kernel.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | src/kernel.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | #include <common/stdint.h>
#include <boot/bootinfo.h>
#include <pointers.h>
#include <IO/APIC/apic.h> //COMMENT
#include <smp/smp.h> //COMMENT
#include <gdt/gdt.h>
#include <gdt/tss.h> //COMMENT
#include <paging/PageTableManager.h>
#include <paging/PageFrameAllocator.h>
#include <memory/memory.h>
#include <memory/heap.h>
#include <process/Scheduler/Scheduler.h> //Comment (INCLUDES PROCESSES)
#include <interrupts/interrupts.h>
#include <exceptions/exceptions.h>
#include <interrupts/syscalls.h> //Comment
#include <interrupts/timer/pit.h>
#include <drivers/Driver.h>
#include <drivers/Intel/AHCI/AHCI.h>
#include <IO/DeviceManager/DeviceManager.h> //Comment
#include <fs/VolumeManager.h> //Comment
#include <drivers/Input/PS2KeyboardDriver.h>
#include <drivers/Input/PS2MouseDriver.h>
#include <common/stdio.h>
#include <common/cstring.h>
using namespace UnifiedOS;
using namespace UnifiedOS::Boot;
using namespace UnifiedOS::GlobalDescriptorTable;
using namespace UnifiedOS::Paging;
using namespace UnifiedOS::Memory;
using namespace UnifiedOS::Processes;
using namespace UnifiedOS::Interrupts;
using namespace UnifiedOS::Exceptions;
using namespace UnifiedOS::Interrupts::Syscalls;
using namespace UnifiedOS::Interrupts::Timer;
using namespace UnifiedOS::Drivers;
using namespace UnifiedOS::Devices;
using namespace UnifiedOS::FileSystem;
//SOMETHING TO HAVE A LOOK INTO FOR MAXIMUM MEMORY EFFICIENCY
//Look over code and make sure all needed * are kept but all un needed get removed
// (delete pointer)
//
//
//
//
#include <files/tga.h>
#include <interrupts/syscall.h>
void InitVolumes(DriverManager* driverM){
//NOTE
//TRY TO SETUP WITH LOOKING TO SEE IF THE VOLUME
//Locate Driver
Driver* driver = driverM->FindDriver("ACPI 1.0 Driver");
//Ensure Driver Found
if(driver != nullptr){
//Convert to AHCI
if(driver->MainObject != nullptr){
Drivers::AHCI::AHCIDriver* AHCIdriver = (Drivers::AHCI::AHCIDriver*)(driver->MainObject);
//Look at ports
for(int p = 0; p < AHCIdriver->portCount; p++){
//Find Disks
if(AHCIdriver->Ports[p]->portType == AHCI::AHCIPort::PortType::SATA){
//Mount
__FS_VOLUME_MANAGER__->MountVolume(AHCIdriver->Ports[p]);
}
}
}
}
}
void DrawBootScreen(){
Clear(0x00);
//Read the icon file
GeneralFile* File = syscall(6, "B:/UnifiedIcon.tga");
//If the file is found displat the logo
if(File->Found){
uint8_t* Buffer = (uint8_t*)Memory::malloc(__BOOT__BootContext__->framebuffer->BufferSize);
File->Disk->Read((File->Sectors[0]*512), File->FileSize, Buffer);
//Recode this!
TGA_Image image = TGA().GetImage(Buffer);
Memory::free(Buffer);
//Work out system center
uint64_t xoff = (__BOOT__BootContext__->framebuffer->Width / 2) - (image.header.width / 2);
uint64_t xoffText = (__BOOT__BootContext__->framebuffer->Width / 2) - ((strlen("Loading System") * 16) / 4);
uint64_t xoffText1 = (__BOOT__BootContext__->framebuffer->Width / 2) - ((strlen("Unified OS: Version 0.0.1") * 16) / 4);
uint64_t yoff = (__BOOT__BootContext__->framebuffer->Height / 4) - (image.header.width / 2);
uint64_t yoffText = ((__BOOT__BootContext__->framebuffer->Height / 2)) - 8;
for(int y = image.header.height - 1; y >= 0; y--){
for(int x = image.header.width - 1; x >= 0; x--){
putPix(x + xoff, (image.header.height - 1) - y + yoff, image.Buffer[(y * image.header.width) + x]);
}
}
//Print boot
SetPosX(xoffText);
SetPosY(yoffText);
printf("Loading System\n");
SetPosX(xoffText1);
printf("Unified OS: Version 0.0.1");
SetPosX(0);
SetPosY(0);
//Delete Image Data after
delete image.Buffer;
}
}
void KernelStage2(){
//Volumes
InitVolumes(Pointers::Drivers::DriverManager);
//GP FAULT CAUSED HERE... ^ on real hardware
// PS2Init();
//Real hardware is to be imagined right now with how this works
//Create Boot Screen
DrawBootScreen();
// TestTGA();
//Load System Modules
while (true)
{
/* code */
}
}
//For locking the memory at the kernel
extern uint64_t _KernelStart;
extern uint64_t _KernelEnd;
void InitialisePaging(){
//Entries (Pages)
uint64_t mMapEntries = __BOOT__BootContext__->mMapSize / __BOOT__BootContext__->DescriptorSize;
//Load Memory To Page Frame Allocator
__PAGING__PFA_GLOBAL = PageFrameAllocator();
__PAGING__PFA_GLOBAL.ReadEFIMemoryMap(__BOOT__BootContext__->mMap, __BOOT__BootContext__->mMapSize, __BOOT__BootContext__->DescriptorSize);
uint64_t SizeOfKernel = (uint64_t)&_KernelEnd - (uint64_t)&_KernelStart;
uint64_t PageCountOfKernel = (uint64_t)SizeOfKernel / 0x1000 + 1;
//Lock memory pages at kernel positions
__PAGING__PFA_GLOBAL.LockPages(&_KernelStart, PageCountOfKernel);
//Get a Page for the Page Table Manager
PageTable* PML4 = (PageTable*)__PAGING__PFA_GLOBAL.RequestPage();
//Fill it with zero to stop any issues with default
memset(PML4, 0, 0x1000);
//Setup the page table manager
__PAGING__PTM_GLOBAL = PageTableManager(PML4);
//Map memory addresses to default
for(uint64_t t = 0; t < __PAGING__TotalMemorySize__; t+=0x1000){ //We do this in 4KiB Pages
__PAGING__PTM_GLOBAL.MapMemory((void*)t, (void*)t);
}
//Lock Framebuffer Pages
uint64_t FramebufferBase = (uint64_t)__BOOT__BootContext__->framebuffer->BaseAddress;
uint64_t FramebufferSize = (uint64_t)__BOOT__BootContext__->framebuffer->BufferSize + 0x1000; //We add this is a padding
__PAGING__PFA_GLOBAL.LockPages((void*)FramebufferBase, FramebufferSize / 0x1000 + 1); // +1 just incase not entire fit
//Map the framebuffer address
for(uint64_t t = FramebufferBase; t < FramebufferBase + FramebufferSize; t+=4096){ //We do this in 4KiB Pages
__PAGING__PTM_GLOBAL.MapMemory((void*)t, (void*)t);
}
//Load the Page Table
asm("mov %0, %%cr3" : : "r" (PML4));
}
// inline void WaitSignal() {
// IO::Port8Bit CommandPort(0x64);
// int timeout = 10000;
// while (timeout--)
// if ((CommandPort.Read() & 0x2) != 0x2)
// return;
// }
//
// template <bool isMouse> inline void WaitData() {
// IO::Port8Bit CommandPort(0x64);
// int timeout = 10000;
// while (timeout--)
// if ((CommandPort.Read() & 0x21) == (isMouse ? 0x21 : 0x1))
// return;
// }
//
// void PS2Init(){
// IO::Port8Bit DataPort(0x60);
// IO::Port8Bit CommandPort(0x64);
// IO::Port8Bit PITMaster(0x20);
//
// // Start by disabling both ports
// WaitSignal();
// CommandPort.Write(0xAD);
// WaitSignal();
// CommandPort.Write(0xA7);
//
// DataPort.Read(); // Discard any data
//
// WaitSignal();
// CommandPort.Write(0x20);
// WaitData<false>();
// uint8_t status = PITMaster.Read();
//
// WaitSignal();
// CommandPort.Write(0xAE);
// WaitSignal();
// CommandPort.Write(0xA8);
//
// // Enable interrupts, enable keyboard and mouse clock
// status = ((status & ~0x30) | 3);
// WaitSignal();
// CommandPort.Write(0x60);
// WaitSignal();
// CommandPort.Write(status);
// WaitData<false>();
// DataPort.Read();
// }
extern "C" void kernelMain(BootInfo* bootInfo)
{
__BOOT__BootContext__ = bootInfo;
//Blank Screen
Clear(0x00);
//Detect SMP cores test
//I Dont know why (I think a delay effect) but whenever I remove the prints
//It stops working???
printf("SMP APIC: \n");
IO::APIC::ReadAPIC();
printf("Found ");
printf(to_string((int64_t)IO::APIC::CoreCount));
printf(", IOAPIC ");
printf(to_hstring(IO::APIC::IOAPIC_PTR));
printf(", LAPIC ");
printf(to_hstring(IO::APIC::LAPIC_PTR));
printf(", Processor IDs: ");
for(int i = 0; i < IO::APIC::CoreCount; i++){
printf(to_string((int64_t)IO::APIC::LAPIC_IDs[i]));
printf(" ");
}
printf("\n");
//Memory
InitialisePaging();
//GDT
LoadGDT(&__GDTDesc);
//Heap
//We use a high address to not interrupt other addresses
//Yes this can lead to issues such as what if we reach the heap and overwrite it
//Im not sure how I can fix that its just how it is. Well I suppose the pages will be locked
//So its not too much of an issue.
InitialiseHeap((void*)0x0000100000000000, 0xFF);
//Interrupts (Default)
Pointers::Interrupts::Interrupts = new InterruptManager();
//Syscalls
Pointers::Interrupts::Syscalls::Syscalls = new SyscallHandler(Pointers::Interrupts::Interrupts);
//Intialise Exceptions
Pointers::Exceptions::Exceptions = new ExceptionManager(Pointers::Interrupts::Interrupts);
//Drivers
Pointers::Drivers::DriverManager = new DriverManager();
//Devices
Pointers::Devices::DeviceManager = new DeviceManager(Pointers::Drivers::DriverManager);
// //Keyboard Driver MAKE USING new
// PrintfKeyboardEventHandler KeyboardHandler;
// PS2KeyboardDriver keyboard(Pointers::Interrupts::Interrupts, &KeyboardHandler);
// Pointers::Drivers::DriverManager->AddDriver(&keyboard);
// //Mouse Driver MAKE USING new
// MouseToScreen MouseHandler;
// PS2MouseDriver mouse(Pointers::Interrupts::Interrupts, &MouseHandler);
// Pointers::Drivers::DriverManager->AddDriver(&mouse);
//Activate Drivers
//SETUP NOTE: Make it so when a driver is called to activate it check if already ative and ignores if active
//To allow for more drivers to be loaded after this boot
Pointers::Drivers::DriverManager->ActivateAll();
//PIT
__TIMER__PIT__ = new PIT(Pointers::Interrupts::Interrupts);
__TIMER__PIT__->SetFrequency(1000); //INACURRATE
//ERRORS WITH PIT MAPPING ON MODERN HARDWARE
//Dissable PIC
Pointers::Interrupts::Interrupts->DissablePIC();
//APIC NOTE
//Sometimes the interrupts do not register which is an issue (With PIT)
//As this will cause the smp to fail to initialise
//However this only seems to be with qemu not real hardware
//APIC Inits
//Spurious Interrupt
IO::APIC::SpuriousInterrupHandler* SpuriousInterupts = new IO::APIC::SpuriousInterrupHandler(Pointers::Interrupts::Interrupts);
IO::APIC::LApicInit();
IO::APIC::IntitateIO();
IO::APIC::MapLegacyIRQ(0x01); //PS2 Keyboard
IO::APIC::MapLegacyIRQ(0x0C); //PS2 Mouse
//Interrupts activation
Pointers::Interrupts::Interrupts->Activate();
//SMP
//Will now boot all the cpu's that are not booted.
//64-Bit gets toggled with gdt
//Interrupts are synced
SMP::Intitialise();
printf("All ");
printf(to_string((int64_t)SMP::ActiveCPUs));
printf(" Have Been Booted!\n\n");
//Issues here with real hardware:
//Either SMP fails to exit (I presume TSS)
//Or somthing wrong with the preparation of the SMP Trampoline just not working (well working but breaking everything else)
//Scheduling has issues with process swapping and all of that swaps
//Processes
Scheduling::IntialiseScheduler(Pointers::Interrupts::Interrupts, (uint64_t)KernelStage2); //CAUSES ISSUES (REAL HARDWARE Div by zero Exception)
// Process* proctest = Scheduling::__SCHEDULER__->NewProcess("TestProcess", (uint64_t)TaskA, 0);
//All issues I thought are actually TSS issues
//TYPES
//User space (NEED TO IMPLEMENT) (https://wiki.osdev.org/Getting_to_Ring_3)
// This will also need to link to system calls for userspace to reach
//Kernel space (This)
// KernelStage2();
while(true){
// printf("Task Kernel...\n");
// asm("hlt"); //Saves performance
}
} | 31.0625 | 147 | 0.662726 |
358d5a54c7d047a78830dec29366b630d8df5df2 | 3,404 | cpp | C++ | data/train/cpp/358d5a54c7d047a78830dec29366b630d8df5df2Share.cpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/train/cpp/358d5a54c7d047a78830dec29366b630d8df5df2Share.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 14 | 2015-02-28T17:11:23.000Z | 2016-09-05T05:00:20.000Z | data/train/cpp/358d5a54c7d047a78830dec29366b630d8df5df2Share.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | #include <Share.h>
#include <bps/event.h>
#include <bps/navigator.h>
#include <bps/navigator_invoke.h>
#include <screen/screen.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <vector>
using namespace std;
namespace openflShareExtension {
void log(const char *msg) {
/*
FILE *logFile = fopen("logs/log.txt", "a");
fprintf(logFile, "%s\n", msg);
fclose(logFile);
*/
}
void doShare(const char *method, const char *text) {
navigator_invoke_invocation_t *invoke = NULL;
navigator_invoke_invocation_create(&invoke);
navigator_invoke_invocation_set_action(invoke, "bb.action.SHARE");
navigator_invoke_invocation_set_data(invoke, text, strlen(text));
navigator_invoke_invocation_set_target(invoke, method);
navigator_invoke_invocation_set_type(invoke, "text/plain");
navigator_invoke_invocation_send(invoke);
navigator_invoke_invocation_destroy(invoke);
}
vector<ShareQueryResult> query() {
/*
FILE *logFile = fopen("logs/log.txt", "w");
fclose(logFile);
char msg[64];
*/
/*
snprintf(msg, 64, "pid %d\n", getpid());
log(msg);
*/
vector<ShareQueryResult> results;
navigator_invoke_query_t *query = NULL;
navigator_invoke_query_create(&query);
navigator_invoke_query_set_id(query, "12345");
navigator_invoke_query_set_action(query, "bb.action.SHARE");
navigator_invoke_query_set_type(query, "text/plain");
if (navigator_invoke_query_send(query)!=BPS_SUCCESS) {
log("navigator_invoke_query_send Failed");
}
bps_event_t *event = NULL;
do {
bps_get_event(&event, -1);
/*
snprintf(msg, 64, "query result %#04x\n", bps_event_get_code(event));
log(msg);
*/
} while (
navigator_get_domain()!=bps_event_get_domain(event) ||
bps_event_get_code(event)!=NAVIGATOR_INVOKE_QUERY_RESULT
);
// create integer holding the number of actions returned by the query
int action_count =
navigator_invoke_event_get_query_result_action_count(event);
// loop listing all actions returned by the query
for (int i=0; i<action_count; i++) {
const navigator_invoke_query_result_action_t *action =
navigator_invoke_event_get_query_result_action(event, i);
// retrieve action attributes
const char *name =
navigator_invoke_query_result_action_get_name(action);
const char *icon =
navigator_invoke_query_result_action_get_icon(action);
const char *label =
navigator_invoke_query_result_action_get_label(action);
// create integer holding the number of targets in the action
int target_count =
navigator_invoke_query_result_action_get_target_count(action);
// loop listing all targets in the action
for (int j=0; j < target_count; j++) {
const navigator_invoke_query_result_target_t *target =
navigator_invoke_query_result_action_get_target(action, j);
if (target==NULL) {
log("target is null!");
}
// retrieve target attributes
ShareQueryResult result;
const char *key =
navigator_invoke_query_result_target_get_key(target);
const char *icon =
navigator_invoke_query_result_target_get_icon(target);
const char *label =
navigator_invoke_query_result_target_get_label(target);
strcpy(result.key, key);
strcpy(result.icon, icon);
strcpy(result.label, label);
results.push_back(result);
}
}
navigator_invoke_query_destroy(query);
return results;
}
}
| 24.314286 | 72 | 0.730317 |
358d5cd6ea327f28e023717bcbd1d58fdbaee75e | 26,828 | cpp | C++ | src/plugins/intel_gna/runtime/pwl.cpp | kurylo/openvino | 4da0941cd2e8f9829875e60df73d3cd01f820b9c | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/plugins/intel_gna/runtime/pwl.cpp | kurylo/openvino | 4da0941cd2e8f9829875e60df73d3cd01f820b9c | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/plugins/intel_gna/runtime/pwl.cpp | kurylo/openvino | 4da0941cd2e8f9829875e60df73d3cd01f820b9c | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
// pwl_design.cpp : simple activation function designer
//
#include <vector>
#include <iostream>
#include <limits>
#include <cstdint>
#include <algorithm>
#ifdef _NO_MKL_
#include <cmath>
#include "backend/make_pwl.hpp"
#define SCOPY(num, in, inci, out, inco) for (int i_ = 0; i_ < *(num); i_++) *(out + i_ * *(inco)) = *(in + i_ * *(inci));
#define SSCAL(num, scale, inout, inco) for (int i_ = 0; i_ < *(num); i_++) *(inout + i_ * *(inco)) = *(scale) * *(inout + i_ * *(inco));
#define TANH(num, in, out) for (int i_ = 0; i_ < num; i_++) *(out+i_) = tanh(*(in+i_))
#else
#include <mkl.h>
#define SCOPY(num, in, incx, out, incy) scopy(num, in, incx, out, incy)
#define SSCAL(num, scale, inout, incx) sscal(num, scale, inout, incx)
#define TANH(num, in, out) vsTanh(num, in, out)
#endif
#include "pwl.h"
#include "gna_plugin_log.hpp"
#include "gna_slope_scale.h"
#include "round_float_define.hpp"
#include "ops/reference/pwl.hpp"
double relu(const double x) { if (x < 0) { return(0.0); } else { return(x); } }
double leaky_relu(const double x) { if (x < 0.0) { return(LEAKYRELU_SLOPE*x); } else { return(x); } }
double clipping(const double x, const double lbound, const double ubound) { return((x < lbound)?lbound:((x > ubound)?ubound:x)); }
inline double power(const double x, const std::tuple<double, double, double>& args) {
return (pow(std::get<2>(args) + std::get<1>(args) * x, std::get<0>(args)));
}
void PwlDesignOpt(const DnnActivation& activation_type,
std::vector<gna_pwl_segment_t> &ptr_segment,
const float scale_in,
const float scale_out,
const bool low_precision,
const std::shared_ptr<ngraph::Node>& node) {
std::vector<pwl_t> pwl;
switch (activation_type) {
case kActPwl: {
make_gna_pwl(node, scale_in, scale_out, low_precision, ptr_segment);
break;
}
case kActRelu:
make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment);
break;
case kActLeakyRelu:
make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment);
break;
case kActIdentity:
case kActFakeQuantize:
make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment);
break;
case kActKaldiLstmClipping:
make_gna_pwl(activation_type, pwl, activation_type.args.clamp.low, activation_type.args.clamp.high,
scale_in, scale_out, low_precision, ptr_segment);
break;
case kActSign:
make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment);
break;
case kActAbs:
make_gna_pwl(activation_type, pwl, -1.0, 1.0, scale_in, scale_out, low_precision, ptr_segment);
break;
default:
THROW_GNA_EXCEPTION << "Unknown piecewise linear function type: " << activation_type.type;
}
}
void PwlDesign(const DnnActivation& activation_type,
gna_pwl_segment_t *ptr_segment,
const uint32_t num_segments,
const float scale_in,
const float scale_out,
const bool low_precision) {
switch (activation_type) {
case kActSigmoid:
{
gnalog() << "=========================== Sigmoid Segments===========================\n";
uint32_t num_segment_size = 0;
int32_t offset = 0;
ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb
num_segment_size = static_cast<int32_t>(SIGMOID_DOMAIN * scale_in / ((num_segments-2) / 2) + 0.5);
offset = -static_cast<int32_t>(num_segment_size * (num_segments-2) / 2);
for (uint32_t i = 1; i < num_segments; i++) {
ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb
offset += num_segment_size;
}
for (uint32_t i = 0; i < num_segments; i++) {
int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK);
int32_t xbasenext = (i < num_segments-1) ? static_cast<int32_t>(ptr_segment[i+1].xBase & XBASEMASK) : INT32_MAX;
float floatarg = static_cast<float>(xbase / (2 * scale_in));
float floatargnext = static_cast<float>(xbasenext / (2 * scale_in));
float floatval, floatvalnext, slope;
TANH(1, &floatarg, &floatval);
floatval = 0.5f * (1.0f + floatval);
TANH(1, &floatargnext, &floatvalnext);
floatvalnext = 0.5f * (1.0f + floatvalnext);
slope = scale_out*(floatvalnext - floatval) / static_cast<float>(xbasenext - xbase);
{
// find best scale factor
uint64_t slope_scale;
uint32_t slope_scale_index;
for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) {
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
if (((slope * slope_scale) <= 32767.0) && ((slope * slope_scale) >= -32768.0))
break;
}
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
ptr_segment[i].slope = FLOAT_TO_INT16(slope * slope_scale);
ptr_segment[i].xBase = ptr_segment[i].xBase | slope_scale_index;
}
ptr_segment[i].yBase = FLOAT_TO_INT16(floatval * scale_out);
gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK))/scale_out)
<< " "
<< (static_cast<float>((ptr_segment[i].yBase))/scale_out)
<< " "
<< (slope/scale_out)
<< "\n";
}
}
break;
case kActTanh:
{
gnalog() << "=========================== Tanh Segments===========================\n";
uint32_t num_segment_size = 0;
int32_t offset = 0;
ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb
num_segment_size = static_cast<int32_t>(TANH_DOMAIN * scale_in / ((num_segments-2) / 2) + 0.5);
offset = -static_cast<int32_t>(num_segment_size * (num_segments-2) / 2);
for (uint32_t i = 1; i < num_segments; i++) {
ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb
offset += num_segment_size;
}
for (uint32_t i = 0; i < num_segments; i++) {
int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK);
int32_t xbasenext = (i < num_segments-1) ?
static_cast<int32_t>(ptr_segment[i+1].xBase & XBASEMASK) :
INT32_MAX;
float floatarg = static_cast<float>(xbase / scale_in);
float floatargnext = static_cast<float>(xbasenext / scale_in);
float floatval, floatvalnext, slope;
TANH(1, &floatarg, &floatval);
TANH(1, &floatargnext, &floatvalnext);
slope = scale_out * (floatvalnext - floatval) /
static_cast<float>(xbasenext - xbase);
{
// find best scale factor
uint64_t slope_scale;
uint32_t slope_scale_index;
for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) {
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
if (((slope * slope_scale) <= 32767.0) && ((slope * slope_scale) >= -32768.0))
break;
}
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
ptr_segment[i].slope = FLOAT_TO_INT16(slope * slope_scale);
ptr_segment[i].xBase = ptr_segment[i].xBase | slope_scale_index;
}
ptr_segment[i].yBase = FLOAT_TO_INT16(floatval * scale_out);
gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK))/scale_out)
<< " "
<< (static_cast<float>((ptr_segment[i].yBase))/scale_out)
<< " "
<< (slope/scale_out)
<< "\n";
}
}
break;
case kActSoftSign:
{
auto softsign = [](const double x) {
return(x / (1.0 + fabs(x)));
};
gnalog() << "=========================== SoftSign Segments===========================\n";
uint32_t num_segment_size = 0;
int32_t offset = 0;
ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb
num_segment_size = static_cast<int32_t>(SOFTSIGN_DOMAIN * scale_in / ((num_segments - 2) / 2) + 0.5);
offset = -static_cast<int32_t>(num_segment_size * (num_segments - 2) / 2);
for (uint32_t i = 1; i < num_segments; i++) {
ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb
offset += num_segment_size;
}
for (uint32_t i = 0; i < num_segments; i++) {
int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK);
int32_t xbasenext = (i < num_segments - 1) ? static_cast<int32_t>(ptr_segment[i + 1].xBase & XBASEMASK) : INT32_MAX;
float floatarg = static_cast<float>(xbase / (2 * scale_in));
float floatargnext = static_cast<float>(xbasenext / (2 * scale_in));
float floatval, floatvalnext, slope;
floatval = softsign(floatarg);
floatvalnext = softsign(floatargnext);
slope = scale_out * (floatvalnext - floatval) / static_cast<float>(xbasenext - xbase);
{
// find best scale factor
uint64_t slope_scale;
uint32_t slope_scale_index;
for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) {
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
if (((slope * slope_scale) <= 32767.0) && ((slope * slope_scale) >= -32768.0))
break;
}
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
ptr_segment[i].slope = FLOAT_TO_INT16(slope * slope_scale);
ptr_segment[i].xBase = ptr_segment[i].xBase | slope_scale_index;
}
ptr_segment[i].yBase = FLOAT_TO_INT16(floatval * scale_out);
gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK)) / scale_out)
<< " "
<< (static_cast<float>((ptr_segment[i].yBase)) / scale_out)
<< " "
<< (slope / scale_out)
<< "\n";
}
}
break;
case kActRelu:
THROW_GNA_EXCEPTION << "Rectilinear activation function design not yet implemented!";
case kActIdentity:
case kActKaldiLstmClipping: // clipping of IDENTITY is more aggressive than Kaldi
{
float slope = 0.0;
int64_t x_lower_limit = static_cast<int64_t>((INT16_MIN / scale_out) * scale_in - 0.5);
int64_t x_upper_limit = static_cast<int64_t>((INT16_MAX / scale_out) * scale_in + 0.5);
int16_t y_lower_limit = INT16_MIN;
int16_t y_upper_limit = INT16_MAX;
if (activation_type == kActKaldiLstmClipping)
gnalog() << "=========================== Clipping Segments ===========================\n";
else
gnalog() << "=========================== Identity Segments ===========================\n";
if (x_lower_limit < INT32_MIN) {
std::cerr << "Warning: saturation in PwlDesign! " << x_lower_limit << " < INT32_MIN"<< std::endl;
x_lower_limit = INT32_MIN;
y_lower_limit = static_cast<int16_t>((scale_out / scale_in)*static_cast<float>(INT32_MIN) - 0.5);
}
if (x_upper_limit > INT32_MAX) {
std::cerr << "Warning: saturation in PwlDesign! " << x_upper_limit << " > INT32_MAX"<< std::endl;
x_upper_limit = INT32_MAX;
y_upper_limit = static_cast<int16_t>((scale_out / scale_in)*static_cast<float>(INT32_MAX) + 0.5);
}
slope =
static_cast<float>(static_cast<uint64_t>(y_upper_limit) - static_cast<uint64_t>(y_lower_limit)) /
static_cast<float>(static_cast<uint64_t>(x_upper_limit) - static_cast<uint64_t>(x_lower_limit));
ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb
ptr_segment[0].yBase = y_lower_limit;
ptr_segment[0].slope = 0;
gnalog() << ptr_segment[0].xBase / scale_in
<< " " << ptr_segment[0].yBase / scale_out
<< " " << 0
<< "\n";
ptr_segment[1].xBase = static_cast<int32_t>(x_lower_limit & XBASEMASK);
ptr_segment[1].yBase = y_lower_limit;
{
// find best scale factor
uint64_t slope_scale = 0;
uint32_t slope_scale_index = 0;
for (slope_scale_index = 3; slope_scale_index > 0; slope_scale_index--) {
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
if (((slope * slope_scale) <= std::numeric_limits<int16_t>::max()) &&
((slope * slope_scale) >= std::numeric_limits<int16_t>::min()))
break;
}
slope_scale = static_cast<uint64_t>(1) << (8 * (1 + slope_scale_index));
ptr_segment[1].slope = FLOAT_TO_INT16(slope * slope_scale);
ptr_segment[1].xBase = ptr_segment[1].xBase | slope_scale_index;
}
ptr_segment[2].xBase = static_cast<int32_t>(x_upper_limit & XBASEMASK);
ptr_segment[2].yBase = y_upper_limit;
ptr_segment[2].slope = 0;
}
break;
case kActPow:
{
gnalog() << "=========================== Pow Segments===========================\n";
uint32_t num_segment_size = 0;
auto fp32eq = [](float p1, float p2) -> bool {
return (std::abs(p1 - p2) <= 0.00001f * std::min(std::abs(p1), std::abs(p2)));
};
auto args = std::tuple<double, double, double>{ activation_type.args.pow.exponent,
activation_type.args.pow.scale,
activation_type.args.pow.offset };
auto input_min_value = static_cast<double>(std::numeric_limits<int32_t>::min());
auto input_max_value = static_cast<double>(std::numeric_limits<int32_t>::max());
double x_min = fp32eq(fmod(activation_type.args.pow.exponent, 1.0), 0.0f)? input_min_value / scale_in: 0.0;
x_min = std::max(x_min, -POW_DOMAIN);
double x_max = input_max_value / scale_in;
x_max = std::min(x_max, POW_DOMAIN);
double pow_domain = x_max - x_min;
ptr_segment[0].xBase = static_cast<int32_t>(INT32_MIN & XBASEMASK); // zero out the 2 lsb
num_segment_size = static_cast<int32_t>(pow_domain * scale_in / (num_segments - 2) + 0.5);
int32_t x_min_scaled = x_min * scale_in + 0.5;
int32_t offset = x_min_scaled;
for (uint32_t i = 1; i < num_segments; i++) {
ptr_segment[i].xBase = static_cast<int32_t>(offset & XBASEMASK); // zero out the 2 lsb
offset += num_segment_size;
}
for (uint32_t i = 0; i < num_segments; i++) {
int32_t xbase = static_cast<int32_t>(ptr_segment[i].xBase & XBASEMASK);
int32_t xbasenext = (i < num_segments - 1) ? static_cast<int32_t>(ptr_segment[i + 1].xBase & XBASEMASK) : INT32_MAX;
double arg = xbase / scale_in;
arg = arg < x_min ? x_min : arg;
double argnext = xbasenext / scale_in;
argnext = argnext < x_min ? x_min : argnext;
double val = power(arg, args);
double valnext = power(argnext, args);
double slope = (valnext - val) / (static_cast<double>(xbasenext - xbase) / scale_in);
auto s = gna_slope(slope, scale_in, scale_out);
ptr_segment[i].slope = FLOAT_TO_INT16(s.slope * s.slope_scale);
ptr_segment[i].xBase = ptr_segment[i].xBase | s.slope_scale_index;
ptr_segment[i].yBase = FLOAT_TO_INT16(val * scale_out);
gnalog() << (static_cast<int32_t>((ptr_segment[i].xBase & XBASEMASK)) / scale_out)
<< " "
<< (static_cast<float>((ptr_segment[i].yBase)) / scale_out)
<< " "
<< (s.slope / scale_out)
<< "\n";
}
}
break;
default:
fprintf(stderr, "Activation function design for %s not yet implemented!\n", intel_dnn_activation_name[activation_type]);
throw -1;
}
}
void PwlApply32(intel_dnn_component_t *component, uint32_t num_subset_size) {
if (component->orientation_in == kDnnInterleavedOrientation) { // subsets only supported in interleaved orientation
PwlApply32(component, 0, num_subset_size - 1, 0, component->num_columns_in - 1);
} else {
PwlApply32(component, 0, component->num_rows_in - 1, 0, component->num_columns_in - 1);
}
}
void PwlApply32(intel_dnn_component_t *component,
uint32_t num_row_start,
uint32_t num_row_end,
uint32_t num_col_start,
uint32_t num_col_end) {
intel_piecewiselinear_t *transform = reinterpret_cast<intel_piecewiselinear_t *>(&component->op.pwl);
float *ptr_in = reinterpret_cast<float *>(component->ptr_inputs);
float *ptr_out = reinterpret_cast<float *>(component->ptr_outputs);
uint32_t num_columns = component->num_columns_in;
switch (transform->func_id.type) {
case kActSigmoid:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = 0.5 * (1.0 + tanh(0.5 * ptr_in[i * num_columns + j]));
}
}
break;
case kActTanh:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = tanh(ptr_in[i * num_columns + j]);
}
}
break;
case kActSoftSign:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = ptr_in[i * num_columns + j] / (1.0 + fabs(ptr_in[i * num_columns + j]));
}
}
break;
case kActRelu:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] =
(ptr_in[i * num_columns + j] < 0.0f) ?
ptr_in[i * num_columns + j] * transform->func_id.args.lrelu.negative_slope :
ptr_in[i * num_columns + j];
}
}
break;
case kActIdentity:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = ptr_in[i * num_columns + j];
}
}
break;
case kActKaldiLstmClipping: {
float upper_limit = component->op.pwl.func_id.args.clamp.high;
float lower_limit = component->op.pwl.func_id.args.clamp.low;
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
float val = ptr_in[i * num_columns + j];
if (val > upper_limit) {
ptr_out[i * num_columns + j] = upper_limit;
} else if (val < lower_limit) {
ptr_out[i * num_columns + j] = lower_limit;
} else {
ptr_out[i * num_columns + j] = val;
}
}
}
break;
}
case kActExp:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = exp(ptr_in[i * num_columns + j]);
}
}
break;
case kActLog:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = log(ptr_in[i * num_columns + j]);
}
}
break;
case kActAbs:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = fabs(ptr_in[i * num_columns + j]);
}
}
break;
case kActSign:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = (ptr_in[i * num_columns + j] == 0) ? 0.0 : ((ptr_in[i * num_columns + j] > 0) ? 1.0 : -1.0);
}
}
break;
case kActNegLog:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = -1.0 * log(ptr_in[i * num_columns + j]);
}
}
break;
case kActNegHalfLog:
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = -0.5 * log(ptr_in[i * num_columns + j]);
}
}
break;
case kActPow: {
float exponent = transform->func_id.args.pow.exponent;
float scale = transform->func_id.args.pow.scale;
float offset = transform->func_id.args.pow.offset;
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
ptr_out[i * num_columns + j] = pow(offset + scale * ptr_in[i * num_columns + j], exponent);
}
}
}
break;
case kActFakeQuantize: {
double levels = transform->func_id.fqParams.levels;
for (uint32_t i = num_row_start; i <= num_row_end; i++) {
auto inputChannel = transform->func_id.fqParams.inputPerChannel ? i : 0;
auto outputChannel = transform->func_id.fqParams.outputPerChannel ? i : 0;
double input_low = transform->func_id.fqParams.input_low[inputChannel];
double input_high = transform->func_id.fqParams.input_high[inputChannel];
double output_low = transform->func_id.fqParams.output_low[outputChannel];
double output_high = transform->func_id.fqParams.output_high[outputChannel];
for (uint32_t j = num_col_start; j <= num_col_end; j++) {
auto offset = i * num_columns + j;
auto x = ptr_in[offset];
if (x <= std::min(input_low, input_high)) {
ptr_out[offset] = output_low;
} else if (x > std::max(input_low, input_high)) {
ptr_out[offset] = output_high;
} else {
ptr_out[offset] = nearbyint((x - input_low) / (input_high - input_low) * (levels - 1)) /
(levels - 1) * (output_high - output_low) + output_low;
}
}
}
break;
}
case kActCustom:
default:
THROW_GNA_EXCEPTION << component->original_layer_name << ", Unknown piecewise linear function type: " << transform->func_id.type;
}
}
| 52.915187 | 143 | 0.502684 |
358dd892ae6a47600fdf23472a3f1d53e967a577 | 2,008 | cpp | C++ | tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 58 | 2015-08-09T14:56:35.000Z | 2022-01-15T22:06:58.000Z | tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp | mamontov-cpp/saddy-graphics-engine-2d | e25a6637fcc49cb26614bf03b70e5d03a3a436c7 | [
"BSD-2-Clause"
] | 245 | 2015-08-08T08:44:22.000Z | 2022-01-04T09:18:08.000Z | tools/ifaceed/ifaceed/gui/uiblocks/uiwayblock.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 23 | 2015-12-06T03:57:49.000Z | 2020-10-12T14:15:50.000Z | #include <new>
#include <cassert>
#include "uiwayblock.h"
#include <QListWidget>
#include <QLineEdit>
#include <QDoubleSpinBox>
#include <QCheckBox>
#include <QPushButton>
gui::uiblocks::UIWayBlock::UIWayBlock() : lstWays(nullptr),
txtWayName(nullptr),
dsbWayTotalTime(nullptr),
cbWayClosed(nullptr),
btnWayAdd(nullptr),
btnWayRemove(nullptr),
lstWayPoints(nullptr),
dsbWayPointX(nullptr),
dsbWayPointY(nullptr),
btnWayPointAdd(nullptr),
btnWayPointRemove(nullptr),
btnWayPointMoveBack(nullptr),
btnWayPointMoveFront(nullptr)
{
}
void gui::uiblocks::UIWayBlock::init(QWidget* w)
{
assert(w);
this->lstWays = w->findChild<QListWidget*>("lstWays");
assert(this->lstWays);
this->txtWayName = w->findChild<QLineEdit*>("txtWayName");
assert(this->txtWayName);
this->dsbWayTotalTime = w->findChild<QDoubleSpinBox*>("dsbWayTotalTime");
assert(this->dsbWayTotalTime);
this->cbWayClosed = w->findChild<QCheckBox*>("cbWayClosed");
assert(this->cbWayClosed);
this->btnWayAdd = w->findChild<QPushButton*>("btnWayAdd");
assert(this->btnWayAdd);
this->btnWayRemove = w->findChild<QPushButton*>("btnWayRemove");
assert(this->btnWayRemove);
this->lstWayPoints = w->findChild<QListWidget*>("lstWayPoints");
assert(this->lstWayPoints);
this->dsbWayPointX = w->findChild<QDoubleSpinBox*>("dsbWayPointX");
assert(this->dsbWayPointX);
this->dsbWayPointY = w->findChild<QDoubleSpinBox*>("dsbWayPointY");
assert(this->dsbWayPointY);
this->btnWayPointAdd = w->findChild<QPushButton*>("btnWayPointAdd");
assert(this->btnWayPointAdd);
this->btnWayPointRemove = w->findChild<QPushButton*>("btnWayPointRemove");
assert(this->btnWayPointRemove);
this->btnWayPointMoveBack = w->findChild<QPushButton*>("btnWayPointMoveBack");
assert(this->btnWayPointMoveBack);
this->btnWayPointMoveFront = w->findChild<QPushButton*>("btnWayPointMoveFront");
assert(this->btnWayPointMoveFront);
}
gui::uiblocks::UIWayBlock::~UIWayBlock()
{
}
| 32.387097 | 84 | 0.731076 |
358f0675afa1d80c560a1dec6fb0401f5642c3dc | 3,833 | cpp | C++ | opengl/hello_3d.cpp | xiwan/opengl | 1e30baf40debd00b55252fc14d0e6b909c94bfbd | [
"MIT"
] | 1 | 2019-02-22T03:11:28.000Z | 2019-02-22T03:11:28.000Z | opengl/hello_3d.cpp | xiwan/opengl | 1e30baf40debd00b55252fc14d0e6b909c94bfbd | [
"MIT"
] | null | null | null | opengl/hello_3d.cpp | xiwan/opengl | 1e30baf40debd00b55252fc14d0e6b909c94bfbd | [
"MIT"
] | null | null | null |
#include "./headers/shader.h"
#include "./headers/opengl_common.h"
#define STB_IMAGE_IMPLEMENTATION_2
#include "./headers/stb_image.h"
int hello_3d()
{
GLFWwindow* window = prepareWindow("hello_3d");
if (!window) {
return -1;
}
Shader textureShader("./shaders/3d.shader.vs", "./shaders/3d.shader.fs");
float textureVertices[] = {
// positions // colors // texture coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
unsigned int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
// Vertex input
unsigned int VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(textureVertices), textureVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
unsigned int texture1, texture2;
texture1 = loadTexture("./pics/container.jpg");
texture2 = loadTexture("./pics/awesomeface.png");
textureShader.use();
textureShader.setInt("texture1", 0);
textureShader.setInt("texture2", 1);
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
textureShader.use();
float timeValue = glfwGetTime();
float sinValue = sin(timeValue);
glm::mat4 trans = glm::mat4(1.0f);
trans = glm::translate(trans, glm::vec3(sinValue, -0.5f, 0.0f));
trans = glm::rotate(trans, timeValue, glm::vec3(0.0f, 0.0f, 1.0f));
glm::mat4 model = glm::mat4(1.0f);
glm::mat4 view = glm::mat4(1.0f);
glm::mat4 projection = glm::mat4(1.0f);
//model = glm::translate(model, glm::vec3(sinValue, -0.5f, 0.0f));
model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f));
//model = glm::rotate(model, timeValue, glm::vec3(0.0f, 0.0f, 1.0f));
// note that we're translating the scene in the reverse direction of where we want to move
// Note that in normalized device coordinates OpenGL actually uses a left-handed system
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
//textureShader.setMatrix4("sinValue", &sinValue);
textureShader.setMat4("model", model);
textureShader.setMat4("view", view);
textureShader.setMat4("projection", projection);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
| 32.760684 | 105 | 0.651448 |
359290ea28eda47cce73bf4f5b53cc9903f2c87c | 5,654 | cpp | C++ | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/examples/debruijn/debruijn24.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/examples/debruijn/debruijn24.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/examples/debruijn/debruijn24.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | //! [snippet1]
// We include what we need for the test
#include <gatb/gatb_core.hpp>
#include <fstream>
#include <queue>
#include <stack>
#include <map>
using namespace std;
#define DEBUG(a) //a
#define INFO(a) //a
/********************************************************************************/
/* Cmd-line: debruijn24 -graph <h5 file> [-out <output file>] */
/* */
/* Sample: debruijn24 -graph gatb-core/gatb-core/test/db/celegans_reads.h5 */
/* */
/* Note: */
/* - '.h5' file contains the HDF5 formatted representation of a de bruijn */
/* graph created from a set of reads. */
/* - a '.h5' file is created using dbgh5 program provided with GATB-Core. */
/* Basic use is as follows: */
/* dbgh5 -in <fasta/q file> -out <h5 file> */
/* You can also control kmer-size and kmer abundance, see dbgh5 help. */
/********************************************************************************/
const char* STR_NODE_TYPE = "-type";
/********************************************************************************/
class DotGeneratorTool : public Tool
{
public:
// Constructor
DotGeneratorTool () : Tool ("DotGenerator")
{
_parser->push_front (new OptionOneParam (STR_URI_GRAPH, "graph file", true ));
_parser->push_front (new OptionOneParam (STR_URI_OUTPUT, "dot file", false ));
_parser->push_front (new OptionOneParam (STR_NODE_TYPE, "node type (0: all, 1:branching)", false, "1" ));
}
void processNode(Graph &graph, ofstream &output)
{
map<Node, u_int64_t> mapping;
u_int64_t count = 0;
GraphIterator<Node> itMap = graph.iterator ();
for (itMap.first(); !itMap.isDone(); itMap.next()) { mapping[itMap.item()] = count++; }
ProgressGraphIterator<Node,ProgressTimer> it = graph.iterator ();
for (it.first(); !it.isDone(); it.next())
{
Node current = it.item();
GraphVector<Node> neighbors = graph.neighbors(current.kmer);
for (size_t i=0; i<neighbors.size(); i++)
{
output << mapping[current.kmer] << " -> " << mapping[neighbors[i].kmer] << " ;\n";
}
}
output << "}\n";
output.close();
}
void processBranchingNode(Graph &graph, ofstream & output)
{
map<Node, u_int64_t> mapping;
u_int64_t count = 0;
GraphIterator<BranchingNode> itMap = graph.iteratorBranching();
for (itMap.first(); !itMap.isDone(); itMap.next()) { mapping[itMap.item()] = count++; }
ProgressGraphIterator<BranchingNode,ProgressTimer> it = graph.iteratorBranching ();
for (it.first(); !it.isDone(); it.next())
{
BranchingNode current = it.item();
GraphVector<BranchingNode> neighbors = graph.neighborsBranching (current.kmer);
for (size_t i=0; i<neighbors.size(); i++)
{
output << mapping[current.kmer] << " -> " << mapping[neighbors[i].kmer] << " ;\n";
}
}
output << "}\n";
output.close();
}
// Actual job done by the tool is here
void execute ()
{
string outputFile = getInput()->get(STR_URI_OUTPUT) ?
getInput()->getStr(STR_URI_OUTPUT) :
(System::file().getBaseName(getInput()->getStr(STR_URI_GRAPH)) + ".dot");
ofstream output (outputFile.c_str());
// We load the graph
Graph graph = Graph::load (getInput()->getStr(STR_URI_GRAPH));
switch (getInput()->getInt(STR_NODE_TYPE))
{
case 0:
output << "digraph " << "all" << "{\n";
processNode(graph, output);
break;
case 1:
output << "digraph " << "branching" << "{\n";
processBranchingNode(graph, output);
break;
default: break;
}
}
};
/********************************************************************************/
/* */
/* Generate dot file from a graph. */
/* */
/* This snippet generates a dot file from a graph file. You can then generate */
/* a pdf file with "dot -Tpdf graph.dot -o graph.pdf" */
/* */
/* NOTE: de Bruijn graphs may be huge and complex, so dot is not the best tool */
/* to display such graphs. You should use it on small graphs with only a few */
/* hundreds of nodes. */
/* */
/********************************************************************************/
int main (int argc, char* argv[])
{
try
{
// We run the tool with the provided command line arguments.
DotGeneratorTool().run (argc, argv);
}
catch (Exception& e)
{
std::cout << "EXCEPTION: " << e.getMessage() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//! [snippet1]
| 36.714286 | 115 | 0.44358 |
359471f04a7f8f0e3fde02afe2e087b4e1c5144b | 5,666 | cpp | C++ | src/Generic/discTagger/DTAltModelSet.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Generic/discTagger/DTAltModelSet.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Generic/discTagger/DTAltModelSet.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h"
#include "Generic/common/limits.h"
#include "Generic/common/UTF8InputStream.h"
#include "Generic/common/ParamReader.h"
#include "Generic/discTagger/DTTagSet.h"
#include "Generic/discTagger/DTFeatureTypeSet.h"
#include "Generic/discTagger/P1Decoder.h"
#include "Generic/maxent/MaxEntModel.h"
#include "Generic/discTagger/DTTagSet.h"
#include "Generic/discTagger/DTFeatureTypeSet.h"
#include "Generic/discTagger/DTObservation.h"
#include "Generic/discTagger/DTAltModelSet.h"
#include <boost/scoped_ptr.hpp>
DTAltModelSet::DTAltModelSet() : _nDecoders(0), _is_initialized(false) {}
void DTAltModelSet::initialize(Symbol modeltype, const char* paramName) {
// already been initialized, so just return
if (_is_initialized)
return;
_is_initialized = true;
char msg[1000];
boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build());
UTF8InputStream& uis(*uis_scoped_ptr);
UTF8Token tok;
/*sub-parameter file looks like
#ofAlternativeModels
MODEL_NAME-1
model-type-1
tagset-1
featureset-1
modelfile-1
MODEL_NAME-2
model-type-2
tagset-2
featureset-2
modelfile-2
.....
*/
std::string stream_name = ParamReader::getParam(paramName);
uis.open(stream_name.c_str());
if (uis.fail()) {
sprintf(msg, "Error opening %s: %s", paramName, stream_name.c_str());
throw UnrecoverableException("DTAltModelSet:DTAltModelSet()", msg);
}
uis >> tok;
_nDecoders = _wtoi(tok.chars());
//std::cout<<"tok: "<<tok.symValue().to_debug_string()<< " _ndecoders: "<<_nDecoders<<std::endl;
if (_nDecoders >= MAX_ALT_DT_DECODERS) {
sprintf(msg,
"Number of decoders in %s is greater than MAX_ALT_DT_DECODERS: %d",
paramName,
MAX_ALT_DT_DECODERS);
throw UnrecoverableException("DTAltModelSet:DTAltModelSet()", msg);
}
for (int i = 0; i < _nDecoders; i++) {
//std::cout<<"reading decoder: "<<i<<std::endl;
uis >> tok;
_altDecoders[i]._name = tok.symValue();
uis >> tok;
if (tok.symValue() == Symbol(L"MAXENT"))
_altDecoders[i]._type = MAXENT;
else if (tok.symValue() == Symbol(L"P1"))
_altDecoders[i]._type = P1;
else {
sprintf(msg,
"Found unexpected model type in %s, should be 'P1' or 'MAXENT'.",
paramName);
throw UnexpectedInputException("DTAltModelSet::DTAltModelSet()", msg);
}
uis >> tok;
char buffer[500];
wcstombs(buffer, tok.chars(), 500);
_altDecoders[i]._tagSet = _new DTTagSet(buffer, false, false);
uis >> tok;
wcstombs(buffer, tok.chars(), 500);
_altDecoders[i]._features = _new DTFeatureTypeSet(buffer, modeltype);
uis >> tok;
wcstombs(buffer, tok.chars(), 500);
_altDecoders[i]._weights = _new DTFeature::FeatureWeightMap(50000);
DTFeature::readWeights(*_altDecoders[i]._weights, buffer, modeltype);
if (_altDecoders[i]._type == P1) {
_altDecoders[i]._p1Decoder = _new P1Decoder(_altDecoders[i]._tagSet,
_altDecoders[i]._features,
_altDecoders[i]._weights, 0, 0);
_altDecoders[i]._maxentDecoder = 0;
} else { // _altDecoders[i]._type == MAXENT
_altDecoders[i]._maxentDecoder = _new MaxEntModel(_altDecoders[i]._tagSet,
_altDecoders[i]._features,
_altDecoders[i]._weights);
_altDecoders[i]._p1Decoder = 0;
}
}
}
DTAltModelSet::~DTAltModelSet() {
for (int i = 0; i < _nDecoders; i++) {
delete _altDecoders[i]._tagSet;
_altDecoders[i]._tagSet = 0;
delete _altDecoders[i]._features;
_altDecoders[i]._features = 0;
delete _altDecoders[i]._weights;
_altDecoders[i]._weights = 0;
delete _altDecoders[i]._p1Decoder;
_altDecoders[i]._p1Decoder= 0;
delete _altDecoders[i]._maxentDecoder;
_altDecoders[i]._maxentDecoder= 0;
}
_nDecoders = 0;
}
int DTAltModelSet::getNAltDecoders() {
return _nDecoders;
}
Symbol DTAltModelSet::getDecoderName(int i) {
char msg[1000];
if( i >= _nDecoders) {
sprintf(msg,
"getDecoderName i is greater than n_decoders: %d",
_nDecoders);
throw UnrecoverableException("DTAltModelSet:getDecoderName()", msg);
}
return _altDecoders[i]._name;
}
Symbol DTAltModelSet::getDecoderPrediction(int i, DTObservation *obs) {
char msg[1000];
if (i >= _nDecoders) {
sprintf(msg,
"getDecoderPrediction i is greater than n_decoders: %d",
_nDecoders);
throw UnrecoverableException("DTAltModelSet:getDecoderPrediction()", msg);
}
Symbol tag;
if (_altDecoders[i]._type == P1)
tag = _altDecoders[i]._p1Decoder->decodeToSymbol(obs);
else // _altDecoders[i]._type == MAXENT
tag = _altDecoders[i]._maxentDecoder->decodeToSymbol(obs);
return tag;
}
Symbol DTAltModelSet::getDecoderPrediction(Symbol name, DTObservation *obs) {
char msg[1000];
int decnum = -1;
for (int i = 0; i <_nDecoders; i++) {
if (_altDecoders[i]._name == name) {
decnum = i;
break;
}
}
if (decnum == -1) {
sprintf(msg,
"No Decoder defined with name: %s",
name.to_debug_string());
throw UnrecoverableException("DTAltModelSet:getDecoderPrediction()", msg);
}
return getDecoderPrediction(decnum, obs);
}
int DTAltModelSet::addDecoderPredictionsToObservation(DTObservation *obs) {
int i = 0;
for (i = 0; i < _nDecoders; i++) {
Symbol result;
if (_altDecoders[i]._type == P1)
result = _altDecoders[i]._p1Decoder->decodeToSymbol(obs);
else // _altDecoders[i]._type == MAXENT
result = _altDecoders[i]._maxentDecoder->decodeToSymbol(obs);
obs->setAltDecoderPrediction(i, result);
}
return i;
}
| 30.793478 | 98 | 0.683022 |