text string | size int64 | token_count int64 |
|---|---|---|
/*****************************************************************************
* Copyright (C) 2013-2017 MulticoreWare, Inc
*
* Authors: Peixuan Zhang <zhangpeixuancn@gmail.com>
* Chunli Zhang <chunli@multicorewareinc.com>
*
* 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.
*
* 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 02111, USA.
*
* This program is also available under a commercial proprietary license.
* For more information, contact us at license @ x265.com.
*****************************************************************************/
#include "common.h"
#include "reconplay.h"
#include <signal.h>
using namespace X265_NS;
#if _WIN32
#define popen _popen
#define pclose _pclose
#define pipemode "wb"
#else
#define pipemode "w"
#endif
bool ReconPlay::pipeValid;
#ifndef _WIN32
static void sigpipe_handler(int)
{
if (ReconPlay::pipeValid)
general_log(NULL, "exec", X265_LOG_ERROR, "pipe closed\n");
ReconPlay::pipeValid = false;
}
#endif
ReconPlay::ReconPlay(const char* commandLine, x265_param& param)
{
#ifndef _WIN32
if (signal(SIGPIPE, sigpipe_handler) == SIG_ERR)
general_log(¶m, "exec", X265_LOG_ERROR, "Unable to register SIGPIPE handler: %s\n", strerror(errno));
#endif
width = param.sourceWidth;
height = param.sourceHeight;
colorSpace = param.internalCsp;
frameSize = 0;
for (int i = 0; i < x265_cli_csps[colorSpace].planes; i++)
frameSize += (uint32_t)((width >> x265_cli_csps[colorSpace].width[i]) * (height >> x265_cli_csps[colorSpace].height[i]));
for (int i = 0; i < RECON_BUF_SIZE; i++)
{
poc[i] = -1;
CHECKED_MALLOC(frameData[i], pixel, frameSize);
}
outputPipe = popen(commandLine, pipemode);
if (outputPipe)
{
const char* csp = (colorSpace >= X265_CSP_I444) ? "444" : (colorSpace >= X265_CSP_I422) ? "422" : "420";
const char* depth = (param.internalBitDepth == 10) ? "p10" : "";
fprintf(outputPipe, "YUV4MPEG2 W%d H%d F%d:%d Ip C%s%s\n", width, height, param.fpsNum, param.fpsDenom, csp, depth);
pipeValid = true;
threadActive = true;
start();
return;
}
else
general_log(¶m, "exec", X265_LOG_ERROR, "popen(%s) failed\n", commandLine);
fail:
threadActive = false;
}
ReconPlay::~ReconPlay()
{
if (threadActive)
{
threadActive = false;
writeCount.poke();
stop();
}
if (outputPipe)
pclose(outputPipe);
for (int i = 0; i < RECON_BUF_SIZE; i++)
X265_FREE(frameData[i]);
}
bool ReconPlay::writePicture(const x265_picture& pic)
{
if (!threadActive || !pipeValid)
return false;
int written = writeCount.get();
int read = readCount.get();
int currentCursor = pic.poc % RECON_BUF_SIZE;
/* TODO: it's probably better to drop recon pictures when the ring buffer is
* backed up on the display app */
while (written - read > RECON_BUF_SIZE - 2 || poc[currentCursor] != -1)
{
read = readCount.waitForChange(read);
if (!threadActive)
return false;
}
X265_CHECK(pic.colorSpace == colorSpace, "invalid color space\n");
X265_CHECK(pic.bitDepth == X265_DEPTH, "invalid bit depth\n");
pixel* buf = frameData[currentCursor];
for (int i = 0; i < x265_cli_csps[colorSpace].planes; i++)
{
char* src = (char*)pic.planes[i];
int pwidth = width >> x265_cli_csps[colorSpace].width[i];
for (int h = 0; h < height >> x265_cli_csps[colorSpace].height[i]; h++)
{
memcpy(buf, src, pwidth * sizeof(pixel));
src += pic.stride[i];
buf += pwidth;
}
}
poc[currentCursor] = pic.poc;
writeCount.incr();
return true;
}
void ReconPlay::threadMain()
{
THREAD_NAME("ReconPlayOutput", 0);
do
{
/* extract the next output picture in display order and write to pipe */
if (!outputFrame())
break;
}
while (threadActive);
threadActive = false;
readCount.poke();
}
bool ReconPlay::outputFrame()
{
int written = writeCount.get();
int read = readCount.get();
int currentCursor = read % RECON_BUF_SIZE;
while (poc[currentCursor] != read)
{
written = writeCount.waitForChange(written);
if (!threadActive)
return false;
}
char* buf = (char*)frameData[currentCursor];
intptr_t remainSize = frameSize * sizeof(pixel);
fprintf(outputPipe, "FRAME\n");
while (remainSize > 0)
{
intptr_t retCount = (intptr_t)fwrite(buf, sizeof(char), remainSize, outputPipe);
if (retCount < 0 || !pipeValid)
/* pipe failure, stop writing and start dropping recon pictures */
return false;
buf += retCount;
remainSize -= retCount;
}
poc[currentCursor] = -1;
readCount.incr();
return true;
}
| 5,531 | 1,920 |
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --- DYNAMIC-GRAPH --- */
#include "dynamic-graph/pool.h"
#include "dynamic-graph/debug.h"
#include "dynamic-graph/entity.h"
#include <list>
#include <sstream>
#include <string>
#include <typeinfo>
using namespace dynamicgraph;
/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */
PoolStorage *PoolStorage::getInstance() {
if (instance_ == 0) {
instance_ = new PoolStorage;
}
return instance_;
}
void PoolStorage::destroy() {
delete instance_;
instance_ = NULL;
}
PoolStorage::~PoolStorage() {
dgDEBUGIN(15);
for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end();
// Here, this is normal that the next iteration is at the beginning
// of the map as deregisterEntity remove the element iter from the map.
iter = entityMap.begin()) {
dgDEBUG(15) << "Delete \"" << (iter->first) << "\"" << std::endl;
Entity *entity = iter->second;
deregisterEntity(iter);
delete (entity);
}
instance_ = 0;
dgDEBUGOUT(15);
}
/* --------------------------------------------------------------------- */
void PoolStorage::registerEntity(const std::string &entname, Entity *ent) {
Entities::iterator entkey = entityMap.find(entname);
if (entkey != entityMap.end()) // key does exist
{
throw ExceptionFactory(
ExceptionFactory::OBJECT_CONFLICT,
"Another entity already defined with the same name. ",
"Entity name is <%s>.", entname.c_str());
} else {
dgDEBUG(10) << "Register entity <" << entname << "> in the pool."
<< std::endl;
entityMap[entname] = ent;
}
}
void PoolStorage::deregisterEntity(const std::string &entname) {
Entities::iterator entkey = entityMap.find(entname);
if (entkey == entityMap.end()) // key doesnot exist
{
throw ExceptionFactory(ExceptionFactory::OBJECT_CONFLICT,
"Entity not defined yet. ", "Entity name is <%s>.",
entname.c_str());
} else {
dgDEBUG(10) << "Deregister entity <" << entname << "> from the pool."
<< std::endl;
deregisterEntity(entkey);
}
}
void PoolStorage::deregisterEntity(const Entities::iterator &entity) {
entityMap.erase(entity);
}
Entity &PoolStorage::getEntity(const std::string &name) {
dgDEBUG(25) << "Get <" << name << ">" << std::endl;
Entities::iterator entPtr = entityMap.find(name);
if (entPtr == entityMap.end()) {
DG_THROW ExceptionFactory(ExceptionFactory::UNREFERED_OBJECT,
"Unknown entity.", " (while calling <%s>)",
name.c_str());
} else
return *entPtr->second;
}
const PoolStorage::Entities &PoolStorage::getEntityMap() const {
return entityMap;
}
bool PoolStorage::existEntity(const std::string &name) {
return entityMap.find(name) != entityMap.end();
}
bool PoolStorage::existEntity(const std::string &name, Entity *&ptr) {
Entities::iterator entPtr = entityMap.find(name);
if (entPtr == entityMap.end())
return false;
else {
ptr = entPtr->second;
return true;
}
}
void PoolStorage::clearPlugin(const std::string &name) {
dgDEBUGIN(5);
std::list<Entity *> toDelete;
for (Entities::iterator entPtr = entityMap.begin(); entPtr != entityMap.end();
++entPtr)
if (entPtr->second->getClassName() == name)
toDelete.push_back(entPtr->second);
for (std::list<Entity *>::iterator iter = toDelete.begin();
iter != toDelete.end(); ++iter)
delete (Entity *)*iter;
dgDEBUGOUT(5);
}
/* --------------------------------------------------------------------- */
#include <dynamic-graph/entity.h>
#ifdef WIN32
#include <time.h>
#endif /*WIN32*/
void PoolStorage::writeGraph(const std::string &aFileName) {
size_t IdxPointFound = aFileName.rfind(".");
std::string tmp1 = aFileName.substr(0, IdxPointFound);
size_t IdxSeparatorFound = aFileName.rfind("/");
std::string GenericName;
if (IdxSeparatorFound != std::string::npos)
GenericName = tmp1.substr(IdxSeparatorFound, tmp1.length());
else
GenericName = tmp1;
/* Reading local time */
time_t ltime;
ltime = time(NULL);
struct tm ltimeformatted;
#ifdef WIN32
localtime_s(<imeformatted, <ime);
#else
localtime_r(<ime, <imeformatted);
#endif /*WIN32*/
/* Opening the file and writing the first comment. */
std::ofstream GraphFile(aFileName.c_str(), std::ofstream::out);
GraphFile << "/* This graph has been automatically generated. " << std::endl;
GraphFile << " " << 1900 + ltimeformatted.tm_year
<< " Month: " << 1 + ltimeformatted.tm_mon
<< " Day: " << ltimeformatted.tm_mday
<< " Time: " << ltimeformatted.tm_hour << ":"
<< ltimeformatted.tm_min;
GraphFile << " */" << std::endl;
GraphFile << "digraph \"" << GenericName << "\" { ";
GraphFile << "\t graph [ label=\"" << GenericName
<< "\" bgcolor = white rankdir=LR ]" << std::endl
<< "\t node [ fontcolor = black, color = black,"
<< "fillcolor = gold1, style=filled, shape=box ] ; " << std::endl;
GraphFile << "\tsubgraph cluster_Entities { " << std::endl;
GraphFile << "\t} " << std::endl;
for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end();
++iter) {
Entity *ent = iter->second;
GraphFile << "\"" << ent->getName() << "\""
<< " [ label = \"" << ent->getName() << "\" ," << std::endl
<< " fontcolor = black, color = black, fillcolor=cyan,"
<< " style=filled, shape=box ]" << std::endl;
ent->writeGraph(GraphFile);
}
GraphFile << "}" << std::endl;
GraphFile.close();
}
void PoolStorage::writeCompletionList(std::ostream &os) {
for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end();
++iter) {
Entity *ent = iter->second;
ent->writeCompletionList(os);
}
}
static bool objectNameParser(std::istringstream &cmdparse, std::string &objName,
std::string &funName) {
const int SIZE = 128;
char buffer[SIZE];
cmdparse >> std::ws;
cmdparse.getline(buffer, SIZE, '.');
if (!cmdparse.good()) // The callback is not an object method
return false;
objName = buffer;
// cmdparse.getline( buffer,SIZE );
// funName = buffer;
cmdparse >> funName;
return true;
}
SignalBase<int> &PoolStorage::getSignal(std::istringstream &sigpath) {
std::string objname, signame;
if (!objectNameParser(sigpath, objname, signame)) {
DG_THROW ExceptionFactory(ExceptionFactory::UNREFERED_SIGNAL,
"Parse error in signal name");
}
Entity &ent = getEntity(objname);
return ent.getSignal(signame);
}
PoolStorage *PoolStorage::instance_ = 0;
| 7,201 | 2,250 |
/* node_page_test.cc
Rémi Attab, 20 January 2012
Copyright (c) 2012 Datacratic. All rights reserved.
Tests for node_page.h
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include "mmap/node_page.h"
#include "soa/utils/threaded_test.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <thread>
#include <future>
#include <stack>
#include <array>
using namespace std;
using namespace boost;
using namespace Datacratic;
using namespace Datacratic::MMap;
using namespace ML;
// Testing utilities used in both para and seq tests.
template <uint32_t size> struct TestUtil {
typedef GenericNodePage<size> NodeT;
static void checkEmpty (NodeT& nodes) {
BOOST_REQUIRE_EQUAL(nodes.metadata.magic, NodeT::magicNum);
BOOST_REQUIRE_EQUAL(
nodes.metadata.full.numFull(), NodeT::metadataNodes);
}
static void checkSize () {
//Not all NodePages uses the full Page
if (sizeof(NodeT) >= page_size-size && sizeof(NodeT) <= page_size)
return;
cerr << "sizeof(GenericNodePage<" << size << ">)="
<< sizeof(NodeT) << endl;
cerr << "{ numNodes = " << NodeT::numNodes
<< ", sizeof(FullBitmap) = " << sizeof(FullBitmap<NodeT::numNodes>)
<< ", metadataSize = " << NodeT::metadataSize
<< ", metadataNodes = " << NodeT::metadataNodes
<< ", metadataPadding = " << NodeT::metadataPadding
<< "}" << endl;
BOOST_REQUIRE(sizeof(NodeT) == page_size);
}
};
// Test various behaviours when allocating and deallocating in a sequential test
template<uint32_t size> struct SequentialTest {
static void exec () {
typedef GenericNodePage<size> NodeT;
NodeT nodes;
nodes.init();
int64_t offset;
bool needUpdate;
TestUtil<size>::checkSize();
for (int k = 0; k < 3; ++k) {
// Exceptions are thrown but it pollutes the console output so disable it.
#if 0
// Try deallocating metadata nodes
for (int i = 0; i < NodeT::metadataNodes; ++i) {
BOOST_CHECK_THROW(
nodes.deallocate(i*size), ML::Assertion_Failure);
}
#endif
// Fully allocate the page.
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::numNodes-1);
BOOST_REQUIRE_EQUAL(offset, i*size);
}
// Over allocate the page.
for(int i = 0; i < 3; ++i) {
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_LE(offset, -1);
}
// De-allocate and reallocate a random node.
int64_t newOffset = (NodeT::numNodes/2) * size;
needUpdate = nodes.deallocate(newOffset);
BOOST_REQUIRE_EQUAL(needUpdate, true);
tie(offset, needUpdate) = nodes.allocate();
BOOST_REQUIRE_EQUAL(needUpdate, true);
BOOST_REQUIRE_EQUAL(offset, newOffset);
// Fully de-allocate the page.
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
bool needUpdate = nodes.deallocate(i*size);
BOOST_REQUIRE_EQUAL(needUpdate, i == NodeT::metadataNodes);
}
// Exceptions are thrown but it pollutes the console output so disable it.
#if 0
// Over de-allocate the page
for (int i = NodeT::metadataNodes; i < NodeT::numNodes; ++i) {
BOOST_CHECK_THROW(nodes.deallocate(i*size), ML::Exception);
}
#endif
// Make sure everything is properly deallocated.
TestUtil<size>::checkEmpty(nodes);
}
}
};
BOOST_AUTO_TEST_CASE(test_seq) {
SequentialTest<8>::exec();
SequentialTest<12>::exec();
SequentialTest<32>::exec();
SequentialTest<64>::exec();
SequentialTest<96>::exec();
SequentialTest<192>::exec();
SequentialTest<256>::exec();
}
// Starts a truck load of tests that randomly allocates and frees nodes.
template<uint32_t size>
struct ParallelTest
{
enum {
threadCount = 4,
iterationCount = 10000
};
typedef GenericNodePage<size> NodeT;
NodeT nodes;
bool allocateNode (stack<int64_t>& s) {
int64_t offset = nodes.allocate().first;
if (offset >= 0) {
s.push(offset);
return true;
}
return false;
}
void deallocateHead(stack<int64_t>& s) {
nodes.deallocate(s.top());
s.pop();
}
void runThread (int id) {
mt19937 engine(id);
uniform_int_distribution<int> opDist(0, 1);
uniform_int_distribution<int> numDist(0, size);
stack<int64_t> allocatedOffsets;
for (int i = 0; i < iterationCount; ++i) {
if (allocatedOffsets.empty()) {
if (!allocateNode(allocatedOffsets)) {
// nothing to allocate or deallocate,
// take a nap and try again.
std::this_thread::yield();
}
continue;
}
else if (opDist(engine) && allocateNode(allocatedOffsets)) {
for (int j = numDist(engine); j > 0; --j) {
if (!allocateNode(allocatedOffsets)) {
break;
}
}
continue;
}
// De-allocate if space is full or we're randomly chosen.
for (int j = numDist(engine);
!allocatedOffsets.empty() && j > 0;
--j)
{
deallocateHead(allocatedOffsets);
}
}
// We're done, cleanup.
while (!allocatedOffsets.empty()) {
deallocateHead(allocatedOffsets);
}
}
void exec() {
nodes.init();
auto runFn = [&] (int id) {
this->runThread(id);
return 0;
};
ThreadedTest test;
test.start(runFn, threadCount);
test.joinAll(10000);
// Make sure everything is properly deallocated.
TestUtil<size>::checkEmpty(nodes);
}
};
BOOST_AUTO_TEST_CASE(test_para) {
ParallelTest<8>().exec();
ParallelTest<48>().exec();
ParallelTest<64>().exec();
ParallelTest<192>().exec();
ParallelTest<256>().exec();
}
| 6,500 | 2,055 |
#include <iostream>
#include "parser.h"
using namespace std;
#define MAX_LINE 50000
int parse_tick(string market, string line, struct Tick* p)
{
size_t num = 0;
unsigned pre = 0;
int ret = -1;
struct Tick tick;
sprintf_s(tick.ExchangeID, "%s", market.c_str());
while ((ret = line.find(',', pre)) > 0)
{
string element = line.substr(pre, ret - pre);
int line_len = element.size();
if (num == 0)
{
string t0 = element.substr(0, 8);
string t1 = element.substr(8, line_len - 3 - 8);
string t2 = element.substr(line_len - 3, 3);
tick.ActionDay = atoi(t0.c_str());
tick.TradingDay = tick.ActionDay;
tick.UpdateTime = atoi(t1.c_str());
tick.UpdateMillisec = atoi(t2.c_str());
}
else if (num == 1)
{
sprintf_s(tick.Symbol, "%s", element.c_str());
sprintf_s(tick.InstrumentID, "%s", element.c_str());
}
else if (num == 2)
{
tick.OpenPrice = atof(element.c_str());
}
else if (num == 3)
{
tick.ClosePrice = atof(element.c_str());
}
else if (num == 4)
{
tick.HighestPrice = atof(element.c_str());
}
else if (num == 5)
{
tick.LowestPrice = atof(element.c_str());
}
else if (num == 6)
{
tick.Turnover = atof(element.c_str());
}
else if (num == 7)
{
tick.Volume = atoi(element.c_str());
}
else if (num == 8)
{
tick.LastPrice = atof(element.c_str());
}
else if (num == 9)
{
tick.AveragePrice = atof(element.c_str());
}
else if (num == 10)
{
tick.PreClosePrice = atof(element.c_str());
}
else if (num == 11)
{
tick.UpperLimitPrice = atof(element.c_str());
}
else if (num == 12)
{
tick.LowerLimitPrice = atof(element.c_str());
}
else if (num == 13)
{
tick.OpenInterest = atoll(element.c_str());
}
else if (num == 14)
{
tick.PreOpenInterest = atoll(element.c_str());
}
else if (num == 15)
{
tick.PreSettlementPrice = atof(element.c_str());
}
else if (num == 16)
{
tick.SettlementPrice = atof(element.c_str());
}
else if (num == 17)
{
tick.AskPrice1 = atof(element.c_str());
}
else if (num == 18)
{
tick.AskPrice2 = atof(element.c_str());
}
else if (num == 19)
{
tick.AskPrice3 = atof(element.c_str());
}
else if (num == 20)
{
tick.AskPrice4 = atof(element.c_str());
}
else if (num == 21)
{
tick.AskPrice5 = atof(element.c_str());
}
else if (num == 22)
{
tick.AskVolume1 = atoi(element.c_str());
}
else if (num == 23)
{
tick.AskVolume2 = atoi(element.c_str());
}
else if (num == 24)
{
tick.AskVolume3 = atoi(element.c_str());
}
else if (num == 25)
{
tick.AskVolume4 = atoi(element.c_str());
}
else if (num == 26)
{
tick.AskVolume5 = atoi(element.c_str());
}
else if (num == 27)
{
tick.BidPrice1 = atof(element.c_str());
}
else if (num == 28)
{
tick.BidPrice2 = atof(element.c_str());
}
else if (num == 29)
{
tick.BidPrice3 = atof(element.c_str());
}
else if (num == 30)
{
tick.BidPrice4 = atof(element.c_str());
}
else if (num == 31)
{
tick.BidPrice5 = atof(element.c_str());
}
else if (num == 32)
{
tick.BidVolume1 = atoi(element.c_str());
}
else if (num == 33)
{
tick.BidVolume2 = atoi(element.c_str());
}
else if (num == 34)
{
tick.BidVolume3 = atoi(element.c_str());
}
else if (num == 35)
{
tick.BidVolume4 = atoi(element.c_str());
}
pre = ret + 1;
num++;
}
string element = line.substr(pre, line.size() - pre);
tick.BidVolume5 = atoi(element.c_str());
memcpy(p, &tick, sizeof(struct Tick));
return 0;
}
size_t append_csv2_buffer(string market, string csv, struct Tick* ptr, size_t ava_num)
{
size_t num = 0;
unsigned pre = 0;
int ret = -1;
while ((ret = csv.find('\n', pre)) > 0)
{
string line = csv.substr(pre, ret + 1 - pre);
if (num < ava_num)
{
if (0 == parse_tick(market, line, ptr + num))
{
num++;
}
}
else
{
break;
}
pre = ret + 1;
}
return num;
}
int parse_string(const char* c_market,const char* content, struct Tick** result, unsigned* len)
{
string market(c_market);
string tts((const char*)content);
*result = (struct Tick*)malloc(sizeof(struct Tick) * MAX_LINE);
int ava_num = MAX_LINE;
*len = append_csv2_buffer(market, tts, *result,ava_num);
return 0;
}
void m_FreeMem(void* ptr)
{
free(ptr);
} | 5,557 | 1,922 |
#include<bits/stdc++.h>
using namespace std;
int AddN(int n)
{
if(n==0)
{
return 0;
}
int presum = AddN(n-1);
return n + presum;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
cout<<AddN(n);
return 0;
} | 335 | 151 |
/**************************************************************************
* Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appeuear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//
//
// Base class for DStar Analysis
//
//
// The D* spectra study is done in pt bins:
// [0,0.5] [0.5,1] [1,2] [2,3] [3,4] [4,5] [5,6] [6,7] [7,8],
// [8,10],[10,12], [12,16], [16,20] and [20,24]
//
// Cuts arew centralized in AliRDHFCutsDStartoKpipi
// Side Band and like sign background are implemented in the macro
//
//-----------------------------------------------------------------------
//
// Author A.Grelli
// ERC-QGP Utrecht University - a.grelli@uu.nl,
// Author Y.Wang
// University of Heidelberg - yifei@physi.uni-heidelberg.de
// Author C.Ivan
// ERC-QGP Utrecht University - c.ivan@uu.nl,
//
// modified for EMCAL production check
//-----------------------------------------------------------------------
#include <TSystem.h>
#include <TParticle.h>
#include <TH1I.h>
#include "TROOT.h"
#include <TDatabasePDG.h>
#include <AliAnalysisDataSlot.h>
#include <AliAnalysisDataContainer.h>
#include "AliRDHFCutsDStartoKpipi.h"
#include "AliMCEvent.h"
#include "AliAnalysisManager.h"
#include "AliAODMCHeader.h"
#include "AliAODHandler.h"
#include "AliLog.h"
#include "AliAODVertex.h"
#include "AliAODRecoDecay.h"
#include "AliAODRecoDecayHF.h"
#include "AliAODRecoCascadeHF.h"
#include "AliAODRecoDecayHF2Prong.h"
#include "AliAnalysisVertexingHF.h"
#include "AliESDtrack.h"
#include "AliAODMCParticle.h"
#include "AliNormalizationCounter.h"
#include "AliAODEvent.h"
#include "AliAnalysisTaskSEDStarEMCALProductionCheck.h"
#include "AliEmcalTriggerDecisionContainer.h"
#include "AliInputEventHandler.h"
#include "AliTrackerBase.h"
#include "AliGenPythiaEventHeader.h"
/// \cond CLASSIMP
ClassImp(AliAnalysisTaskSEDStarEMCALProductionCheck);
/// \endcond
//__________________________________________________________________________
AliAnalysisTaskSEDStarEMCALProductionCheck::AliAnalysisTaskSEDStarEMCALProductionCheck():
AliAnalysisTaskSE(),
fEvents(0),
fAnalysis(0),
fD0Window(0),
fPeakWindow(0),
fUseMCInfo(kFALSE),
fDoSearch(kFALSE),
fOutput(0),
fOutputAll(0),
fOutputPID(0),
fOutputProductionCheck(0),
fNSigma(3),
fCuts(0),
fCEvents(0),
fTrueDiff2(0),
fDeltaMassD1(0),
fCounter(0),
fAODProtection(1),
fDoImpParDstar(kFALSE),
fNImpParBins(400),
fLowerImpPar(-2000.),
fHigherImpPar(2000.),
fNPtBins(0),
fAllhist(0x0),
fPIDhist(0x0),
fDoDStarVsY(kFALSE),
fUseEMCalTrigger(kFALSE),
fTriggerSelectionString(0),
fCheckEMCALAcceptance(kFALSE),
fCheckEMCALAcceptanceNumber(0),
fApplyEMCALClusterEventCut(kFALSE)
{
//
/// Default ctor
//
for (Int_t i = 0; i < 5; i++) fHistMassPtImpParTCDs[i] = 0;
}
//___________________________________________________________________________
AliAnalysisTaskSEDStarEMCALProductionCheck::AliAnalysisTaskSEDStarEMCALProductionCheck(const Char_t* name, AliRDHFCutsDStartoKpipi* cuts) :
AliAnalysisTaskSE(name),
fEvents(0),
fAnalysis(0),
fD0Window(0),
fPeakWindow(0),
fUseMCInfo(kFALSE),
fDoSearch(kFALSE),
fOutput(0),
fOutputAll(0),
fOutputPID(0),
fOutputProductionCheck(0),
fNSigma(3),
fCuts(0),
fCEvents(0),
fTrueDiff2(0),
fDeltaMassD1(0),
fCounter(0),
fAODProtection(1),
fDoImpParDstar(kFALSE),
fNImpParBins(400),
fLowerImpPar(-2000.),
fHigherImpPar(2000.),
fNPtBins(0),
fAllhist(0x0),
fPIDhist(0x0),
fDoDStarVsY(kFALSE),
fUseEMCalTrigger(kFALSE),
fTriggerSelectionString(0),
fCheckEMCALAcceptance(kFALSE),
fCheckEMCALAcceptanceNumber(0),
fApplyEMCALClusterEventCut(kFALSE)
{
//
/// Constructor. Initialization of Inputs and Outputs
//
Info("AliAnalysisTaskSEDStarEMCALProductionCheck", "Calling Constructor");
fCuts = cuts;
for (Int_t i = 0; i < 5; i++) fHistMassPtImpParTCDs[i] = 0;
DefineOutput(1, TList::Class()); //counters
DefineOutput(2, TList::Class()); //All Entries output
DefineOutput(3, TList::Class()); //3sigma PID output
DefineOutput(4, AliRDHFCutsDStartoKpipi::Class()); //My private output
DefineOutput(5, AliNormalizationCounter::Class()); // normalization
DefineOutput(6, TList::Class()); //production check
}
//___________________________________________________________________________
AliAnalysisTaskSEDStarEMCALProductionCheck::~AliAnalysisTaskSEDStarEMCALProductionCheck() {
//
/// destructor
//
Info("~AliAnalysisTaskSEDStarEMCALProductionCheck", "Calling Destructor");
delete fOutput;
delete fOutputAll;
delete fOutputPID;
delete fOutputProductionCheck;
delete fCuts;
delete fCEvents;
delete fDeltaMassD1;
for (Int_t i = 0; i < 5; i++) {
delete fHistMassPtImpParTCDs[i];
}
for (Int_t i = 0; i < ((fNPtBins + 2) * 18); i++) {
delete fAllhist[i];
delete fPIDhist[i];
}
delete [] fAllhist;
delete [] fPIDhist;
}
//_________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::Init() {
//
/// Initialization
//
if (fDebug > 1) printf("AnalysisTaskSEDStarSpectra::Init() \n");
AliRDHFCutsDStartoKpipi* copyfCuts = new AliRDHFCutsDStartoKpipi(*fCuts);
fNPtBins = fCuts->GetNPtBins();
// Post the data
PostData(4, copyfCuts);
return;
}
//_________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::UserExec(Option_t *)
{
/// user exec
if (!fInputEvent) {
Error("UserExec", "NO EVENT FOUND!");
return;
}
fCEvents->Fill(0);//all events
if (fAODProtection >= 0) {
// Protection against different number of events in the AOD and deltaAOD
// In case of discrepancy the event is rejected.
Int_t matchingAODdeltaAODlevel = AliRDHFCuts::CheckMatchingAODdeltaAODevents();
if (matchingAODdeltaAODlevel < 0 || (matchingAODdeltaAODlevel == 0 && fAODProtection == 1)) {
// AOD/deltaAOD trees have different number of entries || TProcessID do not match while it was required
fCEvents->Fill(8);
return;
}
fCEvents->Fill(1);
}
fEvents++;
AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(fInputEvent);
TClonesArray *arrayDStartoD0pi = 0;
TClonesArray *arrayD0toKpi = 0;
if (!aodEvent && AODEvent() && IsStandardAOD()) {
// In case there is an AOD handler writing a standard AOD, use the AOD
// event in memory rather than the input (ESD) event.
aodEvent = dynamic_cast<AliAODEvent*> (AODEvent());
// in this case the braches in the deltaAOD (AliAOD.VertexingHF.root)
// have to taken from the AOD event hold by the AliAODExtension
AliAODHandler* aodHandler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
if (aodHandler->GetExtensions()) {
AliAODExtension *ext = (AliAODExtension*)aodHandler->GetExtensions()->FindObject("AliAOD.VertexingHF.root");
AliAODEvent *aodFromExt = ext->GetAOD();
arrayDStartoD0pi = (TClonesArray*)aodFromExt->GetList()->FindObject("Dstar");
arrayD0toKpi = (TClonesArray*)aodFromExt->GetList()->FindObject("D0toKpi");
}
} else {
arrayDStartoD0pi = (TClonesArray*)aodEvent->GetList()->FindObject("Dstar");
arrayD0toKpi = (TClonesArray*)aodEvent->GetList()->FindObject("D0toKpi");
}
//objects for production check
AliAODMCHeader *mcHeader = nullptr;
AliGenPythiaEventHeader * pythiaHeader = nullptr;
TClonesArray *mcTrackArray = nullptr;
Double_t crossSection = 0.0;
Double_t ptHard = 0.0;
Int_t nTrials = 0;
// Int_t nPtBins = fCuts->GetNPtBins();
// const Int_t nPtBinLimits = nPtBins + 1;
// Int_t PtBinLimits[nPtBinLimits] = fCuts->GetPtBinLimits();
if (fUseMCInfo) {
// load MC header
mcHeader = (AliAODMCHeader*)aodEvent->GetList()->FindObject(AliAODMCHeader::StdBranchName());
if (!mcHeader) {
printf("AliAnalysisTaskSEDStarEMCALProductionCheck::UserExec: MC header branch not found!\n");
return;
}
AliGenPythiaEventHeader * pythiaHeader = (AliGenPythiaEventHeader*)mcHeader->GetCocktailHeader(0);
if (!pythiaHeader) {
printf("AliAnalysisTaskSEDStarEMCALProductionCheck::UserExec: AliGenPythiaEventHeader not found!\n");
return;
}
crossSection = pythiaHeader->GetXsection();
ptHard = pythiaHeader->GetPtHard();
nTrials = pythiaHeader->Trials();
mcTrackArray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcTrackArray) {std::cout << "no track array" << std::endl; return;};
}
// check before event cut
if (fUseMCInfo) {
for (Int_t j = 0; j < mcTrackArray->GetEntriesFast(); j++) {
AliAODMCParticle *mcTrackParticle = dynamic_cast< AliAODMCParticle*>(mcTrackArray->At(j));
if (!mcTrackParticle) {std::cout << "no particle" << std::endl; continue;}
Int_t pdgCodeMC = TMath::Abs(mcTrackParticle->GetPdgCode());
if (pdgCodeMC == 413)
{ //if the track is a DStar we check if it comes from charm
Double_t ptMC = mcTrackParticle->Pt();
Bool_t fromCharm = kFALSE;
Int_t mother = mcTrackParticle->GetMother();
Int_t istep = 0;
while (mother >= 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(mcTrackArray->At(mother));
if (mcGranma) {
Int_t abspdgGranma = TMath::Abs(mcGranma->GetPdgCode());
if ((abspdgGranma == 4) || (abspdgGranma > 400 && abspdgGranma < 500) || (abspdgGranma > 4000 && abspdgGranma < 5000)) fromCharm = kTRUE;
mother = mcGranma->GetMother();
} else {
printf("AliVertexingHFUtils::IsTrackFromCharm: Failed casting the mother particle!");
break;
}
}
if (fromCharm)
{
Bool_t mcPionDStarPresent = kFALSE;
Bool_t mcPionD0Present = kFALSE;
Bool_t mcKaonPresent = kFALSE;
Int_t nDaughterDStar = mcTrackParticle->GetNDaughters();
if (nDaughterDStar == 2) {
for (Int_t iDaughterDStar = 0; iDaughterDStar < 2; iDaughterDStar++) {
AliAODMCParticle* daughterDStar = (AliAODMCParticle*)mcTrackArray->At(mcTrackParticle->GetDaughterLabel(iDaughterDStar));
if (!daughterDStar) break;
Int_t pdgCodeDaughterDStar = TMath::Abs(daughterDStar->GetPdgCode());
if (pdgCodeDaughterDStar == 211) { //if the track is a pion we save its monte carlo label
mcPionDStarPresent = kTRUE;
} else if (pdgCodeDaughterDStar == 421) { //if the track is a D0 we look at its daughters
Int_t mcLabelD0 = mcTrackParticle->GetDaughterLabel(iDaughterDStar);
Int_t nDaughterD0 = daughterDStar->GetNDaughters();
if (nDaughterD0 == 2) {
for (Int_t iDaughterD0 = 0; iDaughterD0 < 2; iDaughterD0++) {
AliAODMCParticle* daughterD0 = (AliAODMCParticle*)mcTrackArray->At(daughterDStar->GetDaughterLabel(iDaughterD0));
if (!daughterD0) break;
Int_t pdgCodeDaughterD0 = TMath::Abs(daughterD0->GetPdgCode());
if (pdgCodeDaughterD0 == 211) {
mcPionD0Present = kTRUE;
} else if (pdgCodeDaughterD0 == 321) {
mcKaonPresent = kTRUE;
} else break;
}
}
} else break;
}
}
if (mcPionDStarPresent && mcPionD0Present && mcKaonPresent)
{
TString fillthis = "";
fillthis = "DStarPtTruePreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStarPtTruePreEventSelectionWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
// fillthis = "PtHardPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard);
// fillthis = "PtHardWeightedPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard, crossSection);
// fillthis = "WeightsPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(crossSection);
// fillthis = "TrialsPreEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->AddBinContent(1,nTrials);
fillthis = "DStar_per_bin_true_PreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStar_per_bin_true_PreEventSelection_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
}
}
}
}
}
TString fillthishist = "";
fillthishist = "PtHardPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard);
fillthishist = "PtHardWeightedPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard, crossSection);
fillthishist = "WeightsPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(crossSection);
fillthishist = "TrialsPreEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->AddBinContent(1,nTrials);
// fix for temporary bug in ESDfilter
// the AODs with null vertex pointer didn't pass the PhysSel
if (!aodEvent->GetPrimaryVertex() || TMath::Abs(aodEvent->GetMagneticField()) < 0.001) return;
fCEvents->Fill(2);
fCounter->StoreEvent(aodEvent, fCuts, fUseMCInfo);
// trigger class for PbPb C0SMH-B-NOPF-ALLNOTRD
TString trigclass = aodEvent->GetFiredTriggerClasses();
if (trigclass.Contains("C0SMH-B-NOPF-ALLNOTRD") || trigclass.Contains("C0SMH-B-NOPF-ALL")) fCEvents->Fill(5);
if (!fCuts->IsEventSelected(aodEvent)) {
if (fCuts->GetWhyRejection() == 6) // rejected for Z vertex
fCEvents->Fill(6);
return;
}
// Use simulated EMCal trigger for MC. AliEmcalTriggerMakerTask needs to be run first.
if (fUseEMCalTrigger)
{
auto triggercont = static_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer*>(fInputEvent->FindListObject("EmcalTriggerDecision"));
if (!triggercont)
{
AliErrorStream() << "Trigger decision container not found in event - not possible to select EMCAL triggers" << std::endl;
return;
}
if (fTriggerSelectionString == "EG1DG1")
{
if (!triggercont->IsEventSelected("EG1") && !triggercont->IsEventSelected("DG1")) return;
} else if (!triggercont->IsEventSelected(fTriggerSelectionString)) return;
}
// Get field for EMCAL acceptance and cut events
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler());
inputHandler->SetNeedField();
if (fApplyEMCALClusterEventCut)
{
Int_t numberOfCaloClustersEvent = aodEvent->GetNumberOfCaloClusters();
if (numberOfCaloClustersEvent >= 0)
{
Bool_t passClusterCuts = kFALSE;
for (Int_t iCluster = 0; iCluster < numberOfCaloClustersEvent; ++iCluster)
{
AliAODCaloCluster * trackEMCALCluster = (AliAODCaloCluster*)aodEvent->GetCaloCluster(iCluster);
if (trackEMCALCluster->GetNonLinCorrEnergy() < 9.0) continue;
if (trackEMCALCluster->GetTOF() > 15e-9) continue;
if (trackEMCALCluster->GetTOF() < -20e-9) continue;
if (trackEMCALCluster->GetIsExotic()) continue;
passClusterCuts = kTRUE;
}
if (!passClusterCuts) return;
} else return;
}
Bool_t isEvSel = fCuts->IsEventSelected(aodEvent);
fCEvents->Fill(3);
if (!isEvSel) return;
// Load the event
// AliInfo(Form("Event %d",fEvents));
//if (fEvents%10000 ==0) AliInfo(Form("Event %d",fEvents));
// counters for efficiencies
Int_t icountReco = 0;
//D* and D0 prongs needed to MatchToMC method
Int_t pdgDgDStartoD0pi[2] = {421, 211};
Int_t pdgDgD0toKpi[2] = {321, 211};
// AOD primary vertex
AliAODVertex *vtx1 = (AliAODVertex*)aodEvent->GetPrimaryVertex();
if (!vtx1) return;
if (vtx1->GetNContributors() < 1) return;
fCEvents->Fill(4);
//save cluster information for EMCal trigger selection check
Int_t numberOfCaloClustersEvent = aodEvent->GetNumberOfCaloClusters();
if (numberOfCaloClustersEvent >= 0)
{
for (Int_t iCluster = 0; iCluster < numberOfCaloClustersEvent; ++iCluster)
{
AliAODCaloCluster * trackEMCALCluster = (AliAODCaloCluster*)aodEvent->GetCaloCluster(iCluster);
//save cluster information
Float_t pos[3]={0};
trackEMCALCluster->GetPosition(pos);
TString fillthis = "";
fillthis = "fHistClusPosition";
((TH3F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(pos[0], pos[1], pos[2]);
}
}
if (!arrayDStartoD0pi || !arrayD0toKpi) {
AliInfo("Could not find array of HF vertices, skipping the event");
return;
} else AliDebug(2, Form("Found %d vertices", arrayDStartoD0pi->GetEntriesFast()));
Int_t nSelectedAna = 0;
Int_t nSelectedProd = 0;
// check after event cut
if (fUseMCInfo) {
for (Int_t j = 0; j < mcTrackArray->GetEntriesFast(); j++) {
AliAODMCParticle *mcTrackParticle = dynamic_cast< AliAODMCParticle*>(mcTrackArray->At(j));
if (!mcTrackParticle) {std::cout << "no particle" << std::endl; continue;}
Int_t pdgCodeMC = TMath::Abs(mcTrackParticle->GetPdgCode());
if (pdgCodeMC == 413)
{ //if the track is a DStar we check if it comes from charm
Double_t ptMC = mcTrackParticle->Pt();
Bool_t fromCharm = kFALSE;
Int_t mother = mcTrackParticle->GetMother();
Int_t istep = 0;
while (mother >= 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(mcTrackArray->At(mother));
if (mcGranma) {
Int_t abspdgGranma = TMath::Abs(mcGranma->GetPdgCode());
if ((abspdgGranma == 4) || (abspdgGranma > 400 && abspdgGranma < 500) || (abspdgGranma > 4000 && abspdgGranma < 5000)) fromCharm = kTRUE;
mother = mcGranma->GetMother();
} else {
printf("AliVertexingHFUtils::IsTrackFromCharm: Failed casting the mother particle!");
break;
}
}
if (fromCharm)
{
Bool_t mcPionDStarPresent = kFALSE;
Bool_t mcPionD0Present = kFALSE;
Bool_t mcKaonPresent = kFALSE;
Int_t nDaughterDStar = mcTrackParticle->GetNDaughters();
if (nDaughterDStar == 2) {
for (Int_t iDaughterDStar = 0; iDaughterDStar < 2; iDaughterDStar++) {
AliAODMCParticle* daughterDStar = (AliAODMCParticle*)mcTrackArray->At(mcTrackParticle->GetDaughterLabel(iDaughterDStar));
if (!daughterDStar) break;
Int_t pdgCodeDaughterDStar = TMath::Abs(daughterDStar->GetPdgCode());
if (pdgCodeDaughterDStar == 211) { //if the track is a pion we save its monte carlo label
mcPionDStarPresent = kTRUE;
} else if (pdgCodeDaughterDStar == 421) { //if the track is a D0 we look at its daughters
Int_t mcLabelD0 = mcTrackParticle->GetDaughterLabel(iDaughterDStar);
Int_t nDaughterD0 = daughterDStar->GetNDaughters();
if (nDaughterD0 == 2) {
for (Int_t iDaughterD0 = 0; iDaughterD0 < 2; iDaughterD0++) {
AliAODMCParticle* daughterD0 = (AliAODMCParticle*)mcTrackArray->At(daughterDStar->GetDaughterLabel(iDaughterD0));
if (!daughterD0) break;
Int_t pdgCodeDaughterD0 = TMath::Abs(daughterD0->GetPdgCode());
if (pdgCodeDaughterD0 == 211) {
mcPionD0Present = kTRUE;
} else if (pdgCodeDaughterD0 == 321) {
mcKaonPresent = kTRUE;
} else break;
}
}
} else break;
}
}
if (mcPionDStarPresent && mcPionD0Present && mcKaonPresent)
{
TString fillthis = "";
fillthis = "DStarPtTruePostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStarPtTruePostEventSelectionWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
// fillthis = "PtHardPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard);
// fillthis = "PtHardWeightedPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard, crossSection);
// fillthis = "WeightsPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(crossSection);
// fillthis = "TrialsPostEventSelection";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->AddBinContent(1,nTrials);
fillthis = "DStar_per_bin_true_PostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStar_per_bin_true_PostEventSelection_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
}
}
}
}
}
fillthishist = "";
fillthishist = "PtHardPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard);
fillthishist = "PtHardWeightedPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard, crossSection);
fillthishist = "WeightsPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(crossSection);
fillthishist = "TrialsPostEventSelection";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->AddBinContent(1,nTrials);
// vHF object is needed to call the method that refills the missing info of the candidates
// if they have been deleted in dAOD reconstruction phase
// in order to reduce the size of the file
AliAnalysisVertexingHF *vHF = new AliAnalysisVertexingHF();
// loop over the tracks to search for candidates soft pion
for (Int_t iDStartoD0pi = 0; iDStartoD0pi < arrayDStartoD0pi->GetEntriesFast(); iDStartoD0pi++) {
// D* candidates and D0 from D*
AliAODRecoCascadeHF* dstarD0pi = (AliAODRecoCascadeHF*)arrayDStartoD0pi->At(iDStartoD0pi);
AliAODRecoDecayHF2Prong *trackD0;
if (dstarD0pi->GetIsFilled() < 1) {
trackD0 = (AliAODRecoDecayHF2Prong*)arrayD0toKpi->At(dstarD0pi->GetProngID(1));
} else {
trackD0 = (AliAODRecoDecayHF2Prong*)dstarD0pi->Get2Prong();
}
fCEvents->Fill(10);
TObjArray arrTracks(3);
for (Int_t ipr = 0; ipr < 3; ipr++) {
AliAODTrack *tr;
if (ipr == 0) tr = vHF->GetProng(aodEvent, dstarD0pi, ipr); //soft pion
else tr = vHF->GetProng(aodEvent, trackD0, ipr - 1); //D0 daughters
arrTracks.AddAt(tr, ipr);
}
if (!fCuts->PreSelect(arrTracks)) {
fCEvents->Fill(13);
continue;
}
Bool_t isDStarCand = kTRUE;
if (!(vHF->FillRecoCasc(aodEvent, dstarD0pi, isDStarCand))) { //Fill the data members of the candidate only if they are empty.
fCEvents->Fill(12); //monitor how often this fails
continue;
}
if (!dstarD0pi->GetSecondaryVtx()) continue;
AliAODRecoDecayHF2Prong* theD0particle = (AliAODRecoDecayHF2Prong*)dstarD0pi->Get2Prong();
if (!theD0particle) continue;
Int_t isDStar = 0;
TClonesArray *mcArray = 0;
// AliAODMCHeader *mcHeader = 0;
Bool_t isPrimary = kTRUE;
Float_t pdgCode = -2;
Float_t trueImpParXY = 0.;
// mc analysis
if (fUseMCInfo) {
//MC array need for maching
mcArray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName()));
if (!mcArray) {
AliError("Could not find Monte-Carlo in AOD");
return;
}
// load MC header
// mcHeader = (AliAODMCHeader*)aodEvent->GetList()->FindObject(AliAODMCHeader::StdBranchName());
// if (!mcHeader) {
// printf("AliAnalysisTaskSEDplus::UserExec: MC header branch not found!\n");
// return;
// }
// find associated MC particle for D* ->D0toKpi
Int_t mcLabel = dstarD0pi->MatchToMC(413, 421, pdgDgDStartoD0pi, pdgDgD0toKpi, mcArray);
if (mcLabel >= 0) {
AliAODMCParticle *partDSt = (AliAODMCParticle*)mcArray->At(mcLabel);
Int_t checkOrigin = CheckOrigin(mcArray, partDSt);
if (checkOrigin == 5) isPrimary = kFALSE;
AliAODMCParticle *dg0 = (AliAODMCParticle*)mcArray->At(partDSt->GetDaughterLabel(0));
// AliAODMCParticle *dg01 = (AliAODMCParticle*)mcArray->At(dg0->GetDaughterLabel(0));
pdgCode = TMath::Abs(partDSt->GetPdgCode());
if (!isPrimary) {
trueImpParXY = GetTrueImpactParameterD0(mcHeader, mcArray, dg0) * 1000.;
}
isDStar = 1;
} else {
pdgCode = -1;
}
}
if (pdgCode == -1) AliDebug(2, "No particle assigned! check\n");
Double_t Dstarpt = dstarD0pi->Pt();
// quality selction on tracks and region of interest
Int_t isTkSelected = fCuts->IsSelected(dstarD0pi, AliRDHFCuts::kTracks); // quality cuts on tracks
if (!isTkSelected) continue;
if (!fCuts->IsInFiducialAcceptance(dstarD0pi->Pt(), dstarD0pi->YDstar())) continue;
// EMCAL acceptance check
if (fCheckEMCALAcceptance)
{
Int_t numberInAcc = 0;
AliAODTrack *track[3];
for (Int_t iDaught = 0; iDaught < 3; iDaught++) {
track[iDaught] = (AliAODTrack*)arrTracks.At(iDaught);
Int_t numberOfCaloClusters = aodEvent->GetNumberOfCaloClusters();
if (numberOfCaloClusters >= 0)
{
Int_t trackEMCALClusterNumber = track[iDaught]->GetEMCALcluster();
if (!(trackEMCALClusterNumber < 0))
{
AliAODCaloCluster * trackEMCALCluster = (AliAODCaloCluster*)aodEvent->GetCaloCluster(trackEMCALClusterNumber);
if (!trackEMCALCluster) continue;
if (trackEMCALCluster->GetNonLinCorrEnergy() < 9.0) continue;
if (trackEMCALCluster->GetTOF() > 15e-9) continue;
if (trackEMCALCluster->GetTOF() < -20e-9) continue;
if (trackEMCALCluster->GetIsExotic()) continue;
numberInAcc++;
}
}
}
// Cut on number of events in EMCAL acceptance
if (numberInAcc < fCheckEMCALAcceptanceNumber) continue;
}
//histos for impact par studies - D0!!!
Double_t ptCand = dstarD0pi->Get2Prong()->Pt();
Double_t invMass = dstarD0pi->InvMassD0();
Double_t impparXY = dstarD0pi->Get2Prong()->ImpParXY() * 10000.;
Double_t arrayForSparse[3] = {invMass, ptCand, impparXY};
Double_t arrayForSparseTrue[3] = {invMass, ptCand, trueImpParXY};
// set the D0 and D* search window bin by bin - D* window useful to speed up the reconstruction and D0 window used *ONLY* to calculate side band bkg for the background subtraction methods, for the standard analysis the value in the cut file is considered
if (0 <= Dstarpt && Dstarpt < 0.5) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.020;
fPeakWindow = 0.0018;
}
}
if (0.5 <= Dstarpt && Dstarpt < 1.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.020;
fPeakWindow = 0.0018;
}
}
if (1.0 <= Dstarpt && Dstarpt < 2.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.020;
fPeakWindow = 0.0018;
}
}
if (2.0 <= Dstarpt && Dstarpt < 3.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.022;
fPeakWindow = 0.0016;
}
}
if (3.0 <= Dstarpt && Dstarpt < 4.0) {
if (fAnalysis == 1) {
fD0Window = 0.035;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.0014;
}
}
if (4.0 <= Dstarpt && Dstarpt < 5.0) {
if (fAnalysis == 1) {
fD0Window = 0.045;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.0014;
}
}
if (5.0 <= Dstarpt && Dstarpt < 6.0) {
if (fAnalysis == 1) {
fD0Window = 0.045;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.006;
}
}
if (6.0 <= Dstarpt && Dstarpt < 7.0) {
if (fAnalysis == 1) {
fD0Window = 0.055;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.006;
}
}
if (Dstarpt >= 7.0) {
if (fAnalysis == 1) {
fD0Window = 0.074;
fPeakWindow = 0.03;
} else {
fD0Window = 0.026;
fPeakWindow = 0.006;
}
}
nSelectedProd++;
nSelectedAna++;
// check that we are close to signal in the DeltaM - here to save time for PbPb
Double_t mPDGD0 = TDatabasePDG::Instance()->GetParticle(421)->Mass();
Double_t mPDGDstar = TDatabasePDG::Instance()->GetParticle(413)->Mass();
Double_t invmassDelta = dstarD0pi->DeltaInvMass();
if (TMath::Abs(invmassDelta - (mPDGDstar - mPDGD0)) > fPeakWindow) continue;
Int_t isSelected = fCuts->IsSelected(dstarD0pi, AliRDHFCuts::kCandidate, aodEvent); //selected
if (isSelected > 0) fCEvents->Fill(11);
// after cuts
if (fDoImpParDstar && isSelected) {
fHistMassPtImpParTCDs[0]->Fill(arrayForSparse);
if (isPrimary) fHistMassPtImpParTCDs[1]->Fill(arrayForSparse);
else {
fHistMassPtImpParTCDs[2]->Fill(arrayForSparse);
fHistMassPtImpParTCDs[3]->Fill(arrayForSparseTrue);
}
}
if (fDoDStarVsY && isSelected) {
((TH3F*) (fOutputPID->FindObject("deltamassVsyVsPt")))->Fill(dstarD0pi->DeltaInvMass(), dstarD0pi->YDstar(), dstarD0pi->Pt() );
}
// check after cuts
if (fUseMCInfo) {
Int_t mcLabel = dstarD0pi->MatchToMC(413, 421, pdgDgDStartoD0pi, pdgDgD0toKpi, mcTrackArray);
if (mcLabel >= 0) {
AliAODMCParticle *mcTrackParticle = dynamic_cast< AliAODMCParticle*>(mcTrackArray->At(mcLabel));
if (!mcTrackParticle) {std::cout << "no particle" << std::endl; continue;}
Int_t pdgCodeMC = TMath::Abs(mcTrackParticle->GetPdgCode());
if (pdgCodeMC == 413)
{ //if the track is a DStar we check if it comes from charm
Double_t ptMC = mcTrackParticle->Pt();
Bool_t fromCharm = kFALSE;
Int_t mother = mcTrackParticle->GetMother();
Int_t istep = 0;
while (mother >= 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(mcTrackArray->At(mother));
if (mcGranma) {
Int_t abspdgGranma = TMath::Abs(mcGranma->GetPdgCode());
if ((abspdgGranma == 4) || (abspdgGranma > 400 && abspdgGranma < 500) || (abspdgGranma > 4000 && abspdgGranma < 5000)) fromCharm = kTRUE;
mother = mcGranma->GetMother();
} else {
printf("AliVertexingHFUtils::IsTrackFromCharm: Failed casting the mother particle!");
break;
}
}
if (fromCharm)
{
Bool_t mcPionDStarPresent = kFALSE;
Bool_t mcPionD0Present = kFALSE;
Bool_t mcKaonPresent = kFALSE;
Int_t nDaughterDStar = mcTrackParticle->GetNDaughters();
if (nDaughterDStar == 2) {
for (Int_t iDaughterDStar = 0; iDaughterDStar < 2; iDaughterDStar++) {
AliAODMCParticle* daughterDStar = (AliAODMCParticle*)mcTrackArray->At(mcTrackParticle->GetDaughterLabel(iDaughterDStar));
if (!daughterDStar) break;
Int_t pdgCodeDaughterDStar = TMath::Abs(daughterDStar->GetPdgCode());
if (pdgCodeDaughterDStar == 211) { //if the track is a pion we save its monte carlo label
mcPionDStarPresent = kTRUE;
} else if (pdgCodeDaughterDStar == 421) { //if the track is a D0 we look at its daughters
Int_t mcLabelD0 = mcTrackParticle->GetDaughterLabel(iDaughterDStar);
Int_t nDaughterD0 = daughterDStar->GetNDaughters();
if (nDaughterD0 == 2) {
for (Int_t iDaughterD0 = 0; iDaughterD0 < 2; iDaughterD0++) {
AliAODMCParticle* daughterD0 = (AliAODMCParticle*)mcTrackArray->At(daughterDStar->GetDaughterLabel(iDaughterD0));
if (!daughterD0) break;
Int_t pdgCodeDaughterD0 = TMath::Abs(daughterD0->GetPdgCode());
if (pdgCodeDaughterD0 == 211) {
mcPionD0Present = kTRUE;
} else if (pdgCodeDaughterD0 == 321) {
mcKaonPresent = kTRUE;
} else break;
}
}
} else break;
}
}
if (mcPionDStarPresent && mcPionD0Present && mcKaonPresent)
{
TString fillthis = "";
fillthis = "DStarPtTruePostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStarPtTruePostCutsWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
// fillthis = "PtHardPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard);
// fillthis = "PtHardWeightedPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptHard, crossSection);
// fillthis = "WeightsPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(crossSection);
// fillthis = "TrialsPostCuts";
// ((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->AddBinContent(1,nTrials);
fillthis = "DStarPtPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt);
fillthis = "DStarPtPostCutsWeighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt, crossSection);
fillthis = "DStar_per_bin_true_PostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC);
fillthis = "DStar_per_bin_true_PostCuts_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(ptMC, crossSection);
fillthis = "DStar_per_bin_PostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt);
fillthis = "DStar_per_bin_PostCuts_weighted";
((TH1F*)(fOutputProductionCheck->FindObject(fillthis)))->Fill(Dstarpt, crossSection);
}
}
}
}
}
fillthishist = "";
fillthishist = "PtHardPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard);
fillthishist = "PtHardWeightedPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(ptHard, crossSection);
fillthishist = "WeightsPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->Fill(crossSection);
fillthishist = "TrialsPostCuts";
((TH1F*)(fOutputProductionCheck->FindObject(fillthishist)))->AddBinContent(1,nTrials);
// fill PID
FillSpectrum(dstarD0pi, isDStar, fCuts, isSelected, fOutputPID, fPIDhist);
SideBandBackground(dstarD0pi, fCuts, isSelected, fOutputPID, fPIDhist);
//WrongSignForDStar(dstarD0pi,fCuts,fOutputPID);
//swich off the PID selection
fCuts->SetUsePID(kFALSE);
Int_t isSelectedNoPID = fCuts->IsSelected(dstarD0pi, AliRDHFCuts::kCandidate, aodEvent); //selected
fCuts->SetUsePID(kTRUE);
FillSpectrum(dstarD0pi, isDStar, fCuts, isSelectedNoPID, fOutputAll, fAllhist);
// SideBandBackground(dstarD0pi,fCuts,isSelectedNoPID, fOutputAll);
// rare D search ------
if (fDoSearch) {
TLorentzVector lorentzTrack1(0, 0, 0, 0); // lorentz 4 vector
TLorentzVector lorentzTrack2(0, 0, 0, 0); // lorentz 4 vector
for (Int_t i = 0; i < aodEvent->GetNumberOfTracks(); i++) {
AliAODTrack* aodTrack = dynamic_cast<AliAODTrack*>(aodEvent->GetTrack(i));
if (!aodTrack) AliFatal("Not a standard AOD");
if (dstarD0pi->Charge() == aodTrack->Charge()) continue;
if ((!(aodTrack->GetStatus()&AliESDtrack::kITSrefit) || (!(aodTrack->GetStatus()&AliESDtrack::kTPCrefit)))) continue;
if (TMath::Abs(invmassDelta - (mPDGDstar - mPDGD0)) > 0.02) continue;
//build the D1 mass
Double_t mass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
lorentzTrack1.SetPxPyPzE( dstarD0pi->Px(), dstarD0pi->Py(), dstarD0pi->Pz(), dstarD0pi->E(413) );
lorentzTrack2.SetPxPyPzE( aodTrack->Px(), aodTrack->Py(), aodTrack->Pz(), aodTrack->E(mass) );
//D1 mass
Double_t d1mass = ((lorentzTrack1 + lorentzTrack2).M());
//mass difference - at 0.4117 and 0.4566
fDeltaMassD1->Fill(d1mass - dstarD0pi->InvMassDstarKpipi());
}
}
if (isDStar == 1) {
fTrueDiff2->Fill(dstarD0pi->Pt(), dstarD0pi->DeltaInvMass());
}
}
fCounter->StoreCandidates(aodEvent, nSelectedProd, kTRUE);
fCounter->StoreCandidates(aodEvent, nSelectedAna, kFALSE);
delete vHF;
AliDebug(2, Form("Found %i Reco particles that are D*!!", icountReco));
PostData(1, fOutput);
PostData(2, fOutputAll);
PostData(3, fOutputPID);
PostData(5, fCounter);
PostData(6, fOutputProductionCheck);
}
//________________________________________ terminate ___________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::Terminate(Option_t*)
{
/// The Terminate() function is the last function to be called during
/// a query. It always runs on the client, it can be used to present
/// the results graphically or save the results to file.
//Info("Terminate","");
AliAnalysisTaskSE::Terminate();
fOutput = dynamic_cast<TList*> (GetOutputData(1));
if (!fOutput) {
printf("ERROR: fOutput not available\n");
return;
}
fCEvents = dynamic_cast<TH1F*>(fOutput->FindObject("fCEvents"));
fDeltaMassD1 = dynamic_cast<TH1F*>(fOutput->FindObject("fDeltaMassD1"));
fTrueDiff2 = dynamic_cast<TH2F*>(fOutput->FindObject("fTrueDiff2"));
fOutputAll = dynamic_cast<TList*> (GetOutputData(1));
if (!fOutputAll) {
printf("ERROR: fOutputAll not available\n");
return;
}
fOutputPID = dynamic_cast<TList*> (GetOutputData(2));
if (!fOutputPID) {
printf("ERROR: fOutputPID not available\n");
return;
}
fOutputProductionCheck = dynamic_cast<TList*> (GetOutputData(6));
if (!fOutputProductionCheck) {
printf("ERROR: fOutputProductionCheck not available\n");
return;
}
return;
}
//___________________________________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::UserCreateOutputObjects() {
/// output
Info("UserCreateOutputObjects", "CreateOutputObjects of task %s\n", GetName());
//slot #1
//OpenFile(1);
fOutput = new TList();
fOutput->SetOwner();
fOutput->SetName("chist0");
fOutputAll = new TList();
fOutputAll->SetOwner();
fOutputAll->SetName("listAll");
fOutputPID = new TList();
fOutputPID->SetOwner();
fOutputPID->SetName("listPID");
fOutputProductionCheck = new TList();
fOutputProductionCheck->SetOwner();
fOutputProductionCheck->SetName("listPID");
// define histograms
DefineHistograms();
//Counter for Normalization
fCounter = new AliNormalizationCounter(Form("%s", GetOutputSlot(5)->GetContainer()->GetName()));
fCounter->Init();
if (fDoImpParDstar) CreateImpactParameterHistos();
PostData(1, fOutput);
PostData(2, fOutputAll);
PostData(3, fOutputPID);
PostData(5, fCounter);
PostData(6, fOutputProductionCheck);
return;
}
//___________________________________ hiostograms _______________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::DefineHistograms() {
/// Create histograms
fCEvents = new TH1F("fCEvents", "counter", 14, 0, 14);
fCEvents->SetStats(kTRUE);
fCEvents->GetXaxis()->SetTitle("1");
fCEvents->GetYaxis()->SetTitle("counts");
fCEvents->GetXaxis()->SetBinLabel(1, "nEventsRead");
fCEvents->GetXaxis()->SetBinLabel(2, "nEvents Matched dAOD");
fCEvents->GetXaxis()->SetBinLabel(3, "good prim vtx and B field");
fCEvents->GetXaxis()->SetBinLabel(4, "no event selected");
fCEvents->GetXaxis()->SetBinLabel(5, "no vtx contributors");
fCEvents->GetXaxis()->SetBinLabel(6, "trigger for PbPb");
fCEvents->GetXaxis()->SetBinLabel(7, "no z vtx");
fCEvents->GetXaxis()->SetBinLabel(9, "nEvents Mismatched dAOD");
fCEvents->GetXaxis()->SetBinLabel(11, "no. of cascade candidates");
fCEvents->GetXaxis()->SetBinLabel(12, "no. of Dstar after selection cuts");
fCEvents->GetXaxis()->SetBinLabel(13, "no. of not on-the-fly rec Dstar");
fCEvents->GetXaxis()->SetBinLabel(14, "no. of Dstar rejected by preselect"); //toadd
fOutput->Add(fCEvents);
fTrueDiff2 = new TH2F("DiffDstar_pt", "True Reco diff vs pt", 200, 0, 15, 900, 0, 0.3);
fOutput->Add(fTrueDiff2);
fDeltaMassD1 = new TH1F("DeltaMassD1", "delta mass d1", 600, 0, 0.8);
fOutput->Add(fDeltaMassD1);
//temp a
fAllhist = new TH1F*[(fNPtBins + 2) * 18];
fPIDhist = new TH1F*[(fNPtBins + 2) * 18];
TString nameMass = " ", nameSgn = " ", nameBkg = " ";
for (Int_t i = -2; i < fNPtBins; i++) {
nameMass = "histDeltaMass_";
nameMass += i + 1;
nameSgn = "histDeltaSgn_";
nameSgn += i + 1;
nameBkg = "histDeltaBkg_";
nameBkg += i + 1;
if (i == -2) {
nameMass = "histDeltaMass";
nameSgn = "histDeltaSgn";
nameBkg = "histDeltaBkg";
}
TH1F* spectrumMass = new TH1F(nameMass.Data(), "D^{*}-D^{0} invariant mass; #DeltaM [GeV/c^{2}]; Entries", 700, 0.13, 0.2);
TH1F* spectrumSgn = new TH1F(nameSgn.Data(), "D^{*}-D^{0} Signal invariant mass - MC; #DeltaM [GeV/c^{2}]; Entries", 700, 0.13, 0.2);
TH1F* spectrumBkg = new TH1F(nameBkg.Data(), "D^{*}-D^{0} Background invariant mass - MC; #DeltaM [GeV/c^{2}]; Entries", 700, 0.13, 0.2);
nameMass = "histD0Mass_";
nameMass += i + 1;
nameSgn = "histD0Sgn_";
nameSgn += i + 1;
nameBkg = "histD0Bkg_";
nameBkg += i + 1;
if (i == -2) {
nameMass = "histD0Mass";
nameSgn = "histD0Sgn";
nameBkg = "histD0Bkg";
}
TH1F* spectrumD0Mass = new TH1F(nameMass.Data(), "D^{0} invariant mass; M(D^{0}) [GeV/c^{2}]; Entries", 200, 1.75, 1.95);
TH1F* spectrumD0Sgn = new TH1F(nameSgn.Data(), "D^{0} Signal invariant mass - MC; M(D^{0}) [GeV/c^{2}]; Entries", 200, 1.75, 1.95);
TH1F* spectrumD0Bkg = new TH1F(nameBkg.Data(), "D^{0} Background invariant mass - MC; M(D^{0}) [GeV/c^{2}]; Entries", 200, 1.75, 1.95);
nameMass = "histDstarMass_";
nameMass += i + 1;
nameSgn = "histDstarSgn_";
nameSgn += i + 1;
nameBkg = "histDstarBkg_";
nameBkg += i + 1;
if (i == -2) {
nameMass = "histDstarMass";
nameSgn = "histDstarSgn";
nameBkg = "histDstarBkg";
}
TH1F* spectrumDstarMass = new TH1F(nameMass.Data(), "D^{*} invariant mass; M(D^{*}) [GeV/c^{2}]; Entries", 200, 1.9, 2.1);
TH1F* spectrumDstarSgn = new TH1F(nameSgn.Data(), "D^{*} Signal invariant mass - MC; M(D^{*}) [GeV/c^{2}]; Entries", 200, 1.9, 2.1);
TH1F* spectrumDstarBkg = new TH1F(nameBkg.Data(), "D^{*} Background invariant mass - MC; M(D^{*}) [GeV/c^{2}]; Entries", 200, 1.9, 2.1);
nameMass = "histSideBandMass_";
nameMass += i + 1;
if (i == -2) {
nameMass = "histSideBandMass";
}
TH1F* spectrumSideBandMass = new TH1F(nameMass.Data(), "D^{*}-D^{0} sideband mass; M(D^{*}) [GeV/c^{2}]; Entries", 200, 0.1, 0.2);
nameMass = "histWrongSignMass_";
nameMass += i + 1;
if (i == -2) {
nameMass = "histWrongSignMass";
}
TH1F* spectrumWrongSignMass = new TH1F(nameMass.Data(), "D^{*}-D^{0} wrongsign mass; M(D^{*}) [GeV/c^{2}]; Entries", 200, 0.1, 0.2);
spectrumMass->Sumw2();
spectrumSgn->Sumw2();
spectrumBkg->Sumw2();
spectrumMass->SetLineColor(6);
spectrumSgn->SetLineColor(2);
spectrumBkg->SetLineColor(4);
spectrumMass->SetMarkerStyle(20);
spectrumSgn->SetMarkerStyle(20);
spectrumBkg->SetMarkerStyle(20);
spectrumMass->SetMarkerSize(0.6);
spectrumSgn->SetMarkerSize(0.6);
spectrumBkg->SetMarkerSize(0.6);
spectrumMass->SetMarkerColor(6);
spectrumSgn->SetMarkerColor(2);
spectrumBkg->SetMarkerColor(4);
spectrumD0Mass->Sumw2();
spectrumD0Sgn->Sumw2();
spectrumD0Bkg->Sumw2();
spectrumD0Mass->SetLineColor(6);
spectrumD0Sgn->SetLineColor(2);
spectrumD0Bkg->SetLineColor(4);
spectrumD0Mass->SetMarkerStyle(20);
spectrumD0Sgn->SetMarkerStyle(20);
spectrumD0Bkg->SetMarkerStyle(20);
spectrumD0Mass->SetMarkerSize(0.6);
spectrumD0Sgn->SetMarkerSize(0.6);
spectrumD0Bkg->SetMarkerSize(0.6);
spectrumD0Mass->SetMarkerColor(6);
spectrumD0Sgn->SetMarkerColor(2);
spectrumD0Bkg->SetMarkerColor(4);
spectrumDstarMass->Sumw2();
spectrumDstarSgn->Sumw2();
spectrumDstarBkg->Sumw2();
spectrumDstarMass->SetLineColor(6);
spectrumDstarSgn->SetLineColor(2);
spectrumDstarBkg->SetLineColor(4);
spectrumDstarMass->SetMarkerStyle(20);
spectrumDstarSgn->SetMarkerStyle(20);
spectrumDstarBkg->SetMarkerStyle(20);
spectrumDstarMass->SetMarkerSize(0.6);
spectrumDstarSgn->SetMarkerSize(0.6);
spectrumDstarBkg->SetMarkerSize(0.6);
spectrumDstarMass->SetMarkerColor(6);
spectrumDstarSgn->SetMarkerColor(2);
spectrumDstarBkg->SetMarkerColor(4);
spectrumSideBandMass->Sumw2();
spectrumSideBandMass->SetLineColor(4);
spectrumSideBandMass->SetMarkerStyle(20);
spectrumSideBandMass->SetMarkerSize(0.6);
spectrumSideBandMass->SetMarkerColor(4);
spectrumWrongSignMass->Sumw2();
spectrumWrongSignMass->SetLineColor(4);
spectrumWrongSignMass->SetMarkerStyle(20);
spectrumWrongSignMass->SetMarkerSize(0.6);
spectrumWrongSignMass->SetMarkerColor(4);
TH1F* allMass = (TH1F*)spectrumMass->Clone();
TH1F* allSgn = (TH1F*)spectrumSgn->Clone();
TH1F* allBkg = (TH1F*)spectrumBkg->Clone();
TH1F* pidMass = (TH1F*)spectrumMass->Clone();
TH1F* pidSgn = (TH1F*)spectrumSgn->Clone();
TH1F* pidBkg = (TH1F*)spectrumBkg->Clone();
fOutputAll->Add(allMass);
fOutputAll->Add(allSgn);
fOutputAll->Add(allBkg);
fAllhist[i + 2 + ((fNPtBins + 2)*kDeltaMass)] = allMass;
fAllhist[i + 2 + ((fNPtBins + 2)*kDeltaSgn)] = allSgn;
fAllhist[i + 2 + ((fNPtBins + 2)*kDeltaBkg)] = allBkg;
fOutputPID->Add(pidMass);
fOutputPID->Add(pidSgn);
fOutputPID->Add(pidBkg);
fPIDhist[i + 2 + ((fNPtBins + 2)*kDeltaMass)] = pidMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDeltaSgn)] = pidSgn;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDeltaBkg)] = pidBkg;
TH1F* allD0Mass = (TH1F*)spectrumD0Mass->Clone();
TH1F* allD0Sgn = (TH1F*)spectrumD0Sgn->Clone();
TH1F* allD0Bkg = (TH1F*)spectrumD0Bkg->Clone();
TH1F* pidD0Mass = (TH1F*)spectrumD0Mass->Clone();
TH1F* pidD0Sgn = (TH1F*)spectrumD0Sgn->Clone();
TH1F* pidD0Bkg = (TH1F*)spectrumD0Bkg->Clone();
fOutputAll->Add(allD0Mass);
fOutputAll->Add(allD0Sgn);
fOutputAll->Add(allD0Bkg);
fAllhist[i + 2 + ((fNPtBins + 2)*kDzMass)] = allD0Mass;
fAllhist[i + 2 + ((fNPtBins + 2)*kDzSgn)] = allD0Sgn;
fAllhist[i + 2 + ((fNPtBins + 2)*kDzBkg)] = allD0Bkg;
fOutputPID->Add(pidD0Mass);
fOutputPID->Add(pidD0Sgn);
fOutputPID->Add(pidD0Bkg);
fPIDhist[i + 2 + ((fNPtBins + 2)*kDzMass)] = pidD0Mass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDzSgn)] = pidD0Sgn;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDzBkg)] = pidD0Bkg;
TH1F* allDstarMass = (TH1F*)spectrumDstarMass->Clone();
TH1F* allDstarSgn = (TH1F*)spectrumDstarSgn->Clone();
TH1F* allDstarBkg = (TH1F*)spectrumDstarBkg->Clone();
TH1F* pidDstarMass = (TH1F*)spectrumDstarMass->Clone();
TH1F* pidDstarSgn = (TH1F*)spectrumDstarSgn->Clone();
TH1F* pidDstarBkg = (TH1F*)spectrumDstarBkg->Clone();
fOutputAll->Add(allDstarMass);
fOutputAll->Add(allDstarSgn);
fOutputAll->Add(allDstarBkg);
fAllhist[i + 2 + ((fNPtBins + 2)*kDstarMass)] = allDstarMass;
fAllhist[i + 2 + ((fNPtBins + 2)*kDstarSgn)] = allDstarSgn;
fAllhist[i + 2 + ((fNPtBins + 2)*kDstarBkg)] = allDstarBkg;
fOutputPID->Add(pidDstarMass);
fOutputPID->Add(pidDstarSgn);
fOutputPID->Add(pidDstarBkg);
fPIDhist[i + 2 + ((fNPtBins + 2)*kDstarMass)] = pidDstarMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDstarSgn)] = pidDstarSgn;
fPIDhist[i + 2 + ((fNPtBins + 2)*kDstarBkg)] = pidDstarBkg;
TH1F* allSideBandMass = (TH1F*)spectrumSideBandMass->Clone();
TH1F* pidSideBandMass = (TH1F*)spectrumSideBandMass->Clone();
fOutputAll->Add(allSideBandMass);
fOutputPID->Add(pidSideBandMass);
fAllhist[i + 2 + ((fNPtBins + 2)*kSideBandMass)] = allSideBandMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kSideBandMass)] = pidSideBandMass;
TH1F* allWrongSignMass = (TH1F*)spectrumWrongSignMass->Clone();
TH1F* pidWrongSignMass = (TH1F*)spectrumWrongSignMass->Clone();
fOutputAll->Add(allWrongSignMass);
fOutputPID->Add(pidWrongSignMass);
fAllhist[i + 2 + ((fNPtBins + 2)*kWrongSignMass)] = allWrongSignMass;
fPIDhist[i + 2 + ((fNPtBins + 2)*kWrongSignMass)] = pidWrongSignMass;
}
// pt spectra
nameMass = "ptMass";
nameSgn = "ptSgn";
nameBkg = "ptBkg";
TH1F* ptspectrumMass = new TH1F(nameMass.Data(), "D^{*} p_{T}; p_{T} [GeV]; Entries", 400, 0, 50);
TH1F* ptspectrumSgn = new TH1F(nameSgn.Data(), "D^{*} Signal p_{T} - MC; p_{T} [GeV]; Entries", 400, 0, 50);
TH1F* ptspectrumBkg = new TH1F(nameBkg.Data(), "D^{*} Background p_{T} - MC; p_{T} [GeV]; Entries", 400, 0, 50);
ptspectrumMass->Sumw2();
ptspectrumSgn->Sumw2();
ptspectrumBkg->Sumw2();
ptspectrumMass->SetLineColor(6);
ptspectrumSgn->SetLineColor(2);
ptspectrumBkg->SetLineColor(4);
ptspectrumMass->SetMarkerStyle(20);
ptspectrumSgn->SetMarkerStyle(20);
ptspectrumBkg->SetMarkerStyle(20);
ptspectrumMass->SetMarkerSize(0.6);
ptspectrumSgn->SetMarkerSize(0.6);
ptspectrumBkg->SetMarkerSize(0.6);
ptspectrumMass->SetMarkerColor(6);
ptspectrumSgn->SetMarkerColor(2);
ptspectrumBkg->SetMarkerColor(4);
TH1F* ptallMass = (TH1F*)ptspectrumMass->Clone();
TH1F* ptallSgn = (TH1F*)ptspectrumSgn->Clone();
TH1F* ptallBkg = (TH1F*)ptspectrumBkg->Clone();
TH1F* ptpidMass = (TH1F*)ptspectrumMass->Clone();
TH1F* ptpidSgn = (TH1F*)ptspectrumSgn->Clone();
TH1F* ptpidBkg = (TH1F*)ptspectrumBkg->Clone();
fOutputAll->Add(ptallMass);
fOutputAll->Add(ptallSgn);
fOutputAll->Add(ptallBkg);
fAllhist[((fNPtBins + 2)*kptMass)] = ptallMass;
fAllhist[((fNPtBins + 2)*kptSgn)] = ptallSgn;
fAllhist[((fNPtBins + 2)*kptBkg)] = ptallBkg;
fOutputPID->Add(ptpidMass);
fOutputPID->Add(ptpidSgn);
fOutputPID->Add(ptpidBkg);
fPIDhist[(fNPtBins + 2)*kptMass] = ptpidMass;
fPIDhist[(fNPtBins + 2)*kptSgn] = ptpidSgn;
fPIDhist[(fNPtBins + 2)*kptBkg] = ptpidBkg;
// eta spectra
nameMass = "etaMass";
nameSgn = "etaSgn";
nameBkg = "etaBkg";
TH1F* etaspectrumMass = new TH1F(nameMass.Data(), "D^{*} #eta; #eta; Entries", 200, -1, 1);
TH1F* etaspectrumSgn = new TH1F(nameSgn.Data(), "D^{*} Signal #eta - MC; #eta; Entries", 200, -1, 1);
TH1F* etaspectrumBkg = new TH1F(nameBkg.Data(), "D^{*} Background #eta - MC; #eta; Entries", 200, -1, 1);
etaspectrumMass->Sumw2();
etaspectrumSgn->Sumw2();
etaspectrumBkg->Sumw2();
etaspectrumMass->SetLineColor(6);
etaspectrumSgn->SetLineColor(2);
etaspectrumBkg->SetLineColor(4);
etaspectrumMass->SetMarkerStyle(20);
etaspectrumSgn->SetMarkerStyle(20);
etaspectrumBkg->SetMarkerStyle(20);
etaspectrumMass->SetMarkerSize(0.6);
etaspectrumSgn->SetMarkerSize(0.6);
etaspectrumBkg->SetMarkerSize(0.6);
etaspectrumMass->SetMarkerColor(6);
etaspectrumSgn->SetMarkerColor(2);
etaspectrumBkg->SetMarkerColor(4);
TH1F* etaallMass = (TH1F*)etaspectrumMass->Clone();
TH1F* etaallSgn = (TH1F*)etaspectrumSgn->Clone();
TH1F* etaallBkg = (TH1F*)etaspectrumBkg->Clone();
TH1F* etapidMass = (TH1F*)etaspectrumMass->Clone();
TH1F* etapidSgn = (TH1F*)etaspectrumSgn->Clone();
TH1F* etapidBkg = (TH1F*)etaspectrumBkg->Clone();
fOutputAll->Add(etaallMass);
fOutputAll->Add(etaallSgn);
fOutputAll->Add(etaallBkg);
fAllhist[(fNPtBins + 2)*ketaMass] = etaallMass;
fAllhist[(fNPtBins + 2)*ketaSgn] = etaallSgn;
fAllhist[(fNPtBins + 2)*ketaBkg] = etaallBkg;
fOutputPID->Add(etapidMass);
fOutputPID->Add(etapidSgn);
fOutputPID->Add(etapidBkg);
fPIDhist[(fNPtBins + 2)*ketaMass] = etapidMass;
fPIDhist[(fNPtBins + 2)*ketaSgn] = etapidSgn;
fPIDhist[(fNPtBins + 2)*ketaBkg] = etapidBkg;
if (fDoDStarVsY) {
TH3F* deltamassVsyVsPtPID = new TH3F("deltamassVsyVsPt", "delta mass Vs y Vs pT; #DeltaM [GeV/c^{2}]; y; p_{T} [GeV/c]", 700, 0.13, 0.2, 40, -1, 1, 36, 0., 36.);
fOutputPID->Add(deltamassVsyVsPtPID);
}
TString name_DStarPtTruePreEventSelection = "DStarPtTruePreEventSelection";
TH1F* hist_DStarPtTruePreEventSelection = new TH1F(name_DStarPtTruePreEventSelection.Data(), "DStarPtTruePreEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePreEventSelection->Sumw2();
hist_DStarPtTruePreEventSelection->SetLineColor(6);
hist_DStarPtTruePreEventSelection->SetMarkerStyle(20);
hist_DStarPtTruePreEventSelection->SetMarkerSize(0.6);
hist_DStarPtTruePreEventSelection->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePreEventSelection = (TH1F*)hist_DStarPtTruePreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePreEventSelection);
TString name_DStarPtTruePreEventSelectionWeighted = "DStarPtTruePreEventSelectionWeighted";
TH1F* hist_DStarPtTruePreEventSelectionWeighted = new TH1F(name_DStarPtTruePreEventSelectionWeighted.Data(), "DStarPtTruePreEventSelectionWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePreEventSelectionWeighted->Sumw2();
hist_DStarPtTruePreEventSelectionWeighted->SetLineColor(6);
hist_DStarPtTruePreEventSelectionWeighted->SetMarkerStyle(20);
hist_DStarPtTruePreEventSelectionWeighted->SetMarkerSize(0.6);
hist_DStarPtTruePreEventSelectionWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePreEventSelectionWeighted = (TH1F*)hist_DStarPtTruePreEventSelectionWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePreEventSelectionWeighted);
TString name_DStarPtTruePostEventSelection = "DStarPtTruePostEventSelection";
TH1F* hist_DStarPtTruePostEventSelection = new TH1F(name_DStarPtTruePostEventSelection.Data(), "DStarPtTruePostEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostEventSelection->Sumw2();
hist_DStarPtTruePostEventSelection->SetLineColor(6);
hist_DStarPtTruePostEventSelection->SetMarkerStyle(20);
hist_DStarPtTruePostEventSelection->SetMarkerSize(0.6);
hist_DStarPtTruePostEventSelection->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostEventSelection = (TH1F*)hist_DStarPtTruePostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostEventSelection);
TString name_DStarPtTruePostEventSelectionWeighted = "DStarPtTruePostEventSelectionWeighted";
TH1F* hist_DStarPtTruePostEventSelectionWeighted = new TH1F(name_DStarPtTruePostEventSelectionWeighted.Data(), "DStarPtTruePostEventSelectionWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostEventSelectionWeighted->Sumw2();
hist_DStarPtTruePostEventSelectionWeighted->SetLineColor(6);
hist_DStarPtTruePostEventSelectionWeighted->SetMarkerStyle(20);
hist_DStarPtTruePostEventSelectionWeighted->SetMarkerSize(0.6);
hist_DStarPtTruePostEventSelectionWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostEventSelectionWeighted = (TH1F*)hist_DStarPtTruePostEventSelectionWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostEventSelectionWeighted);
TString name_DStarPtTruePostCuts = "DStarPtTruePostCuts";
TH1F* hist_DStarPtTruePostCuts = new TH1F(name_DStarPtTruePostCuts.Data(), "DStarPtTruePostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostCuts->Sumw2();
hist_DStarPtTruePostCuts->SetLineColor(6);
hist_DStarPtTruePostCuts->SetMarkerStyle(20);
hist_DStarPtTruePostCuts->SetMarkerSize(0.6);
hist_DStarPtTruePostCuts->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostCuts = (TH1F*)hist_DStarPtTruePostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostCuts);
TString name_DStarPtTruePostCutsWeighted = "DStarPtTruePostCutsWeighted";
TH1F* hist_DStarPtTruePostCutsWeighted = new TH1F(name_DStarPtTruePostCutsWeighted.Data(), "DStarPtTruePostCutsWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtTruePostCutsWeighted->Sumw2();
hist_DStarPtTruePostCutsWeighted->SetLineColor(6);
hist_DStarPtTruePostCutsWeighted->SetMarkerStyle(20);
hist_DStarPtTruePostCutsWeighted->SetMarkerSize(0.6);
hist_DStarPtTruePostCutsWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtTruePostCutsWeighted = (TH1F*)hist_DStarPtTruePostCutsWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtTruePostCutsWeighted);
TString name_DStarPtPostCuts = "DStarPtPostCuts";
TH1F* hist_DStarPtPostCuts = new TH1F(name_DStarPtPostCuts.Data(), "DStarPtPostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtPostCuts->Sumw2();
hist_DStarPtPostCuts->SetLineColor(6);
hist_DStarPtPostCuts->SetMarkerStyle(20);
hist_DStarPtPostCuts->SetMarkerSize(0.6);
hist_DStarPtPostCuts->SetMarkerColor(6);
TH1F* histogram_DStarPtPostCuts = (TH1F*)hist_DStarPtPostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStarPtPostCuts);
TString name_DStarPtPostCutsWeighted = "DStarPtPostCutsWeighted";
TH1F* hist_DStarPtPostCutsWeighted = new TH1F(name_DStarPtPostCutsWeighted.Data(), "DStarPtPostCutsWeighted; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_DStarPtPostCutsWeighted->Sumw2();
hist_DStarPtPostCutsWeighted->SetLineColor(6);
hist_DStarPtPostCutsWeighted->SetMarkerStyle(20);
hist_DStarPtPostCutsWeighted->SetMarkerSize(0.6);
hist_DStarPtPostCutsWeighted->SetMarkerColor(6);
TH1F* histogram_DStarPtPostCutsWeighted = (TH1F*)hist_DStarPtPostCutsWeighted->Clone();
fOutputProductionCheck->Add(histogram_DStarPtPostCutsWeighted);
TString name_PtHardPreEventSelection = "PtHardPreEventSelection";
TH1F* hist_PtHardPreEventSelection = new TH1F(name_PtHardPreEventSelection.Data(), "PtHardPreEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardPreEventSelection->Sumw2();
hist_PtHardPreEventSelection->SetLineColor(6);
hist_PtHardPreEventSelection->SetMarkerStyle(20);
hist_PtHardPreEventSelection->SetMarkerSize(0.6);
hist_PtHardPreEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardPreEventSelection = (TH1F*)hist_PtHardPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardPreEventSelection);
TString name_PtHardPostEventSelection = "PtHardPostEventSelection";
TH1F* hist_PtHardPostEventSelection = new TH1F(name_PtHardPostEventSelection.Data(), "PtHardPostEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardPostEventSelection->Sumw2();
hist_PtHardPostEventSelection->SetLineColor(6);
hist_PtHardPostEventSelection->SetMarkerStyle(20);
hist_PtHardPostEventSelection->SetMarkerSize(0.6);
hist_PtHardPostEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardPostEventSelection = (TH1F*)hist_PtHardPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardPostEventSelection);
TString name_PtHardPostCuts = "PtHardPostCuts";
TH1F* hist_PtHardPostCuts = new TH1F(name_PtHardPostCuts.Data(), "PtHardPostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardPostCuts->Sumw2();
hist_PtHardPostCuts->SetLineColor(6);
hist_PtHardPostCuts->SetMarkerStyle(20);
hist_PtHardPostCuts->SetMarkerSize(0.6);
hist_PtHardPostCuts->SetMarkerColor(6);
TH1F* histogram_PtHardPostCuts = (TH1F*)hist_PtHardPostCuts->Clone();
fOutputProductionCheck->Add(histogram_PtHardPostCuts);
TString name_PtHardWeightedPreEventSelection = "PtHardWeightedPreEventSelection";
TH1F* hist_PtHardWeightedPreEventSelection = new TH1F(name_PtHardWeightedPreEventSelection.Data(), "PtHardWeightedPreEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardWeightedPreEventSelection->Sumw2();
hist_PtHardWeightedPreEventSelection->SetLineColor(6);
hist_PtHardWeightedPreEventSelection->SetMarkerStyle(20);
hist_PtHardWeightedPreEventSelection->SetMarkerSize(0.6);
hist_PtHardWeightedPreEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardWeightedPreEventSelection = (TH1F*)hist_PtHardWeightedPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardWeightedPreEventSelection);
TString name_PtHardWeightedPostEventSelection = "PtHardWeightedPostEventSelection";
TH1F* hist_PtHardWeightedPostEventSelection = new TH1F(name_PtHardWeightedPostEventSelection.Data(), "PtHardWeightedPostEventSelection; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardWeightedPostEventSelection->Sumw2();
hist_PtHardWeightedPostEventSelection->SetLineColor(6);
hist_PtHardWeightedPostEventSelection->SetMarkerStyle(20);
hist_PtHardWeightedPostEventSelection->SetMarkerSize(0.6);
hist_PtHardWeightedPostEventSelection->SetMarkerColor(6);
TH1F* histogram_PtHardWeightedPostEventSelection = (TH1F*)hist_PtHardWeightedPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_PtHardWeightedPostEventSelection);
TString name_PtHardWeightedPostCuts = "PtHardWeightedPostCuts";
TH1F* hist_PtHardWeightedPostCuts = new TH1F(name_PtHardWeightedPostCuts.Data(), "PtHardWeightedPostCuts; p_{T} [GeV/c]; Entries", 5000, 0, 1000);
hist_PtHardWeightedPostCuts->Sumw2();
hist_PtHardWeightedPostCuts->SetLineColor(6);
hist_PtHardWeightedPostCuts->SetMarkerStyle(20);
hist_PtHardWeightedPostCuts->SetMarkerSize(0.6);
hist_PtHardWeightedPostCuts->SetMarkerColor(6);
TH1F* histogram_PtHardWeightedPostCuts = (TH1F*)hist_PtHardWeightedPostCuts->Clone();
fOutputProductionCheck->Add(histogram_PtHardWeightedPostCuts);
TString name_WeightsPreEventSelection = "WeightsPreEventSelection";
TH1F* hist_WeightsPreEventSelection = new TH1F(name_WeightsPreEventSelection.Data(), "WeightsPreEventSelection; p_{T} [GeV/c]; Entries", 50000, 0, 1000);
hist_WeightsPreEventSelection->Sumw2();
hist_WeightsPreEventSelection->SetLineColor(6);
hist_WeightsPreEventSelection->SetMarkerStyle(20);
hist_WeightsPreEventSelection->SetMarkerSize(0.6);
hist_WeightsPreEventSelection->SetMarkerColor(6);
TH1F* histogram_WeightsPreEventSelection = (TH1F*)hist_WeightsPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_WeightsPreEventSelection);
TString name_WeightsPostEventSelection = "WeightsPostEventSelection";
TH1F* hist_WeightsPostEventSelection = new TH1F(name_WeightsPostEventSelection.Data(), "WeightsPostEventSelection; p_{T} [GeV/c]; Entries", 50000, 0, 1000);
hist_WeightsPostEventSelection->Sumw2();
hist_WeightsPostEventSelection->SetLineColor(6);
hist_WeightsPostEventSelection->SetMarkerStyle(20);
hist_WeightsPostEventSelection->SetMarkerSize(0.6);
hist_WeightsPostEventSelection->SetMarkerColor(6);
TH1F* histogram_WeightsPostEventSelection = (TH1F*)hist_WeightsPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_WeightsPostEventSelection);
TString name_WeightsPostCuts = "WeightsPostCuts";
TH1F* hist_WeightsPostCuts = new TH1F(name_WeightsPostCuts.Data(), "WeightsPostCuts; p_{T} [GeV/c]; Entries", 50000, 0, 1000);
hist_WeightsPostCuts->Sumw2();
hist_WeightsPostCuts->SetLineColor(6);
hist_WeightsPostCuts->SetMarkerStyle(20);
hist_WeightsPostCuts->SetMarkerSize(0.6);
hist_WeightsPostCuts->SetMarkerColor(6);
TH1F* histogram_WeightsPostCuts = (TH1F*)hist_WeightsPostCuts->Clone();
fOutputProductionCheck->Add(histogram_WeightsPostCuts);
TString name_TrialsPreEventSelection = "TrialsPreEventSelection";
TH1F* hist_TrialsPreEventSelection = new TH1F(name_TrialsPreEventSelection.Data(), "TrialsPreEventSelection; p_{T} [GeV/c]; Entries", 1, 0, 1);
hist_TrialsPreEventSelection->Sumw2();
hist_TrialsPreEventSelection->SetLineColor(6);
hist_TrialsPreEventSelection->SetMarkerStyle(20);
hist_TrialsPreEventSelection->SetMarkerSize(0.6);
hist_TrialsPreEventSelection->SetMarkerColor(6);
TH1F* histogram_TrialsPreEventSelection = (TH1F*)hist_TrialsPreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_TrialsPreEventSelection);
TString name_TrialsPostEventSelection = "TrialsPostEventSelection";
TH1F* hist_TrialsPostEventSelection = new TH1F(name_TrialsPostEventSelection.Data(), "TrialsPostEventSelection; p_{T} [GeV/c]; Entries", 1, 0, 1);
hist_TrialsPostEventSelection->Sumw2();
hist_TrialsPostEventSelection->SetLineColor(6);
hist_TrialsPostEventSelection->SetMarkerStyle(20);
hist_TrialsPostEventSelection->SetMarkerSize(0.6);
hist_TrialsPostEventSelection->SetMarkerColor(6);
TH1F* histogram_TrialsPostEventSelection = (TH1F*)hist_TrialsPostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_TrialsPostEventSelection);
TString name_TrialsPostCuts = "TrialsPostCuts";
TH1F* hist_TrialsPostCuts = new TH1F(name_TrialsPostCuts.Data(), "TrialsPostCuts; p_{T} [GeV/c]; Entries", 1, 0, 1);
hist_TrialsPostCuts->Sumw2();
hist_TrialsPostCuts->SetLineColor(6);
hist_TrialsPostCuts->SetMarkerStyle(20);
hist_TrialsPostCuts->SetMarkerSize(0.6);
hist_TrialsPostCuts->SetMarkerColor(6);
TH1F* histogram_TrialsPostCuts = (TH1F*)hist_TrialsPostCuts->Clone();
fOutputProductionCheck->Add(histogram_TrialsPostCuts);
Int_t nPtBins = fCuts->GetNPtBins();
// const Int_t nPtBinLimits = nPtBins + 1;
Float_t * PtBinLimits = fCuts->GetPtBinLimits();
TString name_DStar_per_bin_true_PreEventSelection ="DStar_per_bin_true_PreEventSelection";
TH1F* hist_DStar_per_bin_true_PreEventSelection = new TH1F(name_DStar_per_bin_true_PreEventSelection.Data(),"DStar_per_bin_true_PreEventSelection; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PreEventSelection = (TH1F*)hist_DStar_per_bin_true_PreEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PreEventSelection);
TString name_DStar_per_bin_true_PreEventSelection_weighted ="DStar_per_bin_true_PreEventSelection_weighted";
TH1F* hist_DStar_per_bin_true_PreEventSelection_weighted = new TH1F(name_DStar_per_bin_true_PreEventSelection_weighted.Data(),"DStar_per_bin_true_PreEventSelection_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PreEventSelection_weighted = (TH1F*)hist_DStar_per_bin_true_PreEventSelection_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PreEventSelection_weighted);
TString name_DStar_per_bin_true_PostEventSelection ="DStar_per_bin_true_PostEventSelection";
TH1F* hist_DStar_per_bin_true_PostEventSelection = new TH1F(name_DStar_per_bin_true_PostEventSelection.Data(),"DStar_per_bin_true_PostEventSelection; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostEventSelection = (TH1F*)hist_DStar_per_bin_true_PostEventSelection->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostEventSelection);
TString name_DStar_per_bin_true_PostEventSelection_weighted ="DStar_per_bin_true_PostEventSelection_weighted";
TH1F* hist_DStar_per_bin_true_PostEventSelection_weighted = new TH1F(name_DStar_per_bin_true_PostEventSelection_weighted.Data(),"DStar_per_bin_true_PostEventSelection_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostEventSelection_weighted = (TH1F*)hist_DStar_per_bin_true_PostEventSelection_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostEventSelection_weighted);
TString name_DStar_per_bin_true_PostCuts ="DStar_per_bin_true_PostCuts";
TH1F* hist_DStar_per_bin_true_PostCuts = new TH1F(name_DStar_per_bin_true_PostCuts.Data(),"DStar_per_bin_true_PostCuts; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostCuts = (TH1F*)hist_DStar_per_bin_true_PostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostCuts);
TString name_DStar_per_bin_true_PostCuts_weighted ="DStar_per_bin_true_PostCuts_weighted";
TH1F* hist_DStar_per_bin_true_PostCuts_weighted = new TH1F(name_DStar_per_bin_true_PostCuts_weighted.Data(),"DStar_per_bin_true_PostCuts_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_true_PostCuts_weighted = (TH1F*)hist_DStar_per_bin_true_PostCuts_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_true_PostCuts_weighted);
TString name_DStar_per_bin_PostCuts ="DStar_per_bin_PostCuts";
TH1F* hist_DStar_per_bin_PostCuts = new TH1F(name_DStar_per_bin_PostCuts.Data(),"DStar_per_bin_PostCuts; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_PostCuts = (TH1F*)hist_DStar_per_bin_PostCuts->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_PostCuts);
TString name_DStar_per_bin_PostCuts_weighted ="DStar_per_bin_PostCuts_weighted";
TH1F* hist_DStar_per_bin_PostCuts_weighted = new TH1F(name_DStar_per_bin_PostCuts_weighted.Data(),"DStar_per_bin_PostCuts_weighted; Entries",nPtBins,PtBinLimits);
TH1F* histogram_DStar_per_bin_PostCuts_weighted = (TH1F*)hist_DStar_per_bin_PostCuts_weighted->Clone();
fOutputProductionCheck->Add(histogram_DStar_per_bin_PostCuts_weighted);
TString name_fHistClusPosition ="fHistClusPosition";
TH3F* hist_fHistClusPosition = new TH3F(name_fHistClusPosition.Data(),";#it{x} (cm);#it{y} (cm);#it{z} (cm)", 50, -500, 500, 50, -500, 500, 50, -500, 500);
TH3F* histogram_fHistClusPosition = (TH3F*)hist_fHistClusPosition->Clone();
fOutputProductionCheck->Add(histogram_fHistClusPosition);
return;
}
//________________________________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::FillSpectrum(AliAODRecoCascadeHF *part, Int_t isDStar, AliRDHFCutsDStartoKpipi *cuts, Int_t isSel, TList *listout, TH1F** histlist) {
//
/// Fill histos for D* spectrum
//
if (!isSel) return;
// D0 window
Double_t mPDGD0 = TDatabasePDG::Instance()->GetParticle(421)->Mass();
Double_t invmassD0 = part->InvMassD0();
Int_t ptbin = cuts->PtBin(part->Pt());
Double_t pt = part->Pt();
Double_t eta = part->Eta();
Double_t invmassDelta = part->DeltaInvMass();
Double_t invmassDstar = part->InvMassDstarKpipi();
TString fillthis = "";
Bool_t massInRange = kFALSE;
Double_t mPDGDstar = TDatabasePDG::Instance()->GetParticle(413)->Mass();
// delta M(Kpipi)-M(Kpi)
if (TMath::Abs(invmassDelta - (mPDGDstar - mPDGD0)) < fPeakWindow) massInRange = kTRUE;
if (fUseMCInfo) {
if (isDStar == 1) {
histlist[ptbin + 1 + ((fNPtBins + 2)*kDzSgn)]->Fill(invmassD0);
histlist[(fNPtBins + 2)*kDzSgn]->Fill(invmassD0);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDstarSgn)]->Fill(invmassDstar);
histlist[(fNPtBins + 2)*kDstarSgn]->Fill(invmassDstar);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDeltaSgn)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kDeltaSgn]->Fill(invmassDelta);
if (massInRange) {
histlist[(fNPtBins + 2)*kptSgn]->Fill(pt);
histlist[(fNPtBins + 2)*ketaSgn]->Fill(eta);
}
}
else {//background
histlist[ptbin + 1 + ((fNPtBins + 2)*kDzBkg)]->Fill(invmassD0);
histlist[(fNPtBins + 2)*kDzBkg]->Fill(invmassD0);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDstarBkg)]->Fill(invmassDstar);
histlist[(fNPtBins + 2)*kDstarBkg]->Fill(invmassDstar);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDeltaBkg)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kDeltaBkg]->Fill(invmassDelta);
if (massInRange) {
histlist[(fNPtBins + 2)*kptBkg]->Fill(pt);
histlist[(fNPtBins + 2)*ketaBkg]->Fill(eta);
}
}
}
//no MC info, just cut selection
histlist[ptbin + 1 + ((fNPtBins + 2)*kDzMass)]->Fill(invmassD0);
histlist[(fNPtBins + 2)*kDzMass]->Fill(invmassD0);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDstarMass)]->Fill(invmassDstar);
histlist[(fNPtBins + 2)*kDstarMass]->Fill(invmassDstar);
histlist[ptbin + 1 + ((fNPtBins + 2)*kDeltaMass)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kDeltaMass]->Fill(invmassDelta);
if (massInRange) {
histlist[(fNPtBins + 2)*kptMass]->Fill(pt);
histlist[(fNPtBins + 2)*ketaMass]->Fill(eta);
}
return;
}
//______________________________ side band background for D*___________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::SideBandBackground(AliAODRecoCascadeHF *part, AliRDHFCutsDStartoKpipi *cuts, Int_t isSel, TList *listout, TH1F** histlist) {
/// D* side band background method. Two side bands, in M(Kpi) are taken at ~6 sigmas
/// (expected detector resolution) on the left and right frm the D0 mass. Each band
/// has a width of ~5 sigmas. Two band needed for opening angle considerations
if (!isSel) return;
Int_t ptbin = cuts->PtBin(part->Pt());
// select the side bands intervall
Double_t invmassD0 = part->InvMassD0();
if (TMath::Abs(invmassD0 - 1.865) > 4 * fD0Window && TMath::Abs(invmassD0 - 1.865) < 8 * fD0Window) {
// for pt and eta
Double_t invmassDelta = part->DeltaInvMass();
histlist[ptbin + 1 + ((fNPtBins + 2)*kSideBandMass)]->Fill(invmassDelta);
histlist[(fNPtBins + 2)*kSideBandMass]->Fill(invmassDelta);
}
}
//________________________________________________________________________________________________________________
void AliAnalysisTaskSEDStarEMCALProductionCheck::WrongSignForDStar(AliAODRecoCascadeHF *part, AliRDHFCutsDStartoKpipi *cuts, TList *listout) {
//
/// assign the wrong charge to the soft pion to create background
//
Int_t ptbin = cuts->PtBin(part->Pt());
Double_t mPDGD0 = TDatabasePDG::Instance()->GetParticle(421)->Mass();
Double_t invmassD0 = part->InvMassD0();
if (TMath::Abs(invmassD0 - mPDGD0) > fD0Window) return;
AliAODRecoDecayHF2Prong* theD0particle = (AliAODRecoDecayHF2Prong*)part->Get2Prong();
Int_t okDzWrongSign;
Double_t wrongMassD0 = 0.;
Int_t isSelected = cuts->IsSelected(part, AliRDHFCuts::kCandidate); //selected
if (!isSelected) {
return;
}
okDzWrongSign = 1;
//if is D*+ than assume D0bar
if (part->Charge() > 0 && (isSelected == 1)) {
okDzWrongSign = 0;
}
// assign the wrong mass in case the cuts return both D0 and D0bar
if (part->Charge() > 0 && (isSelected == 3)) {
okDzWrongSign = 0;
}
//wrong D0 inv mass
if (okDzWrongSign != 0) {
wrongMassD0 = theD0particle->InvMassD0();
} else if (okDzWrongSign == 0) {
wrongMassD0 = theD0particle->InvMassD0bar();
}
if (TMath::Abs(wrongMassD0 - 1.865) < fD0Window) {
// wrong D* inv mass
Double_t e[3];
if (part->Charge() > 0) {
e[0] = theD0particle->EProng(0, 321);
e[1] = theD0particle->EProng(1, 211);
} else {
e[0] = theD0particle->EProng(0, 211);
e[1] = theD0particle->EProng(1, 321);
}
e[2] = part->EProng(0, 211);
Double_t esum = e[0] + e[1] + e[2];
Double_t pds = part->P();
Double_t wrongMassDstar = TMath::Sqrt(esum * esum - pds * pds);
TString fillthis = "";
fillthis = "histWrongSignMass_";
fillthis += ptbin;
((TH1F*)(listout->FindObject(fillthis)))->Fill(wrongMassDstar - wrongMassD0);
fillthis = "histWrongSignMass";
((TH1F*)(listout->FindObject(fillthis)))->Fill(wrongMassDstar - wrongMassD0);
}
}
//-------------------------------------------------------------------------------
Int_t AliAnalysisTaskSEDStarEMCALProductionCheck::CheckOrigin(TClonesArray* arrayMC, const AliAODMCParticle *mcPartCandidate) const {
//
// checking whether the mother of the particles come from a charm or a bottom quark
//
Int_t pdgGranma = 0;
Int_t mother = 0;
mother = mcPartCandidate->GetMother();
Int_t istep = 0;
Int_t abspdgGranma = 0;
Bool_t isFromB = kFALSE;
while (mother > 0 ) {
istep++;
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(arrayMC->At(mother));
if (mcGranma) {
pdgGranma = mcGranma->GetPdgCode();
abspdgGranma = TMath::Abs(pdgGranma);
if ((abspdgGranma > 500 && abspdgGranma < 600) || (abspdgGranma > 5000 && abspdgGranma < 6000)) {
isFromB = kTRUE;
}
mother = mcGranma->GetMother();
} else {
AliError("Failed casting the mother particle!");
break;
}
}
if (isFromB) return 5;
else return 4;
}
//-------------------------------------------------------------------------------------
Float_t AliAnalysisTaskSEDStarEMCALProductionCheck::GetTrueImpactParameterD0(const AliAODMCHeader *mcHeader, TClonesArray* arrayMC, const AliAODMCParticle *partDp) const {
/// true impact parameter calculation
Double_t vtxTrue[3];
mcHeader->GetVertex(vtxTrue);
Double_t origD[3];
partDp->XvYvZv(origD);
Short_t charge = partDp->Charge();
Double_t pXdauTrue[3], pYdauTrue[3], pZdauTrue[3];
Int_t labelFirstDau = partDp->GetDaughterLabel(0);
Int_t nDau = partDp->GetNDaughters();
Int_t theDau = 0;
if (nDau == 2) {
for (Int_t iDau = 0; iDau < 2; iDau++) {
Int_t ind = labelFirstDau + iDau;
AliAODMCParticle* part = dynamic_cast<AliAODMCParticle*>(arrayMC->At(ind));
if (!part) {
AliError("Daughter particle not found in MC array");
return 99999.;
}
Int_t pdgCode = TMath::Abs(part->GetPdgCode());
if (pdgCode == 211 || pdgCode == 321) {
pXdauTrue[theDau] = part->Px();
pYdauTrue[theDau] = part->Py();
pZdauTrue[theDau] = part->Pz();
++theDau;
}
}
}
if (theDau != 2) {
AliError("Wrong number of decay prongs");
return 99999.;
}
Double_t d0dummy[3] = {0., 0., 0.};
AliAODRecoDecayHF aodD0MC(vtxTrue, origD, 3, charge, pXdauTrue, pYdauTrue, pZdauTrue, d0dummy);
return aodD0MC.ImpParXY();
}
//______________________________________________________-
void AliAnalysisTaskSEDStarEMCALProductionCheck::CreateImpactParameterHistos() {
/// Histos for impact paramter study
Int_t nbins[3] = {400, 200, fNImpParBins};
Double_t xmin[3] = {1.75, 0., fLowerImpPar};
Double_t xmax[3] = {1.98, 20., fHigherImpPar};
fHistMassPtImpParTCDs[0] = new THnSparseF("hMassPtImpParAll",
"Mass vs. pt vs.imppar - All",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[1] = new THnSparseF("hMassPtImpParPrompt",
"Mass vs. pt vs.imppar - promptD",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[2] = new THnSparseF("hMassPtImpParBfeed",
"Mass vs. pt vs.imppar - DfromB",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[3] = new THnSparseF("hMassPtImpParTrueBfeed",
"Mass vs. pt vs.true imppar -DfromB",
3, nbins, xmin, xmax);
fHistMassPtImpParTCDs[4] = new THnSparseF("hMassPtImpParBkg",
"Mass vs. pt vs.imppar - backgr.",
3, nbins, xmin, xmax);
for (Int_t i = 0; i < 5; i++) {
fOutput->Add(fHistMassPtImpParTCDs[i]);
}
}
| 80,944 | 32,051 |
#include "kindyn/controller/cardsflow_command_interface.hpp"
namespace hardware_interface
{
CardsflowHandle::CardsflowHandle() : CardsflowStateHandle(){}
/**
* @param js This joint's state handle
* @param cmd A pointer to the storage for this joint's output command
*/
CardsflowHandle::CardsflowHandle(const CardsflowStateHandle& js, double* joint_position_cmd,
double* joint_velocity_cmd, double* joint_torque_cmd, VectorXd *motor_cmd)
: CardsflowStateHandle(js), joint_position_cmd_(joint_position_cmd), joint_velocity_cmd_(joint_velocity_cmd),
joint_torque_cmd_(joint_torque_cmd), motor_cmd_(motor_cmd)
{
}
void CardsflowHandle::setMotorCommand(VectorXd command) {*motor_cmd_ = command;}
double CardsflowHandle::getJointPositionCommand() const {return *joint_position_cmd_;}
double CardsflowHandle::getJointVelocityCommand() const {return *joint_velocity_cmd_;}
double CardsflowHandle::getJointTorqueCommand() const {return *joint_torque_cmd_;}
void CardsflowHandle::setJointPositionCommand(double cmd){*joint_position_cmd_ = cmd;}
void CardsflowHandle::setJointVelocityCommand(double cmd){*joint_velocity_cmd_ = cmd;}
void CardsflowHandle::setJointTorqueCommand(double cmd){*joint_torque_cmd_ = cmd;}
}
| 1,338 | 414 |
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/format_utils.h"
#include <set>
#include <string>
#include "ops/tuple_get_item.h"
#include "ops/depend.h"
#include "ops/make_tuple.h"
#include "ops/return.h"
#include "ops/batch_norm.h"
#include "ops/batch_to_space.h"
#include "ops/bias_add.h"
#include "ops/depth_to_space.h"
#include "ops/fused_batch_norm.h"
#include "ops/fusion/avg_pool_fusion.h"
#include "ops/fusion/conv2d_fusion.h"
#include "ops/fusion/conv2d_transpose_fusion.h"
#include "ops/fusion/max_pool_fusion.h"
#include "ops/fusion/prelu_fusion.h"
#include "ops/fusion/topk_fusion.h"
#include "ops/instance_norm.h"
#include "ops/lrn.h"
#include "ops/resize.h"
#include "ops/roi_pooling.h"
#include "ops/space_to_batch.h"
#include "ops/space_to_batch_nd.h"
#include "ops/space_to_depth.h"
#include "common/anf_util.h"
namespace mindspore {
namespace dpico {
namespace {
const std::set<std::string> kAssignedFormatOpSet = {
mindspore::ops::kNameAvgPoolFusion, mindspore::ops::kNameBatchNorm,
mindspore::ops::kNameBatchToSpace, mindspore::ops::kNameBiasAdd,
mindspore::ops::kNameConv2DFusion, mindspore::ops::kNameConv2dTransposeFusion,
mindspore::ops::kNameDepthToSpace, mindspore::ops::kNameFusedBatchNorm,
mindspore::ops::kNameInstanceNorm, mindspore::ops::kNameLRN,
mindspore::ops::kNameMaxPoolFusion, mindspore::ops::kNamePReLUFusion,
mindspore::ops::kNameResize, mindspore::ops::kNameROIPooling,
mindspore::ops::kNameSpaceToBatch, mindspore::ops::kNameSpaceToBatchND,
mindspore::ops::kNameSpaceToDepth, mindspore::ops::kNameTopKFusion};
} // namespace
const std::set<std::string> &GetAssignedFormatOpSet() { return kAssignedFormatOpSet; }
bool IsSpecialType(const api::CNodePtr &cnode) {
return CheckPrimitiveType(cnode, api::MakeShared<ops::TupleGetItem>()) ||
CheckPrimitiveType(cnode, api::MakeShared<ops::Depend>()) ||
CheckPrimitiveType(cnode, api::MakeShared<ops::MakeTuple>()) ||
CheckPrimitiveType(cnode, api::MakeShared<ops::Return>());
}
std::string FormatEnumToString(mindspore::Format format) {
static std::vector<std::string> names = {
"NCHW", "NHWC", "NHWC4", "HWKC", "HWCK", "KCHW", "CKHW", "KHWC", "CHWK",
"HW", "HW4", "NC", "NC4", "NC4HW4", "NUM_OF_FORMAT", "NCDHW", "NWC", "NCW",
};
if (format < mindspore::NCHW || format > mindspore::NCW) {
return "";
}
return names[format];
}
} // namespace dpico
} // namespace mindspore
| 3,046 | 1,165 |
//1462
#include <iostream>
#include <fstream>
#include <cmath>
#include <cctype>
#include <stdlib.h>
#include <string.h>
#define zero 1e-8
#define MAXN 110
using namespace std;
double t[MAXN];
char code[MAXN][MAXN][MAXN], name[100][100], del[300], *tok;
int m[MAXN], N, n;
double state[MAXN][MAXN], A[MAXN][MAXN + 1], r;
void Gauss()
{
int i, j, k;
for (j = 1; j <= n; j++)
{
for (i = j; i <= n; i++)
if (!(fabs(A[i][j]) < zero))
break;
if (i != j)
for (k = 1; k <= n + 1; k++)
swap(A[i][k], A[j][k]);
r = A[j][j];
for (k = j; k <= n + 1; k++)
A[j][k] /= r;
for (i = j + 1; i <= n; i++)
{
r = A[i][j];
for (k = j; k <= n + 1; k++)
A[i][k] -= r * A[j][k];
}
}
for (j = n; j >= 1; j--)
{
for (i = j - 1; i >= 1; i--)
{
r = A[i][j];
for (k = 1; k <= n + 1; k++)
A[i][k] -= A[j][k] * r;
}
}
}
void IntoA(int x)
{
int i;
for (i = 1; i <= n; i++)
A[x][i] = state[x][i];
A[x][n + 1] = - state[x][0];
A[x][x]--;
}
bool calc(int x)
{
double case1, case2;
int i, j, k;
char s[100];
n = m[x];
for (i = 0; i <= n; i++)
state[n][i] = 0;
IntoA(n);
for (k = n - 1; k >= 1; k--)
{
for (i = 0; i <= n; i++)
state[k][i] = state[k + 1][i];
if (strstr(code[x][k], "NOP;") != 0)
state[k][0]++;
else
{
strcpy(s, code[x][k]);
tok = strtok(s, del);
tok = strtok(NULL, del);
tok = strtok(NULL, del);
case1 = atof(tok);
case2 = 1 - case1;
if (strstr(code[x][k], ">") != 0)
swap(case1, case2);
tok = strtok(NULL, del);
tok = strtok(NULL, del);
if (strstr(code[x][k], "PROC") != 0)
{
for (i = 1; i <= N; i++)
if (strcmp(name[i], tok) == 0)
break;
if (fabs(t[i]) < zero)
return false;
state[k][0] += case1 * t[i];
state[k][0]++;
}
else
{
j = atoi(tok);
for (i = 0; i <= n; i++)
state[k][i] *= case2;
if (j > k)
for (i = 0; i <= n; i++)
state[k][i] += case1 * state[j][i];
else
state[k][j] += case1;
state[k][0]++;
}
}
IntoA(k);
}
return true;
}
int main()
{
int i, j, ndel;
char s[100];
ndel = 0;
for (i = 255; i >= 0; i--)
if (! (isalpha(char(i)) || isdigit(char(i)) || char(i) == '.'))
del[++ndel - 1] = char(i);
del[ndel] = '\0';
ifstream cin("random.dat", ios::in);
cin.getline(s, 200, '\n');
N = 0;
while (1)
{
cin.getline(s, 100, '\n');
if (strcmp(s, "PROG_END") == 0)
break;
N++;
m[N] = 0;
tok = strtok(s, del);
tok = strtok(NULL, del);
strcpy(name[N], tok);
while (1)
{
cin.getline(s, 100, '\n');
++m[N];
strcpy(code[N][m[N]], s);
if (strcmp(s, "END;") == 0)
break;
}
}
for (i = 1; i <= N; i++)
t[i] = 0;
i = N;
while (i > 0)
{
for (j = 1; j <= N; j++)
if (fabs(t[j]) < zero)
if (calc(j))
{
i--;
Gauss();
t[j] = A[1][n + 1];
}
}
while (1)
{
cin.getline(s, 100, '\n');
if (strcmp(s, "REQUEST_END") == 0)
break;
for (i = 1; i <= N; i++)
if (strcmp(s, name[i]) == 0)
{
printf("%.3Lf\n", t[i]);
break;
}
}
cin.close();
//system("pause");
return 0;
} | 3,320 | 1,811 |
#include "pxt.h"
using namespace pxt;
namespace test {
//%
void dammy(int32_t x, int32_t y){
uBit.display.image.setPixelValue(0, 0, 255);
}
} | 151 | 77 |
#include <cstdlib>
#include <iostream>
typedef int ElemType;
typedef struct LinkNode {
ElemType data;
struct LinkNode *next;
} LinkNode, *LinkList;
void outPut(LinkList L) {
LinkNode *p = L->next;
while (p != NULL) {
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
void rearInsert(LinkList &L, ElemType x) {
LinkNode *s = new LinkNode;
s->data = x;
L->next = s;
L = s;
}
void rearInsertCreate(LinkList &L, ElemType arr[], int length) {
L = new LinkNode;
LinkNode *p = L;
for (int i = 0; i < length; i++) {
rearInsert(p, arr[i]);
}
p->next = NULL;
}
// 题目要求根据大写、小写和数字分类,这样我还得重新定义char类型的链表,太麻烦了
// 所以我按照大写、小写、数字的ASCII码范围来分类,这样都能保证是int型
// 数字:48 ~ 57,放在A里
// 大写:65 ~ 90,放在B里
// 小写:97 ~ 122,放在C里
void SeprateByCharType(LinkList &A, LinkList &B, LinkList &C) {
LinkNode *pre = A;
LinkNode *p = A->next;
B = new LinkNode;
LinkNode *q = B;
C = new LinkNode;
LinkNode *r = C;
while (p != NULL) {
// 放在A里
if (p->data >= 48 && p->data <= 57) {
p = p->next;
pre = pre->next;
continue; //终止当前这次循环,直接进入下一次循环
}
// 放在B里
if (p->data >= 65 && p->data <= 90) {
rearInsert(q, p->data);
// 在A中删除p所指的位置,然后把p定位到下一个位置
pre->next = p->next;
delete p;
p = pre->next;
continue;
}
// 放在C里
if (p->data >= 97 && p->data <= 122) {
rearInsert(r, p->data);
pre->next = p->next;
delete p;
p = pre->next;
// 这里就不用加continue了,因为下面已经没有语句了,肯定会执行下一次循环
}
}
q->next = NULL;
r->next = NULL;
}
int main() {
ElemType arr[] = {49, 66, 98, 50, 67, 99, 51, 68, 100, 52, 69, 101};
int length = sizeof(arr) / sizeof(int);
LinkList L1 = NULL;
LinkList L2 = NULL;
LinkList L3 = NULL;
rearInsertCreate(L1, arr, length);
outPut(L1);
SeprateByCharType(L1, L2, L3);
outPut(L1);
outPut(L2);
outPut(L3);
return 0;
}
// 输出结果:
// 49 66 98 50 67 99 51 68 100 52 69 101
// 49 50 51 52
// 66 67 68 69
// 98 99 100 101
| 2,204 | 1,071 |
#ifdef PIXELBOOST_PLATFORM_ANDROID
#include "pixelboost/network/networkHelpers.h"
namespace pb
{
namespace NetworkHelpers
{
std::string GetWifiAddress()
{
return "";
}
}
}
#endif | 197 | 79 |
/*
** Copyright (c) 2018-2019 Valve Corporation
** Copyright (c) 2018-2019 LunarG, Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include "decode/compression_converter.h"
#include "format/format_util.h"
#include "util/logging.h"
#include <cassert>
GFXRECON_BEGIN_NAMESPACE(gfxrecon)
GFXRECON_BEGIN_NAMESPACE(decode)
CompressionConverter::CompressionConverter() : bytes_written_(0), compressor_(nullptr), decompressing_(false) {}
CompressionConverter::~CompressionConverter()
{
Destroy();
}
bool CompressionConverter::Initialize(std::string filename,
const format::FileHeader& file_header,
const std::vector<format::FileOptionPair>& option_list,
format::CompressionType target_compression_type)
{
bool success = false;
// Modify compression setting and write file header to a new file.
filename_ = filename;
file_stream_ = std::make_unique<util::FileOutputStream>(filename_);
if (format::CompressionType::kNone == target_compression_type)
{
decompressing_ = true;
compressor_ = nullptr;
}
else
{
decompressing_ = false;
compressor_ = format::CreateCompressor(target_compression_type);
if (nullptr == compressor_)
{
GFXRECON_LOG_WARNING("Failed to initialized file compression module (type = %u)", target_compression_type);
return false;
}
}
std::vector<format::FileOptionPair> new_option_list = option_list;
for (auto& option : new_option_list)
{
switch (option.key)
{
case format::FileOption::kCompressionType:
// Change the file option to the new compression type
option.value = static_cast<uint32_t>(target_compression_type);
break;
default:
GFXRECON_LOG_WARNING("Ignoring unrecognized file header option %u", option.key);
break;
}
}
if (file_stream_->IsValid())
{
bytes_written_ = 0;
bytes_written_ += file_stream_->Write(&file_header, sizeof(file_header));
bytes_written_ +=
file_stream_->Write(new_option_list.data(), new_option_list.size() * sizeof(format::FileOptionPair));
success = true;
}
else
{
GFXRECON_LOG_ERROR("Failed to open file %s", filename_.c_str());
}
return success;
}
void CompressionConverter::Destroy()
{
if (nullptr != compressor_)
{
delete compressor_;
compressor_ = nullptr;
}
}
void CompressionConverter::DecodeFunctionCall(format::ApiCallId call_id,
const ApiCallInfo& call_info,
const uint8_t* buffer,
size_t buffer_size)
{
bool write_uncompressed = decompressing_;
if (!decompressing_)
{
// Compress the buffer with the new compression format and write to the new file.
format::CompressedFunctionCallHeader compressed_func_call_header = {};
size_t packet_size = 0;
size_t compressed_size = compressor_->Compress(buffer_size, buffer, &compressed_buffer_);
if (0 < compressed_size && compressed_size < buffer_size)
{
compressed_func_call_header.block_header.type = format::BlockType::kCompressedFunctionCallBlock;
compressed_func_call_header.api_call_id = call_id;
compressed_func_call_header.thread_id = call_info.thread_id;
compressed_func_call_header.uncompressed_size = buffer_size;
packet_size += sizeof(compressed_func_call_header.api_call_id) +
sizeof(compressed_func_call_header.thread_id) +
sizeof(compressed_func_call_header.uncompressed_size) + compressed_size;
compressed_func_call_header.block_header.size = packet_size;
// Write compressed function call block header.
bytes_written_ += file_stream_->Write(&compressed_func_call_header, sizeof(compressed_func_call_header));
// Write parameter data.
bytes_written_ += file_stream_->Write(compressed_buffer_.data(), compressed_size);
}
else
{
// It's bigger compressed than uncompressed, so only write the uncompressed data.
write_uncompressed = true;
}
}
if (write_uncompressed)
{
// Buffer is currently not compressed; it was decompressed prior to this call.
format::FunctionCallHeader func_call_header = {};
size_t packet_size = 0;
func_call_header.block_header.type = format::BlockType::kFunctionCallBlock;
func_call_header.api_call_id = call_id;
func_call_header.thread_id = call_info.thread_id;
packet_size += sizeof(func_call_header.api_call_id) + sizeof(func_call_header.thread_id) + buffer_size;
func_call_header.block_header.size = packet_size;
// Write compressed function call block header.
bytes_written_ += file_stream_->Write(&func_call_header, sizeof(func_call_header));
// Write parameter data.
bytes_written_ += file_stream_->Write(buffer, buffer_size);
}
}
void CompressionConverter::DispatchStateBeginMarker(uint64_t frame_number)
{
format::Marker marker;
marker.header.size = sizeof(marker.marker_type) + sizeof(marker.frame_number);
marker.header.type = format::kStateMarkerBlock;
marker.marker_type = format::kBeginMarker;
marker.frame_number = frame_number;
bytes_written_ += file_stream_->Write(&marker, sizeof(marker));
}
void CompressionConverter::DispatchStateEndMarker(uint64_t frame_number)
{
format::Marker marker;
marker.header.size = sizeof(marker.marker_type) + sizeof(marker.frame_number);
marker.header.type = format::kStateMarkerBlock;
marker.marker_type = format::kEndMarker;
marker.frame_number = frame_number;
bytes_written_ += file_stream_->Write(&marker, sizeof(marker));
}
void CompressionConverter::DispatchDisplayMessageCommand(format::ThreadId thread_id, const std::string& message)
{
size_t message_length = message.size();
format::DisplayMessageCommandHeader message_cmd;
message_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
message_cmd.meta_header.block_header.size =
sizeof(message_cmd.meta_header.meta_data_type) + sizeof(message_cmd.thread_id) + message_length;
message_cmd.meta_header.meta_data_type = format::MetaDataType::kDisplayMessageCommand;
message_cmd.thread_id = thread_id;
bytes_written_ += file_stream_->Write(&message_cmd, sizeof(message_cmd));
bytes_written_ += file_stream_->Write(message.c_str(), message_length);
}
void CompressionConverter::DispatchFillMemoryCommand(
format::ThreadId thread_id, uint64_t memory_id, uint64_t offset, uint64_t size, const uint8_t* data)
{
// NOTE: Don't apply the offset to the write_address here since it's coming from the file_processor
// at the start of the stream. We only need to record the writing offset for future info.
format::FillMemoryCommandHeader fill_cmd;
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, size);
size_t write_size = static_cast<size_t>(size);
fill_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
fill_cmd.meta_header.meta_data_type = format::MetaDataType::kFillMemoryCommand;
fill_cmd.thread_id = thread_id;
fill_cmd.memory_id = memory_id;
fill_cmd.memory_offset = offset;
fill_cmd.memory_size = write_size;
if ((!decompressing_) && (compressor_ != nullptr))
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
// We don't have a special header for compressed fill commands because the header always includes
// the uncompressed size, so we just change the type to indicate the data is compressed.
fill_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
fill_cmd.meta_header.block_header.size = sizeof(fill_cmd.meta_header.meta_data_type) + sizeof(fill_cmd.thread_id) +
sizeof(fill_cmd.memory_id) + sizeof(fill_cmd.memory_offset) +
sizeof(fill_cmd.memory_size) + write_size;
bytes_written_ += file_stream_->Write(&fill_cmd, sizeof(fill_cmd));
bytes_written_ += file_stream_->Write(write_address, write_size);
}
void CompressionConverter::DispatchResizeWindowCommand(format::ThreadId thread_id,
format::HandleId surface_id,
uint32_t width,
uint32_t height)
{
format::ResizeWindowCommand resize_cmd;
resize_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
resize_cmd.meta_header.block_header.size = sizeof(resize_cmd.meta_header.meta_data_type) +
sizeof(resize_cmd.thread_id) + sizeof(resize_cmd.surface_id) +
sizeof(resize_cmd.width) + sizeof(resize_cmd.height);
resize_cmd.meta_header.meta_data_type = format::MetaDataType::kResizeWindowCommand;
resize_cmd.thread_id = thread_id;
resize_cmd.surface_id = surface_id;
resize_cmd.width = width;
resize_cmd.height = height;
bytes_written_ += file_stream_->Write(&resize_cmd, sizeof(resize_cmd));
}
void CompressionConverter::DispatchSetSwapchainImageStateCommand(
format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId swapchain_id,
uint32_t last_presented_image,
const std::vector<format::SwapchainImageStateInfo>& image_state)
{
format::SetSwapchainImageStateCommandHeader header;
size_t image_count = image_state.size();
size_t image_state_size = 0;
// Initialize standard block header.
header.meta_header.block_header.size = sizeof(header.meta_header.meta_data_type) + sizeof(header.thread_id) +
sizeof(header.device_id) + sizeof(header.swapchain_id) +
sizeof(header.last_presented_image) + sizeof(header.image_info_count);
header.meta_header.block_header.type = format::kMetaDataBlock;
if (image_count > 0)
{
image_state_size = image_count * sizeof(image_state[0]);
header.meta_header.block_header.size += image_state_size;
}
// Initialize block data for set-swapchain-image-state meta-data command.
header.meta_header.meta_data_type = format::kSetSwapchainImageStateCommand;
header.thread_id = thread_id;
header.device_id = device_id;
header.swapchain_id = swapchain_id;
header.last_presented_image = last_presented_image;
header.image_info_count = static_cast<uint32_t>(image_count);
bytes_written_ += file_stream_->Write(&header, sizeof(header));
bytes_written_ += file_stream_->Write(image_state.data(), image_state_size);
}
void CompressionConverter::DispatchBeginResourceInitCommand(format::ThreadId thread_id,
format::HandleId device_id,
uint64_t max_resource_size,
uint64_t max_copy_size)
{
format::BeginResourceInitCommand begin_cmd;
begin_cmd.meta_header.block_header.size = sizeof(begin_cmd) - sizeof(begin_cmd.meta_header.block_header);
begin_cmd.meta_header.block_header.type = format::kMetaDataBlock;
begin_cmd.meta_header.meta_data_type = format::kBeginResourceInitCommand;
begin_cmd.thread_id = thread_id;
begin_cmd.device_id = device_id;
begin_cmd.max_resource_size = max_resource_size;
begin_cmd.max_copy_size = max_copy_size;
bytes_written_ += file_stream_->Write(&begin_cmd, sizeof(begin_cmd));
}
void CompressionConverter::DispatchEndResourceInitCommand(format::ThreadId thread_id, format::HandleId device_id)
{
format::EndResourceInitCommand end_cmd;
end_cmd.meta_header.block_header.size = sizeof(end_cmd) - sizeof(end_cmd.meta_header.block_header);
end_cmd.meta_header.block_header.type = format::kMetaDataBlock;
end_cmd.meta_header.meta_data_type = format::kEndResourceInitCommand;
end_cmd.thread_id = thread_id;
end_cmd.device_id = device_id;
bytes_written_ += file_stream_->Write(&end_cmd, sizeof(end_cmd));
}
void CompressionConverter::DispatchInitBufferCommand(format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId buffer_id,
uint64_t data_size,
const uint8_t* data)
{
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, data_size);
size_t write_size = static_cast<size_t>(data_size);
format::InitBufferCommandHeader init_cmd;
init_cmd.meta_header.block_header.type = format::kMetaDataBlock;
init_cmd.meta_header.meta_data_type = format::kInitBufferCommand;
init_cmd.thread_id = thread_id;
init_cmd.device_id = device_id;
init_cmd.buffer_id = buffer_id;
init_cmd.data_size = write_size; // Uncompressed data size.
if (compressor_ != nullptr)
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
init_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
init_cmd.meta_header.block_header.size =
(sizeof(init_cmd) - sizeof(init_cmd.meta_header.block_header)) + write_size;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
bytes_written_ += file_stream_->Write(write_address, write_size);
}
void CompressionConverter::DispatchInitImageCommand(format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId image_id,
uint64_t data_size,
uint32_t aspect,
uint32_t layout,
const std::vector<uint64_t>& level_sizes,
const uint8_t* data)
{
format::InitImageCommandHeader init_cmd;
// Packet size without the resource data.
init_cmd.meta_header.block_header.size = sizeof(init_cmd) - sizeof(init_cmd.meta_header.block_header);
init_cmd.meta_header.block_header.type = format::kMetaDataBlock;
init_cmd.meta_header.meta_data_type = format::kInitImageCommand;
init_cmd.thread_id = thread_id;
init_cmd.device_id = device_id;
init_cmd.image_id = image_id;
init_cmd.aspect = aspect;
init_cmd.layout = layout;
if (data_size > 0)
{
assert(!level_sizes.empty());
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, data_size);
size_t write_size = static_cast<size_t>(data_size);
// Store uncompressed data size in packet.
init_cmd.data_size = write_size;
init_cmd.level_count = static_cast<uint32_t>(level_sizes.size());
if (compressor_ != nullptr)
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
init_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
size_t levels_size = level_sizes.size() * sizeof(level_sizes[0]);
init_cmd.meta_header.block_header.size += levels_size + write_size;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
bytes_written_ += file_stream_->Write(level_sizes.data(), levels_size);
bytes_written_ += file_stream_->Write(write_address, write_size);
}
else
{
// Write a packet without resource data; replay must still perform a layout transition at image
// initialization.
init_cmd.data_size = 0;
init_cmd.level_count = 0;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
}
}
GFXRECON_END_NAMESPACE(decode)
GFXRECON_END_NAMESPACE(gfxrecon)
| 19,215 | 5,422 |
/*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the YSI 2.0 SA:MP plugin.
*
* The Initial Developer of the Original Code is Alex "Y_Less" Cole.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Peter Beverloo
* Marcus Bauer
*/
#include "utils.h"
bool IsPointInRange(float x1, float y1, float z1, float x2, float y2, float z2, float distance)
{
return (GetRangeSquared(x1, y1, z1, x2, y2, z2) < (float)(distance * distance));
}
bool IsPointInRangeSq(float x1, float y1, float z1, float x2, float y2, float z2, float distance)
{
return (GetRangeSquared(x1, y1, z1, x2, y2, z2) < distance);
}
float GetRangeSquared(float x1, float y1, float z1, float x2, float y2, float z2)
{
x1 -= x2;
y1 -= y2;
z1 -= z2;
return ((float)((float)(x1 * x1) + (float)(y1 * y1) + (float)(z1 * z1)));
}
| 1,450 | 541 |
//===================================================================================================================
//
// DebugVars.cc -- Variables used by the debugger
//
// Copyright (c) 2017-2020 -- Adam Clark
// Licensed under "THE BEER-WARE LICENSE"
// See License.md for details.
//
// ------------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2020-Apr-02 Initial v0.6.0a ADCL Initial version
//
//===================================================================================================================
#include "types.h"
#include "debugger.h"
//
// -- This is the current variable that identifies the current state
// --------------------------------------------------------------
EXPORT KERNEL_BSS
DebuggerState_t debugState;
//
// -- This is the buffer for the command being entered
// ------------------------------------------------
EXPORT KERNEL_BSS
char debugCommand[DEBUG_COMMAND_LEN];
//
// -- For each state, this is the visual representation where on the command tree the user is and what the
// valid commands are (indexed by state).
// ----------------------------------------------------------------------------------------------------
EXPORT KERNEL_DATA
DebugPrompt_t dbgPrompts[] {
// -- location allowed
{"-", "scheduler,timer,msgq"}, // -- DBG_HOME
{"sched", "show,status,run,ready,list,exit"}, // -- DBG_SCHED
{"sched:ready", "all,os,high,normal,low,idle,exit"}, // -- DBG_SCHED_RDY
{"sched:list", "blocked,sleeping,zombie,exit"}, // -- DBG_SCHED_LIST
{"timer", "counts,config,exit"}, // -- DBG_TIMER
{"msgq", "status,show,exit"}, // -- DBG_MSGQ
};
//
// -- This is the actual debug communication structure
// ------------------------------------------------
EXPORT KERNEL_BSS
DebugComm_t debugCommunication = {0};
| 2,291 | 581 |
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @file
*/
#pragma once
#include <builders/ie_layer_decorator.hpp>
#include <ie_network.hpp>
#include <string>
#include <vector>
namespace InferenceEngine {
namespace Builder {
/**
* @deprecated Use ngraph API instead.
* @brief The class represents a builder for Crop layer
*/
IE_SUPPRESS_DEPRECATED_START
class INFERENCE_ENGINE_NN_BUILDER_API_CLASS(CropLayer): public LayerDecorator {
public:
/**
* @brief The constructor creates a builder with the name
* @param name Layer name
*/
explicit CropLayer(const std::string& name = "");
/**
* @brief The constructor creates a builder from generic builder
* @param layer pointer to generic builder
*/
explicit CropLayer(const Layer::Ptr& layer);
/**
* @brief The constructor creates a builder from generic builder
* @param layer constant pointer to generic builder
*/
explicit CropLayer(const Layer::CPtr& layer);
/**
* @brief Sets the name for the layer
* @param name Layer name
* @return reference to layer builder
*/
CropLayer& setName(const std::string& name);
/**
* @brief Returns input ports
* @return Vector of input ports
*/
const std::vector<Port>& getInputPorts() const;
/**
* @brief Sets input ports
* @param ports Vector of input ports
* @return reference to layer builder
*/
CropLayer& setInputPorts(const std::vector<Port>& ports);
/**
* @brief Return output port
* @return Output port
*/
const Port& getOutputPort() const;
/**
* @brief Sets output port
* @param port Output port
* @return reference to layer builder
*/
CropLayer& setOutputPort(const Port& port);
/**
* @brief Returns axis
* @return Vector of axis
*/
const std::vector<size_t> getAxis() const;
/**
* @brief Sets axis
* @param axis Vector of axis
* @return reference to layer builder
*/
CropLayer& setAxis(const std::vector<size_t>& axis);
/**
* @brief Returns offsets
* @return Vector of offsets
*/
const std::vector<size_t> getOffset() const;
/**
* @brief Sets offsets
* @param offsets Vector of offsets
* @return reference to layer builder
*/
CropLayer& setOffset(const std::vector<size_t>& offsets);
};
IE_SUPPRESS_DEPRECATED_END
} // namespace Builder
} // namespace InferenceEngine
| 2,519 | 776 |
// test_6414.cpp - a test driver for UNtoU3 class.
//
// License: BSD 2-Clause (https://opensource.org/licenses/BSD-2-Clause)
//
// Copyright (c) 2019, Daniel Langr
// All rights reserved.
//
// Program implements the U(N) to U(3) reduction where n=5 (N=21) for the input irrep
// [f] = [2,2,2,2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
// which is represented by a number of twos n2=6, number of ones n1=1, and number of zeros n0=14.
// Its dimension is dim[f] = 2168999910.
//
// After reduction, the program iterates over generated U(3) weights and calculates the sum of
// dimensions of resulting U(3) irrpes multiplied by their level dimensionalities. This sum
// should be equal to dim[f].
#include <iostream>
// #define UNTOU3_DISABLE_TCO
// #define UNTOU3_DISABLE_UNORDERED
// #define UNTOU3_DISABLE_PRECALC
#define UNTOU3_ENABLE_OPENMP
#include "UNtoU3.h"
unsigned long dim(const UNtoU3<>::U3Weight & irrep) {
return (irrep[0] - irrep[1] + 1) * (irrep[0] - irrep[2] + 2) * (irrep[1] - irrep[2] + 1) / 2;
}
int main() {
UNtoU3<> gen;
// n=5 - a given HO level, N = (n+1)*(n+2)/2 = 21
gen.generateXYZ(5);
// generation of U(3) irreps in the input U(21) irrep [f]
gen.generateU3Weights(6, 1, 14);
// calculated sum
unsigned long sum = 0;
// iteration over generated U(3) weights
for (const auto & pair : gen.multMap()) {
// get U(3) weight lables
const auto & weight = pair.first;
// get its level dimensionality if its nonzero and the U(3) weight is a U(3) irrep
if (auto D_l = gen.getLevelDimensionality(weight))
// add contribution of this U(3) irrep to the sum
sum += D_l * dim(weight);
}
std::cout << sum << std::endl;
}
| 1,715 | 685 |
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "core/components/common/layout/constants.h"
#include "core/components/popup/popup_component.h"
#include "frameworks/bridge/common/dom/dom_document.h"
#include "frameworks/bridge/common/dom/dom_popup.h"
#include "frameworks/bridge/test/unittest/jsfrontend/dom_node_factory.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Ace::Framework {
namespace {
const Placement PLACEMENT_VALUE = Placement::LEFT;
const std::string MASK_COLOR_DEFAULT = "#0x0000ff";
} // namespace
class DomPopupTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
};
void DomPopupTest::SetUpTestCase() {}
void DomPopupTest::TearDownTestCase() {}
void DomPopupTest::SetUp() {}
void DomPopupTest::TearDown() {}
/**
* @tc.name: DomPopupCreatorTest001
* @tc.desc: Test create popup node successfully and popupcomponent create as desire.
* @tc.type: FUNC
* @tc.require: AR000DD66M
* @tc.author: chenbenzhi
*/
HWTEST_F(DomPopupTest, DomPopupCreatorTest001, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the json string of popup component with tag only.
*/
const std::string jsonPopupStr = ""
"{ "
" \"tag\": \"popup\" "
"}";
/**
* @tc.steps: step2. Verify whether the DomPopup.
* @tc.expected: step3. DomPopup is not null.
*/
auto popup = DOMNodeFactory::GetInstance().CreateDOMNodeFromDsl(jsonPopupStr);
EXPECT_TRUE(popup);
}
/**
* @tc.name: DomPopupTest002
* @tc.desc: Verify that DomPopup can be set attributes and styles.
* @tc.type: FUNC
* @tc.require: AR000DD66M
* @tc.author: chenbenzhi
*/
HWTEST_F(DomPopupTest, DomPopupTest002, TestSize.Level1)
{
/**
* @tc.steps: step1. construct the json string of DomPopup with attributes and styles.
*/
const std::string jsonPopupStr = ""
"{ "
" \"tag\": \"popup\", "
" \"attr\": [ "
" {"
" \"placement\" : \"left\" "
" }], "
" \"style\": [{ "
" \"maskColor\" : \"#0x0000ff\" "
" }]"
"}";
/**
* @tc.steps: step2. call jsonPopupStr interface, create DomPopup and set its style.
*/
auto domNodeRoot = DOMNodeFactory::GetInstance().CreateDOMNodeFromDsl(jsonPopupStr);
auto popupChild = AceType::DynamicCast<PopupComponent>(domNodeRoot->GetSpecializedComponent());
ACE_DCHECK(popupChild);
/**
* @tc.steps: step3. Check all the attributes and styles matched.
* @tc.expected: step3. All the attributes and styles are matched.
*/
EXPECT_TRUE(popupChild);
EXPECT_EQ(popupChild->GetPopupParam()->GetPlacement(), PLACEMENT_VALUE);
EXPECT_EQ(popupChild->GetPopupParam()->GetMaskColor(), Color::FromString(MASK_COLOR_DEFAULT));
}
/**
* @tc.name: DomPopupTest003
* @tc.desc: Test add event to popup component successfully.
* @tc.type: FUNC
* @tc.require: AR000DD66M
* @tc.author: chenbenzhi
*/
HWTEST_F(DomPopupTest, DomPopupTest003, TestSize.Level1)
{
/**
* @tc.steps: step1. Construct string with right fields, then create popup node with it.
* @tc.expected: step1. Popup node and is created successfully.
*/
const std::string jsonPopupStr = ""
"{ "
" \"tag\": \"popup\", "
" \"event\": [ \"visibilitychange\" ] "
"}";
auto domNodeRoot = DOMNodeFactory::GetInstance().CreateDOMNodeFromDsl(jsonPopupStr);
auto popupChild = AceType::DynamicCast<PopupComponent>(domNodeRoot->GetSpecializedComponent());
ACE_DCHECK(popupChild);
/**
* @tc.steps: step2. Check eventId of created popup component.
* @tc.expected: step2. The eventId value of popup component is as expected.
*/
EXPECT_TRUE(popupChild);
EXPECT_EQ(popupChild->GetPopupParam()->GetOnVisibilityChange(), std::to_string(domNodeRoot->GetNodeId()));
}
} // namespace OHOS::Ace::Framework
| 5,491 | 1,609 |
#include "procx.h"
#include <assert.h>
ProcessClass::ProcessClass(void)
{
State = STATE_ON;
RodzajWej = '.';
RodzajWyj = '.';
PrevProcess = NULL;
NextProcess = NULL;
}
void ProcessClass::LocalDestructor(void)
{
if(NextProcess != NULL)
{
NextProcess->LocalDestructor();
delete NextProcess;
NextProcess = NULL;
}
}
ProcessClass::~ProcessClass(void)
{
LocalDestructor();
}
int ProcessClass::Init(int, char *[])
{
SygError("To nie powinno być wywoływane");
return RESULT_OFF;
}
int ProcessClass::Work(int, Byte *, int)
{
SygError("To nie powinno być wywoływane");
return 0;
}
ProcessClass * ProcessClass::FindUnusedPointer(void)
{
ProcessClass * tmp;
tmp = NULL;
if(NextProcess != NULL)
{
tmp = NextProcess->FindUnusedPointer();
}
else
{
if(RodzajWyj == 'M' || RodzajWyj == 'B')
{
tmp = this;
}
}
return tmp;
}
/* Podłącza w wolne miejsce wskaźnik następnego procesu. Wartość zwracana:
1 - OK, 0 - błąd */
int ProcessClass::ConnectPointer(ProcessClass * proc)
{
int status;
status = 0;
if(NextProcess == NULL)
{
NextProcess = proc;
proc->PrevProcess = this;
status = 1;
}
else
{
SygError("Proces twierdził, że ma miejsce na podłączenie następnego?");
}
return status;
}
/* Sprawdza, czy do aktualnego obiektu można podłączyć następny obiekt.
Dozwolone są tylko połączenia "B->M" i "M->B". Wartość zwrotna: 1 - typy
są zgodne, 0 - typy są niezgodne, co zabrania tworzenia takiego połączenia */
int ProcessClass::ZgodnyTyp(ProcessClass *proc)
{
int status;
status = 0;
if(RodzajWyj == 'B')
{
if(proc->RodzajWej == 'M')
{
status = 1;
}
}
else
{
if(RodzajWyj == 'M')
{
if(proc->RodzajWej == 'B')
{
status = 1;
}
}
}
return status;
}
/* Funkcja sprawdza, czy podany proces może pracować jako proces wejściowy.
Wartość zwrotna: 1 - tak, 0 - nie */
int ProcessClass::ProcesWejsciowy(void)
{
int status;
status = 0;
if(RodzajWej == '-')
{
status = 1;
}
return status;
}
/* Zmienia stan obiektu na podany. Jeśli to jest zmiana na STATE_OFF,
to od razu powiadamia sąsiadów z obu stron. */
void ProcessClass::ZmienStan(int nowy, int kier)
{
assert(nowy == STATE_OFF || nowy == STATE_EOF);
assert(kier == KIER_PROSTO || kier == KIER_WSTECZ || kier == KIER_INNY);
if(nowy == STATE_OFF)
{
if(State != nowy)
{
State = nowy;
if(kier != KIER_WSTECZ)
{
if(NextProcess != NULL)
{
NextProcess->Work(SAND_OFF, NULL, KIER_PROSTO);
}
}
}
}
else
{
State = nowy;
}
}
/* Tworzenie nowych wątków dla obsługi systemu i budzenie ich.
Wartość zwrotna: 1 - OK (udało się pomyślnie utworzyć nowe wątki),
0 - błąd (możemy kończyć pracę systemu, bo się nie udał przydział wątków */
int ProcessClass::Rozszczepianie(void)
{
int status;
status = 1; /* Tak ogólnie niczego nie trzeba rozszczepiać */
if(NextProcess != NULL)
{
status = NextProcess->Rozszczepianie();
}
return status;
}
| 2,911 | 1,193 |
#include "componentMask.h"
#include "nomad.h"
namespace nomad {
bool ComponentMask::isNewMatch(nomad::ComponentMask oldMask, nomad::ComponentMask systemMask) {
return matches(systemMask) && !oldMask.matches(systemMask);
}
bool ComponentMask::isNoLongerMatched(nomad::ComponentMask oldMask, nomad::ComponentMask systemMask) {
return oldMask.matches(systemMask) && !matches(systemMask);
}
bool ComponentMask::matches(nomad::ComponentMask systemMask) { return ((mask & systemMask.mask) == systemMask.mask); }
} // namespace nomad
| 535 | 161 |
#include <ESP8266WiFi.h>
#include "Arduino.h"
#include <FastLED.h>
// How many leds in your strip?
#define NUM_LEDS 8
void coracao(uint16_t color256);
// For led chips like WS2812, which have a data line, ground, and power, you just
// need to define DATA_PIN. For led chipsets that are SPI based (four wires - data, clock,
#define DATA_PIN D3
// Define the array of leds
CRGB leds[NUM_LEDS];
const char* ssid = "Your_SSID"; // Net Virtua 169 2g
const char* password = "Your_PSK";
//Host e chave disponíveis na plataforma IFTTT.
const char* host = "maker.ifttt.com";
//Led indica que a mensagem foi disparada ao IFTTT.
#define BUTTON_PIN D7
const char* eventName1 = "/trigger/button_pressed/with/key/briI0wuHkLJTMEcWOUnXe4";
const char* eventName2 = "/trigger/button_released/with/key/briI0wuHkLJTMEcWOUnXe4";
void button_pressed();
void button_released();
void connectToWifi();
void setup() {
// pinMode(D6,OUTPUT);
// digitalWrite(D6, LOW);
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS); // GRB ordering is assumed
delay(50);
//Porta serial configurada em 115200 baud rate.
Serial.begin(74880);
delay(10);
// set button pin as an input
pinMode(BUTTON_PIN, INPUT);
connectToWifi();
}
void loop()
{
//Assim que o botao for pressionado o SMS é disparado.
if(digitalRead(BUTTON_PIN) == LOW){
button_pressed();
delay(5000);
button_released();
}
coracao(32000);
FastLED.show();
}
void connectToWifi()
{
//Serial monitor indica comunicacao entre Wi-Fi e ESP8266.
Serial.print("Conectado em:");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi conectado");
Serial.println("Endereco IP: ");
Serial.println(WiFi.localIP());
}
void button_pressed()
{
// Turn the LED on, then pause
for (size_t i = 0; i < NUM_LEDS/2; i++)
{
leds[i] = CRGB::Red; //cor fabi 123457
leds[7-i] = CRGB::Red;
FastLED.show();
delay(100);
}
Serial.print("conectado em: ");
Serial.println(host);
WiFiClient client;
//Estabelece comunicacao através da porta 80 - HTTP.
const int httpPort = 80;
//Caso a conexao nao seja estabelecida entre ESP82666 e IFTTT.
if (!client.connect(host, httpPort)) {
Serial.println("Falha de Conexao");
return;
}
//Dispara eventName através da chave de comunicacao do IFTTT.
String url = eventName1;
Serial.print("URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Conexao: Fechada\r\n\r\n");
int timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) {
Serial.println(">>> Tempo Excedido !");
client.stop();
return;
}
}
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("Fechando Conexao");
delay(1000);
}
void button_released()
{
Serial.print("conectado em: ");
Serial.println(host);
WiFiClient client;
//Estabelece comunicacao através da porta 80 - HTTP.
const int httpPort = 80;
//Caso a conexao nao seja estabelecida entre ESP82666 e IFTTT.
if (!client.connect(host, httpPort)) {
Serial.println("Falha de Conexao");
return;
}
//Dispara eventName através da chave de comunicacao do IFTTT.
String url = eventName2;
Serial.print("URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Conexao: Fechada\r\n\r\n");
int timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) {
Serial.println(">>> Tempo Excedido !");
client.stop();
return;
}
}
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("Fechando Conexao");
delay(1000);
// Now turn the LED off, then pause
for (size_t i = 0; i < NUM_LEDS/2; i++)
{
leds[i] = CRGB::Black;
leds[7-i] = CRGB::Black;
FastLED.show();
delay(100);
}
}
void coracao(uint16_t color256)
{
static uint16_t sPseudotime = 0;
static uint16_t sLastMillis = 0;
uint8_t sat8 = beatsin88( 87, 220, 250);
uint8_t brightdepth = beatsin88( 341, 96, 254);
uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
uint8_t msmultiplier = beatsin88(147, 23, 60);
uint16_t hue16 = color256;
uint16_t ms = millis();
uint16_t deltams = ms - sLastMillis ;
sLastMillis = ms;
sPseudotime += deltams * msmultiplier;
uint16_t brightnesstheta16 = sPseudotime;
for( uint16_t i = 0 ; i < NUM_LEDS; i++) {
uint8_t hue8 = hue16 / 256;
brightnesstheta16 += brightnessthetainc16;
uint16_t b16 = sin16( brightnesstheta16 ) + 32768;
uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
bri8 += (255 - brightdepth);
CRGB newcolor = CHSV( hue8, sat8, bri8);
uint16_t pixelnumber = i;
pixelnumber = (NUM_LEDS-1) - pixelnumber;
nblend( leds[pixelnumber], newcolor, 64);
}
}
| 4,998 | 2,213 |
/*=========================================================================
Program: ParaView
Module: pqImportCinemaReaction.cxx
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========================================================================*/
#include "pqImportCinemaReaction.h"
#include "vtkPVConfig.h"
#include "pqActiveObjects.h"
#include "pqCoreUtilities.h"
#include "pqFileDialog.h"
#include "pqServer.h"
#include "pqStandardRecentlyUsedResourceLoaderImplementation.h"
#include "pqUndoStack.h"
#include "pqView.h"
#include "vtkNew.h"
#if defined(VTKGL2) && defined(PARAVIEW_ENABLE_PYTHON)
#include "vtkSMCinemaDatabaseImporter.h"
#endif
#include <sstream>
//-----------------------------------------------------------------------------
pqImportCinemaReaction::pqImportCinemaReaction(QAction* parentObject)
: Superclass(parentObject)
{
pqActiveObjects* activeObjects = &pqActiveObjects::instance();
QObject::connect(
activeObjects, SIGNAL(serverChanged(pqServer*)), this, SLOT(updateEnableState()));
this->updateEnableState();
}
//-----------------------------------------------------------------------------
pqImportCinemaReaction::~pqImportCinemaReaction()
{
}
//-----------------------------------------------------------------------------
void pqImportCinemaReaction::updateEnableState()
{
#if defined(VTKGL2) && defined(PARAVIEW_ENABLE_PYTHON)
bool enable_state = false;
pqActiveObjects& activeObjects = pqActiveObjects::instance();
vtkSMSession* session =
activeObjects.activeServer() ? activeObjects.activeServer()->session() : NULL;
if (session)
{
vtkNew<vtkSMCinemaDatabaseImporter> importer;
enable_state = importer->SupportsCinema(session);
}
this->parentAction()->setEnabled(enable_state);
#else
this->parentAction()->setEnabled(true);
#endif
}
//-----------------------------------------------------------------------------
bool pqImportCinemaReaction::loadCinemaDatabase()
{
#if !defined(VTKGL2)
pqCoreUtilities::promptUser("pqImportCinemaReaction::NoOpenGL2", QMessageBox::Critical,
tr("Incompatible rendering backend"),
tr("'OpenGL2' rendering backend is required to load a Cinema database, "
"but is not available in this build."),
QMessageBox::Ok | QMessageBox::Save);
return false;
#elif !defined(PARAVIEW_ENABLE_PYTHON)
pqCoreUtilities::promptUser("pqImportCinemaReaction::NoPython", QMessageBox::Critical,
tr("Python support not enabled"), tr("Python support is required to load a Cinema database, "
"but is not available in this build."),
QMessageBox::Ok | QMessageBox::Save);
return false;
#else
pqServer* server = pqActiveObjects::instance().activeServer();
pqFileDialog fileDialog(server, pqCoreUtilities::mainWidget(), tr("Open Cinema Database:"),
QString(), "Cinema Database Files (info.json);;All files(*)");
fileDialog.setObjectName("FileOpenDialog");
fileDialog.setFileMode(pqFileDialog::ExistingFiles);
if (fileDialog.exec() == QDialog::Accepted)
{
return pqImportCinemaReaction::loadCinemaDatabase(fileDialog.getSelectedFiles(0)[0]);
}
return false;
#endif
}
//-----------------------------------------------------------------------------
bool pqImportCinemaReaction::loadCinemaDatabase(const QString& dbase, pqServer* server)
{
#if defined(VTKGL2) && defined(PARAVIEW_ENABLE_PYTHON)
CLEAR_UNDO_STACK();
server = (server != NULL) ? server : pqActiveObjects::instance().activeServer();
pqView* view = pqActiveObjects::instance().activeView();
vtkNew<vtkSMCinemaDatabaseImporter> importer;
if (!importer->ImportCinema(
dbase.toLatin1().data(), server->session(), (view ? view->getViewProxy() : NULL)))
{
qCritical("Failed to import Cinema database.");
return false;
}
pqStandardRecentlyUsedResourceLoaderImplementation::addCinemaDatabaseToRecentResources(
server, dbase);
if (view)
{
view->render();
}
CLEAR_UNDO_STACK();
return true;
#else
(void)dbase;
(void)server;
return false;
#endif
}
| 5,152 | 1,706 |
/* ============================================================
* QupZilla - Qt web browser
* Copyright (C) 2016-2017 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "webscrollbarmanager.h"
#include "webscrollbar.h"
#include "webview.h"
#include "webpage.h"
#include "mainapplication.h"
#include "scripts.h"
#include "settings.h"
#include <QPointer>
#include <QPaintEvent>
#include <QWebEngineProfile>
#include <QWebEngineScriptCollection>
#include <QStyle>
#include <QStyleOption>
Q_GLOBAL_STATIC(WebScrollBarManager, qz_web_scrollbar_manager)
class WebScrollBarCornerWidget : public QWidget
{
public:
explicit WebScrollBarCornerWidget(WebView *view)
: QWidget()
, m_view(view)
{
setAutoFillBackground(true);
}
void updateVisibility(bool visible, int thickness)
{
if (visible) {
setParent(m_view->overlayWidget());
resize(thickness, thickness);
move(m_view->width() - width(), m_view->height() - height());
show();
} else {
hide();
}
}
private:
void paintEvent(QPaintEvent *ev) override
{
Q_UNUSED(ev)
QStyleOption option;
option.initFrom(this);
option.rect = rect();
QPainter p(this);
if (mApp->styleName() == QL1S("breeze")) {
p.fillRect(ev->rect(), option.palette.background());
} else {
style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
}
}
WebView *m_view;
};
struct ScrollBarData {
~ScrollBarData() {
delete vscrollbar;
delete hscrollbar;
delete corner;
}
WebScrollBar *vscrollbar;
WebScrollBar *hscrollbar;
bool vscrollbarVisible = false;
bool hscrollbarVisible = false;
WebScrollBarCornerWidget *corner;
};
WebScrollBarManager::WebScrollBarManager(QObject *parent)
: QObject(parent)
{
m_scrollbarJs = QL1S("(function() {"
"var head = document.getElementsByTagName('head')[0];"
"if (!head) return;"
"var css = document.createElement('style');"
"css.setAttribute('type', 'text/css');"
"var size = %1 / window.devicePixelRatio + 'px';"
"css.appendChild(document.createTextNode('"
" body::-webkit-scrollbar{width:'+size+';height:'+size+';}"
"'));"
"head.appendChild(css);"
"})()");
loadSettings();
}
void WebScrollBarManager::loadSettings()
{
m_enabled = Settings().value(QSL("Web-Browser-Settings/UseNativeScrollbars"), false).toBool();
if (!m_enabled) {
for (WebView *view : m_scrollbars.keys()) {
removeWebView(view);
}
}
}
void WebScrollBarManager::addWebView(WebView *view)
{
if (!m_enabled) {
return;
}
delete m_scrollbars.value(view);
ScrollBarData *data = new ScrollBarData;
data->vscrollbar = new WebScrollBar(Qt::Vertical, view);
data->hscrollbar = new WebScrollBar(Qt::Horizontal, view);
data->corner = new WebScrollBarCornerWidget(view);
m_scrollbars[view] = data;
const int thickness = data->vscrollbar->thickness();
auto updateValues = [=]() {
const QSize viewport = viewportSize(view, thickness);
data->vscrollbar->updateValues(viewport);
data->vscrollbar->setVisible(data->vscrollbarVisible);
data->hscrollbar->updateValues(viewport);
data->hscrollbar->setVisible(data->hscrollbarVisible);
data->corner->updateVisibility(data->vscrollbarVisible && data->hscrollbarVisible, thickness);
};
connect(view, &WebView::viewportResized, data->vscrollbar, updateValues);
connect(view->page(), &WebPage::scrollPositionChanged, data->vscrollbar, updateValues);
connect(view->page(), &WebPage::contentsSizeChanged, data->vscrollbar, [=]() {
const QString source = QL1S("var out = {"
"vertical: document.documentElement && window.innerWidth > document.documentElement.clientWidth,"
"horizontal: document.documentElement && window.innerHeight > document.documentElement.clientHeight"
"};out;");
QPointer<WebView> p(view);
view->page()->runJavaScript(source, WebPage::SafeJsWorld, [=](const QVariant &res) {
if (!p || !m_scrollbars.contains(view)) {
return;
}
const QVariantMap map = res.toMap();
data->vscrollbarVisible = map.value(QSL("vertical")).toBool();
data->hscrollbarVisible = map.value(QSL("horizontal")).toBool();
updateValues();
});
});
connect(view, &WebView::zoomLevelChanged, data->vscrollbar, [=]() {
view->page()->runJavaScript(m_scrollbarJs.arg(thickness));
});
if (m_scrollbars.size() == 1) {
createUserScript(thickness);
}
}
void WebScrollBarManager::removeWebView(WebView *view)
{
if (!m_scrollbars.contains(view)) {
return;
}
if (m_scrollbars.size() == 1) {
removeUserScript();
}
delete m_scrollbars.take(view);
}
QScrollBar *WebScrollBarManager::scrollBar(Qt::Orientation orientation, WebView *view) const
{
ScrollBarData *d = m_scrollbars.value(view);
if (!d) {
return nullptr;
}
return orientation == Qt::Vertical ? d->vscrollbar : d->hscrollbar;
}
WebScrollBarManager *WebScrollBarManager::instance()
{
return qz_web_scrollbar_manager();
}
void WebScrollBarManager::createUserScript(int thickness)
{
QWebEngineScript script;
script.setName(QSL("_qupzilla_scrollbar"));
script.setInjectionPoint(QWebEngineScript::DocumentReady);
script.setWorldId(WebPage::SafeJsWorld);
script.setSourceCode(m_scrollbarJs.arg(thickness));
mApp->webProfile()->scripts()->insert(script);
}
void WebScrollBarManager::removeUserScript()
{
QWebEngineScript script = mApp->webProfile()->scripts()->findScript(QSL("_qupzilla_scrollbar"));
mApp->webProfile()->scripts()->remove(script);
}
QSize WebScrollBarManager::viewportSize(WebView *view, int thickness) const
{
QSize viewport = view->size();
thickness /= view->devicePixelRatioF();
ScrollBarData *data = m_scrollbars.value(view);
Q_ASSERT(data);
if (data->vscrollbarVisible) {
viewport.setWidth(viewport.width() - thickness);
}
if (data->hscrollbarVisible) {
viewport.setHeight(viewport.height() - thickness);
}
#if 0
const QSize content = view->page()->contentsSize().toSize();
// Check both axis
if (content.width() - viewport.width() > 0) {
viewport.setHeight(viewport.height() - thickness);
}
if (content.height() - viewport.height() > 0) {
viewport.setWidth(viewport.width() - thickness);
}
// Check again against adjusted size
if (viewport.height() == view->height() && content.width() - viewport.width() > 0) {
viewport.setHeight(viewport.height() - thickness);
}
if (viewport.width() == view->width() && content.height() - viewport.height() > 0) {
viewport.setWidth(viewport.width() - thickness);
}
#endif
return viewport;
}
| 8,050 | 2,430 |
#include "font.hpp"
namespace grower::ui::text {
LOGGER_IMPL(font);
void font::add_font(const std::string &file_name) {
if(!FcConfigAppFontAddFile(FcConfigGetCurrent(), (FcChar8 *) file_name.c_str())) {
log->warn("Error adding font: {}", file_name);
}
}
void font::load_default_fonts() {
std::string fonts[]{
"TitilliumWeb-Black.ttf",
"TitilliumWeb-Bold.ttf",
"TitilliumWeb-BoldItalic.ttf",
"TitilliumWeb-ExtraLight.ttf",
"TitilliumWeb-ExtraLightItalic.ttf",
"TitilliumWeb-Italic.ttf",
"TitilliumWeb-Light.ttf",
"TitilliumWeb-LightItalic.ttf",
"TitilliumWeb-Regular.ttf",
"TitilliumWeb-SemiBold.ttf",
"TitilliumWeb-SemiBoldItalic.ttf",
"Font Awesome 5 Free-Solid-900.otf"
};
for(const auto& font : fonts) {
log->info("Adding font: {}", font);
add_font(fmt::format("resources/{}", font));
}
}
} | 1,021 | 372 |
/*
Part of Catfish
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/
#include "subsetsum.h"
#include "config.h"
#include <cstdio>
#include <cmath>
#include <climits>
#include <algorithm>
#include <cassert>
subsetsum::subsetsum(const vector<PI> &s, const vector<PI> &t)
: source(s), target(t)
{
eqns.clear();
}
int subsetsum::solve()
{
init();
fill();
optimize();
return 0;
}
int subsetsum::init()
{
sort(source.begin(), source.end());
sort(target.begin(), target.end());
ubound = target[target.size() - 1].first;
table1.resize(source.size() + 1);
table2.resize(source.size() + 1);
for(int i = 0; i < table1.size(); i++)
{
table1[i].assign(ubound + 1, false);
table2[i].assign(ubound + 1, -1);
}
for(int i = 0; i <= source.size(); i++)
{
table1[i][0] = false;
table2[i][0] = 0;
}
for(int j = 1; j <= ubound; j++)
{
table1[0][j] = false;
table2[0][j] = -1;
}
return 0;
}
int subsetsum::fill()
{
for(int j = 1; j <= ubound; j++)
{
for(int i = 1; i <= source.size(); i++)
{
int s = source[i - 1].first;
if(j >= s && table2[i - 1][j - s] >= 0)
{
table1[i][j] = true;
table2[i][j] = i;
}
if(table2[i - 1][j] >= 0)
{
table2[i][j] = table2[i - 1][j];
}
}
}
return 0;
}
int subsetsum::optimize()
{
eqns.clear();
for(int i = 0; i < target.size(); i++)
{
equation eqn(0);
backtrace(i, eqn);
if(eqn.s.size() == 0) continue;
eqns.push_back(eqn);
}
return 0;
}
int subsetsum::backtrace(int ti, equation &eqn)
{
int t = target[ti].first;
int n = source.size();
if(table2[n][t] == -1) return 0;
eqn.s.push_back(target[ti].second);
int x = t;
int s = table2[n][t];
while(x >= 1 && s >= 1)
{
assert(table2[s][x] >= 0);
eqn.t.push_back(source[s - 1].second);
x -= source[s - 1].first;
s = table2[s - 1][x];
}
return 0;
}
int subsetsum::print()
{
printf("table 1\n");
printf(" ");
for(int i = 0; i < table1[0].size(); i++) printf("%3d", i);
printf("\n");
for(int i = 0; i < table1.size(); i++)
{
printf("%3d", i);
for(int j = 0; j < table1[i].size(); j++)
{
printf("%3d", table1[i][j] ? 1 : 0);
}
printf("\n");
}
printf("table 2\n");
printf(" ");
for(int i = 0; i < table2[0].size(); i++) printf("%3d", i);
printf("\n");
for(int i = 0; i < table2.size(); i++)
{
printf("%3d", i);
for(int j = 0; j < table2[i].size(); j++)
{
printf("%3d", table2[i][j]);
}
printf("\n");
}
for(int i = 0; i < eqns.size(); i++)
{
eqns[i].print(i);
}
return 0;
}
int subsetsum::test()
{
vector<PI> v;
v.push_back(PI(5, 1));
v.push_back(PI(6, 2));
v.push_back(PI(8, 3));
v.push_back(PI(3, 5));
v.push_back(PI(10,8));
vector<PI> t;
t.push_back(PI(20, 2));
t.push_back(PI(8, 4));
t.push_back(PI(11, 5));
t.push_back(PI(18, 3));
t.push_back(PI(10, 1));
subsetsum sss(v, t);
sss.solve();
sss.print();
return 0;
}
| 2,921 | 1,491 |
#include "scanner.hpp"
#include <cctype>
#include <algorithm>
#include <array>
#include <iterator>
#include <utility>
#include <boost/lexical_cast.hpp>
using std::isalnum;
using std::isalpha;
using std::isdigit;
using std::array;
using std::back_inserter;
using std::copy_if;
using std::find_if;
using std::move;
using std::pair;
using std::string;
using std::to_string;
using boost::lexical_cast;
// Allow the internal linkage section to access names
using namespace motts::lox;
// Not exported (internal linkage)
namespace {
const array<pair<const char*, Token_type>, 18> reserved_words {{
{"and", Token_type::and_},
{"class", Token_type::class_},
{"else", Token_type::else_},
{"false", Token_type::false_},
{"for", Token_type::for_},
{"fun", Token_type::fun_},
{"if", Token_type::if_},
{"nil", Token_type::nil_},
{"or", Token_type::or_},
{"print", Token_type::print_},
{"return", Token_type::return_},
{"super", Token_type::super_},
{"this", Token_type::this_},
{"true", Token_type::true_},
{"var", Token_type::var_},
{"while", Token_type::while_},
{"break", Token_type::break_},
{"continue", Token_type::continue_}
}};
}
// Exported (external linkage)
namespace motts { namespace lox {
Token_iterator::Token_iterator(const string& source) :
source_ {&source},
token_begin_ {source_->cbegin()},
token_end_ {source_->cbegin()},
token_ {consume_token()}
{}
Token_iterator::Token_iterator() = default;
Token_iterator& Token_iterator::operator++() {
if (token_begin_ != source_->end()) {
// We are at the beginning of the next lexeme
token_begin_ = token_end_;
token_ = consume_token();
} else {
source_ = nullptr;
}
return *this;
}
Token_iterator Token_iterator::operator++(int) {
Token_iterator copy {*this};
operator++();
return copy;
}
bool Token_iterator::operator==(const Token_iterator& rhs) const {
return (
(!source_ && !rhs.source_) ||
(source_ == rhs.source_ && token_begin_ == rhs.token_begin_)
);
}
bool Token_iterator::operator!=(const Token_iterator& rhs) const {
return !(*this == rhs);
}
const Token& Token_iterator::operator*() const & {
return token_;
}
Token&& Token_iterator::operator*() && {
return move(token_);
}
const Token* Token_iterator::operator->() const {
return &token_;
}
Token Token_iterator::make_token(Token_type token_type) {
return Token{token_type, string{token_begin_, token_end_}, {}, line_};
}
Token Token_iterator::make_token(Token_type token_type, Literal&& literal_value) {
return Token{token_type, string{token_begin_, token_end_}, move(literal_value), line_};
}
bool Token_iterator::advance_if_match(char expected) {
if (token_end_ != source_->end() && *token_end_ == expected) {
++token_end_;
return true;
}
return false;
}
Token Token_iterator::consume_string() {
while (token_end_ != source_->end() && *token_end_ != '"') {
if (*token_end_ == '\n') {
++line_;
}
++token_end_;
}
// Check unterminated string
if (token_end_ == source_->end()) {
throw Scanner_error{"Unterminated string.", line_};
}
// The closing "
++token_end_;
// Trim surrounding quotes and normalize line endings for literal value
string literal_value;
copy_if(token_begin_ + 1, token_end_ - 1, back_inserter(literal_value), [] (auto c) {
return c != '\r';
});
return make_token(Token_type::string, Literal{move(literal_value)});
}
Token Token_iterator::consume_number() {
while (token_end_ != source_->end() && isdigit(*token_end_)) {
++token_end_;
}
// Look for a fractional part
if (
token_end_ != source_->end() && *token_end_ == '.' &&
(token_end_ + 1) != source_->end() && isdigit(*(token_end_ + 1))
) {
// Consume the "." and one digit
token_end_ += 2;
while (token_end_ != source_->end() && isdigit(*token_end_)) {
++token_end_;
}
}
return make_token(Token_type::number, Literal{lexical_cast<double>(string{token_begin_, token_end_})});
}
Token Token_iterator::consume_identifier() {
while (token_end_ != source_->end() && (isalnum(*token_end_) || *token_end_ == '_')) {
++token_end_;
}
const string identifier {token_begin_, token_end_};
const auto found = find_if(reserved_words.cbegin(), reserved_words.cend(), [&] (const auto& pair) {
return pair.first == identifier;
});
return make_token(found != reserved_words.cend() ? found->second : Token_type::identifier);
}
Token Token_iterator::consume_token() {
// Loop because we might skip some tokens
for (; token_end_ != source_->end(); token_begin_ = token_end_) {
auto c = *token_end_;
++token_end_;
switch (c) {
// Single char tokens
case '(': return make_token(Token_type::left_paren);
case ')': return make_token(Token_type::right_paren);
case '{': return make_token(Token_type::left_brace);
case '}': return make_token(Token_type::right_brace);
case ',': return make_token(Token_type::comma);
case '.': return make_token(Token_type::dot);
case '-': return make_token(Token_type::minus);
case '+': return make_token(Token_type::plus);
case ';': return make_token(Token_type::semicolon);
case '*': return make_token(Token_type::star);
// One or two char tokens
case '/':
if (advance_if_match('/')) {
// A comment goes until the end of the line
while (token_end_ != source_->end() && *token_end_ != '\n') {
++token_end_;
}
continue;
} else {
return make_token(Token_type::slash);
}
case '!':
return make_token(advance_if_match('=') ? Token_type::bang_equal : Token_type::bang);
case '=':
return make_token(advance_if_match('=') ? Token_type::equal_equal : Token_type::equal);
case '>':
return make_token(advance_if_match('=') ? Token_type::greater_equal : Token_type::greater);
case '<':
return make_token(advance_if_match('=') ? Token_type::less_equal : Token_type::less);
// Whitespace
case '\n':
++line_;
continue;
case ' ':
case '\r':
case '\t':
continue;
// Literals and Keywords
case '"': return consume_string();
default:
if (isdigit(c)) {
return consume_number();
} else if (isalpha(c) || c == '_') {
return consume_identifier();
} else {
throw Scanner_error{"Unexpected character.", line_};
}
}
}
// The final token is always EOF
return Token{Token_type::eof, "", {}, line_};
}
Scanner_error::Scanner_error(const string& what, int line) :
Runtime_error {"[Line " + to_string(line) + "] Error: " + what}
{}
}}
| 8,100 | 2,353 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2022 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx library is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#ifndef NDN_CXX_ENCODING_ESTIMATOR_HPP
#define NDN_CXX_ENCODING_ESTIMATOR_HPP
#include "ndn-cxx/encoding/block.hpp"
namespace ndn {
namespace encoding {
/**
* @brief Helper class to estimate size of TLV encoding.
*
* The interface of this class (mostly) matches that of the Encoder class.
*
* @sa Encoder
*/
class Estimator : noncopyable
{
public: // common interface between Encoder and Estimator
/**
* @brief Prepend a sequence of bytes
*/
constexpr size_t
prependBytes(span<const uint8_t> bytes) const noexcept
{
return bytes.size();
}
/**
* @brief Append a sequence of bytes
*/
constexpr size_t
appendBytes(span<const uint8_t> bytes) const noexcept
{
return bytes.size();
}
/**
* @brief Prepend a single byte
* @deprecated
*/
[[deprecated("use prependBytes()")]]
constexpr size_t
prependByte(uint8_t) const noexcept
{
return 1;
}
/**
* @brief Append a single byte
* @deprecated
*/
[[deprecated("use appendBytes()")]]
constexpr size_t
appendByte(uint8_t) const noexcept
{
return 1;
}
/**
* @brief Prepend a byte array @p array of length @p length
* @deprecated
*/
[[deprecated("use prependBytes()")]]
constexpr size_t
prependByteArray(const uint8_t*, size_t length) const noexcept
{
return length;
}
/**
* @brief Append a byte array @p array of length @p length
* @deprecated
*/
[[deprecated("use appendBytes()")]]
constexpr size_t
appendByteArray(const uint8_t*, size_t length) const noexcept
{
return length;
}
/**
* @brief Prepend bytes from the range [@p first, @p last)
*/
template<class Iterator>
constexpr size_t
prependRange(Iterator first, Iterator last) const noexcept
{
return std::distance(first, last);
}
/**
* @brief Append bytes from the range [@p first, @p last)
*/
template<class Iterator>
constexpr size_t
appendRange(Iterator first, Iterator last) const noexcept
{
return std::distance(first, last);
}
/**
* @brief Prepend @p n in VarNumber encoding
*/
constexpr size_t
prependVarNumber(uint64_t n) const noexcept
{
return tlv::sizeOfVarNumber(n);
}
/**
* @brief Append @p n in VarNumber encoding
*/
constexpr size_t
appendVarNumber(uint64_t n) const noexcept
{
return tlv::sizeOfVarNumber(n);
}
/**
* @brief Prepend @p n in NonNegativeInteger encoding
*/
constexpr size_t
prependNonNegativeInteger(uint64_t n) const noexcept
{
return tlv::sizeOfNonNegativeInteger(n);
}
/**
* @brief Append @p n in NonNegativeInteger encoding
*/
constexpr size_t
appendNonNegativeInteger(uint64_t n) const noexcept
{
return tlv::sizeOfNonNegativeInteger(n);
}
/**
* @brief Prepend TLV block of type @p type and value from buffer @p array of size @p arraySize
* @deprecated
*/
[[deprecated("use encoding::prependBinaryBlock()")]]
constexpr size_t
prependByteArrayBlock(uint32_t type, const uint8_t* array, size_t arraySize) const noexcept
{
return tlv::sizeOfVarNumber(type) + tlv::sizeOfVarNumber(arraySize) + arraySize;
}
/**
* @brief Append TLV block of type @p type and value from buffer @p array of size @p arraySize
* @deprecated
*/
[[deprecated]]
constexpr size_t
appendByteArrayBlock(uint32_t type, const uint8_t* array, size_t arraySize) const noexcept
{
return tlv::sizeOfVarNumber(type) + tlv::sizeOfVarNumber(arraySize) + arraySize;
}
/**
* @brief Prepend TLV block @p block
* @deprecated
*/
[[deprecated("use encoding::prependBlock()")]]
size_t
prependBlock(const Block& block) const;
/**
* @brief Append TLV block @p block
* @deprecated
*/
[[deprecated]]
size_t
appendBlock(const Block& block) const;
};
} // namespace encoding
} // namespace ndn
#endif // NDN_CXX_ENCODING_ESTIMATOR_HPP
| 4,915 | 1,750 |
//===----------------------------------------------------------------------===//
//
// Peloton
//
// gc_delete_test_coop.cpp
//
// Identification: tests/executor/gc_delete_test_coop.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <atomic>
#include "harness.h"
#include "backend/catalog/schema.h"
#include "backend/common/value_factory.h"
#include "backend/common/types.h"
#include "backend/common/pool.h"
#include "backend/executor/executor_context.h"
#include "backend/executor/delete_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/executor/seq_scan_executor.h"
#include "backend/executor/update_executor.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/table_factory.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "executor/executor_tests_util.h"
#include "executor/mock_executor.h"
#include "backend/planner/delete_plan.h"
#include "backend/planner/insert_plan.h"
#include "backend/planner/seq_scan_plan.h"
#include "backend/planner/update_plan.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// GC Tests
//===--------------------------------------------------------------------===//
class GCDeleteTestCoop : public PelotonTest {};
std::atomic<int> tuple_id;
std::atomic<int> delete_tuple_id;
enum GCType type = GC_TYPE_COOPERATIVE;
void InsertTuple(storage::DataTable *table, VarlenPool *pool) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
for (oid_t tuple_itr = 0; tuple_itr < 10; tuple_itr++) {
auto tuple = ExecutorTestsUtil::GetTuple(table, ++tuple_id, pool);
planner::InsertPlan node(table, std::move(tuple));
executor::InsertExecutor executor(&node, context.get());
executor.Execute();
}
txn_manager.CommitTransaction();
}
void DeleteTuple(storage::DataTable *table) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
std::vector<storage::Tuple *> tuples;
// Delete
planner::DeletePlan delete_node(table, false);
executor::DeleteExecutor delete_executor(&delete_node, context.get());
// Predicate
// WHERE ATTR_0 > 60
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(VALUE_TYPE_INTEGER, 0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(60));
auto predicate = new expression::ComparisonExpression<expression::CmpGt>(
EXPRESSION_TYPE_COMPARE_GREATERTHAN, tup_val_exp, const_val_exp);
// Seq scan
std::vector<oid_t> column_ids = {0};
std::unique_ptr<planner::SeqScanPlan> seq_scan_node(
new planner::SeqScanPlan(table, predicate, column_ids));
executor::SeqScanExecutor seq_scan_executor(seq_scan_node.get(),
context.get());
// Parent-Child relationship
delete_node.AddChild(std::move(seq_scan_node));
delete_executor.AddChild(&seq_scan_executor);
EXPECT_TRUE(delete_executor.Init());
EXPECT_TRUE(delete_executor.Execute());
// EXPECT_TRUE(delete_executor.Execute());
txn_manager.CommitTransaction();
}
TEST_F(GCDeleteTestCoop, DeleteTest) {
peloton::gc::GCManagerFactory::Configure(type);
peloton::gc::GCManagerFactory::GetInstance().StartGC();
auto *table = ExecutorTestsUtil::CreateTable(1024);
auto &manager = catalog::Manager::GetInstance();
storage::Database db(DEFAULT_DB_ID);
manager.AddDatabase(&db);
db.AddTable(table);
// We are going to insert a tile group into a table in this test
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
auto before_insert = catalog::Manager::GetInstance().GetMemoryFootprint();
LaunchParallelTest(1, InsertTuple, table, testing_pool);
auto after_insert = catalog::Manager::GetInstance().GetMemoryFootprint();
EXPECT_GT(after_insert, before_insert);
LaunchParallelTest(1, DeleteTuple, table);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
LOG_INFO("new transaction");
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, nullptr, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
EXPECT_TRUE(seq_scan_executor.Init());
auto tuple_cnt = 0;
while (seq_scan_executor.Execute()) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
seq_scan_executor.GetOutput());
tuple_cnt += result_logical_tile->GetTupleCount();
}
txn_manager.CommitTransaction();
EXPECT_EQ(tuple_cnt, 6);
auto after_delete = catalog::Manager::GetInstance().GetMemoryFootprint();
EXPECT_EQ(after_insert, after_delete);
tuple_id = 0;
}
} // namespace test
} // namespace peloton
| 5,788 | 1,857 |
//============================================================================
//
// SSSS tt lll lll
// SS SS tt ll ll
// SS tttttt eeee ll ll aaaa
// SSSS tt ee ee ll ll aa
// SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator"
// SS SS tt ee ll ll aa aa
// SSSS ttt eeeee llll llll aaaaa
//
// Copyright (c) 1995-2014 by Bradford W. Mott, Stephen Anthony
// and the Stella Team
//
// See the file "License.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: PackedBitArray.cxx 2838 2014-01-17 23:34:03Z stephena $
//============================================================================
#include "bspf.hxx"
#include "PackedBitArray.hxx"
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PackedBitArray::PackedBitArray(uInt32 length)
: words(length / wordSize + 1)
{
bits = new uInt32[ words ];
for(uInt32 i = 0; i < words; ++i)
bits[i] = 0;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PackedBitArray::~PackedBitArray()
{
delete[] bits;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt32 PackedBitArray::isSet(uInt32 bit) const
{
uInt32 word = bit / wordSize;
bit %= wordSize;
return (bits[word] & (1 << bit));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt32 PackedBitArray::isClear(uInt32 bit) const
{
uInt32 word = bit / wordSize;
bit %= wordSize;
return !(bits[word] & (1 << bit));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void PackedBitArray::toggle(uInt32 bit)
{
uInt32 word = bit / wordSize;
bit %= wordSize;
bits[word] ^= (1 << bit);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void PackedBitArray::set(uInt32 bit)
{
uInt32 word = bit / wordSize;
bit %= wordSize;
bits[word] |= (1 << bit);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void PackedBitArray::clear(uInt32 bit)
{
uInt32 word = bit / wordSize;
bit %= wordSize;
bits[word] &= (~(1 << bit));
}
| 2,264 | 987 |
#pragma once
#include "Input.hpp"
#include <switch.h>
#include "SDL2/SDL.h"
#include <vector>
#include <functional>
class GameObject
{
public:
GameObject(int, int, int, int);
void SetAction(std::function<void()>);
void Press() { if (_onPress != nullptr) _onPress(); };
bool Hovered(TouchInfo*);
void Move(int, int);
virtual ~GameObject() {};
protected:
SDL_Rect* _rect;
private:
std::function<void()> _onPress;
}; | 493 | 167 |
#include "Animation_RuntimeGraphNode_Ragdoll.h"
#include "Engine/Animation/TaskSystem/Tasks/Animation_Task_Ragdoll.h"
#include "Engine/Animation/TaskSystem/Tasks/Animation_Task_DefaultPose.h"
#include "Engine/Physics/PhysicsRagdoll.h"
#include "Engine/Physics/PhysicsScene.h"
#include "System/Core/Logging/Log.h"
//-------------------------------------------------------------------------
namespace KRG::Animation::GraphNodes
{
void PoweredRagdollNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const
{
auto pNode = CreateNode<PoweredRagdollNode>( nodePtrs, options );
SetOptionalNodePtrFromIndex( nodePtrs, m_physicsBlendWeightNodeIdx, pNode->m_pBlendWeightValueNode );
PassthroughNode::Settings::InstantiateNode( nodePtrs, pDataSet, GraphNode::Settings::InitOptions::OnlySetPointers );
pNode->m_pRagdollDefinition = pDataSet->GetResource<Physics::RagdollDefinition>( m_dataSlotIdx );
}
bool PoweredRagdollNode::IsValid() const
{
return PassthroughNode::IsValid() && m_pRagdollDefinition != nullptr && m_pRagdoll != nullptr;
}
void PoweredRagdollNode::InitializeInternal( GraphContext& context, SyncTrackTime const& initialTime )
{
KRG_ASSERT( context.IsValid() );
PassthroughNode::InitializeInternal( context, initialTime );
// Create ragdoll
if ( m_pRagdollDefinition != nullptr && context.m_pPhysicsScene != nullptr )
{
auto pNodeSettings = GetSettings<PoweredRagdollNode>();
m_pRagdoll = context.m_pPhysicsScene->CreateRagdoll( m_pRagdollDefinition, pNodeSettings->m_profileID, context.m_graphUserID );
m_pRagdoll->SetPoseFollowingEnabled( true );
m_pRagdoll->SetGravityEnabled( pNodeSettings->m_isGravityEnabled );
}
//-------------------------------------------------------------------------
if ( m_pBlendWeightValueNode != nullptr )
{
m_pBlendWeightValueNode->Initialize( context );
}
m_isFirstUpdate = true;
}
void PoweredRagdollNode::ShutdownInternal( GraphContext& context )
{
KRG_ASSERT( context.IsValid() );
if ( m_pBlendWeightValueNode != nullptr )
{
m_pBlendWeightValueNode->Shutdown( context );
}
//-------------------------------------------------------------------------
// Destroy the ragdoll
if ( m_pRagdoll != nullptr )
{
m_pRagdoll->RemoveFromScene();
KRG::Delete( m_pRagdoll );
}
PassthroughNode::ShutdownInternal( context );
}
GraphPoseNodeResult PoweredRagdollNode::Update( GraphContext& context )
{
GraphPoseNodeResult result;
if ( IsValid() )
{
result = PassthroughNode::Update( context );
result = RegisterRagdollTasks( context, result );
}
else
{
result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::DefaultPoseTask>( GetNodeIndex(), Pose::InitialState::ReferencePose );
}
return result;
}
GraphPoseNodeResult PoweredRagdollNode::Update( GraphContext& context, SyncTrackTimeRange const& updateRange )
{
GraphPoseNodeResult result;
if ( IsValid() )
{
result = PassthroughNode::Update( context, updateRange );
result = RegisterRagdollTasks( context, result );
}
else
{
result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::DefaultPoseTask>( GetNodeIndex(), Pose::InitialState::ReferencePose );
}
return result;
}
GraphPoseNodeResult PoweredRagdollNode::RegisterRagdollTasks( GraphContext& context, GraphPoseNodeResult const& childResult )
{
KRG_ASSERT( IsValid() );
GraphPoseNodeResult result = childResult;
//-------------------------------------------------------------------------
Tasks::RagdollSetPoseTask::InitOption const initOptions = m_isFirstUpdate ? Tasks::RagdollSetPoseTask::InitializeBodies : Tasks::RagdollSetPoseTask::DoNothing;
TaskIndex const setPoseTaskIdx = context.m_pTaskSystem->RegisterTask<Tasks::RagdollSetPoseTask>( m_pRagdoll, GetNodeIndex(), childResult.m_taskIdx, initOptions );
m_isFirstUpdate = false;
//-------------------------------------------------------------------------
float const physicsWeight = ( m_pBlendWeightValueNode != nullptr ) ? m_pBlendWeightValueNode->GetValue<float>( context ) : GetSettings<PoweredRagdollNode>()->m_physicsBlendWeight;
result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::RagdollGetPoseTask>( m_pRagdoll, GetNodeIndex(), setPoseTaskIdx, physicsWeight );
return result;
}
} | 4,870 | 1,458 |
// clang-format disabled because clang-format doesn't format lest's macros correctly
// clang-format off
/*
Test cases for dkm.hpp
This is just simple test harness without any external dependencies.
*/
#include "../../include/dkm.hpp"
#include "../../include/dkm_utils.hpp"
#include "lest.hpp"
#include <vector>
#include <array>
#include <cstdint>
#include <algorithm>
#include <tuple>
#ifdef __clang__
#pragma clang diagnostic ignored "-Wmissing-braces"
#endif
const lest::test specification[] = {
CASE("Small 2D dataset is successfully segmented into 3 clusters",) {
SETUP("Small 2D dataset") {
std::vector<std::array<float, 2>> data{{1.f, 1.f}, {2.f, 2.f}, {1200.f, 1200.f}, {2.f, 2.f}};
uint32_t k = 3;
SECTION("Distance squared calculated correctly") {
EXPECT(dkm::details::distance_squared(data[0], data[1]) == lest::approx(2.f));
EXPECT(dkm::details::distance_squared(data[1], data[2]) == lest::approx(2870408.f));
}
SECTION("Initial means picked correctly") {
auto means = dkm::details::random_plusplus(data, k);
EXPECT(means.size() == 3u);
// means are 4 values from the input data vector
uint32_t count = 0;
for (auto& m : means) {
for (auto& d : data) {
if (m == d) {
++count;
break;
}
}
}
EXPECT(count == 3u);
// means aren't all the same value
EXPECT((means[0] != means[1] || means[1] != means[2] || means[0] != means[2]));
}
SECTION("K-means calculated correctly via Lloyds method") {
auto means_clusters = dkm::kmeans_lloyd(data, 3);
auto means = std::get<0>(means_clusters);
auto clusters = std::get<1>(means_clusters);
// verify results
EXPECT(means.size() == 3u);
EXPECT(clusters.size() == data.size());
std::vector<std::array<float, 2>> expected_means{{1.f, 1.f}, {2.f, 2.f}, {1200.f, 1200.f}};
std::sort(means.begin(), means.end());
EXPECT(means == expected_means);
// Can't verify clusters easily because order may differ from run to run
// Sorting the means before assigning clusters would help, but would also slow the algorithm down
EXPECT(std::count(clusters.cbegin(), clusters.cend(), 0) > 0);
EXPECT(std::count(clusters.cbegin(), clusters.cend(), 1) > 0);
EXPECT(std::count(clusters.cbegin(), clusters.cend(), 2) > 0);
EXPECT(std::count(clusters.cbegin(), clusters.cend(), 3) == 0);
}
}
},
CASE("Test dkm::get_cluster",) {
SETUP() {
std::vector<std::array<double, 2>> points{
{0, 0},
{1, 1},
{2, 2},
{3, 3},
{4, 4},
{5, 5},
{6, 6},
{7, 7},
{8, 8},
{9, 9},
};
std::vector<uint32_t> labels{0, 2, 1, 1, 0, 2, 2, 1, 1, 0};
SECTION("Non-empty and same size points and labels") {
SECTION("Correct points for existing labels") {
auto cluster = dkm::get_cluster(points, labels, 0);
std::vector<std::array<double, 2>> res{
{0, 0},
{4, 4},
{9, 9}
};
EXPECT(cluster == res);
cluster = dkm::get_cluster(points, labels, 1);
res = {
{2, 2},
{3, 3},
{7, 7},
{8, 8}
};
EXPECT(cluster == res);
cluster = dkm::get_cluster(points, labels, 2);
res = {
{1, 1},
{5, 5},
{6, 6},
};
EXPECT(cluster == res);
}
SECTION("Empty set of points for non-existing labels") {
auto cluster = dkm::get_cluster(points, labels, 4);
std::vector<std::array<double, 2>> empty;
EXPECT(cluster == empty);
}
}
SECTION("Empty points and labels") {
std::vector<std::array<double, 2>> points;
std::vector<uint32_t> labels;
SECTION("Empty set of points") {
auto cluster = dkm::get_cluster(points, labels, 0);
std::vector<std::array<double, 2>> empty;
EXPECT(cluster == empty);
}
}
SECTION("points and labels sequences with different sizes") {
std::vector<std::array<double, 2>> points{
{0, 1},
{2, 3.5}
};
std::vector<uint32_t> labels{2, 4, 1, 1};
}
}
},
CASE("Test dkm::dist_to_center",) {
SETUP() {
std::vector<std::array<double, 2>> points{
{1, 5},
{2.2, 3},
{8, 12},
{11.4, 4.87},
{0.27, 50},
{1, 1}
};
std::array<double, 2> center{17.2, 24.5};
std::vector<double> res{25.3513, 26.2154, 15.5206, 20.4689, 30.6084, 28.5427};
SECTION("Non-empty sequence of points") {
std::vector<double> out = dkm::dist_to_center(points, center);
for (size_t i = 0; i < out.size(); ++i)
EXPECT(lest::approx(out[i]) == res[i]);
}
SECTION("Empty sequence of points returns an empty vector") {
std::vector<std::array<double, 2>> points;
std::array<double, 2> center{5, 4};
std::vector<double> empty;
std::vector<double> out = dkm::dist_to_center(points, center);
EXPECT(out == empty);
}
}
},
CASE("Test dkm::sum_dist",) {
SETUP() {
std::vector<std::array<double, 2>> points{
{1, 5},
{2.2, 3},
{8, 12},
{11.4, 4.87},
{0.27, 50},
{1, 1}
};
std::vector<double> out(points.size());
std::array<double, 2> center{17.2, 24.5};
std::vector<double> res{25.3513, 26.2154, 15.5206, 20.4689, 30.6084, 28.5427};
SECTION("Non-empty sequence of points") {
EXPECT(dkm::sum_dist(points, center) == lest::approx(146.7073));
}
SECTION("Empty sequence of points returns 0") {
std::vector<std::array<double, 2>> points;
std::array<double, 2> center{5, 4};
EXPECT(dkm::sum_dist(points, center) == 0);
}
}
},
CASE("Test dkm::means_inertia",) {
SETUP() {
std::vector<std::array<double, 2>> points{
{66.01742226, 48.70477854},
{62.30094932, 108.44049522},
{39.60740312, 12.07668535},
{35.57096194, -7.10722525},
{39.90890238, 61.89509695},
{27.5850295 , 85.50226002},
{51.14012591, 27.90650051},
{58.6414776 , 31.97020798},
{14.75127435, 69.36707669},
{73.66255253, 84.73455103},
{-1.31034384, 66.10406579},
{41.91865987, 56.5003107 },
{33.31116528, 45.92203855},
{57.12362692, 37.73753163},
{ 2.68915431, 51.35514789},
{39.76543196, -5.99499795},
{72.64312341, 61.43756623},
{30.97140948, 29.49960625},
{25.31232669, 35.88059477},
{57.67046396, 35.05019015}
};
std::vector<std::array<double, 2>> centroids{
{10, 10},
{20, 20},
{40, 30}
};
std::vector<uint32_t> labels{
0, 0, 1, 2, 2, 1, 1, 0, 0, 0,
1, 1, 2, 1, 0, 0, 1, 2, 1, 0
};
uint32_t k = 3;
SECTION("Non-empty set of points, fixed 3 clusters") {
std::tuple<std::vector<std::array<double, 2>>, std::vector<uint32_t>> means{centroids, labels};
double inertia = 0;
for (size_t i = 0; i < labels.size(); ++i) {
auto center = centroids[labels[i]];
auto point = points[i];
inertia += dkm::details::distance(point, center);
}
EXPECT(lest::approx(inertia) == dkm::means_inertia(points, means, k));
}
SECTION("Empty set of points should give 0 inertia") {
std::vector<std::array<double, 2>> points;
std::tuple<std::vector<std::array<double, 2>>, std::vector<uint32_t>> means;
EXPECT(dkm::means_inertia(points, means, k) == lest::approx(0));
}
SECTION() {
std::vector<std::array<double, 2>> data{
{1, 1},
{2, 2},
{1200, 1200},
{1000, 1000}
};
uint32_t k = 2;
auto means = dkm::kmeans_lloyd(data, k);
double inertia = dkm::means_inertia(data, means, k);
EXPECT(284.256926 == lest::approx(inertia).epsilon(1e-6));
}
}
},
CASE("Test dkm::get_best_means",) {
SETUP() {
std::vector<std::array<double, 2>> points{
{8, 8},
{9, 9},
{11, 11},
{12, 12},
{18, 18},
{19, 19},
{21, 21},
{22, 22},
{39, 39},
{41, 41},
};
std::vector<std::array<double, 2>> centroids{
{10, 10},
{20, 20},
{40, 40}
};
std::vector<uint32_t> labels{0, 0, 0, 0, 1, 1, 1, 1, 2, 2};
uint32_t k = 3;
SECTION("Test if we get the clustering with the least inertia") {
auto means = dkm::get_best_means(points, k, 20);
std::vector<std::array<double, 2>> returned_centroids;
std::vector<uint32_t> returned_labels;
std::tie(returned_centroids, returned_labels) = means;
// every point is assigned to the same cluster center
for (uint32_t i = 0; i < points.size(); ++i) {
auto expected_center = centroids[labels[i]];
auto returned_center = returned_centroids[returned_labels[i]];
EXPECT(expected_center[0] == lest::approx(returned_center[0]));
EXPECT(expected_center[1] == lest::approx(returned_center[1]));
}
}
}
}
};
int main(int argc, char** argv) {
return lest::run(specification, argc, argv);
}
| 8,700 | 4,717 |
/*
* Copyright (c) 2017-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "src/gpu/cl/kernels/ClDirectConv2dKernel.h"
#include "arm_compute/core/CL/CLHelpers.h"
#include "arm_compute/core/CL/CLKernelLibrary.h"
#include "arm_compute/core/CL/ICLTensor.h"
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/ITensor.h"
#include "arm_compute/core/PixelValue.h"
#include "arm_compute/core/Utils.h"
#include "arm_compute/core/utils/misc/ShapeCalculator.h"
#include "arm_compute/core/utils/quantization/AsymmHelpers.h"
#include "src/core/AccessWindowStatic.h"
#include "src/core/CL/CLUtils.h"
#include "src/core/CL/CLValidate.h"
#include "src/core/helpers/AutoConfiguration.h"
#include "src/core/helpers/WindowHelpers.h"
#include "src/gpu/cl/kernels/gemm/ClGemmHelpers.h"
#include "support/Cast.h"
#include "support/StringSupport.h"
namespace arm_compute
{
namespace opencl
{
namespace kernels
{
namespace
{
Status validate_arguments(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info)
{
ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(src);
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8_SIGNED, DataType::QASYMM8, DataType::F16, DataType::F32);
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, weights);
const DataLayout data_layout = src->data_layout();
const int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH);
const int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT);
const int channel_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL);
ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(channel_idx) != src->dimension(channel_idx), "Weights feature map dimension should match the respective src's one");
ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->num_dimensions() > 4, "Weights can be at most 4 dimensional");
if(data_layout == DataLayout::NCHW)
{
ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(width_idx) != weights->dimension(height_idx), "Weights should have same width and height");
ARM_COMPUTE_RETURN_ERROR_ON_MSG((weights->dimension(width_idx) == 1) && std::get<0>(conv_info.stride()) > 3, "Strides larger than 3 not supported for 1x1 convolution.");
ARM_COMPUTE_RETURN_ERROR_ON_MSG((weights->dimension(width_idx) == 3 || weights->dimension(width_idx) == 5 || weights->dimension(width_idx) == 9) && std::get<0>(conv_info.stride()) > 2,
"Strides larger than 2 not supported for 3x3, 5x5, 9x9 convolution.");
ARM_COMPUTE_RETURN_ERROR_ON_MSG(!is_data_type_float(src->data_type()) && act_info.enabled(), "Activation supported only for floating point and NHWC.");
if(is_data_type_quantized(src->data_type()))
{
ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(width_idx) != 1 && weights->dimension(width_idx) != 3 && weights->dimension(width_idx) != 5 && weights->dimension(width_idx) != 9,
"Kernel sizes other than 1x1, 3x3, 5x5 or 9x9 are not supported with quantized data types");
}
else
{
ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(width_idx) != 1 && weights->dimension(width_idx) != 3 && weights->dimension(width_idx) != 5,
"Kernel sizes other than 1x1, 3x3 or 5x5 are not supported with float data types");
}
}
if(biases != nullptr)
{
if(is_data_type_quantized_asymmetric(src->data_type()))
{
ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32);
}
else
{
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(weights, biases);
}
ARM_COMPUTE_RETURN_ERROR_ON_MSG(biases->dimension(0) != weights->dimension(3),
"Biases size and number of dst feature maps should match");
ARM_COMPUTE_RETURN_ERROR_ON_MSG(biases->num_dimensions() > 1,
"Biases should be one dimensional");
}
// Checks performed when dst is configured
if(dst->total_size() != 0)
{
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(dst->tensor_shape(),
misc::shape_calculator::compute_deep_convolution_shape(*src, *weights, conv_info));
ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, dst);
}
const auto data_type = src->data_type();
if(is_data_type_quantized(data_type))
{
const UniformQuantizationInfo iqinfo = src->quantization_info().uniform();
const UniformQuantizationInfo wqinfo = weights->quantization_info().uniform();
const UniformQuantizationInfo oqinfo = dst->quantization_info().uniform();
float multiplier = iqinfo.scale * wqinfo.scale / oqinfo.scale;
int output_multiplier = 0;
int output_shift = 0;
ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift));
}
return Status{};
}
bool export_to_cl_image_support(ITensorInfo *tensor, GPUTarget gpu_target, DataLayout data_layout)
{
if(tensor->tensor_shape()[0] % 4 || (data_layout != DataLayout::NHWC))
{
return false;
}
// If not floating point
if(!is_data_type_float(tensor->data_type()))
{
return false;
}
if(gpu_target == GPUTarget::G71 || get_arch_from_target(gpu_target) == GPUTarget::MIDGARD)
{
return false;
}
// Check if the cl_khr_image2d_from_buffer extension is supported on the target platform
if(!image2d_from_buffer_supported(CLKernelLibrary::get().get_device()))
{
return false;
}
// Check cl image pitch alignment
if(get_cl_image_pitch_alignment(CLKernelLibrary::get().get_device()) == 0)
{
return false;
}
const size_t image_w = tensor->tensor_shape()[0] / 4;
const size_t image_h = tensor->tensor_shape()[1] * tensor->tensor_shape()[2] * tensor->tensor_shape()[3];
const size_t max_image_w = CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_IMAGE2D_MAX_WIDTH>();
const size_t max_image_h = CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_IMAGE2D_MAX_HEIGHT>();
if(image_w > max_image_w || image_h > max_image_h)
{
return false;
}
return true;
}
} // namespace
ClDirectConv2dKernel::ClDirectConv2dKernel()
{
_type = CLKernelType::DIRECT;
}
void ClDirectConv2dKernel::configure(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *biases, ITensorInfo *dst,
const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info)
{
ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst);
// Perform validation
ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, weights, biases, dst, conv_info, act_info));
const int conv_stride_x = std::get<0>(conv_info.stride());
const int conv_stride_y = std::get<1>(conv_info.stride());
_data_layout = src->data_layout();
_conv_info = conv_info;
const unsigned int width_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH);
const unsigned int height_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT);
const unsigned int channel_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::CHANNEL);
const unsigned int kernel_size = weights->dimension(width_idx);
const DataType data_type = src->data_type();
const GPUTarget gpu_target = get_target();
unsigned int _num_elems_processed_per_iteration = 0;
// Get dst shape
TensorShape output_shape = misc::shape_calculator::compute_deep_convolution_shape(*src, *weights, conv_info);
// Output auto inizialitation if not yet initialized
auto_init_if_empty(*dst, output_shape,
1,
src->data_type(),
src->quantization_info());
// Configure kernel window
Window win;
if(_data_layout == DataLayout::NHWC)
{
const unsigned int vec_size = std::min(static_cast<unsigned int>(dst->tensor_shape()[0]), 4u);
unsigned int num_rows = 1U;
if(dst->tensor_shape()[0] > 16)
{
num_rows = src->data_type() == DataType::F32 ? 2U : 4U;
}
// Create window and update padding
win = calculate_max_window(output_shape, Steps(vec_size, num_rows));
}
else if(_data_layout == DataLayout::NCHW)
{
_num_elems_processed_per_iteration = 1u;
win = calculate_max_window(*dst, Steps(_num_elems_processed_per_iteration));
}
ICLKernel::configure_internal(win);
std::stringstream kernel_name;
CLBuildOptions build_options;
if(_data_layout == DataLayout::NHWC)
{
kernel_name << "direct_convolution_nhwc";
const unsigned int n0 = win.x().step();
const unsigned int m0 = win.y().step();
const unsigned int k0 = adjust_vec_size(is_data_type_quantized(data_type) ? 16u : 8u, src->dimension(channel_idx));
const unsigned int partial_store_n0 = dst->dimension(channel_idx) % n0;
const unsigned int pad_left = conv_info.pad_left();
const unsigned int pad_top = conv_info.pad_top();
const bool export_to_cl_image = export_to_cl_image_support(weights, gpu_target, _data_layout);
// Update the padding for the weights tensor if we can export to cl_image
if(export_to_cl_image)
{
gemm::update_padding_for_cl_image(weights);
}
if(biases != nullptr)
{
build_options.add_option(std::string("-DHAS_BIAS"));
build_options.add_option(std::string("-DBIA_DATA_TYPE=" + get_cl_type_from_data_type(biases->data_type())));
}
build_options.add_option("-cl-fast-relaxed-math");
build_options.add_option("-DSRC_TENSOR_TYPE=BUFFER");
build_options.add_option("-DSRC_DATA_TYPE=" + get_cl_type_from_data_type(src->data_type()));
build_options.add_option("-DDST_TENSOR_TYPE=BUFFER");
build_options.add_option("-DDST_DATA_TYPE=" + get_cl_type_from_data_type(dst->data_type()));
build_options.add_option_if_else(export_to_cl_image, "-DWEI_TENSOR_TYPE=IMAGE", "-DWEI_TENSOR_TYPE=BUFFER");
build_options.add_option("-DWEI_WIDTH=" + support::cpp11::to_string(weights->dimension(width_idx)));
build_options.add_option("-DWEI_HEIGHT=" + support::cpp11::to_string(weights->dimension(height_idx)));
build_options.add_option("-DWEI_DATA_TYPE=" + get_cl_type_from_data_type(weights->data_type()));
build_options.add_option("-DSTRIDE_X=" + support::cpp11::to_string(conv_stride_x));
build_options.add_option("-DSTRIDE_Y=" + support::cpp11::to_string(conv_stride_y));
build_options.add_option("-DPAD_LEFT=" + support::cpp11::to_string(pad_left));
build_options.add_option("-DPAD_TOP=" + support::cpp11::to_string(pad_top));
build_options.add_option("-DN0=" + support::cpp11::to_string(n0));
build_options.add_option("-DM0=" + support::cpp11::to_string(m0));
build_options.add_option("-DK0=" + support::cpp11::to_string(k0));
build_options.add_option("-DPARTIAL_N0=" + support::cpp11::to_string(partial_store_n0));
build_options.add_option_if((src->dimension(channel_idx) % k0) != 0, "-DLEFTOVER_LOOP");
build_options.add_option("-DACTIVATION_TYPE=" + lower_string(string_from_activation_func(act_info.activation())));
if(is_data_type_quantized(data_type))
{
const UniformQuantizationInfo iqinfo = src->quantization_info().uniform();
const UniformQuantizationInfo wqinfo = weights->quantization_info().uniform();
const UniformQuantizationInfo oqinfo = dst->quantization_info().uniform();
PixelValue zero_value = PixelValue(0, src->data_type(), src->quantization_info());
int zero_value_s32;
zero_value.get(zero_value_s32);
float multiplier = iqinfo.scale * wqinfo.scale / oqinfo.scale;
int output_multiplier = 0;
int output_shift = 0;
quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift);
build_options.add_option("-DIS_QUANTIZED");
build_options.add_option("-DDST_MULTIPLIER=" + support::cpp11::to_string(output_multiplier));
build_options.add_option("-DDST_SHIFT=" + support::cpp11::to_string(output_shift));
build_options.add_option("-DSRC_OFFSET=" + support::cpp11::to_string(-iqinfo.offset));
build_options.add_option("-DWEI_OFFSET=" + support::cpp11::to_string(-wqinfo.offset));
build_options.add_option("-DDST_OFFSET=" + support::cpp11::to_string(oqinfo.offset));
build_options.add_option("-DZERO_VALUE=" + support::cpp11::to_string(zero_value_s32));
build_options.add_option("-DACC_DATA_TYPE=" + get_cl_type_from_data_type(DataType::S32));
}
else
{
build_options.add_option("-DACC_DATA_TYPE=" + get_cl_type_from_data_type(data_type));
build_options.add_option("-DZERO_VALUE=" + support::cpp11::to_string(0));
build_options.add_option("-DSRC_OFFSET=" + support::cpp11::to_string(0));
build_options.add_option("-DWEI_OFFSET=" + support::cpp11::to_string(0));
build_options.add_option("-DDST_OFFSET=" + support::cpp11::to_string(0));
build_options.add_option_if(act_info.enabled(), "-DA_VAL=" + float_to_string_with_full_precision(act_info.a()));
build_options.add_option_if(act_info.enabled(), "-DB_VAL=" + float_to_string_with_full_precision(act_info.b()));
}
}
else
{
kernel_name << "direct_convolution_nchw";
build_options.add_option_if(biases != nullptr, std::string("-DHAS_BIAS"));
build_options.add_option("-DSRC_WIDTH=" + support::cpp11::to_string(src->dimension(width_idx)));
build_options.add_option("-DSRC_HEIGHT=" + support::cpp11::to_string(src->dimension(height_idx)));
build_options.add_option("-DSRC_CHANNELS=" + support::cpp11::to_string(src->dimension(channel_idx)));
build_options.add_option("-DPAD_LEFT=" + support::cpp11::to_string(conv_info.pad_left()));
build_options.add_option("-DPAD_TOP=" + support::cpp11::to_string(conv_info.pad_top()));
build_options.add_option("-DSTRIDE_X=" + support::cpp11::to_string(conv_stride_x));
build_options.add_option("-DSTRIDE_Y=" + support::cpp11::to_string(conv_stride_y));
build_options.add_option("-DWEI_WIDTH=" + support::cpp11::to_string(weights->dimension(width_idx)));
build_options.add_option("-DWEI_HEIGHT=" + support::cpp11::to_string(weights->dimension(height_idx)));
build_options.add_option(std::string("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type)));
build_options.add_option(std::string("-DDATA_SIZE=" + get_data_size_from_data_type(data_type)));
build_options.add_option(std::string("-DWEIGHTS_DEPTH=" + support::cpp11::to_string(weights->dimension(channel_idx))));
build_options.add_option(std::string("-DSTRIDE_X=" + support::cpp11::to_string(conv_stride_x)));
build_options.add_option(std::string("-DDATA_TYPE_PROMOTED=" + get_cl_type_from_data_type(data_type)));
build_options.add_option(std::string("-DVEC_SIZE=" + support::cpp11::to_string(_num_elems_processed_per_iteration)));
build_options.add_option(std::string("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(src->dimension(0) % _num_elems_processed_per_iteration)));
if(is_data_type_quantized(data_type))
{
const UniformQuantizationInfo iqinfo = src->quantization_info().uniform();
const UniformQuantizationInfo wqinfo = weights->quantization_info().uniform();
const UniformQuantizationInfo oqinfo = dst->quantization_info().uniform();
float multiplier = iqinfo.scale * wqinfo.scale / oqinfo.scale;
int output_multiplier = 0;
int output_shift = 0;
quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift);
build_options.add_option("-DIS_QUANTIZED");
build_options.add_option("-DOUTPUT_MULTIPLIER=" + support::cpp11::to_string(output_multiplier));
build_options.add_option("-DOUTPUT_SHIFT=" + support::cpp11::to_string(output_shift));
build_options.add_option("-DKERNEL_SIZE=" + support::cpp11::to_string(kernel_size));
build_options.add_option("-DINPUT_OFFSET=" + support::cpp11::to_string(-iqinfo.offset));
build_options.add_option("-DWEIGHTS_OFFSET=" + support::cpp11::to_string(-wqinfo.offset));
build_options.add_option("-DOUTPUT_OFFSET=" + support::cpp11::to_string(oqinfo.offset));
}
}
_kernel = create_kernel(compile_context, kernel_name.str(), build_options.options());
// Set config_id for enabling LWS tuning
_config_id = kernel_name.str();
_config_id += "_";
_config_id += lower_string(string_from_data_type(data_type));
_config_id += "_";
_config_id += support::cpp11::to_string(kernel_size);
_config_id += "_";
_config_id += support::cpp11::to_string(border_size().left);
_config_id += "_";
_config_id += support::cpp11::to_string(border_size().top);
_config_id += "_";
_config_id += support::cpp11::to_string(border_size().right);
_config_id += "_";
_config_id += support::cpp11::to_string(border_size().bottom);
_config_id += "_";
_config_id += support::cpp11::to_string(conv_stride_x);
_config_id += "_";
_config_id += support::cpp11::to_string(conv_stride_y);
_config_id += "_";
_config_id += support::cpp11::to_string(dst->dimension(width_idx));
_config_id += "_";
_config_id += support::cpp11::to_string(dst->dimension(height_idx));
_config_id += "_";
_config_id += lower_string(string_from_data_layout(_data_layout));
}
Status ClDirectConv2dKernel::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst,
const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info)
{
ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src, weights, biases, dst, conv_info, act_info));
return Status{};
}
void ClDirectConv2dKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue)
{
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window);
// Get initial windows
Window slice = window.first_slice_window_3D();
const auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_0));
const auto weights = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_1));
const auto biases = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_2));
auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST));
if(_data_layout == DataLayout::NHWC)
{
cl::Image2D weights_cl_image;
const size_t dim_y_collapsed = ceil_to_multiple(dst->info()->dimension(1) * dst->info()->dimension(2), slice.y().step());
const bool export_to_cl_image = export_to_cl_image_support(weights->info(), get_target(), _data_layout);
slice.set(Window::DimY, Window::Dimension(0, dim_y_collapsed, slice.y().step()));
slice.set(Window::DimZ, Window::Dimension(0, dst->info()->dimension(3), 1));
if(export_to_cl_image)
{
const size_t image_w = weights->info()->dimension(0) / 4;
const size_t image_h = weights->info()->dimension(1) * weights->info()->dimension(2) * weights->info()->dimension(3);
const TensorShape shape2d(image_w, image_h);
const size_t image_row_pitch = weights->info()->strides_in_bytes()[1];
// Export cl_buffer to cl_image
weights_cl_image = create_image2d_from_buffer(CLKernelLibrary::get().context(), weights->cl_buffer(), shape2d, weights->info()->data_type(), image_row_pitch);
}
unsigned int idx = 0;
add_4d_tensor_nhwc_argument(idx, src);
add_4d_tensor_nhwc_argument(idx, dst);
if(export_to_cl_image)
{
_kernel.setArg(idx++, weights_cl_image);
}
add_4d_tensor_nhwc_argument(idx, weights);
if(biases != nullptr)
{
add_1D_tensor_argument(idx, biases, slice);
}
enqueue(queue, *this, slice, lws_hint());
}
else
{
unsigned int idx1 = 2 * num_arguments_per_3D_tensor();
add_3D_tensor_argument(idx1, weights, slice);
if(biases != nullptr)
{
Window slice_biases;
slice_biases.use_tensor_dimensions(biases->info()->tensor_shape());
add_1D_tensor_argument(idx1, biases, slice_biases);
}
_kernel.setArg(idx1++, static_cast<unsigned int>(weights->info()->strides_in_bytes()[3]));
do
{
unsigned int idx = 0;
add_3D_tensor_argument(idx, src, slice);
add_3D_tensor_argument(idx, dst, slice);
enqueue(queue, *this, slice, lws_hint());
}
while(window.slide_window_slice_3D(slice));
}
}
} // namespace kernels
} // namespace opencl
} // namespace arm_compute
| 23,299 | 7,917 |
#include "testCommon.h"
using namespace ff_dynamic;
namespace test_common {
std::atomic<bool> g_bExit = ATOMIC_VAR_INIT(false);
std::atomic<int> g_bInterruptCount = ATOMIC_VAR_INIT(0);
void sigIntHandle(int sig) {
g_bExit = true;
LOG(INFO) << "sig " << sig << " captured. count" << g_bInterruptCount;
if (++g_bInterruptCount >= 3) {
LOG(INFO) << "exit program";
exit(1);
}
}
int testInit(const string & logtag) {
google::InitGoogleLogging(logtag.c_str());
google::InstallFailureSignalHandler();
FLAGS_stderrthreshold = 0;
FLAGS_logtostderr = 1;
auto & sigHandle = GlobalSignalHandle::getInstance();
sigHandle.registe(SIGINT, sigIntHandle);
av_log_set_callback([] (void *ptr, int level, const char *fmt, va_list vl) {
if (level > AV_LOG_WARNING)
return ;
char message[8192];
const char *ffmpegModule = nullptr;
if (ptr) {
AVClass *avc = *(AVClass**) ptr;
if (avc->item_name)
ffmpegModule = avc->item_name(ptr);
}
vsnprintf(message, sizeof(message), fmt, vl);
LOG(WARNING) << "[FFMPEG][" << (ffmpegModule ? ffmpegModule : "") << "]" << message;
});
return 0;
}
} // namespace test_common
| 1,270 | 444 |
////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2022 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "Test.h"
#if defined(REAPER_USE_BULLET_PHYSICS)
# include <BulletCollision/CollisionShapes/btBoxShape.h>
# include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
# include <BulletCollision/CollisionShapes/btTriangleMesh.h>
# include <BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h>
# include <btBulletDynamicsCommon.h>
#endif
#include "mesh/Mesh.h"
#include "core/Assert.h"
#include "profiling/Scope.h"
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/projection.hpp>
#include <glm/vec3.hpp>
#include <bit>
namespace SplineSonic
{
namespace
{
#if defined(REAPER_USE_BULLET_PHYSICS)
inline glm::vec3 toGlm(btVector3 const& vec) { return glm::vec3(vec.getX(), vec.getY(), vec.getZ()); }
inline glm::quat toGlm(btQuaternion const& quat)
{
return glm::quat(quat.getW(), quat.getX(), quat.getY(), quat.getZ());
}
inline glm::fmat4x3 toGlm(const btTransform& transform)
{
const btMatrix3x3 basis = transform.getBasis();
const glm::fvec3 translation = toGlm(transform.getOrigin());
return glm::fmat4x3(toGlm(basis[0]), toGlm(basis[1]), toGlm(basis[2]), translation);
}
inline btVector3 toBt(glm::vec3 const& vec) { return btVector3(vec.x, vec.y, vec.z); }
inline btMatrix3x3 m33toBt(const glm::fmat3x3& m)
{
return btMatrix3x3(m[0].x, m[1].x, m[2].x, m[0].y, m[1].y, m[2].y, m[0].z, m[1].z, m[2].z);
}
// inline btQuaternion toBt(glm::quat const& quat) { return btQuaternion(quat.w, quat.x, quat.y, quat.z); }
inline btTransform toBt(const glm::fmat4x3& transform)
{
btMatrix3x3 mat = m33toBt(glm::fmat3x3(transform));
btTransform ret = btTransform(mat, toBt(glm::column(transform, 3)));
return ret;
}
static const int SimulationMaxSubStep = 3; // FIXME
glm::fvec3 forward() { return glm::vec3(1.0f, 0.0f, 0.0f); }
glm::fvec3 up() { return glm::vec3(0.0f, 0.0f, 1.0f); }
void pre_tick(PhysicsSim& sim, const ShipInput& input, float /*dt*/)
{
REAPER_PROFILE_SCOPE_FUNC();
btRigidBody* playerRigidBody = sim.players[0];
const glm::fmat4x3 player_transform = toGlm(playerRigidBody->getWorldTransform());
const glm::fvec3 player_position_ws = player_transform[3];
const glm::quat player_orientation = toGlm(playerRigidBody->getWorldTransform().getRotation());
float min_dist_sq = 10000000.f;
const btRigidBody* closest_track_chunk = nullptr;
for (auto track_chunk : sim.static_rigid_bodies)
{
glm::fvec3 delta = player_position_ws - toGlm(track_chunk->getWorldTransform().getOrigin());
float dist_sq = glm::dot(delta, delta);
if (dist_sq < min_dist_sq)
{
min_dist_sq = dist_sq;
closest_track_chunk = track_chunk;
}
}
Assert(closest_track_chunk);
// FIXME const glm::fmat4x3 projected_transform = toGlm(closest_track_chunk->getWorldTransform());
const glm::quat projected_orientation = toGlm(closest_track_chunk->getWorldTransform().getRotation());
glm::vec3 shipUp;
glm::vec3 shipFwd;
shipUp = projected_orientation * up();
shipFwd = player_orientation * forward();
// shipFwd = glm::normalize(shipFwd - glm::proj(shipFwd, shipUp)); // Ship Fwd in on slice plane
// Re-eval ship orientation
// FIXME player_orientation = glm::quat(glm::mat3(shipFwd, shipUp, glm::cross(shipFwd, shipUp)));
const glm::fvec3 linear_speed = toGlm(playerRigidBody->getLinearVelocity());
// change steer angle
{
// float steerMultiplier = 0.035f;
// float inclinationMax = 2.6f;
// float inclForce = (log(glm::length(linear_speed * 0.5f) + 1.0f) + 0.2f) * input.steer;
// float inclinationRepel = -movement.inclination * 5.0f;
// movement.inclination =
// glm::clamp(movement.inclination + (inclForce + inclinationRepel) * dtSecs, -inclinationMax,
// inclinationMax);
// movement.orientation *= glm::angleAxis(-input.steer * steerMultiplier, up());
}
ShipStats ship_stats;
ship_stats.thrust = 100.f;
ship_stats.braking = 10.f;
// Integrate forces
glm::vec3 forces = {};
forces += -shipUp * 98.331f; // 10x earth gravity
forces += shipFwd * input.throttle * ship_stats.thrust; // Engine thrust
// forces += shipFwd * player.getAcceleration(); // Engine thrust
forces += -glm::proj(linear_speed, shipFwd) * input.brake * ship_stats.braking; // Brakes force
// forces += -glm::proj(movement.speed, glm::cross(shipFwd, shipUp)) * sim.pHandling; // Handling term
forces += -linear_speed * sim.linear_friction;
forces += -linear_speed * glm::length(linear_speed) * sim.quadratic_friction;
// Progressive repelling force that pushes the ship downwards
// FIXME
// float upSpeed = glm::length(movement.speed - glm::proj(movement.speed, shipUp));
// if (projection.relativePosition.y > 2.0f && upSpeed > 0.0f)
// forces += player_orientation * (glm::vec3(0.0f, 2.0f - upSpeed, 0.0f) * 10.0f);
playerRigidBody->clearForces();
playerRigidBody->applyCentralForce(toBt(forces));
}
/*
{
shipUp = projection.orientation * glm::up();
shipFwd = movement.orientation * glm::forward();
shipFwd = glm::normalize(shipFwd - glm::proj(shipFwd, shipUp)); // Ship Fwd in on slice plane
// Re-eval ship orientation
movement.orientation = glm::quat(glm::mat3(shipFwd, shipUp, glm::cross(shipFwd, shipUp)));
// change steer angle
steer(dt, movement, factors.getTurnFactor());
// sum all forces
// forces += - shipUp * 98.331f; // 10x earth gravity
forces += -shipUp * 450.0f; // lot of times earth gravity
forces += shipFwd * factors.getThrustFactor() * player->getAcceleration(); // Engine thrust
forces += -glm::proj(movement.speed, shipFwd) * factors.getBrakeFactor() * _pBrakesForce; // Brakes force
forces += -glm::proj(movement.speed, glm::cross(shipFwd, shipUp)) * _pHandling; // Handling term
forces += -movement.speed * linear_friction; // Linear friction
term forces += -movement.speed * glm::length(movement.speed) * _pQuadFriction; // Quadratic friction
term
// Progressive repelling force that pushes the ship downwards
float upSpeed = glm::length(movement.speed - glm::proj(movement.speed, shipUp));
if (projection.relativePosition.y > 2.0f && upSpeed > 0.0f)
forces += movement.orientation * (glm::vec3(0.0f, 2.0f - upSpeed, 0.0f) * 10.0f);
playerRigidBody->clearForces();
playerRigidBody->applyCentralForce(toBt(forces));
}
*/
void post_tick(PhysicsSim& sim, float /*dt*/)
{
REAPER_PROFILE_SCOPE_FUNC();
btRigidBody* playerRigidBody = sim.players.front(); // FIXME
toGlm(playerRigidBody->getLinearVelocity());
toGlm(playerRigidBody->getOrientation());
}
#endif
} // namespace
PhysicsSim create_sim()
{
PhysicsSim sim = {};
// Physics tweakables
sim.linear_friction = 4.0f;
sim.quadratic_friction = 0.01f;
#if defined(REAPER_USE_BULLET_PHYSICS)
// Boilerplate code for a standard rigidbody simulation
sim.broadphase = new btDbvtBroadphase();
sim.collisionConfiguration = new btDefaultCollisionConfiguration();
sim.dispatcher = new btCollisionDispatcher(sim.collisionConfiguration);
btGImpactCollisionAlgorithm::registerAlgorithm(sim.dispatcher);
sim.solver = new btSequentialImpulseConstraintSolver;
// Putting all of that together
sim.dynamicsWorld =
new btDiscreteDynamicsWorld(sim.dispatcher, sim.broadphase, sim.solver, sim.collisionConfiguration);
#endif
return sim;
}
void destroy_sim(PhysicsSim& sim)
{
#if defined(REAPER_USE_BULLET_PHYSICS)
for (auto player_rigid_body : sim.players)
{
sim.dynamicsWorld->removeRigidBody(player_rigid_body);
delete player_rigid_body->getMotionState();
delete player_rigid_body;
}
for (auto rb : sim.static_rigid_bodies)
{
sim.dynamicsWorld->removeRigidBody(rb);
delete rb->getMotionState();
delete rb;
}
for (auto collision_shape : sim.collision_shapes)
{
delete collision_shape;
}
for (auto vb : sim.vertexArrayInterfaces)
delete vb;
// Delete the rest of the bullet context
delete sim.dynamicsWorld;
delete sim.solver;
delete sim.dispatcher;
delete sim.collisionConfiguration;
delete sim.broadphase;
#else
static_cast<void>(sim);
#endif
}
namespace
{
#if defined(REAPER_USE_BULLET_PHYSICS)
void pre_tick_callback(btDynamicsWorld* world, btScalar dt)
{
PhysicsSim* sim_ptr = static_cast<PhysicsSim*>(world->getWorldUserInfo());
Assert(sim_ptr);
PhysicsSim& sim = *sim_ptr;
pre_tick(sim, sim.last_input, dt);
}
void post_tick_callback(btDynamicsWorld* world, btScalar dt)
{
PhysicsSim* sim_ptr = static_cast<PhysicsSim*>(world->getWorldUserInfo());
Assert(sim_ptr);
post_tick(*sim_ptr, dt);
}
#endif
} // namespace
void sim_start(PhysicsSim* sim)
{
REAPER_PROFILE_SCOPE_FUNC();
Assert(sim);
#if defined(REAPER_USE_BULLET_PHYSICS)
sim->dynamicsWorld->setInternalTickCallback(pre_tick_callback, sim, true);
sim->dynamicsWorld->setInternalTickCallback(post_tick_callback, sim, false);
#endif
}
void sim_update(PhysicsSim& sim, const ShipInput& input, float dt)
{
REAPER_PROFILE_SCOPE_FUNC();
sim.last_input = input; // FIXME
#if defined(REAPER_USE_BULLET_PHYSICS)
sim.dynamicsWorld->stepSimulation(dt, SimulationMaxSubStep);
#else
static_cast<void>(sim);
static_cast<void>(dt);
#endif
}
glm::fmat4x3 get_player_transform(PhysicsSim& sim)
{
#if defined(REAPER_USE_BULLET_PHYSICS)
const btRigidBody* playerRigidBody = sim.players.front();
const btMotionState* playerMotionState = playerRigidBody->getMotionState();
btTransform output;
playerMotionState->getWorldTransform(output);
return toGlm(output);
#else
static_cast<void>(sim);
AssertUnreachable();
return glm::fmat4x3(1.f); // FIXME
#endif
}
void sim_register_static_collision_meshes(PhysicsSim& sim, const nonstd::span<Mesh> meshes,
nonstd::span<const glm::fmat4x3> transforms_no_scale,
nonstd::span<const glm::fvec3> scales)
{
// FIXME Assert scale values
#if defined(REAPER_USE_BULLET_PHYSICS)
Assert(meshes.size() == transforms_no_scale.size());
Assert(scales.empty() || scales.size() == transforms_no_scale.size());
for (u32 i = 0; i < meshes.size(); i++)
{
const Mesh& mesh = meshes[i];
// Describe how the mesh is laid out in memory
btIndexedMesh indexedMesh;
indexedMesh.m_numTriangles = mesh.indexes.size() / 3;
indexedMesh.m_triangleIndexBase = reinterpret_cast<const u8*>(mesh.indexes.data());
indexedMesh.m_triangleIndexStride = 3 * sizeof(mesh.indexes[0]);
indexedMesh.m_numVertices = mesh.positions.size();
indexedMesh.m_vertexBase = reinterpret_cast<const u8*>(mesh.positions.data());
indexedMesh.m_vertexStride = sizeof(mesh.positions[0]);
indexedMesh.m_indexType = PHY_INTEGER;
indexedMesh.m_vertexType = PHY_FLOAT;
// Create bullet collision shape based on the mesh described
btTriangleIndexVertexArray* meshInterface = new btTriangleIndexVertexArray();
sim.vertexArrayInterfaces.push_back(meshInterface);
meshInterface->addIndexedMesh(indexedMesh);
btBvhTriangleMeshShape* meshShape = new btBvhTriangleMeshShape(meshInterface, true);
sim.collision_shapes.push_back(meshShape);
const btVector3 scale = scales.empty() ? btVector3(1.f, 1.f, 1.f) : toBt(scales[i]);
btScaledBvhTriangleMeshShape* scaled_mesh_shape = new btScaledBvhTriangleMeshShape(meshShape, scale);
sim.collision_shapes.push_back(scaled_mesh_shape);
btDefaultMotionState* chunkMotionState = new btDefaultMotionState(btTransform(toBt(transforms_no_scale[i])));
// Create the rigidbody with the collision shape
btRigidBody::btRigidBodyConstructionInfo staticMeshRigidBodyInfo(0, chunkMotionState, scaled_mesh_shape);
btRigidBody* staticRigidMesh = new btRigidBody(staticMeshRigidBodyInfo);
sim.static_rigid_bodies.push_back(staticRigidMesh);
// Add it to our scene
sim.dynamicsWorld->addRigidBody(staticRigidMesh);
}
#else
static_cast<void>(sim);
static_cast<void>(meshes);
static_cast<void>(transforms_no_scale);
static_cast<void>(scales);
#endif
}
void sim_create_player_rigid_body(PhysicsSim& sim, const glm::fmat4x3& player_transform, const glm::fvec3& shape_extent)
{
#if defined(REAPER_USE_BULLET_PHYSICS)
btMotionState* motionState = new btDefaultMotionState(toBt(player_transform));
btCollisionShape* collisionShape = new btBoxShape(toBt(shape_extent));
sim.collision_shapes.push_back(collisionShape);
btScalar mass = 10.f; // FIXME
btVector3 inertia(0.f, 0.f, 0.f);
collisionShape->calculateLocalInertia(mass, inertia);
btRigidBody::btRigidBodyConstructionInfo constructInfo(mass, motionState, collisionShape, inertia);
btRigidBody* player_rigid_body = new btRigidBody(constructInfo);
player_rigid_body->setFriction(0.1f);
player_rigid_body->setRollingFriction(0.8f);
// FIXME doesn't do anything? Wrong collision mesh?
player_rigid_body->setCcdMotionThreshold(0.05f);
player_rigid_body->setCcdSweptSphereRadius(shape_extent.x);
sim.dynamicsWorld->addRigidBody(player_rigid_body);
sim.players.push_back(player_rigid_body);
#else
static_cast<void>(sim);
static_cast<void>(player_transform);
static_cast<void>(shape_extent);
#endif
}
} // namespace SplineSonic
| 14,769 | 5,244 |
//+-------------------------------------------------------------------
//
// File: FILESEC.hxx
//
// Contents: class encapsulating file security.
//
// Classes: CFileSecurity
//
// History: Nov-93 Created DaveMont
// Oct-96 Modified BrunoSc
//
//--------------------------------------------------------------------
#ifndef __FILESEC__
#define __FILESEC__
#include "t2.hxx"
#include "daclwrap.hxx"
//+-------------------------------------------------------------------
//
// Class: CFileSecurity
//
// Purpose: encapsulation of File security, this class wraps the
// NT security descriptor for a file, allowing application
// of a class that wraps DACLS to it, thus changing the
// acces control on the file.
//
//--------------------------------------------------------------------
class CFileSecurity
{
public:
CFileSecurity(LPWSTR filename);
~CFileSecurity();
ULONG Init();
// methods to actually set the security on the file
ULONG SetFS(BOOL fmodify, CDaclWrap *pcdw, BOOL fdir);
private:
BYTE * _psd ;
LPWSTR _pwfilename ;
};
#endif // __FILESEC__
| 1,270 | 387 |
#include "keypad.h"
#include <QApplication>
#include <QCoreApplication>
#include <QGridLayout>
#include <QKeyEvent>
#include <QToolButton>
Keypad::Keypad(QWidget *parent) : QWidget{parent} {
QGridLayout *lay = new QGridLayout{this};
const std::vector<Keys> keys = {
{"1", Qt::Key_1}, {"2", Qt::Key_2}, {"3", Qt::Key_3},
{"4", Qt::Key_4}, {"5", Qt::Key_5}, {"6", Qt::Key_6},
{"7", Qt::Key_7}, {"8", Qt::Key_8}, {"9", Qt::Key_9},
{".", Qt::Key_Colon}, {"del", Qt::Key_Delete}, {"enter", Qt::Key_Return}};
for (unsigned int i = 0; i < keys.size(); i++) {
QToolButton *button = new QToolButton;
button->setFixedSize(64, 64);
const Keys &_key = keys[i];
button->setText(_key.name);
lay->addWidget(button, i / 3, i % 3);
button->setProperty("key", _key.key);
connect(button, &QToolButton::clicked, this, &Keypad::on_clicked);
}
}
void Keypad::on_clicked() {
QToolButton *button = qobject_cast<QToolButton *>(sender());
const QString &text = button->text();
int key = button->property("key").toInt();
QWidget *widget = QApplication::focusWidget();
if (text == "del") {
QKeyEvent *event =
new QKeyEvent(QEvent::KeyPress, Qt::Key_A, Qt::ControlModifier, text);
QCoreApplication::postEvent(widget, event);
}
QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, text);
QCoreApplication::postEvent(widget, event);
}
| 1,453 | 534 |
//
// GLPool.cpp
// MNN
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "GLPool.hpp"
#include "AllShader.hpp"
#include "GLBackend.hpp"
#include "Macro.h"
namespace MNN {
namespace OpenGL {
ErrorCode GLPool::onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) {
auto inputTensor = inputs[0];
auto pool = mPool;
if (!pool->isGlobal()) {
int kx = pool->kernelX();
int ky = pool->kernelY();
int sx = pool->strideX();
int sy = pool->strideY();
int px = pool->padX();
int py = pool->padY();
mSetUniform = [=] {
glUniform2i(2, kx, ky);
glUniform2i(3, sx, sy);
glUniform2i(4, px, py);
};
} else {
mSetUniform = [=] {
glUniform2i(2, inputTensor->width(), inputTensor->height());
glUniform2i(3, 1, 1);
glUniform2i(4, 0, 0);
};
}
return NO_ERROR;
}
ErrorCode GLPool::onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) {
auto imageInput = inputs[0]->deviceId();
auto imageOutput = outputs[0]->deviceId();
auto outputTensor = outputs[0];
auto inputTensor = inputs[0];
MNN_ASSERT(mPoolProgram.get() != NULL);
mPoolProgram->useProgram();
glBindImageTexture(0, imageInput, 0, GL_TRUE, 0, GL_READ_ONLY, TEXTURE_FORMAT);
glBindImageTexture(1, imageOutput, 0, GL_TRUE, 0, GL_WRITE_ONLY, TEXTURE_FORMAT);
mSetUniform();
glUniform3i(10, outputTensor->width(), outputTensor->height(), UP_DIV(outputTensor->channel(), 4));
glUniform3i(11, inputTensor->width(), inputTensor->height(), UP_DIV(inputTensor->channel(), 4));
OPENGL_CHECK_ERROR;
auto depthQuad = UP_DIV(outputTensor->channel(), 4);
((GLBackend *)backend())->compute(UP_DIV(outputTensor->width(), 2), UP_DIV(outputTensor->height(), 2), UP_DIV(depthQuad, 16));
OPENGL_CHECK_ERROR;
return NO_ERROR;
}
GLPool::~GLPool() {
}
GLPool::GLPool(const std::vector<Tensor *> &inputs, const Op *op, Backend *bn) : Execution(bn) {
auto extra = (GLBackend *)bn;
auto pool = op->main_as_Pool();
switch (pool->type()) {
case PoolType_MAXPOOL:
mPoolProgram = extra->getProgram("maxPool", glsl_maxpool_glsl);
break;
case PoolType_AVEPOOL:
mPoolProgram = extra->getProgram("meanPool", glsl_avgpool_glsl);
break;
default:
MNN_ASSERT(false);
break;
}
mPool = pool;
}
GLCreatorRegister<TypedCreator<GLPool>> __pool_op(OpType_Pooling);
} // namespace OpenGL
} // namespace MNN
| 2,719 | 996 |
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> slices;
vector<int> sortedSlices;
vector<int> pizzas;
int greedy(int maxi){
int counter = maxi;
for(int i=0; i < sortedSlices.size(); i++){
//cout << sortedSlices[i] << endl;
if(counter - sortedSlices[i] > 0 && sortedSlices[i] != -1){
counter-=sortedSlices[i];
pizzas.push_back(sortedSlices[i]);
sortedSlices[i]=-1;
}
}
}
int main(){
freopen("e_also_big.in","r",stdin);
freopen("nesh_e.out","w",stdout);
int maxSlices, types = 0;
cin >> maxSlices >> types;
for(int i=0; i < types; i++){
int temp;
cin >> temp;
slices.push_back(temp);
}
sortedSlices = slices;
sort(sortedSlices.begin(), sortedSlices.end());
reverse(sortedSlices.begin(), sortedSlices.end());
greedy(maxSlices);
cout << pizzas.size() << endl;
for(int i=0; i < pizzas.size(); i++){
vector<int>::iterator it = find(slices.begin(), slices.end(), pizzas[i]);
int index = distance(slices.begin(), it);
cout << index << ' ';
}
} | 1,040 | 440 |
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int min_till;
min_till = prices[0];
int profit = 0;
int n = prices.size();
for (int i = 1; i < n; i++)
{
//cout<<min_till<<" ";
int cost = prices[i] - min_till;
profit = max(profit, cost);
min_till = min(min_till, prices[i]);
}
//cout<<endl;
return profit;
}
}; | 458 | 157 |
// count
#include"iostream"
#include"set"
#include"algorithm"
using namespace std;
int main()
{
multiset<int,less<int> > intSet;
intSet.insert(85);
intSet.insert(90);
intSet.insert(100);
intSet.insert(85);
intSet.insert(85);
cout<<"Set: ";
multiset<int,less<int> >::iterator it=intSet.begin();
for(int i=0;i<intSet.size();i++)
cout<<*it++<<' ';
cout<<endl;
int cnt=count(intSet.begin(),intSet.end(),85); // 统计85分的数量
cout<<"85的数量为:"<<cnt<<endl;
system("pause");
return 0;
} | 491 | 231 |
#include "cl/stdafx.h"
#include "Logger.h"
#include <filesystem>
#include <cstddef>
namespace cl {
Logger& g_Logger = Logger::Instance();
void Logger::Start(void)
{
m_LogLevel = INFO;
m_HConsole = GetStdHandle(STD_OUTPUT_HANDLE);
Print(L"Starting Logging system...% % % %\n", 5, true, false, 4);
SetLocale(LC_ALL);
}
void Logger::Shutdown(void)
{
Print(L"Shutting down Logging system...\n");
}
void Logger::SetLocale(s32 locale)
{
const char* l = setlocale(locale, "");
//Print(!l ? "Locale not set\n" : "Locale set to %\n", l);
}
void Logger::SetLogLevel(LogLevel level)
{
m_LogLevel = level;
}
void Logger::PrintNumber(StringBuffer& buffer, u64 number, u64 base)
{
constexpr wchar* table = L"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_#";
ASSERT(base >= 2, "Invalid base!");
ASSERT(base <= 64, "Invalid base!");
constexpr u32 MAX_OUTPUT_LEN = 64;
wchar output[MAX_OUTPUT_LEN];
wchar* end = &output[MAX_OUTPUT_LEN];
wchar* p = end;
while (number)
{
u64 place = number % base;
number /= base;
p -= 1;
*p = table[place];
}
if (p == end)
{
p -= 1;
*p = L'0';
}
buffer.AppendString(p, u32(end - p));
}
void Logger::HandleArgument(StringBuffer& buffer, const PrintArg& arg)
{
const std::any& value = arg.m_Value;
switch (arg.m_Type)
{
case PrintArg::TypeEnum::INTEGER:
{
{
FormatInt& formatInt = std::any_cast<FormatInt>(value);
if (formatInt.m_Base == 10 && formatInt.m_Negative)
buffer.AppendString(L"-");
PrintNumber(buffer, formatInt.m_IntegerValue, formatInt.m_Base);
}
break;
}
case PrintArg::TypeEnum::FLOAT:
{
FormatFloat& formatFloat = std::any_cast<FormatFloat>(value);
wchar temp[512] = { 0 };
swprintf(temp, L"%*.*f", formatFloat.m_FieldWidth, formatFloat.m_Precision, formatFloat.m_FloatValue);
buffer.AppendString(temp);
}
break;
case PrintArg::TypeEnum::STRING:
{
SmartString& str = std::any_cast<SmartString>(value);
buffer.AppendString(str.String);
str.TryFree();
}
break;
case PrintArg::TypeEnum::BOOL:
buffer.AppendString(std::any_cast<bool>(value) ? L"true" : L"false");
break;
}
}
void Logger::PrintInternal(StringBuffer& buffer, const PrintArg* args, u32 argc)
{
const PrintArg& first = args[0];
if (u32 arg = 1; first.m_Type == PrintArg::TypeEnum::STRING)
{
SmartString& str = std::any_cast<SmartString>(first.m_Value);
wchar* s = str.String;
wchar* t = s;
while (*t)
{
if (*t == L'%')
{
if (arg < argc)
{
buffer.AppendString(s, u32(t - s));
HandleArgument(buffer, args[arg]);
t++;
s = t;
arg++;
}
}
t++;
}
buffer.AppendString(s, u32(t - s));
str.TryFree();
}
}
void Logger::PrintSequenceInternal(StringBuffer& buffer, const PrintArg* args, u32 argc)
{
for (u32 arg = 0; arg < argc; arg++)
HandleArgument(buffer, args[arg]);
}
void Logger::PrintColored(StringBuffer& buffer, LogLevel level)
{
switch (level)
{
case FATAL:
SetConsoleTextAttribute(m_HConsole, BACKGROUND_RED | BACKGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
break;
case ERROR:
SetConsoleTextAttribute(m_HConsole, FOREGROUND_RED | FOREGROUND_INTENSITY);
break;
case WARN:
SetConsoleTextAttribute(m_HConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
break;
}
wprintf(buffer.Data);
SetConsoleTextAttribute(m_HConsole, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN);
}
void PrintArg::HandleString(const char ch)
{
StringBuffer buffer;
buffer.AppendChar(ch);
m_Value = std::any(SmartString(buffer.Data, true));
}
void PrintArg::HandleString(const char* str)
{
StringBuffer buffer;
buffer.AppendString(str);
m_Value = std::any(SmartString(buffer.Data, true));
}
void PrintArg::HandlePrinter(const IPrintable& printable)
{
StringBuffer buffer;
printable.Print(buffer);
m_Value = std::any(SmartString(buffer.Data, true));
}
} | 4,069 | 1,824 |
#include <ktlexcept.hpp>
#include <string.hpp>
namespace ktl {
NTSTATUS out_of_range::code() const noexcept {
return STATUS_ARRAY_BOUNDS_EXCEEDED;
}
NTSTATUS range_error::code() const noexcept {
return STATUS_RANGE_NOT_FOUND;
}
NTSTATUS overflow_error::code() const noexcept {
return STATUS_BUFFER_OVERFLOW;
}
NTSTATUS kernel_error::code() const noexcept {
return m_code;
}
NTSTATUS format_error::code() const noexcept {
return STATUS_BAD_DESCRIPTOR_FORMAT;
}
} // namespace ktl | 494 | 187 |
//
// Created by wuggy on 02/12/2017.
//
#include <fstream>
#include "day02.h"
#include "../utils/aocutils.h"
int main()
{
std::ifstream ifs("input.txt");
std::vector< std::vector<std::size_t> > sheet = AOCUtils::parseByLines<std::vector<std::size_t> >(ifs, AOCUtils::parseItem<std::size_t>);
std::cout << Day2::solve_part1(sheet) << std::endl;
std::cout << Day2::solve_part2(sheet) << std::endl;
return 0;
}
| 424 | 187 |
//depot/Lab03_N/DS/security/services/w32time/w32tm/OtherCmds.cpp#16 - edit change 15254 (text)
//--------------------------------------------------------------------
// OtherCmds-implementation
// Copyright (C) Microsoft Corporation, 1999
//
// Created by: Louis Thomas (louisth), 2-17-00
//
// Other useful w32tm commands
//
#include "pch.h" // precompiled headers
#include <strsafe.h>
//--------------------------------------------------------------------
//####################################################################
//##
//## Copied from c run time and modified to be 64bit capable
//##
#include <crt\limits.h>
/* flag values */
#define FL_UNSIGNED 1 /* wcstoul called */
#define FL_NEG 2 /* negative sign found */
#define FL_OVERFLOW 4 /* overflow occured */
#define FL_READDIGIT 8 /* we've read at least one correct digit */
MODULEPRIVATE unsigned __int64 my_wcstoxl (const WCHAR * nptr, WCHAR ** endptr, int ibase, int flags) {
const WCHAR *p;
WCHAR c;
unsigned __int64 number;
unsigned __int64 digval;
unsigned __int64 maxval;
p=nptr; /* p is our scanning pointer */
number=0; /* start with zero */
c=*p++; /* read char */
while (iswspace(c))
c=*p++; /* skip whitespace */
if (c=='-') {
flags|=FL_NEG; /* remember minus sign */
c=*p++;
}
else if (c=='+')
c=*p++; /* skip sign */
if (ibase<0 || ibase==1 || ibase>36) {
/* bad base! */
if (endptr)
/* store beginning of string in endptr */
*endptr=(wchar_t *)nptr;
return 0L; /* return 0 */
}
else if (ibase==0) {
/* determine base free-lance, based on first two chars of
string */
if (c != L'0')
ibase=10;
else if (*p==L'x' || *p==L'X')
ibase=16;
else
ibase=8;
}
if (ibase==16) {
/* we might have 0x in front of number; remove if there */
if (c==L'0' && (*p==L'x' || *p==L'X')) {
++p;
c=*p++; /* advance past prefix */
}
}
/* if our number exceeds this, we will overflow on multiply */
maxval=_UI64_MAX / ibase;
for (;;) { /* exit in middle of loop */
/* convert c to value */
if (iswdigit(c))
digval=c-L'0';
else if (iswalpha(c))
digval=(TCHAR)CharUpper((LPTSTR)c)-L'A'+10;
else
break;
if (digval>=(unsigned)ibase)
break; /* exit loop if bad digit found */
/* record the fact we have read one digit */
flags|=FL_READDIGIT;
/* we now need to compute number=number*base+digval,
but we need to know if overflow occured. This requires
a tricky pre-check. */
if (number<maxval || (number==maxval &&
(unsigned __int64)digval<=_UI64_MAX%ibase)) {
/* we won't overflow, go ahead and multiply */
number=number*ibase+digval;
}
else {
/* we would have overflowed -- set the overflow flag */
flags|=FL_OVERFLOW;
}
c=*p++; /* read next digit */
}
--p; /* point to place that stopped scan */
if (!(flags&FL_READDIGIT)) {
/* no number there; return 0 and point to beginning of
string */
if (endptr)
/* store beginning of string in endptr later on */
p=nptr;
number=0L; /* return 0 */
}
else if ((flags&FL_OVERFLOW) ||
(!(flags&FL_UNSIGNED) &&
(((flags&FL_NEG) && (number>-_I64_MIN)) ||
(!(flags&FL_NEG) && (number>_I64_MAX)))))
{
/* overflow or signed overflow occurred */
//errno=ERANGE;
if ( flags&FL_UNSIGNED )
number=_UI64_MAX;
else if ( flags&FL_NEG )
number=(unsigned __int64)(-_I64_MIN);
else
number=_I64_MAX;
}
if (endptr != NULL)
/* store pointer to char that stopped the scan */
*endptr=(wchar_t *)p;
if (flags&FL_NEG)
/* negate result if there was a neg sign */
number=(unsigned __int64)(-(__int64)number);
return number; /* done. */
}
MODULEPRIVATE unsigned __int64 wcstouI64(const WCHAR *nptr, WCHAR ** endptr, int ibase) {
return my_wcstoxl(nptr, endptr, ibase, FL_UNSIGNED);
}
MODULEPRIVATE HRESULT my_wcstoul_safe(const WCHAR *wsz, ULONG ulMin, ULONG ulMax, ULONG *pulResult) {
HRESULT hr;
ULONG ulResult;
WCHAR *wszLast;
if (L'\0' == *wsz) {
hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
_JumpError(hr, error, "my_wcstoul_safe: empty string is not valid");
}
ulResult = wcstoul(wsz, &wszLast, 0);
// Ensure that we were able to parse the whole string:
if (wsz+wcslen(wsz) != wszLast) {
hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
_JumpError(hr, error, "wcstoul");
}
// Ensure that we lie within the bounds specified by the caler:
if (!((ulMin <= ulResult) && (ulResult <= ulMax))) {
hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
_JumpError(hr, error, "my_wcstoul_safe: result not within bounds");
}
*pulResult = ulResult;
hr = S_OK;
error:
return hr;
}
//####################################################################
//--------------------------------------------------------------------
HRESULT myHExceptionCode(EXCEPTION_POINTERS * pep) {
HRESULT hr=pep->ExceptionRecord->ExceptionCode;
if (!FAILED(hr)) {
hr=HRESULT_FROM_WIN32(hr);
}
return hr;
}
//--------------------------------------------------------------------
// NOTE: this function is accessed through a hidden option, and does not need to be localized.
void PrintNtpPeerInfo(W32TIME_NTP_PEER_INFO *pnpInfo) {
LPWSTR pwszNULL = L"(null)";
wprintf(L"PEER: %s\n", pnpInfo->wszUniqueName ? pnpInfo->wszUniqueName : pwszNULL);
wprintf(L"ulSize: %d\n", pnpInfo->ulSize);
wprintf(L"ulResolveAttempts: %d\n", pnpInfo->ulResolveAttempts);
wprintf(L"u64TimeRemaining: %I64u\n", pnpInfo->u64TimeRemaining);
wprintf(L"u64LastSuccessfulSync: %I64u\n", pnpInfo->u64LastSuccessfulSync);
wprintf(L"ulLastSyncError: 0x%08X\n", pnpInfo->ulLastSyncError);
wprintf(L"ulLastSyncErrorMsgId: 0x%08X\n", pnpInfo->ulLastSyncErrorMsgId);
wprintf(L"ulValidDataCounter: %d\n", pnpInfo->ulValidDataCounter);
wprintf(L"ulAuthTypeMsgId: 0x%08X\n", pnpInfo->ulAuthTypeMsgId);
wprintf(L"ulMode: %d\n", pnpInfo->ulMode);
wprintf(L"ulStratum: %d\n", pnpInfo->ulStratum);
wprintf(L"ulReachability: %d\n", pnpInfo->ulReachability);
wprintf(L"ulPeerPollInterval: %d\n", pnpInfo->ulPeerPollInterval);
wprintf(L"ulHostPollInterval: %d\n", pnpInfo->ulHostPollInterval);
}
//--------------------------------------------------------------------
// NOTE: this function is accessed through a hidden option, and does not need to be localized.
void PrintNtpProviderData(W32TIME_NTP_PROVIDER_DATA *pNtpProviderData) {
wprintf(L"ulSize: %d, ulError: 0x%08X, ulErrorMsgId: 0x%08X, cPeerInfo: %d\n",
pNtpProviderData->ulSize,
pNtpProviderData->ulError,
pNtpProviderData->ulErrorMsgId,
pNtpProviderData->cPeerInfo
);
for (DWORD dwIndex = 0; dwIndex < pNtpProviderData->cPeerInfo; dwIndex++) {
wprintf(L"\n");
PrintNtpPeerInfo(&(pNtpProviderData->pPeerInfo[dwIndex]));
}
}
//--------------------------------------------------------------------
HRESULT PrintStr(HANDLE hOut, WCHAR * wszBuf)
{
return MyWriteConsole(hOut, wszBuf, wcslen(wszBuf));
}
//--------------------------------------------------------------------
HRESULT Print(HANDLE hOut, WCHAR * wszFormat, ...) {
HRESULT hr;
WCHAR wszBuf[1024];
va_list vlArgs;
va_start(vlArgs, wszFormat);
// print the formatted data to our buffer:
hr=StringCchVPrintf(wszBuf, ARRAYSIZE(wszBuf), wszFormat, vlArgs);
va_end(vlArgs);
if (SUCCEEDED(hr)) {
// only print the string if our vprintf was successful:
hr = PrintStr(hOut, wszBuf);
}
return hr;
}
//--------------------------------------------------------------------
MODULEPRIVATE HRESULT PrintNtTimeAsLocalTime(HANDLE hOut, unsigned __int64 qwTime) {
HRESULT hr;
FILETIME ftLocal;
SYSTEMTIME stLocal;
unsigned int nChars;
// must be cleaned up
WCHAR * wszDate=NULL;
WCHAR * wszTime=NULL;
if (!FileTimeToLocalFileTime((FILETIME *)(&qwTime), &ftLocal)) {
_JumpLastError(hr, error, "FileTimeToLocalFileTime");
}
if (!FileTimeToSystemTime(&ftLocal, &stLocal)) {
_JumpLastError(hr, error, "FileTimeToSystemTime");
}
nChars=GetDateFormat(NULL, 0, &stLocal, NULL, NULL, 0);
if (0==nChars) {
_JumpLastError(hr, error, "GetDateFormat");
}
wszDate=(WCHAR *)LocalAlloc(LPTR, nChars*sizeof(WCHAR));
_JumpIfOutOfMemory(hr, error, wszDate);
nChars=GetDateFormat(NULL, 0, &stLocal, NULL, wszDate, nChars);
if (0==nChars) {
_JumpLastError(hr, error, "GetDateFormat");
}
nChars=GetTimeFormat(NULL, 0, &stLocal, NULL, NULL, 0);
if (0==nChars) {
_JumpLastError(hr, error, "GetTimeFormat");
}
wszTime=(WCHAR *)LocalAlloc(LPTR, nChars*sizeof(WCHAR));
_JumpIfOutOfMemory(hr, error, wszTime);
nChars=GetTimeFormat(NULL, 0, &stLocal, NULL, wszTime, nChars);
if (0==nChars) {
_JumpLastError(hr, error, "GetTimeFormat");
}
Print(hOut, L"%s %s (local time)", wszDate, wszTime);
hr=S_OK;
error:
if (NULL!=wszDate) {
LocalFree(wszDate);
}
if (NULL!=wszTime) {
LocalFree(wszTime);
}
return hr;
}
//--------------------------------------------------------------------
void PrintNtTimePeriod(HANDLE hOut, NtTimePeriod tp) {
Print(hOut, L"%02I64u.%07I64us", tp.qw/10000000,tp.qw%10000000);
}
//--------------------------------------------------------------------
void PrintNtTimeOffset(HANDLE hOut, NtTimeOffset to) {
NtTimePeriod tp;
if (to.qw<0) {
PrintStr(hOut, L"-");
tp.qw=(unsigned __int64)-to.qw;
} else {
PrintStr(hOut, L"+");
tp.qw=(unsigned __int64)to.qw;
}
PrintNtTimePeriod(hOut, tp);
}
//####################################################################
//--------------------------------------------------------------------
void PrintHelpOtherCmds(void) {
DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_OTHERCMD_HELP);
}
//--------------------------------------------------------------------
HRESULT PrintNtte(CmdArgs * pca) {
HRESULT hr;
unsigned __int64 qwTime;
HANDLE hOut;
// must be cleaned up
WCHAR * wszDate=NULL;
WCHAR * wszTime=NULL;
if (pca->nNextArg!=pca->nArgs-1) {
if (pca->nNextArg==pca->nArgs) {
LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_MISSING_PARAM);
} else {
LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_TOO_MANY_PARAMS);
}
hr=E_INVALIDARG;
_JumpError(hr, error, "(command line parsing)");
}
qwTime=wcstouI64(pca->rgwszArgs[pca->nNextArg], NULL, 0);
{
unsigned __int64 qwTemp=qwTime;
DWORD dwNanoSecs=(DWORD)(qwTemp%10000000);
qwTemp/=10000000;
DWORD dwSecs=(DWORD)(qwTemp%60);
qwTemp/=60;
DWORD dwMins=(DWORD)(qwTemp%60);
qwTemp/=60;
DWORD dwHours=(DWORD)(qwTemp%24);
DWORD dwDays=(DWORD)(qwTemp/24);
DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_NTTE, dwDays, dwHours, dwMins, dwSecs, dwNanoSecs);
}
hOut=GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE==hOut) {
_JumpLastError(hr, error, "GetStdHandle");
}
hr=PrintNtTimeAsLocalTime(hOut, qwTime);
if (FAILED(hr)) {
if (HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER)==hr) {
LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_INVALID_LOCALTIME);
} else {
_JumpError(hr, error, "PrintNtTimeAsLocalTime");
}
}
wprintf(L"\n");
hr=S_OK;
error:
if (NULL!=wszDate) {
LocalFree(wszDate);
}
if (NULL!=wszTime) {
LocalFree(wszTime);
}
return hr;
}
//--------------------------------------------------------------------
HRESULT PrintNtpte(CmdArgs * pca) {
HRESULT hr;
unsigned __int64 qwTime;
HANDLE hOut;
// must be cleaned up
WCHAR * wszDate=NULL;
WCHAR * wszTime=NULL;
if (pca->nNextArg!=pca->nArgs-1) {
if (pca->nNextArg==pca->nArgs) {
LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_MISSING_PARAM);
} else {
LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_TOO_MANY_PARAMS);
}
hr=E_INVALIDARG;
_JumpError(hr, error, "(command line parsing)");
}
qwTime=wcstouI64(pca->rgwszArgs[pca->nNextArg], NULL, 0);
{
NtpTimeEpoch teNtp={qwTime};
qwTime=NtTimeEpochFromNtpTimeEpoch(teNtp).qw;
unsigned __int64 qwTemp=qwTime;
DWORD dwNanoSecs=(DWORD)(qwTemp%10000000);
qwTemp/=10000000;
DWORD dwSecs=(DWORD)(qwTemp%60);
qwTemp/=60;
DWORD dwMins=(DWORD)(qwTemp%60);
qwTemp/=60;
DWORD dwHours=(DWORD)(qwTemp%24);
DWORD dwDays=(DWORD)(qwTemp/24);
DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_NTPTE, qwTime, dwDays, dwHours, dwMins, dwSecs, dwNanoSecs);
}
hOut=GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE==hOut) {
_JumpLastError(hr, error, "GetStdHandle")
}
hr=PrintNtTimeAsLocalTime(hOut, qwTime);
if (FAILED(hr)) {
if (HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER)==hr) {
LocalizedWPrintf(IDS_W32TM_ERRORGENERAL_INVALID_LOCALTIME);
} else {
_JumpError(hr, error, "PrintNtTimeAsLocalTime");
}
}
wprintf(L"\n");
hr=S_OK;
error:
if (NULL!=wszDate) {
LocalFree(wszDate);
}
if (NULL!=wszTime) {
LocalFree(wszTime);
}
return hr;
}
//--------------------------------------------------------------------
// NOTE: this function is accessed through a hidden option, and does not need to be localized.
HRESULT SysExpr(CmdArgs * pca) {
HRESULT hr;
unsigned __int64 qwExprDate;
HANDLE hOut;
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
hOut=GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE==hOut) {
_JumpLastError(hr, error, "GetStdHandle")
}
GetSysExpirationDate(&qwExprDate);
wprintf(L"0x%016I64X - ", qwExprDate);
if (0==qwExprDate) {
wprintf(L"no expiration date\n");
} else {
hr=PrintNtTimeAsLocalTime(hOut, qwExprDate);
_JumpIfError(hr, error, "PrintNtTimeAsLocalTime")
wprintf(L"\n");
}
hr=S_OK;
error:
return hr;
}
//--------------------------------------------------------------------
HRESULT ResyncCommand(CmdArgs * pca) {
HANDLE hTimeSlipEvent = NULL;
HRESULT hr;
WCHAR * wszComputer=NULL;
WCHAR * wszComputerDisplay;
bool bUseDefaultErrorPrinting = false;
bool bHard=true;
bool bNoWait=false;
bool bRediscover=false;
unsigned int nArgID;
DWORD dwResult;
DWORD dwSyncFlags=0;
// must be cleaned up
WCHAR * wszError=NULL;
// find out what computer to resync
if (FindArg(pca, L"computer", &wszComputer, &nArgID)) {
MarkArgUsed(pca, nArgID);
}
wszComputerDisplay=wszComputer;
if (NULL==wszComputerDisplay) {
wszComputerDisplay=L"local computer";
}
// find out if we need to use the w32tm named timeslip event to resync
if (FindArg(pca, L"event", NULL, &nArgID)) {
MarkArgUsed(pca, nArgID);
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
hTimeSlipEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, W32TIME_NAMED_EVENT_SYSTIME_NOT_CORRECT);
if (NULL == hTimeSlipEvent) {
bUseDefaultErrorPrinting = true;
_JumpLastError(hr, error, "OpenEvent");
}
if (!SetEvent(hTimeSlipEvent)) {
bUseDefaultErrorPrinting = true;
_JumpLastError(hr, error, "SetEvent");
}
} else {
// find out if we need to do a soft resync
if (FindArg(pca, L"soft", NULL, &nArgID)) {
MarkArgUsed(pca, nArgID);
dwSyncFlags = TimeSyncFlag_SoftResync;
} else if (FindArg(pca, L"update", NULL, &nArgID)) {
MarkArgUsed(pca, nArgID);
dwSyncFlags = TimeSyncFlag_UpdateAndResync;
} else if (FindArg(pca, L"rediscover", NULL, &nArgID)) {
// find out if we need to do a rediscover
MarkArgUsed(pca, nArgID);
dwSyncFlags = TimeSyncFlag_Rediscover;
} else {
dwSyncFlags = TimeSyncFlag_HardResync;
}
// find out if we don't want to wait
if (FindArg(pca, L"nowait", NULL, &nArgID)) {
MarkArgUsed(pca, nArgID);
bNoWait=true;
}
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
if (bRediscover && !bHard) {
LocalizedWPrintfCR(IDS_W32TM_WARN_IGNORE_SOFT);
}
LocalizedWPrintf2(IDS_W32TM_STATUS_SENDING_RESYNC_TO, L" %s...\n", wszComputerDisplay);
dwResult=W32TimeSyncNow(wszComputer, !bNoWait, TimeSyncFlag_ReturnResult | dwSyncFlags);
if (ResyncResult_Success==dwResult) {
LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_COMMAND_SUCCESSFUL);
} else if (ResyncResult_NoData==dwResult) {
LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_NO_TIME_DATA);
} else if (ResyncResult_StaleData==dwResult) {
LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_STALE_DATA);
} else if (ResyncResult_Shutdown==dwResult) {
LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_SHUTTING_DOWN);
} else if (ResyncResult_ChangeTooBig==dwResult) {
LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_CHANGE_TOO_BIG);
} else {
bUseDefaultErrorPrinting = true;
hr = HRESULT_FROM_WIN32(dwResult);
_JumpError(hr, error, "W32TimeSyncNow");
}
}
hr=S_OK;
error:
if (FAILED(hr)) {
HRESULT hr2 = GetSystemErrorString(hr, &wszError);
_IgnoreIfError(hr2, "GetSystemErrorString");
if (SUCCEEDED(hr2)) {
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
}
}
if (NULL!=hTimeSlipEvent) {
CloseHandle(hTimeSlipEvent);
}
if (NULL!=wszError) {
LocalFree(wszError);
}
return hr;
}
//--------------------------------------------------------------------
HRESULT Stripchart(CmdArgs * pca) {
HRESULT hr;
WCHAR * wszParam;
WCHAR * wszComputer;
bool bDataOnly=false;
unsigned int nArgID;
unsigned int nIpAddrs;
TIME_ZONE_INFORMATION timezoneinfo;
signed __int64 nFullTzBias;
DWORD dwTimeZoneMode;
DWORD dwSleepSeconds;
HANDLE hOut;
bool bDontRunForever=false;
unsigned int nSamples=0;
NtTimeEpoch teNow;
// must be cleaned up
bool bSocketLayerOpened=false;
in_addr * rgiaLocalIpAddrs=NULL;
in_addr * rgiaRemoteIpAddrs=NULL;
// find out what computer to watch
if (FindArg(pca, L"computer", &wszComputer, &nArgID)) {
MarkArgUsed(pca, nArgID);
} else {
LocalizedWPrintfCR(IDS_W32TM_ERRORPARAMETER_COMPUTER_MISSING);
hr=E_INVALIDARG;
_JumpError(hr, error, "command line parsing");
}
// find out how often to watch
if (FindArg(pca, L"period", &wszParam, &nArgID)) {
MarkArgUsed(pca, nArgID);
dwSleepSeconds=wcstoul(wszParam, NULL, 0);
if (dwSleepSeconds<1) {
dwSleepSeconds=1;
}
} else {
dwSleepSeconds=2;
}
// find out if we want a limited number of samples
if (FindArg(pca, L"samples", &wszParam, &nArgID)) {
MarkArgUsed(pca, nArgID);
bDontRunForever=true;
nSamples=wcstoul(wszParam, NULL, 0);
}
// find out if we only want to dump data
if (FindArg(pca, L"dataonly", NULL, &nArgID)) {
MarkArgUsed(pca, nArgID);
bDataOnly=true;
}
// redirect to file handled via stdout
hOut=GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE==hOut) {
_JumpLastError(hr, error, "GetStdHandle")
}
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
dwTimeZoneMode=GetTimeZoneInformation(&timezoneinfo);
if (TIME_ZONE_ID_INVALID==dwTimeZoneMode) {
_JumpLastError(hr, error, "GetTimeZoneInformation");
} else if (TIME_ZONE_ID_DAYLIGHT==dwTimeZoneMode) {
nFullTzBias=(signed __int64)(timezoneinfo.Bias+timezoneinfo.DaylightBias);
} else {
nFullTzBias=(signed __int64)(timezoneinfo.Bias+timezoneinfo.StandardBias);
}
nFullTzBias*=600000000; // convert to from minutes to 10^-7s
hr=OpenSocketLayer();
_JumpIfError(hr, error, "OpenSocketLayer");
bSocketLayerOpened=true;
hr=MyGetIpAddrs(wszComputer, &rgiaLocalIpAddrs, &rgiaRemoteIpAddrs, &nIpAddrs, NULL);
_JumpIfError(hr, error, "MyGetIpAddrs");
// write out who we are tracking
Print(hOut, L"Tracking %s [%u.%u.%u.%u].\n",
wszComputer,
rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b1, rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b2,
rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b3, rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b4);
if (bDontRunForever) {
Print(hOut, L"Collecting %u samples.\n", nSamples);
}
// Write out the current time in full, since we will be using abbreviations later.
PrintStr(hOut, L"The current time is ");
AccurateGetSystemTime(&teNow.qw);
PrintNtTimeAsLocalTime(hOut, teNow.qw);
PrintStr(hOut, L".\n");
while (false==bDontRunForever || nSamples>0) {
const DWORD c_dwTimeout=1000;
NtpPacket npPacket;
NtTimeEpoch teDestinationTimestamp;
DWORD dwSecs;
DWORD dwMins;
DWORD dwHours;
signed int nMsMin=-10000;
signed int nMsMax=10000;
unsigned int nGraphWidth=55;
AccurateGetSystemTime(&teNow.qw);
teNow.qw-=nFullTzBias;
teNow.qw/=10000000;
dwSecs=(DWORD)(teNow.qw%60);
teNow.qw/=60;
dwMins=(DWORD)(teNow.qw%60);
teNow.qw/=60;
dwHours=(DWORD)(teNow.qw%24);
if (!bDataOnly) {
Print(hOut, L"%02u:%02u:%02u ", dwHours, dwMins, dwSecs);
} else {
Print(hOut, L"%02u:%02u:%02u, ", dwHours, dwMins, dwSecs);
}
hr=MyNtpPing(&(rgiaRemoteIpAddrs[0]), c_dwTimeout, &npPacket, &teDestinationTimestamp);
if (FAILED(hr)) {
Print(hOut, L"error: 0x%08X", hr);
} else {
// calculate the offset
NtTimeEpoch teOriginateTimestamp=NtTimeEpochFromNtpTimeEpoch(npPacket.teOriginateTimestamp);
NtTimeEpoch teReceiveTimestamp=NtTimeEpochFromNtpTimeEpoch(npPacket.teReceiveTimestamp);
NtTimeEpoch teTransmitTimestamp=NtTimeEpochFromNtpTimeEpoch(npPacket.teTransmitTimestamp);
NtTimeOffset toLocalClockOffset=
(teReceiveTimestamp-teOriginateTimestamp)
+ (teTransmitTimestamp-teDestinationTimestamp);
toLocalClockOffset/=2;
// calculate the delay
NtTimeOffset toRoundtripDelay=
(teDestinationTimestamp-teOriginateTimestamp)
- (teTransmitTimestamp-teReceiveTimestamp);
if (!bDataOnly) {
PrintStr(hOut, L"d:");
PrintNtTimeOffset(hOut, toRoundtripDelay);
PrintStr(hOut, L" o:");
PrintNtTimeOffset(hOut, toLocalClockOffset);
} else {
PrintNtTimeOffset(hOut, toLocalClockOffset);
}
// draw graph
if (!bDataOnly) {
unsigned int nSize=nMsMax-nMsMin+1;
double dRatio=((double)nGraphWidth)/nSize;
signed int nPoint=(signed int)(toLocalClockOffset.qw/10000);
bool bOutOfRange=false;
if (nPoint>nMsMax) {
nPoint=nMsMax;
bOutOfRange=true;
} else if (nPoint<nMsMin) {
nPoint=nMsMin;
bOutOfRange=true;
}
unsigned int nLeftOffset=(unsigned int)((nPoint-nMsMin)*dRatio);
unsigned int nZeroOffset=(unsigned int)((0-nMsMin)*dRatio);
PrintStr(hOut, L" [");
unsigned int nIndex;
for (nIndex=0; nIndex<nGraphWidth; nIndex++) {
if (nIndex==nLeftOffset) {
if (bOutOfRange) {
PrintStr(hOut, L"@");
} else {
PrintStr(hOut, L"*");
}
} else if (nIndex==nZeroOffset) {
PrintStr(hOut, L"|");
} else {
PrintStr(hOut, L" ");
}
}
PrintStr(hOut, L"]");
} // <- end drawing graph
} // <- end if sample received
PrintStr(hOut, L"\n");
nSamples--;
if (0!=nSamples) {
Sleep(dwSleepSeconds*1000);
}
} // <- end sample collection loop
hr=S_OK;
error:
if (NULL!=rgiaLocalIpAddrs) {
LocalFree(rgiaLocalIpAddrs);
}
if (NULL!=rgiaRemoteIpAddrs) {
LocalFree(rgiaRemoteIpAddrs);
}
if (bSocketLayerOpened) {
HRESULT hr2=CloseSocketLayer();
_TeardownError(hr, hr2, "CloseSocketLayer");
}
if (FAILED(hr)) {
WCHAR * wszError;
HRESULT hr2=GetSystemErrorString(hr, &wszError);
if (FAILED(hr2)) {
_IgnoreError(hr2, "GetSystemErrorString");
} else {
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
LocalFree(wszError);
}
}
return hr;
}
//--------------------------------------------------------------------
HRESULT Config(CmdArgs * pca) {
HRESULT hr;
DWORD dwRetval;
WCHAR * wszParam;
WCHAR * wszComputer;
unsigned int nArgID;
bool bManualPeerList=false;
bool bUpdate=false;
bool bSyncFromFlags=false;
bool bLocalClockDispersion=false;
bool bReliable=false;
bool bLargePhaseOffset=false;
unsigned int nManualPeerListLenBytes=0;
DWORD dwSyncFromFlags=0;
DWORD dwLocalClockDispersion;
DWORD dwAnnounceFlags;
DWORD dwLargePhaseOffset;
// must be cleaned up
WCHAR * mwszManualPeerList=NULL;
HKEY hkLMRemote=NULL;
HKEY hkW32TimeConfig=NULL;
HKEY hkW32TimeParameters=NULL;
SC_HANDLE hSCM=NULL;
SC_HANDLE hTimeService=NULL;
// find out what computer to talk to
if (FindArg(pca, L"computer", &wszComputer, &nArgID)) {
MarkArgUsed(pca, nArgID);
} else {
// modifying local computer
wszComputer=NULL;
}
// find out if we want to notify the service
if (FindArg(pca, L"update", NULL, &nArgID)) {
MarkArgUsed(pca, nArgID);
bUpdate=true;
}
// see if they want to change the manual peer list
if (FindArg(pca, L"manualpeerlist", &wszParam, &nArgID)) {
MarkArgUsed(pca, nArgID);
nManualPeerListLenBytes=(wcslen(wszParam)+1)*sizeof(WCHAR);
mwszManualPeerList=(WCHAR *)LocalAlloc(LPTR, nManualPeerListLenBytes);
_JumpIfOutOfMemory(hr, error, mwszManualPeerList);
hr = StringCbCopy(mwszManualPeerList, nManualPeerListLenBytes, wszParam);
_JumpIfError(hr, error, "StringCbCopy");
bManualPeerList=true;
}
// see if they want to change the syncfromflags
if (FindArg(pca, L"syncfromflags", &wszParam, &nArgID)) {
MarkArgUsed(pca, nArgID);
// find keywords in the string
dwSyncFromFlags=0;
WCHAR * wszKeyword=wszParam;
bool bLastKeyword=false;
while (false==bLastKeyword) {
WCHAR * wszNext=wcschr(wszKeyword, L',');
if (NULL==wszNext) {
bLastKeyword=true;
} else {
wszNext[0]=L'\0';
wszNext++;
}
if (L'\0'==wszKeyword[0]) {
// 'empty' keyword - no changes, but can be used to sync from nowhere.
} else if (0==_wcsicmp(L"manual", wszKeyword)) {
dwSyncFromFlags|=NCSF_ManualPeerList;
} else if (0==_wcsicmp(L"domhier", wszKeyword)) {
dwSyncFromFlags|=NCSF_DomainHierarchy;
} else {
LocalizedWPrintf2(IDS_W32TM_ERRORPARAMETER_UNKNOWN_PARAMETER_SYNCFROMFLAGS, L" '%s'.\n", wszKeyword);
hr=E_INVALIDARG;
_JumpError(hr, error, "command line parsing");
}
wszKeyword=wszNext;
}
bSyncFromFlags=true;
}
// see if they want to change the local clock dispersion
if (FindArg(pca, L"localclockdispersion", &wszParam, &nArgID)) {
MarkArgUsed(pca, nArgID);
hr = my_wcstoul_safe(wszParam, 0, 16, &dwLocalClockDispersion);
if (FAILED(hr)) {
DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_BAD_NUMERIC_INPUT_VALUE, L"localclockdispersion", 0, 16);
hr = E_INVALIDARG;
_JumpError(hr, error, "Config: bad large phase offset");
}
bLocalClockDispersion=true;
}
if (FindArg(pca, L"reliable", &wszParam, &nArgID)) {
dwAnnounceFlags=0;
if (0 == _wcsicmp(L"YES", wszParam)) {
dwAnnounceFlags=Timeserv_Announce_Yes | Reliable_Timeserv_Announce_Yes;
} else if (0 == _wcsicmp(L"NO", wszParam)) {
dwAnnounceFlags=Timeserv_Announce_Auto | Reliable_Timeserv_Announce_Auto;
}
if (dwAnnounceFlags) {
MarkArgUsed(pca, nArgID);
bReliable=true;
}
}
if (FindArg(pca, L"largephaseoffset", &wszParam, &nArgID)) {
MarkArgUsed(pca, nArgID);
// Command-line tool takes argument in millis, registry value is stored in 10^-7 second units.
hr = my_wcstoul_safe(wszParam, 0, 120000, &dwLargePhaseOffset);
if (FAILED(hr)) {
DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_BAD_NUMERIC_INPUT_VALUE, L"largephaseoffset", 0, 120000);
hr = E_INVALIDARG;
_JumpError(hr, error, "Config: bad large phase offset");
}
dwLargePhaseOffset*=10000; // scale: user input (milliseconds) --> NT time (10^-7 seconds)
bLargePhaseOffset=true;
}
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
if (!bManualPeerList && !bSyncFromFlags && !bUpdate && !bLocalClockDispersion && !bReliable && !bLargePhaseOffset) {
LocalizedWPrintfCR(IDS_W32TM_ERRORCONFIG_NO_CHANGE_SPECIFIED);
hr=E_INVALIDARG;
_JumpError(hr, error, "command line parsing");
}
// make registry changes
if (bManualPeerList || bSyncFromFlags || bLocalClockDispersion || bReliable || bLargePhaseOffset) {
// open the key
dwRetval=RegConnectRegistry(wszComputer, HKEY_LOCAL_MACHINE, &hkLMRemote);
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegConnectRegistry");
}
// set "w32time\parameters" reg values
if (bManualPeerList || bSyncFromFlags) {
dwRetval=RegOpenKey(hkLMRemote, wszW32TimeRegKeyParameters, &hkW32TimeParameters);
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegOpenKey");
}
if (bManualPeerList) {
dwRetval=RegSetValueEx(hkW32TimeParameters, wszW32TimeRegValueNtpServer, 0, REG_SZ, (BYTE *)mwszManualPeerList, nManualPeerListLenBytes);
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegSetValueEx");
}
}
if (bSyncFromFlags) {
LPWSTR pwszType;
switch (dwSyncFromFlags) {
case NCSF_NoSync: pwszType = W32TM_Type_NoSync; break;
case NCSF_ManualPeerList: pwszType = W32TM_Type_NTP; break;
case NCSF_DomainHierarchy: pwszType = W32TM_Type_NT5DS; break;
case NCSF_ManualAndDomhier: pwszType = W32TM_Type_AllSync; break;
default:
hr = E_NOTIMPL;
_JumpError(hr, error, "SyncFromFlags not supported.");
}
dwRetval=RegSetValueEx(hkW32TimeParameters, wszW32TimeRegValueType, 0, REG_SZ, (BYTE *)pwszType, (wcslen(pwszType)+1) * sizeof(WCHAR));
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegSetValueEx");
}
}
}
if (bLocalClockDispersion || bReliable || bLargePhaseOffset) {
dwRetval=RegOpenKey(hkLMRemote, wszW32TimeRegKeyConfig, &hkW32TimeConfig);
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegOpenKey");
}
if (bLocalClockDispersion) {
dwRetval=RegSetValueEx(hkW32TimeConfig, wszW32TimeRegValueLocalClockDispersion, 0, REG_DWORD, (BYTE *)&dwLocalClockDispersion, sizeof(dwLocalClockDispersion));
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegSetValueEx");
}
}
if (bReliable) {
dwRetval=RegSetValueEx(hkW32TimeConfig, wszW32TimeRegValueAnnounceFlags, 0, REG_DWORD, (BYTE *)&dwAnnounceFlags, sizeof(dwAnnounceFlags));
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegSetValueEx");
}
}
if (bLargePhaseOffset) {
dwRetval=RegSetValueEx(hkW32TimeConfig, wszW32TimeRegValueLargePhaseOffset, 0, REG_DWORD, (BYTE *)&dwLargePhaseOffset, sizeof(dwLargePhaseOffset));
if (ERROR_SUCCESS!=dwRetval) {
hr=HRESULT_FROM_WIN32(dwRetval);
_JumpError(hr, error, "RegSetValueEx");
}
}
}
}
// send service message
if (bUpdate) {
SERVICE_STATUS servicestatus;
hSCM=OpenSCManager(wszComputer, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT);
if (NULL==hSCM) {
_JumpLastError(hr, error, "OpenSCManager");
}
hTimeService=OpenService(hSCM, L"w32time", SERVICE_PAUSE_CONTINUE);
if (NULL==hTimeService) {
_JumpLastError(hr, error, "OpenService");
}
if (!ControlService(hTimeService, SERVICE_CONTROL_PARAMCHANGE, &servicestatus)) {
_JumpLastError(hr, error, "ControlService");
}
}
hr=S_OK;
error:
if (NULL!=mwszManualPeerList) {
LocalFree(mwszManualPeerList);
}
if (NULL!=hkW32TimeConfig) {
RegCloseKey(hkW32TimeConfig);
}
if (NULL!=hkW32TimeParameters) {
RegCloseKey(hkW32TimeParameters);
}
if (NULL!=hkLMRemote) {
RegCloseKey(hkLMRemote);
}
if (NULL!=hTimeService) {
CloseServiceHandle(hTimeService);
}
if (NULL!=hSCM) {
CloseServiceHandle(hSCM);
}
if (FAILED(hr) && E_INVALIDARG!=hr) {
WCHAR * wszError;
HRESULT hr2=GetSystemErrorString(hr, &wszError);
if (FAILED(hr2)) {
_IgnoreError(hr2, "GetSystemErrorString");
} else {
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
LocalFree(wszError);
}
} else if (S_OK==hr) {
LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_COMMAND_SUCCESSFUL);
}
return hr;
}
//--------------------------------------------------------------------
// NOTE: this function is accessed through a hidden option, and does not need to be localized.
HRESULT TestInterface(CmdArgs * pca) {
HRESULT hr;
WCHAR * wszComputer=NULL;
WCHAR * wszComputerDisplay;
unsigned int nArgID;
DWORD dwResult;
unsigned long ulBits;
void (* pfnW32TimeVerifyJoinConfig)(void);
void (* pfnW32TimeVerifyUnjoinConfig)(void);
// must be cleaned up
WCHAR * wszError=NULL;
HMODULE hmW32Time=NULL;
// check for gnsb (get netlogon service bits)
if (true==CheckNextArg(pca, L"gnsb", NULL)) {
// find out what computer to resync
if (FindArg(pca, L"computer", &wszComputer, &nArgID)) {
MarkArgUsed(pca, nArgID);
}
wszComputerDisplay=wszComputer;
if (NULL==wszComputerDisplay) {
wszComputerDisplay=L"local computer";
}
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
LocalizedWPrintf2(IDS_W32TM_STATUS_CALLING_GETNETLOGONBITS_ON, L" %s.\n", wszComputerDisplay);
dwResult=W32TimeGetNetlogonServiceBits(wszComputer, &ulBits);
if (S_OK==dwResult) {
wprintf(L"Bits: 0x%08X\n", ulBits);
} else {
hr=GetSystemErrorString(HRESULT_FROM_WIN32(dwResult), &wszError);
_JumpIfError(hr, error, "GetSystemErrorString");
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
}
// check for vjc (verify join config)
} else if (true==CheckNextArg(pca, L"vjc", NULL)) {
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
LocalizedWPrintfCR(IDS_W32TM_STATUS_CALLING_JOINCONFIG);
hmW32Time=LoadLibrary(wszDLLNAME);
if (NULL==hmW32Time) {
_JumpLastError(hr, vjcerror, "LoadLibrary");
}
pfnW32TimeVerifyJoinConfig=(void (*)(void))GetProcAddress(hmW32Time, "W32TimeVerifyJoinConfig");
if (NULL==pfnW32TimeVerifyJoinConfig) {
_JumpLastErrorStr(hr, vjcerror, "GetProcAddress", L"W32TimeVerifyJoinConfig");
}
_BeginTryWith(hr) {
pfnW32TimeVerifyJoinConfig();
} _TrapException(hr);
_JumpIfError(hr, vjcerror, "pfnW32TimeVerifyJoinConfig");
hr=S_OK;
vjcerror:
if (FAILED(hr)) {
HRESULT hr2=GetSystemErrorString(hr, &wszError);
if (FAILED(hr2)) {
_IgnoreError(hr2, "GetSystemErrorString");
} else {
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
}
goto error;
}
// check for vuc (verify unjoin config)
} else if (true==CheckNextArg(pca, L"vuc", NULL)) {
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
LocalizedWPrintfCR(IDS_W32TM_STATUS_CALLING_UNJOINCONFIG);
hmW32Time=LoadLibrary(wszDLLNAME);
if (NULL==hmW32Time) {
_JumpLastError(hr, vucerror, "LoadLibrary");
}
pfnW32TimeVerifyUnjoinConfig=(void (*)(void))GetProcAddress(hmW32Time, "W32TimeVerifyUnjoinConfig");
if (NULL==pfnW32TimeVerifyUnjoinConfig) {
_JumpLastErrorStr(hr, vucerror, "GetProcAddress", L"W32TimeVerifyJoinConfig");
}
_BeginTryWith(hr) {
pfnW32TimeVerifyUnjoinConfig();
} _TrapException(hr);
_JumpIfError(hr, vucerror, "pfnW32TimeVerifyUnjoinConfig");
hr=S_OK;
vucerror:
if (FAILED(hr)) {
HRESULT hr2=GetSystemErrorString(hr, &wszError);
if (FAILED(hr2)) {
_IgnoreError(hr2, "GetSystemErrorString");
} else {
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
}
goto error;
}
// error out appropriately
} else if (true==CheckNextArg(pca, L"qps", NULL)) {
// find out what computer to resync
if (FindArg(pca, L"computer", &wszComputer, &nArgID)) {
MarkArgUsed(pca, nArgID);
}
wszComputerDisplay=wszComputer;
if (NULL==wszComputerDisplay) {
wszComputerDisplay=L"local computer";
}
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
//LocalizedWPrintf2(IDS_W32TM_STATUS_CALLING_GETNETLOGONBITS_ON, L" %s.\n", wszComputerDisplay);
{
W32TIME_NTP_PROVIDER_DATA *ProviderInfo = NULL;
dwResult=W32TimeQueryNTPProviderStatus(wszComputer, 0, L"NtpClient", &ProviderInfo);
if (S_OK==dwResult) {
PrintNtpProviderData(ProviderInfo);
} else {
hr=GetSystemErrorString(HRESULT_FROM_WIN32(dwResult), &wszError);
_JumpIfError(hr, error, "GetSystemErrorString");
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
}
}
} else {
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
LocalizedWPrintf(IDS_W32TM_ERRORGENERAL_NOINTERFACE);
hr=E_INVALIDARG;
_JumpError(hr, error, "command line parsing");
}
hr=S_OK;
error:
if (NULL!=hmW32Time) {
FreeLibrary(hmW32Time);
}
if (NULL!=wszError) {
LocalFree(wszError);
}
return hr;
}
//--------------------------------------------------------------------
HRESULT ShowTimeZone(CmdArgs * pca) {
DWORD dwTimeZoneID;
HRESULT hr;
LPWSTR pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED = NULL;
LPWSTR pwsz_IDS_W32TM_TIMEZONE_CURRENT_TIMEZONE = NULL;
LPWSTR pwsz_IDS_W32TM_TIMEZONE_DAYLIGHT = NULL;
LPWSTR pwsz_IDS_W32TM_TIMEZONE_STANDARD = NULL;
LPWSTR pwsz_IDS_W32TM_TIMEZONE_UNKNOWN = NULL;
LPWSTR wszDaylightDate = NULL;
LPWSTR wszStandardDate = NULL;
LPWSTR wszTimeZoneId = NULL;
TIME_ZONE_INFORMATION tzi;
// Load the strings we'll need
struct LocalizedStrings {
UINT id;
LPWSTR *ppwsz;
} rgStrings[] = {
{ IDS_W32TM_SIMPLESTRING_UNSPECIFIED, &pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED },
{ IDS_W32TM_TIMEZONE_CURRENT_TIMEZONE, &pwsz_IDS_W32TM_TIMEZONE_CURRENT_TIMEZONE },
{ IDS_W32TM_TIMEZONE_DAYLIGHT, &pwsz_IDS_W32TM_TIMEZONE_DAYLIGHT },
{ IDS_W32TM_TIMEZONE_STANDARD, &pwsz_IDS_W32TM_TIMEZONE_STANDARD },
{ IDS_W32TM_TIMEZONE_UNKNOWN, &pwsz_IDS_W32TM_TIMEZONE_UNKNOWN }
};
for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) {
if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, rgStrings[dwIndex].id, rgStrings[dwIndex].ppwsz)) {
hr = HRESULT_FROM_WIN32(GetLastError());
_JumpError(hr, error, "WriteMsg");
}
}
hr=VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
dwTimeZoneID=GetTimeZoneInformation(&tzi);
switch (dwTimeZoneID)
{
case TIME_ZONE_ID_DAYLIGHT: wszTimeZoneId = pwsz_IDS_W32TM_TIMEZONE_DAYLIGHT; break;
case TIME_ZONE_ID_STANDARD: wszTimeZoneId = pwsz_IDS_W32TM_TIMEZONE_STANDARD; break;
case TIME_ZONE_ID_UNKNOWN: wszTimeZoneId = pwsz_IDS_W32TM_TIMEZONE_UNKNOWN; break;
default:
hr = HRESULT_FROM_WIN32(GetLastError());
LocalizedWPrintfCR(IDS_W32TM_ERRORTIMEZONE_INVALID);
_JumpError(hr, error, "GetTimeZoneInformation")
}
// Construct a string representing the "StandardDate" field of the TimeZoneInformation:
if (0==tzi.StandardDate.wMonth) {
wszStandardDate = pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED;
} else if (tzi.StandardDate.wMonth>12 || tzi.StandardDate.wDay>5 ||
tzi.StandardDate.wDay<1 || tzi.StandardDate.wDayOfWeek>6) {
if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_INVALID_TZ_DATE, &wszStandardDate,
tzi.StandardDate.wMonth, tzi.StandardDate.wDay, tzi.StandardDate.wDayOfWeek)) {
_JumpLastError(hr, error, "WriteMsg");
}
} else {
if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_VALID_TZ_DATE, &wszStandardDate,
tzi.StandardDate.wMonth, tzi.StandardDate.wDay, tzi.StandardDate.wDayOfWeek)) {
_JumpLastError(hr, error, "WriteMsg");
}
}
// Construct a string representing the "DaylightDate" field of the TimeZoneInformation:
if (0==tzi.DaylightDate.wMonth) {
wszDaylightDate = pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED;
} else if (tzi.DaylightDate.wMonth>12 || tzi.DaylightDate.wDay>5 ||
tzi.DaylightDate.wDay<1 || tzi.DaylightDate.wDayOfWeek>6) {
if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_INVALID_TZ_DATE, &wszDaylightDate,
tzi.DaylightDate.wMonth, tzi.DaylightDate.wDay, tzi.DaylightDate.wDayOfWeek)) {
_JumpLastError(hr, error, "WriteMsg");
}
} else {
if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_VALID_TZ_DATE, &wszDaylightDate,
tzi.DaylightDate.wMonth, tzi.DaylightDate.wDay, tzi.DaylightDate.wDayOfWeek)) {
_JumpLastError(hr, error, "WriteMsg");
}
}
DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_TIMEZONE_INFO,
wszTimeZoneId, tzi.Bias,
tzi.StandardName, tzi.StandardBias, wszStandardDate,
tzi.DaylightName, tzi.DaylightBias, wszDaylightDate);
hr=S_OK;
error:
// Free our localized strings:
for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) {
if (NULL != *(rgStrings[dwIndex].ppwsz)) { LocalFree(*(rgStrings[dwIndex].ppwsz)); }
}
if (NULL != wszDaylightDate) {
LocalFree(wszDaylightDate);
}
if (NULL != wszStandardDate) {
LocalFree(wszStandardDate);
}
if (FAILED(hr) && E_INVALIDARG!=hr) {
WCHAR * wszError;
HRESULT hr2=GetSystemErrorString(hr, &wszError);
if (FAILED(hr2)) {
_IgnoreError(hr2, "GetSystemErrorString");
} else {
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
LocalFree(wszError);
}
}
return hr;
}
//--------------------------------------------------------------------
HRESULT PrintRegLine(IN HANDLE hOut,
IN DWORD dwValueNameOffset,
IN LPWSTR pwszValueName,
IN DWORD dwValueTypeOffset,
IN LPWSTR pwszValueType,
IN DWORD dwValueDataOffset,
IN LPWSTR pwszValueData)
{
DWORD dwCurrentOffset = 0;
HRESULT hr;
LPWSTR pwszCurrent;
LPWSTR pwszEnd;
WCHAR pwszLine[1024];
WCHAR wszNULL[] = L"<NULL>";
if (NULL == pwszValueName) { pwszValueName = &wszNULL[0]; }
if (NULL == pwszValueType) { pwszValueType = &wszNULL[0]; }
if (NULL == pwszValueData) { pwszValueData = &wszNULL[0]; }
pwszEnd = pwszLine + ARRAYSIZE(pwszLine); // point to the end of the line buffer
pwszCurrent = &pwszLine[0]; // point to the beginning of the line buffer
//
// Use the safe string functions to populate the line buffer
//
hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, pwszValueName);
_JumpIfError(hr, error, "StringCchCopy");
pwszCurrent += wcslen(pwszCurrent);
// Insert enough spaces to align the "type" field with the type offset
for (DWORD dwIndex = pwszCurrent-pwszLine; dwIndex < dwValueTypeOffset; dwIndex++) {
hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, L" ");
_JumpIfError(hr, error, "StringCchCopy");
pwszCurrent++;
}
hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, pwszValueType);
_JumpIfError(hr, error, "StringCchCopy");
pwszCurrent += wcslen(pwszCurrent);
// Insert enoughs spaces to align the "data" field with the data offset
for (DWORD dwIndex = pwszCurrent-pwszLine; dwIndex < dwValueDataOffset; dwIndex++) {
hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, L" ");
_JumpIfError(hr, error, "StringCchCopy");
pwszCurrent++;
}
hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, pwszValueData);
_JumpIfError(hr, error, "StringCchCopy");
pwszCurrent += wcslen(pwszCurrent);
hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, L"\n");
_JumpIfError(hr, error, "StringCchCopy");
// Finally, display the reg line
PrintStr(hOut, &pwszLine[0]);
hr = S_OK;
error:
return hr;
}
HRESULT DumpReg(CmdArgs * pca)
{
BOOL fFreeRegData = FALSE; // Used to indicate whether we've dymanically allocated pwszRegData
BOOL fLoggedFailure = FALSE;
DWORD dwMaxValueNameLen = 0; // Size in TCHARs.
DWORD dwMaxValueDataLen = 0; // Size in bytes.
DWORD dwNumValues = 0;
DWORD dwRetval = 0;
DWORD dwType = 0;
DWORD dwValueNameLen = 0; // Size in TCHARs.
DWORD dwValueDataLen = 0; // Size in bytes.
HANDLE hOut = NULL;
HKEY hKeyConfig = NULL;
HKEY HKLM = HKEY_LOCAL_MACHINE;
HKEY HKLMRemote = NULL;
HRESULT hr = E_FAIL;
LPWSTR pwszValueName = NULL;
LPBYTE pbValueData = NULL;
LPWSTR pwszSubkeyName = NULL;
LPWSTR pwszComputerName = NULL;
LPWSTR pwszRegType = NULL;
LPWSTR pwszRegData = NULL;
unsigned int nArgID = 0;
WCHAR rgwszKeyName[1024];
// Variables to display formatted output:
DWORD dwCurrentOffset = 0;
DWORD dwValueNameOffset = 0;
DWORD dwValueTypeOffset = 0;
DWORD dwValueDataOffset = 0;
// Localized strings:
LPWSTR pwsz_VALUENAME = NULL;
LPWSTR pwsz_VALUETYPE = NULL;
LPWSTR pwsz_VALUEDATA = NULL;
LPWSTR pwsz_REGTYPE_BINARY = NULL;
LPWSTR pwsz_REGTYPE_DWORD = NULL;
LPWSTR pwsz_REGTYPE_SZ = NULL;
LPWSTR pwsz_REGTYPE_MULTISZ = NULL;
LPWSTR pwsz_REGTYPE_EXPANDSZ = NULL;
LPWSTR pwsz_REGTYPE_UNKNOWN = NULL;
LPWSTR pwsz_REGDATA_UNPARSABLE = NULL;
// Load the strings we'll need
struct LocalizedStrings {
UINT id;
LPWSTR *ppwsz;
} rgStrings[] = {
{ IDS_W32TM_VALUENAME, &pwsz_VALUENAME },
{ IDS_W32TM_VALUETYPE, &pwsz_VALUETYPE },
{ IDS_W32TM_VALUEDATA, &pwsz_VALUEDATA },
{ IDS_W32TM_REGTYPE_BINARY, &pwsz_REGTYPE_BINARY },
{ IDS_W32TM_REGTYPE_DWORD, &pwsz_REGTYPE_DWORD },
{ IDS_W32TM_REGTYPE_SZ, &pwsz_REGTYPE_SZ },
{ IDS_W32TM_REGTYPE_MULTISZ, &pwsz_REGTYPE_MULTISZ },
{ IDS_W32TM_REGTYPE_EXPANDSZ, &pwsz_REGTYPE_EXPANDSZ },
{ IDS_W32TM_REGTYPE_UNKNOWN, &pwsz_REGTYPE_UNKNOWN },
{ IDS_W32TM_REGDATA_UNPARSABLE, &pwsz_REGDATA_UNPARSABLE }
};
for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) {
if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, rgStrings[dwIndex].id, rgStrings[dwIndex].ppwsz)) {
hr = HRESULT_FROM_WIN32(GetLastError());
_JumpError(hr, error, "WriteMsg");
}
}
hr = StringCchCopy(&rgwszKeyName[0], ARRAYSIZE(rgwszKeyName), wszW32TimeRegKeyRoot);
_JumpIfError(hr, error, "StringCchCopy");
if (true==FindArg(pca, L"subkey", &pwszSubkeyName, &nArgID)) {
MarkArgUsed(pca, nArgID);
if (NULL == pwszSubkeyName) {
LocalizedWPrintfCR(IDS_W32TM_ERRORDUMPREG_NO_SUBKEY_SPECIFIED);
fLoggedFailure = TRUE;
hr = E_INVALIDARG;
_JumpError(hr, error, "command line parsing");
}
hr = StringCchCat(&rgwszKeyName[0], ARRAYSIZE(rgwszKeyName), L"\\");
_JumpIfError(hr, error, "StringCchCopy");
hr = StringCchCat(&rgwszKeyName[0], ARRAYSIZE(rgwszKeyName), pwszSubkeyName);
_JumpIfError(hr, error, "StringCchCopy");
}
if (true==FindArg(pca, L"computer", &pwszComputerName, &nArgID)) {
MarkArgUsed(pca, nArgID);
dwRetval = RegConnectRegistry(pwszComputerName, HKEY_LOCAL_MACHINE, &HKLMRemote);
if (ERROR_SUCCESS != dwRetval) {
hr = HRESULT_FROM_WIN32(dwRetval);
_JumpErrorStr(hr, error, "RegConnectRegistry", L"HKEY_LOCAL_MACHINE");
}
HKLM = HKLMRemote;
}
hr = VerifyAllArgsUsed(pca);
_JumpIfError(hr, error, "VerifyAllArgsUsed");
dwRetval = RegOpenKeyEx(HKLM, rgwszKeyName, 0, KEY_QUERY_VALUE, &hKeyConfig);
if (ERROR_SUCCESS != dwRetval) {
hr = HRESULT_FROM_WIN32(dwRetval);
_JumpErrorStr(hr, error, "RegOpenKeyEx", rgwszKeyName);
}
dwRetval = RegQueryInfoKey
(hKeyConfig,
NULL, // class buffer
NULL, // size of class buffer
NULL, // reserved
NULL, // number of subkeys
NULL, // longest subkey name
NULL, // longest class string
&dwNumValues, // number of value entries
&dwMaxValueNameLen, // longest value name
&dwMaxValueDataLen, // longest value data
NULL,
NULL
);
if (ERROR_SUCCESS != dwRetval) {
hr = HRESULT_FROM_WIN32(dwRetval);
_JumpErrorStr(hr, error, "RegQueryInfoKey", rgwszKeyName);
} else if (0 == dwNumValues) {
hr = HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS);
_JumpErrorStr(hr, error, "RegQueryInfoKey", rgwszKeyName);
}
dwMaxValueNameLen += sizeof(WCHAR); // Include space for NULL character
pwszValueName = (LPWSTR)LocalAlloc(LPTR, dwMaxValueNameLen * sizeof(WCHAR));
_JumpIfOutOfMemory(hr, error, pwszValueName);
pbValueData = (LPBYTE)LocalAlloc(LPTR, dwMaxValueDataLen);
_JumpIfOutOfMemory(hr, error, pbValueData);
dwValueNameOffset = 0;
dwValueTypeOffset = dwValueNameOffset + dwMaxValueNameLen + 3;
dwValueDataOffset += dwValueTypeOffset + 20;
// Print table header:
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE==hOut) {
_JumpLastError(hr, error, "GetStdHandle");
}
PrintStr(hOut, L"\n");
PrintRegLine(hOut, dwValueNameOffset, pwsz_VALUENAME, dwValueTypeOffset, pwsz_VALUETYPE, dwValueDataOffset, pwsz_VALUEDATA);
// Next line:
dwCurrentOffset = dwValueNameOffset;
for (DWORD dwIndex = dwCurrentOffset; dwIndex < (dwValueDataOffset + wcslen(pwsz_VALUEDATA) + 3); dwIndex++) {
PrintStr(hOut, L"-");
}
PrintStr(hOut, L"\n\n");
for (DWORD dwIndex = 0; dwIndex < dwNumValues; dwIndex++) {
dwValueNameLen = dwMaxValueNameLen;
dwValueDataLen = dwMaxValueDataLen;
memset(reinterpret_cast<LPBYTE>(pwszValueName), 0, dwMaxValueNameLen * sizeof(WCHAR));
memset(pbValueData, 0, dwMaxValueDataLen);
dwRetval = RegEnumValue
(hKeyConfig, // handle to key to query
dwIndex, // index of value to query
pwszValueName, // value buffer
&dwValueNameLen, // size of value buffer (in TCHARs)
NULL, // reserved
&dwType, // type buffer
pbValueData, // data buffer
&dwValueDataLen // size of data buffer
);
if (ERROR_SUCCESS != dwRetval) {
hr = HRESULT_FROM_WIN32(dwRetval);
_JumpErrorStr(hr, error, "RegEnumValue", wszW32TimeRegKeyConfig);
}
_Verify(dwValueNameLen <= dwMaxValueNameLen, hr, error);
_Verify(dwValueDataLen <= dwMaxValueDataLen, hr, error);
{
switch (dwType) {
case REG_DWORD:
{
WCHAR rgwszDwordData[20];
// Ensure that the returned data buffer is large enough to contain a DWORD:
_Verify(dwValueDataLen >= sizeof(long), hr, error);
_ltow(*(reinterpret_cast<long *>(pbValueData)), rgwszDwordData, 10);
pwszRegType = pwsz_REGTYPE_DWORD;
pwszRegData = &rgwszDwordData[0];
}
break;
case REG_MULTI_SZ:
{
DWORD cbMultiSzData = 0;
WCHAR wszDelimiter[] = { L'\0', L'\0', L'\0' };
LPWSTR pwsz;
// calculate the size of the string buffer needed to contain the string data for this MULTI_SZ
for (pwsz = (LPWSTR)pbValueData; L'\0' != *pwsz; pwsz += wcslen(pwsz)+1) {
cbMultiSzData += sizeof(WCHAR)*(wcslen(pwsz)+1);
cbMultiSzData += sizeof(WCHAR)*2; // include space for delimiter
}
cbMultiSzData += sizeof(WCHAR); // include space for NULL-termination char
// allocate the buffer
pwszRegData = (LPWSTR)LocalAlloc(LPTR, cbMultiSzData);
_JumpIfOutOfMemory(hr, error, pwszRegData);
fFreeRegData = TRUE;
for (pwsz = (LPWSTR)pbValueData; L'\0' != *pwsz; pwsz += wcslen(pwsz)+1) {
hr = StringCbCat(pwszRegData, cbMultiSzData, wszDelimiter);
_JumpIfError(hr, error, "StringCbCat");
hr = StringCbCat(pwszRegData, cbMultiSzData, pwsz);
_JumpIfError(hr, error, "StringCbCat");
wszDelimiter[0] = L','; wszDelimiter[1] = L' ';
}
pwszRegType = pwsz_REGTYPE_MULTISZ;
}
break;
case REG_EXPAND_SZ:
{
pwszRegType = pwsz_REGTYPE_EXPANDSZ;
pwszRegData = reinterpret_cast<WCHAR *>(pbValueData);
}
break;
case REG_SZ:
{
pwszRegType = pwsz_REGTYPE_SZ;
pwszRegData = reinterpret_cast<WCHAR *>(pbValueData);
}
break;
case REG_BINARY:
{
DWORD ccRegData = (2*dwValueDataLen);
pwszRegType = pwsz_REGTYPE_BINARY;
// Allocate 2 characters per each byte of the binary data.
pwszRegData = (LPWSTR)LocalAlloc(LPTR, sizeof(WCHAR)*(ccRegData+1));
_JumpIfOutOfMemory(hr, error, pwszRegData);
fFreeRegData = TRUE;
LPBYTE pb = pbValueData;
for (LPWSTR pwsz = pwszRegData; pwsz < pwsz+ccRegData; ) {
hr = StringCchPrintf(pwsz, ccRegData+1, L"%02X", *pb);
_JumpIfError(hr, error, "StringCchPrintf");
pwsz += 2;
ccRegData -= 2;
pb++;
}
}
break;
default:
// Unrecognized reg type...
pwszRegType = pwsz_REGTYPE_UNKNOWN;
pwszRegData = pwsz_REGDATA_UNPARSABLE;
}
PrintRegLine(hOut, dwValueNameOffset, pwszValueName, dwValueTypeOffset, pwszRegType, dwValueDataOffset, pwszRegData);
if (fFreeRegData) {
LocalFree(pwszRegData);
fFreeRegData = FALSE;
}
pwszRegData = NULL;
}
}
PrintStr(hOut, L"\n");
hr = S_OK;
error:
// Free our localized strings:
for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) {
if (NULL != *(rgStrings[dwIndex].ppwsz)) { LocalFree(*(rgStrings[dwIndex].ppwsz)); }
}
if (NULL != hKeyConfig) { RegCloseKey(hKeyConfig); }
if (NULL != HKLMRemote) { RegCloseKey(HKLMRemote); }
if (NULL != pwszValueName) { LocalFree(pwszValueName); }
if (NULL != pbValueData) { LocalFree(pbValueData); }
if (fFreeRegData && NULL != pwszRegData) {
LocalFree(pwszRegData);
}
if (FAILED(hr) && !fLoggedFailure) {
WCHAR * wszError;
HRESULT hr2=GetSystemErrorString(hr, &wszError);
if (FAILED(hr2)) {
_IgnoreError(hr2, "GetSystemErrorString");
} else {
LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError);
LocalFree(wszError);
}
}
return hr;
}
| 62,837 | 22,973 |
#include "MainWindow.h"
#include <QDebug>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QSettings>
#include <QSortFilterProxyModel>
#include "LVGLDialog.h"
#include "LVGLFontData.h"
#include "LVGLFontDialog.h"
#include "LVGLHelper.h"
#include "LVGLItem.h"
#include "LVGLNewDialog.h"
#include "LVGLObjectModel.h"
#include "LVGLProject.h"
#include "LVGLPropertyModel.h"
#include "LVGLSimulator.h"
#include "LVGLStyleModel.h"
#include "LVGLWidgetListView.h"
#include "LVGLWidgetModel.h"
#include "LVGLWidgetModelDisplay.h"
#include "LVGLWidgetModelInput.h"
#include "ListDelegate.h"
#include "ListViewItem.h"
#include "TabWidget.h"
#include "lvgl/lvgl.h"
#include "ui_MainWindow.h"
#include "widgets/LVGLWidgets.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
m_ui(new Ui::MainWindow),
m_zoom_slider(new QSlider(Qt::Horizontal)),
m_project(nullptr),
m_maxFileNr(5),
m_curSimulation(nullptr),
m_proxyModel(nullptr),
m_objectModel(nullptr),
m_proxyModelDPW(nullptr),
m_proxyModelIPW(nullptr),
m_widgetModel(nullptr),
m_widgetModelDPW(nullptr),
m_widgetModelIPW(nullptr),
m_filter(nullptr),
m_curTabWIndex(-1),
m_frun(true) {
m_ui->setupUi(this);
m_ui->style_tree->setStyleSheet(
"QTreeView::item{border:1px solid "
"#f2f2f2;}");
m_ui->property_tree->setStyleSheet(
"QTreeView::item{border:1px solid "
"#f2f2f2;}");
m_propertyModel = new LVGLPropertyModel();
m_ld1 = new ListDelegate(m_ui->list_widgets->getlistview());
m_ld2 = new ListDelegate(m_ui->list_widgets_2->getlistview());
m_ld3 = new ListDelegate(m_ui->list_widgets_3->getlistview());
m_ui->property_tree->setModel(m_propertyModel);
m_ui->property_tree->setItemDelegate(new LVGLPropertyDelegate);
m_ui->button_remove_image->setEnabled(false);
m_ui->button_remove_font->setEnabled(false);
m_zoom_slider->setRange(-2, 2);
m_ui->statusbar->addPermanentWidget(m_zoom_slider);
m_styleModel = new LVGLStyleModel;
connect(m_styleModel, &LVGLStyleModel::styleChanged, this,
&MainWindow::styleChanged);
m_ui->style_tree->setModel(m_styleModel);
m_ui->style_tree->setItemDelegate(
new LVGLStyleDelegate(m_styleModel->styleBase()));
m_ui->style_tree->expandAll();
connect(m_ui->action_new, &QAction::triggered, this,
&MainWindow::openNewProject);
// recent configurations
QAction *recentFileAction = nullptr;
for (int i = 0; i < m_maxFileNr; i++) {
recentFileAction = new QAction(this);
recentFileAction->setVisible(false);
connect(recentFileAction, &QAction::triggered, this,
&MainWindow::loadRecent);
m_recentFileActionList.append(recentFileAction);
m_ui->menu_resent_filess->addAction(recentFileAction);
}
updateRecentActionList();
// add style editor dock to property dock and show the property dock
tabifyDockWidget(m_ui->PropertyEditor, m_ui->ObjecInspector);
m_ui->PropertyEditor->raise();
m_ui->StyleEditor->raise();
// add font editor dock to image dock and show the image dock
tabifyDockWidget(m_ui->ImageEditor, m_ui->FontEditor);
m_ui->ImageEditor->raise();
m_liststate << LV_STATE_DEFAULT << LV_STATE_CHECKED << LV_STATE_FOCUSED
<< LV_STATE_EDITED << LV_STATE_HOVERED << LV_STATE_PRESSED
<< LV_STATE_DISABLED;
connect(m_ui->tabWidget, &QTabWidget::currentChanged, this,
&MainWindow::tabChanged);
// initcodemap();
// initNewWidgets();
LVGLHelper::getInstance().setMainW(this);
}
MainWindow::~MainWindow() { delete m_ui; }
LVGLSimulator *MainWindow::simulator() const { return m_curSimulation; }
void MainWindow::updateProperty() {
LVGLObject *o = m_curSimulation->selectedObject();
if (o == nullptr) return;
LVGLProperty *p = o->widgetClass()->property("Geometry");
if (p == nullptr) return;
for (int i = 0; i < p->count(); ++i) {
auto index = m_propertyModel->propIndex(p->child(i), o->widgetClass(), 1);
emit m_propertyModel->dataChanged(index, index);
}
}
void MainWindow::setCurrentObject(LVGLObject *obj) {
m_ui->combo_style->clear();
m_ui->combo_state->setCurrentIndex(0);
m_propertyModel->setObject(obj);
if (obj) {
auto parts = obj->widgetClass()->parts();
m_styleModel->setPart(parts[0]);
m_styleModel->setState(LV_STATE_DEFAULT);
m_styleModel->setObj(obj->obj());
m_ui->combo_style->addItems(obj->widgetClass()->styles());
m_styleModel->setStyle(obj->style(0, 0),
obj->widgetClass()->editableStyles(0));
updateItemDelegate();
} else {
m_styleModel->setStyle(nullptr);
}
}
void MainWindow::styleChanged() {
LVGLObject *obj = m_curSimulation->selectedObject();
if (obj) {
int index = m_ui->combo_style->currentIndex();
obj->widgetClass()->setStyle(obj->obj(), index, obj->style(index));
// refresh_children_style(obj->obj());
// lv_obj_refresh_style(obj->obj());
}
}
void MainWindow::loadRecent() {
QAction *action = qobject_cast<QAction *>(QObject::sender());
if (action == nullptr) return;
loadProject(action->data().toString());
}
void MainWindow::openNewProject() {
LVGLNewDialog dialog(this);
if (dialog.exec() == QDialog::Accepted) {
if (m_curSimulation != nullptr) revlvglConnect();
TabWidget *tabw = new TabWidget(dialog.selectedName(), this);
lvgl = tabw->getCore();
const auto res = dialog.selectedResolution();
lvgl->init(res.width(), res.height());
if (m_frun) {
m_frun = false;
initNewWidgets();
initcodemap();
}
lvgl->initw(m_widgets);
lvgl->initwDP(m_widgetsDisplayW);
lvgl->initwIP(m_widgetsInputW);
m_coreRes[lvgl] = res;
m_listTabW.push_back(tabw);
m_ui->tabWidget->addTab(tabw, tabw->getName());
m_ui->tabWidget->setCurrentIndex(m_listTabW.size() - 1);
setEnableBuilder(true);
m_curSimulation->clear();
m_project = tabw->getProject();
m_project->setres(res);
lvgl->changeResolution(res);
} else if (m_project == nullptr) {
setEnableBuilder(false);
setWindowTitle("LVGL Builder");
}
}
void MainWindow::addImage(LVGLImageData *img, QString name) {
LVGLImageDataCast cast;
cast.ptr = img;
QListWidgetItem *item = new QListWidgetItem(img->icon(), name);
item->setData(Qt::UserRole + 3, cast.i);
m_ui->list_images->addItem(item);
}
void MainWindow::updateImages() {
m_ui->list_images->clear();
for (LVGLImageData *i : lvgl->images()) {
if (i->fileName().isEmpty()) continue;
QString name = QFileInfo(i->fileName()).baseName() +
QString(" [%1x%2]").arg(i->width()).arg(i->height());
addImage(i, name);
}
}
void MainWindow::addFont(LVGLFontData *font, QString name) {
LVGLFontDataCast cast;
cast.ptr = font;
QListWidgetItem *item = new QListWidgetItem(name);
item->setData(Qt::UserRole + 3, cast.i);
m_ui->list_fonts->addItem(item);
}
void MainWindow::updateFonts() {
m_ui->list_fonts->clear();
for (const LVGLFontData *f : lvgl->customFonts())
addFont(const_cast<LVGLFontData *>(f), f->name());
}
void MainWindow::updateRecentActionList() {
QSettings settings("at.fhooe.lvgl", "LVGL Builder");
QStringList recentFilePaths;
for (const QString &f : settings.value("recentFiles").toStringList()) {
if (QFile(f).exists()) recentFilePaths.push_back(f);
}
int itEnd = m_maxFileNr;
if (recentFilePaths.size() <= m_maxFileNr) itEnd = recentFilePaths.size();
for (int i = 0; i < itEnd; i++) {
QString strippedName = QFileInfo(recentFilePaths.at(i)).fileName();
m_recentFileActionList.at(i)->setText(strippedName);
m_recentFileActionList.at(i)->setData(recentFilePaths.at(i));
m_recentFileActionList.at(i)->setVisible(true);
}
for (int i = itEnd; i < m_maxFileNr; i++)
m_recentFileActionList.at(i)->setVisible(false);
}
void MainWindow::adjustForCurrentFile(const QString &fileName) {
QSettings settings("at.fhooe.lvgl", "LVGL Builder");
QStringList recentFilePaths = settings.value("recentFiles").toStringList();
recentFilePaths.removeAll(fileName);
recentFilePaths.prepend(fileName);
while (recentFilePaths.size() > m_maxFileNr) recentFilePaths.removeLast();
settings.setValue("recentFiles", recentFilePaths);
updateRecentActionList();
}
void MainWindow::loadProject(const QString &fileName) {
delete m_project;
m_curSimulation->clear();
m_project = LVGLProject::load(fileName);
if (m_project == nullptr) {
QMessageBox::critical(this, "Error", "Could not load lvgl file!");
setWindowTitle("LVGL Builder");
setEnableBuilder(false);
} else {
adjustForCurrentFile(fileName);
setWindowTitle("LVGL Builder - [" + m_project->name() + "]");
lvgl->changeResolution(m_project->resolution());
m_curSimulation->changeResolution(m_project->resolution());
setEnableBuilder(true);
}
updateImages();
updateFonts();
}
void MainWindow::setEnableBuilder(bool enable) {
m_ui->action_save->setEnabled(enable);
m_ui->action_export_c->setEnabled(enable);
m_ui->action_run->setEnabled(enable);
m_ui->WidgeBox->setEnabled(enable);
m_ui->ImageEditor->setEnabled(enable);
m_ui->FontEditor->setEnabled(enable);
}
void MainWindow::updateItemDelegate() {
auto it = m_ui->style_tree->itemDelegate();
if (nullptr != it) delete it;
m_ui->style_tree->setItemDelegate(
new LVGLStyleDelegate(m_styleModel->styleBase()));
}
void MainWindow::on_action_load_triggered() {
QString path;
if (m_project != nullptr) path = m_project->fileName();
QString fileName =
QFileDialog::getOpenFileName(this, "Load lvgl", path, "LVGL (*.lvgl)");
if (fileName.isEmpty()) return;
loadProject(fileName);
}
void MainWindow::on_action_save_triggered() {
QString path;
if (m_project != nullptr) path = m_project->fileName();
QString fileName =
QFileDialog::getSaveFileName(this, "Save lvgl", path, "LVGL (*.lvgl)");
if (fileName.isEmpty()) return;
if (!m_project->save(fileName)) {
QMessageBox::critical(this, "Error", "Could not save lvgl file!");
} else {
adjustForCurrentFile(fileName);
}
}
void MainWindow::on_combo_style_currentIndexChanged(int index) {
LVGLObject *obj = m_curSimulation->selectedObject();
if (obj && (index >= 0)) {
auto parts = obj->widgetClass()->parts();
m_styleModel->setState(m_liststate[m_ui->combo_state->currentIndex()]);
m_styleModel->setPart(parts[index]);
m_styleModel->setStyle(
obj->style(index, m_ui->combo_state->currentIndex()),
obj->widgetClass()->editableStyles(m_ui->combo_style->currentIndex()));
m_ui->combo_state->setCurrentIndex(0);
on_combo_state_currentIndexChanged(0);
}
}
void MainWindow::on_action_export_c_triggered() {
QString dir;
if (m_project != nullptr) {
QFileInfo fi(m_project->fileName());
dir = fi.absoluteFilePath();
}
QString path = QFileDialog::getExistingDirectory(this, "Export C files", dir);
if (path.isEmpty()) return;
if (m_project->exportCode(path))
QMessageBox::information(this, "Export", "C project exported!");
}
void MainWindow::on_button_add_image_clicked() {
QString dir;
if (m_project != nullptr) {
QFileInfo fi(m_project->fileName());
dir = fi.absoluteFilePath();
}
QStringList fileNames = QFileDialog::getOpenFileNames(
this, "Import image", dir, "Image (*.png *.jpg *.bmp *.jpeg)");
for (const QString &fileName : fileNames) {
QImage image(fileName);
if (image.isNull()) continue;
if (image.width() >= 2048 || image.height() >= 2048) {
QMessageBox::critical(
this, "Error Image Size",
tr("Image size must be under 2048! (Src: '%1')").arg(fileName));
continue;
}
QString name = QFileInfo(fileName).baseName();
LVGLImageData *i = lvgl->addImage(fileName, name);
name += QString(" [%1x%2]").arg(i->width()).arg(i->height());
addImage(i, name);
}
}
void MainWindow::on_button_remove_image_clicked() {
QListWidgetItem *item = m_ui->list_images->currentItem();
if (item == nullptr) return;
const int row = m_ui->list_images->currentRow();
LVGLImageDataCast cast;
cast.i = item->data(Qt::UserRole + 3).toLongLong();
if (lvgl->removeImage(cast.ptr)) m_ui->list_images->takeItem(row);
}
void MainWindow::on_list_images_customContextMenuRequested(const QPoint &pos) {
QPoint item = m_ui->list_images->mapToGlobal(pos);
QListWidgetItem *listItem = m_ui->list_images->itemAt(pos);
if (listItem == nullptr) return;
QMenu menu;
QAction *save = menu.addAction("Save as ...");
QAction *color = menu.addAction("Set output color ...");
QAction *sel = menu.exec(item);
if (sel == save) {
LVGLImageDataCast cast;
cast.i = listItem->data(Qt::UserRole + 3).toLongLong();
QStringList options({"C Code (*.c)", "Binary (*.bin)"});
QString selected;
QString fileName = QFileDialog::getSaveFileName(
this, "Save image as c file", cast.ptr->codeName(), options.join(";;"),
&selected);
if (fileName.isEmpty()) return;
bool ok = false;
if (selected == options.at(0))
ok = cast.ptr->saveAsCode(fileName);
else if (selected == options.at(1))
ok = cast.ptr->saveAsBin(fileName);
if (!ok) {
QMessageBox::critical(this, "Error",
tr("Could not save image '%1'").arg(fileName));
}
} else if (sel == color) {
LVGLImageDataCast cast;
cast.i = listItem->data(Qt::UserRole + 3).toLongLong();
int index = static_cast<int>(cast.ptr->colorFormat());
QString ret =
QInputDialog::getItem(this, "Output color", "Select output color",
LVGLImageData::colorFormats(), index, false);
index = LVGLImageData::colorFormats().indexOf(ret);
if (index >= 0)
cast.ptr->setColorFormat(static_cast<LVGLImageData::ColorFormat>(index));
}
}
void MainWindow::on_list_images_currentItemChanged(QListWidgetItem *current,
QListWidgetItem *previous) {
Q_UNUSED(previous)
m_ui->button_remove_image->setEnabled(current != nullptr);
}
void MainWindow::on_button_add_font_clicked() {
LVGLFontDialog dialog(this);
if (dialog.exec() != QDialog::Accepted) return;
LVGLFontData *f =
lvgl->addFont(dialog.selectedFontPath(), dialog.selectedFontSize());
if (f)
addFont(f, f->name());
else
QMessageBox::critical(this, "Error", "Could not load font!");
}
void MainWindow::on_button_remove_font_clicked() {
QListWidgetItem *item = m_ui->list_fonts->currentItem();
if (item == nullptr) return;
const int row = m_ui->list_fonts->currentRow();
LVGLFontDataCast cast;
cast.i = item->data(Qt::UserRole + 3).toLongLong();
if (lvgl->removeFont(cast.ptr)) m_ui->list_fonts->takeItem(row);
}
void MainWindow::on_list_fonts_customContextMenuRequested(const QPoint &pos) {
QPoint item = m_ui->list_fonts->mapToGlobal(pos);
QListWidgetItem *listItem = m_ui->list_fonts->itemAt(pos);
if (listItem == nullptr) return;
QMenu menu;
QAction *save = menu.addAction("Save as ...");
QAction *sel = menu.exec(item);
if (sel == save) {
LVGLFontDataCast cast;
cast.i = listItem->data(Qt::UserRole + 3).toLongLong();
QStringList options({"C Code (*.c)", "Binary (*.bin)"});
QString selected;
QString fileName = QFileDialog::getSaveFileName(
this, "Save font as c file", cast.ptr->codeName(), options.join(";;"),
&selected);
if (fileName.isEmpty()) return;
bool ok = false;
if (selected == options.at(0)) ok = cast.ptr->saveAsCode(fileName);
if (!ok) {
QMessageBox::critical(this, "Error",
tr("Could not save font '%1'").arg(fileName));
}
}
}
void MainWindow::on_list_fonts_currentItemChanged(QListWidgetItem *current,
QListWidgetItem *previous) {
Q_UNUSED(previous)
m_ui->button_remove_font->setEnabled(current != nullptr);
}
void MainWindow::on_action_run_toggled(bool run) {
m_curSimulation->setMouseEnable(run);
m_curSimulation->setSelectedObject(nullptr);
}
void MainWindow::showEvent(QShowEvent *event) {
QMainWindow::showEvent(event);
if (m_project == nullptr)
QTimer::singleShot(50, this, SLOT(openNewProject()));
}
QPixmap MainWindow::getPix(int type) {
QPixmap p;
switch (type) {
case 0:
p.load(":/icons/Arc.png");
break;
case 1:
p.load(":/icons/Bar.png");
break;
case 2:
p.load(":/icons/Button.png");
break;
case 3:
p.load(":/icons/Button Matrix.png");
break;
case 4:
p.load(":/icons/Calendar.png");
break;
case 5:
p.load(":/icons/Canvas.png");
break;
case 6:
p.load(":/icons/Check box.png");
break;
case 7:
p.load(":/icons/Chart.png");
break;
case 8:
p.load(":/icons/Container.png");
break;
case 9:
p.load(":/icons/Color picker.png");
break;
case 10:
p.load(":/icons/Dropdown.png");
break;
case 11:
p.load(":/icons/Gauge.png");
break;
case 12:
p.load(":/icons/Image.png");
break;
case 13:
p.load(":/icons/Image button.png");
break;
case 16:
p.load(":/icons/Keyboard.png");
break;
case 17:
p.load(":/icons/Label.png");
break;
case 18:
p.load(":/icons/LED.png");
break;
case 19:
p.load(":/icons/Line.png");
break;
case 20:
p.load(":/icons/List.png");
break;
case 21:
p.load(":/icons/Line meter.png");
break;
case 22:
p.load(":/icons/Message box.png");
break;
case 23:
p.load(":/icons/ObjectMask.png");
break;
case 24:
p.load(":/icons/Page.png");
break;
case 25:
p.load(":/icons/Roller.png");
break;
case 26:
p.load(":/icons/Slider.png");
break;
case 27:
p.load(":/icons/Spinbox.png");
break;
case 28:
p.load(":/icons/Spinner.png");
break;
case 29:
p.load(":/icons/Switch.png");
break;
case 30:
p.load(":/icons/Table.png");
break;
case 31:
p.load(":/icons/Tabview.png");
break;
case 32:
p.load(":/icons/Text area.png");
break;
case 33:
p.load(":/icons/TileView.png");
break;
case 34:
p.load(":/icons/Window.png");
break;
}
return p;
}
void MainWindow::addWidget(LVGLWidget *w) {
w->setPreview(getPix(w->type()));
m_widgets.insert(w->className(), w);
}
void MainWindow::addWidgetDisplayW(LVGLWidget *w) {
w->setPreview(getPix(w->type()));
m_widgetsDisplayW.insert(w->className(), w);
}
void MainWindow::addWidgetInputW(LVGLWidget *w) {
w->setPreview(getPix(w->type()));
m_widgetsInputW.insert(w->className(), w);
}
void MainWindow::initcodemap() {
auto pt = lv_obj_create(NULL, NULL);
m_codemap[0] = lv_arc_create(pt, NULL);
m_codemap[1] = lv_bar_create(pt, NULL);
m_codemap[2] = lv_btn_create(pt, NULL);
m_codemap[3] = lv_btnmatrix_create(pt, NULL);
m_codemap[4] = lv_calendar_create(pt, NULL);
m_codemap[5] = lv_canvas_create(pt, NULL);
m_codemap[6] = lv_checkbox_create(pt, NULL);
m_codemap[7] = lv_chart_create(pt, NULL);
m_codemap[8] = lv_cont_create(pt, NULL);
m_codemap[9] = lv_cpicker_create(pt, NULL);
m_codemap[10] = lv_dropdown_create(pt, NULL);
m_codemap[11] = lv_gauge_create(pt, NULL);
m_codemap[12] = lv_img_create(pt, NULL);
m_codemap[13] = lv_imgbtn_create(pt, NULL);
m_codemap[16] = lv_keyboard_create(pt, NULL);
m_codemap[17] = lv_label_create(pt, NULL);
m_codemap[18] = lv_led_create(pt, NULL);
m_codemap[19] = lv_line_create(pt, NULL);
m_codemap[20] = lv_list_create(pt, NULL);
m_codemap[21] = lv_linemeter_create(pt, NULL);
m_codemap[22] = lv_msgbox_create(pt, NULL);
m_codemap[23] = lv_objmask_create(pt, NULL);
m_codemap[24] = lv_page_create(pt, NULL);
m_codemap[25] = lv_roller_create(pt, NULL);
m_codemap[26] = lv_slider_create(pt, NULL);
m_codemap[27] = lv_spinbox_create(pt, NULL);
m_codemap[28] = lv_spinner_create(pt, NULL);
m_codemap[29] = lv_switch_create(pt, NULL);
m_codemap[30] = lv_table_create(pt, NULL);
m_codemap[31] = lv_tabview_create(pt, NULL);
m_codemap[32] = lv_textarea_create(pt, NULL);
m_codemap[33] = lv_tileview_create(pt, NULL);
m_codemap[34] = lv_win_create(pt, NULL);
}
void MainWindow::initNewWidgets() {
addWidget(new LVGLButton);
addWidget(new LVGLButtonMatrix);
addWidget(new LVGLImageButton);
addWidgetDisplayW(new LVGLArc);
addWidgetDisplayW(new LVGLBar);
addWidgetDisplayW(new LVGLImage);
addWidgetDisplayW(new LVGLLabel);
addWidgetDisplayW(new LVGLLED);
addWidgetDisplayW(new LVGLMessageBox);
addWidgetDisplayW(new LVGLObjectMask);
addWidgetDisplayW(new LVGLPage);
addWidgetDisplayW(new LVGLTable);
addWidgetDisplayW(new LVGLTabview);
addWidgetDisplayW(new LVGLTileView);
addWidgetDisplayW(new LVGLTextArea);
addWidgetDisplayW(new LVGLWindow);
addWidgetInputW(new LVGLCalendar);
addWidgetInputW(new LVGLCanvas);
addWidgetInputW(new LVGLChart);
addWidgetInputW(new LVGLCheckBox);
addWidgetInputW(new LVGLColorPicker);
addWidgetInputW(new LVGLContainer);
addWidgetInputW(new LVGLDropDownList);
addWidgetInputW(new LVGLGauge);
addWidgetInputW(new LVGLKeyboard);
addWidgetInputW(new LVGLLine);
addWidgetInputW(new LVGLList);
addWidgetInputW(new LVGLLineMeter);
addWidgetInputW(new LVGLRoller);
addWidgetInputW(new LVGLSlider);
addWidgetInputW(new LVGLSpinbox);
addWidgetInputW(new LVGLSpinner);
addWidgetInputW(new LVGLSwitch);
}
void MainWindow::initlvglConnect() {
if (m_objectModel) delete m_objectModel;
if (m_proxyModel) delete m_proxyModel;
if (m_proxyModelDPW) delete m_proxyModelDPW;
if (m_proxyModelIPW) delete m_proxyModelIPW;
if (m_widgetModel) delete m_widgetModel;
if (m_widgetModelDPW) delete m_widgetModelDPW;
if (m_widgetModelIPW) delete m_widgetModelIPW;
m_objectModel = new LVGLObjectModel(this);
m_widgetModel = new LVGLWidgetModel(this);
m_widgetModelDPW = new LVGLWidgetModelDisplay(this);
m_widgetModelIPW = new LVGLWidgetModelInput(this);
m_proxyModel = new QSortFilterProxyModel(this);
m_proxyModelDPW = new QSortFilterProxyModel(this);
m_proxyModelIPW = new QSortFilterProxyModel(this);
m_ui->object_tree->setModel(m_objectModel);
m_curSimulation->setObjectModel(m_objectModel);
m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_proxyModel->setSourceModel(m_widgetModel);
m_proxyModel->sort(0);
m_proxyModelDPW->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_proxyModelDPW->setSourceModel(m_widgetModelDPW);
m_proxyModelDPW->sort(0);
m_proxyModelIPW->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_proxyModelIPW->setSourceModel(m_widgetModelIPW);
m_proxyModelIPW->sort(0);
m_ui->list_widgets->getlistview()->setItemDelegate(m_ld1);
m_ui->list_widgets_2->getlistview()->setItemDelegate(m_ld2);
m_ui->list_widgets_3->getlistview()->setItemDelegate(m_ld3);
m_ui->list_widgets->getlistview()->setModel(m_proxyModel);
m_ui->list_widgets_2->getlistview()->setModel(m_proxyModelDPW);
m_ui->list_widgets_3->getlistview()->setModel(m_proxyModelIPW);
m_ui->list_widgets->settoolbtnText(tr("Button"));
m_ui->list_widgets_2->settoolbtnText(tr("DisplayWidgets"));
m_ui->list_widgets_3->settoolbtnText(tr("InputWidgts"));
connect(m_curSimulation, &LVGLSimulator::objectSelected, this,
&MainWindow::setCurrentObject);
connect(m_curSimulation, &LVGLSimulator::objectSelected, m_ui->property_tree,
&QTreeView::expandAll);
connect(m_curSimulation->item(), &LVGLItem::geometryChanged, this,
&MainWindow::updateProperty);
connect(m_curSimulation, &LVGLSimulator::objectAdded, m_ui->object_tree,
&QTreeView::expandAll);
connect(m_curSimulation, &LVGLSimulator::objectSelected, m_objectModel,
&LVGLObjectModel::setCurrentObject);
connect(m_ui->object_tree, &QTreeView::doubleClicked, this,
[this](const QModelIndex &index) {
m_curSimulation->setSelectedObject(m_objectModel->object(index));
});
connect(m_zoom_slider, &QSlider::valueChanged, m_curSimulation,
&LVGLSimulator::setZoomLevel);
connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModel,
&QSortFilterProxyModel::setFilterWildcard);
connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelDPW,
&QSortFilterProxyModel::setFilterWildcard);
connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelIPW,
&QSortFilterProxyModel::setFilterWildcard);
if (m_filter != nullptr) delete m_filter;
m_filter = new LVGLKeyPressEventFilter(m_curSimulation, qApp);
qApp->installEventFilter(m_filter);
m_ui->combo_state->clear();
QStringList statelist;
statelist << "LV_STATE_DEFAULT"
<< "LV_STATE_CHECKED"
<< "LV_STATE_FOCUSED"
<< "LV_STATE_EDITED"
<< "LV_STATE_HOVERED"
<< "LV_STATE_PRESSED"
<< "LV_STATE_DISABLED";
m_ui->combo_state->addItems(statelist);
}
void MainWindow::revlvglConnect() {
disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModel,
&QSortFilterProxyModel::setFilterWildcard);
disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelDPW,
&QSortFilterProxyModel::setFilterWildcard);
disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelIPW,
&QSortFilterProxyModel::setFilterWildcard);
disconnect(m_curSimulation, &LVGLSimulator::objectSelected, this,
&MainWindow::setCurrentObject);
disconnect(m_curSimulation, &LVGLSimulator::objectSelected,
m_ui->property_tree, &QTreeView::expandAll);
disconnect(m_curSimulation->item(), &LVGLItem::geometryChanged, this,
&MainWindow::updateProperty);
disconnect(m_curSimulation, &LVGLSimulator::objectAdded, m_ui->object_tree,
&QTreeView::expandAll);
disconnect(m_curSimulation, &LVGLSimulator::objectSelected, m_objectModel,
&LVGLObjectModel::setCurrentObject);
disconnect(m_zoom_slider, &QSlider::valueChanged, m_curSimulation,
&LVGLSimulator::setZoomLevel);
}
void MainWindow::on_combo_state_currentIndexChanged(int index) {
LVGLObject *obj = m_curSimulation->selectedObject();
if (obj && (index >= 0)) {
auto parts = obj->widgetClass()->parts();
m_styleModel->setPart(parts[m_ui->combo_style->currentIndex()]);
m_styleModel->setState(m_liststate[index]);
m_styleModel->setStyle(
obj->style(m_ui->combo_style->currentIndex(), index),
obj->widgetClass()->editableStyles(m_ui->combo_style->currentIndex()));
updateItemDelegate();
}
}
void MainWindow::tabChanged(int index) {
if (index != m_curTabWIndex) {
if (nullptr != m_curSimulation) m_curSimulation->setSelectedObject(nullptr);
m_curSimulation = m_listTabW[index]->getSimulator();
lvgl = m_listTabW[index]->getCore();
m_project = m_listTabW[index]->getProject(); // dont need
initlvglConnect();
lvgl->changeResolution(m_coreRes[lvgl]);
m_curSimulation->changeResolution(m_coreRes[lvgl]);
m_curSimulation->repaint();
m_curTabWIndex = index;
}
}
| 27,348 | 9,964 |
//===- lib/os/thread_win32.cpp --------------------------------------------===//
//* _ _ _ *
//* | |_| |__ _ __ ___ __ _ __| | *
//* | __| '_ \| '__/ _ \/ _` |/ _` | *
//* | |_| | | | | | __/ (_| | (_| | *
//* \__|_| |_|_| \___|\__,_|\__,_| *
//* *
//===----------------------------------------------------------------------===//
//
// Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
// See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
// information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file thread.cpp
#include "pstore/os/thread.hpp"
#ifdef _WIN32
# include <array>
# include <cerrno>
# include <cstring>
# include <system_error>
# include "pstore/config/config.hpp"
# include "pstore/support/error.hpp"
namespace pstore {
namespace threads {
static thread_local char thread_name[name_size];
void set_name (gsl::not_null<gsl::czstring> name) {
// This code taken from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
// Sadly, threads don't actually have names in Win32. The process via
// RaiseException is just a "Secret Handshake" with the VS Debugger, who
// actually stores the thread -> name mapping. Windows itself has no
// notion of a thread "name".
std::strncpy (thread_name, name, name_size);
thread_name[name_size - 1] = '\0';
# ifndef NDEBUG
DWORD const MS_VC_EXCEPTION = 0x406D1388;
# pragma pack(push, 8)
struct THREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
};
# pragma pack(pop)
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = GetCurrentThreadId ();
info.dwFlags = 0;
__try {
RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR),
(ULONG_PTR *) &info);
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
# endif // NDEBUG
}
gsl::czstring get_name (gsl::span<char, name_size> name /*out*/) {
auto const length = name.size ();
if (name.data () == nullptr || length < 1) {
raise (errno_erc{EINVAL});
}
std::strncpy (name.data (), thread_name, length);
name[length - 1] = '\0';
return name.data ();
}
} // end namespace threads
} // end namespace pstore
#endif //_WIN32
| 2,964 | 938 |
// Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include <TrustWalletCore/TWTezosAddress.h>
#include "../Tezos/Address.h"
#include <TrustWalletCore/TWHash.h>
#include <TrustWalletCore/TWPublicKey.h>
#include <TrezorCrypto/ecdsa.h>
#include <string.h>
#include <memory>
using namespace TW;
using namespace TW::Tezos;
bool TWTezosAddressEqual(struct TWTezosAddress *_Nonnull lhs, struct TWTezosAddress *_Nonnull rhs) {
return lhs->impl == rhs->impl;
}
bool TWTezosAddressIsValidString(TWString *_Nonnull string) {
auto s = reinterpret_cast<const std::string*>(string);
return Address::isValid(*s);
}
struct TWTezosAddress *_Nullable TWTezosAddressCreateWithString(TWString *_Nonnull string) {
auto s = reinterpret_cast<const std::string*>(string);
const auto address = Address(*s);
return new TWTezosAddress{ std::move(address) };
}
struct TWTezosAddress *_Nonnull TWTezosAddressCreateWithPublicKey(struct TWPublicKey *_Nonnull publicKey) {
return new TWTezosAddress{ Address(publicKey->impl) };
}
void TWTezosAddressDelete(struct TWTezosAddress *_Nonnull address) {
delete address;
}
TWString *_Nonnull TWTezosAddressDescription(struct TWTezosAddress *_Nonnull address) {
const auto string = address->impl.string();
return TWStringCreateWithUTF8Bytes(string.c_str());
}
TWData *_Nonnull TWTezosAddressKeyHash(struct TWTezosAddress *_Nonnull address) {
return TWDataCreateWithBytes(address->impl.bytes.data(), Address::size);
}
| 1,694 | 580 |
#include <loxpp_pch.h>
#include <Object.h>
#include <VisitHelpers.h>
namespace Loxpp::Object {
// Handy template class and function to cast from a variant T1 to variant T2,
// where T2 is a superset of T1: https://stackoverflow.com/a/47204507/15150338
template <class... Args> struct variant_cast_proxy {
std::variant<Args...> v;
template <class... ToArgs> operator std::variant<ToArgs...>() const {
return std::visit(
[](auto&& arg) -> std::variant<ToArgs...> { return arg; }, v);
}
};
template <class... Args>
auto variant_cast(const std::variant<Args...>& v)
-> variant_cast_proxy<Args...> {
return {v};
}
LoxObj FromLiteralValue(const Lexer::LiteralValue& value) {
return LoxObj{variant_cast(value)};
}
bool IsTruthy(const LoxObj& obj) {
return std::visit(overloaded{[](std::monostate /*m*/) { return false; },
[](bool b) { return b; },
[](auto&& arg) { return true; }},
obj);
}
} // namespace Loxpp::Object | 1,055 | 356 |
#include<iostream>
#include<vector>
#include<unordered_set>
#include<algorithm>
using namespace std;
//find the longest band in a given array of integers
//Input: {1,9,3,0,5,2,4,10,7,12,6}
//Output: 8 {0,1,2,3,4,5,6,7}
int longestBand(vector<int> arr){
int result = 0;
unordered_set<int> os;
for(int element : arr){
os.insert(element);
}
for(auto element: os){ //note that you can iterate through an unordered set like this. You looked this up.
int parent = element -1 ; // find the root of a sequence
if(os.find(parent)==os.end()){ // if root is found
int count = 1; // start counting
int next_element = element + 1; //find next element
while(os.find(next_element)!=os.end()){ //keep incrementing as long as the sequence holds
count++;
next_element++;
}
if(count > result){// update maximum sequence found till now
result = count;
}
}
}
return result; //return maximum sequence
}
int main(){
int result = longestBand({1,9,3,0,5,4,10,7,12,6});
cout << "The longest band is: " << result << endl;
return 0;
} | 1,243 | 415 |
#include "JPos_Controller.hpp"
#include <random>
void karl_Controller::initializeController() {
_loadPath = "/home/user/raisim_workspace/Cheetah-Software/actor_model/actor_1700.pt";
try {
// Deserialize the ScriptModule from a file using torch::jit::load().
_actor = torch::jit::load(_loadPath);
}
catch (const c10::Error& e) {
std::cerr << "!!!!Error loading the model!!!!\n";
}
_obsDim = 34;
_obsMean.setZero(_obsDim);
_obsVar.setZero(_obsDim);
std::string in_line;
std::ifstream obsMean_file("/home/user/raisim_workspace/Cheetah-Software/actor_model/mean1700.csv");
std::ifstream obsVariance_file("/home/user/raisim_workspace/Cheetah-Software/actor_model/var1700.csv");
if(obsMean_file.is_open()) {
for(int i = 0; i < _obsMean.size(); i++){
std::getline(obsMean_file, in_line);
_obsMean(i) = std::stod(in_line);
}
}
if(obsVariance_file.is_open()) {
for(int i = 0; i < _obsVar.size(); i++){
std::getline(obsVariance_file, in_line);
_obsVar(i) = std::stod(in_line);
}
}
obsMean_file.close();
obsVariance_file.close();
// RotMat<float> a;
// Quat<float> q;
// q[0] = 0.5, q[1] = 0.5, q[2] = 0.5, q[3] = 0.5;
// a = ori::quaternionToRotationMatrix(q);
// std::cout << "a: " << a.transpose().row(2) << std::endl;
}
void karl_Controller::runController(){
Eigen::Matrix<float, 12, 1> qInitVec;
Vec3<float> qInitVec1, qInitVec2, qInitVec3, qInitVec4;
Mat3<float> kpMat;
Mat3<float> kdMat;
//kpMat << 20, 0, 0, 0, 20, 0, 0, 0, 20;
//kdMat << 2.1, 0, 0, 0, 2.1, 0, 0, 0, 2.1;
qInitVec1 << userParameters.q_init1[0], userParameters.q_init1[1], userParameters.q_init1[2];
qInitVec2 << userParameters.q_init2[0], userParameters.q_init2[1], userParameters.q_init2[2];
qInitVec3 << userParameters.q_init3[0], userParameters.q_init3[1], userParameters.q_init3[2];
qInitVec4 << userParameters.q_init4[0], userParameters.q_init4[1], userParameters.q_init4[2];
qInitVec << qInitVec1, qInitVec2, qInitVec3, qInitVec4;
kpMat << userParameters.kp[0], 0, 0, 0, userParameters.kp[1], 0, 0, 0, userParameters.kp[2];
kdMat << userParameters.kd[0], 0, 0, 0, userParameters.kd[1], 0, 0, 0, userParameters.kd[2];
// std::cout << "orientation: " << _stateEstimate->orientation << std::endl;
/// TODO: check each variable is appropriate.
_bodyHeight = _stateEstimate->position(2); // body height 1
_bodyOri << _stateEstimate->rBody.transpose().row(2).transpose(); // body orientation 3
_jointQ << _legController->datas[0].q, _legController->datas[1].q, _legController->datas[2].q, _legController->datas[3].q; // joint angles 3 3 3 3 = 12
_bodyVel << _stateEstimate->vWorld; // velocity 3
_bodyAngularVel << _stateEstimate->omegaWorld; // angular velocity 3
_jointQd << _legController->datas[0].qd, _legController->datas[1].qd, _legController->datas[2].qd, _legController->datas[3].qd; // joint velocity 3 3 3 3 = 12
_obs.setZero(_obsDim);
_obs << _bodyHeight,
_bodyOri,
_jointQ,
_bodyVel,
_bodyAngularVel,
_jointQd;
static int iter(0);
++iter;
// std::cout << "obs: " << _obs << std::endl;
///
if(iter%1000 == 0) {
std::cout << "Test 1: Observation before normalization." << std::endl;
std::cout << _obs << std::endl;
}
///
for(int i = 0; i < _obs.size(); i++) {
_obs(i) = (_obs(i) - _obsMean(i)) / std::sqrt(_obsVar(i) + 1e-8);
if(_obs(i) > 10) _obs(i) = 10.0;
if(_obs(i) < -10) _obs(i) = -10.0;
}
///
// std::cout << "Test 2-1: Observation after normalization, but without being converted to tensor." << std::endl;
// std::cout << _obs << std::endl;
///
_input.push_back(torch::jit::IValue(torch::from_blob(_obs.data(), {_obs.cols(),_obs.rows()}).clone()));
// std::cout << "observation: " << torch::from_blob(_obs.data(), {_obs.cols(),_obs.rows()}) << std::endl;
torch::Tensor action_tensor = _actor.forward(_input).toTensor(); // action of Tensor type
float* action_f = action_tensor.data_ptr<float>(); // action of float pointer type
Eigen::Map<Eigen::MatrixXf> action_eigen(action_f, action_tensor.size(0), action_tensor.size(1)); // action of MatrixXf type
_input.pop_back();
///
// std::cout << "Test 3: Actor must have the same output for the same input." << std::endl;
// Eigen::VectorXf obs_test;
// obs_test.setZero(_obsDim);
// _input.push_back(torch::jit::IValue(torch::from_blob(obs_test.data(), {obs_test.cols(),obs_test.rows()}).clone()));
// torch::Tensor action_tensor_test = _actor.forward(_input).toTensor(); // action of Tensor type
// float* action_f_test = action_tensor_test.data_ptr<float>(); // action of float pointer type
// Eigen::Map<Eigen::MatrixXf> action_eigen_test(action_f_test, action_tensor_test.size(0), action_tensor_test.size(1)); // action of MatrixXf type
// _input.pop_back();
// std::cout << "test input: " << obs_test << std::endl;
// std::cout << "action: " << action_eigen_test << std::endl;
// std::cout << "action dimension: " << action_eigen_test.size() << std::endl;
//
// std::cout << "Test 4: action scaling." << std::endl;
// std::cout << "For the same input action, normalized action output must be the same." << std::endl;
///
// action scaling
Eigen::VectorXd q_init;
Eigen::VectorXd pTarget_12;
q_init.setZero(12);
pTarget_12.setZero(12);
// q_init << -0.726685, -0.947298, 2.7, 0.726636, -0.947339, 2.7, -0.727, -0.94654, 2.65542, 0.727415, -0.946541, 2.65542;
q_init << 0, -0.7854, 1.8326, 0, -0.7854, 1.8326, 0, -0.7854, 1.8326, 0, -0.7854, 1.8326;
pTarget_12 = action_eigen.row(0).cast<double>();
pTarget_12 *= 0.3;
pTarget_12 += q_init;
// std::cout << "input: " << action_tensor << std::endl;
// std::cout << "output: " << pTarget_12 << std::endl;
///
// std::cout << "Test 5: P Gain & D Gain." << std::endl;
// std::cout << "Kp: " << kpMat << std::endl;
// std::cout << "Kd: " << kdMat << std::endl;
///
_legController->_maxTorque = 18;
_legController->_legsEnabled = true;
if(iter < 10){
for(int leg(0); leg<4; ++leg){
for(int jidx(0); jidx<3; ++jidx){
_jpos_ini[3*leg+jidx] = _legController->datas[leg].q[jidx];
}
}
return;
} else if(iter < 1000) {
for(int leg(0); leg<4; ++leg){
for(int jidx(0); jidx<3; ++jidx){
_legController->commands[leg].qDes[jidx] = _jpos_ini[3*leg+jidx] + iter/999.*(qInitVec(leg*3 + jidx)-_jpos_ini[3*leg+jidx]);
_legController->commands[leg].qdDes[jidx] = 0.;
_legController->commands[leg].tauFeedForward[jidx] = userParameters.tau_ff;
}
_legController->commands[leg].kpJoint = kpMat*10;
_legController->commands[leg].kdJoint = kdMat*10;
// std::cout << "Joint position: " << _legController->datas[leg].q << std::endl;
}
return;
}
// if(iter % 1000 == 0) {
// std::cout << "observation after normalization: " << std::endl;
// std::cout << "obs: " << _obs << std::endl;
// std::cout << "joint target after scaling: " << std::endl;
// std::cout << "pTarget12: " << pTarget_12 << std::endl;
// }
if(userParameters.calibrate > 0.4) {
_legController->_calibrateEncoders = userParameters.calibrate;
} else {
if(userParameters.zero > 0.5) {
_legController->_zeroEncoders = true;
} else {
_legController->_zeroEncoders = false;
for(int leg(0); leg<4; ++leg){
for(int jidx(0); jidx<3; ++jidx){
// pTarget_12(leg*3 + jidx) = _legController->datas[leg].q[jidx] + 0.1 * (pTarget_12(leg*3 + jidx) - _legController->datas[leg].q[jidx]);
// std::cout << "joint angle" << leg << jidx << ": " << _legController->datas[leg].q[jidx];
// std::cout << "joint target" << leg << jidx << ": " << pTarget_12(leg*3 + jidx);
_legController->commands[leg].qDes[jidx] = pTarget_12(leg*3 + jidx);
// _legController->commands[leg].qDes[jidx] = qInitVec(leg*3 + jidx);
_legController->commands[leg].qdDes[jidx] = 0.;
_legController->commands[leg].tauFeedForward[jidx] = userParameters.tau_ff;
}
_legController->commands[leg].kpJoint = kpMat;
_legController->commands[leg].kdJoint = kdMat;
}
// std::cout << std::endl;
}
}
}
| 8,227 | 3,423 |
/** ***************************************************************************
* Various helper functions
*
* (c)2020 Christian Bendele
*
*/
#include "Helper.h"
#include <sstream>
#include <iostream>
namespace Grandma {
std::vector<std::string> Helper::vectorize_path(const std::string path) {
std::stringstream ss;
if(path[0] == '/') {
ss << path.substr(1);
} else {
ss << path;
}
std::string segment;
std::vector<std::string> vectorized;
while(getline(ss, segment, '/')) {
vectorized.push_back(segment);
}
return vectorized;
}
// TODO: this can hardly be called a real URL parser. It is very simplicistic and supports only a
// small part of RFCxxxx. Also, string operations in C++ are not my forte...
bool Helper::URL::parse_from_string(std::string s_uri) {
std::cout << "Parsing URI " << s_uri << std::endl;
// parse protocol
size_t delim = s_uri.find("://");
if(delim == std::string::npos) return false;
std::string proto_s = s_uri.substr(0, delim);
std::cout << "proto_s is " << proto_s << std::endl;
if("http" == proto_s || "HTTP" == proto_s) {
protocol = Protocol::HTTP;
} else if("https" == proto_s || "HTTPS" == proto_s) {
protocol = Protocol::HTTPS;
} else {
return false;
}
s_uri = s_uri.substr(delim+3);
// parse path
delim = s_uri.find("/");
if(delim == std::string::npos) {
path = "/";
} else {
path = s_uri.substr(delim);
s_uri = s_uri.substr(0, delim);
}
std::cout << "Path is " << path << std::endl;
//parse port
delim = s_uri.find(":");
if(delim == std::string::npos) {
port = 8080;
} else {
std::string s_port = s_uri.substr(delim+1);
port = std::stoi(s_port); // FIXME: may throw exception
}
std::cout << "Port is " << port << std::endl;
// reminder is server
server = s_uri.substr(0, delim);
std::cout << "server is " << server << std::endl;
return true;
}
} // namespace
| 1,939 | 714 |
// C/C++ File
// Author: Alexandre Tea <alexandre.qtea@gmail.com>
// File: /Users/alexandretea/Work/ddti/srcs/utils/datetime.cpp
// Purpose: datetime utilities
// Created: 2017-07-29 22:52:26
// Modified: 2017-08-23 23:19:15
#include <ctime>
#include "datetime.hpp"
namespace utils {
namespace datetime {
std::string
now_str(char const* format)
{
std::time_t t = std::time(0);
char cstr[128];
std::strftime(cstr, sizeof(cstr), format, std::localtime(&t));
return cstr;
}
// Timer class
Timer::Timer()
: _start(chrono::system_clock::now()),
_end(chrono::system_clock::now())
{
}
Timer::~Timer()
{
}
void
Timer::start()
{
_start = chrono::system_clock::now();
_end = chrono::system_clock::now();
}
void
Timer::stop()
{
_end = chrono::system_clock::now();
}
void
Timer::reset()
{
_start = chrono::system_clock::now();
_end = chrono::system_clock::now();
}
} // end of namespace datetime
} // end of namespace utils
| 996 | 400 |
#define _CRT_NONSTDC_NO_DEPRECATE
#include <AllStat/AllStat.h>
#include "Generator.h"
using namespace AllStat;
#pragma warning(disable : 4996 26812)
AllStat::Generator* AllStat::Generator::First = nullptr;
Generator::Generator(
const char* name
, const char* format
, AS_GENERATOR id
, FGetTables gettables
, FGetInfo getinfo
, FGetConst getconst
)
: Next(nullptr)
, ID(id)
, Name(name)
, Format(format)
, Tables{}
, GetInfo(getinfo)
, GetConst(getconst)
{
gettables(Tables);
Next = First;
First = this;
}
std::string Generator::ToStr(uint32_t e)
{
const STATUS_ITEM* p = EntryByCode(e, Tables.Items, Tables.Code2name);
return FormatName(e, p, Format);
}
const char* Generator::ToStrC(uint32_t e)
{
std::string str = ToStr(e);
return strdup(str.c_str());
}
ItemArray Generator::ToInfo(uint32_t e)
{
ItemArray aa;
auto a = EntryByCodeArray(e, Tables.Items, Tables.Code2name);
for (auto it = a.begin(); it != a.end(); ++it)
{
auto item = *it;
AS_ITEM ai;
ItemFromStatusItem(*item, ai, ID, ID);
aa.push_back(ai);
}
return aa;
}
PAS_ITEM_ARRAY Generator::ToInfoC(uint32_t e)
{
ItemArray arr = ToInfo(e);
return BuildItemArray(arr);
}
const char* Generator::ToName(uint32_t e)
{
const STATUS_ITEM* p = EntryByCode(e, Tables.Items, Tables.Code2name);
return p ? p->Name : nullptr;
}
uint32_t Generator::ToItem(const char* constant_name, PAS_ITEM pitem)
{
if (pitem == nullptr)
{
assert(pitem);
return AS_UNKNOWN;
}
auto e = EntryByName(constant_name, Tables.Items, Tables.Name2code);
if (e == nullptr)
return AS_UNKNOWN;
ItemFromStatusItem(*e, *pitem, ID, ID);
return 0;
}
| 1,771 | 722 |
/* $Id: ATAPIPassthrough.cpp $ */
/** @file
* VBox storage devices: ATAPI emulation (common code for DevATA and DevAHCI).
*/
/*
* Copyright (C) 2012-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#define LOG_GROUP LOG_GROUP_DEV_IDE
#include <iprt/log.h>
#include <iprt/assert.h>
#include <iprt/mem.h>
#include <iprt/string.h>
#include <VBox/log.h>
#include <VBox/err.h>
#include <VBox/cdefs.h>
#include <VBox/scsi.h>
#include <VBox/scsiinline.h>
#include "ATAPIPassthrough.h"
/** The track was not detected yet. */
#define TRACK_FLAGS_UNDETECTED RT_BIT_32(0)
/** The track is the lead in track of the medium. */
#define TRACK_FLAGS_LEAD_IN RT_BIT_32(1)
/** The track is the lead out track of the medium. */
#define TRACK_FLAGS_LEAD_OUT RT_BIT_32(2)
/** Don't clear already detected tracks on the medium. */
#define ATAPI_TRACK_LIST_REALLOCATE_FLAGS_DONT_CLEAR RT_BIT_32(0)
/**
* Track main data form.
*/
typedef enum TRACKDATAFORM
{
/** Invalid data form. */
TRACKDATAFORM_INVALID = 0,
/** 2352 bytes of data. */
TRACKDATAFORM_CDDA,
/** CDDA data is pause. */
TRACKDATAFORM_CDDA_PAUSE,
/** Mode 1 with 2048 bytes sector size. */
TRACKDATAFORM_MODE1_2048,
/** Mode 1 with 2352 bytes sector size. */
TRACKDATAFORM_MODE1_2352,
/** Mode 1 with 0 bytes sector size (generated by the drive). */
TRACKDATAFORM_MODE1_0,
/** XA Mode with 2336 bytes sector size. */
TRACKDATAFORM_XA_2336,
/** XA Mode with 2352 bytes sector size. */
TRACKDATAFORM_XA_2352,
/** XA Mode with 0 bytes sector size (generated by the drive). */
TRACKDATAFORM_XA_0,
/** Mode 2 with 2336 bytes sector size. */
TRACKDATAFORM_MODE2_2336,
/** Mode 2 with 2352 bytes sector size. */
TRACKDATAFORM_MODE2_2352,
/** Mode 2 with 0 bytes sector size (generated by the drive). */
TRACKDATAFORM_MODE2_0
} TRACKDATAFORM;
/**
* Subchannel data form.
*/
typedef enum SUBCHNDATAFORM
{
/** Invalid subchannel data form. */
SUBCHNDATAFORM_INVALID = 0,
/** 0 bytes for the subchannel (generated by the drive). */
SUBCHNDATAFORM_0,
/** 96 bytes of data for the subchannel. */
SUBCHNDATAFORM_96
} SUBCHNDATAFORM;
/**
* Track entry.
*/
typedef struct TRACK
{
/** Start LBA of the track. */
int64_t iLbaStart;
/** Number of sectors in the track. */
uint32_t cSectors;
/** Data form of main data. */
TRACKDATAFORM enmMainDataForm;
/** Data form of sub channel. */
SUBCHNDATAFORM enmSubChnDataForm;
/** Flags for the track. */
uint32_t fFlags;
} TRACK, *PTRACK;
/**
* Media track list.
*/
typedef struct TRACKLIST
{
/** Number of detected tracks of the current medium. */
unsigned cTracksCurrent;
/** Maximum number of tracks the list can contain. */
unsigned cTracksMax;
/** Variable list of tracks. */
PTRACK paTracks;
} TRACKLIST, *PTRACKLIST;
/**
* Reallocate the given track list to be able to hold the given number of tracks.
*
* @returns VBox status code.
* @param pTrackList The track list to reallocate.
* @param cTracks Number of tracks the list must be able to hold.
* @param fFlags Flags for the reallocation.
*/
static int atapiTrackListReallocate(PTRACKLIST pTrackList, unsigned cTracks, uint32_t fFlags)
{
int rc = VINF_SUCCESS;
if (!(fFlags & ATAPI_TRACK_LIST_REALLOCATE_FLAGS_DONT_CLEAR))
ATAPIPassthroughTrackListClear(pTrackList);
if (pTrackList->cTracksMax < cTracks)
{
PTRACK paTracksNew = (PTRACK)RTMemRealloc(pTrackList->paTracks, cTracks * sizeof(TRACK));
if (paTracksNew)
{
pTrackList->paTracks = paTracksNew;
/* Mark new tracks as undetected. */
for (unsigned i = pTrackList->cTracksMax; i < cTracks; i++)
pTrackList->paTracks[i].fFlags |= TRACK_FLAGS_UNDETECTED;
pTrackList->cTracksMax = cTracks;
}
else
rc = VERR_NO_MEMORY;
}
if (RT_SUCCESS(rc))
pTrackList->cTracksCurrent = cTracks;
return rc;
}
/**
* Initilizes the given track from the given CUE sheet entry.
*
* @returns nothing.
* @param pTrack The track to initialize.
* @param pbCueSheetEntry CUE sheet entry to use.
*/
static void atapiTrackListEntryCreateFromCueSheetEntry(PTRACK pTrack, const uint8_t *pbCueSheetEntry)
{
TRACKDATAFORM enmTrackDataForm = TRACKDATAFORM_INVALID;
SUBCHNDATAFORM enmSubChnDataForm = SUBCHNDATAFORM_INVALID;
/* Determine size of main data based on the data form field. */
switch (pbCueSheetEntry[3] & 0x3f)
{
case 0x00: /* CD-DA with data. */
enmTrackDataForm = TRACKDATAFORM_CDDA;
break;
case 0x01: /* CD-DA without data (used for pauses between tracks). */
enmTrackDataForm = TRACKDATAFORM_CDDA_PAUSE;
break;
case 0x10: /* CD-ROM mode 1 */
case 0x12:
enmTrackDataForm = TRACKDATAFORM_MODE1_2048;
break;
case 0x11:
case 0x13:
enmTrackDataForm = TRACKDATAFORM_MODE1_2352;
break;
case 0x14:
enmTrackDataForm = TRACKDATAFORM_MODE1_0;
break;
case 0x20: /* CD-ROM XA, CD-I */
case 0x22:
enmTrackDataForm = TRACKDATAFORM_XA_2336;
break;
case 0x21:
case 0x23:
enmTrackDataForm = TRACKDATAFORM_XA_2352;
break;
case 0x24:
enmTrackDataForm = TRACKDATAFORM_XA_0;
break;
case 0x31: /* CD-ROM Mode 2 */
case 0x33:
enmTrackDataForm = TRACKDATAFORM_MODE2_2352;
break;
case 0x30:
case 0x32:
enmTrackDataForm = TRACKDATAFORM_MODE2_2336;
break;
case 0x34:
enmTrackDataForm = TRACKDATAFORM_MODE2_0;
break;
default: /* Reserved, invalid mode. Log and leave default sector size. */
LogRel(("ATA: Invalid data form mode %d for current CUE sheet\n",
pbCueSheetEntry[3] & 0x3f));
}
/* Determine size of sub channel data based on data form field. */
switch ((pbCueSheetEntry[3] & 0xc0) >> 6)
{
case 0x00: /* Sub channel all zeroes, autogenerated by the drive. */
enmSubChnDataForm = SUBCHNDATAFORM_0;
break;
case 0x01:
case 0x03:
enmSubChnDataForm = SUBCHNDATAFORM_96;
break;
default:
LogRel(("ATA: Invalid sub-channel data form mode %u for current CUE sheet\n",
pbCueSheetEntry[3] & 0xc0));
}
pTrack->enmMainDataForm = enmTrackDataForm;
pTrack->enmSubChnDataForm = enmSubChnDataForm;
pTrack->iLbaStart = scsiMSF2LBA(&pbCueSheetEntry[5]);
if (pbCueSheetEntry[1] != 0xaa)
{
/* Calculate number of sectors from the next entry. */
int64_t iLbaNext = scsiMSF2LBA(&pbCueSheetEntry[5+8]);
pTrack->cSectors = iLbaNext - pTrack->iLbaStart;
}
else
{
pTrack->fFlags |= TRACK_FLAGS_LEAD_OUT;
pTrack->cSectors = 0;
}
pTrack->fFlags &= ~TRACK_FLAGS_UNDETECTED;
}
/**
* Update the track list from a SEND CUE SHEET request.
*
* @returns VBox status code.
* @param pTrackList Track list to update.
* @param pbCDB CDB of the SEND CUE SHEET request.
* @param pvBuf The CUE sheet.
*/
static int atapiTrackListUpdateFromSendCueSheet(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf)
{
int rc = VINF_SUCCESS;
unsigned cbCueSheet = scsiBE2H_U24(pbCDB + 6);
unsigned cTracks = cbCueSheet / 8;
AssertReturn(cbCueSheet % 8 == 0 && cTracks, VERR_INVALID_PARAMETER);
rc = atapiTrackListReallocate(pTrackList, cTracks, 0);
if (RT_SUCCESS(rc))
{
const uint8_t *pbCueSheet = (uint8_t *)pvBuf;
PTRACK pTrack = pTrackList->paTracks;
for (unsigned i = 0; i < cTracks; i++)
{
atapiTrackListEntryCreateFromCueSheetEntry(pTrack, pbCueSheet);
if (i == 0)
pTrack->fFlags |= TRACK_FLAGS_LEAD_IN;
pTrack++;
pbCueSheet += 8;
}
}
return rc;
}
static int atapiTrackListUpdateFromSendDvdStructure(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf)
{
RT_NOREF(pTrackList, pbCDB, pvBuf);
return VERR_NOT_IMPLEMENTED;
}
/**
* Update track list from formatted TOC data.
*
* @returns VBox status code.
* @param pTrackList The track list to update.
* @param iTrack The first track the TOC has data for.
* @param fMSF Flag whether block addresses are in MSF or LBA format.
* @param pbBuf Buffer holding the formatted TOC.
* @param cbBuffer Size of the buffer.
*/
static int atapiTrackListUpdateFromFormattedToc(PTRACKLIST pTrackList, uint8_t iTrack,
bool fMSF, const uint8_t *pbBuf, uint32_t cbBuffer)
{
RT_NOREF(iTrack, cbBuffer); /** @todo unused parameters */
int rc = VINF_SUCCESS;
unsigned cbToc = scsiBE2H_U16(pbBuf);
uint8_t iTrackFirst = pbBuf[2];
unsigned cTracks;
cbToc -= 2;
pbBuf += 4;
AssertReturn(cbToc % 8 == 0, VERR_INVALID_PARAMETER);
cTracks = cbToc / 8 + iTrackFirst;
rc = atapiTrackListReallocate(pTrackList, iTrackFirst + cTracks, ATAPI_TRACK_LIST_REALLOCATE_FLAGS_DONT_CLEAR);
if (RT_SUCCESS(rc))
{
PTRACK pTrack = &pTrackList->paTracks[iTrackFirst];
for (unsigned i = iTrackFirst; i < cTracks; i++)
{
if (pbBuf[1] & 0x4)
pTrack->enmMainDataForm = TRACKDATAFORM_MODE1_2048;
else
pTrack->enmMainDataForm = TRACKDATAFORM_CDDA;
pTrack->enmSubChnDataForm = SUBCHNDATAFORM_0;
if (fMSF)
pTrack->iLbaStart = scsiMSF2LBA(&pbBuf[4]);
else
pTrack->iLbaStart = scsiBE2H_U32(&pbBuf[4]);
if (pbBuf[2] != 0xaa)
{
/* Calculate number of sectors from the next entry. */
int64_t iLbaNext;
if (fMSF)
iLbaNext = scsiMSF2LBA(&pbBuf[4+8]);
else
iLbaNext = scsiBE2H_U32(&pbBuf[4+8]);
pTrack->cSectors = iLbaNext - pTrack->iLbaStart;
}
else
pTrack->cSectors = 0;
pTrack->fFlags &= ~TRACK_FLAGS_UNDETECTED;
pbBuf += 8;
pTrack++;
}
}
return rc;
}
static int atapiTrackListUpdateFromReadTocPmaAtip(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf)
{
int rc = VINF_SUCCESS;
uint16_t cbBuffer = scsiBE2H_U16(&pbCDB[7]);
bool fMSF = (pbCDB[1] & 0x2) != 0;
uint8_t uFmt = pbCDB[2] & 0xf;
uint8_t iTrack = pbCDB[6];
switch (uFmt)
{
case 0x00:
rc = atapiTrackListUpdateFromFormattedToc(pTrackList, iTrack, fMSF, (uint8_t *)pvBuf, cbBuffer);
break;
case 0x01:
case 0x02:
case 0x03:
case 0x04:
rc = VERR_NOT_IMPLEMENTED;
break;
case 0x05:
rc = VINF_SUCCESS; /* Does not give information about the tracklist. */
break;
default:
rc = VERR_INVALID_PARAMETER;
}
return rc;
}
static int atapiTrackListUpdateFromReadTrackInformation(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf)
{
RT_NOREF(pTrackList, pbCDB, pvBuf);
return VERR_NOT_IMPLEMENTED;
}
static int atapiTrackListUpdateFromReadDvdStructure(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf)
{
RT_NOREF(pTrackList, pbCDB, pvBuf);
return VERR_NOT_IMPLEMENTED;
}
static int atapiTrackListUpdateFromReadDiscInformation(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf)
{
RT_NOREF(pTrackList, pbCDB, pvBuf);
return VERR_NOT_IMPLEMENTED;
}
#ifdef LOG_ENABLED
/**
* Converts the given track data form to a string.
*
* @returns Track data form as a string.
* @param enmTrackDataForm The track main data form.
*/
static const char *atapiTrackListMainDataFormToString(TRACKDATAFORM enmTrackDataForm)
{
switch (enmTrackDataForm)
{
case TRACKDATAFORM_CDDA:
return "CD-DA";
case TRACKDATAFORM_CDDA_PAUSE:
return "CD-DA Pause";
case TRACKDATAFORM_MODE1_2048:
return "Mode 1 (2048 bytes)";
case TRACKDATAFORM_MODE1_2352:
return "Mode 1 (2352 bytes)";
case TRACKDATAFORM_MODE1_0:
return "Mode 1 (0 bytes)";
case TRACKDATAFORM_XA_2336:
return "XA (2336 bytes)";
case TRACKDATAFORM_XA_2352:
return "XA (2352 bytes)";
case TRACKDATAFORM_XA_0:
return "XA (0 bytes)";
case TRACKDATAFORM_MODE2_2336:
return "Mode 2 (2336 bytes)";
case TRACKDATAFORM_MODE2_2352:
return "Mode 2 (2352 bytes)";
case TRACKDATAFORM_MODE2_0:
return "Mode 2 (0 bytes)";
case TRACKDATAFORM_INVALID:
default:
return "Invalid";
}
}
/**
* Converts the given subchannel data form to a string.
*
* @returns Subchannel data form as a string.
* @param enmSubChnDataForm The subchannel main data form.
*/
static const char *atapiTrackListSubChnDataFormToString(SUBCHNDATAFORM enmSubChnDataForm)
{
switch (enmSubChnDataForm)
{
case SUBCHNDATAFORM_0:
return "0";
case SUBCHNDATAFORM_96:
return "96";
case SUBCHNDATAFORM_INVALID:
default:
return "Invalid";
}
}
/**
* Dump the complete track list to the release log.
*
* @returns nothing.
* @param pTrackList The track list to dump.
*/
static void atapiTrackListDump(PTRACKLIST pTrackList)
{
LogRel(("Track List: cTracks=%u\n", pTrackList->cTracksCurrent));
for (unsigned i = 0; i < pTrackList->cTracksCurrent; i++)
{
PTRACK pTrack = &pTrackList->paTracks[i];
LogRel((" Track %u: LBAStart=%lld cSectors=%u enmMainDataForm=%s enmSubChnDataForm=%s fFlags=[%s%s%s]\n",
i, pTrack->iLbaStart, pTrack->cSectors, atapiTrackListMainDataFormToString(pTrack->enmMainDataForm),
atapiTrackListSubChnDataFormToString(pTrack->enmSubChnDataForm),
pTrack->fFlags & TRACK_FLAGS_UNDETECTED ? "UNDETECTED " : "",
pTrack->fFlags & TRACK_FLAGS_LEAD_IN ? "Lead-In " : "",
pTrack->fFlags & TRACK_FLAGS_LEAD_OUT ? "Lead-Out" : ""));
}
}
#endif /* LOG_ENABLED */
DECLHIDDEN(int) ATAPIPassthroughTrackListCreateEmpty(PTRACKLIST *ppTrackList)
{
int rc = VERR_NO_MEMORY;
PTRACKLIST pTrackList = (PTRACKLIST)RTMemAllocZ(sizeof(TRACKLIST));
if (pTrackList)
{
rc = VINF_SUCCESS;
*ppTrackList = pTrackList;
}
return rc;
}
DECLHIDDEN(void) ATAPIPassthroughTrackListDestroy(PTRACKLIST pTrackList)
{
if (pTrackList->paTracks)
RTMemFree(pTrackList->paTracks);
RTMemFree(pTrackList);
}
DECLHIDDEN(void) ATAPIPassthroughTrackListClear(PTRACKLIST pTrackList)
{
AssertPtrReturnVoid(pTrackList);
pTrackList->cTracksCurrent = 0;
/* Mark all tracks as undetected. */
for (unsigned i = 0; i < pTrackList->cTracksMax; i++)
pTrackList->paTracks[i].fFlags |= TRACK_FLAGS_UNDETECTED;
}
DECLHIDDEN(int) ATAPIPassthroughTrackListUpdate(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf)
{
int rc = VINF_SUCCESS;
switch (pbCDB[0])
{
case SCSI_SEND_CUE_SHEET:
rc = atapiTrackListUpdateFromSendCueSheet(pTrackList, pbCDB, pvBuf);
break;
case SCSI_SEND_DVD_STRUCTURE:
rc = atapiTrackListUpdateFromSendDvdStructure(pTrackList, pbCDB, pvBuf);
break;
case SCSI_READ_TOC_PMA_ATIP:
rc = atapiTrackListUpdateFromReadTocPmaAtip(pTrackList, pbCDB, pvBuf);
break;
case SCSI_READ_TRACK_INFORMATION:
rc = atapiTrackListUpdateFromReadTrackInformation(pTrackList, pbCDB, pvBuf);
break;
case SCSI_READ_DVD_STRUCTURE:
rc = atapiTrackListUpdateFromReadDvdStructure(pTrackList, pbCDB, pvBuf);
break;
case SCSI_READ_DISC_INFORMATION:
rc = atapiTrackListUpdateFromReadDiscInformation(pTrackList, pbCDB, pvBuf);
break;
default:
LogRel(("ATAPI: Invalid opcode %#x while determining media layout\n", pbCDB[0]));
rc = VERR_INVALID_PARAMETER;
}
#ifdef LOG_ENABLED
atapiTrackListDump(pTrackList);
#endif
return rc;
}
DECLHIDDEN(uint32_t) ATAPIPassthroughTrackListGetSectorSizeFromLba(PTRACKLIST pTrackList, uint32_t iAtapiLba)
{
PTRACK pTrack = NULL;
uint32_t cbAtapiSector = 2048;
if (pTrackList->cTracksCurrent)
{
if ( iAtapiLba > UINT32_C(0xffff4fa1)
&& (int32_t)iAtapiLba < -150)
{
/* Lead-In area, this is always the first entry in the cue sheet. */
pTrack = pTrackList->paTracks;
Assert(pTrack->fFlags & TRACK_FLAGS_LEAD_IN);
LogFlowFunc(("Selected Lead-In area\n"));
}
else
{
int64_t iAtapiLba64 = (int32_t)iAtapiLba;
pTrack = &pTrackList->paTracks[1];
/* Go through the track list and find the correct entry. */
for (unsigned i = 1; i < pTrackList->cTracksCurrent - 1; i++)
{
if (pTrack->fFlags & TRACK_FLAGS_UNDETECTED)
continue;
if ( pTrack->iLbaStart <= iAtapiLba64
&& iAtapiLba64 < pTrack->iLbaStart + pTrack->cSectors)
break;
pTrack++;
}
}
if (pTrack)
{
switch (pTrack->enmMainDataForm)
{
case TRACKDATAFORM_CDDA:
case TRACKDATAFORM_MODE1_2352:
case TRACKDATAFORM_XA_2352:
case TRACKDATAFORM_MODE2_2352:
cbAtapiSector = 2352;
break;
case TRACKDATAFORM_MODE1_2048:
cbAtapiSector = 2048;
break;
case TRACKDATAFORM_CDDA_PAUSE:
case TRACKDATAFORM_MODE1_0:
case TRACKDATAFORM_XA_0:
case TRACKDATAFORM_MODE2_0:
cbAtapiSector = 0;
break;
case TRACKDATAFORM_XA_2336:
case TRACKDATAFORM_MODE2_2336:
cbAtapiSector = 2336;
break;
case TRACKDATAFORM_INVALID:
default:
AssertMsgFailed(("Invalid track data form %d\n", pTrack->enmMainDataForm));
}
switch (pTrack->enmSubChnDataForm)
{
case SUBCHNDATAFORM_0:
break;
case SUBCHNDATAFORM_96:
cbAtapiSector += 96;
break;
case SUBCHNDATAFORM_INVALID:
default:
AssertMsgFailed(("Invalid subchannel data form %d\n", pTrack->enmSubChnDataForm));
}
}
}
return cbAtapiSector;
}
static uint8_t atapiPassthroughCmdErrorSimple(uint8_t *pbSense, size_t cbSense, uint8_t uATAPISenseKey, uint8_t uATAPIASC)
{
memset(pbSense, '\0', cbSense);
if (RT_LIKELY(cbSense >= 13))
{
pbSense[0] = 0x70 | (1 << 7);
pbSense[2] = uATAPISenseKey & 0x0f;
pbSense[7] = 10;
pbSense[12] = uATAPIASC;
}
return SCSI_STATUS_CHECK_CONDITION;
}
DECLHIDDEN(bool) ATAPIPassthroughParseCdb(const uint8_t *pbCdb, size_t cbCdb, size_t cbBuf,
PTRACKLIST pTrackList, uint8_t *pbSense, size_t cbSense,
PDMMEDIATXDIR *penmTxDir, size_t *pcbXfer,
size_t *pcbSector, uint8_t *pu8ScsiSts)
{
uint32_t uLba = 0;
uint32_t cSectors = 0;
size_t cbSector = 0;
size_t cbXfer = 0;
bool fPassthrough = false;
PDMMEDIATXDIR enmTxDir = PDMMEDIATXDIR_NONE;
RT_NOREF(cbCdb);
switch (pbCdb[0])
{
/* First the commands we can pass through without further processing. */
case SCSI_BLANK:
case SCSI_CLOSE_TRACK_SESSION:
case SCSI_LOAD_UNLOAD_MEDIUM:
case SCSI_PAUSE_RESUME:
case SCSI_PLAY_AUDIO_10:
case SCSI_PLAY_AUDIO_12:
case SCSI_PLAY_AUDIO_MSF:
case SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL:
case SCSI_REPAIR_TRACK:
case SCSI_RESERVE_TRACK:
case SCSI_SCAN:
case SCSI_SEEK_10:
case SCSI_SET_CD_SPEED:
case SCSI_SET_READ_AHEAD:
case SCSI_START_STOP_UNIT:
case SCSI_STOP_PLAY_SCAN:
case SCSI_SYNCHRONIZE_CACHE:
case SCSI_TEST_UNIT_READY:
case SCSI_VERIFY_10:
fPassthrough = true;
break;
case SCSI_ERASE_10:
uLba = scsiBE2H_U32(pbCdb + 2);
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_FORMAT_UNIT:
cbXfer = cbBuf;
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_GET_CONFIGURATION:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_GET_EVENT_STATUS_NOTIFICATION:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_GET_PERFORMANCE:
cbXfer = cbBuf;
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_INQUIRY:
cbXfer = scsiBE2H_U16(pbCdb + 3);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_MECHANISM_STATUS:
cbXfer = scsiBE2H_U16(pbCdb + 8);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_MODE_SELECT_10:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_MODE_SENSE_10:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_10:
uLba = scsiBE2H_U32(pbCdb + 2);
cSectors = scsiBE2H_U16(pbCdb + 7);
cbSector = 2048;
cbXfer = cSectors * cbSector;
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_12:
uLba = scsiBE2H_U32(pbCdb + 2);
cSectors = scsiBE2H_U32(pbCdb + 6);
cbSector = 2048;
cbXfer = cSectors * cbSector;
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_BUFFER:
cbXfer = scsiBE2H_U24(pbCdb + 6);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_BUFFER_CAPACITY:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_CAPACITY:
cbXfer = 8;
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_CD:
case SCSI_READ_CD_MSF:
{
/* Get sector size based on the expected sector type field. */
switch ((pbCdb[1] >> 2) & 0x7)
{
case 0x0: /* All types. */
{
uint32_t iLbaStart;
if (pbCdb[0] == SCSI_READ_CD)
iLbaStart = scsiBE2H_U32(&pbCdb[2]);
else
iLbaStart = scsiMSF2LBA(&pbCdb[3]);
if (pTrackList)
cbSector = ATAPIPassthroughTrackListGetSectorSizeFromLba(pTrackList, iLbaStart);
else
cbSector = 2048; /* Might be incorrect if we couldn't determine the type. */
break;
}
case 0x1: /* CD-DA */
cbSector = 2352;
break;
case 0x2: /* Mode 1 */
cbSector = 2048;
break;
case 0x3: /* Mode 2 formless */
cbSector = 2336;
break;
case 0x4: /* Mode 2 form 1 */
cbSector = 2048;
break;
case 0x5: /* Mode 2 form 2 */
cbSector = 2324;
break;
default: /* Reserved */
AssertMsgFailed(("Unknown sector type\n"));
cbSector = 0; /** @todo we should probably fail the command here already. */
}
if (pbCdb[0] == SCSI_READ_CD)
cbXfer = scsiBE2H_U24(pbCdb + 6) * cbSector;
else /* SCSI_READ_MSF */
{
cSectors = scsiMSF2LBA(pbCdb + 6) - scsiMSF2LBA(pbCdb + 3);
if (cSectors > 32)
cSectors = 32; /* Limit transfer size to 64~74K. Safety first. In any case this can only harm software doing CDDA extraction. */
cbXfer = cSectors * cbSector;
}
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
}
case SCSI_READ_DISC_INFORMATION:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_DVD_STRUCTURE:
cbXfer = scsiBE2H_U16(pbCdb + 8);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_FORMAT_CAPACITIES:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_SUBCHANNEL:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_TOC_PMA_ATIP:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_READ_TRACK_INFORMATION:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_REPORT_KEY:
cbXfer = scsiBE2H_U16(pbCdb + 8);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_REQUEST_SENSE:
cbXfer = pbCdb[4];
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_SEND_CUE_SHEET:
cbXfer = scsiBE2H_U24(pbCdb + 6);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_SEND_DVD_STRUCTURE:
cbXfer = scsiBE2H_U16(pbCdb + 8);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_SEND_EVENT:
cbXfer = scsiBE2H_U16(pbCdb + 8);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_SEND_KEY:
cbXfer = scsiBE2H_U16(pbCdb + 8);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_SEND_OPC_INFORMATION:
cbXfer = scsiBE2H_U16(pbCdb + 7);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_SET_STREAMING:
cbXfer = scsiBE2H_U16(pbCdb + 9);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_WRITE_10:
case SCSI_WRITE_AND_VERIFY_10:
uLba = scsiBE2H_U32(pbCdb + 2);
cSectors = scsiBE2H_U16(pbCdb + 7);
if (pTrackList)
cbSector = ATAPIPassthroughTrackListGetSectorSizeFromLba(pTrackList, uLba);
else
cbSector = 2048;
cbXfer = cSectors * cbSector;
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_WRITE_12:
uLba = scsiBE2H_U32(pbCdb + 2);
cSectors = scsiBE2H_U32(pbCdb + 6);
if (pTrackList)
cbSector = ATAPIPassthroughTrackListGetSectorSizeFromLba(pTrackList, uLba);
else
cbSector = 2048;
cbXfer = cSectors * cbSector;
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
case SCSI_WRITE_BUFFER:
switch (pbCdb[1] & 0x1f)
{
case 0x04: /* download microcode */
case 0x05: /* download microcode and save */
case 0x06: /* download microcode with offsets */
case 0x07: /* download microcode with offsets and save */
case 0x0e: /* download microcode with offsets and defer activation */
case 0x0f: /* activate deferred microcode */
LogRel(("ATAPI: CD-ROM passthrough command attempted to update firmware, blocked\n"));
*pu8ScsiSts = atapiPassthroughCmdErrorSimple(pbSense, cbSense, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET);
break;
default:
cbXfer = scsiBE2H_U16(pbCdb + 6);
enmTxDir = PDMMEDIATXDIR_TO_DEVICE;
fPassthrough = true;
break;
}
break;
case SCSI_REPORT_LUNS: /* Not part of MMC-3, but used by Windows. */
cbXfer = scsiBE2H_U32(pbCdb + 6);
enmTxDir = PDMMEDIATXDIR_FROM_DEVICE;
fPassthrough = true;
break;
case SCSI_REZERO_UNIT:
/* Obsolete command used by cdrecord. What else would one expect?
* This command is not sent to the drive, it is handled internally,
* as the Linux kernel doesn't like it (message "scsi: unknown
* opcode 0x01" in syslog) and replies with a sense code of 0,
* which sends cdrecord to an endless loop. */
*pu8ScsiSts = atapiPassthroughCmdErrorSimple(pbSense, cbSense, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
break;
default:
LogRel(("ATAPI: Passthrough unimplemented for command %#x\n", pbCdb[0]));
*pu8ScsiSts = atapiPassthroughCmdErrorSimple(pbSense, cbSense, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE);
break;
}
if (fPassthrough)
{
*penmTxDir = enmTxDir;
*pcbXfer = cbXfer;
*pcbSector = cbSector;
}
return fPassthrough;
}
| 32,161 | 11,817 |
#include "bar.hpp"
using namespace odfaeg::graphic;
using namespace odfaeg::math;
using namespace odfaeg::physic;
Bar::Bar(Vec2f position, Vec2f size) : Entity(position, size, size * 0.5f, "E_BAR") {
BoundingVolume* bv = new BoundingBox(position.x, position.y, 0 ,size.x, size.y, 0);
setCollisionVolume(bv);
}
| 318 | 126 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/search/suggestions/suggestions_service.h"
#include <map>
#include <string>
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/prefs/pref_service.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/search/suggestions/proto/suggestions.pb.h"
#include "chrome/browser/search/suggestions/suggestions_service_factory.h"
#include "chrome/test/base/testing_profile.h"
#include "components/variations/entropy_provider.h"
#include "components/variations/variations_associated_data.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "net/url_request/url_request_status.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kFakeSuggestionsURL[] = "https://mysuggestions.com/proto";
const char kTestTitle[] = "a title";
const char kTestUrl[] = "http://go.com";
scoped_ptr<net::FakeURLFetcher> CreateURLFetcher(
const GURL& url, net::URLFetcherDelegate* delegate,
const std::string& response_data, net::HttpStatusCode response_code,
net::URLRequestStatus::Status status) {
scoped_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher(
url, delegate, response_data, response_code, status));
if (response_code == net::HTTP_OK) {
scoped_refptr<net::HttpResponseHeaders> download_headers(
new net::HttpResponseHeaders(""));
download_headers->AddHeader("Content-Type: text/html");
fetcher->set_response_headers(download_headers);
}
return fetcher.Pass();
}
} // namespace
namespace suggestions {
class SuggestionsServiceTest : public testing::Test {
public:
void CheckSuggestionsData(const SuggestionsProfile& suggestions_profile) {
EXPECT_EQ(1, suggestions_profile.suggestions_size());
EXPECT_EQ(kTestTitle, suggestions_profile.suggestions(0).title());
EXPECT_EQ(kTestUrl, suggestions_profile.suggestions(0).url());
++suggestions_data_check_count_;
}
void ExpectEmptySuggestionsProfile(const SuggestionsProfile& profile) {
EXPECT_EQ(0, profile.suggestions_size());
++suggestions_empty_data_count_;
}
int suggestions_data_check_count_;
int suggestions_empty_data_count_;
protected:
SuggestionsServiceTest()
: suggestions_data_check_count_(0),
suggestions_empty_data_count_(0),
factory_(NULL, base::Bind(&CreateURLFetcher)) {
profile_ = profile_builder_.Build();
}
virtual ~SuggestionsServiceTest() {}
// Enables the "ChromeSuggestions.Group1" field trial.
void EnableFieldTrial(const std::string& url) {
// Clear the existing |field_trial_list_| to avoid firing a DCHECK.
field_trial_list_.reset(NULL);
field_trial_list_.reset(
new base::FieldTrialList(new metrics::SHA1EntropyProvider("foo")));
chrome_variations::testing::ClearAllVariationParams();
std::map<std::string, std::string> params;
params[kSuggestionsFieldTrialStateParam] =
kSuggestionsFieldTrialStateEnabled;
params[kSuggestionsFieldTrialURLParam] = url;
chrome_variations::AssociateVariationParams(kSuggestionsFieldTrialName,
"Group1", params);
field_trial_ = base::FieldTrialList::CreateFieldTrial(
kSuggestionsFieldTrialName, "Group1");
field_trial_->group();
}
SuggestionsService* CreateSuggestionsService() {
SuggestionsServiceFactory* suggestions_service_factory =
SuggestionsServiceFactory::GetInstance();
return suggestions_service_factory->GetForProfile(profile_.get());
}
protected:
net::FakeURLFetcherFactory factory_;
private:
content::TestBrowserThreadBundle thread_bundle_;
scoped_ptr<base::FieldTrialList> field_trial_list_;
scoped_refptr<base::FieldTrial> field_trial_;
TestingProfile::Builder profile_builder_;
scoped_ptr<TestingProfile> profile_;
DISALLOW_COPY_AND_ASSIGN(SuggestionsServiceTest);
};
TEST_F(SuggestionsServiceTest, ServiceBeingCreated) {
// Field trial not enabled.
EXPECT_TRUE(CreateSuggestionsService() == NULL);
// Field trial enabled.
EnableFieldTrial("");
EXPECT_TRUE(CreateSuggestionsService() != NULL);
}
TEST_F(SuggestionsServiceTest, FetchSuggestionsData) {
// Field trial enabled with a specific suggestions URL.
EnableFieldTrial(kFakeSuggestionsURL);
SuggestionsService* suggestions_service = CreateSuggestionsService();
EXPECT_TRUE(suggestions_service != NULL);
SuggestionsProfile suggestions_profile;
ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();
suggestion->set_title(kTestTitle);
suggestion->set_url(kTestUrl);
factory_.SetFakeResponse(GURL(kFakeSuggestionsURL),
suggestions_profile.SerializeAsString(),
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
// Send the request. The data will be returned to the callback.
suggestions_service->FetchSuggestionsData(
base::Bind(&SuggestionsServiceTest::CheckSuggestionsData,
base::Unretained(this)));
// Send the request a second time.
suggestions_service->FetchSuggestionsData(
base::Bind(&SuggestionsServiceTest::CheckSuggestionsData,
base::Unretained(this)));
// (Testing only) wait until suggestion fetch is complete.
base::MessageLoop::current()->RunUntilIdle();
// Ensure that CheckSuggestionsData() ran twice.
EXPECT_EQ(2, suggestions_data_check_count_);
}
TEST_F(SuggestionsServiceTest, FetchSuggestionsDataRequestError) {
// Field trial enabled with a specific suggestions URL.
EnableFieldTrial(kFakeSuggestionsURL);
SuggestionsService* suggestions_service = CreateSuggestionsService();
EXPECT_TRUE(suggestions_service != NULL);
// Fake a request error.
factory_.SetFakeResponse(GURL(kFakeSuggestionsURL),
"irrelevant",
net::HTTP_OK,
net::URLRequestStatus::FAILED);
// Send the request. Empty data will be returned to the callback.
suggestions_service->FetchSuggestionsData(
base::Bind(&SuggestionsServiceTest::ExpectEmptySuggestionsProfile,
base::Unretained(this)));
// (Testing only) wait until suggestion fetch is complete.
base::MessageLoop::current()->RunUntilIdle();
// Ensure that ExpectEmptySuggestionsProfile ran once.
EXPECT_EQ(1, suggestions_empty_data_count_);
}
TEST_F(SuggestionsServiceTest, FetchSuggestionsDataResponseNotOK) {
// Field trial enabled with a specific suggestions URL.
EnableFieldTrial(kFakeSuggestionsURL);
SuggestionsService* suggestions_service = CreateSuggestionsService();
EXPECT_TRUE(suggestions_service != NULL);
// Response code != 200.
factory_.SetFakeResponse(GURL(kFakeSuggestionsURL),
"irrelevant",
net::HTTP_BAD_REQUEST,
net::URLRequestStatus::SUCCESS);
// Send the request. Empty data will be returned to the callback.
suggestions_service->FetchSuggestionsData(
base::Bind(&SuggestionsServiceTest::ExpectEmptySuggestionsProfile,
base::Unretained(this)));
// (Testing only) wait until suggestion fetch is complete.
base::MessageLoop::current()->RunUntilIdle();
// Ensure that ExpectEmptySuggestionsProfile ran once.
EXPECT_EQ(1, suggestions_empty_data_count_);
}
} // namespace suggestions
| 7,792 | 2,393 |
#pragma once
#include <memory>
#include <random>
#include "../Types.hpp"
#include "AudioFormat.hpp"
namespace sound
{
class RawAudioBuffer;
class Mixer
{
public:
Mixer(const AudioFormat& format);
void setFormat(const AudioFormat& format);
void mix(std::shared_ptr<RawAudioBuffer> rawAudioBuffer);
private:
void mixUnorm8(Range<uint8_t> data);
void mixUnorm16(Range<uint16_t> data);
void mixUnorm32(Range<uint32_t> data);
void mixFloat32(Range<float> data);
AudioFormat m_format;
float m_mixerTime;
std::mt19937 m_gen;
};
}
| 640 | 218 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/nearby_sharing/nearby_per_session_discovery_manager.h"
#include <string>
#include "base/callback_forward.h"
#include "base/callback_helpers.h"
#include "base/optional.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/mock_callback.h"
#include "chrome/browser/nearby_sharing/mock_nearby_sharing_service.h"
#include "chrome/browser/nearby_sharing/share_target.h"
#include "chrome/browser/nearby_sharing/transfer_metadata.h"
#include "chrome/browser/nearby_sharing/transfer_metadata_builder.h"
#include "chrome/browser/ui/webui/nearby_share/nearby_share.mojom.h"
#include "content/public/test/browser_task_environment.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
using testing::_;
MATCHER_P(MatchesTarget, target, "") {
return arg.id == target.id;
}
const char kTextAttachmentBody[] = "Test text payload";
std::vector<std::unique_ptr<Attachment>> CreateTextAttachments() {
std::vector<std::unique_ptr<Attachment>> attachments;
attachments.push_back(std::make_unique<TextAttachment>(
TextAttachment::Type::kText, kTextAttachmentBody, /*title=*/base::nullopt,
/*mime_type=*/base::nullopt));
return attachments;
}
std::vector<std::unique_ptr<Attachment>> CreateFileAttachments(
size_t count,
std::string mime_type,
sharing::mojom::FileMetadata::Type type) {
std::vector<std::unique_ptr<Attachment>> attachments;
for (size_t i = 0; i < count; i++) {
std::string file_name("File-" + base::NumberToString(i));
attachments.push_back(
std::make_unique<FileAttachment>(i, i, file_name, mime_type, type));
}
return attachments;
}
void ExpectTextAttachment(
const std::string& text_body,
const std::vector<std::unique_ptr<Attachment>>& attachments) {
ASSERT_EQ(1u, attachments.size());
ASSERT_TRUE(attachments[0]);
ASSERT_EQ(Attachment::Family::kText, attachments[0]->family());
auto* text_attachment = static_cast<TextAttachment*>(attachments[0].get());
EXPECT_EQ(text_body, text_attachment->text_body());
}
class MockShareTargetListener
: public nearby_share::mojom::ShareTargetListener {
public:
MockShareTargetListener() = default;
~MockShareTargetListener() override = default;
mojo::PendingRemote<ShareTargetListener> Bind() {
return receiver_.BindNewPipeAndPassRemote();
}
void reset() { receiver_.reset(); }
// nearby_share::mojom::ShareTargetListener:
MOCK_METHOD(void, OnShareTargetDiscovered, (const ShareTarget&), (override));
MOCK_METHOD(void, OnShareTargetLost, (const ShareTarget&), (override));
private:
mojo::Receiver<ShareTargetListener> receiver_{this};
};
class MockTransferUpdateListener
: public nearby_share::mojom::TransferUpdateListener {
public:
MockTransferUpdateListener() = default;
~MockTransferUpdateListener() override = default;
void Bind(mojo::PendingReceiver<TransferUpdateListener> receiver) {
return receiver_.Bind(std::move(receiver));
}
// nearby_share::mojom::TransferUpdateListener:
MOCK_METHOD(void,
OnTransferUpdate,
(nearby_share::mojom::TransferStatus status,
const base::Optional<std::string>&),
(override));
private:
mojo::Receiver<TransferUpdateListener> receiver_{this};
};
class NearbyPerSessionDiscoveryManagerTest : public testing::Test {
public:
using MockSelectShareTargetCallback = base::MockCallback<
NearbyPerSessionDiscoveryManager::SelectShareTargetCallback>;
using MockStartDiscoveryCallback = base::MockCallback<
NearbyPerSessionDiscoveryManager::StartDiscoveryCallback>;
using MockGetPayloadPreviewCallback = base::MockCallback<
nearby_share::mojom::DiscoveryManager::GetPayloadPreviewCallback>;
enum SharingServiceState { None, Transferring, Connecting, Scanning };
NearbyPerSessionDiscoveryManagerTest() = default;
~NearbyPerSessionDiscoveryManagerTest() override = default;
void SetUp() override {
EXPECT_CALL(sharing_service(), IsTransferring())
.WillRepeatedly(testing::ReturnPointee(&is_transferring_));
EXPECT_CALL(sharing_service(), IsConnecting())
.WillRepeatedly(testing::ReturnPointee(&is_connecting_));
EXPECT_CALL(sharing_service(), IsScanning())
.WillRepeatedly(testing::ReturnPointee(&is_scanning_));
}
void SetSharingServiceState(SharingServiceState state) {
is_transferring_ = state == SharingServiceState::Transferring;
is_connecting_ = state == SharingServiceState::Connecting;
is_scanning_ = state == SharingServiceState::Scanning;
}
MockNearbySharingService& sharing_service() { return sharing_service_; }
NearbyPerSessionDiscoveryManager& manager() { return manager_; }
private:
content::BrowserTaskEnvironment task_environment_;
MockNearbySharingService sharing_service_;
NearbyPerSessionDiscoveryManager manager_{&sharing_service_,
CreateTextAttachments()};
bool is_transferring_ = false;
bool is_scanning_ = false;
bool is_connecting_ = false;
};
} // namespace
TEST_F(NearbyPerSessionDiscoveryManagerTest, CreateDestroyWithoutRegistering) {
EXPECT_CALL(sharing_service(), RegisterSendSurface(&manager(), &manager(), _))
.Times(0);
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.Times(0);
{
NearbyPerSessionDiscoveryManager manager(&sharing_service(),
CreateTextAttachments());
// Creating and destroying an instance should not register itself with the
// NearbySharingService.
}
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, StartDiscovery_Success) {
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
MockStartDiscoveryCallback callback;
EXPECT_CALL(
callback,
Run(
/*result=*/nearby_share::mojom::StartDiscoveryResult::kSuccess));
EXPECT_CALL(
sharing_service(),
RegisterSendSurface(&manager(), &manager(),
NearbySharingService::SendSurfaceState::kForeground))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.Times(0); // Should not be called!
MockShareTargetListener listener;
manager().StartDiscovery(listener.Bind(), callback.Get());
// Reset the listener here like the UI does when switching pages.
listener.reset();
// We have to run util idle to give the disconnect handler a chance to run.
// We no longer have a disconnect handler, but we want to very that once the
// mojo connection is torn down, that we don't unregister.
base::RunLoop run_loop;
run_loop.RunUntilIdle();
// Verify that UnregisterSendSurface was NOT called due to the disconnect.
// This previously failed when disconnect handler was being registered.
EXPECT_TRUE(::testing::Mock::VerifyAndClearExpectations(&sharing_service()));
// However, we do expect UnregisterSendSurface to be called from the
// destructor.
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, StartDiscovery_ErrorInProgress) {
MockStartDiscoveryCallback callback;
MockShareTargetListener listener;
EXPECT_CALL(callback,
Run(/*result=*/nearby_share::mojom::StartDiscoveryResult::
kErrorInProgressTransferring));
SetSharingServiceState(SharingServiceState::Transferring);
manager().StartDiscovery(listener.Bind(), callback.Get());
listener.reset();
EXPECT_CALL(callback,
Run(/*result=*/nearby_share::mojom::StartDiscoveryResult::
kErrorInProgressTransferring));
SetSharingServiceState(SharingServiceState::Connecting);
manager().StartDiscovery(listener.Bind(), callback.Get());
listener.reset();
EXPECT_CALL(callback,
Run(/*result=*/nearby_share::mojom::StartDiscoveryResult::
kErrorInProgressTransferring));
SetSharingServiceState(SharingServiceState::Scanning);
manager().StartDiscovery(listener.Bind(), callback.Get());
listener.reset();
EXPECT_CALL(
callback,
Run(/*result=*/nearby_share::mojom::StartDiscoveryResult::kSuccess));
SetSharingServiceState(SharingServiceState::None);
manager().StartDiscovery(listener.Bind(), callback.Get());
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, StartDiscovery_Error) {
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
MockStartDiscoveryCallback callback;
EXPECT_CALL(
callback,
Run(
/*result=*/nearby_share::mojom::StartDiscoveryResult::kErrorGeneric));
EXPECT_CALL(
sharing_service(),
RegisterSendSurface(&manager(), &manager(),
NearbySharingService::SendSurfaceState::kForeground))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kError));
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.Times(0);
MockShareTargetListener listener;
manager().StartDiscovery(listener.Bind(), callback.Get());
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, OnShareTargetDiscovered) {
MockShareTargetListener listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
manager().StartDiscovery(listener.Bind(), base::DoNothing());
ShareTarget share_target;
base::RunLoop run_loop;
EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target)))
.WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
manager().OnShareTargetDiscovered(share_target);
run_loop.Run();
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest,
OnShareTargetDiscovered_DuplicateDeviceId) {
MockShareTargetListener listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
manager().StartDiscovery(listener.Bind(), base::DoNothing());
ShareTarget share_target1;
share_target1.device_id = "device_id";
ShareTarget share_target2;
share_target2.device_id = "device_id";
{
base::RunLoop run_loop;
EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target1)))
.WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
manager().OnShareTargetDiscovered(share_target1);
run_loop.Run();
}
// If a newly discovered share target has the same device ID as a previously
// discovered share target, remove the old share target then add the new share
// target.
{
base::RunLoop run_loop;
EXPECT_CALL(listener, OnShareTargetLost(MatchesTarget(share_target1)));
EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target2)))
.WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
manager().OnShareTargetDiscovered(share_target2);
run_loop.Run();
}
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, OnShareTargetLost) {
MockShareTargetListener listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
manager().StartDiscovery(listener.Bind(), base::DoNothing());
ShareTarget share_target;
// A share-target-lost notification should only be sent if the lost share
// target has already been discovered and has not already been removed from
// the list of discovered devices.
EXPECT_CALL(listener, OnShareTargetLost(MatchesTarget(share_target)))
.Times(0);
manager().OnShareTargetLost(share_target);
{
base::RunLoop run_loop;
EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target)))
.WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
manager().OnShareTargetDiscovered(share_target);
run_loop.Run();
}
{
base::RunLoop run_loop;
EXPECT_CALL(listener, OnShareTargetLost(MatchesTarget(share_target)))
.WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
manager().OnShareTargetLost(share_target);
run_loop.Run();
}
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, SelectShareTarget_Invalid) {
MockShareTargetListener listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
manager().StartDiscovery(listener.Bind(), base::DoNothing());
MockSelectShareTargetCallback callback;
EXPECT_CALL(
callback,
Run(nearby_share::mojom::SelectShareTargetResult::kInvalidShareTarget,
testing::IsFalse(), testing::IsFalse()));
manager().SelectShareTarget({}, callback.Get());
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, SelectShareTarget_SendSuccess) {
// Setup share target
MockShareTargetListener listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
manager().StartDiscovery(listener.Bind(), base::DoNothing());
ShareTarget share_target;
manager().OnShareTargetDiscovered(share_target);
MockSelectShareTargetCallback callback;
EXPECT_CALL(callback, Run(nearby_share::mojom::SelectShareTargetResult::kOk,
testing::IsTrue(), testing::IsTrue()));
EXPECT_CALL(sharing_service(), SendAttachments(_, _))
.WillOnce(testing::Invoke(
[&share_target](
const ShareTarget& target,
std::vector<std::unique_ptr<Attachment>> attachments) {
EXPECT_EQ(share_target.id, target.id);
ExpectTextAttachment(kTextAttachmentBody, attachments);
return NearbySharingService::StatusCodes::kOk;
}));
manager().SelectShareTarget(share_target.id, callback.Get());
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, SelectShareTarget_SendError) {
// Setup share target
MockShareTargetListener listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
manager().StartDiscovery(listener.Bind(), base::DoNothing());
ShareTarget share_target;
manager().OnShareTargetDiscovered(share_target);
// Expect an error if NearbySharingService::Send*() fails.
MockSelectShareTargetCallback callback;
EXPECT_CALL(callback,
Run(nearby_share::mojom::SelectShareTargetResult::kError,
testing::IsFalse(), testing::IsFalse()));
EXPECT_CALL(sharing_service(), SendAttachments(_, _))
.WillOnce(testing::Invoke(
[&share_target](
const ShareTarget& target,
std::vector<std::unique_ptr<Attachment>> attachments) {
EXPECT_EQ(share_target.id, target.id);
ExpectTextAttachment(kTextAttachmentBody, attachments);
return NearbySharingService::StatusCodes::kError;
}));
manager().SelectShareTarget(share_target.id, callback.Get());
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, OnTransferUpdate_WaitRemote) {
// Setup share target
MockShareTargetListener listener;
MockTransferUpdateListener transfer_listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
base::RunLoop run_loop;
EXPECT_CALL(transfer_listener, OnTransferUpdate(_, _))
.WillOnce(testing::Invoke(
[&run_loop](nearby_share::mojom::TransferStatus status,
const base::Optional<std::string>& token) {
EXPECT_EQ(
nearby_share::mojom::TransferStatus::kAwaitingRemoteAcceptance,
status);
EXPECT_FALSE(token.has_value());
run_loop.Quit();
}));
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
manager().StartDiscovery(listener.Bind(), base::DoNothing());
ShareTarget share_target;
EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target)))
.Times(1);
manager().OnShareTargetDiscovered(share_target);
MockSelectShareTargetCallback callback;
EXPECT_CALL(callback, Run(nearby_share::mojom::SelectShareTargetResult::kOk,
testing::IsTrue(), testing::IsTrue()))
.WillOnce(testing::Invoke(
[&transfer_listener](
nearby_share::mojom::SelectShareTargetResult result,
mojo::PendingReceiver<nearby_share::mojom::TransferUpdateListener>
listener,
mojo::PendingRemote<nearby_share::mojom::ConfirmationManager>
manager) { transfer_listener.Bind(std::move(listener)); }));
EXPECT_CALL(sharing_service(), SendAttachments(_, _))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
manager().SelectShareTarget(share_target.id, callback.Get());
auto metadata =
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kAwaitingRemoteAcceptance)
.build();
manager().OnTransferUpdate(share_target, metadata);
run_loop.Run();
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, OnTransferUpdate_WaitLocal) {
// Setup share target
MockShareTargetListener listener;
MockTransferUpdateListener transfer_listener;
EXPECT_CALL(sharing_service(),
RegisterSendSurface(testing::_, testing::_, testing::_))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
const std::string expected_token = "Test Token";
base::RunLoop run_loop;
EXPECT_CALL(transfer_listener, OnTransferUpdate(_, _))
.WillOnce(testing::Invoke([&run_loop, &expected_token](
nearby_share::mojom::TransferStatus status,
const base::Optional<std::string>& token) {
EXPECT_EQ(
nearby_share::mojom::TransferStatus::kAwaitingLocalConfirmation,
status);
EXPECT_EQ(expected_token, token);
run_loop.Quit();
}));
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
manager().StartDiscovery(listener.Bind(), base::DoNothing());
ShareTarget share_target;
EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target)))
.Times(1);
manager().OnShareTargetDiscovered(share_target);
MockSelectShareTargetCallback callback;
EXPECT_CALL(callback, Run(nearby_share::mojom::SelectShareTargetResult::kOk,
testing::IsTrue(), testing::IsTrue()))
.WillOnce(testing::Invoke(
[&transfer_listener](
nearby_share::mojom::SelectShareTargetResult result,
mojo::PendingReceiver<nearby_share::mojom::TransferUpdateListener>
listener,
mojo::PendingRemote<nearby_share::mojom::ConfirmationManager>
manager) { transfer_listener.Bind(std::move(listener)); }));
EXPECT_CALL(sharing_service(), SendAttachments(_, _))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
manager().SelectShareTarget(share_target.id, callback.Get());
auto metadata =
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kAwaitingLocalConfirmation)
.set_token(expected_token)
.build();
manager().OnTransferUpdate(share_target, metadata);
run_loop.Run();
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, TransferUpdateWithoutListener) {
MockStartDiscoveryCallback callback;
EXPECT_CALL(
callback,
Run(
/*result=*/nearby_share::mojom::StartDiscoveryResult::kSuccess));
EXPECT_CALL(
sharing_service(),
RegisterSendSurface(&manager(), &manager(),
NearbySharingService::SendSurfaceState::kForeground))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.Times(0); // Should not be called!
EXPECT_CALL(sharing_service(), IsTransferring()).Times(1);
MockShareTargetListener listener;
manager().StartDiscovery(listener.Bind(), callback.Get());
// It is possible that during registration if a transfer is in progress
// already we might get a transfer update before selecting the share target.
// This used to cause a crash due to transfer_update_listener_ not being
// bound.
ShareTarget share_target;
manager().OnTransferUpdate(
share_target, TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kComplete)
.build());
// However, we do expect UnregisterSendSurface to be called from the
// destructor.
EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager()))
.WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk));
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewText) {
NearbyPerSessionDiscoveryManager manager(&sharing_service(),
CreateTextAttachments());
MockGetPayloadPreviewCallback callback;
nearby_share::mojom::PayloadPreview payload_preview;
EXPECT_CALL(callback, Run(_))
.WillOnce(testing::SaveArgPointee<0>(&payload_preview));
manager.GetPayloadPreview(callback.Get());
EXPECT_EQ(payload_preview.description, kTextAttachmentBody);
EXPECT_EQ(payload_preview.file_count, 0);
EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kText);
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewSingleVideo) {
NearbyPerSessionDiscoveryManager manager(
&sharing_service(),
CreateFileAttachments(/*count=*/1, /*mime_type=*/"",
/*type=*/FileAttachment::Type::kVideo));
MockGetPayloadPreviewCallback callback;
nearby_share::mojom::PayloadPreview payload_preview;
EXPECT_CALL(callback, Run(_))
.WillOnce(testing::SaveArgPointee<0>(&payload_preview));
manager.GetPayloadPreview(callback.Get());
EXPECT_EQ(payload_preview.description, "File-0");
EXPECT_EQ(payload_preview.file_count, 1);
EXPECT_EQ(payload_preview.share_type,
nearby_share::mojom::ShareType::kVideoFile);
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewSinglePDF) {
NearbyPerSessionDiscoveryManager manager(
&sharing_service(),
CreateFileAttachments(/*count=*/1, /*mime_type=*/"application/pdf",
/*type=*/FileAttachment::Type::kUnknown));
MockGetPayloadPreviewCallback callback;
nearby_share::mojom::PayloadPreview payload_preview;
EXPECT_CALL(callback, Run(_))
.WillOnce(testing::SaveArgPointee<0>(&payload_preview));
manager.GetPayloadPreview(callback.Get());
EXPECT_EQ(payload_preview.description, "File-0");
EXPECT_EQ(payload_preview.file_count, 1);
EXPECT_EQ(payload_preview.share_type,
nearby_share::mojom::ShareType::kPdfFile);
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewSingleUnknownFile) {
NearbyPerSessionDiscoveryManager manager(
&sharing_service(),
CreateFileAttachments(/*count=*/1, /*mime_type=*/"",
/*type=*/FileAttachment::Type::kUnknown));
MockGetPayloadPreviewCallback callback;
nearby_share::mojom::PayloadPreview payload_preview;
EXPECT_CALL(callback, Run(_))
.WillOnce(testing::SaveArgPointee<0>(&payload_preview));
manager.GetPayloadPreview(callback.Get());
EXPECT_EQ(payload_preview.description, "File-0");
EXPECT_EQ(payload_preview.file_count, 1);
EXPECT_EQ(payload_preview.share_type,
nearby_share::mojom::ShareType::kUnknownFile);
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewMultipleFiles) {
NearbyPerSessionDiscoveryManager manager(
&sharing_service(),
CreateFileAttachments(/*count=*/2, /*mime_type=*/"",
/*type=*/FileAttachment::Type::kUnknown));
MockGetPayloadPreviewCallback callback;
nearby_share::mojom::PayloadPreview payload_preview;
EXPECT_CALL(callback, Run(_))
.WillOnce(testing::SaveArgPointee<0>(&payload_preview));
manager.GetPayloadPreview(callback.Get());
EXPECT_EQ(payload_preview.description, "File-0");
EXPECT_EQ(payload_preview.file_count, 2);
EXPECT_EQ(payload_preview.share_type,
nearby_share::mojom::ShareType::kMultipleFiles);
}
TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewNoAttachments) {
NearbyPerSessionDiscoveryManager manager(
&sharing_service(),
CreateFileAttachments(/*count=*/0, /*mime_type=*/"",
/*type=*/FileAttachment::Type::kUnknown));
MockGetPayloadPreviewCallback callback;
nearby_share::mojom::PayloadPreview payload_preview;
EXPECT_CALL(callback, Run(_))
.WillOnce(testing::SaveArgPointee<0>(&payload_preview));
manager.GetPayloadPreview(callback.Get());
EXPECT_EQ(payload_preview.description, "");
EXPECT_EQ(payload_preview.file_count, 0);
EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kText);
}
| 27,224 | 8,541 |
/*
// Copyright (c) 2015-2018 Pierre Guillot.
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/
#include "PluginProcessor.h"
#include "PluginParameter.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// MIDI METHODS //
//////////////////////////////////////////////////////////////////////////////////////////////
void CamomileAudioProcessor::receiveNoteOn(const int channel, const int pitch, const int velocity)
{
if(velocity == 0)
{
m_midi_buffer_out.addEvent(MidiMessage::noteOff(channel, pitch, uint8(0)), m_audio_advancement);
}
else
{
m_midi_buffer_out.addEvent(MidiMessage::noteOn(channel, pitch, static_cast<uint8>(velocity)), m_audio_advancement);
}
}
void CamomileAudioProcessor::receiveControlChange(const int channel, const int controller, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::controllerEvent(channel, controller, value), m_audio_advancement);
}
void CamomileAudioProcessor::receiveProgramChange(const int channel, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::programChange(channel, value), m_audio_advancement);
}
void CamomileAudioProcessor::receivePitchBend(const int channel, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::pitchWheel(channel, value + 8192), m_audio_advancement);
}
void CamomileAudioProcessor::receiveAftertouch(const int channel, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::channelPressureChange(channel, value), m_audio_advancement);
}
void CamomileAudioProcessor::receivePolyAftertouch(const int channel, const int pitch, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::aftertouchChange(channel, pitch, value), m_audio_advancement);
}
void CamomileAudioProcessor::receiveMidiByte(const int port, const int byte)
{
m_midi_buffer_out.addEvent(MidiMessage(byte), m_audio_advancement);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// PRINT METHOD //
//////////////////////////////////////////////////////////////////////////////////////////////
void CamomileAudioProcessor::receivePrint(const std::string& message)
{
if(!message.empty())
{
if(!message.compare(0, 6, "error:"))
{
std::string const temp(message.begin()+7, message.end());
add(ConsoleLevel::Error, temp);
}
else if(!message.compare(0, 11, "verbose(4):"))
{
std::string const temp(message.begin()+12, message.end());
add(ConsoleLevel::Error, temp);
}
else if(!message.compare(0, 5, "tried"))
{
add(ConsoleLevel::Log, message);
}
else if(!message.compare(0, 16, "input channels ="))
{
add(ConsoleLevel::Log, message);
}
else
{
add(ConsoleLevel::Normal, message);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// MESSAGE METHOD //
//////////////////////////////////////////////////////////////////////////////////////////////
void CamomileAudioProcessor::receiveMessage(const std::string& msg, const std::vector<pd::Atom>& list)
{
if(msg == std::string("param"))
{
if(list.size() >= 2 && list[0].isSymbol() && list[1].isFloat())
{
std::string const method = list[0].getSymbol();
int const index = static_cast<int>(list[1].getFloat()) - 1;
if(method == "set")
{
if(list.size() >= 3 && list[2].isFloat())
{
CamomileAudioParameter* param = static_cast<CamomileAudioParameter *>(getParameters()[index]);
if(param)
{
param->setOriginalScaledValueNotifyingHost(list[2].getFloat());
if(list.size() > 3) { add(ConsoleLevel::Error,
"camomile parameter set method extra arguments"); }
}
else { add(ConsoleLevel::Error,
"camomile parameter set method index: out of range"); }
}
else { add(ConsoleLevel::Error,
"camomile parameter set method: wrong argument"); }
}
else if(method == "change")
{
if(list.size() >= 3 && list[2].isFloat())
{
AudioProcessorParameter* param = getParameters()[index];
if(param)
{
if(list[2].getFloat() > std::numeric_limits<float>::epsilon())
{
if(m_params_states[index])
{
add(ConsoleLevel::Error,
"camomile parameter change " + std::to_string(index+1) + " already started");
}
else
{
param->beginChangeGesture();
m_params_states[index] = true;
if(list.size() > 3) { add(ConsoleLevel::Error,
"camomile parameter change method extra arguments"); }
}
}
else
{
if(!m_params_states[index])
{
add(ConsoleLevel::Error,
"camomile parameter change " + std::to_string(index+1) + " not started");
}
else
{
param->endChangeGesture();
m_params_states[index] = false;
if(list.size() > 3) { add(ConsoleLevel::Error,
"camomile parameter change method extra arguments"); }
}
}
}
else { add(ConsoleLevel::Error,
"camomile parameter change method index: out of range"); }
}
else { add(ConsoleLevel::Error,
"camomile parameter change method: wrong argument"); }
}
else { add(ConsoleLevel::Error,
"camomile param no method: " + method); }
}
else { add(ConsoleLevel::Error,
"camomile param error syntax: method index..."); }
}
else if(msg == std::string("program"))
{
parseProgram(list);
}
else if(msg == std::string("openpanel"))
{
parseOpenPanel(list);
}
else if(msg == std::string("savepanel"))
{
parseSavePanel(list);
}
else if(msg == std::string("array"))
{
parseArray(list);
}
else if(msg == std::string("save"))
{
parseSaveInformation(list);
}
else if(msg == std::string("gui"))
{
parseGui(list);
}
else if(msg == std::string("audio"))
{
parseAudio(list);
}
else { add(ConsoleLevel::Error, "camomile unknow message : " + msg); }
}
void CamomileAudioProcessor::parseProgram(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1 && list[0].isSymbol() && list[0].getSymbol() == "updated")
{
updateHostDisplay();
}
else
{
add(ConsoleLevel::Error, "camomile program method accepts updated method only");
}
}
void CamomileAudioProcessor::parseOpenPanel(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
if(list.size() > 1)
{
if(list[1].isSymbol())
{
if(list[1].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("openpanel"), list[0].getSymbol(), std::string("-s")});
}
else if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("openpanel"), list[1].getSymbol(), std::string("-s")});
}
else
{
add(ConsoleLevel::Error, "camomile openpanel one argument must be a flag \"-s\"");
}
if(list.size() > 2)
{
add(ConsoleLevel::Error, "camomile openpanel method extra arguments");
}
}
else
{
add(ConsoleLevel::Error, "camomile openpanel second argument must be a symbol");
}
}
else
{
if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("openpanel"), std::string(), std::string("-s")});
}
else
{
m_queue_gui.try_enqueue({std::string("openpanel"), list[0].getSymbol(), std::string()});
}
}
}
else
{
add(ConsoleLevel::Error, "camomile openpanel method argument must be a symbol");
}
}
else
{
m_queue_gui.try_enqueue({std::string("openpanel"), std::string(), std::string()});
}
}
void CamomileAudioProcessor::parseSavePanel(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
if(list.size() > 1)
{
if(list[1].isSymbol())
{
if(list[1].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("savepanel"), list[0].getSymbol(), std::string("-s")});
}
else if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("savepanel"), list[1].getSymbol(), std::string("-s")});
}
else
{
add(ConsoleLevel::Error, "camomile savepanel one argument must be a flag \"-s\"");
}
if(list.size() > 2)
{
add(ConsoleLevel::Error, "camomile savepanel method extra arguments");
}
}
else
{
add(ConsoleLevel::Error, "camomile savepanel second argument must be a symbol");
}
}
else
{
if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("savepanel"), std::string(), std::string("-s")});
}
else
{
m_queue_gui.try_enqueue({std::string("savepanel"), list[0].getSymbol(), std::string()});
}
}
}
else
{
add(ConsoleLevel::Error, "camomile savepanel method argument must be a symbol");
}
}
else
{
m_queue_gui.try_enqueue({std::string("savepanel"), std::string(), std::string()});
}
}
void CamomileAudioProcessor::parseArray(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
m_queue_gui.try_enqueue({std::string("array"), list[0].getSymbol(), ""});
if(list.size() > 1)
{
add(ConsoleLevel::Error, "camomile array method extra arguments");
}
}
else { add(ConsoleLevel::Error, "camomile array method argument must be a symbol"); }
}
else
{
add(ConsoleLevel::Error, "camomile array needs a name");
}
}
void CamomileAudioProcessor::parseGui(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
m_queue_gui.try_enqueue({std::string("gui"), list[0].getSymbol(), ""});
if(list.size() > 1)
{
add(ConsoleLevel::Error, "camomile gui method extra arguments");
}
}
else { add(ConsoleLevel::Error, "camomile gui method argument must be a symbol"); }
}
else
{
add(ConsoleLevel::Error, "camomile gui needs a command");
}
}
void CamomileAudioProcessor::parseAudio(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
if(list[0].getSymbol() == std::string("latency"))
{
if(list.size() >= 2 && list[1].isFloat())
{
const int latency = static_cast<int>(list[1].getFloat());
if(latency >= 0)
{
setLatencySamples(latency + Instance::getBlockSize());
if(list.size() > 2)
{
add(ConsoleLevel::Error, "camomile audio method: latency option extra arguments");
}
if(CamomileEnvironment::isLatencyInitialized())
{
add(ConsoleLevel::Error, "camomile audio method: latency overwrites the preferences");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: latency must be positive or null");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: latency option expects a number");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: unknown option \"" + list[0].getSymbol() + "\"");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: first argument must be an option");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: expects arguments");
}
}
| 14,789 | 3,878 |
/*
* Copyright 2017, alex at staticlibs.net
*
* 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.
*/
/*
* File: file_sink.hpp
* Author: alex
*
* Created on February 6, 2017, 2:44 PM
*/
#ifndef STATICLIB_TINYDIR_FILE_SINK_HPP
#define STATICLIB_TINYDIR_FILE_SINK_HPP
#include <string>
#include "staticlib/config.hpp"
#include "staticlib/io/span.hpp"
#include "staticlib/tinydir/tinydir_exception.hpp"
namespace staticlib {
namespace tinydir {
/**
* Implementation of a file descriptor/handle wrapper with a
* unified interface for *nix and windows
*/
class file_sink {
#ifdef STATICLIB_WINDOWS
void* handle = nullptr;
#else // STATICLIB_WINDOWS
/**
* Native file descriptor (handle on windows)
*/
int fd = -1;
#endif // STATICLIB_WINDOWS
/**
* Path to file
*/
std::string file_path;
public:
/**
* File open mode
*/
enum class open_mode {
create, append, from_file
};
/**
* Constructor
*
* @param file_path path to file
*/
file_sink(const std::string& file_path, open_mode mode = open_mode::create);
/**
* Destructor, will close the descriptor
*/
~file_sink() STATICLIB_NOEXCEPT;
/**
* Deleted copy constructor
*
* @param other instance
*/
file_sink(const file_sink&) = delete;
/**
* Deleted copy assignment operator
*
* @param other instance
* @return this instance
*/
file_sink& operator=(const file_sink&) = delete;
/**
* Move constructor
*
* @param other other instance
*/
file_sink(file_sink&& other) STATICLIB_NOEXCEPT;
/**
* Move assignment operator
*
* @param other other instance
* @return this instance
*/
file_sink& operator=(file_sink&& other) STATICLIB_NOEXCEPT;
/**
* Writes specified number of bytes to this file descriptor
*
* @param buf source buffer
* @param count number of bytes to write
* @return number of bytes successfully written
*/
std::streamsize write(sl::io::span<const char> span);
/**
* Writes the contents of the specified file to this file descriptor
*
* @param string source file path
* @return number of bytes successfully written
*/
std::streamsize write_from_file(const std::string& source_file);
/**
* Seeks over this file descriptor
*
* @param offset offset to seek with starting from the current position
* @return resulting offset location as measured in bytes from the beginning of the file
*/
std::streampos seek(std::streamsize offset);
/**
* No-op
*
* @return zero
*/
std::streamsize flush();
/**
* Closed the underlying file descriptor, will be called automatically
* on destruction
*/
void close() STATICLIB_NOEXCEPT;
/**
* File path accessor
*
* @return path to this file
*/
const std::string& path() const;
};
} // namespace
}
#endif /* STATICLIB_TINYDIR_FILE_SINK_HPP */
| 3,585 | 1,153 |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include <gtest/gtest.h>
#include "common/byteutils.hpp"
using namespace iroha;
using namespace std::string_literals;
/**
* @given hex string
* @when hex string was converted to binary string
* @then converted string match the result we are expected
*/
TEST(StringConverterTest, ConvertHexToBinary) {
std::string hex = "ff000233551117daa110050399";
std::string bin = "\xFF\x00\x02\x33\x55\x11\x17\xDA\xA1\x10\x05\x03\x99"s;
ASSERT_EQ(hexstringToBytestring(hex).value(), bin);
}
/**
* @given invalid hex string
* @when string is converted to binary string
* @then std::nullopt is returned
*/
TEST(StringConverterTest, InvalidHexToBinary) {
std::string invalid_hex = "au";
ASSERT_FALSE(hexstringToBytestring(invalid_hex));
}
/**
* @given binary string
* @when binary string was converted to hex string
* @then converted string match the result we are expected
*/
TEST(StringConverterTest, ConvertBinaryToHex) {
std::string bin = "\xFF\x00\x02\x33\x55\x11\x17\xDA\xA1\x10\x05\x03\x99"s;
ASSERT_EQ(bytestringToHexstring(bin), "ff000233551117daa110050399");
}
/**
* @given hex string of length 256 with all possible byte values
* @when convert it to byte string and back
* @then resulted string is the same as given one
*/
TEST(StringConverterTest, ConvertHexToBinaryAndBack) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (int i = 0; i < 256; ++i) {
ss << std::setw(2) << i;
}
ASSERT_EQ(ss.str(),
bytestringToHexstring(hexstringToBytestring(ss.str()).value()));
}
/**
* @given numeric value
* @when converting it to a hex string
* @then converted string match expected result
*/
TEST(StringConverterTest, ConvertNumToHex) {
// Testing uint64_t values
std::vector<uint64_t> vals64{
0x4234324309085, 0x34532, 0x0, 0x1, 0x3333333333333333};
std::vector<std::string> hexes{"0004234324309085",
"0000000000034532",
"0000000000000000",
"0000000000000001",
"3333333333333333"};
for (size_t i = 0; i < vals64.size(); i++)
ASSERT_EQ(numToHexstring(vals64[i]), hexes[i]);
// Testing int32_t values
std::vector<int32_t> vals32{0x42343243, 0x34532, 0x0, 0x1, 0x79999999};
std::vector<std::string> hexes2{
"42343243", "00034532", "00000000", "00000001", "79999999"};
for (size_t i = 0; i < vals32.size(); i++)
ASSERT_EQ(numToHexstring(vals32[i]), hexes2[i]);
}
| 2,598 | 1,127 |
#ifndef _VOXOMAP_OCTREE_HPP_
#define _VOXOMAP_OCTREE_HPP_
#include <cstdint>
#include <memory>
#include <vector>
#include <assert.h>
namespace voxomap
{
/*!
\defgroup Octree Octree
Classes use for define the octree
*/
/*! \class Octree
\ingroup Octree
\brief Octree container
*/
template <class T_Node>
class Octree
{
public:
using Node = T_Node;
/*!
\brief Default constructor
*/
Octree();
/*!
\brief Copy constructor
*/
Octree(Octree const& other);
/*!
\brief Move constructor
*/
Octree(Octree&& other);
/*!
\brief Default virtual destructor
*/
virtual ~Octree() = default;
/*!
\brief Assignement operator
\param other Right operand
\return Reference to \a this
*/
Octree& operator=(Octree const& other);
/*!
\brief Assignement move operator
\param other Right operand
\return Reference to \a this
*/
Octree& operator=(Octree&& other);
/*!
\brief Pushes \a node into the octree
\param node Node to push
*/
virtual T_Node* push(T_Node& node);
/*!
\brief Removes \a node from the octree
\return
*/
virtual std::unique_ptr<T_Node> pop(T_Node& node);
/*!
\brief Search the node that corresponds to the parameters
\param x X coordinate of the node
\param y Y coordinate of the node
\param z Z coordinate of the node
\param size Size of the node
\return Pointer to the node if it exists otherwise nullptr
*/
T_Node* findNode(int x, int y, int z, uint32_t size) const;
/*!
\brief Clear the octree
Removes all nodes and all elements.
*/
virtual void clear();
/*!
\brief Getter of the root node
\return The root node
*/
T_Node* getRootNode() const;
protected:
// Node method
/*!
\brief Set \a child as child of \a parent
\param parent Parent node
\param child Child node
*/
void setChild(T_Node& parent, T_Node& child);
/*!
\brief Set \a child as child of \a parent
\param parent Parent node
\param child Child node
\param childId Id of the child inside parent's children array
*/
void setChild(T_Node& parent, T_Node& child, uint8_t childId);
/*!
\brief Remove \a child from its parent and so from the octree
*/
void removeFromParent(T_Node& child);
/*!
\brief Remove the child with \a id from the \a parent node
\return The removed node
*/
T_Node* removeChild(T_Node& parent, uint8_t id);
/*!
\brief Find node inside \a parent that can contain \a node
\param parent Parent node
\param node The new node
\param childId Id of the node inside the found parent
\return The found parent node, nullptr if not exist
*/
T_Node* findParentNode(T_Node& parent, T_Node& node, uint8_t& childId) const;
/*!
\brief Push \a node inside \a parent
\param parent Parent node
\param node Node to push
\return Node added, can be different than \a node if a similar node already exist
*/
T_Node* push(T_Node& parent, T_Node& node);
/*!
\brief Push \a node inside \a parent
\param parent Parent node
\param child Child node
\param childId Id of the child inside parent's children array
\return Node added, can be different than \a node if a similar node already exist
*/
T_Node* push(T_Node& parent, T_Node& child, uint8_t childId);
/*!
\brief Create an intermediate node that can contain \a child and \a newChild and push it into octree
*/
void insertIntermediateNode(T_Node& child, T_Node& newChild);
/*!
\brief Merge two nodes
\param currentNode Node already present in the octree
\param newNode Node to merge inside
*/
void merge(T_Node& currentNode, T_Node& newNode);
/*!
\brief Remove useless intermediate node, intermediate node with only one child
\param node The intermediate node
*/
void removeUselessIntermediateNode(T_Node& node);
/*!
\brief Compute the new coordinates and size of the NegPosRootNode
*/
void recomputeNegPosRootNode();
/*!
\brief Called when \a node is remove from the octree
*/
virtual void notifyNodeRemoving(T_Node& node);
std::unique_ptr<T_Node> _rootNode; //!< Main node of the octree
};
}
#include "Octree.ipp"
#endif // _VOXOMAP_OCTREE_HPP_ | 4,744 | 1,417 |
// file: main.cpp (uart)
// brief: VIHAL UART Test
// created: 2021-10-03
// authors: nvitya
#include "platform.h"
#include "cppinit.h"
#include "clockcnt.h"
#include "traces.h"
#include "hwclk.h"
#include "hwpins.h"
#include "hwuart.h"
#include "hwrtc.h"
#include "board_pins.h"
THwRtc gRtc;
volatile unsigned hbcounter = 0;
extern "C" __attribute__((noreturn)) void _start(unsigned self_flashing) // self_flashing = 1: self-flashing required for RAM-loaded applications
{
// after ram setup and region copy the cpu jumps here, with probably RC oscillator
mcu_disable_interrupts();
// Set the interrupt vector table offset, so that the interrupts and exceptions work
mcu_init_vector_table();
// run the C/C++ initialization (variable initializations, constructors)
cppinit();
if (!hwclk_init(EXTERNAL_XTAL_HZ, MCU_CLOCK_SPEED)) // if the EXTERNAL_XTAL_HZ == 0, then the internal RC oscillator will be used
{
while (1)
{
// error
}
}
hwlsclk_init(true);
mcu_enable_fpu(); // enable coprocessor if present
mcu_enable_icache(); // enable instruction cache if present
clockcnt_init();
// go on with the hardware initializations
board_pins_init();
gRtc.init();
THwRtc::time_t startTime, lastTime;
startTime.msec = 768;
startTime.sec = 13;
startTime.min = 43;
startTime.hour = 13;
startTime.day = 13;
startTime.month = 03;
startTime.year = 22;
gRtc.setTime(startTime, lastTime);
THwRtc::time_t aktTime;
gRtc.getTime(aktTime);
TRACE("\r\n--------------------------------------\r\n");
TRACE("%sHello From VIHAL !\r\n", CC_BLU);
TRACE("Board: %s\r\n", BOARD_NAME);
TRACE("SystemCoreClock: %u\r\n", SystemCoreClock);
TRACE("%02hhu:%02hhu:%02hhu.%03hu %02hhu.%02hhu.%02hhu\r\n", aktTime.hour, aktTime.min, aktTime.sec, aktTime.msec, aktTime.day, aktTime.month, aktTime.year);
gRtc.enableWakeupIRQ();
gRtc.setWakeupTimer(100);
mcu_enable_interrupts();
// Infinite loop
while (1)
{
}
}
extern "C" void IRQ_Handler_03()
{
++hbcounter;
if (hbcounter == 20)
{
gRtc.setWakeupTimer(500);
}
THwRtc::time_t aktTime;
gRtc.getTime(aktTime);
switch(hbcounter%8)
{
case 0: TRACE("%s", CC_NRM); break;
case 1: TRACE("%s", CC_RED); break;
case 2: TRACE("%s", CC_GRN); break;
case 3: TRACE("%s", CC_YEL); break;
case 4: TRACE("%s", CC_BLU); break;
case 5: TRACE("%s", CC_MAG); break;
case 6: TRACE("%s", CC_CYN); break;
case 7: TRACE("%s", CC_WHT); break;
}
TRACE("%02hhu:%02hhu:%02hhu.%03hu %02hhu.%02hhu.%02hhu\r\n", aktTime.hour, aktTime.min, aktTime.sec, aktTime.msec, aktTime.day, aktTime.month, aktTime.year);
gRtc.clearWakeupIRQ();
}
// ----------------------------------------------------------------------------
| 2,785 | 1,187 |
#include "stdafx.h"
#include "Headers/PostFX.h"
#include "Headers/PreRenderOperator.h"
#include "Core/Headers/ParamHandler.h"
#include "Core/Headers/PlatformContext.h"
#include "Core/Headers/StringHelper.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Core/Time/Headers/ApplicationTimer.h"
#include "Geometry/Shapes/Predefined/Headers/Quad3D.h"
#include "Managers/Headers/SceneManager.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/CommandBuffer.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"
#include "Platform/Video/Buffers/RenderTarget/Headers/RenderTarget.h"
#include "Rendering/Camera/Headers/Camera.h"
namespace Divide {
const char* PostFX::FilterName(const FilterType filter) noexcept {
switch (filter) {
case FilterType::FILTER_SS_ANTIALIASING: return "SS_ANTIALIASING";
case FilterType::FILTER_SS_REFLECTIONS: return "SS_REFLECTIONS";
case FilterType::FILTER_SS_AMBIENT_OCCLUSION: return "SS_AMBIENT_OCCLUSION";
case FilterType::FILTER_DEPTH_OF_FIELD: return "DEPTH_OF_FIELD";
case FilterType::FILTER_MOTION_BLUR: return "MOTION_BLUR";
case FilterType::FILTER_BLOOM: return "BLOOM";
case FilterType::FILTER_LUT_CORECTION: return "LUT_CORRECTION";
case FilterType::FILTER_UNDERWATER: return "UNDERWATER";
case FilterType::FILTER_NOISE: return "NOISE";
case FilterType::FILTER_VIGNETTE: return "VIGNETTE";
default: break;
}
return "Unknown";
};
PostFX::PostFX(PlatformContext& context, ResourceCache* cache)
: PlatformContextComponent(context),
_preRenderBatch(context.gfx(), *this, cache)
{
std::atomic_uint loadTasks = 0u;
context.paramHandler().setParam<bool>(_ID("postProcessing.enableVignette"), false);
DisableAll(_postFXTarget._drawMask);
SetEnabled(_postFXTarget._drawMask, RTAttachmentType::Colour, to_U8(GFXDevice::ScreenTargets::ALBEDO), true);
Console::printfn(Locale::Get(_ID("START_POST_FX")));
ShaderModuleDescriptor vertModule = {};
vertModule._moduleType = ShaderType::VERTEX;
vertModule._sourceFile = "baseVertexShaders.glsl";
vertModule._variant = "FullScreenQuad";
ShaderModuleDescriptor fragModule = {};
fragModule._moduleType = ShaderType::FRAGMENT;
fragModule._sourceFile = "postProcessing.glsl";
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCREEN %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCREEN)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_NOISE %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_NOISE)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_BORDER %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_BORDER)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_UNDERWATER %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_UNDERWATER)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SSR %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SSR)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCENE_DATA %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_DATA)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCENE_VELOCITY %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_VELOCITY)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_LINDEPTH %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_LINDEPTH)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_DEPTH %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_DEPTH)));
ShaderProgramDescriptor postFXShaderDescriptor = {};
postFXShaderDescriptor._modules.push_back(vertModule);
postFXShaderDescriptor._modules.push_back(fragModule);
_drawConstantsCmd._constants.set(_ID("_noiseTile"), GFX::PushConstantType::FLOAT, 0.1f);
_drawConstantsCmd._constants.set(_ID("_noiseFactor"), GFX::PushConstantType::FLOAT, 0.02f);
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, false);
_drawConstantsCmd._constants.set(_ID("_zPlanes"), GFX::PushConstantType::VEC2, vec2<F32>(0.01f, 500.0f));
TextureDescriptor texDescriptor(TextureType::TEXTURE_2D);
ImageTools::ImportOptions options;
options._isNormalMap = true;
options._useDDSCache = true;
options._outputSRGB = false;
options._alphaChannelTransparency = false;
texDescriptor.textureOptions(options);
ResourceDescriptor textureWaterCaustics("Underwater Normal Map");
textureWaterCaustics.assetName(ResourcePath("terrain_water_NM.jpg"));
textureWaterCaustics.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
textureWaterCaustics.propertyDescriptor(texDescriptor);
textureWaterCaustics.waitForReady(false);
_underwaterTexture = CreateResource<Texture>(cache, textureWaterCaustics, loadTasks);
options._isNormalMap = false;
texDescriptor.textureOptions(options);
ResourceDescriptor noiseTexture("noiseTexture");
noiseTexture.assetName(ResourcePath("bruit_gaussien.jpg"));
noiseTexture.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
noiseTexture.propertyDescriptor(texDescriptor);
noiseTexture.waitForReady(false);
_noise = CreateResource<Texture>(cache, noiseTexture, loadTasks);
ResourceDescriptor borderTexture("borderTexture");
borderTexture.assetName(ResourcePath("vignette.jpeg"));
borderTexture.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
borderTexture.propertyDescriptor(texDescriptor);
borderTexture.waitForReady(false);
_screenBorder = CreateResource<Texture>(cache, borderTexture), loadTasks;
_noiseTimer = 0.0;
_tickInterval = 1.0f / 24.0f;
_randomNoiseCoefficient = 0;
_randomFlashCoefficient = 0;
ResourceDescriptor postFXShader("postProcessing");
postFXShader.propertyDescriptor(postFXShaderDescriptor);
_postProcessingShader = CreateResource<ShaderProgram>(cache, postFXShader, loadTasks);
_postProcessingShader->addStateCallback(ResourceState::RES_LOADED, [this, &context](CachedResource*) {
PipelineDescriptor pipelineDescriptor;
pipelineDescriptor._stateHash = context.gfx().get2DStateBlock();
pipelineDescriptor._shaderProgramHandle = _postProcessingShader->handle();
pipelineDescriptor._primitiveTopology = PrimitiveTopology::TRIANGLES;
_drawPipeline = context.gfx().newPipeline(pipelineDescriptor);
});
WAIT_FOR_CONDITION(loadTasks.load() == 0);
}
PostFX::~PostFX()
{
}
void PostFX::updateResolution(const U16 newWidth, const U16 newHeight) {
if (_resolutionCache.width == newWidth &&
_resolutionCache.height == newHeight||
newWidth < 1 || newHeight < 1)
{
return;
}
_resolutionCache.set(newWidth, newHeight);
_preRenderBatch.reshape(newWidth, newHeight);
_setCameraCmd._cameraSnapshot = Camera::GetUtilityCamera(Camera::UtilityCamera::_2D)->snapshot();
}
void PostFX::prePass(const PlayerIndex idx, const CameraSnapshot& cameraSnapshot, GFX::CommandBuffer& bufferInOut) {
static GFX::BeginDebugScopeCommand s_beginScopeCmd{ "PostFX: PrePass" };
GFX::EnqueueCommand(bufferInOut, s_beginScopeCmd);
GFX::EnqueueCommand<GFX::PushCameraCommand>(bufferInOut)->_cameraSnapshot = _setCameraCmd._cameraSnapshot;
_preRenderBatch.prePass(idx, cameraSnapshot, _filterStack | _overrideFilterStack, bufferInOut);
GFX::EnqueueCommand<GFX::PopCameraCommand>(bufferInOut);
GFX::EnqueueCommand<GFX::EndDebugScopeCommand>(bufferInOut);
}
void PostFX::apply(const PlayerIndex idx, const CameraSnapshot& cameraSnapshot, GFX::CommandBuffer& bufferInOut) {
static GFX::BeginDebugScopeCommand s_beginScopeCmd{ "PostFX: Apply" };
GFX::EnqueueCommand(bufferInOut, s_beginScopeCmd);
GFX::EnqueueCommand(bufferInOut, _setCameraCmd);
_preRenderBatch.execute(idx, cameraSnapshot, _filterStack | _overrideFilterStack, bufferInOut);
GFX::BeginRenderPassCommand beginRenderPassCmd{};
beginRenderPassCmd._target = RenderTargetNames::SCREEN;
beginRenderPassCmd._descriptor = _postFXTarget;
beginRenderPassCmd._name = "DO_POSTFX_PASS";
GFX::EnqueueCommand(bufferInOut, beginRenderPassCmd);
GFX::EnqueueCommand(bufferInOut, GFX::BindPipelineCommand{ _drawPipeline });
if (_filtersDirty) {
_drawConstantsCmd._constants.set(_ID("vignetteEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_VIGNETTE));
_drawConstantsCmd._constants.set(_ID("noiseEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_NOISE));
_drawConstantsCmd._constants.set(_ID("underwaterEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_UNDERWATER));
_drawConstantsCmd._constants.set(_ID("lutCorrectionEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_LUT_CORECTION));
_filtersDirty = false;
};
_drawConstantsCmd._constants.set(_ID("_zPlanes"), GFX::PushConstantType::VEC2, cameraSnapshot._zPlanes);
_drawConstantsCmd._constants.set(_ID("_invProjectionMatrix"), GFX::PushConstantType::VEC2, cameraSnapshot._invProjectionMatrix);
GFX::EnqueueCommand(bufferInOut, _drawConstantsCmd);
const auto& rtPool = context().gfx().renderTargetPool();
const auto& prbAtt = _preRenderBatch.getOutput(false)._rt->getAttachment(RTAttachmentType::Colour, 0);
const auto& linDepthDataAtt =_preRenderBatch.getLinearDepthRT()._rt->getAttachment(RTAttachmentType::Colour, 0);
const auto& ssrDataAtt = rtPool.getRenderTarget(RenderTargetNames::SSR_RESULT)->getAttachment(RTAttachmentType::Colour, 0);
const auto& sceneDataAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Colour, to_base(GFXDevice::ScreenTargets::NORMALS));
const auto& velocityAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Colour, to_base(GFXDevice::ScreenTargets::VELOCITY));
const auto& depthAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Depth_Stencil, 0);
SamplerDescriptor defaultSampler = {};
defaultSampler.wrapUVW(TextureWrap::REPEAT);
const size_t samplerHash = defaultSampler.getHash();
DescriptorSet& set = GFX::EnqueueCommand<GFX::BindDescriptorSetsCommand>(bufferInOut)->_set;
set._usage = DescriptorSetUsage::PER_DRAW_SET;
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCREEN);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { prbAtt->texture()->data(), prbAtt->descriptor()._samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_DEPTH);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { depthAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_LINDEPTH);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { linDepthDataAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SSR);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { ssrDataAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_DATA);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { sceneDataAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_VELOCITY);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { velocityAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_UNDERWATER);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { _underwaterTexture->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_NOISE);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { _noise->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_BORDER);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { _screenBorder->data(), samplerHash };
}
GFX::EnqueueCommand<GFX::DrawCommand>(bufferInOut);
GFX::EnqueueCommand(bufferInOut, GFX::EndRenderPassCommand{});
GFX::EnqueueCommand<GFX::EndDebugScopeCommand>(bufferInOut);
}
void PostFX::idle(const Configuration& config) {
OPTICK_EVENT();
// Update states
if (getFilterState(FilterType::FILTER_NOISE)) {
_noiseTimer += Time::Game::ElapsedMilliseconds();
if (_noiseTimer > _tickInterval) {
_noiseTimer = 0.0;
_randomNoiseCoefficient = Random(1000) * 0.001f;
_randomFlashCoefficient = Random(1000) * 0.001f;
}
_drawConstantsCmd._constants.set(_ID("randomCoeffNoise"), GFX::PushConstantType::FLOAT, _randomNoiseCoefficient);
_drawConstantsCmd._constants.set(_ID("randomCoeffFlash"), GFX::PushConstantType::FLOAT, _randomFlashCoefficient);
}
}
void PostFX::update(const U64 deltaTimeUSFixed, const U64 deltaTimeUSApp) {
OPTICK_EVENT();
if (_fadeActive) {
_currentFadeTimeMS += Time::MicrosecondsToMilliseconds<D64>(deltaTimeUSApp);
F32 fadeStrength = to_F32(std::min(_currentFadeTimeMS / _targetFadeTimeMS , 1.0));
if (!_fadeOut) {
fadeStrength = 1.0f - fadeStrength;
}
if (fadeStrength > 0.99) {
if (_fadeWaitDurationMS < std::numeric_limits<D64>::epsilon()) {
if (_fadeOutComplete) {
_fadeOutComplete();
_fadeOutComplete = DELEGATE<void>();
}
} else {
_fadeWaitDurationMS -= Time::MicrosecondsToMilliseconds<D64>(deltaTimeUSApp);
}
}
_drawConstantsCmd._constants.set(_ID("_fadeStrength"), GFX::PushConstantType::FLOAT, fadeStrength);
_fadeActive = fadeStrength > std::numeric_limits<D64>::epsilon();
if (!_fadeActive) {
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, false);
if (_fadeInComplete) {
_fadeInComplete();
_fadeInComplete = DELEGATE<void>();
}
}
}
_preRenderBatch.update(deltaTimeUSApp);
}
void PostFX::setFadeOut(const UColour3& targetColour, const D64 durationMS, const D64 waitDurationMS, DELEGATE<void> onComplete) {
_drawConstantsCmd._constants.set(_ID("_fadeColour"), GFX::PushConstantType::VEC4, Util::ToFloatColour(targetColour));
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, true);
_targetFadeTimeMS = durationMS;
_currentFadeTimeMS = 0.0;
_fadeWaitDurationMS = waitDurationMS;
_fadeOut = true;
_fadeActive = true;
_fadeOutComplete = MOV(onComplete);
}
// clear any fading effect currently active over the specified time interval
// set durationMS to instantly clear the fade effect
void PostFX::setFadeIn(const D64 durationMS, DELEGATE<void> onComplete) {
_targetFadeTimeMS = durationMS;
_currentFadeTimeMS = 0.0;
_fadeOut = false;
_fadeActive = true;
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, true);
_fadeInComplete = MOV(onComplete);
}
void PostFX::setFadeOutIn(const UColour3& targetColour, const D64 durationFadeOutMS, const D64 waitDurationMS) {
if (waitDurationMS > 0.0) {
setFadeOutIn(targetColour, waitDurationMS * 0.5, waitDurationMS * 0.5, durationFadeOutMS);
}
}
void PostFX::setFadeOutIn(const UColour3& targetColour, const D64 durationFadeOutMS, const D64 durationFadeInMS, const D64 waitDurationMS) {
setFadeOut(targetColour, durationFadeOutMS, waitDurationMS, [this, durationFadeInMS]() {setFadeIn(durationFadeInMS); });
}
};
| 18,465 | 6,026 |
#include <iostream>
#include "Eigen/Dense"
#include "common/config.h"
#include "common/common.h"
int main() {
PrintInfo("The program compiles just fine.");
return 0;
}
| 177 | 63 |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
/*
===== tf_client.cpp ========================================================
HL2 client/server game specific stuff
*/
#include "cbase.h"
#include "hl2mp_player.h"
#include "hl2mp_gamerules.h"
#include "gamerules.h"
#include "teamplay_gamerules.h"
#include "entitylist.h"
#include "physics.h"
#include "game.h"
#include "player_resource.h"
#include "engine/IEngineSound.h"
#include "team.h"
#include "viewport_panel_names.h"
#include "tier0/vprof.h"
#ifdef SecobMod__SAVERESTORE
#include "filesystem.h"
#endif //SecobMod__SAVERESTORE
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
void Host_Say(edict_t *pEdict, bool teamonly);
ConVar sv_motd_unload_on_dismissal("sv_motd_unload_on_dismissal", "0", 0, "If enabled, the MOTD contents will be unloaded when the player closes the MOTD.");
extern CBaseEntity* FindPickerEntityClass(CBasePlayer *pPlayer, char *classname);
extern bool g_fGameOver;
#ifdef SecobMod__USE_PLAYERCLASSES
void SSPlayerClassesBGCheck(CHL2MP_Player *pPlayer)
{
CSingleUserRecipientFilter user(pPlayer);
user.MakeReliable();
UserMessageBegin(user, "SSPlayerClassesBGCheck");
MessageEnd();
}
void ShowSSPlayerClasses(CHL2MP_Player *pPlayer)
{
CSingleUserRecipientFilter user(pPlayer);
user.MakeReliable();
UserMessageBegin(user, "ShowSSPlayerClasses");
MessageEnd();
}
CON_COMMAND(ss_classes_default, "The current map is a background level - do default spawn")
{
CHL2MP_Player *pPlayer = ToHL2MPPlayer(UTIL_GetCommandClient());
if (pPlayer != NULL)
{
CSingleUserRecipientFilter user(pPlayer);
user.MakeReliable();
pPlayer->InitialSpawn();
pPlayer->Spawn();
pPlayer->m_Local.m_iHideHUD |= HIDEHUD_ALL;
pPlayer->RemoveAllItems(true);
//SecobMod__Information These are now commented out because for your own mod you'll have to use the black room spawn method anyway.
// That is for your own maps, you create a seperate room with fully black textures, no light and a single info_player_start.
//You may end up needing to uncomment it if you don't use playerclasses, but you'll figure that out for yourself when you cant see anything but your HUD.
//color32 black = {0,0,0,255};
//UTIL_ScreenFade( pPlayer, black, 0.0f, 0.0f, FFADE_IN|FFADE_PURGE );
}
}
#endif //SecobMod__USE_PLAYERCLASSES
void FinishClientPutInServer(CHL2MP_Player *pPlayer)
{
#ifdef SecobMod__USE_PLAYERCLASSES
pPlayer->InitialSpawn();
pPlayer->Spawn();
pPlayer->RemoveAllItems(true);
SSPlayerClassesBGCheck(pPlayer);
#else
pPlayer->InitialSpawn();
pPlayer->Spawn();
#endif //SecobMod__USE_PLAYERCLASSES
char sName[128];
Q_strncpy(sName, pPlayer->GetPlayerName(), sizeof(sName));
// First parse the name and remove any %'s
for (char *pApersand = sName; pApersand != NULL && *pApersand != 0; pApersand++)
{
// Replace it with a space
if (*pApersand == '%')
*pApersand = ' ';
}
// notify other clients of player joining the game
UTIL_ClientPrintAll(HUD_PRINTNOTIFY, "#Game_connected", sName[0] != 0 ? sName : "<unconnected>");
if (HL2MPRules()->IsTeamplay() == true)
{
ClientPrint(pPlayer, HUD_PRINTTALK, "You are on team %s1\n", pPlayer->GetTeam()->GetName());
}
const ConVar *hostname = cvar->FindVar("hostname");
const char *title = (hostname) ? hostname->GetString() : "MESSAGE OF THE DAY";
KeyValues *data = new KeyValues("data");
data->SetString("title", title); // info panel title
data->SetString("type", "1"); // show userdata from stringtable entry
data->SetString("msg", "motd"); // use this stringtable entry
data->SetBool("unload", sv_motd_unload_on_dismissal.GetBool());
pPlayer->ShowViewPortPanel(PANEL_INFO, true, data);
#ifndef SecobMod__SAVERESTORE
#ifdef SecobMod__USE_PLAYERCLASSES
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
#endif //SecobMod__USE_PLAYERCLASSES
#endif //SecobMod__SAVERESTORE
#ifdef SecobMod__SAVERESTORE
//if (Transitioned)
//{
//SecobMod
KeyValues *pkvTransitionRestoreFile = new KeyValues("transition.cfg");
//Msg ("Transition path is: %s !!!!!\n",TransitionPath);
if (pkvTransitionRestoreFile->LoadFromFile(filesystem, "transition.cfg"))
{
while (pkvTransitionRestoreFile)
{
const char *pszSteamID = pkvTransitionRestoreFile->GetName(); //Gets our header, which we use the players SteamID for.
const char *PlayerSteamID = engine->GetPlayerNetworkIDString(pPlayer->edict()); //Finds the current players Steam ID.
Msg("In-File SteamID is %s.\n", pszSteamID);
Msg("In-Game SteamID is %s.\n", PlayerSteamID);
if (Q_strcmp(PlayerSteamID, pszSteamID) != 0)
{
if (pkvTransitionRestoreFile == NULL)
{
break;
}
//SecobMod__Information No SteamID found for this person, maybe they're new to the game or have "STEAM_ID_PENDING". Show them the class menu and break the loop.
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
break;
}
Msg("SteamID Match Found!");
#ifdef SecobMod__USE_PLAYERCLASSES
//Class.
KeyValues *pkvCurrentClass = pkvTransitionRestoreFile->FindKey("CurrentClass");
#endif //SecobMod__USE_PLAYERCLASSES
//Health
KeyValues *pkvHealth = pkvTransitionRestoreFile->FindKey("Health");
//Armour
KeyValues *pkvArmour = pkvTransitionRestoreFile->FindKey("Armour");
//CurrentHeldWeapon
KeyValues *pkvActiveWep = pkvTransitionRestoreFile->FindKey("ActiveWeapon");
//Weapon_0.
KeyValues *pkvWeapon_0 = pkvTransitionRestoreFile->FindKey("Weapon_0");
KeyValues *pkvWeapon_0_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClip");
KeyValues *pkvWeapon_0_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClip");
KeyValues *pkvWeapon_0_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClipAmmo");
KeyValues *pkvWeapon_0_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClipAmmo");
KeyValues *pkvWeapon_0_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClipAmmoLeft");
KeyValues *pkvWeapon_0_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClipAmmoLeft");
//Weapon_1.
KeyValues *pkvWeapon_1 = pkvTransitionRestoreFile->FindKey("Weapon_1");
KeyValues *pkvWeapon_1_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClip");
KeyValues *pkvWeapon_1_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClip");
KeyValues *pkvWeapon_1_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClipAmmo");
KeyValues *pkvWeapon_1_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClipAmmo");
KeyValues *pkvWeapon_1_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClipAmmoLeft");
KeyValues *pkvWeapon_1_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClipAmmoLeft");
//Weapon_2.
KeyValues *pkvWeapon_2 = pkvTransitionRestoreFile->FindKey("Weapon_2");
KeyValues *pkvWeapon_2_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClip");
KeyValues *pkvWeapon_2_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClip");
KeyValues *pkvWeapon_2_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClipAmmo");
KeyValues *pkvWeapon_2_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClipAmmo");
KeyValues *pkvWeapon_2_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClipAmmoLeft");
KeyValues *pkvWeapon_2_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClipAmmoLeft");
//Weapon_3.
KeyValues *pkvWeapon_3 = pkvTransitionRestoreFile->FindKey("Weapon_3");
KeyValues *pkvWeapon_3_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClip");
KeyValues *pkvWeapon_3_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClip");
KeyValues *pkvWeapon_3_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClipAmmo");
KeyValues *pkvWeapon_3_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClipAmmo");
KeyValues *pkvWeapon_3_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClipAmmoLeft");
KeyValues *pkvWeapon_3_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClipAmmoLeft");
//Weapon_4.
KeyValues *pkvWeapon_4 = pkvTransitionRestoreFile->FindKey("Weapon_4");
KeyValues *pkvWeapon_4_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClip");
KeyValues *pkvWeapon_4_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClip");
KeyValues *pkvWeapon_4_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClipAmmo");
KeyValues *pkvWeapon_4_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClipAmmo");
KeyValues *pkvWeapon_4_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClipAmmoLeft");
KeyValues *pkvWeapon_4_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClipAmmoLeft");
//Weapon_5.
KeyValues *pkvWeapon_5 = pkvTransitionRestoreFile->FindKey("Weapon_5");
KeyValues *pkvWeapon_5_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClip");
KeyValues *pkvWeapon_5_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClip");
KeyValues *pkvWeapon_5_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClipAmmo");
KeyValues *pkvWeapon_5_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClipAmmo");
KeyValues *pkvWeapon_5_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClipAmmoLeft");
KeyValues *pkvWeapon_5_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClipAmmoLeft");
//Weapon_6.
KeyValues *pkvWeapon_6 = pkvTransitionRestoreFile->FindKey("Weapon_6");
KeyValues *pkvWeapon_6_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClip");
KeyValues *pkvWeapon_6_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClip");
KeyValues *pkvWeapon_6_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClipAmmo");
KeyValues *pkvWeapon_6_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClipAmmo");
KeyValues *pkvWeapon_6_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClipAmmoLeft");
KeyValues *pkvWeapon_6_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClipAmmoLeft");
//Weapon_7.
KeyValues *pkvWeapon_7 = pkvTransitionRestoreFile->FindKey("Weapon_7");
KeyValues *pkvWeapon_7_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClip");
KeyValues *pkvWeapon_7_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClip");
KeyValues *pkvWeapon_7_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClipAmmo");
KeyValues *pkvWeapon_7_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClipAmmo");
KeyValues *pkvWeapon_7_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClipAmmoLeft");
KeyValues *pkvWeapon_7_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClipAmmoLeft");
//Weapon_8.
KeyValues *pkvWeapon_8 = pkvTransitionRestoreFile->FindKey("Weapon_8");
KeyValues *pkvWeapon_8_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClip");
KeyValues *pkvWeapon_8_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClip");
KeyValues *pkvWeapon_8_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClipAmmo");
KeyValues *pkvWeapon_8_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClipAmmo");
KeyValues *pkvWeapon_8_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClipAmmoLeft");
KeyValues *pkvWeapon_8_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClipAmmoLeft");
//Weapon_9.
KeyValues *pkvWeapon_9 = pkvTransitionRestoreFile->FindKey("Weapon_9");
KeyValues *pkvWeapon_9_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClip");
KeyValues *pkvWeapon_9_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClip");
KeyValues *pkvWeapon_9_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClipAmmo");
KeyValues *pkvWeapon_9_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClipAmmo");
KeyValues *pkvWeapon_9_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClipAmmoLeft");
KeyValues *pkvWeapon_9_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClipAmmoLeft");
//Weapon_10.
KeyValues *pkvWeapon_10 = pkvTransitionRestoreFile->FindKey("Weapon_10");
KeyValues *pkvWeapon_10_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClip");
KeyValues *pkvWeapon_10_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClip");
KeyValues *pkvWeapon_10_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClipAmmo");
KeyValues *pkvWeapon_10_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClipAmmo");
KeyValues *pkvWeapon_10_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClipAmmoLeft");
KeyValues *pkvWeapon_10_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClipAmmoLeft");
//Weapon_11.
KeyValues *pkvWeapon_11 = pkvTransitionRestoreFile->FindKey("Weapon_11");
KeyValues *pkvWeapon_11_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClip");
KeyValues *pkvWeapon_11_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClip");
KeyValues *pkvWeapon_11_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClipAmmo");
KeyValues *pkvWeapon_11_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClipAmmo");
KeyValues *pkvWeapon_11_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClipAmmoLeft");
KeyValues *pkvWeapon_11_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClipAmmoLeft");
//Weapon_12.
KeyValues *pkvWeapon_12 = pkvTransitionRestoreFile->FindKey("Weapon_12");
KeyValues *pkvWeapon_12_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClip");
KeyValues *pkvWeapon_12_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClip");
KeyValues *pkvWeapon_12_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClipAmmo");
KeyValues *pkvWeapon_12_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClipAmmo");
KeyValues *pkvWeapon_12_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClipAmmoLeft");
KeyValues *pkvWeapon_12_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClipAmmoLeft");
//=====================================================================
if (pszSteamID)
{
//Set ints for the class,health and armour.
#ifdef SecobMod__USE_PLAYERCLASSES
int PlayerClassValue = pkvCurrentClass->GetInt();
#endif
int PlayerHealthValue = pkvHealth->GetInt();
int PlayerArmourValue = pkvArmour->GetInt();
//Current Active Weapon
const char *pkvActiveWep_Value = pkvActiveWep->GetString();
//============================================================================================
#ifdef SecobMod__USE_PLAYERCLASSES
if (PlayerClassValue == 1)
{
pPlayer->m_iCurrentClass = 1;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
Msg("Respawning...\n");
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 125;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(0);
pPlayer->CBasePlayer::SetWalkSpeed(50);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(640);
pPlayer->CBasePlayer::SetJumpHeight(200.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Assaulter");
pPlayer->SetModel("models/sdk/Humans/Group03/male_06_sdk.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_assaulter", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
}
else if (PlayerClassValue == 2)
{
pPlayer->m_iCurrentClass = 2;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
Msg("Respawning...\n");
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 100;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(0);
pPlayer->CBasePlayer::SetWalkSpeed(150);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(500);
pPlayer->CBasePlayer::SetJumpHeight(150.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Supporter");
pPlayer->SetModel("models/sdk/Humans/Group03/l7h_rebel.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_supporter", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
}
else if (PlayerClassValue == 3)
{
pPlayer->m_iCurrentClass = 3;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 80;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(0);
pPlayer->CBasePlayer::SetWalkSpeed(150);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(320);
pPlayer->CBasePlayer::SetJumpHeight(100.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Medic");
pPlayer->SetModel("models/sdk/Humans/Group03/male_05.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_medic", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
pPlayer->EquipSuit(false);
}
else if (PlayerClassValue == 4)
{
pPlayer->m_iCurrentClass = 4;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 150;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(200);
pPlayer->CBasePlayer::SetWalkSpeed(150);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(320);
pPlayer->CBasePlayer::SetJumpHeight(40.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Heavy");
pPlayer->SetModel("models/sdk/Humans/Group03/police_05.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_heavy", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
}
#endif //SecobMod__USE_PLAYERCLASSES
#ifndef SecobMod__USE_PLAYERCLASSES
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 125;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetModel("models/sdk/Humans/Group03/male_06_sdk.mdl");
//Bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
#endif //SecobMod__USE_PLAYERCLASSES NOT
const char *pkvWeapon_Value = NULL;
int Weapon_PriClip_Value = 0;
const char *pkvWeapon_PriClipAmmo_Value = NULL;
int Weapon_SecClip_Value = 0;
const char *pkvWeapon_SecClipAmmo_Value = NULL;
int Weapon_PriClipCurrent_Value = 0;
int Weapon_SecClipCurrent_Value = 0;
//Loop through all of our weapon slots.
for (int i = 0; i < 12; i++)
{
if (i == 0)
{
pkvWeapon_Value = pkvWeapon_0->GetString();
Weapon_PriClip_Value = pkvWeapon_0_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_0_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_0_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_0_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_0_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_0_SecClipAmmoLeft->GetInt();
}
else if (i == 1)
{
pkvWeapon_Value = pkvWeapon_1->GetString();
Weapon_PriClip_Value = pkvWeapon_1_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_1_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_1_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_1_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_1_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_1_SecClipAmmoLeft->GetInt();
}
else if (i == 2)
{
pkvWeapon_Value = pkvWeapon_2->GetString();
Weapon_PriClip_Value = pkvWeapon_2_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_2_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_2_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_2_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_2_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_2_SecClipAmmoLeft->GetInt();
}
else if (i == 3)
{
pkvWeapon_Value = pkvWeapon_3->GetString();
Weapon_PriClip_Value = pkvWeapon_3_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_3_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_3_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_3_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_3_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_3_SecClipAmmoLeft->GetInt();
}
else if (i == 4)
{
pkvWeapon_Value = pkvWeapon_4->GetString();
Weapon_PriClip_Value = pkvWeapon_4_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_4_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_4_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_4_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_4_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_4_SecClipAmmoLeft->GetInt();
}
else if (i == 5)
{
pkvWeapon_Value = pkvWeapon_5->GetString();
Weapon_PriClip_Value = pkvWeapon_5_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_5_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_5_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_5_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_5_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_5_SecClipAmmoLeft->GetInt();
}
else if (i == 6)
{
pkvWeapon_Value = pkvWeapon_6->GetString();
Weapon_PriClip_Value = pkvWeapon_6_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_6_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_6_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_6_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_6_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_6_SecClipAmmoLeft->GetInt();
}
else if (i == 7)
{
pkvWeapon_Value = pkvWeapon_7->GetString();
Weapon_PriClip_Value = pkvWeapon_7_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_7_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_7_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_7_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_7_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_7_SecClipAmmoLeft->GetInt();
}
else if (i == 8)
{
pkvWeapon_Value = pkvWeapon_8->GetString();
Weapon_PriClip_Value = pkvWeapon_8_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_8_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_8_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_8_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_8_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_8_SecClipAmmoLeft->GetInt();
}
else if (i == 9)
{
pkvWeapon_Value = pkvWeapon_9->GetString();
Weapon_PriClip_Value = pkvWeapon_9_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_9_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_9_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_9_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_9_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_9_SecClipAmmoLeft->GetInt();
}
else if (i == 10)
{
pkvWeapon_Value = pkvWeapon_10->GetString();
Weapon_PriClip_Value = pkvWeapon_10_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_10_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_10_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_10_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_10_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_10_SecClipAmmoLeft->GetInt();
}
else if (i == 11)
{
pkvWeapon_Value = pkvWeapon_11->GetString();
Weapon_PriClip_Value = pkvWeapon_11_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_11_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_11_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_11_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_11_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_11_SecClipAmmoLeft->GetInt();
}
else if (i == 12)
{
pkvWeapon_Value = pkvWeapon_12->GetString();
Weapon_PriClip_Value = pkvWeapon_12_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_12_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_12_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_12_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_12_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_12_SecClipAmmoLeft->GetInt();
}
//Now give the weapon and ammo.
pPlayer->GiveNamedItem((pkvWeapon_Value));
pPlayer->Weapon_Switch(pPlayer->Weapon_OwnsThisType(pkvWeapon_Value));
if (pPlayer->GetActiveWeapon()->UsesClipsForAmmo1())
{
if (Weapon_PriClipCurrent_Value != -1)
{
if (strcmp(pkvWeapon_Value, "weapon_crossbow") == 0)
{
pPlayer->GetActiveWeapon()->m_iClip1 = Weapon_PriClipCurrent_Value;
pPlayer->GetActiveWeapon()->m_iPrimaryAmmoType = Weapon_PriClip_Value;
pPlayer->GetActiveWeapon()->SetPrimaryAmmoCount(int(Weapon_PriClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, Weapon_PriClip_Value);
}
else
{
pPlayer->GetActiveWeapon()->m_iClip1 = Weapon_PriClipCurrent_Value;
pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, pkvWeapon_PriClipAmmo_Value);
//Msg("Weapon primary clip value should be: %i\n", Weapon_PriClipCurrent_Value);
}
}
}
else
{
pPlayer->GetActiveWeapon()->m_iPrimaryAmmoType = Weapon_PriClip_Value;
pPlayer->GetActiveWeapon()->SetPrimaryAmmoCount(int(Weapon_PriClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, Weapon_PriClip_Value);
}
if (pPlayer->GetActiveWeapon()->UsesClipsForAmmo2())
{
if (Weapon_SecClipCurrent_Value != -1)
{
if (strcmp(pkvWeapon_Value, "weapon_crossbow") == 0)
{
pPlayer->GetActiveWeapon()->m_iClip2 = Weapon_SecClipCurrent_Value;
pPlayer->GetActiveWeapon()->m_iSecondaryAmmoType = Weapon_SecClip_Value;
pPlayer->GetActiveWeapon()->SetSecondaryAmmoCount(int(Weapon_SecClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, Weapon_SecClip_Value);
}
else
{
pPlayer->GetActiveWeapon()->m_iClip2 = Weapon_SecClipCurrent_Value;
pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, pkvWeapon_SecClipAmmo_Value);
}
}
}
else
{
pPlayer->GetActiveWeapon()->m_iSecondaryAmmoType = Weapon_SecClip_Value;
pPlayer->GetActiveWeapon()->SetSecondaryAmmoCount(int(Weapon_SecClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, Weapon_SecClip_Value);
}
}
//Now restore the players Active Weapon (the weapon they had out at the level transition).
pPlayer->Weapon_Switch(pPlayer->Weapon_OwnsThisType(pkvActiveWep_Value));
}
else
{
//Something went wrong show the class panel.
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
}
break;
}
}
else
{
//Something went wrong show the class panel.
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
}
#endif //SecobMod__SAVERESTORE
#ifdef SecobMod__ENABLE_MAP_BRIEFINGS
pPlayer->ShowViewPortPanel(PANEL_INFO, false, NULL);
const char *brief_title = "Briefing: ";//(hostname) ? hostname->GetString() : "MESSAGE OF THE DAY";
KeyValues *brief_data = new KeyValues("brief_data");
brief_data->SetString("title", brief_title); // info panel title
brief_data->SetString("type", "1"); // show userdata from stringtable entry
brief_data->SetString("msg", "briefing"); // use this stringtable entry
pPlayer->ShowViewPortPanel(PANEL_INFO, true, brief_data);
#endif //SecobMod__ENABLE_MAP_BRIEFINGS
data->deleteThis();
}
/*
===========
ClientPutInServer
called each time a player is spawned into the game
============
*/
void ClientPutInServer(edict_t *pEdict, const char *playername)
{
// Allocate a CBaseTFPlayer for pev, and call spawn
CHL2MP_Player *pPlayer = CHL2MP_Player::CreatePlayer("player", pEdict);
pPlayer->SetPlayerName(playername);
}
void ClientActive(edict_t *pEdict, bool bLoadGame)
{
// Can't load games in CS!
Assert(!bLoadGame);
CHL2MP_Player *pPlayer = ToHL2MPPlayer(CBaseEntity::Instance(pEdict));
FinishClientPutInServer(pPlayer);
}
/*
===============
const char *GetGameDescription()
Returns the descriptive name of this .dll. E.g., Half-Life, or Team Fortress 2
===============
*/
const char *GetGameDescription()
{
if (g_pGameRules) // this function may be called before the world has spawned, and the game rules initialized
return g_pGameRules->GetGameDescription();
else
return "Half-Life 2 Deathmatch";
}
//-----------------------------------------------------------------------------
// Purpose: Given a player and optional name returns the entity of that
// classname that the player is nearest facing
//
// Input :
// Output :
//-----------------------------------------------------------------------------
CBaseEntity* FindEntity(edict_t *pEdict, char *classname)
{
// If no name was given set bits based on the picked
if (FStrEq(classname, ""))
{
return (FindPickerEntityClass(static_cast<CBasePlayer*>(GetContainingEntity(pEdict)), classname));
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Precache game-specific models & sounds
//-----------------------------------------------------------------------------
void ClientGamePrecache(void)
{
CBaseEntity::PrecacheModel("models/player.mdl");
CBaseEntity::PrecacheModel("models/gibs/agibs.mdl");
CBaseEntity::PrecacheModel("models/weapons/v_hands.mdl");
CBaseEntity::PrecacheScriptSound("HUDQuickInfo.LowAmmo");
CBaseEntity::PrecacheScriptSound("HUDQuickInfo.LowHealth");
CBaseEntity::PrecacheScriptSound("FX_AntlionImpact.ShellImpact");
CBaseEntity::PrecacheScriptSound("Missile.ShotDown");
CBaseEntity::PrecacheScriptSound("Bullets.DefaultNearmiss");
CBaseEntity::PrecacheScriptSound("Bullets.GunshipNearmiss");
CBaseEntity::PrecacheScriptSound("Bullets.StriderNearmiss");
CBaseEntity::PrecacheScriptSound("Geiger.BeepHigh");
CBaseEntity::PrecacheScriptSound("Geiger.BeepLow");
}
// called by ClientKill and DeadThink
void respawn(CBaseEntity *pEdict, bool fCopyCorpse)
{
CHL2MP_Player *pPlayer = ToHL2MPPlayer(pEdict);
if (pPlayer)
{
if (gpGlobals->curtime > pPlayer->GetDeathTime() + DEATH_ANIMATION_TIME)
{
// respawn player
pPlayer->Spawn();
}
else
{
pPlayer->SetNextThink(gpGlobals->curtime + 0.1f);
}
}
}
void GameStartFrame(void)
{
VPROF("GameStartFrame()");
if (g_fGameOver)
return;
gpGlobals->teamplay = (teamplay.GetInt() != 0);
#ifdef DEBUG
extern void Bot_RunAll();
Bot_RunAll();
#endif
}
//=========================================================
// instantiate the proper game rules object
//=========================================================
void InstallGameRules()
{
// vanilla deathmatch
CreateGameRulesObject("CHL2MPRules");
}
| 35,694 | 15,869 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Because of the rules of argument-dependent lookup, we need to include the
// definition of operator<< for ConstantAbstractDomain before that of operator<<
// for DisjointUnionAbstractDomain.
#include "ConstantAbstractDomain.h"
#include "DisjointUnionAbstractDomain.h"
#include <gtest/gtest.h>
#include <string>
#include "AbstractDomainPropertyTest.h"
using namespace sparta;
using IntDomain = ConstantAbstractDomain<int>;
using StringDomain = ConstantAbstractDomain<std::string>;
using IntStringDomain = DisjointUnionAbstractDomain<IntDomain, StringDomain>;
INSTANTIATE_TYPED_TEST_CASE_P(DisjointUnionAbstractDomain,
AbstractDomainPropertyTest,
IntStringDomain);
template <>
std::vector<IntStringDomain>
AbstractDomainPropertyTest<IntStringDomain>::top_values() {
return {IntDomain::top(), StringDomain::top()};
}
template <>
std::vector<IntStringDomain>
AbstractDomainPropertyTest<IntStringDomain>::bottom_values() {
return {IntDomain::bottom(), StringDomain::bottom()};
}
template <>
std::vector<IntStringDomain>
AbstractDomainPropertyTest<IntStringDomain>::non_extremal_values() {
return {IntDomain(0), StringDomain("foo")};
}
TEST(DisjointUnionAbstractDomainTest, basicOperations) {
IntStringDomain zero = IntDomain(0);
IntStringDomain str = StringDomain("");
EXPECT_TRUE(zero.join(str).is_top());
EXPECT_TRUE(zero.meet(str).is_bottom());
EXPECT_NLEQ(zero, str);
EXPECT_NLEQ(str, zero);
EXPECT_NE(zero, str);
}
| 1,697 | 497 |
// This file has been automatically generated by the Unreal Header Implementation tool
#include "FGActorRepresentation.h"
bool UFGActorRepresentation::IsSupportedForNetworking() const{ return bool(); }
void UFGActorRepresentation::GetLifetimeReplicatedProps( TArray<FLifetimeProperty>& OutLifetimeProps) const{ }
FVector UFGActorRepresentation::GetActorLocation() const{ return FVector(); }
FRotator UFGActorRepresentation::GetActorRotation() const{ return FRotator(); }
UTexture2D* UFGActorRepresentation::GetRepresentationTexture() const{ return nullptr; }
FText UFGActorRepresentation::GetRepresentationText() const{ return FText(); }
FLinearColor UFGActorRepresentation::GetRepresentationColor() const{ return FLinearColor(); }
ERepresentationType UFGActorRepresentation::GetRepresentationType() const{ return ERepresentationType(); }
bool UFGActorRepresentation::GetShouldShowInCompass() const{ return bool(); }
bool UFGActorRepresentation::GetShouldShowOnMap() const{ return bool(); }
EFogOfWarRevealType UFGActorRepresentation::GetFogOfWarRevealType() const{ return EFogOfWarRevealType(); }
float UFGActorRepresentation::GetFogOfWarRevealRadius() const{ return float(); }
void UFGActorRepresentation::SetIsOnClient( bool onClient){ }
ECompassViewDistance UFGActorRepresentation::GetCompassViewDistance() const{ return ECompassViewDistance(); }
void UFGActorRepresentation::SetLocalCompassViewDistance( ECompassViewDistance compassViewDistance){ }
AFGActorRepresentationManager* UFGActorRepresentation::GetActorRepresentationManager(){ return nullptr; }
void UFGActorRepresentation::UpdateLocation(){ }
void UFGActorRepresentation::UpdateRotation(){ }
void UFGActorRepresentation::UpdateRepresentationText(){ }
void UFGActorRepresentation::UpdateRepresentationTexture(){ }
void UFGActorRepresentation::UpdateRepresentationColor(){ }
void UFGActorRepresentation::UpdateShouldShowInCompass(){ }
void UFGActorRepresentation::UpdateShouldShowOnMap(){ }
void UFGActorRepresentation::UpdateFogOfWarRevealType(){ }
void UFGActorRepresentation::UpdateFogOfWarRevealRadius(){ }
void UFGActorRepresentation::UpdateCompassViewDistance(){ }
void UFGActorRepresentation::OnRep_ShouldShowInCompass(){ }
void UFGActorRepresentation::OnRep_ShouldShowOnMap(){ }
void UFGActorRepresentation::OnRep_ActorRepresentationUpdated(){ }
| 2,320 | 663 |
#include "CreateStaffDialog.h"
#include "ui_createstaffdialog.h"
#include "model/staffmodel.h"
#include "model/accountmodel.h"
#include "model/account.h"
#include "model/staff.h"
#include "QMessageBox"
#include "mainwindow.h"
#include "stringutil.h"
CreateStaffDialog::CreateStaffDialog(int staffId, QWidget *parent)
: QDialog(parent)
, ui(new Ui::CreateStaffDialog)
, staff(Staff(staffId, "", "", -1))
, account(Account(-1, -1, "", ""))
{
// Load the UI.
ui->setupUi(this);
// Check if we are in modification or add.
int currentIndex = 0;
if(staffId != -1)
{
// Load the staff data.
staff = StaffModel::getStaffById(staffId);
// Fill the forms with the data.
ui->firstNameLineEdit->setText(staff.getFirstName());
ui->lastNameLineEdit->setText(staff.getLastName());
if(staff.getTypeId() == 7)
account = AccountModel::getAccountById(staff.getId());
// Change window title.
setWindowTitle(QString("Modification de la ressource ") + staff.getFirstName() + " " + staff.getLastName());
}
QList<StaffType> types = StaffModel::getStaffTypes();
for(int i = 0; i < types.size(); i++)
{
ui->typeComboBox->addItem(types[i].label);
if(staffId != -1 && types[i].id == staff.getTypeId())
currentIndex = i;
}
if(staffId != -1)
{
ui->typeComboBox->setCurrentIndex(currentIndex);
}
// Hide login and password
onComboBoxChanged();
// Connections.
connect(this, SIGNAL(accepted()), this, SLOT(onDialogAccepted()));
connect(this, SIGNAL(rejected()), this, SLOT(onDialogRejected()));
connect(ui->typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxChanged()));
connect(this, SIGNAL(onStaffAdded()), (MainWindow*)parent, SLOT(onClientAdded()));
// Capitalizer.
QFont font = ui->firstNameLineEdit->font();
font.setCapitalization(QFont::Capitalize);
ui->firstNameLineEdit->setFont(font);
ui->lastNameLineEdit->setFont(font);
}
CreateStaffDialog::~CreateStaffDialog()
{
delete ui;
}
void CreateStaffDialog::onDialogAccepted()
{
if(staff.getId() == -1)
{
// Create staff.
int staffId = StaffModel::addStaff(Staff(-1, StringUtil::capitalize(ui->firstNameLineEdit->text()), StringUtil::capitalize(ui->lastNameLineEdit->text()), StaffModel::getTypeIdFromLabel(ui->typeComboBox->currentText())));
// Create account only if needed.
if(ui->typeComboBox->currentText() == "Informaticien")
{
QString login = ui->loginLineEdit->text();
QString password = ui->passwordLineEdit->text();
AccountModel::createAccount(login, password, staffId);
}
}
else
{
// Create staff.
StaffModel::updateStaff(Staff(staff.getId(), StringUtil::capitalize(ui->firstNameLineEdit->text()), StringUtil::capitalize(ui->lastNameLineEdit->text()), StaffModel::getTypeIdFromLabel(ui->typeComboBox->currentText())));
// Create account only if needed.
if(ui->typeComboBox->currentText() == "Informaticien")
{
QString login = ui->loginLineEdit->text();
QString password = ui->passwordLineEdit->text();
if(staff.getTypeId() == 7)
AccountModel::updateAccount(Account(account.getId(), staff.getId(), login, password));
else
AccountModel::createAccount(login, password, staff.getId());
}
// Type 7 == informaticien
else if(staff.getTypeId() == 7)
{
AccountModel::removeAccountOfStaff(staff.getId());
}
}
emit onStaffAdded();
}
void CreateStaffDialog::onDialogRejected()
{
}
void CreateStaffDialog::onComboBoxChanged()
{
// If the selected role is one with an account, display the login & password.
if(ui->typeComboBox->currentText() == "Informaticien")
{
if(staff.getTypeId() == 7)
{
ui->passwordLineEdit->setText(account.getPassword());
ui->loginLineEdit->setText(account.getLogin());
}
ui->loginLabel->setVisible(true);
ui->loginLineEdit->setVisible(true);
ui->passwordLabel->setVisible(true);
ui->passwordLineEdit->setVisible(true);
}
else
{
if(staff.getTypeId() == 7)
{
QMessageBox::warning(this,"Attention", "Attention cela va supprimer le compte !");
}
ui->loginLabel->setVisible(false);
ui->loginLineEdit->setVisible(false);
ui->passwordLabel->setVisible(false);
ui->passwordLineEdit->setVisible(false);
}
}
| 4,623 | 1,463 |
/**
* Morpheus_Ccl_CsrMatrix.cpp
*
* EPCC, The University of Edinburgh
*
* (c) 2021 The University of Edinburgh
*
* Contributing Authors:
* Christodoulos Stylianou (c.stylianou@ed.ac.uk)
*
* 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 <phost/Morpheus_Ccl_CsrMatrix.hpp>
void ccl_phmat_csr_create_default(ccl_phmat_csr** A) {
*A = (new ccl_phmat_csr());
}
void ccl_phmat_csr_create(ccl_phmat_csr** A, ccl_index_t nrows,
ccl_index_t ncols, ccl_index_t nnnz) {
*A = (new ccl_phmat_csr("ccl_phmat_csr::", nrows, ncols, nnnz));
}
void ccl_phmat_csr_create_from_phmat_csr(ccl_phmat_csr* src,
ccl_phmat_csr** dst) {
*dst = (new ccl_phmat_csr(*src));
}
void ccl_phmat_csr_create_from_phmat_dyn(ccl_phmat_dyn* src,
ccl_phmat_csr** dst) {
*dst = (new ccl_phmat_csr(*src));
}
void ccl_phmat_csr_resize(ccl_phmat_csr* A, const ccl_index_t num_rows,
const ccl_index_t num_cols,
const ccl_index_t num_nnz) {
A->resize(num_rows, num_cols, num_nnz);
}
// Assumes dst matrix is always created
void ccl_phmat_csr_allocate_from_phmat_csr(ccl_phmat_csr* src,
ccl_phmat_csr* dst) {
dst->allocate("ccl_phmat_csr::allocate::", *src);
}
void ccl_phmat_csr_destroy(ccl_phmat_csr** A) { delete (*A); }
ccl_index_t ccl_phmat_csr_nrows(ccl_phmat_csr* A) { return A->nrows(); }
ccl_index_t ccl_phmat_csr_ncols(ccl_phmat_csr* A) { return A->ncols(); }
ccl_index_t ccl_phmat_csr_nnnz(ccl_phmat_csr* A) { return A->nnnz(); }
void ccl_phmat_csr_set_nrows(ccl_phmat_csr* A, ccl_index_t nrows) {
A->set_nrows(nrows);
}
void ccl_phmat_csr_set_ncols(ccl_phmat_csr* A, ccl_index_t ncols) {
A->set_ncols(ncols);
}
void ccl_phmat_csr_set_nnnz(ccl_phmat_csr* A, ccl_index_t nnnz) {
A->set_nnnz(nnnz);
}
ccl_index_t ccl_phmat_csr_row_offsets_at(ccl_phmat_csr* A, ccl_index_t i) {
return A->row_offsets(i);
}
ccl_index_t ccl_phmat_csr_column_indices_at(ccl_phmat_csr* A, ccl_index_t i) {
return A->column_indices(i);
}
ccl_value_t ccl_phmat_csr_values_at(ccl_phmat_csr* A, ccl_index_t i) {
return A->values(i);
}
ccl_phvec_dense_i* ccl_phmat_csr_row_offsets(ccl_phmat_csr* A) {
return &(A->row_offsets());
}
ccl_phvec_dense_i* ccl_phmat_csr_column_indices(ccl_phmat_csr* A) {
return &(A->column_indices());
}
ccl_phvec_dense_v* ccl_phmat_csr_values(ccl_phmat_csr* A) {
return &(A->values());
}
void ccl_phmat_csr_set_row_offsets_at(ccl_phmat_csr* A, ccl_index_t i,
ccl_index_t val) {
A->row_offsets(i) = val;
}
void ccl_phmat_csr_set_column_indices_at(ccl_phmat_csr* A, ccl_index_t i,
ccl_index_t val) {
A->column_indices(i) = val;
}
void ccl_phmat_csr_set_values_at(ccl_phmat_csr* A, ccl_index_t i,
ccl_value_t val) {
A->values(i) = val;
}
ccl_formats_e ccl_phmat_csr_format_enum(ccl_phmat_csr* A) {
return A->format_enum();
}
int ccl_phmat_csr_format_index(ccl_phmat_csr* A) { return A->format_index(); }
void ccl_phmat_csr_hostmirror_create_default(ccl_phmat_csr_hostmirror** A) {
*A = (new ccl_phmat_csr_hostmirror());
}
void ccl_phmat_csr_hostmirror_create(ccl_phmat_csr_hostmirror** A,
ccl_index_t nrows, ccl_index_t ncols,
ccl_index_t nnnz) {
*A = (new ccl_phmat_csr_hostmirror("ccl_phmat_csr_hostmirror::", nrows, ncols,
nnnz));
}
void ccl_phmat_csr_hostmirror_create_from_phmat_csr_hostmirror(
ccl_phmat_csr_hostmirror* src, ccl_phmat_csr_hostmirror** dst) {
*dst = (new ccl_phmat_csr_hostmirror(*src));
}
void ccl_phmat_csr_hostmirror_create_from_phmat_dyn_hostmirror(
ccl_phmat_dyn_hostmirror* src, ccl_phmat_csr_hostmirror** dst) {
*dst = (new ccl_phmat_csr_hostmirror(*src));
}
void ccl_phmat_csr_hostmirror_resize(ccl_phmat_csr_hostmirror* A,
const ccl_index_t num_rows,
const ccl_index_t num_cols,
const ccl_index_t num_nnz) {
A->resize(num_rows, num_cols, num_nnz);
}
// Assumes dst matrix is always created
void ccl_phmat_csr_hostmirror_allocate_from_phmat_csr_hostmirror(
ccl_phmat_csr_hostmirror* src, ccl_phmat_csr_hostmirror* dst) {
dst->allocate("ccl_phmat_csr_hostmirror::allocate::", *src);
}
void ccl_phmat_csr_hostmirror_destroy(ccl_phmat_csr_hostmirror** A) {
delete (*A);
}
ccl_index_t ccl_phmat_csr_hostmirror_nrows(ccl_phmat_csr_hostmirror* A) {
return A->nrows();
}
ccl_index_t ccl_phmat_csr_hostmirror_ncols(ccl_phmat_csr_hostmirror* A) {
return A->ncols();
}
ccl_index_t ccl_phmat_csr_hostmirror_nnnz(ccl_phmat_csr_hostmirror* A) {
return A->nnnz();
}
void ccl_phmat_csr_hostmirror_set_nrows(ccl_phmat_csr_hostmirror* A,
ccl_index_t nrows) {
A->set_nrows(nrows);
}
void ccl_phmat_csr_hostmirror_set_ncols(ccl_phmat_csr_hostmirror* A,
ccl_index_t ncols) {
A->set_ncols(ncols);
}
void ccl_phmat_csr_hostmirror_set_nnnz(ccl_phmat_csr_hostmirror* A,
ccl_index_t nnnz) {
A->set_nnnz(nnnz);
}
ccl_index_t ccl_phmat_csr_hostmirror_row_offsets_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i) {
return A->row_offsets(i);
}
ccl_index_t ccl_phmat_csr_hostmirror_column_indices_at(
ccl_phmat_csr_hostmirror* A, ccl_index_t i) {
return A->column_indices(i);
}
ccl_value_t ccl_phmat_csr_hostmirror_values_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i) {
return A->values(i);
}
ccl_phvec_dense_i_hostmirror* ccl_phmat_csr_hostmirror_row_offsets(
ccl_phmat_csr_hostmirror* A) {
return &(A->row_offsets());
}
ccl_phvec_dense_i_hostmirror* ccl_phmat_csr_hostmirror_column_indices(
ccl_phmat_csr_hostmirror* A) {
return &(A->column_indices());
}
ccl_phvec_dense_v_hostmirror* ccl_phmat_csr_hostmirror_values(
ccl_phmat_csr_hostmirror* A) {
return &(A->values());
}
void ccl_phmat_csr_hostmirror_set_row_offsets_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i,
ccl_index_t val) {
A->row_offsets(i) = val;
}
void ccl_phmat_csr_hostmirror_set_column_indices_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i,
ccl_index_t val) {
A->column_indices(i) = val;
}
void ccl_phmat_csr_hostmirror_set_values_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i, ccl_value_t val) {
A->values(i) = val;
}
ccl_formats_e ccl_phmat_csr_hostmirror_format_enum(
ccl_phmat_csr_hostmirror* A) {
return A->format_enum();
}
int ccl_phmat_csr_hostmirror_format_index(ccl_phmat_csr_hostmirror* A) {
return A->format_index();
}
| 7,655 | 3,301 |
#include "Mesh.h"
namespace Ahwassa {
} | 41 | 19 |
#include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::forms;
namespace examples {
class form1 : public form {
public:
form1() {
text("Checked list box example");
client_size({200, 240});
checked_list_box1.parent(*this);
checked_list_box1.anchor(anchor_styles::top | anchor_styles::left | anchor_styles::bottom | anchor_styles::right);
checked_list_box1.location({20, 20});
checked_list_box1.size({160, 200});
for (auto index = 1; index <= 10; ++index)
checked_list_box1.items().push_back({ustring::format("Item {}", index), index % 2 != 0});
checked_list_box1.selected_index(0);
checked_list_box1.item_check += [](object& sender, item_check_event_args& e) {
cdebug << ustring::format("item_check, index={}, new_value={}, current_value={}", e.index(), e.new_value(), e.current_value()) << endl;
};
}
private:
checked_list_box checked_list_box1;
};
}
int main() {
application::run(examples::form1());
}
| 1,044 | 364 |
/*
** bbannouncer.cpp
** The announcer from Blood (The Voice).
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** 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. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
**---------------------------------------------------------------------------
**
** It's been so long since I played a bloodbath, I don't know when all
** these sounds are used, so much of this usage is me guessing. Some of
** it has also obviously been reused for events that were never present
** in bloodbaths.
**
** I should really have a base Announcer class and derive the Bloodbath
** announcer off of that. That way, multiple announcer styles could be
** supported easily.
*/
// HEADER FILES ------------------------------------------------------------
#include "actor.h"
#include "gstrings.h"
#include "s_sound.h"
#include "m_random.h"
#include "d_player.h"
#include "g_level.h"
#include "doomstat.h"
// MACROS ------------------------------------------------------------------
// TYPES -------------------------------------------------------------------
struct SoundAndString
{
const char *Message;
const char *Sound;
};
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
void SexMessage (const char *from, char *to, int gender,
const char *victim, const char *killer);
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
// PUBLIC DATA DEFINITIONS -------------------------------------------------
CVAR (Bool, cl_bbannounce, false, CVAR_ARCHIVE)
// PRIVATE DATA DEFINITIONS ------------------------------------------------
static const char *BeginSounds[] =
{
"VO1.SFX", // Let the bloodbath begin
"VO2.SFX", // The festival of blood continues
};
static const SoundAndString WorldKillSounds[] =
{
{ "BBA_EXCREMENT", "VO7.SFX" }, // Excrement
{ "BBA_HAMBURGER", "VO8.SFX" }, // Hamburger
{ "BBA_SCROTUM", "VO9.SFX" }, // Scrotum separation
};
static const SoundAndString SuicideSounds[] =
{
{ "BBA_SUICIDE", "VO13.SFX" }, // Unassisted death
{ "BBA_SUICIDE", "VO5.SFX" }, // Kevorkian approves
{ "BBA_POPULATION", "VO12.SFX" }, // Population control
{ "BBA_DARWIN", "VO16.SFX" } // Darwin award
};
static const SoundAndString KillSounds[] =
{
{ "BBA_BONED", "BONED.SFX" }, // Boned
{ "BBA_CREAMED", "CREAMED.SFX" }, // Creamed
{ "BBA_DECIMAT", "DECIMAT.SFX" }, // Decimated
{ "BBA_DESTRO", "DESTRO.SFX" }, // Destroyed
{ "BBA_DICED", "DICED.SFX" }, // Diced
{ "BBA_DISEMBO", "DISEMBO.SFX" }, // Disembowled
{ "BBA_FLATTE", "FLATTE.SFX" }, // Flattened
{ "BBA_JUSTICE", "JUSTICE.SFX" }, // Justice
{ "BBA_MADNESS", "MADNESS.SFX" }, // Madness
{ "BBA_KILLED", "KILLED.SFX" }, // Killed
{ "BBA_MINCMEAT", "MINCMEAT.SFX" }, // Mincemeat
{ "BBA_MASSACR", "MASSACR.SFX" }, // Massacred
{ "BBA_MUTILA", "MUTILA.SFX" }, // Mutilated
{ "BBA_REAMED", "REAMED.SFX" }, // Reamed
{ "BBA_RIPPED", "RIPPED.SFX" }, // Ripped
{ "BBA_SLAUGHT", "SLAUGHT.SFX" }, // Slaughtered
{ "BBA_SMASHED", "SMASHED.SFX" }, // Smashed
{ "BBA_SODOMIZ", "SODOMIZ.SFX" }, // Sodomized
{ "BBA_SPLATT", "SPLATT.SFX" }, // Splattered
{ "BBA_SQUASH", "SQUASH.SFX" }, // Squashed
{ "BBA_THROTTL", "THROTTL.SFX" }, // Throttled
{ "BBA_WASTED", "WASTED.SFX" }, // Wasted
{ "BBA_BODYBAG", "VO10.SFX" }, // Body bagged
{ "BBA_HOSED", "VO25.SFX" }, // Hosed
{ "BBA_TOAST", "VO27.SFX" }, // Toasted
{ "BBA_HELL", "VO28.SFX" }, // Sent to hell
{ "BBA_SPRAYED", "VO35.SFX" }, // Sprayed
{ "BBA_DOGMEAT", "VO36.SFX" }, // Dog meat
{ "BBA_BEATEN", "VO39.SFX" }, // Beaten like a cur
{ "BBA_SNUFF", "VO41.SFX" }, // Snuffed
{ "BBA_CASTRA", "CASTRA.SFX" }, // Castrated
};
static const char *GoodJobSounds[] =
{
"VO22.SFX", // Fine work
"VO23.SFX", // Well done
"VO44.SFX", // Excellent
};
static const char *TooBadSounds[] =
{
"VO17.SFX", // Go play Mario
"VO18.SFX", // Need a tricycle?
"VO37.SFX", // Bye bye now
};
static const char *TelefragSounds[] =
{
"VO29.SFX", // Pass the jelly
"VO34.SFX", // Spillage
"VO40.SFX", // Whipped and creamed
"VO42.SFX", // Spleen vented
"VO43.SFX", // Vaporized
"VO38.SFX", // Ripped him loose
"VO14.SFX", // Shat upon
};
#if 0 // Sounds I don't know what to do with
"VO6.SFX", // Asshole
"VO15.SFX", // Finish him
"VO19.SFX", // Talented
"VO20.SFX", // Good one
"VO21.SFX", // Lunch meat
"VO26.SFX", // Humiliated
"VO30.SFX", // Punishment delivered
"VO31.SFX", // Bobbit-ized
"VO32.SFX", // Stiffed
"VO33.SFX", // He shoots... He scores
#endif
static int LastAnnounceTime;
static FRandom pr_bbannounce ("BBAnnounce");
// CODE --------------------------------------------------------------------
//==========================================================================
//
// DoVoiceAnnounce
//
//==========================================================================
void DoVoiceAnnounce (const char *sound)
{
// Don't play announcements too close together
if (LastAnnounceTime == 0 || LastAnnounceTime <= level.time-5)
{
LastAnnounceTime = level.time;
S_Sound (CHAN_VOICE, sound, 1, ATTN_NONE);
}
}
//==========================================================================
//
// AnnounceGameStart
//
// Called when a new map is entered.
//
//==========================================================================
bool AnnounceGameStart ()
{
LastAnnounceTime = 0;
if (cl_bbannounce && deathmatch)
{
DoVoiceAnnounce (BeginSounds[pr_bbannounce() & 1]);
}
return false;
}
//==========================================================================
//
// AnnounceKill
//
// Called when somebody dies.
//
//==========================================================================
bool AnnounceKill (AActor *killer, AActor *killee)
{
const char *killerName;
const SoundAndString *choice;
const char *message;
int rannum = pr_bbannounce();
if (cl_bbannounce && deathmatch)
{
bool playSound = killee->CheckLocalView (consoleplayer);
if (killer == NULL)
{ // The world killed the player
if (killee->player->userinfo.GetGender() == GENDER_MALE)
{ // Only males have scrotums to separate
choice = &WorldKillSounds[rannum % 3];
}
else
{
choice = &WorldKillSounds[rannum & 1];
}
killerName = NULL;
}
else if (killer == killee)
{ // The player killed self
choice = &SuicideSounds[rannum & 3];
killerName = killer->player->userinfo.GetName();
}
else
{ // Another player did the killing
if (killee->player->userinfo.GetGender() == GENDER_MALE)
{ // Only males can be castrated
choice = &KillSounds[rannum % countof(KillSounds)];
}
else
{
choice = &KillSounds[rannum % (countof(KillSounds) - 1)];
}
killerName = killer->player->userinfo.GetName();
// Blood only plays the announcement sound on the killer's
// computer. I think it sounds neater to also hear it on
// the killee's machine.
playSound |= killer->CheckLocalView (consoleplayer);
}
message = GStrings(choice->Message);
if (message != NULL)
{
char assembled[1024];
SexMessage (message, assembled, killee->player->userinfo.GetGender(),
killee->player->userinfo.GetName(), killerName);
Printf (PRINT_MEDIUM, "%s\n", assembled);
}
if (playSound)
{
DoVoiceAnnounce (choice->Sound);
}
return message != NULL;
}
return false;
}
//==========================================================================
//
// AnnounceTelefrag
//
// Called when somebody dies by telefragging.
//
//==========================================================================
bool AnnounceTelefrag (AActor *killer, AActor *killee)
{
int rannum = pr_bbannounce();
if (cl_bbannounce && multiplayer)
{
const char *message = GStrings("OB_MPTELEFRAG");
if (message != NULL)
{
char assembled[1024];
SexMessage (message, assembled, killee->player->userinfo.GetGender(),
killee->player->userinfo.GetName(), killer->player->userinfo.GetName());
Printf (PRINT_MEDIUM, "%s\n", assembled);
}
if (killee->CheckLocalView (consoleplayer) ||
killer->CheckLocalView (consoleplayer))
{
DoVoiceAnnounce (TelefragSounds[rannum % 7]);
}
return message != NULL;
}
return false;
}
//==========================================================================
//
// AnnounceSpree
//
// Called when somebody is on a spree.
//
//==========================================================================
bool AnnounceSpree (AActor *who)
{
return false;
}
//==========================================================================
//
// AnnounceSpreeLoss
//
// Called when somebody on a spree gets killed.
//
//==========================================================================
bool AnnounceSpreeLoss (AActor *who)
{
if (cl_bbannounce)
{
if (who->CheckLocalView (consoleplayer))
{
DoVoiceAnnounce (TooBadSounds[M_Random() % 3]);
}
}
return false;
}
//==========================================================================
//
// AnnounceMultikill
//
// Called when somebody is quickly raking in kills.
//
//==========================================================================
bool AnnounceMultikill (AActor *who)
{
if (cl_bbannounce)
{
if (who->CheckLocalView (consoleplayer))
{
DoVoiceAnnounce (GoodJobSounds[M_Random() % 3]);
}
}
return false;
}
| 11,254 | 4,419 |
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// 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.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>::Vector4() :
v0(0),
v1(0),
v2(0),
v3(0)
{
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>::Vector4(T V0, T V1, T V2, T V3) :
v0(V0),
v1(V1),
v2(V2),
v3(V3)
{
}
////////////////////////////////////////////////////////////
template <typename T>
template <typename U>
inline Vector4<T>::Vector4(const Vector4<U>& vector) :
v0(static_cast<T>(vector.v0)),
v1(static_cast<T>(vector.v1)),
v2(static_cast<T>(vector.v2)),
v3(static_cast<T>(vector.v3))
{
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator -(const Vector4<T>& left)
{
return Vector4<T>(-left.v0, -left.v1, -left.v2, -left.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator +=(Vector4<T>& left, const Vector4<T>& right)
{
left.v0 += right.v0;
left.v1 += right.v1;
left.v2 += right.v2;
left.v3 += right.v3;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator -=(Vector4<T>& left, const Vector4<T>& right)
{
left.v0 -= right.v0;
left.v1 -= right.v1;
left.v2 -= right.v2;
left.v3 -= right.v3;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator +(const Vector4<T>& left, const Vector4<T>& right)
{
return Vector4<T>(left.v0 + right.v0, left.v1 + right.v1, left.v2 + right.v2, left.v3 + right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator -(const Vector4<T>& left, const Vector4<T>& right)
{
return Vector4<T>(left.v0 - right.v0, left.v1 - right.v1, left.v2 - right.v2, left.v3 - right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator *(const Vector4<T>& left, T right)
{
return Vector4<T>(left.v0 * right, left.v1 * right, left.v2 * right, left.v3 * right);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator *(T left, const Vector4<T>& right)
{
return Vector4<T>(left * right.v0, left * right.v1, left * right.v2, left * right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator *=(Vector4<T>& left, T right)
{
left.v0 *= right;
left.v1 *= right;
left.v2 *= right;
left.v3 *= right;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator /(const Vector4<T>& left, T right)
{
return Vector4<T>(left.v0 / right, left.v1 / right, left.v2 / right, left.v3 / right);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator /=(Vector4<T>& left, T right)
{
left.v0 /= right;
left.v1 /= right;
left.v2 /= right;
left.v3 /= right;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator ==(const Vector4<T>& left, const Vector4<T>& right)
{
return (left.v0 == right.v0) && (left.v1 == right.v1) && (left.v2 == right.v2) && (left.v3 == right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator !=(const Vector4<T>& left, const Vector4<T>& right)
{
return (left.v0 != right.v0) && (left.v1 != right.v1) && (left.v2 != right.v2) && (left.v3 != right.v3);
}
| 4,787 | 1,522 |
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CParseHandlerUtils.cpp
//
// @doc:
// Implementation of the helper methods for parse handler
//
//
// @owner:
//
//
// @test:
//
//
//---------------------------------------------------------------------------
#include "naucrates/dxl/parser/CParseHandlerUtils.h"
#include "naucrates/statistics/IStatistics.h"
using namespace gpos;
using namespace gpdxl;
using namespace gpnaucrates;
//---------------------------------------------------------------------------
// @function:
// CParseHandlerUtils::SetProperties
//
// @doc:
// Parse and the set operator's costing and statistical properties
//
//---------------------------------------------------------------------------
void
CParseHandlerUtils::SetProperties
(
CDXLNode *pdxln,
CParseHandlerProperties *pphProp
)
{
GPOS_ASSERT(NULL != pphProp->Pdxlprop());
// set physical properties
CDXLPhysicalProperties *pdxlprop = pphProp->Pdxlprop();
pdxlprop->AddRef();
pdxln->SetProperties(pdxlprop);
// set the statistical information
CDXLStatsDerivedRelation *pdxlstatsderrel = pphProp->Pdxlstatsderrel();
if (NULL != pdxlstatsderrel)
{
pdxlstatsderrel->AddRef();
pdxlprop->SetStats(pdxlstatsderrel);
}
}
// EOF
| 1,342 | 440 |
#include "ThreadsLimitListener.h"
#include "common/WithErrnoCheck.h"
#include "logger/Logger.h"
#include "seccomp/SeccompRule.h"
#include "seccomp/action/ActionAllow.h"
#include "seccomp/action/ActionKill.h"
#include "seccomp/filter/LibSeccompFilter.h"
namespace s2j {
namespace limits {
ThreadsLimitListener::ThreadsLimitListener(int32_t threadsLimit)
: threadsLimit_{threadsLimit} {
TRACE(threadsLimit);
syscallRules_.emplace_back(
seccomp::SeccompRule("fork", seccomp::action::ActionKill{}));
syscallRules_.emplace_back(
seccomp::SeccompRule("vfork", seccomp::action::ActionKill{}));
if (threadsLimit_ < 0) {
// Disable threads support
syscallRules_.emplace_back(
seccomp::SeccompRule("clone", seccomp::action::ActionKill{}));
}
else {
// Enable threads support
using Arg = seccomp::filter::SyscallArg;
syscallRules_.emplace_back(seccomp::SeccompRule(
"clone",
seccomp::action::ActionAllow{},
(Arg(2) & CLONE_VM) == CLONE_VM));
syscallRules_.emplace_back(seccomp::SeccompRule(
"clone",
seccomp::action::ActionKill(),
(Arg(2) & CLONE_VM) == 0));
// And various thread related
syscallRules_.emplace_back(seccomp::SeccompRule(
// TODO: allow sleep up to time limit
"nanosleep",
seccomp::action::ActionAllow{}));
}
}
std::tuple<tracer::TraceAction, tracer::TraceAction>
ThreadsLimitListener::onPostClone(
const tracer::TraceEvent& traceEvent,
tracer::Tracee& tracee,
tracer::Tracee& traceeChild) {
TRACE(tracee.getPid(), traceeChild.getPid());
if (threadsLimit_ < 0) {
outputBuilder_->setKillReason(
printer::OutputBuilder::KillReason::RV,
"Threads are not allowed");
return {tracer::TraceAction::KILL, tracer::TraceAction::KILL};
}
threadsPids_.insert(traceeChild.getPid());
logger::debug(
"Thread ",
traceeChild.getPid(),
" started, new thread count ",
threadsPids_.size());
if (threadsPids_.size() > static_cast<uint32_t>(threadsLimit_)) {
outputBuilder_->setKillReason(
printer::OutputBuilder::KillReason::RV,
"threads limit exceeded");
logger::info(
"Threads limit ", threadsLimit_, " exceeded, killing tracee");
return {tracer::TraceAction::KILL, tracer::TraceAction::KILL};
}
return {tracer::TraceAction::CONTINUE, tracer::TraceAction::CONTINUE};
}
executor::ExecuteAction ThreadsLimitListener::onExecuteEvent(
const executor::ExecuteEvent& executeEvent) {
TRACE(executeEvent.pid);
if (threadsLimit_ < 0)
return executor::ExecuteAction::CONTINUE;
if (executeEvent.exited || executeEvent.killed) {
threadsPids_.erase(executeEvent.pid);
logger::debug(
"Thread ",
executeEvent.pid,
" exited, new threads count ",
threadsPids_.size());
}
return executor::ExecuteAction::CONTINUE;
}
} // namespace limits
} // namespace s2j
| 3,261 | 982 |
// https://cses.fi/problemset/task/1084/
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vi;
int main() {
int n, m, k;
cin >> n >> m >> k;
vi a(m);
for (int i = 0; i < n; i++) cin >> a[i];
vi b(m);
for (int i = 0; i < m; i++) cin >> b[i];
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int i = 0;
int j = 0;
int c = 0;
while (i < n && j < m)
if (a[i] + k < b[j]) i++;
else if (a[i] - k > b[j]) j++;
else { i++; j++; c++; }
cout << c << endl;
}
| 542 | 254 |
/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2012 Sandro Santilli <strk@kbt.io>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
***********************************************************************
*
* Last port: precision/PrecisionreducerCoordinateOperation.java r591 (JTS-1.12)
*
**********************************************************************/
#include <geos/precision/PrecisionReducerCoordinateOperation.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/LineString.h>
#include <geos/geom/LinearRing.h>
#include <geos/operation/valid/RepeatedPointRemover.h>
#include <geos/util.h>
#include <vector>
using namespace geos::geom;
namespace geos {
namespace precision { // geos.precision
std::unique_ptr<CoordinateSequence>
PrecisionReducerCoordinateOperation::edit(const CoordinateSequence* cs,
const Geometry* geom)
{
auto csSize = cs->size();
if(csSize == 0) {
return nullptr;
}
auto vc = detail::make_unique<std::vector<Coordinate>>(csSize);
// copy coordinates and reduce
for(size_t i = 0; i < csSize; ++i) {
(*vc)[i] = cs->getAt(i);
targetPM.makePrecise((*vc)[i]);
}
// reducedCoords take ownership of 'vc'
auto reducedCoords = geom->getFactory()->getCoordinateSequenceFactory()->create(vc.release());
// remove repeated points, to simplify returned geometry as
// much as possible.
std::unique_ptr<CoordinateSequence> noRepeatedCoords = operation::valid::RepeatedPointRemover::removeRepeatedPoints(reducedCoords.get());
/**
* Check to see if the removal of repeated points
* collapsed the coordinate List to an invalid length
* for the type of the parent geometry.
* It is not necessary to check for Point collapses,
* since the coordinate list can
* never collapse to less than one point.
* If the length is invalid, return the full-length coordinate array
* first computed, or null if collapses are being removed.
* (This may create an invalid geometry - the client must handle this.)
*/
unsigned int minLength = 0;
if(dynamic_cast<const LineString*>(geom)) {
minLength = 2;
}
if(dynamic_cast<const LinearRing*>(geom)) {
minLength = 4;
}
if(removeCollapsed) {
reducedCoords = nullptr;
}
// return null or original length coordinate array
if(noRepeatedCoords->getSize() < minLength) {
return reducedCoords;
}
// ok to return shorter coordinate array
return noRepeatedCoords;
}
} // namespace geos.precision
} // namespace geos
| 3,041 | 919 |
#ifndef XTENSOR_XBLOCKWISE_REDUCER_HPP
#define XTENSOR_XBLOCKWISE_REDUCER_HPP
#include "xtl/xclosure.hpp"
#include "xtl/xsequence.hpp"
#include "xshape.hpp"
#include "xblockwise_reducer_functors.hpp"
#include "xmultiindex_iterator.hpp"
#include "xreducer.hpp"
namespace xt
{
template<class CT, class F, class X, class O>
class xblockwise_reducer
{
public:
using self_type = xblockwise_reducer<CT, F, X, O>;
using raw_options_type = std::decay_t<O>;
using keep_dims = xtl::mpl::contains<raw_options_type, xt::keep_dims_type>;
using xexpression_type = std::decay_t<CT>;
using shape_type = typename xreducer_shape_type<typename xexpression_type::shape_type, std::decay_t<X>, keep_dims>::type;
using functor_type = F;
using value_type = typename functor_type::value_type;
using input_shape_type = typename xexpression_type::shape_type;
using input_chunk_index_type = filter_fixed_shape_t<input_shape_type>;
using input_grid_strides = filter_fixed_shape_t<input_shape_type>;
using axes_type = X;
using chunk_shape_type = filter_fixed_shape_t<shape_type>;
template<class E, class BS, class XX, class OO, class FF>
xblockwise_reducer(E && e, BS && block_shape, XX && axes, OO && options, FF && functor);
const input_shape_type & input_shape()const;
const axes_type & axes() const;
std::size_t dimension() const;
const shape_type & shape() const;
const chunk_shape_type & chunk_shape() const;
template<class R>
void assign_to(R & result) const;
private:
using mapping_type = filter_fixed_shape_t<shape_type>;
using input_chunked_view_type = xchunked_view<const std::decay_t<CT> &>;
using input_const_chunked_iterator_type = typename input_chunked_view_type::const_chunk_iterator;
using input_chunk_range_type = std::array<xmultiindex_iterator<input_chunk_index_type>, 2>;
template<class CI>
void assign_to_chunk(CI & result_chunk_iter) const;
template<class CI>
input_chunk_range_type compute_input_chunk_range(CI & result_chunk_iter) const;
input_const_chunked_iterator_type get_input_chunk_iter(input_chunk_index_type input_chunk_index) const;
void init_shapes();
CT m_e;
xchunked_view<const std::decay_t<CT> &> m_e_chunked_view;
axes_type m_axes;
raw_options_type m_options;
functor_type m_functor;
shape_type m_result_shape;
chunk_shape_type m_result_chunk_shape;
mapping_type m_mapping;
input_grid_strides m_input_grid_strides;
};
template<class CT, class F, class X, class O>
template<class E, class BS, class XX, class OO, class FF>
xblockwise_reducer<CT, F, X, O>::xblockwise_reducer(E && e, BS && block_shape, XX && axes, OO && options, FF && functor)
: m_e(std::forward<E>(e)),
m_e_chunked_view(m_e, std::forward<BS>(block_shape)),
m_axes(std::forward<XX>(axes)),
m_options(std::forward<OO>(options)),
m_functor(std::forward<FF>(functor)),
m_result_shape(),
m_result_chunk_shape(),
m_mapping(),
m_input_grid_strides()
{
init_shapes();
resize_container(m_input_grid_strides, m_e.dimension());
std::size_t stride = 1;
for (std::size_t i = m_input_grid_strides.size(); i != 0; --i)
{
m_input_grid_strides[i-1] = stride;
stride *= m_e_chunked_view.grid_shape()[i - 1];
}
}
template<class CT, class F, class X, class O>
inline auto xblockwise_reducer<CT, F, X, O>::input_shape()const -> const input_shape_type &
{
return m_e.shape();
}
template<class CT, class F, class X, class O>
inline auto xblockwise_reducer<CT, F, X, O>::axes() const -> const axes_type &
{
return m_axes;
}
template<class CT, class F, class X, class O>
inline std::size_t xblockwise_reducer<CT, F, X, O>::dimension() const
{
return m_result_shape.size();
}
template<class CT, class F, class X, class O>
inline auto xblockwise_reducer<CT, F, X, O>::shape() const -> const shape_type &
{
return m_result_shape;
}
template<class CT, class F, class X, class O>
inline auto xblockwise_reducer<CT, F, X, O>::chunk_shape() const -> const chunk_shape_type &
{
return m_result_chunk_shape;
}
template<class CT, class F, class X, class O>
template<class R>
inline void xblockwise_reducer<CT, F, X, O>::assign_to(R & result) const
{
auto result_chunked_view = as_chunked(result, m_result_chunk_shape);
for(auto chunk_iter = result_chunked_view.chunk_begin(); chunk_iter != result_chunked_view.chunk_end(); ++chunk_iter)
{
assign_to_chunk(chunk_iter);
}
}
template<class CT, class F, class X, class O>
auto xblockwise_reducer<CT, F, X, O>::get_input_chunk_iter(input_chunk_index_type input_chunk_index) const ->input_const_chunked_iterator_type
{
std::size_t chunk_linear_index = 0;
for(std::size_t i=0; i<m_e_chunked_view.dimension(); ++i)
{
chunk_linear_index += input_chunk_index[i] * m_input_grid_strides[i];
}
return input_const_chunked_iterator_type(m_e_chunked_view, std::move(input_chunk_index), chunk_linear_index);
}
template<class CT, class F, class X, class O>
template<class CI>
void xblockwise_reducer<CT, F, X, O>::assign_to_chunk(CI & result_chunk_iter) const
{
auto result_chunk_view = *result_chunk_iter;
auto reduction_variable = m_functor.reduction_variable(result_chunk_view);
// get the range of input chunks we need to compute the desired ouput chunk
auto range = compute_input_chunk_range(result_chunk_iter);
// iterate over input chunk (indics)
auto first = true;
// std::for_each(std::get<0>(range), std::get<1>(range), [&](auto && input_chunk_index)
auto iter = std::get<0>(range);
while(iter != std::get<1>(range))
{
const auto & input_chunk_index = *iter;
// get input chunk iterator from chunk index
auto chunked_input_iter = this->get_input_chunk_iter(input_chunk_index);
auto input_chunk_view = *chunked_input_iter;
// compute the per block result
auto block_res = m_functor.compute(input_chunk_view, m_axes, m_options);
// merge
m_functor.merge(block_res, first, result_chunk_view, reduction_variable);
first = false;
++iter;
}
// finalize (ie smth like normalization)
m_functor.finalize(reduction_variable, result_chunk_view, *this);
}
template<class CT, class F, class X, class O>
template<class CI>
auto xblockwise_reducer<CT, F, X, O>::compute_input_chunk_range(CI & result_chunk_iter) const -> input_chunk_range_type
{
auto input_chunks_begin = xtl::make_sequence<input_chunk_index_type>(m_e_chunked_view.dimension(), 0);
auto input_chunks_end = xtl::make_sequence<input_chunk_index_type>(m_e_chunked_view.dimension());
XTENSOR_ASSERT(input_chunks_begin.size() == m_e_chunked_view.dimension());
XTENSOR_ASSERT(input_chunks_end.size() == m_e_chunked_view.dimension());
std::copy(m_e_chunked_view.grid_shape().begin(), m_e_chunked_view.grid_shape().end(), input_chunks_end.begin());
const auto & chunk_index = result_chunk_iter.chunk_index();
for(std::size_t result_ax_index=0; result_ax_index<m_result_shape.size(); ++result_ax_index)
{
if(m_result_shape[result_ax_index] != 1)
{
const auto input_ax_index = m_mapping[result_ax_index];
input_chunks_begin[input_ax_index] = chunk_index[result_ax_index];
input_chunks_end[input_ax_index] = chunk_index[result_ax_index] + 1;
}
}
return input_chunk_range_type{
multiindex_iterator_begin<input_chunk_index_type>(input_chunks_begin, input_chunks_end),
multiindex_iterator_end<input_chunk_index_type>(input_chunks_begin, input_chunks_end)
};
}
template<class CT, class F, class X, class O>
void xblockwise_reducer<CT, F, X, O>::init_shapes()
{
const auto & shape = m_e.shape();
const auto dimension = m_e.dimension();
const auto & block_shape = m_e_chunked_view.chunk_shape();
if (xtl::mpl::contains<raw_options_type, xt::keep_dims_type>::value)
{
resize_container(m_result_shape, dimension);
resize_container(m_result_chunk_shape, dimension);
resize_container(m_mapping, dimension);
for (std::size_t i = 0; i < dimension; ++i)
{
m_mapping[i] = i;
if (std::find(m_axes.begin(), m_axes.end(), i) == m_axes.end())
{
// i not in m_axes!
m_result_shape[i] = shape[i];
m_result_chunk_shape[i] = block_shape[i];
}
else
{
m_result_shape[i] = 1;
m_result_chunk_shape[i] = 1;
}
}
}
else
{
const auto result_dim = dimension - m_axes.size();
resize_container(m_result_shape, result_dim);
resize_container(m_result_chunk_shape, result_dim);
resize_container(m_mapping, result_dim);
for (std::size_t i = 0, idx = 0; i < dimension; ++i)
{
if (std::find(m_axes.begin(), m_axes.end(), i) == m_axes.end())
{
// i not in axes!
m_result_shape[idx] = shape[i];
m_result_chunk_shape[idx] = block_shape[i];
m_mapping[idx] = i;
++idx;
}
}
}
}
template<class E, class CS, class A, class O, class FF>
inline auto blockwise_reducer(E && e, CS && chunk_shape, A && axes, O && raw_options, FF && functor)
{
using functor_type = std::decay_t<FF>;
using closure_type = xtl::const_closure_type_t<E>;
using axes_type = std::decay_t<A>;
return xblockwise_reducer<
closure_type,
functor_type,
axes_type,
O
>(
std::forward<E>(e),
std::forward<CS>(chunk_shape),
std::forward<A>(axes),
std::forward<O>(raw_options),
std::forward<FF>(functor)
);
}
namespace blockwise
{
#define XTENSOR_BLOCKWISE_REDUCER_FUNC(FNAME, FUNCTOR)\
template<class T=void, class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>)\
>\
auto FNAME(E && e, BS && block_shape, X && axes, O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::forward<X>(axes),\
std::forward<O>(options),\
functor_type());\
}\
template<class T=void, class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(xtl::is_integral<std::decay_t<X>>)\
>\
auto FNAME(E && e, BS && block_shape, X axis, O options = O())\
{\
std::array<X,1> axes{axis};\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
axes,\
std::forward<O>(options),\
functor_type());\
}\
template<class T=void, class E, class BS, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(is_reducer_options<O>, xtl::negation<xtl::is_integral<std::decay_t<O>>>)\
>\
auto FNAME(E && e, BS && block_shape, O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using axes_type = filter_fixed_shape_t<typename input_expression_type::shape_type>;\
axes_type axes = xtl::make_sequence<axes_type>(e.dimension());\
XTENSOR_ASSERT(axes.size() == e.dimension());\
std::iota(axes.begin(), axes.end(), 0);\
using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::move(axes),\
std::forward<O>(options),\
functor_type());\
}\
template<class T=void, class E, class BS, class I, std::size_t N, class O = DEFAULT_STRATEGY_REDUCERS>\
auto FNAME(E && e, BS && block_shape, const I (&axes)[N], O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\
using axes_type = std::array<std::size_t, N>;\
auto ax = xt::forward_normalize<axes_type>(e, axes);\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::move(ax),\
std::forward<O>(options),\
functor_type());\
}
XTENSOR_BLOCKWISE_REDUCER_FUNC(sum, xt::detail::blockwise::sum_functor)
XTENSOR_BLOCKWISE_REDUCER_FUNC(prod, xt::detail::blockwise::prod_functor)
XTENSOR_BLOCKWISE_REDUCER_FUNC(amin, xt::detail::blockwise::amin_functor)
XTENSOR_BLOCKWISE_REDUCER_FUNC(amax, xt::detail::blockwise::amax_functor)
XTENSOR_BLOCKWISE_REDUCER_FUNC(mean, xt::detail::blockwise::mean_functor)
XTENSOR_BLOCKWISE_REDUCER_FUNC(variance, xt::detail::blockwise::variance_functor)
XTENSOR_BLOCKWISE_REDUCER_FUNC(stddev, xt::detail::blockwise::stddev_functor)
#undef XTENSOR_BLOCKWISE_REDUCER_FUNC
// norm reducers do *not* allow to to pass a template
// parameter to specifiy the internal computation type
#define XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(FNAME, FUNCTOR)\
template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>)\
>\
auto FNAME(E && e, BS && block_shape, X && axes, O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::forward<X>(axes),\
std::forward<O>(options),\
functor_type());\
}\
template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(xtl::is_integral<std::decay_t<X>>)\
>\
auto FNAME(E && e, BS && block_shape, X axis, O options = O())\
{\
std::array<X,1> axes{axis};\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
axes,\
std::forward<O>(options),\
functor_type());\
}\
template<class E, class BS, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(is_reducer_options<O>, xtl::negation<xtl::is_integral<std::decay_t<O>>>)\
>\
auto FNAME(E && e, BS && block_shape, O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using axes_type = filter_fixed_shape_t<typename input_expression_type::shape_type>;\
axes_type axes = xtl::make_sequence<axes_type>(e.dimension());\
XTENSOR_ASSERT(axes.size() == e.dimension());\
std::iota(axes.begin(), axes.end(), 0);\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::move(axes),\
std::forward<O>(options),\
functor_type());\
}\
template<class E, class BS, class I, std::size_t N, class O = DEFAULT_STRATEGY_REDUCERS>\
auto FNAME(E && e, BS && block_shape, const I (&axes)[N], O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
using axes_type = std::array<std::size_t, N>;\
auto ax = xt::forward_normalize<axes_type>(e, axes);\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::move(ax),\
std::forward<O>(options),\
functor_type());\
}
XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_l0, xt::detail::blockwise::norm_l0_functor)
XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_l1, xt::detail::blockwise::norm_l1_functor)
XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_l2, xt::detail::blockwise::norm_l2_functor)
XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_sq, xt::detail::blockwise::norm_sq_functor)
XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_linf, xt::detail::blockwise::norm_linf_functor)
#undef XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC
#define XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(FNAME, FUNCTOR)\
template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>)\
>\
auto FNAME(E && e, BS && block_shape, double p, X && axes, O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::forward<X>(axes),\
std::forward<O>(options),\
functor_type(p));\
}\
template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(xtl::is_integral<std::decay_t<X>>)\
>\
auto FNAME(E && e, BS && block_shape, double p, X axis, O options = O())\
{\
std::array<X,1> axes{axis};\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
axes,\
std::forward<O>(options),\
functor_type(p));\
}\
template<class E, class BS, class O = DEFAULT_STRATEGY_REDUCERS,\
XTL_REQUIRES(is_reducer_options<O>, xtl::negation<xtl::is_integral<std::decay_t<O>>>)\
>\
auto FNAME(E && e, BS && block_shape, double p, O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using axes_type = filter_fixed_shape_t<typename input_expression_type::shape_type>;\
axes_type axes = xtl::make_sequence<axes_type>(e.dimension());\
XTENSOR_ASSERT(axes.size() == e.dimension());\
std::iota(axes.begin(), axes.end(), 0);\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::move(axes),\
std::forward<O>(options),\
functor_type(p));\
}\
template<class E, class BS, class I, std::size_t N, class O = DEFAULT_STRATEGY_REDUCERS>\
auto FNAME(E && e, BS && block_shape, double p, const I (&axes)[N], O options = O())\
{\
using input_expression_type = std::decay_t<E>;\
using functor_type = FUNCTOR <typename input_expression_type::value_type>;\
using axes_type = std::array<std::size_t, N>;\
auto ax = xt::forward_normalize<axes_type>(e, axes);\
return blockwise_reducer(\
std::forward<E>(e), \
std::forward<BS>(block_shape), \
std::move(ax),\
std::forward<O>(options),\
functor_type(p));\
}
XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_lp_to_p, xt::detail::blockwise::norm_lp_to_p_functor);
XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_lp, xt::detail::blockwise::norm_lp_functor);
#undef XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC
}
}
#endif | 20,677 | 7,260 |
#include "Vulkan/Resources/TextureLoadingDescriptor.hpp"
USING_RUKEN_NAMESPACE
#pragma region Constructor
TextureLoadingDescriptor::TextureLoadingDescriptor(Renderer const& in_renderer, RkChar const* in_path) noexcept:
renderer {in_renderer},
path {in_path}
{
}
#pragma endregion | 308 | 100 |
// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int n;
long long x[100007], h[100007];
long long last=-1000000007;
int wyn;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
scanf("%d", &n);
for (int i=1; i<=n; i++)
{
scanf("%lld%lld", &x[i], &h[i]);
}
for (int i=1; i<n; i++)
{
if (x[i]-h[i]>last)
{
wyn++;
last=x[i];
continue;
}
if (x[i]+h[i]<x[i+1])
{
wyn++;
last=x[i]+h[i];
continue;
}
last=x[i];
}
wyn++;
printf("%d", wyn);
return 0;
} | 1,126 | 481 |
#include "catch.hpp"
#include "DQMOffline/Trigger/interface/EgHLTComCodes.h"
#include "DQMOffline/Trigger/interface/EgHLTEgCutCodes.h"
TEST_CASE("EgHLTComCodes", "[EgHLTComCodes]") {
egHLT::ComCodes codes;
constexpr unsigned int kFoo = 0b1;
constexpr unsigned int kBar = 0b10;
constexpr unsigned int kIsh = 0b100;
constexpr unsigned int kTar = 0b1000;
constexpr unsigned int kash = 0b10000;
codes.setCode("Foo",kFoo);
codes.setCode("Bar",kBar);
codes.setCode("Ish",kIsh);
codes.setCode("Tar",kTar);
codes.setCode("ash",kash);
codes.sort();
SECTION("Sorted") {
REQUIRE(codes.getCode("ash") == kash);
REQUIRE(codes.getCode("Bar") == kBar);
REQUIRE(codes.getCode("Foo") == kFoo);
REQUIRE(codes.getCode("Ish") == kIsh);
REQUIRE(codes.getCode("Tar") == kTar);
}
SECTION("Select multiple") {
REQUIRE(codes.getCode("ash:Ish") == (kash|kIsh));
REQUIRE(codes.getCode("Bar:Foo:Tar") == (kBar|kFoo|kTar));
REQUIRE(codes.getCode("Tar:Foo:Bar") == (kTar|kFoo|kBar));
}
SECTION("Missing") {
REQUIRE(codes.getCode("BAD") == 0);
REQUIRE(codes.getCode("Tar:BAD:Bar") == (kTar|kBar));
//no partial match
REQUIRE(codes.getCode("as") == 0);
REQUIRE(codes.getCode("ashton")==0);
}
}
TEST_CASE("EgHLTCutCodes", "[EgHLTCutCodes]") {
SECTION("get good codes") {
REQUIRE(egHLT::EgCutCodes::getCode("et") == egHLT::EgCutCodes::ET );
REQUIRE(egHLT::EgCutCodes::getCode("maxr9") == egHLT::EgCutCodes::MAXR9 );
}
}
| 1,505 | 693 |
#include "LruvCacheBase.hpp"
using namespace Blam::Data;
LruvCacheBase::LruvCacheBase()
: Unknown32(nullptr), Unknown36(nullptr), Unknown40(nullptr), Unknown44(nullptr), Allocator(nullptr)
{
}
| 196 | 82 |
// framebuffer.cc
// class implementation for Framebuffer
// Author: Christopher Morgan
// CSCI 480 Sp2004
#include "framebuffer.h"
#include "utility.h"
#include <iostream>
#include <fstream>
using namespace std;
#include <limits.h>
//constructor
//framebuffer must be created with width and height
Framebuffer::Framebuffer(int w, int h)
{
width = w;
height = h;
buffer = new int* [w];
colors = new RGBColor* [w];
zBuffer = new float* [w];
for(int k = 0; k < w; k++)
{
buffer[k] = new int[h];
colors[k] = new RGBColor[h];
zBuffer[k] = new float[h];
}
//set all pixels to black initially
RGBColor black(0,0,0);
for(int i = 0; i < w; i++)
for(int j = 0; j < h; j++)
{
buffer[i][j] = 0;
colors[i][j] = black;
zBuffer[i][j] = -1;
}
}
Framebuffer::~Framebuffer()
{
for(int i = 0; i < width; i++)
delete buffer[i];
delete [] buffer;
}
int Framebuffer::getWidth()
{
return width;
}
int Framebuffer::getHeight()
{
return height;
}
//fillPixel
//uses zBuffering to determine if pixel is on top
//if so, fills with color c
//otherwise, does nothing
void Framebuffer::fillPixel(int x, int y, float z, RGBColor c)
{
if(x < 0 || x > width)
return;
else if(y < 0 || y > height)
return;
else
{
if(z < zBuffer[x][y] || zBuffer[x][y] == -1)
{
colors[x][y] = c;
zBuffer[x][y] = z;
}
}
}
// writeOut
// write the framebuffer to a file <image.ppm>
void Framebuffer::writeOut()
{
ofstream outFile("image.ppm", ios::out);
// make sure the file opened
if(!outFile)
{
cout << "Error, could not create output file... aborting." << endl;
exit(-1);
}
// header information
outFile << "P6" << endl << width << " " << height << endl << "255" << endl;
char r, g, b;
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width; j++)
{
// get rgb values from colors array and
// cast to char for P6
r = (char)(colors[j][height - i - 1]).getR();
g = (char)(colors[j][height - i - 1]).getG();
b = (char)(colors[j][height - i - 1]).getB();
// write rgb to file
outFile << r;
outFile << g;
outFile << b;
}
}
}
| 2,188 | 862 |
#include "Shared.hpp"
#include <SFML/Window/Joystick.hpp>
namespace
{
enum Stick
{
Left = 0,
Right,
Pov
};
void getStickPosition(asIScriptGeneric* gen)
{
uint32_t id = gen->GetArgDWord(0);
Stick stick = Stick(gen->GetArgDWord(1));
switch (stick)
{
case Left:
new (gen->GetAddressOfReturnLocation()) sf::Vector2f(
sf::Joystick::getAxisPosition(id, sf::Joystick::X),
sf::Joystick::getAxisPosition(id, sf::Joystick::Y)
); break;
case Right:
new (gen->GetAddressOfReturnLocation()) sf::Vector2f(
sf::Joystick::getAxisPosition(id, sf::Joystick::R),
sf::Joystick::getAxisPosition(id, sf::Joystick::U)
); break;
case Pov:
new (gen->GetAddressOfReturnLocation()) sf::Vector2f(
sf::Joystick::getAxisPosition(id, sf::Joystick::PovX),
sf::Joystick::getAxisPosition(id, sf::Joystick::PovY)
); break;
}
}
}
void as::priv::RegJoystick(asIScriptEngine* eng)
{
AS_ASSERT(eng->SetDefaultNamespace("sf::Joystick"));
AS_ASSERT(eng->RegisterEnum("Axis"));
AS_ASSERT(eng->RegisterEnumValue ("Axis", "X", sf::Joystick::X));
AS_ASSERT(eng->RegisterEnumValue("Axis", "Y", sf::Joystick::Y));
AS_ASSERT(eng->RegisterEnumValue("Axis", "Z", sf::Joystick::Z));
AS_ASSERT(eng->RegisterEnumValue("Axis", "RX", sf::Joystick::R));
AS_ASSERT(eng->RegisterEnumValue("Axis", "RY", sf::Joystick::U));
AS_ASSERT(eng->RegisterEnumValue("Axis", "RZ", sf::Joystick::V));
AS_ASSERT(eng->RegisterEnumValue("Axis", "PovX", sf::Joystick::PovX));
AS_ASSERT(eng->RegisterEnumValue("Axis", "PovY", sf::Joystick::PovY));
AS_ASSERT(eng->RegisterEnum("Stick"));
AS_ASSERT(eng->RegisterEnumValue("Stick", "Left", 0));
AS_ASSERT(eng->RegisterEnumValue("Stick", "Right", 1));
AS_ASSERT(eng->RegisterEnumValue("Stick", "Pov", 2));
AS_ASSERT(eng->RegisterGlobalFunction("bool IsConnected(uint)", asFUNCTION(sf::Joystick::isConnected), asCALL_CDECL));
AS_ASSERT(eng->RegisterGlobalFunction("bool IsPressed(uint,uint)", asFUNCTION(sf::Joystick::isButtonPressed), asCALL_CDECL));
AS_ASSERT(eng->RegisterGlobalFunction("float AxisPosition(uint,Axis)", asFUNCTION(sf::Joystick::getAxisPosition), asCALL_CDECL));
AS_ASSERT(eng->RegisterGlobalFunction("Vec2 StickPosition(uint,Stick=Left)", asFUNCTION(getStickPosition), asCALL_GENERIC));
AS_ASSERT(eng->SetDefaultNamespace(""));
}
| 2,320 | 942 |
// Copyright (C) 2010-2016 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <vector>
#include <string>
#include <algorithm>
#include <memory>
#include <cstring>
#include <chromaprint.h>
#include "fingerprinter.h"
#include "fingerprint_compressor.h"
#include "fingerprint_decompressor.h"
#include "fingerprint_matcher.h"
#include "fingerprinter_configuration.h"
#include "utils/base64.h"
#include "simhash.h"
#include "debug.h"
using namespace chromaprint;
struct ChromaprintContextPrivate {
ChromaprintContextPrivate(int algorithm)
: algorithm(algorithm),
fingerprinter(CreateFingerprinterConfiguration(algorithm)) {}
int algorithm;
Fingerprinter fingerprinter;
FingerprintCompressor compressor;
std::string tmp_fingerprint;
};
struct ChromaprintMatcherContextPrivate {
int algorithm = -1;
std::unique_ptr<FingerprintMatcher> matcher;
std::vector<uint32_t> fp[2];
FingerprintDecompressor decompressor;
};
extern "C" {
#define FAIL_IF(x, msg) if (x) { DEBUG(msg); return 0; }
#define STR(x) #x
#define VERSION_STR(major, minor, patch) \
STR(major) "." STR(minor) "." STR(patch)
static const char *version_str = VERSION_STR(
CHROMAPRINT_VERSION_MAJOR,
CHROMAPRINT_VERSION_MINOR,
CHROMAPRINT_VERSION_PATCH);
const char *chromaprint_get_version(void)
{
return version_str;
}
ChromaprintContext *chromaprint_new(int algorithm)
{
return new ChromaprintContextPrivate(algorithm);
}
void chromaprint_free(ChromaprintContext *ctx)
{
if (ctx) {
delete ctx;
}
}
int chromaprint_set_option(ChromaprintContext *ctx, const char *name, int value)
{
FAIL_IF(!ctx, "context can't be NULL");
return ctx->fingerprinter.SetOption(name, value) ? 1 : 0;
}
int chromaprint_get_num_channels(ChromaprintContext *ctx)
{
return 1;
}
int chromaprint_get_sample_rate(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->sample_rate() : 0;
}
int chromaprint_get_item_duration(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->item_duration() : 0;
}
int chromaprint_get_item_duration_ms(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->item_duration_in_seconds() * 1000 : 0;
}
int chromaprint_get_delay(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->delay() : 0;
}
int chromaprint_get_delay_ms(ChromaprintContext *ctx)
{
return ctx ? ctx->fingerprinter.config()->delay_in_seconds() * 1000 : 0;
}
int chromaprint_start(ChromaprintContext *ctx, int sample_rate, int num_channels)
{
FAIL_IF(!ctx, "context can't be NULL");
return ctx->fingerprinter.Start(sample_rate, num_channels) ? 1 : 0;
}
int chromaprint_feed(ChromaprintContext *ctx, const int16_t *data, int length)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->fingerprinter.Consume(data, length);
return 1;
}
int chromaprint_finish(ChromaprintContext *ctx)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->fingerprinter.Finish();
return 1;
}
int chromaprint_get_fingerprint(ChromaprintContext *ctx, char **data)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->compressor.Compress(ctx->fingerprinter.GetFingerprint(), ctx->algorithm, ctx->tmp_fingerprint);
*data = (char *) malloc(GetBase64EncodedSize(ctx->tmp_fingerprint.size()) + 1);
FAIL_IF(!*data, "can't allocate memory for the result");
Base64Encode(ctx->tmp_fingerprint.begin(), ctx->tmp_fingerprint.end(), *data, true);
return 1;
}
int chromaprint_get_raw_fingerprint(ChromaprintContext *ctx, uint32_t **data, int *size)
{
FAIL_IF(!ctx, "context can't be NULL");
const auto fingerprint = ctx->fingerprinter.GetFingerprint();
*data = (uint32_t *) malloc(sizeof(uint32_t) * fingerprint.size());
FAIL_IF(!*data, "can't allocate memory for the result");
*size = fingerprint.size();
std::copy(fingerprint.begin(), fingerprint.end(), *data);
return 1;
}
int chromaprint_get_raw_fingerprint_size(ChromaprintContext *ctx, int *size)
{
FAIL_IF(!ctx, "context can't be NULL");
const auto fingerprint = ctx->fingerprinter.GetFingerprint();
*size = fingerprint.size();
return 1;
}
int chromaprint_get_fingerprint_hash(ChromaprintContext *ctx, uint32_t *hash)
{
FAIL_IF(!ctx, "context can't be NULL");
*hash = SimHash(ctx->fingerprinter.GetFingerprint());
return 1;
}
int chromaprint_clear_fingerprint(ChromaprintContext *ctx)
{
FAIL_IF(!ctx, "context can't be NULL");
ctx->fingerprinter.ClearFingerprint();
return 1;
}
int chromaprint_encode_fingerprint(const uint32_t *fp, int size, int algorithm, char **encoded_fp, int *encoded_size, int base64)
{
std::vector<uint32_t> uncompressed(fp, fp + size);
std::string encoded = CompressFingerprint(uncompressed, algorithm);
if (base64) {
encoded = Base64Encode(encoded);
}
*encoded_fp = (char *) malloc(encoded.size() + 1);
*encoded_size = encoded.size();
std::copy(encoded.data(), encoded.data() + encoded.size() + 1, *encoded_fp);
return 1;
}
int chromaprint_decode_fingerprint(const char *encoded_fp, int encoded_size, uint32_t **fp, int *size, int *algorithm, int base64)
{
std::string encoded(encoded_fp, encoded_size);
if (base64) {
encoded = Base64Decode(encoded);
}
std::vector<uint32_t> uncompressed = DecompressFingerprint(encoded, algorithm);
*fp = (uint32_t *) malloc(sizeof(uint32_t) * uncompressed.size());
*size = uncompressed.size();
std::copy(uncompressed.begin(), uncompressed.end(), *fp);
return 1;
}
int chromaprint_hash_fingerprint(const uint32_t *fp, int size, uint32_t *hash)
{
if (fp == NULL || size < 0 || hash == NULL) {
return 0;
}
*hash = SimHash(fp, size);
return 1;
}
void chromaprint_dealloc(void *ptr)
{
free(ptr);
}
}; // extern "C"
| 5,628 | 2,222 |
#include "ldapr.h"
//' Validate an LDAP URL.
//'
//' This is a fairly simple version of validation, simply checking whether the URL string starts with \code{ldap://}
//' @keywords internal
//' @param ldap_uri The URI you wish to validate
//'
//' @export
// [[Rcpp::export]]
int ldapr_is_ldap_url(
SEXP ldap_uri
){
int result;
const char *l = Rcpp::as<const char *>(ldap_uri);
// check the URL
result = ldap_is_ldap_url(l);
if(result == 0){
stop("Invalid LDAP URI");
}
// return the result
return result;
}
| 533 | 204 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ssm-contacts/model/ListContactChannelsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::SSMContacts::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListContactChannelsResult::ListContactChannelsResult()
{
}
ListContactChannelsResult::ListContactChannelsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListContactChannelsResult& ListContactChannelsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("NextToken"))
{
m_nextToken = jsonValue.GetString("NextToken");
}
if(jsonValue.ValueExists("ContactChannels"))
{
Array<JsonView> contactChannelsJsonList = jsonValue.GetArray("ContactChannels");
for(unsigned contactChannelsIndex = 0; contactChannelsIndex < contactChannelsJsonList.GetLength(); ++contactChannelsIndex)
{
m_contactChannels.push_back(contactChannelsJsonList[contactChannelsIndex].AsObject());
}
}
return *this;
}
| 1,365 | 445 |
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "common/expression/VertexExpression.h"
#include "common/expression/ExprVisitor.h"
namespace nebula {
const Value &VertexExpression::eval(ExpressionContext &ctx) {
result_ = ctx.getVertex();
return result_;
}
void VertexExpression::accept(ExprVisitor *visitor) { visitor->visit(this); }
} // namespace nebula
| 527 | 169 |
/* @@@LICENSE
*
* Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P.
*
* 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.
*
* LICENSE@@@ */
#include "Common.h"
#include <glib.h>
#include <QGraphicsSceneMouseEvent>
#include <QStateMachine>
#include <QState>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeContext>
#include "DashboardWindowManager.h"
#include "AlertWindow.h"
#include "BannerWindow.h"
#include "DashboardWindow.h"
#include "DashboardWindowContainer.h"
#include "DashboardWindowManagerStates.h"
#include "CoreNaviManager.h"
#include "DisplayManager.h"
#include "GraphicsItemContainer.h"
#include "HostBase.h"
#include "Logging.h"
#include "NewContentIndicatorEvent.h"
#include "NotificationPolicy.h"
#include "PersistentWindowCache.h"
#include "Settings.h"
#include "SystemUiController.h"
#include "Time.h"
#include "WebAppMgrProxy.h"
#include "Window.h"
#include "WindowServer.h"
#include "WindowServerLuna.h"
#include "Preferences.h"
#include "Utils.h"
#include "FlickGesture.h"
#include "DockModeWindowManager.h"
#include <QGraphicsPixmapItem>
static const int kTabletAlertWindowPadding = 5;
static const int kTabletNotificationContentWidth = 320;
DashboardWindowManager::DashboardWindowManager(int maxWidth, int maxHeight)
: WindowManagerBase(maxWidth, maxHeight)
,m_stateMachine(0)
,m_stateDashboardOpen(0)
,m_stateAlertOpen(0)
,m_stateClosed(0)
,m_stateCurrent(0)
,m_bannerWin(0)
,m_bgItem(0)
,m_alertWinContainer(0)
,m_transientContainer(0)
,m_dashboardWinContainer(0)
,m_dashboardRightOffset(0)
,m_qmlNotifMenu(0)
,m_menuObject(0)
,m_notifMenuRightEdgeOffset(0)
,m_activeTransientAlert(0)
{
setObjectName("DashboardWindowManager");
m_notificationPolicy = new NotificationPolicy();
m_bannerHasContent = false;
m_AlertWindowFadeOption = Invalid;
m_deleteWinAfterAnimation = NULL;
m_deleteTransientWinAfterAnimation = false;
m_previousActiveAlertWindow = NULL;
m_inDockModeAnimation = false;
// grab all gestures handled by the scenes viewport widget so
// we can prevent them from being propogated to items below the dashboard
grabGesture(Qt::TapGesture);
grabGesture(Qt::TapAndHoldGesture);
grabGesture(Qt::PinchGesture);
grabGesture((Qt::GestureType) SysMgrGestureFlick);
grabGesture((Qt::GestureType) SysMgrGestureSingleClick);
SystemUiController* suc = SystemUiController::instance();
m_isOverlay = !suc->dashboardOwnsNegativeSpace();
// Connect to this signal only if we own the negative space.
if(!m_isOverlay) {
connect(suc, SIGNAL(signalNegativeSpaceChanged(const QRect&)),
this, SLOT(slotNegativeSpaceChanged(const QRect&)));
connect(suc, SIGNAL(signalNegativeSpaceChangeFinished(const QRect&)),
this, SLOT(slotNegativeSpaceChangeFinished(const QRect&)));
}
else {
connect(suc, SIGNAL(signalPositiveSpaceChanged(const QRect&)),
this, SLOT(slotPositiveSpaceChanged(const QRect&)));
connect(suc, SIGNAL(signalPositiveSpaceChangeFinished(const QRect&)),
this, SLOT(slotPositiveSpaceChangeFinished(const QRect&)));
setFlag(QGraphicsItem::ItemHasNoContents, true);
}
connect(SystemUiController::instance(), SIGNAL(signalCloseDashboard(bool)),
this, SLOT(slotCloseDashboard(bool)));
connect(SystemUiController::instance(), SIGNAL(signalOpenDashboard()),
this, SLOT(slotOpenDashboard()));
connect(SystemUiController::instance(), SIGNAL(signalCloseAlert()),
this, SLOT(slotCloseAlert()));
}
DashboardWindowManager::~DashboardWindowManager()
{
}
void DashboardWindowManager::init()
{
int width = boundingRect().toRect().width();
int height = boundingRect().toRect().height();
if(m_isOverlay) {
QDeclarativeEngine* qmlEngine = WindowServer::instance()->declarativeEngine();
if(qmlEngine) {
QDeclarativeContext* context = qmlEngine->rootContext();
m_dashboardWinContainer = new DashboardWindowContainer(this, kTabletNotificationContentWidth, 0);
if(context) {
context->setContextProperty("DashboardContainer", m_dashboardWinContainer);
}
Settings* settings = Settings::LunaSettings();
std::string systemMenuQmlPath = settings->lunaQmlUiComponentsPath + "DashboardMenu/DashboardMenu.qml";
QUrl url = QUrl::fromLocalFile(systemMenuQmlPath.c_str());
m_qmlNotifMenu = new QDeclarativeComponent(qmlEngine, url, this);
if(m_qmlNotifMenu) {
m_menuObject = qobject_cast<QGraphicsObject *>(m_qmlNotifMenu->create());
if(m_menuObject) {
m_menuObject->setParentItem(this);
m_notifMenuRightEdgeOffset = m_menuObject->property("edgeOffset").toInt();
QMetaObject::invokeMethod(m_menuObject, "setMaximumHeight", Q_ARG(QVariant, m_dashboardWinContainer->getMaximumHeightForMenu()));
}
}
}
}
if(!m_isOverlay)
{
m_dashboardWinContainer = new DashboardWindowContainer(this, width, height);
m_alertWinContainer = new GraphicsItemContainer(width, height, GraphicsItemContainer::SolidRectBackground);
}
else {
m_alertWinContainer = new GraphicsItemContainer(kTabletNotificationContentWidth, 0, GraphicsItemContainer::PopupBackground);
m_alertWinContainer->setBlockGesturesAndMouse(true);
m_alertWinContainer->setAcceptTouchEvents(true);
}
m_transientContainer = new GraphicsItemContainer(kTabletNotificationContentWidth, 0, GraphicsItemContainer::TransientAlertBackground);
m_transientContainer->setBlockGesturesAndMouse(true);
m_transientContainer->setOpacity(0.0);
m_transientContainer->setVisible(true);
m_transientContainer->setAcceptTouchEvents(true);
m_transAlertAnimation.setTargetObject(m_transientContainer);
m_transAlertAnimation.setPropertyName("opacity");
// Connect the signal to process events after animation is complete
connect(&m_transAlertAnimation, SIGNAL(finished()), SLOT(slotTransientAnimationFinished()));
connect(m_dashboardWinContainer, SIGNAL(signalWindowAdded(DashboardWindow*)),
SLOT(slotDashboardWindowAdded(DashboardWindow*)));
connect(m_dashboardWinContainer, SIGNAL(signalWindowsRemoved(DashboardWindow*)),
SLOT(slotDashboardWindowsRemoved(DashboardWindow*)));
connect(m_dashboardWinContainer, SIGNAL(signalViewportHeightChanged()),
SLOT(slotDashboardViewportHeightChanged()));
connect(SystemUiController::instance()->statusBar(), SIGNAL(signalDashboardAreaRightEdgeOffset(int)),
this, SLOT(slotDashboardAreaRightEdgeOffset(int)));
m_bannerWin = new BannerWindow(this, width, Settings::LunaSettings()->positiveSpaceTopPadding);
m_bgItem = new GraphicsItemContainer(width, height, m_isOverlay ? GraphicsItemContainer::NoBackground : GraphicsItemContainer::SolidRectBackground);
if(!m_isOverlay) {
m_dashboardWinContainer->setParentItem(this);
}
// Listen for dock mode
DockModeWindowManager* dmwm = 0;
dmwm = ((DockModeWindowManager*)((WindowServerLuna*)WindowServer::instance())->dockModeManager());
// Listen for dock mode animation to ignore dashboard open / close requests
connect ((WindowServerLuna*)WindowServer::instance(), SIGNAL (signalDockModeAnimationStarted()),
this, SLOT(slotDockModeAnimationStarted()));
connect ((WindowServerLuna*)WindowServer::instance(), SIGNAL (signalDockModeAnimationComplete()),
this, SLOT(slotDockModeAnimationComplete()));
m_alertWinContainer->setParentItem(this);
m_bgItem->setParentItem(this);
m_bannerWin->setParentItem(m_bgItem);
if(m_isOverlay) {
m_transientContainer->setParentItem(this);
// Set the pos of the Alert Containers correctly.
positionAlertWindowContainer();
positionTransientWindowContainer();
if (m_menuObject) {
int uiHeight = SystemUiController::instance()->currentUiHeight();
// temporary location just until the status bar tell us where to place the dashboard container
m_menuObject->setPos(0, -uiHeight/2 + Settings::LunaSettings()->positiveSpaceTopPadding);
}
// Connect the signal to process events after animation is complete
connect(&m_fadeInOutAnimation, SIGNAL(finished()), SLOT(slotDeleteAnimationFinished()));
}
else {
setPosTopLeft(m_alertWinContainer, 0, 0);
m_alertWinContainer->setBrush(Qt::black);
m_bgItem->setBrush(Qt::black);
}
setPosTopLeft(m_bgItem, 0, 0);
setPosTopLeft(m_bannerWin, 0, 0);
setupStateMachine();
}
void DashboardWindowManager::setupStateMachine()
{
m_stateMachine = new QStateMachine(this);
m_stateDashboardOpen = new DWMStateOpen(this);
m_stateAlertOpen = new DWMStateAlertOpen(this);
m_stateClosed = new DWMStateClosed(this);
m_stateMachine->addState(m_stateDashboardOpen);
m_stateMachine->addState(m_stateAlertOpen);
m_stateMachine->addState(m_stateClosed);
// ------------------------------------------------------------------------------
m_stateDashboardOpen->addTransition(this, SIGNAL(signalActiveAlertWindowChanged()), m_stateClosed);
m_stateAlertOpen->addTransition(this, SIGNAL(signalActiveAlertWindowChanged()), m_stateClosed);
m_stateDashboardOpen->addTransition(m_dashboardWinContainer, SIGNAL(signalEmpty()), m_stateClosed);
m_stateClosed->addTransition(new DWMTransitionClosedToAlertOpen(this, m_stateAlertOpen, this, SIGNAL(signalActiveAlertWindowChanged())));
m_stateClosed->addTransition(this, SIGNAL(signalOpen()), m_stateDashboardOpen);
m_stateClosed->addTransition(new DWMTransitionClosedToAlertOpen(this, m_stateAlertOpen, m_stateClosed, SIGNAL(signalNegativeSpaceAnimationFinished())));
m_stateDashboardOpen->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed);
m_stateAlertOpen->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed);
m_stateClosed->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed);
// ------------------------------------------------------------------------------
m_stateMachine->setInitialState(m_stateClosed);
m_stateMachine->start();
}
int DashboardWindowManager::sTabletUiWidth()
{
return kTabletNotificationContentWidth;
}
int DashboardWindowManager::bannerWindowHeight()
{
return m_bannerWin->boundingRect().height();
}
bool DashboardWindowManager::canCloseDashboard() const
{
return m_stateCurrent == m_stateDashboardOpen;
}
bool DashboardWindowManager::dashboardOpen() const
{
return m_stateCurrent == m_stateDashboardOpen;
}
bool DashboardWindowManager::hasDashboardContent() const
{
return m_bannerHasContent || !m_dashboardWinContainer->empty();
}
void DashboardWindowManager::openDashboard()
{
if (m_inDockModeAnimation)
return;
if(!SystemUiController::instance()->statusBarAndNotificationAreaShown())
return;
if (!m_alertWinArray.empty() || m_dashboardWinContainer->empty()) {
return ;
}
Q_EMIT signalOpen();
}
void DashboardWindowManager::slotPositiveSpaceChanged(const QRect& r)
{
positionAlertWindowContainer(r);
positionTransientWindowContainer(r);
positionDashboardContainer(r);
}
void DashboardWindowManager::slotPositiveSpaceChangeFinished(const QRect& r)
{
positionAlertWindowContainer(r);
positionTransientWindowContainer(r);
positionDashboardContainer(r);
}
void DashboardWindowManager::slotNegativeSpaceChanged(const QRect& r)
{
negativeSpaceChanged(r);
}
void DashboardWindowManager::negativeSpaceChanged(const QRect& r)
{
setPos(0, r.y());
update();
}
void DashboardWindowManager::slotNegativeSpaceChangeFinished(const QRect& r)
{
if (G_UNLIKELY(m_stateCurrent == 0)) {
g_critical("m_stateCurrent is null");
return;
}
m_stateCurrent->negativeSpaceAnimationFinished();
}
void DashboardWindowManager::slotOpenDashboard()
{
openDashboard();
}
void DashboardWindowManager::slotCloseDashboard(bool forceClose)
{
if (!forceClose && !m_stateCurrent->allowsSoftClose())
return;
Q_EMIT signalClose(forceClose);
}
void DashboardWindowManager::slotCloseAlert()
{
AlertWindow* win = topAlertWindow();
if(!win)
return;
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
win->close();
}
void DashboardWindowManager::slotDashboardAreaRightEdgeOffset(int offset)
{
if (m_menuObject) {
m_dashboardRightOffset = offset;
m_menuObject->setX((boundingRect().width()/2) - m_dashboardRightOffset - m_menuObject->boundingRect().width() + m_notifMenuRightEdgeOffset);
}
}
void DashboardWindowManager::slotDeleteAnimationFinished()
{
switch(m_AlertWindowFadeOption) {
case FadeInAndOut:
case FadeOutOnly:
// Reset the dimensions and position of the dashboardwindow container to the orignal one.
m_alertWinContainer->resize(kTabletNotificationContentWidth, 0);
positionAlertWindowContainer();
if(m_previousActiveAlertWindow) {
m_previousActiveAlertWindow->setParent(NULL);
m_previousActiveAlertWindow->setVisible(false);
m_previousActiveAlertWindow = NULL;
}
if(m_deleteWinAfterAnimation) {
delete m_deleteWinAfterAnimation;
m_deleteWinAfterAnimation = NULL;
}
if(FadeOutOnly == m_AlertWindowFadeOption) {
// Change the state to closed.
Q_EMIT signalActiveAlertWindowChanged();
}
else if(topAlertWindow()) {
// we need to fade in the new alert window
m_AlertWindowFadeOption = FadeInOnly;
resizeAlertWindowContainer(topAlertWindow(), true);
animateAlertWindow();
notifyActiveAlertWindowActivated (topAlertWindow());
} else {
m_AlertWindowFadeOption = Invalid;
}
m_AlertWindowFadeOption = Invalid;
break;
default:
m_AlertWindowFadeOption = Invalid;
break;
}
}
void DashboardWindowManager::slotTransientAnimationFinished()
{
if(m_deleteTransientWinAfterAnimation) {
if(m_activeTransientAlert) {
delete m_activeTransientAlert;
m_activeTransientAlert = NULL;
}
m_deleteTransientWinAfterAnimation = false;
}
if(m_transientContainer->opacity() == 0.0)
m_transientContainer->setVisible(false);
}
void DashboardWindowManager::setBannerHasContent(bool val)
{
m_bannerHasContent = val;
if (val || !m_dashboardWinContainer->empty()) {
SystemUiController::instance()->setDashboardHasContent(true);
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentAdded();
}
else {
SystemUiController::instance()->setDashboardHasContent(false);
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentRemoved();
}
update();
}
void DashboardWindowManager::focusWindow(Window* w)
{
// we listen to focus and blur only for alert windows
if (!(w->type() == Window::Type_PopupAlert ||
w->type() == Window::Type_BannerAlert))
return;
AlertWindow* win = static_cast<AlertWindow*>(w);
// And only for persistable windows
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!persistCache->shouldPersistWindow(win))
return;
addAlertWindow(win);
}
void DashboardWindowManager::unfocusWindow(Window* w)
{
// we listen to focus and blur only for alert windows
if (w->type() != Window::Type_PopupAlert &&
w->type() != Window::Type_BannerAlert)
return;
AlertWindow* win = static_cast<AlertWindow*>(w);
// Is this window in our current list of windows? If no,
// nothing to do
if (!m_alertWinArray.contains(win))
return;
// Look only for persistable windows
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!persistCache->shouldPersistWindow(win))
return;
// Add to persistent cache if not already in there
if (!persistCache->hasWindow(win))
persistCache->addWindow(win);
hideOrCloseAlertWindow(win);
}
void DashboardWindowManager::animateAlertWindow()
{
// We are running on a tablet and we need to fade the AlertWindows in or out. There are two cases:
// 1: If there are no more alert windows, just animate this one out and be done with it.
// 2: If we have other alert windows, activate them.
// Stop the existing animation
m_fadeInOutAnimation.stop();
m_fadeInOutAnimation.clear();
AlertWindow* w = NULL;
qreal endValue = 0.0;
// Set the opacity of the window to 0;
switch(m_AlertWindowFadeOption) {
case FadeInOnly:
w = topAlertWindow();
m_alertWinContainer->setOpacity(0.0);
w->show();
w->activate();
endValue = 1.0;
break;
case FadeInAndOut:
case FadeOutOnly:
if(m_previousActiveAlertWindow) {
w = m_previousActiveAlertWindow;
}
else {
w = m_deleteWinAfterAnimation;
}
endValue = 0.0;
break;
default:
return;
}
// Start the animation
QPropertyAnimation* a = new QPropertyAnimation(m_alertWinContainer, "opacity");
a->setEndValue(endValue);
// TODO - CHANGE DURATION TO READ FROM ANIMATIONSETTINGS.H
a->setDuration(400);
a->setEasingCurve(QEasingCurve::Linear);
m_fadeInOutAnimation.addAnimation(a);
m_fadeInOutAnimation.start();
}
void DashboardWindowManager::animateTransientAlertWindow(bool in)
{
// Stop the existing animation
m_transAlertAnimation.stop();
if(!m_activeTransientAlert)
return;
qreal endValue = 0.0;
if(in) {
m_transientContainer->setVisible(true);
m_activeTransientAlert->show();
m_activeTransientAlert->activate();
endValue = 1.0;
} else {
endValue = 0.0;
}
// Start the animation
m_transAlertAnimation.setStartValue(m_transientContainer->opacity());
m_transAlertAnimation.setEndValue(endValue);
m_transAlertAnimation.setDuration(400);
m_transAlertAnimation.setEasingCurve(QEasingCurve::Linear);
m_transAlertAnimation.start();
}
void DashboardWindowManager::hideOrCloseAlertWindow(AlertWindow* win)
{
bool isActiveAlert = false;
if (!m_alertWinArray.empty() && (m_alertWinArray[0] == win))
isActiveAlert = true;
int removeIndex = m_alertWinArray.indexOf(win);
if (removeIndex != -1)
m_alertWinArray.remove(removeIndex);
// Is this a window that we want to persist?
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!persistCache->shouldPersistWindow(win)) {
if (isActiveAlert) {
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
}
// No. Close it
win->close();
return;
}
if (!persistCache->hasWindow(win))
persistCache->addWindow(win);
persistCache->hideWindow(win);
if (isActiveAlert) {
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
Q_EMIT signalActiveAlertWindowChanged();
}
}
void DashboardWindowManager::resizeAlertWindowContainer(AlertWindow* w, bool repositionWindow)
{
if(!w)
return;
// This should not be executed if we are running on a phone.
if(!isOverlay())
return;
bool wasResized = false;
QRectF bRect = m_alertWinContainer->boundingRect();
if(w->initialHeight() != bRect.height() || w->initialWidth() != bRect.width()) {
m_alertWinContainer->resize(w->initialWidth(), w->initialHeight());
positionAlertWindowContainer();
wasResized = true;
}
if(true == repositionWindow) {
if(true == wasResized) {
w->setPos(0,0);
}
}
}
void DashboardWindowManager::addAlertWindow(AlertWindow* win)
{
if(win->isTransientAlert()) {
// transient alerts are handled separately
addTransientAlertWindow(win);
return;
}
// This window may have already been added because a persistent
// window called focus before the corresponding webapp was ready
if (m_alertWinArray.contains(win))
return;
bool reSignalOpenAlert = false;
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (persistCache->shouldPersistWindow(win)) {
if (!persistCache->hasWindow(win)) {
persistCache->addWindow(win);
}
}
AlertWindow* oldActiveWindow = 0;
if (!m_alertWinArray.empty())
oldActiveWindow = m_alertWinArray[0];
addAlertWindowBasedOnPriority(win);
// Set the flags depending on whether we are running on phone/tablet.
if(isOverlay()) {
if(Invalid == m_AlertWindowFadeOption) {
m_AlertWindowFadeOption = FadeInOnly;
}
// resize the alertwindowcontainer if there are no other active alert windows.
if(m_stateCurrent != m_stateAlertOpen) {
resizeAlertWindowContainer(win, false);
}
}
if(!isOverlay()) {
if(win->boundingRect().width() != SystemUiController::instance()->currentUiWidth())
{
win->resizeEventSync(SystemUiController::instance()->currentUiWidth(), win->initialHeight());
setPosTopLeft(win, 0, 0);
}
}
else {
win->setPos(0,0);
}
if (!win->parentItem()) {
win->setParentItem(m_alertWinContainer);
if(!m_isOverlay)
setPosTopLeft(win, 0, 0);
else
win->setPos(0,0);
// Initially set the visibility to false
win->setVisible(false);
}
AlertWindow* newActiveWindow = m_alertWinArray[0];
if (oldActiveWindow && (oldActiveWindow == newActiveWindow)) {
// Adding the new window did not displace the current active window.
// Nothing to do further
return;
}
if (oldActiveWindow) {
reSignalOpenAlert = true;
m_previousActiveAlertWindow = oldActiveWindow;
// Displaced the current active window. Need to hide it
if (persistCache->shouldPersistWindow(oldActiveWindow)) {
if (!persistCache->hasWindow(oldActiveWindow))
persistCache->addWindow(oldActiveWindow);
persistCache->hideWindow(oldActiveWindow);
}
else {
oldActiveWindow->deactivate();
}
// Set that we need to fade the existing window out and the new window in.
m_AlertWindowFadeOption = FadeInAndOut;
} else if(FadeOutOnly == m_AlertWindowFadeOption) {
// currently in the process of closing the dashboard (last alert just got deactivated before the new window was added),
// so mark the fade option as Fade Ina dn Out to bring it back with the new alert window
m_AlertWindowFadeOption = FadeInAndOut;
return;
}
if(!isOverlay()) {
Q_EMIT signalActiveAlertWindowChanged();
}
else {
// Check if we need to resignal to show the latest alert.
if(false == reSignalOpenAlert) {
// Dashboard was open. The first signal will close the dashbaord. Resignal to open the alert
if(m_stateCurrent == m_stateDashboardOpen)
reSignalOpenAlert = true;
}
// Signal once to move the state to closed
Q_EMIT signalActiveAlertWindowChanged();
// signal again to move the state to display the active alert window
if(true == reSignalOpenAlert) {
Q_EMIT signalActiveAlertWindowChanged();
}
}
}
void DashboardWindowManager::addTransientAlertWindow(AlertWindow* win)
{
if (m_activeTransientAlert == win)
return;
if(m_activeTransientAlert) {
// only one transient alert is allowed at any given time, so close the current one
m_activeTransientAlert->deactivate();
m_deleteTransientWinAfterAnimation = NULL;
m_transAlertAnimation.stop();
notifyTransientAlertWindowDeactivated(m_activeTransientAlert);
delete m_activeTransientAlert;
m_activeTransientAlert = 0;
}
m_activeTransientAlert = win;
win->setParentItem(m_transientContainer);
win->setVisible(true);
win->setOpacity(1.0);
win->setPos(0,0);
win->resizeEventSync(win->initialWidth(), win->initialHeight());
// resize the transient alert window container if there are no other active alert windows.
QRectF bRect = m_transientContainer->boundingRect();
if(win->initialHeight() != bRect.height() || win->initialWidth() != bRect.width()) {
m_transientContainer->resize(win->initialWidth(), win->initialHeight());
}
positionTransientWindowContainer();
notifyTransientAlertWindowActivated(m_activeTransientAlert);
animateTransientAlertWindow(true);
}
void DashboardWindowManager::removeAlertWindow(AlertWindow* win)
{
if(win->isTransientAlert()) {
// transient alerts are handled separately
removeTransientAlertWindow(win);
return;
}
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!m_alertWinArray.contains(win)) {
// This can happen in two cases:
// * a window was stuffed int the persistent window cache on hiding
// * a window was closed before being added to the window manager
if (persistCache->hasWindow(win)) {
persistCache->removeWindow(win);
}
delete win;
return;
}
if (persistCache->hasWindow(win))
persistCache->removeWindow(win);
bool isActiveAlert = false;
if (!m_alertWinArray.empty() && (m_alertWinArray[0] == win))
isActiveAlert = true;
int removeIndex = m_alertWinArray.indexOf(win);
if (removeIndex != -1) {
m_alertWinArray.remove(removeIndex);
}
if (isActiveAlert) {
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
}
// If we are running on the phone, just signal the state to enter closed.
if(!isOverlay()) {
delete win;
if(isActiveAlert) {
Q_EMIT signalActiveAlertWindowChanged();
}
}
else {
m_deleteWinAfterAnimation = win;
if (isActiveAlert) {
// Change the state if there are more alert windows in the system
if(!m_alertWinArray.empty()) {
// This will cause the state to enter stateClosed.
Q_EMIT signalActiveAlertWindowChanged();
// If we are running on a tablet and if this flag is set to true, signal that we need to display the next alert
if (G_UNLIKELY(m_stateCurrent == 0)) {
g_critical("m_stateCurrent is null");
return;
}
// Set that we need to fade the existing window out and the new window in.
m_AlertWindowFadeOption = FadeInAndOut;
// Signal that we need to bring the next active window in
m_stateCurrent->negativeSpaceAnimationFinished();
}
else {
m_AlertWindowFadeOption = FadeOutOnly;
animateAlertWindow();
}
}
}
}
void DashboardWindowManager::removeTransientAlertWindow(AlertWindow* win)
{
if (m_activeTransientAlert != win) {
delete win;
return;
}
win->deactivate();
notifyTransientAlertWindowDeactivated(win);
m_deleteTransientWinAfterAnimation = true;
animateTransientAlertWindow(false);
}
void DashboardWindowManager::addAlertWindowBasedOnPriority(AlertWindow* win)
{
if (m_alertWinArray.empty()) {
m_alertWinArray.append(win);
return;
}
AlertWindow* activeAlertWin = m_alertWinArray[0];
// Add the window to the list of alert windows, sorted by priority
int newWinPriority = m_notificationPolicy->popupAlertPriority(win->appId(), win->name());
if (newWinPriority == m_notificationPolicy->defaultPriority()) {
// optimization. if we are at default priority we don't need to walk the list
// we will just queue up this window
int oldSize = m_alertWinArray.size();
m_alertWinArray.append(win);
}
else if (newWinPriority < m_notificationPolicy->popupAlertPriority(activeAlertWin->appId(),
activeAlertWin->name())) {
// if the priority of new window is higher than the currently shown window, then we push
// both the windows in the queue with the new window in front
QVector<AlertWindow*>::iterator it = qFind(m_alertWinArray.begin(), m_alertWinArray.end(), activeAlertWin);
Q_ASSERT(it != m_alertWinArray.end());
m_alertWinArray.insert(it, win);
}
else {
bool added = false;
QMutableVectorIterator<AlertWindow*> it(m_alertWinArray);
while (it.hasNext()) {
AlertWindow* a = it.next();
if (newWinPriority < m_notificationPolicy->popupAlertPriority(a->appId(), a->name())) {
it.insert(win);
added = true;
break;
}
}
if (!added)
m_alertWinArray.append(win);
}
}
void DashboardWindowManager::addWindow(Window* win)
{
if (win->type() == Window::Type_PopupAlert || win->type() == Window::Type_BannerAlert)
addAlertWindow(static_cast<AlertWindow*>(win));
else if (win->type() == Window::Type_Dashboard)
m_dashboardWinContainer->addWindow(static_cast<DashboardWindow*>(win));
}
void DashboardWindowManager::removeWindow(Window* win)
{
if (win->type() == Window::Type_PopupAlert || win->type() == Window::Type_BannerAlert)
removeAlertWindow(static_cast<AlertWindow*>(win));
else if (win->type() == Window::Type_Dashboard)
m_dashboardWinContainer->removeWindow(static_cast<DashboardWindow*>(win));
/* if dashboard is empty, all throb requests should have been dismissed
* this is defensive coding to ensure that all requests are cleared
*/
if (m_dashboardWinContainer->empty() && m_alertWinArray.empty())
CoreNaviManager::instance()->clearAllStandbyRequests();
}
int DashboardWindowManager::activeAlertWindowHeight()
{
const Window* alert = getActiveAlertWin();
if(!alertOpen() || !alert) {
if(!isOverlay())
return Settings::LunaSettings()->positiveSpaceBottomPadding;
else
return 0;
}
return alert->boundingRect().height();
}
bool DashboardWindowManager::doesMousePressFallInBannerWindow(QGraphicsSceneMouseEvent* event)
{
QPointF pos = mapToItem(m_bannerWin, event->pos());
if(m_bannerWin->boundingRect().contains(pos)) {
return true;
}
else {
return false;
}
}
/*
BannerWindow is invisible when the DashboardWinContainer is up. So if the user clicks in the BannerWindow area, it will not get any notifications.
So, we need to have this workaround in DashboardWinMgr::mousePressEvent that will detect if the user clicked on BannerWindow area and prevent it
from launching the dashboard again as a part of Qt::GestureComplete
*/
void DashboardWindowManager::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if(!m_isOverlay) {
event->accept();
}
else {
// if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container.
if(true == dashboardOpen()) {
event->accept();
} else {
event->ignore();
}
}
}
void DashboardWindowManager::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if(!m_isOverlay) {
event->accept();
}
else {
// if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container.
if(true == dashboardOpen()) {
event->accept();
} else {
event->ignore();
}
}
}
void DashboardWindowManager::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if(!m_isOverlay) {
event->accept();
}
else {
// if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container.
if(true == dashboardOpen()) {
hideDashboardWindow();
event->accept();
if(true == doesMousePressFallInBannerWindow(event)) {
m_bannerWin->resetIgnoreGestureUpEvent();
}
m_dashboardWinContainer->resetLocalState();
} else {
event->ignore();
}
}
}
bool DashboardWindowManager::sceneEvent(QEvent* event)
{
switch (event->type()) {
case QEvent::GestureOverride: {
QGestureEvent* ge = static_cast<QGestureEvent*>(event);
QList<QGesture*> activeGestures = ge->activeGestures();
Q_FOREACH(QGesture* g, activeGestures) {
if (g->hasHotSpot()) {
QPointF pt = ge->mapToGraphicsScene(g->hotSpot());
if (dashboardOpen()) {
ge->accept(g);
}
else {
ge->ignore(g);
}
}
}
break;
}
default:
break;
}
return WindowManagerBase::sceneEvent(event);
}
void DashboardWindowManager::raiseAlertWindow(AlertWindow* window)
{
g_message("%s", __PRETTY_FUNCTION__);
m_alertWinContainer->show();
m_alertWinContainer->raiseChild(window);
m_bgItem->hide();
if(!m_isOverlay)
m_dashboardWinContainer->hide();
}
void DashboardWindowManager::raiseDashboardWindowContainer()
{
g_message("%s", __PRETTY_FUNCTION__);
if(!m_isOverlay)
m_dashboardWinContainer->show();
m_alertWinContainer->hide();
m_bgItem->hide();
}
void DashboardWindowManager::raiseBackgroundWindow()
{
if(m_stateCurrent != m_stateAlertOpen) {
g_message("%s", __PRETTY_FUNCTION__);
m_alertWinContainer->hide();
m_bgItem->show();
m_bannerWin->show();
if(!m_isOverlay)
m_dashboardWinContainer->hide();
} else {
g_message("%s: In alert state. raise alert window container", __PRETTY_FUNCTION__);
m_alertWinContainer->show();
m_bgItem->hide();
if(!m_isOverlay)
m_dashboardWinContainer->hide();
}
}
void DashboardWindowManager::hideDashboardWindow()
{
if(m_stateCurrent == m_stateDashboardOpen) {
Q_EMIT signalClose(true);
}
if(!m_isOverlay)
m_dashboardWinContainer->hide();
}
void DashboardWindowManager::sendClicktoDashboardWindow(int num, int x, int y, bool whileLocked)
{
m_dashboardWinContainer->sendClickToDashboardWindow(num, QPointF(x, y), true);
}
void DashboardWindowManager::notifyActiveAlertWindowActivated(AlertWindow* win)
{
if (win->isIncomingCallAlert())
DisplayManager::instance()->alert(DISPLAY_ALERT_PHONECALL_ACTIVATED);
else
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_ACTIVATED);
// NOTE: order matters, the DisplayManager needs to act on the alert before anyone else
SystemUiController::instance()->notifyAlertActivated();
Q_EMIT signalAlertWindowActivated(win);
}
void DashboardWindowManager::notifyActiveAlertWindowDeactivated(AlertWindow* win)
{
if (win->isIncomingCallAlert())
DisplayManager::instance()->alert(DISPLAY_ALERT_PHONECALL_DEACTIVATED);
else
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_DEACTIVATED);
SystemUiController::instance()->notifyAlertDeactivated();
Q_EMIT signalAlertWindowDeactivated();
}
void DashboardWindowManager::notifyTransientAlertWindowActivated(AlertWindow* win)
{
if(!alertOpen())
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_ACTIVATED);
// NOTE: order matters, the DisplayManager needs to act on the alert before anyone else
SystemUiController::instance()->notifyTransientAlertActivated();
}
void DashboardWindowManager::notifyTransientAlertWindowDeactivated(AlertWindow* win)
{
if(!alertOpen())
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_DEACTIVATED);
SystemUiController::instance()->notifyTransientAlertDeactivated();
}
void DashboardWindowManager::slotDashboardWindowAdded(DashboardWindow* w)
{
SystemUiController::instance()->setDashboardHasContent(true);
m_bgItem->update();
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentAdded();
}
void DashboardWindowManager::slotDashboardWindowsRemoved(DashboardWindow* w)
{
m_bgItem->update();
if (m_bannerHasContent || !m_dashboardWinContainer->empty())
return;
SystemUiController::instance()->setDashboardHasContent(false);
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentRemoved();
}
void DashboardWindowManager::slotDashboardViewportHeightChanged()
{
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardViewportHeightChanged();
}
void DashboardWindowManager::resize(int width, int height)
{
QRectF bRect = boundingRect();
// accept requests for resizing to the current dimensions, in case we are doing a force resize
WindowManagerBase::resize(width, height);
if(!m_isOverlay) {
m_dashboardWinContainer->resize(width, height);
setPosTopLeft(m_dashboardWinContainer, 0, 0);
m_dashboardWinContainer->resizeWindowsEventSync(width);
m_alertWinContainer->resize(width, height);
setPosTopLeft(m_alertWinContainer, 0, 0);
resizeAlertWindows(width);
}
else {
int yLocCommon = -(height/2) + Settings::LunaSettings()->positiveSpaceTopPadding;
int xLocDashWinCtr;
if (m_menuObject) {
xLocDashWinCtr = (boundingRect().width()/2) - m_dashboardRightOffset - m_menuObject->boundingRect().width() + m_notifMenuRightEdgeOffset;
} else {
xLocDashWinCtr = (boundingRect().width()/2) - m_dashboardRightOffset + m_notifMenuRightEdgeOffset;
}
int yLocDashWinCtr = yLocCommon;
int yLocAlertWinCtr = (m_stateCurrent != m_stateAlertOpen)?yLocCommon:(yLocCommon + topAlertWindow()->initialHeight()/2 + kTabletAlertWindowPadding);
// Set the new position of the m_dashboardWinContainer
if (m_menuObject) {
m_menuObject->setPos(xLocDashWinCtr, yLocDashWinCtr);
}
positionAlertWindowContainer();
}
if(!m_isOverlay) {
// reposition the banner window and the backgound item
m_bgItem->resize(width, height);
setPosTopLeft(m_bgItem, 0, 0);
m_bannerWin->resize(width, Settings::LunaSettings()->positiveSpaceTopPadding);
setPosTopLeft(m_bannerWin, 0, 0);
if((alertOpen())) {
setPos(0, (SystemUiController::instance()->currentUiHeight()/2 + height/2 - activeAlertWindowHeight() - Settings::LunaSettings()->positiveSpaceBottomPadding));
} else if (hasDashboardContent()) {
setPos(0, (SystemUiController::instance()->currentUiHeight()/2 + height/2 - Settings::LunaSettings()->positiveSpaceBottomPadding));
} else {
setPos(0, SystemUiController::instance()->currentUiHeight()/2 + height/2);
}
}
m_stateCurrent->handleUiResizeEvent();
// resize all cached Alert Windows
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
std::set<Window*>* cachedWindows = persistCache->getCachedWindows();
if(cachedWindows) {
std::set<Window*>::iterator it;
it=cachedWindows->begin();
for ( it=cachedWindows->begin() ; it != cachedWindows->end(); it++ ) {
Window* w = *it;
if(w->type() == Window::Type_PopupAlert || w->type() == Window::Type_BannerAlert) {
((AlertWindow*)w)->resizeEventSync((m_isOverlay ? kTabletNotificationContentWidth : width),
((AlertWindow*)w)->initialHeight());
}
}
}
}
void DashboardWindowManager::resizeAlertWindows(int width)
{
Q_FOREACH(AlertWindow* a, m_alertWinArray) {
if (a) {
a->resizeEventSync(width, a->initialHeight());
if(!m_isOverlay)
setPosTopLeft(a, 0, 0);
else
a->setPos(0,0);
}
}
}
void DashboardWindowManager::slotDockModeAnimationStarted()
{
m_inDockModeAnimation = true;
}
void DashboardWindowManager::slotDockModeAnimationComplete()
{
m_inDockModeAnimation = false;
}
void DashboardWindowManager::positionDashboardContainer(const QRect& posSpace)
{
if (m_menuObject) {
QRect positiveSpace;
if(posSpace.isValid())
positiveSpace = posSpace;
else
positiveSpace = SystemUiController::instance()->positiveSpaceBounds();
int uiHeight = SystemUiController::instance()->currentUiHeight();
m_menuObject->setY(-uiHeight/2 + positiveSpace.y());
}
}
void DashboardWindowManager::positionAlertWindowContainer(const QRect& posSpace)
{
QRect positiveSpace;
if(posSpace.isValid())
positiveSpace = posSpace;
else
positiveSpace = SystemUiController::instance()->positiveSpaceBounds();
int uiHeight = SystemUiController::instance()->currentUiHeight();
m_alertWinContainer->setPos(QPoint(positiveSpace.width()/2 - kTabletAlertWindowPadding - m_alertWinContainer->width()/2,
-uiHeight/2 + positiveSpace.y() + kTabletAlertWindowPadding + m_alertWinContainer->height()/2));
}
void DashboardWindowManager::positionTransientWindowContainer(const QRect& posSpace)
{
QRect positiveSpace;
if(posSpace.isValid())
positiveSpace = posSpace;
else
positiveSpace = SystemUiController::instance()->positiveSpaceBounds();
int uiHeight = SystemUiController::instance()->currentUiHeight();
int uiWidth = SystemUiController::instance()->currentUiWidth();
m_transientContainer->setPos(QPoint(positiveSpace.center().x() - uiWidth/2, positiveSpace.center().y() - uiHeight/2));
}
| 38,747 | 13,421 |
#include "stdafx.h"
#include "IKWindow.h"
#include "Editor.h"
using namespace wiECS;
using namespace wiScene;
IKWindow::IKWindow(EditorComponent* editor) : GUI(&editor->GetGUI())
{
assert(GUI && "Invalid GUI!");
window = new wiWindow(GUI, "Inverse Kinematics (IK) Window");
window->SetSize(XMFLOAT2(460, 200));
GUI->AddWidget(window);
float x = 100;
float y = 0;
float step = 25;
float siz = 200;
float hei = 20;
createButton = new wiButton("Create");
createButton->SetTooltip("Create/Remove IK Component to selected entity");
createButton->SetPos(XMFLOAT2(x, y += step));
createButton->SetSize(XMFLOAT2(siz, hei));
window->AddWidget(createButton);
targetCombo = new wiComboBox("Target: ");
targetCombo->SetSize(XMFLOAT2(siz, hei));
targetCombo->SetPos(XMFLOAT2(x, y += step));
targetCombo->SetEnabled(false);
targetCombo->OnSelect([&](wiEventArgs args) {
Scene& scene = wiScene::GetScene();
InverseKinematicsComponent* ik = scene.inverse_kinematics.GetComponent(entity);
if (ik != nullptr)
{
if (args.iValue == 0)
{
ik->target = INVALID_ENTITY;
}
else
{
ik->target = scene.transforms.GetEntity(args.iValue - 1);
}
}
});
targetCombo->SetTooltip("Choose a target entity (with transform) that the IK will follow");
window->AddWidget(targetCombo);
disabledCheckBox = new wiCheckBox("Disabled: ");
disabledCheckBox->SetTooltip("Disable simulation.");
disabledCheckBox->SetPos(XMFLOAT2(x, y += step));
disabledCheckBox->SetSize(XMFLOAT2(hei, hei));
disabledCheckBox->OnClick([=](wiEventArgs args) {
wiScene::GetScene().inverse_kinematics.GetComponent(entity)->SetDisabled(args.bValue);
});
window->AddWidget(disabledCheckBox);
chainLengthSlider = new wiSlider(0, 10, 0, 10, "Chain Length: ");
chainLengthSlider->SetTooltip("How far the hierarchy chain is simulated backwards from this entity");
chainLengthSlider->SetPos(XMFLOAT2(x, y += step));
chainLengthSlider->SetSize(XMFLOAT2(siz, hei));
chainLengthSlider->OnSlide([&](wiEventArgs args) {
wiScene::GetScene().inverse_kinematics.GetComponent(entity)->chain_length = args.iValue;
});
window->AddWidget(chainLengthSlider);
iterationCountSlider = new wiSlider(0, 10, 1, 10, "Iteration Count: ");
iterationCountSlider->SetTooltip("How many iterations to compute the inverse kinematics for. Higher values are slower but more accurate.");
iterationCountSlider->SetPos(XMFLOAT2(x, y += step));
iterationCountSlider->SetSize(XMFLOAT2(siz, hei));
iterationCountSlider->OnSlide([&](wiEventArgs args) {
wiScene::GetScene().inverse_kinematics.GetComponent(entity)->iteration_count = args.iValue;
});
window->AddWidget(iterationCountSlider);
window->Translate(XMFLOAT3((float)wiRenderer::GetDevice()->GetScreenWidth() - 740, 150, 0));
window->SetVisible(false);
SetEntity(INVALID_ENTITY);
}
IKWindow::~IKWindow()
{
window->RemoveWidgets(true);
GUI->RemoveWidget(window);
delete window;
}
void IKWindow::SetEntity(Entity entity)
{
this->entity = entity;
Scene& scene = wiScene::GetScene();
const InverseKinematicsComponent* ik = scene.inverse_kinematics.GetComponent(entity);
if (ik != nullptr)
{
window->SetEnabled(true);
disabledCheckBox->SetCheck(ik->IsDisabled());
chainLengthSlider->SetValue((float)ik->chain_length);
iterationCountSlider->SetValue((float)ik->iteration_count);
targetCombo->ClearItems();
targetCombo->AddItem("NO TARGET");
for (size_t i = 0; i < scene.transforms.GetCount(); ++i)
{
Entity entity = scene.transforms.GetEntity(i);
const NameComponent* name = scene.names.GetComponent(entity);
targetCombo->AddItem(name == nullptr ? std::to_string(entity) : name->name);
if (ik->target == entity)
{
targetCombo->SetSelected((int)i + 1);
}
}
}
else
{
window->SetEnabled(false);
}
const TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity);
if (transform != nullptr)
{
createButton->SetEnabled(true);
if (ik == nullptr)
{
createButton->SetText("Create");
createButton->OnClick([=](wiEventArgs args) {
wiScene::GetScene().inverse_kinematics.Create(entity).chain_length = 1;
SetEntity(entity);
});
}
else
{
createButton->SetText("Remove");
createButton->OnClick([=](wiEventArgs args) {
wiScene::GetScene().inverse_kinematics.Remove_KeepSorted(entity);
SetEntity(entity);
});
}
}
}
| 4,385 | 1,678 |
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "wad/list.hpp"
#include "wad/integer.hpp"
#include "utility.hpp"
TEST_CASE( "std::list save/load", "[std::list]" )
{
std::list<int> upto_16;
std::list<int> upto_u16;
std::list<int> upto_u32;
for(int i=0; i< 5; ++i) {upto_16 .push_back(i);}
for(int i=0; i< 20; ++i) {upto_u16.push_back(i);}
for(int i=0; i<70000; ++i) {upto_u32.push_back(i);}
REQUIRE(wad::save_load(upto_16) == upto_16);
REQUIRE(wad::save_load(upto_u16) == upto_u16);
REQUIRE(wad::save_load(upto_u32) == upto_u32);
}
| 584 | 299 |
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define For(i,a,b) for(int i=a;i<=b;i++)
#define int long long
using namespace std;
char ch[1000005];
int ans[1000005],tot[1000005];
signed main() {
scanf("%s",ch+1);
int n=strlen(ch+1);
For(i,1,n) tot[i]=tot[i-1]+ch[i]-'0';
For(i,1,n) {
ans[i]+=tot[n+1-i];
// cout<<i<<" "<<ans[i]<<'\n';
ans[i+1]+=ans[i]/10;
ans[i]%=10;
// cout<<i<<" "<<ans[i]<<'\n';
}
int len=(ans[n+1]==0?n:n+1);
// cout<<ans[5]<<'\n';
// while(ans[len]>=10){
// ans[len+1]+=ans[len]/10;
// ans[len]%=10;
// len++;
// }
// cout<<"len="<<len<<'\n';
for(int i=len;i>=1;i--) cout<<ans[i];
return 0;
}
| 685 | 387 |
#include <tgmath.h>
#include<algorithm>
#include "apf.h"
#include "ma.h"
#include "maMesh.h"
#include "topo_extinfo.h"
#include "topo_geom.h"
#include "topo_ma.h"
// Get the lowest quality element and it's quality.
std::pair<apf::MeshEntity*, double> calc_valid_q(apf::Mesh2* m,
ma::SizeField* s_f) {
apf::MeshEntity* e_valid = NULL;
double valid = 1;
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
while(elem = m->iterate(it)) {
double q_temp = measureTetQuality(m, s_f, elem);
if(q_temp < valid) {
e_valid = elem;
valid = q_temp;
}
}
m->end(it);
if(valid < std::numeric_limits<double>::min()) {
valid = std::fabs(valid);
}
return std::make_pair(e_valid,valid/5);
}
// Collect elements with quality less than threshold.
double get_low_q(apf::Mesh2* m, ma::SizeField* s_f, std::vector<apf::MeshEntity*> &tets, double q_th) {
std::map<apf::MeshEntity*, bool> low{};
std::map<apf::MeshEntity*, double> qual{};
int nbr = 0;
double valid = 1;
tets.clear();
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
while(elem = m->iterate(it)) {
double q_temp = measureTetQuality(m, s_f, elem);
if(q_temp < q_th) {
nbr = nbr + 1;
low[elem] = true;
qual[elem] = q_temp;
}
if(q_temp < valid)
valid = q_temp;
}
m->end(it);
tets.reserve(nbr);
it = m->begin(3);
while(elem = m->iterate(it)) {
if(low[elem]) {
tets.push_back(elem);
}
}
m->end(it);
if(valid < std::numeric_limits<double>::min()) {
valid = std::fabs(valid);
}
return valid;
}
double calc_good_vol(apf::Mesh2* m, double ref_len, double m_len) {
std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0));
apf::Downward d_v;
apf::Downward d_e;
apf::Downward d_s;
v.at(0) = apf::Vector3(0,0,0);
v.at(1) = apf::Vector3(m_len,0,0);
v.at(2) = apf::Vector3(0,ref_len,0);
v.at(3) = apf::Vector3(0,0,ref_len);
// Create a new entity to calculate it's quailty.
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
elem = m->iterate(it);
m->end(it);
apf::ModelEntity* mdl = m->toModel(elem);
for(int i = 0; i < 4; i++) {
d_v[i] = m->createVert(mdl);
m->setPoint(d_v[i], 0, v.at(i));
}
elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0);
m->getDownward(elem, 1, d_e);
m->getDownward(elem, 2, d_s);
double vol = vd_volume_tet(m, elem);
// Destroy the entities:
m->destroy(elem);
for(int i = 0; i < 4; i++)
m->destroy(d_s[i]);
for(int i = 0; i < 6; i++)
m->destroy(d_e[i]);
for(int i = 0; i < 4; i++)
m->destroy(d_v[i]);
return vol;
}
bool vd_chk_vol_valid(apf::Mesh2* m, apf::MeshEntity* tet, apf::MeshEntity* ent) {
int ent_type = m->getType(ent);
int d = m->typeDimension[ent_type];
assert(d > -1 and d < 3);
bool valid = true;
if(d > 0) {
std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0));
apf::Downward d_v;
apf::Downward d_v2;
m->getDownward(tet, 0, d_v);
std::map<apf::MeshEntity*, apf::Vector3> old_pos{};
for(int i = 0; i < 4; i++) {
m->getPoint(d_v[i], 0, v.at(i));
old_pos[d_v[i]] = v.at(i);
}
int dc = m->getDownward(tet, d, d_v2);
int e1 = findIn(d_v2, dc, ent);
assert(e1 > -1);
dc = m->getDownward(ent, 0, d_v2);
apf::Vector3 midpoint(0,0,0);
midpoint = vd_get_pos(m, ent);
for(int j = 0; j < dc; j++) {
m->setPoint(d_v2[j], 0, midpoint);
bool vol = vd_volume_tet_sign(m, tet);
valid = (valid and vol);
m->setPoint(d_v2[j], 0, old_pos[d_v2[j]]);
}
}
return valid;
}
double calc_good_q(apf::Mesh2* m, double ref_len, double m_len) {
std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0));
apf::Downward d_v;
apf::Downward d_e;
apf::Downward d_s;
v.at(0) = apf::Vector3(0,0,0);
v.at(1) = apf::Vector3(m_len,0,0);
v.at(2) = apf::Vector3(0,ref_len,0);
v.at(3) = apf::Vector3(0,0,ref_len);
// Create a new entity to calculate it's quailty.
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
elem = m->iterate(it);
m->end(it);
apf::ModelEntity* mdl = m->toModel(elem);
for(int i = 0; i < 4; i++) {
d_v[i] = m->createVert(mdl);
m->setPoint(d_v[i], 0, v.at(i));
}
elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0);
m->getDownward(elem, 1, d_e);
m->getDownward(elem, 2, d_s);
ma::IdentitySizeField* ref_0c = new ma::IdentitySizeField(m);
double qual = measureTetQuality(m, ref_0c, elem);
delete ref_0c;
// Destroy the entities:
m->destroy(elem);
for(int i = 0; i < 4; i++)
m->destroy(d_s[i]);
for(int i = 0; i < 6; i++)
m->destroy(d_e[i]);
for(int i = 0; i < 4; i++)
m->destroy(d_v[i]);
return qual;
}
double calc_q(apf::Mesh2* m, std::vector<apf::Vector3> &v) {
apf::Downward d_v;
apf::Downward d_s;
apf::Downward d_e;
// Create a new entity to calculate it's quailty.
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
elem = m->iterate(it);
m->end(it);
apf::ModelEntity* mdl = m->toModel(elem);
for(int i = 0; i < 4; i++) {
d_v[i] = m->createVert(mdl);
m->setPoint(d_v[i], 0, v.at(i));
}
elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0);
m->getDownward(elem, 1, d_e);
m->getDownward(elem, 2, d_s);
ma::IdentitySizeField* ref_0c = new ma::IdentitySizeField(m);
double qual = measureTetQuality(m, ref_0c, elem);
delete ref_0c;
// Destroy the entities:
m->destroy(elem);
for(int i = 0; i < 4; i++)
m->destroy(d_s[i]);
for(int i = 0; i < 6; i++)
m->destroy(d_e[i]);
for(int i = 0; i < 4; i++)
m->destroy(d_v[i]);
return qual;
}
MaSwap3Dcheck::MaSwap3Dcheck(apf::Mesh2* m): mesh(m) {
halves[0].init(m);
halves[1].init(m);
edge = 0;
}
MaSwap3Dcheck::~MaSwap3Dcheck() {}
bool MaSwap3Dcheck::run(apf::MeshEntity* e) {
if (ma::isOnModelEdge(mesh,e))
return false;
edge = e;
if (ma::isOnModelFace(mesh,edge)) {
}
else {
cavityExists[0] = halves[0].setFromEdge(edge);
if(!cavityExists[0]) {
MaLoop loop;
loop.init(mesh);
loop.setEdge(edge);
std::vector<apf::MeshEntity*> tets(0);
std::vector<apf::MeshEntity*> surf(0);
vd_set_up(mesh, e, &surf);
vd_set_up(mesh, &surf, &tets);
apf::ModelEntity* mdl = mesh->toModel(edge);
std::cout << "Curl is not OK! " << edge << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
apf::Downward dv;
apf::Up up;
mesh->getDownward(edge, 0, dv);
mdl = mesh->toModel(dv[0]);
std::cout << "Verts: " << dv[0] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
mdl = mesh->toModel(dv[1]);
std::cout << dv[1] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
for(int i = 0; i < tets.size(); i++) {
mdl = mesh->toModel(tets.at(i));
std::cout << "Tet " << tets.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, tets.at(i))
<< std::endl;
vd_print_down(mesh, tets.at(i));
}
for(int i = 0; i < surf.size(); i++) {
mdl = mesh->toModel(surf.at(i));
std::cout << "Surf " << surf.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, surf.at(i))
<< std::endl;
vd_print_down(mesh, surf.at(i));
vd_set_up(mesh, surf.at(i), &tets);
apf::MeshEntity* v = ma::getTriVertOppositeEdge(mesh,surf.at(i),edge);
for(int j = 0; j < tets.size(); j++) {
mdl = mesh->toModel(tets.at(j));
std::cout << "Tet " << tets.at(j) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< std::endl;
std::cout << "Curl:" << loop.isCurlOk(v,tets.at(j)) << std::endl;
}
}
}
assert(cavityExists[0]);
}
return true;
}
bool MaSwap3Dcheck::run_all_surf(apf::MeshEntity* e) {
bool curl_ok = true;
if (ma::isOnModelEdge(mesh,e))
return curl_ok;
edge = e;
if (ma::isOnModelFace(mesh,edge)) {
}
else {
MaLoop loop;
loop.init(mesh);
loop.setEdge(edge);
std::vector<apf::MeshEntity*> tets(0);
std::vector<apf::MeshEntity*> surf(0);
vd_set_up(mesh, e, &surf);
vd_set_up(mesh, &surf, &tets);
apf::ModelEntity* mdl = mesh->toModel(edge);
std::cout << edge << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
apf::Downward dv;
apf::Up up;
mesh->getDownward(edge, 0, dv);
mdl = mesh->toModel(dv[0]);
std::cout << "Verts: " << dv[0] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
mdl = mesh->toModel(dv[1]);
std::cout << dv[1] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
for(int i = 0; i < tets.size(); i++) {
mdl = mesh->toModel(tets.at(i));
std::cout << "Tet " << tets.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, tets.at(i))
<< std::endl;
vd_print_down(mesh, tets.at(i));
}
for(int i = 0; i < surf.size(); i++) {
mdl = mesh->toModel(surf.at(i));
std::cout << "Surf " << surf.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, surf.at(i))
<< std::endl;
vd_print_down(mesh, surf.at(i));
vd_set_up(mesh, surf.at(i), &tets);
bool curls_tot = false;
apf::MeshEntity* v = ma::getTriVertOppositeEdge(mesh,surf.at(i),edge);
for(int j = 0; j < tets.size(); j++) {
mdl = mesh->toModel(tets.at(j));
std::cout << "Tet " << tets.at(j) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< std::endl;
bool curl_curr = loop.isCurlOk(v,tets.at(j));
std::cout << "Curl:" << curl_curr << std::endl;
curls_tot = curls_tot or curl_curr;
}
curl_ok = curl_ok and curls_tot;
}
}
return curl_ok;
}
bool chk_ma_swap(apf::Mesh2* m) {
MaSwap3Dcheck swap_chk(m);
apf::MeshEntity* e;
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
apf::MeshIterator* it = m->begin(1);
while ((e = m->iterate(it))) {
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
if(!swap_chk.run(e)) {
return false;
}
}
}
m->end(it);
return true;
}
bool chk_ma_swap(apf::Mesh2* m, std::vector<apf::MeshEntity*> &vert_in) {
MaSwap3Dcheck swap_chk(m);
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
std::vector<apf::MeshEntity*> edge(0);
vd_set_up(m, &vert_in, &edge);
apf::MeshEntity* e;
for(int i = 0; i < edge.size(); i++) {
e = edge.at(i);
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
if(!swap_chk.run(e)) {
return false;
}
}
}
return true;
}
bool chk_ma_swap_all(apf::Mesh2* m) {
MaSwap3Dcheck swap_chk(m);
apf::MeshEntity* e;
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
bool curl_ok = true;
apf::MeshIterator* it = m->begin(1);
while ((e = m->iterate(it))) {
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
bool curl_curr = swap_chk.run_all_surf(e);
curl_ok = curl_ok and curl_curr;
}
}
m->end(it);
return curl_ok;
}
bool chk_ma_swap_all(apf::Mesh2* m, std::vector<apf::MeshEntity*> &vert_in) {
MaSwap3Dcheck swap_chk(m);
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
bool curl_ok = true;
std::vector<apf::MeshEntity*> edge(0);
vd_set_up(m, &vert_in, &edge);
apf::MeshEntity* e;
for(int i = 0; i < edge.size(); i++) {
e = edge.at(i);
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
bool curl_curr = swap_chk.run_all_surf(e);
curl_ok = curl_ok and curl_curr;
}
}
return curl_ok;
}
// Given an ma::Input, replace the old size field.
void repl_sz_field(ma::Input* in, apf::Mesh2* m, MA_SIZE_TYPE MA_T) {
if(MA_T == MA_SIZE_TYPE::EDGE_COL) {
delete in->sizeField;
ModelEdgeCollapse* ref = new ModelEdgeCollapse(m);
in->sizeField = ref;
}
else if(MA_T == MA_SIZE_TYPE::EDGE_SPLIT) {
delete in->sizeField;
ModelEdgeSplit* ref = new ModelEdgeSplit(m);
in->sizeField = ref;
}
else if(MA_T == MA_SIZE_TYPE::EDGE_REFINER) {
delete in->sizeField;
ModelEdgeRefiner* ref = new ModelEdgeRefiner(m);
in->sizeField = ref;
}
else {
assert(MA_T == MA_SIZE_TYPE::EDGE_REF_DIST);
delete in->sizeField;
ModelEdgeRefinerDist* ref = new ModelEdgeRefinerDist(m);
in->sizeField = ref;
}
}
void vd_ma_input::set_def() {
maximumIterations = 3;
shouldCoarsen = true;
shouldFixShape = true;
shouldForceAdaptation = false;
shouldPrintQuality = true;
goodQuality = 0.027;
maximumEdgeRatio = 2.0;
shouldCheckQualityForDoubleSplits = false;
validQuality = 1e-10;
maximumImbalance = 1.10;
shouldRunPreZoltan = false;
shouldRunPreZoltanRib = false;
shouldRunPreParma = false;
shouldRunMidZoltan = false;
shouldRunMidParma = false;
shouldRunPostZoltan = false;
shouldRunPostZoltanRib = false;
shouldRunPostParma = false;
shouldTurnLayerToTets = false;
shouldCleanupLayer = false;
shouldRefineLayer = false;
shouldCoarsenLayer = false;
splitAllLayerEdges = false;
}
void vd_ma_input::flip_template(INPUT_TYPE IT_IN) {
assert(IT_IN < INPUT_TYPE::END);
if(IT_IN == INPUT_TYPE::ADAPT_SPLIT) {
shouldRefineLayer = true;
}
else if(IT_IN == INPUT_TYPE::ADAPT_COL) {
shouldRunPreZoltan = false;
shouldRunMidParma = false;
shouldRunPostParma = false;
shouldRefineLayer = false;
shouldCoarsen = true;
shouldCoarsenLayer = true;
shouldFixShape = false;
}
else {
assert(IT_IN == INPUT_TYPE::ADAPT_Q);
shouldRunPreZoltan = true;
shouldRunMidParma = true;
shouldRunPostParma = true;
shouldRefineLayer = true;
shouldFixShape = true;
}
}
void vd_ma_input::set_template(INPUT_TYPE IT_IN) {
set_def();
flip_template(IT_IN);
}
// Get the input fields from ma::Input.
void vd_ma_input::get_input(ma::Input* in) {
maximumIterations = in->maximumIterations;
shouldCoarsen = in->shouldCoarsen;
shouldFixShape = in->shouldFixShape;
shouldForceAdaptation = in->shouldForceAdaptation;
shouldPrintQuality = in->shouldPrintQuality;
goodQuality = in->goodQuality;
maximumEdgeRatio = in->maximumEdgeRatio;
shouldCheckQualityForDoubleSplits = in->shouldCheckQualityForDoubleSplits;
validQuality = in->validQuality;
maximumImbalance = in->maximumImbalance;
shouldRunPreZoltan = in->shouldRunPreZoltan;
shouldRunPreZoltanRib = in->shouldRunPreZoltanRib;
shouldRunPreParma = in->shouldRunPreParma;
shouldRunMidZoltan = in->shouldRunMidZoltan;
shouldRunMidParma = in->shouldRunMidParma;
shouldRunPostZoltan = in->shouldRunPostZoltan;
shouldRunPostZoltanRib = in->shouldRunPostZoltanRib;
shouldRunPostParma = in->shouldRunPostParma;
shouldTurnLayerToTets = in->shouldTurnLayerToTets;
shouldCleanupLayer = in->shouldCleanupLayer;
shouldRefineLayer = in->shouldRefineLayer;
shouldCoarsenLayer = in->shouldCoarsenLayer;
splitAllLayerEdges = in->splitAllLayerEdges;
}
// Transfer the input fields to ma::Input.
void vd_ma_input::set_input(ma::Input* in) {
in->maximumIterations = maximumIterations;
in->shouldCoarsen = shouldCoarsen;
in->shouldFixShape = shouldFixShape;
in->shouldForceAdaptation = shouldForceAdaptation;
in->shouldPrintQuality = shouldPrintQuality;
in->goodQuality = goodQuality;
in->maximumEdgeRatio = maximumEdgeRatio;
in->shouldCheckQualityForDoubleSplits = shouldCheckQualityForDoubleSplits;
in->validQuality = validQuality;
in->maximumImbalance = maximumImbalance;
in->shouldRunPreZoltan = shouldRunPreZoltan;
in->shouldRunPreZoltanRib = shouldRunPreZoltanRib;
in->shouldRunPreParma = shouldRunPreParma;
in->shouldRunMidZoltan = shouldRunMidZoltan;
in->shouldRunMidParma = shouldRunMidParma;
in->shouldRunPostZoltan = shouldRunPostZoltan;
in->shouldRunPostZoltanRib = shouldRunPostZoltanRib;
in->shouldRunPostParma = shouldRunPostParma;
in->shouldTurnLayerToTets = shouldTurnLayerToTets;
in->shouldCleanupLayer = shouldCleanupLayer;
in->shouldRefineLayer = shouldRefineLayer;
in->shouldCoarsenLayer = shouldCoarsenLayer;
in->splitAllLayerEdges = splitAllLayerEdges;
}
// Copy constructor
vd_ma_input::vd_ma_input(const vd_ma_input& that) {
maximumIterations = that.maximumIterations;
shouldCoarsen = that.shouldCoarsen;
shouldFixShape = that.shouldFixShape;
shouldForceAdaptation = that.shouldForceAdaptation;
shouldPrintQuality = that.shouldPrintQuality;
goodQuality = that.goodQuality;
maximumEdgeRatio = that.maximumEdgeRatio;
shouldCheckQualityForDoubleSplits = that.shouldCheckQualityForDoubleSplits;
validQuality = that.validQuality;
maximumImbalance = that.maximumImbalance;
shouldRunPreZoltan = that.shouldRunPreZoltan;
shouldRunPreZoltanRib = that.shouldRunPreZoltanRib;
shouldRunPreParma = that.shouldRunPreParma;
shouldRunMidZoltan = that.shouldRunMidZoltan;
shouldRunMidParma = that.shouldRunMidParma;
shouldRunPostZoltan = that.shouldRunPostZoltan;
shouldRunPostZoltanRib = that.shouldRunPostZoltanRib;
shouldRunPostParma = that.shouldRunPostParma;
shouldTurnLayerToTets = that.shouldTurnLayerToTets;
shouldCleanupLayer = that.shouldCleanupLayer;
shouldRefineLayer = that.shouldRefineLayer;
shouldCoarsenLayer = that.shouldCoarsenLayer;
splitAllLayerEdges = that.splitAllLayerEdges;
}
// Copy
vd_ma_input& vd_ma_input::operator=(const vd_ma_input& that) {
maximumIterations = that.maximumIterations;
shouldCoarsen = that.shouldCoarsen;
shouldFixShape = that.shouldFixShape;
shouldForceAdaptation = that.shouldForceAdaptation;
shouldPrintQuality = that.shouldPrintQuality;
goodQuality = that.goodQuality;
maximumEdgeRatio = that.maximumEdgeRatio;
shouldCheckQualityForDoubleSplits = that.shouldCheckQualityForDoubleSplits;
validQuality = that.validQuality;
maximumImbalance = that.maximumImbalance;
shouldRunPreZoltan = that.shouldRunPreZoltan;
shouldRunPreZoltanRib = that.shouldRunPreZoltanRib;
shouldRunPreParma = that.shouldRunPreParma;
shouldRunMidZoltan = that.shouldRunMidZoltan;
shouldRunMidParma = that.shouldRunMidParma;
shouldRunPostZoltan = that.shouldRunPostZoltan;
shouldRunPostZoltanRib = that.shouldRunPostZoltanRib;
shouldRunPostParma = that.shouldRunPostParma;
shouldTurnLayerToTets = that.shouldTurnLayerToTets;
shouldCleanupLayer = that.shouldCleanupLayer;
shouldRefineLayer = that.shouldRefineLayer;
shouldCoarsenLayer = that.shouldCoarsenLayer;
splitAllLayerEdges = that.splitAllLayerEdges;
}
vd_ma_input::vd_ma_input() :
maximumIterations(3),
shouldCoarsen(true),
shouldFixShape(true),
shouldForceAdaptation(false),
shouldPrintQuality(true),
goodQuality(0.027),
maximumEdgeRatio(2.0),
shouldCheckQualityForDoubleSplits(false),
validQuality(1e-10),
maximumImbalance(1.10),
shouldRunPreZoltan(false),
shouldRunPreZoltanRib(false),
shouldRunPreParma(false),
shouldRunMidZoltan(false),
shouldRunMidParma(false),
shouldRunPostZoltan(false),
shouldRunPostZoltanRib(false),
shouldRunPostParma(false),
shouldTurnLayerToTets(false),
shouldCleanupLayer(false),
shouldRefineLayer(false),
shouldCoarsenLayer(false),
splitAllLayerEdges(false) {
}
vd_ma_input::~vd_ma_input() {}
vd_input_iso::vd_input_iso() {
}
/*
// A wrapper for ma::Input object with common predefined use cases.
// Using INPUT_TYPE flags as input, the input flags can be set for a certain
// option, or the flags associated with a INPUT_TYPE can be flipped.
vd_input_iso::vd_input_iso(apf::Mesh2* m, ma::IsotropicFunction* sf,
ma::IdentitySizeField* ref) :
in(NULL) {
in = ma::configure(m, sf);
if(ref != NULL) {
delete in->sizeField;
in->sizeField = ref;
}
in->shouldRunPreZoltan = true;
in->shouldRunMidParma = true;
in->shouldRunPostParma = true;
in->shouldRefineLayer = true;
in->shouldCoarsenLayer = true;
in->shouldFixShape = true;
in->goodQuality = 0.2;
in->validQuality = 10e-5;
std::cout << "Minimum quality is " << in->validQuality
<< ", good quality is " << in->goodQuality
<< std::endl;
in->maximumEdgeRatio = 12;
in->maximumIterations = 3;
}
*/
//void vd_input_iso::set_valid(double v_in) {
// in->validQuality = v_in;
// std::cout << "Set valid quality to " << in->validQuality
// << std::endl;
//}
//void vd_input_iso::set_good(double g_in) {
// in->goodQuality = g_in;
// std::cout << "Set good quality to " << in->goodQuality
// << std::endl;
//}
vd_input_iso::~vd_input_iso() {
}
//void vd_input_iso::set_sizefield(ma::IdentitySizeField* ref) {
// assert(ref != NULL);
// delete in->sizeField;
// in->sizeField = ref;
//}
void vd_input_iso::set_input(std::vector<INPUT_TYPE> &IT_IN) {
IT = IT_IN;
}
//ma::Input* vd_input_iso::get_input() {
// return in;
//}
// Container for keeping calculations of distances of a given stratum vertices
// from its bounding strata. Calculates for bounding 2s for 3c, 1s for 2s and
// 0s for 1s.
// Set the cell for the distances to be calculated:
void DistBurner::set_cell(int d_in, int id_in, apf::Mesh2* m_in,
vd_entlist & e_list,
cell_base* c_base_in, double len) {
clear();
c_dim = d_in;
c_id = id_in;
sim_len = len;
m = m_in;
c_base = c_base_in;
collect_adj(e_list);
burn_dist();
//consider the distance to entity centers, in addition to vertices.
}
// Collect adjacencies:
void DistBurner::collect_adj(vd_entlist & e_list) {
assert(e_list.e.at(c_dim).at(c_id).at(c_dim).size() > 0);
front.reserve(e_list.e.at(c_dim).at(c_id).at(c_dim).size());
// Link the downward adjacencies of the same dimensional entities of the
// calculated stratum to it's entities of one dimension lower.
int d_lower = c_dim - 1;
apf::Downward d_e;
for(int i = 0; i < e_list.e.at(c_dim).at(c_id).at(c_dim).size(); i++) {
apf::MeshEntity* e_curr = e_list.e.at(c_dim).at(c_id).at(c_dim).at(i);
m->getDownward(e_curr, d_lower, d_e);
for(int j = 0; j < c_dim + 1; j++) {
if(e_map1[d_e[j]] == NULL) {
e_map1[d_e[j]] = e_curr;
}
else {
assert(e_map2[d_e[j]] == NULL);
e_map2[d_e[j]] = e_curr;
}
}
}
ent_conn* edown = new ent_conn();
c_base->get_conn(c_dim, c_id, edown);
// TODO for now, assume no ring-like strata. In future, consider the distance
// from the weighted center.
assert(edown->conn.size() > 0);
// Collect the geometric information about boundary entities.
int lookup_tet_x_surf [4] = {3, 2, 0, 1};
int lookup_v_tri_x_e [3] = {2,0,1};
apf::Vector3 temp(0,0,0);
apf::Downward d_v;
apf::Up up;
for(int c_down = 0; c_down < e_list.e.at(d_lower).size(); c_down++) {
if(e_list.e.at(d_lower).at(c_down).at(d_lower).size() > 0) {
// Walk over downward adjancency lists:
for(int i = 0; i < e_list.e.at(d_lower).at(c_down).at(d_lower).size();
i++) {
apf::MeshEntity* e_curr = e_list.e.at(d_lower).at(c_down)
.at(d_lower).at(i);
m->getUp(e_curr, up);
// The geometric information is assigned. Used in lower dim boundary
// entities to prevent spurious assignment.
std::map<apf::MeshEntity*, bool> asgn{};
bool found = false;
for(int j = 0; j < up.n; j++) {
apf::ModelEntity* mdl = m->toModel(up.e[j]);
int d_up = m->getModelType(mdl);
int id_up = m->getModelTag(mdl) - 1;
if(d_up == c_dim and id_up == c_id) {
assert(!found);
found = true;
front.push_back(up.e[j]);
m->getDownward(up.e[j], d_lower, d_e);
int e1 = findIn(d_e, c_dim+1, e_curr);
// Collecting entities bounding a 1cell:
if(d_lower == 0) {
// The information about the bounding vertex is collected:
m->getPoint(e_curr, 0, temp);
v_pos[e_curr] = temp;
asgn[e_curr] = true;
// The vertex of the front entity is collected:
int v1 = (e1 + 1) % 2;
v_map[up.e[j]] = d_e[v1];
v_id[up.e[j]] = v1;
m->getPoint(d_e[v1], 0, temp);
v_pos[d_e[v1]] = temp;
}
// Collecting entities bounding a 2cell:
else if(d_lower == 1) {
// The vertex of the front entity is collected:
m->getDownward(up.e[j], 0, d_v);
int v1 = lookup_v_tri_x_e[e1];
v_map[up.e[j]] = d_v[v1];
v_id[up.e[j]] = v1;
// Position of the interior vertex.
m->getPoint(d_v[v1], 0, temp);
v_pos[d_v[v1]] = temp;
// The information about the bounding entities are collected:
apf::Vector3 temp2(0,0,0);
int v2 = (v1+1)%3;
m->getPoint(d_v[v2], 0, temp);
v_pos[d_v[v2]] = temp;
asgn[d_v[v2]] = true;
v2 = (v1+2)%3;
m->getPoint(d_v[v2], 0, temp2);
v_pos[d_v[v2]] = temp2;
asgn[d_v[v2]] = true;
e_pos[e_curr] = temp;
e_dir[e_curr] = norm_0(temp2 - temp);
asgn[e_curr] = true;
}
else {
// The vertex of the front entity is collected:
m->getDownward(up.e[j], 0, d_v);
int v1 = lookup_tet_x_surf[e1];
v_map[up.e[j]] = d_v[v1];
v_id[up.e[j]] = v1;
// Position of the interior vertex.
m->getPoint(d_v[v1], 0, temp);
v_pos[d_v[v1]] = temp;
// The information about the bounding entities are collected:
t_pos[e_curr] = apf::Vector3(0,0,0);
for(int k = 0; k < 3; k++) {
int v2 = (v1+k+1)%4;
m->getPoint(d_v[v2], 0, temp);
v_pos[d_v[v2]] = temp;
asgn[d_v[v2]] = true;
t_pos[e_curr] = t_pos[e_curr] + temp;
}
m->getPoint(d_v[v1], 0, temp);
t_dir[e_curr] = vd_area_out_n(m, e_curr);
if((temp - t_pos[e_curr])*t_dir[e_curr] <
- std::numeric_limits<double>::min())
t_dir[e_curr] = t_dir[e_curr]*(-1);
m->getDownward(e_curr, 1, d_e);
for(int k = 0; k < 3; k++) {
m->getDownward(d_e[k], 0, d_v);
assert(asgn[d_v[0]]);
assert(asgn[d_v[1]]);
m->getPoint(d_v[0], 0, temp);
e_pos[d_e[k]] = temp;
m->getPoint(d_v[1], 0, temp);
e_dir[d_e[k]] = norm_0(temp - e_pos[d_e[k]]);
asgn[d_e[k]] = true;
}
}
}
}
assert(found);
}
}
}
delete edown;
}
// Starting from the current entity on the front and moving over the
// adjacent entities, find the smallest distance boundary element
// reachable from the starting element for the vertex associated
// with the starting entity.
void DistBurner::calc_v_3c(apf::MeshEntity* tet) {
apf::Downward d_v;
/*
apf::Vector3 int_pt(0,0,0);
apf::MeshEntity* last;
apf::MeshEntity* next;
next = tri_proj_v(v_map[tet], last, int_pt);
if(last == next)
*/
}
void DistBurner::calc_v_2c(apf::MeshEntity* tri) {
}
void DistBurner::calc_v_1c(apf::MeshEntity* edge) {
}
// Starting from given triangle, return the entity the closest projection of
// the vertex onto the boundary lies on. If the projection is on the triangle,
// return the intersection point.
apf::MeshEntity* DistBurner::tri_proj_v(apf::MeshEntity* v, apf::MeshEntity* tri, apf::Vector3& int_pt) {
apf::MeshEntity* ent = tri;
apf::Vector3 temp1(0,0,0);
apf::Vector3 temp2(0,0,0);
apf::Vector3 edir(0,0,0);
apf::Vector3 epos(0,0,0);
int_pt = v_pos[v] - t_pos[tri];
int_pt = int_pt - t_dir[tri]*(int_pt*t_dir[tri]) + t_pos[tri];
for(int i = 0; i < 3; i++) {
edir = e_dir[e_d[tri].at(i)];
epos = e_pos[e_d[tri].at(i)];
temp1 = (int_pt - epos);
temp1 = temp1 - edir*(temp1*edir);
temp2 = (t_pos[tri] - epos);
temp2 = temp2 - edir*(temp2*edir);
// If outside get the first edge that the projection lies outside of.
if( temp1*temp2 < - std::numeric_limits<double>::min()) {
//std::cout << "v1v2 - t_pos[tri]" << temp1*temp2 << std::endl;
if(e_map1[e_d[tri].at(i)] == tri)
ent = e_map2[e_d[tri].at(i)];
else {
assert(e_map2[e_d[tri].at(i)] == tri);
ent = e_map1[e_d[tri].at(i)];
}
i = 3;
}
}
return ent;
}
// Calculate the distance from the vertex to a given entity.
double DistBurner::calc_d_tri(apf::MeshEntity* v, apf::MeshEntity* tri) {
}
double DistBurner::calc_d_edge(apf::MeshEntity* v, apf::MeshEntity* edge) {
}
double DistBurner::calc_d_vert(apf::MeshEntity* v, apf::MeshEntity* vert) {
apf::Downward d_v;
}
// Burn the vertices below (1+dist_tol)*dist_min distance from the boundary
// remove the burnt entities in the front and add new ones.
void DistBurner::step_front() {
}
// Run step_front until the front is empty.
void DistBurner::burn_dist() {
/*
dist_max = sim_len;
while(front.size() > 0) {
// The end burnt number of tets are burnt and not to be considered.
int burnt = 0;
double dist_min = sim_len;
for(int i = 0; i < front.size() - burnt; i++) {
apf::MeshEntity* t_curr = front.at(i);
assert(!t_burn[t_curr]);
m->getDownward(t_curr, 0, d_v);
bool found = false;
for(int j = 0; j < 4; j++) {
if(!v_burn[d_v[j]]) {
assert(!found);
found = true;
v_map[t_curr] = d_v[j];
v_id[t_curr] = j;
}
}
assert(found);
t_dist[t_curr] = approx_dist(m, v_dist, d_v, v_map[t_curr]);
if(t_dist[t_curr] < v_dist[v_map[t_curr]]) {
v_dist[v_map[t_curr]] = t_dist[t_curr];
if(v_dist[v_map[t_curr]] < dist_min)
dist_min = v_dist[v_map[t_curr]];
}
}
int added = 0;
double dist_th = dist_min*(1+dist_tol);
for(int i = 0; i < front.size() - burnt - added; i++) {
apf::MeshEntity* t_curr = front.at(i);
if(v_dist[v_map[t_curr]] < dist_th) {
v_burn[v_map[t_curr]] = true;
}
}
for(int i = 0; i < front.size() - burnt - added; i++) {
apf::MeshEntity* t_curr = front.at(i);
assert(tv_id[t_curr] > -1);
assert(v_map[t_curr] != NULL);
if(v_dist[v_map[t_curr]] < dist_th) {
m->getDownward(t_curr, 2, d_t);
int v_id = tv_id[t_curr];
for(int j = 0; j < 3; j++) {
int t_id = lookup_tet_surf[v_id][j];
apf::MeshEntity* tri_curr = d_t[t_id];
m->getUp(tri_curr, up);
if(up.n == 2) {
apf::MeshEntity* t_next;
if(up.e[0] == t_curr)
t_next = up.e[1];
else
t_next = up.e[0];
if(!t_burn[t_next]) {
int t1 = findIn(&front, front.size(), t_next);
if(t1 == -1) {
m->getDownward(t_next, 0, d_v);
bool found1 = false;
bool found2 = false;
for(int j = 0; j < 4; j++) {
if(!v_burn[d_v[j]]) {
if(found1)
found2 = true;
else
found1 = true;
}
}
assert(!found2);
if(found1) {
if(burnt > 0) {
int i_b = front.size() - burnt;
assert(!t_burn[front.at(i_b-1)]);
assert(t_burn[front.at(i_b)]);
front.push_back(front.at(i_b));
front.at(i_b) = t_next;
//m->getDownward(t_next, 2, d_t2);
//int t2 = findIn(d_t2, 4, tri_curr);
//assert(t2 > -1);
//v_map[t_next] = d_v[lookup_tet_surf_x[t2]];
//t_dist[t_next] = approx_dist(m, v_dist, d_v,
// v_map[t_curr]);
}
else
front.push_back(t_next);
tv_id[t_next] = -1;
v_map[t_next] = NULL;
added = added + 1;
}
else {
t_burn[t_next] = true;
}
}
}
}
}
t_burn[t_curr] = true;
int i_ub = front.size() - burnt - added - 1;
int i_ad = front.size() - burnt - 1;
if(i_ub != i)
assert(!t_burn[front.at(i_ub)]);
if(added > 0)
assert(!t_burn[front.at(i_ub+1)]);
if(burnt > 0)
assert(t_burn[front.at(i_ub+added+1)]);
front.at(i) = front.at(i_ub);
front.at(i_ub) = front.at(i_ad);
front.at(i_ad) = t_curr;
burnt = burnt + 1;
i = i-1;
}
}
front.resize(front.size() - burnt);
}
*/
}
void DistBurner::clear() {
v_pos.clear();
e_pos.clear();
t_pos.clear();
e_dir.clear();
t_dir.clear();
v_dist.clear();
front.clear();
burn_curr.clear();
e_d.clear();
e_v.clear();
v_map.clear();
v_id.clear();
e_map1.clear();
e_map2.clear();
b_map.clear();
}
DistBurner::DistBurner() :
m(NULL), v_pos{}, e_pos{}, t_pos{}, e_dir{}, t_dir{}, v_dist{},
burn_curr{},
front(0), e_d{}, e_v{}, v_map{}, v_id{}, e_map1{}, e_map2{}, b_map{} {
}
DistBurner::~DistBurner() {
clear();
}
ModelEdgeRefiner::ModelEdgeRefiner(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false) {
}
bool ModelEdgeRefiner::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return true;
return false;
}
bool ModelEdgeRefiner::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return false;
else if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
else if(split_all)
return true;
}
return false;
}
ModelEdgeRefiner::~ModelEdgeRefiner() {
for(int i = 0; i < 3; i++) {
coarse_map.at(i).clear();
}
coarse_map.clear();
}
ModelEdgeRefinerDist::ModelEdgeRefinerDist(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false),
split_target(1.5), coarse_target(0.5) {
field_step = m->findField("adapt_step");
assert(field_step != NULL);
}
double ModelEdgeRefinerDist::measure_dist(ma::Entity* edge) {
// TODO Use integrators of apf to integrate the field directly. For linear
// elements and for isotropic metrics, it is equivalent.
apf::MeshElement* me = apf::createMeshElement(mesh, edge);
double len = measure(edge);
apf::destroyMeshElement(me);
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
double dist = apf::getScalar(field_step, d_v[0], 0);
dist = (dist + apf::getScalar(field_step, d_v[1], 0))/2;
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return len*dist;
}
bool ModelEdgeRefinerDist::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return true;
return this->measure_dist(edge) < coarse_target;
}
bool ModelEdgeRefinerDist::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
//double v0 = apf::getScalar(field_step, d_v[0], 0);
//double v1 = apf::getScalar(field_step, d_v[1], 0);
//double len = vd_meas_ent(mesh, edge);
//return (1 > v0) or (1 > v1);
//return (2*len > v0) or (2*len > v1);
//return (len > v0/4+v1/4);
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return false;
//else if(dim_e == 1 and dim_e > dim_v0 and dim_e > dim_v1)
else if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
else if(split_all)
return true;
}
return this->measure_dist(edge) > split_target;
//else if
}
void ModelEdgeRefinerDist::set_target_th(double coarse_in, double split_in) {
split_target = split_in;
coarse_target = coarse_in;
}
ModelEdgeRefinerDist::~ModelEdgeRefinerDist() {
for(int i = 0; i < 3; i++) {
coarse_map.at(i).clear();
}
coarse_map.clear();
}
ModelEdgeCollapse::ModelEdgeCollapse(ma::Mesh* m) : coarse_map{},
IdentitySizeField(m) {
}
bool ModelEdgeCollapse::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map[edge])
return true;
return false;
}
bool ModelEdgeCollapse::shouldSplit(ma::Entity* edge) {
return false;
}
ModelEdgeCollapse::~ModelEdgeCollapse() {
coarse_map.clear();
}
ModelEdgeSplit::ModelEdgeSplit(ma::Mesh* m) : split_map{},
IdentitySizeField(m) {
}
bool ModelEdgeSplit::shouldCollapse(ma::Entity* edge) {
return false;
}
bool ModelEdgeSplit::shouldSplit(ma::Entity* edge) {
if(split_map[edge])
return true;
return false;
}
ModelEdgeSplit::~ModelEdgeSplit() {
split_map.clear();
}
/////////////////////////////////////
// ModelEdgeRefinerGrain
/////////////////////////////////////
ModelEdgeRefinerGrain::ModelEdgeRefinerGrain(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false) {
field_step = m->findField("adapt_step");
assert(field_step != NULL);
}
double ModelEdgeRefinerGrain::measure_dist(ma::Entity* edge) {
// TODO Use integrators of apf to integrate the field directly. For linear
// elements and for isotropic metrics, it is equivalent.
apf::MeshElement* me = apf::createMeshElement(mesh, edge);
double len = measure(edge);
apf::destroyMeshElement(me);
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
double dist = apf::getScalar(field_step, d_v[0], 0);
dist = (dist + apf::getScalar(field_step, d_v[1], 0))/2;
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return len*dist;
}
bool ModelEdgeRefinerGrain::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return true;
return this->measure_dist(edge) < 0.5;
}
bool ModelEdgeRefinerGrain::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
//double v0 = apf::getScalar(field_step, d_v[0], 0);
//double v1 = apf::getScalar(field_step, d_v[1], 0);
//double len = vd_meas_ent(mesh, edge);
//return (1 > v0) or (1 > v1);
//return (2*len > v0) or (2*len > v1);
//return (len > v0/4+v1/4);
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return false;
else if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
else if(split_all)
return true;
}
return this->measure_dist(edge) > 1.5;
//else if
}
ModelEdgeRefinerGrain::~ModelEdgeRefinerGrain() {
for(int i = 0; i < 3; i++) {
coarse_map.at(i).clear();
}
coarse_map.clear();
}
/////////////////////////////////////
// ModelEdgeRefinerVarying
/////////////////////////////////////
ModelEdgeRefinerVarying::ModelEdgeRefinerVarying(ma::Mesh* m) : len_map(3, std::map<int, double> {}), rat_map(3, std::map<int, double> {}), IdentitySizeField(m), split_target(1.5), coarse_target(0.5) {
gmi_model* mdl = m->getModel();
struct gmi_iter* it_gmi;
struct gmi_ent* e_gmi;
struct gmi_set* s_gmi;
apf::MeshEntity* e;
for(int dim = 1; dim < 4; dim++) {
apf::MeshIterator* it = m->begin(dim);
while ((e = m->iterate(it))) {
apf::ModelEntity* mdl_curr = m->toModel(e);
int c_type = m->getModelType(mdl_curr);
int c_tag = m->getModelTag(mdl_curr);
double meas_curr = vd_meas_ent(m, e);
len_map.at(c_type - 1)[c_tag] = len_map.at(c_type - 1)[c_tag] + meas_curr;
}
m->end(it);
}
double pow[3] = {1., 0.5, 1.0/3};
double coef[3] = {1./2, 1./8, 1./16};
for(int dim = 1; dim < 4; dim++) {
it_gmi = gmi_begin(mdl, dim);
while ((e_gmi = gmi_next(mdl, it_gmi))) {
int c_tag = gmi_tag(mdl,e_gmi);
len_map.at(dim - 1)[c_tag] = std::pow(len_map.at(dim - 1)[c_tag]*coef[dim-1], pow[dim-1]);
rat_map.at(dim - 1)[c_tag] = 1;
}
gmi_end(mdl, it_gmi);
}
}
// Set the rat_map for boundary cells such that they are refined to yield edge
// length len.
void ModelEdgeRefinerVarying::set_all_cell(double len) {
gmi_model* mdl = mesh->getModel();
struct gmi_iter* it_gmi;
struct gmi_ent* e_gmi;
struct gmi_set* s_gmi;
for(int dim = 1; dim < 4; dim++) {
it_gmi = gmi_begin(mdl, dim);
while ((e_gmi = gmi_next(mdl, it_gmi))) {
int c_tag = gmi_tag(mdl,e_gmi);
rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len;
}
gmi_end(mdl, it_gmi);
}
}
// Set the rat_map for boundary cells such that they are refined to yield edge
// length len.
void ModelEdgeRefinerVarying::set_bound_cell(double len,
std::vector<std::pair<int,int> >* cells) {
if(cells != NULL) {
for(int i = 0; i < cells->size(); i++) {
int dim = cells->at(i).first;
int c_tag = cells->at(i).second;
rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len;
}
}
else {
gmi_model* mdl = mesh->getModel();
struct gmi_iter* it_gmi;
struct gmi_ent* e_gmi;
struct gmi_set* s_gmi;
for(int dim = 1; dim < 3; dim++) {
it_gmi = gmi_begin(mdl, dim);
while ((e_gmi = gmi_next(mdl, it_gmi))) {
int c_tag = gmi_tag(mdl,e_gmi);
rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len;
}
gmi_end(mdl, it_gmi);
}
}
}
double ModelEdgeRefinerVarying::measure_dist(ma::Entity* edge) {
// TODO Use integrators of apf to integrate the field directly. For linear
// elements and for isotropic metrics, it is equivalent.
apf::MeshElement* me = apf::createMeshElement(mesh, edge);
double len = measure(edge);
apf::destroyMeshElement(me);
apf::ModelEntity* mdl = mesh->toModel(edge);
int dim_e = mesh->getModelType(mdl);
int tag_e = mesh->getModelTag(mdl);
if(len_map.at(dim_e - 1)[tag_e] < std::numeric_limits<double>::min())
return len;
return len/len_map.at(dim_e - 1)[tag_e]*rat_map.at(dim_e - 1)[tag_e];
}
bool ModelEdgeRefinerVarying::shouldCollapse(ma::Entity* edge) {
return this->measure_dist(edge) < coarse_target;
}
bool ModelEdgeRefinerVarying::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
//double v0 = apf::getScalar(field_step, d_v[0], 0);
//double v1 = apf::getScalar(field_step, d_v[1], 0);
//double len = vd_meas_ent(mesh, edge);
//return (1 > v0) or (1 > v1);
//return (2*len > v0) or (2*len > v1);
//return (len > v0/4+v1/4);
if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
}
return this->measure_dist(edge) > split_target;
}
void ModelEdgeRefinerVarying::set_target_th(double coarse_in, double split_in) {
split_target = split_in;
coarse_target = coarse_in;
}
ModelEdgeRefinerVarying::~ModelEdgeRefinerVarying() {
for(int i = 0; i < 3; i++) {
len_map.at(i).clear();
}
len_map.clear();
}
////////////////////////////
// STEP
////////////////////////////
Step::Step(ma::Mesh* m, double sz) {
if(sz > std::numeric_limits<double>::min())
sizing = sz;
else
sizing = 1;
mesh = m;
average = ma::getAverageEdgeLength(m);
field_step = m->findField("adapt_step");
assert(field_step);
}
double Step::getValue(ma::Entity* v) {
double dist = apf::getScalar(field_step, v, 0);
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return dist/sizing;
}
Step_ns::Step_ns(ma::Mesh* m, double sz) {
if(sz > std::numeric_limits<double>::min())
sizing = sz;
else
sizing = 1;
mesh = m;
average = ma::getAverageEdgeLength(m);
field_step = m->findField("adapt_step");
assert(field_step);
}
double Step_ns::getValue(ma::Entity* v) {
double dist = apf::getScalar(field_step, v, 0);
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return dist;
}
void vd_adapt_0cell(apf::Mesh2* m, struct cell_base* c) {
std::vector<double> avg_cell(0);
avg_cell = upd_cell_rad(m);
Linear_0cell sf(m, c, &avg_cell);
ma::Input* in = ma::configure(m, &sf);
in->shouldRunPreZoltan = true;
in->shouldRunMidParma = true;
in->shouldRunPostParma = true;
in->shouldRefineLayer = true;
ma::adapt(in);
}
void vd_adapt(apf::Mesh2* m) {
Linear sf(m, 1.1);
ma::Input* in = ma::configure(m, &sf);
in->shouldRunPreZoltan = true;
in->shouldRunMidParma = true;
in->shouldRunPostParma = true;
in->shouldRefineLayer = true;
ma::adapt(in);
}
Linear_0cell::Linear_0cell(ma::Mesh* m, struct cell_base* c,
std::vector<double>* avg_cell_in) :
mesh(NULL), average(0), avg_cell(0), cell0(0),
cell0_pos(0, apf::Vector3(0, 0, 0)),
cnc0(0, std::vector<std::vector<int > > (0, std::vector<int >(0) ) ) {
avg_cell = *avg_cell_in;
mesh = m;
c_base = c;
refresh();
}
void Linear_0cell::reload(ma::Mesh* m, struct cell_base* c,
std::vector<double>* avg_cell_in) {
avg_cell = *avg_cell_in;
mesh = m;
c_base = c;
refresh();
}
double Linear_0cell::getValue(ma::Entity* v) {
return getDistance(v);
//return getDistance(v)*sizing;
}
double Linear_0cell::getDistance(ma::Entity* v) {
double distance = average+1;
double temp_len;
apf::Vector3 e_pos;
apf::Vector3 temp;
mesh->getPoint(v, 0, e_pos);
int ent_type = mesh->getType(v);
int d = mesh->typeDimension[ent_type];
apf::ModelEntity* mdl = mesh->toModel(v);
int c_type = mesh->getModelType(mdl);
int c_tag = mesh->getModelTag(mdl);
//std::cout << c_type << "c" << c_tag << " "
// << d << "-ent" << v << std::endl;
for(int i = 0; i < cnc0.at(c_type).at(c_tag-1).size(); i++) {
int c_id = cnc0.at(c_type).at(c_tag-1).at(i);
if(cell0.at(c_id) != NULL) {
//std::cout << "v " << cell0.at(c_id)
// << " pos " << cell0_pos.at(c_id) << std::endl;
temp = e_pos - cell0_pos.at(c_id);
temp_len = temp.getLength();
if(distance > temp_len);
distance = temp_len;
}
}
if(distance < average) {
//if(c_type == 0)
return distance*0.7;
//else
// return distance;
//return distance*3;
//return average*3;
//return average*exp(-average/distance);
}
else
//return avg_cell.at(c_type-1);
return avg_cell.at(0)*0.7;
//return average;
}
Linear_0cell::~Linear_0cell() {
clear();
}
void Linear_0cell::refresh() {
clear();
load_0cell();
average = ma::getAverageEdgeLength(mesh);
}
void Linear_0cell::load_0cell_ent() {
cell0_pos.resize(c_base->get_sz(0));
cell0.resize(c_base->get_sz(0));
double z[3] = {0,0,0};
for(int i = 0; i < cell0_pos.size(); i++) {
cell0_pos.at(i).fromArray(z);
}
for(int i = 0; i < cell0.size(); i++) {
cell0.at(i) = NULL;
}
apf::MeshIterator* it_e = mesh->begin(0);
//std::cout << "Iterator." << std::endl;
apf::MeshEntity* v;
while (v = mesh->iterate(it_e)) {
apf::ModelEntity* mdl = mesh->toModel(v);
int type = mesh->getModelType(mdl);
int tag = mesh->getModelTag(mdl);
if(type == 0) {
assert(cell0.at(tag-1) == NULL);
cell0.at(tag-1) = v;
}
}
mesh->end(it_e);
}
void Linear_0cell::load_0cell_pos() {
apf::Vector3 vert_pos;
for(int i = 0; i < cell0.size(); i++) {
if(cell0.at(i) != NULL) {
mesh->getPoint(cell0.at(i), 0, vert_pos);
cell0_pos.at(i) = vert_pos;
}
}
}
// TODO very ugly notation.
void Linear_0cell::load_0cell() {
load_0cell_ent();
load_0cell_pos();
cnc0.at(3).resize(c_base->get_sz(3));
cnc0.at(2).resize(c_base->get_sz(2));
cnc0.at(1).resize(c_base->get_sz(1));
cnc0.at(0).resize(c_base->get_sz(0));
struct ent_conn e_cover;
int max_sz = 1;
for(int i = 0; i < cnc0.at(3).size(); i++) {
c_base->get_conn_lower(0, 3, i, &e_cover);
cnc0.at(3).at(i).reserve(e_cover.conn.size());
for(int j = 0; j < e_cover.conn.size(); j++) {
cnc0.at(3).at(i).push_back(e_cover.conn.at(j));
}
if(max_sz < e_cover.conn.size())
max_sz = e_cover.conn.size();
}
for(int i = 0; i < cnc0.at(2).size(); i++) {
cnc0.at(2).at(i).reserve(2*max_sz);
}
for(int i = 0; i < cnc0.at(1).size(); i++) {
cnc0.at(1).at(i).reserve(7*max_sz);
}
for(int i = 0; i < cnc0.at(0).size(); i++) {
c_base->get_conn_dim(0, 0, i, &e_cover);
cnc0.at(0).at(i).reserve(e_cover.conn.size());
for(int j = 0; j < e_cover.conn.size(); j++) {
if(i != e_cover.conn.at(j))
cnc0.at(0).at(i).push_back(e_cover.conn.at(j));
}
}
// Go over 2cell adj. of 3cell, check for 0cell adj of the 3cell in the 0cell
// list of the 2cell.
for(int i = 0; i < cnc0.at(3).size(); i++) {
//std::cout << "3c-" << i + 1 << std::endl;
c_base->get_conn_lower(2, 3, i, &e_cover);
for(int j = 0; j < e_cover.conn.size(); j++) {
//std::cout << "2c-" << e_cover.conn.at(j) + 1 << std::endl;
for(int k = 0; k < cnc0.at(3).at(i).size(); k++) {
std::vector<int>::iterator c_st;
std::vector<int>::iterator c_end;
c_st = cnc0.at(2).at(e_cover.conn.at(j)).begin();
c_end = cnc0.at(2).at(e_cover.conn.at(j)).end();
int c0 = cnc0.at(3).at(i).at(k);
//std::cout << "0c-" << c0 + 1 << ", "
// << (std::find(c_st, c_end, c0) != c_end) << ", ";
if(std::find(c_st, c_end, c0) == c_end) {
cnc0.at(2).at(e_cover.conn.at(j)).push_back(c0);
}
}
//std::cout << std::endl;
}
//std::cout << std::endl;
c_base->get_conn_lower(1, 3, i, &e_cover);
for(int j = 0; j < e_cover.conn.size(); j++) {
for(int k = 0; k < cnc0.at(3).at(i).size(); k++) {
std::vector<int>::iterator c_st;
std::vector<int>::iterator c_end;
c_st = cnc0.at(1).at(e_cover.conn.at(j)).begin();
c_end = cnc0.at(1).at(e_cover.conn.at(j)).end();
int c0 = cnc0.at(3).at(i).at(k);
if(std::find(c_st, c_end, c0) == c_end) {
cnc0.at(1).at(e_cover.conn.at(j)).push_back(c0);
}
}
}
}
for(int i = 0; i < cnc0.size(); i++) {
for(int j = 0; j < cnc0.at(i).size(); j++) {
//std::cout << i << "c" << j+1 << std::endl;
for(int k = 0; k < cnc0.at(i).at(j).size(); k++) {
//std::cout << "0" << "c" << cnc0.at(i).at(j).at(k) + 1 << ", ";
}
//std::cout << std::endl;
}
}
}
void Linear_0cell::clear() {
dummy_clear_stop();
cell0_pos.clear();
for(int i = 0; i < cnc0.size(); i++) {
for(int j = 0; j < cnc0.at(i).size(); j++) {
cnc0.at(i).at(j).clear();
}
cnc0.at(i).clear();
}
cnc0.clear();
cnc0.resize(4);
}
| 53,037 | 21,743 |
#include "egpch.h"
#include "ScriptEngineRegistry.h"
#include "ScriptEngine.h"
#include "ScriptWrappers.h"
#include "Eagle/Components/Components.h"
#include "Eagle/Core/Entity.h"
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
namespace Eagle
{
std::unordered_map<MonoType*, std::function<void(Entity&)>> m_AddComponentFunctions;
std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_HasComponentFunctions;
//SceneComponents
std::unordered_map<MonoType*, std::function<void(Entity&, const Transform*)>> m_SetWorldTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, const Transform*)>> m_SetRelativeTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, Transform*)>> m_GetWorldTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, Transform*)>> m_GetRelativeTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetForwardVectorFunctions;
//Light Component
std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetLightColorFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetLightColorFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetAmbientFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetAmbientFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetSpecularFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetSpecularFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, bool)>> m_SetAffectsWorldFunctions;
std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_GetAffectsWorldFunctions;
//BaseColliderComponent
std::unordered_map<MonoType*, std::function<void(Entity&, bool)>> m_SetIsTriggerFunctions;
std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_IsTriggerFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetStaticFrictionFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetDynamicFrictionFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetBouncinessFrictionFunctions;
std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetStaticFrictionFunctions;
std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetDynamicFrictionFunctions;
std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetBouncinessFunctions;
extern MonoImage* s_CoreAssemblyImage;
#define REGISTER_COMPONENT_TYPE(Type)\
{\
MonoType* type = mono_reflection_type_from_name("Eagle." #Type, s_CoreAssemblyImage);\
if (type)\
{\
m_HasComponentFunctions[type] = [](Entity& entity) { return entity.HasComponent<Type>(); };\
m_AddComponentFunctions[type] = [](Entity& entity) { entity.AddComponent<Type>(); };\
\
if (std::is_base_of<SceneComponent, Type>::value)\
{\
m_SetWorldTransformFunctions[type] = [](Entity& entity, const Transform* transform) { ((SceneComponent&)entity.GetComponent<Type>()).SetWorldTransform(*transform); };\
m_SetRelativeTransformFunctions[type] = [](Entity& entity, const Transform* transform) { ((SceneComponent&)entity.GetComponent<Type>()).SetRelativeTransform(*transform); };\
\
m_GetWorldTransformFunctions[type] = [](Entity& entity, Transform* transform) { *transform = ((SceneComponent&)entity.GetComponent<Type>()).GetWorldTransform(); };\
m_GetRelativeTransformFunctions[type] = [](Entity& entity, Transform* transform) { *transform = ((SceneComponent&)entity.GetComponent<Type>()).GetRelativeTransform(); };\
m_GetForwardVectorFunctions[type] = [](Entity& entity, glm::vec3* outVector) { *outVector = ((SceneComponent&)entity.GetComponent<Type>()).GetForwardVector(); };\
}\
\
if (std::is_base_of<LightComponent, Type>::value)\
{\
m_SetLightColorFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).LightColor = *value; };\
m_GetLightColorFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).LightColor; };\
\
m_SetAmbientFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).Ambient = *value; };\
m_GetAmbientFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).Ambient; };\
\
m_SetSpecularFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).Specular = *value; };\
m_GetSpecularFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).Specular; };\
\
m_SetAffectsWorldFunctions[type] = [](Entity& entity, bool value) { ((LightComponent&)entity.GetComponent<Type>()).bAffectsWorld = value; };\
m_GetAffectsWorldFunctions[type] = [](Entity& entity) { return ((LightComponent&)entity.GetComponent<Type>()).bAffectsWorld; };\
}\
if (std::is_base_of<BaseColliderComponent, Type>::value)\
{\
m_SetIsTriggerFunctions[type] = [](Entity& entity, bool bTrigger) { ((BaseColliderComponent&)entity.GetComponent<Type>()).SetIsTrigger(bTrigger); };\
m_IsTriggerFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).IsTrigger(); };\
m_SetStaticFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->StaticFriction = value; comp.SetPhysicsMaterial(mat); };\
m_SetDynamicFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->DynamicFriction = value; comp.SetPhysicsMaterial(mat); };\
m_SetBouncinessFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->Bounciness = value; comp.SetPhysicsMaterial(mat); };\
m_GetStaticFrictionFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->StaticFriction; };\
m_GetDynamicFrictionFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->DynamicFriction; };\
m_GetBouncinessFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->Bounciness; };\
}\
}\
else\
EG_CORE_ERROR("No C# Component found for " #Type "!");\
}
static void InitComponentTypes()
{
REGISTER_COMPONENT_TYPE(TransformComponent);
REGISTER_COMPONENT_TYPE(SceneComponent);
REGISTER_COMPONENT_TYPE(PointLightComponent);
REGISTER_COMPONENT_TYPE(DirectionalLightComponent);
REGISTER_COMPONENT_TYPE(SpotLightComponent);
REGISTER_COMPONENT_TYPE(StaticMeshComponent);
REGISTER_COMPONENT_TYPE(AudioComponent);
REGISTER_COMPONENT_TYPE(RigidBodyComponent);
REGISTER_COMPONENT_TYPE(BoxColliderComponent);
REGISTER_COMPONENT_TYPE(SphereColliderComponent);
REGISTER_COMPONENT_TYPE(CapsuleColliderComponent);
REGISTER_COMPONENT_TYPE(MeshColliderComponent);
}
void ScriptEngineRegistry::RegisterAll()
{
InitComponentTypes();
//Entity
mono_add_internal_call("Eagle.Entity::GetParent_Native", Eagle::Script::Eagle_Entity_GetParent);
mono_add_internal_call("Eagle.Entity::SetParent_Native", Eagle::Script::Eagle_Entity_SetParent);
mono_add_internal_call("Eagle.Entity::GetChildren_Native", Eagle::Script::Eagle_Entity_GetChildren);
mono_add_internal_call("Eagle.Entity::CreateEntity_Native", Eagle::Script::Eagle_Entity_CreateEntity);
mono_add_internal_call("Eagle.Entity::DestroyEntity_Native", Eagle::Script::Eagle_Entity_DestroyEntity);
mono_add_internal_call("Eagle.Entity::AddComponent_Native", Eagle::Script::Eagle_Entity_AddComponent);
mono_add_internal_call("Eagle.Entity::HasComponent_Native", Eagle::Script::Eagle_Entity_HasComponent);
mono_add_internal_call("Eagle.Entity::GetEntityName_Native", Eagle::Script::Eagle_Entity_GetEntityName);
mono_add_internal_call("Eagle.Entity::GetForwardVector_Native", Eagle::Script::Eagle_Entity_GetForwardVector);
mono_add_internal_call("Eagle.Entity::GetRightVector_Native", Eagle::Script::Eagle_Entity_GetRightVector);
mono_add_internal_call("Eagle.Entity::GetUpVector_Native", Eagle::Script::Eagle_Entity_GetUpVector);
//Entity-Physics
mono_add_internal_call("Eagle.Entity::WakeUp_Native", Eagle::Script::Eagle_Entity_WakeUp);
mono_add_internal_call("Eagle.Entity::PutToSleep_Native", Eagle::Script::Eagle_Entity_PutToSleep);
mono_add_internal_call("Eagle.Entity::GetMass_Native", Eagle::Script::Eagle_Entity_GetMass);
mono_add_internal_call("Eagle.Entity::SetMass_Native", Eagle::Script::Eagle_Entity_SetMass);
mono_add_internal_call("Eagle.Entity::AddForce_Native", Eagle::Script::Eagle_Entity_AddForce);
mono_add_internal_call("Eagle.Entity::AddTorque_Native", Eagle::Script::Eagle_Entity_AddTorque);
mono_add_internal_call("Eagle.Entity::GetLinearVelocity_Native", Eagle::Script::Eagle_Entity_GetLinearVelocity);
mono_add_internal_call("Eagle.Entity::SetLinearVelocity_Native", Eagle::Script::Eagle_Entity_SetLinearVelocity);
mono_add_internal_call("Eagle.Entity::GetAngularVelocity_Native", Eagle::Script::Eagle_Entity_GetAngularVelocity);
mono_add_internal_call("Eagle.Entity::SetAngularVelocity_Native", Eagle::Script::Eagle_Entity_SetAngularVelocity);
mono_add_internal_call("Eagle.Entity::GetMaxLinearVelocity_Native", Eagle::Script::Eagle_Entity_GetMaxLinearVelocity);
mono_add_internal_call("Eagle.Entity::SetMaxLinearVelocity_Native", Eagle::Script::Eagle_Entity_SetMaxLinearVelocity);
mono_add_internal_call("Eagle.Entity::GetMaxAngularVelocity_Native", Eagle::Script::Eagle_Entity_GetMaxAngularVelocity);
mono_add_internal_call("Eagle.Entity::SetMaxAngularVelocity_Native", Eagle::Script::Eagle_Entity_SetMaxAngularVelocity);
mono_add_internal_call("Eagle.Entity::SetLinearDamping_Native", Eagle::Script::Eagle_Entity_SetLinearDamping);
mono_add_internal_call("Eagle.Entity::SetAngularDamping_Native", Eagle::Script::Eagle_Entity_SetAngularDamping);
mono_add_internal_call("Eagle.Entity::IsDynamic_Native", Eagle::Script::Eagle_Entity_IsDynamic);
mono_add_internal_call("Eagle.Entity::IsKinematic_Native", Eagle::Script::Eagle_Entity_IsKinematic);
mono_add_internal_call("Eagle.Entity::IsGravityEnabled_Native", Eagle::Script::Eagle_Entity_IsGravityEnabled);
mono_add_internal_call("Eagle.Entity::IsLockFlagSet_Native", Eagle::Script::Eagle_Entity_IsLockFlagSet);
mono_add_internal_call("Eagle.Entity::GetLockFlags_Native", Eagle::Script::Eagle_Entity_GetLockFlags);
mono_add_internal_call("Eagle.Entity::SetKinematic_Native", Eagle::Script::Eagle_Entity_SetKinematic);
mono_add_internal_call("Eagle.Entity::SetGravityEnabled_Native", Eagle::Script::Eagle_Entity_SetGravityEnabled);
mono_add_internal_call("Eagle.Entity::SetLockFlag_Native", Eagle::Script::Eagle_Entity_SetLockFlag);
//Input
mono_add_internal_call("Eagle.Input::IsMouseButtonPressed_Native", Eagle::Script::Eagle_Input_IsMouseButtonPressed);
mono_add_internal_call("Eagle.Input::IsKeyPressed_Native", Eagle::Script::Eagle_Input_IsKeyPressed);
mono_add_internal_call("Eagle.Input::GetMousePosition_Native", Eagle::Script::Eagle_Input_GetMousePosition);
mono_add_internal_call("Eagle.Input::SetCursorMode_Native", Eagle::Script::Eagle_Input_SetCursorMode);
mono_add_internal_call("Eagle.Input::GetCursorMode_Native", Eagle::Script::Eagle_Input_GetCursorMode);
//TransformComponent
mono_add_internal_call("Eagle.TransformComponent::GetWorldTransform_Native", Eagle::Script::Eagle_TransformComponent_GetWorldTransform);
mono_add_internal_call("Eagle.TransformComponent::GetWorldLocation_Native", Eagle::Script::Eagle_TransformComponent_GetWorldLocation);
mono_add_internal_call("Eagle.TransformComponent::GetWorldRotation_Native", Eagle::Script::Eagle_TransformComponent_GetWorldRotation);
mono_add_internal_call("Eagle.TransformComponent::GetWorldScale_Native", Eagle::Script::Eagle_TransformComponent_GetWorldScale);
mono_add_internal_call("Eagle.TransformComponent::SetWorldTransform_Native", Eagle::Script::Eagle_TransformComponent_SetWorldTransform);
mono_add_internal_call("Eagle.TransformComponent::SetWorldLocation_Native", Eagle::Script::Eagle_TransformComponent_SetWorldLocation);
mono_add_internal_call("Eagle.TransformComponent::SetWorldRotation_Native", Eagle::Script::Eagle_TransformComponent_SetWorldRotation);
mono_add_internal_call("Eagle.TransformComponent::SetWorldScale_Native", Eagle::Script::Eagle_TransformComponent_SetWorldScale);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeTransform_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeTransform);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeLocation_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeLocation);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeRotation_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeRotation);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeScale_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeScale);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeTransform_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeTransform);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeLocation_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeLocation);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeRotation_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeRotation);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeScale_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeScale);
//Scene Component
mono_add_internal_call("Eagle.SceneComponent::GetWorldTransform_Native", Eagle::Script::Eagle_SceneComponent_GetWorldTransform);
mono_add_internal_call("Eagle.SceneComponent::GetWorldLocation_Native", Eagle::Script::Eagle_SceneComponent_GetWorldLocation);
mono_add_internal_call("Eagle.SceneComponent::GetWorldRotation_Native", Eagle::Script::Eagle_SceneComponent_GetWorldRotation);
mono_add_internal_call("Eagle.SceneComponent::GetWorldScale_Native", Eagle::Script::Eagle_SceneComponent_GetWorldScale);
mono_add_internal_call("Eagle.SceneComponent::SetWorldTransform_Native", Eagle::Script::Eagle_SceneComponent_SetWorldTransform);
mono_add_internal_call("Eagle.SceneComponent::SetWorldLocation_Native", Eagle::Script::Eagle_SceneComponent_SetWorldLocation);
mono_add_internal_call("Eagle.SceneComponent::SetWorldRotation_Native", Eagle::Script::Eagle_SceneComponent_SetWorldRotation);
mono_add_internal_call("Eagle.SceneComponent::SetWorldScale_Native", Eagle::Script::Eagle_SceneComponent_SetWorldScale);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeTransform_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeTransform);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeLocation_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeLocation);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeRotation_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeRotation);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeScale_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeScale);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeTransform_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeTransform);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeLocation_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeLocation);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeRotation_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeRotation);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeScale_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeScale);
mono_add_internal_call("Eagle.SceneComponent::GetForwardVector_Native", Eagle::Script::Eagle_SceneComponent_GetForwardVector);
//Light Component
mono_add_internal_call("Eagle.LightComponent::GetLightColor_Native", Eagle::Script::Eagle_LightComponent_GetLightColor);
mono_add_internal_call("Eagle.LightComponent::GetAmbientColor_Native", Eagle::Script::Eagle_LightComponent_GetAmbientColor);
mono_add_internal_call("Eagle.LightComponent::GetSpecularColor_Native", Eagle::Script::Eagle_LightComponent_GetSpecularColor);
mono_add_internal_call("Eagle.LightComponent::GetAffectsWorld_Native", Eagle::Script::Eagle_LightComponent_GetAffectsWorld);
mono_add_internal_call("Eagle.LightComponent::SetLightColor_Native", Eagle::Script::Eagle_LightComponent_SetLightColor);
mono_add_internal_call("Eagle.LightComponent::SetAmbientColor_Native", Eagle::Script::Eagle_LightComponent_SetAmbientColor);
mono_add_internal_call("Eagle.LightComponent::SetSpecularColor_Native", Eagle::Script::Eagle_LightComponent_SetSpecularColor);
mono_add_internal_call("Eagle.LightComponent::SetAffectsWorld_Native", Eagle::Script::Eagle_LightComponent_SetAffectsWorld);
//PointLight Component
mono_add_internal_call("Eagle.PointLightComponent::GetIntensity_Native", Eagle::Script::Eagle_PointLightComponent_GetIntensity);
mono_add_internal_call("Eagle.PointLightComponent::SetIntensity_Native", Eagle::Script::Eagle_PointLightComponent_SetIntensity);
//DirectionalLight Component
//SpotLight Component
mono_add_internal_call("Eagle.SpotLightComponent::GetInnerCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_GetInnerCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::GetOuterCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_GetOuterCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::SetInnerCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_SetInnerCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::SetOuterCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_SetOuterCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::SetIntensity_Native", Eagle::Script::Eagle_SpotLightComponent_SetIntensity);
mono_add_internal_call("Eagle.SpotLightComponent::GetIntensity_Native", Eagle::Script::Eagle_SpotLightComponent_GetIntensity);
//Texture
mono_add_internal_call("Eagle.Texture::IsValid_Native", Eagle::Script::Eagle_Texture_IsValid);
//Texture2D
mono_add_internal_call("Eagle.Texture2D::Create_Native", Eagle::Script::Eagle_Texture2D_Create);
//Static Mesh
mono_add_internal_call("Eagle.StaticMesh::Create_Native", Eagle::Script::Eagle_StaticMesh_Create);
mono_add_internal_call("Eagle.StaticMesh::IsValid_Native", Eagle::Script::Eagle_StaticMesh_IsValid);
mono_add_internal_call("Eagle.StaticMesh::SetDiffuseTexture_Native", Eagle::Script::Eagle_StaticMesh_SetDiffuseTexture);
mono_add_internal_call("Eagle.StaticMesh::SetSpecularTexture_Native", Eagle::Script::Eagle_StaticMesh_SetSpecularTexture);
mono_add_internal_call("Eagle.StaticMesh::SetNormalTexture_Native", Eagle::Script::Eagle_StaticMesh_SetNormalTexture);
mono_add_internal_call("Eagle.StaticMesh::SetScalarMaterialParams_Native", Eagle::Script::Eagle_StaticMesh_SetScalarMaterialParams);
mono_add_internal_call("Eagle.StaticMesh::GetMaterial_Native", Eagle::Script::Eagle_StaticMesh_GetMaterial);
//StaticMeshComponent
mono_add_internal_call("Eagle.StaticMeshComponent::SetMesh_Native", Eagle::Script::Eagle_StaticMeshComponent_SetMesh);
mono_add_internal_call("Eagle.StaticMeshComponent::GetMesh_Native", Eagle::Script::Eagle_StaticMeshComponent_GetMesh);
//Sound
mono_add_internal_call("Eagle.Sound2D::Play_Native", Eagle::Script::Eagle_Sound2D_Play);
mono_add_internal_call("Eagle.Sound3D::Play_Native", Eagle::Script::Eagle_Sound3D_Play);
//AudioComponent
mono_add_internal_call("Eagle.AudioComponent::SetMinDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMinDistance);
mono_add_internal_call("Eagle.AudioComponent::SetMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMaxDistance);
mono_add_internal_call("Eagle.AudioComponent::SetMinMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMinMaxDistance);
mono_add_internal_call("Eagle.AudioComponent::SetRollOffModel_Native", Eagle::Script::Eagle_AudioComponent_SetRollOffModel);
mono_add_internal_call("Eagle.AudioComponent::SetVolume_Native", Eagle::Script::Eagle_AudioComponent_SetVolume);
mono_add_internal_call("Eagle.AudioComponent::SetLoopCount_Native", Eagle::Script::Eagle_AudioComponent_SetLoopCount);
mono_add_internal_call("Eagle.AudioComponent::SetLooping_Native", Eagle::Script::Eagle_AudioComponent_SetLooping);
mono_add_internal_call("Eagle.AudioComponent::SetMuted_Native", Eagle::Script::Eagle_AudioComponent_SetMuted);
mono_add_internal_call("Eagle.AudioComponent::SetSound_Native", Eagle::Script::Eagle_AudioComponent_SetSound);
mono_add_internal_call("Eagle.AudioComponent::SetStreaming_Native", Eagle::Script::Eagle_AudioComponent_SetStreaming);
mono_add_internal_call("Eagle.AudioComponent::Play_Native", Eagle::Script::Eagle_AudioComponent_Play);
mono_add_internal_call("Eagle.AudioComponent::Stop_Native", Eagle::Script::Eagle_AudioComponent_Stop);
mono_add_internal_call("Eagle.AudioComponent::SetPaused_Native", Eagle::Script::Eagle_AudioComponent_SetPaused);
mono_add_internal_call("Eagle.AudioComponent::GetMinDistance_Native", Eagle::Script::Eagle_AudioComponent_GetMinDistance);
mono_add_internal_call("Eagle.AudioComponent::GetMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_GetMaxDistance);
mono_add_internal_call("Eagle.AudioComponent::GetRollOffModel_Native", Eagle::Script::Eagle_AudioComponent_GetRollOffModel);
mono_add_internal_call("Eagle.AudioComponent::GetVolume_Native", Eagle::Script::Eagle_AudioComponent_GetVolume);
mono_add_internal_call("Eagle.AudioComponent::GetLoopCount_Native", Eagle::Script::Eagle_AudioComponent_GetLoopCount);
mono_add_internal_call("Eagle.AudioComponent::IsLooping_Native", Eagle::Script::Eagle_AudioComponent_IsLooping);
mono_add_internal_call("Eagle.AudioComponent::IsMuted_Native", Eagle::Script::Eagle_AudioComponent_IsMuted);
mono_add_internal_call("Eagle.AudioComponent::IsStreaming_Native", Eagle::Script::Eagle_AudioComponent_IsStreaming);
mono_add_internal_call("Eagle.AudioComponent::IsPlaying_Native", Eagle::Script::Eagle_AudioComponent_IsPlaying);
//RigidBodyComponent
mono_add_internal_call("Eagle.RigidBodyComponent::SetMass_Native", Eagle::Script::Eagle_RigidBodyComponent_SetMass);
mono_add_internal_call("Eagle.RigidBodyComponent::GetMass_Native", Eagle::Script::Eagle_RigidBodyComponent_GetMass);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLinearDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLinearDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::GetLinearDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_GetLinearDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::SetAngularDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_SetAngularDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::GetAngularDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_GetAngularDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::SetEnableGravity_Native", Eagle::Script::Eagle_RigidBodyComponent_SetEnableGravity);
mono_add_internal_call("Eagle.RigidBodyComponent::IsGravityEnabled_Native", Eagle::Script::Eagle_RigidBodyComponent_IsGravityEnabled);
mono_add_internal_call("Eagle.RigidBodyComponent::SetIsKinematic_Native", Eagle::Script::Eagle_RigidBodyComponent_SetIsKinematic);
mono_add_internal_call("Eagle.RigidBodyComponent::IsKinematic_Native", Eagle::Script::Eagle_RigidBodyComponent_IsKinematic);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPosition_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPosition);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionX_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionX);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionY_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionY);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionZ_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionZ);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotation_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotation);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationX_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationX);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationY_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationY);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationZ_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationZ);
mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionXLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionXLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionYLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionYLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionZLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionZLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationXLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationXLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationYLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationYLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationZLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationZLocked);
//BaseColliderComponent
mono_add_internal_call("Eagle.BaseColliderComponent::SetIsTrigger_Native", Eagle::Script::Eagle_BaseColliderComponent_SetIsTrigger);
mono_add_internal_call("Eagle.BaseColliderComponent::IsTrigger_Native", Eagle::Script::Eagle_BaseColliderComponent_IsTrigger);
mono_add_internal_call("Eagle.BaseColliderComponent::SetStaticFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_SetStaticFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::SetDynamicFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_SetDynamicFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::SetBounciness_Native", Eagle::Script::Eagle_BaseColliderComponent_SetBounciness);
mono_add_internal_call("Eagle.BaseColliderComponent::GetStaticFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_GetStaticFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::GetDynamicFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_GetDynamicFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::GetBounciness_Native", Eagle::Script::Eagle_BaseColliderComponent_GetBounciness);
//BoxColliderComponent
mono_add_internal_call("Eagle.BoxColliderComponent::SetSize_Native", Eagle::Script::Eagle_BoxColliderComponent_SetSize);
mono_add_internal_call("Eagle.BoxColliderComponent::GetSize_Native", Eagle::Script::Eagle_BoxColliderComponent_GetSize);
//SphereColliderComponent
mono_add_internal_call("Eagle.SphereColliderComponent::SetRadius_Native", Eagle::Script::Eagle_SphereColliderComponent_SetRadius);
mono_add_internal_call("Eagle.SphereColliderComponent::GetRadius_Native", Eagle::Script::Eagle_SphereColliderComponent_GetRadius);
//CapsuleColliderComponent
mono_add_internal_call("Eagle.CapsuleColliderComponent::SetRadius_Native", Eagle::Script::Eagle_CapsuleColliderComponent_SetRadius);
mono_add_internal_call("Eagle.CapsuleColliderComponent::GetRadius_Native", Eagle::Script::Eagle_CapsuleColliderComponent_GetRadius);
mono_add_internal_call("Eagle.CapsuleColliderComponent::SetHeight_Native", Eagle::Script::Eagle_CapsuleColliderComponent_SetHeight);
mono_add_internal_call("Eagle.CapsuleColliderComponent::GetHeight_Native", Eagle::Script::Eagle_CapsuleColliderComponent_GetHeight);
//MeshColliderComponent
mono_add_internal_call("Eagle.MeshColliderComponent::SetIsConvex_Native", Eagle::Script::Eagle_MeshColliderComponent_SetIsConvex);
mono_add_internal_call("Eagle.MeshColliderComponent::IsConvex_Native", Eagle::Script::Eagle_MeshColliderComponent_IsConvex);
mono_add_internal_call("Eagle.MeshColliderComponent::SetCollisionMesh_Native", Eagle::Script::Eagle_MeshColliderComponent_SetCollisionMesh);
mono_add_internal_call("Eagle.MeshColliderComponent::GetCollisionMesh_Native", Eagle::Script::Eagle_MeshColliderComponent_GetCollisionMesh);
}
}
| 28,923 | 9,829 |
#include "socket.h"
#include <sys/socket.h>
client::Socket::Socket() {}
| 73 | 28 |
//
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include "Poco/JSON/Parser.h"
#include "RESTAPI_oauth2Handler.h"
#include "uAuthService.h"
void RESTAPI_oauth2Handler::handleRequest(Poco::Net::HTTPServerRequest & Request, Poco::Net::HTTPServerResponse & Response)
{
if(!ContinueProcessing(Request,Response))
return;
try {
if (Request.getMethod() == Poco::Net::HTTPServerRequest::HTTP_POST) {
// Extract the info for login...
Poco::JSON::Parser parser;
Poco::JSON::Object::Ptr Obj = parser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
Poco::DynamicStruct ds = *Obj;
auto userId = ds["userId"].toString();
auto password = ds["password"].toString();
uCentral::Objects::WebToken Token;
if (uCentral::Auth::Authorize(userId, password, Token)) {
Poco::JSON::Object ReturnObj;
Token.to_json(ReturnObj);
ReturnObject(ReturnObj, Response);
} else {
UnAuthorized(Response);
}
} else if (Request.getMethod() == Poco::Net::HTTPServerRequest::HTTP_DELETE) {
if (!IsAuthorized(Request, Response))
return;
auto Token = GetBinding("token", "...");
if (Token == SessionToken_)
uCentral::Auth::Logout(Token);
OK(Response);
}
return;
}
catch (const Poco::Exception &E) {
Logger_.warning(Poco::format( "%s: Failed with: %s" , std::string(__func__), E.displayText()));
}
BadRequest(Response);
} | 1,790 | 544 |
// Copyright 2015 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 "core/layout/ViewFragmentationContext.h"
#include "core/layout/LayoutView.h"
namespace blink {
bool ViewFragmentationContext::isFragmentainerLogicalHeightKnown()
{
ASSERT(m_view.pageLogicalHeight());
return true;
}
LayoutUnit ViewFragmentationContext::fragmentainerLogicalHeightAt(LayoutUnit)
{
ASSERT(m_view.pageLogicalHeight());
return m_view.pageLogicalHeight();
}
LayoutUnit ViewFragmentationContext::remainingLogicalHeightAt(LayoutUnit blockOffset)
{
LayoutUnit pageLogicalHeight = m_view.pageLogicalHeight();
return pageLogicalHeight - intMod(blockOffset, pageLogicalHeight);
}
} // namespace blink
| 810 | 248 |
/* $Id: tstRTSemEventMulti.cpp $ */
/** @file
* IPRT Testcase - Multiple Release Event Semaphores.
*/
/*
* Copyright (C) 2009-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include <iprt/semaphore.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/rand.h>
#include <iprt/stream.h>
#include <iprt/string.h>
#include <iprt/test.h>
#include <iprt/thread.h>
#include <iprt/time.h>
/*********************************************************************************************************************************
* Global Variables *
*********************************************************************************************************************************/
/** The test handle. */
static RTTEST g_hTest;
static DECLCALLBACK(int) test1Thread1(RTTHREAD ThreadSelf, void *pvUser)
{
RTSEMEVENTMULTI hSem = *(PRTSEMEVENTMULTI)pvUser;
RT_NOREF_PV(ThreadSelf);
uint64_t u64 = RTTimeSystemMilliTS();
RTTEST_CHECK_RC(g_hTest, RTSemEventMultiWait(hSem, 1000), VERR_TIMEOUT);
u64 = RTTimeSystemMilliTS() - u64;
RTTEST_CHECK_MSG(g_hTest, u64 < 1500 && u64 > 950, (g_hTest, "u64=%llu\n", u64));
RTTEST_CHECK_RC(g_hTest, RTSemEventMultiWait(hSem, 2000), VINF_SUCCESS);
return VINF_SUCCESS;
}
static DECLCALLBACK(int) test1Thread2(RTTHREAD ThreadSelf, void *pvUser)
{
RTSEMEVENTMULTI hSem = *(PRTSEMEVENTMULTI)pvUser;
RT_NOREF_PV(ThreadSelf);
RTTEST_CHECK_RC(g_hTest, RTSemEventMultiWait(hSem, RT_INDEFINITE_WAIT), VINF_SUCCESS);
return VINF_SUCCESS;
}
static void test1(void)
{
RTTestISub("Three threads");
/*
* Create the threads and let them block on the event multi semaphore.
*/
RTSEMEVENTMULTI hSem;
RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS);
RTTHREAD hThread2;
RTTESTI_CHECK_RC_RETV(RTThreadCreate(&hThread2, test1Thread2, &hSem, 0, RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "test2"), VINF_SUCCESS);
RTThreadSleep(100);
RTTHREAD hThread1;
RTTESTI_CHECK_RC_RETV(RTThreadCreate(&hThread1, test1Thread1, &hSem, 0, RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "test1"), VINF_SUCCESS);
/* Force first thread (which has a timeout of 1 second) to timeout in the
* first wait, and the second wait will succeed. */
RTTESTI_CHECK_RC(RTThreadSleep(1500), VINF_SUCCESS);
RTTESTI_CHECK_RC(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC(RTThreadWait(hThread1, 5000, NULL), VINF_SUCCESS);
RTTESTI_CHECK_RC(RTThreadWait(hThread2, 5000, NULL), VINF_SUCCESS);
RTTESTI_CHECK_RC(RTSemEventMultiDestroy(hSem), VINF_SUCCESS);
}
static void testBasicsWaitTimeout(RTSEMEVENTMULTI hSem, unsigned i)
{
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWait(hSem, 0), VERR_TIMEOUT);
#if 0
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitNoResume(hSem, 0), VERR_TIMEOUT);
#else
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_RELATIVE,
0),
VERR_TIMEOUT);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE,
RTTimeSystemNanoTS() + 1000*i),
VERR_TIMEOUT);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE,
RTTimeNanoTS() + 1000*i),
VERR_TIMEOUT);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_RELATIVE,
0),
VERR_TIMEOUT);
#endif
}
static void testBasicsWaitSuccess(RTSEMEVENTMULTI hSem, unsigned i)
{
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWait(hSem, 0), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWait(hSem, RT_INDEFINITE_WAIT), VINF_SUCCESS);
#if 0
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitNoResume(hSem, 0), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitNoResume(hSem, RT_INDEFINITE_WAIT), VINF_SUCCESS);
#else
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_RELATIVE,
0),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_INDEFINITE, 0), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_NORESUME | RTSEMWAIT_FLAGS_INDEFINITE, 0), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE,
RTTimeSystemNanoTS() + 1000*i),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE,
RTTimeNanoTS() + 1000*i),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE,
0),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE,
_1G),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE,
UINT64_MAX),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE,
RTTimeSystemMilliTS() + 1000*i),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE,
RTTimeMilliTS() + 1000*i),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE,
0),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE,
_1M),
VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem,
RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE,
UINT64_MAX),
VINF_SUCCESS);
#endif
}
static void testBasics(void)
{
RTTestISub("Basics");
RTSEMEVENTMULTI hSem;
RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS);
/* The semaphore is created in a reset state, calling reset explicitly
shouldn't make any difference. */
testBasicsWaitTimeout(hSem, 0);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS);
testBasicsWaitTimeout(hSem, 1);
if (RTTestIErrorCount())
return;
/* When signalling the semaphore all successive wait calls shall
succeed, signalling it again should make no difference. */
RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
testBasicsWaitSuccess(hSem, 2);
if (RTTestIErrorCount())
return;
/* After resetting it we should time out again. */
RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS);
testBasicsWaitTimeout(hSem, 3);
if (RTTestIErrorCount())
return;
/* The number of resets or signal calls shouldn't matter. */
RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS);
testBasicsWaitTimeout(hSem, 4);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
testBasicsWaitSuccess(hSem, 5);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS);
testBasicsWaitTimeout(hSem, 6);
/* Destroy it. */
RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(NIL_RTSEMEVENTMULTI), VINF_SUCCESS);
/* Whether it is reset (above), signalled or not used shouldn't matter. */
RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS);
RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(hSem), VINF_SUCCESS);
RTTestISubDone();
}
int main(int argc, char **argv)
{
RT_NOREF_PV(argc); RT_NOREF_PV(argv);
RTEXITCODE rcExit = RTTestInitAndCreate("tstRTSemEventMulti", &g_hTest);
if (rcExit != RTEXITCODE_SUCCESS)
return rcExit;
testBasics();
if (!RTTestErrorCount(g_hTest))
{
test1();
}
return RTTestSummaryAndDestroy(g_hTest);
}
| 11,982 | 4,350 |