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 int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18e2e6bfbd3fd5f5c12860dc3b002123cc118a69 | 1,581 | cc | C++ | src/mpsrc/wavy_listen.cc | etolabo/kumofs | b0f7ce8263194dbfa92d10ae75849e676e77c067 | [
"Apache-2.0"
] | 38 | 2015-01-21T09:57:36.000Z | 2021-12-13T11:05:19.000Z | src/mpsrc/wavy_listen.cc | frsyuki/kastor | 8bdbf5011aa8cf486b3efd50d7ad471b7a0dfae7 | [
"Apache-2.0"
] | 3 | 2015-12-15T12:43:13.000Z | 2021-07-30T10:31:42.000Z | src/mpsrc/wavy_listen.cc | frsyuki/kastor | 8bdbf5011aa8cf486b3efd50d7ad471b7a0dfae7 | [
"Apache-2.0"
] | 2 | 2015-03-19T18:54:38.000Z | 2019-03-19T13:37:29.000Z | //
// mp::wavy::core::listen
//
// Copyright (C) 2008 FURUHASHI Sadayuki
//
// 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 "wavy_core.h"
#include "mp/exception.h"
namespace mp {
namespace wavy {
class core::impl::listen_handler : public handler {
public:
listen_handler(int fd, core* c, listen_callback_t callback) :
handler(fd), m_core(c), m_callback(callback) { }
~listen_handler() { }
void read_event()
{
while(true) {
int err = 0;
int sock = ::accept(fd(), NULL, NULL);
if(sock < 0) {
if(errno == EAGAIN || errno == EINTR) {
return;
} else {
err = errno;
}
} else if(sock == 0) {
err = errno;
}
try {
m_core->submit(m_callback, sock, err);
} catch(...) { }
if(err) {
throw system_error(errno, "mp::wvy::accept: accept failed");
}
}
}
private:
core* m_core;
listen_callback_t m_callback;
};
void core::listen(int lsock, listen_callback_t callback)
{
add<impl::listen_handler>(lsock, this, callback);
}
} // namespace wavy
} // namespace mp
| 21.657534 | 78 | 0.648956 | etolabo |
18e2f0e9a36d7f2047306da88ff42f8053ad7d0e | 2,906 | cpp | C++ | Samples/HelloDavinci/SrcEngine/SrcEngine.cpp | song0827/samples | dcaf7158168804922f9cbfdab5d1e8386001d3db | [
"BSD-3-Clause"
] | 23 | 2019-07-29T02:15:20.000Z | 2020-01-09T02:20:32.000Z | Samples/HelloDavinci/SrcEngine/SrcEngine.cpp | song0827/samples | dcaf7158168804922f9cbfdab5d1e8386001d3db | [
"BSD-3-Clause"
] | 4 | 2019-09-26T07:50:26.000Z | 2019-11-29T06:01:29.000Z | Samples/HelloDavinci/SrcEngine/SrcEngine.cpp | song0827/samples | dcaf7158168804922f9cbfdab5d1e8386001d3db | [
"BSD-3-Clause"
] | 14 | 2019-08-14T07:54:55.000Z | 2020-01-14T08:09:21.000Z | /**
* ============================================================================
*
* Copyright (C) 2019, Huawei Technologies Co., Ltd. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1 Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2 Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3 Neither the 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*/
#include "SrcEngine.h"
#include <hiaiengine/log.h>
HIAI_REGISTER_DATA_TYPE("input_data_st", input_data_st);
HIAI_StatusT SrcEngine::Init(const hiai::AIConfig &config, const std::vector<hiai::AIModelDescription> &model_desc)
{
if (data_config_ == NULL) {
data_config_ = std::make_shared<comm_context_st>();
}
for (int index = 0; index < config.items_size(); ++index) {
const ::hiai::AIConfigItem &item = config.items(index);
std::string name = item.name();
if (name == "dataType") {
std::string value = item.value();
data_config_->type = atoi(value.data());
}
}
return HIAI_OK;
}
HIAI_IMPL_ENGINE_PROCESS("SrcEngine", SrcEngine, SRCENGINE_INPUT_SIZE)
{
std::shared_ptr<input_data_st> dataToSend = std::make_shared<input_data_st>();
dataToSend->input_info = *data_config_;
int hiai_ret = SendData(0, "input_data_st", std::static_pointer_cast<void>(dataToSend));
if (hiai_ret != HIAI_OK) {
HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "[SrcEngine]SendData fail!ret = %d", hiai_ret);
}
return HIAI_OK;
}
SrcEngine::~SrcEngine()
{
} | 40.929577 | 115 | 0.681693 | song0827 |
18e7e7e160c72daddcb81a1e6f69916196672483 | 42,857 | cpp | C++ | src-qt5/pc-installgui/wizardDisk.cpp | Acidburn0zzz/trueos-utils-qt5 | f17a51698819a7a288a675797c9f954e407205cc | [
"BSD-2-Clause"
] | 1 | 2017-04-10T07:25:34.000Z | 2017-04-10T07:25:34.000Z | src-qt5/pc-installgui/wizardDisk.cpp | Acidburn0zzz/trueos-utils-qt5 | f17a51698819a7a288a675797c9f954e407205cc | [
"BSD-2-Clause"
] | null | null | null | src-qt5/pc-installgui/wizardDisk.cpp | Acidburn0zzz/trueos-utils-qt5 | f17a51698819a7a288a675797c9f954e407205cc | [
"BSD-2-Clause"
] | null | null | null | /****************************************************************************
** ui.h extension file, included from the uic-generated form implementation.
**
** If you want to add, delete, or rename functions or slots, use
** Qt Designer to update this file, preserving your code.
**
** You should not define a constructor or destructor in this file.
** Instead, write your code in functions called init() and destroy().
** These will automatically be called by the form's constructor and
** destructor.
*****************************************************************************/
#include <QDebug>
#include <QInputDialog>
#include <QMessageBox>
#include "wizardDisk.h"
#include "ui_wizardDisk.h"
void wizardDisk::programInit()
{
prevID = 0;
restoreMode=false;
populateDiskInfo();
//connect(pushClose, SIGNAL(clicked()), this, SLOT(slotClose()));
connect(pushSwapSize, SIGNAL(clicked()), this, SLOT(slotSwapSize()));
connect(pushRemoveMount, SIGNAL(clicked()), this, SLOT(slotRemoveFS()));
connect(pushAddMount, SIGNAL(clicked()), this, SLOT(slotAddFS()));
connect(this,SIGNAL(currentIdChanged(int)),this,SLOT(slotCheckComplete()));
connect(lineZpoolName,SIGNAL(textChanged ( const QString & )),this,SLOT(slotCheckComplete()));
connect(groupZFSPool,SIGNAL( clicked(bool)),this,SLOT(slotCheckComplete()));
connect(comboDisk,SIGNAL(currentIndexChanged(int)),this,SLOT(slotCheckComplete()));
connect(comboDisk,SIGNAL(currentIndexChanged(int)),this,SLOT(slotChangedDisk()));
connect(comboPartition,SIGNAL(currentIndexChanged(int)),this,SLOT(slotCheckComplete()));
connect(treeMounts,SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),this,SLOT(slotTreeDiskChanged()));
treeMounts->setContextMenuPolicy(Qt::CustomContextMenu);
connect(treeMounts,SIGNAL(customContextMenuRequested(const QPoint &)),this,SLOT(slotTreeMountsRightClick()));
//connect(pushTerminal, SIGNAL(clicked()), this, SLOT(slotTerminal()));
// ZFS Mode Page
connect(comboZFSMode,SIGNAL(currentIndexChanged(int)),this,SLOT(slotCheckComplete()));
connect(groupZFSOpts,SIGNAL(clicked(bool)),this,SLOT(slotCheckComplete()));
connect(listZFSDisks,SIGNAL(itemClicked(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(listZFSDisks,SIGNAL(itemActivated(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(listZFSDisks,SIGNAL(itemChanged(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(groupZFSCache,SIGNAL(clicked(bool)),this,SLOT(slotCheckComplete()));
connect(listZFSCache,SIGNAL(itemClicked(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(listZFSCache,SIGNAL(itemActivated(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(listZFSCache,SIGNAL(itemChanged(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(groupZFSLog,SIGNAL(clicked(bool)),this,SLOT(slotCheckComplete()));
connect(listZFSLog,SIGNAL(itemClicked(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(listZFSLog,SIGNAL(itemActivated(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(listZFSLog,SIGNAL(itemChanged(QListWidgetItem *)),this,SLOT(slotCheckComplete()));
connect(groupEncrypt,SIGNAL(clicked(bool)),this,SLOT(slotCheckComplete()));
connect(lineEncPass,SIGNAL(textChanged(const QString &)),this,SLOT(slotCheckComplete()));
connect(lineEncPass2,SIGNAL(textChanged(const QString &)),this,SLOT(slotCheckComplete()));
// Check if we are running in EFI mode
if ( system("sysctl -n machdep.bootmethod | grep -q 'UEFI'") == 0 ) {
efiMode=true;
radioMBR->setEnabled(false);
radioGPT->setChecked(true);
} else {
efiMode=false;
radioMBR->setEnabled(true);
radioGPT->setChecked(true);
}
}
void wizardDisk::populateDiskInfo()
{
qDebug() << "Loading Disk Info";
sysDisks = Scripts::Backend::hardDrives();
// load drives
comboDisk->clear();
for (int i=0; i < sysDisks.count(); ++i) {
// Make sure to only add the drives to the comboDisk
if ( sysDisks.at(i).at(0) == "DRIVE" )
comboDisk->addItem(sysDisks.at(i).at(1) + " - " + sysDisks.at(i).at(2) + "MB " + sysDisks.at(i).at(3));
}
// Reload the slice list box
slotChangedDisk();
}
void wizardDisk::slotChangedDisk()
{
QString ptag;
bool ok;
if ( comboDisk->currentText().isEmpty())
return;
comboPartition->clear();
comboPartition->addItem(tr("Use entire disk"));
QString disk = comboDisk->currentText();
disk.truncate(disk.indexOf(" -"));
for (int i=0; i < sysDisks.count(); ++i) {
// Make sure to only add the slices to the listDiskSlices
if ( sysDisks.at(i).at(0) != "SLICE" )
continue;
// Only add the slices for the target disk
if ( disk != sysDisks.at(i).at(1) )
continue;
// If we have freespace, only list if it is -gt 10GB
if ( sysDisks.at(i).at(4) == "Unused Space" ) {
sysDisks.at(i).at(3).toInt(&ok);
if ( !ok )
continue;
if ( sysDisks.at(i).at(3).toInt(&ok) < 6000 )
continue;
}
// Add the slice / partition
ptag = sysDisks.at(i).at(4).section(",", 0, 0);
ptag = ptag.section("/", 0, 0);
ptag.truncate(15);
ptag = "(" + ptag;
if ( ptag.indexOf(")") == -1 )
ptag += ")";
comboPartition->addItem(sysDisks.at(i).at(2) + ": " + sysDisks.at(i).at(3) + "MB " + ptag );
}
}
void wizardDisk::slotClose()
{
close();
}
void wizardDisk::accept()
{
QString partType="none";
bool force4K = false;
QString zpoolName;
if (comboPartition->currentIndex() == 0 ) {
if ( radioGPT->isChecked() ) {
partType="GPT";
} else {
partType="MBR";
}
}
// When doing advanced ZFS setups, make sure to use GPT
if ( radioAdvanced->isChecked() && groupZFSOpts->isChecked() )
partType="GPT";
// When doing advanced ZFS setups, check if 4K is enabled
if ( radioAdvanced->isChecked() && checkForce4K->isChecked() )
force4K = true;
if ( radioAdvanced->isChecked() && groupZFSPool->isChecked() )
zpoolName = lineZpoolName->text();
/*if ( radioExpert->isChecked() )
emit saved(sysFinalDiskLayout, partType, zpoolName, force4K);
else*/
emit saved(sysFinalDiskLayout, partType, zpoolName, force4K);
close();
}
int wizardDisk::nextId() const
{
switch (currentId()) {
case Page_Intro:
//if (radioExpert->isChecked())
//return Page_Expert;
if (radioBasic->isChecked()) {
radioGPT->setChecked(true);
groupScheme->setVisible(false);
checkForce4K->setVisible(false);
groupZFSPool->setVisible(false);
}
if (radioAdvanced->isChecked()) {
groupScheme->setVisible(true);
checkForce4K->setVisible(true);
groupZFSPool->setVisible(true);
}
break;
case Page_BasicDisk:
pushSwapSize->setVisible(true);
if (radioBasic->isChecked())
return Page_Confirmation;
if (comboPartition->currentIndex() != 0 ) {
groupZFSOpts->setEnabled(false);
pushSwapSize->setVisible(true);
return Page_Mounts;
} else {
if ( radioGPT->isChecked() )
groupEncrypt->setEnabled(true);
else
groupEncrypt->setEnabled(false);
groupZFSOpts->setEnabled(true);
return Page_ZFS;
}
break;
case Page_ZFS:
return Page_ZFS2;
break;
case Page_ZFS2:
return Page_Enc;
break;
case Page_Enc:
pushSwapSize->setVisible(true);
return Page_Mounts;
break;
case Page_Mounts:
return Page_Confirmation;
break;
case Page_Confirmation:
return -1;
break;
default:
return currentId() + 1;
}
return currentId() + 1;
}
// Logic checks to see if we are ready to move onto next page
bool wizardDisk::validatePage()
{
bool found;
// Generate suggested disk layout and show disk tree
if ( prevID == Page_BasicDisk && currentId() == Page_Mounts) {
generateDiskLayout();
populateDiskTree();
}
// Generate suggested disk layout and show disk tree
if ( prevID == Page_Enc && currentId() == Page_Mounts) {
generateDiskLayout();
populateDiskTree();
}
// Show the other disks available
if ( prevID == Page_BasicDisk && currentId() == Page_ZFS)
populateZFSDisks();
// Show the other disks available
if ( prevID == Page_ZFS && currentId() == Page_ZFS2)
populateZFSDisks2();
// Basic mode, generate a disk layout and show summary
if ( prevID == Page_BasicDisk && currentId() == Page_Confirmation) {
generateDiskLayout();
generateConfirmationText();
}
// Create the final disk layout from user options
if ( prevID == Page_Mounts && currentId() == Page_Confirmation) {
generateCustomDiskLayout();
generateConfirmationText();
}
// Create the final disk layout from user options
if ( prevID == Page_Expert && currentId() == Page_Confirmation) {
generateConfirmationText();
}
// Reset the prevID
prevID = currentId();
switch (currentId()) {
case Page_Intro:
button(QWizard::NextButton)->setEnabled(true);
return true;
case Page_BasicDisk:
if ( ! radioAdvanced->isChecked() ) {
radioGPT->setChecked(true);
groupScheme->setVisible(false);
checkForce4K->setVisible(false);
checkForce4K->setChecked(false);
} else {
if ( comboPartition->currentIndex() == 0) {
groupScheme->setVisible(true);
} else {
groupScheme->setVisible(false);
}
checkForce4K->setVisible(true);
}
// Doing a Advanced install
if ( radioAdvanced->isChecked() && groupZFSPool->isChecked() )
{
if ( lineZpoolName->text().isEmpty() ) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
if ( lineZpoolName->text() == "root" ) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
if ( lineZpoolName->text().contains(" ") ) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
QRegExp *re = new QRegExp("^[-'a-zA-Z][a-zA-Z0-9]*$");
if (! re->exactMatch(lineZpoolName->text()) ) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
}
// If the select partition is just too small, we can stop here
if ( ! checkDiskSpace() ) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
// if we get this far, all the fields are filled in
button(QWizard::NextButton)->setEnabled(true);
return true;
case Page_ZFS:
// Check if we have valid ZFS disk options specified
if ( ! groupZFSOpts->isChecked() ) {
button(QWizard::NextButton)->setEnabled(true);
return true;
}
// Need at least one other disk for mirroring
if ( comboZFSMode->currentText() == "mirror" ) {
labelZFSMsg->setText(tr("Please select at least 1 other drive for mirroring"));
for ( int i = 0; i < listZFSDisks->count(); ++i )
{
if ( listZFSDisks->item(i)->checkState() == Qt::Checked ) {
button(QWizard::NextButton)->setEnabled(true);
return true;
}
}
}
if ( comboZFSMode->currentText() == "raidz1" ) {
labelZFSMsg->setText(tr("Please select 2 or 4 additional drives for raidz1"));
int numChecked = 0;
for ( int i = 0; i < listZFSDisks->count(); ++i )
if ( listZFSDisks->item(i)->checkState() == Qt::Checked )
numChecked++;
if ( numChecked == 2 || numChecked == 4 ) {
button(QWizard::NextButton)->setEnabled(true);
return true;
}
}
if ( comboZFSMode->currentText() == "raidz2" ) {
labelZFSMsg->setText(tr("Please select 3, 5, or 9 additional drives for raidz2"));
int numChecked = 0;
for ( int i = 0; i < listZFSDisks->count(); ++i )
if ( listZFSDisks->item(i)->checkState() == Qt::Checked )
numChecked++;
if ( numChecked == 3 || numChecked == 5 || numChecked == 9 ) {
button(QWizard::NextButton)->setEnabled(true);
return true;
}
}
if ( comboZFSMode->currentText() == "raidz3" ) {
labelZFSMsg->setText(tr("Please select 4, 6, or 10 additional drives for raidz3"));
int numChecked = 0;
for ( int i = 0; i < listZFSDisks->count(); ++i )
if ( listZFSDisks->item(i)->checkState() == Qt::Checked )
numChecked++;
if ( numChecked == 4 || numChecked == 6 || numChecked == 10 ) {
button(QWizard::NextButton)->setEnabled(true);
return true;
}
}
if ( comboZFSMode->currentText() == "stripe" ) {
labelZFSMsg->setText(tr("Please select the additional disks to stripe"));
int numChecked = 0;
for ( int i = 0; i < listZFSDisks->count(); ++i )
if ( listZFSDisks->item(i)->checkState() == Qt::Checked )
numChecked++;
if ( numChecked >= 1 ) {
button(QWizard::NextButton)->setEnabled(true);
return true;
}
}
// Disable the next button until we get a working config
button(QWizard::NextButton)->setEnabled(false);
return false;
case Page_ZFS2:
// Not using log / cache?
if ( !groupZFSCache->isChecked() && ! groupZFSLog->isChecked() )
{
button(QWizard::NextButton)->setEnabled(true);
return true;
}
// Using both? See if we have any duplicates
if ( groupZFSCache->isChecked() && groupZFSLog->isChecked() )
{
// Check for any matches
for ( int i = 0; i < listZFSCache->count(); ++i ) {
if ( listZFSCache->item(i)->checkState() == Qt::Checked )
for ( int z = 0; z < listZFSLog->count(); ++z ) {
if ( listZFSLog->item(z)->checkState() == Qt::Checked )
if ( listZFSLog->item(z)->text() == listZFSCache->item(i)->text() ) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
}
}
}
// Check that we have at least one item checked
found = false;
if ( groupZFSCache->isChecked() )
{
for ( int i = 0; i < listZFSCache->count(); ++i )
if ( listZFSCache->item(i)->checkState() == Qt::Checked )
found = true;
if ( found == false) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
}
if ( groupZFSLog->isChecked() )
{
for ( int i = 0; i < listZFSLog->count(); ++i )
if ( listZFSLog->item(i)->checkState() == Qt::Checked )
found = true;
if ( found == false) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
}
button(QWizard::NextButton)->setEnabled(true);
return true;
case Page_Enc:
if ( ! groupEncrypt->isChecked() ) {
button(QWizard::NextButton)->setEnabled(true);
return true;
}
if ( lineEncPass->text().isEmpty() || lineEncPass->text() != lineEncPass2->text() ) {
button(QWizard::NextButton)->setEnabled(false);
return false;
}
button(QWizard::NextButton)->setEnabled(true);
return true;
case Page_Confirmation:
button(QWizard::FinishButton)->setEnabled(true);
return true;
default:
button(QWizard::NextButton)->setEnabled(true);
return true;
}
return true;
}
void wizardDisk::populateZFSDisks()
{
qDebug() << "Adding ZFS disks...";
listZFSDisks->clear();
QString curDisk = comboDisk->currentText();
curDisk.truncate(curDisk.indexOf(" -"));
for (int z=0; z < sysDisks.count(); ++z)
if ( sysDisks.at(z).at(0) == "DRIVE" && sysDisks.at(z).at(1) != curDisk )
{
QListWidgetItem *dItem = new QListWidgetItem(sysDisks.at(z).at(1) + " - " + sysDisks.at(z).at(2) + "MB " + sysDisks.at(z).at(3));
dItem->setCheckState(Qt::Unchecked);
listZFSDisks->addItem(dItem);
}
}
void wizardDisk::populateZFSDisks2()
{
qDebug() << "Adding ZFS2 disks...";
listZFSCache->clear();
listZFSLog->clear();
// What is the primary target disk
QString curDisk = comboDisk->currentText();
curDisk.truncate(curDisk.indexOf(" -"));
// Get a list of other disks being used
QStringList usedDisks;
if ( groupZFSOpts->isChecked() ) {
for ( int i = 0; i < listZFSDisks->count(); ++i )
if ( listZFSDisks->item(i)->checkState() == Qt::Checked ) {
QString zDisk = listZFSDisks->item(i)->text();
zDisk.truncate(zDisk.indexOf(" -"));
usedDisks << zDisk;
}
}
// Now add any available disks to the combo boxes
for (int z=0; z < sysDisks.count(); ++z)
if ( sysDisks.at(z).at(0) == "DRIVE" && sysDisks.at(z).at(1) != curDisk && ! usedDisks.contains(sysDisks.at(z).at(1)) )
{
QListWidgetItem *dItem = new QListWidgetItem(sysDisks.at(z).at(1) + " - " + sysDisks.at(z).at(2) + "MB " + sysDisks.at(z).at(3));
dItem->setCheckState(Qt::Unchecked);
listZFSCache->addItem(dItem);
QListWidgetItem *dItem2 = new QListWidgetItem(sysDisks.at(z).at(1) + " - " + sysDisks.at(z).at(2) + "MB " + sysDisks.at(z).at(3));
dItem2->setCheckState(Qt::Unchecked);
listZFSLog->addItem(dItem2);
}
}
bool wizardDisk::checkDiskSpace()
{
if ( getDiskSliceSize() < 4000 )
return false;
return true;
}
void wizardDisk::slotCheckComplete()
{
// Validate this page
validatePage();
}
void wizardDisk::generateDiskLayout()
{
QString targetType, tmp;
int targetLoc, totalSize = 0;
QString targetDisk, targetSlice, tmpPass, fsType, target;
// Clear out the original disk layout
sysFinalDiskLayout.clear();
QStringList fileSystem;
qDebug() << "Generating disk layout";
if ( comboPartition->currentIndex() == 0) {
targetType = "DRIVE";
targetSlice = "ALL";
targetDisk = comboDisk->currentText();
targetDisk.truncate(targetDisk.indexOf(" -"));
target = targetDisk;
targetLoc = 1;
} else {
targetType = "SLICE";
targetDisk = comboDisk->currentText();
targetDisk.truncate(targetDisk.indexOf(" -"));
targetSlice = comboPartition->currentText();
targetSlice.truncate(targetSlice.indexOf(":"));
targetSlice = targetSlice.remove(0, targetSlice.size() -2);
target = targetDisk + targetSlice;
targetLoc = 2;
}
// Get the size of the slice we are working on
totalSize = getDiskSliceSize();
// Setup some swap space
if ( totalSize > 50000 ) {
// 4GB if over 50GB of disk space
swapsize = 4096;
} else if ( totalSize > 30000 ) {
// 2GB if over 30GB of disk space
swapsize = 2048;
} else {
// Minimum 512MB
swapsize = 512;
}
totalSize = totalSize - swapsize;
if ( totalSize != -1 )
{
fsType= "ZFS";
if ( groupEncrypt->isChecked() ) {
fsType="ZFS.eli";
tmpPass=lineEncPass->text();
}
QString rootOpts="";
rootOpts="(compress=lz4|atime=off)";
// This lets the user do nifty stuff like a mirror/raid post-install with a single zpool command
fileSystem << targetDisk << targetSlice << "/" + rootOpts + ",/tmp(compress=lz4|setuid=off),/usr(canmount=off|mountpoint=none),/usr/home(compress=lz4),/usr/jails(compress=lz4),/usr/local/share/doc(compress=gzip),/usr/obj(compress=lz4),/usr/ports(compress=lz4),/usr/src(compress=lz4),/var(canmount=off|atime=on|mountpoint=none),/var/audit(compress=lz4),/var/log(compress=lz4|exec=off|setuid=off),/var/mail(compress=lz4),/var/tmp(compress=lz4|exec=off|setuid=off)" << fsType << tmp.setNum(totalSize) << "" << tmpPass;
sysFinalDiskLayout << fileSystem;
fileSystem.clear();
// If installing to a specific GPT slice, we can't create a 2nd swap partition
if ( swapsize > 0 ) {
// Now add swap space
fileSystem << targetDisk << targetSlice << "SWAP.eli" << "SWAP.eli" << tmp.setNum(swapsize) << "" << "";
sysFinalDiskLayout << fileSystem;
fileSystem.clear();
}
//qDebug() << "Auto-Gen FS:" << fileSystem;
}
qDebug() << "AutoLayout:" << sysFinalDiskLayout;
}
void wizardDisk::populateDiskTree()
{
QStringList tmpList, zMnts;
QString tmp, opts;
// If installing to Free Space, show the option to change partition size
labelNewPartition->setVisible(false);
spinNewPartition->setVisible(false);
spinNewPartition->setRange(0, 0);
spinNewPartition->setValue(0);
if ( comboPartition->currentIndex() != 0 && comboPartition->currentText().contains("Unused") ) {
spinNewPartition->setRange(5000, this->getDiskSliceSize());
spinNewPartition->setValue(getDiskSliceSize());
labelNewPartition->setVisible(true);
spinNewPartition->setVisible(true);
}
treeMounts->clear();
treeMounts->setHeaderLabels(QStringList() << "ID" << tr("ZFS Mounts") << tr("ZFS Options") );
treeMounts->setColumnCount(3);
labelFreeSpace->setVisible(false);
lineFreeMB->setVisible(false);
treeMounts->header()->setSectionHidden(0, true);
treeMounts->header()->setDefaultSectionSize(150);
zMnts = sysFinalDiskLayout.at(0).at(2).split(",");
// Now loop through ZFS mounts
for (int i=0; i < zMnts.count(); ++i) {
tmpList.clear();
opts = zMnts.at(i).section("(", 1, 1).section(")", 0, 0);
tmpList << tmp.setNum(i+1) << zMnts.at(i).split("(").at(0) << opts ;
QTreeWidgetItem *mItem = new QTreeWidgetItem(treeMounts, tmpList);
mItem->setToolTip(2, opts);
}
treeMounts->setCurrentItem(treeMounts->findItems("0", Qt::MatchFixedString).at(0));
slotTreeDiskChanged();
if ( restoreMode ) {
treeMounts->setEnabled(false);
pushRemoveMount->setEnabled(false);
pushAddMount->setEnabled(false);
labelMounts->setText(tr("The original system datasets / mount-points will be automatically restored."));
}
}
int wizardDisk::getDiskSliceSize()
{
bool ok;
QString disk = comboDisk->currentText();
disk.truncate(disk.indexOf(" -"));
int safeBuf = 15;
// If on EFI we subtract 100MiB to save for a FAT16/EFI partition
if ( efiMode )
safeBuf = 115;
// Check the full disk
if ( comboPartition->currentIndex() == 0) {
for (int i=0; i < sysDisks.count(); ++i) {
// Make sure to only add the drives to the comboDiskList
if ( sysDisks.at(i).at(0) == "DRIVE" && sysDisks.at(i).at(1) == disk ) {
//qDebug() << "Selected Disk Size: " + sysDisks.at(i).at(2);
sysDisks.at(i).at(2).toInt(&ok);
if( ok )
return (sysDisks.at(i).at(2).toInt(&ok) - safeBuf);
else
return -1;
}
}
} else {
// Check the selected partition
QString slice = comboPartition->currentText();
slice.truncate(slice.indexOf(":"));
for (int i=0; i < sysDisks.count(); ++i) {
// Make sure to only add the slices to the listDiskSlices
if ( sysDisks.at(i).at(0) == "SLICE" && slice == sysDisks.at(i).at(2)) {
//qDebug() << "Selected Slice Size: " + sysDisks.at(i).at(3);
sysDisks.at(i).at(3).toInt(&ok);
if( ok )
return (sysDisks.at(i).at(3).toInt(&ok) - safeBuf);
else
return -1;
}
}
}
return -1;
}
void wizardDisk::slotTreeDiskChanged()
{
if ( ! treeMounts->currentItem() )
return;
pushRemoveMount->setEnabled(true);
pushAddMount->setEnabled(true);
if ( treeMounts->currentItem()->text(1) == "/boot" || treeMounts->currentItem()->text(1) == "/")
pushRemoveMount->setEnabled(false);
if ( lineFreeMB->text() == "0" )
pushAddMount->setEnabled(false);
}
void wizardDisk::slotResizeFS()
{
if ( ! treeMounts->currentItem() )
return;
QString mnt = treeMounts->currentItem()->text(1);
bool ok;
int curSize, availSize, minSize;
curSize = treeMounts->currentItem()->text(2).toInt(&ok);
availSize = curSize + lineFreeMB->text().toInt(&ok);
minSize = 100;
// See if we need some other sanity check on sizes
if ( mnt == "SWAP.eli" )
minSize = 256;
if ( mnt == "/" )
minSize = 2000;
if ( mnt == "/boot" )
minSize = 1000;
addingMount="";
rFS = new dialogFSSize();
rFS->programInit(QString(tr("Resizing") + " " + mnt), curSize, availSize, minSize);
rFS->setWindowModality(Qt::ApplicationModal);
connect(rFS, SIGNAL(saved(int)), this, SLOT(slotSaveFSResize(int)));
rFS->show();
rFS->raise();
}
void wizardDisk::slotRemoveFS()
{
if ( ! treeMounts->currentItem() )
return;
int ret = QMessageBox::question(this, tr("Remove mount-point"),
tr("Are you sure you want to remove this mount point?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if ( ret != QMessageBox::Yes )
return;
QTreeWidgetItem *rmItem = treeMounts->currentItem();
treeMounts->setCurrentItem(treeMounts->findItems("0", Qt::MatchFixedString).at(0));
delete rmItem;
}
void wizardDisk::slotAddFS()
{
bool ok;
QString tmp;
QString nMount = QInputDialog::getText(this, tr("Enter mount-point"),
tr("Please enter the new mount-point:"), QLineEdit::Normal,
"/", &ok);
if (!ok || nMount.isEmpty())
return;
// Sanity checks
////////////////////////////////////////
if ( nMount.indexOf("/") != 0 ) {
QMessageBox::critical(this, tr("Invalid Mount"),
tr("Mount point should start with '/'"),
QMessageBox::Ok,
QMessageBox::Ok);
return;
}
// End sanity checks
////////////////////////////////////////
// Make sure this mount doesn't already exist
QList<QTreeWidgetItem *> mItems = treeMounts->findItems("*", Qt::MatchWildcard);
for ( int i = 0; i < mItems.size(); ++i) {
if ( mItems.at(i)->text(1) == nMount )
return;
}
new QTreeWidgetItem(treeMounts, QStringList() << tmp.setNum(mItems.size() + 1) << nMount );
}
void wizardDisk::slotSaveFSResize(int newSize)
{
QString tmp, tmp2;
bool ok;
int oSize, availSize, tSize, newAvailSize;
// If adding a new mount point
if ( ! addingMount.isEmpty() ) {
QList<QTreeWidgetItem *> mItems = treeMounts->findItems("*", Qt::MatchWildcard);
new QTreeWidgetItem(treeMounts, QStringList() << tmp.setNum(mItems.size() + 1) << addingMount << tmp2.setNum(newSize) << "UFS+SUJ" );
addingMount="";
availSize = lineFreeMB->text().toInt(&ok);
newAvailSize = availSize - newSize;
lineFreeMB->setText(tmp.setNum(newAvailSize));
return;
}
if ( ! treeMounts->currentItem() )
return;
// Just resizing an existing partition
oSize = treeMounts->currentItem()->text(2).toInt(&ok);
treeMounts->currentItem()->setText(2, tmp.setNum(newSize));
// Set the available size
if ( oSize > newSize ) {
tSize = oSize - newSize;
availSize = lineFreeMB->text().toInt(&ok);
newAvailSize = availSize + tSize;
} else {
tSize = newSize - oSize;
availSize = lineFreeMB->text().toInt(&ok);
newAvailSize = availSize - tSize;
}
lineFreeMB->setText(tmp.setNum(newAvailSize));
// Check if we need to enable the add button
if ( newAvailSize >= 100 )
pushAddMount->setEnabled(true);
else
pushAddMount->setEnabled(false);
}
void wizardDisk::slotTreeMountsRightClick()
{
if ( ! treeMounts->currentItem() )
return;
popup = new QMenu();
popup->setTitle(tr("Editing:") + " " + treeMounts->currentItem()->text(1));
popup->addSeparator();
// Create atime sub-menu
popupAT = popup->addMenu("atime");
popupAT->addAction( "on", this, SLOT(slotZATON()));
popupAT->addAction( "off", this, SLOT(slotZATOFF()));
// Create canmount sub-menu
popupCM = popup->addMenu("canmount");
popupCM->addAction( "on", this, SLOT(slotZCMON()));
popupCM->addAction( "off", this, SLOT(slotZCMOFF()));
popupCM->addAction( "noauto", this, SLOT(slotZCMNOAUTO()));
// Case sensitivity
popupCI = popup->addMenu("casesensitivity");
popupCI->addAction( "sensitive", this, SLOT(slotZCION()));
popupCI->addAction( "insensitive", this, SLOT(slotZCIOFF()));
// Create Checksum sub-menu
popupCH = popup->addMenu("checksum");
popupCH->addAction( "on", this, SLOT(slotZChkON()));
popupCH->addAction( "off", this, SLOT(slotZChkOFF()));
// Create compression sub-menu
popupCmp = popup->addMenu("compression");
popupCmp->addAction( "off", this, SLOT(slotZCmpOFF()));
popupCmp->addAction( "on", this, SLOT(slotZCmpON()));
popupCmp->addAction( "lz4", this, SLOT(slotZCmpLZ4()));
popupCmp->addAction( "lzjb", this, SLOT(slotZCmpLZJB()));
popupCmp->addAction( "gzip", this, SLOT(slotZCmpGZIP()));
popupCmp->addAction( "zle", this, SLOT(slotZCmpZLE()));
// Create dedup sub-menu
// dedup is disabled for now, until such time as it is safe in all cases
//popupDD = popup->addMenu("dedup");
//popupDD->addAction( "off", this, SLOT(slotZDDOFF()));
//popupDD->addAction( "on", this, SLOT(slotZDDON()));
//popupDD->addAction( "verify", this, SLOT(slotZDDVERIFY()));
// Create exec sub-menu
popupNE = popup->addMenu("exec");
popupNE->addAction( "on", this, SLOT(slotZEXON()));
popupNE->addAction( "off", this, SLOT(slotZEXOFF()));
// Add setuid sub-menu
popupNE = popup->addMenu("setuid");
popupNE->addAction( "on", this, SLOT(slotZSUIDON()));
popupNE->addAction( "off", this, SLOT(slotZSUIDOFF()));
popup->exec( QCursor::pos() );
}
void wizardDisk::slotZCION()
{
toggleZFSOpt(QString("casesensitivity=sensitive"));
}
void wizardDisk::slotZCIOFF()
{
toggleZFSOpt(QString("casesensitivity=insensitive"));
}
void wizardDisk::slotZCMNOAUTO()
{
toggleZFSOpt(QString("canmount=noauto"));
}
void wizardDisk::slotZCMOFF()
{
toggleZFSOpt(QString("canmount=off"));
}
void wizardDisk::slotZCMON()
{
toggleZFSOpt(QString("canmount=on"));
}
void wizardDisk::slotZDDVERIFY()
{
toggleZFSOpt(QString("dedup=verify"));
}
void wizardDisk::slotZDDON()
{
toggleZFSOpt(QString("dedup=on"));
}
void wizardDisk::slotZDDOFF()
{
toggleZFSOpt(QString("dedup=off"));
}
void wizardDisk::slotZCmpZLE()
{
toggleZFSOpt(QString("compress=zle"));
}
void wizardDisk::slotZCmpGZIP()
{
toggleZFSOpt(QString("compress=gzip"));
}
void wizardDisk::slotZCmpLZ4()
{
toggleZFSOpt(QString("compress=lz4"));
}
void wizardDisk::slotZCmpLZJB()
{
toggleZFSOpt(QString("compress=lzjb"));
}
void wizardDisk::slotZCmpOFF()
{
toggleZFSOpt(QString("compress=off"));
}
void wizardDisk::slotZCmpON()
{
toggleZFSOpt(QString("compress=on"));
}
void wizardDisk::slotZChkOFF()
{
toggleZFSOpt(QString("checksum=off"));
}
void wizardDisk::slotZChkON()
{
toggleZFSOpt(QString("checksum=on"));
}
void wizardDisk::slotZATON()
{
toggleZFSOpt(QString("atime=on"));
}
void wizardDisk::slotSwapSize()
{
bool ok;
QString tmp;
int size = QInputDialog::getInt(this, tr("Enter SWAP size"),
tr("Size (MB)"), swapsize, 0, 1000000, 1, &ok);
if ( ok )
swapsize = size;
}
void wizardDisk::slotZATOFF()
{
toggleZFSOpt(QString("atime=off"));
}
void wizardDisk::slotZEXOFF()
{
toggleZFSOpt(QString("exec=off"));
}
void wizardDisk::slotZEXON()
{
toggleZFSOpt(QString("exec=on"));
}
void wizardDisk::slotZSUIDOFF()
{
toggleZFSOpt(QString("setuid=off"));
}
void wizardDisk::slotZSUIDON()
{
toggleZFSOpt(QString("setuid=on"));
}
// Toggle an option being on / off for ZFS
void wizardDisk::toggleZFSOpt(QString option)
{
if ( ! treeMounts->currentItem() )
return;
bool found = false;
QString optTag = option.section("=", 0, 0);
QString tmpTag;
QStringList newOpts;
QStringList curOpts = treeMounts->currentItem()->text(2).split("|");
for (int i=0; i < curOpts.count(); ++i) {
tmpTag=curOpts.at(i).section("=", 0, 0);
if ( optTag == tmpTag ) {
found = true;
// Only save option if setting to new value
if ( option != curOpts.at(i) )
newOpts << option;
} else {
if ( !curOpts.at(i).isEmpty() )
newOpts << curOpts.at(i);
}
}
if ( ! found )
newOpts << option;
QString optString;
if ( newOpts.count() <= 1)
optString = newOpts.join("");
else
optString = newOpts.join("|");
treeMounts->currentItem()->setText(2, optString);
treeMounts->currentItem()->setToolTip(2, optString);
}
void wizardDisk::generateCustomDiskLayout()
{
QString targetType, tmp;
int targetLoc;
QString targetDisk, targetSlice, tmpPass, fsType, target;
// Clear out the original disk layout
sysFinalDiskLayout.clear();
QStringList fileSystem;
qDebug() << "Generating custom disk layout";
if ( comboPartition->currentIndex() == 0) {
targetType = "DRIVE";
targetSlice = "ALL";
targetDisk = comboDisk->currentText();
targetDisk.truncate(targetDisk.indexOf(" -"));
target = targetDisk;
targetLoc = 1;
} else {
targetType = "SLICE";
targetDisk = comboDisk->currentText();
targetDisk.truncate(targetDisk.indexOf(" -"));
targetSlice = comboPartition->currentText();
targetSlice.truncate(targetSlice.indexOf(":"));
targetSlice = targetSlice.remove(0, targetSlice.size() -2);
target = targetDisk + targetSlice;
targetLoc = 2;
}
// Check if this is an install to "Unused Space"
for (int z=0; z < sysDisks.count(); ++z)
if ( sysDisks.at(z).at(0) == "SLICE" \
&& sysDisks.at(z).at(2) == targetDisk + targetSlice \
&& sysDisks.at(z).at(4) == "Unused Space" ) {
targetSlice = "free";
}
// Start building the ZFS file-systems
QStringList zMnts;
fsType = "ZFS";
if ( groupEncrypt->isChecked() ) {
fsType="ZFS.eli";
tmpPass=lineEncPass->text();
}
int zpoolSize = getDiskSliceSize();
// If we are using free space, get the user set size
if ( targetSlice == "free" && spinNewPartition->value() != 0 )
zpoolSize = spinNewPartition->value();
// Deduct any swap space
zpoolSize = zpoolSize - swapsize;
// Get the zfs mounts
QList<QTreeWidgetItem *> mItems = treeMounts->findItems("*", Qt::MatchWildcard);
for ( int i = 0; i < mItems.size(); ++i) {
if ( mItems.at(i)->text(2).isEmpty() )
zMnts << mItems.at(i)->text(1);
else
zMnts << mItems.at(i)->text(1) + "(" + mItems.at(i)->text(2) + ")";
}
// If we have any additional ZFS mirror / raidz devices set it up now
QString zOpts, zDisk;
if ( groupZFSOpts->isChecked() && comboPartition->currentIndex() == 0 ) {
zOpts = comboZFSMode->currentText() + ":";
for ( int i = 0; i < listZFSDisks->count(); ++i )
if ( listZFSDisks->item(i)->checkState() == Qt::Checked ) {
zDisk = listZFSDisks->item(i)->text();
zDisk.truncate(zDisk.indexOf(" -"));
zOpts = zOpts + " " + zDisk;
}
}
// Any additional ZFS cache devices?
if ( groupZFSCache->isChecked() ) {
zOpts+=" cache";
for ( int i = 0; i < listZFSCache->count(); ++i )
if ( listZFSCache->item(i)->checkState() == Qt::Checked ) {
zDisk = listZFSCache->item(i)->text();
zDisk.truncate(zDisk.indexOf(" -"));
zOpts = zOpts + " " + zDisk;
}
}
// Any additional ZFS log devices?
if ( groupZFSLog->isChecked() ) {
zOpts+=" log";
for ( int i = 0; i < listZFSLog->count(); ++i )
if ( listZFSLog->item(i)->checkState() == Qt::Checked ) {
zDisk = listZFSLog->item(i)->text();
zDisk.truncate(zDisk.indexOf(" -"));
zOpts = zOpts + " " + zDisk;
}
}
// Save the final disk layout
fileSystem.clear();
fileSystem << targetDisk << targetSlice << zMnts.join(",") << fsType << tmp.setNum(zpoolSize) << zOpts << tmpPass;
sysFinalDiskLayout << fileSystem;
// If installing to a specific GPT slice, we can't create a 2nd swap partition
if ( swapsize > 0 ) {
// Now add swap space
fileSystem.clear();
fileSystem << targetDisk << targetSlice << "SWAP.eli" << "SWAP.eli" << tmp.setNum(swapsize) << "" << "";
sysFinalDiskLayout << fileSystem;
}
qDebug() <<"AutoLayout:" << sysFinalDiskLayout;
}
void wizardDisk::generateConfirmationText()
{
// If running in expert mode, we just create a simple config / confirmation
/*if ( radioExpert->isChecked() ) {
QStringList filesystem;
filesystem << "MANUAL" << "/mnt" ;
sysFinalDiskLayout << filesystem;
textConfirmation->setText(tr("Installing to file-system mounted at /mnt"));
return;
}*/
QList<QStringList> copyList;
QStringList summaryList;
QString tmp, workingDisk, workingSlice, tmpSlice, XtraTmp, startPart, sliceSize;
int disk = 0;
// Copy over the list to a new variable we can mangle without modifying the original
copyList = sysFinalDiskLayout;
// Start our summary
summaryList << "";
summaryList << "<b>" + tr("The disk will be setup with the following configuration:") + "</b>";
while ( ! copyList.empty() )
{
workingDisk = copyList.at(0).at(0);
workingSlice = copyList.at(0).at(1);
tmpSlice = workingSlice;
// Check if this is an install to "Unused Space"
for (int z=0; z < sysDisks.count(); ++z)
if ( sysDisks.at(z).at(0) == "SLICE" \
&& sysDisks.at(z).at(2) == workingDisk + workingSlice \
&& sysDisks.at(z).at(4) == "Unused Space" )
tmpSlice = "free";
// Check for any mirror for this device
for (int i=0; i < copyList.count(); ++i) {
if ( copyList.at(i).at(2).indexOf("MIRROR(" + workingDisk + ")") != -1 )
{
summaryList << tr("Disk:") + copyList.at(i).at(0) + " " + tr("Mirroring:") + workingDisk;
copyList.removeAt(i);
break;
}
}
// If after doing the mirror, our list is empty, break out
if ( copyList.empty() )
break;
// If there is a dedicated /boot partition, need to list that first, see what is found
for (int i=0; i < copyList.count(); ++i) {
QStringList mounts = copyList.at(i).at(2).split(",");
for (int z = 0; z < mounts.size(); ++z) {
if ( copyList.at(i).at(0) == workingDisk \
&& copyList.at(i).at(1) == workingSlice \
&& mounts.at(z) == "/boot" )
startPart="/boot";
}
}
// If no dedicated /boot partition, then lets list "/" first
if(startPart.isEmpty())
startPart="/";
// Start by looking for the root partition
for (int i=0; i < copyList.count(); ++i) {
QStringList mounts = copyList.at(i).at(2).split(",");
for (int z = 0; z < mounts.size(); ++z) {
if ( copyList.at(i).at(0) == workingDisk \
&& copyList.at(i).at(1) == workingSlice \
&& mounts.at(z) == startPart ) {
// Check if we have any extra arguments to throw on the end
XtraTmp="";
if ( ! copyList.at(i).at(5).isEmpty() )
XtraTmp=" (" + copyList.at(i).at(5) + ")" ;
// Write the user summary
summaryList << "";
summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";
if ( copyList.at(i).at(3) == "ZFS" || copyList.at(i).at(3) == "ZFS.eli" ) {
QStringList zDS = copyList.at(i).at(2).split(",/");
QString zTMP;
for (int ds = 0; ds < zDS.size(); ++ds) {
if ( zDS.at(ds) != "/" )
zDS.replace(ds, "/" + zDS.at(ds));
if ( zDS.at(ds).indexOf("(") != -1 ) {
zTMP = zDS.at(ds);
zTMP.replace("(", " (");
zDS.replace(ds, zTMP );
}
}
summaryList << tr("ZFS Datasets:<br>") + " " + zDS.join("<br>");
} else {
summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
}
if ( ! XtraTmp.isEmpty() ) {
summaryList << tr("Options:") + " " + copyList.at(i).at(5);
}
// Done with this item, remove it now
copyList.removeAt(i);
break;
}
}
}
// Now look for SWAP
for (int i=0; i < copyList.count(); ++i) {
if ( copyList.at(i).at(0) == workingDisk \
&& copyList.at(i).at(1) == workingSlice \
&& copyList.at(i).at(2) == "SWAP.eli" ) {
// Write the user summary
summaryList << "";
summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";
// Done with this item, remove it now
copyList.removeAt(i);
break;
}
}
// Now look for any other partitions
int count = copyList.count();
for (int i=0; i < count; ++i) {
if ( copyList.at(i).at(0) == workingDisk \
&& copyList.at(i).at(1) == workingSlice ) {
// Check if we have any extra arguments to throw on the end
XtraTmp="";
if ( ! copyList.at(i).at(5).isEmpty() )
XtraTmp=" (" + copyList.at(i).at(5) + ")" ;
// If we are working on the last partition, set the size to 0 to use remaining disk
if ( i == (count - 1) )
sliceSize = "0";
else
sliceSize=copyList.at(i).at(4);
// Write the user summary
summaryList << "";
summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";
summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
if ( ! XtraTmp.isEmpty() ) {
summaryList << tr("Options:") + " " + copyList.at(i).at(5);
}
// Done with this item, remove it now
copyList.removeAt(i);
i--;
count--;
}
}
// Increment our disk counter
disk++;
}
textConfirmation->setText(summaryList.join("<br>"));
}
/*void wizardDisk::slotTerminal()
{
system("qterminal &");
}*/
void wizardDisk::setRestoreMode()
{
restoreMode=true;
}
| 31.911392 | 519 | 0.597942 | Acidburn0zzz |
18eaeeb33a7a7a7b102b1b18b2b50b4ede77fa31 | 3,485 | cpp | C++ | dali-toolkit/public-api/controls/control.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | dali-toolkit/public-api/controls/control.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | dali-toolkit/public-api/controls/control.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali-toolkit/public-api/controls/control.h>
// INTERNAL INCLUDES
#include <dali-toolkit/public-api/controls/control-impl.h>
namespace Dali
{
namespace Toolkit
{
Control Control::New()
{
return Internal::Control::New();
}
Control::Control()
{
}
Control::Control( const Control& uiControl )
: CustomActor( uiControl )
{
}
Control::~Control()
{
}
Control& Control::operator=( const Control& handle )
{
if( &handle != this )
{
CustomActor::operator=( handle );
}
return *this;
}
Control Control::DownCast( BaseHandle handle )
{
return DownCast< Control, Internal::Control >(handle);
}
void Control::SetKeyInputFocus()
{
Internal::GetImplementation(*this).SetKeyInputFocus();
}
bool Control::HasKeyInputFocus()
{
return Internal::GetImplementation(*this).HasKeyInputFocus();
}
void Control::ClearKeyInputFocus()
{
Internal::GetImplementation(*this).ClearKeyInputFocus();
}
PinchGestureDetector Control::GetPinchGestureDetector() const
{
return Internal::GetImplementation(*this).GetPinchGestureDetector();
}
PanGestureDetector Control::GetPanGestureDetector() const
{
return Internal::GetImplementation(*this).GetPanGestureDetector();
}
TapGestureDetector Control::GetTapGestureDetector() const
{
return Internal::GetImplementation(*this).GetTapGestureDetector();
}
LongPressGestureDetector Control::GetLongPressGestureDetector() const
{
return Internal::GetImplementation(*this).GetLongPressGestureDetector();
}
void Control::SetStyleName( const std::string& styleName )
{
Internal::GetImplementation(*this).SetStyleName( styleName );
}
const std::string& Control::GetStyleName() const
{
return Internal::GetImplementation(*this).GetStyleName();
}
void Control::SetBackgroundColor( const Vector4& color )
{
Internal::GetImplementation(*this).SetBackgroundColor( color );
}
Vector4 Control::GetBackgroundColor() const
{
return Internal::GetImplementation(*this).GetBackgroundColor();
}
void Control::SetBackgroundImage( Image image )
{
Internal::GetImplementation(*this).SetBackgroundImage( image );
}
void Control::ClearBackground()
{
Internal::GetImplementation(*this).ClearBackground();
}
Control::KeyEventSignalType& Control::KeyEventSignal()
{
return Internal::GetImplementation(*this).KeyEventSignal();
}
Control::KeyInputFocusSignalType& Control::KeyInputFocusGainedSignal()
{
return Internal::GetImplementation(*this).KeyInputFocusGainedSignal();
}
Control::KeyInputFocusSignalType& Control::KeyInputFocusLostSignal()
{
return Internal::GetImplementation(*this).KeyInputFocusLostSignal();
}
Control::Control(Internal::Control& implementation)
: CustomActor(implementation)
{
}
Control::Control(Dali::Internal::CustomActor* internal)
: CustomActor(internal)
{
VerifyCustomActorPointer<Internal::Control>(internal);
}
} // namespace Toolkit
} // namespace Dali
| 22.339744 | 75 | 0.757819 | tizenorg |
18eb9ca0a127bc8f5f252f662cbd648ed2d14ddd | 3,308 | cpp | C++ | MeetingManager/MeetingManager/MeetingManager.cpp | hyq5436/playground | 828b9d2266dbb7d0311e2e73b295fcafb101d94f | [
"MIT"
] | 1 | 2021-06-23T08:41:55.000Z | 2021-06-23T08:41:55.000Z | MeetingManager/MeetingManager/MeetingManager.cpp | hyq5436/playground | 828b9d2266dbb7d0311e2e73b295fcafb101d94f | [
"MIT"
] | null | null | null | MeetingManager/MeetingManager/MeetingManager.cpp | hyq5436/playground | 828b9d2266dbb7d0311e2e73b295fcafb101d94f | [
"MIT"
] | null | null | null | #pragma execution_character_set("utf-8")
#include "MeetingManager.h"
#include <QDebug>
#include <QIcon>
#include <QItemDelegate>
#include <QListWidgetItem>
#include <QPainter>
#include <QPushButton>
#include <QStandardItem>
#include <QStandardItemModel>
namespace {
static const int MeetingIconRole = Qt::UserRole + 1;
}
class MeetingNavDelegate : public QItemDelegate {
public:
MeetingNavDelegate(QObject* parent) : QItemDelegate(parent){};
void paint(QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const override {
if (option.state & QStyle::State_Selected) {
QBrush brush(QColor("#c7e2fb"));
QRect fill_rect(option.rect.x(), option.rect.y(),
option.rect.width(), option.rect.height());
painter->fillRect(fill_rect, brush);
} else if (option.state & QStyle::State_MouseOver) {
QBrush brush(QColor("#e2effc"));
QRect fill_rect(option.rect.x(), option.rect.y(),
option.rect.width(), option.rect.height());
painter->fillRect(fill_rect, brush);
}
QString title = index.data(Qt::DisplayRole).toString();
QString iconPath = index.data(MeetingIconRole).toString();
//头像显示区域
QRect iconRect =
QRect(option.rect.x() + 20, option.rect.y() + 10, 30, 30);
QPixmap icon(iconPath);
painter->drawPixmap(iconRect, icon);
//
QRect titleRect =
QRect(option.rect.x() + 30 + 30, option.rect.y(), 100, 50);
painter->drawText(titleRect, title, QTextOption(Qt::AlignVCenter));
}
QSize sizeHint(const QStyleOptionViewItem& option,
const QModelIndex& index) const override {
return QSize(100, 50);
}
};
MeetingManager::MeetingManager(QWidget* parent) : QWidget(parent) {
ui.setupUi(this);
addMeetingType();
}
void MeetingManager::addMeetingType() {
auto* model = new QStandardItemModel(this);
auto* delegate = new MeetingNavDelegate(this);
ui.listMeetingNav->setModel(model);
ui.listMeetingNav->setItemDelegate(delegate);
auto* allHistory =
new QStandardItem(QIcon("Resources/history.png"), tr("我的会议"));
allHistory->setData(QString("Resources/history.png"), MeetingIconRole);
auto* voice =
new QStandardItem(QIcon("Resources/voice.png"), tr("语音会议"));
voice->setData(QString("Resources/voice.png"), MeetingIconRole);
auto* video =
new QStandardItem(QIcon("Resources/video.png"), tr("视频会议"));
video->setData(QString("Resources/video.png"), MeetingIconRole);
auto* live = new QStandardItem(QIcon("Resources/live.png"), tr("直播"));
live->setData(QString("Resources/live.png"), MeetingIconRole);
model->appendRow(allHistory);
model->appendRow(voice);
model->appendRow(video);
model->appendRow(live);
auto* pButtonContainer = new QWidget(ui.tabWidget);
pButtonContainer->resize(QSize(100, ui.tabWidget->tabBar()->height()));
auto* pLayout = new QHBoxLayout;
pButtonContainer->setLayout(pLayout);
auto* pButton = new QPushButton(ui.tabWidget);
pLayout->addWidget(pButton);
// TabBar 按钮
//ui.tabWidget->setCornerWidget(pButtonContainer);
}
| 34.458333 | 75 | 0.64994 | hyq5436 |
18ebdd02697e2bfd979b639889997b357765e36c | 746 | cpp | C++ | Algorithm/ACM/Orientation Training Round #1 Div.1/F.cpp | XJDKC/University-Code-Archive | 2dd9c6edb2164540dc50db1bb94940fe53c6eba0 | [
"MIT"
] | 4 | 2019-04-01T17:33:38.000Z | 2022-01-08T04:07:52.000Z | Algorithm/ACM/Orientation Training Round #1 Div.1/F.cpp | XJDKC/University-Code-Archive | 2dd9c6edb2164540dc50db1bb94940fe53c6eba0 | [
"MIT"
] | null | null | null | Algorithm/ACM/Orientation Training Round #1 Div.1/F.cpp | XJDKC/University-Code-Archive | 2dd9c6edb2164540dc50db1bb94940fe53c6eba0 | [
"MIT"
] | 1 | 2021-01-06T11:04:31.000Z | 2021-01-06T11:04:31.000Z | #include<iostream>
#include<algorithm>
using namespace std;
int a[1000005]={0},maxnum=0;
unsigned int cal(unsigned int num)
{
if (num<1000001&&num>1&&a[num])
{
return a[num];
}
else if (num==1)
{
return 1;
}
else
{
if (num%2)
{
return 1 + cal(num * 3 + 1);
}
else
{
return (1 + cal(num / 2));
}
}
}
int main()
{
bool mark=false;
int x, y,maxn=0;
for (int i=1;i<1000001;i++)
{
if (!a[i])
{
a[i]=cal(i);
}
}
while (cin >> x >> y)
{
maxn = 0;
mark=false;
if (x>y)
{
swap(x,y);
mark=true;
}
for (int i = x; i <= y; i++)
{
maxn = max(a[i], maxn);
}
if (!mark) cout << x << " " << y << " " << maxn << endl;
else cout << y << " " << x << " " << maxn << endl;
}
return 0;
} | 13.563636 | 58 | 0.47319 | XJDKC |
18edc6c5281688e115fb0011230f113d87ea3f50 | 2,471 | hh | C++ | alps/include/alps/pegasus/mappable.hh | liujiawinds/sparkle | 23099cead99603a997803af9f66e17e17161faa2 | [
"Apache-2.0"
] | 40 | 2016-03-15T20:55:01.000Z | 2021-12-01T11:45:43.000Z | alps/include/alps/pegasus/mappable.hh | liujiawinds/sparkle | 23099cead99603a997803af9f66e17e17161faa2 | [
"Apache-2.0"
] | 18 | 2016-05-19T11:10:13.000Z | 2020-03-18T01:42:49.000Z | alps/include/alps/pegasus/mappable.hh | liujiawinds/sparkle | 23099cead99603a997803af9f66e17e17161faa2 | [
"Apache-2.0"
] | 19 | 2016-06-03T16:12:25.000Z | 2022-02-18T07:16:54.000Z | /*
* (c) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _ALPS_PEGASUS_MAPPABLE_HH_
#define _ALPS_PEGASUS_MAPPABLE_HH_
#include "../common/error_code.hh"
#include "pointer.hh"
#include "bits/segmap.hh"
namespace alps {
// forward declarations
class AddressSpace;
class RegionFile;
/**
* \brief A template mixin class for defining mappable region types.
*
* \details
* The MemoryMapImpl class defines the mapping policy that implements
* mapping of the underlying region file(s) onto the logical address space.
*
* The PointerImpl class defines smart pointer types for naming (addressing)
* and referencing locations within the region.
*
* There is no notion of a root pointer baked into the API. However, users may
* agree on a convention where offset 0x0 represents a root, and instantiate a
* smart pointer that points to offset 0x0 and use that as a root pointer.
*
*/
template<class RegionType, class MemoryMapImpl, class PointerImpl>
class Mappable: public RegionType {
friend class AddressSpace;
public:
Mappable(AddressSpace* address_space, RegionFile* file);
public:
// Pointer API
template<class T>
using TPtr = typename PointerImpl::template TPtr<Mappable,T>;
template<class T>
using PPtr = typename PointerImpl::template PPtr<Mappable,T>;
template<class T>
using ZPtr = typename PointerImpl::template ZPtr<Mappable,T>;
public:
// Mapping API
ErrorCode map();
ErrorCode unmap();
template<class T>
TPtr<T> base(LinearAddr offset)
{
//return TPtr<T>(this, offset);
void* base_ptr = reinterpret_cast<void*>(mem_map_->trans(offset));
return TPtr<T>(base_ptr);
}
uintptr_t trans(LinearAddr offset);
private:
MemoryMapImpl* mem_map_; // address space memory map
};
} // namespace alps
#include "bits/mappable.tcc"
#endif // _ALPS_PEGASUS_MAPPABLE_HH_
| 28.079545 | 79 | 0.726427 | liujiawinds |
18f0a76921521335b2ea6c2663514844d5b095b9 | 3,483 | cpp | C++ | codes/CF/CF_1427E.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null | codes/CF/CF_1427E.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null | codes/CF/CF_1427E.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | null | null | null |
//misaka and rin will carry me to cm
#include <iostream>
#include <cstdio>
#include <cstring>
#include <utility>
#include <cassert>
#include <algorithm>
#include <vector>
#include <array>
#include <tuple>
#include <random>
#include <chrono>
#define ll long long
#define lb long double
#define sz(vec) ((int)(vec.size()))
#define all(x) x.begin(), x.end()
const lb eps = 1e-9;
const ll mod = 1e9 + 7, ll_max = 1e18;
//const ll mod = (1 << (23)) * 119 +1;
const int MX = 2e5 +10, int_max = 0x3f3f3f3f;
using namespace std;
//i will learn from moo.
/* Input */
template<class T> void read(T &x) { cin >> x; }
template<class H, class T> void read(pair<H, T> &p) { cin >> p.first >> p.second; }
template<class T, size_t S> void read(array<T, S> &a) { for (T &i : a) read(i); }
template<class T> void read(vector<T> &v) { for (T &i : v) read(i); }
template<class H, class... T> void read(H &h, T &...t) { read(h); read(t...); }
/* Output */
template<class H, class T> ostream &operator<<(ostream &o, pair<H, T> &p) { o << p.first << " " << p.second; return o; }
template<class T, size_t S> ostream &operator<<(ostream &o, array<T, S> &a) { string s; for (T i : a) o << s << i, s = " "; return o; }
template<class T> ostream &operator<<(ostream &o, vector<T> &v) { string s; for (T i : v) o << s << i, s = " "; return o; }
template<class T> void write(T x) { cout << x; }
template<class H, class... T> void write(const H &h, const T &...t) { write(h); write(t...); }
void print() { write('\n'); }
template<class H, class... T> void print(const H &h, const T &...t) { write(h); if (sizeof...(t)) write(' '); print(t...); }
/* Misc */
template <typename T> void ckmin(T &a, const T &b) { a = min(a, b); }
template <typename T> void ckmax(T &a, const T &b) { a = max(a, b); }
inline int hsb(ll x){
assert(x > 0);
return 63-__builtin_clzll(x);
}
vector<ll> gen;
int ope = 0;
struct basis{
const int H = 63;
ll arr[70]; //64 actually
basis(){
memset(arr, 0, sizeof(arr));
}
ll B(int x){
return arr[x];
}
ll norm(ll x, int p = 0){
for(ll i = H; ~i; i--){
if(p){
print(B(i), '^', x);
if(B(i)^x) gen.push_back(B(i)^x);
ope++;
}
if(B(i) && ((x^B(i)) < x)){
x ^= B(i);
}
}
return x;
}
void insert(ll x){
if(x == 0) return ;
if(B(hsb(x)) == 0){
arr[hsb(x)] = x;
return ;
}
insert(norm(x, 1));
}
void erase(int x){
arr[x] = 0;
}
};
#define uid(a, b) uniform_int_distribution<int>(a, b)(rng)
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
void solve(){
//freopen("out.txt", "w", stdout);
const int bckt = 1400, tot = 1e5;
ll aa; read(aa);
ope++;
int scam = 44 - hsb(aa);
basis exist = basis();
cout << tot << "\n";
print(aa, '^', aa); //yes
for(ll t = aa; t<=(1ll << 44); t*=2ll){
print(t, '+', t);
ope++;
gen.push_back(t);
exist.insert(t);
if(t > (1ll << (44))) gen.push_back(t);
}
for(int i = 0; i<bckt; i++){
ll a = gen[uid(0, sz(gen)-1)], b = gen[uid(0, sz(gen)-1)];
//print(a, b);
while(a == b || (a + b) >= (1ll << 44)){
a = gen[uid(0, sz(gen)-1)], b = gen[uid(0, sz(gen)-1)];
//print(a, b, exist.norm(a+b), (a+b >= (1ll << 44)));
}
print(a, '+', b);
ope++;
exist.insert(a+b);
}
while(ope < tot){
ll a = gen[uid(0, sz(gen)-1)], b = gen[uid(0, sz(gen)-1)];
print(a, '^', b);
ope++;
}
assert(exist.B(0) > 0);
}
int main(){
cin.tie(0) -> sync_with_stdio(0);
int T = 1;
//cin >> T;
while(T--){
solve();
}
return 0;
}
| 23.856164 | 135 | 0.547229 | chessbot108 |
18f5c0e068b4c723f573524da3010fabfcbc1985 | 2,614 | cc | C++ | content/renderer/pepper/pepper_browser_connection.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | content/renderer/pepper/pepper_browser_connection.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/pepper/pepper_browser_connection.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/pepper/pepper_browser_connection.h"
#include <limits>
#include "base/logging.h"
#include "content/renderer/pepper/pepper_plugin_delegate_impl.h"
#include "content/renderer/render_view_impl.h"
#include "ipc/ipc_message_macros.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/proxy/resource_message_params.h"
namespace content {
PepperBrowserConnection::PepperBrowserConnection(
PepperPluginDelegateImpl* plugin_delegate)
: plugin_delegate_(plugin_delegate),
next_sequence_number_(1) {
}
PepperBrowserConnection::~PepperBrowserConnection() {
}
bool PepperBrowserConnection::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PepperBrowserConnection, msg)
IPC_MESSAGE_HANDLER(PpapiHostMsg_CreateResourceHostFromHostReply,
OnMsgCreateResourceHostFromHostReply)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void PepperBrowserConnection::SendBrowserCreate(
int child_process_id,
PP_Instance instance,
const IPC::Message& nested_msg,
const PendingResourceIDCallback& callback) {
int32_t sequence_number = GetNextSequence();
pending_create_map_[sequence_number] = callback;
ppapi::proxy::ResourceMessageCallParams params(0, sequence_number);
plugin_delegate_->render_view()->Send(
new PpapiHostMsg_CreateResourceHostFromHost(
child_process_id, params, instance, nested_msg));
}
void PepperBrowserConnection::OnMsgCreateResourceHostFromHostReply(
int32_t sequence_number,
int pending_resource_host_id) {
// Check that the message is destined for the plugin this object is associated
// with.
std::map<int32_t, PendingResourceIDCallback>::iterator it =
pending_create_map_.find(sequence_number);
if (it != pending_create_map_.end()) {
it->second.Run(pending_resource_host_id);
pending_create_map_.erase(it);
} else {
NOTREACHED();
}
}
int32_t PepperBrowserConnection::GetNextSequence() {
// Return the value with wraparound, making sure we don't make a sequence
// number with a 0 ID. Note that signed wraparound is undefined in C++ so we
// manually check.
int32_t ret = next_sequence_number_;
if (next_sequence_number_ == std::numeric_limits<int32_t>::max())
next_sequence_number_ = 1; // Skip 0 which is invalid.
else
next_sequence_number_++;
return ret;
}
} // namespace content
| 33.088608 | 80 | 0.764728 | pozdnyakov |
18f90c444b68cf7840eee9a0bd2bc08ee2daac98 | 3,643 | cpp | C++ | Hack and Slash/Hack and Slash/src/Math.cpp | JoanStinson/Hack_and_Slash | c76b5eea3455091c77fe35542bc773b3786d1896 | [
"MIT"
] | 2 | 2021-03-25T22:39:22.000Z | 2021-03-31T03:42:33.000Z | Hack and Slash/Hack and Slash/src/Math.cpp | JoanStinson/HackAndSlash | c76b5eea3455091c77fe35542bc773b3786d1896 | [
"MIT"
] | null | null | null | Hack and Slash/Hack and Slash/src/Math.cpp | JoanStinson/HackAndSlash | c76b5eea3455091c77fe35542bc773b3786d1896 | [
"MIT"
] | null | null | null | #include "Math.h"
#include <limits>
#include <algorithm>
namespace math {
bool math::collBetweenTwoRects(SDL_Rect &r1, SDL_Rect &r2) {
SDL_Rect intersection;
return SDL_IntersectRect(&r1, &r2, &intersection) ? true : false;
}
float math::angleBetweenTwoPoints(float x1, float y1, float x2, float y2) {
float dx = x2 - x1;
float dy = y2 - y1;
return atan2(dy, dx) * 180 / M_PI;
}
float math::angleBetweenTwoRects(SDL_Rect &r1, SDL_Rect &r2) {
float x1 = r1.x + (r1.w / 2);
float y1 = r1.y + (r1.h / 2);
float x2 = r2.x + (r2.w / 2);
float y2 = r2.y + (r2.h / 2);
return angleBetweenTwoPoints(x1, y1, x2, y2);
}
float math::distBetweenTwoPoints(float x1, float y1, float x2, float y2) {
return abs(sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)));
}
float math::distBetweenTwoRects(SDL_Rect &r1, SDL_Rect &r2) {
SDL_Point p1, p2;
p1.x = r1.x + r1.w / 2;
p1.y = r1.y + r1.h / 2;
p2.x = r2.x + r2.w / 2;
p2.y = r2.y + r2.h / 2;
return abs(sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2)));
}
/*! Return type: gives 0-1 depending on where collision is. 1 means, no collisions, 0 means collide immediately and 0.5 is half way etc.
* params: movingBox is entity being checked
* xv and vy are the velocities our moving box is moving at
* otherbox is some other entities collision box we may collide with
* normalx and normaly let us know which side of otherBox we collided with. these are pass by reference
*/
float math::sweptAABB(SDL_Rect &boxA, float vx, float vy, SDL_Rect &boxB, float &normalX, float &normalY) {
float xInvEntry, xInvExit;
float yInvEntry, yInvExit;
// Find the distance between the objects on the near and far sides or both x and y
if (vx > 0.0f) {
xInvEntry = boxB.x - (boxA.x + boxA.w);
xInvExit = (boxB.x + boxB.w) - boxA.x;
}
else {
xInvEntry = (boxB.x + boxB.w) - boxA.x;
xInvExit = boxB.x - (boxA.x + boxA.w);
}
if (vy > 0.0f) {
yInvEntry = boxB.y - (boxA.y + boxA.h);
yInvExit = (boxB.y + boxB.h) - boxA.y;
}
else {
yInvEntry = (boxB.y + boxB.h) - boxA.y;
yInvExit = boxB.y - (boxA.y + boxA.h);
}
// Find time of collision and time of leacing for each axis (if statement is to prevent dividing by zero)
float xEntry, xExit;
float yEntry, yExit;
if (vx == 0.0f) {
xEntry = -std::numeric_limits<float>::infinity();
xExit = std::numeric_limits<float>::infinity();
}
else {
xEntry = xInvEntry / vx;
xExit = xInvExit / vx;
}
if (vy == 0.0f) {
yEntry = -std::numeric_limits<float>::infinity();
yExit = std::numeric_limits<float>::infinity();
}
else {
yEntry = yInvEntry / vy;
yExit = yInvExit / vy;
}
// Find the earliest/latest times of collision
float entryTime = std::max(xEntry, yEntry);
float exitTime = std::min(xExit, yExit);
// If there was NO collision
if (entryTime > exitTime || xEntry < 0.0f && yEntry < 0.0f || xEntry > 1.0f || yEntry > 1.0f) {
normalX = 0.0f;
normalY = 0.0f;
return 1.0f;
}
else {
// There was a collision
// Work out which sides/normals of the otherbox we collided with
if (xEntry > yEntry) {
// Assume we hit otherbox on the x axis
if (xInvEntry < 0.0f) {
normalX = 1; // Hit right hand side
normalY = 0; // Not hit top or bottom
}
else {
normalX = -1; // Hit left hand side
normalY = 0; // Not hit top or bottom of box
}
}
else {
// Assume we hit otherbox on y axis
if (yEntry < 0.0f) {
normalX = 0;
normalY = 1;
}
else {
normalX = 0;
normalY = -1;
}
}
// Return the time of collision
return entryTime;
}
}
} | 26.985185 | 137 | 0.61625 | JoanStinson |
18fa3ce4f7cf2dd9e3ce3b109c46690492205261 | 1,565 | hpp | C++ | lib/tracer.hpp | ConteDevel/xpertium | dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a | [
"MIT"
] | null | null | null | lib/tracer.hpp | ConteDevel/xpertium | dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a | [
"MIT"
] | null | null | null | lib/tracer.hpp | ConteDevel/xpertium | dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a | [
"MIT"
] | null | null | null | #ifndef TRACER_HPP
#define TRACER_HPP
#include "rule.hpp"
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
namespace xpertium {
template <typename val_t>
class base_tracer_t {
public:
base_tracer_t() {}
virtual ~base_tracer_t() {}
virtual void push_fact(val_t fact) = 0;
virtual void push_rule(const rule_t<val_t> *rule, val_t out) = 0;
virtual void print() = 0;
virtual void clear() = 0;
};
template <typename val_t>
class tracer_t : public base_tracer_t<val_t> {
std::vector<std::string> m_trace;
public:
virtual void push_fact(val_t fact) override {
std::string str = "+ fact: <" + to_string(fact) + ">";
m_trace.push_back(std::move(str));
}
virtual void push_rule(const rule_t<val_t> *rule, val_t out) override {
std::string str = "+ ";
if (rule->target()) { str += "tget: "; }
else { str += "rule: "; }
str += "<" + rule->id() + "> -> <" + to_string(out) + ">";
m_trace.push_back(std::move(str));
}
virtual void print() override {
std::cout << "Trace: " << std::endl;
for (auto it = m_trace.begin(); it != m_trace.end(); ++it) {
std::cout << (*it) << std::endl;
}
}
virtual void clear() override { m_trace.clear(); }
private:
auto to_string(val_t val) {
if constexpr (std::is_same<val_t, std::string>::value) {
return static_cast<std::string>(val);
} else {
return std::to_string(val);
}
}
};
}
#endif // TRACER_HPP
| 25.241935 | 75 | 0.578914 | ConteDevel |
18fb0f180ee417fe44045c01b4643d4d5403283b | 3,064 | cpp | C++ | Huawei-EU-Challenge/BFS/PBFS3/CPU/wbfs.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | Huawei-EU-Challenge/BFS/PBFS3/CPU/wbfs.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | Huawei-EU-Challenge/BFS/PBFS3/CPU/wbfs.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | extern "C"
{
#include "graphio.h"
#include "graph.h"
}
#include <stdio.h>
#include <iostream>
#include <omp.h>
#include <fstream>
#include <limits.h>
#include <random>
#include <vector>
#define N 1
char gfile[2048];
using namespace std;
void printArray(int *x, int len) {
for (int i = 0; i < len; i++) {
cout << x[i] << " ";
}
cout << endl;
}
bool topDown(etype *row, vtype *col, int* distance, int &level, int nov) {
bool improvement = false;
#pragma omp parallel
{
#pragma omp for reduction(||:improvement) schedule(guided, 32)
for (int v = 0; v < nov; v++) {
if (distance[v] == level) {
for (int j = row[v]; j < row[v + 1]; j++) {
int u = col[j];
if (distance[u] < 0) {
distance[u] = level + 1;
improvement = true;
}
}
}
}
}
if (improvement) {
level++;
}
return improvement;
}
int main(int argc, char *argv[])
{
//GRAPH READ
etype *row_ptr;
vtype *col_ind;
ewtype *ewghts;
vwtype *vwghts;
vtype nov, source;
double start, end, total = 0;
const char* fname = argv[1]; // matrix file name
strcpy(gfile, fname);
int zerobased = atoi(argv[2]);
int dummy;
if (read_graph(gfile, &row_ptr, &col_ind, &ewghts, &vwghts, &nov, 0, zerobased, &dummy) == -1)
{
printf("error in graph read\n");
exit(1);
}
/*cout << "Vertices: " << nov << endl;
cout << "Edges: " << row_ptr[nov] << endl;
cout << "Avg degree: " << double(row_ptr[nov]) / double(nov) << endl;
int maxDegree = 0;
int minDegree = INT_MAX;
int d;
for (int i = 0; i < nov; i++) {
d = row_ptr[i + 1] - row_ptr[i];
if (maxDegree < d) maxDegree = d;
if (minDegree > d) minDegree = d;
}
cout << "Min & max degrees: " << minDegree << " & " << maxDegree << endl;*/
vector<int> sources;
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> rand(0, nov - 1);
for (int i = 0; i < N; i++) {
sources.push_back(rand(rng));
}
cout << "Sources: ";
for(int i = 0; i < N; i++) {
cout << sources[i] << " ";
}
cout << endl;
for (int t = 1; t <= 16; t = t * 2) {
total = 0;
for (int n = 0; n < N; n++) {
omp_set_dynamic(0);
omp_set_num_threads(t);
int *distance = new int[nov];
for (int i = 0; i < nov; i++) {
distance[i] = -1;
}
source = sources[n];
distance[source] = 0;
int level = 0;
bool improvement = true;
start = omp_get_wtime();
do {
improvement = topDown(row_ptr, col_ind, distance, level, nov);
} while (improvement);
end = omp_get_wtime();
total += end - start;
int traversed = 0;
for (int i = 0; i < nov; i++) {
if (distance[i] != -1) {
traversed++;
}
}
/*ofstream myfile;
string f = "test" + to_string(t) + ".txt";
myfile.open(f);
for (int x = 0; x < nov; x++)
myfile << to_string(distance[x]) << " ";
myfile << endl;
myfile.close();*/
delete[] distance;
cout << "Threads: " << t << "\tLevel: " << level << "\tDelta: " << nov - traversed << "\tTime: " << total << endl;
}
//cout << "Threads: " << t << "\tTime: " << total / N << endl;
}
return 0;
}
| 20.986301 | 116 | 0.562337 | JackBai0914 |
18ff5467385e0c0e2201d272009d823513ac52c1 | 4,829 | cpp | C++ | ui/osx/tabcontrol.cpp | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 28 | 2017-04-30T13:56:13.000Z | 2022-03-20T06:54:37.000Z | ui/osx/tabcontrol.cpp | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 72 | 2017-04-25T03:42:58.000Z | 2021-12-04T06:35:28.000Z | ui/osx/tabcontrol.cpp | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 12 | 2017-04-16T06:25:24.000Z | 2021-07-07T13:28:27.000Z | // ------------------------------------------------
// tabcontrol.cpp
// PeerCast
//
// Created by mode7 on Fri Apr 02 2004.
// Copyright (c) 2002-2004 peercast.org. All rights reserved.
// ------------------------------------------------
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// ------------------------------------------------
#include "tabcontrol.h"
#include "osxapp.h"
static int tabList[] = { 2, 1001, 1002 };
static ControlID skTabItemID = { 'PCTB', 0 };
TabControl::TabControl( const int signature, const int id, WindowRef windowRef )
:mControlID ( )
, mWindowRef ( windowRef )
, mEventHandler ( TabControl::handler )
, mYPAddress ('PCCG', 1000)
, mDJMessage ('PCCG', 1001)
, mPassword ('PCCG', 1002)
, mMaxRelays ('PCCG', 1003)
, mLastTabIndex ( 1 )
{
mControlID.signature = signature;
mControlID.id = id;
setInitialTab( windowRef );
}
OSStatus TabControl::installHandler()
{
ControlRef tabControlRef;
static const EventTypeSpec tabControlEvents[] =
{
{ kEventClassControl, kEventControlHit }
, { kEventClassWindow, kEventWindowActivated }
};
GetControlByID( getWindow(), &getID(), &tabControlRef );
return InstallControlEventHandler( tabControlRef
, mEventHandler.eventHandler()
, GetEventTypeCount(tabControlEvents)
, tabControlEvents
, this
, NULL );
}
//------------------------------------------------------------------------
void TabControl::updateSettings()
{
if( !servMgr || !chanMgr )
return;
mLock.on();
mYPAddress.setText( mWindowRef, servMgr->rootHost );
mDJMessage.setText( mWindowRef, chanMgr->broadcastMsg );
mPassword.setText( mWindowRef, servMgr->password );
mMaxRelays.setIntValue( mWindowRef, servMgr->maxRelays );
mLock.off();
}
//------------------------------------------------------------------------
void TabControl::saveSettings()
{
if( !servMgr || !chanMgr )
return;
mLock.on();
chanMgr->broadcastMsg.set(mDJMessage.getString( mWindowRef, kCFStringEncodingUnicode ), String::T_ASCII);
servMgr->rootHost = mYPAddress.getString( mWindowRef, kCFStringEncodingASCII );
strncpy( servMgr->password, mPassword.getString( mWindowRef, kCFStringEncodingASCII ), 64 );
servMgr->setMaxRelays( mMaxRelays.getIntValue( mWindowRef ) );
mLock.off();
}
//------------------------------------------------------------------------
void TabControl::setInitialTab(WindowRef window)
{
ControlID controlID = skTabItemID;
for(short i=1; i<tabList[0]+1; ++i)
{
controlID.id = tabList[i];
SetControlVisibility( getControlRef( window, controlID ), false, true );
}
// set
SetControlValue( getControlRef(window, mControlID), mLastTabIndex );
controlID.id = tabList[mLastTabIndex];
SetControlVisibility( getControlRef(window, controlID), true, true );
}
ControlRef TabControl::getControlRef( WindowRef window, const ControlID& controlID )
{
ControlRef controlRef = NULL;
GetControlByID( window, &controlID, &controlRef );
return controlRef;
}
OSStatus TabControl::handler( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData )
{
switch( GetEventKind( inEvent ) )
{
case kEventControlHit:
{
TabControl& tControl = *static_cast<TabControl *>(inUserData);
WindowRef window = static_cast<WindowRef>(tControl.getWindow());
ControlRef tabControl = getControlRef( window, tControl.getID() );
const short controlValue = GetControlValue( tabControl );
if( controlValue != tControl.mLastTabIndex )
{
tControl.updateSettings();
switchItem( window, tabControl, controlValue );
tControl.mLastTabIndex = controlValue;
return noErr;
}
}
break;
}
return eventNotHandledErr;
}
void TabControl::switchItem( WindowRef window, ControlRef tabControl, const short currentTabIndex )
{
ControlRef selectedPaneControl = NULL;
ControlID controlID = skTabItemID;
for(short i=1; i<tabList[0]+1; ++i)
{
controlID.id = tabList[i];
ControlRef userPaneControl = getControlRef( window, controlID );
if( i == currentTabIndex )
{
selectedPaneControl = userPaneControl;
}
else
{
SetControlVisibility( userPaneControl, false, true );
}
}
if( selectedPaneControl != NULL )
{
(void)ClearKeyboardFocus( window );
SetControlVisibility( selectedPaneControl, true, true );
}
Draw1Control( tabControl );
} | 28.916168 | 106 | 0.6579 | plonk |
7a03aedfb9c28a9dd5dbd06551bede105e01773e | 15,976 | cpp | C++ | teapoy/src/sni/sys.cpp | lyramilk/teapoy | 5b450a243432b058512ed7b1c6f810cb0d207f91 | [
"Apache-2.0"
] | 1 | 2017-09-07T02:28:58.000Z | 2017-09-07T02:28:58.000Z | teapoy/src/sni/sys.cpp | lyramilk/teapoy | 5b450a243432b058512ed7b1c6f810cb0d207f91 | [
"Apache-2.0"
] | null | null | null | teapoy/src/sni/sys.cpp | lyramilk/teapoy | 5b450a243432b058512ed7b1c6f810cb0d207f91 | [
"Apache-2.0"
] | null | null | null | #include <libmilk/scriptengine.h>
#include <libmilk/log.h>
#include <libmilk/dict.h>
#include <libmilk/codes.h>
#include <libmilk/json.h>
#include <libmilk/sha1.h>
#include <libmilk/md5.h>
#include <libmilk/inotify.h>
#include "script.h"
#include "env.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>
#include <errno.h>
namespace lyramilk{ namespace teapoy{ namespace native
{
static lyramilk::log::logss log(lyramilk::klog,"teapoy.native");
lyramilk::data::var teapoy_import(const lyramilk::data::array& args,const lyramilk::data::map& senv)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
lyramilk::data::map::const_iterator it_env_eng = senv.find(lyramilk::script::engine::s_env_engine());
if(it_env_eng != senv.end()){
lyramilk::data::datawrapper* urd = it_env_eng->second.userdata();
if(urd && urd->name() == lyramilk::script::engine_datawrapper::class_name()){
lyramilk::script::engine_datawrapper* urdp = (lyramilk::script::engine_datawrapper*)urd;
if(urdp->eng){
// 在文件所在目录查找包含文件
lyramilk::data::string filename = urdp->eng->filename();
std::size_t pos = filename.rfind('/');
if(pos != filename.npos){
filename = filename.substr(0,pos + 1) + args[0].str();
}
// 在环境变量指定的目录中查找文件。
struct stat st = {0};
if(0 !=::stat(filename.c_str(),&st)){
filename = env::get(urdp->eng->name() + ".require").str();
if(!filename.empty() && filename.at(filename.size() - 1) != '/') filename.push_back('/');
filename += args[0].str();
}
// 写入包含信息,防止重复载入
lyramilk::data::var& v = urdp->eng->get_userdata("require");
v.type(lyramilk::data::var::t_array);
lyramilk::data::array& ar = v;
lyramilk::data::array::iterator it = ar.begin();
for(;it!=ar.end();++it){
lyramilk::data::string str = *it;
if(str == args[0].str()){
//log(lyramilk::log::warning,__FUNCTION__) << D("请不要重复包含文件%s",str.c_str()) << std::endl;
return false;
}
}
ar.push_back(args[0].str());
// 执行包含文件。
if(urdp->eng->load_module(filename)){
return true;
}
}
}
}
return false;
}
struct engineitem
{
lyramilk::data::string filename;
lyramilk::data::string type;
lyramilk::data::array args;
unsigned long long msec;
};
static void* thread_task(void* _p)
{
engineitem* p = (engineitem*)_p;
engineitem ei = *p;
delete p;
struct stat st0;
while(0 !=::stat(ei.filename.c_str(),&st0)){
sleep(10);
}
lyramilk::script::engines* pool = engine_pool::instance()->get("js");
lyramilk::script::engines::ptr eng = pool->get();
if(!eng){
log(lyramilk::log::error,"task") << D("获取启动脚本失败") << std::endl;
return nullptr;
}
while(!eng->load_file(ei.filename)){
sleep(10);
}
while(true){
struct stat st1;
while(0 !=::stat(ei.filename.c_str(),&st1)){
sleep(10);
}
if(st1.st_mtime != st0.st_mtime){
st0.st_mtime = st1.st_mtime;
log(lyramilk::log::warning,"task") << D("重新加载%s",ei.filename.c_str()) << std::endl;
eng->reset();
eng->load_file(ei.filename);
}
lyramilk::data::var v;
if(eng->call("ontimer",ei.args,&v)){
if(v.type() == lyramilk::data::var::t_bool && (bool)v == false)break;
}
eng->gc();
usleep(ei.msec * 1000);
};
pthread_exit(0);
return nullptr;
}
static void* thread_once_task(void* _p)
{
engineitem* p = (engineitem*)_p;
engineitem ei = *p;
delete p;
struct stat st0;
while(0 !=::stat(ei.filename.c_str(),&st0)){
sleep(10);
}
lyramilk::script::engine* eng = engine_pool::instance()->create_script_instance("js");
if(!eng){
log(lyramilk::log::error,"once_task") << D("获取启动脚本失败") << std::endl;
return nullptr;
}
while(!eng->load_file(ei.filename)){
sleep(10);
}
do{
struct stat st1;
while(0 !=::stat(ei.filename.c_str(),&st1)){
sleep(10);
}
if(st1.st_mtime != st0.st_mtime){
st0.st_mtime = st1.st_mtime;
log(lyramilk::log::warning,"once_task") << D("重新加载%s",ei.filename.c_str()) << std::endl;
eng->reset();
eng->load_file(ei.filename);
}
lyramilk::data::var v;
if(eng->call("onthread",ei.args,&v)){
if(v.type() == lyramilk::data::var::t_bool && (bool)v == false)break;
}
eng->gc();
}while(false);
engine_pool::instance()->destory_script_instance("js",eng);
pthread_exit(0);
return nullptr;
}
lyramilk::data::var task(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_int);
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,2,lyramilk::data::var::t_str);
pthread_t id_1;
engineitem* p = new engineitem;
p->type = args[0].str();
p->msec = args[1];
p->filename = args[2].str();
if(args.size() > 3){
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,3,lyramilk::data::var::t_array);
p->args = args[3];
}
int ret = pthread_create(&id_1,NULL,thread_task,p);
pthread_detach(id_1);
return 0 == ret;
}
lyramilk::data::var task_once(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_str);
pthread_t id_1;
engineitem* p = new engineitem;
p->type = args[0].str();
p->filename = args[1].str();
if(args.size() > 2){
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,2,lyramilk::data::var::t_array);
p->args = args[2];
}
int ret = pthread_create(&id_1,NULL,thread_once_task,p);
pthread_detach(id_1);
return 0 == ret;
}
lyramilk::data::var daemon(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
::daemon(1,0);
return true;
}
lyramilk::data::var crand(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
if(args.size() > 0){
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_int);
unsigned int seed = args[0];
srand(seed);
}
return rand();
}
lyramilk::data::var msleep(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_int);
unsigned long long usecond = args[0];
return usleep(usecond * 1000);
}
lyramilk::data::var su(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
lyramilk::data::string username = args[0];
// useradd -s /sbin/nologin username
struct passwd *pw = getpwnam(username.c_str());
if(pw){
if(setgid(pw->pw_gid) == 0 && setuid(pw->pw_uid) == 0){
log(__FUNCTION__) << D("切换到用户[%s]",username.c_str()) << std::endl;
log(__FUNCTION__) << D("切换到用户组[%s]",username.c_str()) << std::endl;
return true;
}
}
log(lyramilk::log::warning,__FUNCTION__) << D("切换到用户[%s]失败%s",username.c_str(),strerror(errno)) << std::endl;
return false;
}
lyramilk::data::var add_require_dir(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
TODO();
return true;
}
lyramilk::data::var serialize(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
if(args.size() < 1) throw lyramilk::exception(D("%s参数不足",__FUNCTION__));
lyramilk::data::var v = args[0];
lyramilk::data::stringstream ss;
v.serialize(ss);
lyramilk::data::string str = ss.str();
lyramilk::data::chunk bstr((const unsigned char*)str.c_str(),str.size());
return bstr;
}
lyramilk::data::var deserialize(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_bin);
lyramilk::data::string seq = args[0];
lyramilk::data::var v;
lyramilk::data::stringstream ss(seq);
v.deserialize(ss);
return v;
}
lyramilk::data::var json_stringify(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
if(args.size() < 1) throw lyramilk::exception(D("%s参数不足",__FUNCTION__));
lyramilk::data::string jsonstr;
lyramilk::data::var v = args[0];
lyramilk::data::json::stringify(v,&jsonstr);
return jsonstr;
}
lyramilk::data::var json_parse(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
lyramilk::data::var v;
lyramilk::data::json::parse(args[0],&v);
return v;
}
lyramilk::data::var system(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
lyramilk::data::string str = args[0];
lyramilk::data::string ret;
FILE *pp = popen(str.c_str(), "r");
char tmp[1024];
while (fgets(tmp, sizeof(tmp), pp) != NULL) {
ret.append(tmp);
}
pclose(pp);
return ret;
}
lyramilk::data::var decode(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_str);
lyramilk::data::string type = args[0];
lyramilk::data::string str = args[1];
return lyramilk::data::codes::instance()->decode(type,str);
}
lyramilk::data::var encode(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_str);
lyramilk::data::string type = args[0];
lyramilk::data::string str = args[1];
return lyramilk::data::codes::instance()->encode(type,str);
}
lyramilk::data::var sha1(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
lyramilk::data::string str = args[0];
lyramilk::cryptology::sha1 c1;
c1 << str;
return c1.get_key().str();
}
lyramilk::data::var md5_16(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
lyramilk::data::string str = args[0];
lyramilk::cryptology::md5 c1;
c1 << str;
return c1.get_key().str16();
}
lyramilk::data::var md5_32(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
lyramilk::data::string str = args[0];
lyramilk::cryptology::md5 c1;
c1 << str;
return c1.get_key().str32();
}
lyramilk::data::string inline md5(lyramilk::data::string str)
{
lyramilk::cryptology::md5 c1;
c1 << str;
return c1.get_key().str32();
}
lyramilk::data::var http_digest_authentication(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str);
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_map);
lyramilk::data::string emptystr;
lyramilk::data::string algorithm = args[0];
lyramilk::data::map m = args[1];
lyramilk::data::string realm = m["realm"].conv(emptystr);
if(realm.empty()) return lyramilk::data::var::nil;
lyramilk::data::string nonce = m["nonce"].conv(emptystr);
if(nonce.empty()) return lyramilk::data::var::nil;
lyramilk::data::string cnonce = m["cnonce"].conv(emptystr);
if(cnonce.empty()) return lyramilk::data::var::nil;
lyramilk::data::string nc = m["nc"].conv(emptystr);
if(nc.empty()) return lyramilk::data::var::nil;
lyramilk::data::string qop = m["qop"].conv(emptystr);
if(qop.empty()) return lyramilk::data::var::nil;
lyramilk::data::string uri = m["uri"].conv(emptystr);
if(uri.empty()) return lyramilk::data::var::nil;
lyramilk::data::string method = m["method"].conv(emptystr);
if(method.empty()) return lyramilk::data::var::nil;
lyramilk::data::string HA1 = m["HA1"].conv(emptystr);
lyramilk::data::string HA2 = m["HA2"].conv(emptystr);
lyramilk::data::string HD = m["HD"].conv(emptystr);
if(HA1.empty()){
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,2,lyramilk::data::var::t_str);
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,3,lyramilk::data::var::t_str);
lyramilk::data::string username = args[2];
lyramilk::data::string password = args[3];
if(algorithm == "MD5"){
HA1 = md5(username + ":" + realm + ":" + password);
}else if(algorithm == "MD5-sess"){
HA1 = md5(md5(username + ":" + realm + ":" + password) + ":" + nonce + ":" + cnonce);
}
}
if(qop == "auth-int"){
lyramilk::data::string body = m["body"].conv(emptystr);
if(body.empty()) return lyramilk::data::var::nil;
if(HD.empty()) HD = nonce + ":" + nc + ":" + cnonce + ":" + qop;
if(uri.empty()){
}else{
if(HA2.empty()) HA2 = md5(method + ":" + uri + ":" + md5(body));
}
}else if(qop == ""){
if(HD.empty()) HD = nonce;
if(uri.empty()){
if(HA2.empty()) HA2 = md5(method);
}else{
if(HA2.empty()) HA2 = md5(method + ":" + uri);
}
}else if(qop == "auth"){
if(HD.empty()) HD = nonce + ":" + nc + ":" + cnonce + ":" + qop;
if(uri.empty()){
if(HA2.empty()) HA2 = md5(method);
}else{
if(HA2.empty()) HA2 = md5(method + ":" + uri);
}
}else{
return lyramilk::data::var::nil;
}
return md5(HA1 + ":" + HD + ":" + HA2);
}
lyramilk::data::var bin2str(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_bin);
return args[0].str();
}
lyramilk::data::var srand(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_int);
int seed = args[0];
::srand(seed);
return true;
}
lyramilk::data::var rand(const lyramilk::data::array& args,const lyramilk::data::map& env)
{
return ::rand();
}
static int define(lyramilk::script::engine* p)
{
int i = 0;
{
p->define("require",teapoy_import);++i;
p->define("task",task);++i;
p->define("create_thread",task_once);++i;
p->define("daemon",daemon);++i;
p->define("crand",crand);++i;
p->define("msleep",msleep);++i;
p->define("su",su);++i;
p->define("add_require_dir",add_require_dir);++i;
p->define("serialize",serialize);++i;
p->define("deserialize",deserialize);++i;
p->define("json_stringify",json_stringify);++i;
p->define("json_parse",json_parse);++i;
p->define("system",system);++i;
p->define("decode",decode);++i;
p->define("encode",encode);++i;
p->define("sha1",sha1);++i;
p->define("md5_16",md5_16);++i;
p->define("md5_32",md5_32);++i;
p->define("md5",md5_32);++i;
p->define("bin2str",bin2str);++i;
p->define("srand",srand);++i;
p->define("rand",rand);++i;
p->define("http_digest_authentication",http_digest_authentication);++i;
}
return i;
}
static __attribute__ ((constructor)) void __init()
{
lyramilk::teapoy::script_interface_master::instance()->regist("sys",define);
}
}}} | 31.264188 | 113 | 0.659176 | lyramilk |
7a0452eb3f7c791a6759324a8cc74c66ba20d538 | 1,190 | hpp | C++ | components/esm/records.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | components/esm/records.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | components/esm/records.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #ifndef OPENMW_ESM_RECORDS_H
#define OPENMW_ESM_RECORDS_H
#include "defs.hpp"
#include "loadacti.hpp"
#include "loadalch.hpp"
#include "loadappa.hpp"
#include "loadarmo.hpp"
#include "loadbody.hpp"
#include "loadbook.hpp"
#include "loadbsgn.hpp"
#include "loadcell.hpp"
#include "loadclas.hpp"
#include "loadclot.hpp"
#include "loadcont.hpp"
#include "loadcrea.hpp"
#include "loadcrec.hpp"
#include "loadinfo.hpp"
#include "loaddial.hpp"
#include "loaddoor.hpp"
#include "loadench.hpp"
#include "loadfact.hpp"
#include "loadglob.hpp"
#include "loadgmst.hpp"
#include "loadingr.hpp"
#include "loadland.hpp"
#include "loadlevlist.hpp"
#include "loadligh.hpp"
#include "loadlock.hpp"
#include "loadrepa.hpp"
#include "loadprob.hpp"
#include "loadltex.hpp"
#include "loadmgef.hpp"
#include "loadmisc.hpp"
#include "loadnpc.hpp"
#include "loadnpcc.hpp"
#include "loadpgrd.hpp"
#include "loadrace.hpp"
#include "loadregn.hpp"
#include "loadscpt.hpp"
#include "loadskil.hpp"
#include "loadsndg.hpp"
#include "loadsoun.hpp"
#include "loadspel.hpp"
#include "loadsscr.hpp"
#include "loadstat.hpp"
#include "loadweap.hpp"
// Special records which are not loaded from ESM
#include "attr.hpp"
#endif
| 22.884615 | 48 | 0.755462 | Bodillium |
bb400e14e0d7088770b63a16f1268300e13aa728 | 13,786 | cpp | C++ | src/event_schedule_manager/EventScheduleContainer.cpp | ysan/atpp | 46ff6c836778e8cc3f2677d9ab630778253ec796 | [
"MIT"
] | 4 | 2021-01-31T02:43:08.000Z | 2021-10-06T15:23:29.000Z | src/event_schedule_manager/EventScheduleContainer.cpp | ysan/atpp | 46ff6c836778e8cc3f2677d9ab630778253ec796 | [
"MIT"
] | 1 | 2020-12-28T17:09:11.000Z | 2020-12-28T17:09:11.000Z | src/event_schedule_manager/EventScheduleContainer.cpp | ysan/atpp | 46ff6c836778e8cc3f2677d9ab630778253ec796 | [
"MIT"
] | 1 | 2019-12-03T03:52:19.000Z | 2019-12-03T03:52:19.000Z | #include <string.h>
#include <unistd.h>
#include <errno.h>
#include "EventScheduleContainer.h"
CEventScheduleContainer::CEventScheduleContainer (void)
:mp_settings (NULL)
{
mp_settings = CSettings::getInstance();
m_sched_map_json_path.clear();
m_sched_map.clear ();
}
CEventScheduleContainer::~CEventScheduleContainer (void)
{
mp_settings = NULL;
m_sched_map_json_path.clear();
m_sched_map.clear ();
}
void CEventScheduleContainer::setScheduleMapJsonPath (std::string sched_map_json_path)
{
m_sched_map_json_path = sched_map_json_path;
}
bool CEventScheduleContainer::addScheduleMap (const SERVICE_KEY_t &key, std::vector <CEvent*> *p_sched)
{
if (!p_sched || p_sched->size() == 0) {
return false;
}
// m_sched_map.insert (pair<SERVICE_KEY_t, std::vector <CEvent*> *>(key, p_sched));
std::vector<std::unique_ptr<CEvent>> *_p_sched = new std::vector<std::unique_ptr<CEvent>>;
for (const auto e : *p_sched) {
std::unique_ptr<CEvent> up_e (e);
_p_sched->push_back (std::move(up_e));
}
std::unique_ptr<std::vector<std::unique_ptr<CEvent>>> _up_sched(_p_sched);
m_sched_map.insert (std::make_pair(key, std::move(_up_sched)));
return true;
}
void CEventScheduleContainer::deleteScheduleMap (const SERVICE_KEY_t &key)
{
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.find (key);
const auto iter = m_sched_map.find (key);
if (iter == m_sched_map.end()) {
return ;
}
// std::vector <CEvent*> *p_sched = iter->second;
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
// clearSchedule (p_sched);
clearSchedule (*p_sched);
// delete p_sched;
m_sched_map.erase (iter);
}
bool CEventScheduleContainer::hasScheduleMap (const SERVICE_KEY_t &key) const
{
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.find (key);
const auto iter = m_sched_map.find (key);
if (iter == m_sched_map.end()) {
return false;
} else {
// std::vector <CEvent*> *p_sched = iter->second;
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
if (!p_sched || (p_sched->size() == 0)) {
return false;
}
}
return true;
}
void CEventScheduleContainer::dumpScheduleMap (void) const
{
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.begin ();
auto iter = m_sched_map.cbegin ();
if (iter == m_sched_map.end()) {
return ;
}
for (; iter != m_sched_map.end(); ++ iter) {
SERVICE_KEY_t key = iter->first;
key.dump();
// std::vector <CEvent*> *p_sched = iter->second;
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
if (p_sched) {
_UTL_LOG_I (" [%d] items", p_sched->size());
}
}
}
void CEventScheduleContainer::dumpScheduleMap (const SERVICE_KEY_t &key) const
{
if (!hasScheduleMap (key)) {
_UTL_LOG_I ("not hasScheduleMap...");
return ;
}
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.find (key);
const auto iter = m_sched_map.find (key);
if (iter == m_sched_map.end()) {
return ;
} else {
// std::vector <CEvent*> *p_sched = iter->second;
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
if (!p_sched || (p_sched->size() == 0)) {
return ;
} else {
// dumpSchedule (p_sched);
dumpSchedule (*p_sched);
}
}
}
const CEvent *CEventScheduleContainer::getEvent (const SERVICE_KEY_t &key, uint16_t event_id) const
{
if (!hasScheduleMap (key)) {
_UTL_LOG_I ("not hasScheduleMap...");
return NULL;
}
CEvent *r = NULL;
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.find (key);
const auto iter = m_sched_map.find (key);
if (iter == m_sched_map.end()) {
return NULL;
} else {
// std::vector <CEvent*> *p_sched = iter->second;
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
if (p_sched->size() == 0) {
return NULL;
} else {
// std::vector<CEvent*>::const_iterator iter_event = p_sched->begin();
std::vector<std::unique_ptr<CEvent>>::const_iterator iter_event = p_sched->begin();
for (; iter_event != p_sched->end(); ++ iter_event) {
// CEvent* p = *iter_event;
CEvent* p = iter_event->get();
if (
(p->transport_stream_id == key.transport_stream_id) &&
(p->original_network_id == key.original_network_id) &&
(p->service_id == key.service_id) &&
(p->event_id == event_id)
) {
r = p;
break;
}
}
}
}
return r;
}
const CEvent *CEventScheduleContainer::getEvent (const SERVICE_KEY_t &key, int index) const
{
if (!hasScheduleMap (key)) {
_UTL_LOG_I ("not hasScheduleMap...");
return NULL;
}
CEvent *r = NULL;
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.find (key);
const auto iter = m_sched_map.find (key);
if (iter == m_sched_map.end()) {
return NULL;
} else {
// std::vector <CEvent*> *p_sched = iter->second;
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
if (p_sched->size() == 0) {
return NULL;
} else {
int _idx = 0;
// std::vector<CEvent*>::const_iterator iter_event = p_sched->begin();
std::vector<std::unique_ptr<CEvent>>::const_iterator iter_event = p_sched->begin();
for (; iter_event != p_sched->end(); ++ iter_event) {
if (index == _idx) {
// CEvent* p = *iter_event;
CEvent* p = iter_event->get();
r = p;
break;
}
++ _idx;
}
}
}
return r;
}
int CEventScheduleContainer::getEvents (
const char *p_keyword,
CEventScheduleManagerIf::EVENT_t *p_out_events,
int out_array_num,
bool is_check_extendedEvent
) const
{
if (!p_keyword || !p_out_events || out_array_num <= 0) {
return -1;
}
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.begin ();
auto iter = m_sched_map.cbegin ();
if (iter == m_sched_map.end()) {
return 0;
}
int n = 0;
for (; iter != m_sched_map.end(); ++ iter) {
if (out_array_num == 0) {
break;
}
// std::vector <CEvent*> *p_sched = iter->second;
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
if (p_sched) {
// std::vector<CEvent*>::const_iterator iter_event = p_sched->begin();
std::vector<std::unique_ptr<CEvent>>::const_iterator iter_event = p_sched->begin();
for (; iter_event != p_sched->end(); ++ iter_event) {
if (out_array_num == 0) {
break;
}
// CEvent* p_event = *iter_event;
CEvent* p_event = iter_event->get();
if (p_event) {
char *s_evt_name = NULL;
char *s_evt_text = NULL;
char *s_ex_item_desc = NULL;
char *s_ex_item = NULL;
if (is_check_extendedEvent) {
// check event text
s_evt_text = strstr ((char*)p_event->text.c_str(), p_keyword);
// check extened event
std::vector<CEvent::CExtendedInfo>::const_iterator iter_ex = p_event->extendedInfos.begin();
for (; iter_ex != p_event->extendedInfos.end(); ++ iter_ex) {
s_ex_item_desc = strstr ((char*)iter_ex->item_description.c_str(), p_keyword);
s_ex_item = strstr ((char*)iter_ex->item.c_str(), p_keyword);
if (s_ex_item_desc || s_ex_item) {
break;
}
}
// debug dump
if (s_evt_text || s_ex_item_desc || s_ex_item) {
_UTL_LOG_I ("====================================");
_UTL_LOG_I ("==== keyword:[%s] ====", p_keyword);
_UTL_LOG_I ("====================================");
p_event->dump();
p_event->dump_detail();
}
} else {
// check event name
s_evt_name = strstr ((char*)p_event->event_name.c_str(), p_keyword);
}
// check result
if (s_evt_name || s_evt_text || s_ex_item_desc || s_ex_item) {
p_out_events->transport_stream_id = p_event->transport_stream_id;
p_out_events->original_network_id = p_event->original_network_id;
p_out_events->service_id = p_event->service_id;
p_out_events->event_id = p_event->event_id;
p_out_events->start_time = p_event->start_time;
p_out_events->end_time = p_event->end_time;
// アドレスで渡してますが 基本的には schedule casheが走らない限り
// アドレスは変わらない前提です
p_out_events->p_event_name = &p_event->event_name;
p_out_events->p_text = &p_event->text;
++ p_out_events;
-- out_array_num;
++ n;
}
}
}
}
}
return n;
}
//void CEventScheduleContainer::clearSchedule (std::vector <CEvent*> *p_sched)
void CEventScheduleContainer::clearSchedule (std::vector<std::unique_ptr<CEvent>> &sched)
{
// if (!p_sched || p_sched->size() == 0) {
if (sched.size() == 0) {
return;
}
// std::vector<CEvent*>::const_iterator iter = p_sched->begin();
// for (; iter != p_sched->end(); ++ iter) {
// CEvent* p = *iter;
// if (p) {
// p->clear();
// delete p;
// }
// }
// p_sched->clear();
sched.clear();
}
//void CEventScheduleContainer::dumpSchedule (const std::vector <CEvent*> *p_sched) const
void CEventScheduleContainer::dumpSchedule (const std::vector<std::unique_ptr<CEvent>> &sched) const
{
// if (!p_sched || p_sched->size() == 0) {
if (sched.size() == 0) {
return;
}
int i = 0;
// std::vector<CEvent*>::const_iterator iter = p_sched->begin();
std::vector<std::unique_ptr<CEvent>>::const_iterator iter = sched.begin();
// for (; iter != p_sched->end(); ++ iter) {
for (; iter != sched.end(); ++ iter) {
// CEvent* p = *iter;
CEvent* p = (*iter).get();
if (p) {
_UTL_LOG_I ("-----------------------------------");
_UTL_LOG_I ("[[[ %d ]]]", i);
_UTL_LOG_I ("-----------------------------------");
p->dump();
++ i;
}
}
}
void CEventScheduleContainer::clear (void)
{
// std::map <SERVICE_KEY_t, std::vector <CEvent*> *> ::const_iterator iter = m_sched_map.begin ();
auto iter = m_sched_map.cbegin ();
if (iter == m_sched_map.end()) {
m_sched_map.clear();
return ;
}
for (; iter != m_sched_map.end(); ++ iter) {
SERVICE_KEY_t key = iter->first;
deleteScheduleMap (key);
iter = m_sched_map.begin (); // renew iter
}
m_sched_map.clear();
}
void CEventScheduleContainer::saveScheduleMap (void)
{
std::stringstream ss;
{
cereal::JSONOutputArchive out_archive (ss);
out_archive (CEREAL_NVP(m_sched_map));
}
if (m_sched_map_json_path.length() == 0) {
_UTL_LOG_E("m_sched_map_json_path.length 0.");
return;
}
std::ofstream ofs (m_sched_map_json_path.c_str(), std::ios::out);
ofs << ss.str();
ofs.close();
ss.clear();
}
void CEventScheduleContainer::loadScheduleMap (void)
{
if (m_sched_map_json_path.length() == 0) {
_UTL_LOG_I("m_sched_map_json_path.length 0.");
return;
}
std::ifstream ifs (m_sched_map_json_path.c_str(), std::ios::in);
if (!ifs.is_open()) {
_UTL_LOG_I("[%s] is not found.", m_sched_map_json_path.c_str());
return;
}
std::stringstream ss;
ss << ifs.rdbuf();
cereal::JSONInputArchive in_archive (ss);
in_archive (CEREAL_NVP(m_sched_map));
ifs.close();
ss.clear();
// CEtimeの値は直接 tv_sec,tv_nsecに書いてるので toString用の文字はここで作ります
auto iter = m_sched_map.cbegin ();
for (; iter != m_sched_map.end(); ++ iter) {
std::vector <std::unique_ptr<CEvent>> *p_sched = iter->second.get();
if (p_sched) {
auto iter_event = p_sched->cbegin();
for (; iter_event != p_sched->end(); ++ iter_event) {
CEvent* p_event = iter_event->get();
if (p_event) {
p_event->start_time.updateStrings();
p_event->end_time.updateStrings();
}
}
}
}
}
//--------------------------------------------------------------------------------
template <class Archive>
void serialize (Archive &archive, struct _service_key &k)
{
archive (
cereal::make_nvp("transport_stream_id", k.transport_stream_id)
,cereal::make_nvp("original_network_id", k.original_network_id)
,cereal::make_nvp("service_id", k.service_id)
,cereal::make_nvp("service_type", k.service_type)
,cereal::make_nvp("service_name", k.service_name)
);
}
template <class Archive>
void serialize (Archive &archive, struct timespec &t)
{
archive (
cereal::make_nvp("tv_sec", t.tv_sec)
,cereal::make_nvp("tv_nsec", t.tv_nsec)
);
}
template <class Archive>
void serialize (Archive &archive, CEtime &t)
{
archive (
cereal::make_nvp("m_time", t.m_time)
);
}
template <class Archive>
void serialize (Archive &archive, CEvent::CExtendedInfo &ex)
{
archive (
cereal::make_nvp("item_description", ex.item_description)
,cereal::make_nvp("item", ex.item)
);
}
template <class Archive>
void serialize (Archive &archive, CEvent::CGenre &g)
{
archive (
cereal::make_nvp("content_nibble_level_1", g.content_nibble_level_1)
,cereal::make_nvp("content_nibble_level_2", g.content_nibble_level_2)
);
}
template <class Archive>
void serialize (Archive &archive, CEvent &e)
{
archive (
cereal::make_nvp("table_id", e.table_id)
,cereal::make_nvp("transport_stream_id", e.transport_stream_id)
,cereal::make_nvp("original_network_id", e.original_network_id)
,cereal::make_nvp("service_id", e.service_id)
,cereal::make_nvp("section_number", e.section_number)
,cereal::make_nvp("event_id", e.event_id)
,cereal::make_nvp("start_time", e.start_time)
,cereal::make_nvp("end_time", e.end_time)
,cereal::make_nvp("event_name", e.event_name)
,cereal::make_nvp("text", e.text)
,cereal::make_nvp("component_type", e.component_type)
,cereal::make_nvp("component_tag", e.component_tag)
,cereal::make_nvp("audio_component_type", e.audio_component_type)
,cereal::make_nvp("audio_component_tag", e.audio_component_tag)
,cereal::make_nvp("ES_multi_lingual_flag", e.ES_multi_lingual_flag)
,cereal::make_nvp("main_component_flag", e.main_component_flag)
,cereal::make_nvp("quality_indicator", e.quality_indicator)
,cereal::make_nvp("sampling_rate", e.sampling_rate)
,cereal::make_nvp("genres", e.genres)
,cereal::make_nvp("extendedInfos", e.extendedInfos)
);
}
| 26.409962 | 103 | 0.652546 | ysan |
bb43114a487af71d36c85fab409165ca69ed9b9a | 3,221 | cpp | C++ | stlsoft/test/winstl/findvolume_sequence_test/findvolume_sequence_test.cpp | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 86 | 2018-05-24T12:03:44.000Z | 2022-03-13T03:01:25.000Z | stlsoft/test/winstl/findvolume_sequence_test/findvolume_sequence_test.cpp | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 1 | 2019-05-30T01:38:40.000Z | 2019-10-26T07:15:01.000Z | stlsoft/test/winstl/findvolume_sequence_test/findvolume_sequence_test.cpp | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 14 | 2018-07-16T08:29:12.000Z | 2021-08-23T06:21:30.000Z | // findvolume_sequence_test.cpp
//
// Updated: 22nd April 2004
// This will cause various compile-time messages to be emitted. When you get
// sick of them just comment out or remove this #define
#define _STLSOFT_COMPILE_VERBOSE
#include <stlsoft.h>
#include <winstl.h>
#include <stlsoft_simple_algorithms.h>
#include <winstl_findvolume_sequence.h>
winstl_ns_using(findvolume_sequence_a)
winstl_ns_using(findvolume_sequence_w)
#include <stdio.h>
#include <wchar.h>
#include <functional>
#include <algorithm>
#if !defined(_WIN32_WINNT) || \
(_WIN32_WINNT < 0x0500)
static FARPROC GetKernel32ProcOrTerminate(LPSTR procName)
{
// We're incrementing KERNEL32's reference count, but that's ok,
// because it's KERNEL32. Not to be recommended normally.
FARPROC fp = ::GetProcAddress(::LoadLibrary("Kernel32"), procName);
return (fp != NULL) ? fp : (::ExitProcess(1), FARPROC(0));
}
HANDLE WINAPI FindFirstVolumeA(LPSTR lpszVolumeName, DWORD cchBufferLength)
{
return (*reinterpret_cast<HANDLE (WINAPI *)(LPSTR , DWORD )>(GetKernel32ProcOrTerminate("FindFirstVolumeA")))(lpszVolumeName, cchBufferLength);
}
HANDLE WINAPI FindFirstVolumeW(LPWSTR lpszVolumeName, DWORD cchBufferLength)
{
return (*reinterpret_cast<HANDLE (WINAPI *)(LPWSTR , DWORD )>(GetKernel32ProcOrTerminate("FindFirstVolumeW")))(lpszVolumeName, cchBufferLength);
}
BOOL WINAPI FindNextVolumeA(HANDLE hFindVolume, LPSTR lpszVolumeName, DWORD cchBufferLength)
{
return (*reinterpret_cast<BOOL (WINAPI *)(HANDLE, LPSTR , DWORD )>(GetKernel32ProcOrTerminate("FindNextVolumeA")))(hFindVolume, lpszVolumeName, cchBufferLength);
}
BOOL WINAPI FindNextVolumeW(HANDLE hFindVolume, LPWSTR lpszVolumeName, DWORD cchBufferLength)
{
return (*reinterpret_cast<BOOL (WINAPI *)(HANDLE, LPWSTR , DWORD )>(GetKernel32ProcOrTerminate("FindNextVolumeW")))(hFindVolume, lpszVolumeName, cchBufferLength);
}
BOOL WINAPI FindVolumeClose(HANDLE hFindVolume)
{
return (*reinterpret_cast<BOOL (WINAPI *)(HANDLE)>(GetKernel32ProcOrTerminate("FindVolumeClose")))(hFindVolume);
}
#endif /* !_WIN32_WINNT || (_WIN32_WINNT < 0x0500) */
// Because of the difficulties that Borland and GNU compilers have with
// these definitions, this functional looks extremely complex. When
// writing for a single compiler, or for a set that includes the 'better'
// compilers (Intel, Metrowerks, Comeau, Digital Mars) it would not be
// an issue.
struct print_path
{
public:
void operator ()(winstl_ns_qual(findvolume_sequence_a)::value_type const &value)
{
fprintf(stdout, "%s\n", (const char *)value);
}
void operator ()(winstl_ns_qual(findvolume_sequence_w)::value_type const &value)
{
fwprintf(stdout, L"%s\n", (const wchar_t *)value);
}
};
int main(int /* argc */, char ** /*argv*/)
{
winstl_ns_qual(findvolume_sequence_a) volumes_a;
winstl_ns_qual(findvolume_sequence_w) volumes_w;
printf("Current volumes (ANSI):\n");
stlsoft_ns_qual(for_each_preinc)(volumes_a.begin(), volumes_a.end(), print_path());
printf("Current volumes (Unicode):\n");
stlsoft_ns_qual(for_each_postinc)(volumes_w.begin(), volumes_w.end(), print_path());
return 0;
}
| 33.206186 | 164 | 0.73859 | masscry |
bb435e8bd2d9eef2a964efa8005a5374741e7147 | 3,553 | hpp | C++ | src/include/1_2/CL/cl2xrt.hpp | AlphaBu/XRT | 72d34d637d3292e56871f9384888e6aed73b5969 | [
"Apache-2.0"
] | 359 | 2018-10-05T03:05:08.000Z | 2022-03-31T06:28:16.000Z | src/include/1_2/CL/cl2xrt.hpp | AlphaBu/XRT | 72d34d637d3292e56871f9384888e6aed73b5969 | [
"Apache-2.0"
] | 5,832 | 2018-10-02T22:43:29.000Z | 2022-03-31T22:28:05.000Z | src/include/1_2/CL/cl2xrt.hpp | AlphaBu/XRT | 72d34d637d3292e56871f9384888e6aed73b5969 | [
"Apache-2.0"
] | 442 | 2018-10-02T23:06:29.000Z | 2022-03-21T08:34:44.000Z | /**
* Copyright (C) 2021 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://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.
*/
#ifndef XRT_CL2XRT_HPP
#define XRT_CL2XRT_HPP
#include "experimental/xrt_bo.h"
#include "experimental/xrt_device.h"
#include "experimental/xrt_kernel.h"
#include <CL/cl.h>
#if defined(_WIN32)
# ifdef XOCL_SOURCE
# define XOCL_EXPORT __declspec(dllexport)
# else
# define XOCL_EXPORT __declspec(dllimport)
# endif
#else
# define XOCL_EXPORT __attribute__((visibility("default")))
#endif
#ifdef __cplusplus
// C++ extensions that allow host applications to move from OpenCL
// objects to corresponding XRT native C++ objects
namespace xrt { namespace opencl {
/**
* get_xrt_device() - Retrieve underlying xrt::device object
*
* @device: OpenCL device ID
* Return: xrt::device object associated with the OpenCL device
*/
XOCL_EXPORT
xrt::device
get_xrt_device(cl_device_id device);
/**
* get_xrt_bo() - Retrieve underlying xrt::bo object
*
* @device: OpenCL device ID
* @mem: OpenCL memory object to convert to xrt::bo
* Return: xrt::bo object associated with the OpenCL buffer
*
* OpenCL memory objects are created in a cl_context and are
* not uniquely associated with one single device. It is
* possible the cl_mem buffer has not been associated with a
* device and if so, the returned xrt::bo object is empty.
*/
XOCL_EXPORT
xrt::bo
get_xrt_bo(cl_device_id device, cl_mem mem);
/**
* get_xrt_kernel() - Retrieve underlying xrt::kernel object
*
* @device: OpenCL device ID
* @kernel: OpenCL kernel object to convert to xrt::kernel
* Return: xrt::kernel object associated with the OpenCL kernel
*
* OpenCL kernel objects are created in a cl_context and are not
* uniquely associated with a single cl_device. However, a
* xrt::kernel objects is created for each device in the context in
* which the cl_kernel objects was created. This function returns the
* xrt::kernel object for specified device and kernel pair.
*/
XOCL_EXPORT
xrt::kernel
get_xrt_kernel(cl_device_id device, cl_kernel kernel);
/**
* get_xrt_run() - Retrieve underlying xrt::run object
*
* @device: OpenCL device ID
* @kernel: OpenCL kernel object to convert to xrt::run
* Return: xrt::run object associated with the OpenCL kernel
*
* OpenCL kernel object is associated with an xrt::kernel object for
* each device in the context in which the cl_kernel was created.
* This function returns the xrt::run object corresponding to the
* xrt::kernel object that in turn is associated with the cl_device
* and cl_kernel pair.
*
* The returned run object reflects any scalar argument that were set
* on the cl_kernel object, but does not reflect the global memory
* objects as these are not mapped to a device until the enqueue
* operation.
*
* The returned run object is cloned and detached from the cl_kernel
* meaning that any changes to the run object are not reflected
* in the cl_kernel object.
*/
XOCL_EXPORT
xrt::run
get_xrt_run(cl_device_id device, cl_kernel kernel);
}} // opencl, xrt
#endif // __cplusplus
#endif
| 31.166667 | 76 | 0.748382 | AlphaBu |
bb43e4b192ad4725033d5404103b4cf334583627 | 796 | cpp | C++ | EraseSecure/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | EraseSecure/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | EraseSecure/main.cpp | KalawelaLo/Kattis | cbe2cc742f9902f5d325deb04fd39208774070c5 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main() {
string orginal, processed, flipped;
int proc_num;
cin >> proc_num >> orginal >> processed;
if(proc_num%2 == 0){
if(orginal == processed){
cout << "Deletion succeeded" << endl;
}
else{
cout << "Deletion failed" << endl;
}
}
else{
int stop = orginal.size();
for(int i = 0; i < stop; i++){
if(orginal[i]=='1'){
flipped += "0";
}
else{
flipped += "1";
}
}
if(flipped == processed){
cout << "Deletion succeeded" << endl;
}
else{
cout << "Deletion failed" << endl;
}
}
return 0;
} | 21.513514 | 49 | 0.430905 | KalawelaLo |
bb465d208dd903ddd91135f9ad04d04b9cc13d37 | 292 | cpp | C++ | thread/CriticalSection_POSIX.cpp | wbminera1/Framework | dd987a34e642e13e1e8d29e794a58a521e8642e4 | [
"MIT"
] | null | null | null | thread/CriticalSection_POSIX.cpp | wbminera1/Framework | dd987a34e642e13e1e8d29e794a58a521e8642e4 | [
"MIT"
] | null | null | null | thread/CriticalSection_POSIX.cpp | wbminera1/Framework | dd987a34e642e13e1e8d29e794a58a521e8642e4 | [
"MIT"
] | null | null | null | #include "CriticalSection.h"
namespace thread
{
CriticalSection::CriticalSection()
{
}
CriticalSection::~CriticalSection()
{
}
bool CriticalSection::TryLock()
{
return false;
}
void CriticalSection::Lock()
{
}
void CriticalSection::Unlock()
{
}
} // namespace thread
| 10.068966 | 36 | 0.678082 | wbminera1 |
bb4ba5442d4b040866523fa2e0d7fdd29772dad3 | 12,686 | cpp | C++ | lib/src/PyParse/PyVectorFunction.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | null | null | null | lib/src/PyParse/PyVectorFunction.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | null | null | null | lib/src/PyParse/PyVectorFunction.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 1 | 2021-04-13T19:06:43.000Z | 2021-04-13T19:06:43.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include "Python.h"
#include "PyVectorFunction.H"
#include "CH_assert.H"
#include <iostream>
#include "NamespaceHeader.H"
using namespace std;
//-----------------------------------------------------------------------
bool
PyVectorFunction::
isValid(PyObject* a_pyObject)
{
// If the object is a 2-tuple with valid contents, it's also okay.
if (PyTuple_Check(a_pyObject) &&
(PyTuple_Size(a_pyObject) == 2) &&
PyVectorFunction::isValid(PyTuple_GetItem(a_pyObject, 0),
PyTuple_GetItem(a_pyObject, 1)))
return true;
// If we are given a vector, we can interpret the function as constant
// in both space and time.
if (PySequence_Check(a_pyObject) && (PySequence_Length(a_pyObject) == SpaceDim))
{
bool isVector = true;
for (int d = 0; d < SpaceDim; ++d)
{
PyObject* item = PySequence_GetItem(a_pyObject, d);
if (!PyFloat_Check(item) && !PyInt_Check(item))
isVector = false;
Py_DECREF(item);
}
return isVector;
}
// Otherwise, if it can't be called, it is an abomination.
if (!PyCallable_Check(a_pyObject))
return false;
// Try to call it at time 0 at the origin.
PyObject* x = PyTuple_New(SpaceDim);
for (int d = 0; d < SpaceDim; ++d)
{
PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15));
}
double t = 0.0;
PyObject* result = PyObject_CallFunction(a_pyObject, (char*)"Od", x, t);
if (result == NULL)
{
// The 2-argument form doesn't work. Try the single-argument form.
PyErr_Clear();
result = PyObject_CallFunctionObjArgs(a_pyObject, x, NULL);
if (result == NULL)
{
// Nope. No good.
PyErr_Clear();
Py_DECREF(x);
return false;
}
}
Py_DECREF(x);
// The result should be interpretable as a vector.
bool isVector = (PySequence_Check(result) &&
(PySequence_Length(result) == SpaceDim));
if (isVector)
{
for (int d = 0; d < SpaceDim; ++d)
{
PyObject* item = PySequence_GetItem(result, d);
if (!PyFloat_Check(item) && !PyInt_Check(item))
isVector = false;
Py_DECREF(item);
}
}
Py_DECREF(result);
return isVector;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
bool
PyVectorFunction::
isValid(PyObject* a_pyFunction,
PyObject* a_pyDerivs)
{
// First of all, if they can't be called, they are abominations.
if (!PyCallable_Check(a_pyFunction) || !PyCallable_Check(a_pyDerivs))
return false;
// Try to call it at time 0 at the origin.
PyObject* order = PyTuple_New(SpaceDim);
PyObject* x = PyTuple_New(SpaceDim);
for (int d = 0; d < SpaceDim; ++d)
{
PyTuple_SetItem(order, d, PyInt_FromLong(1));
PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15));
}
double t = 0.0;
PyObject* result = PyObject_CallFunction(a_pyFunction, (char*)"Od", x, t);
PyObject* derivResult;
if (result == NULL)
{
// The 2-argument form doesn't work. Try the single-argument form.
PyErr_Clear();
result = PyObject_CallFunctionObjArgs(a_pyFunction, x, NULL);
if (result == NULL)
{
// Nope. No good.
PyErr_Clear();
Py_DECREF(order);
Py_DECREF(x);
return false;
}
// Okay, the single-argument form of the function works, which means
// that it is constant in time. Therefore, the 2-argument form of
// the derivative should work.
derivResult = PyObject_CallFunction(a_pyDerivs, (char*)"OO", order, x);
if (derivResult == NULL)
{
// Well, we almost made it.
PyErr_Clear();
Py_DECREF(order);
Py_DECREF(x);
return false;
}
}
else
{
// The 2-argument form of the function works, which means
// that it is time-dependent. Therefore, the 3-argument form of
// the derivative should work.
derivResult = PyObject_CallFunction(a_pyDerivs, (char*)"OOd", order, x, t);
if (derivResult == NULL)
{
// No luck.
PyErr_Clear();
Py_DECREF(order);
Py_DECREF(x);
return false;
}
}
Py_DECREF(order);
Py_DECREF(x);
// The result should be interpretable as a vector.
bool funcIsVector = (PySequence_Check(result) &&
(PySequence_Length(result) == SpaceDim));
bool derivIsVector = (PySequence_Check(derivResult) &&
(PySequence_Length(derivResult) == SpaceDim));
if (funcIsVector && derivIsVector)
{
for (int d = 0; d < SpaceDim; ++d)
{
PyObject* funcItem = PySequence_GetItem(result, d);
PyObject* derivItem = PySequence_GetItem(result, d);
if (!PyFloat_Check(funcItem) && !PyInt_Check(funcItem))
funcIsVector = false;
if (!PyFloat_Check(derivItem) && !PyInt_Check(derivItem))
funcIsVector = false;
Py_DECREF(funcItem);
Py_DECREF(derivItem);
}
}
Py_DECREF(result);
Py_DECREF(derivResult);
return (funcIsVector && derivIsVector);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
PyVectorFunction::
PyVectorFunction(PyObject* a_pyObject):
VectorFunction(false, false),
m_func(a_pyObject),
m_derivs(NULL)
{
CH_assert(a_pyObject != NULL);
CH_assert(isValid(a_pyObject));
// If the object is a 2-tuple with valid contents, crack it open.
if (PyTuple_Check(a_pyObject) &&
(PyTuple_Size(a_pyObject) == 2) &&
isValid(PyTuple_GetItem(a_pyObject, 0), PyTuple_GetItem(a_pyObject, 1)))
{
m_func = PyTuple_GetItem(a_pyObject, 0);
m_derivs = PyTuple_GetItem(a_pyObject, 1);
}
// If we are given a vector, we can interpret the function as constant
// in both space and time.
else if (PySequence_Check(a_pyObject) && (PySequence_Length(a_pyObject) == SpaceDim))
{
m_isConstant = m_isHomogeneous = true;
return;
}
// Figure out whether the function takes one or two arguments.
PyObject* x = PyTuple_New(SpaceDim);
for (int d = 0; d < SpaceDim; ++d)
{
PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15));
}
double t = 0.0;
PyObject* result = PyObject_CallFunction(a_pyObject, (char*)"Od", x, t);
Py_DECREF(x);
if (result == NULL)
{
// The 2-argument form doesn't work, so the function is constant in time.
PyErr_Clear();
m_isConstant = true;
}
Py_XDECREF(result);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
PyVectorFunction::
PyVectorFunction(PyObject* a_pyFunction,
PyObject* a_pyDerivs):
VectorFunction(false, false),
m_func(a_pyFunction),
m_derivs(a_pyDerivs)
{
CH_assert(a_pyFunction != NULL);
CH_assert(a_pyDerivs != NULL);
CH_assert(isValid(a_pyFunction, a_pyDerivs));
Py_INCREF(a_pyFunction);
Py_INCREF(a_pyDerivs);
// Figure out whether the function takes one or two arguments.
PyObject* x = PyTuple_New(SpaceDim);
for (int d = 0; d < SpaceDim; ++d)
{
PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15));
}
double t = 0.0;
PyObject* result = PyObject_CallFunction(a_pyFunction, (char*)"Od", x, t);
Py_DECREF(x);
if (result == NULL)
{
// The 2-argument form doesn't work, so the function is constant in time.
PyErr_Clear();
m_isConstant = true;
}
Py_XDECREF(result);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
PyVectorFunction::
~PyVectorFunction()
{
Py_XDECREF(m_func);
Py_XDECREF(m_derivs);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
RealVect
PyVectorFunction::
operator()(const RealVect& a_x, Real a_t) const
{
// If we're constant and homogeneous, interpret the function
// as a vector.
RealVect v;
if (m_isConstant && m_isHomogeneous)
{
for (int d = 0; d < SpaceDim; ++d)
{
PyObject* item = PyTuple_GetItem(m_func, d);
v[d] = (PyFloat_Check(item)) ? PyFloat_AsDouble(item)
: static_cast<double>(PyInt_AsLong(item));
}
return v;
}
// Construct a d-tuple for a_x.
PyObject* x = PyTuple_New(SpaceDim);
for (int d = 0; d < SpaceDim; ++d)
{
PyTuple_SetItem(x, d, PyFloat_FromDouble(a_x[d]));
}
// Call the function with our arguments.
PyObject* result;
if (isConstant())
{
result = PyObject_CallFunctionObjArgs(m_func, x, NULL);
}
else
{
result = PyObject_CallFunction(m_func, (char*)"Od", x,
static_cast<double>(a_t));
}
Py_DECREF(x);
if (PyErr_Occurred())
{
PyErr_Print();
MayDay::Error("Evaluation of Python-supplied vector function failed.");
}
// Extract our vector.
CH_assert(PySequence_Check(result) && (PySequence_Length(result) == SpaceDim));
for (int d = 0; d < SpaceDim; ++d)
{
PyObject* item = PySequence_GetItem(result, d);
v[d] = (PyFloat_Check(item)) ? static_cast<double>(PyFloat_AsDouble(item))
: static_cast<double>(PyInt_AsLong(item));
Py_DECREF(item);
}
Py_DECREF(result);
return v;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
RealVect
PyVectorFunction::
derivative(const IntVect& a_order, const RealVect& a_x, Real a_t) const
{
// If the order is zero, return the function's value.
if (a_order == IntVect::Zero)
return (*this)(a_x, a_t);
// If the function is homogeneous, return 0 for all derivatives.
if (m_isHomogeneous)
return RealVect::Zero;
// If we don't have a mechanism for evaluating derivatives,
// we are unable to continue.
if (m_derivs == NULL)
MayDay::Error("This vector function does not define derivatives");
// Construct d-tuples for a_order and a_x.
PyObject* order = PyTuple_New(SpaceDim);
PyObject* x = PyTuple_New(SpaceDim);
for (int d = 0; d < SpaceDim; ++d)
{
PyTuple_SetItem(order, d, PyInt_FromLong(a_order[d]));
PyTuple_SetItem(x, d, PyFloat_FromDouble(a_x[d]));
}
// Call the function with our arguments.
PyObject* result;
if (isConstant())
{
result = PyObject_CallFunction(m_derivs, (char*)"OO", order, x);
}
else
{
result = PyObject_CallFunction(m_derivs, (char*)"OOd", order, x,
static_cast<double>(a_t));
}
Py_DECREF(order);
Py_DECREF(x);
if (PyErr_Occurred())
{
PyErr_Print();
MayDay::Error("Evaluation of Python-supplied vector function derivative failed.");
}
RealVect v;
CH_assert(PySequence_Check(result) && (PySequence_Length(result) == SpaceDim));
for (int d = 0; d < SpaceDim; ++d)
{
PyObject* item = PySequence_GetItem(result, d);
v[d] = (PyFloat_Check(item)) ? static_cast<double>(PyFloat_AsDouble(item))
: static_cast<double>(PyInt_AsLong(item));
Py_DECREF(item);
}
Py_DECREF(result);
return v;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
bool
PyVectorFunction::
hasDerivative(const IntVect& a_order) const
{
// We always have the zeroth order derivative. :-P
if ((a_order == IntVect::Zero) || m_isHomogeneous)
return true;
// If we don't have a mechanism for evaluating derivatives,
// we are unable to continue.
if (m_derivs == NULL)
return false;
// Construct d-tuples for a_order and a_x.
PyObject* order = PyTuple_New(SpaceDim);
PyObject* x = PyTuple_New(SpaceDim);
for (int d = 0; d < SpaceDim; ++d)
{
PyTuple_SetItem(order, d, PyInt_FromLong(a_order[d]));
PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15));
}
// Call the function with our arguments.
PyObject* result;
if (isConstant())
{
result = PyObject_CallFunction(m_derivs, (char*)"OO", order, x);
}
else
{
result = PyObject_CallFunction(m_derivs, (char*)"OOd", order, x,
static_cast<double>(0.0));
}
Py_DECREF(order);
Py_DECREF(x);
if (PyErr_Occurred())
{
PyErr_Clear();
return false;
}
Py_DECREF(result);
return true;
}
//-----------------------------------------------------------------------
#include "NamespaceFooter.H"
| 29.297921 | 87 | 0.580719 | rmrsk |
bb51fbadc27935f9a34938e73987c0f622e9da94 | 2,479 | cpp | C++ | src/timeopt/problem.cpp | ggory15/hpp_timeopt_python | 3100d044be65bae521913bea0b9ed902cc5d346c | [
"BSD-2-Clause"
] | null | null | null | src/timeopt/problem.cpp | ggory15/hpp_timeopt_python | 3100d044be65bae521913bea0b9ed902cc5d346c | [
"BSD-2-Clause"
] | 1 | 2019-10-23T20:24:14.000Z | 2019-10-31T05:23:05.000Z | src/timeopt/problem.cpp | ggory15/hpp_timeopt_python | 3100d044be65bae521913bea0b9ed902cc5d346c | [
"BSD-2-Clause"
] | 2 | 2019-01-17T13:16:08.000Z | 2019-03-25T13:24:47.000Z | // Copyright (c) 2018-2019, CNRS
// Authors: Sanghyun Kim <ggory15@snu.ac.kr>
#include "timeopt/problem.hpp"
#include <momentumopt/cntopt/ContactPlanFromFile.hpp>
#include <fstream>
#include <iomanip>
namespace timeopt
{
ProblemInfo::ProblemInfo()
: phases_() // pre-allocation
, init_com_(Vector3d::Ones()*1000)
, final_com_(Vector3d::Ones()*1000)
, mass_(0.0)
{
init_state_ = new InitialState();
contact_state_ = new ContactState();
planner_ = new ContactPlanner();
}
ProblemInfo::ProblemInfo(const Index size)
: phases_(size) // pre-allocation
, init_com_(Vector3d::Ones()*1000)
, final_com_(Vector3d::Ones()*1000)
, mass_(0.0)
{
init_state_ = new InitialState();
contact_state_ = new ContactState(size);
planner_ = new ContactPlanner();
}
void ProblemInfo::setConfigurationFile(const std::string & file_location) const throw (std::invalid_argument)
{
if (init_com_.norm() > 1000){
const std::string exception_message("Initial COM does not seem to be a valid value.");
}
if (final_com_.norm() > 1000){
const std::string exception_message("Final COM does not seem to be a valid value.");
}
if (mass_ < 0.001){
const std::string exception_message("Robot's Mass does not seem to be a valid value.");
}
init_state_->save();
contact_state_->save();
planner_->initialize(file_location, *init_state_, *contact_state_);
planner_->setTimehorizon(contact_state_->getTimeHorizon());
planner_->saveToFile();
}
void ProblemInfo::setTimeoptSolver(const std::string & file){
std::string cfg_file;
cfg_file = file.substr(0, file.size()-5)+"_final.yaml";
planner_setting_.initialize(cfg_file);
dynamic_state_.fillInitialRobotState(cfg_file);
ref_sequence_.resize(planner_setting_.get(momentumopt::PlannerIntParam_NumTimesteps));
}
void ProblemInfo::solve(){
momentumopt::ContactPlanFromFile contact_plan;
contact_plan.initialize(planner_setting_);
contact_plan.optimize(dynamic_state_);
dyn_optimizer_.initialize(planner_setting_, dynamic_state_, &contact_plan);
dyn_optimizer_.optimize(ref_sequence_);
time_traj_.resize(getNumSize());
int size = getNumSize();
time_traj_(0) = dyn_optimizer_.dynamicsSequence().dynamicsState(0).time();
for (int i=1; i<size; i++)
time_traj_(i) = dyn_optimizer_.dynamicsSequence().dynamicsState(i).time() + time_traj_(i-1);
}
}
| 32.194805 | 111 | 0.696652 | ggory15 |
bb526e0faabcef75d91ed4603c78592be141e192 | 14,292 | cpp | C++ | Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapAtlas.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapAtlas.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/Atom/Feature/Common/Code/Source/CoreLights/ShadowmapAtlas.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <CoreLights/ShadowmapAtlas.h>
#include <Atom/RPI.Public/Buffer/Buffer.h>
#include <AzCore/std/sort.h>
namespace AZ
{
namespace Render
{
void ShadowmapAtlas::Initialize()
{
m_requireFinalize = true;
m_indicesForSize.clear();
m_locations.clear();
m_baseShadowmapSize = ShadowmapSize::None;
m_maxArraySlice = 0;
m_shadowmapIndexNodeTree.clear();
m_indexTableData.clear();
}
void ShadowmapAtlas::SetShadowmapSize(size_t index, ShadowmapSize size)
{
AZ_Assert(m_requireFinalize, "Initialize before set shadowmap size");
m_requireFinalize = true;
m_indicesForSize[size].push_back(index);
m_baseShadowmapSize = AZStd::GetMax(size, m_baseShadowmapSize);
}
void ShadowmapAtlas::Finalize()
{
AZ_Assert(m_requireFinalize, "Initialize before finalization.");
// Determine shadowmap location in the atlas from the larger shadowmaps.
Location currentLocation;
for (ShadowmapSize size = m_baseShadowmapSize;
size >= MinShadowmapImageSize;
size = static_cast<ShadowmapSize>(static_cast<uint32_t>(size) / 2))
{
// The length of the location indicates the width of shadowmap.
// When we make the width half, we extend the sequence by 1.
currentLocation.resize(currentLocation.size() + 1);
if (m_indicesForSize.find(size) != m_indicesForSize.end())
{
for (const size_t index : m_indicesForSize[size])
{
m_locations[index] = currentLocation;
SetShadowmapIndexInTree(currentLocation, index);
m_maxArraySlice = AZStd::GetMax(m_maxArraySlice, currentLocation[0]);
SucceedLocation(currentLocation);
}
}
}
m_requireFinalize = false;
AZ_Assert(m_shadowmapIndexNodeTree.empty() || GetNodeOfTree(Location{}).size() == GetArraySliceCount(),
"The atlas has a shadowmap, but the root subtable does not have size of the array slice count.");
BuildIndexTableData();
}
uint16_t ShadowmapAtlas::GetArraySliceCount() const
{
AZ_Assert(!m_requireFinalize, "Finalization is required.");
// If no shadowmap is added, it returns 1
// since an image resource have to be created for such a case.
return static_cast<uint16_t>(m_maxArraySlice) + 1;
}
ShadowmapSize ShadowmapAtlas::GetBaseShadowmapSize() const
{
AZ_Assert(!m_requireFinalize, "Finalization is required.");
return m_baseShadowmapSize;
}
ShadowmapAtlas::Origin ShadowmapAtlas::GetOrigin(size_t index) const
{
AZ_Assert(!m_requireFinalize, "Finalization is required.");
Origin origin;
if (m_locations.find(index) == m_locations.end())
{
return origin; // disabled shadowmap for this light
}
const Location location = m_locations.at(index);
if (location.empty())
{
return origin; // disabled shadowmap for this light
}
origin.m_arraySlice = static_cast<uint16_t>(location[0]);
uint32_t sizeDiff = static_cast<uint32_t>(m_baseShadowmapSize);
for (size_t digitIndex = 1; digitIndex < location.size(); ++digitIndex)
{
sizeDiff /= 2;
AZ_Assert(location[digitIndex] <= LocationIndexNum, "Digit in atlas location is illegal.");
origin.m_originInSlice[0] += (location[digitIndex] & 1) ? sizeDiff : 0;
origin.m_originInSlice[1] += (location[digitIndex] & 2) ? sizeDiff : 0;
}
return origin;
}
void ShadowmapAtlas::SucceedLocation(Location& location)
{
constexpr uint8_t LocationIndexMax = LocationIndexNum - 1;
// A location is a finite sequence of non-negative integers.
// We consider it as a number of base LocationIndexMax (base 4) except 0-th digit.
for (size_t digitIndex = location.size() - 1; digitIndex > 0; --digitIndex)
{
if (location[digitIndex] < LocationIndexMax)
{
// If the figure of the current digit is < LocationIndexMax(=3),
// just succeed the figure and finish.
// (e.g., [1,0,_0_] -> [1,0,_1_])
++location[digitIndex];
return;
}
else
{
// If the figure of the current digit is already max,
// carry over and consider the next digit.
// (e.g., [1,0,_3_] -> [1,_0_,0] and next execution of the loop it will be [1,_1_,0])
location[digitIndex] = 0; // carry over
}
}
// The first index indicates array slice index,
// so just add a new slice and carry over.
// This case happens when the all following figures are already LocationIndexMax(=3).
// (e.g., [1,3,3,3] input -> [2,0,0,0] output)
++location[0];
AZ_Assert(location[0] != 0, "Array slice index is overflowed.");
}
void ShadowmapAtlas::SetShadowmapIndexInTree(const Location& location, size_t index)
{
const Location parentLocation(location.begin(), location.end() - 1);
ShadowmapIndicesInNode& parentNode = GetNodeOfTree(parentLocation);
if (parentLocation.empty())
{
// parentLocation indicates the root location.
// The root subtable's size is not determined at this point,
// so just reserve the required size.
AZ_Assert(parentNode.size() == location.back(), "Root node should grow its size gradually.");
parentNode.push_back(index);
}
else
{
// parentLocation is not root. Then its size does not change.
parentNode[location.back()] = index;
}
}
ShadowmapAtlas::ShadowmapIndicesInNode& ShadowmapAtlas::GetNodeOfTree(const Location& location)
{
auto it = m_shadowmapIndexNodeTree.find(location);
if (it != m_shadowmapIndexNodeTree.end())
{
return it->second;
}
if (location.empty())
{
// The root subtable has size the array slice count of the atlas image resource,
// it is not determined at this point. (It is detemined during Finalize().)
// So we create it as an empty ShadowmapIndicesInNode here.
m_shadowmapIndexNodeTree.emplace(location, ShadowmapIndicesInNode(0));
}
else
{
// It reserves parent subtable node placeholder.
const Location parentLocation(location.begin(), location.end() - 1);
ShadowmapIndicesInNode& parentNode = GetNodeOfTree(parentLocation);
if (parentLocation.empty() && location.back() >= parentNode.size())
{
// parentLocation indicates the root location.
// The root subtable's size is not determined at this point,
// so just reserve the required size.
// The adding location is shared by multiple shadowmaps,
// so its value is InvalidIndex.
AZ_Assert(parentNode.size() == location.back(), "Root node should grow its size gradually.");
parentNode.push_back(InvalidIndex);
}
// A non root subtable has size LocationIndexNum.
m_shadowmapIndexNodeTree.emplace(location, ShadowmapIndicesInNode(LocationIndexNum, InvalidIndex));
}
return m_shadowmapIndexNodeTree.at(location);
}
Data::Instance<RPI::Buffer> ShadowmapAtlas::CreateShadowmapIndexTableBuffer(const AZStd::string& bufferName) const
{
AZ_Assert(!m_requireFinalize, "Finalization is required.");
RPI::CommonBufferDescriptor desc;
desc.m_poolType = RPI::CommonBufferPoolType::ReadOnly;
desc.m_bufferName = bufferName;
desc.m_elementSize = sizeof(ShadowmapIndexNode);
desc.m_elementFormat = RHI::Format::R32G32_UINT;
desc.m_byteCount = m_indexTableData.size() * sizeof(ShadowmapIndexNode);
desc.m_bufferData = m_indexTableData.data();
return RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc);
}
const AZStd::vector<ShadowmapAtlas::ShadowmapIndexNode> &ShadowmapAtlas::GetShadowmapIndexTable() const
{
AZ_Assert(!m_requireFinalize, "Finalization is required.");
return m_indexTableData;
}
void ShadowmapAtlas::BuildIndexTableData()
{
AZ_Assert(!m_requireFinalize, "Finalization is required.");
const size_t subtableCount = m_shadowmapIndexNodeTree.size();
const uint32_t rootSubtableSize = GetArraySliceCount();
if (subtableCount == 0)
{
m_indexTableData.resize(rootSubtableSize);
return;
}
const size_t nonRootSubtableCount = subtableCount - 1;
// The subtable of root (at location []) has the size of array slice count,
// and the other subtabls has the size LocationIndexNum.
m_indexTableData.resize(rootSubtableSize + nonRootSubtableCount * LocationIndexNum);
// Determine indices of subtables, which enables calculation
// of offset of each subtable in the table.
AZStd::vector<Location> nodes;
nodes.reserve(nonRootSubtableCount);
AZStd::unordered_map<Location, uint32_t, LocationHasher> indices;
{ // scope to avoid variable name pollution.
for (const auto& it : m_shadowmapIndexNodeTree)
{
const Location& location = it.first;
if (location.empty())
{
continue; // skip entry in the root subtable
}
nodes.push_back(location);
}
AZStd::sort(
nodes.begin(), nodes.end(),
[](const Location& lhs, const Location& rhs) -> bool
{
if (lhs.size() == rhs.size())
{
for (size_t index = 0; index < lhs.size(); ++index)
{
if (lhs[index] != rhs[index])
{
return lhs[index] < rhs[index];
}
}
}
return lhs.size() < rhs.size();
});
AZ_Assert(nodes.size() == nonRootSubtableCount, "subtable count has an unexpected value.");
for (uint32_t index = 0; index < nodes.size(); ++index)
{
indices[nodes[index]] = index;
}
}
// Store the next table offsets and shadowmap indices into the table.
for (const auto& it : m_shadowmapIndexNodeTree)
{
const Location& location = it.first;
const ShadowmapIndicesInNode& indicesInNode = it.second;
uint8_t digitCount = LocationIndexNum;
uint32_t indexInTableBase = 0;
if (location.empty())
{
digitCount = m_maxArraySlice + 1;
}
else
{
const uint32_t subtableIndex = indices.at(location);
indexInTableBase = rootSubtableSize + subtableIndex * LocationIndexNum;
}
for (uint8_t digit = 0; digit < digitCount; ++digit)
{
const uint32_t indexInTable = indexInTableBase + digit;
if (indicesInNode[digit] == InvalidIndex)
{
// This atlas does not have shadowmap in this location.
// In such a case, look for the subtable,
// and put its offset to m_nextTableOffset if it exists.
Location childLocation = location;
childLocation.push_back(digit);
const auto childIt = indices.find(childLocation);
if (childIt != indices.end())
{
const uint32_t offset = rootSubtableSize + childIt->second * LocationIndexNum;
m_indexTableData[indexInTable].m_nextTableOffset = offset;
}
}
else
{
// This atlas has a shadowmap of index indicesInNode[digit] in this location.
// In such a case, put its auxiliary data and
// set m_nextTableOffset to 0.
m_indexTableData[indexInTable].m_shadowmapIndex = aznumeric_cast<uint32_t>(indicesInNode[digit]);
m_indexTableData[indexInTable].m_nextTableOffset = 0;
}
}
}
}
} // namespace Render
} // namespace AZ
| 44.523364 | 122 | 0.540092 | cypherdotXd |
bb5383432fec5dee2ad0f76712cf2f68954277d4 | 555 | cpp | C++ | Section_6_Loops/Break_and_Continue/exercise_2.cpp | mattlyon93/LearningCPlusPlus | 33d413e8ccc24c345bb9b26cb554fd8552ebbffc | [
"MIT"
] | null | null | null | Section_6_Loops/Break_and_Continue/exercise_2.cpp | mattlyon93/LearningCPlusPlus | 33d413e8ccc24c345bb9b26cb554fd8552ebbffc | [
"MIT"
] | null | null | null | Section_6_Loops/Break_and_Continue/exercise_2.cpp | mattlyon93/LearningCPlusPlus | 33d413e8ccc24c345bb9b26cb554fd8552ebbffc | [
"MIT"
] | null | null | null | #include <stdio.h>
using namespace std;
int main(){
// Initialize variables
int sum = 0;
int i = 1;
char res;
// Do the loop
while(true){
// Get user input
printf("The current sum is: %d\n", sum);
printf("Do you want to add %d? (Y/N): ", i);
scanf(" %c", &res);
if (res == 'Y' || res == 'y'){
sum += i++;
}
else if ( res == 'N' || res == 'n'){
i++;
continue;
}
else {
break;
}
}
return 0;
} | 17.903226 | 52 | 0.390991 | mattlyon93 |
bb57a1994515696061ad300d1f0be7e6f7559710 | 3,121 | cpp | C++ | src/particle_dynamics/PDApp.cpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null | src/particle_dynamics/PDApp.cpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null | src/particle_dynamics/PDApp.cpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null |
# include "PDApp.hpp"
using namespace std;
// -------------------------------------------------------------------------
// Constructor:
// -------------------------------------------------------------------------
PDApp::PDApp(const GetPot& input_params)
{
// ---------------------------------------
// Assign variables from 'input_params':
// ---------------------------------------
p.NX = input_params("Domain/nx",1);
p.NY = input_params("Domain/ny",1);
p.NZ = input_params("Domain/nz",1);
p.dx = input_params("Domain/dx",1.0);
p.dy = input_params("Domain/dy",1.0);
p.dz = input_params("Domain/dz",1.0);
p.dt = input_params("Time/dt",1.0);
p.iskip = input_params("Output/iskip",1);
p.jskip = input_params("Output/jskip",1);
p.kskip = input_params("Output/kskip",1);
p.LX = p.NX*p.dx;
p.LY = p.NY*p.dy;
p.LZ = p.NZ*p.dz;
// get number of particles to determin if greater than zero
numberOfParticles = input_params("PDApp/N",0);
// ---------------------------------------
// Get some MPI parameters:
// ---------------------------------------
p.np = MPI::COMM_WORLD.Get_size(); // # of processors
p.rank = MPI::COMM_WORLD.Get_rank(); // my processor number
// ---------------------------------------
// Set dimensions:
// ---------------------------------------
ptrdiff_t locsize, locnx, offx;
fftw_mpi_init();
locsize = fftw_mpi_local_size_3d(p.NX,p.NY,p.NZ,MPI_COMM_WORLD,&locnx,&offx);
p.nx = locnx;
p.ny = p.NY;
p.nz = p.NZ;
p.xOff = offx;
// ---------------------------------------
// Create a PD object:
// ---------------------------------------
pd_object = new PDParticles(p,input_params);
}
// -------------------------------------------------------------------------
// Destructor:
// -------------------------------------------------------------------------
PDApp::~PDApp()
{
delete pd_object;
}
// -------------------------------------------------------------------------
// Initialize system:
// -------------------------------------------------------------------------
void PDApp::initSystem()
{
pd_object->initParticles();
}
// -------------------------------------------------------------------------
// Take one step forward in time:
// -------------------------------------------------------------------------
void PDApp::stepForward(int step)
{
// ----------------------------------------
// Set the time step:
// ----------------------------------------
current_step = step;
pd_object->setTimeStep(current_step);
// ----------------------------------------
// Update Particles system:
// ----------------------------------------
pd_object->updateParticles();
}
// -------------------------------------------------------------------------
// Write output:
// -------------------------------------------------------------------------
void PDApp::writeOutput(int step)
{
pd_object->setTimeStep(step);
if(numberOfParticles > 0)
pd_object->outputParticles();
}
| 26.008333 | 81 | 0.360141 | flowzario |
bb5c5d89cd016f9de17cb1d5903775df13d11182 | 1,559 | hpp | C++ | search/algos.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 2 | 2019-01-24T15:36:20.000Z | 2019-12-26T10:03:48.000Z | search/algos.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 13 | 2015-09-28T13:59:23.000Z | 2015-10-08T20:12:45.000Z | search/algos.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2018-10-01T10:27:21.000Z | 2018-10-01T10:27:21.000Z | #pragma once
#include "base/base.hpp"
#include "std/algorithm.hpp"
#include "std/vector.hpp"
namespace search
{
namespace impl
{
struct LS
{
size_t prevDecreasePos, decreaseValue;
size_t prevIncreasePos, increaseValue;
LS(size_t i)
{
prevDecreasePos = i;
decreaseValue = 1;
prevIncreasePos = i;
increaseValue = 1;
}
};
}
template <class T, class OutIterT, class CompT>
void LongestSubsequence(vector<T> const & in, OutIterT out, CompT cmp)
{
if (in.empty())
return;
vector<impl::LS> v;
v.reserve(in.size());
for (size_t i = 0; i < in.size(); ++i)
v.push_back(impl::LS(i));
size_t res = 1;
size_t pos = 0;
for (size_t i = 0; i < v.size(); ++i)
{
for (size_t j = i+1; j < v.size(); ++j)
{
if (cmp.Less(in[i], in[j]) && v[i].increaseValue + 1 >= v[j].increaseValue)
{
v[j].increaseValue = v[i].increaseValue + 1;
v[j].prevIncreasePos = i;
}
if (cmp.Greater(in[i], in[j]) && v[i].decreaseValue + 1 >= v[j].decreaseValue)
{
v[j].decreaseValue = v[i].decreaseValue + 1;
v[j].prevDecreasePos = i;
}
size_t const m = max(v[j].increaseValue, v[j].decreaseValue);
if (m > res)
{
res = m;
pos = j;
}
}
}
bool increasing = true;
if (v[pos].increaseValue < v[pos].decreaseValue)
increasing = false;
while (res-- > 0)
{
*out++ = in[pos];
if (increasing)
pos = v[pos].prevIncreasePos;
else
pos = v[pos].prevDecreasePos;
}
}
}
| 19.012195 | 84 | 0.556126 | bowlofstew |
bb5fe46dc2f7860e7d9508c915a012f26cb07f11 | 12,666 | hpp | C++ | include/RootMotion/FinalIK/IKSolverLookAt.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/IKSolverLookAt.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/IKSolverLookAt.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: RootMotion.FinalIK.IKSolver
#include "RootMotion/FinalIK/IKSolver.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: RootMotion::FinalIK
namespace RootMotion::FinalIK {
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
// Forward declaring type: AnimationCurve
class AnimationCurve;
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Size: 0xC8
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.IKSolverLookAt
class IKSolverLookAt : public RootMotion::FinalIK::IKSolver {
public:
// Nested type: RootMotion::FinalIK::IKSolverLookAt::LookAtBone
class LookAtBone;
// public UnityEngine.Transform target
// Size: 0x8
// Offset: 0x58
UnityEngine::Transform* target;
// Field size check
static_assert(sizeof(UnityEngine::Transform*) == 0x8);
// public RootMotion.FinalIK.IKSolverLookAt/LookAtBone[] spine
// Size: 0x8
// Offset: 0x60
::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* spine;
// Field size check
static_assert(sizeof(::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>*) == 0x8);
// public RootMotion.FinalIK.IKSolverLookAt/LookAtBone head
// Size: 0x8
// Offset: 0x68
RootMotion::FinalIK::IKSolverLookAt::LookAtBone* head;
// Field size check
static_assert(sizeof(RootMotion::FinalIK::IKSolverLookAt::LookAtBone*) == 0x8);
// public RootMotion.FinalIK.IKSolverLookAt/LookAtBone[] eyes
// Size: 0x8
// Offset: 0x70
::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* eyes;
// Field size check
static_assert(sizeof(::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>*) == 0x8);
// [RangeAttribute] Offset: 0xE0869C
// public System.Single bodyWeight
// Size: 0x4
// Offset: 0x78
float bodyWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [RangeAttribute] Offset: 0xE086B4
// public System.Single headWeight
// Size: 0x4
// Offset: 0x7C
float headWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [RangeAttribute] Offset: 0xE086CC
// public System.Single eyesWeight
// Size: 0x4
// Offset: 0x80
float eyesWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [RangeAttribute] Offset: 0xE086E4
// public System.Single clampWeight
// Size: 0x4
// Offset: 0x84
float clampWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [RangeAttribute] Offset: 0xE086FC
// public System.Single clampWeightHead
// Size: 0x4
// Offset: 0x88
float clampWeightHead;
// Field size check
static_assert(sizeof(float) == 0x4);
// [RangeAttribute] Offset: 0xE08714
// public System.Single clampWeightEyes
// Size: 0x4
// Offset: 0x8C
float clampWeightEyes;
// Field size check
static_assert(sizeof(float) == 0x4);
// [RangeAttribute] Offset: 0xE0872C
// public System.Int32 clampSmoothing
// Size: 0x4
// Offset: 0x90
int clampSmoothing;
// Field size check
static_assert(sizeof(int) == 0x4);
// Padding between fields: clampSmoothing and: spineWeightCurve
char __padding10[0x4] = {};
// public UnityEngine.AnimationCurve spineWeightCurve
// Size: 0x8
// Offset: 0x98
UnityEngine::AnimationCurve* spineWeightCurve;
// Field size check
static_assert(sizeof(UnityEngine::AnimationCurve*) == 0x8);
// public UnityEngine.Vector3 spineTargetOffset
// Size: 0xC
// Offset: 0xA0
UnityEngine::Vector3 spineTargetOffset;
// Field size check
static_assert(sizeof(UnityEngine::Vector3) == 0xC);
// Padding between fields: spineTargetOffset and: spineForwards
char __padding12[0x4] = {};
// protected UnityEngine.Vector3[] spineForwards
// Size: 0x8
// Offset: 0xB0
::Array<UnityEngine::Vector3>* spineForwards;
// Field size check
static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8);
// protected UnityEngine.Vector3[] headForwards
// Size: 0x8
// Offset: 0xB8
::Array<UnityEngine::Vector3>* headForwards;
// Field size check
static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8);
// protected UnityEngine.Vector3[] eyeForward
// Size: 0x8
// Offset: 0xC0
::Array<UnityEngine::Vector3>* eyeForward;
// Field size check
static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8);
// Creating value type constructor for type: IKSolverLookAt
IKSolverLookAt(UnityEngine::Transform* target_ = {}, ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* spine_ = {}, RootMotion::FinalIK::IKSolverLookAt::LookAtBone* head_ = {}, ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* eyes_ = {}, float bodyWeight_ = {}, float headWeight_ = {}, float eyesWeight_ = {}, float clampWeight_ = {}, float clampWeightHead_ = {}, float clampWeightEyes_ = {}, int clampSmoothing_ = {}, UnityEngine::AnimationCurve* spineWeightCurve_ = {}, UnityEngine::Vector3 spineTargetOffset_ = {}, ::Array<UnityEngine::Vector3>* spineForwards_ = {}, ::Array<UnityEngine::Vector3>* headForwards_ = {}, ::Array<UnityEngine::Vector3>* eyeForward_ = {}) noexcept : target{target_}, spine{spine_}, head{head_}, eyes{eyes_}, bodyWeight{bodyWeight_}, headWeight{headWeight_}, eyesWeight{eyesWeight_}, clampWeight{clampWeight_}, clampWeightHead{clampWeightHead_}, clampWeightEyes{clampWeightEyes_}, clampSmoothing{clampSmoothing_}, spineWeightCurve{spineWeightCurve_}, spineTargetOffset{spineTargetOffset_}, spineForwards{spineForwards_}, headForwards{headForwards_}, eyeForward{eyeForward_} {}
// public System.Void SetLookAtWeight(System.Single weight)
// Offset: 0x1BE41A4
void SetLookAtWeight(float weight);
// public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight)
// Offset: 0x1BE4228
void SetLookAtWeight(float weight, float bodyWeight);
// public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight)
// Offset: 0x1BE42D4
void SetLookAtWeight(float weight, float bodyWeight, float headWeight);
// public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight, System.Single eyesWeight)
// Offset: 0x1BE439C
void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight);
// public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight, System.Single eyesWeight, System.Single clampWeight)
// Offset: 0x1BE4488
void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight, float clampWeight);
// public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight, System.Single eyesWeight, System.Single clampWeight, System.Single clampWeightHead, System.Single clampWeightEyes)
// Offset: 0x1BE4594
void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight, float clampWeight, float clampWeightHead, float clampWeightEyes);
// public System.Boolean SetChain(UnityEngine.Transform[] spine, UnityEngine.Transform head, UnityEngine.Transform[] eyes, UnityEngine.Transform root)
// Offset: 0x1BE5158
bool SetChain(::Array<UnityEngine::Transform*>* spine, UnityEngine::Transform* head, ::Array<UnityEngine::Transform*>* eyes, UnityEngine::Transform* root);
// protected System.Boolean get_spineIsValid()
// Offset: 0x1BE4AE4
bool get_spineIsValid();
// protected System.Boolean get_spineIsEmpty()
// Offset: 0x1BE4CBC
bool get_spineIsEmpty();
// protected System.Void SolveSpine()
// Offset: 0x1BE58FC
void SolveSpine();
// protected System.Boolean get_headIsValid()
// Offset: 0x1BE4BC8
bool get_headIsValid();
// protected System.Boolean get_headIsEmpty()
// Offset: 0x1BE4CE0
bool get_headIsEmpty();
// protected System.Void SolveHead()
// Offset: 0x1BE5B28
void SolveHead();
// protected System.Boolean get_eyesIsValid()
// Offset: 0x1BE4BD8
bool get_eyesIsValid();
// protected System.Boolean get_eyesIsEmpty()
// Offset: 0x1BE4D5C
bool get_eyesIsEmpty();
// protected System.Void SolveEyes()
// Offset: 0x1BE5D84
void SolveEyes();
// protected UnityEngine.Vector3[] GetForwards(ref UnityEngine.Vector3[] forwards, UnityEngine.Vector3 baseForward, UnityEngine.Vector3 targetForward, System.Int32 bones, System.Single clamp)
// Offset: 0x1BE62B0
::Array<UnityEngine::Vector3>* GetForwards(::Array<UnityEngine::Vector3>*& forwards, UnityEngine::Vector3 baseForward, UnityEngine::Vector3 targetForward, int bones, float clamp);
// protected System.Void SetBones(UnityEngine.Transform[] array, ref RootMotion.FinalIK.IKSolverLookAt/LookAtBone[] bones)
// Offset: 0x1BE5208
void SetBones(::Array<UnityEngine::Transform*>* array, ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>*& bones);
// public override System.Void StoreDefaultLocalState()
// Offset: 0x1BE46DC
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::StoreDefaultLocalState()
void StoreDefaultLocalState();
// public override System.Void FixTransforms()
// Offset: 0x1BE480C
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::FixTransforms()
void FixTransforms();
// public override System.Boolean IsValid(ref System.String message)
// Offset: 0x1BE4950
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Boolean IKSolver::IsValid(ref System.String message)
bool IsValid(::Il2CppString*& message);
// public override RootMotion.FinalIK.IKSolver/Point[] GetPoints()
// Offset: 0x1BE4D80
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: RootMotion.FinalIK.IKSolver/Point[] IKSolver::GetPoints()
::Array<RootMotion::FinalIK::IKSolver::Point*>* GetPoints();
// public override RootMotion.FinalIK.IKSolver/Point GetPoint(UnityEngine.Transform transform)
// Offset: 0x1BE4FB8
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: RootMotion.FinalIK.IKSolver/Point IKSolver::GetPoint(UnityEngine.Transform transform)
RootMotion::FinalIK::IKSolver::Point* GetPoint(UnityEngine::Transform* transform);
// protected override System.Void OnInitiate()
// Offset: 0x1BE53AC
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::OnInitiate()
void OnInitiate();
// protected override System.Void OnUpdate()
// Offset: 0x1BE57F8
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::OnUpdate()
void OnUpdate();
// public System.Void .ctor()
// Offset: 0x1BE6750
// Implemented from: RootMotion.FinalIK.IKSolver
// Base method: System.Void IKSolver::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IKSolverLookAt* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::IKSolverLookAt::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IKSolverLookAt*, creationType>()));
}
}; // RootMotion.FinalIK.IKSolverLookAt
#pragma pack(pop)
static check_size<sizeof(IKSolverLookAt), 192 + sizeof(::Array<UnityEngine::Vector3>*)> __RootMotion_FinalIK_IKSolverLookAtSizeCheck;
static_assert(sizeof(IKSolverLookAt) == 0xC8);
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::IKSolverLookAt*, "RootMotion.FinalIK", "IKSolverLookAt");
| 50.86747 | 1,130 | 0.706063 | darknight1050 |
bb60f6a1b1d41a32bd5ac791dfccd0d914f586f4 | 3,143 | hpp | C++ | lib/charLib.hpp | captainpeng/6-6 | 67ba91f0a7d639b3778fc78bb5a253812d2c3029 | [
"MIT",
"Unlicense"
] | null | null | null | lib/charLib.hpp | captainpeng/6-6 | 67ba91f0a7d639b3778fc78bb5a253812d2c3029 | [
"MIT",
"Unlicense"
] | null | null | null | lib/charLib.hpp | captainpeng/6-6 | 67ba91f0a7d639b3778fc78bb5a253812d2c3029 | [
"MIT",
"Unlicense"
] | null | null | null | /*!
* \autor captainpeng
* \date 2018-12-29
* \update 2018-12-29
* \version 1.0
* \copyright
*/
#ifndef charLib_hpp
#define charLib_hpp
#include<cctype>
#include<cwctype>
namespace my{
template<typename CharT>
class charLib;
template<>
class charLib<char>{
public:
using charType=char;
static inline bool isalnum(charType ch){
return static_cast<bool>(std::isalnum(ch));
}
static inline bool isalpha(charType ch){
return static_cast<bool>(std::isalpha(ch));
}
static inline bool islower(charType ch){
return static_cast<bool>(std::islower(ch));
}
static inline bool isupper(charType ch){
return static_cast<bool>(std::isupper(ch));
}
static inline bool isdigit(charType ch){
return static_cast<bool>(std::isdigit(ch));
}
static inline bool isxdigit(charType ch){
return static_cast<bool>(std::isxdigit(ch));
}
static inline bool iscntrl(charType ch){
return static_cast<bool>(std::iscntrl(ch));
}
static inline bool isgraph(charType ch){
return static_cast<bool>(std::isgraph(ch));
}
static inline bool isspace(charType ch){
return static_cast<bool>(std::isspace(ch));
}
static inline bool isblank(charType ch){
return static_cast<bool>(std::isblank(ch));
}
static inline bool isprint(charType ch){
return static_cast<bool>(std::isprint(ch));
}
static inline bool ispunct(charType ch){
return static_cast<bool>(std::ispunct(ch));
}
static inline charType tolower(charType ch){
return static_cast<charType>(std::tolower(ch));
}
static inline charType toupper(charType ch){
return static_cast<charType>(std::toupper(ch));
}
};
template<>
class charLib<wchar_t>{
public:
using charType=wchar_t;
static inline bool isalnum(charType ch){
return static_cast<bool>(std::iswalnum(ch));
}
static inline bool isalpha(charType ch){
return static_cast<bool>(std::iswalpha(ch));
}
static inline bool islower(charType ch){
return static_cast<bool>(std::iswlower(ch));
}
static inline bool isupper(charType ch){
return static_cast<bool>(std::iswupper(ch));
}
static inline bool isdigit(charType ch){
return static_cast<bool>(std::iswdigit(ch));
}
static inline bool isxdigit(charType ch){
return static_cast<bool>(std::iswxdigit(ch));
}
static inline bool iscntrl(charType ch){
return static_cast<bool>(std::iswcntrl(ch));
}
static inline bool isgraph(charType ch){
return static_cast<bool>(std::iswgraph(ch));
}
static inline bool isspace(charType ch){
return static_cast<bool>(std::iswspace(ch));
}
static inline bool isblank(charType ch){
return static_cast<bool>(std::iswblank(ch));
}
static inline bool isprint(charType ch){
return static_cast<bool>(std::iswprint(ch));
}
static inline bool ispunct(charType ch){
return static_cast<bool>(std::iswpunct(ch));
}
static inline charType tolower(charType ch){
return static_cast<charType>(std::towlower(ch));
}
static inline charType toupper(charType ch){
return static_cast<charType>(std::towupper(ch));
}
};
}
#endif
| 21.09396 | 53 | 0.689787 | captainpeng |
bb6303130e8fe80b35a4a2da7dfc83c4d54ac643 | 3,363 | cpp | C++ | src/Window.cpp | jparimaa/varjo-dx11-minimal | 489e9db74edfbaa1e745e6eaa5eb12dc202bfc3d | [
"MIT"
] | null | null | null | src/Window.cpp | jparimaa/varjo-dx11-minimal | 489e9db74edfbaa1e745e6eaa5eb12dc202bfc3d | [
"MIT"
] | null | null | null | src/Window.cpp | jparimaa/varjo-dx11-minimal | 489e9db74edfbaa1e745e6eaa5eb12dc202bfc3d | [
"MIT"
] | null | null | null | #include "Window.h"
#include "Log.h"
#include "Utility.h"
#include <wrl/client.h>
namespace
{
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_ACTIVATEAPP:
break;
case WM_CHAR:
if (wParam == 0x1B) // ESC
{
PostQuitMessage(0);
}
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
break;
case WM_INPUT:
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MOUSEWHEEL:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_MOUSEHOVER:
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
} // namespace
Window::Window()
{
}
Window::~Window()
{
releaseDXPtr(m_swapChain);
}
void Window::init(HINSTANCE hInstance, int nCmdShow, IUnknown* device)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_APPLICATION);
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = "varjo-test";
wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_APPLICATION);
if (!RegisterClassEx(&wcex))
{
printError("Could not register window class");
abort();
}
m_instanceHandle = hInstance;
RECT rc = {0, 0, m_width, m_height};
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
m_windowHandle = CreateWindow("varjo-test", "Direct3D", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance, nullptr);
if (!m_windowHandle)
{
printError("Could not create window");
abort();
}
ShowWindow(m_windowHandle, nCmdShow);
Microsoft::WRL::ComPtr<IDXGIFactory> factory = nullptr;
const HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory));
DXGI_SWAP_CHAIN_DESC swapChainDesc{};
swapChainDesc.BufferCount = swapChainLength;
swapChainDesc.BufferDesc.Width = m_width;
swapChainDesc.BufferDesc.Height = m_height;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.OutputWindow = m_windowHandle;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.Windowed = TRUE;
HRESULT result = factory->CreateSwapChain(device, &swapChainDesc, &m_swapChain);
checkHresult(result);
}
IDXGISwapChain* Window::getSwapChain()
{
return m_swapChain;
}
void Window::present()
{
m_swapChain->Present(1, 0);
}
| 25.671756 | 189 | 0.679453 | jparimaa |
bb66baedfe2a51e6d6513d303d87005b1a4a3d01 | 245 | hpp | C++ | tests/EnjoLibTest/src/ThreadedLoopTplTest.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | 3 | 2021-06-14T15:36:46.000Z | 2022-02-28T15:16:08.000Z | tests/EnjoLibTest/src/ThreadedLoopTplTest.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | 1 | 2021-07-17T07:52:15.000Z | 2021-07-17T07:52:15.000Z | tests/EnjoLibTest/src/ThreadedLoopTplTest.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | 3 | 2021-07-12T14:52:38.000Z | 2021-11-28T17:10:33.000Z | #ifndef THREADEDLOOPTPLTEST_HPP
#define THREADEDLOOPTPLTEST_HPP
class ThreadedLoopTplTest
{
public:
ThreadedLoopTplTest();
virtual ~ThreadedLoopTplTest();
protected:
private:
};
#endif // THREADEDLOOPTPLTEST_HPP
| 14.411765 | 39 | 0.722449 | hlp2 |
bb6c2fc1c6f0b78a3df0f73d226dc65baf9209cf | 370 | cpp | C++ | solutions/beecrowd/1012/1012.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 18 | 2015-01-22T04:08:51.000Z | 2022-01-08T22:36:47.000Z | solutions/beecrowd/1012/1012.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 4 | 2016-04-25T12:32:46.000Z | 2021-06-15T18:01:30.000Z | solutions/beecrowd/1012/1012.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 25 | 2015-03-02T06:21:51.000Z | 2021-09-12T20:49:21.000Z | #include <cstdio>
#define pi 3.14159
int main() {
float a, b, c;
while (scanf("%f %f %f", &a, &b, &c) != EOF) {
printf("TRIANGULO: %.3f\n", a * c / 2);
printf("CIRCULO: %.3f\n", pi * (c * c));
printf("TRAPEZIO: %.3f\n", c * ((a + b) / 2));
printf("QUADRADO: %.3f\n", b * b);
printf("RETANGULO: %.3f\n", a * b);
}
}
| 23.125 | 54 | 0.437838 | deniscostadsc |
bb7007b7a9847aaa33a9fe86947eafde14b971cf | 1,484 | cc | C++ | src/carnot/planner/compiler/analyzer/resolve_metadata_property_rule.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 1,821 | 2020-04-08T00:45:27.000Z | 2021-09-01T14:56:25.000Z | src/carnot/planner/compiler/analyzer/resolve_metadata_property_rule.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 142 | 2020-04-09T06:23:46.000Z | 2021-08-24T06:02:12.000Z | src/carnot/planner/compiler/analyzer/resolve_metadata_property_rule.cc | hangqiu/pixie | 1dd4af47d40ff856c4d52a1d6de81f78a76ff31e | [
"Apache-2.0"
] | 105 | 2021-09-08T10:26:50.000Z | 2022-03-29T09:13:36.000Z | /*
* Copyright 2018- The Pixie Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "src/carnot/planner/compiler/analyzer/resolve_metadata_property_rule.h"
namespace px {
namespace carnot {
namespace planner {
namespace compiler {
StatusOr<bool> ResolveMetadataPropertyRule::Apply(IRNode* ir_node) {
if (!Match(ir_node, Metadata())) {
return false;
}
auto metadata = static_cast<MetadataIR*>(ir_node);
if (metadata->has_property()) {
return false;
}
// Check to see whether metadata is valid.
if (!md_handler_->HasProperty(metadata->name())) {
return metadata->CreateIRNodeError("'$0' unavailable metadata key.", metadata->name());
}
PL_ASSIGN_OR_RETURN(MetadataProperty * md_property, md_handler_->GetProperty(metadata->name()));
metadata->set_property(md_property);
return true;
}
} // namespace compiler
} // namespace planner
} // namespace carnot
} // namespace px
| 30.285714 | 98 | 0.727089 | hangqiu |
bb73c42cfd1672b2dacbf2f87caabe1641b86080 | 492 | cpp | C++ | Engine/Source/UISliderComponent.cpp | Osvak/TurboTribble | fd4f565d2fb67894adc138d0446ffb8cf24323e6 | [
"MIT"
] | null | null | null | Engine/Source/UISliderComponent.cpp | Osvak/TurboTribble | fd4f565d2fb67894adc138d0446ffb8cf24323e6 | [
"MIT"
] | 1 | 2022-01-18T16:30:42.000Z | 2022-01-18T16:30:42.000Z | Engine/Source/UISliderComponent.cpp | Osvak/TurboTribble | fd4f565d2fb67894adc138d0446ffb8cf24323e6 | [
"MIT"
] | null | null | null | #include "Application.h"
#include "SDL.h"
#include "UISliderComponent.h"
#include "ModuleCamera3D.h"
#include "CameraComponent.h"
UISliderComponent::UISliderComponent(int id, std::string text)
{
type = ComponentType::UI_SLIDER;
value = 0;
minValue = 50;
maxValue = 100;
sliderText.SetText(text, float2(5, 5), 0.5f, float4(255,255,255,255));
}
UISliderComponent::~UISliderComponent()
{
}
bool UISliderComponent::Update(float dt)
{
return true;
}
void UISliderComponent::Draw()
{
} | 16.965517 | 71 | 0.727642 | Osvak |
bb74cdb8f97444680bafab6b6d9d3bcf49ccaa0a | 3,009 | cc | C++ | client/src/client.cc | zinhart/kvs | decac5308007bde0921f50200cf76d81b2b32251 | [
"MIT"
] | null | null | null | client/src/client.cc | zinhart/kvs | decac5308007bde0921f50200cf76d81b2b32251 | [
"MIT"
] | null | null | null | client/src/client.cc | zinhart/kvs | decac5308007bde0921f50200cf76d81b2b32251 | [
"MIT"
] | null | null | null | //#include "common"
#include <iostream>
#include <algorithm>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "4000" // the port client will be connecting to
#define MAXDATASIZE 100 // max number of bytes we can get at once
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET)
{
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
if(argc <= 4)
{
std::cerr<<"USAGE: ./client <hostname> <portnum> <cmds>\n";
std::cerr<<"ACTIONS: <GET> key\n<PUT> <key> <value>\n<Delete> <key> <value>\n";
std::exit(1);
}
std::int32_t error, i;
std::string packet_buffer;
std::uint32_t packet_length;
char * host_name, * port, * cmd, * key, * value;
host_name = argv[1];
port = argv[2];
cmd = argv[3];
key = argv[4];
value = (argc <= 4) ? NULL : argv[5];
std::int32_t sockfd, numbytes;
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(host_name, port, &hints, &servinfo)) != 0)
{
//std::cerr<<"getaddrinfo: %s\n", gai_strerror(rv)<<"\n";
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
{
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
perror("client: connect");
close(sockfd);
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
printf("client: connecting to %s\n", s);
std::uint32_t size = 1 + strlen(cmd) + strlen(key) + (value == NULL) ? 0 : strlen(value);
char packet[size];
strcpy(packet,cmd);
strcpy(packet+ strlen(cmd), key);
(value == NULL) ? 0 : strcpy(packet+ strlen(key), value) ;
freeaddrinfo(servinfo); // all done with this structur
printf("packet: %s %s %s length %d\n", packet, cmd, key,strlen(packet));
//send command, key, and possibly value
if( (numbytes = sendto(sockfd, packet, strlen(packet), 0, p->ai_addr, p->ai_addrlen)) == -1)
{
std::cerr<<"sendto\n";
std::exit(1);
}
//recieve value strlen(cmd) determins the number of bytes to wait for and must be coordinated with what the server sends
if ((numbytes = recv(sockfd, packet, strlen(packet), 0)) == -1)
{
std::cerr<<"recv\n";
std::exit(1);
}
packet[numbytes] = '\0';
printf("client: received '%s'\n", packet);
close(sockfd);
return 0;
}
| 27.354545 | 122 | 0.636092 | zinhart |
bb74d5a004cf7c24fff1b74c9805452df806caf5 | 114 | cpp | C++ | source/serviceclass/worklist_scp.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 15 | 2016-01-28T16:54:57.000Z | 2021-04-16T08:28:21.000Z | source/serviceclass/worklist_scp.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | null | null | null | source/serviceclass/worklist_scp.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 3 | 2016-07-16T05:22:11.000Z | 2020-04-03T08:59:26.000Z | #include "worklist_scp.hpp"
namespace dicom
{
namespace serviceclass
{
worklist_scp::worklist_scp()
{
}
}
}
| 6.705882 | 28 | 0.710526 | mariusherzog |
bb7c7240b9401b01a5f4e04705dcf6c9f67ba5f7 | 860 | cpp | C++ | Neps/Problems/Times - 253.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | Neps/Problems/Times - 253.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | Neps/Problems/Times - 253.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int n, t;
vector < pair <int, string> > alunos;
vector <string> times[1005];
int main (){
string name;
int h;
cin >> n >> t;
for (int i = 0; i < n; i++){
cin >> name >> h;
alunos.emplace_back(h, name);
}
sort (alunos.begin(), alunos.end());
n--;
int cont = 0;
while (n >= 0){
times[cont].push_back(alunos[n].second);
n--;
if (cont == t-1){
cont=0;
continue;
}
cont++;
}
for(int i = 0; i < t; i++){
sort(times[i].begin(), times[i].end());
}
for(int i = 0; i < t; i++){
cout << "Time " << i+1 << endl;
for (int j = 0; j < times[i].size(); j++){
cout << times[i][j] << endl;
}
cout << endl;
}
return 0;
} | 18.297872 | 50 | 0.417442 | lucaswilliamgomes |
bb7daab5fb3f1ee0a87ed71b096707a6165d1857 | 3,820 | cpp | C++ | GLUI/GLCommandPanel.cpp | chen0040/cpp-steering-behaviors | c73d2ae8037556d42440b54ba6eb6190e467fae9 | [
"MIT"
] | 2 | 2020-11-10T12:24:41.000Z | 2021-09-25T08:24:06.000Z | GLUI/GLCommandPanel.cpp | chen0040/cpp-steering-behaviors | c73d2ae8037556d42440b54ba6eb6190e467fae9 | [
"MIT"
] | null | null | null | GLUI/GLCommandPanel.cpp | chen0040/cpp-steering-behaviors | c73d2ae8037556d42440b54ba6eb6190e467fae9 | [
"MIT"
] | 1 | 2021-08-14T16:34:33.000Z | 2021-08-14T16:34:33.000Z | #include "GLCommandPanel.h"
#include "GLFlowLayout.h"
#include <iostream>
#include <cassert>
GLCommandPanel::GLCommandPanel(GLLayout* pLayout)
: GLUIObj()
, m_pEventReceiver_MouseButtonDown(NULL)
, m_pEventReceiver_MouseButtonUp(NULL)
, m_pEventReceiver_MouseMoved(NULL)
, m_bShowPanel(false)
{
if(pLayout==NULL)
{
m_pLayout=new GLFlowLayout(GLFlowLayout::HORIZONTAL_ALIGNMENT);
m_pLayout->SetParent(this);
}
else
{
m_pLayout=pLayout;
m_pLayout->SetParent(this);
}
SetBoundingRect(0, 640, 0, 480);
}
void GLCommandPanel::SetLayout(GLLayout* pLayout)
{
assert(!pLayout==NULL);
if(m_pLayout != NULL)
{
delete m_pLayout;
m_pLayout=NULL;
}
m_pLayout=pLayout;
m_pLayout->SetParent(this);
}
GLCommandPanel::~GLCommandPanel()
{
if(m_pLayout != NULL)
{
delete m_pLayout;
m_pLayout=NULL;
}
}
void GLCommandPanel::MouseButtonDown(const int& iButton, const int& iX, const int& iY, const int& iXRel, const int& iYRel)
{
if(!m_bVisible)
{
return;
}
m_pEventReceiver_MouseButtonDown=NULL;
m_pLayout->MouseButtonDown(iButton, iX, iY, iXRel, iYRel);
}
void GLCommandPanel::MouseButtonUp(const int& iButton, const int& iX, const int& iY, const int& iXRel, const int& iYRel)
{
if(!m_bVisible)
{
return;
}
m_pEventReceiver_MouseButtonUp=NULL;
m_pLayout->MouseButtonUp(iButton, iX, iY, iXRel, iYRel);
}
void GLCommandPanel::MouseMoved(const int& iButton, const int& iX, const int& iY, const int& iXRel, const int& iYRel)
{
if(!m_bVisible)
{
return;
}
m_pEventReceiver_MouseMoved=NULL;
m_pLayout->MouseMoved(iButton, iX, iY, iXRel, iYRel);
}
void GLCommandPanel::EventNotified_MouseButtonDown(GLUIObj* pSender)
{
GLUIObj::EventNotified_MouseButtonDown(pSender);
m_pEventReceiver_MouseButtonDown=pSender;
}
void GLCommandPanel::EventNotified_MouseButtonUp(GLUIObj* pSender)
{
GLUIObj::EventNotified_MouseButtonDown(pSender);
m_pEventReceiver_MouseButtonUp=pSender;
}
void GLCommandPanel::EventNotified_MouseMoved(GLUIObj* pSender)
{
GLUIObj::EventNotified_MouseMoved(pSender);
m_pEventReceiver_MouseMoved=pSender;
}
void GLCommandPanel::AddUIObj(GLUIObj* pObj)
{
m_pLayout->AddUIObj(pObj);
}
void GLCommandPanel::AddUIObj(int row, int col, GLUIObj* pObj)
{
m_pLayout->AddUIObj(row, col, pObj);
}
void GLCommandPanel::AddUIObj(GLUIObj* pObj, int position)
{
m_pLayout->AddUIObj(pObj, position);
}
GLUIObj* GLCommandPanel::GetUIObj(int position) const
{
return m_pLayout->GetUIObj(position);
}
GLUIObj* GLCommandPanel::GetUIObj(int row, int col) const
{
return m_pLayout->GetUIObj(row, col);
}
void GLCommandPanel::RemoveUIObj(int position)
{
m_pLayout->RemoveUIObj(position);
}
void GLCommandPanel::RemoveUIObj(int row, int col)
{
m_pLayout->RemoveUIObj(row, col);
}
void GLCommandPanel::ClearUIObjs()
{
m_pLayout->ClearUIObjs();
}
void GLCommandPanel::PreRender()
{
if(!m_bVisible)
{
return;
}
GLint matViewport[4];
glGetIntegerv(GL_VIEWPORT, matViewport);
double window_width=static_cast<double>(matViewport[2]);
double window_height=static_cast<double>(matViewport[3]);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, window_width, window_height, 0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
void GLCommandPanel::PostRender()
{
if(!m_bVisible)
{
return;
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
void GLCommandPanel::Render()
{
if(!m_bVisible)
{
return;
}
if(m_bShowPanel)
{
RenderPanel();
}
m_pLayout->Render();
}
void GLCommandPanel::RenderPanel()
{
if(!m_bVisible)
{
return;
}
GLRect rect=GetInsettedRect();
glBegin(GL_LINE_LOOP);
glVertex2d(rect.left, rect.top);
glVertex2d(rect.right, rect.top);
glVertex2d(rect.right, rect.bottom);
glVertex2d(rect.left, rect.bottom);
glEnd();
} | 18.277512 | 122 | 0.746859 | chen0040 |
bb8077bce9382641ac4a9e679a37e38709e22767 | 445 | cpp | C++ | LoveBabbar/05_linked_list/16_check_if_circular_linklist.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | LoveBabbar/05_linked_list/16_check_if_circular_linklist.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | LoveBabbar/05_linked_list/16_check_if_circular_linklist.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | /*
link: https://practice.geeksforgeeks.org/problems/circular-linked-list/1#
*/
// ----------------------------------------------------------------------------------------------------------------------- //
bool isCircular(Node* head)
{
// Your code here
if (head->next == NULL) return 0;
Node* curr = head->next;
while (curr->next && curr->next != head) curr = curr->next;
return curr->next == head;
} | 26.176471 | 126 | 0.417978 | Next-Gen-UI |
bb82118acf1af34ea093d1ef19a9bc66ba77650d | 2,470 | cpp | C++ | libs/tex/generate_texture_views.cpp | sucongCJS/mvs-texturing | 413ad0619eaadb1a9416ae347ff1f9989b29ca59 | [
"BSD-3-Clause"
] | null | null | null | libs/tex/generate_texture_views.cpp | sucongCJS/mvs-texturing | 413ad0619eaadb1a9416ae347ff1f9989b29ca59 | [
"BSD-3-Clause"
] | null | null | null | libs/tex/generate_texture_views.cpp | sucongCJS/mvs-texturing | 413ad0619eaadb1a9416ae347ff1f9989b29ca59 | [
"BSD-3-Clause"
] | null | null | null | #include <util/timer.h>
#include <util/tokenizer.h>
#include <util/file_system.h>
#include <mve/image_io.h>
#include <mve/image_tools.h>
#include <mve/bundle_io.h>
#include <mve/scene.h>
#include "texturing.h"
#include "progress_counter.h"
TEX_NAMESPACE_BEGIN
void from_mve_scene(std::string const & scene_dir, std::string const & image_name, TextureViews * texture_views){
mve::Scene::Ptr scene;
try{
scene = mve::Scene::create(scene_dir);
}
catch(std::exception & e){
std::cerr<<"无法打开scene目录: "<<e.what()<<std::endl;
std::exit(EXIT_FAILURE);
}
std::size_t num_views = scene->get_views().size();
texture_views->reserve(num_views);
ProgressCounter view_counter("\t加载视角图片: ", num_views);
for(std::size_t i=0; i<num_views; ++i){ // 遍历每一个view
view_counter.progress<SIMPLE>();
mve::View::Ptr view = scene->get_view_by_id(i);
if(view == NULL){
view_counter.inc();
continue;
}
if(!view->has_image(image_name, mve::IMAGE_TYPE_UINT8)){
std::cout<<"警告: 视角"<<view->get_name()<<"没有字节图片"<<image_name<<std::endl;
continue;
}
mve::View::ImageProxy const * image_proxy = view->get_image_proxy(image_name);
if (image_proxy->channels < 3) {
std::cerr<<"图片"<<image_name<<"在视角"<<view->get_name()<<"中不是三通道的图片!"<<std::endl;
exit(EXIT_FAILURE);
}
texture_views->push_back(
TextureView(view->get_id(), view->get_camera(), util::fs::abspath(util::fs::join_path(view->get_directory(), image_proxy->filename))));
view_counter.inc();
}
}
void generate_texture_views(std::string const & in_scene, TextureViews * texture_views, std::string const & tmp_dir){
/* MVE_SCENE::EMBEDDING */
size_t pos = in_scene.rfind("::");
if (pos != std::string::npos) {
std::string scene_dir = in_scene.substr(0, pos);
std::string image_name = in_scene.substr(pos + 2, in_scene.size());
from_mve_scene(scene_dir, image_name, texture_views);
}
std::sort(texture_views->begin(), texture_views->end(),
[] (TextureView const & l, TextureView const & r) -> bool {
return l.get_id() < r.get_id();
}
); // 按id排序
std::size_t num_views = texture_views->size();
if(num_views == 0){
std::cerr<< "没有正确地导入scene目录里的内容"<< std::endl;
exit(EXIT_FAILURE);
}
}
TEX_NAMESPACE_END | 31.265823 | 147 | 0.615385 | sucongCJS |
bb83045231c80ed464ddaed973569050f5d4e5c6 | 1,779 | cpp | C++ | src/layers/PostSSAOLayer.cpp | QtOpenGL/tp_maps-_OpenGL_engine | cc5fdc60c393cedf5572d9221a8c75ce0237f88c | [
"MIT"
] | null | null | null | src/layers/PostSSAOLayer.cpp | QtOpenGL/tp_maps-_OpenGL_engine | cc5fdc60c393cedf5572d9221a8c75ce0237f88c | [
"MIT"
] | null | null | null | src/layers/PostSSAOLayer.cpp | QtOpenGL/tp_maps-_OpenGL_engine | cc5fdc60c393cedf5572d9221a8c75ce0237f88c | [
"MIT"
] | 4 | 2018-08-30T10:01:30.000Z | 2020-10-07T10:55:11.000Z | #include "tp_maps/layers/PostSSAOLayer.h"
#include "tp_maps/shaders/PostSSAOShader.h"
#include "tp_maps/Map.h"
namespace tp_maps
{
//##################################################################################################
struct PostSSAOLayer::Private
{
PostSSAOLayer* q;
PostSSAOParameters parameters;
//################################################################################################
void recompileShaders()
{
if(q->map())
q->map()->deleteShader(PostSSAOShader::name());
}
//################################################################################################
Private(PostSSAOLayer* q_):
q(q_)
{
}
};
//##################################################################################################
PostSSAOLayer::PostSSAOLayer(Map* map, RenderPass customRenderPass):
PostLayer(map, customRenderPass),
d(new Private(this))
{
}
//##################################################################################################
PostSSAOLayer::~PostSSAOLayer()
{
delete d;
}
//##################################################################################################
const PostSSAOParameters& PostSSAOLayer::parameters() const
{
return d->parameters;
}
//##################################################################################################
void PostSSAOLayer::setParameters(const PostSSAOParameters& parameters)
{
d->parameters = parameters;
d->recompileShaders();
}
//##################################################################################################
PostShader* PostSSAOLayer::makeShader()
{
return map()->getShader<PostSSAOShader>([&](Map* m, tp_maps::OpenGLProfile p)
{
return new PostSSAOShader(m, p, d->parameters);
});
}
}
| 26.954545 | 100 | 0.38561 | QtOpenGL |
bb86061ddafa9c5754ce5e20b43c1402fdc18c74 | 4,649 | cpp | C++ | PolarisV2/world_inspector.cpp | QPixel/Polaris | 42f09e35afb2027b535fe5ca6a8c96fd1dc2cc86 | [
"BSD-2-Clause"
] | 5 | 2021-07-27T20:44:44.000Z | 2021-12-27T15:47:11.000Z | PolarisV2/world_inspector.cpp | NathanTurnYT/Polaris | ec0d0b6f4ff6dd9a9a30f8273ac4c0fa26219210 | [
"BSD-2-Clause"
] | null | null | null | PolarisV2/world_inspector.cpp | NathanTurnYT/Polaris | ec0d0b6f4ff6dd9a9a30f8273ac4c0fa26219210 | [
"BSD-2-Clause"
] | 1 | 2021-01-08T21:41:46.000Z | 2021-01-08T21:41:46.000Z | #include "world_inspector.h"
#include "ui_renderer.h"
#include "globals.h"
#include "imgui_text_extension.h"
#include "sdk_utils.h"
#include "json.hpp"
#include <iostream>
#include <fstream>
using json = nlohmann::json;
namespace polaris::ui::window::windows
{
WorldInspector::WorldInspector()
{
}
void WorldInspector::Draw()
{
auto world = (*globals::gpWorld);
ImGui::SetNextWindowSize(ImVec2(820, 440), ImGuiCond_Appearing);
ImGui::Begin("World Inspector", &m_bIsOpen);
{
if (world == nullptr || (world && world->Levels.Count == 0))
{
ImGui::SetCursorPosX(ImGui::GetWindowWidth() / 2 - ImGui::CalcTextSize("There's no levels loaded!").x / 1.15f);
ImGui::SetCursorPosY(ImGui::GetWindowHeight() / 2);
ImGui::Header("There's no levels loaded!");
ImGui::End();
return;
}
static int selectedLevel = 0;
static int selectedActor = 0;
{
ImGui::BeginChild("Hierarchy", ImVec2(300, 0), true);
{
for (int i = 0; i < world->Levels.Count; i++)
{
if (world->Levels.IsValidIndex(i) && world->Levels[i])
{
auto level = world->Levels[i];
auto name = level->GetFullName();
auto formattedName = name.substr(0, name.find(".")).substr(5, name.length() - 1);
if (ImGui::TreeNode(formattedName.c_str()))
{
for (int j = 0; j < level->Actors.Count; j++)
{
if (level->Actors.IsValidIndex(j) && level->Actors[j])
{
auto actor = level->Actors[j];
if (ImGui::Selectable(actor->GetName().c_str(), selectedActor == j && selectedLevel == i))
{
selectedLevel = i;
selectedActor = j;
}
}
}
ImGui::TreePop();
}
}
}
ImGui::EndChild();
}
}
ImGui::SameLine();
auto level = world->Levels[selectedLevel];
auto actor = level->Actors[selectedActor];
if (actor)
{
bool actorHasAuthority = actor->HasAuthority();
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::BeginChild("Inspector", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()));
{
ImGui::Header2(actor->GetName().c_str());
ImGui::Separator();
{
ImGui::TextWrapped("ID: %s", actor->GetFullName().c_str());
auto location = actor->K2_GetActorLocation();
ImGui::TextWrapped("Position: (%d, %d, %d)", location.X, location.Y, location.Z);
auto rotation = actor->K2_GetActorRotation();
ImGui::TextWrapped("Rotation: (%d, %d, %d)", rotation.Pitch, rotation.Roll, rotation.Yaw);
auto scale = actor->GetActorScale3D();
ImGui::TextWrapped("Scale: (%d, %d, %d)", scale.X, scale.Y, scale.Z);
ImGui::Separator();
}
{
auto ownerLabel = actor->Owner != nullptr ? actor->Owner->GetName().c_str() : "None";
ImGui::TextWrapped("Owner: %s", ownerLabel);
auto authorityLabel = actor->HasAuthority() ? "Yes" : "No";
ImGui::TextWrapped("Has Authority: %s", authorityLabel);
}
ImGui::EndChild();
}
if (ImGui::Button("Destroy"))
actor->K2_DestroyActor();
ImGui::SameLine();
if (ImGui::Button("Toggle Authority"))
actor->Role = actorHasAuthority ? SDK::ENetRole::ROLE_None : SDK::ENetRole::ROLE_Authority;
ImGui::EndGroup();
}
ImGui::End();
}
}
} | 36.606299 | 130 | 0.422456 | QPixel |
bb8a200aea6523c5d3ee51471472beb68474090c | 659 | cpp | C++ | src/0028.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | 38 | 2020-03-05T06:38:32.000Z | 2022-03-11T02:32:14.000Z | src/0028.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | null | null | null | src/0028.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | 16 | 2020-04-02T15:13:20.000Z | 2022-02-25T07:34:35.000Z | class Solution {
public:
int strStr(string haystack, string needle) {
if (empty(needle)) {
return 0;
}
vector<int> pi(size(needle));
for (int i = 1, j = 0; i < size(pi); ++i) {
while (j > 0 && needle[i] != needle[j]) {
j = pi[j - 1];
}
if (needle[i] == needle[j]) {
++j;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < size(haystack); ++i) {
while (j > 0 && haystack[i] != needle[j]) {
j = pi[j - 1];
}
if (haystack[i] == needle[j]) {
++j;
}
if (j == size(needle)) {
return i - size(needle) + 1;
}
}
return -1;
}
};
| 21.258065 | 53 | 0.408194 | downdemo |
bb8c518dce6e9213ebd9845de0af88e4efde6f6e | 420 | hpp | C++ | include/HelloWorldApplication.hpp | smac89/witty-helloworld | 68f4818937de18f04722e41e4efd0c40ab4736a5 | [
"WTFPL"
] | null | null | null | include/HelloWorldApplication.hpp | smac89/witty-helloworld | 68f4818937de18f04722e41e4efd0c40ab4736a5 | [
"WTFPL"
] | null | null | null | include/HelloWorldApplication.hpp | smac89/witty-helloworld | 68f4818937de18f04722e41e4efd0c40ab4736a5 | [
"WTFPL"
] | null | null | null | #ifndef WITTYHELLOWORLD_HELLOWORLD_HPP
#define WITTYHELLOWORLD_HELLOWORLD_HPP
#include <Wt/WApplication.h>
#include <Wt/WLineEdit.h>
#include <Wt/WText.h>
class HelloWorldApplication: public Wt::WApplication {
public:
explicit HelloWorldApplication(const Wt::WEnvironment &environment);
private:
Wt::WLineEdit *nameEdit;
Wt::WText *greeting;
void greet();
};
#endif //WITTYHELLOWORLD_HELLOWORLD_HPP
| 21 | 72 | 0.771429 | smac89 |
bb8e551dcd238ce79eec1dcd1753190f77bb5def | 41,117 | cpp | C++ | blades/xbmc/xbmc/pictures/GUIWindowSlideShow.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/pictures/GUIWindowSlideShow.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/pictures/GUIWindowSlideShow.cpp | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "threads/SystemClock.h"
#include "system.h"
#include "GUIWindowSlideShow.h"
#include "Application.h"
#include "messaging/ApplicationMessenger.h"
#include "utils/URIUtils.h"
#include "URL.h"
#include "guilib/TextureManager.h"
#include "guilib/GUILabelControl.h"
#include "input/Key.h"
#include "GUIInfoManager.h"
#include "filesystem/Directory.h"
#include "GUIDialogPictureInfo.h"
#include "GUIUserMessages.h"
#include "guilib/GUIWindowManager.h"
#include "settings/DisplaySettings.h"
#include "settings/Settings.h"
#include "FileItem.h"
#include "guilib/Texture.h"
#include "windowing/WindowingFactory.h"
#include "guilib/LocalizeStrings.h"
#include "threads/SingleLock.h"
#include "utils/log.h"
#include "utils/Variant.h"
#include "interfaces/AnnouncementManager.h"
#include "pictures/GUIViewStatePictures.h"
#include "pictures/PictureThumbLoader.h"
using namespace XFILE;
using namespace KODI::MESSAGING;
#define MAX_ZOOM_FACTOR 10
#define MAX_PICTURE_SIZE 2048*2048
#define IMMEDIATE_TRANSISTION_TIME 20
#define PICTURE_MOVE_AMOUNT 0.02f
#define PICTURE_MOVE_AMOUNT_ANALOG 0.01f
#define PICTURE_MOVE_AMOUNT_TOUCH 0.002f
#define PICTURE_VIEW_BOX_COLOR 0xffffff00 // YELLOW
#define PICTURE_VIEW_BOX_BACKGROUND 0xff000000 // BLACK
#define ROTATION_SNAP_RANGE 10.0f
#define FPS 25
#define BAR_IMAGE 1
#define LABEL_ROW1 10
#define LABEL_ROW2 11
#define LABEL_ROW2_EXTRA 12
#define CONTROL_PAUSE 13
static float zoomamount[10] = { 1.0f, 1.2f, 1.5f, 2.0f, 2.8f, 4.0f, 6.0f, 9.0f, 13.5f, 20.0f };
CBackgroundPicLoader::CBackgroundPicLoader() : CThread("BgPicLoader")
{
m_pCallback = NULL;
m_isLoading = false;
}
CBackgroundPicLoader::~CBackgroundPicLoader()
{
StopThread();
}
void CBackgroundPicLoader::Create(CGUIWindowSlideShow *pCallback)
{
m_pCallback = pCallback;
m_isLoading = false;
CThread::Create(false);
}
void CBackgroundPicLoader::Process()
{
unsigned int totalTime = 0;
unsigned int count = 0;
while (!m_bStop)
{ // loop around forever, waiting for the app to call LoadPic
if (AbortableWait(m_loadPic,10) == WAIT_SIGNALED)
{
if (m_pCallback)
{
unsigned int start = XbmcThreads::SystemClockMillis();
CBaseTexture* texture = CTexture::LoadFromFile(m_strFileName, m_maxWidth, m_maxHeight);
totalTime += XbmcThreads::SystemClockMillis() - start;
count++;
// tell our parent
bool bFullSize = false;
if (texture)
{
bFullSize = ((int)texture->GetWidth() < m_maxWidth) && ((int)texture->GetHeight() < m_maxHeight);
if (!bFullSize)
{
int iSize = texture->GetWidth() * texture->GetHeight() - MAX_PICTURE_SIZE;
if ((iSize + (int)texture->GetWidth() > 0) || (iSize + (int)texture->GetHeight() > 0))
bFullSize = true;
if (!bFullSize && texture->GetWidth() == g_Windowing.GetMaxTextureSize())
bFullSize = true;
if (!bFullSize && texture->GetHeight() == g_Windowing.GetMaxTextureSize())
bFullSize = true;
}
}
m_pCallback->OnLoadPic(m_iPic, m_iSlideNumber, m_strFileName, texture, bFullSize);
m_isLoading = false;
}
}
}
if (count > 0)
CLog::Log(LOGDEBUG, "Time for loading %u images: %u ms, average %u ms",
count, totalTime, totalTime / count);
}
void CBackgroundPicLoader::LoadPic(int iPic, int iSlideNumber, const std::string &strFileName, const int maxWidth, const int maxHeight)
{
m_iPic = iPic;
m_iSlideNumber = iSlideNumber;
m_strFileName = strFileName;
m_maxWidth = maxWidth;
m_maxHeight = maxHeight;
m_isLoading = true;
m_loadPic.Set();
}
CGUIWindowSlideShow::CGUIWindowSlideShow(void)
: CGUIWindow(WINDOW_SLIDESHOW, "SlideShow.xml")
{
m_pBackgroundLoader = NULL;
m_slides = new CFileItemList;
m_Resolution = RES_INVALID;
m_loadType = KEEP_IN_MEMORY;
Reset();
}
CGUIWindowSlideShow::~CGUIWindowSlideShow(void)
{
Reset();
delete m_slides;
}
void CGUIWindowSlideShow::AnnouncePlayerPlay(const CFileItemPtr& item)
{
CVariant param;
param["player"]["speed"] = m_bSlideShow && !m_bPause ? 1 : 0;
param["player"]["playerid"] = PLAYLIST_PICTURE;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Player, "xbmc", "OnPlay", item, param);
}
void CGUIWindowSlideShow::AnnouncePlayerPause(const CFileItemPtr& item)
{
CVariant param;
param["player"]["speed"] = 0;
param["player"]["playerid"] = PLAYLIST_PICTURE;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Player, "xbmc", "OnPause", item, param);
}
void CGUIWindowSlideShow::AnnouncePlayerStop(const CFileItemPtr& item)
{
CVariant param;
param["player"]["playerid"] = PLAYLIST_PICTURE;
param["end"] = true;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Player, "xbmc", "OnStop", item, param);
}
void CGUIWindowSlideShow::AnnouncePlaylistRemove(int pos)
{
CVariant data;
data["playlistid"] = PLAYLIST_PICTURE;
data["position"] = pos;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Playlist, "xbmc", "OnRemove", data);
}
void CGUIWindowSlideShow::AnnouncePlaylistClear()
{
CVariant data;
data["playlistid"] = PLAYLIST_PICTURE;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Playlist, "xbmc", "OnClear", data);
}
void CGUIWindowSlideShow::AnnouncePlaylistAdd(const CFileItemPtr& item, int pos)
{
CVariant data;
data["playlistid"] = PLAYLIST_PICTURE;
data["position"] = pos;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Playlist, "xbmc", "OnAdd", item, data);
}
void CGUIWindowSlideShow::AnnouncePropertyChanged(const std::string &strProperty, const CVariant &value)
{
if (strProperty.empty() || value.isNull())
return;
CVariant data;
data["player"]["playerid"] = PLAYLIST_PICTURE;
data["property"][strProperty] = value;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Player, "xbmc", "OnPropertyChanged", data);
}
bool CGUIWindowSlideShow::IsPlaying() const
{
return m_Image[m_iCurrentPic].IsLoaded();
}
void CGUIWindowSlideShow::Reset()
{
g_infoManager.SetShowCodec(false);
m_bSlideShow = false;
m_bShuffled = false;
m_bPause = false;
m_bPlayingVideo = false;
m_bErrorMessage = false;
m_Image[0].UnLoad();
m_Image[0].Close();
m_Image[1].UnLoad();
m_Image[1].Close();
m_fRotate = 0.0f;
m_fInitialRotate = 0.0f;
m_iZoomFactor = 1;
m_fZoom = 1.0f;
m_fInitialZoom = 0.0f;
m_iCurrentSlide = 0;
m_iNextSlide = 1;
m_iCurrentPic = 0;
m_iDirection = 1;
m_iLastFailedNextSlide = -1;
CSingleLock lock(m_slideSection);
m_slides->Clear();
AnnouncePlaylistClear();
m_Resolution = g_graphicsContext.GetVideoResolution();
}
void CGUIWindowSlideShow::OnDeinitWindow(int nextWindowID)
{
if (m_Resolution != CDisplaySettings::GetInstance().GetCurrentResolution())
{
//FIXME: Use GUI resolution for now
//g_graphicsContext.SetVideoResolution(CDisplaySettings::GetInstance().GetCurrentResolution(), TRUE);
}
// Reset();
if (nextWindowID != WINDOW_PICTURES)
m_ImageLib.Unload();
if (nextWindowID != WINDOW_FULLSCREEN_VIDEO)
{
// wait for any outstanding picture loads
if (m_pBackgroundLoader)
{
// sleep until the loader finishes loading the current pic
CLog::Log(LOGDEBUG,"Waiting for BackgroundLoader thread to close");
while (m_pBackgroundLoader->IsLoading())
Sleep(10);
// stop the thread
CLog::Log(LOGDEBUG,"Stopping BackgroundLoader thread");
m_pBackgroundLoader->StopThread();
delete m_pBackgroundLoader;
m_pBackgroundLoader = NULL;
}
// and close the images.
m_Image[0].Close();
m_Image[1].Close();
}
g_infoManager.ResetCurrentSlide();
CGUIWindow::OnDeinitWindow(nextWindowID);
}
void CGUIWindowSlideShow::Add(const CFileItem *picture)
{
CFileItemPtr item(new CFileItem(*picture));
if (!item->HasVideoInfoTag() && !item->HasPictureInfoTag())
{
// item without tag; get mimetype then we can tell whether it's video item
item->FillInMimeType();
if (!item->IsVideo())
// then it is a picture and force tag generation
item->GetPictureInfoTag();
}
AnnouncePlaylistAdd(item, m_slides->Size());
m_slides->Add(item);
}
void CGUIWindowSlideShow::ShowNext()
{
if (m_slides->Size() == 1)
return;
m_iDirection = 1;
m_iNextSlide = GetNextSlide();
m_iZoomFactor = 1;
m_fZoom = 1.0f;
m_fRotate = 0.0f;
m_bLoadNextPic = true;
}
void CGUIWindowSlideShow::ShowPrevious()
{
if (m_slides->Size() == 1)
return;
m_iDirection = -1;
m_iNextSlide = GetNextSlide();
m_iZoomFactor = 1;
m_fZoom = 1.0f;
m_fRotate = 0.0f;
m_bLoadNextPic = true;
}
void CGUIWindowSlideShow::Select(const std::string& strPicture)
{
for (int i = 0; i < m_slides->Size(); ++i)
{
const CFileItemPtr item = m_slides->Get(i);
if (item->GetPath() == strPicture)
{
m_iDirection = 1;
if (!m_Image[m_iCurrentPic].IsLoaded() && (!m_pBackgroundLoader || !m_pBackgroundLoader->IsLoading()))
{
// will trigger loading current slide when next Process call.
m_iCurrentSlide = i;
m_iNextSlide = GetNextSlide();
}
else
{
m_iNextSlide = i;
m_bLoadNextPic = true;
}
return ;
}
}
}
const CFileItemList &CGUIWindowSlideShow::GetSlideShowContents()
{
return *m_slides;
}
void CGUIWindowSlideShow::GetSlideShowContents(CFileItemList &list)
{
for (int index = 0; index < m_slides->Size(); index++)
list.Add(CFileItemPtr(new CFileItem(*m_slides->Get(index))));
}
const CFileItemPtr CGUIWindowSlideShow::GetCurrentSlide()
{
if (m_iCurrentSlide >= 0 && m_iCurrentSlide < m_slides->Size())
return m_slides->Get(m_iCurrentSlide);
return CFileItemPtr();
}
bool CGUIWindowSlideShow::InSlideShow() const
{
return m_bSlideShow;
}
void CGUIWindowSlideShow::StartSlideShow()
{
m_bSlideShow = true;
m_iDirection = 1;
if (m_slides->Size())
AnnouncePlayerPlay(m_slides->Get(m_iCurrentSlide));
}
void CGUIWindowSlideShow::SetDirection(int direction)
{
direction = direction >= 0 ? 1 : -1;
if (m_iDirection != direction)
{
m_iDirection = direction;
m_iNextSlide = GetNextSlide();
}
}
void CGUIWindowSlideShow::Process(unsigned int currentTime, CDirtyRegionList ®ions)
{
const RESOLUTION_INFO res = g_graphicsContext.GetResInfo();
// reset the screensaver if we're in a slideshow
// (unless we are the screensaver!)
if (m_bSlideShow && !m_bPause && !g_application.IsInScreenSaver())
g_application.ResetScreenSaver();
int iSlides = m_slides->Size();
if (!iSlides) return ;
// if we haven't processed yet, we should mark the whole screen
if (!HasProcessed())
regions.push_back(CRect(0.0f, 0.0f, (float)g_graphicsContext.GetWidth(), (float)g_graphicsContext.GetHeight()));
if (m_iCurrentSlide < 0 || m_iCurrentSlide >= m_slides->Size())
m_iCurrentSlide = 0;
if (m_iNextSlide < 0 || m_iNextSlide >= m_slides->Size())
m_iNextSlide = GetNextSlide();
// Create our background loader if necessary
if (!m_pBackgroundLoader)
{
m_pBackgroundLoader = new CBackgroundPicLoader();
if (!m_pBackgroundLoader)
{
throw 1;
}
m_pBackgroundLoader->Create(this);
}
bool bSlideShow = m_bSlideShow && !m_bPause && !m_bPlayingVideo;
if (bSlideShow && m_slides->Get(m_iCurrentSlide)->HasProperty("unplayable"))
{
m_iNextSlide = GetNextSlide();
if (m_iCurrentSlide == m_iNextSlide)
return;
m_iCurrentSlide = m_iNextSlide;
m_iNextSlide = GetNextSlide();
}
if (m_bErrorMessage)
{ // we have an error when loading either the current or next picture
// check to see if we have a picture loaded
CLog::Log(LOGDEBUG, "We have an error loading picture %d!", m_pBackgroundLoader->SlideNumber());
if (m_iCurrentSlide == m_pBackgroundLoader->SlideNumber())
{
if (m_Image[m_iCurrentPic].IsLoaded())
{
// current image was already loaded, so we can ignore this error.
m_bErrorMessage = false;
}
else
{
CLog::Log(LOGERROR, "Error loading the current image %d: %s", m_iCurrentSlide, m_slides->Get(m_iCurrentSlide)->GetPath().c_str());
if (!m_slides->Get(m_iCurrentPic)->IsVideo())
{
// try next if we are in slideshow
CLog::Log(LOGINFO, "set image %s unplayable", m_slides->Get(m_iCurrentSlide)->GetPath().c_str());
m_slides->Get(m_iCurrentSlide)->SetProperty("unplayable", true);
}
if (m_bLoadNextPic || (bSlideShow && !m_bPause && !m_slides->Get(m_iCurrentPic)->IsVideo()))
{
// change to next item, wait loading.
m_iCurrentSlide = m_iNextSlide;
m_iNextSlide = GetNextSlide();
m_bErrorMessage = false;
}
// else just drop through - there's nothing we can do (error message will be displayed)
}
}
else if (m_iNextSlide == m_pBackgroundLoader->SlideNumber())
{
CLog::Log(LOGERROR, "Error loading the next image %d: %s", m_iNextSlide, m_slides->Get(m_iNextSlide)->GetPath().c_str());
// load next image failed, then skip to load next of next if next is not video.
if (!m_slides->Get(m_iNextSlide)->IsVideo())
{
CLog::Log(LOGINFO, "set image %s unplayable", m_slides->Get(m_iNextSlide)->GetPath().c_str());
m_slides->Get(m_iNextSlide)->SetProperty("unplayable", true);
// change to next item, wait loading.
m_iNextSlide = GetNextSlide();
}
else
{ // prevent reload the next pic and repeat fail.
m_iLastFailedNextSlide = m_iNextSlide;
}
m_bErrorMessage = false;
}
else
{ // Non-current and non-next slide, just ignore error.
CLog::Log(LOGERROR, "Error loading the non-current non-next image %d/%d: %s", m_iNextSlide, m_pBackgroundLoader->SlideNumber(), m_slides->Get(m_iNextSlide)->GetPath().c_str());
m_bErrorMessage = false;
}
}
if (m_bErrorMessage)
{ // hack, just mark it all
regions.push_back(CRect(0.0f, 0.0f, (float)g_graphicsContext.GetWidth(), (float)g_graphicsContext.GetHeight()));
return;
}
CSingleLock lock(m_slideSection);
if (!m_Image[m_iCurrentPic].IsLoaded() && !m_pBackgroundLoader->IsLoading())
{ // load first image
CFileItemPtr item = m_slides->Get(m_iCurrentSlide);
std::string picturePath = GetPicturePath(item.get());
if (!picturePath.empty())
{
if (item->IsVideo())
CLog::Log(LOGDEBUG, "Loading the thumb %s for current video %d: %s", picturePath.c_str(), m_iCurrentSlide, item->GetPath().c_str());
else
CLog::Log(LOGDEBUG, "Loading the current image %d: %s", m_iCurrentSlide, item->GetPath().c_str());
// load using the background loader
int maxWidth, maxHeight;
GetCheckedSize((float)res.iWidth * m_fZoom,
(float)res.iHeight * m_fZoom,
maxWidth, maxHeight);
m_pBackgroundLoader->LoadPic(m_iCurrentPic, m_iCurrentSlide, picturePath, maxWidth, maxHeight);
m_iLastFailedNextSlide = -1;
m_bLoadNextPic = false;
}
}
// check if we should discard an already loaded next slide
if (m_Image[1 - m_iCurrentPic].IsLoaded() && m_Image[1 - m_iCurrentPic].SlideNumber() != m_iNextSlide)
m_Image[1 - m_iCurrentPic].Close();
if (m_iNextSlide != m_iCurrentSlide && m_Image[m_iCurrentPic].IsLoaded() && !m_Image[1 - m_iCurrentPic].IsLoaded() && !m_pBackgroundLoader->IsLoading() && m_iLastFailedNextSlide != m_iNextSlide)
{ // load the next image
m_iLastFailedNextSlide = -1;
CFileItemPtr item = m_slides->Get(m_iNextSlide);
std::string picturePath = GetPicturePath(item.get());
if (!picturePath.empty() && (!item->IsVideo() || !m_bSlideShow || m_bPause))
{
if (item->IsVideo())
CLog::Log(LOGDEBUG, "Loading the thumb %s for next video %d: %s", picturePath.c_str(), m_iNextSlide, item->GetPath().c_str());
else
CLog::Log(LOGDEBUG, "Loading the next image %d: %s", m_iNextSlide, item->GetPath().c_str());
int maxWidth, maxHeight;
GetCheckedSize((float)res.iWidth * m_fZoom,
(float)res.iHeight * m_fZoom,
maxWidth, maxHeight);
m_pBackgroundLoader->LoadPic(1 - m_iCurrentPic, m_iNextSlide, picturePath, maxWidth, maxHeight);
}
}
if (m_slides->Get(m_iCurrentSlide)->IsVideo() && bSlideShow)
{
if (!PlayVideo())
return;
bSlideShow = false;
}
// render the current image
if (m_Image[m_iCurrentPic].IsLoaded())
{
m_Image[m_iCurrentPic].SetInSlideshow(bSlideShow);
m_Image[m_iCurrentPic].Pause(!bSlideShow);
m_Image[m_iCurrentPic].Process(currentTime, regions);
}
// Check if we should be transistioning immediately
if (m_bLoadNextPic && m_Image[m_iCurrentPic].IsLoaded())
{
CLog::Log(LOGDEBUG, "Starting immediate transistion due to user wanting slide %s", m_slides->Get(m_iNextSlide)->GetPath().c_str());
if (m_Image[m_iCurrentPic].StartTransistion())
{
m_Image[m_iCurrentPic].SetTransistionTime(1, IMMEDIATE_TRANSISTION_TIME); // only 20 frames for the transistion
m_bLoadNextPic = false;
}
}
// render the next image
if (m_Image[m_iCurrentPic].DrawNextImage())
{
if (m_bSlideShow && !m_bPause && m_slides->Get(m_iNextSlide)->IsVideo())
{
// do not show thumb of video when playing slideshow
}
else if (m_Image[1 - m_iCurrentPic].IsLoaded())
{
// first time render the next image, make sure using current display effect.
if (!m_Image[1 - m_iCurrentPic].IsStarted())
{
CSlideShowPic::DISPLAY_EFFECT effect = GetDisplayEffect(m_iNextSlide);
if (m_Image[1 - m_iCurrentPic].DisplayEffectNeedChange(effect))
m_Image[1 - m_iCurrentPic].Reset(effect);
}
// set the appropriate transistion time
m_Image[1 - m_iCurrentPic].SetTransistionTime(0, m_Image[m_iCurrentPic].GetTransistionTime(1));
m_Image[1 - m_iCurrentPic].Pause(!m_bSlideShow || m_bPause || m_slides->Get(m_iNextSlide)->IsVideo());
m_Image[1 - m_iCurrentPic].Process(currentTime, regions);
}
else // next pic isn't loaded. We should hang around if it is in progress
{
if (m_pBackgroundLoader->IsLoading())
{
// CLog::Log(LOGDEBUG, "Having to hold the current image (%s) while we load %s", m_vecSlides[m_iCurrentSlide].c_str(), m_vecSlides[m_iNextSlide].c_str());
m_Image[m_iCurrentPic].Keep();
}
}
}
// check if we should swap images now
if (m_Image[m_iCurrentPic].IsFinished() || (m_bLoadNextPic && !m_Image[m_iCurrentPic].IsLoaded()))
{
m_bLoadNextPic = false;
if (m_Image[m_iCurrentPic].IsFinished())
CLog::Log(LOGDEBUG, "Image %s is finished rendering, switching to %s", m_slides->Get(m_iCurrentSlide)->GetPath().c_str(), m_slides->Get(m_iNextSlide)->GetPath().c_str());
else
// what if it's bg loading?
CLog::Log(LOGDEBUG, "Image %s is not loaded, switching to %s", m_slides->Get(m_iCurrentSlide)->GetPath().c_str(), m_slides->Get(m_iNextSlide)->GetPath().c_str());
if (m_Image[m_iCurrentPic].IsFinished() && m_iCurrentSlide == m_iNextSlide && m_Image[m_iCurrentPic].SlideNumber() == m_iNextSlide)
m_Image[m_iCurrentPic].Reset(GetDisplayEffect(m_iCurrentSlide));
else
{
if (m_Image[m_iCurrentPic].IsLoaded())
m_Image[m_iCurrentPic].Reset(GetDisplayEffect(m_iCurrentSlide));
else
m_Image[m_iCurrentPic].Close();
if ((m_Image[1 - m_iCurrentPic].IsLoaded() && m_Image[1 - m_iCurrentPic].SlideNumber() == m_iNextSlide) ||
(m_pBackgroundLoader->IsLoading() && m_pBackgroundLoader->SlideNumber() == m_iNextSlide && m_pBackgroundLoader->Pic() == 1 - m_iCurrentPic))
{
m_iCurrentPic = 1 - m_iCurrentPic;
}
else
{
m_Image[1 - m_iCurrentPic].Close();
m_iCurrentPic = 1 - m_iCurrentPic;
}
m_iCurrentSlide = m_iNextSlide;
m_iNextSlide = GetNextSlide();
}
AnnouncePlayerPlay(m_slides->Get(m_iCurrentSlide));
m_iZoomFactor = 1;
m_fZoom = 1.0f;
m_fRotate = 0.0f;
}
if (m_Image[m_iCurrentPic].IsLoaded())
g_infoManager.SetCurrentSlide(*m_slides->Get(m_iCurrentSlide));
RenderPause();
CGUIWindow::Process(currentTime, regions);
}
void CGUIWindowSlideShow::Render()
{
if (m_Image[m_iCurrentPic].IsLoaded())
m_Image[m_iCurrentPic].Render();
if (m_Image[m_iCurrentPic].DrawNextImage() && m_Image[1 - m_iCurrentPic].IsLoaded())
m_Image[1 - m_iCurrentPic].Render();
RenderErrorMessage();
CGUIWindow::Render();
}
int CGUIWindowSlideShow::GetNextSlide()
{
if (m_slides->Size() <= 1)
return m_iCurrentSlide;
int step = m_iDirection >= 0 ? 1 : -1;
int nextSlide = (m_iCurrentSlide + step + m_slides->Size()) % m_slides->Size();
while (nextSlide != m_iCurrentSlide)
{
if (!m_slides->Get(nextSlide)->HasProperty("unplayable"))
return nextSlide;
nextSlide = (nextSlide + step + m_slides->Size()) % m_slides->Size();
}
return m_iCurrentSlide;
}
EVENT_RESULT CGUIWindowSlideShow::OnMouseEvent(const CPoint &point, const CMouseEvent &event)
{
if (event.m_id == ACTION_GESTURE_NOTIFY)
{
int result = EVENT_RESULT_ROTATE | EVENT_RESULT_ZOOM;
if (m_iZoomFactor == 1 || !m_Image[m_iCurrentPic].m_bCanMoveHorizontally)
result |= EVENT_RESULT_SWIPE;
else
result |= EVENT_RESULT_PAN_HORIZONTAL;
if (m_Image[m_iCurrentPic].m_bCanMoveVertically)
result |= EVENT_RESULT_PAN_VERTICAL;
return (EVENT_RESULT)result;
}
else if (event.m_id == ACTION_GESTURE_BEGIN)
{
m_firstGesturePoint = point;
m_fInitialZoom = m_fZoom;
m_fInitialRotate = m_fRotate;
return EVENT_RESULT_HANDLED;
}
else if (event.m_id == ACTION_GESTURE_PAN)
{
// zoomed in - free move mode
if (m_iZoomFactor != 1 &&
(m_Image[m_iCurrentPic].m_bCanMoveHorizontally || m_Image[m_iCurrentPic].m_bCanMoveVertically))
{
Move(PICTURE_MOVE_AMOUNT_TOUCH / m_iZoomFactor * (m_firstGesturePoint.x - point.x), PICTURE_MOVE_AMOUNT_TOUCH / m_iZoomFactor * (m_firstGesturePoint.y - point.y));
m_firstGesturePoint = point;
}
return EVENT_RESULT_HANDLED;
}
else if (event.m_id == ACTION_GESTURE_SWIPE_LEFT || event.m_id == ACTION_GESTURE_SWIPE_RIGHT)
{
if (m_iZoomFactor == 1 || !m_Image[m_iCurrentPic].m_bCanMoveHorizontally)
{
// on zoomlevel 1 just detect swipe left and right
if (event.m_id == ACTION_GESTURE_SWIPE_LEFT)
OnAction(CAction(ACTION_NEXT_PICTURE));
else
OnAction(CAction(ACTION_PREV_PICTURE));
}
}
else if (event.m_id == ACTION_GESTURE_END)
{
if (m_fRotate != 0.0f)
{
// "snap" to nearest of 0, 90, 180 and 270 if the
// difference in angle is +/-10 degrees
float reminder = fmodf(m_fRotate, 90.0f);
if (fabs(reminder) < ROTATION_SNAP_RANGE)
Rotate(-reminder);
else if (reminder > 90.0f - ROTATION_SNAP_RANGE)
Rotate(90.0f - reminder);
else if (-reminder > 90.0f - ROTATION_SNAP_RANGE)
Rotate(-90.0f - reminder);
}
m_fInitialZoom = 0.0f;
m_fInitialRotate = 0.0f;
return EVENT_RESULT_HANDLED;
}
else if (event.m_id == ACTION_GESTURE_ZOOM)
{
ZoomRelative(m_fInitialZoom * event.m_offsetX, true);
return EVENT_RESULT_HANDLED;
}
else if (event.m_id == ACTION_GESTURE_ROTATE)
{
Rotate(m_fInitialRotate + event.m_offsetX - m_fRotate, true);
return EVENT_RESULT_HANDLED;
}
return EVENT_RESULT_UNHANDLED;
}
bool CGUIWindowSlideShow::OnAction(const CAction &action)
{
switch (action.GetID())
{
case ACTION_SHOW_CODEC:
{
CGUIDialogPictureInfo *pictureInfo = (CGUIDialogPictureInfo *)g_windowManager.GetWindow(WINDOW_DIALOG_PICTURE_INFO);
if (pictureInfo)
{
// no need to set the picture here, it's done in Render()
pictureInfo->Open();
}
}
break;
case ACTION_PREVIOUS_MENU:
case ACTION_NAV_BACK:
case ACTION_STOP:
if (m_slides->Size())
AnnouncePlayerStop(m_slides->Get(m_iCurrentSlide));
g_windowManager.PreviousWindow();
break;
case ACTION_NEXT_PICTURE:
ShowNext();
break;
case ACTION_PREV_PICTURE:
ShowPrevious();
break;
case ACTION_MOVE_RIGHT:
if (m_iZoomFactor == 1 || !m_Image[m_iCurrentPic].m_bCanMoveHorizontally)
ShowNext();
else
Move(PICTURE_MOVE_AMOUNT, 0);
break;
case ACTION_MOVE_LEFT:
if (m_iZoomFactor == 1 || !m_Image[m_iCurrentPic].m_bCanMoveHorizontally)
ShowPrevious();
else
Move( -PICTURE_MOVE_AMOUNT, 0);
break;
case ACTION_MOVE_DOWN:
Move(0, PICTURE_MOVE_AMOUNT);
break;
case ACTION_MOVE_UP:
Move(0, -PICTURE_MOVE_AMOUNT);
break;
case ACTION_PAUSE:
case ACTION_PLAYER_PLAY:
if (m_slides->Size() == 0)
break;
if (m_slides->Get(m_iCurrentSlide)->IsVideo())
{
if (!m_bPlayingVideo)
{
if (m_bSlideShow)
{
SetDirection(1);
m_bPause = false;
}
PlayVideo();
}
}
else if (!m_bSlideShow || m_bPause)
{
m_bSlideShow = true;
m_bPause = false;
SetDirection(1);
if (m_Image[m_iCurrentPic].IsLoaded())
{
CSlideShowPic::DISPLAY_EFFECT effect = GetDisplayEffect(m_iCurrentSlide);
if (m_Image[m_iCurrentPic].DisplayEffectNeedChange(effect))
m_Image[m_iCurrentPic].Reset(effect);
}
AnnouncePlayerPlay(m_slides->Get(m_iCurrentSlide));
}
else if (action.GetID() == ACTION_PAUSE)
{
m_bPause = true;
AnnouncePlayerPause(m_slides->Get(m_iCurrentSlide));
}
break;
case ACTION_ZOOM_OUT:
Zoom(m_iZoomFactor - 1);
break;
case ACTION_ZOOM_IN:
Zoom(m_iZoomFactor + 1);
break;
case ACTION_GESTURE_SWIPE_UP:
case ACTION_GESTURE_SWIPE_DOWN:
if (m_iZoomFactor == 1 || !m_Image[m_iCurrentPic].m_bCanMoveVertically)
{
bool swipeOnLeft = action.GetAmount() < g_graphicsContext.GetWidth() / 2.0f;
bool swipeUp = action.GetID() == ACTION_GESTURE_SWIPE_UP;
if (swipeUp == swipeOnLeft)
Rotate(90.0f);
else
Rotate(-90.0f);
}
break;
case ACTION_ROTATE_PICTURE_CW:
Rotate(90.0f);
break;
case ACTION_ROTATE_PICTURE_CCW:
Rotate(-90.0f);
break;
case ACTION_ZOOM_LEVEL_NORMAL:
case ACTION_ZOOM_LEVEL_1:
case ACTION_ZOOM_LEVEL_2:
case ACTION_ZOOM_LEVEL_3:
case ACTION_ZOOM_LEVEL_4:
case ACTION_ZOOM_LEVEL_5:
case ACTION_ZOOM_LEVEL_6:
case ACTION_ZOOM_LEVEL_7:
case ACTION_ZOOM_LEVEL_8:
case ACTION_ZOOM_LEVEL_9:
Zoom((action.GetID() - ACTION_ZOOM_LEVEL_NORMAL) + 1);
break;
case ACTION_ANALOG_MOVE:
// this action is used and works, when CAction object provides both x and y coordinates
Move(action.GetAmount()*PICTURE_MOVE_AMOUNT_ANALOG, -action.GetAmount(1)*PICTURE_MOVE_AMOUNT_ANALOG);
break;
case ACTION_ANALOG_MOVE_X:
// this and following action are used and work, when CAction object provides either x of y coordinate
Move(action.GetAmount()*PICTURE_MOVE_AMOUNT_ANALOG, 0.0f);
break;
case ACTION_ANALOG_MOVE_Y:
Move(0.0f, action.GetAmount(0)*PICTURE_MOVE_AMOUNT_ANALOG);
break;
default:
return CGUIWindow::OnAction(action);
}
return true;
}
void CGUIWindowSlideShow::RenderErrorMessage()
{
if (!m_bErrorMessage)
return ;
const CGUIControl *control = GetControl(LABEL_ROW1);
if (NULL == control || control->GetControlType() != CGUIControl::GUICONTROL_LABEL)
{
return;
}
CGUIFont *pFont = ((CGUILabelControl *)control)->GetLabelInfo().font;
CGUITextLayout::DrawText(pFont, 0.5f*g_graphicsContext.GetWidth(), 0.5f*g_graphicsContext.GetHeight(), 0xffffffff, 0, g_localizeStrings.Get(747), XBFONT_CENTER_X | XBFONT_CENTER_Y);
}
bool CGUIWindowSlideShow::OnMessage(CGUIMessage& message)
{
switch ( message.GetMessage() )
{
case GUI_MSG_WINDOW_INIT:
{
m_Resolution = (RESOLUTION) CSettings::GetInstance().GetInt(CSettings::SETTING_PICTURES_DISPLAYRESOLUTION);
//FIXME: Use GUI resolution for now
if (0 /*m_Resolution != CDisplaySettings::GetInstance().GetCurrentResolution() && m_Resolution != INVALID && m_Resolution!=AUTORES*/)
g_graphicsContext.SetVideoResolution(m_Resolution);
else
m_Resolution = g_graphicsContext.GetVideoResolution();
CGUIWindow::OnMessage(message);
if (message.GetParam1() != WINDOW_PICTURES)
m_ImageLib.Load();
// turn off slideshow if we only have 1 image
if (m_slides->Size() <= 1)
m_bSlideShow = false;
return true;
}
break;
case GUI_MSG_SHOW_PICTURE:
{
std::string strFile = message.GetStringParam();
Reset();
CFileItem item(strFile, false);
Add(&item);
RunSlideShow("", false, false, true, "", false);
}
break;
case GUI_MSG_START_SLIDESHOW:
{
std::string strFolder = message.GetStringParam();
unsigned int iParams = message.GetParam1();
std::string beginSlidePath = message.GetStringParam(1);
//decode params
bool bRecursive = false;
bool bRandom = false;
bool bNotRandom = false;
bool bPause = false;
if (iParams > 0)
{
if ((iParams & 1) == 1)
bRecursive = true;
if ((iParams & 2) == 2)
bRandom = true;
if ((iParams & 4) == 4)
bNotRandom = true;
if ((iParams & 8) == 8)
bPause = true;
}
RunSlideShow(strFolder, bRecursive, bRandom, bNotRandom, beginSlidePath, !bPause);
}
break;
case GUI_MSG_PLAYLISTPLAYER_STOPPED:
{
}
break;
case GUI_MSG_PLAYBACK_STARTED:
{
if (m_bPlayingVideo)
g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO);
}
break;
case GUI_MSG_PLAYBACK_STOPPED:
{
if (m_bPlayingVideo)
{
m_bPlayingVideo = false;
if (m_bSlideShow)
m_bPause = true;
}
}
break;
case GUI_MSG_PLAYBACK_ENDED:
{
if (m_bPlayingVideo)
{
m_bPlayingVideo = false;
if (m_bSlideShow)
{
m_bPause = false;
if (m_iCurrentSlide == m_iNextSlide)
break;
m_Image[m_iCurrentPic].Close();
m_iCurrentPic = 1 - m_iCurrentPic;
m_iCurrentSlide = m_iNextSlide;
m_iNextSlide = GetNextSlide();
AnnouncePlayerPlay(m_slides->Get(m_iCurrentSlide));
m_iZoomFactor = 1;
m_fZoom = 1.0f;
m_fRotate = 0.0f;
}
}
}
break;
}
return CGUIWindow::OnMessage(message);
}
void CGUIWindowSlideShow::RenderPause()
{ // display the pause icon
if (m_bPause)
{
SET_CONTROL_VISIBLE(CONTROL_PAUSE);
}
else
{
SET_CONTROL_HIDDEN(CONTROL_PAUSE);
}
/*
static DWORD dwCounter=0;
dwCounter++;
if (dwCounter > 25)
{
dwCounter=0;
}
if (!m_bPause) return;
if (dwCounter <13) return;*/
}
void CGUIWindowSlideShow::Rotate(float fAngle, bool immediate /* = false */)
{
if (m_Image[m_iCurrentPic].DrawNextImage())
return;
m_fRotate += fAngle;
m_Image[m_iCurrentPic].Rotate(fAngle, immediate);
}
void CGUIWindowSlideShow::Zoom(int iZoom)
{
if (iZoom > MAX_ZOOM_FACTOR || iZoom < 1)
return;
ZoomRelative(zoomamount[iZoom - 1]);
}
void CGUIWindowSlideShow::ZoomRelative(float fZoom, bool immediate /* = false */)
{
if (fZoom < zoomamount[0])
fZoom = zoomamount[0];
else if (fZoom > zoomamount[MAX_ZOOM_FACTOR - 1])
fZoom = zoomamount[MAX_ZOOM_FACTOR - 1];
if (m_Image[m_iCurrentPic].DrawNextImage())
return;
m_fZoom = fZoom;
// find the nearest zoom factor
for (unsigned int i = 1; i < MAX_ZOOM_FACTOR; i++)
{
if (m_fZoom > zoomamount[i])
continue;
if (fabs(m_fZoom - zoomamount[i - 1]) < fabs(m_fZoom - zoomamount[i]))
m_iZoomFactor = i;
else
m_iZoomFactor = i + 1;
break;
}
m_Image[m_iCurrentPic].Zoom(m_fZoom, immediate);
}
void CGUIWindowSlideShow::Move(float fX, float fY)
{
if (m_Image[m_iCurrentPic].IsLoaded() && m_Image[m_iCurrentPic].GetZoom() > 1)
{ // we move in the opposite direction, due to the fact we are moving
// the viewing window, not the picture.
m_Image[m_iCurrentPic].Move( -fX, -fY);
}
}
bool CGUIWindowSlideShow::PlayVideo()
{
CFileItemPtr item = m_slides->Get(m_iCurrentSlide);
if (!item || !item->IsVideo())
return false;
CLog::Log(LOGDEBUG, "Playing current video slide %s", item->GetPath().c_str());
m_bPlayingVideo = true;
PlayBackRet ret = g_application.PlayFile(*item);
if (ret == PLAYBACK_OK)
return true;
if (ret == PLAYBACK_FAIL)
{
CLog::Log(LOGINFO, "set video %s unplayable", item->GetPath().c_str());
item->SetProperty("unplayable", true);
}
else if (ret == PLAYBACK_CANCELED)
m_bPause = true;
m_bPlayingVideo = false;
return false;
}
CSlideShowPic::DISPLAY_EFFECT CGUIWindowSlideShow::GetDisplayEffect(int iSlideNumber) const
{
if (m_bSlideShow && !m_bPause && !m_slides->Get(iSlideNumber)->IsVideo())
return CSettings::GetInstance().GetBool(CSettings::SETTING_SLIDESHOW_DISPLAYEFFECTS) ? CSlideShowPic::EFFECT_RANDOM : CSlideShowPic::EFFECT_NONE;
else
return CSlideShowPic::EFFECT_NO_TIMEOUT;
}
void CGUIWindowSlideShow::OnLoadPic(int iPic, int iSlideNumber, const std::string &strFileName, CBaseTexture* pTexture, bool bFullSize)
{
if (pTexture)
{
// set the pic's texture + size etc.
CSingleLock lock(m_slideSection);
if (iSlideNumber >= m_slides->Size() || GetPicturePath(m_slides->Get(iSlideNumber).get()) != strFileName)
{ // throw this away - we must have cleared the slideshow while we were still loading
delete pTexture;
return;
}
CLog::Log(LOGDEBUG, "Finished background loading slot %d, %d: %s", iPic, iSlideNumber, m_slides->Get(iSlideNumber)->GetPath().c_str());
m_Image[iPic].SetTexture(iSlideNumber, pTexture, GetDisplayEffect(iSlideNumber));
m_Image[iPic].SetOriginalSize(pTexture->GetOriginalWidth(), pTexture->GetOriginalHeight(), bFullSize);
m_Image[iPic].m_bIsComic = false;
if (URIUtils::IsInRAR(m_slides->Get(m_iCurrentSlide)->GetPath()) || URIUtils::IsInZIP(m_slides->Get(m_iCurrentSlide)->GetPath())) // move to top for cbr/cbz
{
CURL url(m_slides->Get(m_iCurrentSlide)->GetPath());
std::string strHostName = url.GetHostName();
if (URIUtils::HasExtension(strHostName, ".cbr|.cbz"))
{
m_Image[iPic].m_bIsComic = true;
m_Image[iPic].Move((float)m_Image[iPic].GetOriginalWidth(),(float)m_Image[iPic].GetOriginalHeight());
}
}
}
else if (iSlideNumber >= m_slides->Size() || GetPicturePath(m_slides->Get(iSlideNumber).get()) != strFileName)
{ // Failed to load image. and not match values calling LoadPic, then something is changed, ignore.
CLog::Log(LOGDEBUG, "CGUIWindowSlideShow::OnLoadPic(%d, %d, %s) on failure not match current state (cur %d, next %d, curpic %d, pic[0, 1].slidenumber=%d, %d, %s)", iPic, iSlideNumber, strFileName.c_str(), m_iCurrentSlide, m_iNextSlide, m_iCurrentPic, m_Image[0].SlideNumber(), m_Image[1].SlideNumber(), iSlideNumber >= m_slides->Size() ? "" : m_slides->Get(iSlideNumber)->GetPath().c_str());
}
else
{ // Failed to load image. What should be done??
// We should wait for the current pic to finish rendering, then transistion it out,
// release the texture, and try and reload this pic from scratch
m_bErrorMessage = true;
}
}
void CGUIWindowSlideShow::Shuffle()
{
m_slides->Randomize();
m_iCurrentSlide = 0;
m_iNextSlide = GetNextSlide();
m_bShuffled = true;
AnnouncePropertyChanged("shuffled", true);
}
int CGUIWindowSlideShow::NumSlides() const
{
return m_slides->Size();
}
int CGUIWindowSlideShow::CurrentSlide() const
{
return m_iCurrentSlide + 1;
}
void CGUIWindowSlideShow::AddFromPath(const std::string &strPath,
bool bRecursive,
SortBy method, SortOrder order, SortAttribute sortAttributes,
const std::string &strExtensions)
{
if (strPath!="")
{
// reset the slideshow
Reset();
m_strExtensions = strExtensions;
if (bRecursive)
{
path_set recursivePaths;
AddItems(strPath, &recursivePaths, method, order, sortAttributes);
}
else
AddItems(strPath, NULL, method, order, sortAttributes);
}
}
void CGUIWindowSlideShow::RunSlideShow(const std::string &strPath,
bool bRecursive /* = false */, bool bRandom /* = false */,
bool bNotRandom /* = false */, const std::string &beginSlidePath /* = "" */,
bool startSlideShow /* = true */, SortBy method /* = SortByLabel */,
SortOrder order /* = SortOrderAscending */, SortAttribute sortAttributes /* = SortAttributeNone */,
const std::string &strExtensions)
{
// stop any video
if (g_application.m_pPlayer->IsPlayingVideo())
g_application.StopPlaying();
AddFromPath(strPath, bRecursive, method, order, sortAttributes, strExtensions);
if (!NumSlides())
return;
// mutually exclusive options
// if both are set, clear both and use the gui setting
if (bRandom && bNotRandom)
bRandom = bNotRandom = false;
// NotRandom overrides the window setting
if ((!bNotRandom && CSettings::GetInstance().GetBool(CSettings::SETTING_SLIDESHOW_SHUFFLE)) || bRandom)
Shuffle();
if (!beginSlidePath.empty())
Select(beginSlidePath);
if (startSlideShow)
StartSlideShow();
else
{
CVariant param;
param["player"]["speed"] = 0;
param["player"]["playerid"] = PLAYLIST_PICTURE;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::Player, "xbmc", "OnPlay", GetCurrentSlide(), param);
}
g_windowManager.ActivateWindow(WINDOW_SLIDESHOW);
}
void CGUIWindowSlideShow::AddItems(const std::string &strPath, path_set *recursivePaths, SortBy method, SortOrder order, SortAttribute sortAttributes)
{
// check whether we've already added this path
if (recursivePaths)
{
std::string path(strPath);
URIUtils::RemoveSlashAtEnd(path);
if (recursivePaths->find(path) != recursivePaths->end())
return;
recursivePaths->insert(path);
}
CFileItemList items;
CGUIViewStateWindowPictures viewState(items);
// fetch directory and sort accordingly
if (!CDirectory::GetDirectory(strPath, items, viewState.GetExtensions(), DIR_FLAG_NO_FILE_DIRS, true))
return;
items.Sort(method, order, sortAttributes);
// need to go into all subdirs
for (int i = 0; i < items.Size(); i++)
{
CFileItemPtr item = items[i];
if (item->m_bIsFolder && recursivePaths)
{
AddItems(item->GetPath(), recursivePaths);
}
else if (!item->m_bIsFolder && !URIUtils::IsRAR(item->GetPath()) && !URIUtils::IsZIP(item->GetPath()))
{ // add to the slideshow
Add(item.get());
}
}
}
void CGUIWindowSlideShow::GetCheckedSize(float width, float height, int &maxWidth, int &maxHeight)
{
maxWidth = g_Windowing.GetMaxTextureSize();
maxHeight = g_Windowing.GetMaxTextureSize();
}
std::string CGUIWindowSlideShow::GetPicturePath(CFileItem *item)
{
bool isVideo = item->IsVideo();
std::string picturePath = item->GetPath();
if (isVideo)
{
picturePath = item->GetArt("thumb");
if (picturePath.empty() && !item->HasProperty("nothumb"))
{
CPictureThumbLoader thumbLoader;
thumbLoader.LoadItem(item);
picturePath = item->GetArt("thumb");
if (picturePath.empty())
item->SetProperty("nothumb", true);
}
}
return picturePath;
}
| 31.243921 | 395 | 0.667729 | krattai |
bb8eac9f978ff2afac67af52fd866c14e8027207 | 1,186 | cpp | C++ | IndexBuilder/main.cpp | Dudi119/SearchYA | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 5 | 2017-08-29T15:33:16.000Z | 2020-12-09T08:34:02.000Z | IndexBuilder/main.cpp | Dudi119/MesosBenchMark | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 1 | 2017-09-26T11:44:01.000Z | 2017-09-27T06:40:01.000Z | IndexBuilder/main.cpp | Dudi119/MesosBenchMark | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 2 | 2017-08-19T04:41:16.000Z | 2020-07-21T17:38:16.000Z | #include <memory>
#include "Core/src/Enviorment.h"
#include "Core/src/Logger.h"
#include "Core/src/CommandLine.h"
#include "Core/src/Logger.h"
#include "Core/src/TraceListener.h"
#include "cppkin/cppkin.h"
#include "IndexBuilder.h"
using namespace core;
using namespace std;
int main(int argc, char** argv)
{
CommandLine::Instance().Parse(argc, const_cast<const char**>(argv));
const string& workinDir = CommandLine::Instance().GetArgument("workingdir");
Enviorment::Instance().Init();
Logger::Instance().AddListener(make_shared<FileRotationListener>(TraceSeverity::Info, workinDir + "/IndexBuilder", 50 * 1024 * 1024, 20));
Logger::Instance().Start(TraceSeverity::Info);
TRACE_INFO("Index Builder starting");
cppkin::GeneralParams cppkinParams;
cppkinParams.AddParam(cppkin::ConfigTags::HOST_ADDRESS, string("127.0.0.1"));//ConfigParams::Instance().GetZipkinHostAddress());
cppkinParams.AddParam(cppkin::ConfigTags::PORT, 9410);
cppkinParams.AddParam(cppkin::ConfigTags::SERVICE_NAME, string("Index_Builder"));
INIT(cppkinParams);
IndexBuilder::Instance().InitializeMesos();
IndexBuilder::Instance().WaitForCompletion();
Logger::Instance().Flush();
return 0;
}
| 37.0625 | 139 | 0.752108 | Dudi119 |
bb8ffb56b7c980e985717913696e97f8883cc384 | 380 | hpp | C++ | Ladybug3D/Libraries/Renderer/SceneObject.hpp | wlsvy/Ladybug3D | 9cd92843bf6cdff806aa4283c5594028a53e20b3 | [
"MIT"
] | null | null | null | Ladybug3D/Libraries/Renderer/SceneObject.hpp | wlsvy/Ladybug3D | 9cd92843bf6cdff806aa4283c5594028a53e20b3 | [
"MIT"
] | null | null | null | Ladybug3D/Libraries/Renderer/SceneObject.hpp | wlsvy/Ladybug3D | 9cd92843bf6cdff806aa4283c5594028a53e20b3 | [
"MIT"
] | null | null | null | #pragma once
#include "Object.hpp"
namespace Ladybug3D {
class Transform;
class Model;
class SceneObject : public Object {
public:
SceneObject(const std::string& name = "SceneObject");
~SceneObject();
auto& GetTransform() { return m_Transform; }
void OnImGui() override;
std::shared_ptr<Model> Model;
protected:
std::shared_ptr<Transform> m_Transform;
};
} | 17.272727 | 55 | 0.710526 | wlsvy |
bb95bed7c3fa0b21fa19c5cff9430e306cd3c1d5 | 599 | hpp | C++ | libs/opencl/include/sge/opencl/platform/object_sequence.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/opencl/include/sge/opencl/platform/object_sequence.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/opencl/include/sge/opencl/platform/object_sequence.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_OPENCL_PLATFORM_OBJECT_SEQUENCE_HPP_INCLUDED
#define SGE_OPENCL_PLATFORM_OBJECT_SEQUENCE_HPP_INCLUDED
#include <sge/opencl/platform/object_fwd.hpp>
#include <fcppt/config/external_begin.hpp>
#include <vector>
#include <fcppt/config/external_end.hpp>
namespace sge::opencl::platform
{
using object_sequence = std::vector<sge::opencl::platform::object>;
}
#endif
| 27.227273 | 67 | 0.764608 | cpreh |
bb97c24e2c10f7f9e089ea04c47e47f27ef49442 | 6,394 | hpp | C++ | src/rdx/rdx_io.hpp | elasota/rdx2 | e08ca09a07d3ac8675f7f950a7bdf838a9f5f907 | [
"MIT"
] | null | null | null | src/rdx/rdx_io.hpp | elasota/rdx2 | e08ca09a07d3ac8675f7f950a7bdf838a9f5f907 | [
"MIT"
] | null | null | null | src/rdx/rdx_io.hpp | elasota/rdx2 | e08ca09a07d3ac8675f7f950a7bdf838a9f5f907 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2011-2013 Eric Lasota
*
* 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 __RDX_IO_HPP__
#define __RDX_IO_HPP__
#include "rdx_basictypes.hpp"
#include "rdx_objectmanagement.hpp"
struct rdxSCharSpan;
struct rdxIFileScanState
{
virtual void Close() = 0;
virtual rdxCRef(rdxCString) NextFile(rdxSOperationContext *ctx, rdxIObjectManager *objm) = 0;
};
struct rdxIFileSystem
{
virtual rdxIFileStream *Open(const rdxChar *path, bool write) = 0;
//virtual rdxIFileScanState *ScanDirectory(const rdxChar *directory, const rdxChar *wildcard, const rdxChar *vext) = 0;
};
struct rdxIFileStream
{
virtual rdxLargeUInt WriteBytes(const void *src, rdxLargeUInt numBytes) = 0;
virtual rdxLargeUInt ReadBytes(void *dest, rdxLargeUInt numBytes) = 0;
virtual void SeekStart(rdxLargeUInt offset) = 0;
virtual void SeekEnd(rdxLargeInt offset) = 0;
virtual void SeekCurrent(rdxLargeInt offset) = 0;
virtual void SeekForward(rdxLargeUInt offset) = 0;
virtual rdxLargeUInt Tell() = 0;
virtual void Close() = 0;
virtual bool HasAborted() const = 0;
virtual void Abort() = 0;
inline static bool ShouldByteSwap()
{
rdxUInt32 RDX_BYTE_ORDER_LITTLE_ENDIAN = 1;
rdxUInt32 RDX_BYTE_ORDER_BIG_ENDIAN = 0x01000000;
union
{
rdxUInt32 u32;
rdxUInt8 u8[4];
} u;
u.u32 = 0;
u.u8[0] = 1;
return (u.u32 != RDX_BINARY_STORAGE_ORDER);
}
inline rdxLargeUInt WriteSwappedBytes(const void *src, rdxLargeUInt numBytes)
{
rdxUInt8 buffer[16];
rdxLargeUInt bufferOffset = 0;
rdxLargeUInt cumulative = 0;
const rdxUInt8 *bsrc = reinterpret_cast<const rdxUInt8*>(src) + numBytes;
for(rdxLargeUInt i=0;i<numBytes;i++)
{
bsrc--;
buffer[bufferOffset++] = *bsrc;
if(bufferOffset == sizeof(buffer))
{
cumulative += this->WriteBytes(buffer, sizeof(buffer));
bufferOffset = 0;
}
}
if(bufferOffset)
cumulative += this->WriteBytes(buffer, bufferOffset);
return cumulative;
}
inline rdxLargeUInt ReadSwappedBytes(void *dest, rdxLargeUInt numBytes)
{
rdxLargeUInt nRead = this->ReadBytes(dest, numBytes);
if(nRead == numBytes)
{
rdxUInt8 *bytes = reinterpret_cast<rdxUInt8*>(dest);
rdxLargeUInt halfPoint = nRead / 2;
for(rdxLargeUInt i=0;i<halfPoint;i++)
{
rdxUInt8 temp;
temp = bytes[i];
bytes[i] = bytes[nRead-1-i];
bytes[nRead-1-i] = temp;
}
}
return nRead;
}
inline rdxLargeUInt ReadSwappableBytes(void *dest, rdxLargeUInt numBytes)
{
if(ShouldByteSwap())
return ReadSwappedBytes(dest, numBytes);
else
return ReadBytes(dest, numBytes);
}
rdxLargeUInt WriteSwappableBytes(const void *src, rdxLargeUInt numBytes)
{
if(ShouldByteSwap())
return WriteSwappedBytes(src, numBytes);
else
return WriteBytes(src, numBytes);
}
template<class _Tfrom, class _Tto>
inline void WriteConverted(_Tfrom val)
{
_Tto binVal = static_cast<_Tto>(val);
if(static_cast<_Tfrom>(binVal) != val)
this->Abort();
else
this->WriteSwappableBytes(&binVal, sizeof(binVal));
}
template<class _Tfrom, class _Tto>
inline bool ReadConverted(_Tto *valOut, bool &overflowed, bool &readFailed)
{
_Tfrom fromBin;
if(this->ReadSwappableBytes(&fromBin, sizeof(_Tfrom)) != sizeof(_Tfrom))
{
readFailed = true;
return false;
}
_Tto toVal = static_cast<_Tto>(fromBin);
if(static_cast<_Tfrom>(toVal) != fromBin)
{
overflowed = true;
return false;
}
*valOut = toVal;
return true;
}
};
struct rdxITextDeserializer : public rdxIFileStream
{
static const rdxLargeUInt COMPACT_TOKEN_SIZE = 128;
struct SCompactToken
{
rdxSCharSpan GetCharSpan() const;
rdxChar *InitCompactChars(rdxLargeUInt numChars);
void SetStrChars(rdxWeakRTRef(rdxCString) str);
SCompactToken();
SCompactToken(const SCompactToken &other);
private:
rdxCRef(rdxCString) m_str;
bool m_isCompact;
rdxLargeUInt m_compactSize;
rdxChar m_compactChars[COMPACT_TOKEN_SIZE+1];
};
virtual bool CheckToken(const char *str) = 0;
virtual void ParseToken(rdxSOperationContext *ctx, rdxIObjectManager *objm, bool *pIsString, SCompactToken *outToken = RDX_CNULL) = 0;
virtual void SkipToken(rdxSOperationContext *ctx) = 0;
};
#include "rdx_charspan.hpp"
inline rdxITextDeserializer::SCompactToken::SCompactToken()
: m_isCompact(false)
{
}
inline rdxITextDeserializer::SCompactToken::SCompactToken(const SCompactToken &other)
: m_str(other.m_str)
, m_isCompact(other.m_isCompact)
, m_compactSize(other.m_compactSize)
{
memcpy(m_compactChars, other.m_compactChars, sizeof(m_compactChars));
}
inline rdxSCharSpan rdxITextDeserializer::SCompactToken::GetCharSpan() const
{
if(m_isCompact)
return rdxSCharSpan(m_compactChars, m_compactSize);
return rdxSCharSpan(m_str->AsChars()->ArrayData(), m_str->Length());
}
inline rdxChar *rdxITextDeserializer::SCompactToken::InitCompactChars(rdxLargeUInt numChars)
{
m_isCompact = true;
m_str = rdxWeakRTRef(rdxCString)::Null();
m_compactChars[numChars] = 0;
m_compactSize = numChars;
return m_compactChars;
}
inline void rdxITextDeserializer::SCompactToken::SetStrChars(rdxWeakRTRef(rdxCString) str)
{
m_isCompact = false;
m_str = str;
}
#endif
| 28.672646 | 136 | 0.715827 | elasota |
bb9b9f11072857fdc7000753e3fe7bd5d78aa9d5 | 14,429 | cpp | C++ | connecter/mmloop_test/getopt.cpp | mqtter/mqtter | a60f57d866f3e50ffc3abe5020737fe8d0aeeba3 | [
"MIT"
] | 2 | 2018-07-25T13:04:14.000Z | 2019-01-14T03:58:54.000Z | mmloop_test/getopt.cpp | skybosi/maomao | 88e556cb4c56ebc0dbf597f0a5835a495d8ab5df | [
"MIT"
] | 1 | 2017-07-29T02:19:59.000Z | 2017-07-30T12:48:21.000Z | mmloop_test/getopt.cpp | skybosi/maomao | 88e556cb4c56ebc0dbf597f0a5835a495d8ab5df | [
"MIT"
] | 2 | 2017-11-27T14:40:42.000Z | 2019-01-14T03:58:56.000Z | #include "getopt.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int opterr; /* if error message should be printed */
int optind; /* index into parent argv vector */
int optopt; /* character checked for validity */
int optreset; /* reset getopt */
char *optarg; /* argument associated with option */
const char *_getopt_initialize (int argc, char *const *argv, const char *optstring);
static int first_nonopt;
static int last_nonopt;
static char *nextchar;
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
} ordering;
static char *posixly_correct;
static void exchange (char **);
int __getopt_initialized;
int _getopt_internal (int argc,char *const *argv,const char *optstring,const struct option *longopts, int *longind,int long_only)
{
int print_errors = opterr;
if (optstring[0] == ':')
print_errors = 0;
if (argc < 1)
return -1;
optarg = NULL;
if (optind == 0 || !__getopt_initialized)
{
if (optind == 0)
optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
}
#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
if (nextchar == NULL || *nextchar == '\0')
{
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > optind)
last_nonopt = optind;
if (first_nonopt > optind)
first_nonopt = optind;
if (ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (last_nonopt != optind)
first_nonopt = optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (optind < argc && NONOPTION_P)
optind++;
last_nonopt = optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (optind != argc && !strcmp (argv[optind], "--"))
{
optind++;
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = optind;
last_nonopt = argc;
optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (ordering == REQUIRE_ORDER)
return -1;
optarg = argv[optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[optind] + 1
+ (longopts != NULL && argv[optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[optind][1] == '-'
|| (long_only && (argv[optind][2] || !strchr(optstring, argv[optind][1])))))
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */
;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar)
== (unsigned int) strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else if (long_only
|| pfound->has_arg != p->has_arg
|| pfound->flag != p->flag
|| pfound->val != p->val)
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (print_errors)
{
fprintf (stderr, "%s: option `%s' is ambiguous\n",argv[0], argv[optind]);
}
nextchar += strlen (nextchar);
optind++;
optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (print_errors)
{
if (argv[optind - 1][1] == '-')
{
fprintf (stderr, "%s: option `--%s' doesn't allow an argument\n",argv[0], pfound->name);
}
else
{
fprintf (stderr, "%s: option `%c%s' doesn't allow an argument\n",argv[0], argv[optind - 1][0], pfound->name);
}
}
nextchar += strlen (nextchar);
optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (print_errors)
{
fprintf (stderr,"%s: option `%s' requires an argument\n",argv[0], argv[optind - 1]);
}
nextchar += strlen (nextchar);
optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[optind][1] == '-'
|| strchr(optstring, *nextchar) == NULL)
{
if (print_errors)
{
if (argv[optind][1] == '-')
{
/* --option */
fprintf (stderr, "%s: unrecognized option `--%s'\n",argv[0], nextchar);
}
else
{
/* +option or -option */
fprintf (stderr, "%s: unrecognized option `%c%s'\n",argv[0], argv[optind][0], nextchar);
}
}
nextchar = (char *) "";
optind++;
optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
const char *temp = strchr(optstring, c);
/* Increment `optind' when we start to process its last character. */
if (*nextchar == '\0')
++optind;
if (temp == NULL || c == ':')
{
if (print_errors)
{
if (posixly_correct)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
}
else
{
fprintf (stderr, "%s: invalid option -- %c\n", argv[0], c);
}
}
optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (print_errors)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr, "%s: option requires an argument -- %c\n",argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
/* optarg is now the argument, see if it's in the
table of longopts. */
for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */
;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar) == strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (print_errors)
{
fprintf (stderr, "%s: option `-W %s' is ambiguous\n",argv[0], argv[optind]);
}
nextchar += strlen (nextchar);
optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (print_errors)
{
fprintf (stderr, "%s: option `-W %s' doesn't allow an argument\n",argv[0], pfound->name);
}
nextchar += strlen (nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (print_errors)
{
fprintf (stderr,"%s: option `%s' requires an argument\n",argv[0], argv[optind - 1]);
}
nextchar += strlen (nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0')
{
optarg = nextchar;
optind++;
}
else
optarg = NULL;
nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (print_errors)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr,"%s: option requires an argument -- %c\n",argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
nextchar = NULL;
}
}
return c;
}
}
const char *_getopt_initialize (int argc, char *const *argv, const char *optstring)
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = optind;
nextchar = NULL;
posixly_correct = getenv ("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
return optstring;
}
void exchange (char **argv)
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
first_nonopt += (optind - last_nonopt);
last_nonopt = optind;
}
int getopt (int argc,char *const *argv,const char *optstring)
{
return _getopt_internal (argc, argv, optstring,(const struct option *) 0,(int *) 0,0);
}
int getopt_long (int argc,char *const *argv,const char *options,const struct option *long_options,int *opt_index)
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
}
| 24.877586 | 129 | 0.584933 | mqtter |
bba7f4103dff199da36fc105011c01580921bb83 | 656 | hpp | C++ | source/framework/python/src/command_line.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/framework/python/src/command_line.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/framework/python/src/command_line.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #pragma once
#include "lue/py/configure.hpp"
#include <functional>
#include <memory>
#include <vector>
namespace lue {
class CommandLine
{
public:
CommandLine();
int argc() const;
char** argv() const;
private:
// For each argument a string
std::vector<std::string> _argument_strings;
// For each argument a pointer to the array of characters
std::vector<char*> _argument_pointers;
// Command line arguments, to be used by HPX runtime startup code
int _argc;
char** _argv;
};
} // namespace lue
| 18.222222 | 77 | 0.559451 | computationalgeography |
bba8d2173d21836cf67544c380b550a95ed4d092 | 4,480 | cpp | C++ | core/fpdfapi/cmaps/fpdf_cmaps.cpp | aosp-caf-upstream/platform_external_pdfium | c8a0db7d7c3e0017de4eeeb69e434b5f3b6ee386 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | core/fpdfapi/cmaps/fpdf_cmaps.cpp | aosp-caf-upstream/platform_external_pdfium | c8a0db7d7c3e0017de4eeeb69e434b5f3b6ee386 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | core/fpdfapi/cmaps/fpdf_cmaps.cpp | aosp-caf-upstream/platform_external_pdfium | c8a0db7d7c3e0017de4eeeb69e434b5f3b6ee386 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fpdfapi/cmaps/cmap_int.h"
#include <algorithm>
#include "core/fpdfapi/cpdf_modulemgr.h"
#include "core/fpdfapi/font/cpdf_fontglobals.h"
#include "core/fpdfapi/page/cpdf_pagemodule.h"
namespace {
const FXCMAP_CMap* FindNextCMap(const FXCMAP_CMap* pMap) {
return pMap->m_UseOffset ? pMap + pMap->m_UseOffset : nullptr;
}
} // namespace
const FXCMAP_CMap* FPDFAPI_FindEmbeddedCMap(const ByteString& bsName,
int charset,
int coding) {
CPDF_FontGlobals* pFontGlobals =
CPDF_ModuleMgr::Get()->GetPageModule()->GetFontGlobals();
const FXCMAP_CMap* pCMaps;
uint32_t count;
std::tie(count, pCMaps) = pFontGlobals->GetEmbeddedCharset(charset);
for (uint32_t i = 0; i < count; i++) {
if (bsName == pCMaps[i].m_Name)
return &pCMaps[i];
}
return nullptr;
}
uint16_t FPDFAPI_CIDFromCharCode(const FXCMAP_CMap* pMap, uint32_t charcode) {
ASSERT(pMap);
const uint16_t loword = static_cast<uint16_t>(charcode);
if (charcode >> 16) {
while (pMap) {
if (pMap->m_pDWordMap) {
const FXCMAP_DWordCIDMap* begin = pMap->m_pDWordMap;
const auto* end = begin + pMap->m_DWordCount;
const auto* found = std::lower_bound(
begin, end, charcode,
[](const FXCMAP_DWordCIDMap& element, uint32_t charcode) {
uint16_t hiword = static_cast<uint16_t>(charcode >> 16);
if (element.m_HiWord != hiword)
return element.m_HiWord < hiword;
return element.m_LoWordHigh < static_cast<uint16_t>(charcode);
});
if (found != end && loword >= found->m_LoWordLow &&
loword <= found->m_LoWordHigh) {
return found->m_CID + loword - found->m_LoWordLow;
}
}
pMap = FindNextCMap(pMap);
}
return 0;
}
while (pMap) {
if (!pMap->m_pWordMap)
return 0;
if (pMap->m_WordMapType == FXCMAP_CMap::Single) {
struct SingleCmap {
uint16_t code;
uint16_t cid;
};
const auto* begin = reinterpret_cast<const SingleCmap*>(pMap->m_pWordMap);
const auto* end = begin + pMap->m_WordCount;
const auto* found = std::lower_bound(
begin, end, loword, [](const SingleCmap& element, uint16_t code) {
return element.code < code;
});
if (found != end && found->code == loword)
return found->cid;
} else {
ASSERT(pMap->m_WordMapType == FXCMAP_CMap::Range);
struct RangeCmap {
uint16_t low;
uint16_t high;
uint16_t cid;
};
const auto* begin = reinterpret_cast<const RangeCmap*>(pMap->m_pWordMap);
const auto* end = begin + pMap->m_WordCount;
const auto* found = std::lower_bound(
begin, end, loword, [](const RangeCmap& element, uint16_t code) {
return element.high < code;
});
if (found != end && loword >= found->low && loword <= found->high)
return found->cid + loword - found->low;
}
pMap = FindNextCMap(pMap);
}
return 0;
}
uint32_t FPDFAPI_CharCodeFromCID(const FXCMAP_CMap* pMap, uint16_t cid) {
// TODO(dsinclair): This should be checking both pMap->m_WordMap and
// pMap->m_DWordMap. There was a second while() but it was never reached as
// the first always returns. Investigate and determine how this should
// really be working. (https://codereview.chromium.org/2235743003 removed the
// second while loop.)
ASSERT(pMap);
while (pMap) {
if (pMap->m_WordMapType == FXCMAP_CMap::Single) {
const uint16_t* pCur = pMap->m_pWordMap;
const uint16_t* pEnd = pMap->m_pWordMap + pMap->m_WordCount * 2;
while (pCur < pEnd) {
if (pCur[1] == cid)
return pCur[0];
pCur += 2;
}
} else {
ASSERT(pMap->m_WordMapType == FXCMAP_CMap::Range);
const uint16_t* pCur = pMap->m_pWordMap;
const uint16_t* pEnd = pMap->m_pWordMap + pMap->m_WordCount * 3;
while (pCur < pEnd) {
if (cid >= pCur[2] && cid <= pCur[2] + pCur[1] - pCur[0])
return pCur[0] + cid - pCur[2];
pCur += 3;
}
}
pMap = FindNextCMap(pMap);
}
return 0;
}
| 33.432836 | 80 | 0.613839 | aosp-caf-upstream |
bbab7f4d1e831fc0c378a8ce92e6bd1731f92d0f | 1,384 | cc | C++ | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/ext/profile/replace_new.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/ext/profile/replace_new.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/ext/profile/replace_new.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | // -*- C++ -*-
// Copyright (C) 2006-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-require-profile-mode "" }
#include <vector>
#include <testsuite_hooks.h>
using std::vector;
void* operator new(std::size_t size) THROW(std::bad_alloc)
{
void* p = std::malloc(size);
if (!p)
throw std::bad_alloc();
return p;
}
void* operator new (std::size_t size, const std::nothrow_t&) throw()
{
// With _GLIBCXX_PROFILE, the instrumentation of the vector constructor
// will call back into this new operator.
vector<int> v;
return std::malloc(size);
}
void operator delete(void* p) throw()
{
if (p)
std::free(p);
}
int
main()
{
vector<int> v;
return 0;
}
| 25.163636 | 74 | 0.695087 | best08618 |
bbae4cf5bf79b0fc2ddab28fa18b226832f433f4 | 1,443 | cpp | C++ | src/system/runtime_loader/pe.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/system/runtime_loader/pe.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/system/runtime_loader/pe.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2013-2014, Haiku, Inc.
* Distributed under the terms of the MIT License.
*
* Authors:
* Alexander von Gluck IV, <kallisti5@unixzen.com>
*/
#include "pe.h"
#include <ctype.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static status_t
parse_mz_header(MzHeader* mzHeader, off_t* peOffset)
{
if (memcmp(&mzHeader->magic, MZ_MAGIC, 2) != 0)
return B_NOT_AN_EXECUTABLE;
*peOffset = (off_t)mzHeader->lfaNew;
return B_OK;
}
static status_t
parse_pe_header(PeHeader* peHeader)
{
if (memcmp(&peHeader->magic, PE_MAGIC, 2) != 0)
return B_NOT_AN_EXECUTABLE;
// Looks like an old BeOS R3 x86 program
if (peHeader->characteristics == 0x10E)
return B_LEGACY_EXECUTABLE;
return B_OK;
}
/*! Read and verify the PE header */
status_t
pe_verify_header(void *header, size_t length)
{
if (length < sizeof(MzHeader))
return B_NOT_AN_EXECUTABLE;
// Verify MZ header, pull PE header offset
off_t peOffset = 0;
if (parse_mz_header((MzHeader*)header, &peOffset) != B_OK)
return B_NOT_AN_EXECUTABLE;
// MS-DOS program
if (peOffset == 0)
return B_UNKNOWN_EXECUTABLE;
// Something is wrong with the binary
if (peOffset + sizeof(PeHeader) > length)
return B_UNKNOWN_EXECUTABLE;
// Find the PE header based on MZ provided offset
uint8* pePtr = (uint8*)header;
pePtr += peOffset;
// Win32 program or old BeOS R3 x86 program
return parse_pe_header((PeHeader*)pePtr);
}
| 20.323944 | 59 | 0.718642 | Kirishikesan |
bbb7c5dc56e6f5c60b0485f0896f159ce624ad07 | 1,224 | cpp | C++ | src/powerext/DnaInfo/DnaInfo.cpp | ssidpat/powerext | dd89281cf2008fdfda6eb1090cd381eb004e8f6c | [
"BSD-3-Clause"
] | 15 | 2017-07-15T02:10:58.000Z | 2022-01-04T23:09:23.000Z | src/powerext/DnaInfo/DnaInfo.cpp | ssidpat/powerext | dd89281cf2008fdfda6eb1090cd381eb004e8f6c | [
"BSD-3-Clause"
] | 2 | 2017-12-07T19:12:23.000Z | 2020-09-30T19:05:23.000Z | src/powerext/DnaInfo/DnaInfo.cpp | ssidpat/powerext | dd89281cf2008fdfda6eb1090cd381eb004e8f6c | [
"BSD-3-Clause"
] | 3 | 2019-01-18T00:55:00.000Z | 2021-09-08T11:06:45.000Z | // DnaInfo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "../PowerExt/AssemblyName.h"
#include "../PowerExt/HResultDecoder.h"
#include <iostream>
#include <string>
int _tmain(int argc, TCHAR* argv[])
{
std::wcout << _T("DnaInfo.exe (.NET Assembly Information)") << std::endl << std::endl;
if (argc < 2)
{
std::wcout << _T("Usage:") << std::endl;
std::wcout << std::endl;
std::wcout << _T("DnaInfo.exe <assembly>") << std::endl;
std::wcout << std::endl;
std::wcout << _T(" <assembly> = Path to a .NET dll or exe") << std::endl;
return 1;
}
std::wstring assemblyFile(argv[1]);
std::wcout << assemblyFile << std::endl << std::endl;
try
{
AssemblyName assemblyName(assemblyFile);
std::wstring fullName = assemblyName.GetFullName();
std::wcout << std::endl << std::endl << _T("FullName:") << std::endl;
std::wcout << fullName << std::endl << std::endl;
}
catch (std::exception& e)
{
std::wcout << L"Error: " << e.what() << std::endl << std::endl ;
}
catch (HResultDecoder e)
{
std::wcout << L"Error: " << e.GetErrorCode()
<< L" (" << e.GetHexErrorCode() << L") -- "
<< e.GetErrorMessage() << std::endl << std::endl;
}
return 0;
}
| 25.5 | 87 | 0.606209 | ssidpat |
c7d9a33f16cb8c5506761d2a8528d130c30b7384 | 16,083 | cpp | C++ | amd_openvx_extensions/amd_nn/src/crop_and_resize_layer.cpp | asalmanp/MIVisionX | a964774944331827c8d6e9bb1ffbb2578f335056 | [
"MIT"
] | 153 | 2018-12-20T19:33:15.000Z | 2022-03-30T03:51:14.000Z | amd_openvx_extensions/amd_nn/src/crop_and_resize_layer.cpp | asalmanp/MIVisionX | a964774944331827c8d6e9bb1ffbb2578f335056 | [
"MIT"
] | 484 | 2019-01-02T23:51:58.000Z | 2022-03-31T15:52:43.000Z | amd_openvx_extensions/amd_nn/src/crop_and_resize_layer.cpp | asalmanp/MIVisionX | a964774944331827c8d6e9bb1ffbb2578f335056 | [
"MIT"
] | 105 | 2018-12-21T00:02:38.000Z | 2022-03-25T15:44:02.000Z | #include <kernels.h>
static vx_status VX_CALLBACK validateCropAndResizeLayer(vx_node node, const vx_reference *parameters, vx_uint32 num, vx_meta_format metas[]) {
vx_enum type, out_type;
vx_size num_dims;
vx_size input_dims[4], output_dims[4];
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[0], VX_TENSOR_NUMBER_OF_DIMS, &num_dims, sizeof(num_dims)));
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[0], VX_TENSOR_DATA_TYPE, &type, sizeof(type)));
if (num_dims != 4) return VX_ERROR_INVALID_DIMENSION;
if ((type != VX_TYPE_FLOAT32) && (type != VX_TYPE_FLOAT16)) return VX_ERROR_INVALID_TYPE;
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[0], VX_TENSOR_DIMS, input_dims, sizeof(input_dims)));
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[1], VX_TENSOR_NUMBER_OF_DIMS, &num_dims, sizeof(num_dims)));
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[1], VX_TENSOR_DATA_TYPE, &out_type, sizeof(out_type)));
if (num_dims != 4) return VX_ERROR_INVALID_DIMENSION;
if ((out_type != VX_TYPE_FLOAT32) && (out_type != VX_TYPE_FLOAT16)) return VX_ERROR_INVALID_TYPE;
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[1], VX_TENSOR_DIMS, output_dims, sizeof(output_dims)));
vx_int32 x_coord, y_coord, width, height, mode, scaleFactor;
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[2], &x_coord, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[3], &y_coord, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[4], &width, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[5], &height, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[6], &scaleFactor, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[7], &mode, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
if (x_coord < 0 || y_coord < 0 || x_coord > input_dims[0] || y_coord > input_dims[1]) {
printf("Crop coordinates out of bound\n");
return VX_ERROR_INVALID_PARAMETERS;
}
if (x_coord + width > input_dims[0] || y_coord + height > input_dims[1]) {
printf("Crop width/height out of bound\n");
return VX_ERROR_INVALID_PARAMETERS;
}
if (scaleFactor <= 0) {
printf("The scale factor has to be a positive integer\n");
return VX_ERROR_INVALID_PARAMETERS;
}
if (mode != 0 && mode != 1) {
printf("Mode should be either 0 or 1\n");
return VX_ERROR_INVALID_PARAMETERS;
}
if (output_dims[0] != width*scaleFactor || output_dims[1] != height*scaleFactor) {
printf("Output tensor's width/height should match the crop width/height multiplied by the scale factor\n");
return VX_ERROR_INVALID_PARAMETERS;
}
if (out_type != type) return VX_ERROR_INVALID_TYPE;
if (output_dims[2] != input_dims[2] || output_dims[3] != input_dims[3]) return VX_ERROR_INVALID_DIMENSION;
out_type = type;
num_dims = 4;
ERROR_CHECK_STATUS(vxSetMetaFormatAttribute(metas[1], VX_TENSOR_DATA_TYPE, &out_type, sizeof(out_type)));
ERROR_CHECK_STATUS(vxSetMetaFormatAttribute(metas[1], VX_TENSOR_NUMBER_OF_DIMS, &num_dims, sizeof(num_dims)));
ERROR_CHECK_STATUS(vxSetMetaFormatAttribute(metas[1], VX_TENSOR_DIMS, &output_dims, sizeof(output_dims)));
return VX_SUCCESS;
}
static vx_status VX_CALLBACK query_target_support(vx_graph graph, vx_node node,
vx_bool use_opencl_1_2,
vx_uint32& supported_target_affinity
)
{
supported_target_affinity = AGO_TARGET_AFFINITY_GPU;
return VX_SUCCESS;
}
static vx_status VX_CALLBACK opencl_codegen(
vx_node node, // [input] node
const vx_reference parameters[], // [input] parameters
vx_uint32 num, // [input] number of parameters
bool opencl_load_function, // [input] false: normal OpenCL kernel; true: reserved
char opencl_kernel_function_name[64], // [output] kernel_name for clCreateKernel()
std::string& opencl_kernel_code, // [output] string for clCreateProgramWithSource()
std::string& opencl_build_options, // [output] options for clBuildProgram()
vx_uint32& opencl_work_dim, // [output] work_dim for clEnqueueNDRangeKernel()
vx_size opencl_global_work[], // [output] global_work[] for clEnqueueNDRangeKernel()
vx_size opencl_local_work[], // [output] local_work[] for clEnqueueNDRangeKernel()
vx_uint32& opencl_local_buffer_usage_mask, // [output] reserved: must be ZERO
vx_uint32& opencl_local_buffer_size_in_bytes // [output] reserved: must be ZERO
)
{
//get tensor dimensions
vx_size input_dims[4], output_dims[4];
vx_size num_of_dims;
vx_enum type;
vx_uint32 x_coord, y_coord, width, height, mode;
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[0], VX_TENSOR_NUMBER_OF_DIMS, &num_of_dims, sizeof(num_of_dims)));
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[0], VX_TENSOR_DIMS, input_dims, sizeof(input_dims)));
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[1], VX_TENSOR_DIMS, output_dims, sizeof(output_dims)));
ERROR_CHECK_STATUS(vxQueryTensor((vx_tensor)parameters[1], VX_TENSOR_DATA_TYPE, &type, sizeof(type)));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[2], &x_coord, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[3], &y_coord, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[4], &width, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[5], &height, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
ERROR_CHECK_STATUS(vxCopyScalar((vx_scalar)parameters[7], &mode, VX_READ_ONLY, VX_MEMORY_TYPE_HOST));
strcpy(opencl_kernel_function_name, "crop_and_resize_layer");
vx_uint32 input_dim_size = input_dims[0] * input_dims[1] * input_dims[2] * input_dims[3];
opencl_work_dim = 3;
// Setting variables required by the interface
opencl_local_buffer_usage_mask = 0;
opencl_local_buffer_size_in_bytes = 0;
if (num_of_dims == 4) {
char item[8192];
if (mode == 0) {
opencl_global_work[0] = width;
opencl_global_work[1] = height;
opencl_global_work[2] = input_dims[2];
if (type == VX_TYPE_FLOAT32) {
sprintf(item,
"#pragma OPENCL EXTENSION cl_amd_media_ops : enable\n"
"__kernel void %s(__global uchar * in, uint in_offset, uint4 in_stride, __global uchar * out, uint out_offset, uint4 out_stride, uint x_coord, uint y_coord, uint width, uint height, uint scaleFactor, uint mode) \n"
"{ \n"
" uint x = get_global_id(0) + %d;\n"
" uint y = get_global_id(1) + %d;\n"
" uint c = get_global_id(2);\n"
" float value = *(__global float*)&in[in_offset + x*in_stride.s0 + y*in_stride.s1 + c*in_stride.s2];\n"
" out += out_offset + get_global_id(0)*out_stride.s0*scaleFactor + get_global_id(1)*out_stride.s1*scaleFactor + get_global_id(2)*out_stride.s2;\n"
" for (uint s0 = 0; s0 < scaleFactor; s0++) {\n"
" for (uint s1 = 0; s1 < scaleFactor; s1++) {\n"
" *(__global float *)&out[s0*out_stride.s0 + s1*out_stride.s1] = value;\n"
" }\n"
" }\n"
"}\n", opencl_kernel_function_name, (int)x_coord, (int)y_coord);
}
else {
sprintf(item,
"#pragma OPENCL EXTENSION cl_amd_media_ops : enable\n"
"__kernel void %s(__global uchar * in, uint in_offset, uint4 in_stride, __global uchar * out, uint out_offset, uint4 out_stride, uint x_coord, uint y_coord, uint width, uint height, uint scaleFactor, uint mode) \n"
"{ \n"
" uint x = get_global_id(0) + %d;\n"
" uint y = get_global_id(1) + %d;\n"
" uint c = get_global_id(2);\n"
" half value = *(__global half*)&in[in_offset + x*in_stride.s0 + y*in_stride.s1 + c*in_stride.s2];\n"
" out += out_offset + get_global_id(0)*out_stride.s0*scaleFactor + get_global_id(1)*out_stride.s1*scaleFactor + get_global_id(2)*out_stride.s2;\n"
" for (uint s0 = 0; s0 < scaleFactor; s0++) {\n"
" for (uint s1 = 0; s1 < scaleFactor; s1++) {\n"
" *(__global half *)&out[s0*out_stride.s0 + s1*out_stride.s1] = value;\n"
" }\n"
" }\n"
"}\n", opencl_kernel_function_name, (int)x_coord, (int)y_coord);
}
}
else {
opencl_global_work[0] = output_dims[0];
opencl_global_work[1] = output_dims[1];
opencl_global_work[2] = input_dims[2];
if (type == VX_TYPE_FLOAT32) {
sprintf(item,
"#pragma OPENCL EXTENSION cl_amd_media_ops : enable\n"
"__kernel void %s(__global uchar * in, uint in_offset, uint4 in_stride, __global uchar * out, uint out_offset, uint4 out_stride, uint x_coord, uint y_coord, uint width, uint height, uint scaleFactor, uint mode) \n"
"{ \n"
" uint x = get_global_id(0);\n"
" uint y = get_global_id(1);\n"
" uint c = get_global_id(2);\n"
" uint px = (int)(x / scaleFactor);\n"
" uint py = (int)(y / scaleFactor);\n"
" uint nx = px + %d;\n"
" uint ny = py + %d;\n"
" float fx1 = (float)x / (float)scaleFactor - (float)px;\n"
" float fx2 = 1 - fx1;\n"
" float fy1 = (float)y / (float)scaleFactor - (float)py;\n"
" float fy2 = 1 - fy1;\n"
" float w1 = fx2 * fy2;\n"
" float w2 = fx1 * fy2;\n"
" float w3 = fx2 * fy1;\n"
" float w4 = fx1 * fy1;\n"
" float value1 = *(__global float*)&in[in_offset + nx*in_stride.s0 + ny*in_stride.s1 + c*in_stride.s2];\n"
" float value2 = *(__global float*)&in[in_offset + (nx+1)*in_stride.s0 + ny*in_stride.s1 + c*in_stride.s2];\n"
" float value3 = *(__global float*)&in[in_offset + nx*in_stride.s0 + (ny+1)*in_stride.s1 + c*in_stride.s2];\n"
" float value4 = *(__global float*)&in[in_offset + (nx+1)*in_stride.s0 + (ny+1)*in_stride.s1 + c*in_stride.s2];\n"
" out += out_offset + get_global_id(0)*out_stride.s0 + get_global_id(1)*out_stride.s1 + get_global_id(2)*out_stride.s2;\n"
" *(__global float *)&out[0] = w1*value1 + w2*value2 + w3*value3 + w4*value4;\n"
"}\n", opencl_kernel_function_name, (int)x_coord, (int)y_coord);
}
else {
sprintf(item,
"#pragma OPENCL EXTENSION cl_amd_media_ops : enable\n"
"__kernel void %s(__global uchar * in, uint in_offset, uint4 in_stride, __global uchar * out, uint out_offset, uint4 out_stride, uint x_coord, uint y_coord, uint width, uint height, uint scaleFactor, uint mode) \n"
"{ \n"
" uint x = get_global_id(0);\n"
" uint y = get_global_id(1);\n"
" uint c = get_global_id(2);\n"
" uint px = (int)(x / scaleFactor);\n"
" uint py = (int)(y / scaleFactor);\n"
" uint nx = px + %d;\n"
" uint ny = py + %d;\n"
" half fx1 = (half)x / (half)scaleFactor - (half)px;\n"
" half fx2 = 1 - fx1;\n"
" half fy1 = (half)y / (half)scaleFactor - (half)py;\n"
" half fy2 = 1 - fy1;\n"
" half w1 = fx2 * fy2;\n"
" half w2 = fx1 * fy2;\n"
" half w3 = fx2 * fy1;\n"
" half w4 = fx1 * fy1;\n"
" half value1 = *(__global halft*)&in[in_offset + nx*in_stride.s0 + ny*in_stride.s1 + c*in_stride.s2];\n"
" half value2 = *(__global half*)&in[in_offset + (nx+1)*in_stride.s0 + ny*in_stride.s1 + c*in_stride.s2];\n"
" half value3 = *(__global half*)&in[in_offset + nx*in_stride.s0 + (ny+1)*in_stride.s1 + c*in_stride.s2];\n"
" half value4 = *(__global half*)&in[in_offset + (nx+1)*in_stride.s0 + (ny+1)*in_stride.s1 + c*in_stride.s2];\n"
" out += out_offset + get_global_id(0)*out_stride.s0 + get_global_id(1)*out_stride.s1 + get_global_id(2)*out_stride.s2;\n"
" *(__global half *)&out[0] = w1*value1 + w2*value2 + w3*value3 + w4*value4;\n"
"}\n", opencl_kernel_function_name, (int)x_coord, (int)y_coord);
}
}
opencl_kernel_code = item;
}
return VX_SUCCESS;
}
static vx_status VX_CALLBACK host_kernel(vx_node node, const vx_reference * parameters, vx_uint32 num) {
return VX_ERROR_NOT_IMPLEMENTED;
}
vx_status publishCropAndResizeLayer(vx_context context) {
vx_kernel kernel = vxAddUserKernel(context, "com.amd.nn_extension.crop_and_resize_layer", VX_KERNEL_CROP_AND_RESIZE_LAYER_AMD, host_kernel, 8, validateCropAndResizeLayer, NULL, NULL);
ERROR_CHECK_OBJECT(kernel);
amd_kernel_query_target_support_f query_target_support_f = query_target_support;
amd_kernel_opencl_codegen_callback_f opencl_codegen_callback_f = opencl_codegen;
ERROR_CHECK_STATUS(vxSetKernelAttribute(kernel, VX_KERNEL_ATTRIBUTE_AMD_QUERY_TARGET_SUPPORT, &query_target_support_f, sizeof(query_target_support_f)));
ERROR_CHECK_STATUS(vxSetKernelAttribute(kernel, VX_KERNEL_ATTRIBUTE_AMD_OPENCL_CODEGEN_CALLBACK, &opencl_codegen_callback_f, sizeof(opencl_codegen_callback_f)));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 0, VX_INPUT, VX_TYPE_TENSOR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 1, VX_OUTPUT, VX_TYPE_TENSOR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 2, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 3, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 4, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 5, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 6, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxAddParameterToKernel(kernel, 7, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
ERROR_CHECK_STATUS(vxFinalizeKernel(kernel));
ERROR_CHECK_STATUS(vxReleaseKernel(&kernel));
return VX_SUCCESS;
}
VX_API_ENTRY vx_node VX_API_CALL vxCropAndResizeLayer(vx_graph graph, vx_tensor input, vx_tensor output, vx_scalar x_coord, vx_scalar y_coord, vx_scalar width, vx_scalar height, vx_scalar scaleFactor, vx_scalar mode)
{
vx_node node = NULL;
vx_context context = vxGetContext((vx_reference)graph);
if (vxGetStatus((vx_reference)context) == VX_SUCCESS) {
vx_reference params[] = {
(vx_reference) input,
(vx_reference) output,
(vx_reference) x_coord,
(vx_reference) y_coord,
(vx_reference) width,
(vx_reference) height,
(vx_reference) scaleFactor,
(vx_reference) mode
};
node = createNode(graph, VX_KERNEL_CROP_AND_RESIZE_LAYER_AMD, params, sizeof(params) / sizeof(params[0]));
}
return node;
}
| 57.234875 | 230 | 0.641982 | asalmanp |
c7de29be989e742aa72b87500b286f1742317a29 | 6,081 | cc | C++ | spot/spot/twaalgos/translate.cc | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | 1 | 2018-03-02T14:29:57.000Z | 2018-03-02T14:29:57.000Z | spot/spot/twaalgos/translate.cc | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | null | null | null | spot/spot/twaalgos/translate.cc | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | 1 | 2015-06-05T12:42:07.000Z | 2015-06-05T12:42:07.000Z | // -*- coding: utf-8 -*-
// Copyright (C) 2013-2017 Laboratoire de Recherche et Développement
// de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <spot/twaalgos/translate.hh>
#include <spot/twaalgos/ltl2tgba_fm.hh>
#include <spot/twaalgos/compsusp.hh>
#include <spot/misc/optionmap.hh>
#include <spot/tl/relabel.hh>
#include <spot/twaalgos/relabel.hh>
namespace spot
{
void translator::setup_opt(const option_map* opt)
{
comp_susp_ = early_susp_ = skel_wdba_ = skel_simul_ = 0;
relabel_bool_ = tls_impl_ = -1;
if (!opt)
return;
relabel_bool_ = opt->get("relabel-bool", 4);
comp_susp_ = opt->get("comp-susp", 0);
if (comp_susp_ == 1)
{
early_susp_ = opt->get("early-susp", 0);
skel_wdba_ = opt->get("skel-wdba", -1);
skel_simul_ = opt->get("skel-simul", 1);
}
tls_impl_ = opt->get("tls-impl", -1);
}
void translator::build_simplifier(const bdd_dict_ptr& dict)
{
tl_simplifier_options options(false, false, false);
switch (level_)
{
case High:
options.containment_checks = true;
options.containment_checks_stronger = true;
SPOT_FALLTHROUGH;
case Medium:
options.synt_impl = true;
SPOT_FALLTHROUGH;
case Low:
options.reduce_basics = true;
options.event_univ = true;
}
// User-supplied fine-tuning?
if (tls_impl_ >= 0)
switch (tls_impl_)
{
case 0:
options.synt_impl = false;
options.containment_checks = false;
options.containment_checks_stronger = false;
break;
case 1:
options.synt_impl = true;
options.containment_checks = false;
options.containment_checks_stronger = false;
break;
case 2:
options.synt_impl = true;
options.containment_checks = true;
options.containment_checks_stronger = false;
break;
case 3:
options.synt_impl = true;
options.containment_checks = true;
options.containment_checks_stronger = true;
break;
default:
throw std::runtime_error
("tls-impl should take a value between 0 and 3");
}
simpl_owned_ = simpl_ = new tl_simplifier(options, dict);
}
twa_graph_ptr translator::run(formula* f)
{
bool unambiguous = (pref_ & postprocessor::Unambiguous);
if (unambiguous && type_ == postprocessor::Monitor)
{
// Deterministic monitor are unambiguous, so the unambiguous
// option is not really relevant for monitors.
unambiguous = false;
set_pref(pref_ | postprocessor::Deterministic);
}
// Do we want to relabel Boolean subformulas?
// If we have a huge formula such as
// (a1 & a2 & ... & an) U (b1 | b2 | ... | bm)
// then it is more efficient to translate
// a U b
// and then fix the automaton. We use relabel_bse() to find
// sub-formulas that are Boolean but do not have common terms.
//
// This rewriting is enabled only if the formula
// 1) has some Boolean subformula
// 2) has more than relabel_bool_ atomic propositions (the default
// is 4, but this can be changed)
// 3) relabel_bse() actually reduces the number of atomic
// propositions.
relabeling_map m;
formula to_work_on = *f;
if (relabel_bool_ > 0)
{
bool has_boolean_sub = false; // that is not atomic
std::set<formula> aps;
to_work_on.traverse([&](const formula& f)
{
if (f.is(op::ap))
aps.insert(f);
else if (f.is_boolean())
has_boolean_sub = true;
return false;
});
unsigned atomic_props = aps.size();
if (has_boolean_sub && (atomic_props >= (unsigned) relabel_bool_))
{
formula relabeled = relabel_bse(to_work_on, Pnn, &m);
if (m.size() < atomic_props)
to_work_on = relabeled;
else
m.clear();
}
}
formula r = simpl_->simplify(to_work_on);
if (to_work_on == *f)
*f = r;
// This helps ltl_to_tgba_fm() to order BDD variables in a more
// natural way (improving the degeneralization).
simpl_->clear_as_bdd_cache();
twa_graph_ptr aut;
if (comp_susp_ > 0)
{
// FIXME: Handle unambiguous_ automata?
int skel_wdba = skel_wdba_;
if (skel_wdba < 0)
skel_wdba = (pref_ == postprocessor::Deterministic) ? 1 : 2;
aut = compsusp(r, simpl_->get_dict(), skel_wdba == 0,
skel_simul_ == 0, early_susp_ != 0,
comp_susp_ == 2, skel_wdba == 2, false);
}
else
{
bool exprop = unambiguous || level_ == postprocessor::High;
aut = ltl_to_tgba_fm(r, simpl_->get_dict(), exprop,
true, false, false, nullptr, nullptr,
unambiguous);
}
aut = this->postprocessor::run(aut, r);
if (!m.empty())
relabel_here(aut, &m);
return aut;
}
twa_graph_ptr translator::run(formula f)
{
return run(&f);
}
void translator::clear_caches()
{
simpl_->clear_caches();
}
}
| 31.671875 | 74 | 0.588226 | mcc-petrinets |
c7e42f144afc7e32cc637eb5589570661ffe69d5 | 3,533 | cpp | C++ | src/atta/memorySystem/tests/speed.cpp | brenocq/atta | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 5 | 2021-11-18T02:44:45.000Z | 2021-12-21T17:46:10.000Z | src/atta/memorySystem/tests/speed.cpp | Brenocq/RobotSimulator | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 6 | 2021-03-11T21:01:27.000Z | 2021-09-06T19:41:46.000Z | src/atta/memorySystem/tests/speed.cpp | Brenocq/RobotSimulator | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 3 | 2020-09-10T07:17:00.000Z | 2020-11-05T10:24:41.000Z | //--------------------------------------------------
// Atta Memory Tests
// speed.cpp
// Date: 2021-08-20
// By Breno Cunha Queiroz
//--------------------------------------------------
#include <gtest/gtest.h>
#include <atta/core/stringId.h>
#include <atta/memorySystem/memoryManager.h>
#include <atta/memorySystem/allocatedObject.h>
#include <atta/memorySystem/allocators/stackAllocator.h>
#include <atta/memorySystem/allocators/mallocAllocator.h>
using namespace atta;
namespace
{
constexpr int NUM_IT = 1000;
constexpr int NUM_OBJ = 5000;
struct TestStack : public AllocatedObject<TestStack, SID("Stack")>
{
int x, y, z;
};
struct TestMalloc : public AllocatedObject<TestMalloc, SID("Malloc")>
{
int x, y, z;
};
struct TestCpp
{
int x, y, z;
};
class Memory_Speed : public ::testing::Test
{
public:
void SetUp()
{
MemoryManager::registerAllocator(
SID("Stack"),
static_cast<Allocator*>(new StackAllocator(sizeof(TestStack)*NUM_OBJ)));
MemoryManager::registerAllocator(
SID("Malloc"),
static_cast<Allocator*>(new MallocAllocator()));
}
};
TEST_F(Memory_Speed, DefaultNewCpp)
{
TestCpp* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new TestCpp();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
delete a[i];
}
}
}
TEST_F(Memory_Speed, MallocWithMemoryManager)
{
TestMalloc* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new TestMalloc();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
delete a[i];
}
}
}
TEST_F(Memory_Speed, StackObj)
{
StackAllocator stack = StackAllocator(sizeof(TestStack)*NUM_OBJ);
TestStack* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new (stack.alloc<TestStack>()) TestStack();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
stack.free<TestStack>(a[i]);
}
}
}
TEST_F(Memory_Speed, StackPtr)
{
StackAllocator* stack = MemoryManager::getAllocator<StackAllocator>(SID("Stack"));
TestStack* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new (stack->alloc<TestStack>()) TestStack();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
stack->free<TestStack>(a[i]);
}
}
EXPECT_EQ(stack->getUsedMemory(), 0);
}
TEST_F(Memory_Speed, StackWithMemoryManager)
{
TestStack* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new TestStack();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
delete a[i];
}
}
StackAllocator* stack = MemoryManager::getAllocator<StackAllocator>(SID("Stack"));
EXPECT_EQ(stack->getUsedMemory(), 0);
}
}
| 25.977941 | 92 | 0.463063 | brenocq |
c7ea1e1dbdf21ac93cb344d6fcf42752583cc5a7 | 2,067 | cpp | C++ | src/SelfGravity/Init_FFTW.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 3 | 2019-04-13T02:08:01.000Z | 2020-11-17T12:45:37.000Z | src/SelfGravity/Init_FFTW.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | null | null | null | src/SelfGravity/Init_FFTW.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 2 | 2019-11-12T02:00:20.000Z | 2019-12-09T14:52:31.000Z |
#include "DAINO.h"
#ifdef GRAVITY
#ifdef SERIAL
rfftwnd_plan FFTW_Plan, FFTW_Plan_Inv;
#else
rfftwnd_mpi_plan FFTW_Plan, FFTW_Plan_Inv;
#endif
//-------------------------------------------------------------------------------------------------------
// Function : Init_FFTW
// Description : Create the FFTW plans
//-------------------------------------------------------------------------------------------------------
void Init_FFTW()
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s ... ", __FUNCTION__ );
# ifdef SERIAL
FFTW_Plan = rfftw3d_create_plan( NX0_TOT[2], NX0_TOT[1], NX0_TOT[0], FFTW_REAL_TO_COMPLEX,
FFTW_ESTIMATE | FFTW_IN_PLACE );
FFTW_Plan_Inv = rfftw3d_create_plan( NX0_TOT[2], NX0_TOT[1], NX0_TOT[0], FFTW_COMPLEX_TO_REAL,
FFTW_ESTIMATE | FFTW_IN_PLACE );
# else
FFTW_Plan = rfftw3d_mpi_create_plan( MPI_COMM_WORLD, NX0_TOT[2], NX0_TOT[1], NX0_TOT[0],
FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE );
FFTW_Plan_Inv = rfftw3d_mpi_create_plan( MPI_COMM_WORLD, NX0_TOT[2], NX0_TOT[1], NX0_TOT[0],
FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE );
# endif
if ( MPI_Rank == 0 ) Aux_Message( stdout, "done\n" );
} // FUNCTION : Init_FFTW
//-------------------------------------------------------------------------------------------------------
// Function : End_FFTW
// Description : Delete the FFTW plans
//-------------------------------------------------------------------------------------------------------
void End_FFTW()
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s ... ", __FUNCTION__ );
# ifdef SERIAL
rfftwnd_destroy_plan ( FFTW_Plan );
rfftwnd_destroy_plan ( FFTW_Plan_Inv );
# else
rfftwnd_mpi_destroy_plan( FFTW_Plan );
rfftwnd_mpi_destroy_plan( FFTW_Plan_Inv );
# endif
if ( MPI_Rank == 0 ) Aux_Message( stdout, "done\n" );
} // FUNCTION : End_FFTW
#endif // #ifdef GRAVITY
| 27.932432 | 105 | 0.490082 | zhulianhua |
c7ed2d1bc3fb2cbf5d63984700fc53908b5d510b | 15,457 | cc | C++ | unittest/gunit/opt_range-t.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | unittest/gunit/opt_range-t.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | unittest/gunit/opt_range-t.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
// First include (the generated) my_config.h, to get correct platform defines.
#include "my_config.h"
#include <gtest/gtest.h>
#include "test_utils.h"
#include "opt_range.cc"
namespace opt_range_unittest {
using my_testing::Server_initializer;
class SelArgTest : public ::testing::Test
{
protected:
SelArgTest()
{
memset(&m_opt_param, 0, sizeof(m_opt_param));
}
virtual void SetUp()
{
initializer.SetUp();
m_opt_param.thd= thd();
m_opt_param.mem_root= &m_alloc;
m_opt_param.current_table= 1<<0;
init_sql_alloc(&m_alloc, thd()->variables.range_alloc_block_size, 0);
}
virtual void TearDown()
{
initializer.TearDown();
free_root(&m_alloc, MYF(0));
}
THD *thd() { return initializer.thd(); }
Server_initializer initializer;
MEM_ROOT m_alloc;
RANGE_OPT_PARAM m_opt_param;
};
/*
Experiment with these to measure performance of
'new (thd->mem_root)' Foo vs. 'new Foo'.
With gcc 4.4.2 I see ~4% difference (in optimized mode).
*/
const int num_iterations= 10;
const int num_allocs= 10;
TEST_F(SelArgTest, AllocateExplicit)
{
for (int ix= 0; ix < num_iterations; ++ix)
{
free_root(thd()->mem_root, MYF(MY_KEEP_PREALLOC));
for (int ii= 0; ii < num_allocs; ++ii)
new (thd()->mem_root) SEL_ARG;
}
}
TEST_F(SelArgTest, AllocateImplicit)
{
for (int ix= 0; ix < num_iterations; ++ix)
{
free_root(thd()->mem_root, MYF(MY_KEEP_PREALLOC));
for (int ii= 0; ii < num_allocs; ++ii)
new SEL_ARG;
}
}
/*
We cannot do EXPECT_NE(NULL, get_mm_tree(...))
because of limits in google test.
*/
const SEL_TREE *null_tree= NULL;
const SEL_ARG *null_arg= NULL;
class Mock_field_long : public Field_long
{
public:
Mock_field_long(THD *thd, Item *item)
: Field_long(0, // ptr_arg
8, // len_arg
NULL, // null_ptr_arg
0, // null_bit_arg
Field::NONE, // unireg_check_arg
"field_name", // field_name_arg
false, // zero_arg
false) // unsigned_arg
{
m_table_name= "mock_table";
memset(&m_share, 0, sizeof(m_share));
const char *foo= "mock_db";
m_share.db.str= const_cast<char*>(foo);
m_share.db.length= strlen(m_share.db.str);
bitmap_init(&share_allset, 0, sizeof(my_bitmap_map), 0);
bitmap_set_above(&share_allset, 0, 1); //all bits 1
m_share.all_set= share_allset;
memset(&m_table, 0, sizeof(m_table));
m_table.s= &m_share;
bitmap_init(&tbl_readset, 0, sizeof(my_bitmap_map), 0);
m_table.read_set= &tbl_readset;
bitmap_init(&tbl_writeset, 0, sizeof(my_bitmap_map), 0);
m_table.write_set= &tbl_writeset;
m_table.map= 1<<0;
m_table.in_use= thd;
this->table_name= &m_table_name;
this->table= &m_table;
this->ptr= (uchar*) alloc_root((thd->mem_root), KEY_LENGTH);
if (item)
item->save_in_field_no_warnings(this, true);
}
~Mock_field_long()
{
bitmap_free(&share_allset);
bitmap_free(&tbl_readset);
bitmap_free(&tbl_writeset);
}
// #bytes to store the value - see Field_long::key_lenght()
static const int KEY_LENGTH= 4;
const char *m_table_name;
TABLE_SHARE m_share;
TABLE m_table;
MY_BITMAP share_allset;
MY_BITMAP tbl_readset;
MY_BITMAP tbl_writeset;
};
static void print_selarg_ranges(String *s, SEL_ARG *sel_arg,
const KEY_PART_INFO *kpi)
{
for (SEL_ARG *cur= sel_arg->first();
cur != &null_element;
cur= cur->right)
{
String current_range;
append_range(¤t_range, kpi, cur->min_value, cur->max_value,
cur->min_flag | cur->max_flag);
if (s->length() > 0)
s->append(STRING_WITH_LEN("\n"));
s->append(current_range);
}
}
TEST_F(SelArgTest, SimpleCond)
{
EXPECT_NE(null_tree, get_mm_tree(&m_opt_param, new Item_int(42)));
}
/*
TODO: Here we try to build a range, but a lot of mocking remains
before it works as intended. Currently get_mm_tree() returns NULL
because m_opt_param.key_parts and m_opt_param.key_parts_end have not
been setup.
*/
TEST_F(SelArgTest, EqualCond)
{
Mock_field_long field_long(thd(), NULL);
m_opt_param.table= &field_long.m_table;
SEL_TREE *tree= get_mm_tree(&m_opt_param,
new Item_equal(new Item_int(42),
new Item_field(&field_long)));
EXPECT_EQ(null_tree, tree);
}
TEST_F(SelArgTest, SelArgOnevalue)
{
Mock_field_long field_long7(thd(), new Item_int(7));
KEY_PART_INFO kpi;
kpi.init_from_field(&field_long7);
uchar range_val7[field_long7.KEY_LENGTH];
field_long7.get_key_image(range_val7, kpi.length, Field::itRAW);
SEL_ARG sel_arg7(&field_long7, range_val7, range_val7);
String range_string;
print_selarg_ranges(&range_string, &sel_arg7, &kpi);
const char expected[]= "7 <= field_name <= 7";
EXPECT_STREQ(expected, range_string.c_ptr());
sel_arg7.min_flag|= NO_MIN_RANGE;
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg7, &kpi);
const char expected2[]= "field_name <= 7";
EXPECT_STREQ(expected2, range_string.c_ptr());
sel_arg7.max_flag= NEAR_MAX;
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg7, &kpi);
const char expected3[]= "field_name < 7";
EXPECT_STREQ(expected3, range_string.c_ptr());
sel_arg7.min_flag= NEAR_MIN;
sel_arg7.max_flag= NO_MAX_RANGE;
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg7, &kpi);
const char expected4[]= "7 < field_name";
EXPECT_STREQ(expected4, range_string.c_ptr());
sel_arg7.min_flag= 0;
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg7, &kpi);
const char expected5[]= "7 <= field_name";
EXPECT_STREQ(expected5, range_string.c_ptr());
}
TEST_F(SelArgTest, SelArgBetween)
{
Mock_field_long field_long3(thd(), new Item_int(3));
Mock_field_long field_long5(thd(), new Item_int(5));
KEY_PART_INFO kpi;
kpi.init_from_field(&field_long3);
uchar range_val3[field_long3.KEY_LENGTH];
field_long3.get_key_image(range_val3, kpi.length, Field::itRAW);
uchar range_val5[field_long5.KEY_LENGTH];
field_long5.get_key_image(range_val5, kpi.length, Field::itRAW);
SEL_ARG sel_arg35(&field_long3, range_val3, range_val5);
String range_string;
print_selarg_ranges(&range_string, &sel_arg35, &kpi);
const char expected[]= "3 <= field_name <= 5";
EXPECT_STREQ(expected, range_string.c_ptr());
range_string.length(0);
sel_arg35.min_flag= NEAR_MIN;
print_selarg_ranges(&range_string, &sel_arg35, &kpi);
const char expected2[]= "3 < field_name <= 5";
EXPECT_STREQ(expected2, range_string.c_ptr());
range_string.length(0);
sel_arg35.max_flag= NEAR_MAX;
print_selarg_ranges(&range_string, &sel_arg35, &kpi);
const char expected3[]= "3 < field_name < 5";
EXPECT_STREQ(expected3, range_string.c_ptr());
range_string.length(0);
sel_arg35.min_flag= 0;
print_selarg_ranges(&range_string, &sel_arg35, &kpi);
const char expected4[]= "3 <= field_name < 5";
EXPECT_STREQ(expected4, range_string.c_ptr());
range_string.length(0);
sel_arg35.min_flag= NO_MIN_RANGE;
sel_arg35.max_flag= 0;
print_selarg_ranges(&range_string, &sel_arg35, &kpi);
const char expected5[]= "field_name <= 5";
EXPECT_STREQ(expected5, range_string.c_ptr());
range_string.length(0);
sel_arg35.min_flag= 0;
sel_arg35.max_flag= NO_MAX_RANGE;
print_selarg_ranges(&range_string, &sel_arg35, &kpi);
const char expected6[]= "3 <= field_name";
EXPECT_STREQ(expected6, range_string.c_ptr());
}
TEST_F(SelArgTest, CopyMax)
{
Mock_field_long field_long3(thd(), new Item_int(3));
Mock_field_long field_long5(thd(), new Item_int(5));
KEY_PART_INFO kpi;
kpi.init_from_field(&field_long3);
uchar range_val3[field_long3.KEY_LENGTH];
field_long3.get_key_image(range_val3, kpi.length, Field::itRAW);
uchar range_val5[field_long5.KEY_LENGTH];
field_long5.get_key_image(range_val5, kpi.length, Field::itRAW);
SEL_ARG sel_arg3(&field_long3, range_val3, range_val3);
sel_arg3.min_flag= NO_MIN_RANGE;
SEL_ARG sel_arg5(&field_long5, range_val5, range_val5);
sel_arg5.min_flag= NO_MIN_RANGE;
String range_string;
print_selarg_ranges(&range_string, &sel_arg3, &kpi);
const char expected[]= "field_name <= 3";
EXPECT_STREQ(expected, range_string.c_ptr());
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg5, &kpi);
const char expected2[]= "field_name <= 5";
EXPECT_STREQ(expected2, range_string.c_ptr());
/*
Ranges now:
-inf ----------------3-5----------- +inf
sel_arg3: [-------------------->
sel_arg5: [---------------------->
Below: merge these two ranges into sel_arg3 using copy_max()
*/
bool full_range= sel_arg3.copy_max(&sel_arg5);
// The merged range does not cover all possible values
EXPECT_FALSE(full_range);
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg3, &kpi);
const char expected3[]= "field_name <= 5";
EXPECT_STREQ(expected3, range_string.c_ptr());
range_string.length(0);
sel_arg5.min_flag= 0;
sel_arg5.max_flag= NO_MAX_RANGE;
print_selarg_ranges(&range_string, &sel_arg5, &kpi);
const char expected4[]= "5 <= field_name";
EXPECT_STREQ(expected4, range_string.c_ptr());
/*
Ranges now:
-inf ----------------3-5----------- +inf
sel_arg3: [---------------------->
sel_arg5: <---------------]
Below: merge these two ranges into sel_arg3 using copy_max()
*/
full_range= sel_arg3.copy_max(&sel_arg5);
// The new range covers all possible values
EXPECT_TRUE(full_range);
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg3, &kpi);
const char expected5[]= "field_name";
EXPECT_STREQ(expected5, range_string.c_ptr());
}
TEST_F(SelArgTest, CopyMin)
{
Mock_field_long field_long3(thd(), new Item_int(3));
Mock_field_long field_long5(thd(), new Item_int(5));
KEY_PART_INFO kpi;
kpi.init_from_field(&field_long3);
uchar range_val3[field_long3.KEY_LENGTH];
field_long3.get_key_image(range_val3, kpi.length, Field::itRAW);
uchar range_val5[field_long5.KEY_LENGTH];
field_long5.get_key_image(range_val5, kpi.length, Field::itRAW);
SEL_ARG sel_arg3(&field_long3, range_val3, range_val3);
sel_arg3.max_flag= NO_MAX_RANGE;
SEL_ARG sel_arg5(&field_long5, range_val5, range_val5);
sel_arg5.max_flag= NO_MAX_RANGE;
String range_string;
print_selarg_ranges(&range_string, &sel_arg3, &kpi);
const char expected[]= "3 <= field_name";
EXPECT_STREQ(expected, range_string.c_ptr());
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg5, &kpi);
const char expected2[]= "5 <= field_name";
EXPECT_STREQ(expected2, range_string.c_ptr());
/*
Ranges now:
-inf ----------------3-5----------- +inf
sel_arg3: <-----------------]
sel_arg5: <---------------]
Below: merge these two ranges into sel_arg3 using copy_max()
*/
bool full_range= sel_arg5.copy_min(&sel_arg3);
// The merged range does not cover all possible values
EXPECT_FALSE(full_range);
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg5, &kpi);
const char expected3[]= "3 <= field_name";
EXPECT_STREQ(expected3, range_string.c_ptr());
range_string.length(0);
sel_arg3.max_flag= 0;
sel_arg3.min_flag= NO_MIN_RANGE;
print_selarg_ranges(&range_string, &sel_arg3, &kpi);
const char expected4[]= "field_name <= 3";
EXPECT_STREQ(expected4, range_string.c_ptr());
/*
Ranges now:
-inf ----------------3-5----------- +inf
sel_arg3: [-------------------->
sel_arg5: <-----------------]
Below: merge these two ranges into sel_arg5 using copy_min()
*/
full_range= sel_arg5.copy_min(&sel_arg3);
// The new range covers all possible values
EXPECT_TRUE(full_range);
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg5, &kpi);
const char expected5[]= "field_name";
EXPECT_STREQ(expected5, range_string.c_ptr());
}
TEST_F(SelArgTest, KeyOr1)
{
Mock_field_long field_long3(thd(), new Item_int(3));
Mock_field_long field_long4(thd(), new Item_int(4));
KEY_PART_INFO kpi;
kpi.init_from_field(&field_long3);
uchar range_val3[field_long3.KEY_LENGTH];
field_long3.get_key_image(range_val3, kpi.length, Field::itRAW);
uchar range_val4[field_long4.KEY_LENGTH];
field_long4.get_key_image(range_val4, kpi.length, Field::itRAW);
SEL_ARG sel_arg_lt3(&field_long3, range_val3, range_val3);
sel_arg_lt3.part= 0;
sel_arg_lt3.min_flag= NO_MIN_RANGE;
sel_arg_lt3.max_flag= NEAR_MAX;
SEL_ARG sel_arg_gt3(&field_long3, range_val3, range_val3);
sel_arg_gt3.part= 0;
sel_arg_gt3.min_flag= NEAR_MIN;
sel_arg_gt3.max_flag= NO_MAX_RANGE;
SEL_ARG sel_arg_lt4(&field_long4, range_val4, range_val4);
sel_arg_lt4.part= 0;
sel_arg_lt4.min_flag= NO_MIN_RANGE;
sel_arg_lt4.max_flag= NEAR_MAX;
String range_string;
print_selarg_ranges(&range_string, &sel_arg_lt3, &kpi);
const char expected_lt3[]= "field_name < 3";
EXPECT_STREQ(expected_lt3, range_string.c_ptr());
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg_gt3, &kpi);
const char expected_gt3[]= "3 < field_name";
EXPECT_STREQ(expected_gt3, range_string.c_ptr());
range_string.length(0);
print_selarg_ranges(&range_string, &sel_arg_lt4, &kpi);
const char expected_lt4[]= "field_name < 4";
EXPECT_STREQ(expected_lt4, range_string.c_ptr());
/*
Ranges now:
-inf ----------------34----------- +inf
sel_arg_lt3: [-------------------->
sel_arg_gt3: <---------------]
sel_arg_lt4: [--------------------->
*/
SEL_ARG *tmp= key_or(NULL, &sel_arg_lt3, &sel_arg_gt3);
/*
Ranges now:
-inf ----------------34----------- +inf
tmp: [--------------------><---------------]
sel_arg_lt4: [--------------------->
*/
range_string.length(0);
print_selarg_ranges(&range_string, tmp, &kpi);
const char expected_merged[]=
"field_name < 3\n"
"3 < field_name";
EXPECT_STREQ(expected_merged, range_string.c_ptr());
SEL_ARG *tmp2= key_or(NULL, tmp, &sel_arg_lt4);
EXPECT_EQ(null_arg, tmp2);
}
}
| 30.487179 | 83 | 0.662289 | hervewenjie |
c7ed511b9d0ade7a00ed856912190bbbfc7477c7 | 578 | cpp | C++ | acmicpc/14627.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/14627.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/14627.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
using namespace std;
#define MAX 1000001
#define ll long long
const ll INF = 1e9+7;
ll n, k, p, total;
ll pa[MAX];
bool check(ll mid)
{
ll cnt = 0;
for (int i=0; i<n; ++i)
cnt += pa[i] / mid;
return cnt >= k;
}
int main()
{
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
cin >> n >> k;
for (int i=0; i<n; ++i) {
cin >> pa[i];
total += pa[i];
}
ll l = 1, r = INF;
while (l <= r) {
ll mid = (l+r)/2LL;
if (check(mid)) {
l = mid+1;
p = mid;
} else {
r = mid-1;
}
}
cout << total - k * p << '\n';
return 0;
}
| 12.844444 | 31 | 0.50692 | juseongkr |
c7f08fc096d3392d0f15755c7d8791cb590f6508 | 552 | hpp | C++ | android-31/java/lang/LinkageError.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/lang/LinkageError.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/lang/LinkageError.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "./Error.hpp"
class JString;
class JThrowable;
namespace java::lang
{
class LinkageError : public java::lang::Error
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit LinkageError(const char *className, const char *sig, Ts...agv) : java::lang::Error(className, sig, std::forward<Ts>(agv)...) {}
LinkageError(QJniObject obj);
// Constructors
LinkageError();
LinkageError(JString arg0);
LinkageError(JString arg0, JThrowable arg1);
// Methods
};
} // namespace java::lang
| 19.714286 | 163 | 0.688406 | YJBeetle |
c7f19c0e759845db014af34b2e387e65bb1dfc3e | 786 | cc | C++ | src/obj/object.cc | abyss7/libgit- | 0e2dee26fbe64ebfb6a6cfa332b8dc4a3bdea11d | [
"MIT"
] | 1 | 2019-11-09T22:22:23.000Z | 2019-11-09T22:22:23.000Z | src/obj/object.cc | abyss7/libgitxx | 0e2dee26fbe64ebfb6a6cfa332b8dc4a3bdea11d | [
"MIT"
] | null | null | null | src/obj/object.cc | abyss7/libgitxx | 0e2dee26fbe64ebfb6a6cfa332b8dc4a3bdea11d | [
"MIT"
] | null | null | null | #include "object.hh"
#include <base/exception.hh>
namespace git {
Object::Type Object::type() const {
switch (git_object_type(raw_object())) {
case GIT_OBJ_BLOB:
return BLOB;
case GIT_OBJ_COMMIT:
return COMMIT;
case GIT_OBJ_TREE:
return TREE;
default:
return UNKNOWN;
}
}
Object::Id::Id(const String& content, Type type) : _id(new git_oid) {
git_otype git_type;
switch (type) {
case BLOB:
git_type = GIT_OBJ_BLOB;
break;
case COMMIT:
git_type = GIT_OBJ_COMMIT;
break;
case TREE:
git_type = GIT_OBJ_TREE;
break;
default:
git_type = GIT_OBJ_BAD;
}
TryGitCall(git_odb_hash(const_cast<git_oid*>(_id.get()), content.data(), content.size(), git_type));
}
} // namespace git
| 19.170732 | 102 | 0.63486 | abyss7 |
c7f448a0f4c0ed6170eca03602a0725b897d3871 | 404 | cpp | C++ | swig_example/third party/swig-example.cpp | Lukemtesta/python-binding | bef3978ac48ce4e683014798ccac9a88cfd73ee0 | [
"Apache-2.0"
] | null | null | null | swig_example/third party/swig-example.cpp | Lukemtesta/python-binding | bef3978ac48ce4e683014798ccac9a88cfd73ee0 | [
"Apache-2.0"
] | null | null | null | swig_example/third party/swig-example.cpp | Lukemtesta/python-binding | bef3978ac48ce4e683014798ccac9a88cfd73ee0 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "liba.h"
#include "swig-example.h"
void swig_example_hello()
{
std::cout << "Hello from swig-example" << std::endl;
}
void link_liba_hello()
{
liba_hello();
}
void blah()
{
std::cout << "blah" << std::endl;
}
void vector_print()
{
std::cout << "vector print" << std::endl;
}
std::vector<int> random_vector_int()
{
return std::vector<int>{ 1, 2, 3, 4, 5 };
} | 13.466667 | 56 | 0.618812 | Lukemtesta |
c7f53d3c297632110eedc8c7962b70178fa1f375 | 667 | cpp | C++ | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/VolumeEvent.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2016-03-29T21:45:21.000Z | 2016-12-20T00:50:38.000Z | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/VolumeEvent.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/VolumeEvent.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | // VolumeEvent.cpp
#include "VolumeEvent.h"
// constructor
VolumeEvent::VolumeEvent(uint32 type, vnode_id target)
: Referencable(true),
fType(type),
fTarget(target)
{
}
// destructor
VolumeEvent::~VolumeEvent()
{
}
// GetType
uint32
VolumeEvent::GetType() const
{
return fType;
}
// SetTarget
void
VolumeEvent::SetTarget(vnode_id target)
{
fTarget = target;
}
// GetTarget
vnode_id
VolumeEvent::GetTarget() const
{
return fTarget;
}
// #pragma mark -
// constructor
ConnectionBrokenEvent::ConnectionBrokenEvent(vnode_id target)
: VolumeEvent(CONNECTION_BROKEN_EVENT, target)
{
}
// destructor
ConnectionBrokenEvent::~ConnectionBrokenEvent()
{
}
| 12.584906 | 61 | 0.736132 | axeld |
c7fa467a0f1aa0846ad7eaf95175e148869b76e2 | 435 | cpp | C++ | UVa 10545 - Maximal Quadrilateral/sample/10545 - Maximal Quadrilateral.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 10545 - Maximal Quadrilateral/sample/10545 - Maximal Quadrilateral.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 10545 - Maximal Quadrilateral/sample/10545 - Maximal Quadrilateral.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <math.h>
// http://en.wikipedia.org/wiki/Brahmagupta%27s_formula
int main() {
scanf("%*d");
int cases = 0;
double p, a, b;
while(scanf("%lf %lf %lf", &p, &a, &b) == 3) {
printf("Case %d: ", ++cases);
if (a > p - a || b > p - b) {
puts("Eta Shombhob Na.");
continue;
}
double c = p/2 - a;
double d = p/2 - b;
printf("%.6f\n", sqrt(a * b * c * d) * 2 / (a + b + c + d));
}
return 0;
}
| 21.75 | 62 | 0.501149 | tadvi |
c7fe942d4e6736080ae2b254888cb2a4396eb117 | 5,140 | cc | C++ | src/cpp/charmove.cc | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | 32 | 2015-02-21T17:11:50.000Z | 2022-02-10T16:34:16.000Z | src/cpp/charmove.cc | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | null | null | null | src/cpp/charmove.cc | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | 8 | 2016-05-30T07:24:19.000Z | 2021-11-13T10:46:27.000Z | // Copyright (c) 2014, Tamas Csala
#include "./charmove.h"
#include <GLFW/glfw3.h>
#include <algorithm>
#include "engine/game_engine.h"
CharacterMovement::CharacterMovement(engine::GameObject *parent,
float horizontal_speed,
float rotationSpeed_PerSec)
: engine::GameObject(parent)
, transform_(*parent->transform())
, curr_rot_(0)
, dest_rot_(0)
, rot_speed_(rotationSpeed_PerSec)
, vert_speed_(0)
, horiz_speed_(horizontal_speed)
, horiz_speed_factor_(1.0f)
, walking_(false)
, jumping_(false)
, flip_(false)
, can_flip_(true)
, transition_(false)
, anim_(nullptr)
, camera_(nullptr)
, can_jump_functor_(nullptr)
, can_flip_functor_(nullptr)
{ }
void CharacterMovement::handleSpacePressed() {
if (!jumping_) {
if (can_jump_functor_ == nullptr || can_jump_functor_()) {
jumping_ = true;
flip_ = false;
vert_speed_ = 10.0f;
horiz_speed_factor_ = 1.0f;
}
} else if (can_flip_) {
if (can_flip_functor_ == nullptr || can_flip_functor_()) {
can_flip_ = false;
flip_ = true;
vert_speed_ = 11.0f;
horiz_speed_factor_ = 1.3f;
}
}
}
void CharacterMovement::update() {
float time = scene_->game_time().current;
const engine::Camera& cam = *camera_;
glm::vec2 character_offset = anim_->offsetSinceLastFrame();
static float prevTime = 0;
float dt = time - prevTime;
prevTime = time;
glm::ivec2 moveDir; // up and right is positive
bool w = glfwGetKey(scene_->window(), GLFW_KEY_W) == GLFW_PRESS;
bool a = glfwGetKey(scene_->window(), GLFW_KEY_A) == GLFW_PRESS;
bool s = glfwGetKey(scene_->window(), GLFW_KEY_S) == GLFW_PRESS;
bool d = glfwGetKey(scene_->window(), GLFW_KEY_D) == GLFW_PRESS;
if (w && !s) {
moveDir.y = 1;
} else if (s && !w) {
moveDir.y = -1;
}
if (d && !a) {
moveDir.x = 1;
} else if (a && !d) {
moveDir.x = -1;
}
static glm::ivec2 lastMoveDir;
bool lastWalking = walking_;
walking_ = moveDir.x || moveDir.y;
transition_ = transition_ || (walking_ != lastWalking) ||
(lastMoveDir != moveDir);
lastMoveDir = moveDir;
if (walking_) {
glm::vec3 fwd = cam.transform()->forward();
double cameraRot = -atan2(fwd.z, fwd.x);
double moveRot = atan2(moveDir.y, moveDir.x); // +y is forward
dest_rot_ = cameraRot + moveRot;
dest_rot_ = fmod(dest_rot_, 2*M_PI);
double diff = dest_rot_ - curr_rot_;
double sign = diff / fabs(diff);
// Take the shorter path.
while (fabs(diff) > M_PI) {
dest_rot_ -= sign * 2*M_PI;
diff = dest_rot_ - curr_rot_;
sign = diff / fabs(diff);
}
if (transition_) {
if (fabs(diff) > rot_speed_ / 20.0f) {
curr_rot_ += sign * dt * rot_speed_;
curr_rot_ = fmod(curr_rot_, 2*M_PI);
} else {
transition_ = false;
}
} else {
curr_rot_ = fmod(dest_rot_, 2*M_PI);
}
}
glm::mat4 rotation = glm::rotate(glm::mat4(),
static_cast<float>(fmod(curr_rot_, 2*M_PI)),
glm::vec3(0, 1, 0));
transform_.set_rot(glm::quat_cast(rotation));
glm::vec3 pos = transform_.pos();
pos += glm::mat3(rotation) *
glm::vec3(character_offset.x, 0, character_offset.y);
if (jumping_) {
pos += glm::mat3(rotation) *
glm::vec3(0, 0, horiz_speed_ * horiz_speed_factor_ * dt);
}
transform_.set_pos(pos);
updateHeight(time);
}
void CharacterMovement::keyAction(int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
handleSpacePressed();
}
}
void CharacterMovement::updateHeight(float time) {
glm::vec3 local_pos = transform_.local_pos();
static float prevTime = 0;
float diff_time = time - prevTime;
prevTime = time;
while (diff_time > 0) {
float time_step = 0.01f;
float dt = std::min(time_step, diff_time);
diff_time -= time_step;
if (local_pos.y < 0 && jumping_ && vert_speed_ < 0) {
jumping_ = false;
flip_ = false;
can_flip_ = true;
local_pos.y = 0;
return;
}
if (!jumping_) {
const float offs =
std::max<float>(fabs(local_pos.y / 2.0f), 0.05f) * dt * 20.0f;
if (fabs(local_pos.y) > offs) {
local_pos.y -= local_pos.y / fabs(local_pos.y) * offs;
}
} else {
if (local_pos.y < 0) {
local_pos.y += std::max(local_pos.y, vert_speed_) * dt;
} else {
local_pos.y += vert_speed_ * dt;
}
vert_speed_ -= dt * scene_->gravity();
}
}
transform_.set_local_pos(local_pos);
}
bool CharacterMovement::isJumping() const {
return jumping_;
}
bool CharacterMovement::isJumpingRise() const {
return jumping_ && !flip_ && vert_speed_ > 0;
}
bool CharacterMovement::isJumpingFall() const {
return jumping_ && !flip_ && vert_speed_ < 0;
}
bool CharacterMovement::isDoingFlip() const {
return flip_;
}
void CharacterMovement::setFlip(bool flip) {
flip_ = flip;
}
bool CharacterMovement::isWalking() const {
return walking_;
}
| 26.091371 | 80 | 0.6107 | Tomius |
2a064dae7b4f94058d585d6e386bae6f52c918ac | 1,469 | cpp | C++ | Engine/Source/Developer/FriendsAndChat/Private/Layers/Presentation/ChatTipViewModel.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Developer/FriendsAndChat/Private/Layers/Presentation/ChatTipViewModel.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Developer/FriendsAndChat/Private/Layers/Presentation/ChatTipViewModel.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "FriendsAndChatPrivatePCH.h"
#include "FriendsChatMarkupService.h"
#include "ChatTipViewModel.h"
class FChatTipViewModelImpl
: public FChatTipViewModel
{
public:
~FChatTipViewModelImpl()
{
MarkupService->OnInputUpdated().RemoveAll(this);
}
DECLARE_DERIVED_EVENT(FChatTipViewModelImpl, FChatTipViewModel::FChatTipAvailable, FChatTipAvailable)
virtual FChatTipAvailable& OnChatTipAvailable() override
{
return ChatTipAvailableEvent;
}
virtual TArray<TSharedRef<IChatTip> >& GetChatTips() override
{
return MarkupService->GetChatTips();
}
virtual TSharedPtr<IChatTip> GetActiveTip() override
{
return MarkupService->GetActiveTip();
}
private:
void HandleChatInputChanged()
{
OnChatTipAvailable().Broadcast();
}
void Initialize()
{
MarkupService->OnInputUpdated().AddSP(this, &FChatTipViewModelImpl::HandleChatInputChanged);
}
FChatTipViewModelImpl(const TSharedRef<FFriendsChatMarkupService>& InMarkupService)
: MarkupService(InMarkupService)
{
}
private:
TSharedRef<FFriendsChatMarkupService> MarkupService;
FChatTipAvailable ChatTipAvailableEvent;
friend FChatTipViewModelFactory;
};
TSharedRef< FChatTipViewModel > FChatTipViewModelFactory::Create(const TSharedRef<FFriendsChatMarkupService>& MarkupService)
{
TSharedRef< FChatTipViewModelImpl > ViewModel(new FChatTipViewModelImpl(MarkupService));
ViewModel->Initialize();
return ViewModel;
} | 23.693548 | 124 | 0.801225 | PopCap |
2a097d3ec1dfe1c331751073885e827411bc8cab | 2,490 | cpp | C++ | 1_Naive_solution.cpp | ansa1/SberGamesTest | 148194e83eed9ced8dac61659182d468d8f80ff5 | [
"MIT"
] | null | null | null | 1_Naive_solution.cpp | ansa1/SberGamesTest | 148194e83eed9ced8dac61659182d468d8f80ff5 | [
"MIT"
] | null | null | null | 1_Naive_solution.cpp | ansa1/SberGamesTest | 148194e83eed9ced8dac61659182d468d8f80ff5 | [
"MIT"
] | null | null | null | /*
* Author: Abirov Ansat
* Description: Naive solution
* Complexity: O(N^4)
* Details: Consider all possible turns(O(N^2)) and
check that at least 1 row or column has 3 in a row
* Elapsed time: 1.5h
*/
#include <iostream>
#include <algorithm>
bool check_3_in_a_row(int** field, int n, int m) {
// rows
for (int i = 0; i < n; ++i) {
int max_length = 1;
for (int j = 0; j < m; ++j) {
if (field[i][j] == 0) {
max_length = 1;
continue;
}
if (j > 0 && field[i][j] == field[i][j - 1]) {
max_length++;
if (max_length == 3) {
return true;
}
}
else {
max_length = 1;
}
}
}
// columns
for (int j = 0; j < m; ++j) {
int max_length = 1;
for (int i = 0; i < n; ++i) {
if (field[i][j] == 0) {
max_length = 1;
continue;
}
if (i > 0 && field[i][j] == field[i - 1][j]) {
max_length++;
if (max_length == 3) {
return true;
}
}
else {
max_length = 1;
}
}
}
return false;
}
bool is_possible_turn(int **field, int n, int m) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (i + 1 < n) {
std::swap(field[i][j], field[i + 1][j]);
bool result = check_3_in_a_row(field, n, m);
std::swap(field[i][j], field[i + 1][j]);
if (result) {
return true;
}
}
if (j + 1 < m) {
std::swap(field[i][j], field[i][j + 1]);
bool result = check_3_in_a_row(field, n, m);
std::swap(field[i][j], field[i][j + 1]);
if (result) {
return true;
}
}
}
}
return false;
}
int main() {
// init
const int N = 6, M = 6;
int **field = new int*[N];
for (int i = 0; i < N; ++i) {
field[i] = new int[M];
}
// input
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
std::cin >> field[i][j];
}
}
// output
std::cout << (is_possible_turn(field, N, M) ? "Yes" : "No");
return 0;
} | 24.653465 | 65 | 0.36747 | ansa1 |
2a0ae0111bb4284ec5b9af8e8406546f232bdd2b | 215 | cpp | C++ | Plugins/VirtuosoInput/Source/VirtuosoInput/Private/VirtuosoTrackingState.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | 3 | 2021-05-26T14:12:01.000Z | 2022-01-09T01:15:12.000Z | Plugins/VirtuosoInput/Source/VirtuosoInput/Private/VirtuosoTrackingState.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | null | null | null | Plugins/VirtuosoInput/Source/VirtuosoInput/Private/VirtuosoTrackingState.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | null | null | null | // Copyright 2020 Charles River Analytics, Inc. All Rights Reserved.
#include "VirtuosoTrackingState.h"
UVirtuosoTrackingState::UVirtuosoTrackingState()
{
}
UVirtuosoTrackingState::~UVirtuosoTrackingState()
{
}
| 16.538462 | 68 | 0.795349 | charles-river-analytics |
2a0f66cf05f312fc1cc7e36ec7f09caf9c29361f | 13,868 | cpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AudioPlayer/volume_bar.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AudioPlayer/volume_bar.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AudioPlayer/volume_bar.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | // Generated by imageconverter. Please, do not edit!
#include <touchgfx/hal/Config.hpp>
LOCATION_EXTFLASH_PRAGMA
KEEP extern const unsigned char _volume_bar[] LOCATION_EXTFLASH_ATTRIBUTE = { // 170x4 ARGB8888 pixels.
0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x27,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x27
};
| 252.145455 | 320 | 0.797159 | ramkumarkoppu |
2a101a79b18945b9f171d6ce995edb45c666134c | 7,774 | cpp | C++ | src/hash_tables.cpp | dfwteinos/Search-Clustering | 174a26ac7aabf9d3a7ce06976e3ebe77c6a8c1bd | [
"MIT"
] | null | null | null | src/hash_tables.cpp | dfwteinos/Search-Clustering | 174a26ac7aabf9d3a7ce06976e3ebe77c6a8c1bd | [
"MIT"
] | null | null | null | src/hash_tables.cpp | dfwteinos/Search-Clustering | 174a26ac7aabf9d3a7ce06976e3ebe77c6a8c1bd | [
"MIT"
] | null | null | null | #include "../include/hash_tables.h"
#include "../include/arguments.h"
template <class T>
HashTable<T>::HashTable(vector_list_collection<T> data_set, int k_value, int l_value, int R_value, int N_value, double C_value)
{
table_size = data_set.size() / 16;
vector_size = data_set[0].second.size();
K = k_value;
L = l_value;
R = R_value;
N = N_value;
c = C_value;
}
template <class T>
T manhattan_distance(std::vector<T> x, std::vector<T> y)
{
T result = 0;
typename std::vector<T>::iterator it;
typename std::vector<T>::iterator ti;
for (it = x.begin(), ti = y.begin(); it != x.end(); ++it, ++ti)
{
result += abs(*it - *ti);
}
return result;
}
template <class T>
bool sortbysec(cand_img<T> &a, cand_img<T> &b)
{
return (a.second < b.second);
}
template <class T>
image<T> bruteforce(vector_list_collection<T> data_set, image<T> query, T &res)
{
image<T> best;
T best_distance = std::numeric_limits<T>::max();
T current;
for (ssize_t i = 0; i < data_set.size(); i++)
{
current = manhattan_distance<T>(data_set[i].second, query.second);
if (current < best_distance)
{
best_distance = current;
best = data_set[i];
}
}
res = best_distance;
return best;
}
template <class T>
std::vector<cand_img<T>> bruteforcelsh(vector_list_collection<T> data_set, image<T> query, int N)
{
std::vector<cand_img<T>> best_imgs(N); //Vector with <Key:Image , Value:Distance>
best_imgs.clear();
image<T> temp_img; //Each image that we check
T temp_dist; //Each distance that we check
cand_img<T> temp_cand; //A pair of image and its distance
for (int i = 0; i < data_set.size(); i++)
{
temp_img = data_set[i];
temp_dist = manhattan_distance<T>(data_set[i].second, query.second);
temp_cand = make_pair(temp_img, temp_dist);
if (i <= N)
{ //If our list is not full
if (i == N)
{
std::sort(best_imgs.begin(), best_imgs.end(), sortbysec<T>);
if (temp_dist < best_imgs.back().second)
{ //If the temp. distance if lower than the last item of our candidates, then replace it
best_imgs[N - 1] = temp_cand; //If doesen't work, try vector.insert(vector.end(), x)
std::sort(best_imgs.begin(), best_imgs.end(), sortbysec<T>);
}
}
else
best_imgs.push_back(temp_cand);
}
else
{ //If our list is full, then we need to compare the elements
if (temp_dist < best_imgs.back().second)
{ //If the temp. distance if lower than the last item of our candidates, then replace it
best_imgs[N - 1] = temp_cand; //If doesen't work, try vector.insert(vector.end(), x)
std::sort(best_imgs.begin(), best_imgs.end(), sortbysec<T>);
}
}
}
return best_imgs;
}
uint32_t swap_endian(uint32_t val)
{
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | (val >> 16);
}
void read_metadata(std::ifstream &file, uint32_t &magic_num, uint32_t &num_of_images, uint32_t &rows, uint32_t &columns, int size)
{ //Take the metadata (magic number, number of images, rows and columns)
file.read(reinterpret_cast<char *>(&magic_num), size); //we are doing this type of cast bcz we are playing with bits, and bcz we want to convert: 0x00000803 -> 2051
magic_num = swap_endian(magic_num);
std::cout << "magic num: " << magic_num << std::endl;
file.read(reinterpret_cast<char *>(&num_of_images), size);
num_of_images = swap_endian(num_of_images);
std::cout << "#images: " << num_of_images << std::endl;
file.read(reinterpret_cast<char *>(&rows), size);
rows = swap_endian(rows);
std::cout << "#rows: " << rows << std::endl;
file.read(reinterpret_cast<char *>(&columns), size);
columns = swap_endian(columns);
std::cout << "#columns: " << columns << std::endl;
}
template <class T>
vector_list_collection<T> HashTable<T>::vectorise_data(std::string file_name)
{
vector_list_collection<T> data;
std::ifstream file; // Stream class to read from files
file.open(file_name, std::ios::in | std::ios::binary); // in(open for input operations), binary(open in binary mode)
if (file.is_open()) //If the file has successfully opened
{
uint32_t magic_num = 0, num_of_images = 0, rows = 0, columns = 0; //uint32_t => unsigned byte, [ 0, 2^32 -1 ]. That's the type of the magic num, noi,r, c, according to the assignment.
read_metadata(file, magic_num, num_of_images, rows, columns, 4);
for (uint32_t i = 0; i < num_of_images; ++i)
{
data.push_back(std::pair<int, std::vector<T>>(i, std::vector<T>()));
for (uint32_t r = 0; r < rows; ++r)
{
for (uint32_t c = 0; c < columns; ++c)
{
unsigned char temp = 0;
file.read((char *)&temp, sizeof(temp));
data[i].second.push_back((int)temp); //each pixel of image (Question(?)) => Why not (char) temp? Each pixel is 0 until 255. Int is a waste of memory(?)
}
}
}
std::cout << "done reading files" << std::endl;
}
else
{
std::cout << "Something went wrong while reading the file " << file_name << std::endl;
exit(EXIT_FAILURE);
}
return data;
}
template <class T>
void HashTable<T>::get_neighbours(std::ostream &my_file)
{
if (this->R != 0)
{
for (auto it = this->neighbours.begin(); it != this->neighbours.end(); it++)
{
my_file << (*it).first << std::endl;
}
}
this->neighbours.clear();
return;
}
template <class T>
bool handle_conflicts(vector_list_collection<T> ¢roids, image<T> &image, clusters<T> &i2c, int dist)
{
for (auto it = i2c.begin(); it != i2c.end(); ++it) //For all vectors of centroids
{
int index = 0;
for (auto ti = (it->second).begin(); ti < (it->second).end(); ++ti) //Check if given image is part of any cluster
{
if (image.first == ti->first) //If yes, calculate the Manhattan distance between cluster's centroid and image
{
if (manhattan_distance(image.second, (it->first).second) > dist)
{
(it->second).erase((it->second).begin() + index); //If distance is larger than given distance erase image from current cluster
return true;
}
else
{
return false;
}
}
index++;
}
}
return true; //If it reaches that point, given image wasn't part of any cluster yet
}
template class HashTable<int>;
template class HashTable<double>;
template image<int> bruteforce(vector_list_collection<int>, image<int>, int &);
template image<double> bruteforce(vector_list_collection<double>, image<double>, double &);
template std::vector<cand_img<int>> bruteforcelsh(vector_list_collection<int>, image<int>, int);
template std::vector<cand_img<double>> bruteforcelsh(vector_list_collection<double>, image<double>, int);
template bool sortbysec<int>(cand_img<int> &a, cand_img<int> &b);
template bool sortbysec<double>(cand_img<double> &a, cand_img<double> &b);
template bool handle_conflicts<int>(vector_list_collection<int> &, image<int> &, clusters<int> &, int);
template bool handle_conflicts<double>(vector_list_collection<double> &, image<double> &, clusters<double> &, int);
| 33.65368 | 191 | 0.593645 | dfwteinos |
2a13ee99d2c4490dda1e4ba956ef71fd24d735c8 | 16,691 | cpp | C++ | src/test/dag/temporal_components.cpp | arashbm/dag | 26559581f696fabf7aacb3fbc045df811ddbd37d | [
"MIT"
] | null | null | null | src/test/dag/temporal_components.cpp | arashbm/dag | 26559581f696fabf7aacb3fbc045df811ddbd37d | [
"MIT"
] | 14 | 2021-05-24T12:11:05.000Z | 2022-03-02T22:15:01.000Z | src/test/dag/temporal_components.cpp | arashbm/dag | 26559581f696fabf7aacb3fbc045df811ddbd37d | [
"MIT"
] | null | null | null | #include <vector>
#include <set>
#include <unordered_set>
#include <catch2/catch.hpp>
using Catch::Matchers::UnorderedEquals;
using Catch::Matchers::Equals;
#include <dag/temporal_components.hpp>
#include <dag/temporal_edges.hpp>
#include <dag/estimators.hpp>
TEST_CASE("temporal components", "[dag::temporal_component]") {
using EdgeType = dag::directed_delayed_temporal_edge<int, int>;
dag::temporal_component<EdgeType, dag::exact_estimator> comp(0ul);
EdgeType a(1, 2, 1, 3), b(2, 1, 2, 1), c(2, 3, 6, 1);
comp.insert(a, a.mutated_verts());
comp.insert(b, b.mutated_verts());
SECTION("correct basic properties") {
REQUIRE(comp.node_set().set() == std::unordered_set<int>({1, 2}));
REQUIRE(comp.edge_set().set() == std::unordered_set<EdgeType>({a, b}));
REQUIRE(comp.cause_lifetime() == std::make_pair(1, 2));
REQUIRE(comp.effect_lifetime() == std::make_pair(3, 4));
}
SECTION("insertion") {
comp.insert(c, c.mutated_verts());
REQUIRE(comp.node_set().set() == std::unordered_set<int>({1, 2, 3}));
REQUIRE(comp.edge_set().set() == std::unordered_set<EdgeType>({a, b, c}));
REQUIRE(comp.cause_lifetime() == std::make_pair(1, 6));
REQUIRE(comp.effect_lifetime() == std::make_pair(3, 7));
}
SECTION("merging") {
dag::temporal_component<EdgeType, dag::exact_estimator> comp2(0ul);
comp2.insert(c, c.mutated_verts());
comp.merge(comp2);
REQUIRE(comp.node_set().set() == std::unordered_set<int>({1, 2, 3}));
REQUIRE(comp.edge_set().set() == std::unordered_set<EdgeType>({a, b, c}));
REQUIRE(comp.cause_lifetime() == std::make_pair(1, 6));
REQUIRE(comp.effect_lifetime() == std::make_pair(3, 7));
}
}
#include "../../../include/dag/implicit_event_graph.hpp"
TEST_CASE("in- and out- components for implicit event graph",
"[dag::out_component][dag::in_component]"
"[dag::out_components][dag::in_components]") {
SECTION("undirected temporal network") {
using EdgeType = dag::undirected_temporal_edge<int, int>;
using ProbType = dag::adjacency_prob::deterministic<EdgeType>;
using CompType = dag::temporal_component<EdgeType, dag::exact_estimator>;
dag::network<EdgeType> network(
{{1, 2, 1}, {2, 1, 2}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}, {5, 6, 1}});
ProbType prob(3);
dag::implicit_event_graph<EdgeType, ProbType> eg(network, prob, 0ul);
SECTION("out component") {
CompType c = dag::out_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {3, 4, 8}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 3, 4}));
}
SECTION("in component") {
CompType c = dag::in_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {1, 2, 5}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 3, 1}));
}
SECTION("all out components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_oc({
{{1, 2, 1}, {{1, 2, 1}, {2, 1, 2}}},
{{2, 1, 2}, {{2, 1, 2}}},
{{1, 2, 5}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{2, 3, 6}, {{2, 3, 6}, {3, 4, 8}}},
{{3, 4, 8}, {{3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{1, 2, 1}, {1, 2, 5}, {5, 6, 1}})));
}
SECTION("root and non-root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("all in components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_ic({
{{2, 1, 2}, {{2, 1, 2}, {1, 2, 1}}},
{{1, 2, 1}, {{1, 2, 1}}},
{{1, 2, 5}, {{1, 2, 5}}},
{{2, 3, 6}, {{1, 2, 5}, {2, 3, 6}}},
{{3, 4, 8}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{2, 1, 2}, {3, 4, 8}, {5, 6, 1}})));
}
SECTION("root and non-root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("weakly connected components") {
std::set<EdgeType>
w1({{1, 2, 1}, {2, 1, 2}}),
w2({{2, 3, 6}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}}),
w3({{5, 6, 1}});
SECTION("with singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2, w3}));
}
SECTION("without singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul, false);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2}));
}
}
}
SECTION("directed temporal network") {
using EdgeType = dag::directed_temporal_edge<int, int>;
using ProbType = dag::adjacency_prob::deterministic<EdgeType>;
using CompType = dag::temporal_component<EdgeType, dag::exact_estimator>;
dag::network<EdgeType> network(
{{1, 2, 1}, {2, 1, 2}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}, {5, 6, 1}});
ProbType prob(3);
dag::implicit_event_graph<EdgeType, ProbType> eg(network, prob, 0ul);
SECTION("out component") {
CompType c = dag::out_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {3, 4, 8}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({3, 4}));
}
SECTION("in component") {
CompType c = dag::in_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {1, 2, 5}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 1}));
}
SECTION("all out components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_oc({
{{1, 2, 1}, {{1, 2, 1}, {2, 1, 2}}},
{{2, 1, 2}, {{2, 1, 2}}},
{{1, 2, 5}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{2, 3, 6}, {{2, 3, 6}, {3, 4, 8}}},
{{3, 4, 8}, {{3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{1, 2, 1}, {1, 2, 5}, {5, 6, 1}})));
}
SECTION("root and non-root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("all in components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_ic({
{{2, 1, 2}, {{2, 1, 2}, {1, 2, 1}}},
{{1, 2, 1}, {{1, 2, 1}}},
{{1, 2, 5}, {{1, 2, 5}}},
{{2, 3, 6}, {{1, 2, 5}, {2, 3, 6}}},
{{3, 4, 8}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{2, 1, 2}, {3, 4, 8}, {5, 6, 1}})));
}
SECTION("root and non-root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("weakly connected components") {
std::set<EdgeType>
w1({{1, 2, 1}, {2, 1, 2}}),
w2({{2, 3, 6}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}}),
w3({{5, 6, 1}});
SECTION("with singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2, w3}));
}
SECTION("without singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul, false);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2}));
}
}
}
SECTION("directed delayed temporal network") {
using EdgeType = dag::directed_delayed_temporal_edge<int, int>;
using ProbType = dag::adjacency_prob::deterministic<EdgeType>;
using CompType = dag::temporal_component<EdgeType, dag::exact_estimator>;
dag::network<EdgeType> network(
{{1, 2, 1, 4}, {2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1}, {3, 4, 8, 1},
{5, 6, 1, 2}});
ProbType prob(3);
dag::implicit_event_graph<EdgeType, ProbType> eg(network, prob, 0ul);
SECTION("out component") {
CompType c = dag::out_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6, 1}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6, 1}, {3, 4, 8, 1}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({3, 4}));
}
SECTION("in component") {
CompType c = dag::in_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6, 1}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>(
{{2, 1, 2, 1}, {2, 3, 6, 1}, {1, 2, 5, 0}, {1, 2, 1, 4}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 1}));
}
SECTION("all out components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_oc({
{{1, 2, 1, 4}, {{1, 2, 1, 4}, {2, 3, 6, 1}, {3, 4, 8, 1}}},
{{2, 1, 2, 1},
{{2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1}, {3, 4, 8, 1}}},
{{1, 2, 5, 0}, {{1, 2, 5, 0}, {2, 3, 6, 1}, {3, 4, 8, 1}}},
{{2, 3, 6, 1}, {{2, 3, 6, 1}, {3, 4, 8, 1}}},
{{3, 4, 8, 1}, {{3, 4, 8, 1}}},
{{5, 6, 1, 2}, {{5, 6, 1, 2}}},
});
SECTION("root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>(
{{1, 2, 1, 4}, {2, 1, 2, 1}, {5, 6, 1, 2}})));
}
SECTION("root and non-root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("all in components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_ic({
{{1, 2, 1, 4}, {{1, 2, 1, 4}}},
{{2, 1, 2, 1}, {{2, 1, 2, 1}}},
{{1, 2, 5, 0}, {{1, 2, 5, 0}, {2, 1, 2, 1}}},
{{2, 3, 6, 1},
{{2, 3, 6, 1}, {1, 2, 5, 0}, {2, 1, 2, 1}, {1, 2, 1, 4}}},
{{3, 4, 8, 1},
{{2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1},
{1, 2, 1, 4}, {3, 4, 8, 1}}},
{{5, 6, 1, 2}, {{5, 6, 1, 2}}},
});
SECTION("root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{3, 4, 8, 1}, {5, 6, 1, 2}})));
}
SECTION("root and non-root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("weakly connected components") {
std::set<EdgeType>
w1({{1, 2, 1, 4}, {2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1},
{3, 4, 8, 1}}),
w2({{5, 6, 1, 2}});
SECTION("with singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results == std::set<std::set<EdgeType>>({w1, w2}));
}
SECTION("without singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul, false);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results == std::set<std::set<EdgeType>>({w1}));
}
}
}
}
| 36.60307 | 80 | 0.522617 | arashbm |
2a14be0a116e52c8069e13b13ed08e3b958a4d5b | 11,002 | cpp | C++ | HoloIntervention/Source/Rendering/CameraResources.cpp | adamrankin/HoloIntervention | 0f2a4dc702729a0a04af5c210884ef4e08e49267 | [
"Apache-2.0"
] | 2 | 2020-06-17T09:55:59.000Z | 2021-04-03T16:18:29.000Z | HoloIntervention/Source/Rendering/CameraResources.cpp | adamrankin/HoloIntervention | 0f2a4dc702729a0a04af5c210884ef4e08e49267 | [
"Apache-2.0"
] | 1 | 2018-09-02T02:39:21.000Z | 2018-09-02T02:39:21.000Z | HoloIntervention/Source/Rendering/CameraResources.cpp | adamrankin/HoloIntervention | 0f2a4dc702729a0a04af5c210884ef4e08e49267 | [
"Apache-2.0"
] | null | null | null | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
// Local includes
#include "pch.h"
#include "CameraResources.h"
#include "DeviceResources.h"
#include "DirectXHelper.h"
// WinRT includes
#include <windows.graphics.directx.direct3d11.interop.h>
// Unnecessary, but reduces intellisense errors
#include <WindowsNumerics.h>
using namespace DirectX;
using namespace Microsoft::WRL;
using namespace Windows::Foundation::Numerics;
using namespace Windows::Graphics::DirectX::Direct3D11;
using namespace Windows::Graphics::Holographic;
using namespace Windows::Perception::Spatial;
namespace DX
{
//----------------------------------------------------------------------------
CameraResources::CameraResources(HolographicCamera^ camera)
: m_holographicCamera(camera)
, m_isStereo(camera->IsStereo)
, m_d3dRenderTargetSize(camera->RenderTargetSize)
{
m_d3dViewport = CD3D11_VIEWPORT(0.f, 0.f, m_d3dRenderTargetSize.Width, m_d3dRenderTargetSize.Height);
};
//----------------------------------------------------------------------------
void CameraResources::CreateResourcesForBackBuffer(
DX::DeviceResources* pDeviceResources,
HolographicCameraRenderingParameters^ cameraParameters
)
{
const auto device = pDeviceResources->GetD3DDevice();
IDirect3DSurface^ surface = cameraParameters->Direct3D11BackBuffer;
ComPtr<ID3D11Resource> resource;
DX::ThrowIfFailed(GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(&resource)));
ComPtr<ID3D11Texture2D> cameraBackBuffer;
DX::ThrowIfFailed(resource.As(&cameraBackBuffer));
if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
{
m_d3dBackBuffer = cameraBackBuffer;
DX::ThrowIfFailed(device->CreateRenderTargetView(m_d3dBackBuffer.Get(), nullptr, &m_d3dRenderTargetView));
D3D11_TEXTURE2D_DESC backBufferDesc;
m_d3dBackBuffer->GetDesc(&backBufferDesc);
m_dxgiFormat = backBufferDesc.Format;
Windows::Foundation::Size currentSize = m_holographicCamera->RenderTargetSize;
if (m_d3dRenderTargetSize != currentSize)
{
m_d3dRenderTargetSize = currentSize;
m_d3dDepthStencilView.Reset();
}
}
// Refresh depth stencil resources, if needed.
if (m_d3dDepthStencilView == nullptr)
{
CD3D11_TEXTURE2D_DESC depthStencilDesc(DXGI_FORMAT_D16_UNORM, static_cast<UINT>(m_d3dRenderTargetSize.Width), static_cast<UINT>(m_d3dRenderTargetSize.Height),
m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
1, // Use a single mipmap level.
D3D11_BIND_DEPTH_STENCIL
);
ComPtr<ID3D11Texture2D> depthStencil;
DX::ThrowIfFailed(device->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencil));
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D);
DX::ThrowIfFailed(device->CreateDepthStencilView(depthStencil.Get(), &depthStencilViewDesc, &m_d3dDepthStencilView));
}
// Create the constant buffer, if needed.
if (m_viewProjectionConstantBuffer == nullptr)
{
// Create a constant buffer to store view and projection matrices for the camera.
CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
DX::ThrowIfFailed(device->CreateBuffer(&constantBufferDesc, nullptr, &m_viewProjectionConstantBuffer));
}
}
//----------------------------------------------------------------------------
void CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
{
const auto context = pDeviceResources->GetD3DDeviceContext();
// Release camera-specific resources.
m_d3dBackBuffer.Reset();
m_d3dRenderTargetView.Reset();
m_d3dDepthStencilView.Reset();
m_viewProjectionConstantBuffer.Reset();
// Ensure system references to the back buffer are released by clearing the render
// target from the graphics pipeline state, and then flushing the Direct3D context.
ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
context->Flush();
}
//----------------------------------------------------------------------------
bool CameraResources::Update(std::shared_ptr<DX::DeviceResources> deviceResources, HolographicCameraPose^ cameraPose, SpatialCoordinateSystem^ coordinateSystem)
{
m_d3dViewport = CD3D11_VIEWPORT(cameraPose->Viewport.Left, cameraPose->Viewport.Top, cameraPose->Viewport.Width, cameraPose->Viewport.Height);
HolographicStereoTransform cameraProjectionTransform = cameraPose->ProjectionTransform;
Platform::IBox<HolographicStereoTransform>^ viewTransformContainer = cameraPose->TryGetViewTransform(coordinateSystem);
auto frustrumBox = cameraPose->TryGetCullingFrustum(coordinateSystem);
if (frustrumBox != nullptr)
{
m_spatialBoundingFrustum = std::make_shared<SpatialBoundingFrustum>(frustrumBox->Value);
}
bool viewTransformAcquired = viewTransformContainer != nullptr;
if (viewTransformAcquired)
{
HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer->Value;
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.hmdToView[0], XMLoadFloat4x4(&viewCoordinateSystemTransform.Left));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.hmdToView[1], XMLoadFloat4x4(&viewCoordinateSystemTransform.Right));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.projection[0], XMLoadFloat4x4(&cameraProjectionTransform.Left));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.projection[1], XMLoadFloat4x4(&cameraProjectionTransform.Right));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.viewProjection[0], XMLoadFloat4x4(&viewCoordinateSystemTransform.Left) * XMLoadFloat4x4(&cameraProjectionTransform.Left));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.viewProjection[1], XMLoadFloat4x4(&viewCoordinateSystemTransform.Right) * XMLoadFloat4x4(&cameraProjectionTransform.Right));
float4x4 viewInverse;
bool invertible = Windows::Foundation::Numerics::invert(viewCoordinateSystemTransform.Left, &viewInverse);
if (invertible)
{
float4 cameraPosition = float4(viewInverse.m41, viewInverse.m42, viewInverse.m43, 0.f);
float4 lightPosition = cameraPosition + float4(0.f, 0.25f, 0.f, 0.f);
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.cameraPosition[0], DirectX::XMLoadFloat4(&cameraPosition));
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.lightPosition[0], DirectX::XMLoadFloat4(&lightPosition));
}
invertible = Windows::Foundation::Numerics::invert(viewCoordinateSystemTransform.Right, &viewInverse);
if (invertible)
{
float4 cameraPosition = float4(viewInverse.m41, viewInverse.m42, viewInverse.m43, 0.f);
float4 lightPosition = cameraPosition + float4(0.f, 0.25f, 0.f, 0.f);
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.cameraPosition[1], DirectX::XMLoadFloat4(&cameraPosition));
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.lightPosition[1], DirectX::XMLoadFloat4(&lightPosition));
}
}
const auto context = deviceResources->GetD3DDeviceContext();
if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
{
m_framePending = false;
return false;
}
else
{
context->UpdateSubresource(m_viewProjectionConstantBuffer.Get(), 0, nullptr, &m_cpuViewProjectionConstantBuffer, 0, 0);
m_framePending = true;
return true;
}
}
//----------------------------------------------------------------------------
bool CameraResources::Attach(std::shared_ptr<DX::DeviceResources> deviceResources)
{
const auto context = deviceResources->GetD3DDeviceContext();
if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
{
return false;
}
context->RSSetViewports(1, &m_d3dViewport);
context->VSSetConstantBuffers(1, 1, m_viewProjectionConstantBuffer.GetAddressOf());
context->PSSetConstantBuffers(1, 1, m_viewProjectionConstantBuffer.GetAddressOf());
m_framePending = false;
return true;
}
//----------------------------------------------------------------------------
DX::ViewProjectionConstantBuffer CameraResources::GetLatestViewProjectionBuffer() const
{
return m_cpuViewProjectionConstantBuffer;
}
//----------------------------------------------------------------------------
bool CameraResources::GetLatestSpatialBoundingFrustum(Windows::Perception::Spatial::SpatialBoundingFrustum& outFrustum) const
{
if (m_spatialBoundingFrustum == nullptr)
{
return false;
}
outFrustum = *m_spatialBoundingFrustum;
return true;
}
//----------------------------------------------------------------------------
ID3D11RenderTargetView* CameraResources::GetBackBufferRenderTargetView() const
{
return m_d3dRenderTargetView.Get();
}
//----------------------------------------------------------------------------
ID3D11DepthStencilView* CameraResources::GetDepthStencilView() const
{
return m_d3dDepthStencilView.Get();
}
//----------------------------------------------------------------------------
ID3D11Texture2D* CameraResources::GetBackBufferTexture2D() const
{
return m_d3dBackBuffer.Get();
}
//----------------------------------------------------------------------------
D3D11_VIEWPORT CameraResources::GetViewport() const
{
return m_d3dViewport;
}
//----------------------------------------------------------------------------
DXGI_FORMAT CameraResources::GetBackBufferDXGIFormat() const
{
return m_dxgiFormat;
}
//----------------------------------------------------------------------------
Windows::Foundation::Size CameraResources::GetRenderTargetSize() const
{
return m_d3dRenderTargetSize;
}
//----------------------------------------------------------------------------
bool CameraResources::IsRenderingStereoscopic() const
{
return m_isStereo;
}
//----------------------------------------------------------------------------
Windows::Graphics::Holographic::HolographicCamera^ CameraResources::GetHolographicCamera() const
{
return m_holographicCamera;
}
} | 41.052239 | 181 | 0.655699 | adamrankin |
2a1607449de6e64dc5c8c7ec2813e4dec7f91e5c | 3,586 | cc | C++ | client/fs_fuse.cc | apardyl/cloudrun-hashfs | 09420e16ab8e37c140af9684afbb895e742ac11f | [
"MIT"
] | null | null | null | client/fs_fuse.cc | apardyl/cloudrun-hashfs | 09420e16ab8e37c140af9684afbb895e742ac11f | [
"MIT"
] | 1 | 2018-08-30T20:08:14.000Z | 2018-08-31T18:57:42.000Z | client/fs_fuse.cc | apardyl/cloudrun-fs | 09420e16ab8e37c140af9684afbb895e742ac11f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <unistd.h>
#include <dirent.h>
#include <cerrno>
#include "fs_fuse.h"
#include "hash_fs.h"
#include "common/config.h"
#include "cache_fs.h"
static HashFS *hfs;
static CacheFS *cfs;
static bool ignoredPath(const char *path) {
return strncmp(path, "/dev/", 5) == 0 || strncmp(path, "/sys/", 5) == 0 || strncmp(path, "/proc/", 6) == 0 ||
strncmp(path, "/tmp/", 5) == 0 || strncmp(path, "/run/", 5) == 0;
}
static bool ignoredDir(const char *path) {
return strncmp(path, "/dev", 4) == 0 || strncmp(path, "/sys", 4) == 0 || strncmp(path, "/proc", 5) == 0 ||
strncmp(path, "/tmp", 4) == 0 || strncmp(path, "/run", 4) == 0;
}
static int hfs_getattr(const char *path, struct stat *stbuf) {
int res;
debug_print("getattr %s\n", path);
if (ignoredPath(path)) {
return -ENOENT;
}
res = hfs->lstat(path, stbuf);
if (res == -2) {
res = cfs->lstat(path, stbuf);
}
if (res == -1) {
return -errno;
}
return 0;
}
static int hfs_readlink(const char *path, char *buf, size_t size) {
ssize_t res;
debug_print("readlink %s\n", path);
if (ignoredPath(path)) {
return -ENOENT;
}
res = hfs->readlink(path, buf, size - 1);
if (res == -2) {
res = cfs->readlink(path, buf, size - 1);
}
if (res == -1) {
return -errno;
}
buf[res] = '\0';
return 0;
}
static int hfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi) {
int res;
debug_print("readdir %s\n", path);
(void) offset;
(void) fi;
if (ignoredDir(path)) {
filler(buf, ".", nullptr, 0);
filler(buf, "..", nullptr, 0);
return 0;
}
std::map<std::string, struct stat> dirs;
res = hfs->getdir(path, &dirs);
if (res == -2) {
res = cfs->getdir(path, &dirs);
}
if (res == -1) {
return -errno;
}
filler(buf, ".", nullptr, 0);
filler(buf, "..", nullptr, 0);
for (auto &d : dirs) {
filler(buf, d.first.c_str(), &d.second, 0);
}
return 0;
}
static int hfs_open(const char *path, struct fuse_file_info *fi) {
debug_print("open %s\n", path);
if (ignoredPath(path)) {
return -ENOENT;
}
if ((fi->flags & (O_WRONLY | O_RDWR)) != 0) {
errno = EACCES;
return -1;
}
int fd;
fd = hfs->open(path, fi->flags);
if (fd == -2) {
fd = cfs->open(path, fi->flags);
}
if (fd == -1) {
return -errno;
}
fi->fh = static_cast<uint64_t>(fd);
return 0;
}
static int hfs_release(const char *path, struct fuse_file_info *fi) {
(void) path;
close(static_cast<int>(fi->fh));
return 0;
}
static int hfs_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi) {
debug_print("read %s\n", path);
int res;
(void) path;
res = static_cast<int>(pread(static_cast<int>(fi->fh), buf, size, offset));
if (res == -1)
res = -errno;
return res;
}
int hfs_main(fuse_args args, HashFS *hashfs, CacheFS *cachedFS) {
hfs = hashfs;
cfs = cachedFS;
umask(0);
fuse_operations hfs_operations{};
hfs_operations.getattr = hfs_getattr;
hfs_operations.readlink = hfs_readlink;
hfs_operations.readdir = hfs_readdir;
hfs_operations.open = hfs_open;
hfs_operations.read = hfs_read;
hfs_operations.release = hfs_release;
return fuse_main(args.argc, args.argv, &hfs_operations, nullptr);
}
| 23.592105 | 113 | 0.560234 | apardyl |
2a1cd6d8c00eae8458bd896922ab1595262bf9d6 | 6,012 | cpp | C++ | src/libawkward/typedbuilder/IndexedOptionArrayBuilder.cpp | ioanaif/awkward-1.0 | 22501ba218646dc24dc515c4394eb22f126d340d | [
"BSD-3-Clause"
] | null | null | null | src/libawkward/typedbuilder/IndexedOptionArrayBuilder.cpp | ioanaif/awkward-1.0 | 22501ba218646dc24dc515c4394eb22f126d340d | [
"BSD-3-Clause"
] | null | null | null | src/libawkward/typedbuilder/IndexedOptionArrayBuilder.cpp | ioanaif/awkward-1.0 | 22501ba218646dc24dc515c4394eb22f126d340d | [
"BSD-3-Clause"
] | null | null | null | // BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
#define FILENAME(line) FILENAME_FOR_EXCEPTIONS("src/libawkward/builder/IndexedOptionArrayBuilder.cpp", line)
#include "awkward/typedbuilder/IndexedOptionArrayBuilder.h"
#include "awkward/typedbuilder/TypedArrayBuilder.h"
#include "awkward/array/IndexedArray.h"
namespace awkward {
///
IndexedOptionArrayBuilder::IndexedOptionArrayBuilder(const IndexedOptionFormPtr& form,
const std::string attribute,
const std::string partition)
: form_(form),
form_key_(!form.get()->form_key() ?
std::make_shared<std::string>(std::string("node-id")
+ std::to_string(TypedArrayBuilder::next_id()))
: form.get()->form_key()),
attribute_(attribute),
partition_(partition),
content_(TypedArrayBuilder::formBuilderFromA(form.get()->content())) {
vm_output_data_ = std::string("part")
.append(partition_).append("-")
.append(*form_key_).append("-")
.append(attribute_);
vm_func_name_ = std::string(*form_key_).append("-").append(attribute_);
vm_func_type_ = content_.get()->vm_func_type();
vm_output_ = std::string("output ")
.append(vm_output_data_)
.append(" ")
.append(index_form_to_name(form_.get()->index()))
.append("\n")
.append(content_.get()->vm_output());
vm_func_.append(content_.get()->vm_func())
.append(": ").append(vm_func_name()).append("\n")
.append("dup ").append(std::to_string(static_cast<utype>(state::null)))
.append(" = if").append("\n")
.append("drop\n")
.append("variable null -1 null !").append("\n")
.append("null @ ")
.append(vm_output_data_).append(" <- stack").append("\n")
.append("exit\n")
.append("else\n")
.append("variable index 1 index +!").append("\n")
.append("index @ 1- ")
.append(vm_output_data_).append(" <- stack").append("\n")
.append(content_.get()->vm_func_name()).append("\n")
.append("then\n")
.append(";").append("\n");
vm_data_from_stack_ = std::string(content_.get()->vm_from_stack())
.append("0 ").append(vm_output_data_).append(" <- stack").append("\n");
vm_error_ = content_.get()->vm_error();
validate();
}
void
IndexedOptionArrayBuilder::validate() const {
if (form_.get()->parameter_equals("__array__", "\"categorical\"")) {
throw std::invalid_argument(
std::string("categorical form of a ") + classname()
+ std::string(" is not supported yet ")
+ FILENAME(__LINE__));
}
}
const std::string
IndexedOptionArrayBuilder::classname() const {
return "IndexedOptionArrayBuilder";
}
const ContentPtr
IndexedOptionArrayBuilder::snapshot(const ForthOutputBufferMap& outputs) const {
auto search = outputs.find(vm_output_data_);
if (search != outputs.end()) {
switch (form_.get()->index()) {
// case Index::Form::i8:
case Index::Form::i32:
return std::make_shared<IndexedOptionArray32>(
Identities::none(),
form_.get()->parameters(),
Index32(std::static_pointer_cast<int32_t>(search->second.get()->ptr()),
1,
search->second.get()->len() - 1,
kernel::lib::cpu),
content_.get()->snapshot(outputs));
case Index::Form::i64:
return std::make_shared<IndexedOptionArray64>(
Identities::none(),
form_.get()->parameters(),
Index64(std::static_pointer_cast<int64_t>(search->second.get()->ptr()),
1,
search->second.get()->len() - 1,
kernel::lib::cpu),
content_.get()->snapshot(outputs));
default:
break;
};
}
throw std::invalid_argument(
std::string("Snapshot of a ") + classname()
+ std::string(" needs an index ")
+ FILENAME(__LINE__));
}
const FormPtr
IndexedOptionArrayBuilder::form() const {
return std::static_pointer_cast<Form>(form_);
}
const std::string
IndexedOptionArrayBuilder::vm_output() const {
return vm_output_;
}
const std::string
IndexedOptionArrayBuilder::vm_output_data() const {
return vm_output_data_;
}
const std::string
IndexedOptionArrayBuilder::vm_func() const {
return vm_func_;
}
const std::string
IndexedOptionArrayBuilder::vm_func_name() const {
return vm_func_name_;
}
const std::string
IndexedOptionArrayBuilder::vm_func_type() const {
return vm_func_type_;
}
const std::string
IndexedOptionArrayBuilder::vm_from_stack() const {
return vm_data_from_stack_;
}
const std::string
IndexedOptionArrayBuilder::vm_error() const {
return vm_error_;
}
void
IndexedOptionArrayBuilder::boolean(bool x, TypedArrayBuilder* builder) {
content_.get()->boolean(x, builder);
}
void
IndexedOptionArrayBuilder::int64(int64_t x, TypedArrayBuilder* builder) {
content_.get()->int64(x, builder);
}
void
IndexedOptionArrayBuilder::float64(double x, TypedArrayBuilder* builder) {
content_.get()->float64(x, builder);
}
void
IndexedOptionArrayBuilder::complex(std::complex<double> x, TypedArrayBuilder* builder) {
content_.get()->complex(x, builder);
}
void
IndexedOptionArrayBuilder::bytestring(const std::string& x, TypedArrayBuilder* builder) {
content_.get()->bytestring(x, builder);
}
void
IndexedOptionArrayBuilder::string(const std::string& x, TypedArrayBuilder* builder) {
content_.get()->string(x, builder);
}
void
IndexedOptionArrayBuilder::begin_list(TypedArrayBuilder* builder) {
content_.get()->begin_list(builder);
}
void
IndexedOptionArrayBuilder::end_list(TypedArrayBuilder* builder) {
content_.get()->end_list(builder);
}
}
| 31.150259 | 108 | 0.626414 | ioanaif |
2a1d3fd812f5cbf3af8e947032ee73c06d113109 | 921 | hpp | C++ | include/Module/Source/User/Source_user_binary.hpp | FredrikBlomgren/aff3ct | fa616bd923b2dcf03a4cf119cceca51cf810d483 | [
"MIT"
] | 315 | 2016-06-21T13:32:14.000Z | 2022-03-28T09:33:59.000Z | include/Module/Source/User/Source_user_binary.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 153 | 2017-01-17T03:51:06.000Z | 2022-03-24T15:39:26.000Z | include/Module/Source/User/Source_user_binary.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 119 | 2017-01-04T14:31:58.000Z | 2022-03-21T08:34:16.000Z | #ifndef SOURCE_USER_BINARY_HPP_
#define SOURCE_USER_BINARY_HPP_
#include <string>
#include <vector>
#include <fstream>
#include <memory>
#include "Module/Source/Source.hpp"
namespace aff3ct
{
namespace module
{
template <typename B = int32_t>
class Source_user_binary : public Source<B>
{
private:
std::ifstream source_file;
const bool auto_reset;
const bool fifo_mode;
bool done;
size_t n_left;
std::vector<char> memblk;
std::vector<B> left_bits; // to store bits that are left by last call (n_left & n_completing)
public:
Source_user_binary(const int K,
const std::string &filename,
const bool auto_reset = true,
const bool fifo_mode = false);
virtual ~Source_user_binary() = default;
virtual bool is_done() const;
virtual void reset();
protected:
void _generate(B *U_K, const size_t frame_id);
};
}
}
#endif /* SOURCE_USER_BINARY_HPP_ */
| 20.466667 | 94 | 0.703583 | FredrikBlomgren |
2a21d57b9949a9f12817b8dbc9977955ced6201b | 7,174 | cpp | C++ | Visual Mercutio/zBaseLib/PSS_PLFNAutoNumbered.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 1 | 2022-01-31T06:24:24.000Z | 2022-01-31T06:24:24.000Z | Visual Mercutio/zBaseLib/PSS_PLFNAutoNumbered.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-04-11T15:50:42.000Z | 2021-06-05T08:23:04.000Z | Visual Mercutio/zBaseLib/PSS_PLFNAutoNumbered.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-01-08T00:55:18.000Z | 2022-01-31T06:24:18.000Z | /****************************************************************************
* ==> PSS_PLFNAutoNumbered ------------------------------------------------*
****************************************************************************
* Description : Provides an financial plan auto-numbered object *
* Developer : Processsoft *
****************************************************************************/
#include <StdAfx.h>
#include "PSS_PLFNAutoNumbered.h"
// processsoft
#include "PSS_Document.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_PLFNAutoNumbered, PSS_PlanFinObject, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_PLFNAutoNumbered
//---------------------------------------------------------------------------
PSS_PLFNAutoNumbered::PSS_PLFNAutoNumbered() :
PSS_PlanFinObject(),
m_pObject(NULL),
m_TextOffset(20),
m_SectionNumber(0),
m_Level(0),
m_AutoCalculate(TRUE)
{}
//---------------------------------------------------------------------------
PSS_PLFNAutoNumbered::PSS_PLFNAutoNumbered(const PSS_PLFNAutoNumbered& other) :
PSS_PlanFinObject(),
m_pObject(NULL),
m_TextOffset(20),
m_SectionNumber(0),
m_Level(0),
m_AutoCalculate(TRUE)
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_PLFNAutoNumbered::~PSS_PLFNAutoNumbered()
{
if (m_pObject)
delete m_pObject;
}
//---------------------------------------------------------------------------
const PSS_PLFNAutoNumbered& PSS_PLFNAutoNumbered::operator = (const PSS_PLFNAutoNumbered& other)
{
PSS_PlanFinObject::operator = ((inherited&)other);
m_TextLevel = other.m_TextLevel;
m_pObject = other.m_pObject->Clone();
m_TextOffset = other.m_TextOffset;
m_SectionNumber = other.m_SectionNumber;
m_Level = other.m_Level;
m_AutoCalculate = other.m_AutoCalculate;
return *this;
}
//---------------------------------------------------------------------------
const PSS_PLFNAutoNumbered& PSS_PLFNAutoNumbered::operator = (const PSS_PLFNAutoNumbered* pOther)
{
PSS_PlanFinObject::operator = ((inherited*)pOther);
if (!pOther)
{
m_pObject = NULL;
m_TextOffset = 20;
m_SectionNumber = 0;
m_Level = 0;
m_AutoCalculate = TRUE;
}
else
{
m_TextLevel = pOther->m_TextLevel;
m_pObject = pOther->m_pObject->Clone();
m_TextOffset = pOther->m_TextOffset;
m_SectionNumber = pOther->m_SectionNumber;
m_Level = pOther->m_Level;
m_AutoCalculate = pOther->m_AutoCalculate;
}
return *this;
}
//---------------------------------------------------------------------------
PSS_PlanFinObject* PSS_PLFNAutoNumbered::Clone() const
{
return new PSS_PLFNAutoNumbered(*this);
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::CopyObject(PSS_PlanFinObject* pSrc)
{
operator = (dynamic_cast<PSS_PLFNAutoNumbered*>(pSrc));
}
//---------------------------------------------------------------------------
CString PSS_PLFNAutoNumbered::GetFormattedObject()
{
if (m_pObject)
return m_pObject->GetFormattedObject();
return "";
}
//---------------------------------------------------------------------------
BOOL PSS_PLFNAutoNumbered::ConvertFormattedObject(const CString& value, BOOL locateFormat, BOOL emptyWhenZero)
{
if (m_pObject)
return m_pObject->ConvertFormattedObject(value, locateFormat, emptyWhenZero);
// hasn't changed
return FALSE;
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::DrawObject(CDC* pDC, PSS_View* pView)
{
DrawFillObject(pDC, pView);
m_TextLevel.DrawObject(pDC, pView);
// must draw the object
if (m_pObject)
m_pObject->DrawObject(pDC, pView);
PSS_PlanFinObject::DrawObject(pDC, pView);
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::SizePositionHasChanged()
{
if (!m_pObject)
return;
// call the basic fonction
PSS_PlanFinObject::SizePositionHasChanged();
// recalculate all element positions.
GetTextLevel().SetClientRect(m_ObjectRect);
m_pObject->SetClientRect(m_ObjectRect);
m_pObject->GetClientRect().left += GetTextOffset();
// if automatic recalculation of section
if (GetAutoCalculate())
{
CWnd* pWnd = ::AfxGetMainWnd();
if (pWnd)
pWnd->SendMessageToDescendants(UM_REBUILDAUTOMATICNUMBER);
}
}
//---------------------------------------------------------------------------
CString PSS_PLFNAutoNumbered::GetUnformattedObject()
{
if (m_pObject)
return m_pObject->GetUnformattedObject();
return "";
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::SetStyle(PSS_Style::Handle hStyle)
{
if (m_pObject)
m_pObject->SetStyle(hStyle);
}
//---------------------------------------------------------------------------
const COLORREF PSS_PLFNAutoNumbered::GetFillColor() const
{
if (m_pObject)
return m_pObject->GetFillColor();
return 0;
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::SetFillColor(COLORREF value)
{
if (m_pObject)
m_pObject->SetFillColor(value);
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::Serialize(CArchive& ar)
{
PSS_PlanFinObject::Serialize(ar);
if (ar.IsStoring())
{
// write the elements
ar << WORD(m_TextOffset);
ar << WORD(m_AutoCalculate);
ar << WORD(m_SectionNumber);
ar << WORD(m_Level);
// serialize the defined object
ar << m_pObject;
}
else
{
// read the elements
WORD wValue;
ar >> wValue;
m_TextOffset = wValue;
ar >> wValue;
m_AutoCalculate = wValue;
ar >> wValue;
m_SectionNumber = wValue;
ar >> wValue;
m_Level = wValue;
// serialize the defined object
ar >> m_pObject;
}
// should serialize the static member, serialize the Text Level
m_TextLevel.Serialize(ar);
}
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNAutoNumbered::AssertValid() const
{
CObject::AssertValid();
}
#endif
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNAutoNumbered::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
}
#endif
//---------------------------------------------------------------------------
| 30.922414 | 110 | 0.476164 | Jeanmilost |
2a24a43d5020c4e757efdc26e46e319dcae98a08 | 1,584 | cpp | C++ | sources/UseCases/Multithreading/f1/function1.cpp | alrinach/ARISS | b84ace8412ebb037d7c1690ee488c111aef57b64 | [
"CECILL-B",
"MIT"
] | null | null | null | sources/UseCases/Multithreading/f1/function1.cpp | alrinach/ARISS | b84ace8412ebb037d7c1690ee488c111aef57b64 | [
"CECILL-B",
"MIT"
] | null | null | null | sources/UseCases/Multithreading/f1/function1.cpp | alrinach/ARISS | b84ace8412ebb037d7c1690ee488c111aef57b64 | [
"CECILL-B",
"MIT"
] | null | null | null | #include "CBasefunction.h"
#include <iostream>
#include <stdlib.h>
#define SEMKEY_1 50000
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * fonction_thread(void * arg) {
long numero = (long) arg;
std::cout << "numéro vaut : " << numero << std::endl;
//usleep(random());
std::cout << "Before while " << std::endl;
while (1) {
fprintf(stderr, "[%d] demande le mutexn\n", numero);
if (numero != 2)
while (pthread_mutex_trylock(& mutex) != 0)
;
else
pthread_mutex_lock(& mutex);
fprintf(stderr, " [%d] tient le mutexn\n", numero);
sleep(1);
fprintf(stderr, "[%d] lache le mutexn\n", numero);
pthread_mutex_unlock(& mutex);
usleep(100);
}
std::cout << "exit thread " << std::endl;
return NULL;
}
#define NB_THREADS 5
int main(int argc, char *argv[]) {
int redemarrage = atoi(argv[7]);
int position = atoi(argv[6]);
GUI_ARINC_partition("Partition1", position, redemarrage);
long i;
pthread_t thread[NB_THREADS];
pthread_mutex_lock(& mutex);
for (i = 0; i < NB_THREADS; i++) {
long argument = i + 1;
std::cout << "argument vaut : " << argument << std::endl;
pthread_create(& thread[i], NULL, fonction_thread, (void *) argument);
usleep(10000);
}
sleep(1);
fprintf(stderr, "Liberation initiale du mutex\n");
pthread_mutex_unlock(& mutex);
for (i = 0; i < NB_THREADS; i++)
pthread_join(thread[i], NULL);
return EXIT_SUCCESS;
}
| 24.75 | 78 | 0.581439 | alrinach |
2a26d9cdad17739ee5bd7f530447d991615bbd4e | 1,243 | cpp | C++ | source/Game/Entities/Aircraft.cpp | zhiayang/controller_game | a0800f991067e81850d44d7298d80b8772c5384f | [
"Apache-2.0"
] | 1 | 2021-02-07T08:42:12.000Z | 2021-02-07T08:42:12.000Z | source/Game/Entities/Aircraft.cpp | zhiayang/controller_game | a0800f991067e81850d44d7298d80b8772c5384f | [
"Apache-2.0"
] | null | null | null | source/Game/Entities/Aircraft.cpp | zhiayang/controller_game | a0800f991067e81850d44d7298d80b8772c5384f | [
"Apache-2.0"
] | null | null | null | // Aircraft.cpp
// Copyright (c) 2014 - The Foreseeable Future, zhiayang@gmail.com
// Licensed under the Apache License Version 2.0.
#include "Game.h"
#include <random>
#include "Config.h"
#include "Game/Scene.h"
#include "Game/Aircraft.h"
namespace Game
{
Aircraft::Aircraft(Entity* p) : MovingEntity(p), ai(this)
{
}
Aircraft::~Aircraft()
{
}
void Aircraft::Render(SDL::Renderer* r)
{
glPushMatrix();
// move the shape to local origin, then rotate it, then move it back
// prevents the rotation from screwing with position
glTranslated(this->pos().x, this->pos().y, 0);
glRotated(Math::Vector2(this->velocity.x, this->velocity.y).angle(), 0, 0, 1);
glTranslated(-this->pos().x, -this->pos().y, 0);
r->SetColour(this->colour);
r->RenderEqTriangle(Math::Vector2(this->pos().x, this->pos().y), 12);
glPopMatrix();
// render our callsign
r->SetColour(Util::Colour::white());
SDL::Font* f = Util::Font::get("menlo", 8, true);
r->RenderText(this->callsign, f, Math::Vector2(this->pos().x, this->pos().y) + Math::Vector2(3, 3));
// render our children
this->MovingEntity::Render(r);
}
void Aircraft::Update(float dt)
{
this->ai.UpdateAI(dt);
this->MovingEntity::Update(dt);
}
}
| 19.123077 | 102 | 0.652454 | zhiayang |
2a270ca12258cf80c0517bd0c8d8a56ad38daa67 | 382 | ipp | C++ | include/particles/implementation/component/ParticleEmitterSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | 3 | 2021-06-24T10:20:12.000Z | 2021-07-18T14:43:19.000Z | include/particles/implementation/component/ParticleEmitterSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | 2 | 2021-07-22T15:31:03.000Z | 2021-07-28T14:27:28.000Z | include/particles/implementation/component/ParticleEmitterSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | 1 | 2021-07-22T15:24:24.000Z | 2021-07-22T15:24:24.000Z | /**
* @file
* @author University of Warwick
* @version 1.0
*
* @section LICENSE
*
* @section DESCRIPTION
*
* Description
*
* Contains header level definitions for the ParticleEmitterSimple Class
*
*/
#ifndef CUPCFD_PARTICLES_PARTICLE_EMITTER_SIMPLE_IPP_H
#define CUPCFD_PARTICLES_PARTICLE_EMITTER_SIMPLE_IPP_H
namespace cupcfd
{
namespace particles
{
}
}
#endif
| 13.642857 | 72 | 0.746073 | thorbenlouw |
2a27b02e1482815b9058d92ded33c79b7818caa3 | 2,947 | cpp | C++ | oshgui/Controls/RadioButton.cpp | zhuhuibeishadiao/osh_sdk | 087df8876443c36254b6de127b732e74ddf77167 | [
"MIT"
] | 6 | 2018-10-31T12:53:37.000Z | 2019-01-12T23:12:43.000Z | OSHGui/Controls/RadioButton.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 4 | 2018-10-31T16:39:43.000Z | 2019-01-14T07:30:24.000Z | OSHGui/Controls/RadioButton.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 2 | 2021-01-20T21:17:35.000Z | 2022-03-12T08:18:43.000Z | /*
* OldSchoolHack GUI
*
* by KN4CK3R https://www.oldschoolhack.me/
*
* See license in OSHGui.hpp
*/
#include "RadioButton.hpp"
#include "Label.hpp"
#include "../Misc/Exceptions.hpp"
namespace OSHGui
{
//---------------------------------------------------------------------------
//Constructor
//---------------------------------------------------------------------------
RadioButton::RadioButton()
{
type_ = ControlType::RadioButton;
}
//---------------------------------------------------------------------------
//Getter/Setter
//---------------------------------------------------------------------------
void RadioButton::SetChecked(bool checked)
{
if (checked_ != checked)
{
if (GetParent() != nullptr)
{
//uncheck other radiobuttons
for (auto &control : GetParent()->GetControls())
{
if (control->GetType() == ControlType::RadioButton)
{
static_cast<RadioButton*>(control)->SetCheckedInternal(false);
}
}
SetCheckedInternal(checked);
}
}
}
//---------------------------------------------------------------------------
void RadioButton::SetCheckedInternal(bool checked)
{
if (checked_ != checked)
{
checked_ = checked;
checkedChangedEvent_.Invoke(this);
Invalidate();
}
}
//---------------------------------------------------------------------------
void RadioButton::PopulateGeometry()
{
using namespace Drawing;
Graphics g(*geometry_);
g.FillRectangle(GetBackColor(), RectangleF(PointF(0, 0), SizeF(DefaultCheckBoxSize, DefaultCheckBoxSize)));
g.FillRectangleGradient(ColorRectangle(Color::White(), Color::White() - Color::FromARGB(0, 137, 137, 137)), RectangleF(PointF(1, 1), SizeF(15, 15)));
g.FillRectangleGradient(ColorRectangle(GetBackColor(), GetBackColor() + Color::FromARGB(0, 55, 55, 55)), RectangleF(PointF(2, 2), SizeF(13, 13)));
if (checked_)
{
g.FillRectangle(Color::White() - Color::FromARGB(0, 128, 128, 128), RectangleF(PointF(5, 7), SizeF(7, 3)));
const ColorRectangle colors(Color::White(), Color::White() - Color::FromARGB(0, 137, 137, 137));
g.FillRectangleGradient(colors, RectangleF(PointF(7, 5), SizeF(3, 7)));
g.FillRectangleGradient(colors, RectangleF(PointF(6, 6), SizeF(5, 5)));
}
}
//---------------------------------------------------------------------------
//Event-Handling
//---------------------------------------------------------------------------
void RadioButton::OnMouseClick(const MouseMessage &mouse)
{
Control::OnMouseClick(mouse);
SetChecked(true);
}
//---------------------------------------------------------------------------
bool RadioButton::OnKeyUp(const KeyboardMessage &keyboard)
{
if (!Control::OnKeyUp(keyboard))
{
if (keyboard.GetKeyCode() == Key::Space)
{
SetChecked(true);
clickEvent_.Invoke(this);
}
}
return true;
}
//---------------------------------------------------------------------------
} | 28.892157 | 151 | 0.491686 | zhuhuibeishadiao |
2a28eca7795b2d1148dcae007a3dfd6f2fb9b78b | 625 | cc | C++ | caffe2/core/event_test.cc | huiqun2001/caffe2 | 97209961b675c8bea3831450ba46c9e8b7bad3de | [
"MIT"
] | null | null | null | caffe2/core/event_test.cc | huiqun2001/caffe2 | 97209961b675c8bea3831450ba46c9e8b7bad3de | [
"MIT"
] | null | null | null | caffe2/core/event_test.cc | huiqun2001/caffe2 | 97209961b675c8bea3831450ba46c9e8b7bad3de | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "caffe2/core/context.h"
#include "caffe2/core/event.h"
namespace caffe2 {
// For the CPU event test, we only test if these functions are properly
// registered. Nothing special needs to be checked since CPU events are no-ops.
TEST(EventCPUTest, EventBasics) {
DeviceOption device_option;
device_option.set_device_type(CPU);
Event event(device_option);
CPUContext context;
// Calling from Context
context.WaitEvent(event);
context.Record(&event);
// Calling from Event
event.Finish();
event.Record(CPU, &context);
event.Wait(CPU, &context);
}
} // namespace caffe2
| 24.038462 | 79 | 0.736 | huiqun2001 |
2a29354894a525a0b0963bffe5958b6445acdf82 | 10,172 | cpp | C++ | PinGUI/GUI_Elements/ComboBox.cpp | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 60 | 2017-04-16T15:31:13.000Z | 2021-12-22T19:01:07.000Z | PinGUI/GUI_Elements/ComboBox.cpp | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 4 | 2017-02-14T19:05:21.000Z | 2020-07-16T10:04:27.000Z | PinGUI/GUI_Elements/ComboBox.cpp | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 20 | 2017-02-15T19:07:17.000Z | 2021-12-22T19:01:07.000Z | /**
PinGUI
Copyright (c) 2017 Lubomir Barantal <l.pinsius@gmail.com>
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 "ComboBox.h"
ComboBox::ComboBox(GUIPos x,
GUIPos y,
std::vector<std::string> itemList,
clipboardData data,
std::vector<std::shared_ptr<GUI_Element>>* ELEMENTS,
int maxNumOfItems,
bool* update):
_maxNumberOfItems(maxNumOfItems),
_needUpdate(update),
_scroller(nullptr),
_mainItem(nullptr),
_ELEMENTS(ELEMENTS),
_clickable(true),
_rollbackVect(0,0)
{
_position.x = x;
_position.y = y;
_data.texter = data.texter;
_maxSize = 0;
findLongestWord(itemList);
initMainSprites(x,y,data);
for (std::size_t i = 0; i < itemList.size(); i++)
addItem(itemList[i]);
initScroller();
}
ComboBox::ComboBox(GUIPos x,
GUIPos y,
std::vector<std::string> itemList,
clipboardData data,
std::vector<std::shared_ptr<GUI_Element>>* ELEMENTS,
int maxNumOfItems,
bool* update,
int maxSize):
_maxNumberOfItems(maxNumOfItems),
_needUpdate(update),
_scroller(nullptr),
_mainItem(nullptr),
_ELEMENTS(ELEMENTS),
_clickable(true),
_rollbackVect(0,0)
{
_position.x = x;
_position.y = y;
_data.texter = data.texter;
_maxSize = maxSize;
initMainSprites(x,y,data);
for (std::size_t i = 0; i < itemList.size(); i++)
addItem(itemList[i]);
initScroller();
}
ComboBox::~ComboBox()
{
_ITEMS.clear();
}
void ComboBox::initMainSprites(const GUIPos& x, const GUIPos& y, clipboardData& data){
SDL_Surface* tmpSurface;
int tmp_width, tmp_height;
fakeInputText(tmp_width,tmp_height,data);
addCollider(x,y,tmp_width,tmp_height);
_offsetCollider = *(getCollider());
_textStorage = std::make_shared<TextStorage>(data.texter);
initText();
//Now need to rearrange the width by adding the width of scroller
tmp_width += PINGUI_WINDOW_DEFAULT_SCROLLER_W-BORDER_LINE;
tmpSurface = SheetManager::createRectangle(tmp_width,tmp_height,BOARD,BORDER_LINE);
SheetManager::putOnSurface(tmpSurface,COMBO_BOX_ARROW,tmp_width - POSITION_OF_COMBO_ARROW_X,(tmp_height/2)-(PINGUI_COMBO_BOX_ARROW_H/2));
addSprite(x,y,tmpSurface);
deleteCollider(0);
addCollider(x,y,tmp_width,tmp_height);
SDL_FreeSurface(tmpSurface);
}
void ComboBox::initScroller(){
PinGUI::Vector2<GUIPos> tmpPos(_offsetCollider.x + _offsetCollider.w - BORDER_LINE,
_offsetCollider.y - (_maxNumberOfItems * (_offsetCollider.h-BORDER_LINE) ));
int height = _maxNumberOfItems * (_offsetCollider.h-BORDER_LINE);
_scroller = std::make_shared<VerticalScroller>(tmpPos,height,_needUpdate,_ELEMENTS);
//Now init cropRect and add function that performs it
_cropRect.rect.x = getSprite()->getX();
int num;
if (_ITEMS.size()>=_maxNumberOfItems)
num = _maxNumberOfItems;
else
num = int(_ITEMS.size());
_cropRect.rect.w = _offsetCollider.w;
_cropRect.rect.h = num * _offsetCollider.h;
_cropRect.rect.y = _position.y - _cropRect.rect.h;
_cropRect.realRect = _cropRect.rect;
//Set clFunction
PinGUI::scrollFuncPointer f;
f._function = boost::bind(&ComboBox::updateCropArea,this,_1);
_scroller->setCamRollFunction(f);
_scroller->setNetworking(true);
_ELEMENTS->push_back(_scroller);
_scroller->createArrows(_ELEMENTS);
_scroller->hideScroller();
}
void ComboBox::updateCropArea(PinGUI::Vector2<GUIPos> vect){
_rollbackVect += vect;
for (std::size_t i = 0; i < _ITEMS.size(); i++){
_ITEMS[i]->moveElement(vect);
_ITEMS[i]->cropElement(_cropRect.rect);
}
*_needUpdate = true;
}
std::vector<std::string> ComboBox::getStringVector(){
std::vector<std::string> tmp;
for (std::size_t i = 0; i < _ITEMS.size(); i++)
tmp.push_back(_ITEMS[i]->getStorage()->getText()->getString());
return tmp;
}
void ComboBox::findLongestWord(std::vector<std::string>& itemList){
for (std::size_t i = 0; i < itemList.size(); i++){
if (itemList[i].size() > _maxSize)
_maxSize = int(itemList[i].size());
}
}
void ComboBox::addItem(std::string name){
PinGUI::Vector2<GUIPos> tmpPos (_position.x, getPosOfNextItem());
PinGUI::basicPointer f(boost::bind(&ComboBox::uploadContent,this));
auto ptr = std::make_shared<ComboBoxItem>(tmpPos,name,&_mainItem,f,_maxSize,_data);
_ITEMS.push_back(ptr);
_ELEMENTS->push_back(_ITEMS.back());
_ITEMS.back()->setOption(int(_ITEMS.size()));
if (!_clickable)
_ITEMS.back()->setCollidable(false);
*_needUpdate = true;
}
void ComboBox::deleteItem(std::string name){
for (std::size_t i = 0; i < _ITEMS.size(); i++){
if (_ITEMS[i]->getStorage()->getText()->getString()==name){
_ITEMS[i]->setExist(false);
_ITEMS.erase(_ITEMS.begin() + i);
}
}
reMoveTabs();
}
void ComboBox::clearComboBox(){
for (std::size_t i = 0; i < _ITEMS.size(); i++){
_ITEMS[i]->setExist(false);
}
_ITEMS.clear();
}
void ComboBox::reMoveTabs(){
PinGUI::Vector2<GUIPos> tmp(0.0f,float(_offsetCollider.h-BORDER_LINE));
for (std::size_t i = 0; i < _ITEMS.size(); i++){
_ITEMS[i]->moveElement(tmp);
}
*_needUpdate = true;
}
GUIPos ComboBox::getPosOfNextItem(){
return (_position.y - (getSprite()->getH() * (_ITEMS.size()+1)) + (_ITEMS.size()+1));
}
void ComboBox::moveElement(const PinGUI::Vector2<GUIPos>& vect){
ClipBoard::moveElement(vect);
_scroller->moveElement(vect);
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->moveElement(vect);
moveCollider(_offsetCollider,vect);
moveCollider(_cropRect.realRect,vect);
moveCollider(_cropRect.rect,vect);
}
void ComboBox::onClick(){
if (_cropRect.rect != _cropRect.realRect){
ErrorManager::infoLog("PinGUI error 2","Combobox list cannot be loaded due to cropped area. Move it to normal area");
return;
}
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setShow(true);
PinGUI::basicPointer tmpF;
tmpF._function = boost::bind(&ComboBox::hideContent,this);
PinGUI::Input_Manager::setCallbackFunction(tmpF);
_cropRect.rect.x = _offsetCollider.x;
_cropRect.rect.w = _offsetCollider.w;
_cropRect.rect.h = _maxNumberOfItems * (_offsetCollider.h-BORDER_LINE);
if (_ITEMS.size()>_maxNumberOfItems){
_cropRect.rect.w += PINGUI_WINDOW_DEFAULT_SCROLLER_W-BORDER_LINE;
_cropRect.rect.h = _maxNumberOfItems * (_offsetCollider.h-BORDER_LINE);
} else {
_cropRect.rect.h = int(_ITEMS.size()) * (_offsetCollider.h-BORDER_LINE);
}
_cropRect.rect.y = _offsetCollider.y - _cropRect.rect.h;
_cropRect.realRect = _cropRect.rect;
PinGUI::Input_Manager::setTarget(true,_cropRect.rect);
if (_maxNumberOfItems< _ITEMS.size()){
loadScroller();
_scroller->setShow(true);
PinGUI::basicPointer f;
f._function = boost::bind(&Scroller::checkForWheelMove,_scroller);
PinGUI::Input_Manager::setTMPWheeledInfo(_scroller->getSprite(1),_needUpdate,f);
}
updateCropArea(_rollbackVect);
}
void ComboBox::loadScroller(){
_scroller->loadScrollMover(_cropRect.rect.h,(int(_ITEMS.size()) * (_offsetCollider.h-1)));
}
bool ComboBox::listenForClick(manip_Element manipulatingElement){
return GUI_Element::listenForClick(manipulatingElement);
}
void ComboBox::hideContent(){
_rollbackVect.y *= -1;
updateCropArea(_rollbackVect);
_rollbackVect.clearVector();
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setShow(false);
if (_maxNumberOfItems< _ITEMS.size()){
_scroller->hideScroller();
PinGUI::Input_Manager::cancelTMPWheeledInfo();
PinGUI::Input_Manager::setAllowWheel(false);
}
}
void ComboBox::uploadContent(){
setClipboardText(_mainItem->getStorage()->getText()->getString(),_offsetCollider);
_func.exec(_mainItem->getOption());
hideContent();
}
void ComboBox::setShow(bool state){
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setShow(state);
if (_maxNumberOfItems< _ITEMS.size()){
loadScroller();
}
}
elementType ComboBox::getElementType(){
return COMBOBOX;
}
void ComboBox::cropElement(PinGUI::Rect& rect){
ClipBoard::cropElement(rect);
CropManager::cropRect(rect,_cropRect);
}
void ComboBox::setFunc(PinGUI::comboBoxFuncPointer func){
_func = func;
}
void ComboBox::setUnclickable(){
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setCollidable(false);
_clickable = false;
}
| 26.1491 | 142 | 0.630161 | Pinsius |
2a2df2581625dc70da8397d83fcb7692a5abd9db | 1,061 | cpp | C++ | chapter_06/Emirp.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | chapter_06/Emirp.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | 31 | 2021-05-14T03:37:24.000Z | 2022-03-13T17:38:32.000Z | chapter_06/Emirp.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | // Exercise 6.23 - Emirp
#include <iostream>
#include <iomanip>
bool isPrime(int number)
{
for (int divisor = 2; divisor <= number / 2; divisor++)
{
if (number % divisor == 0)
{
return false;
}
}
return true;
}
int reverseNumber(int extract)
{
int reverseNumber = 0;
while (extract > 0)
{
reverseNumber = (reverseNumber * 10) + (extract % 10);
extract /= 10;
}
return reverseNumber;
}
bool hasEmirp(int number)
{
if (isPrime(reverseNumber(number)))
{
return true;
}
return false;
}
void displayEmirp(int displayAmount, int amountPerLine)
{
int count = 2, displayed = 1;
while (displayed <= displayAmount)
{
if (isPrime(count) && hasEmirp(count))
{
std::cout << std::setw(6) << std::right << count;
if (displayed % amountPerLine == 0)
std::cout << std::endl;
displayed++;
}
count++;
}
}
int main()
{
displayEmirp(100, 10);
return 0;
} | 17.683333 | 62 | 0.528746 | Kevin-Oudai |
2a3085cc6a7a51b8ae06a24d22cc51647488b9aa | 1,877 | cpp | C++ | src/texture/Texture.cpp | Owlinated/Chess | 0a4e7d02bca1af6423ed88ed780b8fb0cae1ccb8 | [
"MIT"
] | 1 | 2022-01-05T18:37:47.000Z | 2022-01-05T18:37:47.000Z | src/texture/Texture.cpp | flostellbrink/Chess | 0a4e7d02bca1af6423ed88ed780b8fb0cae1ccb8 | [
"MIT"
] | null | null | null | src/texture/Texture.cpp | flostellbrink/Chess | 0a4e7d02bca1af6423ed88ed780b8fb0cae1ccb8 | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include "Texture.h"
#include <src/texture/Image.h>
Texture::Texture() : texture_handle_()
{
}
Texture::Texture(const std::string& texturePath, const GLenum target, const GLenum repeatMode)
{
texture_handle_ = 0;
glGenTextures(1, &texture_handle_);
glBindTexture(target, texture_handle_);
if (target == GL_TEXTURE_CUBE_MAP)
{
for (GLuint i = 0; i < 6; i++)
{
auto image = Image(texturePath + std::to_string(i) + ".png");
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0,
GL_RGBA,
image.GetWidth(),
image.GetHeight(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image.GetData());
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
auto image = Image(texturePath);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
image.GetWidth(),
image.GetHeight(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image.GetData());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeatMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeatMode);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
void Texture::Bind(const GLenum target, const unsigned int textureNum) const
{
glActiveTexture(GL_TEXTURE0 + textureNum);
glBindTexture(target, texture_handle_);
}
Texture::~Texture()
{
glDeleteTextures(1, &texture_handle_);
}
| 27.602941 | 94 | 0.631327 | Owlinated |
2a354182883b2e7e1caaf1490d9b37b87a3becba | 564 | cpp | C++ | 450/Utkarsh/array/firstAndLastX.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | 1 | 2021-07-27T03:54:41.000Z | 2021-07-27T03:54:41.000Z | 450/Utkarsh/array/firstAndLastX.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | null | null | null | 450/Utkarsh/array/firstAndLastX.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | null | null | null | //https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x/1
#include <bits/stdc++.h>
using namespace std;
void firstAndLastX(int a[], int n, int x)
{
if (binary_search(a, a + n, x) == 0) cout<<"-1";
else cout<< lower_bound(a, a + n, x)-a <<" "<<upper_bound(a, a + n, x)-1-a;
}
int main()
{
int T;
cin >> T;
while(T--)
{
int N, X;
cin >> N >> X;
int arr[N];
for(int i = 0; i < N; i++)
cin >> arr[i];
firstAndLastX(arr, N, X);
cout << endl;
}
return 0;
} | 21.692308 | 79 | 0.498227 | stunnerhash |
2a3723e5f939c1099664bd34f378158ccf76eae6 | 4,623 | cpp | C++ | Core/Contents/Source/PolyGLSLProgram.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | 1 | 2020-08-25T06:30:49.000Z | 2020-08-25T06:30:49.000Z | Core/Contents/Source/PolyGLSLProgram.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | null | null | null | Core/Contents/Source/PolyGLSLProgram.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | null | null | null | /*
Copyright (C) 2011 by Ivan Safrin
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 "PolyGLSLProgram.h"
#include "PolyVector3.h"
#include "PolyVector2.h"
#include "PolyColor.h"
#include "PolyLogger.h"
#ifdef _WINDOWS
#include <windows.h>
#endif
#include "PolyGLHeaders.h"
using std::vector;
#ifdef _WINDOWS
extern PFNGLUSEPROGRAMPROC glUseProgram;
extern PFNGLUNIFORM1IPROC glUniform1i;
extern PFNGLACTIVETEXTUREPROC glActiveTexture;
extern PFNGLCREATESHADERPROC glCreateShader;
extern PFNGLSHADERSOURCEPROC glShaderSource;
extern PFNGLCOMPILESHADERPROC glCompileShader;
extern PFNGLCREATEPROGRAMPROC glCreateProgram;
extern PFNGLATTACHSHADERPROC glAttachShader;
extern PFNGLLINKPROGRAMPROC glLinkProgram;
extern PFNGLDETACHSHADERPROC glDetachShader;
extern PFNGLDELETESHADERPROC glDeleteShader;
extern PFNGLDELETEPROGRAMPROC glDeleteProgram;
#ifndef _MINGW
extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation;
#endif
#endif
using namespace Polycode;
GLSLProgram::GLSLProgram(int type) : Resource(Resource::RESOURCE_PROGRAM) {
this->type = type;
}
GLSLProgram::~GLSLProgram() {
glDeleteShader(program);
}
GLSLProgramParam GLSLProgram::addParam(const String& name, const String& typeString, const String& valueString, bool isAuto, int autoID, int paramType, void *defaultData, void *minData, void *maxData) {
GLSLProgramParam newParam;
newParam.name = name;
newParam.typeString = typeString;
newParam.valueString = valueString;
newParam.paramType = paramType;
newParam.defaultData = defaultData;
newParam.minValue = minData;
newParam.maxValue = maxData;
newParam.isAuto = isAuto;
newParam.autoID = autoID;
params.push_back(newParam);
return newParam;
}
void GLSLProgramParam::createParamData(int *retType, const String& type, const String& value, const String& min, const String& max, void **valueRes, void **minRes, void **maxRes) {
(*valueRes) = NULL;
(*minRes) = NULL;
(*maxRes) = NULL;
if(type == "Number") {
*retType = GLSLProgramParam::PARAM_Number;
Number *val = new Number();
*val = atof(value.c_str());
(*valueRes) = (void*)val;
val = new Number();
*val = atof(min.c_str());
(*minRes) = (void*)val;
val = new Number();
*val = atof(max.c_str());
(*maxRes) = (void*)val;
return;
} else if(type == "Vector2") {
*retType = GLSLProgramParam::PARAM_Vector2;
Vector2 *val = new Vector2();
(*valueRes) = (void*)val;
vector<String> values = value.split(" ");
if(values.size() == 2) {
val->set(atof(values[0].c_str()), atof(values[1].c_str()));
} else {
Logger::log("Error: A Vector2 must have 2 values (%d provided)!\n", values.size());
}
return;
} else if(type == "Vector3") {
*retType = GLSLProgramParam::PARAM_Vector3;
Vector3 *val = new Vector3();
(*valueRes) = (void*)val;
vector<String> values = value.split(" ");
if(values.size() == 3) {
val->set(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()));
} else {
Logger::log("Error: A Vector3 must have 3 values (%d provided)!\n", values.size());
}
return;
} else if(type == "Color") {
*retType = GLSLProgramParam::PARAM_Color;
Color *val = new Color();
(*valueRes) = (void*)val;
vector<String> values = value.split(" ");
if(values.size() == 4) {
val->setColor(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()), atof(values[3].c_str()));
} else {
Logger::log("Error: A Color must have 4 values (%d provided)!\n", values.size());
}
return;
} else {
*retType = GLSLProgramParam::PARAM_UNKNOWN;
(*valueRes) = NULL;
}
}
| 32.787234 | 202 | 0.717932 | Guendeli |
2a374262715fee77b0dc8a70db55bc86ed65192d | 1,633 | hpp | C++ | include/sre/Resource.hpp | estrac/SimpleRenderEngine | af8f25378e1394448a12b50fd9a19297e5de28d2 | [
"MIT"
] | 313 | 2017-01-13T10:54:58.000Z | 2022-03-18T03:08:53.000Z | include/sre/Resource.hpp | AntonyChan818/SimpleRenderEngine | 7e52507ecf6e93c1ddce7f9c2175acb159f49492 | [
"MIT"
] | 13 | 2016-09-29T12:50:23.000Z | 2019-04-21T05:17:33.000Z | include/sre/Resource.hpp | AntonyChan818/SimpleRenderEngine | 7e52507ecf6e93c1ddce7f9c2175acb159f49492 | [
"MIT"
] | 61 | 2016-08-31T07:34:42.000Z | 2022-03-16T23:02:11.000Z | /*
* SimpleRenderEngine (https://github.com/mortennobel/SimpleRenderEngine)
*
* Created by Morten Nobel-Jørgensen ( http://www.nobel-joergensen.com/ )
* License: MIT
*/
#pragma once
#include <string>
#include <set>
#include <map>
namespace sre {
enum ResourceType {
BuiltIn = 0b001,
File = 0b010,
Memory = 0b100,
All = 0b111,
};
// The resource class allows accessing resources in a uniform way. The resources are either built-in resources,
// file-resources or memory resources. File resources overwrites built-in resources, and memory resources overwrites
// both built-in and file-resources.
// The resource class is a key-value map, where each key must be uses a filename notation.
class Resource {
public:
// load resource from built-in, filesystem or memory
// returns empty string if not found
static std::string loadText(std::string key, ResourceType filter = ResourceType::All);
// set memory resource
static void set(const std::string& key, const std::string& value);
static void reset(); // reset memory resources
// get keys in resource system
static std::set<std::string> getKeys(ResourceType filter = ResourceType::All);
private:
static std::map<std::string,std::string> memoryOnlyResources;
};
} | 41.871795 | 120 | 0.560931 | estrac |
2a3d8ae74318d4784bb0a7ebb271d69e305c468b | 1,462 | cpp | C++ | Modules/SegmentationUI/Qmitk/QmitkRegionGrowingToolGUI.cpp | samsmu/MITK | c93dce6dc38d8f4c961de4440e4dd113b9841c8c | [
"BSD-3-Clause"
] | 5 | 2015-02-05T10:58:41.000Z | 2019-04-17T15:04:07.000Z | Modules/SegmentationUI/Qmitk/QmitkRegionGrowingToolGUI.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Modules/SegmentationUI/Qmitk/QmitkRegionGrowingToolGUI.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | #include "QmitkRegionGrowingToolGUI.h"
MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkRegionGrowingToolGUI, "")
QmitkRegionGrowingToolGUI::QmitkRegionGrowingToolGUI()
: QmitkToolGUI()
{
m_Controls.setupUi(this);
connect(this, SIGNAL(NewToolAssociated(mitk::Tool*)), this, SLOT(OnNewToolAssociated(mitk::Tool*)));
}
QmitkRegionGrowingToolGUI::~QmitkRegionGrowingToolGUI()
{
if (m_RegionGrowingTool.IsNotNull())
{
m_RegionGrowingTool->thresholdsChanged -=
mitk::MessageDelegate2<QmitkRegionGrowingToolGUI, double, double>(this, &QmitkRegionGrowingToolGUI::onThresholdsChanged);
}
}
void QmitkRegionGrowingToolGUI::OnNewToolAssociated(mitk::Tool* tool)
{
if (m_RegionGrowingTool.IsNotNull())
{
m_RegionGrowingTool->thresholdsChanged -=
mitk::MessageDelegate2<QmitkRegionGrowingToolGUI, double, double>(this, &QmitkRegionGrowingToolGUI::onThresholdsChanged);
}
m_RegionGrowingTool = dynamic_cast<mitk::RegionGrowingTool*>(m_Tool.GetPointer());
if (m_RegionGrowingTool.IsNotNull())
{
m_RegionGrowingTool->thresholdsChanged +=
mitk::MessageDelegate2<QmitkRegionGrowingToolGUI, double, double>(this, &QmitkRegionGrowingToolGUI::onThresholdsChanged);
}
}
void QmitkRegionGrowingToolGUI::onThresholdsChanged(double lowThreshold, double highThreshold)
{
m_Controls.lowThresholdValue->setText(QString::number(lowThreshold));
m_Controls.highThresholdValue->setText(QString::number(highThreshold));
}
| 32.488889 | 127 | 0.792066 | samsmu |
2a3e7982560ba836040315476accb9cbc193c9f4 | 4,524 | cpp | C++ | src/fluxions_renderer_gles30_snapshot.cpp | microwerx/fluxions-renderer | d461ac437e9c410577eeb609b52b6dd386e03b03 | [
"MIT"
] | null | null | null | src/fluxions_renderer_gles30_snapshot.cpp | microwerx/fluxions-renderer | d461ac437e9c410577eeb609b52b6dd386e03b03 | [
"MIT"
] | null | null | null | src/fluxions_renderer_gles30_snapshot.cpp | microwerx/fluxions-renderer | d461ac437e9c410577eeb609b52b6dd386e03b03 | [
"MIT"
] | null | null | null | #include "fluxions_renderer_pch.hpp"
#include <fluxions_renderer_gles30_snapshot.hpp>
namespace Fluxions {
//////////////////////////////////////////////////////////////////////
// RendererGLES30Snapshot ///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
RendererGLES30Snapshot::RendererGLES30Snapshot() {}
RendererGLES30Snapshot::~RendererGLES30Snapshot() {}
void RendererGLES30Snapshot::save() {
glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTexture);
if (activeTexture >= GL_TEXTURE0)
activeTexture -= GL_TEXTURE0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture2D);
glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &textureCubeMap);
glActiveTexture(GL_TEXTURE0);
glGetIntegerv(GL_CURRENT_PROGRAM, &program);
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer);
glGetIntegerv(GL_RENDERBUFFER_BINDING, &renderbuffer);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &arrayBuffer);
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &elementArrayBuffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &vertexArray);
glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRgb);
glGetIntegerv(GL_BLEND_DST_RGB, &blendDstRgb);
glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDstAlpha);
glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRgb);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha);
glGetIntegerv(GL_VIEWPORT, viewport.v());
glGetIntegerv(GL_SCISSOR_BOX, scissorBox.v());
glGetIntegerv(GL_DEPTH_FUNC, &depthFunc);
glGetIntegerv(GL_STENCIL_FUNC, &stencilFunc);
glGetIntegerv(GL_STENCIL_REF, &stencilRef);
glGetIntegerv(GL_STENCIL_VALUE_MASK, &stencilValueMask);
glGetIntegerv(GL_STENCIL_BACK_FUNC, &stencilBackFunc);
glGetIntegerv(GL_STENCIL_BACK_VALUE_MASK, &stencilBackValueMask);
glGetIntegerv(GL_STENCIL_BACK_REF, &stencilBackRef);
glGetIntegerv(GL_STENCIL_FAIL, &stencilFail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &stencilPassDepthFail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &stencilPassDepthPass);
glGetIntegerv(GL_STENCIL_BACK_FAIL, &stencilBackFail);
glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_FAIL, &stencilBackPassDepthFail);
glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_PASS, &stencilBackPassDepthPass);
glGetIntegerv(GL_CULL_FACE_MODE, &cullFaceMode);
glGetFloatv(GL_COLOR_CLEAR_VALUE, colorClearValue.ptr());
blendEnabled = glIsEnabled(GL_BLEND);
cullFaceEnabled = glIsEnabled(GL_CULL_FACE);
depthTestEnabled = glIsEnabled(GL_DEPTH_TEST);
scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
stencilTestEnabled = glIsEnabled(GL_STENCIL_TEST);
framebufferSrgbEnabled = glIsEnabled(GL_FRAMEBUFFER_SRGB);
}
void RendererGLES30Snapshot::restore() {
glUseProgram(program);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glActiveTexture(GL_TEXTURE0 + activeTexture);
glBindTexture(GL_TEXTURE_2D, texture2D);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureCubeMap);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glBindVertexArray(vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementArrayBuffer);
glBlendEquationSeparate(blendEquationRgb, blendEquationAlpha);
glBlendFuncSeparate(blendSrcRgb, blendDstRgb, blendSrcAlpha, blendDstAlpha);
glDepthFunc(depthFunc);
glStencilFuncSeparate(GL_FRONT, stencilFunc, stencilRef, stencilValueMask);
glStencilFuncSeparate(GL_BACK, stencilBackFunc, stencilBackRef, stencilBackValueMask);
glStencilOpSeparate(GL_FRONT, stencilFail, stencilPassDepthFail, stencilPassDepthPass);
glStencilOpSeparate(GL_BACK, stencilBackFail, stencilBackPassDepthFail, stencilBackPassDepthPass);
glCullFace(cullFaceMode);
glClearColor(colorClearValue.r, colorClearValue.g, colorClearValue.b, colorClearValue.a);
if (blendEnabled)
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
if (cullFaceEnabled)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
if (depthTestEnabled)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
if (scissorTestEnabled)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
if (stencilTestEnabled)
glEnable(GL_STENCIL_TEST);
else
glDisable(GL_STENCIL_TEST);
if (framebufferSrgbEnabled)
glEnable(GL_FRAMEBUFFER_SRGB);
else
glDisable(GL_FRAMEBUFFER_SRGB);
glViewport(viewport.x, viewport.y, viewport.w, viewport.h);
glScissor(scissorBox.x, scissorBox.y, scissorBox.w, scissorBox.h);
}
}
| 41.888889 | 100 | 0.782051 | microwerx |
2a48a46382db2584bb71399229333cf710812a53 | 35,596 | cpp | C++ | src/lib/pubkey/newhope/newhope.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | 1 | 2018-01-07T03:42:28.000Z | 2018-01-07T03:42:28.000Z | src/lib/pubkey/newhope/newhope.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | null | null | null | src/lib/pubkey/newhope/newhope.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | null | null | null | /*
* NEWHOPE Ring-LWE scheme
* Based on the public domain reference implementation by the
* designers (https://github.com/tpoeppelmann/newhope)
*
* Further changes
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/newhope.h>
#include <botan/hash.h>
#include <botan/stream_cipher.h>
#include <botan/loadstor.h>
namespace Botan {
typedef newhope_poly poly;
// Don't change this :)
#define PARAM_Q 12289
#define PARAM_N 1024
#define NEWHOPE_POLY_BYTES 1792
#define NEWHOPE_SEED_BYTES 32
namespace {
/* Incomplete-reduction routines; for details on allowed input ranges
* and produced output ranges, see the description in the paper:
* https://cryptojedi.org/papers/#newhope */
inline uint16_t montgomery_reduce(uint32_t a)
{
const uint32_t qinv = 12287; // -inverse_mod(p,2^18)
const uint32_t rlog = 18;
uint32_t u;
u = (a * qinv);
u &= ((1<<rlog)-1);
u *= PARAM_Q;
a = a + u;
return a >> 18;
}
inline uint16_t barrett_reduce(uint16_t a)
{
uint32_t u = (static_cast<uint32_t>(a) * 5) >> 16;
u *= PARAM_Q;
a -= u;
return a;
}
inline void mul_coefficients(uint16_t* poly, const uint16_t* factors)
{
for(size_t i = 0; i < PARAM_N; i++)
poly[i] = montgomery_reduce((poly[i] * factors[i]));
}
/* GS_bo_to_no; omegas need to be in Montgomery domain */
inline void ntt(uint16_t * a, const uint16_t* omega)
{
for(size_t i=0;i<10;i+=2)
{
// Even level
size_t distance = (1<<i);
for(size_t start = 0; start < distance;start++)
{
size_t jTwiddle = 0;
for(size_t j=start;j<PARAM_N-1;j+=2*distance)
{
uint16_t W = omega[jTwiddle++];
uint16_t temp = a[j];
a[j] = (temp + a[j + distance]); // Omit reduction (be lazy)
a[j + distance] = montgomery_reduce((W * (static_cast<uint32_t>(temp) + 3*PARAM_Q - a[j + distance])));
}
}
// Odd level
distance <<= 1;
for(size_t start = 0; start < distance;start++)
{
size_t jTwiddle = 0;
for(size_t j=start;j<PARAM_N-1;j+=2*distance)
{
uint16_t W = omega[jTwiddle++];
uint16_t temp = a[j];
a[j] = barrett_reduce((temp + a[j + distance]));
a[j + distance] = montgomery_reduce((W * (static_cast<uint32_t>(temp) + 3*PARAM_Q - a[j + distance])));
}
}
}
}
inline void poly_frombytes(poly *r, const uint8_t *a)
{
for(size_t i=0;i<PARAM_N/4;i++)
{
r->coeffs[4*i+0] = a[7*i+0] | ((static_cast<uint16_t>(a[7*i+1]) & 0x3f) << 8);
r->coeffs[4*i+1] = (a[7*i+1] >> 6) | (static_cast<uint16_t>(a[7*i+2]) << 2) | (static_cast<uint16_t>(a[7*i+3] & 0x0f) << 10);
r->coeffs[4*i+2] = (a[7*i+3] >> 4) | (static_cast<uint16_t>(a[7*i+4]) << 4) | (static_cast<uint16_t>(a[7*i+5] & 0x03) << 12);
r->coeffs[4*i+3] = (a[7*i+5] >> 2) | (static_cast<uint16_t>(a[7*i+6]) << 6);
}
}
inline void poly_tobytes(uint8_t *r, const poly *p)
{
for(size_t i=0;i<PARAM_N/4;i++)
{
uint16_t t0 = barrett_reduce(p->coeffs[4*i+0]); //Make sure that coefficients have only 14 bits
uint16_t t1 = barrett_reduce(p->coeffs[4*i+1]);
uint16_t t2 = barrett_reduce(p->coeffs[4*i+2]);
uint16_t t3 = barrett_reduce(p->coeffs[4*i+3]);
uint16_t m;
int16_t c;
m = t0 - PARAM_Q;
c = m;
c >>= 15;
t0 = m ^ ((t0^m)&c); // <Make sure that coefficients are in [0,q]
m = t1 - PARAM_Q;
c = m;
c >>= 15;
t1 = m ^ ((t1^m)&c); // <Make sure that coefficients are in [0,q]
m = t2 - PARAM_Q;
c = m;
c >>= 15;
t2 = m ^ ((t2^m)&c); // <Make sure that coefficients are in [0,q]
m = t3 - PARAM_Q;
c = m;
c >>= 15;
t3 = m ^ ((t3^m)&c); // <Make sure that coefficients are in [0,q]
r[7*i+0] = t0 & 0xff;
r[7*i+1] = (t0 >> 8) | (t1 << 6);
r[7*i+2] = (t1 >> 2);
r[7*i+3] = (t1 >> 10) | (t2 << 4);
r[7*i+4] = (t2 >> 4);
r[7*i+5] = (t2 >> 12) | (t3 << 2);
r[7*i+6] = (t3 >> 6);
}
}
inline void poly_getnoise(Botan::RandomNumberGenerator& rng, poly *r)
{
uint8_t buf[4*PARAM_N];
rng.randomize(buf, 4*PARAM_N);
for(size_t i=0;i<PARAM_N;i++)
{
uint32_t t = load_le<uint32_t>(buf, i);
uint32_t d = 0;
for(int j=0;j<8;j++)
d += (t >> j) & 0x01010101;
uint32_t a = ((d >> 8) & 0xff) + (d & 0xff);
uint32_t b = (d >> 24) + ((d >> 16) & 0xff);
r->coeffs[i] = a + PARAM_Q - b;
}
}
inline void poly_pointwise(poly *r, const poly *a, const poly *b)
{
for(size_t i=0;i<PARAM_N;i++)
{
uint16_t t = montgomery_reduce(3186*b->coeffs[i]); /* t is now in Montgomery domain */
r->coeffs[i] = montgomery_reduce(a->coeffs[i] * t); /* r->coeffs[i] is back in normal domain */
}
}
inline void poly_add(poly *r, const poly *a, const poly *b)
{
for(size_t i=0;i<PARAM_N;i++)
r->coeffs[i] = barrett_reduce(a->coeffs[i] + b->coeffs[i]);
}
inline void poly_ntt(poly *r)
{
static const uint16_t omegas_montgomery[PARAM_N/2] = {
4075, 6974, 7373, 7965, 3262, 5079, 522, 2169, 6364, 1018, 1041, 8775, 2344,
11011, 5574, 1973, 4536, 1050, 6844, 3860, 3818, 6118, 2683, 1190, 4789,
7822, 7540, 6752, 5456, 4449, 3789, 12142, 11973, 382, 3988, 468, 6843, 5339,
6196, 3710, 11316, 1254, 5435, 10930, 3998, 10256, 10367, 3879, 11889, 1728,
6137, 4948, 5862, 6136, 3643, 6874, 8724, 654, 10302, 1702, 7083, 6760, 56,
3199, 9987, 605, 11785, 8076, 5594, 9260, 6403, 4782, 6212, 4624, 9026, 8689,
4080, 11868, 6221, 3602, 975, 8077, 8851, 9445, 5681, 3477, 1105, 142, 241,
12231, 1003, 3532, 5009, 1956, 6008, 11404, 7377, 2049, 10968, 12097, 7591,
5057, 3445, 4780, 2920, 7048, 3127, 8120, 11279, 6821, 11502, 8807, 12138,
2127, 2839, 3957, 431, 1579, 6383, 9784, 5874, 677, 3336, 6234, 2766, 1323,
9115, 12237, 2031, 6956, 6413, 2281, 3969, 3991, 12133, 9522, 4737, 10996,
4774, 5429, 11871, 3772, 453, 5908, 2882, 1805, 2051, 1954, 11713, 3963,
2447, 6142, 8174, 3030, 1843, 2361, 12071, 2908, 3529, 3434, 3202, 7796,
2057, 5369, 11939, 1512, 6906, 10474, 11026, 49, 10806, 5915, 1489, 9789,
5942, 10706, 10431, 7535, 426, 8974, 3757, 10314, 9364, 347, 5868, 9551,
9634, 6554, 10596, 9280, 11566, 174, 2948, 2503, 6507, 10723, 11606, 2459,
64, 3656, 8455, 5257, 5919, 7856, 1747, 9166, 5486, 9235, 6065, 835, 3570,
4240, 11580, 4046, 10970, 9139, 1058, 8210, 11848, 922, 7967, 1958, 10211,
1112, 3728, 4049, 11130, 5990, 1404, 325, 948, 11143, 6190, 295, 11637, 5766,
8212, 8273, 2919, 8527, 6119, 6992, 8333, 1360, 2555, 6167, 1200, 7105, 7991,
3329, 9597, 12121, 5106, 5961, 10695, 10327, 3051, 9923, 4896, 9326, 81,
3091, 1000, 7969, 4611, 726, 1853, 12149, 4255, 11112, 2768, 10654, 1062,
2294, 3553, 4805, 2747, 4846, 8577, 9154, 1170, 2319, 790, 11334, 9275, 9088,
1326, 5086, 9094, 6429, 11077, 10643, 3504, 3542, 8668, 9744, 1479, 1, 8246,
7143, 11567, 10984, 4134, 5736, 4978, 10938, 5777, 8961, 4591, 5728, 6461,
5023, 9650, 7468, 949, 9664, 2975, 11726, 2744, 9283, 10092, 5067, 12171,
2476, 3748, 11336, 6522, 827, 9452, 5374, 12159, 7935, 3296, 3949, 9893,
4452, 10908, 2525, 3584, 8112, 8011, 10616, 4989, 6958, 11809, 9447, 12280,
1022, 11950, 9821, 11745, 5791, 5092, 2089, 9005, 2881, 3289, 2013, 9048,
729, 7901, 1260, 5755, 4632, 11955, 2426, 10593, 1428, 4890, 5911, 3932,
9558, 8830, 3637, 5542, 145, 5179, 8595, 3707, 10530, 355, 3382, 4231, 9741,
1207, 9041, 7012, 1168, 10146, 11224, 4645, 11885, 10911, 10377, 435, 7952,
4096, 493, 9908, 6845, 6039, 2422, 2187, 9723, 8643, 9852, 9302, 6022, 7278,
1002, 4284, 5088, 1607, 7313, 875, 8509, 9430, 1045, 2481, 5012, 7428, 354,
6591, 9377, 11847, 2401, 1067, 7188, 11516, 390, 8511, 8456, 7270, 545, 8585,
9611, 12047, 1537, 4143, 4714, 4885, 1017, 5084, 1632, 3066, 27, 1440, 8526,
9273, 12046, 11618, 9289, 3400, 9890, 3136, 7098, 8758, 11813, 7384, 3985,
11869, 6730, 10745, 10111, 2249, 4048, 2884, 11136, 2126, 1630, 9103, 5407,
2686, 9042, 2969, 8311, 9424, 9919, 8779, 5332, 10626, 1777, 4654, 10863,
7351, 3636, 9585, 5291, 8374, 2166, 4919, 12176, 9140, 12129, 7852, 12286,
4895, 10805, 2780, 5195, 2305, 7247, 9644, 4053, 10600, 3364, 3271, 4057,
4414, 9442, 7917, 2174};
static const uint16_t psis_bitrev_montgomery[PARAM_N] = {
4075, 6974, 7373, 7965, 3262, 5079, 522, 2169, 6364, 1018, 1041, 8775, 2344,
11011, 5574, 1973, 4536, 1050, 6844, 3860, 3818, 6118, 2683, 1190, 4789,
7822, 7540, 6752, 5456, 4449, 3789, 12142, 11973, 382, 3988, 468, 6843, 5339,
6196, 3710, 11316, 1254, 5435, 10930, 3998, 10256, 10367, 3879, 11889, 1728,
6137, 4948, 5862, 6136, 3643, 6874, 8724, 654, 10302, 1702, 7083, 6760, 56,
3199, 9987, 605, 11785, 8076, 5594, 9260, 6403, 4782, 6212, 4624, 9026, 8689,
4080, 11868, 6221, 3602, 975, 8077, 8851, 9445, 5681, 3477, 1105, 142, 241,
12231, 1003, 3532, 5009, 1956, 6008, 11404, 7377, 2049, 10968, 12097, 7591,
5057, 3445, 4780, 2920, 7048, 3127, 8120, 11279, 6821, 11502, 8807, 12138,
2127, 2839, 3957, 431, 1579, 6383, 9784, 5874, 677, 3336, 6234, 2766, 1323,
9115, 12237, 2031, 6956, 6413, 2281, 3969, 3991, 12133, 9522, 4737, 10996,
4774, 5429, 11871, 3772, 453, 5908, 2882, 1805, 2051, 1954, 11713, 3963,
2447, 6142, 8174, 3030, 1843, 2361, 12071, 2908, 3529, 3434, 3202, 7796,
2057, 5369, 11939, 1512, 6906, 10474, 11026, 49, 10806, 5915, 1489, 9789,
5942, 10706, 10431, 7535, 426, 8974, 3757, 10314, 9364, 347, 5868, 9551,
9634, 6554, 10596, 9280, 11566, 174, 2948, 2503, 6507, 10723, 11606, 2459,
64, 3656, 8455, 5257, 5919, 7856, 1747, 9166, 5486, 9235, 6065, 835, 3570,
4240, 11580, 4046, 10970, 9139, 1058, 8210, 11848, 922, 7967, 1958, 10211,
1112, 3728, 4049, 11130, 5990, 1404, 325, 948, 11143, 6190, 295, 11637, 5766,
8212, 8273, 2919, 8527, 6119, 6992, 8333, 1360, 2555, 6167, 1200, 7105, 7991,
3329, 9597, 12121, 5106, 5961, 10695, 10327, 3051, 9923, 4896, 9326, 81,
3091, 1000, 7969, 4611, 726, 1853, 12149, 4255, 11112, 2768, 10654, 1062,
2294, 3553, 4805, 2747, 4846, 8577, 9154, 1170, 2319, 790, 11334, 9275, 9088,
1326, 5086, 9094, 6429, 11077, 10643, 3504, 3542, 8668, 9744, 1479, 1, 8246,
7143, 11567, 10984, 4134, 5736, 4978, 10938, 5777, 8961, 4591, 5728, 6461,
5023, 9650, 7468, 949, 9664, 2975, 11726, 2744, 9283, 10092, 5067, 12171,
2476, 3748, 11336, 6522, 827, 9452, 5374, 12159, 7935, 3296, 3949, 9893,
4452, 10908, 2525, 3584, 8112, 8011, 10616, 4989, 6958, 11809, 9447, 12280,
1022, 11950, 9821, 11745, 5791, 5092, 2089, 9005, 2881, 3289, 2013, 9048,
729, 7901, 1260, 5755, 4632, 11955, 2426, 10593, 1428, 4890, 5911, 3932,
9558, 8830, 3637, 5542, 145, 5179, 8595, 3707, 10530, 355, 3382, 4231, 9741,
1207, 9041, 7012, 1168, 10146, 11224, 4645, 11885, 10911, 10377, 435, 7952,
4096, 493, 9908, 6845, 6039, 2422, 2187, 9723, 8643, 9852, 9302, 6022, 7278,
1002, 4284, 5088, 1607, 7313, 875, 8509, 9430, 1045, 2481, 5012, 7428, 354,
6591, 9377, 11847, 2401, 1067, 7188, 11516, 390, 8511, 8456, 7270, 545, 8585,
9611, 12047, 1537, 4143, 4714, 4885, 1017, 5084, 1632, 3066, 27, 1440, 8526,
9273, 12046, 11618, 9289, 3400, 9890, 3136, 7098, 8758, 11813, 7384, 3985,
11869, 6730, 10745, 10111, 2249, 4048, 2884, 11136, 2126, 1630, 9103, 5407,
2686, 9042, 2969, 8311, 9424, 9919, 8779, 5332, 10626, 1777, 4654, 10863,
7351, 3636, 9585, 5291, 8374, 2166, 4919, 12176, 9140, 12129, 7852, 12286,
4895, 10805, 2780, 5195, 2305, 7247, 9644, 4053, 10600, 3364, 3271, 4057,
4414, 9442, 7917, 2174, 3947, 11951, 2455, 6599, 10545, 10975, 3654, 2894,
7681, 7126, 7287, 12269, 4119, 3343, 2151, 1522, 7174, 7350, 11041, 2442,
2148, 5959, 6492, 8330, 8945, 5598, 3624, 10397, 1325, 6565, 1945, 11260,
10077, 2674, 3338, 3276, 11034, 506, 6505, 1392, 5478, 8778, 1178, 2776,
3408, 10347, 11124, 2575, 9489, 12096, 6092, 10058, 4167, 6085, 923, 11251,
11912, 4578, 10669, 11914, 425, 10453, 392, 10104, 8464, 4235, 8761, 7376,
2291, 3375, 7954, 8896, 6617, 7790, 1737, 11667, 3982, 9342, 6680, 636, 6825,
7383, 512, 4670, 2900, 12050, 7735, 994, 1687, 11883, 7021, 146, 10485, 1403,
5189, 6094, 2483, 2054, 3042, 10945, 3981, 10821, 11826, 8882, 8151, 180,
9600, 7684, 5219, 10880, 6780, 204, 11232, 2600, 7584, 3121, 3017, 11053,
7814, 7043, 4251, 4739, 11063, 6771, 7073, 9261, 2360, 11925, 1928, 11825,
8024, 3678, 3205, 3359, 11197, 5209, 8581, 3238, 8840, 1136, 9363, 1826,
3171, 4489, 7885, 346, 2068, 1389, 8257, 3163, 4840, 6127, 8062, 8921, 612,
4238, 10763, 8067, 125, 11749, 10125, 5416, 2110, 716, 9839, 10584, 11475,
11873, 3448, 343, 1908, 4538, 10423, 7078, 4727, 1208, 11572, 3589, 2982,
1373, 1721, 10753, 4103, 2429, 4209, 5412, 5993, 9011, 438, 3515, 7228, 1218,
8347, 5232, 8682, 1327, 7508, 4924, 448, 1014, 10029, 12221, 4566, 5836,
12229, 2717, 1535, 3200, 5588, 5845, 412, 5102, 7326, 3744, 3056, 2528, 7406,
8314, 9202, 6454, 6613, 1417, 10032, 7784, 1518, 3765, 4176, 5063, 9828,
2275, 6636, 4267, 6463, 2065, 7725, 3495, 8328, 8755, 8144, 10533, 5966,
12077, 9175, 9520, 5596, 6302, 8400, 579, 6781, 11014, 5734, 11113, 11164,
4860, 1131, 10844, 9068, 8016, 9694, 3837, 567, 9348, 7000, 6627, 7699, 5082,
682, 11309, 5207, 4050, 7087, 844, 7434, 3769, 293, 9057, 6940, 9344, 10883,
2633, 8190, 3944, 5530, 5604, 3480, 2171, 9282, 11024, 2213, 8136, 3805, 767,
12239, 216, 11520, 6763, 10353, 7, 8566, 845, 7235, 3154, 4360, 3285, 10268,
2832, 3572, 1282, 7559, 3229, 8360, 10583, 6105, 3120, 6643, 6203, 8536,
8348, 6919, 3536, 9199, 10891, 11463, 5043, 1658, 5618, 8787, 5789, 4719,
751, 11379, 6389, 10783, 3065, 7806, 6586, 2622, 5386, 510, 7628, 6921, 578,
10345, 11839, 8929, 4684, 12226, 7154, 9916, 7302, 8481, 3670, 11066, 2334,
1590, 7878, 10734, 1802, 1891, 5103, 6151, 8820, 3418, 7846, 9951, 4693, 417,
9996, 9652, 4510, 2946, 5461, 365, 881, 1927, 1015, 11675, 11009, 1371,
12265, 2485, 11385, 5039, 6742, 8449, 1842, 12217, 8176, 9577, 4834, 7937,
9461, 2643, 11194, 3045, 6508, 4094, 3451, 7911, 11048, 5406, 4665, 3020,
6616, 11345, 7519, 3669, 5287, 1790, 7014, 5410, 11038, 11249, 2035, 6125,
10407, 4565, 7315, 5078, 10506, 2840, 2478, 9270, 4194, 9195, 4518, 7469,
1160, 6878, 2730, 10421, 10036, 1734, 3815, 10939, 5832, 10595, 10759, 4423,
8420, 9617, 7119, 11010, 11424, 9173, 189, 10080, 10526, 3466, 10588, 7592,
3578, 11511, 7785, 9663, 530, 12150, 8957, 2532, 3317, 9349, 10243, 1481,
9332, 3454, 3758, 7899, 4218, 2593, 11410, 2276, 982, 6513, 1849, 8494, 9021,
4523, 7988, 8, 457, 648, 150, 8000, 2307, 2301, 874, 5650, 170, 9462, 2873,
9855, 11498, 2535, 11169, 5808, 12268, 9687, 1901, 7171, 11787, 3846, 1573,
6063, 3793, 466, 11259, 10608, 3821, 6320, 4649, 6263, 2929};
mul_coefficients(r->coeffs, psis_bitrev_montgomery);
ntt(r->coeffs, omegas_montgomery);
}
inline void bitrev_vector(uint16_t* poly)
{
static const uint16_t bitrev_table[1024] = {
0,512,256,768,128,640,384,896,64,576,320,832,192,704,448,960,32,544,288,800,160,672,416,928,96,608,352,864,224,736,480,992,
16,528,272,784,144,656,400,912,80,592,336,848,208,720,464,976,48,560,304,816,176,688,432,944,112,624,368,880,240,752,496,1008,
8,520,264,776,136,648,392,904,72,584,328,840,200,712,456,968,40,552,296,808,168,680,424,936,104,616,360,872,232,744,488,1000,
24,536,280,792,152,664,408,920,88,600,344,856,216,728,472,984,56,568,312,824,184,696,440,952,120,632,376,888,248,760,504,1016,
4,516,260,772,132,644,388,900,68,580,324,836,196,708,452,964,36,548,292,804,164,676,420,932,100,612,356,868,228,740,484,996,
20,532,276,788,148,660,404,916,84,596,340,852,212,724,468,980,52,564,308,820,180,692,436,948,116,628,372,884,244,756,500,1012,
12,524,268,780,140,652,396,908,76,588,332,844,204,716,460,972,44,556,300,812,172,684,428,940,108,620,364,876,236,748,492,1004,
28,540,284,796,156,668,412,924,92,604,348,860,220,732,476,988,60,572,316,828,188,700,444,956,124,636,380,892,252,764,508,1020,
2,514,258,770,130,642,386,898,66,578,322,834,194,706,450,962,34,546,290,802,162,674,418,930,98,610,354,866,226,738,482,994,
18,530,274,786,146,658,402,914,82,594,338,850,210,722,466,978,50,562,306,818,178,690,434,946,114,626,370,882,242,754,498,1010,
10,522,266,778,138,650,394,906,74,586,330,842,202,714,458,970,42,554,298,810,170,682,426,938,106,618,362,874,234,746,490,1002,
26,538,282,794,154,666,410,922,90,602,346,858,218,730,474,986,58,570,314,826,186,698,442,954,122,634,378,890,250,762,506,1018,
6,518,262,774,134,646,390,902,70,582,326,838,198,710,454,966,38,550,294,806,166,678,422,934,102,614,358,870,230,742,486,998,
22,534,278,790,150,662,406,918,86,598,342,854,214,726,470,982,54,566,310,822,182,694,438,950,118,630,374,886,246,758,502,1014,
14,526,270,782,142,654,398,910,78,590,334,846,206,718,462,974,46,558,302,814,174,686,430,942,110,622,366,878,238,750,494,1006,
30,542,286,798,158,670,414,926,94,606,350,862,222,734,478,990,62,574,318,830,190,702,446,958,126,638,382,894,254,766,510,1022,
1,513,257,769,129,641,385,897,65,577,321,833,193,705,449,961,33,545,289,801,161,673,417,929,97,609,353,865,225,737,481,993,
17,529,273,785,145,657,401,913,81,593,337,849,209,721,465,977,49,561,305,817,177,689,433,945,113,625,369,881,241,753,497,1009,
9,521,265,777,137,649,393,905,73,585,329,841,201,713,457,969,41,553,297,809,169,681,425,937,105,617,361,873,233,745,489,1001,
25,537,281,793,153,665,409,921,89,601,345,857,217,729,473,985,57,569,313,825,185,697,441,953,121,633,377,889,249,761,505,1017,
5,517,261,773,133,645,389,901,69,581,325,837,197,709,453,965,37,549,293,805,165,677,421,933,101,613,357,869,229,741,485,997,
21,533,277,789,149,661,405,917,85,597,341,853,213,725,469,981,53,565,309,821,181,693,437,949,117,629,373,885,245,757,501,1013,
13,525,269,781,141,653,397,909,77,589,333,845,205,717,461,973,45,557,301,813,173,685,429,941,109,621,365,877,237,749,493,1005,
29,541,285,797,157,669,413,925,93,605,349,861,221,733,477,989,61,573,317,829,189,701,445,957,125,637,381,893,253,765,509,1021,
3,515,259,771,131,643,387,899,67,579,323,835,195,707,451,963,35,547,291,803,163,675,419,931,99,611,355,867,227,739,483,995,
19,531,275,787,147,659,403,915,83,595,339,851,211,723,467,979,51,563,307,819,179,691,435,947,115,627,371,883,243,755,499,1011,
11,523,267,779,139,651,395,907,75,587,331,843,203,715,459,971,43,555,299,811,171,683,427,939,107,619,363,875,235,747,491,1003,
27,539,283,795,155,667,411,923,91,603,347,859,219,731,475,987,59,571,315,827,187,699,443,955,123,635,379,891,251,763,507,1019,
7,519,263,775,135,647,391,903,71,583,327,839,199,711,455,967,39,551,295,807,167,679,423,935,103,615,359,871,231,743,487,999,
23,535,279,791,151,663,407,919,87,599,343,855,215,727,471,983,55,567,311,823,183,695,439,951,119,631,375,887,247,759,503,1015,
15,527,271,783,143,655,399,911,79,591,335,847,207,719,463,975,47,559,303,815,175,687,431,943,111,623,367,879,239,751,495,1007,
31,543,287,799,159,671,415,927,95,607,351,863,223,735,479,991,63,575,319,831,191,703,447,959,127,639,383,895,255,767,511,1023
};
unsigned int i,r;
uint16_t tmp;
for(i = 0; i < PARAM_N; i++)
{
r = bitrev_table[i];
if (i < r)
{
tmp = poly[i];
poly[i] = poly[r];
poly[r] = tmp;
}
}
}
inline void poly_invntt(poly *r)
{
static const uint16_t omegas_inv_montgomery[PARAM_N/2] = {
4075, 5315, 4324, 4916, 10120, 11767, 7210, 9027, 10316, 6715, 1278, 9945,
3514, 11248, 11271, 5925, 147, 8500, 7840, 6833, 5537, 4749, 4467, 7500,
11099, 9606, 6171, 8471, 8429, 5445, 11239, 7753, 9090, 12233, 5529, 5206,
10587, 1987, 11635, 3565, 5415, 8646, 6153, 6427, 7341, 6152, 10561, 400,
8410, 1922, 2033, 8291, 1359, 6854, 11035, 973, 8579, 6093, 6950, 5446,
11821, 8301, 11907, 316, 52, 3174, 10966, 9523, 6055, 8953, 11612, 6415,
2505, 5906, 10710, 11858, 8332, 9450, 10162, 151, 3482, 787, 5468, 1010,
4169, 9162, 5241, 9369, 7509, 8844, 7232, 4698, 192, 1321, 10240, 4912, 885,
6281, 10333, 7280, 8757, 11286, 58, 12048, 12147, 11184, 8812, 6608, 2844,
3438, 4212, 11314, 8687, 6068, 421, 8209, 3600, 3263, 7665, 6077, 7507, 5886,
3029, 6695, 4213, 504, 11684, 2302, 1962, 1594, 6328, 7183, 168, 2692, 8960,
4298, 5184, 11089, 6122, 9734, 10929, 3956, 5297, 6170, 3762, 9370, 4016,
4077, 6523, 652, 11994, 6099, 1146, 11341, 11964, 10885, 6299, 1159, 8240,
8561, 11177, 2078, 10331, 4322, 11367, 441, 4079, 11231, 3150, 1319, 8243,
709, 8049, 8719, 11454, 6224, 3054, 6803, 3123, 10542, 4433, 6370, 7032,
3834, 8633, 12225, 9830, 683, 1566, 5782, 9786, 9341, 12115, 723, 3009, 1693,
5735, 2655, 2738, 6421, 11942, 2925, 1975, 8532, 3315, 11863, 4754, 1858,
1583, 6347, 2500, 10800, 6374, 1483, 12240, 1263, 1815, 5383, 10777, 350,
6920, 10232, 4493, 9087, 8855, 8760, 9381, 218, 9928, 10446, 9259, 4115,
6147, 9842, 8326, 576, 10335, 10238, 10484, 9407, 6381, 11836, 8517, 418,
6860, 7515, 1293, 7552, 2767, 156, 8298, 8320, 10008, 5876, 5333, 10258,
10115, 4372, 2847, 7875, 8232, 9018, 8925, 1689, 8236, 2645, 5042, 9984,
7094, 9509, 1484, 7394, 3, 4437, 160, 3149, 113, 7370, 10123, 3915, 6998,
2704, 8653, 4938, 1426, 7635, 10512, 1663, 6957, 3510, 2370, 2865, 3978,
9320, 3247, 9603, 6882, 3186, 10659, 10163, 1153, 9405, 8241, 10040, 2178,
1544, 5559, 420, 8304, 4905, 476, 3531, 5191, 9153, 2399, 8889, 3000, 671,
243, 3016, 3763, 10849, 12262, 9223, 10657, 7205, 11272, 7404, 7575, 8146,
10752, 242, 2678, 3704, 11744, 5019, 3833, 3778, 11899, 773, 5101, 11222,
9888, 442, 2912, 5698, 11935, 4861, 7277, 9808, 11244, 2859, 3780, 11414,
4976, 10682, 7201, 8005, 11287, 5011, 6267, 2987, 2437, 3646, 2566, 10102,
9867, 6250, 5444, 2381, 11796, 8193, 4337, 11854, 1912, 1378, 404, 7644,
1065, 2143, 11121, 5277, 3248, 11082, 2548, 8058, 8907, 11934, 1759, 8582,
3694, 7110, 12144, 6747, 8652, 3459, 2731, 8357, 6378, 7399, 10861, 1696,
9863, 334, 7657, 6534, 11029, 4388, 11560, 3241, 10276, 9000, 9408, 3284,
10200, 7197, 6498, 544, 2468, 339, 11267, 9, 2842, 480, 5331, 7300, 1673,
4278, 4177, 8705, 9764, 1381, 7837, 2396, 8340, 8993, 4354, 130, 6915, 2837,
11462, 5767, 953, 8541, 9813, 118, 7222, 2197, 3006, 9545, 563, 9314, 2625,
11340, 4821, 2639, 7266, 5828, 6561, 7698, 3328, 6512, 1351, 7311, 6553,
8155, 1305, 722, 5146, 4043, 12288, 10810, 2545, 3621, 8747, 8785, 1646,
1212, 5860, 3195, 7203, 10963, 3201, 3014, 955, 11499, 9970, 11119, 3135,
3712, 7443, 9542, 7484, 8736, 9995, 11227, 1635, 9521, 1177, 8034, 140,
10436, 11563, 7678, 4320, 11289, 9198, 12208, 2963, 7393, 2366, 9238 };
static const uint16_t psis_inv_montgomery[PARAM_N] = {
256, 10570, 1510, 7238, 1034, 7170, 6291, 7921, 11665, 3422, 4000, 2327,
2088, 5565, 795, 10647, 1521, 5484, 2539, 7385, 1055, 7173, 8047, 11683,
1669, 1994, 3796, 5809, 4341, 9398, 11876, 12230, 10525, 12037, 12253, 3506,
4012, 9351, 4847, 2448, 7372, 9831, 3160, 2207, 5582, 2553, 7387, 6322, 9681,
1383, 10731, 1533, 219, 5298, 4268, 7632, 6357, 9686, 8406, 4712, 9451,
10128, 4958, 5975, 11387, 8649, 11769, 6948, 11526, 12180, 1740, 10782, 6807,
2728, 7412, 4570, 4164, 4106, 11120, 12122, 8754, 11784, 3439, 5758, 11356,
6889, 9762, 11928, 1704, 1999, 10819, 12079, 12259, 7018, 11536, 1648, 1991,
2040, 2047, 2048, 10826, 12080, 8748, 8272, 8204, 1172, 1923, 7297, 2798,
7422, 6327, 4415, 7653, 6360, 11442, 12168, 7005, 8023, 9924, 8440, 8228,
2931, 7441, 1063, 3663, 5790, 9605, 10150, 1450, 8985, 11817, 10466, 10273,
12001, 3470, 7518, 1074, 1909, 7295, 9820, 4914, 702, 5367, 7789, 8135, 9940,
1420, 3714, 11064, 12114, 12264, 1752, 5517, 9566, 11900, 1700, 3754, 5803,
829, 1874, 7290, 2797, 10933, 5073, 7747, 8129, 6428, 6185, 11417, 1631, 233,
5300, 9535, 10140, 11982, 8734, 8270, 2937, 10953, 8587, 8249, 2934, 9197,
4825, 5956, 4362, 9401, 1343, 3703, 529, 10609, 12049, 6988, 6265, 895, 3639,
4031, 4087, 4095, 585, 10617, 8539, 4731, 4187, 9376, 3095, 9220, 10095,
10220, 1460, 10742, 12068, 1724, 5513, 11321, 6884, 2739, 5658, 6075, 4379,
11159, 10372, 8504, 4726, 9453, 3106, 7466, 11600, 10435, 8513, 9994, 8450,
9985, 3182, 10988, 8592, 2983, 9204, 4826, 2445, 5616, 6069, 867, 3635, 5786,
11360, 5134, 2489, 10889, 12089, 1727, 7269, 2794, 9177, 1311, 5454, 9557,
6632, 2703, 9164, 10087, 1441, 3717, 531, 3587, 2268, 324, 5313, 759, 1864,
5533, 2546, 7386, 9833, 8427, 4715, 11207, 1601, 7251, 4547, 11183, 12131,
1733, 10781, 10318, 1474, 10744, 5046, 4232, 11138, 10369, 6748, 964, 7160,
4534, 7670, 8118, 8182, 4680, 11202, 6867, 981, 8918, 1274, 182, 26, 7026,
8026, 11680, 12202, 10521, 1503, 7237, 4545, 5916, 9623, 8397, 11733, 10454,
3249, 9242, 6587, 941, 1890, 270, 10572, 6777, 9746, 6659, 6218, 6155, 6146,
878, 1881, 7291, 11575, 12187, 1741, 7271, 8061, 11685, 6936, 4502, 9421,
4857, 4205, 7623, 1089, 10689, 1527, 8996, 10063, 11971, 10488, 6765, 2722,
3900, 9335, 11867, 6962, 11528, 5158, 4248, 4118, 5855, 2592, 5637, 6072,
2623, 7397, 8079, 9932, 4930, 5971, 853, 3633, 519, 8852, 11798, 3441, 11025,
1575, 225, 8810, 11792, 12218, 3501, 9278, 3081, 9218, 4828, 7712, 8124,
11694, 12204, 3499, 4011, 573, 3593, 5780, 7848, 9899, 10192, 1456, 208,
7052, 2763, 7417, 11593, 10434, 12024, 8740, 11782, 10461, 3250, 5731, 7841,
9898, 1414, 202, 3540, 7528, 2831, 2160, 10842, 5060, 4234, 4116, 588, 84,
12, 7024, 2759, 9172, 6577, 11473, 1639, 9012, 3043, 7457, 6332, 11438, 1634,
1989, 9062, 11828, 8712, 11778, 12216, 10523, 6770, 9745, 10170, 4964, 9487,
6622, 946, 8913, 6540, 6201, 4397, 9406, 8366, 9973, 8447, 8229, 11709, 8695,
10020, 3187, 5722, 2573, 10901, 6824, 4486, 4152, 9371, 8361, 2950, 2177,
311, 1800, 9035, 8313, 11721, 3430, 490, 70, 10, 1757, 251, 3547, 7529,
11609, 3414, 7510, 4584, 4166, 9373, 1339, 5458, 7802, 11648, 1664, 7260,
9815, 10180, 6721, 9738, 10169, 8475, 8233, 9954, 1422, 8981, 1283, 5450,
11312, 1616, 3742, 11068, 10359, 4991, 713, 3613, 9294, 8350, 4704, 672, 96,
7036, 9783, 11931, 3460, 5761, 823, 10651, 12055, 10500, 1500, 5481, 783,
3623, 11051, 8601, 8251, 8201, 11705, 10450, 5004, 4226, 7626, 2845, 2162,
3820, 7568, 9859, 3164, 452, 10598, 1514, 5483, 6050, 6131, 4387, 7649, 8115,
6426, 918, 8909, 8295, 1185, 5436, 11310, 8638, 1234, 5443, 11311, 5127,
2488, 2111, 10835, 5059, 7745, 2862, 3920, 560, 80, 1767, 2008, 3798, 11076,
6849, 2734, 10924, 12094, 8750, 1250, 10712, 6797, 971, 7161, 1023, 8924,
4786, 7706, 4612, 4170, 7618, 6355, 4419, 5898, 11376, 10403, 10264, 6733,
4473, 639, 5358, 2521, 9138, 3061, 5704, 4326, 618, 5355, 765, 5376, 768,
7132, 4530, 9425, 3102, 9221, 6584, 11474, 10417, 10266, 12000, 6981, 6264,
4406, 2385, 7363, 4563, 4163, 7617, 9866, 3165, 9230, 11852, 10471, 5007,
5982, 11388, 5138, 734, 3616, 11050, 12112, 6997, 11533, 12181, 10518, 12036,
3475, 2252, 7344, 9827, 4915, 9480, 6621, 4457, 7659, 9872, 6677, 4465, 4149,
7615, 4599, 657, 3605, 515, 10607, 6782, 4480, 640, 1847, 3775, 5806, 2585,
5636, 9583, 1369, 10729, 8555, 10000, 11962, 5220, 7768, 8132, 8184, 9947,
1421, 203, 29, 8782, 11788, 1684, 10774, 10317, 4985, 9490, 8378, 4708,
11206, 5112, 5997, 7879, 11659, 12199, 8765, 10030, 4944, 5973, 6120, 6141,
6144, 7900, 11662, 1666, 238, 34, 3516, 5769, 9602, 8394, 9977, 6692, 956,
10670, 6791, 9748, 11926, 8726, 11780, 5194, 742, 106, 8793, 10034, 3189,
10989, 5081, 4237, 5872, 4350, 2377, 10873, 6820, 6241, 11425, 10410, 10265,
3222, 5727, 9596, 4882, 2453, 2106, 3812, 11078, 12116, 5242, 4260, 11142,
8614, 11764, 12214, 5256, 4262, 4120, 11122, 5100, 11262, 5120, 2487, 5622,
9581, 8391, 8221, 2930, 10952, 12098, 6995, 6266, 9673, 4893, 699, 3611,
4027, 5842, 11368, 1624, 232, 8811, 8281, 1183, 169, 8802, 3013, 2186, 5579,
797, 3625, 4029, 11109, 1587, 7249, 11569, 8675, 6506, 2685, 10917, 12093,
12261, 12285, 1755, 7273, 1039, 1904, 272, 3550, 9285, 3082, 5707, 6082,
4380, 7648, 11626, 5172, 4250, 9385, 8363, 8217, 4685, 5936, 848, 8899, 6538,
934, 1889, 3781, 9318, 10109, 10222, 6727, 961, 5404, 772, 5377, 9546, 8386,
1198, 8949, 3034, 2189, 7335, 4559, 5918, 2601, 10905, 5069, 9502, 3113,
7467, 8089, 11689, 5181, 9518, 8382, 2953, 3933, 4073, 4093, 7607, 8109,
2914, 5683, 4323, 11151, 1593, 10761, 6804, 972, 3650, 2277, 5592, 4310,
7638, 9869, 4921, 703, 1856, 9043, 4803, 9464, 1352, 8971, 11815, 5199, 7765,
6376, 4422, 7654, 2849, 407, 8836, 6529, 7955, 2892, 9191, 1313, 10721,
12065, 12257, 1751, 9028, 8312, 2943, 2176, 3822, 546, 78, 8789, 11789,
10462, 12028, 6985, 4509, 9422, 1346, 5459, 4291, 613, 10621, 6784, 9747,
3148, 7472, 2823, 5670, 810, 7138, 8042, 4660, 7688, 6365, 6176, 6149, 2634,
5643, 9584, 10147, 11983, 5223, 9524, 11894, 10477, 8519, 1217, 3685, 2282,
326, 10580, 3267, 7489, 4581, 2410, 5611, 11335, 6886, 8006, 8166, 11700,
3427, 11023, 8597, 10006, 3185, 455, 65, 5276, 7776, 4622, 5927, 7869, 9902,
11948, 5218, 2501, 5624, 2559, 10899, 1557, 1978, 10816, 10323, 8497, 4725,
675, 1852, 10798, 12076, 10503, 3256, 9243, 3076, 2195, 10847, 12083, 10504,
12034, 10497 };
bitrev_vector(r->coeffs);
ntt(r->coeffs, omegas_inv_montgomery);
mul_coefficients(r->coeffs, psis_inv_montgomery);
}
inline void encode_a(uint8_t *r, const poly *pk, const uint8_t *seed)
{
int i;
poly_tobytes(r, pk);
for(i=0;i<NEWHOPE_SEED_BYTES;i++)
r[NEWHOPE_POLY_BYTES+i] = seed[i];
}
inline void decode_a(poly *pk, uint8_t *seed, const uint8_t *r)
{
int i;
poly_frombytes(pk, r);
for(i=0;i<NEWHOPE_SEED_BYTES;i++)
seed[i] = r[NEWHOPE_POLY_BYTES+i];
}
inline void encode_b(uint8_t *r, const poly *b, const poly *c)
{
poly_tobytes(r,b);
for(size_t i=0;i<PARAM_N/4;i++)
r[NEWHOPE_POLY_BYTES+i] = c->coeffs[4*i] | (c->coeffs[4*i+1] << 2) | (c->coeffs[4*i+2] << 4) | (c->coeffs[4*i+3] << 6);
}
inline void decode_b(poly *b, poly *c, const uint8_t *r)
{
poly_frombytes(b, r);
for(size_t i=0;i<PARAM_N/4;i++)
{
c->coeffs[4*i+0] = r[NEWHOPE_POLY_BYTES+i] & 0x03;
c->coeffs[4*i+1] = (r[NEWHOPE_POLY_BYTES+i] >> 2) & 0x03;
c->coeffs[4*i+2] = (r[NEWHOPE_POLY_BYTES+i] >> 4) & 0x03;
c->coeffs[4*i+3] = (r[NEWHOPE_POLY_BYTES+i] >> 6);
}
}
inline int32_t ct_abs(int32_t v)
{
int32_t mask = v >> 31;
return (v ^ mask) - mask;
}
inline int32_t f(int32_t *v0, int32_t *v1, int32_t x)
{
int32_t xit, t, r, b;
// Next 6 lines compute t = x/PARAM_Q;
b = x*2730;
t = b >> 25;
b = x - t*12289;
b = 12288 - b;
b >>= 31;
t -= b;
r = t & 1;
xit = (t>>1);
*v0 = xit+r; // v0 = round(x/(2*PARAM_Q))
t -= 1;
r = t & 1;
*v1 = (t>>1)+r;
return ct_abs(x-((*v0)*2*PARAM_Q));
}
inline int32_t g(int32_t x)
{
int32_t t,c,b;
// Next 6 lines compute t = x/(4*PARAM_Q);
b = x*2730;
t = b >> 27;
b = x - t*49156;
b = 49155 - b;
b >>= 31;
t -= b;
c = t & 1;
t = (t >> 1) + c; // t = round(x/(8*PARAM_Q))
t *= 8*PARAM_Q;
return ct_abs(t - x);
}
inline int16_t LDDecode(int32_t xi0, int32_t xi1, int32_t xi2, int32_t xi3)
{
int32_t t;
t = g(xi0);
t += g(xi1);
t += g(xi2);
t += g(xi3);
t -= 8*PARAM_Q;
t >>= 31;
return t&1;
}
inline void helprec(poly *c, const poly *v, RandomNumberGenerator& rng)
{
int32_t v0[4], v1[4];
uint8_t rand[32];
int i;
rng.randomize(rand, 32);
for(i=0; i<256; i++)
{
uint8_t rbit = (rand[i>>3] >> (i&7)) & 1;
int32_t k;
k = f(v0+0, v1+0, 8*v->coeffs[ 0+i] + 4*rbit);
k += f(v0+1, v1+1, 8*v->coeffs[256+i] + 4*rbit);
k += f(v0+2, v1+2, 8*v->coeffs[512+i] + 4*rbit);
k += f(v0+3, v1+3, 8*v->coeffs[768+i] + 4*rbit);
k = (2*PARAM_Q-1-k) >> 31;
int32_t v_tmp[4];
v_tmp[0] = ((~k) & v0[0]) ^ (k & v1[0]);
v_tmp[1] = ((~k) & v0[1]) ^ (k & v1[1]);
v_tmp[2] = ((~k) & v0[2]) ^ (k & v1[2]);
v_tmp[3] = ((~k) & v0[3]) ^ (k & v1[3]);
c->coeffs[ 0+i] = (v_tmp[0] - v_tmp[3]) & 3;
c->coeffs[256+i] = (v_tmp[1] - v_tmp[3]) & 3;
c->coeffs[512+i] = (v_tmp[2] - v_tmp[3]) & 3;
c->coeffs[768+i] = ( -k + 2*v_tmp[3]) & 3;
}
}
inline void rec(uint8_t *key, const poly *v, const poly *c)
{
int i;
int32_t tmp[4];
for(i=0;i<32;i++)
key[i] = 0;
for(i=0; i<256; i++)
{
tmp[0] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[ 0+i]) - PARAM_Q * (2*c->coeffs[ 0+i]+c->coeffs[768+i]);
tmp[1] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[256+i]) - PARAM_Q * (2*c->coeffs[256+i]+c->coeffs[768+i]);
tmp[2] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[512+i]) - PARAM_Q * (2*c->coeffs[512+i]+c->coeffs[768+i]);
tmp[3] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[768+i]) - PARAM_Q * ( c->coeffs[768+i]);
key[i>>3] |= LDDecode(tmp[0], tmp[1], tmp[2], tmp[3]) << (i & 7);
}
}
void gen_a(poly *a, const uint8_t *seed, Newhope_Mode mode)
{
std::vector<uint8_t> buf(168*16);
std::unique_ptr<StreamCipher> xof;
if(mode == Newhope_Mode::BoringSSL)
{
xof = StreamCipher::create_or_throw("CTR-BE(AES-128)");
xof->set_key(seed, 16);
xof->set_iv(seed + 16, 16);
}
else
{
xof = StreamCipher::create_or_throw("SHAKE-128");
xof->set_key(seed, NEWHOPE_SEED_BYTES);
}
zeroise(buf);
xof->encrypt(buf);
unsigned int pos=0, ctr=0;
while(ctr < PARAM_N)
{
uint16_t val = (buf[pos] | (static_cast<uint16_t>(buf[pos+1]) << 8)) & 0x3fff; // Specialized for q = 12889
if(val < PARAM_Q)
a->coeffs[ctr++] = val;
pos += 2;
if(pos >= buf.size())
{
zeroise(buf);
xof->encrypt(buf);
pos = 0;
}
}
}
}
// API FUNCTIONS
void newhope_keygen(uint8_t *send, poly *sk, RandomNumberGenerator& rng,
Newhope_Mode mode)
{
poly a, e, r, pk;
uint8_t seed[NEWHOPE_SEED_BYTES];
rng.randomize(seed, NEWHOPE_SEED_BYTES);
gen_a(&a, seed, mode);
poly_getnoise(rng, sk);
poly_ntt(sk);
poly_getnoise(rng, &e);
poly_ntt(&e);
poly_pointwise(&r,sk,&a);
poly_add(&pk,&e,&r);
encode_a(send, &pk, seed);
}
void newhope_sharedb(uint8_t *sharedkey, uint8_t *send, const uint8_t *received,
RandomNumberGenerator& rng,
Newhope_Mode mode)
{
poly sp, ep, v, a, pka, c, epp, bp;
uint8_t seed[NEWHOPE_SEED_BYTES];
decode_a(&pka, seed, received);
gen_a(&a, seed, mode);
poly_getnoise(rng, &sp);
poly_ntt(&sp);
poly_getnoise(rng, &ep);
poly_ntt(&ep);
poly_pointwise(&bp, &a, &sp);
poly_add(&bp, &bp, &ep);
poly_pointwise(&v, &pka, &sp);
poly_invntt(&v);
poly_getnoise(rng, &epp);
poly_add(&v, &v, &epp);
helprec(&c, &v, rng);
encode_b(send, &bp, &c);
rec(sharedkey, &v, &c);
std::unique_ptr<HashFunction> hash(HashFunction::create(
(mode == Newhope_Mode::SHA3) ? "SHA-3(256)" : "SHA-256"));
if(!hash)
throw Exception("NewHope hash function not available");
hash->update(sharedkey, 32);
hash->final(sharedkey);
}
void newhope_shareda(uint8_t *sharedkey, const poly *sk, const uint8_t *received,
Newhope_Mode mode)
{
poly v,bp, c;
decode_b(&bp, &c, received);
poly_pointwise(&v,sk,&bp);
poly_invntt(&v);
rec(sharedkey, &v, &c);
std::unique_ptr<HashFunction> hash(HashFunction::create(
(mode == Newhope_Mode::SHA3) ? "SHA-3(256)" : "SHA-256"));
if(!hash)
throw Exception("NewHope hash function not available");
hash->update(sharedkey, 32);
hash->final(sharedkey);
}
}
#undef PARAM_N
#undef PARAM_Q
| 44.944444 | 129 | 0.631504 | reneme |
2a505c049f9516569b3517a5107ed5ae53a81031 | 15,575 | cpp | C++ | private/windows/shell/regwiz/regwiz/modem.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/windows/shell/regwiz/regwiz/modem.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/windows/shell/regwiz/regwiz/modem.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | /*********************************************************************
Registration Wizard
This file houses a set of functions that use TAPI to access
information about installed modems.
11/15/94 - Tracy Ferrier
(c) 1994-95 Microsoft Corporation
Original source: MOS development
**********************************************************************/
#include <windows.h>
#include <mcx.h>
#include <tapi.h>
#include <devcfg.h>
#include "mcm.h"
#include "resource.h"
#include "ATK_RAS.h"
#include "rw_common.h"
#define pcszDataModem _T("comm/datamodem")
#define pcszWaitLineCreate _T("MCMLineCreate")
#define PTSTR(wszID) GetSz(hInst, wszID)
#define chBackslash '\\'
#define irgMaxSzs 5
// Globals
static _TCHAR szStrTable[irgMaxSzs][256];
static INT iSzTable = 0;
MODEMSTATUS MSDetectModemTAPI(HINSTANCE hInstance);
BOOL DoInstallDialog(HINSTANCE hInstance,int nDialogType);
INT_PTR CALLBACK NoModemDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void SetWaitLineCreateEvent(void);
void CenterDlg(HWND hWnd);
PVOID PVReadRegSt(HINSTANCE hInst, WORD wiszKey, WORD wiszVal);
PVOID PVReadReg(HKEY hKeyM, HINSTANCE hInst, WORD wiszKey, WORD wiszVal);
PTSTR GetSz(HINSTANCE hInst, WORD wszID);
void CALLBACK LineCallback(DWORD hDevice, DWORD dwMessage, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2, DWORD dwParam3);
void CALLBACK CountryLineCallback1(DWORD hDevice, DWORD dwMessage, DWORD dwInstance, DWORD dwParam1,
DWORD dwParam2, DWORD dwParam3)
{
}
MODEMSTATUS MSEnsureModemTAPI(HINSTANCE hInstance,HWND hwnd)
/*********************************************************************
Ensures that a modem is installed and that tapi is setup. if not, user
will be prompted to do so.
Returns:
- kMsModemOk
- kMsModemNotFound
- kMsModemTooSlow
**********************************************************************/
{
MODEMSTATUS msReturnVal = kMsModemNotFound;
do
{
msReturnVal = MSDetectModemTAPI(hInstance);
if (msReturnVal != kMsModemOk)
{
INT_PTR dlgReturn;
int iDialogID = msReturnVal == kMsModemNotFound ? IDD_NOMODEM : IDD_MODEM_TOO_SLOW;
dlgReturn = DialogBox(hInstance, MAKEINTRESOURCE(iDialogID), hwnd,
NoModemDlgProc);
if (!dlgReturn)
{
return kMsModemNotFound;
}
msReturnVal = MSDetectModemTAPI(hInstance);
}
}while (msReturnVal != kMsModemOk);
return (msReturnVal);
}
MODEMSTATUS MSDetectModemTAPI(HINSTANCE hInstance)
/*********************************************************************
Returns:
- kMsModemOk
- kMsModemNotFound
- kMsModemTooSlow
**********************************************************************/
{
HLINEAPP hLineApp;
DWORD dwAPI;
DWORD dwDevice;
BOOL fModem;
const DWORD cMarvelBpsMin = 2400;
MODEMSTATUS msReturnVal = kMsModemNotFound;
DWORD dwIndex = 0;
#ifdef _LOG_IN_FILE
RW_DEBUG <<"\n Inside MSDetectModemTAPI " << flush;
#endif
do
{
fModem = FGetDeviceID(hInstance, &hLineApp, &dwAPI, &dwDevice,dwIndex++);
if (fModem)
{
DWORD dwSpeed;
if (FGetModemSpeed(hInstance, dwDevice,&dwSpeed))
{
if (dwSpeed >= cMarvelBpsMin || 0 == dwSpeed )
{
msReturnVal = kMsModemOk; //modem speed is ok
}
else
{
msReturnVal = kMsModemTooSlow;
}
}
lineShutdown(hLineApp);
}
RW_DEBUG << "\n Index:" << dwIndex << "fModem:"<<fModem <<flush;
}while (fModem == TRUE && msReturnVal != kMsModemOk);
return msReturnVal;
}
BOOL DoInstallDialog(HINSTANCE hInstance,int nDialogType)
/*********************************************************************
This function puts up the "Install new modem" control panel, and
returns only when the user has dismissed the dialog (either after
installing a new modem, or canceling).
Returns: FALSE if an error prevented the dialog from being displayed.
**********************************************************************/
{
_TCHAR szCmdLine[128];
STARTUPINFO si;
PROCESS_INFORMATION pi;
BOOL fControlProcessDone = FALSE;
BOOL fProcessStatus;
//HWND hwndProcess;
if(nDialogType == 1)
{
LoadString(hInstance,IDS_ADDMODEMCOMMAND,szCmdLine,128);
}
else
{
_tcscpy(szCmdLine,_T(""));
LoadString(hInstance,IDS_DIALINGPROPERTIES,szCmdLine,128);
}
si.cb = sizeof(STARTUPINFO);
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.lpTitle = NULL;
si.dwFlags = 0L;
si.cbReserved2 = 0;
si.lpReserved2 = NULL;
fProcessStatus = CreateProcess(NULL,szCmdLine,NULL,NULL,FALSE,
CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_PROCESS_GROUP | NORMAL_PRIORITY_CLASS,NULL,NULL,&si,&pi);
if (fProcessStatus == FALSE)
{
return FALSE;
}
return TRUE;
}
// ======================== NoModemDlgProc ==============================
INT_PTR CALLBACK NoModemDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static fInstallModemDlgStarted = FALSE;
static fDialingPropertiesStarted = FALSE;
HINSTANCE hInstance = (HINSTANCE) GetWindowLongPtr(hWnd,GWLP_HINSTANCE);
switch (uMsg)
{
case WM_INITDIALOG:
CenterDlg(hWnd);
SetForegroundWindow(hWnd);
return fTrue;
case WM_ACTIVATE:
if (wParam != 0 && fInstallModemDlgStarted == TRUE)
{
DoInstallDialog(hInstance,2);
fDialingPropertiesStarted = TRUE;
fInstallModemDlgStarted = FALSE;
}
if (wParam != 0 && fDialingPropertiesStarted == TRUE)
{
fDialingPropertiesStarted = FALSE;
EndDialog(hWnd,fTrue);
}
break;
case WM_CLOSE:
EndDialog(hWnd, fFalse);
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDCANCEL:
EndDialog(hWnd, fFalse);
break;
case IDYES:
DoInstallDialog(hInstance,1);
fInstallModemDlgStarted = TRUE;
EnableWindow(GetDlgItem(hWnd,IDYES),FALSE);
break;
case IDNO:
EndDialog(hWnd, fFalse);
return (fTrue);
}
break;
}
return (fFalse);
}
BOOL FGetModemSpeed(HINSTANCE hInstance, DWORD dwDevice, PDWORD pdwSpeed)
/*********************************************************************
Given a lineDevice ID in the dwDevice parameter, FGetModemSpeed
returns the operating speed of the device represented by that ID.
**********************************************************************/
{
BOOL fRet = fFalse;
PSTR pvs = NULL;
DWORD dwRet;
*pdwSpeed = 0; //7/12/94 UmeshM. Init the variable
Try
{
VARSTRING vs;
vs.dwTotalSize = sizeof(vs);
dwRet = lineGetDevConfig(dwDevice, &vs, pcszDataModem);
if (dwRet != 0 && dwRet != LINEERR_STRUCTURETOOSMALL)
{
//Dprintf("linegetdevconfig = %X\n", dwRet);
Leave;
}
pvs =(char *) LocalAlloc(LPTR, vs.dwNeededSize);
if (!pvs)
Leave;
((VARSTRING *) pvs)->dwTotalSize = vs.dwNeededSize;
dwRet = lineGetDevConfig(dwDevice, (LPVARSTRING) pvs, pcszDataModem);
if (dwRet != 0)
{
//Dprintf("linegetdevconfig = %X\n", dwRet);
Leave;
}
{
LPDEVCFG pDevCfg = (LPDEVCFG)(pvs + sizeof(VARSTRING));
COMMCONFIG *pConf = (COMMCONFIG*)(pvs + sizeof(VARSTRING) + sizeof(DEVCFGHDR));
MODEMSETTINGS *pSet;
pSet = (MODEMSETTINGS*)( ((char*)pConf) + pConf->dwProviderOffset);
//if (FAmIOnline())
// *pdwSpeed = pSet->dwNegotiatedDCERate;
//else
*pdwSpeed = pConf->dcb.BaudRate;
fRet = fTrue;
}
} // Try
Finally
{
if (pvs)
LocalFree(pvs);
}
return (fRet);
} // FGetModemSpeed()
// ======================== FGetDeviceID ==============================
BOOL FGetDeviceID(HINSTANCE hInstance, HLINEAPP *phLineApp, PDWORD pdwAPI, PDWORD pdwDevice, DWORD dwIndex)
{
DWORD dwDevices, iDevice, dwRet;
LINEEXTENSIONID ExtID;
LINEDEVCAPS dc, *pdc;
PSTR pszCL;
DWORD dwLocalIndex;
#ifdef _LOG_IN_FILE
RW_DEBUG <<"\n Inside FGetDeviceID " << flush;
#endif
//Assert(phLineApp && pdwDevice && pdwAPI);
if ((dwRet = lineInitialize(phLineApp, hInstance, (LINECALLBACK) LineCallback, NULL, &dwDevices)) != 0)
{
#ifdef _LOG_IN_FILE
RW_DEBUG <<"\n lineInitialize Error " << dwRet << flush;
#endif
return (fFalse);
}
pszCL = (PSTR) PVReadRegSt(hInstance, iszLoginKey, IDS_CURRENTCOMMDEV);
*pdwDevice = INVALID_PORTID;
dc.dwTotalSize = sizeof(LINEDEVCAPS);
dwLocalIndex = 0;
RW_DEBUG << "dwDevices: " << dwDevices << flush;
for (iDevice = 0; iDevice < dwDevices; iDevice ++)
{
DWORD dwAPILowVersion = 0 << 16;
DWORD dwAPIHighVersion = 3 << 16;
RW_DEBUG << "\n Enter 0" << flush;
dwRet = lineNegotiateAPIVersion(*phLineApp, iDevice, dwAPILowVersion,dwAPIHighVersion, pdwAPI, &ExtID);
dwRet |= lineGetDevCaps(*phLineApp, iDevice, *pdwAPI, 0, &dc);
if (dc.dwMediaModes & LINEMEDIAMODE_DATAMODEM && dwRet == 0)
{
RW_DEBUG << "\ndwIndex:" <<dwIndex<< " dwLocalIndex:" << dwLocalIndex <<flush;
if (dwLocalIndex++ == dwIndex)
{
RW_DEBUG << "\n Enter 2 iDevice:" << iDevice << flush;
if (*pdwDevice == INVALID_PORTID)
*pdwDevice = iDevice;
pdc = (LINEDEVCAPS *) LocalAlloc(LPTR, dc.dwNeededSize);
if (pdc)
{
RW_DEBUG << "\n Enter 3" << flush;
pdc->dwTotalSize = dc.dwNeededSize;
dwRet |= lineGetDevCaps(*phLineApp, iDevice, *pdwAPI, 0, pdc);
if (pdc->dwLineNameSize > 0 && pszCL)
{
RW_DEBUG << "\n Enter 3" << flush;
PSTR pszLineName;
pszLineName = (LPSTR)(pdc) + pdc->dwLineNameOffset;
// Use if specified in registry
if (strcmp(pszCL, pszLineName) == 0)
*pdwDevice = iDevice;
}
LocalFree(pdc);
RW_DEBUG << "\n Exit 3" << flush;
}
RW_DEBUG << "\n Exit 2" << flush;
}
RW_DEBUG << "\n Exit 1" << flush;
}
RW_DEBUG << "\n Exit 0" << flush;
}
if (*pdwDevice == INVALID_PORTID)
{ // no data modem found
#ifdef _LOG_IN_FILE
RW_DEBUG <<"\n lineGetDevCaps returned INVALID_PORTID Error" << flush;
#endif
lineShutdown(*phLineApp);
return (fFalse);
}
return (fTrue);
} // FGetDeviceID()
void CenterDlg(HWND hWnd)
{
HWND hwndOwner;
RECT rcOwner, rcDlg, rc;
if (((hwndOwner = GetParent(hWnd)) == NULL) || IsIconic(hwndOwner) || !IsWindowVisible(hWnd))
hwndOwner = GetDesktopWindow();
GetWindowRect(hwndOwner, &rcOwner);
GetWindowRect(hWnd, &rcDlg);
CopyRect(&rc, &rcOwner);
// Offset the owner and dialog box rectangles so that
// right and bottom values represent the width and
// height, and then offset the owner again to discard
// space taken up by the dialog box.
OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
OffsetRect(&rc, -rc.left, -rc.top);
OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
// The new position is the sum of half the remaining
// space and the owner's original position.
SetWindowPos(hWnd,HWND_TOP, rcOwner.left + (rc.right / 2),
rcOwner.top + (rc.bottom / 2), 0, 0, SWP_NOSIZE);
} // CenterDlg
// ======================== PVReadRegSt ==============================
PVOID PVReadRegSt(HINSTANCE hInst, WORD wiszKey, WORD wiszVal)
{
return (PVReadReg(HKEY_CURRENT_USER, hInst, wiszKey, wiszVal));
} // PVReadRegSt()
// ======================== PVReadReg ==============================
// returns pointer to struct. REMEMBER to free the pointer(LocalFree)
PVOID PVReadReg(HKEY hKeyM, HINSTANCE hInst, WORD wiszKey, WORD wiszVal)
{
HKEY hKey = NULL;
PVOID pVal = NULL;
DWORD dwCb;
BOOL fRead = fFalse;
Try
{
if (RegOpenKey(hKeyM, PTSTR(wiszKey), &hKey) != ERROR_SUCCESS)
Leave;
if (!(RegQueryValueEx(hKey, PTSTR(wiszVal), NULL, NULL, NULL, &dwCb) == ERROR_SUCCESS && dwCb))
Leave;
pVal = LocalAlloc(LPTR, dwCb);
if (pVal == NULL)
Leave;
if (RegQueryValueEx(hKey, PTSTR(wiszVal), NULL,
NULL,(LPBYTE ) pVal, &dwCb) != ERROR_SUCCESS)
Leave;
fRead = fTrue;
}
Finally
{
RegCloseKey(hKey);
if (fRead == fFalse)
{
if(pVal != NULL)
{
LocalFree(pVal);
pVal = NULL;
}
}
}
return (pVal);
} // PVReadReg()
// BEWARE uses static variable.
PTSTR GetSz(HINSTANCE hInst, WORD wszID)
{
PTSTR psz = szStrTable[iSzTable];
iSzTable ++;
if (iSzTable >= irgMaxSzs)
iSzTable = 0;
if (!LoadString(hInst, wszID, psz, 256))
{ // now u could return a error but then everybody will have to check
// the return value
//AssertGLE(0);
*psz = 0;
}
return (psz);
} // GetSz()
void SetWaitLineCreateEvent(void)
{
HANDLE hEvent;
hEvent = OpenEvent(SYNCHRONIZE, fFalse, pcszWaitLineCreate);
if (hEvent)
{
SetEvent(hEvent);
CloseHandle(hEvent);
}
}
void CALLBACK LineCallback(DWORD hDevice, DWORD dwMessage, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2, DWORD dwParam3)
{
switch (dwMessage)
{
case LINE_LINEDEVSTATE:
{
if (dwParam1 == LINEDEVSTATE_REINIT)
{
SetWaitLineCreateEvent();
}
}
break;
}
} // LineCallback
#define MAX_RAS_DEVICES 10
#define SZ_BUF_RET_SZ 256
//
// iModemIndex : Index of Modem Nane required, should be starting from 1 to MAX_RAS_DEVICES
//
//
TCHAR * GetModemDeviceInformation(HINSTANCE hInstance, int iModemIndex)
{
static TCHAR szRetValue[MAX_RAS_DEVICES][SZ_BUF_RET_SZ]
={ _T(""),_T(""),_T(""),
_T(""),_T(""),_T(""),
_T(""),_T(""),_T(""),
_T("")};
static TCHAR szNoModem[] = _T("NOMODEM");
static int iFirstTimeCall=0;
static int nNoofModemDevice = 0;
RASDEVINFO *pdi,*pDevInfo;
DWORD dwSize=0,dwNum=0,dwRet;
int iEntries;
int i;
if( iModemIndex < 1 ) {
return szNoModem;
}
if(iFirstTimeCall == 0 )
{
iFirstTimeCall = 1;
if( ATK_IsRasDllOk() == RAS_DLL_LOADED)
{
dwRet = ATK_RasEnumDevices(NULL,&dwSize,&dwNum);
iEntries = dwSize /sizeof(RASDEVINFO);
pDevInfo = (LPRASDEVINFO)LocalAlloc(LPTR,dwSize);
pdi = pDevInfo;
for(i=0; i< iEntries;i++) {
pdi->dwSize = sizeof(RASDEVINFO);
pdi++;
}
dwRet = ATK_RasEnumDevices(pdi,&dwSize,&dwNum);
if(dwRet == 0)
{
for(i=0; i< iEntries;i++)
{
#ifdef _LOG_IN_FILE
RW_DEBUG << "\n Device Name:"<< ConvertToANSIString(pdi->szDeviceName) << flush;
RW_DEBUG << "\n Device Type:"<< ConvertToANSIString(pdi->szDeviceType) << flush;
#endif
if( !_tcscmp(pdi->szDeviceType, RASDT_Modem) )
{
_tcscpy(szRetValue[nNoofModemDevice],pdi->szDeviceName);
nNoofModemDevice++;
//i=iEntries+1;
}
pdi++;
}
}
else
{
switch(dwRet)
{
case ERROR_BUFFER_TOO_SMALL:
RW_DEBUG <<"\n ERROR_BUFFER_TOO_SMALL"<< flush;
break;
case ERROR_NOT_ENOUGH_MEMORY:
RW_DEBUG <<"\n ERROR_NOT_ENOUGH_MEMORY"<< flush;
break;
case ERROR_INVALID_PARAMETER:
RW_DEBUG <<"\n ERROR_INVALID_PARAMETER"<< flush;
break;
case ERROR_INVALID_USER_BUFFER :
RW_DEBUG <<"\n ERROR_INVALID_USER_BUFFER"<< flush;
break;
default:
RW_DEBUG <<"\n UNKNOWN_ERROR"<< flush;
break;
}
}
LocalFree(pDevInfo);
}
else
{
return szNoModem;
}
}
// Return the modem device name
if( iModemIndex > nNoofModemDevice ) {
return szNoModem;
}else {
return &szRetValue[iModemIndex-1][0];
}
}
| 25.36645 | 126 | 0.60443 | King0987654 |
2a51b855bb274eaff678f9a4d1ea714d70f276e2 | 1,091 | cpp | C++ | 28_New_delete/main.cpp | SokolovVadim/AdvancedCpp11 | b2cdd70b3c8ec25f2ae66aa0a642ed8c069da4b2 | [
"MIT"
] | null | null | null | 28_New_delete/main.cpp | SokolovVadim/AdvancedCpp11 | b2cdd70b3c8ec25f2ae66aa0a642ed8c069da4b2 | [
"MIT"
] | null | null | null | 28_New_delete/main.cpp | SokolovVadim/AdvancedCpp11 | b2cdd70b3c8ec25f2ae66aa0a642ed8c069da4b2 | [
"MIT"
] | null | null | null | #include <iostream>
void* operator new(std::size_t size)/* throw(std::bad_alloc)*/
{
while(true)
{
void* pMem = malloc(size);
if(pMem)
return pMem;
std::new_handler Handler = std::set_new_handler(0); // get new handler
std::set_new_handler(Handler);
if(Handler)
(*Handler)(); // Invoke new handler
else
throw std::bad_alloc();
}
}
class Dog
{
static void customDeleteForDog()
{}
public:
static void operator delete(void* pMemory) throw()
{
std::cout << "I'm deleting a dog\n";
customDeleteForDog();
free(pMemory);
}
virtual ~Dog() {}
};
class YellowDog: public Dog
{
static void customDeleteForYellowDog()
{}
public:
static void operator delete(void* pMemory) throw()
{
std::cout << "I'm deleting a YellowDog\n";
customDeleteForYellowDog();
free(pMemory);
}
};
// --------------------------------------------------------------------
int main()
{
/* int* ptr = (int*)operator new(10);
delete ptr;*/
Dog* pd = new Dog();
delete pd;
YellowDog* yd = new YellowDog();
delete yd;
Dog* pd1 = new YellowDog();
delete pd1;
return 0;
}
| 16.784615 | 72 | 0.609533 | SokolovVadim |
2a5579b49e8dcaecd38d4cb1636e32896d144f31 | 149 | hpp | C++ | RPC/GpApiRPC.hpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | RPC/GpApiRPC.hpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | RPC/GpApiRPC.hpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "RqRs/GpApiRqRs.hpp"
#include "Client/GpApiClient.hpp"
#include "Server/GpApiServer.hpp"
#include "GpApiVoidDesc.hpp"
| 18.625 | 34 | 0.738255 | ITBear |
2a58dfc89d20ff1d53638ffe6f7f9e24b9ed8eb4 | 48,690 | cpp | C++ | Intersectable.cpp | jambolo/Math | 470d58579a9aa18930f419f00332f10a7a2fd008 | [
"MIT"
] | null | null | null | Intersectable.cpp | jambolo/Math | 470d58579a9aa18930f419f00332f10a7a2fd008 | [
"MIT"
] | null | null | null | Intersectable.cpp | jambolo/Math | 470d58579a9aa18930f419f00332f10a7a2fd008 | [
"MIT"
] | null | null | null | #include "Intersectable.h"
#include "Box.h"
#include "Cone.h"
#include "Frustum.h"
#include "Line.h"
#include "MyMath.h"
#include "Plane.h"
#include "Point.h"
#include "Sphere.h"
#pragma warning( disable : 4100 ) // 'identifier' : unreferenced formal parameter
//! @param a The point to test.
//! @param b The point to test.
Intersectable::Result Intersectable::Intersects(Point const & a, Point const & b)
{
if ( MyMath::IsRelativelyCloseTo(a.value_.m_X, b.value_.m_X)
&& MyMath::IsRelativelyCloseTo(a.value_.m_Y, b.value_.m_Y)
&& MyMath::IsRelativelyCloseTo(a.value_.m_Z, b.value_.m_Z))
{
return INTERSECTS;
}
else
return NO_INTERSECTION;
}
//! @param point The point to test.
//! @param line The line to test.
//!
//! @return Returns NO_INTERSECTION or INTERSECTS
Intersectable::Result Intersectable::Intersects(Point const & point, Line const & line)
{
// // The point is on the line if the distance is close to 0
//
// return MyMath::IsCloseToZero( line.Distance( point ) );
//
// Yes, but also ...
// point is on the line if the distance from m_B to point is the same as the distance from m_B to the projection
// of point onto the line (which implies distance squared is a valid test, too).
Vector3 const pb = point.value_ - line.m_B; // Vector from m_B to point
float const d = Dot(pb, line.m_M); // Distance from m_B to the projection
if (MyMath::IsRelativelyCloseTo(d * d, pb.Length2()))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test.
//! @param ray The ray to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Ray const & ray)
{
// // The point is on the line if the distance is close to 0
//
// return MyMath::IsCloseToZero( ray.Distance( point ) );
//
// Yes, but also like the line ...
// point is on the ray if the distance from m_B to point is the same as the distance from m_B to the projection
// of point onto the line (which implies distance squared is a valid test, too), and t >= 0. Note that t is the
// distance from m_B to the projection of point onto the line. Zoinks!
Vector3 const pb = point.value_ - ray.m_B; // Vector from m_B to point
float const t = Dot(pb, ray.m_M); // Also, distance from m_B to the projection
if (t >= 0.f && MyMath::IsRelativelyCloseTo(t * t, pb.Length2()))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param segment The segment to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Segment const & segment)
{
// // The point is on the segment if the distance is close to 0
//
// return MyMath::IsCloseToZero( segment.Distance( point ) );
//
// Yes, but also like the line ...
// point is on the ray if the distance from m_B to point is the same as the distance from m_B to the projection
// of point onto the line (which implies distance squared is a valid test, too), and 0 <= t <= 1. Note that the
// length of m_M is the length of the segment in this case. Yowzer! That means the math is simple but it is not
// so obvious.
Vector3 const pb = point.value_ - segment.m_B; // Vector from m_B to point
float const s2 = segment.m_M.Length2(); // Length of segment squared
float const a = Dot(pb, segment.m_M); // t * s2
if (a >= 0.f && a <= s2 && MyMath::IsRelativelyCloseTo(a * a, pb.Length2()))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param plane The plane to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Plane const & plane)
{
if (MyMath::IsCloseToZero(Distance(point, plane)))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Point const & point, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param sphere The sphere to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Sphere const & sphere)
{
float const d2 = (point.value_ - sphere.m_C).Length2(); // Distance from center to point squared
if (d2 <= sphere.m_R * sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param cone The cone to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Cone const & cone)
{
Vector3 const p = point.value_ - cone.m_V;
float const ddp = Dot(cone.m_D, p);
if (ddp >= 0.f && ddp * ddp >= p.Length2() * cone.m_A * cone.m_A)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param aabox The AA box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, AABox const & aabox)
{
Vector3 const xpoint = point.value_ - aabox.m_Position;
if ( 0 <= xpoint.m_X && xpoint.m_X <= aabox.m_Scale.m_X
&& 0 <= xpoint.m_Y && xpoint.m_Y <= aabox.m_Scale.m_Y
&& 0 <= xpoint.m_Z && xpoint.m_Z <= aabox.m_Scale.m_Z)
{
return INTERSECTS;
}
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param box The oriented box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Box const & box)
{
Vector3 const xpoint = box.m_InverseOrientation * (point.value_ - box.m_Position);
if ( 0 <= xpoint.m_X && xpoint.m_X <= box.m_Scale.m_X
&& 0 <= xpoint.m_Y && xpoint.m_Y <= box.m_Scale.m_Y
&& 0 <= xpoint.m_Z && xpoint.m_Z <= box.m_Scale.m_Z)
{
return INTERSECTS;
}
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param frustum The frustum to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Frustum const & frustum)
{
for (auto const & side : frustum.sides_)
{
if (side.DirectedDistance(point) > 0.f)
return NO_INTERSECTION;
}
return INTERSECTS;
}
//! @param a The line to test
//! @param b The line to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & a, Line const & b)
{
if (MyMath::IsCloseToZero(Distance(a, b)))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param ray The ray to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Ray const & ray)
{
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param segment The segment to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Segment const & segment)
{
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param plane The plane to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, Plane const & plane)
{
if (!MyMath::IsCloseToZero(Dot(line.m_M, plane.m_N)))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param sphere The sphere to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, Sphere const & sphere)
{
if (Distance(sphere.m_C, line) <= sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param aabox The AA box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, AABox const & aabox)
{
Vector3 const box_max = aabox.m_Position + aabox.m_Scale; // Convenience and speed
// If the line intersects the yz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(line.m_M.m_X))
{
// Check the min yz plane
float const umin = (aabox.m_Position.m_X - line.m_B.m_X) / line.m_M.m_X;
float const ymin = line.m_B.m_Y + umin * line.m_M.m_Y;
float const zmin = line.m_B.m_Z + umin * line.m_M.m_Z;
if ( ymin >= aabox.m_Position.m_Y && ymin <= box_max.m_Y
&& zmin >= aabox.m_Position.m_Z && zmin <= box_max.m_Z)
{
return INTERSECTS;
}
// Check the max yz plane
float const umax = (box_max.m_X - line.m_B.m_X) / line.m_M.m_X;
float const ymax = line.m_B.m_Y + umax * line.m_M.m_Y;
float const zmax = line.m_B.m_Z + umax * line.m_M.m_Z;
if ( ymax >= aabox.m_Position.m_Y && ymax <= box_max.m_Y
&& zmax >= aabox.m_Position.m_Z && zmax <= box_max.m_Z)
{
return INTERSECTS;
}
}
// If the line intersects the xz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(line.m_M.m_Y))
{
// Check the min xz plane
float const umin = (aabox.m_Position.m_Y - line.m_B.m_Y) / line.m_M.m_Y;
float const xmin = line.m_B.m_X + umin * line.m_M.m_X;
float const zmin = line.m_B.m_Z + umin * line.m_M.m_Z;
if ( xmin >= aabox.m_Position.m_X && xmin <= box_max.m_X
&& zmin >= aabox.m_Position.m_Z && zmin <= box_max.m_Z)
{
return INTERSECTS;
}
// Check the max xz plane
float const umax = (box_max.m_Y - line.m_B.m_Y) / line.m_M.m_Y;
float const xmax = line.m_B.m_X + umax * line.m_M.m_X;
float const zmax = line.m_B.m_Z + umax * line.m_M.m_Z;
if ( xmax >= aabox.m_Position.m_X && xmax <= box_max.m_X
&& zmax >= aabox.m_Position.m_Z && zmax <= box_max.m_Z)
{
return INTERSECTS;
}
}
// If the line intersects the xy planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(line.m_M.m_Z))
{
// Check the min xy plane
float const umin = (aabox.m_Position.m_Z - line.m_B.m_Z) / line.m_M.m_Z;
float const xmin = line.m_B.m_X + umin * line.m_M.m_X;
float const ymin = line.m_B.m_Y + umin * line.m_M.m_Y;
if ( xmin >= aabox.m_Position.m_X && xmin <= box_max.m_X
&& ymin >= aabox.m_Position.m_Y && ymin <= box_max.m_Y)
{
return INTERSECTS;
}
// Check the max xy plane
float const umax = (box_max.m_Z - line.m_B.m_Z) / line.m_M.m_Z;
float const xmax = line.m_B.m_X + umax * line.m_M.m_X;
float const ymax = line.m_B.m_Y + umax * line.m_M.m_Y;
if ( xmax >= aabox.m_Position.m_X && xmax <= box_max.m_X
&& ymax >= aabox.m_Position.m_Y && ymax <= box_max.m_Y)
{
return INTERSECTS;
}
}
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param box The oriented box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, Box const & box)
{
// Transform the line into the box's space (except for scale)
Vector3 const tb = box.m_InverseOrientation * (line.m_B - box.m_Position);
Vector3 const tm = box.m_InverseOrientation * line.m_M;
// If the line intersects the yz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(tm.m_X))
{
// Check the min yz plane
float const umin = (0.f - tb.m_X) / tm.m_X;
float const ymin = tb.m_Y + umin * tm.m_Y;
float const zmin = tb.m_Z + umin * tm.m_Z;
if (ymin >= 0.f && ymin <= box.m_Scale.m_Y && zmin >= 0.f && zmin <= box.m_Scale.m_Z)
return INTERSECTS;
// Check the max yz plane
float const umax = (box.m_Scale.m_X - tb.m_X) / tm.m_X;
float const ymax = tb.m_Y + umax * tm.m_Y;
float const zmax = tb.m_Z + umax * tm.m_Z;
if (ymax >= 0.f && ymax <= box.m_Scale.m_Y && zmax >= 0.f && zmax <= box.m_Scale.m_Z)
return INTERSECTS;
}
// If the line intersects the xz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(tm.m_Y))
{
// Check the min xz plane
float const umin = (0.f - tb.m_Y) / tm.m_Y;
float const xmin = tb.m_X + umin * tm.m_X;
float const zmin = tb.m_Z + umin * tm.m_Z;
if (xmin >= 0.f && xmin <= box.m_Scale.m_X && zmin >= 0.f && zmin <= box.m_Scale.m_Z)
return INTERSECTS;
// Check the max xz plane
float const umax = (box.m_Scale.m_Y - tb.m_Y) / tm.m_Y;
float const xmax = tb.m_X + umax * tm.m_X;
float const zmax = tb.m_Z + umax * tm.m_Z;
if (xmax >= 0.f && xmax <= box.m_Scale.m_X && zmax >= 0.f && zmax <= box.m_Scale.m_Z)
return INTERSECTS;
}
// If the line intersects the xy planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(tm.m_Z))
{
// Check the min xy plane
float const umin = (0.f - tb.m_Z) / tm.m_Z;
float const xmin = tb.m_X + umin * tm.m_X;
float const ymin = tb.m_Y + umin * tm.m_Y;
if (xmin >= 0.f && xmin <= box.m_Scale.m_X && ymin >= 0.f && ymin <= box.m_Scale.m_Y)
return INTERSECTS;
// Check the max xy plane
float const umax = (box.m_Scale.m_Z - tb.m_Z) / tm.m_Z;
float const xmax = tb.m_X + umax * tm.m_X;
float const ymax = tb.m_Y + umax * tm.m_Y;
if (xmax >= 0.f && xmax <= box.m_Scale.m_X && ymax >= 0.f && ymax <= box.m_Scale.m_Y)
return INTERSECTS;
}
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The ray to test.
//! @param b The ray to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & a, Ray const & b)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param segment The segment to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Segment const & segment)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param plane The plane to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Plane const & plane)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param sphere The sphere to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Box const & box)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The line segment to test
//! @param b The line segment to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Segment const & a, Segment const & b)
{
// First of all, reject if the AABoxes don't intersect.
if (Intersectable::Intersects(AABox(a.m_B, a.m_M), AABox(b.m_B, b.m_M)) == NO_INTERSECTION)
return NO_INTERSECTION;
// The line segments a and b intersect if 0<=s<=1 and 0<=t<=1 when a.m_B + s * a.m_M == b.m_B + t * b.m_M.
//
// Solving for s and t:
//
// a.m_B + s * a.m_M = b.m_B + t * b.m_M
// a.m_B - b.m_B = t * b.m_M - s * a.m_M
// c = t * b.m_M - s * a.m_M, c = a.m_B - b.m_B
//
// c.x = t * b.m_M.m_X - s * a.m_M.m_X
// c.y = t * b.m_M.m_Y - s * a.m_M.m_Y
// c.z = t * b.m_M.m_Z - s * a.m_M.m_Z
//
// sxy = ( c.x * b.m_M.m_Y - c.y * b.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Y - b.m_M.m_Y * a.m_M.m_X )
// txy = ( c.x * a.m_M.m_Y - c.y * a.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Y - b.m_M.m_Y * a.m_M.m_X )
// sxz = ( c.x * b.m_M.m_Z - c.z * b.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_X )
// txz = ( c.x * a.m_M.m_Z - c.z * a.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_X )
// syz = ( c.y * b.m_M.m_Z - c.z * b.m_M.m_Y ) / ( b.m_M.m_Y * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_Y )
// tyz = ( c.y * a.m_M.m_Z - c.z * a.m_M.m_Y ) / ( b.m_M.m_Y * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_Y )
//
// The segments intersect if sxy == sxz == syz and txy == txz == tyz, and 0<=s<=1 and 0<=t<=1, s = sxy and t = txy.
//
// Ideally only two of each of the three computations need to be checked, because the third is redundant. Rather
// than just picking two, all three are checked and the segments are considered to intersect if two of the three
// pass. Also, the division is never done -- it is integrated into the range test. These steps avoid precision
// problems and divide-by-0 when one or both segments are (nearly) parallel to an axis.
Vector3 const c = a.m_B - b.m_B;
int pass = 0; // Number of tests that pass
// Check if they intersect in the xy plane.
float const sxy = (c.m_X * b.m_M.m_Y - c.m_Y * b.m_M.m_X);
float const txy = (c.m_X * a.m_M.m_Y - c.m_Y * a.m_M.m_X);
float const dxy = b.m_M.m_X * a.m_M.m_Y - b.m_M.m_Y * a.m_M.m_X;
if (dxy > 0.f)
{
if (sxy >= 0.f && sxy <= dxy && txy >= 0 && txy <= dxy)
++pass;
}
else
{
if (sxy <= 0.f && sxy >= dxy && txy <= 0 && txy >= dxy)
++pass;
}
// Check if they intersect in the xz plane.
float const sxz = (c.m_X * b.m_M.m_Z - c.m_Z * b.m_M.m_X);
float const txz = (c.m_X * a.m_M.m_Z - c.m_Z * a.m_M.m_X);
float const dxz = b.m_M.m_X * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_X;
if (dxz > 0.f)
{
if (sxz >= 0.f && sxz <= dxz && txz >= 0 && txz <= dxz)
++pass;
}
else
{
if (sxz <= 0.f && sxz >= dxz && txz <= 0 && txz >= dxz)
++pass;
}
// Check if they intersect in the yz plane.
// The third test is needed only if one of the previous passed and one failed.
if (pass == 1)
{
float const syz = (c.m_Y * b.m_M.m_Z - c.m_Z * b.m_M.m_Y);
float const tyz = (c.m_Y * a.m_M.m_Z - c.m_Z * a.m_M.m_Y);
float const dyz = b.m_M.m_Y * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_Y;
if (dyz > 0.f)
{
if (syz >= 0.f && syz <= dyz && tyz >= 0 && tyz <= dyz)
++pass;
}
else
{
if (syz <= 0.f && syz >= dyz && tyz <= 0 && tyz >= dyz)
++pass;
}
}
if (pass >= 2)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param plane The plane to test.
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Segment const & segment, Plane const & plane)
{
float const da = plane.DirectedDistance(segment.m_B);
float const db = plane.DirectedDistance(segment.m_B + segment.m_M);
if (MyMath::IsCloseToZero(da) || MyMath::IsCloseToZero(db) || da * db < 0.f)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param sphere The sphere to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param aabox The line AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Box const & box)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param frustum The line frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The plane to test
//! @param b The plane to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Plane const & a, Plane const & b)
{
float const dot = Dot(a.m_N, b.m_N);
if (!MyMath::IsCloseTo(fabsf(dot), 1.0))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param sphere The sphere to test.
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Plane const & plane, Sphere const & sphere)
{
if (Distance(sphere.m_C, plane) <= sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param aabox The AA box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Plane const & plane, AABox const & aabox)
{
HalfSpace const halfspace(plane);
if (Intersects(halfspace, aabox) == INTERSECTS)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Box const & box)
{
// // Plane equation: z = - ( plane.m_D + plane.m_N.m_X * x + plane.m_N.m_Y * y ) / plane.m_N.m_Z
// if ( !MyMath::IsCloseToZero( plane.m_N.m_X )
// {
// float const yy = plane.m_N.m_X * box.m_X;
// float const yyh = plane.m_N.m_X * ( box.m_X + box.m_W );
// float const zz = plane.m_N.m_Z * box.m_Z;
// float const zzd = plane.m_N.m_Z * ( box.m_Z + box.m_D );
// float const xw = box.m_X + box.m_W;
// float x;
// x = - ( plane.m_D + yy + zz ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// x = - ( plane.m_D + yyh + zz ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// x = - ( plane.m_D + yy + zzd ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// x = - ( plane.m_D + yyh + zzd ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// }
// if ( !MyMath::IsCloseToZero( plane.m_N.m_Y )
// {
// float const xx = plane.m_N.m_X * box.m_X;
// float const xxw = plane.m_N.m_X * ( box.m_X + box.m_W );
// float const zz = plane.m_N.m_Z * box.m_Z;
// float const zzd = plane.m_N.m_Z * ( box.m_Z + box.m_D );
// float const yh = box.m_Y + box.m_H;
// float y;
// y = - ( plane.m_D + xx + zz ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// y = - ( plane.m_D + xxw + zz ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// y = - ( plane.m_D + xx + zzd ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// y = - ( plane.m_D + xxw + zzd ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// }
// if ( !MyMath::IsCloseToZero( plane.m_N.m_Z )
// {
// float const xx = plane.m_N.m_X * box.m_X;
// float const xxw = plane.m_N.m_X * ( box.m_X + box.m_W );
// float const yy = plane.m_N.m_Y * box.m_Y;
// float const yyh = plane.m_N.m_Y * ( box.m_Y + box.m_H );
// float const zd = box.m_Z + box.m_D;
// float z;
// z = - ( plane.m_D + xx + yy ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// z = - ( plane.m_D + xxw + yy ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// z = - ( plane.m_D + xx + yyh ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// z = - ( plane.m_D + xxw + yyh ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// }
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The poly to test.
//! @param b The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & a, Poly const & b)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param sphere The sphere to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Box const & box)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The sphere to test.
//! @param b The sphere to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
Intersectable::Result Intersectable::Intersects(Sphere const & a, Sphere const & b)
{
float const dc2 = (a.m_C - b.m_C).Length2();
if (dc2 <= (a.m_R + b.m_R) * (a.m_R + b.m_R))
{
if (dc2 <= (a.m_R - b.m_R) * (a.m_R - b.m_R))
{
if (a.m_R < b.m_R)
return ENCLOSED_BY;
else
return ENCLOSES;
}
else
{
return INTERSECTS;
}
}
else
{
return NO_INTERSECTION;
}
}
//! @param sphere The sphere to test.
//! @param cone The cone to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
//!
//! @warning Not sure if this works
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, Cone const & cone)
{
float const c2 = cone.m_A * cone.m_A;
Vector3 const v1 = sphere.m_C - cone.m_V;
Vector3 const v2 = sqrtf(1.f - c2) * v1 + sphere.m_R * cone.m_D;
float const ddv2 = Dot(cone.m_D, v2);
if (ddv2 < 0.f || ddv2 * ddv2 < v2.Length2() * c2)
return NO_INTERSECTION;
float const ddv1 = Dot(cone.m_D, v1);
float const ld2 = v1.Length2();
if (ddv1 > 0.f || ddv1 * ddv1 < ld2 * (1.f - c2) || ld2 <= sphere.m_R * sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param sphere The sphere to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param sphere The sphere to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, Box const & box)
{
return NO_INTERSECTION;
}
//! @param sphere The sphere to test.
//! @param frustum The frustum to test
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
//!
//! @warning This test returns false positives near the corners of the frustum.
//! @warning This function returns INTERSECTS when it should return ENCLOSES.
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, Frustum const & frustum)
{
Result intersection = ENCLOSED_BY;
for (auto const & side : frustum.sides_)
{
float const d = side.DirectedDistance(sphere.m_C);
if (d > sphere.m_R)
return NO_INTERSECTION;
if (d > -sphere.m_R)
intersection = INTERSECTS;
}
return intersection;
}
//! @param a The cone to test.
//! @param b The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & a, Cone const & b)
{
return NO_INTERSECTION;
}
//! @param cone The cone to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & cone, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param cone The cone to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & cone, Box const & box)
{
return NO_INTERSECTION;
}
//! @param cone The cone to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & cone, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The AABox to test.
//! @param b The AABox to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
Intersectable::Result Intersectable::Intersects(AABox const & a, AABox const & b)
{
float const ax0 = a.m_Position.m_X;
float const ay0 = a.m_Position.m_Y;
float const az0 = a.m_Position.m_Z;
float const ax1 = a.m_Position.m_X + a.m_Scale.m_X;
float const ay1 = a.m_Position.m_Y + a.m_Scale.m_Y;
float const az1 = a.m_Position.m_Z + a.m_Scale.m_Z;
float const bx0 = b.m_Position.m_X;
float const by0 = b.m_Position.m_Y;
float const bz0 = b.m_Position.m_Z;
float const bx1 = b.m_Position.m_X + b.m_Scale.m_X;
float const by1 = b.m_Position.m_Y + b.m_Scale.m_Y;
float const bz1 = b.m_Position.m_Z + b.m_Scale.m_Z;
assert(a.m_Scale.m_X >= 0.0f);
assert(a.m_Scale.m_Y >= 0.0f);
assert(a.m_Scale.m_Z >= 0.0f);
assert(b.m_Scale.m_X >= 0.0f);
assert(b.m_Scale.m_Y >= 0.0f);
assert(b.m_Scale.m_Z >= 0.0f);
if (ax0 <= bx1 && bx0 <= ax1 && ay0 <= by1 && by0 <= ay1 && az0 <= bz1 && bz0 <= az1)
{
if (bx0 <= ax0 && ax1 <= bx1 && by0 <= ay0 && ay1 <= by1 && bz0 <= az0 && az1 <= bz1)
return ENCLOSED_BY;
else if (ax0 <= bx0 && bx1 <= ax1 && ay0 <= by0 && by1 <= ay1 && az0 <= bz0 && bz1 <= az1)
return ENCLOSES;
else
return INTERSECTS;
}
else
{
return NO_INTERSECTION;
}
}
//! @param aabox The AABox to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(AABox const & aabox, Box const & box)
{
return NO_INTERSECTION;
}
//! @param aabox The AABox to test.
//! @param frustum The frustum to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, or ENCLOSED_BY
//!
//! @warning Returns INTERSECTS when it should return ENCLOSES.
Intersectable::Result Intersectable::Intersects(AABox const & aabox, Frustum const & frustum)
{
// from Moller, Thomas. Realtime Rendering, 2nd Ed., pp. 612-3
//
// The box intersects the frustum if it is not in front of any of the planes of the frustum. The box is enclosed by the frustum
// if none of its vertexes is in front of any of the planes
// of the frustum.
bool intersectsAnyPlane = false;
for (auto const & side : frustum.sides_)
{
Result ic = Intersects(HalfSpace(side), aabox);
if (ic == NO_INTERSECTION)
return NO_INTERSECTION;
if (ic == INTERSECTS)
intersectsAnyPlane = true;
}
// Since it is not completely outside the frustum, if it intersects any plane then it intersects the frustum.
// Otherwise it is completely inside.
if (intersectsAnyPlane)
return INTERSECTS;
else
return ENCLOSED_BY;
}
//! @param a The oriented box to test.
//! @param b The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Box const & a, Box const & b)
{
return NO_INTERSECTION;
}
//! @param box The oriented box to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Box const & box, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The frustum to test.
//! @param b The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Frustum const & a, Frustum const & b)
{
return NO_INTERSECTION;
}
//! @param point point to test
//! @param halfspace halfspace to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, HalfSpace const & halfspace)
{
if (halfspace.m_Plane.DirectedDistance(point) <= 0.0f)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line line to test
//! @param halfspace halfspace to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, HalfSpace const & halfspace)
{
if (MyMath::IsCloseToZero(Dot(line.m_M, halfspace.m_Plane.m_N)))
return Intersects(Point(line.m_B), halfspace);
else
return INTERSECTS;
}
//! @param ray ray to test
//! @param halfspace halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, HalfSpace const & halfspace)
{
return NO_INTERSECTION;
}
//! @param segment line segment to test
//! @param halfspace halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, HalfSpace const & halfspace)
{
return NO_INTERSECTION;
}
//! @param plane plane to test
//! @param halfspace halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, HalfSpace const & halfspace)
{
return NO_INTERSECTION;
}
//! @param a halfspace to test
//! @param b halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & a, HalfSpace const & b)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param poly poly to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param sphere sphere to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param cone cone to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param aabox AA box to test
//!
//! @return Returns NO_INTERSECTION, INTERSECTS or ENCLOSES.
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, AABox const & aabox)
{
// from Moller, Thomas. Realtime Rendering, 2nd Ed., pp. 586-8
//
// The box intersects the plane if at least one of the vertexes of the box is not on the same side as the
// one of the others. An optimization is to test only two vertexes along the diagonal most closely aligned
// with the plane's normal.
Point p0;
Point p1;
// Find the diagonal of the box (with endpoints p0 and p1) most closely aligned with the plane's normal
if (halfspace.m_Plane.m_N.m_X >= 0.0f)
{
p0.value_.m_X = aabox.m_Position.m_X;
p1.value_.m_X = aabox.m_Position.m_X + aabox.m_Scale.m_X;
}
else
{
p0.value_.m_X = aabox.m_Position.m_X + aabox.m_Scale.m_X;
p1.value_.m_X = aabox.m_Position.m_X;
}
if (halfspace.m_Plane.m_N.m_Y >= 0.0f)
{
p0.value_.m_Y = aabox.m_Position.m_Y;
p1.value_.m_Y = aabox.m_Position.m_Y + aabox.m_Scale.m_Y;
}
else
{
p0.value_.m_Y = aabox.m_Position.m_Y + aabox.m_Scale.m_Y;
p1.value_.m_Y = aabox.m_Position.m_Y;
}
if (halfspace.m_Plane.m_N.m_Z >= 0.0f)
{
p0.value_.m_Z = aabox.m_Position.m_Z;
p1.value_.m_Z = aabox.m_Position.m_Z + aabox.m_Scale.m_Z;
}
else
{
p0.value_.m_Z = aabox.m_Position.m_Z + aabox.m_Scale.m_Z;
p1.value_.m_Z = aabox.m_Position.m_Z;
}
// If p0 is in front of the plane then the box is outside the half-space. If p1 is behind the plane then the
// box is enclosed by the half-space. Otherwise, the box intersects the plane. Other cases do not need to be
// considered because in the direction of the normal p1 is always greater than p0.
if (halfspace.m_Plane.DirectedDistance(p0) > 0.0f)
return NO_INTERSECTION;
else if (halfspace.m_Plane.DirectedDistance(p1) < 0.0f)
return ENCLOSES;
else
return INTERSECTS;
}
//! @param halfspace halfspace to test
//! @param box oriented box to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Box const & box)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param frustum frustum to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The line to test.
//! @param b The line to test.
//! @param ps The place to store the parameter for line @a a where the intersection occurs.
//! @param pt The place to store the parameter for line @a b where the intersection occurs.
//!
//! @return Number of intersections
int Intersectable::Intersection(Line const & a, Line const & b, float * ps, float * pt)
{
Vector3 const n = Cross(a.m_M, b.m_M);
Vector3 const ab = b.m_B - a.m_B;
// If the lines are parallel, then there are either 0 or infinite intersections ...
if (MyMath::IsCloseToZero(n.Length2(), 2. * MyMath::DEFAULT_FLOAT_TOLERANCE))
{
float const d = Dot(ab, a.m_M);
if (MyMath::IsRelativelyCloseTo(ab.Length2(), d * d, 2. * MyMath::DEFAULT_FLOAT_TOLERANCE))
return std::numeric_limits<int>::max(); // Co-linear, return infinity
else
return 0; // No intersection, return 0
}
// ... they are not parallel but if the distance between them is > 0 ...
else if (!MyMath::IsCloseToZero(Dot(n, ab)))
{
return 0; // No intersection, return 0
}
// ... otherwise, they intersect at a single point ...
else
{
// Source: http://www.flipcode.com/geometry/gprimer2_issue02.shtml
// Use the minor with largest determinant to maintain precision and prevent divide-by-0
if (fabs(n.m_Z) > fabs(n.m_X) && fabs(n.m_Z) > fabs(n.m_Y))
{
*ps = (ab.m_X * b.m_M.m_Y - ab.m_Y * b.m_M.m_X) / n.m_Z;
*pt = -(ab.m_X * a.m_M.m_Y - ab.m_Y * a.m_M.m_X) / n.m_Z;
}
else if (fabs(n.m_X) > fabs(n.m_Y))
{
*ps = (ab.m_Y * b.m_M.m_Z - ab.m_Z * b.m_M.m_Y) / n.m_X;
*pt = -(ab.m_Y * a.m_M.m_Z - ab.m_Z * a.m_M.m_Y) / n.m_X;
}
else
{
*ps = (ab.m_Z * b.m_M.m_X - ab.m_X * b.m_M.m_Z) / n.m_Y;
*pt = -(ab.m_Z * a.m_M.m_X - ab.m_X * a.m_M.m_Z) / n.m_Y;
}
return 1; // 1 intersection, return 1
}
}
//! @param a The line to test.
//! @param b The line to test.
//! @param pi The place to store the point of the intersection
//!
//! @return The number of intersections.
int Intersectable::Intersection(Line const & a, Line const & b, Point * pi)
{
float t, u;
int const n = Intersection(a, b, &t, &u);
if (n == 1)
*pi = a.m_M * t + a.m_B;
return n;
}
//! @param a The line segment to test.
//! @param b The line segment to test.
//! @param pi The place to store the point of the intersection (if the intersection is a point)
//!
//! @return The number of intersections.
int Intersectable::Intersection(Segment const & a, Segment const & b, Point * pi)
{
float t, u;
int const n = Intersection(Line(a.m_M, a.m_B), Line(b.m_M, b.m_B), &t, &u);
if (n == 1)
{
t *= a.m_M.ILength();
u *= b.m_M.ILength();
if (t < 0.f || t > 1.f || u < 0.f || u > 1.f)
return 0;
*pi = a.m_M * t + a.m_B;
}
return n;
}
//! @param line The line to test.
//! @param plane The plane to test.
//! @param pt Where to store the line's value of t at the intersection.
//!
//! @return Number of intersections
int Intersectable::Intersection(Line const & line, Plane const & plane, float * pt)
{
float const dot = Dot(line.m_M, plane.m_N);
float const distance = Distance(line.m_B, plane);
// If the line and the plane are parallel then there are 0 or > 1 intersections
if (MyMath::IsCloseToZero(dot))
{
if (MyMath::IsCloseToZero(distance))
return std::numeric_limits<int>::max(); // Line is co-planar
else
return 0; // Line does not intersect
}
*pt = -distance / dot;
return 1; // 1 intersection
}
//! @param line The line to test.
//! @param plane The plane to test.
//! @param pi The place to store the point of the intersection (if the intersection is a point)
//!
//! @return Number of intersections
int Intersectable::Intersection(Line const & line, Plane const & plane, Point * pi)
{
float t;
int const n = Intersection(line, plane, &t);
if (n == 1)
*pi = line.m_M * t + line.m_B;
return n;
}
//! @param a The plane to test.
//! @param b The plane to test.
//! @param pi The place to store the intersection (if the intersection is a line)
//!
//! @return Number of intersections
int Intersectable::Intersection(Plane const & a, Plane const & b, Line * pi)
{
float const n1n2 = Dot(a.m_N, b.m_N);
// If the Cross product of the normals is close to 0, the planes are parallel and possibly coincident
if (MyMath::IsCloseTo(fabsf(n1n2), 1.))
{
// The planes are parallel, if the D values are the same, the planes are coincident, otherwise the do
// not intersect
if (MyMath::IsRelativelyCloseTo(a.m_D, b.m_D))
return std::numeric_limits<int>::max();
else
return 0;
}
else
{
// p = ( c1 * N1 + c2 * N2 ) + u * ( N1 ^ N2 )
float const n1n1 = Dot(a.m_N, a.m_N);
float const n2n2 = Dot(b.m_N, b.m_N);
float const d = n1n1 * n2n2 - n1n2 * n1n2;
float const c1 = (b.m_D * n1n2 - a.m_D * n2n2) / d;
float const c2 = (a.m_D * n1n2 - b.m_D * n1n1) / d;
pi->m_B = a.m_N * c1 + b.m_N * c2;
pi->m_M = Cross(a.m_N, b.m_N);
return 1;
}
}
//! @param a The point to test.
//! @param b The point to test.
//!
//! Returns the distance between the points.
float Distance(Point const & a, Point const & b)
{
return (a.value_ - b.value_).Length();
}
//! @param point The point to test.
//! @param line The line to test.
//!
//! Returns the distance between the point and the line.
float Distance(Point const & point, Line const & line)
{
// Distance in n-space is
//
// || (P - B) - ((P - B) dot M)M ||
//
// but in 3D/2D, it is also
//
// || M cross (P - B) ||
//
// which is slightly faster
return Cross(point.value_ - line.m_B, line.m_M).Length();
}
//! @param point The point to test.
//! @param ray The ray to test.
//!
//! Returns the distance between the point and the ray.
float Distance(Point const & point, Ray const & ray)
{
float const t = Dot((point.value_ - ray.m_B), ray.m_M);
if (t <= 0.f)
return Distance(point, ray.m_B);
else
return Distance(point, ray.m_B + ray.m_M * t);
}
//! @param point The point to test.
//! @param segment The line segment to test.
//!
//! Returns the distance between the point and the line segment.
float Distance(Point const & point, Segment const & segment)
{
assert(!MyMath::IsCloseToZero(segment.m_M.Length2()));
float const t = Dot((point.value_ - segment.m_B), segment.m_M) / segment.m_M.Length2();
if (t <= 0.f)
return Distance(point, segment.m_B);
else if (t < 1.f)
return Distance(point, segment.m_B + segment.m_M * t);
else
return Distance(point, segment.m_B + segment.m_M);
}
//! @param point The point to test.
//! @param plane The plane to test.
//!
//! Returns the distance between the point and the plane.
float Distance(Point const & point, Plane const & plane)
{
return fabsf(Dot(plane.m_N, point.value_) + plane.m_D);
}
//! @param a The line to test.
//! @param b The line to test.
//!
//! Returns the distance between the lines.
float Distance(Line const & a, Line const & b)
{
// The distance between two lines is abs( ( a.m_M cross b.m_M ) dot ( a.m_B - b.m_B ) ) assuming the lines
// are not parallel. If the lines are parallel, the distance is the distance from the line to any point
// on the other line.
Vector3 const cross = Cross(a.m_M, b.m_M);
if (!MyMath::IsCloseToZero(cross.Length2(), 2. * MyMath::DEFAULT_FLOAT_TOLERANCE))
return fabsf(Dot(cross, (a.m_B - b.m_B)));
else
return Distance(a.m_B, b);
}
| 28.507026 | 131 | 0.625488 | jambolo |
2a595f10e7726880050db0c4ae8725f99808f58c | 4,668 | cpp | C++ | src/CAENDigitizerException.cpp | flagarde/CAENcpp | f008098ec7b0a4ca609e217df9d13b87179491c9 | [
"MIT"
] | null | null | null | src/CAENDigitizerException.cpp | flagarde/CAENcpp | f008098ec7b0a4ca609e217df9d13b87179491c9 | [
"MIT"
] | null | null | null | src/CAENDigitizerException.cpp | flagarde/CAENcpp | f008098ec7b0a4ca609e217df9d13b87179491c9 | [
"MIT"
] | null | null | null | #include "CAENDigitizerException.hpp"
#include "CAENDigitizerType.h"
namespace CAEN
{
const char* Exception::what() const noexcept
{
return m_What.c_str();
}
const char* Exception::description() const noexcept
{
return m_Description.c_str();
}
std::int_least8_t Exception::code() const noexcept
{
return m_Code;
}
Exception::Exception(const int_least8_t& code,const source_location& location) : source_location(location), m_Code(code)
{
constructMessage();
if(code != CAEN_DGTZ_Success) throw *this;
}
void Exception::constructMessage()
{
switch(m_Code)
{
case CAEN_DGTZ_Success:
m_Description = "Operation completed successfully";
break;
case CAEN_DGTZ_CommError:
m_Description = "Communication error";
break;
case CAEN_DGTZ_GenericError:
m_Description = "Unspecified error";
break;
case CAEN_DGTZ_InvalidParam:
m_Description = "Invalid parameter";
break;
case CAEN_DGTZ_InvalidLinkType:
m_Description = "Invalid Link Type";
break;
case CAEN_DGTZ_InvalidHandle:
m_Description = "Invalid device handle";
break;
case CAEN_DGTZ_MaxDevicesError:
m_Description = "Maximum number of devices exceeded";
break;
case CAEN_DGTZ_BadBoardType:
m_Description = "The operation is not allowed on this type of board";
break;
case CAEN_DGTZ_BadInterruptLev:
m_Description = "The interrupt level is not allowed";
break;
case CAEN_DGTZ_BadEventNumber:
m_Description = "The event number is bad";
break;
case CAEN_DGTZ_ReadDeviceRegisterFail:
m_Description = "Unable to read the registry";
break;
case CAEN_DGTZ_WriteDeviceRegisterFail:
m_Description = "Unable to write into the registry";
break;
case CAEN_DGTZ_InvalidChannelNumber:
m_Description = "The channel number is invalid";
break;
case CAEN_DGTZ_ChannelBusy:
m_Description = "The Channel is busy";
break;
case CAEN_DGTZ_FPIOModeInvalid:
m_Description = "Invalid FPIO Mode";
break;
case CAEN_DGTZ_WrongAcqMode:
m_Description = "Wrong acquisition mode";
break;
case CAEN_DGTZ_FunctionNotAllowed:
m_Description = "This function is not allowed for this module";
break;
case CAEN_DGTZ_Timeout:
m_Description = "Communication Timeout";
break;
case CAEN_DGTZ_InvalidBuffer:
m_Description = "The buffer is invalid";
break;
case CAEN_DGTZ_EventNotFound:
m_Description = "The event is not found";
break;
case CAEN_DGTZ_InvalidEvent:
m_Description = "The vent is invalid";
break;
case CAEN_DGTZ_OutOfMemory:
m_Description = "Out of memory";
break;
case CAEN_DGTZ_CalibrationError:
m_Description = "Unable to calibrate the board";
break;
case CAEN_DGTZ_DigitizerNotFound:
m_Description = "Unable to open the digitizer";
break;
case CAEN_DGTZ_DigitizerAlreadyOpen:
m_Description = "The Digitizer is already open";
break;
case CAEN_DGTZ_DigitizerNotReady:
m_Description = "The Digitizer is not ready to operate";
break;
case CAEN_DGTZ_InterruptNotConfigured:
m_Description = "The Digitizer has not the IRQ configured";\
break;
case CAEN_DGTZ_DigitizerMemoryCorrupted:
m_Description = "The digitizer flash memory is corrupted";
break;
case CAEN_DGTZ_DPPFirmwareNotSupported:
m_Description = "The digitizer dpp firmware is not supported in this lib version";
break;
case CAEN_DGTZ_InvalidLicense:
m_Description = "Invalid Firmware License";
break;
case CAEN_DGTZ_InvalidDigitizerStatus:
m_Description = "The digitizer is found in a corrupted status";
break;
case CAEN_DGTZ_UnsupportedTrace:
m_Description = "The given trace is not supported by the digitizer";
break;
case CAEN_DGTZ_InvalidProbe:
m_Description = "The given probe is not supported for the given digitizer's trace";
break;
case CAEN_DGTZ_UnsupportedBaseAddress:
m_Description = "The Base Address is not supported, it's a Desktop device ?";
break;
case CAEN_DGTZ_NotYetImplemented:
m_Description = "The function is not yet implemented";
break;
default:
m_Description = "Error code unknown";
break;
}
m_What = "\n\t[Code] : "+std::to_string(m_Code)+"\n\t[Description] : "+m_Description+"\n\t[File] : "+file_name()+"\n\t[Function] : "+function_name()+"\n\t[Line] : "+std::to_string(line())+"\n\t[Column] : "+std::to_string(column())+"\n";
}
};
| 31.972603 | 238 | 0.687875 | flagarde |
39895bee8a6c943606dcdb78e1e39735de17bf14 | 9,824 | cpp | C++ | RendererCore/src/WindowRegister.cpp | Gaiyitp9/TGRenderLab | 9251161088643bacdd82586210e468e28b4ce5d7 | [
"MIT"
] | null | null | null | RendererCore/src/WindowRegister.cpp | Gaiyitp9/TGRenderLab | 9251161088643bacdd82586210e468e28b4ce5d7 | [
"MIT"
] | null | null | null | RendererCore/src/WindowRegister.cpp | Gaiyitp9/TGRenderLab | 9251161088643bacdd82586210e468e28b4ce5d7 | [
"MIT"
] | null | null | null | /****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#include "WindowRegister.hpp"
#include "Window.hpp"
#include "Diagnostics/Debug.hpp"
#include <format>
#define REGISTER_MESSAGE(msg) {msg, L#msg}
namespace LCH
{
WindowRegister::WindowRegister()
: windowMessage({
REGISTER_MESSAGE(WM_NULL),
REGISTER_MESSAGE(WM_CREATE),
REGISTER_MESSAGE(WM_DESTROY),
REGISTER_MESSAGE(WM_MOVE),
REGISTER_MESSAGE(WM_SIZE),
REGISTER_MESSAGE(WM_ACTIVATE),
REGISTER_MESSAGE(WM_SETFOCUS),
REGISTER_MESSAGE(WM_KILLFOCUS),
REGISTER_MESSAGE(WM_ENABLE),
REGISTER_MESSAGE(WM_SETREDRAW),
REGISTER_MESSAGE(WM_SETTEXT),
REGISTER_MESSAGE(WM_GETTEXT),
REGISTER_MESSAGE(WM_GETTEXTLENGTH),
REGISTER_MESSAGE(WM_PAINT),
REGISTER_MESSAGE(WM_CLOSE),
REGISTER_MESSAGE(WM_QUERYENDSESSION),
REGISTER_MESSAGE(WM_QUIT),
REGISTER_MESSAGE(WM_QUERYOPEN),
REGISTER_MESSAGE(WM_ERASEBKGND),
REGISTER_MESSAGE(WM_SYSCOLORCHANGE),
REGISTER_MESSAGE(WM_ENDSESSION),
REGISTER_MESSAGE(WM_SHOWWINDOW),
REGISTER_MESSAGE(WM_CTLCOLORMSGBOX),
REGISTER_MESSAGE(WM_CTLCOLOREDIT),
REGISTER_MESSAGE(WM_CTLCOLORLISTBOX),
REGISTER_MESSAGE(WM_CTLCOLORBTN),
REGISTER_MESSAGE(WM_CTLCOLORDLG),
REGISTER_MESSAGE(WM_CTLCOLORSCROLLBAR),
REGISTER_MESSAGE(WM_CTLCOLORSTATIC),
REGISTER_MESSAGE(WM_WININICHANGE),
REGISTER_MESSAGE(WM_SETTINGCHANGE),
REGISTER_MESSAGE(WM_DEVMODECHANGE),
REGISTER_MESSAGE(WM_ACTIVATEAPP),
REGISTER_MESSAGE(WM_FONTCHANGE),
REGISTER_MESSAGE(WM_TIMECHANGE),
REGISTER_MESSAGE(WM_CANCELMODE),
REGISTER_MESSAGE(WM_SETCURSOR),
REGISTER_MESSAGE(WM_MOUSEACTIVATE),
REGISTER_MESSAGE(WM_CHILDACTIVATE),
REGISTER_MESSAGE(WM_QUEUESYNC),
REGISTER_MESSAGE(WM_GETMINMAXINFO),
REGISTER_MESSAGE(WM_ICONERASEBKGND),
REGISTER_MESSAGE(WM_NEXTDLGCTL),
REGISTER_MESSAGE(WM_SPOOLERSTATUS),
REGISTER_MESSAGE(WM_DRAWITEM),
REGISTER_MESSAGE(WM_MEASUREITEM),
REGISTER_MESSAGE(WM_DELETEITEM),
REGISTER_MESSAGE(WM_VKEYTOITEM),
REGISTER_MESSAGE(WM_CHARTOITEM),
REGISTER_MESSAGE(WM_SETFONT),
REGISTER_MESSAGE(WM_GETFONT),
REGISTER_MESSAGE(WM_QUERYDRAGICON),
REGISTER_MESSAGE(WM_COMPAREITEM),
REGISTER_MESSAGE(WM_GETOBJECT),
REGISTER_MESSAGE(WM_COMPACTING),
REGISTER_MESSAGE(WM_NCCREATE),
REGISTER_MESSAGE(WM_NCDESTROY),
REGISTER_MESSAGE(WM_NCCALCSIZE),
REGISTER_MESSAGE(WM_NCHITTEST),
REGISTER_MESSAGE(WM_NCPAINT),
REGISTER_MESSAGE(WM_NCACTIVATE),
REGISTER_MESSAGE(WM_GETDLGCODE),
REGISTER_MESSAGE(WM_NCMOUSEMOVE),
REGISTER_MESSAGE(WM_NCLBUTTONDOWN),
REGISTER_MESSAGE(WM_NCLBUTTONUP),
REGISTER_MESSAGE(WM_NCLBUTTONDBLCLK),
REGISTER_MESSAGE(WM_NCRBUTTONDOWN),
REGISTER_MESSAGE(WM_NCRBUTTONUP),
REGISTER_MESSAGE(WM_NCRBUTTONDBLCLK),
REGISTER_MESSAGE(WM_NCMBUTTONDOWN),
REGISTER_MESSAGE(WM_NCMBUTTONUP),
REGISTER_MESSAGE(WM_NCMBUTTONDBLCLK),
REGISTER_MESSAGE(WM_KEYDOWN),
REGISTER_MESSAGE(WM_KEYUP),
REGISTER_MESSAGE(WM_CHAR),
REGISTER_MESSAGE(WM_DEADCHAR),
REGISTER_MESSAGE(WM_SYSKEYDOWN),
REGISTER_MESSAGE(WM_SYSKEYUP),
REGISTER_MESSAGE(WM_SYSCHAR),
REGISTER_MESSAGE(WM_SYSDEADCHAR),
REGISTER_MESSAGE(WM_KEYLAST),
REGISTER_MESSAGE(WM_INITDIALOG),
REGISTER_MESSAGE(WM_COMMAND),
REGISTER_MESSAGE(WM_SYSCOMMAND),
REGISTER_MESSAGE(WM_TIMER),
REGISTER_MESSAGE(WM_HSCROLL),
REGISTER_MESSAGE(WM_VSCROLL),
REGISTER_MESSAGE(WM_INITMENU),
REGISTER_MESSAGE(WM_INITMENUPOPUP),
REGISTER_MESSAGE(WM_MENUSELECT),
REGISTER_MESSAGE(WM_MENUCHAR),
REGISTER_MESSAGE(WM_ENTERIDLE),
REGISTER_MESSAGE(WM_MOUSEWHEEL),
REGISTER_MESSAGE(WM_MOUSEMOVE),
REGISTER_MESSAGE(WM_LBUTTONDOWN),
REGISTER_MESSAGE(WM_LBUTTONUP),
REGISTER_MESSAGE(WM_LBUTTONDBLCLK),
REGISTER_MESSAGE(WM_RBUTTONDOWN),
REGISTER_MESSAGE(WM_RBUTTONUP),
REGISTER_MESSAGE(WM_RBUTTONDBLCLK),
REGISTER_MESSAGE(WM_MBUTTONDOWN),
REGISTER_MESSAGE(WM_MBUTTONUP),
REGISTER_MESSAGE(WM_MBUTTONDBLCLK),
REGISTER_MESSAGE(WM_PARENTNOTIFY),
REGISTER_MESSAGE(WM_MDICREATE),
REGISTER_MESSAGE(WM_MDIDESTROY),
REGISTER_MESSAGE(WM_MDIACTIVATE),
REGISTER_MESSAGE(WM_MDIRESTORE),
REGISTER_MESSAGE(WM_MDINEXT),
REGISTER_MESSAGE(WM_MDIMAXIMIZE),
REGISTER_MESSAGE(WM_MDITILE),
REGISTER_MESSAGE(WM_MDICASCADE),
REGISTER_MESSAGE(WM_MDIICONARRANGE),
REGISTER_MESSAGE(WM_MDIGETACTIVE),
REGISTER_MESSAGE(WM_MDISETMENU),
REGISTER_MESSAGE(WM_CUT),
REGISTER_MESSAGE(WM_COPYDATA),
REGISTER_MESSAGE(WM_COPY),
REGISTER_MESSAGE(WM_PASTE),
REGISTER_MESSAGE(WM_CLEAR),
REGISTER_MESSAGE(WM_UNDO),
REGISTER_MESSAGE(WM_RENDERFORMAT),
REGISTER_MESSAGE(WM_RENDERALLFORMATS),
REGISTER_MESSAGE(WM_DESTROYCLIPBOARD),
REGISTER_MESSAGE(WM_DRAWCLIPBOARD),
REGISTER_MESSAGE(WM_PAINTCLIPBOARD),
REGISTER_MESSAGE(WM_VSCROLLCLIPBOARD),
REGISTER_MESSAGE(WM_SIZECLIPBOARD),
REGISTER_MESSAGE(WM_ASKCBFORMATNAME),
REGISTER_MESSAGE(WM_CHANGECBCHAIN),
REGISTER_MESSAGE(WM_HSCROLLCLIPBOARD),
REGISTER_MESSAGE(WM_QUERYNEWPALETTE),
REGISTER_MESSAGE(WM_PALETTEISCHANGING),
REGISTER_MESSAGE(WM_PALETTECHANGED),
REGISTER_MESSAGE(WM_DROPFILES),
REGISTER_MESSAGE(WM_POWER),
REGISTER_MESSAGE(WM_WINDOWPOSCHANGED),
REGISTER_MESSAGE(WM_WINDOWPOSCHANGING),
REGISTER_MESSAGE(WM_HELP),
REGISTER_MESSAGE(WM_NOTIFY),
REGISTER_MESSAGE(WM_CONTEXTMENU),
REGISTER_MESSAGE(WM_TCARD),
REGISTER_MESSAGE(WM_MDIREFRESHMENU),
REGISTER_MESSAGE(WM_MOVING),
REGISTER_MESSAGE(WM_STYLECHANGED),
REGISTER_MESSAGE(WM_STYLECHANGING),
REGISTER_MESSAGE(WM_SIZING),
REGISTER_MESSAGE(WM_SETHOTKEY),
REGISTER_MESSAGE(WM_PRINT),
REGISTER_MESSAGE(WM_PRINTCLIENT),
REGISTER_MESSAGE(WM_POWERBROADCAST),
REGISTER_MESSAGE(WM_HOTKEY),
REGISTER_MESSAGE(WM_GETICON),
REGISTER_MESSAGE(WM_EXITMENULOOP),
REGISTER_MESSAGE(WM_ENTERMENULOOP),
REGISTER_MESSAGE(WM_DISPLAYCHANGE),
REGISTER_MESSAGE(WM_STYLECHANGED),
REGISTER_MESSAGE(WM_STYLECHANGING),
REGISTER_MESSAGE(WM_GETICON),
REGISTER_MESSAGE(WM_SETICON),
REGISTER_MESSAGE(WM_SIZING),
REGISTER_MESSAGE(WM_MOVING),
REGISTER_MESSAGE(WM_CAPTURECHANGED),
REGISTER_MESSAGE(WM_DEVICECHANGE),
REGISTER_MESSAGE(WM_PRINT),
REGISTER_MESSAGE(WM_PRINTCLIENT),
REGISTER_MESSAGE(WM_IME_SETCONTEXT),
REGISTER_MESSAGE(WM_IME_NOTIFY),
REGISTER_MESSAGE(WM_NCMOUSELEAVE),
REGISTER_MESSAGE(WM_EXITSIZEMOVE),
REGISTER_MESSAGE(WM_DWMNCRENDERINGCHANGED),
REGISTER_MESSAGE(WM_ENTERSIZEMOVE),
})
{
if (hInstance = GetModuleHandleW(nullptr))
ThrowLastError();
WNDCLASSEX wc = {};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WindowProcSetup;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = nullptr;
wc.hCursor = nullptr;
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.hIconSm = nullptr;
wc.lpszMenuName = nullptr;
wc.lpszClassName = L"Default";
if (RegisterClassExW(&wc))
ThrowLastError();
windowClassName[WindowType::Default] = L"Default";
}
WindowRegister::~WindowRegister()
{
for (auto& pair : windowClassName)
UnregisterClassW(pair.second.c_str(), hInstance);
}
LRESULT WindowRegister::WindowProcSetup(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// 注:窗口处理函数不能向上传递异常,还没有想到好的解决方案。这个项目里的异常主要是为了定位,
// 而且涉及的函数主要是一些简单的WIN32函数和c++的STL,基本上不会出错,所以在这里不处理异常
if (msg == WM_NCCREATE)
{
const CREATESTRUCT* const pCreate = reinterpret_cast<CREATESTRUCT*>(lParam);
Window* const pWnd = static_cast<Window*>(pCreate->lpCreateParams);
SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd));
SetWindowLongPtrW(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(WindowProcThunk));
return pWnd->WindowProc(hwnd, msg, wParam, lParam);
}
// 处理WM_NCCREATE之前的消息
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
LRESULT WindowRegister::WindowProcThunk(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// 注:窗口处理函数不能向上传递异常,还没有想到好的解决方案。这个项目里的异常主要是为了定位,
// 涉及的函数是一些简单的WIN32函数和c++的STL,基本上不会出错,所以在这里不处理异常
Window* const pWnd = reinterpret_cast<Window*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
// 是否监控窗口消息
if (pWnd->spyMessage)
Debug::LogLine(WindowRegister::GetInstance().GetWindowMesssageInfo(pWnd->name, msg, wParam, lParam));
// 窗口被销毁后,窗口类也需要被销毁
if (msg == WM_DESTROY)
pWnd->destroy = true;
return pWnd->WindowProc(hwnd, msg, wParam, lParam);
}
WindowRegister& WindowRegister::GetInstance()
{
static WindowRegister s;
return s;
}
HINSTANCE WindowRegister::GetHInstance() const noexcept
{
return hInstance;
}
const std::wstring& WindowRegister::GetWindowClassName(const WindowType& type) const
{
return windowClassName.at(type);
}
std::wstring WindowRegister::GetWindowMesssageInfo(const std::wstring& window, UINT msg, WPARAM wp, LPARAM lp) const
{
std::wstring msgInfo;
msgInfo += std::format(L"{:<10}", window);
const auto it = windowMessage.find(msg);
if (it == windowMessage.end())
{
msgInfo += std::format(L" {:<25}", std::format(L"Unknown message: {:#x}", msg));
}
else
{
msgInfo += std::format(L" {:<25}", it->second);
}
msgInfo += std::format(L" LP: {:#018x}", lp);
msgInfo += std::format(L" WP: {:#018x}", wp);
return msgInfo;
}
} | 33.99308 | 118 | 0.739414 | Gaiyitp9 |
3989ab37c948861fd15cf884e9a594898755aee8 | 5,586 | cpp | C++ | owGame/WMO/WMO.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 30 | 2017-09-02T20:25:47.000Z | 2021-12-31T10:12:07.000Z | owGame/WMO/WMO.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | null | null | null | owGame/WMO/WMO.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 23 | 2018-02-04T17:18:33.000Z | 2022-03-22T09:45:36.000Z | #include "stdafx.h"
#ifdef USE_WMO_MODELS
// Include
#include "WMO_Base_Instance.h"
// General
#include "WMO.h"
CWMO::CWMO(const IBaseManager& BaseManager, IRenderDevice& RenderDevice, const std::string& Filename)
: m_FileName(Filename)
, m_TexturesNames(nullptr)
, m_DoodadsFilenames(nullptr)
, m_BaseManager(BaseManager)
, m_RenderDevice(RenderDevice)
{
m_ChunkReader = std::make_unique<WoWChunkReader>(m_BaseManager, m_FileName);
// Version
{
auto buffer = m_ChunkReader->OpenChunk("MVER");
uint32 version;
buffer->readBytes(&version, 4);
_ASSERT(version == 17);
}
// Header
{
auto buffer = m_ChunkReader->OpenChunk("MOHD");
buffer->readBytes(&m_Header, sizeof(SWMO_MOHD));
m_Bounds = m_Header.bounding_box.Convert();
}
}
CWMO::~CWMO()
{
//Log::Error("Deleted.");
}
//
// ISceneNodeProvider
//
void CWMO::CreateInsances(const std::shared_ptr<CWMO_Base_Instance>& Parent) const
{
for (const auto& it : m_Groups)
{
auto groupInstance = Parent->CreateSceneNode<CWMO_Group_Instance>(Parent->GetWorldClient(), it);
Parent->AddGroupInstance(groupInstance);
//if (it->IsOutdoor())
// Parent->AddOutdoorGroupInstance(groupInstance);
m_BaseManager.GetManager<ILoader>()->AddToLoadQueue(groupInstance);
}
}
//
// ILoadable
//
bool CWMO::Load()
{
// Textures
if (auto buffer = m_ChunkReader->OpenChunk("MOTX"))
{
m_TexturesNames = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(m_TexturesNames.get(), buffer->getSize());
m_TexturesNames[buffer->getSize()] = '\0';
}
// Materials
for (const auto& mat : m_ChunkReader->OpenChunkT<SWMO_MOMT>("MOMT"))
{
auto material = MakeShared(WMO_Part_Material, m_RenderDevice, *this, mat);
m_Materials.push_back(material);
}
if (m_Materials.size() != m_Header.nTextures)
throw CException("WMO::Load: Materials count '%d' isn't equal textures count '%d'.", m_Materials.size(), m_Header.nTextures);
// Group names
if (auto buffer = m_ChunkReader->OpenChunk("MOGN"))
{
m_GroupNames = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(m_GroupNames.get(), buffer->getSize());
m_GroupNames[buffer->getSize()] = '\0';
}
// Skybox
if (auto buffer = m_ChunkReader->OpenChunk("MOSB"))
{
if (buffer->getSize() > 4)
{
std::unique_ptr<char[]> skyboxFilename = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(skyboxFilename.get(), buffer->getSize());
skyboxFilename[buffer->getSize()] = '\0';
Log::Error("WMO[%s]: Skybox [%s]", m_FileName.c_str(), skyboxFilename.get());
}
}
// Portal vertices
std::vector<glm::vec3> portalVertices;
for (const auto& pv : m_ChunkReader->OpenChunkT<glm::vec3>("MOPV"))
{
portalVertices.push_back(Fix_From_XZmY_To_XYZ(pv));
}
// Portal defs
std::vector<CWMO_Part_Portal> portals;
for (const auto& pt : m_ChunkReader->OpenChunkT<SWMO_MOPT>("MOPT"))
{
portals.push_back(CWMO_Part_Portal(portalVertices, pt));
}
// Portal references
std::vector<SWMO_MOPR> portalsReferences;
for (const auto& pr : m_ChunkReader->OpenChunkT<SWMO_MOPR>("MOPR"))
{
_ASSERT(pr.portalIndex >= 0 && pr.portalIndex < portals.size());
auto& portal = portals[pr.portalIndex];
portal.setGroup(pr.groupIndex, pr.side);
portalsReferences.push_back(pr);
}
#if 0
// Visible vertices
for (const auto& vv : m_ChunkReader->OpenChunkT<glm::vec3>("MOVV"))
{
m_VisibleBlockVertices.push_back(Fix_From_XZmY_To_XYZ(vv));
}
// Visible blocks
for (const auto& vb : m_ChunkReader->OpenChunkT<SWMO_MOVB>("MOVB"))
{
m_VisibleBlockList.push_back(vb);
}
#endif
// Lights
for (const auto& lt : m_ChunkReader->OpenChunkT<SWMO_MOLT>("MOLT"))
{
m_Lights.push_back(MakeShared(WMO_Part_Light, lt));
}
// Doodads set
for (const auto& ds : m_ChunkReader->OpenChunkT<SWMO_MODS>("MODS"))
{
m_DoodadsSetInfos.push_back(ds);
}
// Doodads filenames
if (auto buffer = m_ChunkReader->OpenChunk("MODN"))
{
m_DoodadsFilenames = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(m_DoodadsFilenames.get(), buffer->getSize());
m_DoodadsFilenames[buffer->getSize()] = '\0';
}
// Doodads placemnts
for (const auto& dd : m_ChunkReader->OpenChunkT<SWMO_MODD>("MODD"))
{
m_DoodadsPlacementInfos.push_back(dd);
}
// HACK! INCORRECT SIZE
//m_Header.nDoodadDefs = m_DoodadsPlacementInfos.size();
// Fog
for (const auto& fog : m_ChunkReader->OpenChunkT<SWMO_MFOG>("MFOG"))
{
m_Fogs.push_back(MakeShared(WMO_Part_Fog, fog));
}
// Group info
{
uint32 cntr = 0;
for (const auto& gi : m_ChunkReader->OpenChunkT<SWMO_MOGI>("MOGI"))
{
auto wmoGroup = MakeShared(CWMOGroup, m_BaseManager, m_RenderDevice, *this, cntr++, gi);
wmoGroup->AddParentLoadable(shared_from_this());
m_BaseManager.GetManager<ILoader>()->AddToLoadQueue(wmoGroup);
m_Groups.push_back(wmoGroup);
}
//for (const auto& groupIt : m_Groups)
}
m_ChunkReader.reset();
// Setup group portals
{
for (const auto& ref : portalsReferences)
{
auto portal = portals[ref.portalIndex];
auto group = m_Groups[ref.groupIndex];
if (ref.groupIndex == group->GetGroupIndex())
{
group->AddPortal(portal);
}
else _ASSERT(false);
}
}
/*
// Create portal controller
if (portals.size() > 0)
{
#ifdef USE_WMO_PORTALS_CULLING
m_PortalController = MakeShared(CWMO_PortalsComponent);
for (const auto& it : portalsReferences)
{
_ASSERT(it.portalIndex < portals.size());
_ASSERT(it.groupIndex < m_Groups.size());
}
#endif
}*/
return true;
}
bool CWMO::Delete()
{
return false;
}
#endif
| 23.470588 | 127 | 0.697637 | Chaos192 |
398a014d168421009d498635e782844e8a350fa4 | 16,655 | cxx | C++ | osprey/common/com/wn_simp.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/wn_simp.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/wn_simp.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2004, 2005, 2006 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
/* ====================================================================
* ====================================================================
*
* Module: wn_simp
*
* ====================================================================
* ====================================================================
*/
#include <stdint.h>
#ifdef USE_PCH
#include "common_com_pch.h"
#endif /* USE_PCH */
#pragma hdrstop
#include "defs.h"
#include "errors.h"
#include "erglob.h"
#include "tracing.h"
#include "wn.h"
#include "stab.h"
#include "wn_util.h"
#include "ir_reader.h"
#include "config.h"
#include "config_opt.h"
#include "config_targ.h"
#include "const.h"
#include "targ_const.h"
#ifdef BACK_END
#include "opt_alias_interface.h"
#endif
#include "wn_simp.h"
#if defined(KEY) && defined(Is_True_On)
#include "config_opt.h"
#endif
#ifdef BACK_END
BOOL WN_Simp_Fold_ILOAD = TRUE;
#else
BOOL WN_Simp_Fold_ILOAD = FALSE;
#endif
BOOL WN_Simp_Fold_LDA = FALSE;
#ifdef KEY
BOOL WN_Simp_Rsqrt_Newton_Raphson = TRUE;
#endif
/* Parent maps from LNO and anyone else who wants it */
WN_MAP WN_SimpParentMap = WN_MAP_UNDEFINED;
#define TRACEFILE TFile
/* To tell wn_simp_code.h that it's working on WHIRL */
#define WN_SIMP_WORKING_ON_WHIRL
/* Definitions for wn_simp_code.h */
/* Type definition */
typedef WN * simpnode;
/* Accessors */
#define SIMPNODE_operator(x) WN_operator(x)
#define SIMPNODE_rtype(x) WN_rtype(x)
#define SIMPNODE_desc(x) WN_desc(x)
#define SIMPNODE_opcode WN_opcode
#define SIMPNODE_load_offset WN_load_offset
#define SIMPNODE_cvtl_bits WN_cvtl_bits
#define SIMPNODE_st WN_st
#define SIMPNODE_st_idx WN_st_idx
#define SIMPNODE_ty WN_ty
#define SIMPNODE_object_ty WN_object_ty
#define SIMPNODE_load_addr_ty WN_load_addr_ty
#define SIMPNODE_kid0 WN_kid0
#define SIMPNODE_kid1 WN_kid1
#define SIMPNODE_kid WN_kid
#define SIMPNODE_element_size WN_element_size
#define SIMPNODE_idname_offset WN_idname_offset
#define SIMPNODE_lda_offset WN_lda_offset
#define SIMPNODE_label_number WN_label_number
#define SIMPNODE_num_dim WN_num_dim
#define SIMPNODE_array_base WN_array_base
#define SIMPNODE_array_index WN_array_index
#define SIMPNODE_array_dim WN_array_dim
#define SIMPNODE_intrinsic WN_intrinsic
#define SIMPNODE_kid_count WN_kid_count
#define SIMPNODE_kid WN_kid
#define SIMPNODE_const_val WN_const_val
#define SIMPNODE_fconst_val Const_Val
#define SIMPNODE_field_id WN_field_id // get the field id
#define SIMPNODE_i_field_id WN_field_id // get the field id
#define SIMPNODE_bit_offset WN_bit_offset // get the bit offset
#define SIMPNODE_i_bit_offset WN_bit_offset // get the bit offset
#define SIMPNODE_enable Enable_WN_Simp
#define SIMPNODE_op_bit_offset WN_bit_offset
#define SIMPNODE_op_bit_size WN_bit_size
/* Functions */
#define SIMPNODE_SimpCreateExp1 WN_SimpCreateExp1
#define SIMPNODE_SimpCreateExp2 WN_SimpCreateExp2
#define SIMPNODE_SimpCreateExp3 WN_SimpCreateExp3
#define SIMPNODE_SimpCreateCvtl WN_SimpCreateCvtl
#define SIMPNODE_SimpCreateExtract WN_SimpCreateExtract
#define SIMPNODE_SimpCreateDeposit WN_SimpCreateDeposit
#define SIMPNODE_TREE_DELETE WN_DELETE_Tree
#define SIMPNODE_DELETE WN_Delete
#define SIMPNODE_CopyNode WN_CopyNode
#define SIMPNODE_CreateIntconst WN_CreateIntconst
#define SIMPNODE_CreateFloatconstFromTcon Make_Const
#ifdef TARG_X8664
#define SIMPNODE_CreateSIMDconstFromTcon Make_Const
#endif
#define SIMPNODE_Simplify_Initialize WN_Simplify_Initialize
#define SIMPNODE_Compare_Symbols WN_Compare_Symbols
#define SIMPNODE_is_volatile WN_Is_Volatile_Mem
/* externally visible routines. These three are defined in wn_simp_code.h.
* They need a name defined here and in whatever external interface file
* exists for the routine
*/
#define SIMPNODE_SimplifyExp1 WN_SimplifyExp1
#define SIMPNODE_SimplifyExp2 WN_SimplifyExp2
#define SIMPNODE_SimplifyExp3 WN_SimplifyExp3
#define SIMPNODE_SimplifyCvtl WN_SimplifyCvtl
#define SIMPNODE_SimplifyIntrinsic WN_SimplifyIntrinsic
#define SIMPNODE_SimplifyIload WN_SimplifyIload
#define SIMPNODE_SimplifyIstore WN_SimplifyIstore
#define SIMPNODE_Simp_Compare_Trees WN_Simp_Compare_Trees
static void show_tree(OPCODE opc, WN *k0, WN *k1, WN *r)
{
fprintf(TRACEFILE,"\nBefore:\n");
fdump_tree(TRACEFILE,k0);
if (OPCODE_operator(opc) != OPR_CVTL) {
if (k1)
fdump_tree(TRACEFILE,k1);
fprintf(TRACEFILE,"%s\n",OPCODE_name(opc));
} else
fprintf(TRACEFILE,"%s %d\n",OPCODE_name(opc),(INT) (INTPS) k1);
fprintf(TRACEFILE,"=====\nAfter:\n");
fdump_tree(TRACEFILE,r);
fprintf(TRACEFILE,
"-----------------------------------------------------\n");
}
/* Walk a tree, simplifying from the bottom up. For operators
* that the simplifier doesn't know how to deal with, simplify and replace the
* children. For those that it does, simplify the children, then try and
* simplify the argument with new children.
*/
WN *WN_Simplify_Tree(WN *t, ALIAS_MANAGER *alias_manager)
{
OPCODE op;
OPERATOR opr;
WN *k0, *k1, *k2, *r=NULL, *temp, *result, *next, *prev;
INT16 numkids;
INT32 i;
numkids = WN_kid_count(t);
op = WN_opcode(t);
opr = OPCODE_operator(op);
result = t;
if (op == OPC_BLOCK) {
result = t;
r = WN_first(t);
while (r) {
prev = WN_prev(r);
next = WN_next(r);
temp = WN_Simplify_Tree(r);
if (temp != r) {
/* a simplification happened */
WN_next(temp) = next;
WN_prev(temp) = prev;
if (next) WN_prev(next) = temp;
if (prev) WN_next(prev) = temp;
if (WN_first(t) == r) WN_first(t) = temp;
if (WN_last(t) == r) WN_last(t) = temp;
}
r = next;
}
} else if (opr == OPR_ILOAD) {
k0 = WN_Simplify_Tree(WN_kid0(t));
r = WN_SimplifyIload(op,WN_load_offset(t),WN_ty(t),WN_field_id(t),WN_load_addr_ty(t),k0);
if (r) {
#ifdef BACK_END
if (alias_manager) {
Copy_alias_info(alias_manager,t,r);
}
#endif
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
result = t;
}
} else if (opr == OPR_ISTORE) {
k0 = WN_Simplify_Tree(WN_kid0(t));
k1 = WN_Simplify_Tree(WN_kid1(t));
r = WN_SimplifyIstore(op,WN_load_offset(t),WN_ty(t),WN_field_id(t),k0,k1);
if (r) {
#ifdef BACK_END
if (alias_manager) {
Copy_alias_info(alias_manager,t,r);
}
#endif
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
WN_kid1(t) = k1;
result = t;
}
} else if (opr == OPR_INTRINSIC_OP) {
for (i=0; i < numkids; i++) {
WN_kid(t,i) = WN_Simplify_Tree(WN_kid(t,i));
}
r = WN_SimplifyIntrinsic(op, WN_intrinsic(t), numkids, &WN_kid0(t));
if (r) {
WN_Delete(t);
result = r;
} else {
result = t;
}
} else if (opr == OPR_IO_ITEM) {
// For IO_ITEM, just simplify the kids
for (i=0; i < numkids; i++) {
WN_kid(t,i) = WN_Simplify_Tree(WN_kid(t,i));
}
result = t;
} else if (numkids == 1) {
k0 = WN_Simplify_Tree(WN_kid0(t));
if (WN_operator(t) != OPR_CVTL) {
r = WN_SimplifyExp1(op, k0);
} else {
r = WN_SimplifyCvtl(op, WN_cvtl_bits(t),k0);
}
if (r) {
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
result = t;
}
} else if (numkids == 2) {
k0 = WN_Simplify_Tree(WN_kid0(t));
k1 = WN_Simplify_Tree(WN_kid1(t));
r = WN_SimplifyExp2(op, k0, k1);
if (r) {
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
WN_kid1(t) = k1;
result = t;
}
} else if (numkids == 3) {
k0 = WN_Simplify_Tree(WN_kid0(t));
k1 = WN_Simplify_Tree(WN_kid1(t));
k2 = WN_Simplify_Tree(WN_kid(t,2));
r = WN_SimplifyExp3(op, k0, k1, k2);
if (r) {
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
WN_kid1(t) = k1;
WN_kid(t,2) = k2;
result = t;
}
} else {
for (i=0; i < numkids; i++) {
WN_kid(t,i) = WN_Simplify_Tree(WN_kid(t,i));
}
result = t;
}
/* Update parent pointers */
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
numkids = WN_kid_count(result);
for (i=0; i < numkids; i++) {
WN_MAP_Set(WN_SimpParentMap, WN_kid(result,i), (void *) result);
}
}
return (result);
}
/* Assume that all children are already simplified, rebuild a tree using the new children.
* This only applies itself to a subset of expression nodes.
*/
WN *WN_Simplify_Rebuild_Expr_Tree(WN *t,ALIAS_MANAGER *alias_manager)
{
OPCODE op;
OPERATOR opr;
WN *k0, *k1, *k2, *r=NULL, *result;
INT16 numkids;
# if defined(KEY) && defined(Is_True_On)
static INT cur_idx = 0;
# endif
op = WN_opcode(t);
if (!OPCODE_is_expression(op)) return (t);
numkids = WN_kid_count(t);
opr = OPCODE_operator(op);
result = t;
if (opr == OPR_ILOAD) {
k0 = WN_kid0(t);
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyIload(op,WN_load_offset(t),WN_ty(t),WN_field_id(t),WN_load_addr_ty(t),k0);
if (r) {
# ifdef BACK_END
if (alias_manager) {
Copy_alias_info(alias_manager,t,r);
}
# endif
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else if (opr == OPR_INTRINSIC_OP) {
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyIntrinsic(op, WN_intrinsic(t), numkids, &WN_kid0(t));
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else if (numkids == 1) {
k0 = WN_kid0(t);
if (WN_operator(t) != OPR_CVTL) {
if (WN_operator(t) == OPR_EXTRACT_BITS) {
r = WN_SimplifyExp1(op,t);
} else {
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyExp1(op, k0);
}
} else {
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyCvtl(op, WN_cvtl_bits(t),k0);
}
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
WN_kid0(t) = k0;
result = t;
}
} else if (numkids == 2) {
k0 = WN_kid0(t);
k1 = WN_kid1(t);
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
#ifdef KEY // bug 13507
if (opr != OPR_PAIR)
#endif
r = WN_SimplifyExp2(op, k0, k1);
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else if (numkids == 3) {
k0 = WN_kid0(t);
k1 = WN_kid1(t);
k2 = WN_kid(t,2);
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyExp3(op, k0, k1, k2);
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else {
result = t;
}
return (result);
}
/* Allow the simplifier to be turned on and off */
BOOL WN_Simplifier_Enable(BOOL enable)
{
BOOL r = Enable_WN_Simp;
Enable_WN_Simp = enable;
return (r);
}
/* Utility procedure which does a comparison on two symbols */
static INT32 WN_Compare_Symbols(simpnode t1, simpnode t2)
{
ST_IDX s1 = SIMPNODE_st_idx(t1);
ST_IDX s2 = SIMPNODE_st_idx(t2);
if (s1 < s2)
return -1;
else if (s1 > s2)
return 1;
else
return 0;
}
/************ The code is here *******************/
#include "wn_simp_code.h"
/**************************************************/
/* Things which need to be written by the user */
/* Interface to WN_CreateExp3, checking for parent updates */
static simpnode WN_SimpCreateExp3(OPCODE opc,
simpnode k0, simpnode k1, simpnode k2)
{
simpnode wn;
wn = WN_SimplifyExp3(opc, k0, k1, k2);
if (!wn) {
wn = WN_Create(opc,3);
WN_kid0(wn) = k0;
WN_kid1(wn) = k1;
WN_kid(wn,2) = k2;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k1, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k2, (void *) wn);
}
}
return(wn);
}
/* Interface to WN_CreateExp2, checking for parent updates */
static simpnode WN_SimpCreateExp2(OPCODE opc, simpnode k0, simpnode k1)
{
simpnode wn;
wn = WN_SimplifyExp2(opc, k0, k1);
if (!wn) {
wn = WN_Create(opc,2);
WN_kid0(wn) = k0;
WN_kid1(wn) = k1;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k1, (void *) wn);
}
}
return(wn);
}
/* Interface to WN_CreateExp1, checking for parent updates */
static simpnode WN_SimpCreateExp1(OPCODE opc, simpnode k0)
{
simpnode wn;
wn = WN_SimplifyExp1(opc, k0);
if (!wn) {
wn = WN_Create(opc,1);
WN_kid0(wn) = k0;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
}
}
return(wn);
}
/* Interface to WN_CreateCvtl, checking for parent updates */
static simpnode WN_SimpCreateCvtl(OPCODE opc, INT16 bits, simpnode k0)
{
simpnode wn;
wn = WN_SimplifyCvtl(opc, bits, k0);
if (!wn) {
wn = WN_Create(opc,1);
WN_kid0(wn) = k0;
WN_cvtl_bits(wn) = bits;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
}
}
return(wn);
}
static simpnode WN_SimpCreateExtract(OPCODE opc, INT16 boffset, INT16 bsize, simpnode k0)
{
simpnode wn;
wn = WN_Create(opc,1);
WN_kid0(wn) = k0;
WN_set_bit_offset_size(wn,boffset,bsize);
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
}
return(wn);
}
static simpnode WN_SimpCreateDeposit(OPCODE opc, INT16 boffset, INT16 bsize, simpnode k0, simpnode k1)
{
simpnode wn;
wn = WN_Create(opc,2);
WN_kid0(wn) = k0;
WN_kid1(wn) = k1;
WN_set_bit_offset_size(wn,boffset,bsize);
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k1, (void *) wn);
}
return(wn);
}
static void SIMPNODE_Simplify_Initialize( void )
{
trace_rules = (Get_Trace(TP_WHIRLSIMP, 1) != 0);
trace_trees = (Get_Trace(TP_WHIRLSIMP, 2) != 0);
SIMPNODE_simp_initialized = TRUE;
}
| 27.620232 | 124 | 0.653197 | sharugupta |
398a765b86b2c2511401a8ffcded4ab9c2fa53d7 | 5,374 | cpp | C++ | D3/BillboardParticles.cpp | Sudoka/D3 | 40c43bfc8bc619a344796c69a720be752e660eac | [
"CC-BY-3.0"
] | 1 | 2018-06-21T04:04:45.000Z | 2018-06-21T04:04:45.000Z | D3/BillboardParticles.cpp | Sudoka/D3 | 40c43bfc8bc619a344796c69a720be752e660eac | [
"CC-BY-3.0"
] | null | null | null | D3/BillboardParticles.cpp | Sudoka/D3 | 40c43bfc8bc619a344796c69a720be752e660eac | [
"CC-BY-3.0"
] | null | null | null | //
// BillboardParticles.cpp
// D3
//
// Created by Srđan Rašić on 10/7/12.
// Copyright (c) 2012 Srđan Rašić. All rights reserved.
//
#include "BillboardParticles.hpp"
namespace d3 {
BillboardParticles::BillboardParticles(shared_ptr<ParticleSystem> particle_system) : emitter(particle_system)
{
unsigned max_particle_count = emitter->max_particle_count;
/* Create index buffer */
ibo = shared_ptr<VertexData>(new BufferedVertexData(sizeof(unsigned) * max_particle_count * 6,
sizeof(unsigned), GL_STATIC_DRAW, GL_ELEMENT_ARRAY_BUFFER, NULL));
unsigned * indices = (unsigned *)ibo->mapData();
IndexTemplate tmp;
for (int i = 0; i < max_particle_count * 6; i++)
indices[i] = (i/6)*4 + tmp.indices[i%6];
ibo->unmapData();
/* Create texcoord buffer */
tbo = shared_ptr<VertexData>(new BufferedVertexData(sizeof(Vec3) * 4 * max_particle_count,
sizeof(Vec3), GL_STATIC_DRAW, GL_ARRAY_BUFFER, NULL));
Vec3 * texcoords = (Vec3 *)tbo->mapData();
for (int i = 0; i < max_particle_count; i++) {
texcoords[i*4+0] = Vec3(0, 0, 0);
texcoords[i*4+1] = Vec3(1, 0, 0);
texcoords[i*4+2] = Vec3(1, 1, 0);
texcoords[i*4+3] = Vec3(0, 1, 0);
}
tbo->unmapData();
tbo->setAttribute("in_texcoord", VertexData::AttribProps(0, 2, GL_FLOAT));
/* Create position and colour buffer */
vbo_size = sizeof(VertexTemplate) * 4 * max_particle_count;
vbo = shared_ptr<VertexData>(new BufferedVertexData(vbo_size * getNumberOfOccurrences(),
sizeof(VertexTemplate), GL_STREAM_DRAW, GL_ARRAY_BUFFER, NULL));
vbo->setAttribute("in_position", VertexData::AttribProps(0, 3, GL_FLOAT));
vbo->setAttribute("in_color", VertexData::AttribProps(sizeof(Vec3), 4, GL_UNSIGNED_BYTE, GL_TRUE));
}
//! SceneSimulator::Updatable:: Updates VBO
void BillboardParticles::update(float dt)
{
this->particle_count = emitter->particle_count;
/* Set positions and colors */
vbo->resetSize(sizeof(VertexTemplate) * 4 * particle_count * getNumberOfOccurrences());
VertexTemplate * vbo_array = (VertexTemplate *)vbo->mapData();
unsigned ctr = 0;
for (SceneNode * node : getOriginList()) {
Mat4 cam_transform = Application::get().getScene().getCamera().getTransform() * node->getCachedTransformRef();
Vec3 up(cam_transform.a01, cam_transform.a11, cam_transform.a21);
Vec3 right(cam_transform.a00, cam_transform.a10, cam_transform.a20);
for (unsigned i = 0; i < particle_count; i++) {
unsigned index = (particle_count * ctr + i) * 4;
float size = emitter->properties_array[i].size;
Vec3 position = emitter->properties_array[i].position;
int color = to8BitVec4(emitter->properties_array[i].color);
//Vec4 color = emitter->properties_array[i].color;
vbo_array[index+0].color = color; vbo_array[index+0].position = (up * (-1) - right) * size + position;
vbo_array[index+1].color = color; vbo_array[index+1].position = (up - right) * size + position;
vbo_array[index+2].color = color; vbo_array[index+2].position = (up + right) * size + position;
vbo_array[index+3].color = color; vbo_array[index+3].position = (right - up) * size + position;
}
ctr++;
}
vbo->unmapData();
}
//! Drawable:: Called upon drawing
void BillboardParticles::preDraw(SceneRenderer & renderer)
{
renderer.useProgram("BillboardParticleShader.shader");
renderer.setDepthMask(false);
renderer.setBlend(true);
renderer.setBlendFunc(GL_SRC_ALPHA, GL_ONE);
renderer.useTexture(emitter->properties->texture);
renderer.getProgram().setVertexData(tbo.get());
current_node = 0;
}
//! Drawable:: Draw one occurrence
void BillboardParticles::drawOccurrence(SceneRenderer & renderer, SceneNode & node)
{
Mat4 model_view = node.getScene().getCamera().getTransform() * node.getCachedTransformRef();
Mat4 model_view_projection = node.getScene().getCamera().getProjection() * model_view;
renderer.getProgram().setParamMat4("model_view_projection_matrix", model_view_projection);
renderer.getProgram().setVertexData(vbo.get(), current_node * sizeof(VertexTemplate) * particle_count * 4);
renderer.drawElements(GL_TRIANGLE_STRIP, particle_count * 6, ibo);
current_node++;
}
//! Drawable:: Called after drawing
void BillboardParticles::postDraw(SceneRenderer & renderer)
{
renderer.setDepthMask(true);
renderer.setBlend(false);
renderer.getProgram().disableArrayPtr("in_position");
renderer.getProgram().disableArrayPtr("in_texcoord");
renderer.getProgram().disableArrayPtr("in_color");
}
} | 44.783333 | 126 | 0.598995 | Sudoka |