text
stringlengths 5
1.04M
|
|---|
// Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_CONTAINER_INDEX_MAP_HPP_INCLUDED
#define FCPPT_CONTAINER_INDEX_MAP_HPP_INCLUDED
#include <fcppt/container/index_map_decl.hpp>
#include <fcppt/container/index_map_fwd.hpp>
#include <fcppt/container/index_map_impl.hpp>
#endif
|
/**
* This file is part of GEO Project.
* It is subject to the license terms in the LICENSE.md file found in the top-level directory
* of this distribution and at https://github.com/GEO-Project/GEO-Project/blob/master/LICENSE.md
*
* No part of GEO Project, including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE.md file.
*/
#include "ResourcesManager.h"
void ResourcesManager::putResource(
BaseResource::Shared resource) {
attachResourceSignal(
resource);
}
void ResourcesManager::requestPaths(
const TransactionUUID &transactionUUID,
const NodeUUID &contractorUUID) const {
requestPathsResourcesSignal(
transactionUUID,
contractorUUID);
}
|
/******************************************************************************/
/* */
/* Name : LINETBL.CPP */
/* Date : 10/17/1997 */
/* Author : Jim Susoy */
/* Notice : (C) 1997 Qualcomm, Inc. - All Rights Reserved */
/* Copyright (c) 2016, Computer History Museum
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to
the limitations in the disclaimer below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Computer History Museum nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE
COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE. */
/* Desc. : IDSPConfig Implementation */
/* */
/******************************************************************************/
#pragma warning(disable : 4514 4706)
#include <afx.h>
#include <ole2.h>
#include <stdio.h>
#include "DebugNewHelpers.h"
#include "database.h"
#include "QCUtils.h"
#define LINEBUFSZ 0x10000 /* 64K line buffer size */
/* Protected */
HRESULT __stdcall CDatabase::AddLine(LPSTR pszBuf)
{
LPLTBL pTbl = DEBUG_NEW_NOTHROW LTBL;
if(pTbl) {
memset( pTbl, 0, sizeof(LTBL) );
if(NULL == (pTbl->pszLine = SafeStrdupMT(pszBuf))) {
delete pTbl;
return E_OUTOFMEMORY;
}
m_pLineTable->Attach(pTbl);
return S_OK;
}
return E_OUTOFMEMORY;
}
HRESULT __stdcall CDatabase::FoldInTheAddresBookKludge(LPSTR pszFoldedLine)
{
int nLen = lstrlen(pszFoldedLine);
LPLTBL pTbl = (LPLTBL) m_pLineTable->Head();
if(pTbl) {
LPSTR pszSave = NULL;
int oLen = 0;
LPSTR pszNewLine = NULL;
/* Get the "tail" of the list; the last line that was added */
pTbl = (LPLTBL) ILIST_ITEMPREV(pTbl);
/* save off a pointer to it and get it's length */
pszSave = pTbl->pszLine;
oLen = lstrlen(pszSave);
/* Then alloc a buffer for the new combined line */
pszNewLine = DEBUG_NEW_NOTHROW char[nLen+oLen+1];
if(pszNewLine) {
lstrcpy(pszNewLine,pszSave);
lstrcat(pszNewLine,pszFoldedLine);
delete [] pTbl->pszLine;
pTbl->pszLine = pszNewLine;
return S_OK;
}
return E_OUTOFMEMORY;
}
return E_FAIL;
}
HRESULT __stdcall CDatabase::BuildLineTable()
{
HRESULT hErr = E_FAIL;
FILE *hFile = NULL;
LPSTR pszBuf = DEBUG_NEW_NOTHROW char [LINEBUFSZ];
if(!pszBuf)
return E_OUTOFMEMORY;
if(NULL != (hFile = fopen(m_pszPath,"r"))) {
while(NULL != fgets(pszBuf,LINEBUFSZ,hFile)) {
int nLen = lstrlen(pszBuf);
/* Remove CR and LF from data */
nLen--; /* adjust for zero relative */
while(nLen >= 0 && ('\n' == pszBuf[nLen] || '\r' == pszBuf[nLen])) {
pszBuf[nLen] = 0;
nLen--;
}
if(' ' == *pszBuf) {
if(FAILED (hErr = FoldInTheAddresBookKludge(pszBuf))) {
break;
}
}
else if(*pszBuf) {
if(FAILED(hErr = AddLine(pszBuf))) {
break;
}
}
}
fclose(hFile);
}
delete [] pszBuf;
return hErr;
}
|
/**
* Copyright 2020-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <map>
#include <string>
#include <vector>
#include <memory>
#include "ops/real_div.h"
#include "ops/op_utils.h"
#include "utils/check_convert_utils.h"
#include "abstract/primitive_infer_map.h"
namespace mindspore {
namespace ops {
namespace {
abstract::ShapePtr InferShape(const PrimitivePtr &primitive, const std::vector<AbstractBasePtr> &input_args) {
MS_EXCEPTION_IF_NULL(primitive);
auto prim_name = primitive->name();
const int64_t input_num = 2;
(void)CheckAndConvertUtils::CheckInteger("input number", SizeToLong(input_args.size()), kEqual, input_num, prim_name);
for (const auto &item : input_args) {
MS_EXCEPTION_IF_NULL(item);
}
return BroadCastInferShape(prim_name, input_args);
}
TypePtr InferType(const PrimitivePtr &prim, const std::vector<AbstractBasePtr> &input_args) {
MS_EXCEPTION_IF_NULL(prim);
for (const auto &item : input_args) {
MS_EXCEPTION_IF_NULL(item);
}
auto op_name = prim->name();
const int64_t input_num = 2;
(void)CheckAndConvertUtils::CheckInteger("infer", SizeToLong(input_args.size()), kGreaterEqual, input_num, op_name);
std::map<std::string, TypePtr> types;
(void)types.emplace("x", input_args[0]->BuildType());
(void)types.emplace("y", input_args[1]->BuildType());
return CheckAndConvertUtils::CheckTensorTypeSame(types, common_valid_types, prim->name());
}
} // namespace
AbstractBasePtr RealDivInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive,
const std::vector<AbstractBasePtr> &input_args) {
return abstract::MakeAbstract(InferShape(primitive, input_args), InferType(primitive, input_args));
}
REGISTER_PRIMITIVE_C(kNameRealDiv, RealDiv);
} // namespace ops
} // namespace mindspore
|
#include <boost/interprocess/offset_ptr.hpp>
#include "../../util/src/configuration/ImoveConfiguration.hpp"
#include "../../util/src/Projection.hpp"
#include "Scene/Scene.h"
#include "Scene/SceneConfiguration.h"
#include "../../scene_interface_sma/src/PeopleQueue.hpp"
#include "../../peopleextractor_interface_sma/src/SceneframeQueue.hpp"
#include "../../imove/src/Running.hpp"
// Setups people extractor and Scene, can let the Scene run using constant input of people extractor
class ImoveSceneManager {
public:
/**
* Setup people extractor and Scene.
*
* @param calibration The imove configuration
* @param configuration_lighttrail The light trail Scene configuration
**/
ImoveSceneManager(ImoveConfiguration* calibration, const SceneConfiguration& sceneConfig);
// Run the people extractor and Scene frame by frame
void run();
protected:
ImoveConfiguration* calibration;
Projection projection;
Scene* scene = NULL;
std::queue<sf::Image> sceneframe_queue;
// shared memory segment
boost::interprocess::managed_shared_memory* segment;
// People extractor queue
boost::interprocess::offset_ptr<scene_interface_sma::PeopleQueue> si_people_queue;
// Scene frames queue
boost::interprocess::offset_ptr<peopleextractor_interface_sma::SceneframeQueue> pi_sceneframe_queue;
// whole application running
boost::interprocess::offset_ptr<Running> running;
/**
* Receive extracted people from people extractor in shared memory queue and update scene
**/
void receiveExtractedpeopleAndUpdateScene();
static void sendingSceneFrameThread(ImoveSceneManager* imove_scene_manager);
/**
* Send scene frame to people extractor via shared memory queue
**/
void sendingSceneFrame();
};
|
// Implement pow(x,n)
class Solution {
public:
double myPow(double x, int n)
{
double temp;
if( n == 0)
return 1;
temp = myPow(x, n/2);
if (n%2 == 0)
return temp*temp;
else
{
if(n > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
};
|
/*
* Copyright (c) 2020, Alibaba Group Holding Limited
* 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 configuration.cc
* @brief the implement of the configuration
*/
#include <assert.h>
#include <algorithm>
#include "paxos.h"
#include "paxos_configuration.h"
namespace alisql {
void StableConfiguration::forEach(const SideEffect& sideEffect, void *ptr)
{
for (auto& it : servers)
if(it)
sideEffect(*it, ptr);
}
void StableConfiguration::forEachLearners(const SideEffect& sideEffect, void *ptr)
{
for (auto& it : learners)
if(it)
sideEffect(*it, ptr);
}
bool StableConfiguration::quorumAll(const Predicate& predicate) const
{
if (servers.empty())
return true;
uint64_t count = 0;
for (auto& it : servers)
if(it)
if (predicate(*it))
++count;
return (count >= getServerNum() / 2 + 1);
}
uint64_t StableConfiguration::quorumMin(const GetValue& getValue) const
{
if (servers.empty())
return 0;
std::vector<uint64_t> values;
for (auto& it : servers)
if(it)
values.push_back(getValue(*it));
std::sort(values.begin(), values.end());
return values.at((values.size() - 1)/ 2);
}
uint64_t StableConfiguration::forceMin(const GetValue& getValue) const
{
if (servers.empty())
return 0;
uint64_t value= UINT64_MAX;
for (auto& it : servers)
{
if (it && it->forceSync)
{
auto tmp= getValue(*it);
if (tmp < value)
{
value= tmp;
}
}
}
return value;
}
uint64_t StableConfiguration::allMin(const GetValue& getValue) const
{
if (servers.empty())
return 0;
uint64_t value= UINT64_MAX;
for (auto& it : servers)
{
if(it)
{
auto tmp= getValue(*it);
if (tmp < value)
{
value= tmp;
}
}
}
return value;
}
Configuration::ServerRef StableConfiguration::getServer(uint64_t serverId)
{
if (serverId == 0)
return nullptr;
if (serverId < 100)
{
serverId -= 1;
//servers' id start from 1
if (servers.size() > serverId)
return servers[serverId];
else
return nullptr;
}
else // getLearners
{
//learners' id start from 0
/*
serverId -= 100;
if (learners.size() > serverId)
return learners[serverId];
else
return nullptr;
*/
for (auto& learner : learners)
{
if (learner && learner->serverId == serverId)
return learner;
}
return nullptr;
}
}
Configuration::ServerRef StableConfiguration::getLearnerByAddr(const std::string& addr)
{
for (auto& learner : learners)
{
if (learner && getAddr(learner->strAddr) == addr)
return learner;
}
return nullptr;
}
uint64_t StableConfiguration::getServerIdFromAddr(const std::string& addr)
{
for (auto& server : servers)
{
if (server && getAddr(server->strAddr) == addr)
return server->serverId;
}
for (auto& learner : learners)
{
if (learner && getAddr(learner->strAddr) == addr)
return learner->serverId;
}
return 0;
}
void StableConfiguration::installConfig(const std::vector<std::string>& strConfig, uint64_t current, Paxos *paxos, std::shared_ptr<LocalServer> localServer)
{
uint64_t i= 0;
std::shared_ptr<LocalServer> ptrL;
std::shared_ptr<RemoteServer> ptrR;
forEach(&Server::stop, NULL);
servers.clear();
servers.resize(strConfig.size());
for (auto &str : strConfig)
{
++ i;
if (str == "0")
{
/* empty server */
servers[i-1]= nullptr;
continue;
}
serversNum++;
if (i != current)
{
servers[i-1]= (ptrR= std::make_shared<RemoteServer>(i));
initServerFromString(ptrR, str);
ptrR->srv= paxos->getService();
ptrR->paxos= paxos;
ptrR->heartbeatTimer= std::unique_ptr<ThreadTimer>(new ThreadTimer(paxos->getService()->getThreadTimerService(), paxos->getService(), paxos->getHeartbeatTimeout(), ThreadTimer::Repeatable, Paxos::heartbeatCallback, std::move(std::weak_ptr<RemoteServer>(ptrR))));
}
else
{
std::shared_ptr<LocalServer> tmpServer;
tmpServer= localServer ? localServer : std::make_shared<LocalServer>(i);
tmpServer->serverId= i;
servers[i-1]= (ptrL= tmpServer);
initServerFromString(ptrL, str);
paxos->setLocalServer(ptrL);
ptrL->paxos= paxos;
}
}
assert(i == strConfig.size());
}
std::string StableConfiguration::memberToString(ServerRef server)
{
std::string ret("");
ret += server->strAddr;
ret += "#";
ret += server->electionWeight + '0';
ret += server->forceSync ? "F" : "N";
return ret;
}
std::string StableConfiguration::learnerToString(ServerRef server)
{
std::string ret("");
ret += server->strAddr;
ret += "$";
ret += server->learnerSource/10 + '0';
ret += server->learnerSource%10 + '0';
return ret;
}
std::string StableConfiguration::configToString(std::vector<ServerRef>& servers, const std::string& localAddr, bool forceMember)
{
std::string ret("");
uint64_t localIndex= 0, i= 1;
for (auto& server : servers)
{
if (server != nullptr)
{
if (localAddr != "" || forceMember)
{
ret += memberToString(server);
}
else
{
ret += learnerToString(server);
}
ret += ";";
if (localAddr != "" && server->strAddr == localAddr)
localIndex= i;
}
else
{
ret += "0;";
}
++ i;
}
if (i != 1)
{
if (localAddr != "")
{
assert(localIndex != 0);
ret[ret.size() - 1]= '@';
ret += std::to_string(localIndex);
}
else
{
ret.resize(ret.size() - 1);
}
}
return ret;
}
Configuration::ServerRef StableConfiguration::addServer(std::vector<ServerRef>& servers, ServerRef newServer, bool useAppend)
{
uint64_t id= 0;
for (auto& it : servers)
{
++ id;
if (!useAppend && it == nullptr)
{
it= newServer;
newServer->serverId= id;
return newServer;
}
}
++ id;
servers.push_back(newServer);
newServer->serverId= id;
return newServer;
}
void StableConfiguration::initServerFromString(ServerRef server, std::string str, bool isLearner)
{
auto size= str.size();
uint64_t pos= 0;
if (str.at(size -3) == '#')
{
server->forceSync= (str.at(size -1) == 'S');
server->electionWeight= str.at(size -2) - '0';
str.resize(size -3);
}
else if ((pos= str.find('$', 0)) != std::string::npos)
{
uint64_t tmpSource= str.at(pos + 1) - '0';
tmpSource *= 10;
tmpSource += str.at(pos + 2) - '0';
str.resize(pos);
server->learnerSource= tmpSource;
server->forceSync= 0;
server->electionWeight= 5;
}
else
{
server->forceSync= 0;
if (isLearner)
server->electionWeight= 0;
else
server->electionWeight= 5;
}
server->strAddr= str;
}
void StableConfiguration::initServerDefault(ServerRef serverArg)
{
auto server= std::dynamic_pointer_cast<RemoteServer>(serverArg);
server->isLearner= false;
server->forceSync= false;
server->electionWeight= 5;
server->appliedIndex= 0;
}
std::vector<std::string> StableConfiguration::stringToVector(const std::string& str, uint64_t& currentIndex)
{
/* Return obj has already been optimized in C++11. */
/* 127.0.0.1:10001;127.0.0.1:10002;127.0.0.1:10003@1 */
/* 127.0.0.1:10001#9N;127.0.0.1:10002#5N;127.0.0.1:10003#0N@1 */
std::vector<std::string> ret;
uint64_t start=0, stop= 0;
do
{
stop= str.find(';', start);
if (stop == std::string::npos)
break;
/* If learner source is larger than 109, skip this ';', it represents 11. */
if (stop > 1 && str[stop - 1] == '$')
stop= str.find(';', stop + 1);
if (stop == std::string::npos)
break;
ret.push_back(str.substr(start, stop - start));
start= stop + 1;
}
while (stop != std::string::npos);
stop= str.find('@', start);
/* If learner source is larger than 159, skip this '@', it represents 16. */
if (stop == std::string::npos || (stop > 1 && str[stop - 1] == '$'))
{
if (str.size() != 0)
ret.push_back(str.substr(start, stop - start));
}
else
{
ret.push_back(str.substr(start, stop - start));
start= stop + 1;
currentIndex= std::stoull(str.substr(start));
}
return ret;
}
uint64_t StableConfiguration::getServerNum() const
{
uint64_t cnt= 0;
for (auto& it : servers)
if(it)
++cnt;
return cnt;
}
uint64_t StableConfiguration::getLearnerNum() const
{
uint64_t cnt= 0;
for (auto& it : learners)
if(it)
++cnt;
return cnt;
}
bool StableConfiguration::needWeightElection(uint64_t localWeight)
{
for (auto& it : servers)
{
if (it && it->electionWeight > localWeight)
return true;
}
return false;
}
uint64_t StableConfiguration::getMaxWeightServerId(uint64_t baseEpoch, ServerRef localServer)
{
uint64_t ret= localServer->serverId;
uint64_t priv= localServer->electionWeight;
for (auto& it : servers)
{
if (it == nullptr)
continue;
auto lastAckEpoch= it->getLastAckEpoch();
if (it->electionWeight > priv && lastAckEpoch > baseEpoch)
{
ret= it->serverId;
priv= it->electionWeight;
}
}
return ret;
}
int StableConfiguration::addMember(const std::string& strAddr, Paxos *paxos)
{
std::string logBuf= "";
for (auto& server : servers)
{
if (server)
{
logBuf += std::to_string(server->serverId);
logBuf += ":";
logBuf += server->strAddr;
logBuf += " ";
}
}
easy_warn_log("Server %d : StableConfiguration::addMember: current servers(%s), add server(%s)\n", paxos->getLocalServer()->serverId, logBuf.c_str(), strAddr.c_str());
for (auto it= learners.begin(); it != learners.end(); ++it)
if (*it && (*it)->strAddr == strAddr)
{
auto server= std::dynamic_pointer_cast<RemoteServer>(*it);
serversNum.fetch_add(1);
addServer(servers, server);
*it= nullptr;
//servers.push_back(server);
//learners.erase(it);
//server->serverId= servers.size();
initServerDefault(server);
if (paxos->getState() == Paxos::LEADER)
{
server->beginLeadership((void *)1);
}
else
server->stepDown(NULL);
server->connect(NULL);
logBuf= "";
for (auto& server : servers)
{
if (server)
{
logBuf += std::to_string(server->serverId);
logBuf += ":";
logBuf += server->strAddr;
logBuf += " ";
}
}
while (learners.size() > 0 && learners[learners.size() - 1] == nullptr)
learners.resize(learners.size() - 1);
paxos->getLog()->setMetaData(Paxos::keyLearnerConfigure, learnersToString());
paxos->getLog()->setMetaData(Paxos::keyMemberConfigure, membersToString(paxos->getLocalServer()->strAddr));
easy_warn_log("Server %d : StableConfiguration::addMember: success current servers(%s)\n", paxos->getLocalServer()->serverId, logBuf.c_str());
return 0;
}
easy_warn_log("Server %d : StableConfiguration::addMember: fail current servers(%s)\n", paxos->getLocalServer()->serverId, logBuf.c_str());
return -1;
}
int StableConfiguration::delMember(const std::string& strAddr, Paxos *paxos)
{
int ret= -1;
for (auto it= servers.begin(); it != servers.end(); ++ it)
{
if (*it == nullptr)
continue;
if ((*it)->strAddr == strAddr)
{
auto serverId= (*it)->serverId;
(*it)->stop(NULL);
serversNum.fetch_sub(1);
//servers.erase(it);
*it= nullptr;
ret= 0;
/* recycle the last nullptr in the servers */
if (serverId == servers.size() && servers.size() > 0)
{
while (servers[servers.size() - 1] == nullptr)
servers.resize(servers.size() - 1);
}
if (paxos)
paxos->getLog()->setMetaData(Paxos::keyMemberConfigure, membersToString(paxos->getLocalServer()->strAddr));
break;
}
}
return ret;
}
int StableConfiguration::configureLearner(const uint64_t serverId, uint64_t source, Paxos *paxos)
{
auto server= this->getServer(serverId);
if (!server)
{
easy_warn_log("Server %d : StableConfiguration::configureLearner: server %d not found, just skip.", paxos->getLocalServer()->serverId, serverId);
return 0;
}
server->learnerSource= source;
if (paxos)
paxos->getLog()->setMetaData(Paxos::keyLearnerConfigure, learnersToString());
return 0;
}
int StableConfiguration::configureMember(const uint64_t serverId, bool forceSync, uint electionWeight, Paxos *paxos)
{
auto server= this->getServer(serverId);
if (!server)
{
easy_warn_log("Server %d : StableConfiguration::configureMember: server %d not found, just skip.", paxos->getLocalServer()->serverId, serverId);
return 0;
}
server->forceSync= forceSync;
server->electionWeight= electionWeight;
if (paxos)
paxos->getLog()->setMetaData(Paxos::keyMemberConfigure, membersToString(paxos->getLocalServer()->strAddr));
return 0;
}
void StableConfiguration::addLearners(const std::vector<std::string>& strConfig, Paxos *paxos, bool replaceAll)
{
if (strConfig.size() == 0)
return;
std::shared_ptr<RemoteServer> ptrR;
uint64_t i= 0;
/*
if (learners.size() == 0)
i= 100;
else
i= learners.back()->serverId + 1;
*/
for (auto &str : strConfig)
{
++ i;
if (str == "0")
{
/* empty server */
if (learners.size() >= i)
learners[i-1]= nullptr;
else
{
assert(learners.size() == i - 1);
learners.push_back(nullptr);
}
continue;
}
//learners.push_back(ptrR= std::make_shared<RemoteServer>(i++));
ptrR= std::make_shared<RemoteServer>(0);
addServer(learners, ptrR, replaceAll);
ptrR->serverId += 99;
ptrR->srv= paxos->getService();
ptrR->paxos= paxos;
ptrR->isLearner= true;
initServerFromString(ptrR, str);
//ptrR->strAddr= str;
//ptrR->forceSync= false;
//ptrR->electionWeight= 0;
ptrR->appliedIndex= 0;
/* The Learner will become follower finally, so we create heartbeatTimer here. */
ptrR->heartbeatTimer= std::unique_ptr<ThreadTimer>(new ThreadTimer(paxos->getService()->getThreadTimerService(), paxos->getService(), paxos->getHeartbeatTimeout(), ThreadTimer::Repeatable, Paxos::heartbeatCallback, std::move(std::weak_ptr<RemoteServer>(ptrR))));
if ((paxos->getState() == Paxos::LEADER && ptrR->learnerSource == 0)
|| ptrR->learnerSource == paxos->getLocalServer()->serverId)
ptrR->beginLeadership((void *)1);
}
paxos->getLog()->setMetaData(Paxos::keyLearnerConfigure, learnersToString());
}
void StableConfiguration::delLearners(const std::vector<std::string>& strConfig, Paxos *paxos)
{
for (auto &str : strConfig)
{
for (auto it= learners.begin(); it != learners.end(); ++it)
if (*it && (*it)->strAddr == str)
{
/* TODO: clear for RemoteServer. */
(*it)->stop(NULL);
*it= nullptr;
//learners.erase(it);
break;
}
}
while (learners.size() > 0 && learners[learners.size() - 1] == nullptr)
learners.resize(learners.size() - 1);
if (paxos)
paxos->getLog()->setMetaData(Paxos::keyLearnerConfigure, learnersToString());
}
void StableConfiguration::delAllLearners()
{
for (auto it= learners.begin(); it != learners.end(); ++it)
if (*it)
(*it)->stop(NULL);
learners.clear();
}
void StableConfiguration::delAllRemoteServer(const std::string& localStrAddr, Paxos *paxos)
{
//uint64_t id= 1;
for (auto it= servers.begin(); it != servers.end();++ it)
{
if (*it && (*it)->strAddr != localStrAddr)
{
(*it)->stop(NULL);
serversNum.fetch_sub(1);
*it= nullptr;
//servers.erase(it);
}
}
assert(serversNum.load() == 1);
if (paxos)
paxos->getLog()->setMetaData(Paxos::keyMemberConfigure, membersToString(paxos->getLocalServer()->strAddr));
if (servers.size() > 0)
{
while (servers[servers.size() - 1] == nullptr)
servers.resize(servers.size() - 1);
}
}
void StableConfiguration::mergeFollowerMeta(const ::google::protobuf::RepeatedPtrField< ::alisql::ClusterInfoEntry >& ciEntries)
{
for (auto cit= ciEntries.begin(); cit != ciEntries.end(); ++ cit)
{
auto learner= std::dynamic_pointer_cast<RemoteServer>(getServer(cit->serverid()));
if (learner == nullptr)
{
easy_warn_log("StableConfiguration::mergeFollowerMeta: try to find server %d, but not in current configure!!\n", cit->serverid());
continue;
}
if (learner->serverId == cit->serverid() && learner->learnerSource == cit->learnersource())
{
learner->matchIndex.store(cit->matchindex());
learner->nextIndex.store(cit->nextindex());
learner->appliedIndex.store(cit->appliedindex());
learner->lastMergeTP= learner->now();
}
}
}
std::string StableConfiguration::getAddr(const std::string& addr)
{
std::string ret= addr;
uint64_t pos= std::string::npos;
pos= ret.find('$', 0);
if (pos == std::string::npos)
pos= ret.find('#', 0);
if (pos != std::string::npos)
ret.resize(pos);
return ret;
}
bool StableConfiguration::isServerInVector(const std::string& server, const std::vector<std::string>& strConfig)
{
std::string addr= getAddr(server);
for (auto& str : strConfig)
{
if (addr == getAddr(str))
return true;
}
return false;
}
void StableConfiguration::reset_flow_control()
{
for (auto& server : servers)
if (server)
server->flowControl = 0;
for (auto& learner : learners)
if (learner)
learner->flowControl = 0;
}
void StableConfiguration::set_flow_control(uint64_t serverId, int64_t fc)
{
for (auto& server : servers)
{
if (server && server->serverId == serverId)
{
server->flowControl = fc;
return;
}
}
for (auto& learner : learners)
{
if (learner && learner->serverId == serverId)
{
learner->flowControl = fc;
return;
}
}
}
} //namespace alisql
|
// Copyright (c) 2007-2014 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(HPX_RUNTIME_THREADS_DETAIL_SCHEDULING_LOOP_JAN_11_2013_0838PM)
#define HPX_RUNTIME_THREADS_DETAIL_SCHEDULING_LOOP_JAN_11_2013_0838PM
#include <hpx/hpx_fwd.hpp>
#include <hpx/state.hpp>
#include <hpx/runtime/threads/thread_data.hpp>
#include <hpx/runtime/agas/interface.hpp>
#include <hpx/util/itt_notify.hpp>
#include <hpx/util/hardware/timestamp.hpp>
#include <boost/cstdint.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/asio/basic_deadline_timer.hpp>
namespace hpx { namespace threads { namespace detail
{
///////////////////////////////////////////////////////////////////////
template <typename SchedulingPolicy>
inline void periodic_maintenance_handler(SchedulingPolicy& scheduler,
boost::atomic<hpx::state>& global_state, boost::mpl::false_)
{
}
template <typename SchedulingPolicy>
inline void periodic_maintenance_handler(SchedulingPolicy& scheduler,
boost::atomic<hpx::state>& global_state, boost::mpl::true_)
{
scheduler.periodic_maintenance(global_state == running);
if (global_state.load() == running)
{
// create timer firing in correspondence with given time
typedef boost::asio::basic_deadline_timer<
boost::chrono::steady_clock
, util::chrono_traits<boost::chrono::steady_clock>
> deadline_timer;
deadline_timer t(
get_thread_pool("timer-thread")->get_io_service(),
boost::chrono::milliseconds(1000));
void (*handler)(SchedulingPolicy&, boost::atomic<hpx::state>&, boost::mpl::true_) =
&periodic_maintenance_handler<SchedulingPolicy>;
t.async_wait(boost::bind(handler, boost::ref(scheduler),
boost::ref(global_state), boost::mpl::true_()));
}
}
template <typename SchedulingPolicy>
inline void start_periodic_maintenance(SchedulingPolicy&,
boost::atomic<hpx::state>& global_state, boost::mpl::false_)
{
}
template <typename SchedulingPolicy>
inline void start_periodic_maintenance(SchedulingPolicy& scheduler,
boost::atomic<hpx::state>& global_state, boost::mpl::true_)
{
scheduler.periodic_maintenance(global_state == running);
// create timer firing in correspondence with given time
typedef boost::asio::basic_deadline_timer<
boost::chrono::steady_clock
, util::chrono_traits<boost::chrono::steady_clock>
> deadline_timer;
deadline_timer t (
get_thread_pool("io-thread")->get_io_service(),
boost::chrono::milliseconds(1000));
void (*handler)(SchedulingPolicy&, boost::atomic<hpx::state>&, boost::mpl::true_) =
&periodic_maintenance_handler<SchedulingPolicy>;
t.async_wait(boost::bind(handler, boost::ref(scheduler),
boost::ref(global_state), boost::mpl::true_()));
}
///////////////////////////////////////////////////////////////////////
inline void write_new_state_log_debug(std::size_t num_thread,
thread_data_base* thrd, thread_state_enum state, char const* info)
{
LTM_(debug) << "tfunc(" << num_thread << "): " //-V128
<< "thread(" << thrd->get_thread_id().get() << "), "
<< "description(" << thrd->get_description() << "), "
<< "new state(" << get_thread_state_name(state) << "), "
<< info;
}
inline void write_new_state_log_warning(std::size_t num_thread,
thread_data_base* thrd, thread_state_enum state, char const* info)
{
// log this in any case
LTM_(warning) << "tfunc(" << num_thread << "): " //-V128
<< "thread(" << thrd->get_thread_id().get() << "), "
<< "description(" << thrd->get_description() << "), "
<< "new state(" << get_thread_state_name(state) << "), "
<< info;
}
inline void write_old_state_log(std::size_t num_thread,
thread_data_base* thrd, thread_state_enum state)
{
LTM_(debug) << "tfunc(" << num_thread << "): " //-V128
<< "thread(" << thrd->get_thread_id().get() << "), "
<< "description(" << thrd->get_description() << "), "
<< "old state(" << get_thread_state_name(state) << ")";
}
///////////////////////////////////////////////////////////////////////
// helper class for switching thread state in and out during execution
class switch_status
{
public:
switch_status (thread_data_base* t, thread_state prev_state)
: thread_(t), prev_state_(prev_state),
need_restore_state_(t->set_state_tagged(active, prev_state_, orig_state_))
{}
~switch_status ()
{
if (need_restore_state_)
store_state(prev_state_);
}
bool is_valid() const { return need_restore_state_; }
// allow to change the state the thread will be switched to after
// execution
thread_state operator=(thread_state_enum new_state)
{
return prev_state_ = thread_state(new_state, prev_state_.get_tag() + 1);
}
// Get the state this thread was in before execution (usually pending),
// this helps making sure no other worker-thread is started to execute this
// HPX-thread in the meantime.
thread_state get_previous() const
{
return prev_state_;
}
// This restores the previous state, while making sure that the
// original state has not been changed since we started executing this
// thread. The function returns true if the state has been set, false
// otherwise.
bool store_state(thread_state& newstate)
{
disable_restore();
if (thread_->restore_state(prev_state_, orig_state_)) {
newstate = prev_state_;
return true;
}
return false;
}
// disable default handling in destructor
void disable_restore() { need_restore_state_ = false; }
private:
thread_data_base* thread_;
thread_state prev_state_;
thread_state orig_state_;
bool need_restore_state_;
};
#ifdef HPX_HAVE_THREAD_IDLE_RATES
struct idle_collect_rate
{
idle_collect_rate(boost::uint64_t& tfunc_time, boost::uint64_t& exec_time)
: start_timestamp_(util::hardware::timestamp())
, tfunc_time_(tfunc_time)
, exec_time_(exec_time)
{}
void collect_exec_time(boost::uint64_t timestamp)
{
exec_time_ += util::hardware::timestamp() - timestamp;
}
void take_snapshot()
{
if (tfunc_time_ == boost::uint64_t(-1))
{
start_timestamp_ = util::hardware::timestamp();
tfunc_time_ = 0;
exec_time_ = 0;
}
else
{
tfunc_time_ = util::hardware::timestamp() - start_timestamp_;
}
}
boost::uint64_t start_timestamp_;
boost::uint64_t& tfunc_time_;
boost::uint64_t& exec_time_;
};
struct exec_time_wrapper
{
exec_time_wrapper(idle_collect_rate& idle_rate)
: timestamp_(util::hardware::timestamp())
, idle_rate_(idle_rate)
{}
~exec_time_wrapper()
{
idle_rate_.collect_exec_time(timestamp_);
}
boost::uint64_t timestamp_;
idle_collect_rate& idle_rate_;
};
struct tfunc_time_wrapper
{
tfunc_time_wrapper(idle_collect_rate& idle_rate)
: idle_rate_(idle_rate)
{
}
~tfunc_time_wrapper()
{
idle_rate_.take_snapshot();
}
idle_collect_rate& idle_rate_;
};
#else
struct idle_collect_rate
{
idle_collect_rate(boost::uint64_t&, boost::uint64_t&) {}
};
struct exec_time_wrapper
{
exec_time_wrapper(idle_collect_rate&) {}
};
struct tfunc_time_wrapper
{
tfunc_time_wrapper(idle_collect_rate&) {}
};
#endif
///////////////////////////////////////////////////////////////////////////
template <typename SchedulingPolicy>
void scheduling_loop(std::size_t num_thread, SchedulingPolicy& scheduler,
boost::atomic<hpx::state>& global_state, boost::int64_t& executed_threads,
boost::int64_t& executed_thread_phases, boost::uint64_t& tfunc_time,
boost::uint64_t& exec_time,
util::function_nonser<void()> const& cb_outer = util::function_nonser<void()>(),
util::function_nonser<void()> const& cb_inner = util::function_nonser<void()>())
{
util::itt::stack_context ctx; // helper for itt support
util::itt::domain domain(get_thread_name().data());
// util::itt::id threadid(domain, this);
util::itt::frame_context fctx(domain);
boost::int64_t idle_loop_count = 0;
boost::int64_t busy_loop_count = 0;
idle_collect_rate idle_rate(tfunc_time, exec_time);
tfunc_time_wrapper tfunc_time_collector(idle_rate);
typedef typename SchedulingPolicy::has_periodic_maintenance pred;
detail::start_periodic_maintenance(scheduler, global_state, pred());
while (true) {
// Get the next HPX thread from the queue
thread_data_base* thrd = NULL;
if (scheduler.SchedulingPolicy::get_next_thread(num_thread,
global_state == running, idle_loop_count, thrd))
{
tfunc_time_wrapper tfunc_time_collector(idle_rate);
idle_loop_count = 0;
++busy_loop_count;
// Only pending HPX threads will be executed.
// Any non-pending HPX threads are leftovers from a set_state()
// call for a previously pending HPX thread (see comments above).
thread_state state = thrd->get_state();
thread_state_enum state_val = state;
detail::write_old_state_log(num_thread, thrd, state_val);
if (pending == state_val) {
// switch the state of the thread to active and back to
// what the thread reports as its return value
{
// tries to set state to active (only if state is still
// the same as 'state')
detail::switch_status thrd_stat (thrd, state);
if (thrd_stat.is_valid() && thrd_stat.get_previous() == pending)
{
tfunc_time_wrapper tfunc_time_collector(idle_rate);
// thread returns new required state
// store the returned state in the thread
{
#ifdef HPX_HAVE_ITTNOTIFY
util::itt::caller_context cctx(ctx);
util::itt::undo_frame_context undoframe(fctx);
util::itt::task task(domain, thrd->get_description());
#endif
// Record time elapsed in thread changing state
// and add to aggregate execution time.
exec_time_wrapper exec_time_collector(idle_rate);
thrd_stat = (*thrd)();
}
#ifdef HPX_HAVE_THREAD_CUMULATIVE_COUNTS
++executed_thread_phases;
#endif
}
else {
// some other worker-thread got in between and started
// executing this HPX-thread, we just continue with
// the next one
thrd_stat.disable_restore();
detail::write_new_state_log_warning(
num_thread, thrd, state_val, "no execution");
continue;
}
// store and retrieve the new state in the thread
if (!thrd_stat.store_state(state)) {
// some other worker-thread got in between and changed
// the state of this thread, we just continue with
// the next one
detail::write_new_state_log_warning(
num_thread, thrd, state_val, "no state change");
continue;
}
state_val = state;
// any exception thrown from the thread will reset its
// state at this point
}
//detail::write_new_state_log_debug(num_thread, thrd,
// state_val, "normal");
// Re-add this work item to our list of work items if the HPX
// thread should be re-scheduled. If the HPX thread is suspended
// now we just keep it in the map of threads.
if (state_val == pending) {
// schedule other work
scheduler.SchedulingPolicy::wait_or_add_new(num_thread,
global_state == running, idle_loop_count);
// schedule this thread again, make sure it ends up at
// the end of the queue
scheduler.SchedulingPolicy::schedule_thread_last(thrd, num_thread);
scheduler.SchedulingPolicy::do_some_work(num_thread);
}
}
else if (active == state_val) {
LTM_(warning) << "tfunc(" << num_thread << "): " //-V128
"thread(" << thrd->get_thread_id().get() << "), "
"description(" << thrd->get_description() << "), "
"rescheduling";
// re-schedule thread, if it is still marked as active
// this might happen, if some thread has been added to the
// scheduler queue already but the state has not been reset
// yet
//
// REVIEW: Passing a specific target thread may set off
// the round robin queuing.
scheduler.SchedulingPolicy::schedule_thread(thrd, num_thread);
}
// Remove the mapping from thread_map_ if HPX thread is depleted
// or terminated, this will delete the HPX thread as all
// references go out of scope.
// REVIEW: what has to be done with depleted HPX threads?
if (state_val == depleted || state_val == terminated)
{
#ifdef HPX_HAVE_THREAD_CUMULATIVE_COUNTS
++executed_threads;
#endif
scheduler.SchedulingPolicy::destroy_thread(thrd, busy_loop_count);
}
}
// if nothing else has to be done either wait or terminate
else {
++idle_loop_count;
if (scheduler.SchedulingPolicy::wait_or_add_new(num_thread,
global_state == running, idle_loop_count))
{
break;
}
// do background work in parcel layer and in agas
if (hpx::parcelset::do_background_work(num_thread))
idle_loop_count = 0;
if (0 == num_thread)
{
hpx::agas::garbage_collect_non_blocking();
}
// call back into invoking context
if (!cb_inner.empty())
cb_inner();
}
// something went badly wrong, give up
if (global_state == terminating)
break;
if (busy_loop_count > HPX_BUSY_LOOP_COUNT_MAX)
{
busy_loop_count = 0;
// do background work in parcel layer and in agas
if (hpx::parcelset::do_background_work(num_thread))
idle_loop_count = 0;
if (0 == num_thread)
{
hpx::agas::garbage_collect_non_blocking();
}
}
else if (idle_loop_count > HPX_IDLE_LOOP_COUNT_MAX)
{
// call back into invoking context
if (!cb_outer.empty())
cb_outer();
// clean up terminated threads
idle_loop_count = 0;
scheduler.SchedulingPolicy::cleanup_terminated(true);
}
}
}
}}}
#endif
|
//asked in Amazon, Samsung, Snapdeal, Accolite.
#include<iostream>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
const int N=100; //should be N=1e6+2 but compiler not able to handle so did 100.
int idx[N];
for(int i=0;i<N;i++){
idx[i]=-1;
}
for(int i=0;i<n;i++){
if(arr[i]<0){
continue;
}
else{
idx[arr[i]]=i;
}
}
for(int i=0;i<N;i++){
if(idx[i]==-1){
cout<<i<<endl;
break;
}
}
}
return 0;
}
//NOTE-> done using Hashing technique.
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
const vector<int> v = {1, 2, 3, 4, 4, 3, 7, 8, 9, 10};
const int value1 = 3;
int num_value1 = count(v.cbegin(), v.cend(), value1);
cout << "Count of " << value1 << " is: " << num_value1 << endl;
return 0;
}
|
#include "core/bepch.h"
#include "ConfigurationPanel.h"
#include "core/preferences/editor/EditorPreferences.h"
BoxerEngine::ConfigurationPanel::ConfigurationPanel() : Panel("Configuration", true)
{
}
void BoxerEngine::ConfigurationPanel::Update()
{
prefs = static_cast<EditorPreferences*>(App->preferences->GetEditorPreferences());
ImGui::SetNextWindowSize(ImVec2(325, 260), ImGuiCond_FirstUseEver);
if (!ImGui::Begin(StringUtils::Concat(ICON_MD_SETTINGS, GetTitle()).c_str(), &visible))
{
ImGui::End();
return;
}
float maxFps = game_options.GetMaxFPS();
ImGui::SliderFloat("##FPSSlider", &maxFps, 24.0f, 250.0f, "FPS %.1f");
game_options.SetMaxFPS(maxFps);
bool vsync = prefs->GetVsync();
ImGui::TextWrapped("Vsync");
ImGui::SameLine();
ImGui::Checkbox("##vsync", &vsync);
prefs->SetVsync(vsync);
bool fullscreen = prefs->IsFullscreen();
ImGui::TextWrapped("Fullscreen");
ImGui::SameLine();
ImGui::Checkbox("##fullscreen", &fullscreen);
prefs->SetFullscreen(fullscreen);
bool displayDebugDraw = prefs->IsDisplayDebugDraw();
ImGui::TextWrapped("Display debug draw");
ImGui::SameLine();
ImGui::Checkbox("##debugdraw", &displayDebugDraw);
prefs->SetDisplayDebugDraw(displayDebugDraw);
// float3 values = float3::zero;
// std::string label = "Camera";
// BoxerEngine::AxisSlider::Build(label, values);
ImGui::End();
}
|
/*
* icon.cpp
*
* This file is a part of NSIS.
*
* Copyright (C) 1999-2021 Nullsoft and Contributors
*
* Licensed under the zlib/libpng license (the "License");
* you may not use this file except in compliance with the License.
*
* Licence details can be found in the file COPYING.
*
* This software is provided 'as-is', without any express or implied
* warranty.
*/
#include "Platform.h"
#include "icon.h"
#include "util.h"
#include "lang.h"
#include <stdio.h>
#include <stdexcept>
#include <vector>
#include <algorithm>
using namespace std;
extern int g_display_errors;
extern FILE *g_output;
#define SIZEOF_RSRC_ICON_GROUP_ENTRY 14
enum { ICO_TYPE_ICON = 1, ICO_TYPE_CURSOR = 2 };
static bool is_valid_header(const void*headerdata)
{
assert(sizeof(IconGroupHeader) == 6);
IconGroupHeader*pGH = (IconGroupHeader*) headerdata;
if (pGH->wReserved != FIX_ENDIAN_INT16(0x0000)) return false;
WORD type = FIX_ENDIAN_INT16(pGH->wType);
if (type != ICO_TYPE_ICON && type != ICO_TYPE_CURSOR) return false;
return FIX_ENDIAN_INT16(pGH->wCount) != 0;
}
template<class S> static WORD read_icon_header(S*f, IconGroupHeader& igh)
{
if (!freadall(&igh, sizeof(IconGroupHeader), f))
{
fclose(f);
throw runtime_error("unable to read header from file");
}
if (!is_valid_header(&igh))
{
igh.wType = igh.wCount = 0;
fclose(f);
throw runtime_error("invalid icon file");
}
FIX_ENDIAN_INT16_INPLACE(igh.wReserved);
FIX_ENDIAN_INT16_INPLACE(igh.wType);
FIX_ENDIAN_INT16_INPLACE(igh.wCount);
return igh.wCount;
}
void free_loaded_icon(IconGroup&icon)
{
for (IconGroup::size_type i = 0; i < icon.size(); i++)
delete [] icon[i].data;
icon.clear();
}
IconGroup load_icon_res(CResourceEditor* re, LPWSTR RT, WORD RN, LANGID RL)
{
IconGroupHeader* header;
IconGroup result;
LPBYTE group = re->GetResource(RT, RN, RL);
if (!group)
throw runtime_error("can't find icon group");
header = (IconGroupHeader*) group;
// Note: To handle cursors, use CResourceEditor::ExtractIcoCur
if (MAKEINTRESOURCE((size_t) RT) != RT_GROUP_ICON)
throw runtime_error("unsupported type");
for (WORD i = 0; i < FIX_ENDIAN_INT16(header->wCount); i++)
{
Icon icon;
icon.index = i;
RsrcIconGroupEntry* entry = (RsrcIconGroupEntry*) (group
+ sizeof(IconGroupHeader) + SIZEOF_RSRC_ICON_GROUP_ENTRY * i);
memcpy(&icon.meta, &entry->header, sizeof(IconGroupEntry));
WORD rsrc_id = FIX_ENDIAN_INT16(entry->wRsrcId);
icon.data = re->GetResource(RT_ICON, rsrc_id, RL);
if (!icon.data)
{
free_loaded_icon(result);
throw runtime_error("can't find icon");
}
result.push_back(icon);
}
re->FreeResource(group);
return result;
}
IconGroup load_icon_res(CResourceEditor* re, WORD id)
{
return load_icon_res(re, RT_GROUP_ICON, id, NSIS_DEFAULT_LANG);
}
template<class S> static IconGroup load_iconimages_from_stream(const IconGroupHeader&iconHeader, S&file)
{
IconGroup result;
for (WORD i = 0; i < iconHeader.wCount; i++)
{
Icon icon;
icon.index = i;
icon.data = NULL;
if (!freadall(&icon.meta, sizeof(IconGroupEntry), file))
{
free_loaded_icon(result);
throw runtime_error("unable to read entry from file");
}
DWORD size = FIX_ENDIAN_INT32(icon.meta.dwRawSize);
if (size > 1048576) // magic numbers are great
{
free_loaded_icon(result);
throw runtime_error("invalid icon file size");
}
DWORD iconOffset;
if (!freadall(&iconOffset, sizeof(DWORD), file))
{
free_loaded_icon(result);
throw runtime_error("unable to read offset from file");
}
FIX_ENDIAN_INT32_INPLACE(iconOffset);
fpos_t pos;
fgetpos(file, &pos);
if (fseek(file, iconOffset, SEEK_SET))
{
free_loaded_icon(result);
throw runtime_error("corrupted icon file, too small");
}
icon.data = new BYTE[size];
if (!freadall(icon.data, size, file)) die:
{
free_loaded_icon(result);
throw runtime_error("unable to read icon from file");
}
if (fsetpos(file, &pos))
goto die;
result.push_back(icon);
}
return result;
}
template<class S> static IconGroup load_icon_from_stream(S*file)
{
IconGroupHeader iconHeader;
read_icon_header(file, iconHeader);
return load_iconimages_from_stream(iconHeader, file);
}
IconGroup load_icon_file(const TCHAR* filename)
{
FILE* f = FOPEN(filename, ("rb"));
if (!f)
throw runtime_error("can't open file");
MANAGE_WITH(f, fclose);
return load_icon_from_stream(f);
}
IconGroup load_icon(const TCHAR* filename)
{
if (CResourceEditor::IsResProtocol(filename)) // Try opening embedded resource
{
CResourceEditor::EXTERNAL x;
if (CResourceEditor::MapExternal(filename, CResourceEditor::TM_ICON, x))
{
CStdFileStreamOnMemory stream(x.Data, x.cbData);
IconGroup icon = load_icon_from_stream(&stream);
CResourceEditor::FreeExternal(x);
return icon;
}
}
return load_icon_file(filename);
}
typedef struct
{
unsigned index1;
unsigned index2;
DWORD size;
unsigned size_index;
} IconPair;
typedef vector<IconPair> IconPairs;
static bool compare_icon(Icon a, Icon b)
{
return FIX_ENDIAN_INT32(a.meta.dwRawSize) > FIX_ENDIAN_INT32(b.meta.dwRawSize);
}
static IconGroup sort_icon(IconGroup icon)
{
IconGroup sorted = icon;
sort(sorted.begin(), sorted.end(), compare_icon);
return sorted;
}
static bool compare_pairs_index1(IconPair a, IconPair b)
{
return a.index1 < b.index1;
}
static bool compare_pairs_index2(IconPair a, IconPair b)
{
return a.index2 < b.index2;
}
static IconPairs sort_pairs(IconPairs pairs, bool first)
{
IconPairs sorted = pairs;
sort(sorted.begin(), sorted.end(), first ? compare_pairs_index1 : compare_pairs_index2);
return sorted;
}
static IconPairs get_icon_order(IconGroup icon1, IconGroup icon2)
{
IconGroup sorted_icons1 = sort_icon(icon1);
IconGroup sorted_icons2 = sort_icon(icon2);
IconGroup::size_type shared_count = min(sorted_icons1.size(), sorted_icons2.size());
IconGroup::size_type total_count = max(sorted_icons1.size(), sorted_icons2.size());
IconPairs result;
IconGroup::size_type i;
for (i = 0; i < shared_count; i++)
{
IconPair pair;
pair.index1 = sorted_icons1[i].index;
pair.index2 = sorted_icons2[i].index;
pair.size = max(
FIX_ENDIAN_INT32(sorted_icons1[i].meta.dwRawSize),
FIX_ENDIAN_INT32(sorted_icons2[i].meta.dwRawSize)
);
pair.size_index = truncate_cast(unsigned int,i);
result.push_back(pair);
}
for (; i < total_count; i++)
{
IconPair pair;
if (i < sorted_icons1.size())
{
pair.index1 = sorted_icons1[i].index;
pair.index2 = 0xffff;
pair.size = FIX_ENDIAN_INT32(sorted_icons1[i].meta.dwRawSize);
pair.size_index = truncate_cast(unsigned int,i);
}
if (i < sorted_icons2.size())
{
pair.index2 = sorted_icons2[i].index;
pair.index1 = 0xffff;
pair.size = FIX_ENDIAN_INT32(sorted_icons2[i].meta.dwRawSize);
pair.size_index = truncate_cast(unsigned int,i);
}
result.push_back(pair);
}
return result;
}
#define destroy_icon_group(p) ( delete [] (p) )
static LPBYTE generate_icon_group(IconGroup icon, IconPairs order, bool first)
{
size_t groupsize =
sizeof(IconGroupHeader) // header
+ order.size() * SIZEOF_RSRC_ICON_GROUP_ENTRY; // entries
LPBYTE group = new BYTE[groupsize];
memset(group, 0, groupsize); // Reproducible builds (bug #1230)
IconGroupHeader* header = (IconGroupHeader*) group;
header->wReserved = 0;
header->wType = FIX_ENDIAN_INT16(ICO_TYPE_ICON);
header->wCount = FIX_ENDIAN_INT16((WORD)icon.size());
order = sort_pairs(order, first);
for (IconGroup::size_type i = 0; i < icon.size(); i++)
{
RsrcIconGroupEntry* entry = (RsrcIconGroupEntry*)
&group[sizeof(IconGroupHeader) + SIZEOF_RSRC_ICON_GROUP_ENTRY * i];
unsigned index = first ? order[i].index1 : order[i].index2;
memcpy(&entry->header, &icon[index].meta, sizeof(IconGroupEntry));
entry->wRsrcId = FIX_ENDIAN_INT16(order[i].size_index + 1);
}
return group;
}
// set_icon, must get an initialized resource editor
void set_main_icon(CResourceEditor* re, WORD wIconId, IconGroup icon1, IconGroup icon2)
{
IconPairs order = get_icon_order(icon1, icon2);
// genreate group
LPBYTE group1 = generate_icon_group(icon1, order, true);
// set group
size_t group_size = sizeof(IconGroupHeader) // header
+ order.size() * SIZEOF_RSRC_ICON_GROUP_ENTRY; // entries
re->UpdateResource(RT_GROUP_ICON, wIconId, NSIS_DEFAULT_LANG, group1, (DWORD)group_size, CResourceEditor::TM_RAW); // Update the group entries but not the images
destroy_icon_group(group1);
// delete old icons
unsigned i = 1;
while (i <= MAIN_ICON_LAST_IMAGE && re->UpdateResource(RT_ICON, i++, NSIS_DEFAULT_LANG, 0, 0));
// set new icons
IconGroup::size_type order_index;
for (order_index = 0; order_index < order.size(); order_index++)
{
WORD size_index = order[order_index].size_index;
DWORD size = order[order_index].size;
LPBYTE data = new BYTE[size];
memset(data, 0, size);
if (order_index < icon1.size())
{
Icon* icon = &icon1[order[order_index].index1];
memcpy(data, icon->data, FIX_ENDIAN_INT32(icon->meta.dwRawSize));
}
re->UpdateResource(RT_ICON, size_index + 1, NSIS_DEFAULT_LANG, data, size);
delete [] data;
}
}
#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
// returns the data of the uninstaller icon that should replace the installer icon data
unsigned char* generate_uninstall_icon_data(IconGroup icon1, IconGroup icon2, size_t &data_size)
{
IconGroup::size_type i;
IconPairs order = get_icon_order(icon1, icon2);
// genreate group
LPBYTE group = generate_icon_group(icon2, order, false);
// calculate size
size_t group_size = sizeof(IconGroupHeader) // header
+ order.size() * SIZEOF_RSRC_ICON_GROUP_ENTRY; // entries
data_size = group_size // group header
+ sizeof(DWORD) * 2 // offset and size of group header
+ (sizeof(DWORD) * 2) * icon2.size() // offset and size per entry
+ sizeof(DWORD); // terminator
for (i = 0; i < icon2.size(); i++)
{
// add icon sizes
data_size += FIX_ENDIAN_INT32(icon2[i].meta.dwRawSize);
}
// allocate memory
LPBYTE uninst_data = new BYTE[data_size];
LPBYTE seeker = uninst_data;
// fill group header
*(LPDWORD) seeker = FIX_ENDIAN_INT32((UINT32)group_size);
seeker += sizeof(DWORD);
*(LPDWORD) seeker = 0;
seeker += sizeof(DWORD);
memcpy(seeker, group, group_size);
seeker += group_size;
// fill entries
for (i = 0; i < icon2.size(); i++)
{
Icon* icon = &icon2[order[i].index2];
DWORD size = icon->meta.dwRawSize;
memcpy(seeker, &size, sizeof(size));
seeker += sizeof(size);
memset(seeker, 0, sizeof(DWORD));
seeker += sizeof(DWORD);
memcpy(seeker, icon->data, size);
seeker += FIX_ENDIAN_INT32(size);
}
// add terminator
memset(seeker, 0, sizeof(DWORD));
// done
destroy_icon_group(group);
return uninst_data;
}
// Fill the array of icons for uninstall with their offsets
// Returns zero on failure
int generate_unicons_offsets(LPBYTE exeHeader, size_t exeHeaderSize, LPBYTE uninstIconData, WORD wIconId)
{
try
{
DWORD offset;
DWORD size;
CResourceEditor re(exeHeader, (DWORD)exeHeaderSize, false);
LPBYTE seeker = uninstIconData;
offset = re.GetResourceOffset(RT_GROUP_ICON, wIconId, NSIS_DEFAULT_LANG);
size = FIX_ENDIAN_INT32(*(LPDWORD)seeker);
seeker += sizeof(DWORD);
*(LPDWORD) seeker = FIX_ENDIAN_INT32(offset);
seeker += sizeof(DWORD);
seeker += size;
WORD icon_index = 1;
while (*(LPDWORD)seeker)
{
offset = re.GetResourceOffset(RT_ICON, icon_index, NSIS_DEFAULT_LANG);
if (offset > exeHeaderSize)
{
throw runtime_error("invalid icon offset (possibly compressed icon)");
}
DWORD real_size = re.GetResourceSize(RT_ICON, icon_index, NSIS_DEFAULT_LANG);
size = FIX_ENDIAN_INT32(*(LPDWORD)seeker);
seeker += sizeof(DWORD);
if (real_size < size) // uninst icon could be smaller, in case we don't have perfect matches
{
throw runtime_error("invalid icon size (possibly compressed icon)");
}
*(LPDWORD) seeker = FIX_ENDIAN_INT32(offset);
seeker += sizeof(DWORD);
seeker += size;
icon_index++;
}
}
catch (const exception& e)
{
if (g_display_errors)
PrintColorFmtMsg_ERR(_T("\nError generating uninstaller icon: %") NPRIs _T(" -- failing!\n"), CtoTStrParam(e.what()));
return 0;
}
return 1;
}
#endif // NSIS_CONFIG_UNINSTALL_SUPPORT
|
#pragma once
#include <QTreeWidget>
#include "core/NodeWidget/nodewidget.h"
#include "napi.h"
class NTreeWidget : public QTreeWidget, public NodeWidget {
Q_OBJECT
NODEWIDGET_IMPLEMENTATIONS(QTreeWidget)
public:
using QTreeWidget::QTreeWidget; // inherit all constructors of QTreeWidget
void connectWidgetSignalsToEventEmitter() {
QObject::connect(this, &QTreeWidget::itemSelectionChanged, [=]() {
Napi::Env env = this->emitOnNode.Env();
Napi::HandleScope scope(env);
this->emitOnNode.Call({Napi::String::New(env, "itemSelectionChanged")});
});
}
};
|
#include "OnRamp.hpp"
#include <unistd.h>
using namespace marlin::core;
using namespace marlin::asyncio;
using namespace marlin::beacon;
using namespace marlin::pubsub;
using namespace marlin::rlpx;
int main(int argc, char **argv) {
std::string beacon_addr = "127.0.0.1:8002";
std::string discovery_addr = "0.0.0.0:20202";
std::string pubsub_addr = "0.0.0.0:20200";
int c;
while ((c = getopt (argc, argv, "b::d::p::")) != -1) {
switch (c) {
case 'b':
beacon_addr = std::string(optarg);
break;
case 'd':
discovery_addr = std::string(optarg);
break;
case 'p':
pubsub_addr = std::string(optarg);
break;
default:
return 1;
}
}
SPDLOG_INFO(
"Beacon: {}, Discovery: {}, PubSub: {}",
beacon_addr,
discovery_addr,
pubsub_addr
);
uint8_t static_sk[crypto_box_SECRETKEYBYTES];
uint8_t static_pk[crypto_box_PUBLICKEYBYTES];
crypto_box_keypair(static_pk, static_sk);
DefaultMulticastClientOptions clop {
static_sk,
static_pk,
std::vector<uint16_t>({0, 1}),
beacon_addr,
discovery_addr,
pubsub_addr
};
OnRamp onramp(clop);
return uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
|
//
// Created by Hesray on 2020/3/29.
//
/* DO NOT EDIT THIS FILE - it is machine generated */
#include "ImageProc.h"
#include <opencv2/core/core.hpp>
#include <string>
#include <vector>
#include <iostream>
using namespace cv;
using namespace std;
extern "C" {
JNIEXPORT jintArray JNICALL Java_com_demo_cv_ImageProc_trasformToGray(
JNIEnv *env, jclass ojb, jintArray buf, jint w, jint h) {
jint *cbuf;
cbuf = env->GetIntArrayElements(buf, false);
if (cbuf == NULL) {
return 0;
}
Mat imgData(h, w, CV_8UC4, (unsigned char*) cbuf);
uchar* ptr = imgData.ptr(0);
for (int i = 0; i < w * h; i++) {
int grayScale = (int) (ptr[4 * i + 2] * 0.299 + ptr[4 * i + 1] * 0.587
+ ptr[4 * i + 0] * 0.114);
ptr[4 * i + 1] = grayScale;
ptr[4 * i + 2] = grayScale;
ptr[4 * i + 0] = grayScale;
}
int size = w * h;
jintArray result = env->NewIntArray(size);
env->SetIntArrayRegion(result, 0, size, cbuf);
env->ReleaseIntArrayElements(buf, cbuf, 0);
cout << "After image_proc transformToGray..\n";
return result;
}
}
|
struct A { void foo(); };
struct B { A* operator->(); };
struct C { B operator->(); };
struct D { C operator->(); };
int main()
{
D d;
d->foo();
}
|
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2020 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/memory.h"
#include <algorithm>
#include <cstring>
#include <utility>
#include "third_party/fmt/include/fmt/format.h"
#include "xenia/base/assert.h"
#include "xenia/base/byte_stream.h"
#include "xenia/base/clock.h"
#include "xenia/base/cvar.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/base/threading.h"
#include "xenia/cpu/mmio_handler.h"
// TODO(benvanik): move xbox.h out
#include "xenia/xbox.h"
DEFINE_bool(protect_zero, true, "Protect the zero page from reads and writes.",
"Memory");
DEFINE_bool(protect_on_release, false,
"Protect released memory to prevent accesses.", "Memory");
DEFINE_bool(scribble_heap, false,
"Scribble 0xCD into all allocated heap memory.", "Memory");
namespace xe {
uint32_t get_page_count(uint32_t value, uint32_t page_size) {
return xe::round_up(value, page_size) / page_size;
}
/**
* Memory map:
* 0x00000000 - 0x3FFFFFFF (1024mb) - virtual 4k pages
* 0x40000000 - 0x7FFFFFFF (1024mb) - virtual 64k pages
* 0x80000000 - 0x8BFFFFFF ( 192mb) - xex 64k pages
* 0x8C000000 - 0x8FFFFFFF ( 64mb) - xex 64k pages (encrypted)
* 0x90000000 - 0x9FFFFFFF ( 256mb) - xex 4k pages
* 0xA0000000 - 0xBFFFFFFF ( 512mb) - physical 64k pages
* 0xC0000000 - 0xDFFFFFFF - physical 16mb pages
* 0xE0000000 - 0xFFFFFFFF - physical 4k pages
*
* We use the host OS to create an entire addressable range for this. That way
* we don't have to emulate a TLB. It'd be really cool to pass through page
* sizes or use madvice to let the OS know what to expect.
*
* We create our own heap of committed memory that lives at
* memory_HEAP_LOW to memory_HEAP_HIGH - all normal user allocations
* come from there. Since the Xbox has no paging, we know that the size of
* this heap will never need to be larger than ~512MB (realistically, smaller
* than that). We place it far away from the XEX data and keep the memory
* around it uncommitted so that we have some warning if things go astray.
*
* For XEX/GPU/etc data we allow placement allocations (base_address != 0) and
* commit the requested memory as needed. This bypasses the standard heap, but
* XEXs should never be overwriting anything so that's fine. We can also query
* for previous commits and assert that we really isn't committing twice.
*
* GPU memory is mapped onto the lower 512mb of the virtual 4k range (0).
* So 0xA0000000 = 0x00000000. A more sophisticated allocator could handle
* this.
*/
static Memory* active_memory_ = nullptr;
void CrashDump() {
static std::atomic<int> in_crash_dump(0);
if (in_crash_dump.fetch_add(1)) {
xe::FatalError(
"Hard crash: the memory system crashed while dumping a crash dump.");
return;
}
active_memory_->DumpMap();
--in_crash_dump;
}
Memory::Memory() {
system_page_size_ = uint32_t(xe::memory::page_size());
system_allocation_granularity_ =
uint32_t(xe::memory::allocation_granularity());
assert_zero(active_memory_);
active_memory_ = this;
}
Memory::~Memory() {
assert_true(active_memory_ == this);
active_memory_ = nullptr;
// Uninstall the MMIO handler, as we won't be able to service more
// requests.
mmio_handler_.reset();
for (auto invalidation_callback : physical_memory_invalidation_callbacks_) {
delete invalidation_callback;
}
heaps_.v00000000.Dispose();
heaps_.v40000000.Dispose();
heaps_.v80000000.Dispose();
heaps_.v90000000.Dispose();
heaps_.vA0000000.Dispose();
heaps_.vC0000000.Dispose();
heaps_.vE0000000.Dispose();
heaps_.physical.Dispose();
// Unmap all views and close mapping.
if (mapping_ != xe::memory::kFileMappingHandleInvalid) {
UnmapViews();
xe::memory::CloseFileMappingHandle(mapping_, file_name_);
mapping_base_ = nullptr;
mapping_ = xe::memory::kFileMappingHandleInvalid;
}
virtual_membase_ = nullptr;
physical_membase_ = nullptr;
}
bool Memory::Initialize() {
file_name_ = fmt::format("xenia_memory_{}", Clock::QueryHostTickCount());
// Create main page file-backed mapping. This is all reserved but
// uncommitted (so it shouldn't expand page file).
mapping_ = xe::memory::CreateFileMappingHandle(
file_name_,
// entire 4gb space + 512mb physical:
0x11FFFFFFF, xe::memory::PageAccess::kReadWrite, false);
if (mapping_ == xe::memory::kFileMappingHandleInvalid) {
XELOGE("Unable to reserve the 4gb guest address space.");
assert_always();
return false;
}
// Attempt to create our views. This may fail at the first address
// we pick, so try a few times.
mapping_base_ = 0;
for (size_t n = 32; n < 64; n++) {
auto mapping_base = reinterpret_cast<uint8_t*>(1ull << n);
if (!MapViews(mapping_base)) {
mapping_base_ = mapping_base;
break;
}
}
if (!mapping_base_) {
XELOGE("Unable to find a continuous block in the 64bit address space.");
assert_always();
return false;
}
virtual_membase_ = mapping_base_;
physical_membase_ = mapping_base_ + 0x100000000ull;
// Prepare virtual heaps.
heaps_.v00000000.Initialize(this, virtual_membase_, 0x00000000, 0x40000000,
4096);
heaps_.v40000000.Initialize(this, virtual_membase_, 0x40000000,
0x40000000 - 0x01000000, 64 * 1024);
heaps_.v80000000.Initialize(this, virtual_membase_, 0x80000000, 0x10000000,
64 * 1024);
heaps_.v90000000.Initialize(this, virtual_membase_, 0x90000000, 0x10000000,
4096);
// Prepare physical heaps.
heaps_.physical.Initialize(this, physical_membase_, 0x00000000, 0x20000000,
4096);
heaps_.vA0000000.Initialize(this, virtual_membase_, 0xA0000000, 0x20000000,
64 * 1024, &heaps_.physical);
heaps_.vC0000000.Initialize(this, virtual_membase_, 0xC0000000, 0x20000000,
16 * 1024 * 1024, &heaps_.physical);
heaps_.vE0000000.Initialize(this, virtual_membase_, 0xE0000000, 0x1FD00000,
4096, &heaps_.physical);
// Protect the first and last 64kb of memory.
heaps_.v00000000.AllocFixed(
0x00000000, 0x10000, 0x10000,
kMemoryAllocationReserve | kMemoryAllocationCommit,
!cvars::protect_zero ? kMemoryProtectRead | kMemoryProtectWrite
: kMemoryProtectNoAccess);
heaps_.physical.AllocFixed(0x1FFF0000, 0x10000, 0x10000,
kMemoryAllocationReserve, kMemoryProtectNoAccess);
// GPU writeback.
// 0xC... is physical, 0x7F... is virtual. We may need to overlay these.
heaps_.vC0000000.AllocFixed(
0xC0000000, 0x01000000, 32,
kMemoryAllocationReserve | kMemoryAllocationCommit,
kMemoryProtectRead | kMemoryProtectWrite);
// Add handlers for MMIO.
mmio_handler_ = cpu::MMIOHandler::Install(
virtual_membase_, physical_membase_, physical_membase_ + 0x1FFFFFFF,
HostToGuestVirtualThunk, this, AccessViolationCallbackThunk, this);
if (!mmio_handler_) {
XELOGE("Unable to install MMIO handlers");
assert_always();
return false;
}
// ?
uint32_t unk_phys_alloc;
heaps_.vA0000000.Alloc(0x340000, 64 * 1024, kMemoryAllocationReserve,
kMemoryProtectNoAccess, true, &unk_phys_alloc);
return true;
}
static const struct {
uint64_t virtual_address_start;
uint64_t virtual_address_end;
uint64_t target_address;
} map_info[] = {
// (1024mb) - virtual 4k pages
{
0x00000000,
0x3FFFFFFF,
0x0000000000000000ull,
},
// (1024mb) - virtual 64k pages (cont)
{
0x40000000,
0x7EFFFFFF,
0x0000000040000000ull,
},
// (16mb) - GPU writeback + 15mb of XPS?
{
0x7F000000,
0x7FFFFFFF,
0x0000000100000000ull,
},
// (256mb) - xex 64k pages
{
0x80000000,
0x8FFFFFFF,
0x0000000080000000ull,
},
// (256mb) - xex 4k pages
{
0x90000000,
0x9FFFFFFF,
0x0000000080000000ull,
},
// (512mb) - physical 64k pages
{
0xA0000000,
0xBFFFFFFF,
0x0000000100000000ull,
},
// - physical 16mb pages
{
0xC0000000,
0xDFFFFFFF,
0x0000000100000000ull,
},
// - physical 4k pages
{
0xE0000000,
0xFFFFFFFF,
0x0000000100001000ull,
},
// - physical raw
{
0x100000000,
0x11FFFFFFF,
0x0000000100000000ull,
},
};
int Memory::MapViews(uint8_t* mapping_base) {
assert_true(xe::countof(map_info) == xe::countof(views_.all_views));
// 0xE0000000 4 KB offset is emulated via host_address_offset and on the CPU
// side if system allocation granularity is bigger than 4 KB.
uint64_t granularity_mask = ~uint64_t(system_allocation_granularity_ - 1);
for (size_t n = 0; n < xe::countof(map_info); n++) {
views_.all_views[n] = reinterpret_cast<uint8_t*>(xe::memory::MapFileView(
mapping_, mapping_base + map_info[n].virtual_address_start,
map_info[n].virtual_address_end - map_info[n].virtual_address_start + 1,
xe::memory::PageAccess::kReadWrite,
map_info[n].target_address & granularity_mask));
if (!views_.all_views[n]) {
// Failed, so bail and try again.
UnmapViews();
return 1;
}
}
return 0;
}
void Memory::UnmapViews() {
for (size_t n = 0; n < xe::countof(views_.all_views); n++) {
if (views_.all_views[n]) {
size_t length = map_info[n].virtual_address_end -
map_info[n].virtual_address_start + 1;
xe::memory::UnmapFileView(mapping_, views_.all_views[n], length);
}
}
}
void Memory::Reset() {
heaps_.v00000000.Reset();
heaps_.v40000000.Reset();
heaps_.v80000000.Reset();
heaps_.v90000000.Reset();
heaps_.physical.Reset();
}
const BaseHeap* Memory::LookupHeap(uint32_t address) const {
if (address < 0x40000000) {
return &heaps_.v00000000;
} else if (address < 0x7F000000) {
return &heaps_.v40000000;
} else if (address < 0x80000000) {
return nullptr;
} else if (address < 0x90000000) {
return &heaps_.v80000000;
} else if (address < 0xA0000000) {
return &heaps_.v90000000;
} else if (address < 0xC0000000) {
return &heaps_.vA0000000;
} else if (address < 0xE0000000) {
return &heaps_.vC0000000;
} else if (address < 0xFFD00000) {
return &heaps_.vE0000000;
} else {
return nullptr;
}
}
BaseHeap* Memory::LookupHeapByType(bool physical, uint32_t page_size) {
if (physical) {
if (page_size <= 4096) {
return &heaps_.vE0000000;
} else if (page_size <= 64 * 1024) {
return &heaps_.vA0000000;
} else {
return &heaps_.vC0000000;
}
} else {
if (page_size <= 4096) {
return &heaps_.v00000000;
} else {
return &heaps_.v40000000;
}
}
}
VirtualHeap* Memory::GetPhysicalHeap() { return &heaps_.physical; }
uint32_t Memory::HostToGuestVirtual(const void* host_address) const {
size_t virtual_address = reinterpret_cast<size_t>(host_address) -
reinterpret_cast<size_t>(virtual_membase_);
uint32_t vE0000000_host_offset = heaps_.vE0000000.host_address_offset();
size_t vE0000000_host_base =
size_t(heaps_.vE0000000.heap_base()) + vE0000000_host_offset;
if (virtual_address >= vE0000000_host_base &&
virtual_address <=
(vE0000000_host_base + (heaps_.vE0000000.heap_size() - 1))) {
virtual_address -= vE0000000_host_offset;
}
return uint32_t(virtual_address);
}
uint32_t Memory::HostToGuestVirtualThunk(const void* context,
const void* host_address) {
return reinterpret_cast<const Memory*>(context)->HostToGuestVirtual(
host_address);
}
uint32_t Memory::GetPhysicalAddress(uint32_t address) const {
const BaseHeap* heap = LookupHeap(address);
if (!heap || !heap->IsGuestPhysicalHeap()) {
return UINT32_MAX;
}
return static_cast<const PhysicalHeap*>(heap)->GetPhysicalAddress(address);
}
void Memory::Zero(uint32_t address, uint32_t size) {
std::memset(TranslateVirtual(address), 0, size);
}
void Memory::Fill(uint32_t address, uint32_t size, uint8_t value) {
std::memset(TranslateVirtual(address), value, size);
}
void Memory::Copy(uint32_t dest, uint32_t src, uint32_t size) {
uint8_t* pdest = TranslateVirtual(dest);
const uint8_t* psrc = TranslateVirtual(src);
std::memcpy(pdest, psrc, size);
}
uint32_t Memory::SearchAligned(uint32_t start, uint32_t end,
const uint32_t* values, size_t value_count) {
assert_true(start <= end);
auto p = TranslateVirtual<const uint32_t*>(start);
auto pe = TranslateVirtual<const uint32_t*>(end);
while (p != pe) {
if (*p == values[0]) {
const uint32_t* pc = p + 1;
size_t matched = 1;
for (size_t n = 1; n < value_count; n++, pc++) {
if (*pc != values[n]) {
break;
}
matched++;
}
if (matched == value_count) {
return HostToGuestVirtual(p);
}
}
p++;
}
return 0;
}
bool Memory::AddVirtualMappedRange(uint32_t virtual_address, uint32_t mask,
uint32_t size, void* context,
cpu::MMIOReadCallback read_callback,
cpu::MMIOWriteCallback write_callback) {
if (!xe::memory::AllocFixed(TranslateVirtual(virtual_address), size,
xe::memory::AllocationType::kCommit,
xe::memory::PageAccess::kNoAccess)) {
XELOGE("Unable to map range; commit/protect failed");
return false;
}
return mmio_handler_->RegisterRange(virtual_address, mask, size, context,
read_callback, write_callback);
}
cpu::MMIORange* Memory::LookupVirtualMappedRange(uint32_t virtual_address) {
return mmio_handler_->LookupRange(virtual_address);
}
bool Memory::AccessViolationCallback(
std::unique_lock<std::recursive_mutex> global_lock_locked_once,
void* host_address, bool is_write) {
// Access via physical_membase_ is special, when need to bypass everything
// (for instance, for a data provider to actually write the data) so only
// triggering callbacks on virtual memory regions.
if (reinterpret_cast<size_t>(host_address) <
reinterpret_cast<size_t>(virtual_membase_) ||
reinterpret_cast<size_t>(host_address) >=
reinterpret_cast<size_t>(physical_membase_)) {
return false;
}
uint32_t virtual_address = HostToGuestVirtual(host_address);
BaseHeap* heap = LookupHeap(virtual_address);
if (!heap->IsGuestPhysicalHeap()) {
return false;
}
// Access violation callbacks from the guest are triggered when the global
// critical region mutex is locked once.
//
// Will be rounded to physical page boundaries internally, so just pass 1 as
// the length - guranteed not to cross page boundaries also.
auto physical_heap = static_cast<PhysicalHeap*>(heap);
return physical_heap->TriggerCallbacks(std::move(global_lock_locked_once),
virtual_address, 1, is_write, false);
}
bool Memory::AccessViolationCallbackThunk(
std::unique_lock<std::recursive_mutex> global_lock_locked_once,
void* context, void* host_address, bool is_write) {
return reinterpret_cast<Memory*>(context)->AccessViolationCallback(
std::move(global_lock_locked_once), host_address, is_write);
}
bool Memory::TriggerPhysicalMemoryCallbacks(
std::unique_lock<std::recursive_mutex> global_lock_locked_once,
uint32_t virtual_address, uint32_t length, bool is_write,
bool unwatch_exact_range, bool unprotect) {
BaseHeap* heap = LookupHeap(virtual_address);
if (heap->IsGuestPhysicalHeap()) {
auto physical_heap = static_cast<PhysicalHeap*>(heap);
return physical_heap->TriggerCallbacks(std::move(global_lock_locked_once),
virtual_address, length, is_write,
unwatch_exact_range, unprotect);
}
return false;
}
void* Memory::RegisterPhysicalMemoryInvalidationCallback(
PhysicalMemoryInvalidationCallback callback, void* callback_context) {
auto entry = new std::pair<PhysicalMemoryInvalidationCallback, void*>(
callback, callback_context);
auto lock = global_critical_region_.Acquire();
physical_memory_invalidation_callbacks_.push_back(entry);
return entry;
}
void Memory::UnregisterPhysicalMemoryInvalidationCallback(
void* callback_handle) {
auto entry =
reinterpret_cast<std::pair<PhysicalMemoryInvalidationCallback, void*>*>(
callback_handle);
{
auto lock = global_critical_region_.Acquire();
auto it = std::find(physical_memory_invalidation_callbacks_.begin(),
physical_memory_invalidation_callbacks_.end(), entry);
assert_true(it != physical_memory_invalidation_callbacks_.end());
if (it != physical_memory_invalidation_callbacks_.end()) {
physical_memory_invalidation_callbacks_.erase(it);
}
}
delete entry;
}
void Memory::EnablePhysicalMemoryAccessCallbacks(
uint32_t physical_address, uint32_t length,
bool enable_invalidation_notifications, bool enable_data_providers) {
heaps_.vA0000000.EnableAccessCallbacks(physical_address, length,
enable_invalidation_notifications,
enable_data_providers);
heaps_.vC0000000.EnableAccessCallbacks(physical_address, length,
enable_invalidation_notifications,
enable_data_providers);
heaps_.vE0000000.EnableAccessCallbacks(physical_address, length,
enable_invalidation_notifications,
enable_data_providers);
}
uint32_t Memory::SystemHeapAlloc(uint32_t size, uint32_t alignment,
uint32_t system_heap_flags) {
// TODO(benvanik): lightweight pool.
bool is_physical = !!(system_heap_flags & kSystemHeapPhysical);
auto heap = LookupHeapByType(is_physical, 4096);
uint32_t address;
if (!heap->Alloc(size, alignment,
kMemoryAllocationReserve | kMemoryAllocationCommit,
kMemoryProtectRead | kMemoryProtectWrite, false, &address)) {
return 0;
}
Zero(address, size);
return address;
}
void Memory::SystemHeapFree(uint32_t address) {
if (!address) {
return;
}
// TODO(benvanik): lightweight pool.
auto heap = LookupHeap(address);
heap->Release(address);
}
void Memory::DumpMap() {
XELOGE("==================================================================");
XELOGE("Memory Dump");
XELOGE("==================================================================");
XELOGE(" System Page Size: {0} ({0:08X})", system_page_size_);
XELOGE(" System Allocation Granularity: {0} ({0:08X})",
system_allocation_granularity_);
XELOGE(" Virtual Membase: {}", virtual_membase_);
XELOGE(" Physical Membase: {}", physical_membase_);
XELOGE("");
XELOGE("------------------------------------------------------------------");
XELOGE("Virtual Heaps");
XELOGE("------------------------------------------------------------------");
XELOGE("");
heaps_.v00000000.DumpMap();
heaps_.v40000000.DumpMap();
heaps_.v80000000.DumpMap();
heaps_.v90000000.DumpMap();
XELOGE("");
XELOGE("------------------------------------------------------------------");
XELOGE("Physical Heaps");
XELOGE("------------------------------------------------------------------");
XELOGE("");
heaps_.physical.DumpMap();
heaps_.vA0000000.DumpMap();
heaps_.vC0000000.DumpMap();
heaps_.vE0000000.DumpMap();
XELOGE("");
}
bool Memory::Save(ByteStream* stream) {
XELOGD("Serializing memory...");
heaps_.v00000000.Save(stream);
heaps_.v40000000.Save(stream);
heaps_.v80000000.Save(stream);
heaps_.v90000000.Save(stream);
heaps_.physical.Save(stream);
return true;
}
bool Memory::Restore(ByteStream* stream) {
XELOGD("Restoring memory...");
heaps_.v00000000.Restore(stream);
heaps_.v40000000.Restore(stream);
heaps_.v80000000.Restore(stream);
heaps_.v90000000.Restore(stream);
heaps_.physical.Restore(stream);
return true;
}
xe::memory::PageAccess ToPageAccess(uint32_t protect) {
if ((protect & kMemoryProtectRead) && !(protect & kMemoryProtectWrite)) {
return xe::memory::PageAccess::kReadOnly;
} else if ((protect & kMemoryProtectRead) &&
(protect & kMemoryProtectWrite)) {
return xe::memory::PageAccess::kReadWrite;
} else {
return xe::memory::PageAccess::kNoAccess;
}
}
uint32_t FromPageAccess(xe::memory::PageAccess protect) {
switch (protect) {
case memory::PageAccess::kNoAccess:
return kMemoryProtectNoAccess;
case memory::PageAccess::kReadOnly:
return kMemoryProtectRead;
case memory::PageAccess::kReadWrite:
return kMemoryProtectRead | kMemoryProtectWrite;
case memory::PageAccess::kExecuteReadWrite:
// Guest memory cannot be executable - this should never happen :)
assert_always();
return kMemoryProtectRead | kMemoryProtectWrite;
}
return kMemoryProtectNoAccess;
}
BaseHeap::BaseHeap()
: membase_(nullptr), heap_base_(0), heap_size_(0), page_size_(0) {}
BaseHeap::~BaseHeap() = default;
void BaseHeap::Initialize(Memory* memory, uint8_t* membase, uint32_t heap_base,
uint32_t heap_size, uint32_t page_size,
uint32_t host_address_offset) {
memory_ = memory;
membase_ = membase;
heap_base_ = heap_base;
heap_size_ = heap_size;
page_size_ = page_size;
host_address_offset_ = host_address_offset;
page_table_.resize(heap_size / page_size);
}
void BaseHeap::Dispose() {
// Walk table and release all regions.
for (uint32_t page_number = 0; page_number < page_table_.size();
++page_number) {
auto& page_entry = page_table_[page_number];
if (page_entry.state) {
xe::memory::DeallocFixed(TranslateRelative(page_number * page_size_), 0,
xe::memory::DeallocationType::kRelease);
page_number += page_entry.region_page_count;
}
}
}
void BaseHeap::DumpMap() {
auto global_lock = global_critical_region_.Acquire();
XELOGE("------------------------------------------------------------------");
XELOGE("Heap: {:08X}-{:08X}", heap_base_, heap_base_ + (heap_size_ - 1));
XELOGE("------------------------------------------------------------------");
XELOGE(" Heap Base: {:08X}", heap_base_);
XELOGE(" Heap Size: {0} ({0:08X})", heap_size_);
XELOGE(" Page Size: {0} ({0:08X})", page_size_);
XELOGE(" Page Count: {}", page_table_.size());
XELOGE(" Host Address Offset: {0} ({0:08X})", host_address_offset_);
bool is_empty_span = false;
uint32_t empty_span_start = 0;
for (uint32_t i = 0; i < uint32_t(page_table_.size()); ++i) {
auto& page = page_table_[i];
if (!page.state) {
if (!is_empty_span) {
is_empty_span = true;
empty_span_start = i;
}
continue;
}
if (is_empty_span) {
XELOGE(" {:08X}-{:08X} {:6d}p {:10d}b unreserved",
heap_base_ + empty_span_start * page_size_,
heap_base_ + i * page_size_, i - empty_span_start,
(i - empty_span_start) * page_size_);
is_empty_span = false;
}
const char* state_name = " ";
if (page.state & kMemoryAllocationCommit) {
state_name = "COM";
} else if (page.state & kMemoryAllocationReserve) {
state_name = "RES";
}
char access_r = (page.current_protect & kMemoryProtectRead) ? 'R' : ' ';
char access_w = (page.current_protect & kMemoryProtectWrite) ? 'W' : ' ';
XELOGE(" {:08X}-{:08X} {:6d}p {:10d}b {} {}{}",
heap_base_ + i * page_size_,
heap_base_ + (i + page.region_page_count) * page_size_,
page.region_page_count, page.region_page_count * page_size_,
state_name, access_r, access_w);
i += page.region_page_count - 1;
}
if (is_empty_span) {
XELOGE(" {:08X}-{:08X} - {} unreserved pages)",
heap_base_ + empty_span_start * page_size_,
heap_base_ + (heap_size_ - 1),
page_table_.size() - empty_span_start);
}
}
uint32_t BaseHeap::GetTotalPageCount() { return uint32_t(page_table_.size()); }
uint32_t BaseHeap::GetUnreservedPageCount() {
auto global_lock = global_critical_region_.Acquire();
uint32_t count = 0;
bool is_empty_span = false;
uint32_t empty_span_start = 0;
uint32_t size = uint32_t(page_table_.size());
for (uint32_t i = 0; i < size; ++i) {
auto& page = page_table_[i];
if (!page.state) {
if (!is_empty_span) {
is_empty_span = true;
empty_span_start = i;
}
continue;
}
if (is_empty_span) {
is_empty_span = false;
count += i - empty_span_start;
}
i += page.region_page_count - 1;
}
if (is_empty_span) {
count += size - empty_span_start;
}
return count;
}
bool BaseHeap::Save(ByteStream* stream) {
XELOGD("Heap {:08X}-{:08X}", heap_base_, heap_base_ + (heap_size_ - 1));
for (size_t i = 0; i < page_table_.size(); i++) {
auto& page = page_table_[i];
stream->Write(page.qword);
if (!page.state) {
// Unallocated.
continue;
}
// TODO(DrChat): write compressed with snappy.
if (page.state & kMemoryAllocationCommit) {
void* addr = TranslateRelative(i * page_size_);
memory::PageAccess old_access;
memory::Protect(addr, page_size_, memory::PageAccess::kReadWrite,
&old_access);
stream->Write(addr, page_size_);
memory::Protect(addr, page_size_, old_access, nullptr);
}
}
return true;
}
bool BaseHeap::Restore(ByteStream* stream) {
XELOGD("Heap {:08X}-{:08X}", heap_base_, heap_base_ + (heap_size_ - 1));
for (size_t i = 0; i < page_table_.size(); i++) {
auto& page = page_table_[i];
page.qword = stream->Read<uint64_t>();
if (!page.state) {
// Unallocated.
continue;
}
memory::PageAccess page_access = memory::PageAccess::kNoAccess;
if ((page.current_protect & kMemoryProtectRead) &&
(page.current_protect & kMemoryProtectWrite)) {
page_access = memory::PageAccess::kReadWrite;
} else if (page.current_protect & kMemoryProtectRead) {
page_access = memory::PageAccess::kReadOnly;
}
// Commit the memory if it isn't already. We do not need to reserve any
// memory, as the mapping has already taken care of that.
if (page.state & kMemoryAllocationCommit) {
xe::memory::AllocFixed(TranslateRelative(i * page_size_), page_size_,
memory::AllocationType::kCommit,
memory::PageAccess::kReadWrite);
}
// Now read into memory. We'll set R/W protection first, then set the
// protection back to its previous state.
// TODO(DrChat): read compressed with snappy.
if (page.state & kMemoryAllocationCommit) {
void* addr = TranslateRelative(i * page_size_);
xe::memory::Protect(addr, page_size_, memory::PageAccess::kReadWrite,
nullptr);
stream->Read(addr, page_size_);
xe::memory::Protect(addr, page_size_, page_access, nullptr);
}
}
return true;
}
void BaseHeap::Reset() {
// TODO(DrChat): protect pages.
std::memset(page_table_.data(), 0, sizeof(PageEntry) * page_table_.size());
// TODO(Triang3l): Remove access callbacks from pages if this is a physical
// memory heap.
}
bool BaseHeap::Alloc(uint32_t size, uint32_t alignment,
uint32_t allocation_type, uint32_t protect, bool top_down,
uint32_t* out_address) {
*out_address = 0;
size = xe::round_up(size, page_size_);
alignment = xe::round_up(alignment, page_size_);
uint32_t low_address = heap_base_;
uint32_t high_address = heap_base_ + (heap_size_ - 1);
return AllocRange(low_address, high_address, size, alignment, allocation_type,
protect, top_down, out_address);
}
bool BaseHeap::AllocFixed(uint32_t base_address, uint32_t size,
uint32_t alignment, uint32_t allocation_type,
uint32_t protect) {
alignment = xe::round_up(alignment, page_size_);
size = xe::align(size, alignment);
assert_true(base_address % alignment == 0);
uint32_t page_count = get_page_count(size, page_size_);
uint32_t start_page_number = (base_address - heap_base_) / page_size_;
uint32_t end_page_number = start_page_number + page_count - 1;
if (start_page_number >= page_table_.size() ||
end_page_number > page_table_.size()) {
XELOGE("BaseHeap::AllocFixed passed out of range address range");
return false;
}
auto global_lock = global_critical_region_.Acquire();
// - If we are reserving the entire range requested must not be already
// reserved.
// - If we are committing it's ok for pages within the range to already be
// committed.
for (uint32_t page_number = start_page_number; page_number <= end_page_number;
++page_number) {
uint32_t state = page_table_[page_number].state;
if ((allocation_type == kMemoryAllocationReserve) && state) {
// Already reserved.
XELOGE(
"BaseHeap::AllocFixed attempting to reserve an already reserved "
"range");
return false;
}
if ((allocation_type == kMemoryAllocationCommit) &&
!(state & kMemoryAllocationReserve)) {
// Attempting a commit-only op on an unreserved page.
// This may be OK.
XELOGW("BaseHeap::AllocFixed attempting commit on unreserved page");
allocation_type |= kMemoryAllocationReserve;
break;
}
}
// Allocate from host.
if (allocation_type == kMemoryAllocationReserve) {
// Reserve is not needed, as we are mapped already.
} else {
auto alloc_type = (allocation_type & kMemoryAllocationCommit)
? xe::memory::AllocationType::kCommit
: xe::memory::AllocationType::kReserve;
void* result = xe::memory::AllocFixed(
TranslateRelative(start_page_number * page_size_),
page_count * page_size_, alloc_type, ToPageAccess(protect));
if (!result) {
XELOGE("BaseHeap::AllocFixed failed to alloc range from host");
return false;
}
if (cvars::scribble_heap && protect & kMemoryProtectWrite) {
std::memset(result, 0xCD, page_count * page_size_);
}
}
// Set page state.
for (uint32_t page_number = start_page_number; page_number <= end_page_number;
++page_number) {
auto& page_entry = page_table_[page_number];
if (allocation_type & kMemoryAllocationReserve) {
// Region is based on reservation.
page_entry.base_address = start_page_number;
page_entry.region_page_count = page_count;
}
page_entry.allocation_protect = protect;
page_entry.current_protect = protect;
page_entry.state = kMemoryAllocationReserve | allocation_type;
}
return true;
}
bool BaseHeap::AllocRange(uint32_t low_address, uint32_t high_address,
uint32_t size, uint32_t alignment,
uint32_t allocation_type, uint32_t protect,
bool top_down, uint32_t* out_address) {
*out_address = 0;
alignment = xe::round_up(alignment, page_size_);
uint32_t page_count = get_page_count(size, page_size_);
low_address = std::max(heap_base_, xe::align(low_address, alignment));
high_address = std::min(heap_base_ + (heap_size_ - 1),
xe::align(high_address, alignment));
uint32_t low_page_number = (low_address - heap_base_) / page_size_;
uint32_t high_page_number = (high_address - heap_base_) / page_size_;
low_page_number = std::min(uint32_t(page_table_.size()) - 1, low_page_number);
high_page_number =
std::min(uint32_t(page_table_.size()) - 1, high_page_number);
if (page_count > (high_page_number - low_page_number)) {
XELOGE("BaseHeap::Alloc page count too big for requested range");
return false;
}
auto global_lock = global_critical_region_.Acquire();
// Find a free page range.
// The base page must match the requested alignment, so we first scan for
// a free aligned page and only then check for continuous free pages.
// TODO(benvanik): optimized searching (free list buckets, bitmap, etc).
uint32_t start_page_number = UINT_MAX;
uint32_t end_page_number = UINT_MAX;
uint32_t page_scan_stride = alignment / page_size_;
high_page_number = high_page_number - (high_page_number % page_scan_stride);
if (top_down) {
for (int64_t base_page_number =
high_page_number - xe::round_up(page_count, page_scan_stride);
base_page_number >= low_page_number;
base_page_number -= page_scan_stride) {
if (page_table_[base_page_number].state != 0) {
// Base page not free, skip to next usable page.
continue;
}
// Check requested range to ensure free.
start_page_number = uint32_t(base_page_number);
end_page_number = uint32_t(base_page_number) + page_count - 1;
assert_true(end_page_number < page_table_.size());
bool any_taken = false;
for (uint32_t page_number = uint32_t(base_page_number);
!any_taken && page_number <= end_page_number; ++page_number) {
bool is_free = page_table_[page_number].state == 0;
if (!is_free) {
// At least one page in the range is used, skip to next.
// We know we'll be starting at least before this page.
any_taken = true;
if (page_count > page_number) {
// Not enough space left to fit entire page range. Breaks outer
// loop.
base_page_number = -1;
} else {
base_page_number = page_number - page_count;
base_page_number -= base_page_number % page_scan_stride;
base_page_number += page_scan_stride; // cancel out loop logic
}
break;
}
}
if (!any_taken) {
// Found our place.
break;
}
// Retry.
start_page_number = end_page_number = UINT_MAX;
}
} else {
for (uint32_t base_page_number = low_page_number;
base_page_number <= high_page_number - page_count;
base_page_number += page_scan_stride) {
if (page_table_[base_page_number].state != 0) {
// Base page not free, skip to next usable page.
continue;
}
// Check requested range to ensure free.
start_page_number = base_page_number;
end_page_number = base_page_number + page_count - 1;
bool any_taken = false;
for (uint32_t page_number = base_page_number;
!any_taken && page_number <= end_page_number; ++page_number) {
bool is_free = page_table_[page_number].state == 0;
if (!is_free) {
// At least one page in the range is used, skip to next.
// We know we'll be starting at least after this page.
any_taken = true;
base_page_number = xe::round_up(page_number + 1, page_scan_stride);
base_page_number -= page_scan_stride; // cancel out loop logic
break;
}
}
if (!any_taken) {
// Found our place.
break;
}
// Retry.
start_page_number = end_page_number = UINT_MAX;
}
}
if (start_page_number == UINT_MAX || end_page_number == UINT_MAX) {
// Out of memory.
XELOGE("BaseHeap::Alloc failed to find contiguous range");
assert_always("Heap exhausted!");
return false;
}
// Allocate from host.
if (allocation_type == kMemoryAllocationReserve) {
// Reserve is not needed, as we are mapped already.
} else {
auto alloc_type = (allocation_type & kMemoryAllocationCommit)
? xe::memory::AllocationType::kCommit
: xe::memory::AllocationType::kReserve;
void* result = xe::memory::AllocFixed(
TranslateRelative(start_page_number * page_size_),
page_count * page_size_, alloc_type, ToPageAccess(protect));
if (!result) {
XELOGE("BaseHeap::Alloc failed to alloc range from host");
return false;
}
if (cvars::scribble_heap && (protect & kMemoryProtectWrite)) {
std::memset(result, 0xCD, page_count * page_size_);
}
}
// Set page state.
for (uint32_t page_number = start_page_number; page_number <= end_page_number;
++page_number) {
auto& page_entry = page_table_[page_number];
page_entry.base_address = start_page_number;
page_entry.region_page_count = page_count;
page_entry.allocation_protect = protect;
page_entry.current_protect = protect;
page_entry.state = kMemoryAllocationReserve | allocation_type;
}
*out_address = heap_base_ + (start_page_number * page_size_);
return true;
}
bool BaseHeap::Decommit(uint32_t address, uint32_t size) {
uint32_t page_count = get_page_count(size, page_size_);
uint32_t start_page_number = (address - heap_base_) / page_size_;
uint32_t end_page_number = start_page_number + page_count - 1;
start_page_number =
std::min(uint32_t(page_table_.size()) - 1, start_page_number);
end_page_number = std::min(uint32_t(page_table_.size()) - 1, end_page_number);
auto global_lock = global_critical_region_.Acquire();
// Release from host.
// TODO(benvanik): find a way to actually decommit memory;
// mapped memory cannot be decommitted.
/*BOOL result =
VirtualFree(TranslateRelative(start_page_number * page_size_),
page_count * page_size_, MEM_DECOMMIT);
if (!result) {
PLOGW("BaseHeap::Decommit failed due to host VirtualFree failure");
return false;
}*/
// Perform table change.
for (uint32_t page_number = start_page_number; page_number <= end_page_number;
++page_number) {
auto& page_entry = page_table_[page_number];
page_entry.state &= ~kMemoryAllocationCommit;
}
return true;
}
bool BaseHeap::Release(uint32_t base_address, uint32_t* out_region_size) {
auto global_lock = global_critical_region_.Acquire();
// Given address must be a region base address.
uint32_t base_page_number = (base_address - heap_base_) / page_size_;
auto base_page_entry = page_table_[base_page_number];
if (base_page_entry.base_address != base_page_number) {
XELOGE("BaseHeap::Release failed because address is not a region start");
return false;
}
if (heap_base_ == 0x00000000 && base_page_number == 0) {
XELOGE("BaseHeap::Release: Attempt to free 0!");
return false;
}
if (out_region_size) {
*out_region_size = (base_page_entry.region_page_count * page_size_);
}
// Release from host not needed as mapping reserves the range for us.
// TODO(benvanik): protect with NOACCESS?
/*BOOL result = VirtualFree(
TranslateRelative(base_page_number * page_size_), 0, MEM_RELEASE);
if (!result) {
PLOGE("BaseHeap::Release failed due to host VirtualFree failure");
return false;
}*/
// Instead, we just protect it, if we can.
if (page_size_ == xe::memory::page_size() ||
((base_page_entry.region_page_count * page_size_) %
xe::memory::page_size() ==
0 &&
((base_page_number * page_size_) % xe::memory::page_size() == 0))) {
// TODO(benvanik): figure out why games are using memory after releasing
// it. It's possible this is some virtual/physical stuff where the GPU
// still can access it.
if (cvars::protect_on_release) {
if (!xe::memory::Protect(TranslateRelative(base_page_number * page_size_),
base_page_entry.region_page_count * page_size_,
xe::memory::PageAccess::kNoAccess, nullptr)) {
XELOGW("BaseHeap::Release failed due to host VirtualProtect failure");
}
}
}
// Perform table change.
uint32_t end_page_number =
base_page_number + base_page_entry.region_page_count - 1;
for (uint32_t page_number = base_page_number; page_number <= end_page_number;
++page_number) {
auto& page_entry = page_table_[page_number];
page_entry.qword = 0;
}
return true;
}
bool BaseHeap::Protect(uint32_t address, uint32_t size, uint32_t protect,
uint32_t* old_protect) {
if (!size) {
XELOGE("BaseHeap::Protect failed due to zero size");
return false;
}
// From the VirtualProtect MSDN page:
//
// "The region of affected pages includes all pages containing one or more
// bytes in the range from the lpAddress parameter to (lpAddress+dwSize).
// This means that a 2-byte range straddling a page boundary causes the
// protection attributes of both pages to be changed."
//
// "The access protection value can be set only on committed pages. If the
// state of any page in the specified region is not committed, the function
// fails and returns without modifying the access protection of any pages in
// the specified region."
uint32_t start_page_number = (address - heap_base_) / page_size_;
if (start_page_number >= page_table_.size()) {
XELOGE("BaseHeap::Protect failed due to out-of-bounds base address {:08X}",
address);
return false;
}
uint32_t end_page_number =
uint32_t((uint64_t(address) + size - 1 - heap_base_) / page_size_);
if (end_page_number >= page_table_.size()) {
XELOGE(
"BaseHeap::Protect failed due to out-of-bounds range ({:08X} bytes "
"from {:08x})",
size, address);
return false;
}
auto global_lock = global_critical_region_.Acquire();
// Ensure all pages are in the same reserved region and all are committed.
uint32_t first_base_address = UINT_MAX;
for (uint32_t page_number = start_page_number; page_number <= end_page_number;
++page_number) {
auto page_entry = page_table_[page_number];
if (first_base_address == UINT_MAX) {
first_base_address = page_entry.base_address;
} else if (first_base_address != page_entry.base_address) {
XELOGE("BaseHeap::Protect failed due to request spanning regions");
return false;
}
if (!(page_entry.state & kMemoryAllocationCommit)) {
XELOGE("BaseHeap::Protect failed due to uncommitted page");
return false;
}
}
// Attempt host change (hopefully won't fail).
// We can only do this if our size matches system page granularity.
uint32_t page_count = end_page_number - start_page_number + 1;
if (page_size_ == xe::memory::page_size() ||
(((page_count * page_size_) % xe::memory::page_size() == 0) &&
((start_page_number * page_size_) % xe::memory::page_size() == 0))) {
memory::PageAccess old_protect_access;
if (!xe::memory::Protect(TranslateRelative(start_page_number * page_size_),
page_count * page_size_, ToPageAccess(protect),
old_protect ? &old_protect_access : nullptr)) {
XELOGE("BaseHeap::Protect failed due to host VirtualProtect failure");
return false;
}
if (old_protect) {
*old_protect = FromPageAccess(old_protect_access);
}
} else {
XELOGW("BaseHeap::Protect: ignoring request as not 4k page aligned");
return false;
}
// Perform table change.
for (uint32_t page_number = start_page_number; page_number <= end_page_number;
++page_number) {
auto& page_entry = page_table_[page_number];
page_entry.current_protect = protect;
}
return true;
}
bool BaseHeap::QueryRegionInfo(uint32_t base_address,
HeapAllocationInfo* out_info) {
uint32_t start_page_number = (base_address - heap_base_) / page_size_;
if (start_page_number > page_table_.size()) {
XELOGE("BaseHeap::QueryRegionInfo base page out of range");
return false;
}
auto global_lock = global_critical_region_.Acquire();
auto start_page_entry = page_table_[start_page_number];
out_info->base_address = base_address;
out_info->allocation_base = 0;
out_info->allocation_protect = 0;
out_info->region_size = 0;
out_info->state = 0;
out_info->protect = 0;
if (start_page_entry.state) {
// Committed/reserved region.
out_info->allocation_base = start_page_entry.base_address * page_size_;
out_info->allocation_protect = start_page_entry.allocation_protect;
out_info->allocation_size = start_page_entry.region_page_count * page_size_;
out_info->state = start_page_entry.state;
out_info->protect = start_page_entry.current_protect;
// Scan forward and report the size of the region matching the initial
// base address's attributes.
for (uint32_t page_number = start_page_number;
page_number <
start_page_entry.base_address + start_page_entry.region_page_count;
++page_number) {
auto page_entry = page_table_[page_number];
if (page_entry.base_address != start_page_entry.base_address ||
page_entry.state != start_page_entry.state ||
page_entry.current_protect != start_page_entry.current_protect) {
// Different region or different properties within the region; done.
break;
}
out_info->region_size += page_size_;
}
} else {
// Free region.
for (uint32_t page_number = start_page_number;
page_number < page_table_.size(); ++page_number) {
auto page_entry = page_table_[page_number];
if (page_entry.state) {
// First non-free page; done with region.
break;
}
out_info->region_size += page_size_;
}
}
return true;
}
bool BaseHeap::QuerySize(uint32_t address, uint32_t* out_size) {
uint32_t page_number = (address - heap_base_) / page_size_;
if (page_number > page_table_.size()) {
XELOGE("BaseHeap::QuerySize base page out of range");
*out_size = 0;
return false;
}
auto global_lock = global_critical_region_.Acquire();
auto page_entry = page_table_[page_number];
*out_size = (page_entry.region_page_count * page_size_);
return true;
}
bool BaseHeap::QueryBaseAndSize(uint32_t* in_out_address, uint32_t* out_size) {
uint32_t page_number = (*in_out_address - heap_base_) / page_size_;
if (page_number > page_table_.size()) {
XELOGE("BaseHeap::QuerySize base page out of range");
*out_size = 0;
return false;
}
auto global_lock = global_critical_region_.Acquire();
auto page_entry = page_table_[page_number];
*in_out_address = (page_entry.base_address * page_size_);
*out_size = (page_entry.region_page_count * page_size_);
return true;
}
bool BaseHeap::QueryProtect(uint32_t address, uint32_t* out_protect) {
uint32_t page_number = (address - heap_base_) / page_size_;
if (page_number > page_table_.size()) {
XELOGE("BaseHeap::QueryProtect base page out of range");
*out_protect = 0;
return false;
}
auto global_lock = global_critical_region_.Acquire();
auto page_entry = page_table_[page_number];
*out_protect = page_entry.current_protect;
return true;
}
xe::memory::PageAccess BaseHeap::QueryRangeAccess(uint32_t low_address,
uint32_t high_address) {
if (low_address > high_address || low_address < heap_base_ ||
(high_address - heap_base_) >= heap_size_) {
return xe::memory::PageAccess::kNoAccess;
}
uint32_t low_page_number = (low_address - heap_base_) / page_size_;
uint32_t high_page_number = (high_address - heap_base_) / page_size_;
uint32_t protect = kMemoryProtectRead | kMemoryProtectWrite;
{
auto global_lock = global_critical_region_.Acquire();
for (uint32_t i = low_page_number; protect && i <= high_page_number; ++i) {
protect &= page_table_[i].current_protect;
}
}
return ToPageAccess(protect);
}
VirtualHeap::VirtualHeap() = default;
VirtualHeap::~VirtualHeap() = default;
void VirtualHeap::Initialize(Memory* memory, uint8_t* membase,
uint32_t heap_base, uint32_t heap_size,
uint32_t page_size) {
BaseHeap::Initialize(memory, membase, heap_base, heap_size, page_size);
}
PhysicalHeap::PhysicalHeap() : parent_heap_(nullptr) {}
PhysicalHeap::~PhysicalHeap() = default;
void PhysicalHeap::Initialize(Memory* memory, uint8_t* membase,
uint32_t heap_base, uint32_t heap_size,
uint32_t page_size, VirtualHeap* parent_heap) {
uint32_t host_address_offset;
if (heap_base >= 0xE0000000 &&
xe::memory::allocation_granularity() > 0x1000) {
host_address_offset = 0x1000;
} else {
host_address_offset = 0;
}
BaseHeap::Initialize(memory, membase, heap_base, heap_size, page_size,
host_address_offset);
parent_heap_ = parent_heap;
system_page_size_ = uint32_t(xe::memory::page_size());
system_page_count_ =
(size_t(heap_size_) + host_address_offset + (system_page_size_ - 1)) /
system_page_size_;
system_page_flags_.resize((system_page_count_ + 63) / 64);
}
bool PhysicalHeap::Alloc(uint32_t size, uint32_t alignment,
uint32_t allocation_type, uint32_t protect,
bool top_down, uint32_t* out_address) {
*out_address = 0;
// Default top-down. Since parent heap is bottom-up this prevents
// collisions.
top_down = true;
// Adjust alignment size our page size differs from the parent.
size = xe::round_up(size, page_size_);
alignment = xe::round_up(alignment, page_size_);
auto global_lock = global_critical_region_.Acquire();
// Allocate from parent heap (gets our physical address in 0-512mb).
uint32_t parent_heap_start = GetPhysicalAddress(heap_base_);
uint32_t parent_heap_end = GetPhysicalAddress(heap_base_ + (heap_size_ - 1));
uint32_t parent_address;
if (!parent_heap_->AllocRange(parent_heap_start, parent_heap_end, size,
alignment, allocation_type, protect, top_down,
&parent_address)) {
XELOGE(
"PhysicalHeap::Alloc unable to alloc physical memory in parent heap");
return false;
}
// Given the address we've reserved in the parent heap, pin that here.
// Shouldn't be possible for it to be allocated already.
uint32_t address = heap_base_ + parent_address - parent_heap_start;
if (!BaseHeap::AllocFixed(address, size, alignment, allocation_type,
protect)) {
XELOGE(
"PhysicalHeap::Alloc unable to pin physical memory in physical heap");
// TODO(benvanik): don't leak parent memory.
return false;
}
*out_address = address;
return true;
}
bool PhysicalHeap::AllocFixed(uint32_t base_address, uint32_t size,
uint32_t alignment, uint32_t allocation_type,
uint32_t protect) {
// Adjust alignment size our page size differs from the parent.
size = xe::round_up(size, page_size_);
alignment = xe::round_up(alignment, page_size_);
auto global_lock = global_critical_region_.Acquire();
// Allocate from parent heap (gets our physical address in 0-512mb).
// NOTE: this can potentially overwrite heap contents if there are already
// committed pages in the requested physical range.
// TODO(benvanik): flag for ensure-not-committed?
uint32_t parent_base_address = GetPhysicalAddress(base_address);
if (!parent_heap_->AllocFixed(parent_base_address, size, alignment,
allocation_type, protect)) {
XELOGE(
"PhysicalHeap::Alloc unable to alloc physical memory in parent heap");
return false;
}
// Given the address we've reserved in the parent heap, pin that here.
// Shouldn't be possible for it to be allocated already.
uint32_t address =
heap_base_ + parent_base_address - GetPhysicalAddress(heap_base_);
if (!BaseHeap::AllocFixed(address, size, alignment, allocation_type,
protect)) {
XELOGE(
"PhysicalHeap::Alloc unable to pin physical memory in physical heap");
// TODO(benvanik): don't leak parent memory.
return false;
}
return true;
}
bool PhysicalHeap::AllocRange(uint32_t low_address, uint32_t high_address,
uint32_t size, uint32_t alignment,
uint32_t allocation_type, uint32_t protect,
bool top_down, uint32_t* out_address) {
*out_address = 0;
// Adjust alignment size our page size differs from the parent.
size = xe::round_up(size, page_size_);
alignment = xe::round_up(alignment, page_size_);
auto global_lock = global_critical_region_.Acquire();
// Allocate from parent heap (gets our physical address in 0-512mb).
low_address = std::max(heap_base_, low_address);
high_address = std::min(heap_base_ + (heap_size_ - 1), high_address);
uint32_t parent_low_address = GetPhysicalAddress(low_address);
uint32_t parent_high_address = GetPhysicalAddress(high_address);
uint32_t parent_address;
if (!parent_heap_->AllocRange(parent_low_address, parent_high_address, size,
alignment, allocation_type, protect, top_down,
&parent_address)) {
XELOGE(
"PhysicalHeap::Alloc unable to alloc physical memory in parent heap");
return false;
}
// Given the address we've reserved in the parent heap, pin that here.
// Shouldn't be possible for it to be allocated already.
uint32_t address =
heap_base_ + parent_address - GetPhysicalAddress(heap_base_);
if (!BaseHeap::AllocFixed(address, size, alignment, allocation_type,
protect)) {
XELOGE(
"PhysicalHeap::Alloc unable to pin physical memory in physical heap");
// TODO(benvanik): don't leak parent memory.
return false;
}
*out_address = address;
return true;
}
bool PhysicalHeap::Decommit(uint32_t address, uint32_t size) {
auto global_lock = global_critical_region_.Acquire();
uint32_t parent_address = GetPhysicalAddress(address);
if (!parent_heap_->Decommit(parent_address, size)) {
XELOGE("PhysicalHeap::Decommit failed due to parent heap failure");
return false;
}
// Not caring about the contents anymore.
TriggerCallbacks(std::move(global_lock), address, size, true, true);
return BaseHeap::Decommit(address, size);
}
bool PhysicalHeap::Release(uint32_t base_address, uint32_t* out_region_size) {
auto global_lock = global_critical_region_.Acquire();
uint32_t parent_base_address = GetPhysicalAddress(base_address);
if (!parent_heap_->Release(parent_base_address, out_region_size)) {
XELOGE("PhysicalHeap::Release failed due to parent heap failure");
return false;
}
// Must invalidate here because the range being released may be reused in
// another mapping of physical memory - but callback flags are set in each
// heap separately (https://github.com/xenia-project/xenia/issues/1559 -
// dynamic vertices in Viva Pinata start screen and menu allocated in
// 0xA0000000 at addresses that overlap intro video textures in 0xE0000000,
// with the state of the allocator as of February 24th, 2020). If memory is
// invalidated in Alloc instead, Alloc won't be aware of callbacks enabled in
// other heaps, thus callback handlers will keep considering this range valid
// forever.
uint32_t region_size;
if (QuerySize(base_address, ®ion_size)) {
TriggerCallbacks(std::move(global_lock), base_address, region_size, true,
true);
}
return BaseHeap::Release(base_address, out_region_size);
}
bool PhysicalHeap::Protect(uint32_t address, uint32_t size, uint32_t protect,
uint32_t* old_protect) {
auto global_lock = global_critical_region_.Acquire();
// Only invalidate if making writable again, for simplicity - not when simply
// marking some range as immutable, for instance.
if (protect & kMemoryProtectWrite) {
TriggerCallbacks(std::move(global_lock), address, size, true, true, false);
}
if (!parent_heap_->Protect(GetPhysicalAddress(address), size, protect,
old_protect)) {
XELOGE("PhysicalHeap::Protect failed due to parent heap failure");
return false;
}
return BaseHeap::Protect(address, size, protect);
}
void PhysicalHeap::EnableAccessCallbacks(uint32_t physical_address,
uint32_t length,
bool enable_invalidation_notifications,
bool enable_data_providers) {
// TODO(Triang3l): Implement data providers.
assert_false(enable_data_providers);
if (!enable_invalidation_notifications && !enable_data_providers) {
return;
}
uint32_t physical_address_offset = GetPhysicalAddress(heap_base_);
if (physical_address < physical_address_offset) {
if (physical_address_offset - physical_address >= length) {
return;
}
length -= physical_address_offset - physical_address;
physical_address = physical_address_offset;
}
uint32_t heap_relative_address = physical_address - physical_address_offset;
if (heap_relative_address >= heap_size_) {
return;
}
length = std::min(length, heap_size_ - heap_relative_address);
if (length == 0) {
return;
}
uint32_t system_page_first =
(heap_relative_address + host_address_offset()) / system_page_size_;
uint32_t system_page_last =
(heap_relative_address + length - 1 + host_address_offset()) /
system_page_size_;
system_page_last = std::min(system_page_last, system_page_count_ - 1);
assert_true(system_page_first <= system_page_last);
// Update callback flags for system pages and make their protection stricter
// if needed.
xe::memory::PageAccess protect_access =
enable_data_providers ? xe::memory::PageAccess::kNoAccess
: xe::memory::PageAccess::kReadOnly;
uint8_t* protect_base = membase_ + heap_base_;
uint32_t protect_system_page_first = UINT32_MAX;
auto global_lock = global_critical_region_.Acquire();
for (uint32_t i = system_page_first; i <= system_page_last; ++i) {
// Check if need to enable callbacks for the page and raise its protection.
//
// If enabling invalidation notifications:
// - Page writable and not watched for changes yet - protect and enable
// invalidation notifications.
// - Page seen as writable by the guest, but only needs data providers -
// just set the bits to enable invalidation notifications (already has
// even stricter protection than needed).
// - Page not writable as requested by the game - don't do anything (need
// real access violations here).
// If enabling data providers:
// - Page accessible (either read/write or read-only) and didn't need data
// providers initially - protect and enable data providers.
// - Otherwise - do nothing.
//
// It's safe not to await data provider completion here before protecting as
// this never makes protection lighter, so it can't interfere with page
// faults that await data providers.
//
// Enabling data providers doesn't need to be deferred - providers will be
// polled for the last time without releasing the lock.
SystemPageFlagsBlock& page_flags_block = system_page_flags_[i >> 6];
uint64_t page_flags_bit = uint64_t(1) << (i & 63);
uint32_t guest_page_number =
xe::sat_sub(i * system_page_size_, host_address_offset()) / page_size_;
xe::memory::PageAccess current_page_access =
ToPageAccess(page_table_[guest_page_number].current_protect);
bool protect_system_page = false;
// Don't do anything with inaccessible pages - don't protect, don't enable
// callbacks - because real access violations are needed there. And don't
// enable invalidation notifications for read-only pages for the same
// reason.
if (current_page_access != xe::memory::PageAccess::kNoAccess) {
// TODO(Triang3l): Enable data providers.
if (enable_invalidation_notifications) {
if (current_page_access != xe::memory::PageAccess::kReadOnly &&
(page_flags_block.notify_on_invalidation & page_flags_bit) == 0) {
// TODO(Triang3l): Check if data providers are already enabled.
// If data providers are already enabled for the page, it has even
// stricter protection.
protect_system_page = true;
page_flags_block.notify_on_invalidation |= page_flags_bit;
}
}
}
if (protect_system_page) {
if (protect_system_page_first == UINT32_MAX) {
protect_system_page_first = i;
}
} else {
if (protect_system_page_first != UINT32_MAX) {
xe::memory::Protect(
protect_base + protect_system_page_first * system_page_size_,
(i - protect_system_page_first) * system_page_size_,
protect_access);
protect_system_page_first = UINT32_MAX;
}
}
}
if (protect_system_page_first != UINT32_MAX) {
xe::memory::Protect(
protect_base + protect_system_page_first * system_page_size_,
(system_page_last + 1 - protect_system_page_first) * system_page_size_,
protect_access);
}
}
bool PhysicalHeap::TriggerCallbacks(
std::unique_lock<std::recursive_mutex> global_lock_locked_once,
uint32_t virtual_address, uint32_t length, bool is_write,
bool unwatch_exact_range, bool unprotect) {
// TODO(Triang3l): Support read watches.
assert_true(is_write);
if (!is_write) {
return false;
}
if (virtual_address < heap_base_) {
if (heap_base_ - virtual_address >= length) {
return false;
}
length -= heap_base_ - virtual_address;
virtual_address = heap_base_;
}
uint32_t heap_relative_address = virtual_address - heap_base_;
if (heap_relative_address >= heap_size_) {
return false;
}
length = std::min(length, heap_size_ - heap_relative_address);
if (length == 0) {
return false;
}
uint32_t system_page_first =
(heap_relative_address + host_address_offset()) / system_page_size_;
uint32_t system_page_last =
(heap_relative_address + length - 1 + host_address_offset()) /
system_page_size_;
system_page_last = std::min(system_page_last, system_page_count_ - 1);
assert_true(system_page_first <= system_page_last);
uint32_t block_index_first = system_page_first >> 6;
uint32_t block_index_last = system_page_last >> 6;
// Check if watching any page, whether need to call the callback at all.
bool any_watched = false;
for (uint32_t i = block_index_first; i <= block_index_last; ++i) {
uint64_t block = system_page_flags_[i].notify_on_invalidation;
if (i == block_index_first) {
block &= ~((uint64_t(1) << (system_page_first & 63)) - 1);
}
if (i == block_index_last && (system_page_last & 63) != 63) {
block &= (uint64_t(1) << ((system_page_last & 63) + 1)) - 1;
}
if (block) {
any_watched = true;
break;
}
}
if (!any_watched) {
return false;
}
// Trigger callbacks.
if (!unprotect) {
// If not doing anything with protection, no point in unwatching excess
// pages.
unwatch_exact_range = true;
}
uint32_t physical_address_offset = GetPhysicalAddress(heap_base_);
uint32_t physical_address_start =
xe::sat_sub(system_page_first * system_page_size_,
host_address_offset()) +
physical_address_offset;
uint32_t physical_length = std::min(
xe::sat_sub(system_page_last * system_page_size_ + system_page_size_,
host_address_offset()) +
physical_address_offset - physical_address_start,
heap_size_ - (physical_address_start - physical_address_offset));
uint32_t unwatch_first = 0;
uint32_t unwatch_last = UINT32_MAX;
for (auto invalidation_callback :
memory_->physical_memory_invalidation_callbacks_) {
std::pair<uint32_t, uint32_t> callback_unwatch_range =
invalidation_callback->first(invalidation_callback->second,
physical_address_start, physical_length,
unwatch_exact_range);
if (!unwatch_exact_range) {
unwatch_first = std::max(unwatch_first, callback_unwatch_range.first);
unwatch_last = std::min(
unwatch_last,
xe::sat_add(
callback_unwatch_range.first,
std::max(callback_unwatch_range.second, uint32_t(1)) - 1));
}
}
if (!unwatch_exact_range) {
// Always unwatch at least the requested pages.
unwatch_first = std::min(unwatch_first, physical_address_start);
unwatch_last =
std::max(unwatch_last, physical_address_start + physical_length - 1);
// Don't unprotect too much if not caring much about the region (limit to
// 4 MB - somewhat random, but max 1024 iterations of the page loop).
const uint32_t kMaxUnwatchExcess = 4 * 1024 * 1024;
unwatch_first = std::max(unwatch_first,
physical_address_start & ~(kMaxUnwatchExcess - 1));
unwatch_last =
std::min(unwatch_last, (physical_address_start + physical_length - 1) |
(kMaxUnwatchExcess - 1));
// Convert to heap-relative addresses.
unwatch_first = xe::sat_sub(unwatch_first, physical_address_offset);
unwatch_last = xe::sat_sub(unwatch_last, physical_address_offset);
// Clamp to the heap upper bound.
unwatch_first = std::min(unwatch_first, heap_size_ - 1);
unwatch_last = std::min(unwatch_last, heap_size_ - 1);
// Convert to system pages and update the range.
unwatch_first += host_address_offset();
unwatch_last += host_address_offset();
assert_true(unwatch_first <= unwatch_last);
system_page_first = unwatch_first / system_page_size_;
system_page_last = unwatch_last / system_page_size_;
block_index_first = system_page_first >> 6;
block_index_last = system_page_last >> 6;
}
// Unprotect ranges that need unprotection.
if (unprotect) {
uint8_t* protect_base = membase_ + heap_base_;
uint32_t unprotect_system_page_first = UINT32_MAX;
for (uint32_t i = system_page_first; i <= system_page_last; ++i) {
// Check if need to allow writing to this page.
bool unprotect_page = (system_page_flags_[i >> 6].notify_on_invalidation &
(uint64_t(1) << (i & 63))) != 0;
if (unprotect_page) {
uint32_t guest_page_number =
xe::sat_sub(i * system_page_size_, host_address_offset()) /
page_size_;
if (ToPageAccess(page_table_[guest_page_number].current_protect) !=
xe::memory::PageAccess::kReadWrite) {
unprotect_page = false;
}
}
if (unprotect_page) {
if (unprotect_system_page_first == UINT32_MAX) {
unprotect_system_page_first = i;
}
} else {
if (unprotect_system_page_first != UINT32_MAX) {
xe::memory::Protect(
protect_base + unprotect_system_page_first * system_page_size_,
(i - unprotect_system_page_first) * system_page_size_,
xe::memory::PageAccess::kReadWrite);
unprotect_system_page_first = UINT32_MAX;
}
}
}
if (unprotect_system_page_first != UINT32_MAX) {
xe::memory::Protect(
protect_base + unprotect_system_page_first * system_page_size_,
(system_page_last + 1 - unprotect_system_page_first) *
system_page_size_,
xe::memory::PageAccess::kReadWrite);
}
}
// Mark pages as not write-watched.
for (uint32_t i = block_index_first; i <= block_index_last; ++i) {
uint64_t mask = 0;
if (i == block_index_first) {
mask |= (uint64_t(1) << (system_page_first & 63)) - 1;
}
if (i == block_index_last && (system_page_last & 63) != 63) {
mask |= ~((uint64_t(1) << ((system_page_last & 63) + 1)) - 1);
}
system_page_flags_[i].notify_on_invalidation &= mask;
}
return true;
}
uint32_t PhysicalHeap::GetPhysicalAddress(uint32_t address) const {
assert_true(address >= heap_base_);
address -= heap_base_;
assert_true(address < heap_size_);
if (heap_base_ >= 0xE0000000) {
address += 0x1000;
}
return address;
}
} // namespace xe
|
/****************************************************************************
**
** Copyright (C) 2017 Ramazan Utku
** Contact: ramazanutku@gmail.com
**
** This file is part of the examples of the Qt Toolkit.
**
** $UKIRIS_BEGIN_LICENSE:BSD$
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** TURKISH
** Her hakkı saklıdır.
** Değişiklik yapılarak veya yapılmaksızın, yeniden dağıtmak veya kaynak ve ikili biçimlerde
** kullanmak, aşağıdaki koşullar yerine getirildiği takdirde serbesttir:
**
** * Kaynak kodun yeniden dağıtımı; yukarıdaki telif hakkı uyarısını, şartlar listesini ve
** aşağıdaki ret yazısını muhafaza etmelidir.
** * İkili biçimde yeniden dağıtımında; yukarıdaki telif hakkı uyarısı, şartlar listesi ve
** aşağıdaki ret yazısı dağıtımla birlikte gelen belgelendirmede ve/veya diğer materyallerde
** tekrarlanmalıdır.
**
** İŞBU YAZILIM TELİF HAKKI SAHİPLERİ VE KATKIDA BULUNANLAR TARAFINDAN OLDUĞU GİBİ” SAĞLANMIŞTIR
** VE TİCARETE ELVERİŞLİLİK VE ÖZEL BİR AMACA UYGUNLUK İÇİN KAPALI BİR TAAHHÜT DE DAHİL OLMAK ÜZERE
** VE BUNUNLA KISITLI OLMAKSIZIN HER TÜRLÜ AÇIK YA DA KAPALI TAAHHÜT REDDEDİLMİŞTİR.
** HİÇBİR KOŞULDA TELİF HAKKI SAHİPLERİ VE KATKIDA BULUNANLAR; HER NE SEBEPLE OLUŞMUŞSA VE SÖZLEŞMEDE,
** KUSURSUZ SORUMLULUKTA, VEYA TAZMİNAT YÜKÜMLÜLÜĞÜNDE OLMAK ÜZERE HANGİ YÜKÜMLÜLÜK KURAMINDA
** YER ALIRSA ALSIN,İŞBU YAZILIMIN KULLANIMIYLA ORTAYA ÇIKAN DOĞRUDAN, DOLAYLI, TESADÜFİ, ÖZEL,
** CEZAİ VEYA BİR SEBEP SONUCUNDA OLUŞAN (YEDEK PARÇA VEYA HİZMETLERİN TEMİNİ; KULLANIM,
** VERİ VEYA RANDIMAN KAYBI; YA DA İŞ KESİNTİSİ DE DAHİL OLMAK ÜZERE VE BUNUNLA KISITLI KALMAKSIZIN)
** HERHANGİ BİR ZARAR İÇİN, BU GİBİ HASARLARIN OLASILIĞI HAKKINDA UYARILMIŞ OLSALAR BİLE, SİZE KARŞI
** SORUMLU DEĞİLLERDİR.
**
** $UKIRIS_END_LICENSE$
**
****************************************************************************/
#include "yayilikuvvetcismi.h"
YayiliKuvvetCismi::YayiliKuvvetCismi(CisimModeli *parent)
: cisimModelim(parent)
{
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
tipim = cisimModelim->tipAl();
siram = cisimModelim->siraAl();
}
QPainterPath YayiliKuvvetCismi::shape() const
{
QPainterPath yol;
yol.addRect(boundingRect());
return yol;
}
void YayiliKuvvetCismi::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
prepareGeometryChange();
painter->setRenderHint(QPainter::Antialiasing);
int x1 = cisimModelim->baslangicKonumuAl();
int x2 = cisimModelim->bitisKonumuAl();
x = x1;
y = 0;
cisimModelim->tipAta(CisimModeli::YayiliKuvvet);
int y1 = -80;
int y2 = -80;
int yaziAcisi = 0;
if (cisimModelim->baslangicKuvvetiAl() > 0) {
painter->rotate(180);
yaziAcisi = -180;
x = x2;
}
if (qFabs(cisimModelim->baslangicKuvvetiAl()) < qFabs(cisimModelim->bitisKuvvetiAl())) {
y1 = -40;
y2 = -80;
}else if (qFabs(cisimModelim->baslangicKuvvetiAl()) > qFabs(cisimModelim->bitisKuvvetiAl())){
y1 = -80;
y2 = -40;
}
if (yaziAcisi != 0) {
int tmpY1 = y1;
y1 = y2;
y2 = tmpY1;
}
painter->drawPolygon(okBasiCiz(0,0));
painter->drawPolygon(okGovdesiCiz(0,y1));
painter->drawPolygon(okBasiCiz(x2-x1,0));
painter->drawPolygon(okGovdesiCiz(x2-x1,y2));
painter->drawLine(0,y1,x2-x1,y2);
int yaziY1 = y1-10;
int yaziY2 = y2-10;
int yaziX1 = 0;
int yaziX2 = x2-x1;
if (yaziAcisi != 0) {
yaziY1 = y2 * -1 + 15;
yaziY2 = y1 * -1 + 15;
yaziX1 = x1-x2;
yaziX2 = 0;
}
painter->rotate(yaziAcisi);
QString kuvvet1 = QString::number(cisimModelim->baslangicKuvvetiAl());
painter->drawText(QPointF(yaziX1,yaziY1),kuvvet1);
QString kuvvet2 = QString::number(cisimModelim->bitisKuvvetiAl());
painter->drawText(QPointF(yaziX2,yaziY2),kuvvet2);
cisimAlani.setRect(x,y,(x2-x1),yaziY2);
}
QPolygonF YayiliKuvvetCismi::okBasiCiz(int x, int y)
{
QPolygonF okBasi;
okBasi << QPointF(x-10,y-30) << QPointF(x,y-10)
<< QPointF(x+10,y-30);
return okBasi;
}
QPolygonF YayiliKuvvetCismi::okGovdesiCiz(int x, int h)
{
QPolygonF okGovdesi;
okGovdesi << QPointF(x,-30) << QPointF(x,h);
return okGovdesi;
}
|
// render texture
// alternative render target
#include "pch.h"
#include "rendertexture.h"
// Initialise texture object based on provided dimensions. Usually to match window.
RenderTexture::RenderTexture(ID3D11Device* device, int ltextureWidth, int ltextureHeight, float screenNear, float screenFar)
{
D3D11_TEXTURE2D_DESC textureDesc;
HRESULT result;
D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
textureWidth = ltextureWidth;
textureHeight = ltextureHeight;
ZeroMemory(&textureDesc, sizeof(textureDesc));
// Setup the render target texture description.
textureDesc.Width = textureWidth;
textureDesc.Height = textureHeight;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
textureDesc.SampleDesc.Count = 1;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = 0;
// Create the render target texture.
result = device->CreateTexture2D(&textureDesc, NULL, &renderTargetTexture);
// Setup the description of the render target view.
renderTargetViewDesc.Format = textureDesc.Format;
renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
renderTargetViewDesc.Texture2D.MipSlice = 0;
// Create the render target view.
result = device->CreateRenderTargetView(renderTargetTexture, &renderTargetViewDesc, &renderTargetView);
// Setup the description of the shader resource view.
shaderResourceViewDesc.Format = textureDesc.Format;
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
shaderResourceViewDesc.Texture2D.MipLevels = 1;
// Create the shader resource view.
result = device->CreateShaderResourceView(renderTargetTexture, &shaderResourceViewDesc, &shaderResourceView);
// Set up the description of the depth buffer.
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
depthBufferDesc.Width = textureWidth;
depthBufferDesc.Height = textureHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
// Create the texture for the depth buffer using the filled out description.
result = device->CreateTexture2D(&depthBufferDesc, NULL, &depthStencilBuffer);
// Set up the depth stencil view description.
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
// Set up the depth stencil view description.
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
// Create the depth stencil view.
result = device->CreateDepthStencilView(depthStencilBuffer, &depthStencilViewDesc, &depthStencilView);
// Setup the viewport for rendering.
viewport.Width = (float)textureWidth;
viewport.Height = (float)textureHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
// Setup the projection matrix.
projectionMatrix = XMMatrixPerspectiveFovLH(((float)XM_PI / 4.0f), ((float)textureWidth / (float)textureHeight), screenNear, screenFar);
// Create an orthographic projection matrix for 2D rendering.
orthoMatrix = XMMatrixOrthographicLH((float)textureWidth, (float)textureHeight, screenNear, screenFar);
}
// Release resources.
RenderTexture::~RenderTexture()
{
if (depthStencilView)
{
depthStencilView->Release();
depthStencilView = 0;
}
if (depthStencilBuffer)
{
depthStencilBuffer->Release();
depthStencilBuffer = 0;
}
if (shaderResourceView)
{
shaderResourceView->Release();
shaderResourceView = 0;
}
if (renderTargetView)
{
renderTargetView->Release();
renderTargetView = 0;
}
if (renderTargetTexture)
{
renderTargetTexture->Release();
renderTargetTexture = 0;
}
}
// Set this renderTexture as the current render target.
// All rendering is now store here, rather than the back buffer.
void RenderTexture::setRenderTarget(ID3D11DeviceContext* deviceContext)
{
deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
// deviceContext->RSSetViewports(1, &viewport);
}
// Clear render texture to specified colour. Similar to clearing the back buffer, ready for the next frame.
void RenderTexture::clearRenderTarget(ID3D11DeviceContext* deviceContext, float red, float green, float blue, float alpha)
{
float color[4];
color[0] = red;
color[1] = green;
color[2] = blue;
color[3] = alpha;
// Clear the back buffer and depth buffer.
deviceContext->ClearRenderTargetView(renderTargetView, color);
deviceContext->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
ID3D11ShaderResourceView* RenderTexture::getShaderResourceView()
{
return shaderResourceView;
}
XMMATRIX RenderTexture::getProjectionMatrix()
{
return projectionMatrix;
}
XMMATRIX RenderTexture::getOrthoMatrix()
{
return orthoMatrix;
}
int RenderTexture::getTextureWidth()
{
return textureWidth;
}
int RenderTexture::getTextureHeight()
{
return textureHeight;
}
|
/*
* BeagleCPUSSEImpl.hpp
* BEAGLE
*
* Copyright 2010 Phylogenetic Likelihood Working Group
*
* This file is part of BEAGLE.
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
* @author Marc Suchard
* @author David Swofford
*/
#ifndef BEAGLE_CPU_SSE_IMPL_HPP
#define BEAGLE_CPU_SSE_IMPL_HPP
#ifdef HAVE_CONFIG_H
#include "libhmsbeagle/config.h"
#endif
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cmath>
#include <cassert>
#include "libhmsbeagle/beagle.h"
#include "libhmsbeagle/CPU/BeagleCPUImpl.h"
#include "libhmsbeagle/CPU/BeagleCPUSSEImpl.h"
#include "libhmsbeagle/CPU/SSEDefinitions.h"
namespace beagle {
namespace cpu {
BEAGLE_CPU_FACTORY_TEMPLATE
inline const char* getBeagleCPUSSEName(){ return "CPU-SSE-Unknown"; };
template<>
inline const char* getBeagleCPUSSEName<double>(){ return "CPU-SSE-Double"; };
template<>
inline const char* getBeagleCPUSSEName<float>(){ return "CPU-SSE-Single"; };
/*
* Calculates partial likelihoods at a node when both children have states.
*/
BEAGLE_CPU_SSE_TEMPLATE
void BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::calcStatesStates(double* destP,
const int* states_q,
const double* matrices_q,
const int* states_r,
const double* matrices_r,
int startPattern,
int endPattern) {
BeagleCPUImpl<BEAGLE_CPU_SSE_DOUBLE>::calcStatesStates(destP,
states_q,
matrices_q,
states_r,
matrices_r,
startPattern,
endPattern);
}
//template <>
//void BeagleCPUSSEImpl<double>::calcStatesStates(double* destP,
// const int* states_q,
// const double* matrices_q,
// const int* states_r,
// const double* matrices_r) {
//
// VecUnion vu_mq[OFFSET][2], vu_mr[OFFSET][2];
//
// int w = 0;
// V_Real *destPvec = (V_Real *)destP;
//
// for (int l = 0; l < kCategoryCount; l++) {
//
// SSE_PREFETCH_MATRICES(matrices_q + w, matrices_r + w, vu_mq, vu_mr);
//
// for (int k = 0; k < kPatternCount; k++) {
//
// const int state_q = states_q[k];
// const int state_r = states_r[k];
//
// *destPvec++ = VEC_MULT(vu_mq[state_q][0].vx, vu_mr[state_r][0].vx);
// *destPvec++ = VEC_MULT(vu_mq[state_q][1].vx, vu_mr[state_r][1].vx);
//
// }
//
// w += OFFSET*4;
// if (kExtraPatterns)
// destPvec += kExtraPatterns * 2;
// }
//}
/*
* Calculates partial likelihoods at a node when one child has states and one has partials.
SSE version
*/
BEAGLE_CPU_SSE_TEMPLATE
void BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::calcStatesPartials(double* destP,
const int* states_q,
const double* matrices_q,
const double* partials_r,
const double* matrices_r,
int startPattern,
int endPattern) {
BeagleCPUImpl<BEAGLE_CPU_SSE_DOUBLE>::calcStatesPartials(destP,
states_q,
matrices_q,
partials_r,
matrices_r,
startPattern,
endPattern);
}
//
//
//template <>
//void BeagleCPUSSEImpl<double>::calcStatesPartials(double* destP,
// const int* states_q,
// const double* matrices_q,
// const double* partials_r,
// const double* matrices_r) {
//
// int v = 0;
// int w = 0;
//
// VecUnion vu_mq[OFFSET][2], vu_mr[OFFSET][2];
// V_Real *destPvec = (V_Real *)destP;
// V_Real destr_01, destr_23;
//
// for (int l = 0; l < kCategoryCount; l++) {
//
// SSE_PREFETCH_MATRICES(matrices_q + w, matrices_r + w, vu_mq, vu_mr);
//
// for (int k = 0; k < kPatternCount; k++) {
//
// const int state_q = states_q[k];
// V_Real vp0, vp1, vp2, vp3;
// SSE_PREFETCH_PARTIALS(vp,partials_r,v);
//
// destr_01 = VEC_MULT(vp0, vu_mr[0][0].vx);
// destr_01 = VEC_MADD(vp1, vu_mr[1][0].vx, destr_01);
// destr_01 = VEC_MADD(vp2, vu_mr[2][0].vx, destr_01);
// destr_01 = VEC_MADD(vp3, vu_mr[3][0].vx, destr_01);
// destr_23 = VEC_MULT(vp0, vu_mr[0][1].vx);
// destr_23 = VEC_MADD(vp1, vu_mr[1][1].vx, destr_23);
// destr_23 = VEC_MADD(vp2, vu_mr[2][1].vx, destr_23);
// destr_23 = VEC_MADD(vp3, vu_mr[3][1].vx, destr_23);
//
// *destPvec++ = VEC_MULT(vu_mq[state_q][0].vx, destr_01);
// *destPvec++ = VEC_MULT(vu_mq[state_q][1].vx, destr_23);
//
// v += 4;
// }
// w += OFFSET*4;
// if (kExtraPatterns) {
// destPvec += kExtraPatterns * 2;
// v += kExtraPatterns * 4;
// }
// }
//}
//template<>
//void inline BeagleCPUSSEImpl<double>::innerPartialsPartals(
// const double* __restrict partials1,
// const double* __restrict matrices1,
// const double* __restrict partials2,
// const double* __restrict matrices2,
// V_Real& sum1_vec,
// V_Real& sum2_vec,
// V_Real& out,
// int& v,
// int& w) {
// int j = 0;
// sum1_vec = VEC_SETZERO();
// sum2_vec = VEC_SETZERO();
// for (; j < kStateCountMinusOne; j += 2) {
// sum1_vec = VEC_MADD(
// VEC_LOAD(matrices1 + w + j), // TODO This only works if w is even
// VEC_LOAD(partials1 + v + j), // TODO This only works if v is even
// sum1_vec);
// sum2_vec = VEC_MADD(
// VEC_LOAD(matrices2 + w + j),
// VEC_LOAD(partials2 + v + j),
// sum2_vec);
// }
//
// out = VEC_MULT(
// VEC_ADD(sum1_vec, VEC_SWAP(sum1_vec)),
// VEC_ADD(sum2_vec, VEC_SWAP(sum2_vec))
// );
//}
//#define DOUBLE_UNROLL // Does not appear to save any time
BEAGLE_CPU_SSE_TEMPLATE
void BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::calcPartialsPartials(double* __restrict destP,
const double* __restrict partials1,
const double* __restrict matrices1,
const double* __restrict partials2,
const double* __restrict matrices2,
int startPattern,
int endPattern) {
int stateCountMinusOne = kPartialsPaddedStateCount - 1;
#pragma omp parallel for num_threads(kCategoryCount)
for (int l = 0; l < kCategoryCount; l++) {
int v = l*kPartialsPaddedStateCount*kPatternCount + kPartialsPaddedStateCount*startPattern;
double* destPu = destP + v;
for (int k = startPattern; k < endPattern; k++) {
int w = l * kMatrixSize;
for (int i = 0; i < kStateCount;
#ifdef DOUBLE_UNROLL
i += 2 // TODO This only works if stateCount is even
#else
++i
#endif
) {
V_Real sum1_vecA = VEC_SETZERO();
V_Real sum2_vecA = VEC_SETZERO();
for (int j = 0; j < stateCountMinusOne; j += 2) {
sum1_vecA = VEC_MADD(
VEC_LOAD(matrices1 + w + j), // TODO This only works if w is even
VEC_LOAD(partials1 + v + j), // TODO This only works if v is even
sum1_vecA);
sum2_vecA = VEC_MADD(
VEC_LOAD(matrices2 + w + j),
VEC_LOAD(partials2 + v + j),
sum2_vecA);
}
sum1_vecA = VEC_MULT(
VEC_ADD(sum1_vecA, VEC_SWAP(sum1_vecA)),
VEC_ADD(sum2_vecA, VEC_SWAP(sum2_vecA))
);
// increment for the extra column at the end
w += kStateCount + T_PAD;
#ifndef DOUBLE_UNROLL
// Store single value
VEC_STORE_SCALAR(destPu, sum1_vecA);
destPu++;
#endif
#ifdef DOUBLE_UNROLL
V_Real sum1_vecB = VEC_SETZERO();
V_Real sum2_vecB = VEC_SETZERO();
for (int j = 0; j < stateCountMinusOne; j += 2) {
sum1_vecB = VEC_MADD(
VEC_LOAD(matrices1 + w + j), // TODO This only works if w is even
VEC_LOAD(partials1 + v + j), // TODO This only works if v is even
sum1_vecB);
sum2_vecB = VEC_MADD(
VEC_LOAD(matrices2 + w + j),
VEC_LOAD(partials2 + v + j),
sum2_vecB);
}
sum1_vecB = VEC_MULT(
VEC_ADD(sum1_vecB, VEC_SWAP(sum1_vecB)),
VEC_ADD(sum2_vecB, VEC_SWAP(sum2_vecB))
);
// increment for the extra column at the end
w += kStateCount + T_PAD;
// Store both partials in one transaction
VEC_STORE(destPu, VEC_MOVE(sum1_vecA, sum1_vecB));
destPu += 2;
#endif
}
if (P_PAD) {
for (int pad = 0; pad < P_PAD; pad++) {
*(destPu++) = 0.0;
}
}
v += kPartialsPaddedStateCount;
}
}
}
BEAGLE_CPU_SSE_TEMPLATE
void BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::calcPartialsPartialsFixedScaling(double* __restrict destP,
const double* __restrict partials1,
const double* __restrict matrices1,
const double* __restrict partials2,
const double* __restrict matrices2,
const double* __restrict scaleFactors,
int startPattern,
int endPattern) {
int stateCountMinusOne = kPartialsPaddedStateCount - 1;
#pragma omp parallel for num_threads(kCategoryCount)
for (int l = 0; l < kCategoryCount; l++) {
int v = l*kPartialsPaddedStateCount*kPatternCount + kPartialsPaddedStateCount*startPattern;
double* destPu = destP + v;
for (int k = startPattern; k < endPattern; k++) {
int w = l * kMatrixSize;
const V_Real scalar = VEC_SPLAT(scaleFactors[k]);
for (int i = 0; i < kStateCount; i++) {
V_Real sum1_vec;
V_Real sum2_vec;
int j = 0;
sum1_vec = VEC_SETZERO();
sum2_vec = VEC_SETZERO();
for ( ; j < stateCountMinusOne; j += 2) {
sum1_vec = VEC_MADD(
VEC_LOAD(matrices1 + w + j), // TODO This only works if w is even
VEC_LOAD(partials1 + v + j), // TODO This only works if v is even
sum1_vec);
sum2_vec = VEC_MADD(
VEC_LOAD(matrices2 + w + j),
VEC_LOAD(partials2 + v + j),
sum2_vec);
}
VEC_STORE_SCALAR(destPu,
VEC_DIV(VEC_MULT(
VEC_ADD(sum1_vec, VEC_SWAP(sum1_vec)),
VEC_ADD(sum2_vec, VEC_SWAP(sum2_vec))
), scalar));
// increment for the extra column at the end
w += kStateCount + T_PAD;
destPu++;
}
if (P_PAD) {
for (int pad = 0; pad < P_PAD; pad++) {
*(destPu++) = 0.0;
}
}
v += kPartialsPaddedStateCount;
}
}
}
BEAGLE_CPU_SSE_TEMPLATE
void BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::calcPartialsPartialsAutoScaling(double* destP,
const double* partials_q,
const double* matrices_q,
const double* partials_r,
const double* matrices_r,
int* activateScaling) {
BeagleCPUImpl<BEAGLE_CPU_SSE_DOUBLE>::calcPartialsPartialsAutoScaling(destP,
partials_q,
matrices_q,
partials_r,
matrices_r,
activateScaling);
}
//template <>
//void BeagleCPUSSEImpl<double>::calcPartialsPartialsAutoScaling(double* destP,
// const double* partials_q,
// const double* matrices_q,
// const double* partials_r,
// const double* matrices_r,
// int* activateScaling) {
// // TODO: implement calcPartialsPartialsAutoScaling with SSE
// BeagleCPUImpl<double>::calcPartialsPartialsAutoScaling(destP,
// partials_q,
// matrices_q,
// partials_r,
// matrices_r,
// activateScaling);
//}
BEAGLE_CPU_SSE_TEMPLATE
int BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::calcEdgeLogLikelihoods(const int parIndex,
const int childIndex,
const int probIndex,
const int categoryWeightsIndex,
const int stateFrequenciesIndex,
const int scalingFactorsIndex,
double* outSumLogLikelihood) {
return BeagleCPUImpl<BEAGLE_CPU_SSE_DOUBLE>::calcEdgeLogLikelihoods(
parIndex,
childIndex,
probIndex,
categoryWeightsIndex,
stateFrequenciesIndex,
scalingFactorsIndex,
outSumLogLikelihood);
}
//template <>
// int BeagleCPUSSEImpl<double>::calcEdgeLogLikelihoods(const int parIndex,
// const int childIndex,
// const int probIndex,
// const int categoryWeightsIndex,
// const int stateFrequenciesIndex,
// const int scalingFactorsIndex,
// double* outSumLogLikelihood) {
// // TODO: implement derivatives for calculateEdgeLnL
//
// int returnCode = BEAGLE_SUCCESS;
//
// assert(parIndex >= kTipCount);
//
// const double* cl_r = gPartials[parIndex];
// double* cl_p = integrationTmp;
// const double* transMatrix = gTransitionMatrices[probIndex];
// const double* wt = gCategoryWeights[categoryWeightsIndex];
// const double* freqs = gStateFrequencies[stateFrequenciesIndex];
//
// memset(cl_p, 0, (kPatternCount * kStateCount)*sizeof(double));
//
// if (childIndex < kTipCount && gTipStates[childIndex]) { // Integrate against a state at the child
//
// const int* statesChild = gTipStates[childIndex];
//
// int w = 0;
// V_Real *vcl_r = (V_Real *)cl_r;
// for(int l = 0; l < kCategoryCount; l++) {
//
// VecUnion vu_m[OFFSET][2];
// SSE_PREFETCH_MATRIX(transMatrix + w, vu_m)
//
// V_Real *vcl_p = (V_Real *)cl_p;
//
// for(int k = 0; k < kPatternCount; k++) {
//
// const int stateChild = statesChild[k];
// V_Real vwt = VEC_SPLAT(wt[l]);
//
// V_Real wtdPartials = VEC_MULT(*vcl_r++, vwt);
// *vcl_p++ = VEC_MADD(vu_m[stateChild][0].vx, wtdPartials, *vcl_p);
//
// wtdPartials = VEC_MULT(*vcl_r++, vwt);
// *vcl_p++ = VEC_MADD(vu_m[stateChild][1].vx, wtdPartials, *vcl_p);
// }
// w += OFFSET*4;
// vcl_r += 2 * kExtraPatterns;
// }
// } else { // Integrate against a partial at the child
//
// const double* cl_q = gPartials[childIndex];
// V_Real * vcl_r = (V_Real *)cl_r;
// int v = 0;
// int w = 0;
//
// for(int l = 0; l < kCategoryCount; l++) {
//
// V_Real * vcl_p = (V_Real *)cl_p;
//
// VecUnion vu_m[OFFSET][2];
// SSE_PREFETCH_MATRIX(transMatrix + w, vu_m)
//
// for(int k = 0; k < kPatternCount; k++) {
// V_Real vclp_01, vclp_23;
// V_Real vwt = VEC_SPLAT(wt[l]);
//
// V_Real vcl_q0, vcl_q1, vcl_q2, vcl_q3;
// SSE_PREFETCH_PARTIALS(vcl_q,cl_q,v);
//
// vclp_01 = VEC_MULT(vcl_q0, vu_m[0][0].vx);
// vclp_01 = VEC_MADD(vcl_q1, vu_m[1][0].vx, vclp_01);
// vclp_01 = VEC_MADD(vcl_q2, vu_m[2][0].vx, vclp_01);
// vclp_01 = VEC_MADD(vcl_q3, vu_m[3][0].vx, vclp_01);
// vclp_23 = VEC_MULT(vcl_q0, vu_m[0][1].vx);
// vclp_23 = VEC_MADD(vcl_q1, vu_m[1][1].vx, vclp_23);
// vclp_23 = VEC_MADD(vcl_q2, vu_m[2][1].vx, vclp_23);
// vclp_23 = VEC_MADD(vcl_q3, vu_m[3][1].vx, vclp_23);
// vclp_01 = VEC_MULT(vclp_01, vwt);
// vclp_23 = VEC_MULT(vclp_23, vwt);
//
// *vcl_p++ = VEC_MADD(vclp_01, *vcl_r++, *vcl_p);
// *vcl_p++ = VEC_MADD(vclp_23, *vcl_r++, *vcl_p);
//
// v += 4;
// }
// w += 4*OFFSET;
// if (kExtraPatterns) {
// vcl_r += 2 * kExtraPatterns;
// v += 4 * kExtraPatterns;
// }
//
// }
// }
//
// int u = 0;
// for(int k = 0; k < kPatternCount; k++) {
// double sumOverI = 0.0;
// for(int i = 0; i < kStateCount; i++) {
// sumOverI += freqs[i] * cl_p[u];
// u++;
// }
//
// outLogLikelihoodsTmp[k] = log(sumOverI);
// }
//
//
// if (scalingFactorsIndex != BEAGLE_OP_NONE) {
// const double* scalingFactors = gScaleBuffers[scalingFactorsIndex];
// for(int k=0; k < kPatternCount; k++)
// outLogLikelihoodsTmp[k] += scalingFactors[k];
// }
//
// *outSumLogLikelihood = 0.0;
// for (int i = 0; i < kPatternCount; i++) {
// *outSumLogLikelihood += outLogLikelihoodsTmp[i] * gPatternWeights[i];
// }
//
// if (!(*outSumLogLikelihood - *outSumLogLikelihood == 0.0))
// returnCode = BEAGLE_ERROR_FLOATING_POINT;
//
// return returnCode;
//}
BEAGLE_CPU_SSE_TEMPLATE
int BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::getPaddedPatternsModulus() {
return 1; // We currently do not vectorize across patterns
}
BEAGLE_CPU_SSE_TEMPLATE
const char* BeagleCPUSSEImpl<BEAGLE_CPU_SSE_FLOAT>::getName() {
return getBeagleCPUSSEName<float>();
}
BEAGLE_CPU_SSE_TEMPLATE
const char* BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::getName() {
return getBeagleCPUSSEName<double>();
}
BEAGLE_CPU_SSE_TEMPLATE
const long BeagleCPUSSEImpl<BEAGLE_CPU_SSE_FLOAT>::getFlags() {
return BEAGLE_FLAG_COMPUTATION_SYNCH |
BEAGLE_FLAG_PROCESSOR_CPU |
BEAGLE_FLAG_PRECISION_SINGLE |
BEAGLE_FLAG_VECTOR_SSE |
BEAGLE_FLAG_FRAMEWORK_CPU;
}
BEAGLE_CPU_SSE_TEMPLATE
const long BeagleCPUSSEImpl<BEAGLE_CPU_SSE_DOUBLE>::getFlags() {
return BEAGLE_FLAG_COMPUTATION_SYNCH |
BEAGLE_FLAG_PROCESSOR_CPU |
BEAGLE_FLAG_PRECISION_DOUBLE |
BEAGLE_FLAG_VECTOR_SSE |
BEAGLE_FLAG_FRAMEWORK_CPU;
}
///////////////////////////////////////////////////////////////////////////////
// BeagleImplFactory public methods
BEAGLE_CPU_FACTORY_TEMPLATE
BeagleImpl* BeagleCPUSSEImplFactory<BEAGLE_CPU_FACTORY_GENERIC>::createImpl(int tipCount,
int partialsBufferCount,
int compactBufferCount,
int stateCount,
int patternCount,
int eigenBufferCount,
int matrixBufferCount,
int categoryCount,
int scaleBufferCount,
int resourceNumber,
int pluginResourceNumber,
long preferenceFlags,
long requirementFlags,
int* errorCode) {
if (!CPUSupportsSSE())
return NULL;
if (stateCount & 1) { // is odd
BeagleCPUSSEImpl<REALTYPE, T_PAD_SSE_ODD, P_PAD_SSE_ODD>* impl =
new BeagleCPUSSEImpl<REALTYPE, T_PAD_SSE_ODD, P_PAD_SSE_ODD>();
try {
if (impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount,
patternCount, eigenBufferCount, matrixBufferCount,
categoryCount,scaleBufferCount, resourceNumber,
pluginResourceNumber,
preferenceFlags, requirementFlags) == 0)
return impl;
}
catch(...) {
if (DEBUGGING_OUTPUT)
std::cerr << "exception in initialize\n";
delete impl;
throw;
}
delete impl;
} else {
BeagleCPUSSEImpl<REALTYPE, T_PAD_SSE_EVEN, P_PAD_SSE_EVEN>* impl =
new BeagleCPUSSEImpl<REALTYPE, T_PAD_SSE_EVEN, P_PAD_SSE_EVEN>();
try {
if (impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount,
patternCount, eigenBufferCount, matrixBufferCount,
categoryCount,scaleBufferCount, resourceNumber,
pluginResourceNumber,
preferenceFlags, requirementFlags) == 0)
return impl;
}
catch(...) {
if (DEBUGGING_OUTPUT)
std::cerr << "exception in initialize\n";
delete impl;
throw;
}
delete impl;
}
return NULL;
}
BEAGLE_CPU_FACTORY_TEMPLATE
const char* BeagleCPUSSEImplFactory<BEAGLE_CPU_FACTORY_GENERIC>::getName() {
return getBeagleCPUSSEName<BEAGLE_CPU_FACTORY_GENERIC>();
}
template <>
const long BeagleCPUSSEImplFactory<double>::getFlags() {
return BEAGLE_FLAG_COMPUTATION_SYNCH |
BEAGLE_FLAG_SCALING_MANUAL | BEAGLE_FLAG_SCALING_ALWAYS | BEAGLE_FLAG_SCALING_AUTO |
BEAGLE_FLAG_THREADING_NONE | BEAGLE_FLAG_THREADING_CPP |
BEAGLE_FLAG_PROCESSOR_CPU |
BEAGLE_FLAG_VECTOR_SSE |
BEAGLE_FLAG_PRECISION_DOUBLE |
BEAGLE_FLAG_SCALERS_LOG | BEAGLE_FLAG_SCALERS_RAW |
BEAGLE_FLAG_EIGEN_COMPLEX | BEAGLE_FLAG_EIGEN_REAL |
BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED |
BEAGLE_FLAG_PREORDER_TRANSPOSE_MANUAL | BEAGLE_FLAG_PREORDER_TRANSPOSE_AUTO |
BEAGLE_FLAG_FRAMEWORK_CPU;
}
template <>
const long BeagleCPUSSEImplFactory<float>::getFlags() {
return BEAGLE_FLAG_COMPUTATION_SYNCH |
BEAGLE_FLAG_SCALING_MANUAL | BEAGLE_FLAG_SCALING_ALWAYS | BEAGLE_FLAG_SCALING_AUTO |
BEAGLE_FLAG_THREADING_NONE | BEAGLE_FLAG_THREADING_CPP |
BEAGLE_FLAG_PROCESSOR_CPU |
BEAGLE_FLAG_VECTOR_SSE |
BEAGLE_FLAG_PRECISION_SINGLE |
BEAGLE_FLAG_SCALERS_LOG | BEAGLE_FLAG_SCALERS_RAW |
BEAGLE_FLAG_EIGEN_COMPLEX | BEAGLE_FLAG_EIGEN_REAL |
BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED |
BEAGLE_FLAG_PREORDER_TRANSPOSE_MANUAL | BEAGLE_FLAG_PREORDER_TRANSPOSE_AUTO |
BEAGLE_FLAG_FRAMEWORK_CPU;
}
// Code to save:
// int j = 0;
//// fprintf(stderr,"v = %d, w = %d\n",v,w);
//// if (kOddStateCount) { // TODO Template for compiler-time optimization
//// // Need to either unroll first or last entry
//// double sum1_end;
//// double sum2_end;
//// if (w & 1) { // v and w are odd, unroll first element
//// fprintf(stderr,"unroll head\n");
//// sum1_end = matrices1[w] * partials1[v];
//// sum2_end = matrices2[w] * partials2[v];
//// j++;
//// } else { // unroll last element
//// fprintf(stderr,"unroll tail\n");
//// sum1_end = matrices1[w + kStateCountMinusOne] *
//// partials1[v + kStateCountMinusOne];
//// sum2_end = matrices2[w + kStateCountMinusOne] *
//// partials2[v + kStateCountMinusOne];
//// }
//// sum1_vec = VEC_SET1(sum1_end);
//// sum2_vec = VEC_SET1(sum2_end);
//// } else {
// sum1_vec = VEC_SETZERO();
// sum2_vec = VEC_SETZERO();
//// }
//// fprintf(stderr,"Done with head/tail\n");
//// fprintf(stderr,"starting SSE at %d:%d\n",(v+j),(w+j));
// Next snippet
//#if 1
// VEC_STORE_SCALAR(destP + u,
// VEC_MULT(
// VEC_ADD(sum1_vec, VEC_SWAP(sum1_vec)),
// VEC_ADD(sum2_vec, VEC_SWAP(sum2_vec))
// ));
//#else
// VecUnion t1, t2;
// t1.vx = sum1_vec;
// t2.vx = sum2_vec;
// destP[u] = (t1.x[0] + t1.x[1] //+ endSum1
// ) * (t2.x[0] + t2.x[1] //+ endSum2
// );
//#endif
}
}
#endif //BEAGLE_CPU_SSE_IMPL_HPP
|
// Copyright David Stone 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <tm/pokemon/max_pokemon_per_team.hpp>
#include <tm/pokemon/pokemon.hpp>
#include <tm/pokemon/pokemon_not_found.hpp>
#include <tm/compress.hpp>
#include <tm/operators.hpp>
#include <bounded/assert.hpp>
#include <bounded/integer.hpp>
#include <containers/algorithms/erase.hpp>
#include <containers/algorithms/find.hpp>
#include <containers/begin_end.hpp>
#include <containers/push_back.hpp>
#include <containers/range_value_t.hpp>
#include <containers/size.hpp>
#include <containers/static_vector.hpp>
#include <numeric_traits/min_max_value.hpp>
#include <stdexcept>
namespace technicalmachine {
using namespace bounded::literal;
template<Generation generation>
struct PokemonCollection {
using Container = containers::static_vector<Pokemon<generation>, max_pokemon_per_team.value()>;
using value_type = containers::range_value_t<Container>;
explicit PokemonCollection(TeamSize const initial_size):
m_real_size(initial_size)
{
}
auto begin() const {
return containers::begin(m_container);
}
auto begin() {
return containers::begin(m_container);
}
auto size() const {
return containers::size(m_container);
}
void set_index(TeamIndex const new_index) {
check_range(new_index);
m_index = new_index;
}
constexpr auto index() const {
return m_index;
}
constexpr decltype(auto) operator()(TeamIndex const specified_index) const {
check_range(specified_index);
return m_container[specified_index];
}
constexpr decltype(auto) operator()(TeamIndex const specified_index) {
check_range(specified_index);
return m_container[specified_index];
}
constexpr decltype(auto) operator()() const {
return m_container[index()];
}
constexpr decltype(auto) operator()() {
return m_container[index()];
}
auto real_size() const {
return m_real_size;
}
Pokemon<generation> & add(Pokemon<generation> pokemon) {
check_not_full();
return containers::push_back(m_container, std::move(pokemon));
}
void remove_active(TeamIndex const index_of_replacement) {
auto const original_index = index();
BOUNDED_ASSERT(original_index != index_of_replacement);
containers::erase(m_container, begin() + original_index);
--m_real_size;
set_index((index_of_replacement < original_index) ?
index_of_replacement :
TeamIndex(index_of_replacement - 1_bi, bounded::non_check)
);
}
friend auto operator==(PokemonCollection const &, PokemonCollection const &) -> bool = default;
friend auto compress(PokemonCollection const & value) {
using containers::size;
static_assert(numeric_traits::max_value<decltype(containers::size(value.m_container))> == 6_bi);
auto const p0 = containers::size(value.m_container) >= 1_bi ? compress(value.m_container[0_bi]) : 0_bi;
auto const p1 = containers::size(value.m_container) >= 2_bi ? compress(value.m_container[1_bi]) : 0_bi;
auto const p2 = containers::size(value.m_container) >= 3_bi ? compress(value.m_container[2_bi]) : 0_bi;
auto const p3 = containers::size(value.m_container) >= 4_bi ? compress(value.m_container[3_bi]) : 0_bi;
auto const p4 = containers::size(value.m_container) >= 5_bi ? compress(value.m_container[4_bi]) : 0_bi;
auto const p5 = containers::size(value.m_container) >= 6_bi ? compress(value.m_container[5_bi]) : 0_bi;
if constexpr (generation == Generation::one) {
return bounded::tuple(
compress_combine(p0, p1, p2, value.m_index),
compress_combine(p3, p4, p5, value.m_real_size)
);
} else {
return bounded::tuple(
compress_combine(p0, p1),
compress_combine(p2, p3),
compress_combine(p4, p5, value.m_index, value.m_real_size)
);
}
}
private:
void check_not_full() {
if (size() == m_real_size) {
throw std::runtime_error("Tried to add too many Pokemon");
}
}
constexpr void check_range(TeamIndex const new_index [[maybe_unused]]) const {
BOUNDED_ASSERT(new_index < size());
}
Container m_container;
TeamIndex m_index = 0_bi;
// The actual size of the foe's team, not just the Pokemon I've seen
TeamSize m_real_size;
};
BOUNDED_COMMON_ARITHMETIC
template<Generation generation>
inline auto find_index(PokemonCollection<generation> const & collection, Species const species) {
return static_cast<TeamIndex>(containers::find_if(collection, [=](Pokemon<generation> const pokemon) { return pokemon.species() == species; }) - collection.begin());
}
template<Generation generation>
inline auto find_present_index(PokemonCollection<generation> const & collection, Species const species) {
auto const index = find_index(collection, species);
if (index == containers::size(collection)) {
throw PokemonNotFound(species);
}
return index;
}
} // namespace technicalmachine
|
#include <memory>
#include "tmachine.h"
#include "tsio_wav.h"
#include "tsystem.h"
#include "tfilepath_io.h"
#include "tsop.h"
using namespace std;
#if !defined(TNZ_LITTLE_ENDIAN)
TNZ_LITTLE_ENDIAN undefined !!
#endif
//------------------------------------------------------------------------------
void
swapAndCopySamples(short *srcBuffer, short *dstBuffer, TINT32 sampleCount);
//==============================================================================
// TWAVChunk: classe base per i vari chunk WAV
class TWAVChunk {
public:
static TINT32 HDR_LENGTH;
string m_name;
TINT32 m_length; // lunghezza del chunk in byte
TWAVChunk(string name, TINT32 length) : m_name(name), m_length(length) {}
virtual ~TWAVChunk() {}
virtual bool read(Tifstream &is) {
skip(is);
return true;
}
void skip(Tifstream &is) { is.seekg(m_length, ios::cur); }
static bool readHeader(Tifstream &is, string &name, TINT32 &length) {
char cName[5];
TINT32 len = 0;
memset(cName, 0, sizeof(cName));
is.read(cName, 4);
if (is.fail()) return false;
cName[4] = '\0';
is.read((char *)&len, sizeof(len));
if (is.fail()) return false;
// il formato WAV memorizza i dati come little-endian
// se la piattaforma non e' little-endian bisogna scambiare i byte
if (!TNZ_LITTLE_ENDIAN) len = swapTINT32(len);
name = string(cName);
length = len;
return true;
}
};
TINT32 TWAVChunk::HDR_LENGTH = 8;
//====================================================================
// FMT Chunk: Chunk contenente le informazioni sulla traccia
class TFMTChunk final : public TWAVChunk {
public:
static TINT32 LENGTH;
USHORT m_encodingType; // PCM, ...
USHORT m_chans; // numero di canali
TUINT32 m_sampleRate;
TUINT32 m_avgBytesPerSecond;
USHORT m_bytesPerSample;
USHORT m_bitPerSample;
TFMTChunk(TINT32 length) : TWAVChunk("fmt ", length) {}
bool read(Tifstream &is) override {
is.read((char *)&m_encodingType, sizeof(m_encodingType));
is.read((char *)&m_chans, sizeof(m_chans));
is.read((char *)&m_sampleRate, sizeof(m_sampleRate));
is.read((char *)&m_avgBytesPerSecond, sizeof(m_avgBytesPerSecond));
is.read((char *)&m_bytesPerSample, sizeof(m_bytesPerSample));
is.read((char *)&m_bitPerSample, sizeof(m_bitPerSample));
if (!TNZ_LITTLE_ENDIAN) {
m_encodingType = swapUshort(m_encodingType);
m_chans = swapUshort(m_chans);
m_sampleRate = swapTINT32(m_sampleRate);
m_avgBytesPerSecond = swapTINT32(m_avgBytesPerSecond);
m_bytesPerSample = swapUshort(m_bytesPerSample);
m_bitPerSample = swapUshort(m_bitPerSample);
}
assert(m_length >= 16);
if (m_length > 16) is.seekg((long)is.tellg() + m_length - 16);
return true;
}
bool write(ofstream &os) {
TUINT32 length = m_length;
USHORT type = m_encodingType;
USHORT chans = m_chans;
TUINT32 sampleRate = m_sampleRate;
TUINT32 bytesPerSecond = m_avgBytesPerSecond;
USHORT bytesPerSample = m_bytesPerSample;
USHORT bitPerSample = m_bitPerSample;
if (!TNZ_LITTLE_ENDIAN) {
length = swapTINT32(length);
type = swapUshort(type);
chans = swapUshort(chans);
sampleRate = swapTINT32(sampleRate);
bytesPerSecond = swapTINT32(bytesPerSecond);
bytesPerSample = swapUshort(bytesPerSample);
bitPerSample = swapUshort(bitPerSample);
}
os.write((char *)"fmt ", 4);
os.write((char *)&length, sizeof(length));
os.write((char *)&type, sizeof(type));
os.write((char *)&chans, sizeof(chans));
os.write((char *)&sampleRate, sizeof(sampleRate));
os.write((char *)&bytesPerSecond, sizeof(bytesPerSecond));
os.write((char *)&bytesPerSample, sizeof(bytesPerSample));
os.write((char *)&bitPerSample, sizeof(bitPerSample));
return true;
}
};
TINT32 TFMTChunk::LENGTH = TWAVChunk::HDR_LENGTH + 16;
//====================================================================
// DATA Chunk: Chunk contenente i campioni
class TDATAChunk final : public TWAVChunk {
public:
std::unique_ptr<UCHAR[]> m_samples;
TDATAChunk(TINT32 length) : TWAVChunk("data", length) {}
bool read(Tifstream &is) override {
// alloca il buffer dei campioni
m_samples.reset(new UCHAR[m_length]);
if (!m_samples) return false;
is.read((char *)m_samples.get(), m_length);
return true;
}
bool write(ofstream &os) {
TINT32 length = m_length;
if (!TNZ_LITTLE_ENDIAN) {
length = swapTINT32(length);
}
os.write((char *)"data", 4);
os.write((char *)&length, sizeof(length));
os.write((char *)m_samples.get(), m_length);
return true;
}
};
//==============================================================================
TSoundTrackReaderWav::TSoundTrackReaderWav(const TFilePath &fp)
: TSoundTrackReader(fp) {}
//------------------------------------------------------------------------------
TSoundTrackP TSoundTrackReaderWav::load() {
char chunkName[5];
char RIFFType[5];
TINT32 chunkLength;
Tifstream is(m_path);
if (!is) throw TException(m_path.getWideString() + L" : File doesn't exist");
// legge il nome del chunk
is.read((char *)&chunkName, sizeof(chunkName) - 1);
chunkName[4] = '\0';
// legge la lunghezza del chunk
is.read((char *)&chunkLength, sizeof(chunkLength));
if (!TNZ_LITTLE_ENDIAN) chunkLength = swapTINT32(chunkLength);
// legge il RIFFType
is.read((char *)&RIFFType, sizeof(RIFFType) - 1);
RIFFType[4] = '\0';
// per i .wav il RIFFType DEVE essere uguale a "WAVE"
if ((string(RIFFType, 4) != "WAVE"))
throw TException("The WAV file doesn't contain the WAVE form");
TFMTChunk *fmtChunk = 0;
TDATAChunk *dataChunk = 0;
while (!is.eof()) {
string name = "";
TINT32 length = 0;
bool ret = TWAVChunk::readHeader(is, name, length);
if (!ret) break;
// legge solo i chunk che ci interessano, ossia FMT e DATA
if (name == "fmt ") {
// legge i dati del chunk FMT
fmtChunk = new TFMTChunk(length);
fmtChunk->read(is);
// considera il byte di pad alla fine del chunk nel caso
// in cui la lunghezza di questi e' dispari
if (length & 1) {
is.seekg((long)is.tellg() + 1);
}
} else if (name == "data") {
// legge i dati del chunk DATA
dataChunk = new TDATAChunk(length);
dataChunk->read(is);
// considera il byte di pad alla fine del chunk nel caso
// in cui la lunghezza di questi e' dispari
if (length & 1) {
is.seekg((long)is.tellg() + 1);
}
} else {
// spostati nello stream di un numero di byte pari a length
if (length & 1)
is.seekg((long)is.tellg() + (long)length + 1);
else
is.seekg((long)is.tellg() + (long)length);
}
}
TSoundTrackP track = 0;
if (fmtChunk && dataChunk) {
TINT32 sampleCount = dataChunk->m_length / fmtChunk->m_bytesPerSample;
bool signedSample = (fmtChunk->m_bitPerSample != 8);
track = TSoundTrack::create(
(int)fmtChunk->m_sampleRate, fmtChunk->m_bitPerSample,
fmtChunk->m_chans, sampleCount, signedSample, fmtChunk->m_encodingType);
if (track) {
switch (fmtChunk->m_bitPerSample) {
case 8:
memcpy((void *)track->getRawData(),
(void *)(dataChunk->m_samples.get()),
sampleCount * fmtChunk->m_bytesPerSample);
break;
case 16:
if (!TNZ_LITTLE_ENDIAN)
swapAndCopySamples((short *)dataChunk->m_samples.get(),
(short *)track->getRawData(),
sampleCount * fmtChunk->m_chans);
else
memcpy((void *)track->getRawData(),
(void *)(dataChunk->m_samples.get()),
sampleCount * fmtChunk->m_bytesPerSample);
//#endif
break;
case 24:
// NOTE: This effectively changes from 24bit to 32bit bitPerSample
if (!TNZ_LITTLE_ENDIAN) {
UCHAR *begin = (UCHAR *)track->getRawData();
for (int i = 0; i < (int)(sampleCount * fmtChunk->m_chans); ++i) {
*(begin + 4 * i) = 0;
*(begin + 4 * i + 1) = *(dataChunk->m_samples.get() + 3 * i + 2);
*(begin + 4 * i + 2) = *(dataChunk->m_samples.get() + 3 * i + 1);
*(begin + 4 * i + 3) = *(dataChunk->m_samples.get() + 3 * i);
}
} else {
UCHAR *begin = (UCHAR *)track->getRawData();
for (int i = 0; i < (int)(sampleCount * fmtChunk->m_chans); ++i) {
memcpy((void *)(begin + 4 * i),
(void *)(dataChunk->m_samples.get() + 3 * i), 3);
*(begin + 4 * i + 3) = 0;
}
}
//#endif
break;
case 32:
if (!TNZ_LITTLE_ENDIAN) {
swapAndCopySamples((short *)dataChunk->m_samples.get(),
(short *)track->getRawData(),
sampleCount * fmtChunk->m_chans);
} else {
memcpy((void *)track->getRawData(),
(void *)(dataChunk->m_samples.get()),
sampleCount * fmtChunk->m_bytesPerSample);
}
break;
}
// Convert all WAV to 32bit PCM
if (fmtChunk->m_bitPerSample != 32 || fmtChunk->m_encodingType != WAVE_FORMAT_PCM) {
TSoundTrackP origTrack = track;
TSoundTrackFormat fmt = track->getFormat();
fmt.m_bitPerSample = 32;
fmt.m_formatType = WAVE_FORMAT_PCM;
track = TSop::convert(origTrack, fmt);
}
}
/*if (!TNZ_LITTLE_ENDIAN)
{
if (fmtChunk->m_bitPerSample > 8)
{
assert(fmtChunk->m_bitPerSample <= 16);
swapAndCopySamples(
(short*)dataChunk->m_samples,
(short*)track->getRawData(),
sampleCount*fmtChunk->m_chans);
}
else
memcpy(
(void*)track->getRawData(),
(void*)(dataChunk->m_samples),
sampleCount*fmtChunk->m_bytesPerSample);
}
else
memcpy(
(void*)track->getRawData(),
(void*)(dataChunk->m_samples),
sampleCount*fmtChunk->m_bytesPerSample);*/
}
if (fmtChunk) delete fmtChunk;
if (dataChunk) delete dataChunk;
return track;
}
//==============================================================================
TSoundTrackWriterWav::TSoundTrackWriterWav(const TFilePath &fp)
: TSoundTrackWriter(fp) {}
//------------------------------------------------------------------------------
bool TSoundTrackWriterWav::save(const TSoundTrackP &sndtrack) {
if (!sndtrack)
throw TException(L"Unable to save the soundtrack: " +
m_path.getWideString());
if (sndtrack->getBitPerSample() == 8 && sndtrack->isSampleSigned())
throw TException("The format (8 bit signed) is incompatible with WAV file");
TINT32 soundDataLength =
(TINT32)(sndtrack->getSampleCount() * (sndtrack->getBitPerSample() / 8) *
sndtrack->getChannelCount() /*sndtrack->getSampleSize()*/);
TINT32 RIFFChunkLength =
TFMTChunk::LENGTH + TWAVChunk::HDR_LENGTH + soundDataLength;
TFileStatus fs(m_path);
if (fs.doesExist() && !fs.isWritable())
throw TException(L"Unable to save the soundtrack: " +
m_path.getWideString() + L" is read-only");
Tofstream os(m_path);
TFMTChunk fmtChunk(16);
fmtChunk.m_encodingType = 1; // PCM
fmtChunk.m_chans = sndtrack->getChannelCount();
fmtChunk.m_sampleRate = sndtrack->getSampleRate();
fmtChunk.m_avgBytesPerSecond = (sndtrack->getBitPerSample() / 8) *
fmtChunk.m_chans * sndtrack->getSampleRate();
// sndtrack->getSampleSize()*sndtrack->getSampleRate();
fmtChunk.m_bytesPerSample = (sndtrack->getBitPerSample() / 8) *
fmtChunk.m_chans; // sndtrack->getSampleSize();
fmtChunk.m_bitPerSample = sndtrack->getBitPerSample();
TDATAChunk dataChunk(soundDataLength);
std::unique_ptr<UCHAR[]> waveData(new UCHAR[soundDataLength]);
if (!TNZ_LITTLE_ENDIAN) RIFFChunkLength = swapTINT32(RIFFChunkLength);
// era if defined(MACOSX)
#if (!TNZ_LITTLE_ENDIAN)
{
if (fmtChunk.m_bitPerSample == 8)
memcpy((void *)waveData, (void *)sndtrack->getRawData(), soundDataLength);
else if (fmtChunk.m_bitPerSample == 16) {
swapAndCopySamples((short *)sndtrack->getRawData(), (short *)waveData,
sndtrack->getSampleCount() * fmtChunk.m_chans);
} else if (fmtChunk.m_bitPerSample == 24) { // swap e togliere quarto byte
UCHAR *begin = (UCHAR *)sndtrack->getRawData();
for (int i = 0; i < (int)sndtrack->getSampleCount() * fmtChunk.m_chans;
++i) {
*(waveData + 3 * i) = *(begin + 4 * i + 3);
*(waveData + 3 * i + 1) = *(begin + 4 * i + 2);
*(waveData + 3 * i + 2) = *(begin + 4 * i + 1);
}
}
}
#else
{
if (fmtChunk.m_bitPerSample != 24)
memcpy((void *)waveData.get(), (void *)sndtrack->getRawData(),
soundDataLength);
else { // togliere quarto byte
UCHAR *begin = (UCHAR *)sndtrack->getRawData();
for (int i = 0; i < (int)sndtrack->getSampleCount() * fmtChunk.m_chans;
++i) {
*(waveData.get() + 3 * i) = *(begin + 4 * i);
*(waveData.get() + 3 * i + 1) = *(begin + 4 * i + 1);
*(waveData.get() + 3 * i + 2) = *(begin + 4 * i + 2);
}
}
}
#endif
dataChunk.m_samples = std::move(waveData);
os.write("RIFF", 4);
os.write((char *)&RIFFChunkLength, sizeof(TINT32));
os.write("WAVE", 4);
fmtChunk.write(os);
dataChunk.write(os);
return true;
}
|
#define _CRT_SECURE_NO_WARNINGS
#include "Mazda.h"
#include <stdlib.h>
#include <string>
Mazda::Mazda() {
this->Name = (char*)malloc(sizeof(char) * 8);
strcpy(this->Name, "Mazda");
setFuelCap(38);
setFuelCons(49);
setAvgSpeed(43);
}
void Mazda::setFuelCons(float n)
{
this->FuelCons = n;
}
void Mazda::setFuelCap(float n)
{
this->FuelCap = n;
}
void Mazda::setAvgSpeed(float n)
{
this->AvgSpeed = n;
}
float Mazda::getFuelCap()
{
return this->FuelCap;
}
float Mazda::getFuelCons()
{
return this->FuelCons;
}
float Mazda::getAvgSpeed()
{
return this->AvgSpeed;
}
char* Mazda::getName()
{
return this->Name;
}
|
/**
* \file DlgWdbeCprNew_evals.cpp
* job handler for job DlgWdbeCprNew (implementation of availability/activation evaluation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
bool DlgWdbeCprNew::evalButCncActive(
DbsWdbe* dbswdbe
) {
// !sge(create)
vector<bool> args;
bool a;
a = false; a = (ixVSge == VecVSge::CREATE);
args.push_back(a);
a = args.back(); args.pop_back();
args.push_back(!a);
return(args.back());
};
bool DlgWdbeCprNew::evalButCreActive(
DbsWdbe* dbswdbe
) {
// sge(idle)&valid()
vector<bool> args;
bool a, b;
a = false; a = (ixVSge == VecVSge::IDLE);
args.push_back(a);
a = false; a = valid;
args.push_back(a);
b = args.back(); args.pop_back();
a = args.back(); args.pop_back();
args.push_back(a && b);
return(args.back());
};
|
#include "PPMAnalyzerSettings.h"
#include <AnalyzerHelpers.h>
PPMAnalyzerSettings::PPMAnalyzerSettings()
: mInputChannel(UNDEFINED_CHANNEL),
mFrequency(50),
mSyncTimePercentage(20)
{
mInputChannelInterface.reset(new AnalyzerSettingInterfaceChannel());
mInputChannelInterface->SetTitleAndTooltip("Serial", "Standard PPM RC");
mInputChannelInterface->SetChannel(mInputChannel);
mFrequencyInterface.reset(new AnalyzerSettingInterfaceInteger());
mFrequencyInterface->SetTitleAndTooltip("Frequency (Hz)", "Approximate frequency of the signal.");
mFrequencyInterface->SetMax(10000000);
mFrequencyInterface->SetMin(1);
mFrequencyInterface->SetInteger(mFrequency);
mSyncTimePercentageInterface.reset(new AnalyzerSettingInterfaceInteger());
mSyncTimePercentageInterface->SetTitleAndTooltip("Sync Time Percentage (%)", "Percentage of the frequency to use as a threshold for detecting the sync time.");
mSyncTimePercentageInterface->SetMax(99);
mSyncTimePercentageInterface->SetMin(1);
mSyncTimePercentageInterface->SetInteger(mSyncTimePercentage);
AddInterface(mInputChannelInterface.get());
AddInterface(mFrequencyInterface.get());
AddInterface(mSyncTimePercentageInterface.get());
AddExportOption(0, "Export as text/csv file");
AddExportExtension(0, "text", "txt");
AddExportExtension(0, "csv", "csv");
ClearChannels();
AddChannel(mInputChannel, "PPM RC", false);
}
PPMAnalyzerSettings::~PPMAnalyzerSettings()
{
}
bool PPMAnalyzerSettings::SetSettingsFromInterfaces()
{
mInputChannel = mInputChannelInterface->GetChannel();
mFrequency = mFrequencyInterface->GetInteger();
mSyncTimePercentage = mSyncTimePercentageInterface->GetInteger();
ClearChannels();
AddChannel(mInputChannel, "PPM RC", true);
return true;
}
void PPMAnalyzerSettings::UpdateInterfacesFromSettings()
{
mInputChannelInterface->SetChannel(mInputChannel);
mFrequencyInterface->SetInteger(mFrequency);
mSyncTimePercentageInterface->SetInteger(mSyncTimePercentage);
}
void PPMAnalyzerSettings::LoadSettings(const char* settings)
{
SimpleArchive text_archive;
text_archive.SetString(settings);
text_archive >> mInputChannel;
text_archive >> mFrequency;
text_archive >> mSyncTimePercentage;
ClearChannels();
AddChannel(mInputChannel, "PPM RC", true);
UpdateInterfacesFromSettings();
}
const char* PPMAnalyzerSettings::SaveSettings()
{
SimpleArchive text_archive;
text_archive << mInputChannel;
text_archive << mFrequency;
text_archive << mSyncTimePercentage;
return SetReturnString(text_archive.GetString());
}
|
#include "DirectionalLight.h"
DirectionalLight::DirectionalLight()
: Light()
, Direction(0.0f, -1.0f, 0.0f)
, Rotation(0.0f, 0.0f, 0.0f)
, ShadowMapPosition(0.0f, 0.0f, 0.0f)
, LookAt(0.0f, 0.0f, 0.0f)
, Matrix()
{
CORE_OBJECT_INIT();
XMStoreFloat4x4(&Matrix, XMMatrixIdentity());
}
DirectionalLight::~DirectionalLight()
{
}
void DirectionalLight::SetRotation(const XMFLOAT3& InRotation)
{
Rotation = InRotation;
CalculateMatrix();
}
void DirectionalLight::SetRotation(float x, float y, float z)
{
SetRotation(XMFLOAT3(x, y, z));
}
void DirectionalLight::SetLookAt(const XMFLOAT3& InLookAt)
{
LookAt = InLookAt;
CalculateMatrix();
}
void DirectionalLight::SetLookAt(float x, float y, float z)
{
SetLookAt(XMFLOAT3(x, y, z));
}
void DirectionalLight::SetShadowNearPlane(float InShadowNearPlane)
{
if (InShadowNearPlane > 0.0f)
{
if (abs(ShadowFarPlane - InShadowNearPlane) >= 0.1f)
{
ShadowNearPlane = InShadowNearPlane;
CalculateMatrix();
}
}
}
void DirectionalLight::SetShadowFarPlane(float InShadowFarPlane)
{
if (InShadowFarPlane > 0.0f)
{
if (abs(InShadowFarPlane - ShadowNearPlane) >= 0.1f)
{
ShadowFarPlane = InShadowFarPlane;
CalculateMatrix();
}
}
}
void DirectionalLight::CalculateMatrix()
{
XMVECTOR XmDirection = XMVectorSet(0.0, -1.0f, 0.0f, 0.0f);;
XMMATRIX XmRotation = XMMatrixRotationRollPitchYaw(Rotation.x, Rotation.y, Rotation.z);
XMVECTOR XmOffset = XMVector3Transform(XmDirection, XmRotation);
XmDirection = XMVector3Normalize(XmOffset);
XMStoreFloat3(&Direction, XmDirection);
const float Scale = (ShadowFarPlane - ShadowNearPlane) / 2.0f;
XmOffset = XMVectorScale(XmOffset, -Scale);
XMVECTOR XmLookAt = XMLoadFloat3(&LookAt);
XMVECTOR XmPosition = XMVectorAdd(XmLookAt, XmOffset);
XMStoreFloat3(&ShadowMapPosition, XmPosition);
XMVECTOR XmUp = XMVectorSet(0.0, 0.0f, 1.0f, 0.0f);
XmUp = XMVector3Normalize(XMVector3Transform(XmUp, XmRotation));
const float Offset = 35.0f;
XMMATRIX XmProjection = XMMatrixOrthographicOffCenterLH(-Offset, Offset, -Offset, Offset, ShadowNearPlane, ShadowFarPlane);
XMMATRIX XmView = XMMatrixLookAtLH(XmPosition, XmLookAt, XmUp);
XMStoreFloat4x4(&Matrix, XMMatrixMultiplyTranspose(XmView, XmProjection));
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:20c51b5d9d5a8a90bda9e887b887b5874af1afd646ef510e2120d03b5083abb0
size 6260
|
// -----------------------------------------------------------------------------
// Fern © Geoneric
//
// This file is part of Geoneric Fern which is available under the terms of
// the GNU General Public License (GPL), version 2. If you do not want to
// be bound by the terms of the GPL, you may purchase a proprietary license
// from Geoneric (http://www.geoneric.eu/contact).
// -----------------------------------------------------------------------------
#include <Python.h> // This one first, to get rid of preprocessor warnings.
#include "fern/language/script/algebra_parser.h"
#include <cassert>
#include <iostream>
#include "Python-ast.h"
#include "fern/core/exception.h"
#include "fern/core/string.h"
#include "fern/language/python/exception.h"
// PyObject* type = PyObject_Type(id);
// PyObject* string = PyObject_Str(type);
// std::cout << PyString_AsString(string) << std::endl;
namespace {
void write_expression_node(
expr_ty const& expression,
std::string& xml);
void write_expression_nodes(
asdl_seq const* expressions,
std::string& xml);
void write_statement_nodes(
asdl_seq const* statements,
std::string& xml);
void throw_unsupported_language_construct(
long line_nr,
long col_nr,
std::string const& kind)
{
BOOST_THROW_EXCEPTION(fern::detail::UnsupportedLanguageConstruct()
<< fern::detail::ExceptionConstruct(kind)
<< fern::detail::ExceptionLineNr(line_nr)
<< fern::detail::ExceptionColNr(col_nr)
);
}
void write_identifier_node(
identifier const identifier,
std::string& xml)
{
assert(PyString_Check(identifier));
// TODO Handle Unicode. In modern Python, identifiers are Unicode strings.
xml += "<Name>";
xml += PyString_AsString(identifier);
xml += "</Name>";
// PyObject* bytes = PyUnicode_AsUTF8String(identifier);
// assert(bytes);
// xml += dev::decodeFromUTF8(PyBytes_AsString(bytes));
}
void write_name_node(
identifier const identifier,
expr_context_ty const& /* context */,
std::string& xml)
{
write_identifier_node(identifier, xml);
}
void write_number_node(
object const& number,
std::string& xml)
{
// TODO Handle all numeric types.
// TODO Use types with a known size: int32, int64, float32, float64, etc.
xml += "<Number>";
// From the Python docs:
// Plain integers (also just called integers) are implemented using
// long in C, which gives them at least 32 bits of precision
// (sys.maxint is always set to the maximum plain integer value for the
// current platform, the minimum value is -sys.maxint - 1).
if(PyInt_CheckExact(number)) {
// The number object contains a C long value. The size of long is
// platform dependent.
xml += "<Integer>";
xml += "<Size>";
xml += (boost::format("%1%") % (sizeof(long) * 8)).str().c_str();
xml += "</Size>";
xml += "<Value>";
xml += (boost::format("%1%") % PyInt_AsLong(number)).str().c_str();
xml += "</Value>";
xml += "</Integer>";
}
else if(PyLong_CheckExact(number)) {
// TODO Can we assume that the value fits in a long long? Otherwise,
// handle overflow.
xml += "<Integer>";
xml += "<Size>";
xml += (boost::format("%1%") % (sizeof(long long) * 8)).str().c_str();
xml += "</Size>";
xml += "<Value>";
xml += (boost::format("%1%") % PyLong_AsLongLong(number)).str().c_str();
xml += "</Value>";
xml += "</Integer>";
}
else if(PyFloat_CheckExact(number)) {
// TODO What is the size of a Python float?
xml += "<Float>";
xml += "<Size>";
xml += (boost::format("%1%") % (sizeof(double) * 8)).str().c_str();
xml += "</Size>";
xml += "<Value>";
xml += (boost::format("%1%") % PyFloat_AsDouble(number)).str().c_str();
xml += "</Value>";
xml += "</Float>";
}
else {
// TODO Error handling.
assert(false);
}
xml += "</Number>";
}
void write_string_node(
string const string,
std::string& xml)
{
// TODO Verify the string is encoded as UTF8.
// TODO Only support Unicode strings? Convert on the fly when it's not?
assert(PyString_Check(string));
if(PyString_Size(string) == 0) {
xml += "<String/>";
}
else {
xml += "<String>";
xml += PyString_AsString(string);
xml += "</String>";
}
}
void write_expressions_node(
asdl_seq const* expressions,
std::string& xml)
{
if(expressions == 0) {
xml += "<Expressions/>";
}
else {
assert(expressions->size > 0);
xml += "<Expressions>";
for(int i = 0; i < expressions->size; ++i) {
expr_ty const expression = static_cast<expr_ty const>(
asdl_seq_GET(expressions, i));
write_expression_node(expression, xml);
}
xml += "</Expressions>";
}
}
void write_call_node(
expr_ty const function,
asdl_seq const* arguments,
#ifndef NDEBUG
asdl_seq const* keywords,
expr_ty const starargs,
expr_ty const kwargs,
#else
asdl_seq const*,
expr_ty const,
expr_ty const,
#endif
std::string& xml)
{
assert(keywords == 0 || keywords->size == 0); // TODO Support keywords.
assert(starargs == 0); // TODO
assert(kwargs == 0); // TODO
xml += "<FunctionCall>";
assert(function->kind == Name_kind);
write_name_node(function->v.Name.id, function->v.Name.ctx, xml);
write_expressions_node(arguments, xml);
xml += "</FunctionCall>";
}
void write_unary_operator_node(
unaryop_ty const unaryOperator,
expr_ty const operand,
std::string& xml)
{
xml += "<Operator><Name>";
switch(unaryOperator) {
case Invert: {
xml += "Invert";
break;
}
case Not: {
xml += "Not";
break;
}
case UAdd: {
xml += "UnaryAdd";
break;
}
case USub: {
xml += "UnarySub";
break;
}
// Don't add a default clause! We want to hear from the compiler if
// we're missing a case.
}
xml += "</Name>";
xml += "<Expressions>";
write_expression_node(operand, xml);
xml += "</Expressions>";
xml += "</Operator>";
}
void write_binary_operator_node(
expr_ty const left_operand,
operator_ty const binary_operator,
expr_ty const right_operand,
std::string& xml)
{
xml += "<Operator><Name>";
switch(binary_operator) {
case Add: {
xml += "add";
break;
}
case Sub: {
xml += "Sub";
break;
}
case Mult: {
xml += "Mult";
break;
}
case Div: {
xml += "Div";
break;
}
case Mod: {
xml += "Mod";
break;
}
case Pow: {
xml += "Pow";
break;
}
case LShift: {
xml += "LShift";
break;
}
case RShift: {
xml += "RShift";
break;
}
case BitOr: {
xml += "BitOr";
break;
}
case BitXor: {
xml += "BitXor";
break;
}
case BitAnd: {
xml += "BitAnd";
break;
}
case FloorDiv: {
xml += "FloorDiv";
break;
}
// Don't add a default clause! We want to hear from the compiler if
// we're missing a case.
}
xml += "</Name>";
xml += "<Expressions>";
write_expression_node(left_operand, xml);
write_expression_node(right_operand, xml);
xml += "</Expressions>";
xml += "</Operator>";
}
void write_boolean_operator_node(
boolop_ty const boolean_operator,
asdl_seq const* operands,
std::string& xml)
{
xml += "<Operator><Name>";
switch(boolean_operator) {
case And: {
xml += "And";
break;
}
case Or: {
xml += "Or";
break;
}
// Don't add a default clause! We want to hear from the compiler if
// we're missing a case.
}
xml += "</Name>";
write_expressions_node(operands, xml);
xml += "</Operator>";
}
void write_comparison_operator_node(
expr_ty const left_operand,
asdl_int_seq const* operators,
asdl_seq const* comparators,
std::string& xml)
{
// http://docs.python.org/reference/expressions.html#notin
// x < y <= z is equivalent to x < y and y <= z
assert(operators->size == 1); // TODO
assert(operators->size == comparators->size);
xml += "<Operator><Name>";
switch(operators->elements[0]) {
case Eq: {
xml += "Eq";
break;
}
case NotEq: {
xml += "NotEq";
break;
}
case Lt: {
xml += "Lt";
break;
}
case LtE: {
xml += "LtE";
break;
}
case Gt: {
xml += "Gt";
break;
}
case GtE: {
xml += "GtE";
break;
}
default: {
// TODO Exception. Unsupported operator. Is=7, IsNot=8, In=9,
// NotIn=10
assert(false);
break;
}
}
xml += "</Name><Expressions>";
write_expression_node(left_operand, xml);
write_expression_node(static_cast<expr_ty const>(
asdl_seq_GET(comparators, 0)), xml);
xml += "</Expressions></Operator>";
}
void write_slice_node(
slice_ty const slice,
std::string& xml)
{
// TODO Raise exception.
assert(slice->kind == Index_kind);
switch(slice->kind) {
case Ellipsis_kind: {
break;
}
case Slice_kind: {
break;
}
case ExtSlice_kind: {
break;
}
case Index_kind: {
write_expression_node(slice->v.Index.value, xml);
break;
}
}
}
void write_subscript_node(
expr_ty const expression,
slice_ty const slice,
expr_context_ty const /* context */,
std::string& xml)
{
// expression is the expression being subscripted.
xml += "<Subscript>";
write_expression_node(expression, xml);
write_slice_node(slice, xml);
xml += "</Subscript>";
}
void write_attribute_node(
expr_ty const expression,
identifier const name,
expr_context_ty const /* context */,
std::string& xml)
{
xml += "<Attribute>";
write_expression_node(expression, xml);
write_identifier_node(name, xml);
xml += "</Attribute>";
}
void write_expression_node(
expr_ty const& expression,
std::string& xml)
{
assert(expression);
// 1-based linenumber.
// 0-based column id.
long line_nr = expression->lineno;
long col_nr = expression->col_offset;
xml += (boost::format("<Expression line=\"%1%\" col=\"%2%\">")
% line_nr
% col_nr).str().c_str();
switch(expression->kind) {
case Name_kind: {
write_name_node(expression->v.Name.id, expression->v.Name.ctx, xml);
break;
}
case Num_kind: {
write_number_node(expression->v.Num.n, xml);
break;
}
case Str_kind: {
write_string_node(expression->v.Str.s, xml);
break;
}
case Call_kind: {
write_call_node(expression->v.Call.func, expression->v.Call.args,
expression->v.Call.keywords, expression->v.Call.starargs,
expression->v.Call.kwargs, xml);
break;
}
case UnaryOp_kind: {
write_unary_operator_node(expression->v.UnaryOp.op,
expression->v.UnaryOp.operand, xml);
break;
}
case BinOp_kind: {
write_binary_operator_node(expression->v.BinOp.left,
expression->v.BinOp.op, expression->v.BinOp.right, xml);
break;
}
case BoolOp_kind: {
write_boolean_operator_node(expression->v.BoolOp.op,
expression->v.BoolOp.values, xml);
break;
}
case Compare_kind: {
write_comparison_operator_node(expression->v.Compare.left,
expression->v.Compare.ops, expression->v.Compare.comparators,
xml);
break;
}
case Subscript_kind: {
write_subscript_node(expression->v.Subscript.value,
expression->v.Subscript.slice, expression->v.Subscript.ctx,
xml);
break;
}
case IfExp_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "if");
break;
}
case Lambda_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "lambda");
break;
}
case Dict_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "dictionary");
break;
}
case DictComp_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"dictionary comprehension");
break;
}
case GeneratorExp_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "generator");
break;
}
case Yield_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "yield");
break;
}
case Repr_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "repr");
break;
}
case Attribute_kind: {
write_attribute_node(expression->v.Attribute.value,
expression->v.Attribute.attr, expression->v.Attribute.ctx, xml);
break;
}
case List_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "list");
break;
}
case ListComp_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"list comprehension");
break;
}
case Set_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "set");
break;
}
case SetComp_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"set comprehension");
break;
}
case Tuple_kind: {
throw_unsupported_language_construct(line_nr, col_nr, "tuple");
break;
}
}
xml += "</Expression>";
}
//!
/*!
\param targets One or more targets of the value or values passed in.
\param value One or more values to assign to the targets.
\return .
\exception .
\warning .
\sa .
*/
void write_assignment_node(
asdl_seq const* targets,
expr_ty const& value,
std::string& xml)
{
// Copy the value expression to one or more targets.
// When there is more than one target, value should be an iterable.
// For now we can limit the number of targets to one.
assert(targets->size == 1); // TODO Error handling.
expr_ty const target = static_cast<expr_ty const>(asdl_seq_GET(targets, 0));
// We don't support attributeref, subscription and slicing.
assert(target->kind == Name_kind); // TODO Error handling.
xml += "<Assignment>";
write_expression_node(target, xml);
write_expression_node(value, xml);
xml += "</Assignment>";
}
void write_if_node(
expr_ty const test,
asdl_seq const* body,
asdl_seq const* orelse,
std::string& xml)
{
xml += "<If>";
write_expression_node(test, xml);
write_statement_nodes(body, xml);
write_statement_nodes(orelse, xml);
xml += "</If>";
}
void write_while_node(
expr_ty const test,
asdl_seq const* body,
asdl_seq const* orelse,
std::string& xml)
{
xml += "<While>";
write_expression_node(test, xml);
write_statement_nodes(body, xml);
write_statement_nodes(orelse, xml);
xml += "</While>";
}
void write_arguments_node(
arguments_ty const arguments,
std::string& xml)
{
// TODO Throw exception in case vararg, kwarg, or defaults are set.
write_expression_nodes(arguments->args, xml);
}
void write_function_definition_node(
identifier const name,
arguments_ty const arguments,
asdl_seq const* body,
asdl_seq const* /* decorator_list */,
std::string& xml)
{
// TODO Exception when decorator_list is not empty.
xml += "<FunctionDefinition>";
write_identifier_node(name, xml);
write_arguments_node(arguments, xml);
write_statement_nodes(body, xml);
xml += "</FunctionDefinition>";
}
void write_return_node(
expr_ty const value,
std::string& xml)
{
if(!value) {
xml += "<Return/>";
}
else {
xml += "<Return>";
write_expression_node(value, xml);
xml += "</Return>";
}
}
// void writePrintFunctionNode(
// expr_ty const dest,
// asdl_seq const* values,
// std::string& xml)
// {
// // assert(!values || values->size == 0); // built-in print specific.
// // assert(values->size == 1);
// // 1-based linenumber.
// // 0-based column id.
// xml += (boost::format("<Expression line=\"%1%\" col=\"%2%\">")
// % expression->lineno
// % expression->col_offset);
// xml += "<FunctionCall>";
// xml += "<Name>";
// xml += "print";
// xml += "</Name>";
// write_expressions_node(values, xml);
// xml += "</FunctionCall>";
// xml += "</Expression>";
// }
void write_expression_nodes(
asdl_seq const* expressions,
std::string& xml)
{
if(!expressions || asdl_seq_LEN(expressions) == 0) {
xml += "<Expressions/>";
}
else {
xml += "<Expressions>";
for(int i = 0; i < asdl_seq_LEN(expressions); ++i) {
expr_ty const expression = static_cast<expr_ty const>(
asdl_seq_GET(expressions, i));
assert(expression);
write_expression_node(expression, xml);
}
xml += "</Expressions>";
}
}
void write_statement_nodes(
asdl_seq const* statements,
std::string& xml)
{
if(!statements || asdl_seq_LEN(statements) == 0) {
xml += "<Statements/>";
}
else {
xml += "<Statements>";
// See Python-ast.h.
for(int i = 0; i < asdl_seq_LEN(statements); ++i) {
stmt_ty const statement = static_cast<stmt_ty const>(
asdl_seq_GET(statements, i));
assert(statement);
// 1-based linenumber.
// 0-based column id.
long line_nr = statement->lineno;
long col_nr = statement->col_offset;
// TODO Add line/col to XML.
// xml += "<Statement>";
xml += (boost::format("<Statement line=\"%1%\" col=\"%2%\">")
% line_nr
% col_nr).str().c_str();
switch(statement->kind) {
case Expr_kind: {
write_expression_node(statement->v.Expr.value, xml);
break;
}
case Assign_kind: {
write_assignment_node(statement->v.Assign.targets,
statement->v.Assign.value, xml);
break;
}
case If_kind: {
write_if_node(statement->v.If.test, statement->v.If.body,
statement->v.If.orelse, xml);
break;
}
case While_kind: {
write_while_node(statement->v.While.test,
statement->v.While.body, statement->v.While.orelse,
xml);
break;
}
case FunctionDef_kind: {
write_function_definition_node(
statement->v.FunctionDef.name,
statement->v.FunctionDef.args,
statement->v.FunctionDef.body,
statement->v.FunctionDef.decorator_list, xml);
break;
}
case Return_kind: {
write_return_node(statement->v.Return.value, xml);
break;
}
case Print_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"print");
break;
}
// {
// writePrintFunctionNode(statement->v.Print.dest,
// statement->v.Print.values, xml);
// break;
// }
case Break_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"break");
break;
}
case Continue_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"continue");
break;
}
case Assert_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"assert");
break;
}
case AugAssign_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"augmented assign");
break;
}
case Global_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"global");
break;
}
case Pass_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"pass");
break;
}
case ClassDef_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"define class");
break;
}
case Delete_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"delete");
break;
}
case For_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"for");
break;
}
case With_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"with");
break;
}
case Raise_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"raise");
break;
}
case TryExcept_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"try/except");
break;
}
case TryFinally_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"try/finally");
break;
}
case Import_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"import");
break;
}
case ImportFrom_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"import from");
break;
}
case Exec_kind: {
throw_unsupported_language_construct(line_nr, col_nr,
"exec");
break;
}
}
xml += "</Statement>";
}
xml += "</Statements>";
}
}
// <string> -> "<string>"
std::string escape(
std::string const& string)
{
std::string result = string;
return fern::replace(fern::replace(fern::replace(fern::replace(
fern::replace(result,
"&" , "&"), // This one first!
"<" , "<"),
">" , ">"),
"\"", """),
"'" , "'")
;
}
std::string python_ast_to_xml(
mod_ty const ast,
std::string const& source_name)
{
assert(ast);
std::string xml;
try {
switch(ast->kind) {
case Module_kind: {
xml += (boost::format("<Fern source=\"%1%\">")
% escape(source_name)).str().c_str();
write_statement_nodes(ast->v.Module.body, xml);
xml += "</Fern>";
break;
}
case Expression_kind: // {
// write_expression_node(ast->v.Expression.body, xml);
// break;
// }
case Interactive_kind:
case Suite_kind: {
// TODO Error message.
#ifndef NDEBUG
bool implemented = false;
assert(implemented);
#endif
break;
}
}
}
catch(fern::detail::Exception& exception) {
exception
<< fern::detail::ExceptionSourceName(source_name)
;
throw;
}
return xml;
}
//! A small class to make creation and deletion of PyArena's easier.
/*!
Whenever the SmartArena goes out of scope, the layered PyArena pointer
is freed.
*/
class SmartArena
{
public:
SmartArena()
: _arena(PyArena_New())
{
assert(_arena);
}
~SmartArena()
{
PyArena_Free(_arena);
}
SmartArena(SmartArena&&)=delete;
SmartArena& operator=(SmartArena&&)=delete;
SmartArena(SmartArena&)=delete;
SmartArena& operator=(SmartArena&)=delete;
PyArena* arena()
{
return _arena;
}
private:
PyArena* _arena;
};
} // Anonymous namespace
namespace fern {
namespace language {
//! Construct an AlgebraParser instance.
/*!
*/
AlgebraParser::AlgebraParser()
: python::Client()
{
assert(python::Client::is_initialized());
}
//! Parse the script in \a string and return an XML document.
/*!
\param string String containing the script to parse.
\return String containing the script as an XML.
\exception .
\warning .
\sa .
*/
std::string AlgebraParser::parse_string(
std::string const& string) const
{
SmartArena smart_arena;
mod_ty ast = PyParser_ASTFromString(string.c_str(), "", Py_file_input, 0,
smart_arena.arena());
if(!ast) {
python::throw_exception("<string>");
}
return "<?xml version=\"1.0\"?>" + python_ast_to_xml(ast, "<string>");
}
//! Parse the script in file \a filename and return an XML document.
/*!
\param filename Name of file containing the script to parse.
\return String containing the script as an XML.
\exception .
\warning .
\sa .
*/
std::string AlgebraParser::parse_file(
std::string const& filename) const
{
SmartArena smart_arena;
std::string filename_in_utf8(filename);
FILE* file_pointer = fopen(filename_in_utf8.c_str(), "r");
if(file_pointer == NULL) {
BOOST_THROW_EXCEPTION(detail::FileOpenError()
<< boost::errinfo_errno(errno)
<< detail::ExceptionSourceName(filename));
}
mod_ty ast = PyParser_ASTFromFile(file_pointer, filename_in_utf8.c_str(),
Py_file_input, 0, 0, 0, 0, smart_arena.arena());
if(!ast) {
python::throw_exception(filename);
}
return "<?xml version=\"1.0\"?>" + python_ast_to_xml(ast, filename);
}
} // namespace language
} // namespace fern
|
/**
* Class to process csv-lines, formatted in the LinTim Activities-periodic.giv, Events-periodic.giv or
* Timetable-periodic.tim format. Use a {@link CsvReader}
* with an instance of this class to read a periodic activities, events or timetable file.
* <p>
*/
#ifndef PERIODICEANREADER_HPP
#define PERIODICEANREADER_HPP
#include "../exception/exceptions.hpp"
#include <string>
#include <algorithm>
#include "../model/PeriodicActivity.hpp"
#include "../model/PeriodicEvent.hpp"
#include "../model/impl/AdjacencyListGraph.hpp"
#include "CsvReader.hpp"
class PeriodicEANReader{
private:
std::string periodicActivitiesFileName;
std::string periodicEventsFileName;
std::string periodicTimetableFileName;
AdjacencyListGraph<PeriodicEvent, PeriodicActivity>* periodicEAN;
public:
/**
* Constructor for a PeriodicEANReader for given file names and periodic EAN. The given names will not influence
* the read file but the used name in any error message, so be sure to use the same name in here and in the
* {@link CsvReader}!
*
* @param periodicActivitiesFileName source file name for periodic activities
* @param periodicEventsFileName source file name for periodic events
* @param periodicTimetableFileName source file name for periodic timetable
* @param periodicEAN periodic event activity network
*/
PeriodicEANReader(AdjacencyListGraph<PeriodicEvent, PeriodicActivity>* periodicEAN,
std::string periodicActivitiesFileName, std::string periodicEventsFileName,
std::string periodicTimetableFileName = ""){
this->periodicActivitiesFileName = periodicActivitiesFileName;
this->periodicEventsFileName = periodicEventsFileName;
this->periodicTimetableFileName = periodicTimetableFileName;
this->periodicEAN = periodicEAN;
}
/**
* Process the content of a periodic event file.
*
* @param args the content of the line
* @param lineNumber the line number, used for error handling
* @throws InputFormatException if the line contains not exactly 5 entries
* @throws InputTypeInconsistencyException if the specific types of the entries do not match the expectations
* @throws DataIllegalEventTypeException if the event type is not defined
* @throws GraphNodeIdMultiplyAssignedException if the event cannot be added to the EAN
*/
void processPeriodicEvent(std::vector <std::string> args, int lineNumber){
if(args.size() != 7){
throw new InputFormatException(periodicEventsFileName, args.size(), 5);
}
int eventId;
EventType type;
int stopId;
int lineId;
double passengers;
LineDirection ldir;
int lineFrequencyRepetition;
try{
eventId = std::stoi(args[0]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicEventsFileName, 1, lineNumber, "int", args[0]);
}
std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower);
if(args[1].find("arrival") != std::string::npos){
type = ARRIVAL;
} else if(args[1].find("departure") != std::string::npos){
type = DEPARTURE;
} else if(args[1].find("fix") != std::string::npos){
type = FIX;
} else if(args[1].find("virtual") != std::string::npos){
type = EXT;
} else{
throw DataIllegalEventTypeException(eventId, args[1]);
}
try{
stopId = std::stoi(args[2]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicEventsFileName, 3, lineNumber, "int", args[2]);
}
try{
lineId = std::stoi(args[3]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicEventsFileName, 4, lineNumber, "int", args[3]);
}
try{
passengers = std::stod(args[4]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicEventsFileName, 5, lineNumber, "double", args[4]);
}
try{
std::string tmp = args[5];
if (tmp.find("<") != std::string::npos) ldir = BACKWARDS;
else if (tmp.find(">") != std::string::npos) ldir = FORWARDS;
else throw DataIllegalLineDirectionException(eventId, args[5]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicEventsFileName, 5, lineNumber, "string", args[5]);
}
try{
lineFrequencyRepetition = std::stoi(args[6]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicEventsFileName, 6, lineNumber, "double", args[6]);
}
PeriodicEvent periodicEvent = PeriodicEvent(eventId, stopId, type, lineId, 0, passengers, ldir, lineFrequencyRepetition);
if(!periodicEAN->addNode(periodicEvent)){
throw GraphNodeIdMultiplyAssignedException(eventId);
}
}
/**
* Process the content of a periodic activity file.
*
* @param args the content of the line
* @param lineNumber the line number, used for error handling
* @throws InputFormatException if the line contains not exactly 7 entries
* @throws InputTypeInconsistencyException if the specific types of the entries do not match the expectations
* @throws DataIllegalActivityTypeException if the activity type is not defined
* @throws GraphIncidentNodeNotFoundException if an event incident to the activity is not found
* @throws GraphEdgeIdMultiplyAssignedException if the activity cannot be added to the EAN
*/
void processPeriodicActivity(std::vector <std::string> args, int lineNumber){
if(args.size() != 7){
throw InputFormatException(periodicActivitiesFileName, args.size(), 7);
}
int activityId;
ActivityType type;
int sourceEventId;
int targetEventId;
int lowerBound;
int upperBound;
double passengers;
try{
activityId = std::stoi(args[0]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicActivitiesFileName, 1, lineNumber, "int", args[0]);
}
std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower);
if(args[1].find("drive") != std::string::npos){
type = DRIVE;
} else if(args[1].find("wait") != std::string::npos){
type = WAIT;
} else if(args[1].find("change") != std::string::npos){
type = CHANGE;
} else if(args[1].find("headway") != std::string::npos){
type = HEADWAY;
} else if(args[1].find("turnaround") != std::string::npos){
type = TURNAROUND;
} else if(args[1].find("sync") != std::string::npos){
type = SYNC;
} else if(args[1].find("virtual") != std::string::npos){
type = VIRTUAL;
} else{
throw DataIllegalActivityTypeException(activityId, args[1]);
}
try{
sourceEventId = std::stoi(args[2]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicActivitiesFileName, 3, lineNumber, "int", args[2]);
}
try{
targetEventId = std::stoi(args[3]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicActivitiesFileName, 4, lineNumber, "int", args[3]);
}
try{
lowerBound = std::stoi(args[4]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicActivitiesFileName, 5, lineNumber, "int", args[4]);
}
try{
upperBound = std::stoi(args[5]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicActivitiesFileName, 6, lineNumber, "int", args[5]);
}
try{
passengers = std::stod(args[6]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicActivitiesFileName, 7, lineNumber, "double", args[6]);
}
PeriodicEvent* sourceEvent = periodicEAN->getNode(sourceEventId);
if(sourceEvent == nullptr){
throw GraphIncidentNodeNotFoundException(activityId, sourceEventId);
}
PeriodicEvent* targetEvent = periodicEAN->getNode(targetEventId);
if(targetEvent == nullptr){
throw GraphIncidentNodeNotFoundException(activityId, targetEventId);
}
if(!periodicEAN->addEdge(PeriodicActivity(activityId, type, sourceEvent, targetEvent,
lowerBound, upperBound, passengers))){
throw GraphEdgeIdMultiplyAssignedException(activityId);
}
}
/**
* Process the content of a timetable file.
*
* @param args the content of the line
* @param lineNumber the line number, used for error handling
* @throws InputFormatException if the line contains not exactly 2 entries
* @throws InputTypeInconsistencyException if the specific types of the entries do not match the expectations
* @throws DataIndexNotFoundException if the event does not exist
*/
void processPeriodicTimetable(std::vector <std::string> args, int lineNumber){
if(args.size() != 2){
throw InputFormatException(periodicTimetableFileName, args.size(), 2);
}
int eventId;
int time;
try{
eventId = std::stoi(args[0]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicTimetableFileName, 1, lineNumber, "int", args[0]);
}
try{
time = std::stoi(args[1]);
} catch(std::exception& e){
throw InputTypeInconsistencyException(periodicTimetableFileName, 2, lineNumber, "int", args[1]);
}
PeriodicEvent* event = periodicEAN->getNode(eventId);
if(event == nullptr){
throw DataIndexNotFoundException("Periodic event", eventId);
}
event->setTime(time);
}
/**
* Reads Everything.
*/
void read(){
CsvReader c;
c.readCsv(periodicEventsFileName, *this, &PeriodicEANReader::processPeriodicEvent);
c.readCsv(periodicActivitiesFileName, *this, &PeriodicEANReader::processPeriodicActivity);
if(!periodicTimetableFileName.empty()){
c.readCsv(periodicTimetableFileName, *this, &PeriodicEANReader::processPeriodicTimetable);
}
}
};
#endif
|
#include <iostream>
#include <string>
using namespace std;
/*
Laboratory 2 Ex 1
Write a program to prompt user name of favourite game and decide what kind of game he chose. Use switch statemant, at least five cases and default case.
*/
int main () {
string favouritegame;
int genre;
cout << "What is your favourite game? ";
cin >> favouritegame;
cout << "and What kind of game is this?\n" << "1.Action\n2.Adventure\n3.Horror\n4.Simulation\n5.Strategy" << endl;
cin >> genre;
switch (genre) {
case 1 :
cout << "Your favourite game is " << favouritegame << ", which is Action game." << endl;
break;
case 2 :
cout << "Your favourite game is " << favouritegame << ", which is Adventure game." << endl;
break;
case 3 :
cout << "Your favourite game is " << favouritegame << ", which is Horror game." << endl;
break;
case 4 :
cout << "Your favourite game is " << favouritegame << ", which is Simulation game." << endl;
break;
case 5 :
cout << "Your favourite game is " << favouritegame << ", which is Strategy game." << endl;
break;
default :
cout << "Your favourite game is " << favouritegame << ", which is lovely game." << endl;
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long long unsigned llu;
typedef double dl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef map<int,int> mii;
typedef map<ll,ll> mll;
typedef map<string,int> msi;
typedef map<char,int> mci;
#define PI acos(-1.0)
#define S second
#define F first
#define PB push_back
#define MP make_pair
#define P push
#define zero(a) memset(a,0,sizeof a)
#define minus(a) memset(a,-1,sizeof a)
#define setinf(a) memset(a,126,sizeof a)
#define all(v) (v.begin(),v.end())
#define vsort(v) sort(v.begin(),v.end())
#define nl puts("")
#define tcase(cs) printf("Case %d:",++cs)
#define endl '\n'
#define READ(in) freopen("in.in","r",stdin)
#define WRITE(out) freopen("out.out","w",stdout)
#define I_O ios_base::sync_with_stdio(0); cin.tie(0);
#define gcd(a,b) __gcd(a,b)
#define sci(a) scanf("%d",&a)
#define scl(a) scanf("%lld",&a)
#define scd(a) scanf("%lf",&a)
//cout << fixed << setprecision(20) << p << endl;
template <class T> inline T BMOD(T p,T e,T m){T ret=1;while(e){if(e&1) ret=(ret*p)%m;p=(p*p)%m;e>>=1;}return (T)ret;}
template <class T> inline T MODINV(T a,T m){return BMOD(a,m-2,m);}
template <class T> inline T isPrime(T a){for(T i=2;i<=sqrt(double(a));i++){if(a%i==0){return 0;}}return 1;}
template <class T> inline T lcm(T a, T b){return (a/gcd(a,b))*b;}
bool vs[10000001];
vl prm,sv;
void F(){
for(ll i=4;i<100001;i+=2) vs[i]=1;
for(ll i=3;i*i<100001;i+=2){
if(!vs[i]){
for(ll j=i*i;j<100001;j+=i) vs[j]=1;
}
}
prm.PB(2);
for(ll i=3;i<100001;i+=2){
if(!vs[i]) prm.PB(i);
}
sv.PB(0);
sv.PB(0);
sv.PB(1);
for(ll i=3;i<3000001;i++){
ll t=i;
ll dv=0;
for(ll j=0;j<(ll)prm.size()&&prm[j]<=sqrt(t);j++){
if(t%prm[j]==0){
ll cnt=0;
while(t%prm[j]==0){
cnt++;
t/=prm[j];
}
dv+=cnt;
}
}
if(t>1) dv++;
sv.PB(dv);
}
for(ll i=1;i<(ll)sv.size();i++){
sv[i]+=sv[i-1];
}
}
int main()
{
F();
//cout<<"OK"<<endl;
//for(int i=0;i<10;i++) cout<<sv[i]<<" ";
ll ts;
ll n,Ans;
cin>>ts;
while(ts--){
cin>>n;
Ans=upper_bound(sv.begin(),sv.end(),n)-sv.begin();
cout<<Ans<<endl;
}
return 0;
}
//~ 3
//~ 3 2 49
//~ 9 1 100
//~ 5 55 235
|
#include "KTimer.h"
#include "KSelectorManager.h"
struct timer_run_param
{
KSelector *selector;
timer_func func;
void *arg;
};
void result_timer_call_back(void *arg, int got)
{
timer_run_param *param = (timer_run_param *)arg;
param->func(param->arg);
delete param;
}
void next_timer_call_back(void *arg, int got)
{
timer_run_param *param = (timer_run_param *)arg;
param->selector->add_timer(result_timer_call_back, param,got,NULL);
}
void timer_run(timer_func func,void *arg,int msec,unsigned short selector)
{
timer_run_param *param = new timer_run_param;
param->selector = (selector == 0 ? selectorManager.getSelector() : selectorManager.getSelectorByIndex(selector));
param->func = func;
param->arg = arg;
param->selector->next(next_timer_call_back, param,msec);
}
bool test_timer()
{
return true;
}
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
namespace ATL
{
struct _IDispEventVtbl
{
HRESULT (WINAPIV *_LocDEQueryInterface)(_IDispEvent *_this, _GUID *, void **);
unsigned int (WINAPIV *AddRef)(_IDispEvent *_this);
unsigned int (WINAPIV *Release)(_IDispEvent *_this);
};
}; // end namespace ATL
END_ATF_NAMESPACE
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <vector>
#include <list>
#include <utility>
#include "gna_plugin_log.hpp"
namespace GNAPluginNS {
template <class T>
class PermuteSequence {
public:
using cnt_type = std::vector<std::pair<T, T>>;
private:
std::vector<T> orderVec;
cnt_type permutes;
public:
explicit PermuteSequence(std::vector<T> && orderVecIn) : orderVec(std::move(orderVecIn)) {
std::vector<bool> counter(orderVec.size());
for (auto && x : this->orderVec) {
if (x < 0) {
THROW_GNA_EXCEPTION << "invalid order: element " << x << " should be >= 0";
}
if (x >= counter.size()) {
THROW_GNA_EXCEPTION << "invalid order: element " << x << " should be < "<< counter.size();
}
if (counter[x]) {
THROW_GNA_EXCEPTION << "invalid order: element " << x << " present more than once";
}
counter[x] = true;
}
// generating permutation graph
std::fill(counter.begin(), counter.end(), false);
// length of current cycle
std::list<cnt_type> permuteCycles;
bool newSeq = false;
for (int i = 0; i != orderVec.size();) {
// we have this permutation on the list already
if (counter[i]) {
newSeq = false;
i++;
continue;
}
counter[i] = true;
// looks we found a permutation
if (orderVec[i] != i) {
if (!newSeq) {
newSeq = true;
permuteCycles.push_back({});
}
permuteCycles.back().push_back({i, orderVec[i]});
counter[i] = true;
i = orderVec[i];
continue;
}
// this dims not permuted
i++;
}
for (auto && cycle : permuteCycles) {
for (int i = 0; i + 1 < cycle.size(); i++) {
permutes.push_back(cycle[i]);
}
}
}
const cnt_type & cnt() const noexcept {
return permutes;
}
};
/**
* @brief generates permutations sequence in order to reach given order
* @tparam Iterator
* @return
*/
template <class Iterator>
inline typename PermuteSequence<typename std::iterator_traits<Iterator>::value_type>::cnt_type genPermutations(
Iterator beg, Iterator en) {
static_assert(
std::is_same<std::random_access_iterator_tag,
typename std::iterator_traits<Iterator>::iterator_category>::value,
"The genPermutations() function only accepts random access iterators or raw pointers to an array.\n");
using value_type = typename std::iterator_traits<Iterator>::value_type;
std::vector<value_type> v;
for (; beg != en; beg++) {
v.push_back(*beg);
}
auto permute = PermuteSequence<value_type> (std::move(v));
return permute.cnt();
}
template <class T>
inline typename PermuteSequence<T>::cnt_type genPermutations(const std::initializer_list<T> & lst) {
return genPermutations(lst.begin(), lst.end());
}
} // namespace GNAPluginNS
|
/*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "Gwen/Gwen.h"
#include "Gwen/Skin.h"
#include "Gwen/Controls/TabButton.h"
#include "Gwen/Controls/TabControl.h"
#include "Gwen/Controls/Highlight.h"
#include "Gwen/DragAndDrop.h"
using namespace Gwen;
using namespace Gwen::Controls;
GWEN_CONTROL_CONSTRUCTOR(TabButton)
{
m_Page = NULL;
m_Control = NULL;
SetPadding(Padding(2, 2, 2, 2));
DragAndDrop_SetPackage(true, "TabButtonMove");
SetAlignment(Pos::Top | Pos::Left);
SetTextPadding(Padding(5, 3, 3, 3));
}
void TabButton::Render(Skin::Base* skin)
{
skin->DrawTabButton(this, m_Page && m_Page->Visible());
}
void TabButton::SetTabControl(TabControl* ctrl)
{
if (m_Control == ctrl) return;
if (m_Control)
{
m_Control->OnLoseTab(this);
}
m_Control = ctrl;
}
bool TabButton::DragAndDrop_ShouldStartDrag()
{
return m_Control->DoesAllowDrag();
}
bool TabButton::OnKeyUp(bool bDown)
{
OnKeyLeft(bDown);
return true;
}
bool TabButton::OnKeyDown(bool bDown)
{
OnKeyRight(bDown);
return true;
}
bool TabButton::OnKeyLeft(bool bDown)
{
if (bDown)
{
Base::List::reverse_iterator it = std::find(m_Parent->Children.rbegin(), m_Parent->Children.rend(), this);
if (it != m_Parent->Children.rend() && (++it != m_Parent->Children.rend()))
{
Base* pNextTab = *it;
GetTabControl()->OnTabPressed(pNextTab);
Gwen::KeyboardFocus = pNextTab;
}
}
return true;
}
bool TabButton::OnKeyRight(bool bDown)
{
if (bDown)
{
Base::List::iterator it = std::find(m_Parent->Children.begin(), m_Parent->Children.end(), this);
if (it != m_Parent->Children.end() && (++it != m_Parent->Children.end()))
{
Base* pNextTab = *it;
GetTabControl()->OnTabPressed(pNextTab);
Gwen::KeyboardFocus = pNextTab;
}
}
return true;
}
|
// Author(s): Thomas Walter
// $Date$
// $Rev$
// $URL$
#ifndef MORPHO_BASIC_HXX_
#define MORPHO_BASIC_HXX_
#include "morpho_utilities.hxx"
namespace vigra{
namespace morpho{
template<class Iterator1, class Accessor1, class Iterator2, class Accessor2, class SElement, class Functor>
void morphoBasicSEOperation( Iterator1 srcUpperLeft, Iterator1 srcLowerRight, Accessor1 srca,
Iterator2 destUpperLeft, Accessor2 desta,
SElement & se,
Functor f) {
typename Accessor1::value_type neutralElement = f.neutralValue;
typename Accessor1::value_type localMax;
// border treatment
// offsets correspond to the maximal extension of the SE.
Diff2D minOffset = se.minOffset();
Diff2D maxOffset = se.maxOffset();
const Iterator1 upperLeftCorner = srcUpperLeft;
const Iterator1 lowerRightCorner = srcLowerRight;
const Iterator1 upperLeftCritical = srcUpperLeft - minOffset;
const Iterator1 lowerRightCritical = srcLowerRight - maxOffset;
for(; srcUpperLeft.y < upperLeftCritical.y; ++srcUpperLeft.y, ++destUpperLeft.y)
{
Iterator1 scurrent = srcUpperLeft;
Iterator2 dcurrent = destUpperLeft;
for(; scurrent.x < srcLowerRight.x; ++scurrent.x, ++dcurrent.x)
{
localMax = neutralElement;
for(typename SElement::ITERATORTYPE iter = se.begin();
iter != se.end();
++iter)
{
if( ( (scurrent + *iter).y >= upperLeftCorner.y)
&& ( (scurrent + *iter).x >= upperLeftCorner.x)
&& ( (scurrent + *iter).x < lowerRightCorner.x))
localMax = f(localMax, srca(scurrent + *iter));
}
desta.set(localMax, dcurrent);
} // end of x loop
} // end for the first y-loop.
for(; srcUpperLeft.y < lowerRightCritical.y; ++srcUpperLeft.y, ++destUpperLeft.y)
{
Iterator1 scurrent = srcUpperLeft;
Iterator2 dcurrent = destUpperLeft;
// x-loop: the left side
for(; scurrent.x < upperLeftCritical.x; ++scurrent.x, ++dcurrent.x)
{
localMax = neutralElement;
for(typename SElement::ITERATORTYPE iter = se.begin();
iter != se.end();
++iter)
{
if( (scurrent + *iter).x >= upperLeftCorner.x )
localMax = f(localMax, srca(scurrent + *iter));
}
desta.set(localMax, dcurrent);
} // end of x loop (left)
for(; scurrent.x < lowerRightCritical.x; ++scurrent.x, ++dcurrent.x)
{
localMax = neutralElement;
for(typename SElement::ITERATORTYPE iter = se.begin();
iter != se.end();
++iter)
{
localMax = f(localMax, srca(scurrent + *iter));
}
desta.set(localMax, dcurrent);
} // end of the middle x loop
// the right side
for(; scurrent.x < srcLowerRight.x; ++scurrent.x, ++dcurrent.x)
{
localMax = neutralElement;
for(typename SElement::ITERATORTYPE iter = se.begin();
iter != se.end();
++iter)
{
if( (scurrent + *iter).x < lowerRightCorner.x)
localMax = f(localMax, srca(scurrent + *iter));
}
desta.set(localMax, dcurrent);
} // end of the right x loop
} // end of y loop (middle)
// y-loop: lower
for(; srcUpperLeft.y < srcLowerRight.y; ++srcUpperLeft.y, ++destUpperLeft.y)
{
Iterator1 scurrent = srcUpperLeft;
Iterator2 dcurrent = destUpperLeft;
for(; scurrent.x < srcLowerRight.x; ++scurrent.x, ++dcurrent.x)
{
localMax = neutralElement;
for(typename SElement::ITERATORTYPE iter = se.begin();
iter != se.end();
++iter)
{
if( ( (scurrent + *iter).y < lowerRightCorner.y)
&& ( (scurrent + *iter).x < lowerRightCorner.x)
&& ( (scurrent + *iter).x >= upperLeftCorner.x) )
localMax = f(localMax, srca(scurrent + *iter));
}
desta.set(localMax, dcurrent);
} // end of x loop
} // end for the lower y-loop.
} // end of morphoBasicSEOperation
/////////////////////////////////////////////////////////////////////////
// EROSION AND DILATION
/////////////////////////////////////////////////////////////////////////
// Morphological dilation
template<class Iterator1, class Accessor1, class Iterator2, class Accessor2, class SElement>
void morphoDilation(vigra::triple<Iterator1, Iterator1, Accessor1> src,
vigra::triple<Iterator2, Iterator2, Accessor2> dest,
SElement se)
{
vigra::BasicImage<typename Accessor2::value_type> temp(dest.second - dest.first);
if(se.size > 0)
morphoBasicSEOperation(src.first, src.second, src.third,
dest.first, dest.third,
se,
MaxFunctor<typename Accessor1::value_type>());
// a morphological dilation with se of size n
// corresponds to n morphological dilations with size 1.
for(int i = 1; i < se.size; i++)
{
if(i%2 == 0)
morphoBasicSEOperation(temp.upperLeft(), temp.lowerRight(), temp.accessor(),
dest.first, dest.third,
se,
MaxFunctor<typename Accessor1::value_type>());
else
morphoBasicSEOperation(dest.first, dest.second, dest.third,
temp.upperLeft(), temp.accessor(),
se,
MaxFunctor<typename Accessor1::value_type>());
}
if(se.size%2 == 0)
vigra::copyImage(temp.upperLeft(), temp.lowerRight(), temp.accessor(),
dest.first, dest.third);
} // end of dilation
// Morphological erosion
template<class Iterator1, class Accessor1, class Iterator2, class Accessor2,class SElement>
void morphoErosion(vigra::triple<Iterator1, Iterator1, Accessor1> src,
vigra::triple<Iterator2, Iterator2, Accessor2> dest,
SElement se)
{
vigra::BasicImage<typename Accessor2::value_type> temp(dest.second - dest.first);
if(se.size > 0)
morphoBasicSEOperation(src.first, src.second, src.third,
dest.first, dest.third,
se,
MinFunctor<typename Accessor1::value_type>());
// a morphological erosion with se of size n
// corresponds to n morphological erosions with size 1.
for(int i = 1; i < se.size; i++)
{
if(i%2 == 0)
morphoBasicSEOperation(temp.upperLeft(), temp.lowerRight(), temp.accessor(),
dest.first, dest.third,
se,
MinFunctor<typename Accessor1::value_type>());
else
morphoBasicSEOperation(dest.first, dest.second, dest.third,
temp.upperLeft(), temp.accessor(),
se,
MinFunctor<typename Accessor1::value_type>());
}
if(se.size%2 == 0)
vigra::copyImage(temp.upperLeft(), temp.lowerRight(), temp.accessor(),
dest.first, dest.third);
} // end of erosion
/////////////////////////////////////////////////////////////////////////
// OPENING AND CLOSING
/////////////////////////////////////////////////////////////////////////
// Morphological opening
template<class Iterator1, class Accessor1,
class Iterator2, class Accessor2,
class SElement>
void morphoOpening(vigra::triple<Iterator1, Iterator1, Accessor1> src,
vigra::triple<Iterator2, Iterator2, Accessor2> dest, SElement se)
{
vigra::BasicImage<typename Accessor1::value_type> temp(src.second - src.first);
morphoErosion(src, vigra::destImageRange(temp), se);
se.transpose();
morphoDilation(vigra::srcImageRange(temp), dest, se);
se.transpose();
} // end of opening
// Morphological closing
template<class Iterator1, class Accessor1,
class Iterator2, class Accessor2,
class SElement>
void morphoClosing(vigra::triple<Iterator1, Iterator1, Accessor1> src,
vigra::triple<Iterator2, Iterator2, Accessor2> dest, SElement se)
{
vigra::BasicImage<typename Accessor1::value_type> temp(src.second - src.first);
morphoDilation(src, vigra::destImageRange(temp), se);
se.transpose();
morphoErosion(vigra::srcImageRange(temp), dest, se);
se.transpose();
} // end of closing
// Morphological gradient
template<class Iterator1, class Accessor1,
class Iterator2, class Accessor2,
class SElement>
void morphoGradient(vigra::triple<Iterator1, Iterator1, Accessor1> src,
vigra::triple<Iterator2, Iterator2, Accessor2> dest,
SElement se,
typename Accessor2::value_type markerVal = 255)
{
typedef typename Accessor1::value_type INTYPE;
typedef typename Accessor2::value_type OUTTYPE;
vigra::BasicImage<INTYPE> dil(src.second - src.first);
vigra::BasicImage<INTYPE> ero(src.second - src.first);
morphoDilation(src, vigra::destImageRange(dil), se);
morphoErosion(src, vigra::destImageRange(ero), se);
vigra::combineTwoImages(srcImageRange(dil), srcImage(ero),
destIter(dest.first, dest.third),
std::minus<INTYPE>() );
} // end of morphogradient
// External gradient
template<class Iterator1, class Accessor1,
class Iterator2, class Accessor2,
class SElement>
void morphoExternalGradient(vigra::triple<Iterator1, Iterator1, Accessor1> src,
vigra::triple<Iterator2, Iterator2, Accessor2> dest,
SElement se,
typename Accessor2::value_type markerVal = 255)
{
typedef typename Accessor1::value_type INTYPE;
typedef typename Accessor2::value_type OUTTYPE;
vigra::BasicImage<INTYPE> dil(src.second - src.first);
morphoDilation(src, vigra::destImageRange(dil), se);
vigra::combineTwoImages(srcImageRange(dil),
srcIter(src.first, src.third),
destIter(dest.first, dest.third),
std::minus<INTYPE>() );
}
// Internal gradient
template<class Iterator1, class Accessor1,
class Iterator2, class Accessor2,
class SElement>
void morphoInternalGradient(vigra::triple<Iterator1, Iterator1, Accessor1> src,
vigra::triple<Iterator2, Iterator2, Accessor2> dest,
SElement se,
typename Accessor2::value_type markerVal = 255)
{
typedef typename Accessor1::value_type INTYPE;
typedef typename Accessor2::value_type OUTTYPE;
vigra::BasicImage<INTYPE> ero(src.second - src.first);
morphoErosion(src, vigra::destImageRange(ero), se);
vigra::combineTwoImages(srcIterRange(src.first, src.second, src.third),
srcImage(ero),
destIter(dest.first, dest.third),
std::minus<INTYPE>() );
}
template<class Image1, class Image2, class SElement>
void morphoInternalGradient(const Image1 & imin, Image2 & imout, SElement se)
{
morphoInternalGradient(srcImageRange(imin), destImageRange(imout), se);
}
template<class Image1, class Image2, class SElement>
void morphoExternalGradient(const Image1 & imin, Image2 & imout, SElement se)
{
morphoExternalGradient(srcImageRange(imin), destImageRange(imout), se);
}
template<class Image1, class Image2, class SElement>
void morphoGradient(const Image1 & imin, Image2 & imout, SElement se)
{
morphoGradient(srcImageRange(imin), destImageRange(imout), se);
}
template<class Image1, class Image2, class SElement>
void morphoErosion(const Image1 & imin, Image2 & imout, SElement se)
{
morphoErosion(srcImageRange(imin), destImageRange(imout), se);
}
template<class Image1, class Image2, class SElement>
void morphoDilation(const Image1 & imin, Image2 & imout, SElement se)
{
morphoDilation(srcImageRange(imin), destImageRange(imout), se);
}
// Open and close
template<class Image1, class Image2, class SElement>
void morphoOpening(const Image1 & imin, Image2 & imout, SElement se)
{
morphoOpening(srcImageRange(imin), destImageRange(imout), se);
}
template<class Image1, class Image2, class SElement>
void morphoClosing(const Image1 & imin, Image2 & imout, SElement se)
{
morphoClosing(srcImageRange(imin), destImageRange(imout), se);
}
}; /* end of namespace morpho */
}; /* end of namespace vigra */
#endif /*BASIC_MORPHO_HXX_*/
|
#include <asset.hpp>
#include <componentlibrary.hpp>
#include "modules/upstage-module.h"
#include "upstage-widget.h"
namespace rack_plugin_DHE_Modules {
struct UpstageButtonDark : rack::SVGSwitch, rack::MomentarySwitch {
UpstageButtonDark() {
addFrame(rack::SVG::load(rack::assetPlugin(plugin, "res/upstage/button-dark-off.svg")));
addFrame(rack::SVG::load(rack::assetPlugin(plugin, "res/upstage/button-dark-on.svg")));
}
};
struct UpstageKnobLarge : rack::RoundKnob {
UpstageKnobLarge() {
setSVG(rack::SVG::load(rack::assetPlugin(plugin, "res/upstage/knob-large.svg")));
shadow->opacity = 0.f;
}
};
struct UpstagePort : rack::SVGPort {
UpstagePort() {
background->svg = rack::SVG::load(assetPlugin(plugin, "res/upstage/port.svg"));
background->wrap();
box.size = background->box.size;
}
};
struct UpstageSwitch2 : rack::SVGSwitch, rack::ToggleSwitch {
UpstageSwitch2() {
addFrame(rack::SVG::load(rack::assetPlugin(plugin, "res/upstage/switch-2-low.svg")));
addFrame(rack::SVG::load(rack::assetPlugin(plugin, "res/upstage/switch-2-high.svg")));
}
};
UpstageWidget::UpstageWidget(rack::Module *module) : ModuleWidget(module, 5, "res/upstage/panel.svg") {
auto widget_right_edge = width();
auto left_x = width()/4.f + 0.333333333f;
auto center_x = widget_right_edge/2.f;
auto right_x = widget_right_edge - left_x;
auto top_row_y = 25.f;
auto row_spacing = 18.5f;
auto row = 0;
install_knob<UpstageKnobLarge>(UpstageModule::LEVEL_KNOB, {center_x, top_row_y + row*row_spacing});
row++;
install_input<UpstagePort>(UpstageModule::LEVEL_CV, {left_x, top_row_y + row*row_spacing});
install_switch<UpstageSwitch2>(UpstageModule::LEVEL_SWITCH, {right_x, top_row_y + row*row_spacing}, 1, 1);
row++;
install_switch<UpstageButtonDark>(UpstageModule::WAIT_BUTTON, {left_x, top_row_y + row*row_spacing});
install_switch<UpstageButtonDark>(UpstageModule::TRIG_BUTTON, {right_x, top_row_y + row*row_spacing});
top_row_y = 82.f;
row_spacing = 15.f;
row = 0;
install_input<UpstagePort>(UpstageModule::WAIT_IN, {left_x, top_row_y + row*row_spacing});
row++;
install_input<UpstagePort>(UpstageModule::TRIG_IN, {left_x, top_row_y + row*row_spacing});
install_output<UpstagePort>(UpstageModule::TRIG_OUT, {right_x, top_row_y + row*row_spacing});
row++;
install_output<UpstagePort>(UpstageModule::ENVELOPE_OUT, {right_x, top_row_y + row*row_spacing});
}
} // namespace rack_plugin_DHE_Modules
using namespace rack_plugin_DHE_Modules;
RACK_PLUGIN_MODEL_INIT(DHE_Modules, Upstage) {
Model *modelUpstage = rack_plugin_DHE_Modules::createModel<rack_plugin_DHE_Modules::UpstageModule, rack_plugin_DHE_Modules::UpstageWidget, rack::ModelTag>("Upstage", rack::ENVELOPE_GENERATOR_TAG);
return modelUpstage;
}
|
#include <assert.h>
#include <algorithm>
#include <cinttypes>
#include <cstdarg>
#include <iomanip>
#include <sstream>
#include <string>
#include "deps/rang/include/rang.hpp"
#include "llv8-inl.h"
#include "llv8.h"
#include "src/settings.h"
namespace llnode {
namespace v8 {
using lldb::addr_t;
using lldb::SBError;
using lldb::SBTarget;
static std::string kConstantPrefix = "v8dbg_";
void LLV8::Load(SBTarget target) {
// Reload process anyway
process_ = target.GetProcess();
// No need to reload
if (target_ == target) return;
target_ = target;
common.Assign(target);
smi.Assign(target, &common);
heap_obj.Assign(target, &common);
map.Assign(target, &common);
js_object.Assign(target, &common);
heap_number.Assign(target, &common);
js_array.Assign(target, &common);
js_function.Assign(target, &common);
shared_info.Assign(target, &common);
uncompiled_data.Assign(target, &common);
code.Assign(target, &common);
scope_info.Assign(target, &common);
context.Assign(target, &common);
script.Assign(target, &common);
string.Assign(target, &common);
one_byte_string.Assign(target, &common);
two_byte_string.Assign(target, &common);
cons_string.Assign(target, &common);
sliced_string.Assign(target, &common);
thin_string.Assign(target, &common);
fixed_array_base.Assign(target, &common);
fixed_array.Assign(target, &common);
fixed_typed_array_base.Assign(target, &common);
js_typed_array.Assign(target, &common);
oddball.Assign(target, &common);
js_array_buffer.Assign(target, &common);
js_array_buffer_view.Assign(target, &common);
js_regexp.Assign(target, &common);
js_date.Assign(target, &common);
descriptor_array.Assign(target, &common);
name_dictionary.Assign(target, &common);
frame.Assign(target, &common);
symbol.Assign(target, &common);
types.Assign(target, &common);
}
int64_t LLV8::LoadPtr(int64_t addr, Error& err) {
SBError sberr;
int64_t value =
process_.ReadPointerFromMemory(static_cast<addr_t>(addr), sberr);
if (sberr.Fail()) {
// TODO(joyeecheung): use Error::Failure() to report information when
// there is less noise from here.
err = Error(true, "Failed to load pointer from v8 memory");
return -1;
}
err = Error::Ok();
return value;
}
int64_t LLV8::LoadUnsigned(int64_t addr, uint32_t byte_size, Error& err) {
SBError sberr;
int64_t value = process_.ReadUnsignedFromMemory(static_cast<addr_t>(addr),
byte_size, sberr);
if (sberr.Fail()) {
// TODO(joyeecheung): use Error::Failure() to report information when
// there is less noise from here.
err = Error(true, "Failed to load unsigned from v8 memory");
return -1;
}
err = Error::Ok();
return value;
}
double LLV8::LoadDouble(int64_t addr, Error& err) {
SBError sberr;
int64_t value = process_.ReadUnsignedFromMemory(static_cast<addr_t>(addr),
sizeof(double), sberr);
if (sberr.Fail()) {
err = Error::Failure(
"Failed to load double from v8 memory, "
"addr=0x%016" PRIx64,
addr);
return -1.0;
}
err = Error::Ok();
// dereferencing type-punned pointer will break strict-aliasing rules
// return *reinterpret_cast<double*>(&value);
double dvalue;
std::memcpy(&dvalue, &value, sizeof(double));
return dvalue;
}
std::string LLV8::LoadBytes(int64_t addr, int64_t length, Error& err) {
uint8_t* buf = new uint8_t[length + 1];
SBError sberr;
process_.ReadMemory(addr, buf, static_cast<size_t>(length), sberr);
if (sberr.Fail()) {
err = Error::Failure(
"Failed to load v8 backing store memory, "
"addr=0x%016" PRIx64 ", length=%" PRId64,
addr, length);
delete[] buf;
return std::string();
}
std::string res;
char tmp[10];
for (int i = 0; i < length; ++i) {
snprintf(tmp, sizeof(tmp), "%s%02x", (i == 0 ? "" : ", "), buf[i]);
res += tmp;
}
delete[] buf;
return res;
}
std::string LLV8::LoadString(int64_t addr, int64_t length, Error& err) {
if (length < 0) {
err = Error::Failure("Failed to load V8 one byte string - Invalid length");
return std::string();
}
char* buf = new char[length + 1];
SBError sberr;
process_.ReadMemory(static_cast<addr_t>(addr), buf,
static_cast<size_t>(length), sberr);
if (sberr.Fail()) {
err = Error::Failure(
"Failed to load v8 one byte string memory, "
"addr=0x%016" PRIx64 ", length=%" PRId64,
addr, length);
delete[] buf;
return std::string();
}
buf[length] = '\0';
std::string res = buf;
delete[] buf;
err = Error::Ok();
return res;
}
std::string LLV8::LoadTwoByteString(int64_t addr, int64_t length, Error& err) {
if (length < 0) {
err = Error::Failure("Failed to load V8 two byte string - Invalid length");
return std::string();
}
char* buf = new char[length * 2 + 1];
SBError sberr;
process_.ReadMemory(static_cast<addr_t>(addr), buf,
static_cast<size_t>(length * 2), sberr);
if (sberr.Fail()) {
err = Error::Failure(
"Failed to load V8 two byte string memory, "
"addr=0x%016" PRIx64 ", length=%" PRId64,
addr, length);
delete[] buf;
return std::string();
}
for (int64_t i = 0; i < length; i++) buf[i] = buf[i * 2];
buf[length] = '\0';
std::string res = buf;
delete[] buf;
err = Error::Ok();
return res;
}
uint8_t* LLV8::LoadChunk(int64_t addr, int64_t length, Error& err) {
uint8_t* buf = new uint8_t[length];
SBError sberr;
process_.ReadMemory(static_cast<addr_t>(addr), buf,
static_cast<size_t>(length), sberr);
if (sberr.Fail()) {
err = Error::Failure(
"Failed to load V8 chunk memory, "
"addr=0x%016" PRIx64 ", length=%" PRId64,
addr, length);
delete[] buf;
return nullptr;
}
err = Error::Ok();
return buf;
}
// reset_line - make line_start absolute vs start of function
// otherwise relative to last end
// returns line cursor
uint32_t JSFrame::GetSourceForDisplay(bool reset_line, uint32_t line_start,
uint32_t line_limit, std::string lines[],
uint32_t& lines_found, Error& err) {
v8::JSFunction fn = GetFunction(err);
if (err.Fail()) {
return line_start;
}
v8::SharedFunctionInfo info = fn.Info(err);
if (err.Fail()) {
return line_start;
}
v8::Script script = info.GetScript(err);
if (err.Fail()) {
return line_start;
}
// Check if this is being run multiple times against the same frame
// if not, reset last line
if (reset_line) {
uint32_t pos = info.StartPosition(err);
if (err.Fail()) {
return line_start;
}
int64_t tmp_line;
int64_t tmp_col;
script.GetLineColumnFromPos(pos, tmp_line, tmp_col, err);
if (err.Fail()) {
return line_start;
}
line_start += tmp_line;
}
script.GetLines(line_start, lines, line_limit, lines_found, err);
if (err.Fail()) {
const char* msg = err.GetMessage();
if (msg == nullptr) {
err = Error::Failure("Failed to get Function Source");
}
return line_start;
}
return line_start + lines_found;
}
// On 64 bits systems, V8 stores SMIs (small ints) in the top 32 bits of
// a 64 bits word. Frame markers used to obey this convention but as of
// V8 5.8, they are stored as 32 bits SMIs with the top half set to zero.
// Shift the raw value up to make it a normal SMI again.
Smi JSFrame::FromFrameMarker(Value value) const {
if (v8()->smi()->kShiftSize == 31 && Smi(value).Check() &&
value.raw() < 1LL << 31) {
value = Value(v8(), value.raw() << 31);
}
return Smi(value);
}
bool JSFrame::MightBeV8Frame(lldb::SBFrame& frame) {
// TODO(mmarchini): There might be a better way to check for V8 builtins
// embedded in the binary.
auto c_function_name = frame.GetFunctionName();
std::string function_name(c_function_name != nullptr ? c_function_name : "");
return !frame.GetSymbol().IsValid() || function_name.find("Builtins_") == 0;
}
std::string JSFunction::GetDebugLine(std::string args, Error& err) {
RETURN_IF_THIS_INVALID(std::string());
// TODO(mmarchini) turn this into CheckedType
std::string res = Name(err);
if (err.Fail()) return std::string();
if (!args.empty()) res += "(" + args + ")";
res += " at ";
res += Info(err).GetPostfix(err);
if (err.Fail()) return std::string();
return res;
}
std::string JSFunction::GetSource(Error& err) {
v8::SharedFunctionInfo info = Info(err);
if (err.Fail()) {
return std::string();
}
v8::Script script = info.GetScript(err);
if (err.Fail()) {
return std::string();
}
// There is no `Script` for functions created in C++ (and possibly others)
int64_t type = script.GetType(err);
if (err.Fail()) {
return std::string();
}
if (type != v8()->types()->kScriptType) {
return std::string();
}
HeapObject source = script.Source(err);
if (err.Fail()) return std::string();
int64_t source_type = source.GetType(err);
if (err.Fail()) return std::string();
// No source
if (source_type > v8()->types()->kFirstNonstringType) {
err = Error::Failure("No source, source_type=%" PRId64, source_type);
return std::string();
}
String str(source);
std::string source_str = str.ToString(err);
int64_t start_pos = info.StartPosition(err);
if (err.Fail()) {
return std::string();
}
int64_t end_pos = info.EndPosition(err);
if (err.Fail()) {
return std::string();
}
int64_t source_len = source_str.length();
if (end_pos > source_len) {
end_pos = source_len;
}
int64_t len = end_pos - start_pos;
std::string res = source_str.substr(start_pos, len);
return res;
}
std::string SharedFunctionInfo::ProperName(Error& err) {
RETURN_IF_THIS_INVALID(std::string());
String name = Name(err);
if (err.Fail()) return std::string();
std::string res = name.ToString(err);
if (err.Fail() || res.empty()) {
Value inferred = GetInferredName(err);
if (err.Fail() || !inferred.Check()) return std::string();
// Function may not have inferred name
if (!inferred.IsHoleOrUndefined(err) && !err.Fail())
res = inferred.ToString(err);
if (err.Fail()) return std::string();
}
if (res.empty()) res = "(anonymous)";
return res;
}
std::string SharedFunctionInfo::GetPostfix(Error& err) {
RETURN_IF_THIS_INVALID(std::string());
Script script = GetScript(err);
if (err.Fail() || !script.Check()) return std::string();
// There is no `Script` for functions created in C++ (and possibly others)
int64_t type = script.GetType(err);
if (err.Fail() || type != v8()->types()->kScriptType)
return std::string("(no script)");
String name = script.Name(err);
if (err.Fail()) return std::string();
int64_t start_pos = StartPosition(err);
if (err.Fail()) return std::string();
std::string res = name.ToString(err);
if (res.empty()) res = "(no script)";
int64_t line = 0;
int64_t column = 0;
script.GetLineColumnFromPos(start_pos, line, column, err);
if (err.Fail()) return std::string();
// NOTE: lines start from 1 in most of editors
char tmp[128];
snprintf(tmp, sizeof(tmp), ":%d:%d", static_cast<int>(line + 1),
static_cast<int>(column));
return res + tmp;
}
std::string SharedFunctionInfo::ToString(Error& err) {
std::string res = ProperName(err);
if (err.Fail()) return std::string();
return res + " at " + GetPostfix(err);
}
// return end_char+1, which may be less than line_limit if source
// ends before end_inclusive
void Script::GetLines(uint64_t start_line, std::string lines[],
uint64_t line_limit, uint32_t& lines_found, Error& err) {
lines_found = 0;
HeapObject source = Source(err);
if (err.Fail()) return;
int64_t type = source.GetType(err);
if (err.Fail()) return;
// No source
if (type > v8()->types()->kFirstNonstringType) {
err = Error::Failure("No source, source_type=%" PRId64, type);
return;
}
String str(source);
std::string source_str = str.ToString(err);
uint64_t limit = source_str.length();
uint64_t length = 0;
uint64_t line_i = 0;
uint64_t i = 0;
for (; i < limit && lines_found < line_limit; i++) {
// \r\n should ski adding a line and column on \r
if (source_str[i] == '\r' && i < limit - 1 && source_str[i + 1] == '\n') {
i++;
}
if (source_str[i] == '\n' || source_str[i] == '\r') {
if (line_i >= start_line) {
lines[lines_found] = std::string(source_str, i - length, length);
lines_found++;
}
line_i++;
length = 0;
} else {
length++;
}
}
if (line_i >= start_line && length != 0 && lines_found < line_limit) {
lines[lines_found] = std::string(source_str, limit - length, length);
lines_found++;
}
}
void Script::GetLineColumnFromPos(int64_t pos, int64_t& line, int64_t& column,
Error& err) {
line = 0;
column = 0;
HeapObject source = Source(err);
if (err.Fail()) return;
int64_t type = source.GetType(err);
if (err.Fail()) return;
// No source
if (type > v8()->types()->kFirstNonstringType) {
err = Error(true, "No source");
return;
}
String str(source);
std::string source_str = str.ToString(err);
int64_t limit = source_str.length();
if (limit > pos) limit = pos;
for (int64_t i = 0; i < limit; i++, column++) {
// \r\n should ski adding a line and column on \r
if (source_str[i] == '\r' && i < limit - 1 && source_str[i + 1] == '\n') {
i++;
}
if (source_str[i] == '\n' || source_str[i] == '\r') {
column = 0;
line++;
}
}
}
bool Value::IsHoleOrUndefined(Error& err) {
HeapObject obj(this);
if (!obj.Check()) return false;
int64_t type = obj.GetType(err);
if (err.Fail()) return false;
if (type != v8()->types()->kOddballType) return false;
Oddball odd(this);
return odd.IsHoleOrUndefined(err);
}
// TODO(indutny): deduplicate this?
bool Value::IsHole(Error& err) {
HeapObject obj(this);
if (!obj.Check()) return false;
int64_t type = obj.GetType(err);
if (err.Fail()) return false;
if (type != v8()->types()->kOddballType) return false;
Oddball odd(this);
return odd.IsHole(err);
}
std::string Value::GetTypeName(Error& err) {
Smi smi(this);
if (smi.Check()) return "(Smi)";
HeapObject obj(this);
if (!obj.Check()) {
err = Error::Failure("Not object and not smi");
return std::string();
}
return obj.GetTypeName(err);
}
std::string Value::ToString(Error& err) {
RETURN_IF_THIS_INVALID(std::string());
Smi smi(this);
if (smi.Check()) return smi.ToString(err);
HeapObject obj(this);
if (!obj.Check()) {
err = Error::Failure("Not object and not smi");
return std::string();
}
return obj.ToString(err);
}
std::string HeapObject::ToString(Error& err) {
int64_t type = GetType(err);
if (err.Fail()) return std::string();
if (type == v8()->types()->kHeapNumberType) {
HeapNumber n(this);
return n.ToString(false, err);
}
if (type < v8()->types()->kFirstNonstringType) {
String str(this);
return str.ToString(err);
}
if (type == v8()->types()->kSymbolType) {
Symbol symbol(this);
return symbol.ToString(err);
}
return "<non-string>";
}
std::string Smi::ToString(Error& err) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", static_cast<int>(GetValue()));
err = Error::Ok();
return buf;
}
/* Utility function to generate short type names for objects.
*/
std::string HeapObject::GetTypeName(Error& err) {
int64_t type = GetType(err);
if (type == v8()->types()->kGlobalObjectType) return "(Global)";
if (type == v8()->types()->kGlobalProxyType) return "(Global proxy)";
if (type == v8()->types()->kCodeType) return "(Code)";
if (type == v8()->types()->kMapType) {
return "(Map)";
}
if (type >= v8()->types()->kFirstContextType &&
type <= v8()->types()->kLastContextType) {
return "Context";
}
if (JSObject::IsObjectType(v8(), type)) {
v8::HeapObject map_obj = GetMap(err);
if (err.Fail()) {
return std::string();
}
v8::Map map(map_obj);
v8::HeapObject constructor_obj = map.Constructor(err);
if (err.Fail()) {
return std::string();
}
int64_t constructor_type = constructor_obj.GetType(err);
if (err.Fail()) {
return std::string();
}
if (constructor_type != v8()->types()->kJSFunctionType) {
return "(Object)";
}
v8::JSFunction constructor(constructor_obj);
return constructor.Name(err);
}
if (type == v8()->types()->kHeapNumberType) {
return "(HeapNumber)";
}
if (type == v8()->types()->kJSArrayType) {
return "(Array)";
}
if (type == v8()->types()->kOddballType) {
return "(Oddball)";
}
if (type == v8()->types()->kJSFunctionType) {
return "(Function)";
}
if (type == v8()->types()->kJSRegExpType) {
return "(RegExp)";
}
if (type < v8()->types()->kFirstNonstringType) {
return "(String)";
}
if (type == v8()->types()->kFixedArrayType) {
return "(FixedArray)";
}
if (type == v8()->types()->kJSArrayBufferType) {
return "(ArrayBuffer)";
}
if (type == v8()->types()->kJSTypedArrayType) {
return "(ArrayBufferView)";
}
if (type == v8()->types()->kJSDateType) {
return "(Date)";
}
std::string unknown("unknown: ");
return unknown + std::to_string(type);
}
std::string HeapNumber::ToString(bool whole, Error& err) {
char buf[128];
const char* fmt = whole ? "%f" : "%.2f";
snprintf(buf, sizeof(buf), fmt, GetValue(err));
err = Error::Ok();
return buf;
}
std::string JSDate::ToString(Error& err) {
v8::Value val(GetValue(err));
// Check if it is SMI
// e.g: date = new Date(1)
v8::Smi smi(val);
if (smi.Check()) {
std::string s = smi.ToString(err);
if (err.Fail()) return "";
return s;
}
// Check if it is HeapNumber
// e.g: date = new Date()
v8::HeapNumber hn(val);
if (hn.Check()) {
std::string s = hn.ToString(true, err);
if (err.Fail()) return "";
return s;
}
PRINT_DEBUG("JSDate is not a Smi neither a HeapNumber");
return "";
}
std::string Symbol::ToString(Error& err) {
if (!String::IsString(v8(), Name(err), err)) {
return "Symbol()";
}
HeapObject name = Name(err);
RETURN_IF_INVALID(name, "Symbol(???)");
return "Symbol('" + String(name).ToString(err) + "')";
}
std::string String::ToString(Error& err) {
CheckedType<int64_t> repr = Representation(err);
RETURN_IF_INVALID(repr, std::string());
int64_t encoding = Encoding(err);
if (err.Fail()) return std::string();
if (*repr == v8()->string()->kSeqStringTag) {
if (encoding == v8()->string()->kOneByteStringTag) {
OneByteString one(this);
return one.ToString(err);
} else if (encoding == v8()->string()->kTwoByteStringTag) {
TwoByteString two(this);
return two.ToString(err);
}
err = Error::Failure("Unsupported seq string encoding %" PRId64, encoding);
return std::string();
}
if (*repr == v8()->string()->kConsStringTag) {
ConsString cons(this);
return cons.ToString(err);
}
if (*repr == v8()->string()->kSlicedStringTag) {
SlicedString sliced(this);
return sliced.ToString(err);
}
// TODO(indutny): add support for external strings
if (*repr == v8()->string()->kExternalStringTag) {
return std::string("(external)");
}
if (*repr == v8()->string()->kThinStringTag) {
ThinString thin(this);
return thin.ToString(err);
}
err = Error::Failure("Unsupported string representation %" PRId64, *repr);
return std::string();
}
// Context locals iterator implementations
Context::Locals::Locals(Context* context, Error& err) {
context_ = context;
HeapObject scope_obj = context_->GetScopeInfo(err);
if (err.Fail()) return;
scope_info_ = ScopeInfo(scope_obj);
Smi local_count_smi = scope_info_.ContextLocalCount(err);
if (err.Fail()) return;
local_count_ = local_count_smi.GetValue();
}
Context::Locals::Iterator Context::Locals::begin() { return Iterator(0, this); }
Context::Locals::Iterator Context::Locals::end() {
return Iterator(local_count_, this);
}
const Context::Locals::Iterator Context::Locals::Iterator::operator++(int) {
current_++;
return Iterator(current_, this->outer_);
}
bool Context::Locals::Iterator::operator!=(Context::Locals::Iterator that) {
return current_ != that.current_ || outer_->context_ != that.outer_->context_;
}
v8::Value Context::Locals::Iterator::operator*() {
Error err;
return outer_->context_->ContextSlot(current_, err);
}
String Context::Locals::Iterator::LocalName(Error& err) {
return outer_->scope_info_.ContextLocalName(current_, err);
}
Value Context::Locals::Iterator::GetValue(Error& err) {
return outer_->context_->ContextSlot(current_, err);
}
HeapObject Map::Constructor(Error& err) {
Map current = this;
do {
HeapObject obj = current.MaybeConstructor(err);
if (err.Fail()) return current;
int64_t type = obj.GetType(err);
if (err.Fail()) return current;
current = obj;
if (type != v8()->types()->kMapType) break;
} while (true);
return current;
}
/* Returns the set of keys on an object - similar to Object.keys(obj) in
* Javascript. That includes array indices but not special fields like
* "length" on an array.
*/
void JSObject::Keys(std::vector<std::string>& keys, Error& err) {
keys.clear();
// First handle array indices.
ElementKeys(keys, err);
HeapObject map_obj = GetMap(err);
Map map(map_obj);
bool is_dict = map.IsDictionary(err);
if (err.Fail()) return;
if (is_dict) {
DictionaryKeys(keys, err);
} else {
DescriptorKeys(keys, map, err);
}
return;
}
std::vector<std::pair<Value, Value>> JSObject::Entries(Error& err) {
HeapObject map_obj = GetMap(err);
Map map(map_obj);
bool is_dict = map.IsDictionary(err);
if (err.Fail()) return {};
if (is_dict) {
return DictionaryEntries(err);
} else {
return DescriptorEntries(map, err);
}
}
std::vector<std::pair<Value, Value>> JSObject::DictionaryEntries(Error& err) {
HeapObject dictionary_obj = Properties(err);
if (err.Fail()) return {};
NameDictionary dictionary(dictionary_obj);
int64_t length = dictionary.Length(err);
if (err.Fail()) return {};
std::vector<std::pair<Value, Value>> entries;
for (int64_t i = 0; i < length; i++) {
Value key = dictionary.GetKey(i, err);
if (err.Fail()) return entries;
// Skip holes
bool is_hole = key.IsHoleOrUndefined(err);
if (err.Fail()) return entries;
if (is_hole) continue;
Value value = dictionary.GetValue(i, err);
entries.push_back(std::pair<Value, Value>(key, value));
}
return entries;
}
std::vector<std::pair<Value, Value>> JSObject::DescriptorEntries(Map map,
Error& err) {
HeapObject descriptors_obj = map.InstanceDescriptors(err);
RETURN_IF_INVALID(descriptors_obj, {});
DescriptorArray descriptors(descriptors_obj);
int64_t own_descriptors_count = map.NumberOfOwnDescriptors(err);
if (err.Fail()) return {};
int64_t in_object_count = map.InObjectProperties(err);
if (err.Fail()) return {};
int64_t instance_size = map.InstanceSize(err);
if (err.Fail()) return {};
HeapObject extra_properties_obj = Properties(err);
if (err.Fail()) return {};
FixedArray extra_properties(extra_properties_obj);
std::vector<std::pair<Value, Value>> entries;
for (int64_t i = 0; i < own_descriptors_count; i++) {
Smi details = descriptors.GetDetails(i);
if (!details.Check()) {
PRINT_DEBUG("Failed to get details for index %ld", i);
entries.push_back(std::pair<Value, Value>(Value(), Value()));
continue;
}
Value key = descriptors.GetKey(i);
if (!key.Check()) continue;
if (descriptors.IsConstFieldDetails(details) ||
descriptors.IsDescriptorDetails(details)) {
Value value;
value = descriptors.GetValue(i);
if (!value.Check()) continue;
entries.push_back(std::pair<Value, Value>(key, value));
continue;
}
// Skip non-fields for now, Object.keys(obj) does
// not seem to return these (for example the "length"
// field on an array).
if (!descriptors.IsFieldDetails(details)) continue;
if (descriptors.IsDoubleField(details)) continue;
int64_t index = descriptors.FieldIndex(details) - in_object_count;
Value value;
if (index < 0) {
value = GetInObjectValue<Value>(instance_size, index, err);
} else {
value = extra_properties.Get<Value>(index, err);
}
entries.push_back(std::pair<Value, Value>(key, value));
}
return entries;
}
void JSObject::ElementKeys(std::vector<std::string>& keys, Error& err) {
HeapObject elements_obj = Elements(err);
if (err.Fail()) return;
FixedArray elements(elements_obj);
Smi length_smi = elements.Length(err);
if (err.Fail()) return;
int64_t length = length_smi.GetValue();
for (int i = 0; i < length; ++i) {
// Add keys for anything that isn't a hole.
Value value = elements.Get<Value>(i, err);
if (err.Fail()) continue;
;
bool is_hole = value.IsHole(err);
if (err.Fail()) continue;
if (!is_hole) {
keys.push_back(std::to_string(i));
}
}
}
void JSObject::DictionaryKeys(std::vector<std::string>& keys, Error& err) {
HeapObject dictionary_obj = Properties(err);
if (err.Fail()) return;
NameDictionary dictionary(dictionary_obj);
int64_t length = dictionary.Length(err);
if (err.Fail()) return;
for (int64_t i = 0; i < length; i++) {
Value key = dictionary.GetKey(i, err);
if (err.Fail()) return;
// Skip holes
bool is_hole = key.IsHoleOrUndefined(err);
if (err.Fail()) return;
if (is_hole) continue;
std::string key_name = key.ToString(err);
if (err.Fail()) {
// TODO - should I continue onto the next key here instead.
return;
}
keys.push_back(key_name);
}
}
void JSObject::DescriptorKeys(std::vector<std::string>& keys, Map map,
Error& err) {
HeapObject descriptors_obj = map.InstanceDescriptors(err);
RETURN_IF_INVALID(descriptors_obj, );
DescriptorArray descriptors(descriptors_obj);
int64_t own_descriptors_count = map.NumberOfOwnDescriptors(err);
if (err.Fail()) return;
for (int64_t i = 0; i < own_descriptors_count; i++) {
Smi details = descriptors.GetDetails(i);
if (!details.Check()) {
PRINT_DEBUG("Failed to get details for index %ld", i);
keys.push_back("???");
continue;
}
Value key = descriptors.GetKey(i);
RETURN_IF_INVALID(key, );
// Skip non-fields for now, Object.keys(obj) does
// not seem to return these (for example the "length"
// field on an array).
if (!descriptors.IsFieldDetails(details)) {
continue;
}
std::string key_name = key.ToString(err);
if (err.Fail()) {
// TODO - should I continue onto the next key here instead.
return;
}
keys.push_back(key_name);
}
}
/* Return the v8 value for a property stored using the given key.
* (Caller should have some idea of what type of object will be stored
* in that key, they will get a v8::Value back that they can cast.)
*/
Value JSObject::GetProperty(std::string key_name, Error& err) {
HeapObject map_obj = GetMap(err);
if (err.Fail()) Value();
Map map(map_obj);
bool is_dict = map.IsDictionary(err);
if (err.Fail()) return Value();
if (is_dict) {
return GetDictionaryProperty(key_name, err);
} else {
return GetDescriptorProperty(key_name, map, err);
}
if (err.Fail()) return Value();
// Nothing's gone wrong, we just didn't find the key.
return Value();
}
Value JSObject::GetDictionaryProperty(std::string key_name, Error& err) {
HeapObject dictionary_obj = Properties(err);
if (err.Fail()) return Value();
NameDictionary dictionary(dictionary_obj);
int64_t length = dictionary.Length(err);
if (err.Fail()) return Value();
for (int64_t i = 0; i < length; i++) {
Value key = dictionary.GetKey(i, err);
if (err.Fail()) return Value();
// Skip holes
bool is_hole = key.IsHoleOrUndefined(err);
if (err.Fail()) return Value();
if (is_hole) continue;
if (key.ToString(err) == key_name) {
Value value = dictionary.GetValue(i, err);
if (err.Fail()) return Value();
return value;
}
}
return Value();
}
Value JSObject::GetDescriptorProperty(std::string key_name, Map map,
Error& err) {
HeapObject descriptors_obj = map.InstanceDescriptors(err);
RETURN_IF_INVALID(descriptors_obj, Value());
DescriptorArray descriptors(descriptors_obj);
int64_t own_descriptors_count = map.NumberOfOwnDescriptors(err);
if (err.Fail()) return Value();
int64_t in_object_count = map.InObjectProperties(err);
if (err.Fail()) return Value();
int64_t instance_size = map.InstanceSize(err);
if (err.Fail()) return Value();
HeapObject extra_properties_obj = Properties(err);
if (err.Fail()) return Value();
FixedArray extra_properties(extra_properties_obj);
for (int64_t i = 0; i < own_descriptors_count; i++) {
Smi details = descriptors.GetDetails(i);
if (!details.Check()) {
PRINT_DEBUG("Failed to get details for index %ld", i);
continue;
}
Value key = descriptors.GetKey(i);
RETURN_IF_INVALID(key, Value());
if (key.ToString(err) != key_name) {
continue;
}
// Found the right key, get the value.
if (err.Fail()) return Value();
if (descriptors.IsConstFieldDetails(details) ||
descriptors.IsDescriptorDetails(details)) {
Value value;
value = descriptors.GetValue(i);
RETURN_IF_INVALID(value, Value());
continue;
}
// Skip non-fields for now
if (!descriptors.IsFieldDetails(details)) {
// This path would return the length field for an array,
// however Object.keys(arr) doesn't return length as a
// field so neither do we.
continue;
}
int64_t index = descriptors.FieldIndex(details) - in_object_count;
if (descriptors.IsDoubleField(details)) {
double value;
if (index < 0) {
value = GetInObjectValue<double>(instance_size, index, err);
} else {
value = extra_properties.Get<double>(index, err);
}
if (err.Fail()) return Value();
} else {
Value value;
if (index < 0) {
value = GetInObjectValue<Value>(instance_size, index, err);
} else {
value = extra_properties.Get<Value>(index, err);
}
if (err.Fail()) {
return Value();
} else {
return value;
};
}
if (err.Fail()) return Value();
}
return Value();
}
/* An array is also an object so this method is on JSObject
* not JSArray.
*/
int64_t JSObject::GetArrayLength(Error& err) {
HeapObject elements_obj = Elements(err);
if (err.Fail()) return 0;
FixedArray elements(elements_obj);
Smi length_smi = elements.Length(err);
if (err.Fail()) return 0;
int64_t length = length_smi.GetValue();
return length;
}
/* An array is also an object so this method is on JSObject
* not JSArray.
* Note that you the user should know what the expect the array to contain
* and should check they haven't been returned a hole.
*/
v8::Value JSObject::GetArrayElement(int64_t pos, Error& err) {
if (pos < 0) {
// TODO - Set err.Fail()?
return Value();
}
HeapObject elements_obj = Elements(err);
if (err.Fail()) return Value();
FixedArray elements(elements_obj);
Smi length_smi = elements.Length(err);
if (err.Fail()) return Value();
int64_t length = length_smi.GetValue();
if (pos >= length) {
return Value();
}
Value value = elements.Get<v8::Value>(pos, err);
if (err.Fail()) return Value();
return value;
}
bool JSError::HasStackTrace(Error& err) {
StackTrace stack_trace = GetStackTrace(err);
return stack_trace.GetFrameCount() > -1;
}
JSArray JSError::GetFrameArray(Error& err) {
RETURN_IF_THIS_INVALID(JSArray());
v8::Value maybe_stack = GetProperty(stack_trace_property(), err);
if (err.Fail() || !maybe_stack.Check()) {
PRINT_DEBUG("Couldn't find a symbol property in the Error object.");
return JSArray();
}
int64_t type = v8::HeapObject(maybe_stack).GetType(err);
if (err.Fail()) {
PRINT_DEBUG("Symbol property references an invalid object.");
return JSArray();
}
// NOTE (mmarchini): The stack is stored as a JSArray
if (type != v8()->types()->kJSArrayType) {
PRINT_DEBUG("Symbol property doesn't have the right type.");
return JSArray();
}
v8::JSArray arr(maybe_stack);
return arr;
}
StackTrace::Iterator StackTrace::begin() {
Error err;
return StackTrace::Iterator(this, err);
}
StackTrace::Iterator StackTrace::end() {
Error err;
return StackTrace::Iterator(this, GetFrameCount(), err);
}
StackTrace::StackTrace(JSArray frame_array, Error& err)
: frame_array_(frame_array) {
if (!frame_array.Check()) {
PRINT_DEBUG("JS Array is not a valid object");
len_ = -1;
multiplier_ = -1;
return;
}
v8::Value maybe_stack_len = frame_array.GetArrayElement(0, err);
if (err.Fail()) {
PRINT_DEBUG("Couldn't get the first element from the stack array");
return;
}
len_ = v8::Smi(maybe_stack_len).GetValue();
multiplier_ = 5;
// On Node.js v8.x, the first array element is the stack size, and each
// stack frame use 5 elements.
if ((len_ * multiplier_ + 1) != frame_array_.GetArrayLength(err)) {
// On Node.js v6.x, the first array element is zero, and each stack frame
// use 4 element.
multiplier_ = 4;
if ((len_ != 0) ||
((frame_array_.GetArrayLength(err) - 1) % multiplier_ != 0)) {
PRINT_DEBUG(
"JSArray doesn't look like a Stack Frames array. stack_len: %d "
"array_len: %ld",
len_, frame_array_.GetArrayLength(err));
len_ = -1;
multiplier_ = -1;
return;
}
len_ = (frame_array_.GetArrayLength(err) - 1) / multiplier_;
}
}
StackTrace JSError::GetStackTrace(Error& err) {
return StackTrace(GetFrameArray(err), err);
}
StackFrame StackTrace::GetFrame(uint32_t index, Error& err) {
return StackFrame(this, index);
}
StackFrame::StackFrame(StackTrace* stack_trace, int index)
: stack_trace_(stack_trace), index_(index) {}
JSFunction StackFrame::GetFunction(Error& err) {
JSArray frame_array = stack_trace_->frame_array_;
v8::Value maybe_fn = frame_array.GetArrayElement(frame_array_index(), err);
if (err.Fail()) return JSFunction();
return JSFunction(maybe_fn);
}
int StackFrame::frame_array_index() {
int multiplier = stack_trace_->multiplier_;
const int js_function_pos = 1;
const int begin_offset = 1;
return begin_offset + js_function_pos + (index_ * multiplier);
}
} // namespace v8
} // namespace llnode
|
// Copyright 2014 Open Source Robotics Foundation, 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.
#ifndef RCLCPP__EXECUTORS__SINGLE_THREADED_EXECUTOR_HPP_
#define RCLCPP__EXECUTORS__SINGLE_THREADED_EXECUTOR_HPP_
#include <rmw/rmw.h>
#include <cassert>
#include <cstdlib>
#include <memory>
#include <vector>
#include "rclcpp/executor.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/memory_strategies.hpp"
#include "rclcpp/node.hpp"
#include "rclcpp/utilities.hpp"
#include "rclcpp/rate.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
namespace executors
{
namespace single_threaded_executor
{
/// Single-threaded executor implementation
// This is the default executor created by rclcpp::spin.
class SingleThreadedExecutor : public executor::Executor
{
public:
RCLCPP_SMART_PTR_DEFINITIONS(SingleThreadedExecutor)
/// Default constructor. See the default constructor for Executor.
RCLCPP_PUBLIC
SingleThreadedExecutor(
const executor::ExecutorArgs & args = rclcpp::executor::create_default_executor_arguments());
/// Default destrcutor.
RCLCPP_PUBLIC
virtual ~SingleThreadedExecutor();
/// Single-threaded implementation of spin.
// This function will block until work comes in, execute it, and keep blocking.
// It will only be interrupt by a CTRL-C (managed by the global signal handler).
RCLCPP_PUBLIC
void
spin();
private:
RCLCPP_DISABLE_COPY(SingleThreadedExecutor)
};
} // namespace single_threaded_executor
} // namespace executors
} // namespace rclcpp
#endif // RCLCPP__EXECUTORS__SINGLE_THREADED_EXECUTOR_HPP_
|
#include "RenderingPipeline.h"
// https://medium.com/@bgolus/anti-aliased-alpha-test-the-esoteric-alpha-to-coverage-8b177335ae4f
// Alpha-to-Coverage(A2C) technique and use of MSAA for VR
// 요즘 게임들은 Deferred rendering같은 technique으로 인해서, 또는 MSAA의 high-cost로 인해 FXAA를 사용함.
// 근데 VR환경에서는 MSAA 가 괜찮음.
namespace gr
{
std::shared_ptr< Context > RenderingPipeline::getCurrentContext() noexcept
{
return this->context;
}
void RenderingPipeline::setContextCurrent(std::shared_ptr< Context > _context) noexcept
{
this->context = _context;
}
void RenderingPipeline::simulate(float _time_limit, float _fps, char const* _video_path) noexcept
{
}
};
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/skin-config.h"
#endif
#include "net.h"
#include "addrman.h"
#include "chainparams.h"
#include "clientversion.h"
#include "miner.h"
#include "obfuscation.h"
#include "primitives/transaction.h"
#include "ui_interface.h"
#include "wallet.h"
#ifdef WIN32
#include <string.h>
#else
#include <fcntl.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
// Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
#ifdef WIN32
#ifndef PROTECTION_LEVEL_UNRESTRICTED
#define PROTECTION_LEVEL_UNRESTRICTED 10
#endif
#ifndef IPV6_PROTECTION_LEVEL
#define IPV6_PROTECTION_LEVEL 23
#endif
#endif
using namespace boost;
using namespace std;
namespace
{
const int MAX_OUTBOUND_CONNECTIONS = 16;
struct ListenSocket {
SOCKET socket;
bool whitelisted;
ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
};
}
//
// Global state variables
//
bool fDiscover = true;
bool fListen = true;
uint64_t nLocalServices = NODE_NETWORK;
CCriticalSection cs_mapLocalHost;
map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64_t nLocalHostNonce = 0;
static std::vector<ListenSocket> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
bool fAddressesInitialized = false;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
NodeId nLastNodeId = 0;
CCriticalSection cs_nLastNodeId;
static CSemaphore* semOutbound = NULL;
boost::condition_variable messageHandlerCondition;
// Signals for message handling
static CNodeSignals g_signals;
CNodeSignals& GetNodeSignals() { return g_signals; }
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr* paddrPeer)
{
if (!fListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) {
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
// Otherwise, return the unroutable 0.0.0.0 but filled in with
// the normal parameters, since the IP may be changed to a useful
// one by discovery.
CAddress GetLocalAddress(const CNetAddr* paddrPeer)
{
CAddress ret(CService("0.0.0.0", GetListenPort()), 0);
CService addr;
if (GetLocal(addr, paddrPeer)) {
ret = CAddress(addr);
}
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while (true) {
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0) {
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
} else if (nBytes <= 0) {
boost::this_thread::interruption_point();
if (nBytes < 0) {
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) {
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0) {
// socket closed
LogPrint("net", "socket closed\n");
return false;
} else {
// socket error
int nErr = WSAGetLastError();
LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
return false;
}
}
}
}
int GetnScore(const CService& addr)
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == LOCAL_NONE)
return 0;
return mapLocalHost[addr].nScore;
}
// Is our peer's addrLocal potentially useful as an external IP source?
bool IsPeerAddrLocalGood(CNode* pnode)
{
return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
!IsLimited(pnode->addrLocal.GetNetwork());
}
// pushes our own address to a peer
void AdvertizeLocal(CNode* pnode)
{
if (fListen && pnode->fSuccessfullyConnected) {
CAddress addrLocal = GetLocalAddress(&pnode->addr);
// If discovery is enabled, sometimes give our peer the address it
// tells us that it sees us as in case it has a better idea of our
// address than we do.
if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) {
addrLocal.SetIP(pnode->addrLocal);
}
if (addrLocal.IsRoutable()) {
pnode->PushAddress(addrLocal);
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo& info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
return true;
}
bool AddLocal(const CNetAddr& addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr& addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given network is one we can probably connect to */
bool IsReachable(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfReachable[net] && !vfLimited[net];
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
enum Network net = addr.GetNetwork();
return IsReachable(net);
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
uint64_t CNode::nTotalBytesRecv = 0;
uint64_t CNode::nTotalBytesSent = 0;
CCriticalSection CNode::cs_totalBytesRecv;
CCriticalSection CNode::cs_totalBytesSent;
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(const std::string& addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
//if using regtest, just check the IP
if ((CNetAddr)pnode->addr == (CNetAddr)addr)
return (pnode);
} else {
if (pnode->addr == addr)
return (pnode);
}
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster)
{
if (pszDest == NULL) {
// we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections()
// so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus()
if (IsLocal(addrConnect) && !obfuScationMaster)
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode) {
pnode->fObfuScationMaster = obfuScationMaster;
pnode->AddRef();
return pnode;
}
}
/// debug print
LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0);
// Connect
SOCKET hSocket;
bool proxyConnectionFailed = false;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) {
if (!IsSelectableSocket(hSocket)) {
LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
CloseSocket(hSocket);
return NULL;
}
addrman.Attempt(addrConnect);
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
if (obfuScationMaster) pnode->fObfuScationMaster = true;
return pnode;
} else if (!proxyConnectionFailed) {
// If connecting to the node failed, and failure is not caused by a problem connecting to
// the proxy, mark this as an attempt.
addrman.Attempt(addrConnect);
}
return NULL;
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET) {
LogPrint("net", "disconnecting peer=%d\n", id);
CloseSocket(hSocket);
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
}
bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand)
{
fDisconnect = false;
if (nVersion < nVersionRequired) {
LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion);
PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol()));
fDisconnect = true;
}
return fDisconnect;
}
void CNode::PushVersion()
{
int nBestHeight = g_signals.GetHeight().get_value_or(0);
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0)));
CAddress addrMe = GetLocalAddress(&addr);
GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
if (fLogIPs)
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
else
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
}
std::map<CNetAddr, int64_t> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
if (i != setBanned.end()) {
int64_t t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Ban(const CNetAddr& addr)
{
int64_t banTime = GetTime() + GetArg("-bantime", 60 * 60 * 24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
return true;
}
std::vector<CSubNet> CNode::vWhitelistedRange;
CCriticalSection CNode::cs_vWhitelistedRange;
bool CNode::IsWhitelistedRange(const CNetAddr& addr)
{
LOCK(cs_vWhitelistedRange);
BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) {
if (subnet.Match(addr))
return true;
}
return false;
}
void CNode::AddWhitelistedRange(const CSubNet& subnet)
{
LOCK(cs_vWhitelistedRange);
vWhitelistedRange.push_back(subnet);
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats& stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nSendBytes);
X(nRecvBytes);
X(fWhitelisted);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (SKIN users should be well used to small numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId());
return false;
}
pch += handled;
nBytes -= handled;
if (msg.complete()) {
msg.nTime = GetTimeMicros();
messageHandlerCondition.notify_one();
}
}
return true;
}
int CNetMessage::readHeader(const char* pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
} catch (const std::exception&) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char* pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode* pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData& data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
pnode->RecordBytesSent(nBytes);
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while (true) {
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) {
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
}
{
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) {
// wait until threads are done using it
if (pnode->GetRefCount() <= 0) {
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete) {
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount) {
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
FD_SET(hListenSocket.socket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket.socket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR) {
if (have_fds) {
int nErr = WSAGetLastError();
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec / 1000);
}
//
// Accept new connections
//
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) {
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
LogPrintf("Warning: Unknown socket family\n");
bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET) {
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
} else if (!IsSelectableSocket(hSocket)) {
LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
CloseSocket(hSocket);
} else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) {
LogPrint("net", "connection from %s dropped (full)\n", addr.ToString());
CloseSocket(hSocket);
} else if (CNode::IsBanned(addr) && !whitelisted) {
LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
CloseSocket(hSocket);
} else {
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
pnode->fWhitelisted = whitelisted;
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0) {
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
pnode->RecordBytesRecv(nBytes);
} else if (nBytes == 0) {
// socket closed gracefully
if (!pnode->fDisconnect)
LogPrint("net", "socket closed\n");
pnode->CloseSocketDisconnect();
} else if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
if (!pnode->fDisconnect)
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend)) {
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
int64_t nTime = GetTime();
if (nTime - pnode->nTimeConnected > 60) {
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) {
LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) {
LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
pnode->fDisconnect = true;
} else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) {
LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char* multicastif = 0;
const char* minissdpdpath = 0;
struct UPNPDev* devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#elif MINIUPNPC_API_VERSION < 14
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
/* miniupnpc 1.9.20150730 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1) {
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
else {
if (externalIPAddress[0]) {
LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
} else
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "SKIN " + FormatFullVersion();
try {
while (true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");
;
MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes
}
} catch (boost::thread_interrupted) {
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist);
devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP) {
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
} else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
MilliSleep(11 * 1000);
LOCK(cs_vNodes);
if (vNodes.size() >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}
const vector<CDNSSeedData>& vSeeds = Params().DNSSeeds();
int found = 0;
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) {
if (HaveNameProxy()) {
AddOneShot(seed.host);
} else {
vector<CNetAddr> vIPs;
vector<CAddress> vAdd;
if (LookupHost(seed.host.c_str(), vIPs)) {
BOOST_FOREACH (CNetAddr& ip, vIPs) {
int nOneDay = 24 * 3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(seed.name, true));
}
}
LogPrintf("%d addresses found from DNS seeds\n", found);
}
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
for (int64_t nLoop = 0;; nLoop++) {
ProcessOneShot();
BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) {
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++) {
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true) {
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if DNS seeds are all down (an infrastructure attack?).
if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
static bool done = false;
if (!done) {
LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
done = true;
}
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true) {
CAddress addr = addrman.Select();
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while (true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH (string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH (string& strAddNode, lAddresses) {
vector<CService> vservNode(0);
if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) {
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH (CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH (CService& addrNode, *(it))
if (pnode->addr == addrNode) {
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH (vector<CService>& vserv, lservAddressesToAdd) {
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!pszDest) {
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort()))
return false;
} else if (FindNode(pszDest))
return false;
CNode* pnode = ConnectNode(addrConnect, pszDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler()
{
boost::mutex condition_mutex;
boost::unique_lock<boost::mutex> lock(condition_mutex);
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true) {
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
pnode->AddRef();
}
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
if (!g_signals.ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize()) {
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) {
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
}
}
// ppcoin: stake minter thread
void static ThreadStakeMinter()
{
boost::this_thread::interruption_point();
LogPrintf("ThreadStakeMinter started\n");
CWallet* pwallet = pwalletMain;
try {
BitcoinMiner(pwallet, true);
boost::this_thread::interruption_point();
} catch (std::exception& e) {
LogPrintf("ThreadStakeMinter() exception \n");
} catch (...) {
LogPrintf("ThreadStakeMinter() error \n");
}
LogPrintf("ThreadStakeMinter exiting,\n");
}
bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
LogPrintf("%s\n", strError);
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET) {
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
if (!IsSelectableSocket(hListenSocket)) {
strError = "Error: Couldn't create a listenable socket for incoming connections";
LogPrintf("%s\n", strError);
return false;
}
#ifndef WIN32
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows!
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
// Set to non-blocking, incoming connections will also inherit this
if (!SetSocketNonBlocking(hListenSocket, true)) {
strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. SKIN Core is probably already running."), addrBind.ToString());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover(boost::thread_group& threadGroup)
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[256] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) {
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr)) {
BOOST_FOREACH (const CNetAddr& addr, vaddr) {
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0) {
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
} else if (ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
}
}
freeifaddrs(myaddrs);
}
#endif
}
void StartNode(boost::thread_group& threadGroup)
{
uiInterface.InitMessage(_("Loading addresses..."));
// Load addresses for peers.dat
int64_t nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
LogPrintf("Invalid or missing peers.dat; recreating\n");
}
LogPrintf("Loaded %i addresses from peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
fAddressesInitialized = true;
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover(threadGroup);
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000));
// ppcoin:mint proof-of-stake blocks in the background
if (GetBoolArg("-staking", true))
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter));
}
bool StopNode()
{
LogPrintf("StopNode()\n");
MapPort(false);
if (semOutbound)
for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
if (fAddressesInitialized) {
DumpAddresses();
fAddressesInitialized = false;
}
return true;
}
class CNetCleanup
{
public:
CNetCleanup() {}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
CloseSocket(pnode->hSocket);
BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket)
if (hListenSocket.socket != INVALID_SOCKET)
if (!CloseSocket(hListenSocket.socket))
LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
BOOST_FOREACH (CNode* pnode, vNodes)
delete pnode;
BOOST_FOREACH (CNode* pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
vhListenSocket.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
} instance_of_cnetcleanup;
void CExplicitNetCleanup::callCleanup()
{
// Explicit call to destructor of CNetCleanup because it's not implicitly called
// when the wallet is restarted from within the wallet itself.
CNetCleanup* tmp = new CNetCleanup();
delete tmp; // Stroustrup's gonna kill me for that
}
void RelayTransaction(const CTransaction& tx)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, ss);
}
void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
{
CInv inv(MSG_TX, tx.GetHash());
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) {
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter) {
if (pnode->pfilter->IsRelevantAndUpdate(tx))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll)
{
CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
//broadcast the new lock
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!relayToAll && !pnode->fRelayTxes)
continue;
pnode->PushMessage("ix", tx);
}
}
void RelayInv(CInv& inv)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes){
if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue;
if (pnode->nVersion >= ActiveProtocol())
pnode->PushInventory(inv);
}
}
void CNode::RecordBytesRecv(uint64_t bytes)
{
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CNode::RecordBytesSent(uint64_t bytes)
{
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
}
uint64_t CNode::GetTotalBytesRecv()
{
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CNode::GetTotalBytesSent()
{
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
void CNode::Fuzz(int nChance)
{
if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
switch (GetRand(3)) {
case 0:
// xor a random byte with a random value:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend[pos] ^= (unsigned char)(GetRand(256));
}
break;
case 1:
// delete a random byte:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend.erase(ssSend.begin() + pos);
}
break;
case 2:
// insert a random byte at a random position
{
CDataStream::size_type pos = GetRand(ssSend.size());
char ch = (char)GetRand(256);
ssSend.insert(ssSend.begin() + pos, ch);
}
break;
}
// Chance of more than one change half the time:
// (more changes exponentially less likely):
Fuzz(2);
}
//
// CAddrDB
//
CAddrDB::CAddrDB()
{
pathAddr = GetDataDir() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("peers.dat.%04x", randv);
// serialize addresses, checksum data up to that point, then append csum
CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
ssPeers << FLATDATA(Params().MessageStart());
ssPeers << addr;
uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
ssPeers << hash;
// open output file, and associate with CAutoFile
boost::filesystem::path pathAddr = GetDataDir() / "peers.dat";
FILE* file = fopen(pathAddr.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// Write and commit header, data
try {
fileout << ssPeers;
} catch (std::exception& e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
return true;
}
bool CAddrDB::Read(CAddrMan& addr)
{
// open input file, and associate with CAutoFile
FILE* file = fopen(pathAddr.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathAddr);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char*)&vchData[0], dataSize);
filein >> hashIn;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
if (hashIn != hashTmp)
return error("%s : Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssPeers >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s : Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssPeers >> addr;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); }
unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); }
CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000)
{
nServices = 0;
hSocket = hSocketIn;
nRecvVersion = INIT_PROTO_VERSION;
nLastSend = 0;
nLastRecv = 0;
nSendBytes = 0;
nRecvBytes = 0;
nTimeConnected = GetTime();
addr = addrIn;
addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
nVersion = 0;
strSubVer = "";
fWhitelisted = false;
fOneShot = false;
fClient = false; // set by version message
fInbound = fInboundIn;
fNetworkNode = false;
fSuccessfullyConnected = false;
fDisconnect = false;
nRefCount = 0;
nSendSize = 0;
nSendOffset = 0;
hashContinue = 0;
nStartingHeight = -1;
fGetAddr = false;
fRelayTxes = false;
setInventoryKnown.max_size(SendBufferSize() / 1000);
pfilter = new CBloomFilter();
nPingNonceSent = 0;
nPingUsecStart = 0;
nPingUsecTime = 0;
fPingQueued = false;
fObfuScationMaster = false;
{
LOCK(cs_nLastNodeId);
id = nLastNodeId++;
}
if (fLogIPs)
LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
else
LogPrint("net", "Added connection peer=%d\n", id);
// Be shy and don't send version until we hear
if (hSocket != INVALID_SOCKET && !fInbound)
PushVersion();
GetNodeSignals().InitializeNode(GetId(), this);
}
CNode::~CNode()
{
CloseSocket(hSocket);
if (pfilter)
delete pfilter;
GetNodeSignals().FinalizeNode(GetId());
}
void CNode::AskFor(const CInv& inv)
{
if (mapAskFor.size() > MAPASKFOR_MAX_SZ)
return;
// We're using mapAskFor as a priority queue,
// the key is the earliest time the request can be sent
int64_t nRequestTime;
limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
if (it != mapAlreadyAskedFor.end())
nRequestTime = it->second;
else
nRequestTime = 0;
LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id);
// Make sure not to reuse time indexes to keep things in the same order
int64_t nNow = GetTimeMicros() - 1000000;
static int64_t nLastTime;
++nLastTime;
nNow = std::max(nNow, nLastTime);
nLastTime = nNow;
// Each retry is 2 minutes after the last
nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
if (it != mapAlreadyAskedFor.end())
mapAlreadyAskedFor.update(it, nRequestTime);
else
mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
mapAskFor.insert(std::make_pair(nRequestTime, inv));
}
void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
{
ENTER_CRITICAL_SECTION(cs_vSend);
assert(ssSend.size() == 0);
ssSend << CMessageHeader(pszCommand, 0);
LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
}
void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
{
ssSend.clear();
LEAVE_CRITICAL_SECTION(cs_vSend);
LogPrint("net", "(aborted)\n");
}
void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
{
// The -*messagestest options are intentionally not documented in the help message,
// since they are only used during development to debug the networking code and are
// not intended for end-users.
if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) {
LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
AbortMessage();
return;
}
if (mapArgs.count("-fuzzmessagestest"))
Fuzz(GetArg("-fuzzmessagestest", 10));
if (ssSend.size() == 0)
return;
// Set the size
unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
// Set the checksum
uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
ssSend.GetAndClear(*it);
nSendSize += (*it).size();
// If write queue empty, attempt "optimistic write"
if (it == vSendMsg.begin())
SocketSendData(this);
LEAVE_CRITICAL_SECTION(cs_vSend);
}
|
// Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'ReqMulti.pas' rev: 6.00
#ifndef ReqMultiHPP
#define ReqMultiHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <HTTPParse.hpp> // Pascal unit
#include <ReqFiles.hpp> // Pascal unit
#include <HTTPApp.hpp> // Pascal unit
#include <Contnrs.hpp> // Pascal unit
#include <Masks.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Reqmulti
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TMultipartContentParser;
class PASCALIMPLEMENTATION TMultipartContentParser : public Httpapp::TAbstractContentParser
{
typedef Httpapp::TAbstractContentParser inherited;
private:
Classes::TStrings* FContentFields;
Reqfiles::TWebRequestFiles* FFiles;
AnsiString FContentBuffer;
protected:
virtual Classes::TStrings* __fastcall GetContentFields(void);
virtual Httpapp::TAbstractWebRequestFiles* __fastcall GetFiles(void);
void __fastcall ExtractContentTypeFields(Classes::TStrings* Strings);
void __fastcall ParseMultiPartContent(void);
void __fastcall ParseMultiPart(void * Part, int Size);
void __fastcall BufferContent(void);
void __fastcall ParseMultipartHeaders(Httpparse::THTTPParser* Parser, void * AContent, int AContentLength);
void __fastcall ExtractMultipartContentFields(void);
public:
__fastcall virtual ~TMultipartContentParser(void);
/* virtual class method */ virtual bool __fastcall CanParse(TMetaClass* vmt, Httpapp::TWebRequest* AWebRequest);
public:
#pragma option push -w-inl
/* TAbstractContentParser.Create */ inline __fastcall virtual TMultipartContentParser(Httpapp::TWebRequest* AWebRequest) : Httpapp::TAbstractContentParser(AWebRequest) { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Reqmulti */
using namespace Reqmulti;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // ReqMulti
|
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: org.apache.http.MethodNotSupportedException
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_METHODNOTSUPPORTEDEXCEPTION_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_METHODNOTSUPPORTEDEXCEPTION_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Throwable; } } }
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpException; } } } }
#include <java/lang/String.hpp>
#include <java/lang/Throwable.hpp>
#include <org/apache/http/HttpException.hpp>
namespace j2cpp {
namespace org { namespace apache { namespace http {
class MethodNotSupportedException;
class MethodNotSupportedException
: public object<MethodNotSupportedException>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
explicit MethodNotSupportedException(jobject jobj)
: object<MethodNotSupportedException>(jobj)
{
}
operator local_ref<org::apache::http::HttpException>() const;
MethodNotSupportedException(local_ref< java::lang::String > const&);
MethodNotSupportedException(local_ref< java::lang::String > const&, local_ref< java::lang::Throwable > const&);
}; //class MethodNotSupportedException
} //namespace http
} //namespace apache
} //namespace org
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_METHODNOTSUPPORTEDEXCEPTION_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_METHODNOTSUPPORTEDEXCEPTION_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_METHODNOTSUPPORTEDEXCEPTION_HPP_IMPL
namespace j2cpp {
org::apache::http::MethodNotSupportedException::operator local_ref<org::apache::http::HttpException>() const
{
return local_ref<org::apache::http::HttpException>(get_jobject());
}
org::apache::http::MethodNotSupportedException::MethodNotSupportedException(local_ref< java::lang::String > const &a0)
: object<org::apache::http::MethodNotSupportedException>(
call_new_object<
org::apache::http::MethodNotSupportedException::J2CPP_CLASS_NAME,
org::apache::http::MethodNotSupportedException::J2CPP_METHOD_NAME(0),
org::apache::http::MethodNotSupportedException::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
org::apache::http::MethodNotSupportedException::MethodNotSupportedException(local_ref< java::lang::String > const &a0, local_ref< java::lang::Throwable > const &a1)
: object<org::apache::http::MethodNotSupportedException>(
call_new_object<
org::apache::http::MethodNotSupportedException::J2CPP_CLASS_NAME,
org::apache::http::MethodNotSupportedException::J2CPP_METHOD_NAME(1),
org::apache::http::MethodNotSupportedException::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1)
)
{
}
J2CPP_DEFINE_CLASS(org::apache::http::MethodNotSupportedException,"org/apache/http/MethodNotSupportedException")
J2CPP_DEFINE_METHOD(org::apache::http::MethodNotSupportedException,0,"<init>","(Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::apache::http::MethodNotSupportedException,1,"<init>","(Ljava/lang/String;Ljava/lang/Throwable;)V")
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_METHODNOTSUPPORTEDEXCEPTION_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
|
/*
* (C) 2015,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "driver.h"
#include <botan/tls_client.h>
class Fuzzer_TLS_Client_Creds : public Credentials_Manager
{
public:
std::string psk_identity_hint(const std::string&, const std::string&) override { return "psk_hint"; }
std::string psk_identity(const std::string&, const std::string&, const std::string&) override { return "psk_id"; }
SymmetricKey psk(const std::string&, const std::string&, const std::string&) override
{
return SymmetricKey("AABBCCDDEEFF00112233445566778899");
}
};
void fuzz(const uint8_t in[], size_t len)
{
if(len == 0)
return;
auto dev_null = [](const byte[], size_t) {};
auto ignore_alerts = [](TLS::Alert, const byte[], size_t) {};
auto ignore_hs = [](const TLS::Session&) { abort(); return true; };
TLS::Session_Manager_Noop session_manager;
TLS::Policy policy;
TLS::Protocol_Version client_offer = TLS::Protocol_Version::TLS_V12;
TLS::Server_Information info("server.name", 443);
const std::vector<std::string> protocols_to_offer = { "fuzz/1.0", "http/1.1", "bunny/1.21.3" };
Fuzzer_TLS_Client_Creds creds;
TLS::Client client(dev_null,
dev_null,
ignore_alerts,
ignore_hs,
session_manager,
creds,
policy,
fuzzer_rng(),
info,
client_offer,
protocols_to_offer);
try
{
while(len > 0)
{
const size_t write_len = in[0];
const size_t left = len - 1;
const size_t consumed = std::min(left, write_len);
client.received_data(in + 1, consumed);
in += consumed + 1;
len -= consumed + 1;
}
}
catch(std::exception& e)
{
}
}
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_CORE_POINT_TYPE_HPP
#define BOOST_GEOMETRY_CORE_POINT_TYPE_HPP
#include <boost/mpl/assert.hpp>
#include <boost/range/value_type.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/util/bare_type.hpp>
namespace boost { namespace geometry
{
namespace traits
{
/*!
\brief Traits class indicating the type of contained points
\ingroup traits
\par Geometries:
- all geometries except point
\par Specializations should provide:
- typedef P type (where P should fulfil the Point concept)
\tparam Geometry geometry
*/
template <typename Geometry>
struct point_type
{
BOOST_MPL_ASSERT_MSG
(
false, NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE, (types<Geometry>)
);
};
} // namespace traits
#ifndef DOXYGEN_NO_DISPATCH
namespace core_dispatch
{
template <typename Tag, typename Geometry>
struct point_type
{
// Default: call traits to get point type
typedef typename boost::remove_const
<
typename traits::point_type<Geometry>::type
>::type type;
};
// Specialization for point: the point itself
template <typename Point>
struct point_type<point_tag, Point>
{
typedef Point type;
};
// Specializations for linestring/ring, via boost::range
template <typename Linestring>
struct point_type<linestring_tag, Linestring>
{
typedef typename boost::range_value<Linestring>::type type;
};
template <typename Ring>
struct point_type<ring_tag, Ring>
{
typedef typename boost::range_value<Ring>::type type;
};
// Specialization for polygon: the point-type is the point-type of its rings
template <typename Polygon>
struct point_type<polygon_tag, Polygon>
{
typedef typename point_type
<
ring_tag,
typename ring_type<polygon_tag, Polygon>::type
>::type type;
};
template <typename MultiPoint>
struct point_type<multi_point_tag, MultiPoint>
{
typedef typename boost::range_value
<
MultiPoint
>::type type;
};
template <typename MultiLinestring>
struct point_type<multi_linestring_tag, MultiLinestring>
{
typedef typename point_type
<
linestring_tag,
typename boost::range_value<MultiLinestring>::type
>::type type;
};
template <typename MultiPolygon>
struct point_type<multi_polygon_tag, MultiPolygon>
{
typedef typename point_type
<
polygon_tag,
typename boost::range_value<MultiPolygon>::type
>::type type;
};
} // namespace core_dispatch
#endif // DOXYGEN_NO_DISPATCH
/*!
\brief \brief_meta{type, point_type, \meta_geometry_type}
\tparam Geometry \tparam_geometry
\ingroup core
\qbk{[include reference/core/point_type.qbk]}
*/
template <typename Geometry>
struct point_type
{
typedef typename core_dispatch::point_type
<
typename tag<Geometry>::type,
typename boost::geometry::util::bare_type<Geometry>::type
>::type type;
};
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_CORE_POINT_TYPE_HPP
|
// license:GPL-2.0+
// copyright-holders:Couriersud
/***************************************************************************
netlib.c
Discrete netlist implementation.
****************************************************************************/
#include "net_lib.h"
#include "nld_system.h"
#include "nl_factory.h"
#include "solver/nld_solver.h"
NETLIST_START(diode_models)
NET_MODEL("D _(IS=1e-15 N=1)")
NET_MODEL("1N914 D(Is=2.52n Rs=.568 N=1.752 Cjo=4p M=.4 tt=20n Iave=200m Vpk=75 mfg=OnSemi type=silicon)")
NET_MODEL("1N4001 D(Is=14.11n N=1.984 Rs=33.89m Ikf=94.81 Xti=3 Eg=1.11 Cjo=25.89p M=.44 Vj=.3245 Fc=.5 Bv=75 Ibv=10u Tt=5.7u Iave=1 Vpk=50 mfg=GI type=silicon)")
NET_MODEL("1N4148 D(Is=2.52n Rs=.568 N=1.752 Cjo=4p M=.4 tt=20n Iave=200m Vpk=75 mfg=OnSemi type=silicon)")
NET_MODEL("1S1588 D(Is=2.52n Rs=.568 N=1.752 Cjo=4p M=.4 tt=20n Iave=200m Vpk=75)")
NET_MODEL("LedRed D(IS=93.2p RS=42M N=3.73 BV=4 IBV=10U CJO=2.97P VJ=.75 M=.333 TT=4.32U Iave=40m Vpk=4 type=LED)")
NET_MODEL("LedGreen D(IS=93.2p RS=42M N=4.61 BV=4 IBV=10U CJO=2.97P VJ=.75 M=.333 TT=4.32U Iave=40m Vpk=4 type=LED)")
NET_MODEL("LedBlue D(IS=93.2p RS=42M N=7.47 BV=5 IBV=10U CJO=2.97P VJ=.75 M=.333 TT=4.32U Iave=40m Vpk=5 type=LED)")
NET_MODEL("LedWhite D(Is=0.27n Rs=5.65 N=6.79 Cjo=42p Iave=30m Vpk=5 type=LED)")
NETLIST_END()
NETLIST_START(bjt_models)
NET_MODEL("NPN _(IS=1e-15 BF=100 NF=1 BR=1 NR=1)")
NET_MODEL("PNP _(IS=1e-15 BF=100 NF=1 BR=1 NR=1)")
NET_MODEL("2SA1015 PNP(Is=295.1E-18 Xti=3 Eg=1.11 Vaf=100 Bf=110 Xtb=1.5 Br=10.45 Rc=15 Cjc=66.2p Mjc=1.054 Vjc=.75 Fc=.5 Cje=5p Mje=.3333 Vje=.75 Tr=10n Tf=1.661n VCEO=45V ICrating=150M MFG=Toshiba)")
NET_MODEL("2SC1815 NPN(Is=2.04f Xti=3 Eg=1.11 Vaf=6 Bf=400 Ikf=20m Xtb=1.5 Br=3.377 Rc=1 Cjc=1p Mjc=.3333 Vjc=.75 Fc=.5 Cje=25p Mje=.3333 Vje=.75 Tr=450n Tf=20n Itf=0 Vtf=0 Xtf=0 VCEO=45V ICrating=150M MFG=Toshiba)")
NET_MODEL("2N3643 NPN(IS=14.34E-15 ISE=14.34E-15 ISC=0 XTI=3 BF=255.9 BR=6.092 IKF=0.2847 IKR=0 XTB=1.5 VAF=74.03 VAR=28 VJE=0.65 VJC=0.65 RE=0.1 RC=1 RB=10 CJE=22.01E-12 CJC=7.306E-12 XCJC=0.75 FC=0.5 NF=1 NR=1 NE=1.307 NC=2 MJE=0.377 MJC=0.3416 TF=411.1E-12 TR=46.91E-9 ITF=0.6 VTF=1.7 XTF=3 EG=1.11 KF=0 AF=1 VCEO=30 ICRATING=500m MFG=NSC)")
NET_MODEL("2N3645 PNP(IS=650.6E-18 ISE=54.81E-15 ISC=0 XTI=3 BF=231.7 BR=3.563 IKF=1.079 IKR=0 XTB=1.5 VAF=115.7 VAR=35 VJE=0.65 VJC=0.65 RE=0.15 RC=0.715 RB=10 CJE=19.82E-12 CJC=14.76E-12 XCJC=0.75 FC=0.5 NF=1 NR=1 NE=1.829 NC=2 MJE=0.3357 MJC=0.5383 TF=603.7E-12 TR=111.3E-9 ITF=0.65 VTF=5 XTF=1.7 EG=1.11 KF=0 AF=1 VCEO=60 ICRATING=500m MFG=NSC)")
// 3644 = 3645 Difference between 3644 and 3645 is voltage rating. 3644: VCBO=45, 3645: VCBO=60
NET_MODEL("2N3644 PNP(IS=650.6E-18 ISE=54.81E-15 ISC=0 XTI=3 BF=231.7 BR=3.563 IKF=1.079 IKR=0 XTB=1.5 VAF=115.7 VAR=35 VJE=0.65 VJC=0.65 RE=0.15 RC=0.715 RB=10 CJE=19.82E-12 CJC=14.76E-12 XCJC=0.75 FC=0.5 NF=1 NR=1 NE=1.829 NC=2 MJE=0.3357 MJC=0.5383 TF=603.7E-12 TR=111.3E-9 ITF=0.65 VTF=5 XTF=1.7 EG=1.11 KF=0 AF=1 VCEO=60 ICRATING=500m MFG=NSC)")
// 2N5190 = BC817-25
NET_MODEL("2N5190 NPN(IS=9.198E-14 NF=1.003 ISE=4.468E-16 NE=1.65 BF=338.8 IKF=0.4913 VAF=107.9 NR=1.002 ISC=5.109E-15 NC=1.071 BR=29.48 IKR=0.193 VAR=25 RB=1 IRB=1000 RBM=1 RE=0.2126 RC=0.143 XTB=0 EG=1.11 XTI=3 CJE=3.825E-11 VJE=0.7004 MJE=0.364 TF=5.229E-10 XTF=219.7 VTF=3.502 ITF=7.257 PTF=0 CJC=1.27E-11 VJC=0.4431 MJC=0.3983 XCJC=0.4555 TR=7E-11 CJS=0 VJS=0.75 MJS=0.333 FC=0.905 Vceo=45 Icrating=500m mfg=Philips)")
NET_MODEL("2SC945 NPN(IS=3.577E-14 BF=2.382E+02 NF=1.01 VAF=1.206E+02 IKF=3.332E-01 ISE=3.038E-16 NE=1.205 BR=1.289E+01 NR=1.015 VAR=1.533E+01 IKR=2.037E-01 ISC=3.972E-14 NC=1.115 RB=3.680E+01 IRB=1.004E-04 RBM=1 RE=8.338E-01 RC=1.557E+00 CJE=1.877E-11 VJE=7.211E-01 MJE=3.486E-01 TF=4.149E-10 XTF=1.000E+02 VTF=9.956 ITF=5.118E-01 PTF=0 CJC=6.876p VJC=3.645E-01 MJC=3.074E-01 TR=5.145E-08 XTB=1.5 EG=1.11 XTI=3 FC=0.5 Vceo=50 Icrating=100m MFG=NEC)")
NET_MODEL("BC237B NPN(IS=1.8E-14 ISE=5.0E-14 ISC=1.72E-13 XTI=3 BF=400 BR=35.5 IKF=0.14 IKR=0.03 XTB=1.5 VAF=80 VAR=12.5 VJE=0.58 VJC=0.54 RE=0.6 RC=0.25 RB=0.56 CJE=13E-12 CJC=4E-12 XCJC=0.75 FC=0.5 NF=0.9955 NR=1.005 NE=1.46 NC=1.27 MJE=0.33 MJC=0.33 TF=0.64E-9 TR=50.72E-9 EG=1.11 KF=0 AF=1 VCEO=45 ICRATING=100M MFG=ZETEX)")
NET_MODEL("BC556B PNP(IS=3.83E-14 NF=1.008 ISE=1.22E-14 NE=1.528 BF=344.4 IKF=0.08039 VAF=21.11 NR=1.005 ISC=2.85E-13 NC=1.28 BR=14.84 IKR=0.047 VAR=32.02 RB=1 IRB=1.00E-06 RBM=1 RE=0.6202 RC=0.5713 XTB=0 EG=1.11 XTI=3 CJE=1.23E-11 VJE=0.6106 MJE=0.378 TF=5.60E-10 XTF=3.414 VTF=5.23 ITF=0.1483 PTF=0 CJC=1.08E-11 VJC=0.1022 MJC=0.3563 XCJC=0.6288 TR=1.00E-32 CJS=0 VJS=0.75 MJS=0.333 FC=0.8027 Vceo=65 Icrating=100m mfg=Philips)")
NET_MODEL("BC548C NPN(IS=1.95E-14 ISE=1.31E-15 ISC=1.0E-13 XTI=3 BF=466 BR=2.42 IKF=0.18 IKR=1 XTB=1.5 VAF=91.7 VAR=24.7 VJE=0.632 VJC=0.339 RE=1 RC=1.73 RB=26.5 RBM=10 IRB=10 CJE=1.33E-11 CJC=5.17E-12 XCJC=1 FC=0.9 NF=0.993 NR=1.2 NE=1.32 NC=2.00 MJE=0.326 MJC=0.319 TF=6.52E-10 TR=0 PTF=0 ITF=1.03 VTF=1.65 XTF=100 EG=1.11 KF=1E-9 AF=1 VCEO=40 ICrating=800M MFG=Siemens)")
NET_MODEL("BC817-25 NPN(IS=9.198E-14 NF=1.003 ISE=4.468E-16 NE=1.65 BF=338.8 IKF=0.4913 VAF=107.9 NR=1.002 ISC=5.109E-15 NC=1.071 BR=29.48 IKR=0.193 VAR=25 RB=1 IRB=1000 RBM=1 RE=0.2126 RC=0.143 XTB=0 EG=1.11 XTI=3 CJE=3.825E-11 VJE=0.7004 MJE=0.364 TF=5.229E-10 XTF=219.7 VTF=3.502 ITF=7.257 PTF=0 CJC=1.27E-11 VJC=0.4431 MJC=0.3983 XCJC=0.4555 TR=7E-11 CJS=0 VJS=0.75 MJS=0.333 FC=0.905 Vceo=45 Icrating=500m mfg=Philips)")
NETLIST_END()
NETLIST_START(family_models)
NET_MODEL("FAMILY _(TYPE=CUSTOM IVL=0.8 IVH=2.0 OVL=0.1 OVH=4.0 ORL=1.0 ORH=130.0)")
NET_MODEL("OPAMP _()")
NET_MODEL("74XXOC FAMILY(IVL=0.8 IVH=2.0 OVL=0.1 OVH=4.95 ORL=10.0 ORH=1.0e8)")
NET_MODEL("74XX FAMILY(TYPE=TTL)")
NET_MODEL("CD4XXX FAMILY(TYPE=CD4XXX)")
NETLIST_END()
#define xstr(s) # s
#define ENTRY1(nic, name, defparam) factory.register_device<nic>( # name, xstr(nic), defparam );
#define ENTRY(nic, name, defparam) ENTRY1(NETLIB_NAME(nic), name, defparam)
#define NETLIB_DEVICE_DECL(chip) extern factory_creator_ptr_t decl_ ## chip;
#define ENTRYX1(nic, name, defparam, decl) factory.register_device( decl (# name, xstr(nic), defparam) );
#define ENTRYX(nic, name, defparam) { NETLIB_DEVICE_DECL(nic) ENTRYX1(NETLIB_NAME(nic), name, defparam, decl_ ## nic) }
namespace netlist
{
namespace devices
{
static void initialize_factory(factory_list_t &factory)
{
ENTRY(R, RES, "R")
ENTRY(POT, POT, "R")
ENTRY(POT2, POT2, "R")
ENTRY(C, CAP, "C")
ENTRY(D, DIODE, "MODEL")
ENTRY(VCVS, VCVS, "-")
ENTRY(VCCS, VCCS, "-")
ENTRY(CCCS, CCCS, "-")
ENTRY(LVCCS, LVCCS, "-")
ENTRY(VS, VS, "V")
ENTRY(CS, CS, "I")
ENTRY(OPAMP, OPAMP, "MODEL")
ENTRYX(dummy_input, DUMMY_INPUT, "-")
ENTRYX(frontier, FRONTIER_DEV, "+I,G,Q") // not intended to be used directly
ENTRYX(function, AFUNC, "N,FUNC") // only for macro devices - NO FEEDBACK loops
ENTRY(QBJT_EB, QBJT_EB, "MODEL")
ENTRY(QBJT_switch, QBJT_SW, "MODEL")
ENTRYX(logic_input, TTL_INPUT, "IN")
ENTRYX(logic_input, LOGIC_INPUT, "IN,FAMILY")
ENTRYX(analog_input, ANALOG_INPUT, "IN")
ENTRYX(log, LOG, "+I")
ENTRYX(logD, LOGD, "+I,I2")
ENTRYX(clock, CLOCK, "FREQ")
ENTRYX(extclock, EXTCLOCK, "FREQ")
ENTRYX(mainclock, MAINCLOCK, "FREQ")
ENTRYX(gnd, GND, "-")
ENTRYX(netlistparams, PARAMETER, "-")
ENTRY(solver, SOLVER, "FREQ")
ENTRYX(res_sw, RES_SWITCH, "+IN,P1,P2")
ENTRY(switch1, SWITCH, "-")
ENTRY(switch2, SWITCH2, "-")
ENTRYX(nicRSFF, NETDEV_RSFF, "+S,R")
ENTRYX(nicDelay, NETDEV_DELAY, "-")
ENTRYX(7450, TTL_7450_ANDORINVERT, "+A,B,C,D")
ENTRYX(7448, TTL_7448, "+A,B,C,D,LTQ,BIQ,RBIQ")
ENTRYX(7474, TTL_7474, "+CLK,D,CLRQ,PREQ")
ENTRYX(7483, TTL_7483, "+A1,A2,A3,A4,B1,B2,B3,B4,C0")
ENTRYX(7490, TTL_7490, "+A,B,R1,R2,R91,R92")
ENTRYX(7493, TTL_7493, "+CLKA,CLKB,R1,R2")
ENTRYX(74107, TTL_74107, "+CLK,J,K,CLRQ")
ENTRYX(74107A, TTL_74107A, "+CLK,J,K,CLRQ")
ENTRYX(74123, TTL_74123, "-")
ENTRYX(74153, TTL_74153, "+C0,C1,C2,C3,A,B,G")
ENTRYX(74175, TTL_74175, "-")
ENTRYX(74192, TTL_74192, "-")
ENTRYX(74193, TTL_74193, "-")
//ENTRY(74279, TTL_74279, "-") // only dip available
ENTRYX(SN74LS629, SN74LS629, "CAP")
ENTRYX(82S16, TTL_82S16, "-")
ENTRYX(9310, TTL_9310, "-")
ENTRYX(9312, TTL_9312, "-")
ENTRYX(9316, TTL_9316, "+CLK,ENP,ENT,CLRQ,LOADQ,A,B,C,D")
ENTRYX(CD4020, CD4020, "")
ENTRYX(CD4066_GATE, CD4066_GATE, "")
/* entries with suffix WI are legacy only */
ENTRYX(CD4020, CD4020_WI, "+IP,RESET,VDD,VSS")
//ENTRY(4066, CD_4066, "+A,B")
ENTRYX(NE555, NE555, "-")
ENTRYX(r2r_dac, R2R_DAC, "+VIN,R,N")
ENTRYX(4538_dip, CD4538_DIP, "-")
ENTRYX(7448_dip, TTL_7448_DIP, "-")
ENTRYX(7450_dip, TTL_7450_DIP, "-")
ENTRYX(7474_dip, TTL_7474_DIP, "-")
ENTRYX(7483_dip, TTL_7483_DIP, "-")
ENTRYX(7490_dip, TTL_7490_DIP, "-")
ENTRYX(7493_dip, TTL_7493_DIP, "-")
ENTRYX(74107_dip, TTL_74107_DIP, "-")
ENTRYX(74123_dip, TTL_74123_DIP, "-")
ENTRYX(74153_dip, TTL_74153_DIP, "-")
ENTRYX(74175_dip, TTL_74175_DIP, "-")
ENTRYX(74192_dip, TTL_74192_DIP, "-")
ENTRYX(74193_dip, TTL_74193_DIP, "-")
ENTRYX(74279_dip, TTL_74279_DIP, "-")
ENTRYX(82S16_dip, TTL_82S16_DIP, "-")
ENTRYX(9602_dip, TTL_9602_DIP, "-")
ENTRYX(9310_dip, TTL_9310_DIP, "-")
ENTRYX(9312_dip, TTL_9312_DIP, "-")
ENTRYX(9316_dip, TTL_9316_DIP, "-")
ENTRYX(SN74LS629_dip, SN74LS629_DIP, "1.CAP1,2.CAP2")
ENTRYX(NE555_dip, NE555_DIP, "-")
ENTRYX(MM5837_dip, MM5837_DIP, "-")
}
} //namespace devices
} // namespace netlist
namespace netlist
{
void initialize_factory(factory_list_t &factory)
{
devices::initialize_factory(factory);
}
}
|
//
// detail/winrt_ssocket_service_base.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_WINRT_SSOCKET_SERVICE_BASE_HPP
#define BOOST_ASIO_DETAIL_WINRT_SSOCKET_SERVICE_BASE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_WINDOWS_RUNTIME)
#include <boost/asio/buffer.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/socket_base.hpp>
#include <boost/asio/detail/addressof.hpp>
#include <boost/asio/detail/buffer_sequence_adapter.hpp>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/detail/winrt_async_manager.hpp>
#include <boost/asio/detail/winrt_socket_recv_op.hpp>
#include <boost/asio/detail/winrt_socket_send_op.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
class winrt_ssocket_service_base
{
public:
// The native type of a socket.
typedef Windows::Networking::Sockets::StreamSocket^ native_handle_type;
// The implementation type of the socket.
struct base_implementation_type
{
// Default constructor.
base_implementation_type()
: socket_(nullptr),
next_(0),
prev_(0)
{
}
// The underlying native socket.
native_handle_type socket_;
// Pointers to adjacent socket implementations in linked list.
base_implementation_type* next_;
base_implementation_type* prev_;
};
// Constructor.
BOOST_ASIO_DECL winrt_ssocket_service_base(
boost::asio::io_service& io_service);
// Destroy all user-defined handler objects owned by the service.
BOOST_ASIO_DECL void shutdown_service();
// Construct a new socket implementation.
BOOST_ASIO_DECL void construct(base_implementation_type&);
// Move-construct a new socket implementation.
BOOST_ASIO_DECL void base_move_construct(base_implementation_type& impl,
base_implementation_type& other_impl);
// Move-assign from another socket implementation.
BOOST_ASIO_DECL void base_move_assign(base_implementation_type& impl,
winrt_ssocket_service_base& other_service,
base_implementation_type& other_impl);
// Destroy a socket implementation.
BOOST_ASIO_DECL void destroy(base_implementation_type& impl);
// Determine whether the socket is open.
bool is_open(const base_implementation_type& impl) const
{
return impl.socket_ != nullptr;
}
// Destroy a socket implementation.
BOOST_ASIO_DECL boost::system::error_code close(
base_implementation_type& impl, boost::system::error_code& ec);
// Get the native socket representation.
native_handle_type native_handle(base_implementation_type& impl)
{
return impl.socket_;
}
// Cancel all operations associated with the socket.
boost::system::error_code cancel(base_implementation_type&,
boost::system::error_code& ec)
{
ec = boost::asio::error::operation_not_supported;
return ec;
}
// Determine whether the socket is at the out-of-band data mark.
bool at_mark(const base_implementation_type&,
boost::system::error_code& ec) const
{
ec = boost::asio::error::operation_not_supported;
return false;
}
// Determine the number of bytes available for reading.
std::size_t available(const base_implementation_type&,
boost::system::error_code& ec) const
{
ec = boost::asio::error::operation_not_supported;
return 0;
}
// Perform an IO control command on the socket.
template <typename IO_Control_Command>
boost::system::error_code io_control(base_implementation_type&,
IO_Control_Command&, boost::system::error_code& ec)
{
ec = boost::asio::error::operation_not_supported;
return ec;
}
// Gets the non-blocking mode of the socket.
bool non_blocking(const base_implementation_type&) const
{
return false;
}
// Sets the non-blocking mode of the socket.
boost::system::error_code non_blocking(base_implementation_type&,
bool, boost::system::error_code& ec)
{
ec = boost::asio::error::operation_not_supported;
return ec;
}
// Gets the non-blocking mode of the native socket implementation.
bool native_non_blocking(const base_implementation_type&) const
{
return false;
}
// Sets the non-blocking mode of the native socket implementation.
boost::system::error_code native_non_blocking(base_implementation_type&,
bool, boost::system::error_code& ec)
{
ec = boost::asio::error::operation_not_supported;
return ec;
}
// Disable sends or receives on the socket.
boost::system::error_code shutdown(base_implementation_type&,
socket_base::shutdown_type, boost::system::error_code& ec)
{
ec = boost::asio::error::operation_not_supported;
return ec;
}
// Send the given data to the peer.
template <typename ConstBufferSequence>
std::size_t send(base_implementation_type& impl,
const ConstBufferSequence& buffers,
socket_base::message_flags flags, boost::system::error_code& ec)
{
return do_send(impl,
buffer_sequence_adapter<boost::asio::const_buffer,
ConstBufferSequence>::first(buffers), flags, ec);
}
// Wait until data can be sent without blocking.
std::size_t send(base_implementation_type&, const null_buffers&,
socket_base::message_flags, boost::system::error_code& ec)
{
ec = boost::asio::error::operation_not_supported;
return 0;
}
// Start an asynchronous send. The data being sent must be valid for the
// lifetime of the asynchronous operation.
template <typename ConstBufferSequence, typename Handler>
void async_send(base_implementation_type& impl,
const ConstBufferSequence& buffers,
socket_base::message_flags flags, Handler& handler)
{
bool is_continuation =
boost_asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef winrt_socket_send_op<ConstBufferSequence, Handler> op;
typename op::ptr p = { boost::asio::detail::addressof(handler),
boost_asio_handler_alloc_helpers::allocate(
sizeof(op), handler), 0 };
p.p = new (p.v) op(buffers, handler);
BOOST_ASIO_HANDLER_CREATION((p.p, "socket", &impl, "async_send"));
start_send_op(impl,
buffer_sequence_adapter<boost::asio::const_buffer,
ConstBufferSequence>::first(buffers),
flags, p.p, is_continuation);
p.v = p.p = 0;
}
// Start an asynchronous wait until data can be sent without blocking.
template <typename Handler>
void async_send(base_implementation_type&, const null_buffers&,
socket_base::message_flags, Handler& handler)
{
boost::system::error_code ec = boost::asio::error::operation_not_supported;
const std::size_t bytes_transferred = 0;
io_service_.get_io_service().post(
detail::bind_handler(handler, ec, bytes_transferred));
}
// Receive some data from the peer. Returns the number of bytes received.
template <typename MutableBufferSequence>
std::size_t receive(base_implementation_type& impl,
const MutableBufferSequence& buffers,
socket_base::message_flags flags, boost::system::error_code& ec)
{
return do_receive(impl,
buffer_sequence_adapter<boost::asio::mutable_buffer,
MutableBufferSequence>::first(buffers), flags, ec);
}
// Wait until data can be received without blocking.
std::size_t receive(base_implementation_type&, const null_buffers&,
socket_base::message_flags, boost::system::error_code& ec)
{
ec = boost::asio::error::operation_not_supported;
return 0;
}
// Start an asynchronous receive. The buffer for the data being received
// must be valid for the lifetime of the asynchronous operation.
template <typename MutableBufferSequence, typename Handler>
void async_receive(base_implementation_type& impl,
const MutableBufferSequence& buffers,
socket_base::message_flags flags, Handler& handler)
{
bool is_continuation =
boost_asio_handler_cont_helpers::is_continuation(handler);
// Allocate and construct an operation to wrap the handler.
typedef winrt_socket_recv_op<MutableBufferSequence, Handler> op;
typename op::ptr p = { boost::asio::detail::addressof(handler),
boost_asio_handler_alloc_helpers::allocate(
sizeof(op), handler), 0 };
p.p = new (p.v) op(buffers, handler);
BOOST_ASIO_HANDLER_CREATION((p.p, "socket", &impl, "async_receive"));
start_receive_op(impl,
buffer_sequence_adapter<boost::asio::mutable_buffer,
MutableBufferSequence>::first(buffers),
flags, p.p, is_continuation);
p.v = p.p = 0;
}
// Wait until data can be received without blocking.
template <typename Handler>
void async_receive(base_implementation_type&, const null_buffers&,
socket_base::message_flags, Handler& handler)
{
boost::system::error_code ec = boost::asio::error::operation_not_supported;
const std::size_t bytes_transferred = 0;
io_service_.get_io_service().post(
detail::bind_handler(handler, ec, bytes_transferred));
}
protected:
// Helper function to obtain endpoints associated with the connection.
BOOST_ASIO_DECL std::size_t do_get_endpoint(
const base_implementation_type& impl, bool local,
void* addr, std::size_t addr_len, boost::system::error_code& ec) const;
// Helper function to set a socket option.
BOOST_ASIO_DECL boost::system::error_code do_set_option(
base_implementation_type& impl,
int level, int optname, const void* optval,
std::size_t optlen, boost::system::error_code& ec);
// Helper function to get a socket option.
BOOST_ASIO_DECL void do_get_option(
const base_implementation_type& impl,
int level, int optname, void* optval,
std::size_t* optlen, boost::system::error_code& ec) const;
// Helper function to perform a synchronous connect.
BOOST_ASIO_DECL boost::system::error_code do_connect(
base_implementation_type& impl,
const void* addr, boost::system::error_code& ec);
// Helper function to start an asynchronous connect.
BOOST_ASIO_DECL void start_connect_op(
base_implementation_type& impl, const void* addr,
winrt_async_op<void>* op, bool is_continuation);
// Helper function to perform a synchronous send.
BOOST_ASIO_DECL std::size_t do_send(
base_implementation_type& impl, const boost::asio::const_buffer& data,
socket_base::message_flags flags, boost::system::error_code& ec);
// Helper function to start an asynchronous send.
BOOST_ASIO_DECL void start_send_op(base_implementation_type& impl,
const boost::asio::const_buffer& data, socket_base::message_flags flags,
winrt_async_op<unsigned int>* op, bool is_continuation);
// Helper function to perform a synchronous receive.
BOOST_ASIO_DECL std::size_t do_receive(
base_implementation_type& impl, const boost::asio::mutable_buffer& data,
socket_base::message_flags flags, boost::system::error_code& ec);
// Helper function to start an asynchronous receive.
BOOST_ASIO_DECL void start_receive_op(base_implementation_type& impl,
const boost::asio::mutable_buffer& data, socket_base::message_flags flags,
winrt_async_op<Windows::Storage::Streams::IBuffer^>* op,
bool is_continuation);
// The io_service implementation used for delivering completions.
io_service_impl& io_service_;
// The manager that keeps track of outstanding operations.
winrt_async_manager& async_manager_;
// Mutex to protect access to the linked list of implementations.
boost::asio::detail::mutex mutex_;
// The head of a linked list of all implementations.
base_implementation_type* impl_list_;
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#if defined(BOOST_ASIO_HEADER_ONLY)
# include <boost/asio/detail/impl/winrt_ssocket_service_base.ipp>
#endif // defined(BOOST_ASIO_HEADER_ONLY)
#endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
#endif // BOOST_ASIO_DETAIL_WINRT_SSOCKET_SERVICE_BASE_HPP
|
// CChar is either an NPC or a Player.
#include "../../common/resource/CResourceLock.h"
#include "../../common/CException.h"
#include "../../common/CUID.h"
#include "../../common/CRect.h"
#include "../../common/CLog.h"
#include "../../sphere/ProfileTask.h"
#include "../clients/CAccount.h"
#include "../clients/CClient.h"
#include "../items/CItem.h"
#include "../items/CItemContainer.h"
#include "../items/CItemMemory.h"
#include "../items/CItemShip.h"
#include "../items/CItemMulti.h"
#include "../components/CCPropsChar.h"
#include "../components/CCPropsItemChar.h"
#include "../components/CCSpawn.h"
#include "../CContainer.h"
#include "../CSector.h"
#include "../CServer.h"
#include "../CWorld.h"
#include "../CWorldGameTime.h"
#include "../CWorldMap.h"
#include "../CWorldTickingList.h"
#include "../spheresvr.h"
#include "../triggers.h"
#include "CChar.h"
#include "CCharBase.h"
#include "CCharNPC.h"
#include <algorithm>
lpctstr const CChar::sm_szTrigName[CTRIG_QTY+1] = // static
{
"@AAAUNUSED",
"@AfterClick",
"@Attack", // I am attacking someone (SRC)
"@CallGuards",
"@charAttack", // Here starts @charXXX section
"@charClick",
"@charClientTooltip",
"@charClientTooltip_AfterDefault",
"@charContextMenuRequest",
"@charContextMenuSelect",
"@charDClick",
"@charTradeAccepted",
"@Click", // I got clicked on by someone.
"@ClientTooltip", // Sending tooltips to someone
"@ClientTooltip_AfterDefault",
"@CombatAdd",
"@CombatDelete",
"@CombatEnd",
"@CombatStart",
"@ContextMenuRequest",
"@ContextMenuSelect",
"@Create", // Newly created (not in the world yet)
"@CreateLoot",
"@Criminal", // Called before somebody becomes "gray" for someone
"@DClick", // Someone has dclicked on me.
"@Death", //+I just got killed.
"@DeathCorpse",
"@Destroy", //+I am nearly destroyed
"@Dismount", // I am trying to get rid of my ride right now
"@Dye", // My color has been changed
"@Eat",
"@EnvironChange", // my environment changed somehow (light,weather,season,region)
"@ExpChange", // EXP is going to change
"@ExpLevelChange", // Experience LEVEL is going to change
"@Falling", //char is falling from height >= 10
"@FameChange", // Fame changed
"@FollowersUpdate",
"@GetHit", // I just got hit.
"@Hit", // I just hit someone. (TARG)
"@HitCheck", // Checking if I can hit my target, overriding also default checks if set to.
"@HitIgnore", // I'm going to avoid a target (attacker.n.ignore=1) , should I un-ignore him?.
"@HitMiss", // I just missed.
"@HitParry", // I succesfully parried an hit.
"@HitTry", // I am trying to hit someone. starting swing.
"@HouseDesignBegin", // Starting to customize.
"@HouseDesignCommit", // I committed a new house design.
"@HouseDesignCommitItem",// I committed an item to the house design.
"@HouseDesignExit", // I exited house design mode.
// ITRIG_QTY
"@itemAfterClick",
"@itemBuy",
"@itemCarveCorpse", // I am carving a corpse.
"@itemClick", // I clicked on an item
"@itemClientTooltip", // Receiving tooltip for something
"@itemClientTooltip_AfterDefault",
"@itemContextMenuRequest",
"@itemContextMenuSelect",
"@itemCreate", //?
"@itemDamage", //?
"@itemDCLICK", // I have dclicked item
"@itemDestroy", //+I am nearly destroyed
"@itemDropOn_Char", // I have been dropped on this char
"@itemDropOn_Ground", // I dropped an item on the ground
"@itemDropOn_Item", // I have been dropped on this item
"@itemDropOn_Self", // An item has been dropped on
"@ItemDropOn_Trade",
"@itemEQUIP", // I have equipped an item
"@itemEQUIPTEST",
"@itemMemoryEquip",
"@itemPICKUP_GROUND",
"@itemPICKUP_PACK", // picked up from inside some container.
"@itemPICKUP_SELF", // picked up from this container
"@itemPICKUP_STACK", // picked up from a stack
"@itemRedeed",
"@ItemRegionEnter",
"@ItemRegionLeave",
"@itemSELL",
"@itemSmelt", // I am smelting an item.
"@itemSPELL", // cast some spell on the item.
"@itemSTEP", // stepped on an item
"@itemTARGON_CANCEL",
"@itemTARGON_CHAR",
"@itemTARGON_GROUND",
"@itemTARGON_ITEM", // I am being combined with an item
"@itemTimer", //?
"@itemToolTip", // Did tool tips on an item
"@itemUNEQUIP", // i have unequipped (or try to unequip) an item
"@Jailed",
"@KarmaChange", // Karma chaged
"@Kill", //+I have just killed someone
"@LogIn", // Client logs in
"@LogOut", // Client logs out (21)
"@Mount", // I'm trying to mount my horse (or whatever)
"@MurderDecay", // One of my kills is gonna to be cleared
"@MurderMark", // I am gonna to be marked as a murderer
"@NotoSend", // Sending notoriety
"@NPCAcceptItem", // (NPC only) i've been given an item i like (according to DESIRES)
"@NPCActFight",
"@NPCActFollow", // (NPC only) following someone right now
"@NPCAction",
"@NPCActWander", // (NPC only) i'm wandering aimlessly
"@NPCHearGreeting", // (NPC only) i have been spoken to for the first time. (no memory of previous hearing)
"@NPCHearUnknown", //+(NPC only) I heard something i don't understand.
"@NPCLookAtChar", // (NPC only) look at a character
"@NPCLookAtItem", // (NPC only) look at a character
"@NPCLostTeleport", //+(NPC only) ready to teleport back to spawn
"@NPCRefuseItem", // (NPC only) i've been given an item i don't want.
"@NPCRestock", // (NPC only)
"@NPCSeeNewPlayer", //+(NPC only) i see u for the first time. (in 20 minutes) (check memory time)
"@NPCSeeWantItem", // (NPC only) i see something good.
"@NPCSpecialAction", // Idle
"@PartyDisband", //I just disbanded my party
"@PartyInvite", //SRC invited me to join a party, so I may chose
"@PartyLeave",
"@PartyRemove", //I have ben removed from the party by SRC
"@PayGold", // I'm going to give out money for a service (Skill Training, hiring...).
"@PersonalSpace", // +i just got stepped on.
"@PetDesert", // I just went wild again
"@Profile", // someone hit the profile button for me.
"@ReceiveItem", // I was just handed an item (Not yet checked if i want it)
"@RegenStat", // Regenerating any stat
"@RegionEnter",
"@RegionLeave",
"@RegionResourceFound", // I just discovered a resource
"@RegionResourceGather",
"@Rename",
"@Resurrect",
"@SeeCrime", // I saw a crime
"@SeeHidden", // Can I see hidden chars?
"@SeeSnoop",
// SKTRIG_QTY
"@SkillAbort",
"@SkillChange",
"@SkillFail",
"@SkillGain",
"@SkillMakeItem",
"@SkillMenu",
"@SkillPreStart",
"@SkillSelect",
"@SkillStart",
"@SkillStroke",
"@SkillSuccess",
"@SkillTargetCancel",
"@SkillUseQuick",
"@SkillWait",
"@SpellBook",
"@SpellCast", // Char is casting a spell.
"@SpellEffect", // A spell just hit me.
"@SpellEffectAdd", // A spell memory item is going to be placed upon me.
"@SpellEffectRemove", // A spell memory item is going to be removed from me.
"@SpellEffectTick", // A spell is going to tick and have an effect on me.
"@SpellFail", // The spell failed
"@SpellSelect", // Selected a spell
"@SpellSuccess", // The spell succeeded
"@SpellTargetCancel", // cancelled spell target
"@StatChange",
"@StepStealth", // Made a step in stealth mode
"@Targon_Cancel", //closing target from TARGETF*
"@ToggleFlying", //Flying On/Off
"@ToolTip", // someone did tool tips on me.
"@TradeAccepted", // Everything went well, and we are about to exchange trade items
"@TradeClose",
"@TradeCreate",
"@UserBugReport",
"@UserChatButton",
"@UserExtCmd",
"@UserExWalkLimit",
"@UserGuildButton",
"@UserKRToolbar",
"@UserMailBag",
"@UserQuestArrowClick",
"@UserQuestButton",
"@UserSkills",
"@UserSpecialMove",
"@UserStats",
"@UserUltimaStoreButton",
"@UserVirtue",
"@UserVirtueInvoke",
"@UserWarmode", // War mode ?
nullptr
};
/////////////////////////////////////////////////////////////////
// -CChar
// Create the "basic" NPC. Not NPC or player yet.
// NOTE: NEVER return nullptr
CChar * CChar::CreateBasic(CREID_TYPE baseID) // static
{
ADDTOCALLSTACK("CChar::CreateBasic");
CChar *pChar = new CChar(baseID);
return pChar;
}
CChar::CChar( CREID_TYPE baseID ) :
CTimedObject(PROFILE_CHARS),
CObjBase( false ),
m_sTitle(false),
m_Skill{}, m_Stat{}
{
g_Serv.StatInc( SERV_STAT_CHARS ); // Count created CChars.
m_pArea = nullptr;
m_pParty = nullptr;
m_pClient = nullptr; // is the char a logged in player?
m_pPlayer = nullptr; // May even be an off-line player!
m_pNPC = nullptr;
m_pRoom = nullptr;
_uiStatFlag = 0;
if ( g_World.m_fSaveParity )
StatFlag_Set(STATF_SAVEPARITY); // It will get saved next time.
m_dirFace = DIR_SE;
m_fonttype = FONT_NORMAL;
m_SpeechHueOverride = 0;
m_EmoteHueOverride = 0;
m_exp = 0;
m_level = 0;
m_defense = 0;
m_height = 0;
m_ModMaxWeight = 0;
_uiRange = RANGE_MAKE(1, 0); // RangeH = 1; RangeL = 0
m_StepStealth = 0;
m_iVisualRange = UO_MAP_VIEW_SIZE_DEFAULT;
m_virtualGold = 0;
_iTimePeriodicTick = 0;
_iTimeCreate = _iTimeLastHitsUpdate = CWorldGameTime::GetCurrentTime().GetTimeRaw();
_iTimeNextRegen = _iTimeLastHitsUpdate + MSECS_PER_SEC; // make it regen in one second from now, no need to instant regen.
_iRegenTickCount = 0;
_iTimeLastCallGuards = 0;
m_zClimbHeight = 0;
m_fClimbUpdated = false;
_wPrev_Hue = HUE_DEFAULT;
_iPrev_id = CREID_INVALID;
SetID( baseID );
CCharBase* pCharDef = Char_GetDef();
ASSERT(pCharDef);
m_attackBase = pCharDef->m_attackBase;
m_attackRange = pCharDef->m_attackRange;
m_defenseBase = pCharDef->m_defenseBase;
m_defenseRange = pCharDef->m_defenseRange;
_wBloodHue = pCharDef->_wBloodHue; // when damaged , what color is the blood (-1) = no blood
SetName( pCharDef->GetTypeName()); // set the name in case there is a name template.
Stat_SetVal( STAT_FOOD, Stat_GetMaxAdjusted(STAT_FOOD) );
m_uiFame = 0;
m_iKarma = 0;
m_Act_Difficulty = 0;
m_Act_SkillCurrent = SKILL_NONE;
m_atUnk.m_dwArg1 = 0;
m_atUnk.m_dwArg2 = 0;
m_atUnk.m_dwArg3 = 0;
g_World.m_uidLastNewChar = GetUID(); // for script access.
// SubscribeComponent Prop Components
TrySubscribeComponentProps<CCPropsChar>();
TrySubscribeComponentProps<CCPropsItemChar>();
// SubscribeComponent regular Components
SubscribeComponent(new CCFaction());
ASSERT(IsDisconnected());
}
// Delete character
CChar::~CChar()
{
EXC_TRY("Cleanup in destructor");
ADDTOCALLSTACK("CChar::~CChar");
CChar::DeletePrepare();
CChar::DeleteCleanup(true);
if (IsClientActive()) // this should never happen.
{
ASSERT( m_pClient );
m_pClient->GetNetState()->markReadClosed();
}
if (m_pParty)
{
m_pParty->RemoveMember( GetUID(), GetUID() );
m_pParty = nullptr;
}
Guild_Resign(MEMORY_GUILD);
Guild_Resign(MEMORY_TOWN);
Attacker_RemoveChar(); // Removing me from enemy's attacker list (I asume that if he is on my list, I'm on his one and no one have me on their list if I dont have them)
if (m_pNPC)
NPC_PetClearOwners(); // Clear follower slots on pet owner
ClearNPC();
ClearPlayer();
g_Serv.StatDec( SERV_STAT_CHARS );
EXC_CATCH;
}
void CChar::DeleteCleanup(bool fForce)
{
ADDTOCALLSTACK("CChar::DeleteCleanup");
_fDeleting = true;
// We don't want to have invalid pointers over there
// Already called by CObjBase::DeletePrepare -> CObjBase::_GoSleep
//CWorldTickingList::DelObjSingle(this);
//CWorldTickingList::DelObjStatusUpdate(this, false);
CWorldTickingList::DelCharPeriodic(this, false);
if (IsStatFlag(STATF_RIDDEN))
{
CItem* pItem = Horse_GetMountItem();
if (pItem)
{
pItem->m_itFigurine.m_UID.InitUID(); // unlink it first.
pItem->Delete(fForce);
}
StatFlag_Clear(STATF_RIDDEN);
}
}
// Called before Delete()
// @Destroy or f_onchar_delete can prevent the deletion
bool CChar::NotifyDelete()
{
ADDTOCALLSTACK("CChar::NotifyDelete");
if (IsDeleted())
return false;
// Checking for delete allowed in @Destroy
if (IsTrigUsed(TRIGGER_DESTROY))
{
//We can forbid the deletion in here with no pain
if (CChar::OnTrigger(CTRIG_Destroy, &g_Serv) == TRIGRET_RET_TRUE)
return false;
}
// If this is a player, check for f_onchar_delete
if (m_pClient)
{
TRIGRET_TYPE trigReturn;
CScriptTriggerArgs Args;
Args.m_pO1 = m_pClient;
r_Call("f_onchar_delete", this, &Args, nullptr, &trigReturn);
if (trigReturn == TRIGRET_RET_TRUE)
return false;
}
// Clear follower slots on pet owner
if (m_pNPC)
NPC_PetClearOwners();
ContentNotifyDelete();
return true;
}
void CChar::DeletePrepare()
{
ADDTOCALLSTACK("CChar::DeletePrepare");
CContainer::ContentDelete(true); // This object and its contents need to be deleted on the same tick
CObjBase::DeletePrepare();
}
bool CChar::Delete(bool fForce)
{
ADDTOCALLSTACK("CChar::Delete");
if ((NotifyDelete() == false) && !fForce)
return false;
// Character has been deleted
if (IsClientActive())
{
CClient* pClient = GetClientActive();
pClient->CharDisconnect();
pClient->GetNetState()->markReadClosed();
}
DeleteCleanup(fForce); // not virtual
return CObjBase::Delete();
}
// Client is detaching from this CChar.
void CChar::ClientDetach()
{
ADDTOCALLSTACK("CChar::ClientDetach");
// remove all trade windows.
for (CSObjContRec* pObjRec : GetIterationSafeCont())
{
CItem* pItem = static_cast<CItem*>(pObjRec);
if (pItem->IsType(IT_EQ_TRADE_WINDOW) )
pItem->Delete();
}
if ( !IsClientActive() )
return;
if ( m_pParty && m_pParty->IsPartyMaster( this ))
{
// Party must disband if the master is logged out.
m_pParty->Disband(GetUID());
m_pParty = nullptr;
}
// If this char is on a IT_SHIP then we need to stop the ship !
if ( m_pArea && m_pArea->IsFlag( REGION_FLAG_SHIP ))
{
CItemShip * pShipItem = dynamic_cast <CItemShip *>( m_pArea->GetResourceID().ItemFindFromResource());
if ( pShipItem )
pShipItem->Stop();
}
m_pClient = nullptr;
}
// Client is Attaching to this CChar.
void CChar::ClientAttach( CClient * pClient )
{
ADDTOCALLSTACK("CChar::ClientAttach");
if ( GetClientActive() == pClient )
return;
if ( ! SetPlayerAccount( pClient->GetAccount())) // i now own this char.
return;
ASSERT(m_pPlayer);
m_pPlayer->_iTimeLastUsed = CWorldGameTime::GetCurrentTime().GetTimeRaw();
m_pClient = pClient;
FixClimbHeight();
}
bool CChar::IsClientType() const noexcept
{
return (m_pClient || m_pPlayer);
}
// Client logged out or NPC is dead.
void CChar::SetDisconnected(CSector* pNewSector)
{
ADDTOCALLSTACK("CChar::SetDisconnected");
if (IsClientActive())
{
GetClientActive()->GetNetState()->markReadClosed();
}
if (m_pPlayer)
{
m_pPlayer->_iTimeLastDisconnected = CWorldGameTime::GetCurrentTime().GetTimeRaw();
}
if (m_pParty)
{
m_pParty->RemoveMember( GetUID(), GetUID() );
m_pParty = nullptr;
}
if ( IsDisconnected() )
return;
// If the char goes offline, we don't want its items to tick anymore when the timer expires.
_GoSleep();
RemoveFromView(); // Remove from views.
MoveToRegion(nullptr, false);
CSector* pCurSector = GetTopPoint().GetSector();
if (pNewSector && (pNewSector != pCurSector))
{
pNewSector->m_Chars_Disconnect.AddCharDisconnected(this);
}
else
{
ASSERT(pCurSector);
pCurSector->m_Chars_Disconnect.AddCharDisconnected(this);
}
}
void CChar::ClearPlayer()
{
ADDTOCALLSTACK("CChar::ClearPlayer");
if ( m_pPlayer == nullptr )
return;
CAccount* pAccount = m_pPlayer->GetAccount();
if (!pAccount)
{
g_Log.EventError("Player '%s' (UID 0%x) not attached to account?\n", GetName(), (dword)GetUID());
}
else
{
if (g_Serv.GetServerMode() != SERVMODE_Exiting)
{
g_Log.EventWarn("Player delete '%s' name from account '%s'.\n", GetName(), pAccount->GetName());
}
pAccount->DetachChar(this); // unlink me from my account.
}
delete m_pPlayer;
m_pPlayer = nullptr;
}
// Set up the char as a Player.
bool CChar::SetPlayerAccount(CAccount *pAccount)
{
ADDTOCALLSTACK("CChar::SetPlayerAccount");
if ( !pAccount )
return false;
if ( m_pPlayer )
{
if ( m_pPlayer->GetAccount() == pAccount )
return true;
DEBUG_ERR(("SetPlayerAccount '%s' already set '%s' != '%s'!\n", GetName(), m_pPlayer->GetAccount()->GetName(), pAccount->GetName()));
return false;
}
if ( m_pNPC )
{
// This could happen if the account is set manually through
// scripts
ClearNPC();
}
m_pPlayer = new CCharPlayer(this, pAccount);
pAccount->AttachChar(this);
return true;
}
bool CChar::SetPlayerAccount( lpctstr pszAccName )
{
ADDTOCALLSTACK("CChar::SetPlayerAccount");
CAccount * pAccount = g_Accounts.Account_Find( pszAccName );
if ( pAccount == nullptr )
{
DEBUG_ERR(( "Trying to attach Char '%s' to unexistent Account '%s'!\n", GetName(), pszAccName ));
return false;
}
return( SetPlayerAccount( pAccount ));
}
// Set up the char as an NPC
bool CChar::SetNPCBrain( NPCBRAIN_TYPE NPCBrain )
{
ADDTOCALLSTACK("CChar::SetNPCBrain");
if ( NPCBrain == NPCBRAIN_NONE )
return false;
if ( m_pPlayer != nullptr )
{
if ( m_pPlayer->GetAccount() != nullptr )
DEBUG_ERR(( "SetNPCBrain to Player Account '%s'\n", m_pPlayer->GetAccount()->GetName() ));
else
DEBUG_ERR(( "SetNPCBrain to Player Name '%s'\n", GetName()));
return false;
}
if ( m_pNPC == nullptr )
m_pNPC = new CCharNPC( this, NPCBrain );
else
m_pNPC->m_Brain = NPCBrain; // just replace existing brain
return true;
}
// Is there something wrong with this char?
// RETURN: invalid code.
int CChar::IsWeird() const
{
ADDTOCALLSTACK_INTENSIVE("CChar::IsWeird");
int iResultCode = CObjBase::IsWeird();
if ( iResultCode )
return iResultCode;
if ( IsDisconnected())
{
if ( ! GetTopSector()->IsCharDisconnectedIn( this ))
{
iResultCode = 0x1102;
return iResultCode;
}
if ( m_pNPC )
{
if ( IsStatFlag( STATF_RIDDEN ))
{
if ( Skill_GetActive() != NPCACT_RIDDEN )
{
iResultCode = 0x1103;
return iResultCode;
}
// Make sure we are still linked back to the world.
if ( Horse_GetMountItem() == nullptr )
{
iResultCode = 0x1104;
return iResultCode;
}
}
else
{
if ( ! IsStatFlag( STATF_DEAD ))
{
iResultCode = 0x1106;
return iResultCode;
}
}
}
}
if ( ! m_pPlayer && ! m_pNPC )
{
iResultCode = 0x1107;
return iResultCode;
}
if ( ! GetTopPoint().IsValidPoint())
{
iResultCode = 0x1108;
return iResultCode;
}
return 0;
}
// Get the Z we should be at
char CChar::GetFixZ( const CPointMap& pt, dword dwBlockFlags)
{
const dword dwCanFlags = GetCanFlags();
const dword dwCanMoveFlags = GetCanMoveFlags(dwCanFlags);
if ( !dwBlockFlags )
dwBlockFlags = dwCanMoveFlags;
if (dwCanMoveFlags == 0xFFFFFFFF)
return pt.m_z;
if (dwCanMoveFlags & CAN_C_WALK )
dwBlockFlags |= CAN_I_CLIMB; // If we can walk than we can climb. Ignore CAN_C_FLY at all here
const short iZClimbed = pt.m_z + m_zClimbHeight;
const height_t uiHeightMount = GetHeightMount( false );
const int iBlockMaxHeight = std::max(int(iZClimbed + uiHeightMount), int(INT8_MAX));
const height_t uiClimbHeight = height_t(std::max(short(iZClimbed + 2), short(UINT8_MAX)));
CServerMapBlockState block( dwBlockFlags, pt.m_z, iBlockMaxHeight, uiClimbHeight, uiHeightMount );
CWorldMap::GetFixPoint( pt, block );
dwBlockFlags = block.m_Bottom.m_dwBlockFlags;
if ( block.m_Top.m_dwBlockFlags )
{
dwBlockFlags |= CAN_I_ROOF; // we are covered by something.
if ( block.m_Top.m_z < (iZClimbed + ((block.m_Top.m_dwTile > TERRAIN_QTY) ? uiHeightMount : uiHeightMount/2 )) )
dwBlockFlags |= CAN_I_BLOCK; // we can't fit under this!
}
if ( dwBlockFlags != 0x0 )
{
if ( (dwBlockFlags & CAN_I_DOOR) && Can(CAN_C_GHOST, dwCanFlags) )
dwBlockFlags &= ~CAN_I_BLOCK;
if ( (dwBlockFlags & CAN_I_WATER) && Can(CAN_C_SWIM, dwCanFlags) )
dwBlockFlags &= ~CAN_I_BLOCK;
if ( !Can(CAN_C_FLY, dwCanFlags) )
{
if ( ! ( dwBlockFlags & CAN_I_CLIMB ) ) // we can climb anywhere
{
if ( block.m_Bottom.m_dwTile > TERRAIN_QTY )
{
if ( block.m_Bottom.m_z > uiClimbHeight) // Too high to climb.
return pt.m_z;
}
else
{
if (block.m_Bottom.m_z > (iZClimbed + uiHeightMount + 3))
return pt.m_z;
}
}
}
if ( (dwBlockFlags & CAN_I_BLOCK) && !Can(CAN_C_PASSWALLS, dwCanFlags) )
return pt.m_z;
if ( block.m_Bottom.m_z >= UO_SIZE_Z )
return pt.m_z;
}
if ( (uiHeightMount + pt.m_z >= block.m_Top.m_z) && g_Cfg.m_iMountHeight && !IsPriv(PRIV_ALLMOVE) )
return pt.m_z;
return block.m_Bottom.m_z;
}
/*
bool CChar::_IsStatFlag(uint64 uiStatFlag) const noexcept
{
return (_uiStatFlag & uiStatFlag);
}
*/
bool CChar::IsStatFlag( uint64 uiStatFlag) const noexcept
{
// THREAD_SHARED_LOCK_SET;
return (_uiStatFlag & uiStatFlag);
}
/*
void CChar::_StatFlag_Set( uint64 uiStatFlag) noexcept
{
_uiStatFlag |= uiStatFlag;
}
*/
void CChar::StatFlag_Set(uint64 uiStatFlag) noexcept
{
// THREAD_UNIQUE_LOCK_SET;
_uiStatFlag |= uiStatFlag;
}
/*
void CChar::_StatFlag_Clear(uint64 uiStatFlag) noexcept
{
_uiStatFlag &= ~uiStatFlag;
}
*/
void CChar::StatFlag_Clear(uint64 uiStatFlag) noexcept
{
// THREAD_UNIQUE_LOCK_SET;
_uiStatFlag &= ~uiStatFlag;
}
/*
void CChar::_StatFlag_Mod(uint64 uiStatFlag, bool fMod) noexcept
{
if ( fMod )
_uiStatFlag |= uiStatFlag;
else
_uiStatFlag &= ~uiStatFlag;
}
*/
void CChar::StatFlag_Mod(uint64 uiStatFlag, bool fMod) noexcept
{
// THREAD_UNIQUE_LOCK_SET;
// _StatFlag_Mod(uiStatFlag, fMod);
if (fMod)
_uiStatFlag |= uiStatFlag;
else
_uiStatFlag &= ~uiStatFlag;
}
bool CChar::IsPriv( word flag ) const
{
// PRIV_GM flags
if ( m_pPlayer == nullptr )
return false; // NPC's have no privs.
return m_pPlayer->GetAccount()->IsPriv( flag );
}
PLEVEL_TYPE CChar::GetPrivLevel() const
{
// The higher the better. // PLEVEL_Counsel
if ( ! m_pPlayer )
return PLEVEL_Player;
return m_pPlayer->GetAccount()->GetPrivLevel();
}
CCharBase * CChar::Char_GetDef() const
{
return static_cast <CCharBase*>( Base_GetDef() );
}
CRegionWorld * CChar::GetRegion() const
{
return m_pArea; // What region are we in now. (for guarded message)
}
CRegion * CChar::GetRoom() const
{
return m_pRoom; // What room are we in now.
}
int CChar::GetVisualRange() const
{
return (int)m_iVisualRange;
}
void CChar::SetVisualRange(byte newSight)
{
CClient* pClient;
{
THREAD_UNIQUE_LOCK_SET;
// max value is 18 on classic clients prior 7.0.55.27 version and 24 on enhanced clients and latest classic clients
m_iVisualRange = minimum(newSight, UO_MAP_VIEW_SIZE_MAX);
pClient = GetClientActive();
}
if (pClient)
{
pClient->addVisualRange(m_iVisualRange);
pClient->addReSync();
}
}
// Clean up weird flags.
// fix Weirdness.
// NOTE:
// Deleting a player char is VERY BAD ! Be careful !
//
// RETURN: false = i can't fix this.
int CChar::FixWeirdness()
{
ADDTOCALLSTACK("CChar::FixWeirdness");
int iResultCode = CObjBase::IsWeird();
if ( iResultCode )
// Not recoverable - must try to delete the object.
return iResultCode;
// NOTE: Stats and skills may go negative temporarily.
const CCharBase * pCharDef = Char_GetDef();
// Make sure my flags are good.
if ( IsStatFlag( STATF_HASSHIELD ))
{
const CItem * pShield = LayerFind( LAYER_HAND2 );
if ( pShield == nullptr )
StatFlag_Clear( STATF_HASSHIELD );
}
if ( IsStatFlag( STATF_ONHORSE ))
{
const CItem * pHorse = LayerFind( LAYER_HORSE );
if ( pHorse == nullptr )
StatFlag_Clear( STATF_ONHORSE );
}
if ( IsStatFlag( STATF_SPAWNED ))
{
if (!GetSpawn())
StatFlag_Clear( STATF_SPAWNED );
}
if ( IsStatFlag( STATF_PET ))
{
const CItemMemory *pMemory = Memory_FindTypes( MEMORY_IPET );
if ( pMemory == nullptr )
StatFlag_Clear( STATF_PET );
}
if ( IsStatFlag( STATF_RIDDEN ))
{
// Move the ridden creature to the same location as it's rider.
if ( m_pPlayer || ! IsDisconnected())
StatFlag_Clear( STATF_RIDDEN );
else
{
if ( Skill_GetActive() != NPCACT_RIDDEN )
{
iResultCode = 0x1203;
return iResultCode;
}
const CItem * pFigurine = Horse_GetValidMountItem();
if ( pFigurine == nullptr )
{
iResultCode = 0x1204;
return iResultCode;
}
const CPointMap& pt = pFigurine->GetTopLevelObj()->GetTopPoint();
if ( pt != GetTopPoint())
{
MoveToChar( pt, true, true );
SetDisconnected();
}
}
}
if ( IsStatFlag( STATF_CRIMINAL ))
{
const CItem * pMemory = LayerFind( LAYER_FLAG_Criminal );
if ( pMemory == nullptr )
StatFlag_Clear( STATF_CRIMINAL );
}
if ( ! IsIndividualName() && pCharDef->GetTypeName()[0] == '#' )
SetName( pCharDef->GetTypeName());
if ( m_pPlayer ) // Player char.
{
Memory_ClearTypes( MEMORY_IPET );
StatFlag_Clear( STATF_RIDDEN );
if ( m_pPlayer->GetSkillClass() == nullptr ) // this should never happen.
{
m_pPlayer->SetSkillClass( this, CResourceID( RES_SKILLCLASS ));
ASSERT(m_pPlayer->GetSkillClass());
}
// Make sure players don't get ridiculous stats.
// m_iOverSkillMultiply disables this check if set to < 1
if (( GetPrivLevel() <= PLEVEL_Player ) && ( g_Cfg.m_iOverSkillMultiply > 0 ))
{
for ( size_t i = 0; i < g_Cfg.m_iMaxSkill; ++i )
{
const ushort uiSkillMax = Skill_GetMax((SKILL_TYPE)i);
const ushort uiSkillVal = Skill_GetBase((SKILL_TYPE)i);
if ( uiSkillVal > uiSkillMax * g_Cfg.m_iOverSkillMultiply )
Skill_SetBase((SKILL_TYPE)i, uiSkillMax);
}
// ??? What if magically enhanced !!!
if ( IsPlayableCharacter() && ( GetPrivLevel() < PLEVEL_Counsel ) && !IsStatFlag( STATF_POLYMORPH ))
{
for ( int j = STAT_STR; j < STAT_BASE_QTY; ++j )
{
const ushort uiStatMax = Stat_GetLimit((STAT_TYPE)j);
if ( Stat_GetAdjusted((STAT_TYPE)j) > (uiStatMax * g_Cfg.m_iOverSkillMultiply) )
Stat_SetBase((STAT_TYPE)j, uiStatMax);
}
}
}
}
else
{
if ( ! m_pNPC )
{
iResultCode = 0x1205;
return iResultCode;
}
// An NPC. Don't keep track of unused skills.
for ( size_t i = 0; i < g_Cfg.m_iMaxSkill; ++i )
{
if ( m_Skill[i] > 0 && m_Skill[i] < g_Cfg.m_iSaveNPCSkills )
Skill_SetBase((SKILL_TYPE)i, 0);
}
}
if ( _GetTimerSAdjusted() > 60*60 )
_SetTimeout(1); // unreasonably long for a char?
return IsWeird();
}
// Creating a new char. (Not loading from save file) Make sure things are set to reasonable values.
void CChar::CreateNewCharCheck()
{
ADDTOCALLSTACK("CChar::CreateNewCharCheck");
_iPrev_id = GetID();
_wPrev_Hue = GetHue();
Stat_SetVal(STAT_STR, Stat_GetMaxAdjusted(STAT_STR));
Stat_SetVal(STAT_DEX, Stat_GetMaxAdjusted(STAT_DEX));
Stat_SetVal(STAT_INT, Stat_GetMaxAdjusted(STAT_INT));
if ( !m_pPlayer ) // need a starting brain tick.
{
// auto-set EXP/LEVEL level
if ( g_Cfg.m_bExperienceSystem && g_Cfg.m_iExperienceMode&EXP_MODE_AUTOSET_EXP )
{
if ( !m_exp )
{
CCharBase *pCharDef = Char_GetDef();
int mult = (Stat_GetMaxAdjusted(STAT_STR) + (Stat_GetMaxAdjusted(STAT_DEX) / 2) + Stat_GetMaxAdjusted(STAT_INT)) / 3;
ushort iSkillArchery = Skill_GetBase(SKILL_ARCHERY), iSkillThrowing = Skill_GetBase(SKILL_THROWING), iSkillSwordsmanship = Skill_GetBase(SKILL_SWORDSMANSHIP);
ushort iSkillMacefighting = Skill_GetBase(SKILL_MACEFIGHTING), iSkillFencing = Skill_GetBase(SKILL_FENCING), iSkillWrestling = Skill_GetBase(SKILL_WRESTLING);
m_exp = maximum(
iSkillArchery,
maximum(iSkillThrowing,
maximum(iSkillSwordsmanship,
maximum(iSkillMacefighting,
maximum(iSkillFencing,
iSkillWrestling))))
) +
(Skill_GetBase(SKILL_TACTICS) / 4) +
(Skill_GetBase(SKILL_PARRYING) / 4) +
(Skill_GetBase(SKILL_MAGERY) / 3) +
(Skill_GetBase(SKILL_PROVOCATION) / 4) +
(Skill_GetBase(SKILL_PEACEMAKING) / 4) +
(Skill_GetBase(SKILL_TAMING) / 4) +
(pCharDef->m_defense * 3) +
(pCharDef->m_attackBase * 6)
;
m_exp = (m_exp * mult) / 100;
}
if ( !m_level && g_Cfg.m_bLevelSystem && ( m_exp > g_Cfg.m_iLevelNextAt ))
ChangeExperience();
}
_SetTimeout(1);
}
}
bool CChar::DupeFrom(const CChar * pChar, bool fNewbieItems )
{
// CChar part
if ( !pChar )
return false;
m_pArea = pChar->m_pArea;
m_pRoom = pChar->m_pRoom;
_uiStatFlag = pChar->_uiStatFlag;
if ( g_World.m_fSaveParity )
StatFlag_Set(STATF_SAVEPARITY); // It will get saved next time.
m_dirFace = pChar->m_dirFace;
m_fonttype = pChar->m_fonttype;
m_SpeechHueOverride = pChar->m_SpeechHueOverride;
m_EmoteHueOverride = pChar->m_EmoteHueOverride;
m_StepStealth = pChar->m_StepStealth;
m_iVisualRange = pChar->m_iVisualRange;
m_virtualGold = pChar->m_virtualGold;
m_exp = pChar->m_exp;
m_level = pChar->m_level;
m_defense = pChar->m_defense;
m_height = pChar->m_height;
m_ModMaxWeight = pChar->m_ModMaxWeight;
_uiRange = pChar->_uiRange;
m_atUnk.m_dwArg1 = pChar->m_atUnk.m_dwArg1;
m_atUnk.m_dwArg2 = pChar->m_atUnk.m_dwArg2;
m_atUnk.m_dwArg3 = pChar->m_atUnk.m_dwArg3;
_iTimeNextRegen = pChar->_iTimeNextRegen;
_iTimeCreate = pChar->_iTimeCreate;
_iTimeLastHitsUpdate = pChar->_iTimeLastHitsUpdate;
_wPrev_Hue = pChar->_wPrev_Hue;
SetHue(pChar->GetHue());
_iPrev_id = pChar->_iPrev_id;
SetID( pChar->GetID() );
m_CanMask = pChar->m_CanMask;
_wBloodHue = pChar->_wBloodHue;
//m_totalweight = 0;
Skill_Cleanup();
for ( uint i = 0; i < STAT_QTY; ++i )
{
m_Stat[i] = pChar->m_Stat[i];
}
for ( uint i = 0; i < g_Cfg.m_iMaxSkill; ++i )
{
m_Skill[i] = pChar->m_Skill[i];
}
m_fClimbUpdated = pChar->m_fClimbUpdated;
/*if ( m_pNPC )
{
if (pChar->m_pNPC)
m_pNPC->m_Speech.Copy(&(pChar->m_pNPC->m_Speech));
else
m_pNPC->m_Speech.Copy(&(pChar->m_pPlayer->m_Speech));
}else{
if (pChar->m_pNPC)
m_pPlayer->m_Speech.Copy(&(pChar->m_pNPC->m_Speech));
else
m_pPlayer->m_Speech.Copy(&(pChar->m_pPlayer->m_Speech));
}*/
if (m_pNPC && pChar->m_pNPC)
{
m_pNPC->m_Brain = pChar->m_pNPC->m_Brain;
//m_pNPC->m_bonded = pChar->m_pNPC->m_bonded;
}
FixWeirdness();
SetName( pChar->GetName()); // SetName after FixWeirdness, otherwise it can be replaced again.
// We copy tags,etc first and place it because of NPC_LoadScript and @Create trigger, so it have information before calling it
m_TagDefs.Copy( &( pChar->m_TagDefs ) );
m_BaseDefs.Copy( &( pChar->m_BaseDefs ) );
//m_OEvents.Copy(&(pChar->m_OEvents));
m_OEvents = pChar->m_OEvents;
//NPC_LoadScript( false ); //Calling it now so everything above can be accessed and overrided in the @Create
//Not calling NPC_LoadScript() because, in some part, it's breaking the name and looking for template names.
// end of CChar
CEntity::Copy(pChar);
CEntityProps::Copy(pChar);
const CUID& myUID(GetUID());
g_World.m_uidLastNewChar = myUID; // for script access.
// Begin copying items.
for ( int i = 0 ; i < LAYER_QTY; ++i)
{
LAYER_TYPE layer = (LAYER_TYPE)i;
CItem * myLayer = LayerFind(layer);
if ( myLayer )
myLayer->Delete();
CItem * fromLayer = pChar->LayerFind( layer );
if ( !fromLayer )
continue;
CItem * pItem = CItem::CreateDupeItem(fromLayer, this, true);
pItem->LoadSetContainer(myUID, layer);
if ( fNewbieItems )
{
pItem->SetAttr(ATTR_NEWBIE);
if (pItem->IsType(IT_CONTAINER) )
{
CItemContainer* pContainer = static_cast<CItemContainer*>(pItem);
for (CSObjContRec* pObjRec : *pContainer)
{
CItem* pItemCont = static_cast<CItem*>(pObjRec);
pItemCont->SetAttr(ATTR_NEWBIE);
const CChar *pTest = CUID::CharFindFromUID(pItemCont->m_itNormal.m_more1);
if (pTest && pTest == pChar)
pItemCont->m_itNormal.m_more1 = myUID;
const CChar *pTest2 = CUID::CharFindFromUID(pItemCont->m_itNormal.m_more2);
if ( pTest2 && pTest2 == pChar )
pItemCont->m_itNormal.m_more2 = myUID;
const CChar *pTest3 = CUID::CharFindFromUID(pItemCont->m_uidLink);
if ( pTest3 && pTest3 == pChar )
pItemCont->m_uidLink = myUID;
}
}
}
const CChar * pTest = CUID::CharFindFromUID(pItem->m_itNormal.m_more1);
if ( pTest && pTest == pChar)
pItem->m_itNormal.m_more1 = myUID;
const CChar * pTest2 = CUID::CharFindFromUID(pItem->m_itNormal.m_more2);
if (pTest2)
{
if (pTest2 == pChar)
pItem->m_itNormal.m_more2 = myUID;
else if ( pTest2->NPC_IsOwnedBy(pChar, true) ) // Mount's fix
{
if ( fNewbieItems ) // Removing any mount references for the memory, so when character dies or dismounts ... no mount will appear.
pItem->m_itNormal.m_more2 = 0;
else // otherwise we create a full new character.
{
pItem->m_itNormal.m_more2 = 0; // more2 should be cleared before removing the memory or the real npc will be removed too.
pItem->Delete(true);
CChar * pChar2 = CreateNPC( pTest2->GetID());
pChar2->SetTopPoint( pChar->GetTopPoint() ); // Moving the mount again because the dupe will place it in the same place as the 'invisible & disconnected' original (usually far away from where the guy will be, so the duped char can't touch the mount).
pChar2->DupeFrom(pTest2, fNewbieItems);
pChar2->NPC_PetSetOwner(this);
Horse_Mount(pChar2);
}
}
}
CChar * pTest3 = CUID::CharFindFromUID(pItem->m_uidLink);
if (pTest3)
{
if (pTest3 == pChar)
pItem->m_uidLink = myUID; //If the character being duped has an item which linked to himself, set the newly duped character link instead.
else if (IsSetOF(OF_PetSlots) && pItem->IsMemoryTypes(MEMORY_IPET) && pTest3 == NPC_PetGetOwner())
{
const short iFollowerSlots = (short)GetDefNum("FOLLOWERSLOTS", true, 1);
//If we have reached the maximum follower slots we remove the ownership of the pet by clearing the memory flag instead of using NPC_PetClearOwners().
if (!pTest3->FollowersUpdate(this, maximum(0, iFollowerSlots)))
Memory_ClearTypes(MEMORY_IPET);
}
}
}
// End copying items.
FixWeight();
if (!pChar->IsSleeping())
{
_GoAwake();
}
//g_World.m_uidNew stored the last duped item, so we need to set back again the newly duped character.
g_World.m_uidNew.SetObjUID(GetUID());
Update();
return true;
}
// Reading triggers from CHARDEF
bool CChar::ReadScriptReducedTrig(CCharBase * pCharDef, CTRIG_TYPE trig, bool fVendor)
{
ADDTOCALLSTACK("CChar::ReadScriptReducedTrig");
if ( !pCharDef || !pCharDef->HasTrigger(trig) )
return false;
CResourceLock s;
if ( !pCharDef->ResourceLock(s) || !OnTriggerFind(s, sm_szTrigName[trig]) )
return false;
return ReadScriptReduced(s, fVendor);
}
// If this is a regen they will have a pack already.
// RETURN:
// true = default return. (mostly ignored).
bool CChar::ReadScriptReduced(CResourceLock &s, bool fVendor)
{
ADDTOCALLSTACK("CChar::ReadScriptReduced");
bool fFullInterp = false;
bool fBlockItemAttr = false; //Set a temporary boolean to block item attributes to set on Character.
CItem * pItem = nullptr;
while ( s.ReadKeyParse() )
{
if ( s.IsKeyHead("ON", 2) )
break;
int iCmd = FindTableSorted(s.GetKey(), CItem::sm_szTemplateTable, CountOf(CItem::sm_szTemplateTable)-1);
bool fItemCreation = false;
if ( fVendor )
{
if (iCmd != -1)
{
switch ( iCmd )
{
case ITC_BUY:
case ITC_SELL:
{
fBlockItemAttr = false; //Make sure we reset the value, if the last input is not a ITEM(NEWBIE) or CONTAINER.
CItemContainer * pCont = GetBank((iCmd == ITC_SELL) ? LAYER_VENDOR_STOCK : LAYER_VENDOR_BUYS );
if ( pCont )
{
pItem = CItem::CreateHeader(s.GetArgRaw(), pCont, false);
if ( pItem )
pItem->m_TagDefs.SetNum("NOSAVE", 1);
}
pItem = nullptr;
continue;
}
case ITC_ITEM:
case ITC_CONTAINER:
case ITC_ITEMNEWBIE:
fBlockItemAttr = true; //Set the value to block next Color or Attribute inputs for items.
pItem = nullptr;
continue;
default:
fBlockItemAttr = false; //Make sure we reset the value, if the last input is not a ITEM(NEWBIE) or CONTAINER.
pItem = nullptr;
continue;
}
}
}
else
{
switch ( iCmd )
{
case ITC_FULLINTERP:
{
lpctstr pszArgs = s.GetArgStr();
GETNONWHITESPACE(pszArgs);
fFullInterp = ( *pszArgs == '\0' ) ? true : ( s.GetArgVal() != 0);
continue;
}
case ITC_NEWBIESWAP:
{
if ( !pItem )
continue;
if ( pItem->IsAttr( ATTR_NEWBIE ) )
{
if ( Calc_GetRandVal( s.GetArgVal() ) == 0 )
pItem->ClrAttr(ATTR_NEWBIE);
}
else
{
if ( Calc_GetRandVal( s.GetArgVal() ) == 0 )
pItem->SetAttr(ATTR_NEWBIE);
}
continue;
}
case ITC_ITEM:
case ITC_CONTAINER:
case ITC_ITEMNEWBIE:
{
fItemCreation = true;
if ( IsStatFlag( STATF_CONJURED ) && iCmd != ITC_ITEMNEWBIE ) // This check is not needed.
break; // conjured creates have no loot.
pItem = CItem::CreateHeader( s.GetArgRaw(), this, iCmd == ITC_ITEMNEWBIE );
if ( pItem == nullptr )
{
m_UIDLastNewItem = GetUID(); // Setting m_UIDLastNewItem to CChar's UID to prevent calling any following functions meant to be called on that item
continue;
}
m_UIDLastNewItem.InitUID(); //Clearing the attr for the next cycle
pItem->_iCreatedResScriptIdx = s.m_iResourceFileIndex;
pItem->_iCreatedResScriptLine = s.m_iLineNum;
if ( iCmd == ITC_ITEMNEWBIE )
pItem->SetAttr(ATTR_NEWBIE);
if ( !pItem->IsItemInContainer() && !pItem->IsItemEquipped())
pItem = nullptr;
continue;
}
case ITC_BREAK:
case ITC_BUY:
case ITC_SELL:
pItem = nullptr;
continue;
}
}
if ( m_UIDLastNewItem == GetUID() )
continue;
if ( fBlockItemAttr ) //Did we force to cancel item attributes?
continue;
if ( pItem != nullptr )
{
if ( fFullInterp ) // Modify the item.
pItem->r_Verb( s, &g_Serv );
else
pItem->r_LoadVal( s );
}
else if (!fItemCreation)
{
TRIGRET_TYPE tRet = OnTriggerRun( s, TRIGRUN_SINGLE_EXEC, &g_Serv, nullptr, nullptr );
if ( (tRet == TRIGRET_RET_FALSE) && fFullInterp )
;
else if ( tRet != TRIGRET_RET_DEFAULT )
{
m_UIDLastNewItem.InitUID();
return (tRet == TRIGRET_RET_FALSE);
}
}
}
return true;
}
void CChar::OnWeightChange( int iChange )
{
ADDTOCALLSTACK("CChar::OnWeightChange");
CContainer::OnWeightChange( iChange );
UpdateStatsFlag();
}
int CChar::GetWeight(word amount) const
{
UNREFERENCED_PARAMETER(amount);
return CContainer::GetTotalWeight();
}
bool CChar::SetName( lpctstr pszName )
{
ADDTOCALLSTACK("CChar::SetName");
return SetNamePool( pszName );
}
height_t CChar::GetHeightMount( bool fEyeSubstract ) const
{
ADDTOCALLSTACK_INTENSIVE("CChar::GetHeightMount");
height_t height = GetHeight();
if ( IsStatFlag(STATF_ONHORSE|STATF_HOVERING) )
height += 4;
if ( fEyeSubstract )
--height;
return height; //if mounted +4, if not -1 (let's say it's eyes' height)
}
height_t CChar::GetHeight() const
{
ADDTOCALLSTACK_INTENSIVE("CChar::GetHeight");
if ( m_height ) //set by a dynamic variable (On=@Create Height=10)
return m_height;
height_t tmpHeight;
const CCharBase * pCharDef = Char_GetDef();
tmpHeight = pCharDef->GetHeight();
if ( tmpHeight ) //set by a chardef variable ([CHARDEF 10] Height=10)
return tmpHeight;
// This is SLOW (since this method is called very frequently)! Move those defs value to CharDef!
char * heightDef = Str_GetTemp();
const uint uiDispID = (uint)pCharDef->GetDispID();
sprintf(heightDef, "height_0%x", uiDispID);
tmpHeight = (height_t)(g_Exp.m_VarDefs.GetKeyNum(heightDef));
if ( tmpHeight ) //set by a defname ([DEFNAME charheight] height_0a)
return tmpHeight;
sprintf(heightDef, "height_%u", uiDispID);
tmpHeight = (height_t)(g_Exp.m_VarDefs.GetKeyNum(heightDef));
if ( tmpHeight ) //set by a defname ([DEFNAME charheight] height_10)
return tmpHeight;
return PLAYER_HEIGHT; //if everything fails
}
CREID_TYPE CChar::GetID() const
{
const CCharBase * pCharDef = Char_GetDef();
ASSERT(pCharDef);
return pCharDef->GetID();
}
word CChar::GetBaseID() const
{
// future: strongly typed enums will remove the need for this cast
return (word)(GetID());
}
CREID_TYPE CChar::GetDispID() const
{
const CCharBase * pCharDef = Char_GetDef();
ASSERT(pCharDef);
return pCharDef->GetDispID();
}
// Just set the base id and not the actual display id.
// NOTE: Never return nullptr
void CChar::SetID( CREID_TYPE id )
{
ADDTOCALLSTACK("CChar::SetID");
CCharBase * pCharDef = CCharBase::FindCharBase(id);
if ( pCharDef == nullptr )
{
if ( (id != -1) && (id != CREID_INVALID) )
DEBUG_ERR(("Create Invalid Char 0%x\n", id));
id = (CREID_TYPE)(g_Cfg.ResourceGetIndexType(RES_CHARDEF, "DEFAULTCHAR"));
if ( id < CREID_INVALID )
id = CREID_MAN;
pCharDef = CCharBase::FindCharBase(id);
}
ASSERT(pCharDef != nullptr);
CCharBase* pCharOldDef = Char_GetDef();
if ( pCharDef == pCharOldDef )
return;
if (pCharOldDef != nullptr)
{
pCharOldDef->DelInstance();
}
pCharDef->AddInstance(); // Increase object instance counter (different from the resource reference counter!)
m_BaseRef.SetRef(pCharDef); // Among the other things, it increases the new resource reference counter and decreases the old, if any
if ( _iPrev_id == CREID_INVALID )
_iPrev_id = GetID();
if ( !IsMountCapable() ) // new body may not be capable of riding mounts
Horse_UnMount();
if (!IsGargoyle()) // new body may not be capable of use gargoyle fly ability
{
StatFlag_Clear(STATF_HOVERING);
}
if ( !Can(CAN_C_EQUIP) ) // new body may not be capable of equipping items (except maybe on hands)
{
UnEquipAllItems(nullptr, Can(CAN_C_USEHANDS));
}
else if ( !Can(CAN_C_USEHANDS) )
{
CItem *pHand = LayerFind(LAYER_HAND1);
if ( pHand )
GetPackSafe()->ContentAdd(pHand);
pHand = LayerFind(LAYER_HAND2);
if ( pHand )
GetPackSafe()->ContentAdd(pHand);
}
UpdateMode(nullptr, true);
}
lpctstr CChar::GetName() const
{
return GetName( true );
}
lpctstr CChar::GetNameWithoutIncognito() const
{
if ( IsStatFlag( STATF_INCOGNITO ) )
{
CItem * pSpell = nullptr;
pSpell = LayerFind(LAYER_SPELL_Incognito);
if ( pSpell == nullptr )
pSpell = LayerFind(LAYER_FLAG_Potion);
if ( pSpell && pSpell->IsType(IT_SPELL) && (pSpell->m_itSpell.m_spell == SPELL_Incognito))
return pSpell->GetName();
}
return GetName();
}
lpctstr CChar::GetName( bool fAllowAlt ) const
{
if ( fAllowAlt )
{
lpctstr pAltName = GetKeyStr( "NAME.ALT" );
if ( pAltName && *pAltName )
return pAltName;
}
if ( ! IsIndividualName() ) // allow some creatures to go unnamed.
{
CCharBase * pCharDef = Char_GetDef();
ASSERT(pCharDef);
return pCharDef->GetTypeName(); // Just use it's type name instead.
}
return CObjBase::GetName();
}
// Create a brand new Player char. Called directly from the packet.
void CChar::InitPlayer( CClient *pClient, const char *pszCharname, bool fFemale, RACE_TYPE rtRace, ushort wStr, ushort wDex, ushort wInt,
PROFESSION_TYPE prProf, SKILL_TYPE skSkill1, ushort uiSkillVal1, SKILL_TYPE skSkill2, ushort uiSkillVal2, SKILL_TYPE skSkill3, ushort uiSkillVal3, SKILL_TYPE skSkill4, ushort uiSkillVal4,
HUE_TYPE wSkinHue, ITEMID_TYPE idHair, HUE_TYPE wHairHue, ITEMID_TYPE idBeard, HUE_TYPE wBeardHue, HUE_TYPE wShirtHue, HUE_TYPE wPantsHue, ITEMID_TYPE idFace, int iStartLoc )
{
ADDTOCALLSTACK("CChar::InitPlayer");
ASSERT(pClient);
CAccount *pAccount = pClient->GetAccount();
if ( pAccount )
SetPlayerAccount(pAccount);
switch ( rtRace )
{
default:
g_Log.EventWarn("Character creation: invalid race. Defaulting to human.\n");
rtRace = RACETYPE_HUMAN;
FALLTHROUGH;
case RACETYPE_HUMAN:
SetID(fFemale ? CREID_WOMAN : CREID_MAN);
break;
case RACETYPE_ELF:
SetID(fFemale ? CREID_ELFWOMAN : CREID_ELFMAN);
break;
case RACETYPE_GARGOYLE:
SetID(fFemale ? CREID_GARGWOMAN : CREID_GARGMAN);
break;
}
// Set name
bool fNameIsAccepted = true;
tchar *zCharName = Str_GetTemp();
Str_CopyLimitNull(zCharName, pszCharname, MAX_NAME_SIZE);
if ( !strlen(zCharName) || g_Cfg.IsObscene(zCharName) || Str_CheckName(zCharName) ||!strnicmp(zCharName, "lord ", 5) || !strnicmp(zCharName, "lady ", 5) ||
!strnicmp(zCharName, "seer ", 5) || !strnicmp(zCharName, "gm ", 3) || !strnicmp(zCharName, "admin ", 6) || !strnicmp(zCharName, "counselor ", 10) )
{
fNameIsAccepted = false;
}
if ( fNameIsAccepted && IsTrigUsed(TRIGGER_RENAME) )
{
CScriptTriggerArgs args;
args.m_s1 = zCharName;
args.m_pO1 = this;
if ( OnTrigger(CTRIG_Rename, this, &args) == TRIGRET_RET_TRUE )
fNameIsAccepted = false;
}
if ( fNameIsAccepted )
SetName(zCharName);
else
SetNamePool(fFemale ? "#NAMES_HUMANFEMALE" : "#NAMES_HUMANMALE");
if ( g_Cfg.m_StartDefs.IsValidIndex(iStartLoc) )
m_ptHome = g_Cfg.m_StartDefs[iStartLoc]->m_pt;
else
m_ptHome.InitPoint();
if ( !m_ptHome.IsValidPoint() )
DEBUG_ERR(("Invalid start location '%d' for character!\n", iStartLoc));
SetUnkPoint(m_ptHome); // don't actually put me in the world yet.
// randomize the skills first.
for ( uint i = 0; i < g_Cfg.m_iMaxSkill; ++i )
{
if ( g_Cfg.m_SkillIndexDefs.IsValidIndex(i) )
Skill_SetBase((SKILL_TYPE)i, (ushort)Calc_GetRandVal(g_Cfg.m_iMaxBaseSkill));
}
if ( wStr > 60 ) wStr = 60;
if ( wDex > 60 ) wDex = 60;
if ( wInt > 60 ) wInt = 60;
if ( uiSkillVal1 > 50 ) uiSkillVal1 = 50;
if ( uiSkillVal2 > 50 ) uiSkillVal2 = 50;
if ( uiSkillVal3 > 50 ) uiSkillVal3 = 50;
if ( uiSkillVal4 > 50 ) uiSkillVal4 = 50;
if ( skSkill4 != SKILL_NONE )
{
if ( (wStr + wDex + wInt) > 90 )
wStr = wDex = wInt = 30;
if ( (uiSkillVal1 + uiSkillVal2 + uiSkillVal3 + uiSkillVal4) > 120 )
uiSkillVal4 = 1;
}
else
{
if ( (wStr + wDex + wInt) > 80 )
wStr = wDex = wInt = 26;
if ( (uiSkillVal1 + uiSkillVal2 + uiSkillVal3) > 100 )
uiSkillVal3 = 1;
}
Stat_SetBase(STAT_STR, wStr);
Stat_SetBase(STAT_DEX, wDex);
Stat_SetBase(STAT_INT, wInt);
if ( IsSkillBase(skSkill1) && g_Cfg.m_SkillIndexDefs.IsValidIndex(skSkill1) )
Skill_SetBase(skSkill1, uiSkillVal1 * 10);
if ( IsSkillBase(skSkill2) && g_Cfg.m_SkillIndexDefs.IsValidIndex(skSkill2) )
Skill_SetBase(skSkill2, uiSkillVal2 * 10);
if ( IsSkillBase(skSkill3) && g_Cfg.m_SkillIndexDefs.IsValidIndex(skSkill3) )
Skill_SetBase(skSkill3, uiSkillVal3 * 10);
if ( skSkill4 != SKILL_NONE )
{
if ( IsSkillBase(skSkill4) && g_Cfg.m_SkillIndexDefs.IsValidIndex(skSkill4) )
Skill_SetBase(skSkill4, uiSkillVal4 * 10);
}
m_pPlayer->m_SpeechHue = HUE_TEXT_DEF; // Set default client-sent speech color
m_pPlayer->m_EmoteHue = HUE_EMOTE_DEF; // Set default emote color
m_fonttype = FONT_NORMAL; // Set speech font type
m_SpeechHueOverride = 0; // Set no server-side speech color override
m_EmoteHueOverride = 0; // Set no server-side emote color override
m_sTitle.Clear(); // Set title
GetBank(LAYER_BANKBOX); // Create bankbox
GetPackSafe(); // Create backpack
// Check skin hue
switch ( rtRace )
{
default:
case RACETYPE_HUMAN:
if ( wSkinHue < HUE_SKIN_LOW )
wSkinHue = (HUE_TYPE)(HUE_SKIN_LOW);
if ( wSkinHue > HUE_SKIN_HIGH )
wSkinHue = (HUE_TYPE)(HUE_SKIN_HIGH);
break;
case RACETYPE_ELF:
{
static constexpr int sm_ElfSkinHues[] =
{
0x0BF, 0x24D, 0x24E, 0x24F, 0x353, 0x361, 0x367, 0x374, 0x375, 0x376, 0x381, 0x382, 0x383, 0x384, 0x385, 0x389,
0x3DE, 0x3E5, 0x3E6, 0x3E8, 0x3E9, 0x430, 0x4A7, 0x4DE, 0x51D, 0x53F, 0x579, 0x76B, 0x76C, 0x76D, 0x835, 0x903
};
constexpr uint iMax = CountOf(sm_ElfSkinHues);
bool isValid = 0;
for ( uint i = 0; i < iMax; ++i )
{
if ( sm_ElfSkinHues[i] == wSkinHue )
{
isValid = 1;
break;
}
}
if ( !isValid )
wSkinHue = (HUE_TYPE)(sm_ElfSkinHues[0]);
}
break;
case RACETYPE_GARGOYLE:
if ( wSkinHue < HUE_GARGSKIN_LOW )
wSkinHue = (HUE_TYPE)(HUE_GARGSKIN_LOW);
if ( wSkinHue > HUE_GARGSKIN_HIGH )
wSkinHue = (HUE_TYPE)(HUE_GARGSKIN_HIGH);
break;
}
SetHue((wSkinHue|HUE_UNDERWEAR));
// Create hair
switch ( rtRace )
{
default:
case RACETYPE_HUMAN:
if ( !(((idHair >= ITEMID_HAIR_SHORT) && (idHair <= ITEMID_HAIR_PONYTAIL)) || ((idHair >= ITEMID_HAIR_MOHAWK) && (idHair <= ITEMID_HAIR_TOPKNOT))) )
idHair = ITEMID_NOTHING; // human can use only a restricted subset of hairs
if ( (fFemale && idHair == ITEMID_HAIR_RECEDING) || (!fFemale && idHair == ITEMID_HAIR_BUNS) )
idHair = ITEMID_NOTHING;
break;
case RACETYPE_ELF:
if ( !(((idHair >= ITEMID_HAIR_ML_ELF) && (idHair <= ITEMID_HAIR_ML_MULLET)) || ((idHair >= ITEMID_HAIR_ML_FLOWER) && (idHair <= ITEMID_HAIR_ML_SPYKE))) )
idHair = ITEMID_NOTHING; // elf can use only a restricted subset of hairs
if ( (fFemale && (idHair == ITEMID_HAIR_ML_LONG2 || idHair == ITEMID_HAIR_ML_ELF)) || (!fFemale && (idHair == ITEMID_HAIR_ML_FLOWER || idHair == ITEMID_HAIR_ML_LONG4)) )
idHair = ITEMID_NOTHING;
break;
case RACETYPE_GARGOYLE:
if ( fFemale )
{
if ( !((idHair == ITEMID_GARG_HORN_FEMALE_1) || (idHair == ITEMID_GARG_HORN_FEMALE_2) || ((idHair >= ITEMID_GARG_HORN_FEMALE_3) && (idHair <= ITEMID_GARG_HORN_FEMALE_5)) || (idHair == ITEMID_GARG_HORN_FEMALE_6) || (idHair == ITEMID_GARG_HORN_FEMALE_7) || (idHair == ITEMID_GARG_HORN_FEMALE_8)) )
idHair = ITEMID_NOTHING;
}
else
{
if ( !((idHair >= ITEMID_GARG_HORN_1) && (idHair <= ITEMID_GARG_HORN_8)) )
idHair = ITEMID_NOTHING;
}
break;
}
if ( idHair )
{
CItem *pHair = CItem::CreateScript(idHair, this);
ASSERT(pHair);
if ( !pHair->IsType(IT_HAIR) )
pHair->Delete();
else
{
switch ( rtRace )
{
default:
case RACETYPE_HUMAN:
if ( wHairHue < HUE_HAIR_LOW )
wHairHue = (HUE_TYPE)(HUE_HAIR_LOW);
if ( wHairHue > HUE_HAIR_HIGH )
wHairHue = (HUE_TYPE)(HUE_HAIR_HIGH);
break;
case RACETYPE_ELF:
{
static constexpr int sm_ElfHairHues[] =
{
0x034, 0x035, 0x036, 0x037, 0x038, 0x039, 0x058, 0x08E, 0x08F, 0x090, 0x091, 0x092,
0x101, 0x159, 0x15A, 0x15B, 0x15C, 0x15D, 0x15E, 0x128, 0x12F, 0x1BD, 0x1E4, 0x1F3,
0x207, 0x211, 0x239, 0x251, 0x26C, 0x2C3, 0x2C9, 0x31D, 0x31E, 0x31F, 0x320, 0x321,
0x322, 0x323, 0x324, 0x325, 0x326, 0x369, 0x386, 0x387, 0x388, 0x389, 0x38A, 0x59D,
0x6B8, 0x725, 0x853
};
constexpr uint iMax = CountOf(sm_ElfHairHues);
bool isValid = 0;
for ( uint i = 0; i < iMax; ++i )
{
if ( sm_ElfHairHues[i] == wHairHue )
{
isValid = 1;
break;
}
}
if ( !isValid )
wHairHue = (HUE_TYPE)(sm_ElfHairHues[0]);
}
break;
case RACETYPE_GARGOYLE:
{
static constexpr int sm_GargoyleHornHues[] =
{
0x709, 0x70B, 0x70D, 0x70F, 0x711, 0x763, 0x765, 0x768, 0x76B,
0x6F3, 0x6F1, 0x6EF, 0x6E4, 0x6E2, 0x6E0, 0x709, 0x70B, 0x70D
};
constexpr uint iMax = CountOf(sm_GargoyleHornHues);
bool isValid = 0;
for ( uint i = 0; i < iMax; ++i )
{
if ( sm_GargoyleHornHues[i] == wHairHue )
{
isValid = 1;
break;
}
}
if ( !isValid )
wHairHue = (HUE_TYPE)(sm_GargoyleHornHues[0]);
}
break;
}
pHair->SetHue(wHairHue);
pHair->SetAttr(ATTR_NEWBIE|ATTR_MOVE_NEVER);
LayerAdd(pHair); // add content
}
}
// Create beard
if (fFemale)
idBeard = ITEMID_NOTHING;
else
{
switch (rtRace)
{
default:
case RACETYPE_HUMAN:
if (!(((idBeard >= ITEMID_BEARD_LONG) && (idBeard <= ITEMID_BEARD_MOUSTACHE)) || ((idBeard >= ITEMID_BEARD_SH_M) && (idBeard <= ITEMID_BEARD_GO_M))))
idBeard = ITEMID_NOTHING;
break;
case RACETYPE_ELF:
idBeard = ITEMID_NOTHING;
break;
case RACETYPE_GARGOYLE:
if (!((idBeard >= ITEMID_GARG_HORN_FACIAL_1) && (idBeard <= ITEMID_GARG_HORN_FACIAL_4)))
idBeard = ITEMID_NOTHING;
break;
}
}
if ( idBeard )
{
CItem *pBeard = CItem::CreateScript(idBeard, this);
ASSERT(pBeard);
if ( !pBeard->IsType(IT_BEARD) )
pBeard->Delete();
else
{
switch ( rtRace )
{
case RACETYPE_HUMAN:
if ( wBeardHue < HUE_HAIR_LOW )
wBeardHue = (HUE_TYPE)(HUE_HAIR_LOW);
if ( wBeardHue > HUE_HAIR_HIGH )
wBeardHue = (HUE_TYPE)(HUE_HAIR_HIGH);
break;
case RACETYPE_GARGOYLE:
{
static constexpr int sm_GargoyleBeardHues[] =
{
0x709, 0x70B, 0x70D, 0x70F, 0x711, 0x763, 0x765, 0x768, 0x76B,
0x6F3, 0x6F1, 0x6EF, 0x6E4, 0x6E2, 0x6E0, 0x709, 0x70B, 0x70D
};
int iMax = CountOf(sm_GargoyleBeardHues);
bool isValid = 0;
for ( int i = 0; i < iMax; ++i )
{
if ( sm_GargoyleBeardHues[i] == wHairHue )
{
isValid = 1;
break;
}
}
if ( !isValid )
wHairHue = (HUE_TYPE)(sm_GargoyleBeardHues[0]);
}
break;
default:
break;
}
pBeard->SetHue(wBeardHue);
pBeard->SetAttr(ATTR_NEWBIE|ATTR_MOVE_NEVER);
LayerAdd(pBeard); // add content
}
}
// Create face (enhanced clients only)
if ( idFace != ITEMID_NOTHING )
{
switch ( rtRace )
{
case RACETYPE_GARGOYLE:
if ( !((idFace >= ITEMID_FACE_1_GARG) && (idFace <= ITEMID_FACE_6_GARG)) )
idFace = ITEMID_NOTHING;
break;
default:
if ( !(((idFace >= ITEMID_FACE_1) && (idFace <= ITEMID_FACE_10)) || ((idFace >= ITEMID_FACE_ANIME) && (idFace <= ITEMID_FACE_VAMPIRE))) )
idFace = ITEMID_NOTHING;
break;
}
CItem *pFace = CItem::CreateScript(idFace, this);
ASSERT(pFace);
pFace->SetHue(wSkinHue);
pFace->SetAttr(ATTR_NEWBIE|ATTR_MOVE_NEVER);
LayerAdd(pFace);
}
// Get starting items for the profession / skills.
int iProfession = INT32_MAX;
bool fCreateSkillItems = true;
switch ( prProf )
{
//default: // not good for custom stuff
// g_Log.EventWarn("Character creation: invalid profession. Defaulting to advanced.\n");
case PROFESSION_ADVANCED:
iProfession = RES_NEWBIE_PROF_ADVANCED;
break;
case PROFESSION_WARRIOR:
iProfession = RES_NEWBIE_PROF_WARRIOR;
break;
case PROFESSION_MAGE:
iProfession = RES_NEWBIE_PROF_MAGE;
break;
case PROFESSION_BLACKSMITH:
iProfession = RES_NEWBIE_PROF_BLACKSMITH;
break;
case PROFESSION_NECROMANCER:
iProfession = RES_NEWBIE_PROF_NECROMANCER;
fCreateSkillItems = false;
break;
case PROFESSION_PALADIN:
iProfession = RES_NEWBIE_PROF_PALADIN;
fCreateSkillItems = false;
break;
case PROFESSION_SAMURAI:
iProfession = RES_NEWBIE_PROF_SAMURAI;
fCreateSkillItems = false;
break;
case PROFESSION_NINJA:
iProfession = RES_NEWBIE_PROF_NINJA;
fCreateSkillItems = false;
break;
}
CResourceLock s;
if ( g_Cfg.ResourceLock(s, CResourceID(RES_NEWBIE, fFemale ? RES_NEWBIE_FEMALE_DEFAULT : RES_NEWBIE_MALE_DEFAULT, (word)rtRace)) )
ReadScriptReduced(s);
else if ( g_Cfg.ResourceLock(s, CResourceID(RES_NEWBIE, fFemale ? RES_NEWBIE_FEMALE_DEFAULT : RES_NEWBIE_MALE_DEFAULT)) )
ReadScriptReduced(s);
if (iProfession != INT32_MAX)
{
if ( g_Cfg.ResourceLock(s, CResourceID(RES_NEWBIE, iProfession, (word)rtRace)) )
ReadScriptReduced(s);
else if ( g_Cfg.ResourceLock(s, CResourceID(RES_NEWBIE, iProfession)) )
ReadScriptReduced(s);
}
if ( fCreateSkillItems )
{
for ( int i = 1; i < 5; ++i )
{
int iSkill = INT32_MAX;
switch ( i )
{
case 1:
iSkill = skSkill1;
break;
case 2:
iSkill = skSkill2;
break;
case 3:
iSkill = skSkill3;
break;
case 4:
iSkill = skSkill4;
break;
}
if ( !g_Cfg.ResourceLock(s, CResourceID(RES_NEWBIE, iSkill, (word)rtRace)) )
{
if ( !g_Cfg.ResourceLock(s, CResourceID(RES_NEWBIE, iSkill)) )
continue;
}
ReadScriptReduced(s);
}
}
CItem *pLayer = LayerFind(LAYER_SHIRT);
if ( pLayer )
{
if ( wShirtHue < HUE_BLUE_LOW )
wShirtHue = HUE_BLUE_LOW;
if ( wShirtHue > HUE_DYE_HIGH )
wShirtHue = HUE_DYE_HIGH;
pLayer->SetHue(wShirtHue);
}
pLayer = LayerFind(LAYER_PANTS);
if ( pLayer )
{
if ( wPantsHue < HUE_BLUE_LOW )
wPantsHue = HUE_BLUE_LOW;
if ( wPantsHue > HUE_DYE_HIGH )
wPantsHue = HUE_DYE_HIGH;
pLayer->SetHue(wPantsHue);
}
CreateNewCharCheck();
}
enum CHR_TYPE
{
CHR_ACCOUNT,
CHR_ACT,
CHR_FINDLAYER,
CHR_HOUSE,
CHR_MEMORYFIND,
CHR_MEMORYFINDTYPE,
CHR_OWNER,
CHR_REGION,
CHR_SHIP,
CHR_WEAPON,
CHR_QTY
};
lpctstr const CChar::sm_szRefKeys[CHR_QTY+1] =
{
"ACCOUNT",
"ACT",
"FINDLAYER",
"HOUSE",
"MEMORYFIND",
"MEMORYFINDTYPE",
"OWNER",
"REGION",
"SHIP",
"WEAPON",
nullptr
};
bool CChar::r_GetRef( lpctstr & ptcKey, CScriptObj * & pRef )
{
ADDTOCALLSTACK("CChar::r_GetRef");
if (CEntity::r_GetRef(ptcKey, pRef))
{
return true;
}
int i = FindTableHeadSorted( ptcKey, sm_szRefKeys, CountOf(sm_szRefKeys)-1 );
if ( i >= 0 )
{
ptcKey += strlen( sm_szRefKeys[i] );
SKIP_SEPARATORS(ptcKey);
switch (i)
{
case CHR_ACCOUNT:
if ( ptcKey[-1] != '.' ) // only used as a ref !
break;
pRef = m_pPlayer ? m_pPlayer->GetAccount() : nullptr;
return true;
case CHR_ACT:
if ( ptcKey[-1] != '.' ) // only used as a ref !
break;
pRef = m_Act_UID.ObjFind();
return true;
case CHR_FINDLAYER: // Find equipped layers.
pRef = LayerFind( (LAYER_TYPE) Exp_GetSingle( ptcKey ));
SKIP_SEPARATORS(ptcKey);
return true;
case CHR_HOUSE:
if (m_pPlayer)
{
const int16 iPos = (int16)Exp_GetSingle(ptcKey);
CMultiStorage* pMultiStorage = m_pPlayer->GetMultiStorage();
if (pMultiStorage->GetHouseCountReal() <= iPos)
{
return false;
}
pRef = static_cast<CItemMulti*>(pMultiStorage->GetHouseAt(iPos).ItemFind());
SKIP_SEPARATORS(ptcKey);
return true;
}
return false;
case CHR_SHIP:
if (m_pPlayer)
{
const int16 iPos = (int16)Exp_GetSingle(ptcKey);
CMultiStorage* pMultiStorage = m_pPlayer->GetMultiStorage();
if (pMultiStorage->GetShipCountReal() <= iPos)
{
return false;
}
pRef = static_cast<CItemShip*>(pMultiStorage->GetShipAt(iPos).ItemFind());
SKIP_SEPARATORS(ptcKey);
return true;
}
return false;
case CHR_MEMORYFINDTYPE: // FInd a type of memory.
pRef = Memory_FindTypes((word)(Exp_GetSingle(ptcKey)));
SKIP_SEPARATORS(ptcKey);
return true;
case CHR_MEMORYFIND: // Find a memory of a UID
pRef = Memory_FindObj( (CUID) Exp_GetSingle( ptcKey ));
SKIP_SEPARATORS(ptcKey);
return true;
case CHR_OWNER:
pRef = GetOwner();
return true;
case CHR_WEAPON:
pRef = m_uidWeapon.ObjFind();
return true;
case CHR_REGION:
pRef = m_pArea;
return true;
}
}
if ( r_GetRefContainer( ptcKey, pRef ))
return true;
return ( CObjBase::r_GetRef( ptcKey, pRef ));
}
enum CHC_TYPE
{
#define ADD(a,b) CHC_##a,
#include "../../tables/CChar_props.tbl"
#undef ADD
CHC_QTY
};
lpctstr const CChar::sm_szLoadKeys[CHC_QTY+1] =
{
#define ADD(a,b) b,
#include "../../tables/CChar_props.tbl"
#undef ADD
nullptr
};
bool CChar::r_WriteVal( lpctstr ptcKey, CSString & sVal, CTextConsole * pSrc, bool fNoCallParent, bool fNoCallChildren )
{
ADDTOCALLSTACK("CChar::r_WriteVal");
EXC_TRY("WriteVal");
if ( IsClientActive() && GetClientActive()->r_WriteVal(ptcKey, sVal, pSrc, true, true) ) // Call CClient::r_WriteVal
return true;
if (!fNoCallChildren)
{
// Checking Props CComponents first (first check CChar props, if not found then check CCharBase)
EXC_SET_BLOCK("EntityProp");
if (CEntityProps::r_WritePropVal(ptcKey, sVal, this, Base_GetDef()))
{
return true;
}
// Now check regular CComponents
EXC_SET_BLOCK("Entity");
if (CEntity::r_WriteVal(ptcKey, sVal, pSrc))
{
return true;
}
}
EXC_SET_BLOCK("Keyword");
const CHC_TYPE iKeyNum = (CHC_TYPE) FindTableHeadSorted( ptcKey, sm_szLoadKeys, CountOf( sm_szLoadKeys )-1 );
if ( iKeyNum < 0 )
{
do_default:
if ( m_pPlayer )
{
if ( m_pPlayer->r_WriteVal( this, ptcKey, sVal ))
return true;
}
if ( m_pNPC )
{
if ( m_pNPC->r_WriteVal( this, ptcKey, sVal ))
return true;
}
if ( r_WriteValContainer(ptcKey, sVal, pSrc))
return true;
// special write values
const SKILL_TYPE iSkill = (SKILL_TYPE)g_Cfg.FindSkillKey( ptcKey );
if ( IsSkillBase(iSkill) )
{
// Check some skill name.
const ushort uiVal = Skill_GetBase( iSkill );
sVal.Format( "%u.%u", uiVal/10, uiVal%10 );
return true;
}
return (fNoCallParent ? false : CObjBase::r_WriteVal( ptcKey, sVal, pSrc, false ));
}
const CCharBase * pCharDef = Char_GetDef();
ASSERT(pCharDef);
CChar * pCharSrc = pSrc->GetChar();
switch ( iKeyNum )
{
//return as decimal number or 0 if not set
case CHC_CURFOLLOWER:
sVal.FormatLLVal(GetDefNum(ptcKey,false));
break;
//On these ones, check BaseDef if not found on dynamic
case CHC_MAXFOLLOWER:
case CHC_SPELLTIMEOUT:
case CHC_TITHING:
sVal.FormatLLVal(GetDefNum(ptcKey, true));
break;
case CHC_ATTACKER:
{
if ( strlen( ptcKey ) == 8 )
{
sVal.FormatSTVal(m_lastAttackers.size());
return true;
}
sVal.FormatVal(0);
ptcKey += 8;
if ( *ptcKey == '.' )
{
++ptcKey;
if ( !strnicmp(ptcKey, "ID", 2 ) )
{
ptcKey += 3; // ID + whitspace
const CChar * pChar = CUID::CharFindFromUID(Exp_GetSingle(ptcKey));
sVal.FormatVal(Attacker_GetID(pChar));
return true;
}
else if ( !strnicmp(ptcKey, "TARGET", 6 ) )
{
ptcKey += 6;
if (m_Act_UID.IsValidUID())
sVal.FormatHex((dword)(m_Fight_Targ_UID));
else
sVal.FormatVal(-1);
return true;
}
if ( !m_lastAttackers.empty() )
{
int attackerIndex = (int)m_lastAttackers.size();
if( !strnicmp(ptcKey, "MAX", 3) )
{
ptcKey += 3;
int64 iMaxDmg = -1, iCurDmg = 0;
for ( size_t iAttacker = 0; iAttacker < m_lastAttackers.size(); ++iAttacker )
{
iCurDmg = m_lastAttackers[iAttacker].amountDone;
if ( iCurDmg > iMaxDmg )
{
iMaxDmg = iCurDmg;
attackerIndex = (int)iAttacker;
}
}
}
else if( !strnicmp(ptcKey, "LAST", 4) )
{
ptcKey += 4;
int64 iLastTime = INT64_MAX, iCurTime = 0;
for ( size_t iAttacker = 0; iAttacker < m_lastAttackers.size(); ++iAttacker )
{
iCurTime = m_lastAttackers[iAttacker].elapsed;
if ( iCurTime <= iLastTime )
{
iLastTime = iCurTime;
attackerIndex = (int)iAttacker;
}
}
}
else
{
attackerIndex = Exp_GetVal(ptcKey);
}
SKIP_SEPARATORS(ptcKey);
if ( attackerIndex < (int)m_lastAttackers.size() )
{
const LastAttackers & refAttacker = m_lastAttackers[(size_t)attackerIndex];
if( !strnicmp(ptcKey, "DAM", 3) )
{
sVal.FormatLLVal(refAttacker.amountDone);
return true;
}
else if( !strnicmp(ptcKey, "ELAPSED", 7) )
{
sVal.FormatLLVal(refAttacker.elapsed);
return true;
}
else if (( !strnicmp(ptcKey, "UID", 3) ) || ( *ptcKey == '\0' ))
{
const CUID uid(refAttacker.charUID);
sVal.FormatHex( uid.CharFind() ? refAttacker.charUID : 0 );
return true;
}
else if (!strnicmp(ptcKey, "THREAT", 6))
{
sVal.FormatVal(refAttacker.threat);
return true;
}
else if (!strnicmp(ptcKey, "IGNORE", 6))
{
sVal.FormatVal(refAttacker.ignore ? 1:0);
return true;
}
}
}
}
return true;
}
case CHC_BREATH:
{
if( !strnicmp(ptcKey, "BREATH.DAM", 10) )
{
CVarDefCont * pVar = GetDefKey(ptcKey, true);
sVal.FormatLLVal(pVar ? pVar->GetValNum() : 0);
return true;
}
else if ( !strnicmp(ptcKey, "BREATH.HUE", 10) || !strnicmp(ptcKey, "BREATH.ANIM", 11) || !strnicmp(ptcKey, "BREATH.TYPE", 11) || !strnicmp(ptcKey, "BREATH.DAMTYPE", 14))
{
CVarDefCont * pVar = GetDefKey(ptcKey, true);
sVal.FormatHex(pVar ? (dword)(pVar->GetValNum()) : 0);
return true;
}
return false;
}
case CHC_NOTOSAVE:
{
if ( strlen( ptcKey ) == 8 )
{
sVal.FormatSTVal(m_notoSaves.size());
return true;
}
sVal.FormatVal(0);
ptcKey += 8;
if ( *ptcKey == '.' )
{
++ptcKey;
if ( !strnicmp(ptcKey, "ID", 2 ) )
{
ptcKey += 2; // ID + whitspace
CChar * pChar = static_cast<CChar*>( CUID(Exp_GetSingle(ptcKey)).CharFind() );
if ( !NotoSave_GetID(pChar) )
sVal.FormatVal( -1 );
else
sVal.FormatVal(NotoSave_GetID(pChar));
return true;
}
if ( m_notoSaves.size() )
{
size_t notoIndex = Exp_GetVal(ptcKey);
SKIP_SEPARATORS(ptcKey);
if ( notoIndex < m_notoSaves.size() )
{
NotoSaves & refnoto = m_notoSaves[notoIndex];
if ( !strnicmp(ptcKey, "VALUE", 5) )
{
sVal.FormatVal(refnoto.value);
return true;
}
else if ( !strnicmp(ptcKey, "ELAPSED", 7) )
{
sVal.FormatLLVal(refnoto.time);
return true;
}
else if (( !strnicmp(ptcKey, "UID", 3) ) || ( *ptcKey == '\0' ))
{
const CUID uid(refnoto.charUID);
sVal.FormatHex( uid.CharFind() ? refnoto.charUID : 0 );
return true;
}
else if (!strnicmp(ptcKey, "COLOR", 5))
{
sVal.FormatVal(refnoto.color);
return true;
}
return false;
}
}
}
return true;
}
case CHC_FIGHTRANGE: //RANGE is now writable so this is changed to FIGHTRANGE as readable only
sVal.FormatVal( Fight_CalcRange( m_uidWeapon.ItemFind() ) );
return true;
case CHC_BLOODCOLOR:
sVal.FormatHex( _wBloodHue );
break;
case CHC_OFAME:
case CHC_FAME:
// How much respect do i give this person ?
// Fame is never negative !
{
if (ptcKey[4] != '.')
{
sVal.FormatUSVal(GetFame());
break;
}
if (g_Cfg.m_Fame.size() <= 0 )
{
DEBUG_ERR(("FAME ranges have not been defined.\n"));
sVal.FormatVal( 0 );
return true;
}
tchar * ppLevel_sep[100];
const CSString* pFameAt0 = g_Cfg.m_Fame[0];
const size_t uiLen = (size_t)pFameAt0->GetLength() + 1;
tchar * pszFameAt0 = new tchar[uiLen];
Str_CopyLimitNull(pszFameAt0, pFameAt0->GetBuffer(), uiLen);
int iFame = GetFame();
int i = Str_ParseCmds( pszFameAt0, ppLevel_sep, CountOf(ppLevel_sep), "," ) - 1; //range
for (;;)
{
if ( !IsStrNumeric( ppLevel_sep[i] ) )
{
DEBUG_ERR(("'%s' is not a valid fame value.\n", ppLevel_sep[i]));
}
else if ( iFame >= Str_ToI(ppLevel_sep[ i ]) )
{
sVal = ( !g_Cfg.m_Fame[(size_t)i + 1]->CompareNoCase( ptcKey + 5 )) ? "1" : "0";
delete[] pszFameAt0;
return true;
}
if ( i == 0 )
break;
--i;
}
sVal = 0;
delete[] pszFameAt0;
return true;
}
case CHC_SKILLCHECK: // odd way to get skills checking into the triggers.
ptcKey += 10;
SKIP_SEPARATORS(ptcKey);
{
tchar * ppArgs[2];
if ( !Str_ParseCmds(const_cast<tchar *>(ptcKey), ppArgs, CountOf(ppArgs)) )
return false;
SKILL_TYPE iSkill = g_Cfg.FindSkillKey( ppArgs[0] );
if ( iSkill == SKILL_NONE )
return false;
sVal.FormatVal( Skill_CheckSuccess( iSkill, Exp_GetVal( ppArgs[1] )));
}
return true;
case CHC_SKILLADJUSTED:
ptcKey += 13;
SKIP_SEPARATORS(ptcKey);
{
SKILL_TYPE iSkill = g_Cfg.FindSkillKey(ptcKey);
if (iSkill == SKILL_NONE)
return false;
ushort iValAdjusted = Skill_GetAdjusted(iSkill);
sVal.Format("%hu.%hu", iValAdjusted / 10, iValAdjusted % 10);
}
return true;
case CHC_SKILLBEST:
// Get the top skill.
ptcKey += 9;
{
uint iRank = 0;
if ( *ptcKey == '.' )
{
SKIP_SEPARATORS(ptcKey);
iRank = Exp_GetSingle(ptcKey);
}
sVal.FormatVal(Skill_GetBest(iRank));
}
return true;
case CHC_SEX: // <SEX milord/milady> sep chars are :,/
ptcKey += 3;
SKIP_SEPARATORS(ptcKey);
{
tchar * ppArgs[2];
if ( !Str_ParseCmds(const_cast<tchar *>(ptcKey), ppArgs, CountOf(ppArgs), ":,/" ) )
return false;
sVal = ( pCharDef->IsFemale()) ? ppArgs[1] : ppArgs[0];
}
return true;
case CHC_OKARMA:
case CHC_KARMA:
// What do i think of this person.
{
if (ptcKey[5] != '.')
{
sVal.FormatSVal(GetKarma());
break;
}
if (g_Cfg.m_Karma.empty())
{
DEBUG_ERR(("KARMA ranges have not been defined.\n"));
sVal.FormatVal( 0 );
return true;
}
tchar * ppLevel_sep[100];
const CSString* pKarmaAt0 = g_Cfg.m_Karma[0];
const size_t uiLen = (size_t)pKarmaAt0->GetLength() + 1;
tchar * pszKarmaAt0 = new tchar[uiLen];
Str_CopyLimitNull(pszKarmaAt0, pKarmaAt0->GetBuffer(), uiLen);
short iKarma = GetKarma();
int i = Str_ParseCmds( pszKarmaAt0, ppLevel_sep, CountOf(ppLevel_sep), "," ) - 1; //range
for (;;)
{
if ( ppLevel_sep[i][0] != '-' && !IsStrNumeric( ppLevel_sep[i] ) )
{
DEBUG_ERR(("'%s' is not a valid karma value.\n", ppLevel_sep[i]));
}
else if ( iKarma >= Str_ToI(ppLevel_sep[ i ]) )
{
sVal = ( !g_Cfg.m_Karma[(size_t)i + 1]->CompareNoCase( ptcKey + 6 )) ? "1" : "0";
delete[] pszKarmaAt0;
return true;
}
if ( i == 0 )
break;
--i;
}
sVal = 0;
delete[] pszKarmaAt0;
return true;
}
case CHC_AR:
case CHC_AC:
sVal.FormatVal( m_defense + pCharDef->m_defense );
return true;
case CHC_AGE:
sVal.FormatLLVal( CWorldGameTime::GetCurrentTime().GetTimeDiff(_iTimeCreate) / ( MSECS_PER_SEC * 60 * 60 *24 ) ); //displayed in days
return true;
case CHC_BANKBALANCE:
{
const CItemContainer* pBank = GetBank();
if (!pBank)
return false;
sVal.FormatVal(pBank->ContentCount(CResourceID(RES_TYPEDEF, IT_GOLD)));
return true;
}
case CHC_CANCAST:
{
ptcKey += 7;
GETNONWHITESPACE(ptcKey);
tchar * ppArgs[2];
int iQty = Str_ParseCmds(const_cast<tchar *>(ptcKey), ppArgs, CountOf( ppArgs ));
// Check that we have at least the first argument
if ( iQty <= 0 )
return false;
// Lookup the spell ID to ensure it's valid
SPELL_TYPE spell = (SPELL_TYPE)(g_Cfg.ResourceGetIndexType( RES_SPELL, ppArgs[0] ));
bool fCheckAntiMagic = true; // AntiMagic check is enabled by default
// Set AntiMagic check if second argument has been provided
if ( iQty == 2 )
fCheckAntiMagic = ( Exp_GetVal( ppArgs[1] ) >= 1 );
sVal.FormatVal( Spell_CanCast( spell, true, this, false, fCheckAntiMagic ) );
}
return true;
case CHC_CANMAKE:
{
// use m_Act_UID ?
ptcKey += 7;
ITEMID_TYPE id = (ITEMID_TYPE)(g_Cfg.ResourceGetIndexType( RES_ITEMDEF, ptcKey ));
sVal.FormatVal( Skill_MakeItem( id, CUID(UID_CLEAR), SKTRIG_SELECT ) );
}
return true;
case CHC_CANMAKESKILL:
{
ptcKey += 12;
ITEMID_TYPE id = (ITEMID_TYPE)(g_Cfg.ResourceGetIndexType( RES_ITEMDEF, ptcKey ));
sVal.FormatVal( Skill_MakeItem( id, CUID(UID_CLEAR), SKTRIG_SELECT, true ) );
}
return true;
case CHC_SKILLUSEQUICK:
{
ptcKey += 13;
GETNONWHITESPACE( ptcKey );
if ( *ptcKey )
{
tchar * ppArgs[4];
int iQty = Str_ParseCmds(const_cast<tchar *>(ptcKey), ppArgs, CountOf( ppArgs ));
if ( iQty >= 2 )
{
SKILL_TYPE iSkill = g_Cfg.FindSkillKey( ppArgs[0] );
if ( iSkill == SKILL_NONE )
return false;
sVal.FormatVal( Skill_UseQuick( iSkill, Exp_GetVal( ppArgs[1] ), true ,(Exp_GetVal(ppArgs[2]) != 0 ? false : true), (Exp_GetVal(ppArgs[3]) != 0 ? true : false)));
return true;
}
}
} return false;
case CHC_SKILLTEST:
{
ptcKey += 9;
if ( *ptcKey )
{
CResourceQtyArray Resources;
if ( Resources.Load(ptcKey) > 0 && SkillResourceTest( &Resources ) )
{
sVal.FormatVal(1);
return true;
}
}
}
sVal.FormatVal(0);
return true;
case CHC_CANMOVE:
{
ptcKey += 7;
GETNONWHITESPACE(ptcKey);
CPointMap ptDst = GetTopPoint();
DIR_TYPE dir = GetDirStr(ptcKey);
ptDst.Move( dir );
dword dwBlockFlags = 0;
CRegion * pArea;
pArea = CheckValidMove( ptDst, &dwBlockFlags, dir, nullptr );
sVal.FormatHex( pArea ? pArea->GetResourceID().IsValidUID() : 0 );
}
return true;
case CHC_MOUNT:
{
CItem *pItem = LayerFind(LAYER_HORSE);
if ( pItem )
sVal.FormatHex(pItem->m_itFigurine.m_UID);
else
sVal.FormatVal(0);
return true;
}
case CHC_MOVE:
{
ptcKey += 4;
GETNONWHITESPACE(ptcKey);
CPointMap ptDst = GetTopPoint();
ptDst.Move( GetDirStr( ptcKey ) );
CRegion * pArea = ptDst.GetRegion( REGION_TYPE_MULTI | REGION_TYPE_AREA );
if ( !pArea )
sVal.FormatHex( UINT32_MAX );
else
{
dword dwBlockFlags = 0;
CWorldMap::GetHeightPoint2( ptDst, dwBlockFlags, true );
sVal.FormatHex( dwBlockFlags );
}
}
return true;
case CHC_DISPIDDEC: // for properties dialog.
sVal.FormatVal( pCharDef->m_trackID );
return true;
case CHC_GUILDABBREV:
{
lpctstr pszAbbrev = Guild_Abbrev(MEMORY_GUILD);
sVal = ( pszAbbrev ) ? pszAbbrev : "";
}
return true;
case CHC_ID:
sVal = g_Cfg.ResourceGetName( pCharDef->GetResourceID());
return true;
case CHC_ISGM:
sVal.FormatVal( IsPriv(PRIV_GM));
return true;
case CHC_ISINPARTY:
if ( m_pPlayer != nullptr )
sVal = ( m_pParty != nullptr ) ? "1" : "0";
else
sVal = "0";
return true;
case CHC_ISMYPET:
if (!m_pNPC)
return false;
sVal = NPC_IsOwnedBy( pCharSrc, true ) ? "1" : "0";
return true;
case CHC_ISONLINE:
if ( m_pPlayer != nullptr )
{
sVal = IsClientActive() ? "1" : "0";
return true;
}
if ( m_pNPC != nullptr )
{
sVal = IsDisconnected() ? "0" : "1";
return true;
}
sVal = 0;
return true;
case CHC_ISSTUCK:
{
sVal.FormatVal(IsStuck(true));
return true;
}
case CHC_ISVENDOR:
sVal.FormatVal(NPC_IsVendor() ? 1 : 0);
return true;
case CHC_ISVERTICALSPACE:
{
ptcKey += 15;
CPointMap pt;
if ( strlen( ptcKey ) )
{
pt = g_Cfg.GetRegionPoint(ptcKey);
if ( ! pt.IsValidPoint() )
{
DEBUG_ERR(("An invalid point passed as an argument to the function IsVerticalSpace.\n"));
return false;
}
}
else
pt = GetTopPoint();
sVal.FormatVal( IsVerticalSpace( pt, false ) );
return true;
}
case CHC_MEMORY:
// What is our memory flags about this pSrc person.
{
uint uiFlags = 0;
CItemMemory *pMemory;
ptcKey += 6;
if ( *ptcKey == '.' )
{
++ptcKey;
pMemory = Memory_FindObj(CUID(Exp_GetVal(ptcKey)));
}
else
pMemory = Memory_FindObj( pCharSrc );
if ( pMemory != nullptr )
{
uiFlags = pMemory->GetMemoryTypes();
}
sVal.FormatHex( uiFlags );
}
return true;
case CHC_NAME:
sVal = GetName(false);
break;
case CHC_SKILLTOTAL:
{
ptcKey += 10;
SKIP_SEPARATORS(ptcKey);
GETNONWHITESPACE(ptcKey);
int iVal = 0;
bool fComp = true;
if ( *ptcKey == '\0' )
;
else if ( *ptcKey == '+' )
iVal = Exp_GetVal( ++ptcKey );
else if ( *ptcKey == '-' )
iVal = - Exp_GetVal( ++ptcKey );
else
{
iVal = Exp_GetVal( ptcKey );
fComp = false;
}
sVal.FormatVal( GetSkillTotal(iVal,fComp) );
}
return true;
case CHC_SWING:
sVal.FormatVal( m_atFight.m_iWarSwingState );
break;
case CHC_TOWNABBREV:
{
lpctstr pszAbbrev = Guild_Abbrev(MEMORY_TOWN);
sVal = ( pszAbbrev ) ? pszAbbrev : "";
}
return true;
case CHC_MAXWEIGHT:
sVal.FormatVal( g_Cfg.Calc_MaxCarryWeight(this));
return true;
case CHC_ACCOUNT:
if ( ptcKey[7] == '.' ) // used as a ref ?
{
if ( m_pPlayer != nullptr )
{
ptcKey += 7;
SKIP_SEPARATORS(ptcKey);
CScriptObj * pRef = m_pPlayer->GetAccount();
if ( pRef )
{
if ( pRef->r_WriteVal( ptcKey, sVal, pSrc ) )
break;
return ( false );
}
}
}
if ( m_pPlayer == nullptr )
sVal.Clear();
else
sVal = m_pPlayer->GetAccount()->GetName();
break;
case CHC_ACT:
if ( ptcKey[3] == '.' ) // used as a ref ?
goto do_default;
sVal.FormatHex( m_Act_UID.GetObjUID() ); // uid
break;
case CHC_ACTP:
if (ptcKey[4] == '.')
{
ptcKey += 4;
SKIP_SEPARATORS(ptcKey);
return m_Act_p.r_WriteVal(ptcKey, sVal);
}
sVal = m_Act_p.WriteUsed();
break;
case CHC_ACTPRV:
sVal.FormatHex( m_Act_Prv_UID.GetObjUID() );
break;
case CHC_ACTDIFF:
if (m_Act_Difficulty >= 0)
{
sVal.FormatVal(m_Act_Difficulty * 10);
}
else
{
sVal.FormatVal(m_Act_Difficulty);
}
break;
case CHC_ACTARG1:
sVal.FormatHex( m_atUnk.m_dwArg1 );
break;
case CHC_ACTARG2:
sVal.FormatHex( m_atUnk.m_dwArg2 );
break;
case CHC_ACTARG3:
sVal.FormatHex( m_atUnk.m_dwArg3 );
break;
case CHC_ACTION:
{
const CSkillDef* pSkillDef = g_Cfg.GetSkillDef(Skill_GetActive());
if (pSkillDef != nullptr)
sVal = pSkillDef->GetKey();
else
{
tchar *z = Str_GetTemp();
sprintf(z, "%d", Skill_GetActive());
sVal = z;
}
}
break;
case CHC_BODY:
sVal = g_Cfg.ResourceGetName( CResourceID( RES_CHARDEF, GetDispID()) );
break;
case CHC_CREATE:
sVal.FormatLLVal( CWorldGameTime::GetCurrentTime().GetTimeDiff(_iTimeCreate) / MSECS_PER_TENTH ); // Displayed in Tenths of Second.
break;
case CHC_DIR:
{
ptcKey +=3;
CChar * pChar = CUID::CharFindFromUID(Exp_GetSingle(ptcKey));
if ( pChar )
sVal.FormatVal( GetDir(pChar) );
else
sVal.FormatVal( m_dirFace );
}break;
case CHC_EMOTEACT:
sVal.FormatVal( IsStatFlag(STATF_EMOTEACTION) );
break;
case CHC_FLAGS:
sVal.FormatULLHex(_uiStatFlag);
break;
case CHC_FONT:
sVal.FormatVal( m_fonttype );
break;
case CHC_SPEECHCOLOROVERRIDE:
sVal.FormatWVal( m_SpeechHueOverride );
break;
case CHC_EMOTECOLOROVERRIDE:
sVal.FormatWVal( m_EmoteHueOverride );
break;
case CHC_STEPSTEALTH:
sVal.FormatVal( m_StepStealth );
break;
case CHC_HEIGHT:
sVal.FormatUCVal( GetHeight() );
break;
case CHC_OSTR:
sVal.FormatUSVal( Stat_GetBase(STAT_STR) );
break;
case CHC_MODSTR:
sVal.FormatVal( Stat_GetMod(STAT_STR) );
break;
case CHC_STR:
sVal.FormatUSVal( Stat_GetAdjusted(STAT_STR) );
break;
case CHC_ODEX:
sVal.FormatUSVal( Stat_GetBase(STAT_DEX) );
break;
case CHC_MODDEX:
sVal.FormatVal( Stat_GetMod(STAT_DEX) );
break;
case CHC_DEX:
sVal.FormatUSVal( Stat_GetAdjusted(STAT_DEX) );
break;
case CHC_OINT:
sVal.FormatUSVal( Stat_GetBase(STAT_INT) );
break;
case CHC_MODINT:
sVal.FormatVal( Stat_GetMod(STAT_INT) );
break;
case CHC_INT:
sVal.FormatUSVal( Stat_GetAdjusted(STAT_INT) );
break;
case CHC_HITPOINTS:
case CHC_HITS:
sVal.FormatUSVal( Stat_GetVal(STAT_STR) );
break;
case CHC_STAM:
case CHC_STAMINA:
sVal.FormatUSVal( Stat_GetVal(STAT_DEX) );
break;
case CHC_MANA:
sVal.FormatUSVal( Stat_GetVal(STAT_INT) );
break;
case CHC_OFOOD:
sVal.FormatUSVal( Stat_GetBase(STAT_FOOD) );
break;
case CHC_FOOD:
sVal.FormatUSVal( Stat_GetVal(STAT_FOOD) );
break;
case CHC_MAXFOOD:
sVal.FormatUSVal( Stat_GetMaxAdjusted(STAT_FOOD) );
break;
case CHC_MAXHITS:
sVal.FormatUSVal( Stat_GetMaxAdjusted(STAT_STR) );
break;
case CHC_OMAXHITS:
sVal.FormatUSVal( Stat_GetMax(STAT_STR) );
break;
case CHC_MAXMANA:
sVal.FormatUSVal( Stat_GetMaxAdjusted(STAT_INT) );
break;
case CHC_OMAXMANA:
sVal.FormatUSVal( Stat_GetMax(STAT_INT) );
break;
case CHC_MAXSTAM:
sVal.FormatUSVal( Stat_GetMaxAdjusted(STAT_DEX) );
break;
case CHC_OMAXSTAM:
sVal.FormatUSVal( Stat_GetMax(STAT_DEX) );
break;
case CHC_MODMAXHITS:
sVal.FormatVal( Stat_GetMaxMod(STAT_STR) );
break;
case CHC_MODMAXMANA:
sVal.FormatVal( Stat_GetMaxMod(STAT_INT) );
break;
case CHC_MODMAXSTAM:
sVal.FormatVal( Stat_GetMaxMod(STAT_DEX) );
break;
case CHC_REGENFOOD:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_FOOD) / MSECS_PER_SEC);
break;
case CHC_REGENFOODD:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_FOOD) / MSECS_PER_TENTH);
break;
case CHC_REGENHITS:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_STR) / MSECS_PER_SEC);
break;
case CHC_REGENHITSD:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_STR) / MSECS_PER_TENTH);
break;
case CHC_REGENSTAM:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_DEX) / MSECS_PER_SEC);
break;
case CHC_REGENSTAMD:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_DEX) / MSECS_PER_TENTH);
break;
case CHC_REGENMANA:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_INT) / MSECS_PER_SEC);
break;
case CHC_REGENMANAD:
sVal.FormatLLVal(Stats_GetRegenRate(STAT_INT) / MSECS_PER_TENTH);
break;
case CHC_REGENVALFOOD:
sVal.FormatUSVal( Stats_GetRegenVal(STAT_FOOD) );
break;
case CHC_REGENVALHITS:
sVal.FormatUSVal( Stats_GetRegenVal(STAT_STR) );
break;
case CHC_REGENVALSTAM:
sVal.FormatUSVal( Stats_GetRegenVal(STAT_DEX) );
break;
case CHC_REGENVALMANA:
sVal.FormatUSVal( Stats_GetRegenVal(STAT_INT) );
break;
case CHC_HOME:
sVal = m_ptHome.WriteUsed();
break;
case CHC_NOTOGETFLAG:
{
ptcKey += 11;
GETNONWHITESPACE(ptcKey);
const CUID uid(Exp_GetDWVal(ptcKey));
SKIP_ARGSEP( ptcKey );
const bool fAllowIncog = ( Exp_GetVal( ptcKey ) >= 1 );
SKIP_ARGSEP( ptcKey );
const bool fAllowInvul = ( Exp_GetVal( ptcKey ) >= 1 );
const CChar * pChar;
if ( ! uid.IsValidUID() )
pChar = pCharSrc;
else
{
pChar = uid.CharFind();
if ( ! pChar )
pChar = pCharSrc;
}
sVal.FormatVal( Noto_GetFlag( pChar, fAllowIncog, fAllowInvul ) );
}
break;
case CHC_NPC:
goto do_default;
case CHC_OBODY:
sVal = g_Cfg.ResourceGetName( CResourceID( RES_CHARDEF, _iPrev_id ));
break;
case CHC_OSKIN:
sVal.FormatHex( _wPrev_Hue );
break;
case CHC_P:
goto do_default;
case CHC_RANGE:
{
const uchar iRangeH = GetRangeH(), iRangeL = GetRangeL();
if ( iRangeL == 0 )
sVal.Format( "%hhd", iRangeH );
else
sVal.Format( "%hhd,%hhd", iRangeH, iRangeL );
break;
}
case CHC_RANGEH:
sVal.FormatBVal(GetRangeH());
break;
case CHC_RANGEL:
sVal.FormatBVal(GetRangeL());
break;
case CHC_STONE:
sVal.FormatVal( IsStatFlag( STATF_STONE ));
break;
case CHC_TITLE:
{
if (strlen(ptcKey) == 5)
sVal = m_sTitle; //GetTradeTitle
else
sVal = GetTradeTitle();
}
break;
case CHC_EXP:
sVal.FormatVal(m_exp);
break;
case CHC_LEVEL:
sVal.FormatVal(m_level);
break;
case CHC_GOLD:
if (!(g_Cfg.m_iFeatureTOL & FEATURE_TOL_VIRTUALGOLD))
{
sVal.FormatVal(ContentCount(CResourceID(RES_TYPEDEF, IT_GOLD)));
break;
}
// not break, just run down to VIRTUALGOLD
FALLTHROUGH;
case CHC_VIRTUALGOLD:
sVal.FormatLLVal(m_virtualGold);
break;
case CHC_VISUALRANGE:
sVal.FormatVal(GetVisualRange());
break;
default:
return false;
}
return true;
EXC_CATCH;
EXC_DEBUG_START;
EXC_ADD_KEYRET(pSrc);
EXC_DEBUG_END;
return false;
}
bool CChar::r_LoadVal( CScript & s )
{
ADDTOCALLSTACK("CChar::r_LoadVal");
EXC_TRY("LoadVal");
// Checking Props CComponents first (first check CChar props, if not found then check CCharBase)
EXC_SET_BLOCK("EntityProps");
if (CEntityProps::r_LoadPropVal(s, this, Base_GetDef()))
{
return true;
}
// Now check regular CComponents
EXC_SET_BLOCK("CEntity");
if (CEntity::r_LoadVal(s))
{
return true;
}
EXC_SET_BLOCK("Keyword");
lpctstr ptcKey = s.GetKey();
CHC_TYPE iKeyNum = (CHC_TYPE) FindTableHeadSorted( ptcKey, sm_szLoadKeys, CountOf( sm_szLoadKeys )-1 );
if ( iKeyNum < 0 )
{
if ( m_pPlayer )
{
if ( m_pPlayer->r_LoadVal( this, s ))
return true;
}
if ( m_pNPC )
{
if ( m_pNPC->r_LoadVal( this, s ))
return true;
}
// special load values
int i = g_Cfg.FindSkillKey( ptcKey );
if ( IsSkillBase((SKILL_TYPE)i) )
{
// Check some skill name.
Skill_SetBase((SKILL_TYPE)i, s.GetArgUSVal() );
return true;
}
return CObjBase::r_LoadVal( s );
}
switch (iKeyNum)
{
//Status Update Variables
case CHC_REGENHITS:
Stats_SetRegenRate(STAT_STR, s.GetArg64Val()* MSECS_PER_SEC);
break;
case CHC_REGENHITSD:
Stats_SetRegenRate(STAT_STR, s.GetArg64Val()* MSECS_PER_TENTH);
break;
case CHC_REGENSTAM:
Stats_SetRegenRate(STAT_DEX, s.GetArg64Val()* MSECS_PER_SEC);
break;
case CHC_REGENSTAMD:
Stats_SetRegenRate(STAT_DEX, s.GetArg64Val()* MSECS_PER_TENTH);
break;
case CHC_REGENMANA:
Stats_SetRegenRate(STAT_INT, s.GetArg64Val()* MSECS_PER_SEC);
break;
case CHC_REGENMANAD:
Stats_SetRegenRate(STAT_INT, s.GetArg64Val()* MSECS_PER_TENTH);
break;
case CHC_REGENFOOD:
Stats_SetRegenRate(STAT_FOOD, s.GetArg64Val()* MSECS_PER_SEC);
break;
case CHC_REGENFOODD:
Stats_SetRegenRate(STAT_FOOD, s.GetArg64Val()* MSECS_PER_TENTH);
break;
case CHC_REGENVALHITS:
Stats_SetRegenVal(STAT_STR, s.GetArgUSVal());
break;
case CHC_REGENVALSTAM:
Stats_SetRegenVal(STAT_DEX, s.GetArgUSVal());
break;
case CHC_REGENVALMANA:
Stats_SetRegenVal(STAT_INT, s.GetArgUSVal());
break;
case CHC_REGENVALFOOD:
Stats_SetRegenVal(STAT_FOOD, s.GetArgUSVal());
break;
case CHC_CURFOLLOWER:
case CHC_MAXFOLLOWER:
case CHC_TITHING:
{
SetDefNum(s.GetKey(), s.GetArgVal(), false);
UpdateStatsFlag();
}
break;
//Set as numbers only
case CHC_SPELLTIMEOUT:
{
SetDefNum(s.GetKey(), s.GetArgVal(), false);
}
break;
case CHC_BLOODCOLOR:
_wBloodHue = (HUE_TYPE)(s.GetArgVal());
break;
case CHC_MODSTR:
Stat_SetMod(STAT_STR, s.GetArgSVal());
break;
case CHC_OSTR:
case CHC_STR:
Stat_SetBase(STAT_STR, s.GetArgUSVal());
break;
case CHC_MODDEX:
Stat_SetMod(STAT_DEX, s.GetArgSVal());
break;
case CHC_ODEX:
case CHC_DEX:
Stat_SetBase(STAT_DEX, s.GetArgUSVal());
break;
case CHC_MODINT:
Stat_SetMod(STAT_INT, s.GetArgSVal());
break;
case CHC_OINT:
case CHC_INT:
Stat_SetBase(STAT_INT, s.GetArgUSVal());
break;
case CHC_MAXFOOD:
Stat_SetMax(STAT_FOOD, s.GetArgUSVal());
break;
case CHC_MODMAXHITS:
Stat_SetMaxMod(STAT_STR, s.GetArgSVal());
break;
case CHC_MAXHITS: // In the save files OMaxHits is stored as MaxHits (for backwards compatibility)
case CHC_OMAXHITS:
Stat_SetMax(STAT_STR, s.GetArgUSVal());
break;
case CHC_MODMAXSTAM:
Stat_SetMaxMod(STAT_DEX, s.GetArgSVal());
break;
case CHC_MAXSTAM: // In the save files OMaxStam is stored as MaxStam (for backwards compatibility)
case CHC_OMAXSTAM:
Stat_SetMax(STAT_DEX, s.GetArgUSVal());
break;
case CHC_MODMAXMANA:
Stat_SetMaxMod(STAT_INT, s.GetArgSVal());
break;
case CHC_MAXMANA: // In the save files OMaxMana is stored as MaxMana (for backwards compatibility)
case CHC_OMAXMANA:
Stat_SetMax(STAT_INT, s.GetArgUSVal());
break;
case CHC_ACCOUNT:
return SetPlayerAccount( s.GetArgStr() );
case CHC_ACT:
m_Act_UID.SetObjUID(s.GetArgDWVal());
break;
case CHC_ACTP:
if ( ! s.HasArgs() )
m_Act_p = GetTopPoint();
else
m_Act_p.Read( s.GetArgStr() );
break;
case CHC_ACTPRV:
m_Act_Prv_UID.SetObjUID(s.GetArgVal());
break;
case CHC_ACTDIFF:
{
int iVal = s.GetArgVal();
if (iVal < -1)
{
iVal = -1;
}
else if (iVal > 0)
{
iVal /= 10;
}
m_Act_Difficulty = iVal;
}
break;
case CHC_ACTARG1:
m_atUnk.m_dwArg1 = s.GetArgVal();
break;
case CHC_ACTARG2:
m_atUnk.m_dwArg2 = s.GetArgVal();
break;
case CHC_ACTARG3:
m_atUnk.m_dwArg3 = s.GetArgVal();
break;
case CHC_ACTION:
{
lpctstr argStr = s.GetArgStr();
SKILL_TYPE skillKey = g_Cfg.FindSkillKey(argStr);
if ( (skillKey == SKILL_NONE) && (s.GetArgVal() != -1) && !IsSkillNPC(skillKey) )
g_Log.EventError("Invalid skill key: %s\n", argStr);
return Skill_Start(skillKey);
}
case CHC_ATTACKER:
{
if ( strlen(ptcKey) > 8 )
{
ptcKey += 8;
if ( *ptcKey == '.' )
{
++ptcKey;
if ( !strnicmp(ptcKey, "CLEAR", 5) )
{
if ( !m_lastAttackers.empty() )
Fight_ClearAll();
return true;
}
else if ( !strnicmp(ptcKey, "DELETE", 6) )
{
if ( !m_lastAttackers.empty() )
{
int idx = s.GetArgVal();
CChar *pChar = CUID::CharFindFromUID(idx);
if (!pChar)
return false;
Attacker_Delete(idx, false, ATTACKER_CLEAR_SCRIPT);
}
return true;
}
else if ( !strnicmp(ptcKey, "ADD", 3) )
{
CChar *pChar = CUID::CharFindFromUID(s.GetArgVal());
if ( !pChar )
return false;
Fight_Attack(pChar);
return true;
}
else if ( !strnicmp(ptcKey, "TARGET", 6) )
{
CChar *pChar = CUID::CharFindFromUID(s.GetArgVal());
if ( !pChar || (pChar == this) ) // can't set ourself as target
{
m_Fight_Targ_UID.InitUID();
return false;
}
m_Fight_Targ_UID = pChar->GetUID();
return true;
}
int attackerIndex = Exp_GetVal(ptcKey);
SKIP_SEPARATORS(ptcKey);
if ( attackerIndex < GetAttackersCount() )
{
if ( !strnicmp(ptcKey, "DAM", 3) )
{
Attacker_SetDam(attackerIndex, s.GetArgVal());
return true;
}
else if ( !strnicmp(ptcKey, "ELAPSED", 7) )
{
Attacker_SetElapsed(attackerIndex, s.GetArgVal());
return true;
}
else if ( !strnicmp(ptcKey, "THREAT", 6) )
{
Attacker_SetThreat(attackerIndex, s.GetArgVal());
return true;
}
else if ( !strnicmp(ptcKey, "DELETE", 6) )
{
Attacker_Delete(attackerIndex, false, ATTACKER_CLEAR_SCRIPT);
return true;
}
else if ( !strnicmp(ptcKey, "IGNORE", 6) )
{
bool fIgnore = s.GetArgVal() < 1 ? 0 : 1;
Attacker_SetIgnore(attackerIndex, fIgnore);
return true;
}
}
}
}
return false;
}
case CHC_BODY:
SetID( (CREID_TYPE)(g_Cfg.ResourceGetIndexType( RES_CHARDEF, s.GetArgStr())) );
break;
case CHC_BREATH:
{
if ( !strnicmp(ptcKey, "BREATH.DAM", 10) || !strnicmp(ptcKey, "BREATH.HUE", 10) || !strnicmp(ptcKey, "BREATH.ANIM", 11) || !strnicmp(ptcKey, "BREATH.TYPE", 11) || !strnicmp(ptcKey, "BREATH.DAMTYPE", 14))
{
SetDefNum(s.GetKey(), s.GetArgLLVal());
return true;
}
return false;
}break;
case CHC_CREATE:
{
if (g_Serv.IsLoading())
{
_iTimeCreate = (CWorldGameTime::GetCurrentTime().GetTimeRaw() - (s.GetArgLLVal() * MSECS_PER_TENTH));
break;
}
return false;
}
case CHC_DIR:
{
DIR_TYPE dir = static_cast<DIR_TYPE>(s.GetArgVal());
if (dir <= DIR_INVALID || dir >= DIR_QTY)
dir = DIR_SE;
m_dirFace = dir;
UpdateDir( dir );
}
break;
case CHC_DISMOUNT:
Horse_UnMount();
break;
case CHC_EMOTEACT:
{
bool fSet = IsStatFlag(STATF_EMOTEACTION);
if ( s.HasArgs() )
fSet = s.GetArgVal() ? true : false;
else
fSet = ! fSet;
StatFlag_Mod(STATF_EMOTEACTION,fSet);
}
break;
case CHC_FLAGS:
if (g_Serv.IsLoading())
{
// Don't set STATF_SAVEPARITY at server startup, otherwise the first worldsave will not save these chars
_uiStatFlag = s.GetArgLLVal() & ~STATF_SAVEPARITY;
break;
}
// Don't modify STATF_SAVEPARITY, STATF_PET, STATF_SPAWNED here
_uiStatFlag = (_uiStatFlag & (STATF_SAVEPARITY | STATF_PET | STATF_SPAWNED)) | (s.GetArgLLVal() & ~(STATF_SAVEPARITY | STATF_PET | STATF_SPAWNED));
NotoSave_Update();
break;
case CHC_FONT:
m_fonttype = (FONT_TYPE)s.GetArgVal();
if (m_fonttype >= FONT_QTY)
m_fonttype = FONT_NORMAL;
break;
case CHC_SPEECHCOLOROVERRIDE:
m_SpeechHueOverride = (HUE_TYPE)s.GetArgWVal();
break;
case CHC_EMOTECOLOROVERRIDE:
m_EmoteHueOverride = (HUE_TYPE)s.GetArgWVal();
break;
case CHC_OFOOD: // used in the save file
Stat_SetBase(STAT_FOOD, s.GetArgUSVal());
break;
case CHC_FOOD:
Stat_SetVal(STAT_FOOD, s.GetArgUSVal());
break;
case CHC_HITPOINTS:
case CHC_HITS:
Stat_SetVal(STAT_STR, (ushort)std::max(s.GetArgVal(), 0));
UpdateHitsFlag();
break;
case CHC_MANA:
Stat_SetVal(STAT_INT, (ushort)std::max(s.GetArgVal(), 0));
UpdateManaFlag();
break;
case CHC_STAM:
case CHC_STAMINA:
Stat_SetVal(STAT_DEX, (ushort)std::max(s.GetArgVal(), 0));
UpdateStamFlag();
break;
case CHC_STEPSTEALTH:
m_StepStealth = s.GetArgVal();
break;
case CHC_HEIGHT:
m_height = (height_t)(s.GetArgVal());
break;
case CHC_HOME:
if ( ! s.HasArgs() )
m_ptHome = GetTopPoint();
else
m_ptHome.Read( s.GetArgStr() );
break;
case CHC_NAME:
{
if ( IsTrigUsed(TRIGGER_RENAME) )
{
CScriptTriggerArgs args;
args.m_s1 = s.GetArgStr();
args.m_pO1 = this;
if ( this->OnTrigger(CTRIG_Rename, this, &args) == TRIGRET_RET_TRUE )
return false;
SetName( args.m_s1 );
}
else
SetName( s.GetArgStr() );
}
break;
case CHC_OFAME:
case CHC_FAME:
SetFame(s.GetArgUSVal());
break;
case CHC_OKARMA:
case CHC_KARMA:
SetKarma(s.GetArgSVal());
break;
case CHC_SKILLUSEQUICK:
{
if ( s.GetArgStr() )
{
tchar * ppArgs[4];
int iQty = Str_ParseCmds(const_cast<tchar *>(s.GetArgStr()), ppArgs, CountOf( ppArgs ));
if ( iQty >= 2 )
{
SKILL_TYPE iSkill = g_Cfg.FindSkillKey( ppArgs[0] );
if ( iSkill == SKILL_NONE )
return false;
Skill_UseQuick( iSkill, Exp_GetVal( ppArgs[1] ), true, (Exp_GetVal(ppArgs[2]) != 0 ? false : true), (Exp_GetVal(ppArgs[3]) != 0 ? true : false));
return true;
}
}
} return false;
case CHC_MEMORY:
{
int64 piCmd[2];
int iArgQty = Str_ParseCmds( s.GetArgStr(), piCmd, CountOf(piCmd) );
if ( iArgQty < 2 )
return false;
const CUID uid((dword)piCmd[0]);
const word wFlags = (word)piCmd[1];
Memory_AddObjTypes( uid, wFlags );
}
break;
case CHC_NPC:
return SetNPCBrain((NPCBRAIN_TYPE)(s.GetArgVal()));
case CHC_OBODY:
{
CREID_TYPE id = (CREID_TYPE)(g_Cfg.ResourceGetIndexType( RES_CHARDEF, s.GetArgStr()));
if ( ! CCharBase::FindCharBase( id ) )
{
DEBUG_ERR(( "OBODY Invalid Char 0%x\n", id ));
return false;
}
_iPrev_id = id;
}
break;
case CHC_OSKIN:
_wPrev_Hue = (HUE_TYPE)(s.GetArgWVal());
break;
case CHC_P:
{
CPointMap pt;
pt.Read( s.GetArgStr() );
if (pt.IsValidPoint())
MoveTo(pt);
else
return false;
}
break;
case CHC_RANGE:
{
_uiRange = CBaseBaseDef::ConvertRangeStr(s.GetArgStr());
break;
}
case CHC_RANGEH:
case CHC_RANGEL:
return false;
case CHC_STONE:
{
bool fSet;
bool fChange = IsStatFlag(STATF_STONE);
if ( s.HasArgs() )
{
fSet = s.GetArgVal() ? true : false;
fChange = ( fSet != fChange );
}
else
{
fSet = ! fChange;
fChange = true;
}
StatFlag_Mod(STATF_STONE,fSet);
if ( fChange )
{
UpdateMode(nullptr, true);
if ( IsClientActive() )
m_pClient->addCharMove(this);
}
}
break;
case CHC_SWING:
{
int iVal = s.GetArgVal();
if ( iVal && ((iVal < -1) || (iVal > WAR_SWING_SWINGING) ) )
return false;
m_atFight.m_iWarSwingState = (WAR_SWING_TYPE)iVal;
}
break;
case CHC_TITLE:
m_sTitle = s.GetArgStr();
break;
case CHC_EXP:
m_exp = s.GetArgUVal();
ChangeExperience(); // auto-update level if applicable
break;
case CHC_LEVEL:
m_level = s.GetArgUVal();
ChangeExperience();
break;
case CHC_GOLD:
{
if (!(g_Cfg.m_iFeatureTOL & FEATURE_TOL_VIRTUALGOLD))
{
int newGold = s.GetArgVal();
if (newGold < 0)
return false;
int currentGold = ContentCount(CResourceID(RES_TYPEDEF, IT_GOLD));
if (newGold < currentGold)
{
ContentConsume(CResourceID(RES_TYPEDEF, IT_GOLD), currentGold - newGold);
}
else if (newGold > currentGold)
{
CItemContainer *pBank = GetBank();
if (!pBank)
return false;
AddGoldToPack(newGold - currentGold, pBank);
}
UpdateStatsFlag();
break;
}
// not break, just run down to VIRTUALGOLD
FALLTHROUGH;
}
case CHC_VIRTUALGOLD:
m_virtualGold = s.GetArgLLVal();
UpdateStatsFlag();
break;
case CHC_VISUALRANGE:
SetVisualRange(s.GetArgBVal());
break;
default:
return false;
}
return true;
EXC_CATCH;
EXC_DEBUG_START;
EXC_ADD_SCRIPT;
EXC_DEBUG_END;
return false;
}
void CChar::r_Write( CScript & s )
{
ADDTOCALLSTACK("CChar::r_Write");
EXC_TRY("r_Write");
s.WriteSection("WORLDCHAR %s", GetResourceName());
s.WriteKeyVal("CREATE", CWorldGameTime::GetCurrentTime().GetTimeDiff(_iTimeCreate) / MSECS_PER_TENTH );
// Do not save TAG.LastHit (used by PreHit combat flag). It's based on the server uptime, so if this tag isn't zeroed,
// after the server restart the char may not be able to attack until the server reaches the serv.time when the previous TAG.LastHit was set.
int64 iValLastHit = 0;
CVarDefContNum* pVarLastHit = m_TagDefs.GetKeyDefNum("LastHit");
if (pVarLastHit)
{
iValLastHit = pVarLastHit->GetValNum();
pVarLastHit->SetValNum(0);
}
CObjBase::r_Write(s);
if (iValLastHit != 0)
{
pVarLastHit->SetValNum(iValLastHit);
}
if ( m_pPlayer )
m_pPlayer->r_WriteChar(this, s);
if ( m_pNPC )
m_pNPC->r_WriteChar(this, s);
const CPointMap& pt = GetTopPoint();
if (pt.IsValidPoint())
s.WriteKeyStr("P", pt.WriteUsed());
if ( !m_sTitle.IsEmpty() )
s.WriteKeyStr("TITLE", m_sTitle);
if ( m_fonttype != FONT_NORMAL )
s.WriteKeyVal("FONT", m_fonttype);
if (m_SpeechHueOverride)
s.WriteKeyVal("SPEECHCOLOROVERRIDE", m_SpeechHueOverride);
if (m_EmoteHueOverride)
s.WriteKeyVal("EMOTECOLOROVERRIDE", m_EmoteHueOverride);
if ( m_dirFace != DIR_SE )
s.WriteKeyVal("DIR", m_dirFace);
if ( _iPrev_id != GetID() )
s.WriteKeyStr("OBODY", g_Cfg.ResourceGetName(CResourceID(RES_CHARDEF, _iPrev_id)));
if ( _wPrev_Hue != HUE_DEFAULT )
s.WriteKeyHex("OSKIN", _wPrev_Hue);
if ( _uiStatFlag )
s.WriteKeyHex("FLAGS", _uiStatFlag);
if ( m_attackBase )
s.WriteKeyFormat("DAM", "%" PRIu16 ",%" PRIu16, m_attackBase, m_attackBase + m_attackRange);
if ( m_defense )
s.WriteKeyVal("ARMOR", m_defense);
const uint uiActUID = m_Act_UID.GetObjUID();
if ((uiActUID & UID_UNUSED) != UID_UNUSED)
s.WriteKeyHex("ACT", uiActUID);
if ( m_Act_p.IsValidPoint() )
s.WriteKeyStr("ACTP", m_Act_p.WriteUsed());
const SKILL_TYPE action = Skill_GetActive();
if (action != SKILL_NONE)
{
const CSkillDef* pSkillDef = g_Cfg.GetSkillDef(action);
tchar* pszActionTemp;
if (pSkillDef != nullptr)
pszActionTemp = const_cast<tchar*>(pSkillDef->GetKey());
else
pszActionTemp = Str_FromI_Fast(action, Str_GetTemp(), STR_TEMPLENGTH, 10);
s.WriteKeyStr("ACTION", pszActionTemp);
/* We save ACTARG1/ACTARG2/ACTARG3 only if the following conditions are satisfied:
ACTARG1/ACTARG2/ACTARG3 is different from 0 AND
The character action is one of the valid skill OR
The character action is one of the NPC Action that uses ACTARG1/ACTARG2/ACTARG3
*/
if ((action > SKILL_NONE && action < SKILL_QTY) || action == NPCACT_FLEE || action == NPCACT_TALK || action == NPCACT_TALK_FOLLOW || action == NPCACT_RIDDEN)
{
if (m_atUnk.m_dwArg1 != 0)
s.WriteKeyHex("ACTARG1", m_atUnk.m_dwArg1);
if (m_atUnk.m_dwArg2 != 0)
s.WriteKeyHex("ACTARG2", m_atUnk.m_dwArg2);
if (m_atUnk.m_dwArg3 != 0)
s.WriteKeyHex("ACTARG3", m_atUnk.m_dwArg3);
}
}
if ( m_virtualGold )
s.WriteKeyVal("VIRTUALGOLD", m_virtualGold);
if ( m_exp )
s.WriteKeyVal("EXP", m_exp);
if ( m_level )
s.WriteKeyVal("LEVEL", m_level);
if ( m_height )
s.WriteKeyVal("HEIGHT", m_height);
if ( m_ptHome.IsValidPoint() )
s.WriteKeyStr("HOME", m_ptHome.WriteUsed());
if ( m_StepStealth )
s.WriteKeyVal("STEPSTEALTH", m_StepStealth);
// Storing them with the O prefix for backwards compatibility
s.WriteKeyVal("OKARMA", GetKarma() );
s.WriteKeyVal("OFAME", GetFame() );
int iVal;
if ((iVal = Stat_GetMod(STAT_FOOD)) != 0)
s.WriteKeyVal("MODFOOD", iVal);
if ((iVal = Stat_GetBase(STAT_FOOD)) != Char_GetDef()->m_MaxFood)
s.WriteKeyVal("OFOOD", iVal);
s.WriteKeyVal("FOOD", Stat_GetVal(STAT_FOOD));
static constexpr lpctstr _ptcKeyModStat[STAT_BASE_QTY] =
{
"MODSTR",
"MODINT",
"MODDEX"
};
static constexpr lpctstr _ptcKeyOStat[STAT_BASE_QTY] =
{
"OSTR",
"OINT",
"ODEX"
};
for (int j = 0; j < STAT_BASE_QTY; ++j)
{
// this is VERY important, saving the MOD first
if ((iVal = Stat_GetMod((STAT_TYPE)j)) != 0)
{
s.WriteKeyVal(_ptcKeyModStat[j], iVal);
}
if ((iVal = Stat_GetBase((STAT_TYPE)j)) != 0)
{
s.WriteKeyVal(_ptcKeyOStat[j], iVal);
}
}
if ((iVal = Stat_GetMaxMod(STAT_STR)) != 0)
s.WriteKeyVal("MODMAXHITS", iVal);
if ((iVal = Stat_GetMax(STAT_STR)) != Stat_GetAdjusted(STAT_STR))
s.WriteKeyVal("MAXHITS", iVal); // should be OMAXHITS, but we keep it like this for backwards compatibility
s.WriteKeyVal("HITS", Stat_GetVal(STAT_STR));
if ((iVal = Stat_GetMaxMod(STAT_DEX)) != 0)
s.WriteKeyVal("MODMAXSTAM", iVal);
if ((iVal = Stat_GetMax(STAT_DEX)) != Stat_GetAdjusted(STAT_DEX))
s.WriteKeyVal("MAXSTAM", iVal); // should be OMAXSTAM, but we keep it like this for backwards compatibility
s.WriteKeyVal("STAM", Stat_GetVal(STAT_DEX));
if ((iVal = Stat_GetMaxMod(STAT_INT)) != 0)
s.WriteKeyVal("MODMAXMANA", iVal);
if ((iVal = Stat_GetMax(STAT_INT)) != Stat_GetAdjusted(STAT_INT))
s.WriteKeyVal("MAXMANA", iVal); // should be OMAXMANA, but we keep it like this for backwards compatibility
s.WriteKeyVal("MANA", Stat_GetVal(STAT_INT));
static constexpr lpctstr _ptcKeyRegen[STAT_QTY] =
{
"REGENHITS",
"REGENMANA",
"REGENSTAM",
"REGENFOOD"
};
for (ushort j = 0; j < STAT_QTY; ++j)
{
const int64 iRegen = Stats_GetRegenRate((STAT_TYPE)j); //we cannot use ushort here because by default REGENFOOD has a value higher than 65k.
if ((iRegen >= 1) && (iRegen != g_Cfg.m_iRegenRate[j]))
s.WriteKeyVal(_ptcKeyRegen[j], iRegen / MSECS_PER_SEC);
}
static constexpr lpctstr _ptcKeyRegenVal[STAT_QTY] =
{
"REGENVALHITS",
"REGENVALMANA",
"REGENVALSTAM",
"REGENVALFOOD"
};
for (ushort j = 0; j < STAT_QTY; ++j)
{
const ushort uiRegenVal = Stats_GetRegenVal((STAT_TYPE)j);
if (uiRegenVal > 1)
s.WriteKeyVal(_ptcKeyRegenVal[j], uiRegenVal);
}
for ( uint j = 0; j < g_Cfg.m_iMaxSkill; ++j )
{
if ( !g_Cfg.m_SkillIndexDefs.IsValidIndex((SKILL_TYPE)j) )
continue;
const ushort uiSkillVal = Skill_GetBase((SKILL_TYPE)j);
if (uiSkillVal == 0)
continue;
s.WriteKeyVal(g_Cfg.GetSkillDef((SKILL_TYPE)j)->GetKey(), uiSkillVal );
}
CEntity::r_Write(s);
CEntityProps::r_Write(s);
r_WriteContent(s);
EXC_CATCH;
}
void CChar::r_WriteParity( CScript & s )
{
ADDTOCALLSTACK("CChar::r_WriteParity");
// overload virtual for world save.
// if ( GetPrivLevel() <= PLEVEL_Guest ) return;
if ( g_World.m_fSaveParity == IsStatFlag(STATF_SAVEPARITY))
{
return; // already saved.
}
StatFlag_Mod( STATF_SAVEPARITY, g_World.m_fSaveParity );
if ( IsWeird() )
return;
r_WriteSafe(s);
}
bool CChar::r_Load( CScript & s ) // Load a character from script
{
ADDTOCALLSTACK("CChar::r_Load");
CScriptObj::r_Load(s);
// Init the STATF_SAVEPARITY flag.
// StatFlag_Mod( STATF_SAVEPARITY, g_World.m_fSaveParity );
// Make sure everything is ok.
if (( m_pPlayer && ! IsClientActive()) ||
( m_pNPC && IsStatFlag( STATF_RIDDEN ))) // ridden npc
{
SetDisconnected();
}
int iResultCode = CObjBase::IsWeird();
if ( iResultCode )
{
DEBUG_ERR(( "Char 0%x Invalid, id='%s', code=0%x\n", (dword)GetUID(), GetResourceName(), iResultCode ));
Delete();
return true;
}
if (m_pNPC)
NPC_GetAllSpellbookSpells();
return true;
}
enum CHV_TYPE
{
#define ADD(a,b) CHV_##a,
#include "../../tables/CChar_functions.tbl"
#undef ADD
CHV_QTY
};
lpctstr const CChar::sm_szVerbKeys[CHV_QTY+1] =
{
#define ADD(a,b) b,
#include "../../tables/CChar_functions.tbl"
#undef ADD
nullptr
};
bool CChar::r_Verb( CScript &s, CTextConsole * pSrc ) // Execute command from script
{
ADDTOCALLSTACK("CChar::r_Verb");
if ( !pSrc )
return false;
EXC_TRY("Verb");
if ( IsClientActive() && GetClientActive()->r_Verb(s, pSrc) )
return true;
if (CEntity::r_Verb(s, pSrc))
{
return true;
}
EXC_SET_BLOCK("Verb-statement");
int index = FindTableSorted( s.GetKey(), sm_szVerbKeys, CountOf(sm_szVerbKeys)-1 );
if ( index < 0 )
{
return ( (m_pNPC && NPC_OnVerb(s, pSrc)) || (m_pPlayer && Player_OnVerb(s, pSrc)) || CObjBase::r_Verb(s, pSrc) );
}
CChar * pCharSrc = pSrc->GetChar();
switch ( index )
{
case CHV_AFK:
// toggle ?
{
bool fAFK = ( Skill_GetActive() == NPCACT_NAPPING );
bool fMode;
if ( s.HasArgs())
fMode = ( s.GetArgVal() != 0 );
else
fMode = ! fAFK;
if ( fMode != fAFK )
{
if ( fMode )
{
SysMessageDefault(DEFMSG_CMDAFK_ENTER);
m_Act_p = GetTopPoint();
Skill_Start( NPCACT_NAPPING );
}
else
{
SysMessageDefault(DEFMSG_CMDAFK_LEAVE);
Skill_Start( SKILL_NONE );
}
}
}
break;
case CHV_ALLSKILLS:
{
ushort uiVal = s.GetArgUSVal();
for ( size_t i = 0; i < g_Cfg.m_iMaxSkill; ++i )
{
if ( !g_Cfg.m_SkillIndexDefs.IsValidIndex((SKILL_TYPE)i) )
continue;
Skill_SetBase((SKILL_TYPE)i, uiVal );
}
}
break;
case CHV_ANIM:
// ANIM, ANIM_TYPE action, bool fBackward = false, byte iFrameDelay = 1
{
int64 Arg_piCmd[3]; // Maximum parameters in one line
int Arg_Qty = Str_ParseCmds(s.GetArgRaw(), Arg_piCmd, CountOf(Arg_piCmd));
if ( !Arg_Qty )
return false;
return UpdateAnimate((ANIM_TYPE)(Arg_piCmd[0]), true, false,
(Arg_Qty > 1) ? (uchar)(Arg_piCmd[1]) : 1,
(Arg_Qty > 2) ? (uchar)(Arg_piCmd[2]) : 1);
}
break;
case CHV_ATTACK:
Fight_Attack(CUID::CharFindFromUID(s.GetArgVal()), true);
break;
case CHV_BANK:
// Open the bank box for this person
if ( pCharSrc == nullptr || ! pCharSrc->IsClientActive() )
return false;
pCharSrc->GetClientActive()->addBankOpen( this, ((s.HasArgs()) ? (LAYER_TYPE)(s.GetArgVal()) : LAYER_BANKBOX ) );
break;
case CHV_BARK: // This plays creature-specific sounds (CRESND_TYPE). Use CHV_SOUND to play a precise sound ID (SOUND_TYPE) instead.
SoundChar(s.HasArgs() ? (CRESND_TYPE)s.GetArgVal() : CRESND_RAND);
break;
case CHV_BOUNCE: // uid
return ItemBounce( CUID::ItemFindFromUID( s.GetArgVal()) );
case CHV_BOW:
if (s.HasArgs())
UpdateDir( CUID::ObjFindFromUID(s.GetArgVal()) );
UpdateAnimate(ANIM_BOW);
break;
case CHV_CONTROL: // Possess
if ( pCharSrc == nullptr || ! pCharSrc->IsClientActive())
return false;
return pCharSrc->GetClientActive()->Cmd_Control(this);
case CHV_CONSUME:
{
CResourceQtyArray Resources;
Resources.Load( s.GetArgStr() );
ResourceConsume( &Resources, 1, false );
}
break;
case CHV_CRIMINAL:
if (s.HasArgs() && !s.GetArgVal())
{
CItem * pMemoryCriminal = LayerFind(LAYER_FLAG_Criminal);
if (pMemoryCriminal)
{
pMemoryCriminal->Delete();
}
else //if (IsStatFlag(STATF_CRIMINAL))
{
// Otherwise clear it manually if there's no memory set
NotoSave_Update();
if (m_pClient)
{
m_pClient->removeBuff(BI_CRIMINALSTATUS);
}
}
StatFlag_Clear(STATF_CRIMINAL);
}
else
Noto_Criminal();
break;
case CHV_DISCONNECT:
// Push a player char off line. CLIENTLINGER thing
if ( IsClientActive())
return GetClientActive()->addKick( pSrc, false );
SetDisconnected();
break;
case CHV_DROP: // uid
return ItemDrop( CUID::ItemFindFromUID(s.GetArgVal()), GetTopPoint() );
case CHV_DUPE: // = dupe a creature !
{
CChar * pChar = CreateNPC( GetID() );
pChar->MoveTo( GetTopPoint() );
pChar->DupeFrom(this, s.GetArgVal() < 1 ? true : false);
pChar->_iCreatedResScriptIdx = s.m_iResourceFileIndex;
pChar->_iCreatedResScriptLine = s.m_iLineNum;
}
break;
case CHV_EQUIP: // uid
return ItemEquip( CUID::ItemFindFromUID(s.GetArgVal()) );
case CHV_EQUIPHALO:
{
// equip a halo light
CItem * pItem = CItem::CreateScript(ITEMID_LIGHT_SRC, this);
ASSERT(pItem);
if ( s.HasArgs()) // how long to last ?
{
int64 iTimer = s.GetArgLLVal();
if ( iTimer > 0 )
pItem->SetTimeout(iTimer);
//pItem->Item_GetDef()->m_ttNormal.m_tData4 = 0; // why would we alter the itemdef data?
}
pItem->SetAttr(ATTR_MOVE_NEVER);
LayerAdd( pItem, LAYER_HAND2 );
}
return true;
case CHV_EQUIPARMOR:
return ItemEquipArmor(false);
case CHV_EQUIPWEAPON:
// find my best waepon for my skill and equip it.
return ItemEquipWeapon(false);
case CHV_FACE:
{
lpctstr pszVerbArg = s.GetArgStr();
GETNONWHITESPACE(pszVerbArg);
if (*pszVerbArg == '\0')
{
UpdateDir(dynamic_cast<CObjBase*>(pCharSrc));
return true;
}
else if (IsStrNumeric(pszVerbArg))
{
CObjBase* pTowards = CUID::ObjFindFromUID(s.GetArgVal());
if (pTowards != nullptr)
{
UpdateDir(pTowards);
return true;
}
}
else
{
CPointMap pt;
pt.Read(s.GetArgStr());
if (pt.IsValidPoint())
{
UpdateDir(pt);
return true;
}
}
return false;
}
case CHV_FIXWEIGHT:
FixWeight();
break;
case CHV_FORGIVE:
Jail( pSrc, false, 0 );
break;
case CHV_GOCHAR: // uid
return TeleportToObj( 1, s.GetArgStr());
case CHV_GOCHARID:
return TeleportToObj( 3, s.GetArgStr());
case CHV_GOCLI: // enum clients
return TeleportToCli( 1, s.GetArgVal());
case CHV_GOITEMID:
return TeleportToObj( 4, s.GetArgStr());
case CHV_GONAME:
return TeleportToObj( 0, s.GetArgStr());
case CHV_GO:
return Spell_Teleport( g_Cfg.GetRegionPoint(s.GetArgStr()), true, false );
case CHV_GOSOCK: // sockid
return TeleportToCli( 0, s.GetArgVal());
case CHV_GOTYPE:
return TeleportToObj( 2, s.GetArgStr());
case CHV_GOUID: // uid
if ( s.HasArgs() )
{
const CObjBaseTemplate * pObj = CUID::ObjFindFromUID(s.GetArgVal());
if ( pObj == nullptr )
return false;
pObj = pObj->GetTopLevelObj();
Spell_Teleport( pObj->GetTopPoint(), true, false );
return true;
}
return false;
case CHV_HEAR:
// NPC will hear this command but no-one else.
if ( m_pPlayer )
SysMessage(s.GetArgStr());
else
NPC_OnHear(s.GetArgStr(), pSrc->GetChar());
break;
case CHV_HUNGRY: // How hungry are we ?
if ( pCharSrc )
{
tchar *z = Str_GetTemp();
if ( pCharSrc == this )
snprintf(z, STR_TEMPLENGTH, g_Cfg.GetDefaultMsg(DEFMSG_MSG_FOOD_LVL_SELF), Food_GetLevelMessage( false, false ));
else
snprintf(z, STR_TEMPLENGTH, g_Cfg.GetDefaultMsg(DEFMSG_MSG_FOOD_LVL_OTHER), GetName(), Food_GetLevelMessage( false, false ));
pCharSrc->ObjMessage(z, this);
}
break;
case CHV_INVIS:
if ( pSrc )
{
_uiStatFlag = s.GetArgLLFlag( _uiStatFlag, STATF_INSUBSTANTIAL );
UpdateMode(nullptr, true);
if ( IsStatFlag(STATF_INSUBSTANTIAL) )
{
if ( IsClientActive() )
GetClientActive()->addBuff(BI_HIDDEN, 1075655, 1075656);
if ( IsSetOF(OF_Command_Sysmsgs) )
pSrc->SysMessage(g_Cfg.GetDefaultMsg(DEFMSG_MSG_INVIS_ON));
}
else
{
if ( IsClientActive() && !IsStatFlag(STATF_HIDDEN) )
GetClientActive()->removeBuff(BI_HIDDEN);
if ( IsSetOF(OF_Command_Sysmsgs) )
pSrc->SysMessage(g_Cfg.GetDefaultMsg(DEFMSG_MSG_INVIS_OFF));
}
}
break;
case CHV_INVUL:
if ( pSrc )
{
_uiStatFlag = s.GetArgLLFlag( _uiStatFlag, STATF_INVUL );
NotoSave_Update();
if ( IsSetOF( OF_Command_Sysmsgs ) )
pSrc->SysMessage( IsStatFlag( STATF_INVUL )? g_Cfg.GetDefaultMsg(DEFMSG_MSG_INVUL_ON) : g_Cfg.GetDefaultMsg(DEFMSG_MSG_INVUL_OFF) );
}
break;
case CHV_JAIL: // i am being jailed
Jail( pSrc, true, s.GetArgVal() );
break;
case CHV_KILL:
{
Effect( EFFECT_LIGHTNING, ITEMID_NOTHING, pCharSrc );
OnTakeDamage( 10000, pCharSrc, DAMAGE_GOD );
Stat_SetVal( STAT_STR, 0 );
g_Log.Event( LOGL_EVENT|LOGM_KILLS|LOGM_GM_CMDS, "'%s' was KILLed by '%s'\n", GetName(), pSrc->GetName());
}
break;
case CHV_MAKEITEM:
{
tchar *psTmp = Str_GetTemp();
Str_CopyLimitNull( psTmp, s.GetArgRaw(), STR_TEMPLENGTH );
GETNONWHITESPACE( psTmp );
tchar * ttVal[2];
int iTmp = 1;
int iArg = Str_ParseCmds( psTmp, ttVal, CountOf( ttVal ), " ,\t" );
if (!iArg)
{
return false;
}
if ( iArg == 2 )
{
if ( IsDigit( ttVal[1][0] ) )
iTmp = Str_ToI( ttVal[1] );
}
//DEBUG_ERR(( "CHV_MAKEITEM iTmp is %d, arg was %s\n",iTmp,psTmp ));
if ( IsClientActive() )
m_Act_UID = m_pClient->m_Targ_UID;
return Skill_MakeItem(
(ITEMID_TYPE)(g_Cfg.ResourceGetIndexType( RES_ITEMDEF, ttVal[0] )),
m_Act_UID, SKTRIG_START, false, iTmp );
}
case CHV_MOUNT:
{
CChar *pChar = CUID::CharFindFromUID(s.GetArgVal());
if ( pChar )
Horse_Mount(pChar);
}
break;
case CHV_NEWBIESKILL:
{
CResourceLock t;
if ( !g_Cfg.ResourceLock( t, RES_NEWBIE, s.GetArgStr()) )
return false;
ReadScriptReduced(t);
}
break;
case CHV_NEWGOLD:
{
// Usage: NEWGOLD amount, pile(1: the new gold is stacked on the existing pile in the pack; 0: stacked in a new pile)
int64 piCmd[2];
int iQty = Str_ParseCmds(s.GetArgRaw(), piCmd, CountOf(piCmd));
if (iQty < 1)
return false;
int64 iGold = piCmd[0];
if (iGold <= 0)
return false;
if (iGold > INT32_MAX)
iGold = INT32_MAX;
const bool fStackNewPile = (iQty >= 2) ? !((bool)piCmd[1]) : true;
AddGoldToPack((int)iGold, GetPackSafe(), fStackNewPile);
}
break;
case CHV_NEWLOOT:
{
if ( m_pNPC && !m_pPlayer && !IsStatFlag(STATF_CONJURED) )
{
CItem *pItem = CItem::CreateHeader(s.GetArgStr(), nullptr, false, this);
if ( !pItem )
{
g_World.m_uidNew.ClearUID();
}
else
{
pItem->_iCreatedResScriptIdx = s.m_iResourceFileIndex;
pItem->_iCreatedResScriptLine = s.m_iLineNum;
ItemEquip(pItem);
g_World.m_uidNew = pItem->GetUID();
}
}
} break;
case CHV_NOTOCLEAR:
NotoSave_Clear();
break;
case CHV_NOTOUPDATE:
NotoSave_Update();
break;
case CHV_OWNER:
{
if (!s.HasArgs()) // If there are no args, direct call on NPC_PetSetOwner.
return NPC_PetSetOwner(pCharSrc);
CChar * pChar = CUID::CharFindFromUID(s.GetArgDWVal()); // otherwise we try to run it from the CChar with the given UID.
if (pChar)
return pChar->NPC_PetSetOwner(this);
return false; // Something went wrong, giving a warning of it.
}
case CHV_PACK:
if ( pCharSrc == nullptr || ! pCharSrc->IsClientActive())
return false;
pCharSrc->m_pClient->addBankOpen( this, LAYER_PACK ); // Send Backpack (with items)
break;
case CHV_POISON:
{
int iSkill = s.GetArgVal();
int iTicks = iSkill / 50;
int64 piCmd[2];
if (Str_ParseCmds(s.GetArgRaw(), piCmd, CountOf(piCmd)) > 1)
iTicks = (int)(piCmd[1]);
SetPoison(iSkill, iTicks, pSrc->GetChar());
}
break;
case CHV_POLY: // result of poly spell script choice. (casting a spell)
{
const CSpellDef *pSpellDef = g_Cfg.GetSpellDef(SPELL_Polymorph);
if ( !pSpellDef )
return false;
m_atMagery.m_iSpell = SPELL_Polymorph;
m_atMagery.m_iSummonID = (CREID_TYPE)(g_Cfg.ResourceGetIndexType(RES_CHARDEF, s.GetArgStr()));
m_Act_UID = GetUID();
m_Act_Prv_UID = GetUID();
if ( m_pClient && IsSetMagicFlags(MAGICF_PRECAST) && !pSpellDef->IsSpellType(SPELLFLAG_NOPRECAST) )
{
Spell_CastDone();
break;
}
int skill;
if ( !pSpellDef->GetPrimarySkill(&skill, nullptr) )
return false;
Skill_Start((SKILL_TYPE)skill);
break;
}
case CHV_PRIVSET:
return SetPrivLevel( pSrc, s.GetArgStr());
case CHV_DESTROY: // remove this char from the world and bypass trigger's return value.
case CHV_REMOVE: // remove this char from the world instantly.
if ( m_pPlayer )
{
if ( s.GetArgRaw()[0] != '1' || pSrc->GetPrivLevel() < PLEVEL_Admin )
{
pSrc->SysMessage( g_Cfg.GetDefaultMsg(DEFMSG_CMD_REMOVE_PLAYER) );
return false;
}
if ( IsClientActive() )
GetClientActive()->addObjectRemove(this);
}
Delete((index == CHV_DESTROY));
break;
case CHV_RESURRECT:
{
if ( !s.GetArgVal() )
return OnSpellEffect( SPELL_Resurrection, pCharSrc, 1000, nullptr );
else
return Spell_Resurrection( nullptr, pCharSrc, true );
}
case CHV_REVEAL:
Reveal( s.GetArgDWVal());
break;
case CHV_SALUTE: // salute to player
{
if (s.HasArgs())
UpdateDir( CUID::ObjFindFromUID(s.GetArgVal()) );
UpdateAnimate(ANIM_SALUTE);
break;
}
case CHV_SKILL:
Skill_Start( g_Cfg.FindSkillKey( s.GetArgStr()));
break;
case CHV_SKILLGAIN:
{
if ( s.HasArgs() )
{
tchar * ppArgs[2];
if ( Str_ParseCmds( s.GetArgRaw(), ppArgs, CountOf( ppArgs )) > 0 )
{
SKILL_TYPE iSkill = g_Cfg.FindSkillKey( ppArgs[0] );
if ( iSkill == SKILL_NONE )
return false;
Skill_Experience( iSkill, Exp_GetVal( ppArgs[1] ));
}
}
}
return true;
case CHV_SLEEP:
SleepStart( s.GetArgVal() != 0 );
break;
case CHV_SUICIDE:
Memory_ClearTypes( MEMORY_FIGHT ); // Clear the list of people who get credit for your death
UpdateAnimate( ANIM_SALUTE );
Stat_SetVal( STAT_STR, 0 );
break;
case CHV_SUMMONCAGE: // i just got summoned
if ( pCharSrc != nullptr )
{
// Let's make a cage to put the player in
ITEMID_TYPE id = (ITEMID_TYPE)(g_Cfg.ResourceGetIndexType( RES_ITEMDEF, "i_multi_cage" ));
if ( id < 0 )
return false;
CItemMulti * pItem = dynamic_cast <CItemMulti*>( CItem::CreateBase( id ));
if ( pItem == nullptr )
return false;
CPointMap pt = pCharSrc->GetTopPoint();
pt.MoveN( pCharSrc->m_dirFace, 3 );
pItem->MoveToDecay( pt, 10*60* MSECS_PER_SEC); // make the cage vanish after 10 minutes.
pItem->Multi_Setup( nullptr, UID_CLEAR );
Spell_Teleport( pt, true, false );
break;
}
return false;
case CHV_SUMMONTO: // i just got summoned
if ( !pCharSrc )
return false;
Spell_Teleport( pCharSrc->GetTopPoint(), true, false );
break;
case CHV_SMSG:
case CHV_SMSGL:
case CHV_SMSGLEX:
case CHV_SMSGU:
case CHV_SYSMESSAGE:
case CHV_SYSMESSAGELOC:
case CHV_SYSMESSAGELOCEX:
case CHV_SYSMESSAGEUA:
// just eat this if it's not a client.
break;
case CHV_TARGETCLOSE:
if ( IsClientActive() )
GetClientActive()->addTargetCancel();
break;
case CHV_UNDERWEAR:
if ( ! IsPlayableCharacter())
return false;
SetHue( GetHue() ^ HUE_UNDERWEAR /*, false, pSrc*/ ); //call @Dye on underwear?
UpdateMode();
break;
case CHV_UNEQUIP: // uid
return ItemBounce( CUID::ItemFindFromUID(s.GetArgVal()) );
case CHV_WHERE:
if ( pCharSrc )
{
tchar *z = Str_GetTemp();
if ( m_pArea )
{
if (m_pArea->GetResourceID().IsUIDItem()) // Inside a multi region
{
snprintf(z, STR_TEMPLENGTH, g_Cfg.GetDefaultMsg(DEFMSG_MSG_WHERE_AREA), m_pArea->GetName(), GetTopPoint().WriteUsed());
}
else
{
const CRegion * pRoom = GetTopPoint().GetRegion( REGION_TYPE_ROOM );
if ( ! pRoom )
snprintf(z, STR_TEMPLENGTH, g_Cfg.GetDefaultMsg(DEFMSG_MSG_WHERE_AREA), m_pArea->GetName(), GetTopPoint().WriteUsed());
else
snprintf(z, STR_TEMPLENGTH, g_Cfg.GetDefaultMsg(DEFMSG_MSG_WHERE_ROOM), m_pArea->GetName(), pRoom->GetName(), GetTopPoint().WriteUsed());
}
}
else
{
snprintf(z, STR_TEMPLENGTH, g_Cfg.GetDefaultMsg(DEFMSG_MSG_WHERE), GetTopPoint().WriteUsed());
}
pCharSrc->ObjMessage(z, this);
}
break;
default:
return false;
}
return true;
EXC_CATCH;
EXC_DEBUG_START;
EXC_ADD_SCRIPTSRC;
EXC_DEBUG_END;
return false;
}
bool CChar::OnTriggerSpeech( bool bIsPet, lpctstr pszText, CChar * pSrc, TALKMODE_TYPE & mode, HUE_TYPE wHue)
{
ADDTOCALLSTACK("CChar::OnTriggerSpeech");
lpctstr pszName;
if ( bIsPet && !g_Cfg.m_sSpeechPet.IsEmpty() )
pszName = static_cast<lpctstr>(g_Cfg.m_sSpeechPet);
else if ( !bIsPet && !g_Cfg.m_sSpeechSelf.IsEmpty() )
pszName = static_cast<lpctstr>(g_Cfg.m_sSpeechSelf);
else
goto lbl_cchar_ontriggerspeech;
{
CScriptObj * pDef = g_Cfg.ResourceGetDefByName( RES_SPEECH, pszName );
if ( pDef )
{
CResourceLink * pLink = dynamic_cast <CResourceLink *>( pDef );
if ( pLink )
{
CResourceLock s;
if ( pLink->ResourceLock(s) && pLink->HasTrigger(XTRIG_UNKNOWN) )
{
TRIGRET_TYPE iRet = OnHearTrigger(s, pszText, pSrc, mode, wHue);
if ( iRet == TRIGRET_RET_TRUE )
return true;
else if ( iRet == TRIGRET_RET_HALFBAKED )
return false;
}
else
DEBUG_ERR(("TriggerSpeech: couldn't run script for speech %s\n", pszName));
}
else
DEBUG_ERR(("TriggerSpeech: couldn't find speech %s\n", pszName));
}
else
DEBUG_ERR(("TriggerSpeech: couldn't find speech resource %s\n", pszName));
}
lbl_cchar_ontriggerspeech:
if ( bIsPet )
return false;
if ( !m_pPlayer )
return false;
if (!m_pPlayer->m_Speech.empty())
{
for ( size_t i = 0; i < m_pPlayer->m_Speech.size(); ++i )
{
CResourceLink * pLinkDSpeech = m_pPlayer->m_Speech[i].GetRef();
if ( !pLinkDSpeech )
continue;
CResourceLock sDSpeech;
if ( !pLinkDSpeech->ResourceLock(sDSpeech) )
continue;
TRIGRET_TYPE iRet = OnHearTrigger( sDSpeech, pszText, pSrc, mode, wHue );
if ( iRet == TRIGRET_RET_TRUE )
return true;
else if ( iRet == TRIGRET_RET_HALFBAKED )
break;
}
}
return false;
}
// Gaining exp
uint Calc_ExpGet_Exp(uint level)
{
if (level <= 1)
return 0;
if (g_Cfg.m_iLevelMode == LEVEL_MODE_LINEAR)
{
return ((level-1) * g_Cfg.m_iLevelNextAt);
}
else // if (g_Cfg.m_iLevelMode == LEVEL_MODE_DOUBLE) // default
{
uint exp = 0;
for ( uint lev = 1; lev < level; ++lev )
{
exp += (g_Cfg.m_iLevelNextAt * (lev + 1));
}
return exp;
}
}
// Increasing level
uint Calc_ExpGet_Level(uint exp)
{
if (g_Cfg.m_iLevelNextAt < 1) //Must do this check in case ini's LevelNextAt is not set or server will freeze because exp will never decrease in the while.
{
g_Log.EventError("Invalid LextNevelAt value.\n");
return 0;
}
if (g_Cfg.m_iLevelMode == LEVEL_MODE_LINEAR)
{
return 1 + (exp / g_Cfg.m_iLevelNextAt);
}
else // if (g_Cfg.m_iLevelMode == LEVEL_MODE_DOUBLE) // default
{
uint level = 0;
uint iNextLevelReq = 0;
while (exp >= iNextLevelReq)
{
// reduce xp and raise level
exp -= iNextLevelReq;
++level;
// calculate requirement for next level
iNextLevelReq = (g_Cfg.m_iLevelNextAt * (level+1));
}
return level;
}
}
void CChar::ChangeExperience(llong delta, CChar *pCharDead)
{
ADDTOCALLSTACK("CChar::ChangeExperience");
if (!g_Cfg.m_iExperienceMode)
return;
static uint const keyWords[] =
{
DEFMSG_MSG_EXP_CHANGE_1, // 0
DEFMSG_MSG_EXP_CHANGE_2,
DEFMSG_MSG_EXP_CHANGE_3,
DEFMSG_MSG_EXP_CHANGE_4,
DEFMSG_MSG_EXP_CHANGE_5,
DEFMSG_MSG_EXP_CHANGE_6, // 5
DEFMSG_MSG_EXP_CHANGE_7,
DEFMSG_MSG_EXP_CHANGE_8
};
if (delta != 0 || pCharDead)// zero call will sync the exp level
{
if (delta < 0)
{
if (!(g_Cfg.m_iExperienceMode&EXP_MODE_ALLOW_DOWN)) // do not allow changes to minus
return;
// limiting delta to current level? check if delta goes out of level
if (g_Cfg.m_bLevelSystem && g_Cfg.m_iExperienceMode&EXP_MODE_DOWN_NOLEVEL)
{
uint exp = Calc_ExpGet_Exp(m_level);
if (delta + m_exp < exp)
delta = (llong)exp - m_exp;
}
}
if ((g_Cfg.m_iDebugFlags & DEBUGF_EXP) && (delta != 0))
{
g_Log.EventDebug("%s %s experience change (was %u, delta %lld, now %u)\n",
(m_pNPC ? "NPC" : "Player"), GetName(), m_exp, delta, (uint)(m_exp + delta));
}
bool fShowMsg = (m_pClient != nullptr);
if (IsTrigUsed(TRIGGER_EXPCHANGE))
{
CScriptTriggerArgs args(delta, fShowMsg);
args.m_pO1 = pCharDead;
if (OnTrigger(CTRIG_ExpChange, this, &args) == TRIGRET_RET_TRUE)
return;
delta = args.m_iN1;
fShowMsg = (args.m_iN2 != 0);
}
// Do not allow an underflow due to negative Exp Change.
if( delta < 0 && m_exp < abs(delta) )
m_exp = 0;
else
m_exp = (uint)(m_exp + delta);
if (m_pClient && fShowMsg && delta)
{
int iWord = 0;
llong absval = abs(delta);
llong maxval = (g_Cfg.m_bLevelSystem && g_Cfg.m_iLevelNextAt) ? maximum(g_Cfg.m_iLevelNextAt, 1000) : 1000;
if (absval >= maxval) // 100%
iWord = 7;
else if (absval >= (maxval * 2) / 3)// 66%
iWord = 6;
else if (absval >= maxval / 2) // 50%
iWord = 5;
else if (absval >= maxval / 3) // 33%
iWord = 4;
else if (absval >= maxval / 5) // 20%
iWord = 3;
else if (absval >= maxval / 7) // 14%
iWord = 2;
else if (absval >= maxval / 14) // 7%
iWord = 1;
m_pClient->SysMessagef(g_Cfg.GetDefaultMsg(DEFMSG_MSG_EXP_CHANGE_0),
(delta > 0) ? g_Cfg.GetDefaultMsg(DEFMSG_MSG_EXP_CHANGE_GAIN) : g_Cfg.GetDefaultMsg(DEFMSG_MSG_EXP_CHANGE_LOST),
g_Cfg.GetDefaultMsg(keyWords[iWord]));
}
}
if (g_Cfg.m_bLevelSystem)
{
llong level = Calc_ExpGet_Level(m_exp);
if (level != m_level)
{
delta = level - m_level;
bool fShowMsg = (m_pClient != nullptr);
if (IsTrigUsed(TRIGGER_EXPLEVELCHANGE))
{
CScriptTriggerArgs args(delta);
if (OnTrigger(CTRIG_ExpLevelChange, this, &args) == TRIGRET_RET_TRUE)
return;
delta = args.m_iN1;
fShowMsg = (args.m_iN2 != 0);
}
level = delta + m_level;
// Prevent integer underflow due to negative level change
if (delta < 0 && abs(delta) > m_level)
{
level = 0;
}
if (g_Cfg.m_iDebugFlags & DEBUGF_LEVEL)
{
g_Log.EventDebug("%s %s level change (was %u, delta %lld, now %u)\n",
(m_pNPC ? "NPC" : "Player"), GetName(), m_level, delta, (uint)level);
}
m_level = (uint)level;
if (m_pClient && fShowMsg)
{
m_pClient->SysMessagef(
((abs(delta) == 1) ? g_Cfg.GetDefaultMsg(DEFMSG_MSG_EXP_LVLCHANGE_0) : g_Cfg.GetDefaultMsg(DEFMSG_MSG_EXP_LVLCHANGE_1)),
((delta > 0) ? g_Cfg.GetDefaultMsg(DEFMSG_MSG_EXP_LVLCHANGE_GAIN) : g_Cfg.GetDefaultMsg(DEFMSG_MSG_EXP_LVLCHANGE_LOST))
);
}
}
}
}
// returns <SkillTotal>
uint CChar::GetSkillTotal(int what, bool how)
{
ADDTOCALLSTACK("CChar::GetSkillTotal");
uint uiTotal = 0;
ushort uiBase;
for ( size_t i = 0; i < g_Cfg.m_iMaxSkill; ++i )
{
uiBase = Skill_GetBase((SKILL_TYPE)i);
if ( how )
{
if ( what < 0 )
{
if ( uiBase >= -what )
continue;
}
else if ( uiBase < what )
continue;
}
else
{
// check group flags
const CSkillDef * pSkill = g_Cfg.GetSkillDef((SKILL_TYPE)i);
if ( !pSkill )
continue;
if ( !( pSkill->m_dwGroup & what ) )
continue;
}
uiTotal += uiBase;
}
return uiTotal;
}
|
//
// Created by Theophile Champion on 02/12/2020.
//
#include <iostream>
#include "catch.hpp"
#include "iterators/ObservedVarIter.h"
#include "contexts/FactorGraphContexts.h"
#include "graphs/FactorGraph.h"
#include "helpers/UnitTests.h"
using namespace hopi::iterators;
using namespace tests;
TEST_CASE( "ObservedVarIter do not crash when no more hidden variables are available" ) {
UnitTests::run([](){
auto fg = FactorGraphContexts::context3();
auto it = ObservedVarIter(fg.get());
for (int i = 0; i < 10; ++i) {
++it;
}
});
}
TEST_CASE( "ObservedVarIter return nullptr when no more hidden variables are available" ) {
UnitTests::run([](){
auto fg = FactorGraphContexts::context3();
auto it = ObservedVarIter(fg.get());
REQUIRE( *it != nullptr );
++it;
REQUIRE( *it != nullptr );
++it;
REQUIRE( *it != nullptr );
++it;
REQUIRE( *it == nullptr );
});
}
TEST_CASE( "ObservedVarIter return the correct hidden variable (==)" ) {
UnitTests::run([](){
auto fg = FactorGraphContexts::context3();
auto it = ObservedVarIter(fg.get());
REQUIRE( *it == fg->node(1) );
++it;
REQUIRE( *it == fg->node(4) );
++it;
REQUIRE( *it == fg->node(5) );
});
}
TEST_CASE( "ObservedVarIter return the correct hidden variable (!=)" ) {
UnitTests::run([](){
auto fg = FactorGraphContexts::context3();
auto it = ObservedVarIter(fg.get());
REQUIRE( *it != fg->node(4) );
REQUIRE( *it != fg->node(5) );
++it;
REQUIRE( *it != fg->node(1) );
REQUIRE( *it != fg->node(5) );
++it;
REQUIRE( *it != fg->node(1) );
REQUIRE( *it != fg->node(4) );
});
}
TEST_CASE( "ObservedVarIter properly support copy (=)" ) {
UnitTests::run([](){
auto fg = FactorGraphContexts::context3();
auto it = ObservedVarIter(fg.get());
REQUIRE( *it == fg->node(1) );
++it;
auto it2 = it;
REQUIRE( *it == fg->node(4) );
REQUIRE( *it2 == fg->node(4) );
++it;
REQUIRE( *it == fg->node(5) );
++it2;
REQUIRE( *it2 == fg->node(5) );
++it;
REQUIRE( *it == nullptr );
++it2;
REQUIRE( *it2 == nullptr );
});
}
|
/*
* 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 "ActsPlayerFuncTest.h"
#include "securec.h"
using namespace std;
using namespace OHOS;
using namespace OHOS::Media;
using namespace testing::ext;
using namespace PlayerNameSpace;
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0100
* @tc.name : 001.prepare-reset,销毁播放器
* @tc.desc : 播控
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0100, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Release());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0200
* @tc.name : 002.prepare-reset,不销毁播放器
* @tc.desc : 播控
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0200, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0300
* @tc.name : 003.prepare-stop-reset,销毁播放器
* @tc.desc : 播控
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0300, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Release());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0400
* @tc.name : 004.prepare-stop-reset,不销毁播放器
* @tc.desc : 播控
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0400, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0600
* @tc.name : 006.prepare-play-reset,不销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0600, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
EXPECT_TRUE(player->IsPlaying());
sleep(PLAYING_TIME);
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(time, PLAYING_TIME * 1000, 1000);
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0700
* @tc.name : 007.prepare-seek-play-reset,销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0700, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(time, PLAYING_TIME * 1000, 1000);
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Release());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0800
* @tc.name : 008.prepare-seek-play-reset,不销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0800, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(time, SEEK_TIME_5_SEC + PLAYING_TIME * 1000, 1000);
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_0900
* @tc.name : 009.prepare-play-seek-reset,销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_0900, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Release());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1000
* @tc.name : 010.prepare-play-seek-reset,不销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1000, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1100
* @tc.name : 011.prepare-play-seek-pause-reset,不销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1100, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1200
* @tc.name : 012.prepare-play-seek-pause-reset,销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1200, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Release());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1300
* @tc.name : 013.prepare-play-seek-pause-stop-reset,不销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1300, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1400
* @tc.name : 014.prepare-play-seek-pause-stop-reset,销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1400, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Release());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1500
* @tc.name : 015.prepare-play-stop-reset,不销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1500, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1600
* @tc.name : 016.prepare-play-stop-reset,销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1600, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Release());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1700
* @tc.name : 017.prepare-stop,不销毁播放器
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1700, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1800
* @tc.name : 018.pause-GetCurrentTime-play-GetCurrentTime
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1800, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(PLAYING_TIME * 1000, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(PLAYING_TIME * 1000 * 2, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_1900
* @tc.name : 019.pause-GetCurrentTime-seek-play-GetCurrentTime
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_1900, Function | MediumTest | Level0)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
int32_t time;
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(PLAYING_TIME * 1000, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_2_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_2_SEC + PLAYING_TIME * 1000, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2000
* @tc.name : 020.play-seek EOS-GetCurrentTime-进入PlaybackCompleted,loop=0
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2000, Function | MediumTest | Level1)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->SetLooping(false));
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime + 1, SEEK_MODE));
EXPECT_EQ(RET_OK, testCallback->WaitForState(PLAYER_PLAYBACK_COMPLETE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_FALSE(player->IsLooping());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(FILE_BEGIN, time);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2100
* @tc.name : 021.seek EOS-GetCurrentTime-进入PlaybackCompleted,loop=0
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2100, Function | MediumTest | Level1)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->SetLooping(false));
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime + 1, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_FALSE(player->IsLooping());
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(FILE_BEGIN, time);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2200
* @tc.name : 022.play-seek EOS-GetCurrentTime,loop=1
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2200, Function | MediumTest | Level1)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time_before;
int32_t time_after;
int32_t time;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->SetLooping(true));
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime + 1, SEEK_MODE));
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsLooping());
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time_before));
sleep(PLAYING_TIME);
EXPECT_EQ(RET_OK, player->GetCurrentTime(time_after));
EXPECT_NEAR(time_after - time_before, PLAYING_TIME * 1000, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(FILE_BEGIN, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2300
* @tc.name : 023.prepare-play-seek EOS-GetCurrentTime-进入PlaybackCompleted-stop,loop=0
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2300, Function | MediumTest | Level1)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->SetLooping(false));
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime + 1, SEEK_MODE));
EXPECT_EQ(RET_OK, testCallback->WaitForState(PLAYER_PLAYBACK_COMPLETE));
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_FALSE(player->IsLooping());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2400
* @tc.name : 024.seek,seek随机+EOS附近
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2400, Function | MediumTest | Level1)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime - 1, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(durationTime, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2500
* @tc.name : 025.pause-seek-resume,不等seek完成
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2500, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
testObj.mutexFlag_ = false;
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
testObj.mutexFlag_ = true;
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC + PLAYING_TIME * 1000, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2600
* @tc.name : 026.seek,不等seek完成,seek
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2600, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
testObj.mutexFlag_ = false;
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
testObj.mutexFlag_ = true;
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_5_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(SEEK_TIME_5_SEC, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2625
* @tc.name : 026.seek,不等seek完成,pause
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2625, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
testObj.mutexFlag_ = false;
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
testObj.mutexFlag_ = true;
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2650
* @tc.name : 026.seek,不等seek完成,GetDuration
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2650, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
testObj.mutexFlag_ = false;
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2651
* @tc.name : 026.seek,不等seek完成,GetCurrentTime
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2651, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
testObj.mutexFlag_ = false;
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(PLAYING_TIME * 1000, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2675
* @tc.name : 026.seek,不等seek完成,play
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2675, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
testObj.mutexFlag_ = false;
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
testObj.mutexFlag_ = true;
EXPECT_EQ(RET_OK, player->Play());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_NEAR(PLAYING_TIME * 1000, time, DELTA_TIME);
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2700
* @tc.name : 027.prepare-seek未完成-seek eos-start-seek eos-start-stop
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2700, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_EQ(RET_OK, player->Seek(durationTime, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_EQ(RET_OK, player->Play());
EXPECT_EQ(RET_OK, testCallback->WaitForState(PLAYER_PLAYBACK_COMPLETE));
EXPECT_FALSE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2800
* @tc.name : 028.prepare-start-pause-seek eos-stop-prepare-start-stop
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2800, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_EQ(RET_OK, player->Stop());
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
sleep(PLAYING_TIME);
EXPECT_TRUE(player->IsPlaying());
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_2900
* @tc.name : 029.prepare-seek eos-start-stop-prepare-seek eos-start-stop,loop=1
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_2900, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t time_before;
int32_t time_after;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->SetLooping(true));
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_EQ(RET_OK, player->Play());
EXPECT_EQ(RET_OK, testCallback->WaitForState(PLAYER_PLAYBACK_COMPLETE));
EXPECT_EQ(RET_OK, player->Stop());
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Seek(durationTime, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
sleep(PLAYING_TIME);
EXPECT_EQ(RET_OK, player->GetCurrentTime(time_before));
sleep(PLAYING_TIME);
EXPECT_EQ(RET_OK, player->GetCurrentTime(time_after));
EXPECT_EQ(RET_OK, player->Play());
EXPECT_EQ(RET_OK, testCallback->WaitForState(PLAYER_PLAYBACK_COMPLETE));
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
/**
* @tc.number : SUB_MEDIA_PLAYER_Local_Async_Function_04_3000
* @tc.name : 030.prepare-start-pause-seek eos-start-stop-prepare-start-pause-seek-start-stop,loop=1
* @tc.desc :
*/
HWTEST_F(ActsPlayerFuncTest, SUB_MEDIA_PLAYER_Local_Async_Function_04_3000, Function | MediumTest | Level3)
{
PlayerSignal testObj;
std::shared_ptr<TestPlayer> player = std::make_shared<TestPlayer>(&testObj);
ASSERT_NE(nullptr, player);
ASSERT_EQ(true, player->CreatePlayer());
int32_t time;
int32_t time_before;
int32_t time_after;
int32_t durationTime;
std::string uri = GetUri();
ASSERT_EQ(RET_OK, player->SetSource(uri));
sptr<Surface> videoSurface = player->GetVideoSurface(g_sub_config);
EXPECT_EQ(RET_OK, player->SetVideoSurface(videoSurface));
std::shared_ptr<TestPlayerCallback> testCallback = std::make_shared<TestPlayerCallback>(&testObj);
EXPECT_EQ(RET_OK, player->SetPlayerCallback(testCallback));
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->SetLooping(true));
EXPECT_EQ(RET_OK, player->Play());
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_EQ(RET_OK, player->GetDuration(durationTime));
EXPECT_EQ(RET_OK, player->Seek(durationTime, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(durationTime, time);
EXPECT_EQ(RET_OK, player->Play());
EXPECT_EQ(RET_OK, testCallback->WaitForState(PLAYER_PLAYBACK_COMPLETE));
sleep(PLAYING_TIME);
EXPECT_EQ(RET_OK, player->GetCurrentTime(time_before));
sleep(PLAYING_TIME);
EXPECT_EQ(RET_OK, player->GetCurrentTime(time_after));
EXPECT_NEAR(time_after - time_before, PLAYING_TIME * 1000, DELTA_TIME);
EXPECT_EQ(RET_OK, player->Stop());
ASSERT_EQ(RET_OK, player->PrepareAsync());
EXPECT_EQ(RET_OK, player->Play());
EXPECT_EQ(RET_OK, player->Pause());
EXPECT_EQ(RET_OK, player->Seek(SEEK_TIME_2_SEC, SEEK_MODE));
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(SEEK_TIME_2_SEC, time);
EXPECT_EQ(RET_OK, player->Stop());
EXPECT_EQ(RET_OK, player->GetCurrentTime(time));
EXPECT_EQ(FILE_BEGIN, time);
EXPECT_EQ(RET_OK, player->Reset());
EXPECT_EQ(RET_OK, testCallback->errorNum);
}
|
/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.0 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Object lifetime tests.
*//*--------------------------------------------------------------------*/
#include "es3fLifetimeTests.hpp"
#include "deRandom.hpp"
#include "deUniquePtr.hpp"
#include "tcuRenderTarget.hpp"
#include "tcuSurface.hpp"
#include "gluDrawUtil.hpp"
#include "gluObjectWrapper.hpp"
#include "gluPixelTransfer.hpp"
#include "gluShaderProgram.hpp"
#include "glsLifetimeTests.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
#include <vector>
namespace deqp
{
namespace gles3
{
namespace Functional
{
namespace
{
using std::vector;
using de::MovePtr;
using de::Random;
using tcu::RenderTarget;
using tcu::Surface;
using tcu::TestContext;
using tcu::TestLog;
using glu::CallLogWrapper;
using glu::RenderContext;
using glu::ProgramSources;
using glu::VertexArray;
using glu::Buffer;
namespace lt = gls::LifetimeTests;
using namespace lt;
using namespace glw;
typedef TestCase::IterateResult IterateResult;
enum { VIEWPORT_SIZE = 128 };
class ScaleProgram : public glu::ShaderProgram
{
public:
ScaleProgram (lt::Context& ctx);
void draw (GLuint vao, GLfloat scale, bool tf, Surface* dst);
void setPos (GLuint buffer, GLuint vao);
private:
ProgramSources getSources (void);
const RenderContext& m_renderCtx;
GLint m_scaleLoc;
GLint m_posLoc;
};
enum { NUM_COMPONENTS = 4, NUM_VERTICES = 3 };
ScaleProgram::ScaleProgram (lt::Context& ctx)
: glu::ShaderProgram (ctx.getRenderContext(), getSources())
, m_renderCtx (ctx.getRenderContext())
{
const Functions& gl = m_renderCtx.getFunctions();
TCU_CHECK(isOk());
m_scaleLoc = gl.getUniformLocation(getProgram(), "scale");
m_posLoc = gl.getAttribLocation(getProgram(), "pos");
}
#define GLSL(VERSION, BODY) ("#version " #VERSION "\n" #BODY "\n")
static const char* const s_vertexShaderSrc = GLSL(
100,
attribute vec4 pos;
uniform float scale;
void main ()
{
gl_Position = vec4(scale * pos.xy, pos.zw);
}
);
static const char* const s_fragmentShaderSrc = GLSL(
100,
void main ()
{
gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);
}
);
ProgramSources ScaleProgram::getSources (void)
{
using namespace glu;
ProgramSources sources;
sources << VertexSource(s_vertexShaderSrc)
<< FragmentSource(s_fragmentShaderSrc)
<< TransformFeedbackMode(GL_INTERLEAVED_ATTRIBS)
<< TransformFeedbackVarying("gl_Position");
return sources;
}
void ScaleProgram::draw (GLuint vao, GLfloat scale, bool tf, Surface* dst)
{
const Functions& gl = m_renderCtx.getFunctions();
de::Random rnd (vao);
Rectangle viewport = randomViewport(m_renderCtx,
VIEWPORT_SIZE, VIEWPORT_SIZE, rnd);
setViewport(m_renderCtx, viewport);
gl.clearColor(0, 0, 0, 1);
gl.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
gl.bindVertexArray(vao);
gl.enableVertexAttribArray(m_posLoc);
GLU_CHECK_CALL_ERROR(gl.useProgram(getProgram()),
gl.getError());
gl.uniform1f(m_scaleLoc, scale);
if (tf)
gl.beginTransformFeedback(GL_TRIANGLES);
GLU_CHECK_CALL_ERROR(gl.drawArrays(GL_TRIANGLES, 0, 3), gl.getError());
if (tf)
gl.endTransformFeedback();
if (dst != DE_NULL)
readRectangle(m_renderCtx, viewport, *dst);
gl.bindVertexArray(0);
}
void ScaleProgram::setPos (GLuint buffer, GLuint vao)
{
const Functions& gl = m_renderCtx.getFunctions();
gl.bindBuffer(GL_ARRAY_BUFFER, buffer);
gl.bindVertexArray(vao);
GLU_CHECK_CALL_ERROR(
gl.vertexAttribPointer(m_posLoc, NUM_COMPONENTS, GL_FLOAT, false, 0, DE_NULL),
gl.getError());
gl.bindVertexArray(0);
gl.bindBuffer(GL_ARRAY_BUFFER, 0);
GLU_CHECK_ERROR(gl.getError());
}
class VertexArrayBinder : public SimpleBinder
{
public:
VertexArrayBinder (lt::Context& ctx)
: SimpleBinder (ctx, 0, GL_NONE, GL_VERTEX_ARRAY_BINDING, true) {}
void bind (GLuint name) { glBindVertexArray(name); }
};
class SamplerBinder : public Binder
{
public:
SamplerBinder (lt::Context& ctx) : Binder(ctx) {}
void bind (GLuint name) { glBindSampler(0, name); }
GLuint getBinding (void)
{
GLint arr[32] = {};
glGetIntegerv(GL_SAMPLER_BINDING, arr);
log() << TestLog::Message << "// First output integer: " << arr[0]
<< TestLog::EndMessage;
return arr[0];
}
bool genRequired (void) const { return true; }
};
class QueryBinder : public Binder
{
public:
QueryBinder (lt::Context& ctx) : Binder(ctx) {}
void bind (GLuint name)
{
if (name != 0)
glBeginQuery(GL_ANY_SAMPLES_PASSED, name);
else
glEndQuery(GL_ANY_SAMPLES_PASSED);
}
GLuint getBinding (void) { return 0; }
};
class BufferVAOAttacher : public Attacher
{
public:
BufferVAOAttacher (lt::Context& ctx, Type& elementType,
Type& varrType, ScaleProgram& program)
: Attacher (ctx, elementType, varrType)
, m_program (program) {}
void initAttachment (GLuint seed, GLuint element);
void attach (GLuint element, GLuint container);
void detach (GLuint element, GLuint container);
bool canAttachDeleted (void) const { return false; }
ScaleProgram& getProgram (void) { return m_program; }
GLuint getAttachment (GLuint container);
private:
ScaleProgram& m_program;
};
static const GLfloat s_varrData[NUM_VERTICES * NUM_COMPONENTS] =
{
-1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
0.0, -1.0, 0.0, 1.0
};
void initBuffer (const Functions& gl, GLuint seed, GLenum usage, GLuint buffer)
{
gl.bindBuffer(GL_ARRAY_BUFFER, buffer);
if (seed == 0)
gl.bufferData(GL_ARRAY_BUFFER, sizeof(s_varrData), s_varrData, usage);
else
{
Random rnd (seed);
GLfloat data[DE_LENGTH_OF_ARRAY(s_varrData)];
for (int ndx = 0; ndx < NUM_VERTICES; ndx++)
{
GLfloat* vertex = &data[ndx * NUM_COMPONENTS];
vertex[0] = 2.0f * (rnd.getFloat() - 0.5f);
vertex[1] = 2.0f * (rnd.getFloat() - 0.5f);
DE_STATIC_ASSERT(NUM_COMPONENTS == 4);
vertex[2] = 0.0f;
vertex[3] = 1.0f;
}
gl.bufferData(GL_ARRAY_BUFFER, sizeof(data), data, usage);
}
gl.bindBuffer(GL_ARRAY_BUFFER, 0);
GLU_CHECK_ERROR(gl.getError());
}
void BufferVAOAttacher::initAttachment (GLuint seed, GLuint buffer)
{
initBuffer(gl(), seed, GL_STATIC_DRAW, buffer);
log() << TestLog::Message << "// Initialized buffer " << buffer << " from seed " << seed
<< TestLog::EndMessage;
}
void BufferVAOAttacher::attach (GLuint buffer, GLuint vao)
{
m_program.setPos(buffer, vao);
log() << TestLog::Message
<< "// Set the `pos` attribute in VAO " << vao << " to buffer " << buffer
<< TestLog::EndMessage;
}
void BufferVAOAttacher::detach (GLuint buffer, GLuint varr)
{
DE_UNREF(buffer);
attach(0, varr);
}
GLuint BufferVAOAttacher::getAttachment (GLuint varr)
{
GLint name = 0;
gl().bindVertexArray(varr);
gl().getVertexAttribiv(0, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &name);
gl().bindVertexArray(0);
GLU_CHECK_ERROR(gl().getError());
return GLuint(name);
}
class BufferVAOInputAttacher : public InputAttacher
{
public:
BufferVAOInputAttacher (BufferVAOAttacher& attacher)
: InputAttacher (attacher)
, m_program (attacher.getProgram()) {}
void drawContainer (GLuint container, Surface& dst);
private:
ScaleProgram& m_program;
};
void BufferVAOInputAttacher::drawContainer (GLuint vao, Surface& dst)
{
m_program.draw(vao, 1.0, false, &dst);
log() << TestLog::Message << "// Drew an output image with VAO " << vao
<< TestLog::EndMessage;
};
class BufferTfAttacher : public Attacher
{
public:
BufferTfAttacher (lt::Context& ctx, Type& bufferType, Type& tfType)
: Attacher (ctx, bufferType, tfType) {}
void initAttachment (GLuint seed, GLuint element);
void attach (GLuint buffer, GLuint tf);
void detach (GLuint buffer, GLuint tf);
bool canAttachDeleted (void) const { return false; }
GLuint getAttachment (GLuint tf);
};
void BufferTfAttacher::initAttachment (GLuint seed, GLuint buffer)
{
initBuffer(gl(), seed, GL_DYNAMIC_READ, buffer);
log() << TestLog::Message << "// Initialized buffer " << buffer << " from seed " << seed
<< TestLog::EndMessage;
}
void BufferTfAttacher::attach (GLuint buffer, GLuint tf)
{
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tf);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, buffer);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
GLU_CHECK_ERROR(gl().getError());
}
void BufferTfAttacher::detach (GLuint buffer, GLuint tf)
{
DE_UNREF(buffer);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tf);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
GLU_CHECK_ERROR(gl().getError());
}
GLuint BufferTfAttacher::getAttachment (GLuint tf)
{
GLint ret = 0;
gl().bindTransformFeedback(GL_TRANSFORM_FEEDBACK, tf);
gl().getIntegeri_v(GL_TRANSFORM_FEEDBACK_BUFFER_BINDING, 0, &ret);
gl().bindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
GLU_CHECK_ERROR(gl().getError());
return GLuint(ret);
}
class BufferTfOutputAttacher : public OutputAttacher
{
public:
BufferTfOutputAttacher (BufferTfAttacher& attacher, ScaleProgram& program)
: OutputAttacher (attacher)
, m_program (program) {}
void setupContainer (GLuint seed, GLuint container);
void drawAttachment (GLuint attachment, Surface& dst);
private:
ScaleProgram& m_program;
};
void BufferTfOutputAttacher::drawAttachment (GLuint buffer, Surface& dst)
{
VertexArray vao(getRenderContext());
m_program.setPos(buffer, *vao);
m_program.draw(*vao, 1.0, false, &dst);
log() << TestLog::Message
<< "// Drew output image with vertices from buffer " << buffer
<< TestLog::EndMessage;
GLU_CHECK_ERROR(gl().getError());
}
void BufferTfOutputAttacher::setupContainer (GLuint seed, GLuint tf)
{
Buffer posBuf (getRenderContext());
VertexArray vao (getRenderContext());
initBuffer(gl(), seed, GL_STATIC_DRAW, *posBuf);
m_program.setPos(*posBuf, *vao);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tf);
m_program.draw(*vao, -1.0, true, DE_NULL);
log() << TestLog::Message
<< "// Drew an image with seed " << seed << " with transform feedback to " << tf
<< TestLog::EndMessage;
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
GLU_CHECK_ERROR(gl().getError());
}
class ES3Types : public ES2Types
{
public:
ES3Types (lt::Context& ctx);
private:
ScaleProgram m_program;
QueryBinder m_queryBind;
SimpleType m_queryType;
SimpleBinder m_tfBind;
SimpleType m_tfType;
VertexArrayBinder m_varrBind;
SimpleType m_varrType;
SamplerBinder m_samplerBind;
SimpleType m_samplerType;
BufferVAOAttacher m_bufVarrAtt;
BufferVAOInputAttacher m_bufVarrInAtt;
BufferTfAttacher m_bufTfAtt;
BufferTfOutputAttacher m_bufTfOutAtt;
};
ES3Types::ES3Types (lt::Context& ctx)
: ES2Types (ctx)
, m_program (ctx)
, m_queryBind (ctx)
, m_queryType (ctx, "query", &CallLogWrapper::glGenQueries,
&CallLogWrapper::glDeleteQueries,
&CallLogWrapper::glIsQuery, &m_queryBind)
, m_tfBind (ctx, &CallLogWrapper::glBindTransformFeedback, GL_TRANSFORM_FEEDBACK,
GL_TRANSFORM_FEEDBACK_BINDING, true)
, m_tfType (ctx, "transform_feedback", &CallLogWrapper::glGenTransformFeedbacks,
&CallLogWrapper::glDeleteTransformFeedbacks,
&CallLogWrapper::glIsTransformFeedback, &m_tfBind)
, m_varrBind (ctx)
, m_varrType (ctx, "vertex_array", &CallLogWrapper::glGenVertexArrays,
&CallLogWrapper::glDeleteVertexArrays,
&CallLogWrapper::glIsVertexArray, &m_varrBind)
, m_samplerBind (ctx)
, m_samplerType (ctx, "sampler", &CallLogWrapper::glGenSamplers,
&CallLogWrapper::glDeleteSamplers,
&CallLogWrapper::glIsSampler, &m_samplerBind, true)
, m_bufVarrAtt (ctx, m_bufferType, m_varrType, m_program)
, m_bufVarrInAtt(m_bufVarrAtt)
, m_bufTfAtt (ctx, m_bufferType, m_tfType)
, m_bufTfOutAtt (m_bufTfAtt, m_program)
{
Type* types[] = { &m_queryType, &m_tfType, &m_varrType, &m_samplerType };
m_types.insert(m_types.end(), DE_ARRAY_BEGIN(types), DE_ARRAY_END(types));
m_attachers.push_back(&m_bufVarrAtt);
m_attachers.push_back(&m_bufTfAtt);
m_inAttachers.push_back(&m_bufVarrInAtt);
m_outAttachers.push_back(&m_bufTfOutAtt);
}
class TfDeleteActiveTest : public TestCase, private CallLogWrapper
{
public:
TfDeleteActiveTest (gles3::Context& context,
const char* name, const char* description);
IterateResult iterate (void);
};
TfDeleteActiveTest::TfDeleteActiveTest (gles3::Context& context,
const char* name, const char* description)
: TestCase (context, name, description)
, CallLogWrapper (context.getRenderContext().getFunctions(),
context.getTestContext().getLog())
{
enableLogging(true);
}
class ScopedTransformFeedbackFeedback
{
public:
ScopedTransformFeedbackFeedback (glu::CallLogWrapper& gl, GLenum type);
~ScopedTransformFeedbackFeedback (void);
private:
glu::CallLogWrapper& m_gl;
};
ScopedTransformFeedbackFeedback::ScopedTransformFeedbackFeedback (glu::CallLogWrapper& gl, GLenum type)
: m_gl(gl)
{
m_gl.glBeginTransformFeedback(type);
GLU_EXPECT_NO_ERROR(m_gl.glGetError(), "glBeginTransformFeedback");
}
ScopedTransformFeedbackFeedback::~ScopedTransformFeedbackFeedback (void)
{
m_gl.glEndTransformFeedback();
}
IterateResult TfDeleteActiveTest::iterate (void)
{
static const char* const s_xfbVertexSource = "#version 300 es\n"
"void main ()\n"
"{\n"
" gl_Position = vec4(float(gl_VertexID) / 2.0, float(gl_VertexID % 2) / 2.0, 0.0, 1.0);\n"
"}\n";
static const char* const s_xfbFragmentSource = "#version 300 es\n"
"layout(location=0) out mediump vec4 dEQP_FragColor;\n"
"void main ()\n"
"{\n"
" dEQP_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n"
"}\n";
glu::Buffer buf (m_context.getRenderContext());
GLuint tf = 0;
glu::ShaderProgram program (m_context.getRenderContext(),
glu::ProgramSources()
<< glu::VertexSource(s_xfbVertexSource)
<< glu::FragmentSource(s_xfbFragmentSource)
<< glu::TransformFeedbackMode(GL_INTERLEAVED_ATTRIBS)
<< glu::TransformFeedbackVarying("gl_Position"));
if (!program.isOk())
{
m_testCtx.getLog() << program;
throw tcu::TestError("failed to build program");
}
try
{
GLU_CHECK_CALL(glUseProgram(program.getProgram()));
GLU_CHECK_CALL(glGenTransformFeedbacks(1, &tf));
GLU_CHECK_CALL(glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tf));
GLU_CHECK_CALL(glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, *buf));
GLU_CHECK_CALL(glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 3 * sizeof(glw::GLfloat[4]), DE_NULL, GL_DYNAMIC_COPY));
{
ScopedTransformFeedbackFeedback xfb(static_cast<glu::CallLogWrapper&>(*this), GL_TRIANGLES);
glDeleteTransformFeedbacks(1, &tf);
{
GLenum err = glGetError();
if (err != GL_INVALID_OPERATION)
getTestContext().setTestResult(
QP_TEST_RESULT_FAIL,
"Deleting active transform feedback did not produce GL_INVALID_OPERATION");
else
getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Pass");
}
}
GLU_CHECK(); // ScopedTransformFeedbackFeedback::dtor might modify error state
GLU_CHECK_CALL(glDeleteTransformFeedbacks(1, &tf));
}
catch (const glu::Error&)
{
glDeleteTransformFeedbacks(1, &tf);
throw;
}
return STOP;
}
class TestGroup : public TestCaseGroup
{
public:
TestGroup (gles3::Context& context)
: TestCaseGroup (context, "lifetime", "Object lifetime tests")
{}
void init (void);
private:
MovePtr<Types> m_types;
};
void TestGroup::init (void)
{
gles3::Context& ctx = getContext();
lt::Context ltCtx (ctx.getRenderContext(), ctx.getTestContext());
m_types = MovePtr<Types>(new ES3Types(ltCtx));
addTestCases(*this, *m_types);
TestCaseGroup* deleteActiveGroup =
new TestCaseGroup(ctx, "delete_active", "Delete active object");
addChild(deleteActiveGroup);
deleteActiveGroup->addChild(
new TfDeleteActiveTest(ctx, "transform_feedback", "Transform Feedback"));
}
} // anonymous
TestCaseGroup* createLifetimeTests (Context& context)
{
return new TestGroup(context);
}
} // Functional
} // gles3
} // deqp
|
#include "myhash.h"
#include "windows.h"
#include "blake2.h"
#include "common.h"
//using namespace CryptoPP;
myhash my;
typedef void (__stdcall *Blake2b_Func)(char* output, long outlen, char* input, long inputlen);
Blake2b_Func func;
CryptoPP::BLAKE2b b(false, 20);
CryptoPP::BLAKE2b b28(false, 28);
CryptoPP::BLAKE2b b40(false, 40);
CryptoPP::BLAKE2b b44(false, 44);
CryptoPP::BLAKE2b b24(false, 24);
int counter1 = 0;
unsigned long timeforhashfunction = 0;
myhash::myhash()
{
//HANDLE h = LoadLibraryA("ConsoleApplication1.dll");
//func=(Blake2b_Func)GetProcAddress((HMODULE)h, "Blake2b");
b2= new
CryptoPP::BLAKE2b (false, 20);
counter1 = 0;
}
void myhash::Blake2bP(void * input, int len, unsigned char * output)
{
b2->CalculateDigest((CryptoPP::byte*)output, (CryptoPP::byte*)input, len);
}
void myhash::Blake2b(void * input, int len, unsigned char * output)
{
#ifdef BREAKDOWN_ANALYSIS
unsigned long t1 = time_us();
#endif
//BLAKE2b b(false, 20);
//CryptoPP::byte buf[256] = { 0 };
//CryptoPP::byte input[256] = { 1,2,3,4,5,6,7,8 };
b.CalculateDigest((CryptoPP::byte*)output, (CryptoPP::byte*)input, len);
#ifdef BREAKDOWN_ANALYSIS
unsigned long t2 = time_us();
timeforhashfunction += (t2 - t1);
#endif
counter1++;
//b.CalculateTruncatedDigest(output, 20, (CryptoPP::byte*)input, len);
//func((char*)output, 20, (char*)input, len);
}
void myhash::Blake2b_28(void * input, int len, unsigned char * output)
{
#ifdef BREAKDOWN_ANALYSIS
unsigned long t1 = time_us();
#endif
//BLAKE2b b(false, 20);
//CryptoPP::byte buf[256] = { 0 };
//CryptoPP::byte input[256] = { 1,2,3,4,5,6,7,8 };
b28.CalculateDigest((CryptoPP::byte*)output, (CryptoPP::byte*)input, len);
#ifdef BREAKDOWN_ANALYSIS
unsigned long t2 = time_us();
timeforhashfunction += (t2 - t1);
#endif
counter1++;
//b.CalculateTruncatedDigest(output, 20, (CryptoPP::byte*)input, len);
//func((char*)output, 20, (char*)input, len);
}
void myhash::Blake2b_40(void* input, int len, unsigned char* output)
{
b40.CalculateDigest((CryptoPP::byte*)output, (CryptoPP::byte*)input, len);
counter1++;
}
void myhash::Blake2b_44(void * input, int len, unsigned char * output)
{
b44.CalculateDigest((CryptoPP::byte*)output, (CryptoPP::byte*)input, len);
counter1++;
}
void myhash::Blake2b_24(void * input, int len, unsigned char * output)
{
b24.CalculateDigest((CryptoPP::byte*)output, (CryptoPP::byte*)input, len);
counter1++;
}
void myhash::SimpleHash_28(void * input, int len, unsigned char * output)
{
//BLAKE2b b(false, 20);
//CryptoPP::byte buf[256] = { 0 };
//CryptoPP::byte input[256] = { 1,2,3,4,5,6,7,8 };
for (int i = 0; i < len; i++)
{
output[i%20] = output[i % 20]+((unsigned char*)input)[i];
};
//b.CalculateTruncatedDigest(output, 20, (CryptoPP::byte*)input, len);
//func((char*)output, 20, (char*)input, len);
}
void hashbytes(void* input, int input_len, int output_len, void* output)
{
CryptoPP::BLAKE2b b(false, output_len);
b.CalculateDigest((CryptoPP::byte*)output, (CryptoPP::byte*)input, input_len);
counter1++;
}
int myhash::counter()
{
return counter1;
}
unsigned long myhash::getTimeElapsed()
{
return timeforhashfunction;
}
myhash::~myhash()
{
//
delete b2;
}
|
#include <iostream>
namespace Foo {
// Goo is a namespace inside Foo namespace
namespace Goo {
const int g_x = 5;
}
}
// C++17
// namespace Foo::Goo{
// const int g_x = 5;
// }
// namespaces alliases
namespace Boo = Foo::Goo; // Boo now refers to Foo::Goo
int main(){
std::cout << Foo::Goo::g_x << "\n";
std::cout << "Namespace allias " << Boo::g_x;
return 0;
}
|
#include "includes.h"
bool GPSCurriculumDesign::Findhead(FILE * FObs)
{
unsigned char buff[MAXRAWLEN];
unsigned char temp[3];
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
temp[0] = buff[0];
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
temp[1] = buff[0];
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
temp[2] = buff[0];
while (!feof(FObs)) {
if (temp[0] == 0xAA && temp[1] == 0x44 && temp[2] == 0x12) {
return true;
}
else {
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
continue;
}
//sscanf(string(buff).c_str(), "%x", hexData);
temp[0] = temp[1];
temp[1] = temp[2];
temp[2] = buff[0];
}
}
return false;
}
/*
typedef struct head{
unsigned char headLength; // 1
unsigned short messageID; // 2
char messageType; // 1
unsigned char portAddress; //1
unsigned short messageLength; // 2
unsigned short sequence; // 2
unsigned char idleTime; // 1
unsigned char timeStatus; // 1
unsigned short week; // 2
long gpsSecondBin = -1; // 4
float gpsSecondASCII = -1; // 4
unsigned long receiverStatus; // 4
unsigned short reserved; // 2
unsigned short receiver; // 2
};
*/
bool GPSCurriculumDesign::DecodeHead(FILE* FObs, head& header, unsigned char* pdata)
{
unsigned char buff[MAXRAWLEN];
int num = 0;
//Head Length 1
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
//Hex2UChar(buff, header.headLength, MAXRAWLEN, num);
unsigned char* pbuff = buff;
Hex2Dec(&pbuff, header.headLength, MAXRAWLEN, num);
//Message ID 2
if (fread(buff, sizeof(unsigned short), 1, FObs) < 1) {
return false;
}
//Hex2UShort(buff, header.messageID, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.messageID, MAXRAWLEN, num);
//message type 1
if (fread(buff, sizeof(char), 1, FObs) < 1) {
return false;
}
//Hex2Char(buff, header.messageType, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.messageType, MAXRAWLEN, num);
//port address 1
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
//Hex2UChar(buff, header.portAddress, totalLen, position);
pbuff = buff;
Hex2Dec<unsigned char>(&pbuff, header.portAddress, MAXRAWLEN, num);
//message length 2
if (fread(buff, sizeof(unsigned short), 1, FObs) < 1) {
return false;
}
//Hex2UShort(buff, header.messageLength, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.messageLength, MAXRAWLEN, num);
//sequence 2
if (fread(buff, sizeof(unsigned short), 1, FObs) < 1) {
return false;
}
//Hex2UShort(buff, header.sequence, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.sequence, MAXRAWLEN, num);
//idle time 1
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
//Hex2UChar(buff, header.idleTime, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.idleTime, MAXRAWLEN, num);
//time status 1
/////////////////data type unknown///////////////////////
if (fread(buff, sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
//Hex2UChar(buff, header.timeStatus, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.timeStatus, MAXRAWLEN, num);
//week 2
if (fread(buff, sizeof(unsigned short), 1, FObs) < 1) {
return false;
}
//Hex2UShort(buff, header.week, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.week, MAXRAWLEN, num);
//ms 4
if (fread(buff, sizeof(long), 1, FObs) < 1) {
return false;
}
//Hex2Long(buff, header.gpsSecondBin, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.gpsSecondBin, MAXRAWLEN, num);
//receiverStatus 4
if (fread(buff, sizeof(unsigned long), 1, FObs) < 1) {
return false;
}
//Hex2ULong(buff, header.receiverStatus, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.receiverStatus, MAXRAWLEN, num);
//reserved 2
if (fread(buff, sizeof(unsigned short), 1, FObs) < 1) {
return false;
}
//Hex2UShort(buff, header.reserved, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.reserved, MAXRAWLEN, num);
//receiver 2
if (fread(buff, sizeof(unsigned short), 1, FObs) < 1) {
return false;
}
//Hex2UShort(buff, header.receiver, totalLen, position);
pbuff = buff;
Hex2Dec(&pbuff, header.receiver, MAXRAWLEN, num);
fseek(FObs, -header.headLength, SEEK_CUR);
if (fread(pdata, sizeof(unsigned char) * (header.messageLength + header.headLength), 1, FObs) < 1) {
return false;
}
return true;
}
/*
typedef struct satellitemessage {
unsigned short PRN; //2
unsigned short glofreq; //2
double psr; //8
float psrStd; //4
double adr; //8
float adrStd; //4
float dopp; //4
float C; //4
float locktime; //4
unsigned long ch_tr_status; //4
};
*/
bool GPSCurriculumDesign::DecodeRange(unsigned char*pdata,int headerLen, int messageLen, std::vector<range>& ranges)
{
if(pdata == nullptr) return false;
if (messageLen <= sizeof(long)) return false;
int position = headerLen;
int totalLen = headerLen + messageLen;
pdata += position;
ranges.clear();
long obs = 0;
Hex2Dec<long>(&pdata, obs, totalLen, position);
for (int i = 0; i < obs; i++) {
range range_;
//PRN 2
Hex2Dec<unsigned short>(&pdata, range_.PRN, totalLen, position);
//glofreq 2
Hex2Dec(&pdata, range_.glofreq, totalLen, position);
//psr 8
Hex2Dec(&pdata, range_.psr, totalLen, position);
//psrStd 4
Hex2Dec(&pdata, range_.psrStd, totalLen, position);
//adr 8
Hex2Dec(&pdata, range_.adr, totalLen, position);
//adrStd 4
Hex2Dec(&pdata, range_.adrStd, totalLen, position);
//dopp 4
Hex2Dec(&pdata, range_.dopp, totalLen, position);
//C 4
Hex2Dec(&pdata, range_.C, totalLen, position);
//locktime 4
Hex2Dec(&pdata, range_.locktime, totalLen, position);
//ch_tr_status 4
Hex2Dec(&pdata, range_.ch_tr_status, totalLen, position);
ranges.push_back(range_);
}
return true;
}
//typedef struct gpsephem {
// unsigned long PRN; // 4
// double tow; // 8
// unsigned long health; // 4
// unsigned long iode1; // 4
// unsigned long iode2; // 4
// unsigned long week; // 4
// unsigned long zweek; // 4
// double toe; // 8
// double A; // 8
// double deltaN; // 8
// double M0; // 8
// double ecc; // 8
// double omega; // 8
// double cuc; // 8
// double cus; // 8
// double crc; // 8
// double crs; // 8
// double cic; // 8
// double cis; // 8
// double l0; // 8
// double I; // 8
// double omega0; // 8
// double oomega; // 8
// unsigned long iodc; //4
// double toc; // 8
// double tgd; // 8
// double af0; // 8
// double af1; // 8
// double af2; // 8
// antispoofing AS; // 4
// double N; // 8
// double URA; // 8
//};
bool GPSCurriculumDesign::DecodeGPSEphem(unsigned char* pdata, int headerLen, int messageLen, std::unordered_map<unsigned long,gpsephem>& gpsephems, unsigned long& PRN)
{
if (pdata == nullptr) return false;
if (messageLen == 0) return false;
int position = headerLen;
int totalLen = headerLen + messageLen;
pdata += headerLen;
gpsephem gpsephem_;
// unsigned long PRN 4
if (!Hex2Dec(&pdata, gpsephem_.PRN, totalLen, position)) {
return false;
}
// double tow 8
if (!Hex2Dec(&pdata, gpsephem_.tow, totalLen, position)) {
return false;
}
// unsigned long health 4
if (!Hex2Dec(&pdata, gpsephem_.health, totalLen, position)) {
return false;
}
// unsigned long iode1 4
if (!Hex2Dec(&pdata, gpsephem_.iode1, totalLen, position)) {
return false;
}
// unsigned long iode2 4
if (!Hex2Dec(&pdata, gpsephem_.iode2, totalLen, position)) {
return false;
}
// unsigned long week 4
if (!Hex2Dec(&pdata, gpsephem_.week, totalLen, position)) {
return false;
}
// unsigned long zweek 4
if (!Hex2Dec(&pdata, gpsephem_.zweek, totalLen, position)) {
return false;
}
// double toe 8
if (!Hex2Dec(&pdata, gpsephem_.toe, totalLen, position)) {
return false;
}
// double A 8
if (!Hex2Dec(&pdata, gpsephem_.A, totalLen, position)) {
return false;
}
// double deltaN 8
if (!Hex2Dec(&pdata, gpsephem_.deltaN, totalLen, position)) {
return false;
}
// double M0 8
if (!Hex2Dec(&pdata, gpsephem_.M0, totalLen, position)) {
return false;
}
// double ecc 8
if (!Hex2Dec(&pdata, gpsephem_.ecc, totalLen, position)) {
return false;
}
// double omega 8
if (!Hex2Dec(&pdata, gpsephem_.omega, totalLen, position)) {
return false;
}
// double cuc 8
if (!Hex2Dec(&pdata, gpsephem_.cuc, totalLen, position)) {
return false;
}
// double cus 8
if (!Hex2Dec(&pdata, gpsephem_.cus, totalLen, position)) {
return false;
}
// double crc 8
if (!Hex2Dec(&pdata, gpsephem_.crc, totalLen, position)) {
return false;
}
// double crs 8
if (!Hex2Dec(&pdata, gpsephem_.crs, totalLen, position)) {
return false;
}
// double cic 8
if (!Hex2Dec(&pdata, gpsephem_.cic, totalLen, position)) {
return false;
}
// double cis 8
if (!Hex2Dec(&pdata, gpsephem_.cis, totalLen, position)) {
return false;
}
// double l0 8
if (!Hex2Dec(&pdata, gpsephem_.i0, totalLen, position)) {
return false;
}
// double I 8
if (!Hex2Dec(&pdata, gpsephem_.dotI, totalLen, position)) {
return false;
}
// double omega0 8
if (!Hex2Dec(&pdata, gpsephem_.omega0, totalLen, position)) {
return false;
}
// double oomega 8
if (!Hex2Dec(&pdata, gpsephem_.dotOmega, totalLen, position)) {
return false;
}
// unsigned long iodc 4
if (!Hex2Dec(&pdata, gpsephem_.iodc, totalLen, position)) {
return false;
}
// double toc 8
if (!Hex2Dec(&pdata, gpsephem_.toc, totalLen, position)) {
return false;
}
// double tgd 8
if (!Hex2Dec(&pdata, gpsephem_.tgd, totalLen, position)) {
return false;
}
// double af0 8
if (!Hex2Dec(&pdata, gpsephem_.af0, totalLen, position)) {
return false;
}
// double af1 8
if (!Hex2Dec(&pdata, gpsephem_.af1, totalLen, position)) {
return false;
}
// double af2 8
if (!Hex2Dec(&pdata, gpsephem_.af2, totalLen, position)) {
return false;
}
// antispoofing AS 4
long temp;
if (!Hex2Dec(&pdata, temp, totalLen, position)) {
return false;
}
gpsephem_.AS = temp == 0 ? FalseAntispoofing : TrueAntispoofing;
// double N 8
if (!Hex2Dec(&pdata, gpsephem_.N, totalLen, position)) {
return false;
}
// double URA 8
if (!Hex2Dec(&pdata, gpsephem_.URA, totalLen, position)) {
return false;
}
std::unordered_map<unsigned long , gpsephem>::iterator it = gpsephems.find(gpsephem_.PRN);
PRN = gpsephem_.PRN;
if (it == gpsephems.end()) {
std::pair<unsigned long, gpsephem> tempgpsephem(gpsephem_.PRN, gpsephem_);
gpsephems.insert(tempgpsephem);
}
else {
gpsephems.at(gpsephem_.PRN) = gpsephem_;
}
return true;
}
//typedef struct ionutc {
// double a0; // 8
// double a1; // 8
// double a2; // 8
// double a3; // 8
// double b0; // 8
// double b1; // 8
// double b2; // 8
// double b3; // 8
// unsigned long utcwn; // 4
// unsigned long tot; // 4
// double A0; // 8
// double A1; // 8
// unsigned long wnlsf; // 4
// unsigned long dn; // 4
// long deltatls; // 4
// long deltatutc; //4
//};
bool GPSCurriculumDesign::DecodeIonutc(unsigned char* pdata, int headerLen, int messageLen, ionutc& ionutc_)
{
if (pdata == nullptr) return false;
if (messageLen == 0) return false;
int position = headerLen;
int totalLen = headerLen + messageLen;
pdata += position;
// double a0 8
if (!Hex2Dec(&pdata, ionutc_.a0, totalLen, position)) {
return false;
}
// double a1; // 8
if (!Hex2Dec(&pdata, ionutc_.a1, totalLen, position)) {
return false;
}
// double a2; // 8
if (!Hex2Dec(&pdata, ionutc_.a2, totalLen, position)) {
return false;
}
// double a3; // 8
if (!Hex2Dec(&pdata, ionutc_.a3, totalLen, position)) {
return false;
}
// double b0; // 8
if (!Hex2Dec(&pdata, ionutc_.b0, totalLen, position)) {
return false;
}
// double b1; // 8
if (!Hex2Dec(&pdata, ionutc_.b1, totalLen, position)) {
return false;
}
// double b2; // 8
if (!Hex2Dec(&pdata, ionutc_.b2, totalLen, position)) {
return false;
}
// double b3; // 8
if (!Hex2Dec(&pdata, ionutc_.b3, totalLen, position)) {
return false;
}
// unsigned long utcwn; // 4
if (!Hex2Dec(&pdata, ionutc_.utcwn, totalLen, position)) {
return false;
}
// unsigned long tot; // 4
if (!Hex2Dec(&pdata, ionutc_.tot, totalLen, position)) {
return false;
}
// double A0; // 8
if (!Hex2Dec(&pdata, ionutc_.A0, totalLen, position)) {
return false;
}
// double A1; // 8
if (!Hex2Dec(&pdata, ionutc_.A1, totalLen, position)) {
return false;
}
// unsigned long wnlsf; // 4
if (!Hex2Dec(&pdata, ionutc_.wnlsf, totalLen, position)) {
return false;
}
// unsigned long dn; // 4
if (!Hex2Dec(&pdata, ionutc_.dn, totalLen, position)) {
return false;
}
// long deltatls; // 4
if (!Hex2Dec(&pdata, ionutc_.deltatls, totalLen, position)) {
return false;
}
// long deltatutc; //4
if (!Hex2Dec(&pdata, ionutc_.deltatutc, totalLen, position)) {
return false;
}
return true;
}
//typedef struct rawephem {
// unsigned long prn; //4
//unsigned long refweek; // 4
//unsigned long refsec; // 4
//subframe subframe1; // 30
//subframe subframe2; // 30
//subframe subframe3; // 30
//};
bool GPSCurriculumDesign::DecodeRawEphem(unsigned char* pdata, int headerLen, int messageLen, std::unordered_map<unsigned long, rawephem>& rawephems)
{
rawephem rawephem_;
if (pdata == nullptr) return false;
if (messageLen == 0) return false;
int position = headerLen;
int totalLen = headerLen + messageLen;
pdata += position;
//unsigned long prn; //4
if (!Hex2Dec(&pdata, rawephem_.prn, totalLen, position)) {
return false;
}
//unsigned long refweek; // 4
if (!Hex2Dec(&pdata, rawephem_.refweek, totalLen, position)) {
return false;
}
//unsigned long refsec; // 4
if (!Hex2Dec(&pdata, rawephem_.refsec, totalLen, position)) {
return false;
}
memcpy(&rawephem_.subframe1, pdata, sizeof(unsigned char) * 30);
pdata += sizeof(unsigned char) * 30;
memcpy(&rawephem_.subframe2, pdata, sizeof(unsigned char) * 30);
pdata += sizeof(unsigned char) * 30;
memcpy(&rawephem_.subframe3, pdata, sizeof(unsigned char) * 30);
pdata += sizeof(unsigned char) * 30;
////subframe subframe1; // 30
//if (!Hex2Dec(&pdata, rawephem_.subframe1, totalLen, position)) {
// return false;
//}
////subframe subframe2; // 30
//if (!Hex2Dec(&pdata, rawephem_.subframe2, totalLen, position)) {
// return false;
//}
////subframe subframe3; // 30
//if (!Hex2Dec(&pdata, rawephem_.subframe3, totalLen, position)) {
// return false;
//}
std::unordered_map<unsigned long, rawephem>::iterator it = rawephems.find(rawephem_.prn);
if (it == rawephems.end()) {
std::pair<unsigned long, rawephem> temprawephem(rawephem_.prn, rawephem_);
rawephems.insert(temprawephem);
}
rawephems.at(rawephem_.prn) = rawephem_;
return true;
}
bool GPSCurriculumDesign::DecodePsrPos(unsigned char* pdata, int headerLen, int messageLen, psrPOS& psrPos_)
{
if (pdata == nullptr) return false;
if (messageLen == 0) return false;
int position = headerLen;
int totalLen = headerLen + messageLen;
pdata += position;
// enum solStat 4
if (!Hex2Dec(&pdata, psrPos_.solStat, totalLen, position)) {
return false;
}
// enum posType 4
if (!Hex2Dec(&pdata, psrPos_.posType, totalLen, position)) {
return false;
}
// double lat 8
if (!Hex2Dec(&pdata, psrPos_.lat, totalLen, position)) {
return false;
}
// double lon 8
if (!Hex2Dec(&pdata, psrPos_.lon, totalLen, position)) {
return false;
}
// double hgt 8
if (!Hex2Dec(&pdata, psrPos_.hgt, totalLen, position)) {
return false;
}
return true;
}
bool GPSCurriculumDesign::CheckCRC(FILE* FObs,const unsigned char* pdata, const int len)
{
const unsigned char* pdata_ = pdata;
unsigned char buff[MAXRAWLEN];
if (fread(buff, 4 * sizeof(unsigned char), 1, FObs) < 1) {
return false;
}
unsigned int crcFormate = (unsigned int)(buff[0] | buff[1] << 8 | buff[2] << 16 | buff[3] << 24);
if (crcFormate == crc32(pdata, len)) {
pdata = pdata_;
return true;
}
pdata = pdata_;
return false;
}
unsigned int GPSCurriculumDesign::crc32(const unsigned char *buff, int len)
{
int i, j;
unsigned int crc = 0;
for (i = 0; i < len; i++)
{
crc ^= buff[i];
for (j = 0; j < 8; j++)
{
if (crc & 1) crc = (crc >> 1) ^ POLYCRC32;
else crc >>= 1;
}
}
return crc;
}
//inline bool GPSDCurriculumDesign::Hex2Char(unsigned char* pdata, char& c, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(char) > totalLen) return false;
// c = *((char*)pdata);
// position += sizeof(char);
// pdata += sizeof(char);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2UChar(unsigned char* pdata, unsigned char& uc, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(unsigned char) > totalLen) return false;
// uc = *((unsigned char*)pdata);
// position += sizeof(char);
// pdata += sizeof(char);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2Short(unsigned char* pdata, short& s, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(short) > totalLen) return false;
// s = *((short*)pdata);
// position += sizeof(short);
// pdata += sizeof(short);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2UShort(unsigned char* pdata, unsigned short& us, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(unsigned short) > totalLen) return false;
// us = *((unsigned short*)pdata);
// position += sizeof(unsigned short);
// pdata += sizeof(unsigned short);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2Int(unsigned char* pdata, int& i, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(int) > totalLen) return false;
// i = *((int*)pdata);
// position += sizeof(int);
// pdata += sizeof(int);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2UInt(unsigned char* pdata, unsigned int& ui, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(unsigned int) > totalLen) return false;
// ui = *((unsigned int*)pdata);
// position += sizeof(unsigned int);
// pdata += sizeof(unsigned int);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2Long(unsigned char* pdata, long& l, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(long) > totalLen) return false;
// l = *((long *)pdata);
// position += sizeof(long);
// pdata += sizeof(long);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2ULong(unsigned char* pdata, unsigned long& ul, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(unsigned long) > totalLen) return false;
// ul = *((unsigned long *)pdata);
// position += sizeof(unsigned long);
// pdata += sizeof(unsigned long);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2Float(unsigned char* pdata, float& f, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(float) > totalLen) return false;
// f = *((float *)pdata);
// position += sizeof(float);
// pdata += sizeof(float);
// return true;
//}
//
//inline bool GPSDCurriculumDesign::Hex2Double(unsigned char* pdata, double& d, int totalLen, int& position)
//{
// if (pdata == nullptr) return false;
// if (position + sizeof(double) > totalLen) return false;
// d = *((double *)pdata);
// position += sizeof(double);
// pdata += sizeof(double);
// return true;
//}
|
#include "RE/B/BSTArray.h"
#include "RE/S/ScrapHeap.h"
namespace RE
{
BSScrapArrayAllocator::~BSScrapArrayAllocator()
{
if (_data) {
deallocate(_data);
}
memzero(this);
}
void* BSScrapArrayAllocator::allocate(std::size_t a_size)
{
if (!_allocator) {
auto heap = MemoryManager::GetSingleton();
_allocator = heap ? heap->GetThreadScrapHeap() : nullptr;
}
assert(_allocator);
auto mem = _allocator->Allocate(a_size, alignof(void*));
assert(mem != nullptr);
std::memset(mem, 0, a_size);
return mem;
}
void BSScrapArrayAllocator::deallocate(void* a_ptr)
{
if (_allocator) {
_allocator->Deallocate(a_ptr);
} else {
assert(false);
}
}
}
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Process dmtrace output.
*
* This is the wrong way to go about it -- C is a clumsy language for
* shuffling data around. It'll do for a first pass.
*/
#include "profile.h" // from VM header
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
/* Version number in the key file.
* Version 1 uses one byte for the thread id.
* Version 2 uses two bytes for the thread ids.
* Version 3 encodes the record size and adds an optional extra timestamp field.
*/
int32_t versionNumber;
/* arbitrarily limit indentation */
#define MAX_STACK_DEPTH 10000
/* thread list in key file is not reliable, so just max out */
#define MAX_THREADS 32768
/* Size of temporary buffers for escaping html strings */
#define HTML_BUFSIZE 10240
const char* htmlHeader =
"<html>\n<head>\n<script type=\"text/javascript\" "
"src=\"%ssortable.js\"></script>\n"
"<script langugage=\"javascript\">\n"
"function toggle(item) {\n"
" obj=document.getElementById(item);\n"
" visible=(obj.style.display!=\"none\" && obj.style.display!=\"\");\n"
" key=document.getElementById(\"x\" + item);\n"
" if (visible) {\n"
" obj.style.display=\"none\";\n"
" key.innerHTML=\"+\";\n"
" } else {\n"
" obj.style.display=\"block\";\n"
" key.innerHTML=\"-\";\n"
" }\n"
"}\n"
"function onMouseOver(obj) {\n"
" obj.style.background=\"lightblue\";\n"
"}\n"
"function onMouseOut(obj) {\n"
" obj.style.background=\"white\";\n"
"}\n"
"</script>\n"
"<style type=\"text/css\">\n"
"div { font-family: courier; font-size: 13 }\n"
"div.parent { margin-left: 15; display: none }\n"
"div.leaf { margin-left: 10 }\n"
"div.header { margin-left: 10 }\n"
"div.link { margin-left: 10; cursor: move }\n"
"span.parent { padding-right: 10; }\n"
"span.leaf { padding-right: 10; }\n"
"a img { border: 0;}\n"
"table.sortable th { border-width: 0px 1px 1px 1px; background-color: "
"#ccc;}\n"
"a { text-decoration: none; }\n"
"a:hover { text-decoration: underline; }\n"
"table.sortable th, table.sortable td { text-align: left;}"
"table.sortable tr.odd td { background-color: #ddd; }\n"
"table.sortable tr.even td { background-color: #fff; }\n"
"</style>\n"
"</head><body>\n\n";
const char* htmlFooter = "\n</body>\n</html>\n";
const char* profileSeparator =
"======================================================================";
const char* tableHeader =
"<table class='sortable' id='%s'><tr>\n"
"<th>Method</th>\n"
"<th>Run 1 (us)</th>\n"
"<th>Run 2 (us)</th>\n"
"<th>Diff (us)</th>\n"
"<th>Diff (%%)</th>\n"
"<th>1: # calls</th>\n"
"<th>2: # calls</th>\n"
"</tr>\n";
const char* tableHeaderMissing =
"<table class='sortable' id='%s'>\n"
"<th>Method</th>\n"
"<th>Exclusive</th>\n"
"<th>Inclusive</th>\n"
"<th># calls</th>\n";
#define GRAPH_LABEL_VISITED 0x0001
#define GRAPH_NODE_VISITED 0x0002
/*
* Values from the header of the data file.
*/
typedef struct DataHeader {
uint32_t magic;
int16_t version;
int16_t offsetToData;
int64_t startWhen;
int16_t recordSize;
} DataHeader;
/*
* Entry from the thread list.
*/
typedef struct ThreadEntry {
int32_t threadId;
const char* threadName;
} ThreadEntry;
struct MethodEntry;
typedef struct TimedMethod {
struct TimedMethod* next;
uint64_t elapsedInclusive;
int32_t numCalls;
struct MethodEntry* method;
} TimedMethod;
typedef struct ClassEntry {
const char* className;
uint64_t elapsedExclusive;
int32_t numMethods;
struct MethodEntry** methods; /* list of methods in this class */
int32_t numCalls[2]; /* 0=normal, 1=recursive */
} ClassEntry;
typedef struct UniqueMethodEntry {
uint64_t elapsedExclusive;
int32_t numMethods;
struct MethodEntry** methods; /* list of methods with same name */
int32_t numCalls[2]; /* 0=normal, 1=recursive */
} UniqueMethodEntry;
/*
* Entry from the method list.
*/
typedef struct MethodEntry {
int64_t methodId;
const char* className;
const char* methodName;
const char* signature;
const char* fileName;
int32_t lineNum;
uint64_t elapsedExclusive;
uint64_t elapsedInclusive;
uint64_t topExclusive; /* non-recursive exclusive time */
uint64_t recursiveInclusive;
struct TimedMethod* parents[2]; /* 0=normal, 1=recursive */
struct TimedMethod* children[2]; /* 0=normal, 1=recursive */
int32_t numCalls[2]; /* 0=normal, 1=recursive */
int32_t index; /* used after sorting to number methods */
int32_t recursiveEntries; /* number of entries on the stack */
int32_t graphState; /* used when graphing to see if this method has been visited before */
} MethodEntry;
/*
* The parsed contents of the key file.
*/
typedef struct DataKeys {
char* fileData; /* contents of the entire file */
int64_t fileLen;
int32_t numThreads;
ThreadEntry* threads;
int32_t numMethods;
MethodEntry* methods; /* 2 extra methods: "toplevel" and "unknown" */
} DataKeys;
#define TOPLEVEL_INDEX 0
#define UNKNOWN_INDEX 1
typedef struct StackEntry {
MethodEntry* method;
uint64_t entryTime;
} StackEntry;
typedef struct CallStack {
int32_t top;
StackEntry calls[MAX_STACK_DEPTH];
uint64_t lastEventTime;
uint64_t threadStartTime;
} CallStack;
typedef struct DiffEntry {
MethodEntry* method1;
MethodEntry* method2;
int64_t differenceExclusive;
int64_t differenceInclusive;
double differenceExclusivePercentage;
double differenceInclusivePercentage;
} DiffEntry;
// Global options
typedef struct Options {
const char* traceFileName;
const char* diffFileName;
const char* graphFileName;
int32_t keepDotFile;
int32_t dump;
int32_t outputHtml;
const char* sortableUrl;
int32_t threshold;
} Options;
typedef struct TraceData {
int32_t numClasses;
ClassEntry* classes;
CallStack* stacks[MAX_THREADS];
int32_t depth[MAX_THREADS];
int32_t numUniqueMethods;
UniqueMethodEntry* uniqueMethods;
} TraceData;
static Options gOptions;
/* Escapes characters in the source string that are html special entities.
* The escaped string is written to "dest" which must be large enough to
* hold the result. A pointer to "dest" is returned. The characters and
* their corresponding escape sequences are:
* '<' <
* '>' >
* '&' &
*/
char* htmlEscape(const char* src, char* dest, int32_t len) {
char* destStart = dest;
if (src == nullptr) return nullptr;
int32_t nbytes = 0;
while (*src) {
if (*src == '<') {
nbytes += 4;
if (nbytes >= len) break;
*dest++ = '&';
*dest++ = 'l';
*dest++ = 't';
*dest++ = ';';
} else if (*src == '>') {
nbytes += 4;
if (nbytes >= len) break;
*dest++ = '&';
*dest++ = 'g';
*dest++ = 't';
*dest++ = ';';
} else if (*src == '&') {
nbytes += 5;
if (nbytes >= len) break;
*dest++ = '&';
*dest++ = 'a';
*dest++ = 'm';
*dest++ = 'p';
*dest++ = ';';
} else {
nbytes += 1;
if (nbytes >= len) break;
*dest++ = *src;
}
src += 1;
}
if (nbytes >= len) {
fprintf(stderr, "htmlEscape(): buffer overflow\n");
exit(1);
}
*dest = 0;
return destStart;
}
/* Initializes a MethodEntry
*/
void initMethodEntry(MethodEntry* method, int64_t methodId, const char* className,
const char* methodName, const char* signature, const char* fileName,
const char* lineNumStr) {
method->methodId = methodId;
method->className = className;
method->methodName = methodName;
method->signature = signature;
method->fileName = fileName;
method->lineNum = (lineNumStr != nullptr) ? atoi(lineNumStr) : -1;
method->elapsedExclusive = 0;
method->elapsedInclusive = 0;
method->topExclusive = 0;
method->recursiveInclusive = 0;
method->parents[0] = nullptr;
method->parents[1] = nullptr;
method->children[0] = nullptr;
method->children[1] = nullptr;
method->numCalls[0] = 0;
method->numCalls[1] = 0;
method->index = 0;
method->recursiveEntries = 0;
}
/*
* This comparison function is called from qsort() to sort
* methods into decreasing order of exclusive elapsed time.
*/
int32_t compareElapsedExclusive(const void* a, const void* b) {
const MethodEntry* methodA = *(const MethodEntry**) a;
const MethodEntry* methodB = *(const MethodEntry**) b;
uint64_t elapsed1 = methodA->elapsedExclusive;
uint64_t elapsed2 = methodB->elapsedExclusive;
if (elapsed1 < elapsed2) return 1;
if (elapsed1 > elapsed2) return -1;
/* If the elapsed times of two methods are equal, then sort them
* into alphabetical order.
*/
int32_t result = strcmp(methodA->className, methodB->className);
if (result == 0) {
if (methodA->methodName == nullptr || methodB->methodName == nullptr) {
int64_t idA = methodA->methodId;
int64_t idB = methodB->methodId;
if (idA < idB) return -1;
if (idA > idB) return 1;
return 0;
}
result = strcmp(methodA->methodName, methodB->methodName);
if (result == 0) result = strcmp(methodA->signature, methodB->signature);
}
return result;
}
/*
* This comparison function is called from qsort() to sort
* methods into decreasing order of inclusive elapsed time.
*/
int32_t compareElapsedInclusive(const void* a, const void* b) {
const MethodEntry* methodA = *(MethodEntry const**) a;
const MethodEntry* methodB = *(MethodEntry const**) b;
uint64_t elapsed1 = methodA->elapsedInclusive;
uint64_t elapsed2 = methodB->elapsedInclusive;
if (elapsed1 < elapsed2) return 1;
if (elapsed1 > elapsed2) return -1;
/* If the elapsed times of two methods are equal, then sort them
* into alphabetical order.
*/
int32_t result = strcmp(methodA->className, methodB->className);
if (result == 0) {
if (methodA->methodName == nullptr || methodB->methodName == nullptr) {
int64_t idA = methodA->methodId;
int64_t idB = methodB->methodId;
if (idA < idB) return -1;
if (idA > idB) return 1;
return 0;
}
result = strcmp(methodA->methodName, methodB->methodName);
if (result == 0) result = strcmp(methodA->signature, methodB->signature);
}
return result;
}
/*
* This comparison function is called from qsort() to sort
* TimedMethods into decreasing order of inclusive elapsed time.
*/
int32_t compareTimedMethod(const void* a, const void* b) {
const TimedMethod* timedA = (TimedMethod const*) a;
const TimedMethod* timedB = (TimedMethod const*) b;
uint64_t elapsed1 = timedA->elapsedInclusive;
uint64_t elapsed2 = timedB->elapsedInclusive;
if (elapsed1 < elapsed2) return 1;
if (elapsed1 > elapsed2) return -1;
/* If the elapsed times of two methods are equal, then sort them
* into alphabetical order.
*/
MethodEntry* methodA = timedA->method;
MethodEntry* methodB = timedB->method;
int32_t result = strcmp(methodA->className, methodB->className);
if (result == 0) {
if (methodA->methodName == nullptr || methodB->methodName == nullptr) {
int64_t idA = methodA->methodId;
int64_t idB = methodB->methodId;
if (idA < idB) return -1;
if (idA > idB) return 1;
return 0;
}
result = strcmp(methodA->methodName, methodB->methodName);
if (result == 0) result = strcmp(methodA->signature, methodB->signature);
}
return result;
}
/*
* This comparison function is called from qsort() to sort
* MethodEntry pointers into alphabetical order of class names.
*/
int32_t compareClassNames(const void* a, const void* b) {
const MethodEntry* methodA = *(const MethodEntry**) a;
const MethodEntry* methodB = *(const MethodEntry**) b;
int32_t result = strcmp(methodA->className, methodB->className);
if (result == 0) {
int64_t idA = methodA->methodId;
int64_t idB = methodB->methodId;
if (idA < idB) return -1;
if (idA > idB) return 1;
return 0;
}
return result;
}
/*
* This comparison function is called from qsort() to sort
* classes into decreasing order of exclusive elapsed time.
*/
int32_t compareClassExclusive(const void* a, const void* b) {
const ClassEntry* classA = *(const ClassEntry**) a;
const ClassEntry* classB = *(const ClassEntry**) b;
uint64_t elapsed1 = classA->elapsedExclusive;
uint64_t elapsed2 = classB->elapsedExclusive;
if (elapsed1 < elapsed2) return 1;
if (elapsed1 > elapsed2) return -1;
/* If the elapsed times of two classs are equal, then sort them
* into alphabetical order.
*/
int32_t result = strcmp(classA->className, classB->className);
if (result == 0) {
/* Break ties with the first method id. This is probably not
* needed.
*/
int64_t idA = classA->methods[0]->methodId;
int64_t idB = classB->methods[0]->methodId;
if (idA < idB) return -1;
if (idA > idB) return 1;
return 0;
}
return result;
}
/*
* This comparison function is called from qsort() to sort
* MethodEntry pointers into alphabetical order by method name,
* then by class name.
*/
int32_t compareMethodNames(const void* a, const void* b) {
const MethodEntry* methodA = *(const MethodEntry**) a;
const MethodEntry* methodB = *(const MethodEntry**) b;
if (methodA->methodName == nullptr || methodB->methodName == nullptr) {
return compareClassNames(a, b);
}
int32_t result = strcmp(methodA->methodName, methodB->methodName);
if (result == 0) {
result = strcmp(methodA->className, methodB->className);
if (result == 0) {
int64_t idA = methodA->methodId;
int64_t idB = methodB->methodId;
if (idA < idB) return -1;
if (idA > idB) return 1;
return 0;
}
}
return result;
}
/*
* This comparison function is called from qsort() to sort
* unique methods into decreasing order of exclusive elapsed time.
*/
int32_t compareUniqueExclusive(const void* a, const void* b) {
const UniqueMethodEntry* uniqueA = *(const UniqueMethodEntry**) a;
const UniqueMethodEntry* uniqueB = *(const UniqueMethodEntry**) b;
uint64_t elapsed1 = uniqueA->elapsedExclusive;
uint64_t elapsed2 = uniqueB->elapsedExclusive;
if (elapsed1 < elapsed2) return 1;
if (elapsed1 > elapsed2) return -1;
/* If the elapsed times of two methods are equal, then sort them
* into alphabetical order.
*/
int32_t result = strcmp(uniqueA->methods[0]->className, uniqueB->methods[0]->className);
if (result == 0) {
int64_t idA = uniqueA->methods[0]->methodId;
int64_t idB = uniqueB->methods[0]->methodId;
if (idA < idB) return -1;
if (idA > idB) return 1;
return 0;
}
return result;
}
/*
* Free a DataKeys struct.
*/
void freeDataKeys(DataKeys* pKeys) {
if (pKeys == nullptr) return;
free(pKeys->fileData);
free(pKeys->threads);
free(pKeys->methods);
free(pKeys);
}
/*
* Find the offset to the next occurrence of the specified character.
*
* "data" should point somewhere within the current line. "len" is the
* number of bytes left in the buffer.
*
* Returns -1 if we hit the end of the buffer.
*/
int32_t findNextChar(const char* data, int32_t len, char lookFor) {
const char* start = data;
while (len > 0) {
if (*data == lookFor) return data - start;
data++;
len--;
}
return -1;
}
/*
* Count the number of lines until the next token.
*
* Returns -1 if none found before EOF.
*/
int32_t countLinesToToken(const char* data, int32_t len) {
int32_t count = 0;
int32_t next;
while (*data != TOKEN_CHAR) {
next = findNextChar(data, len, '\n');
if (next < 0) return -1;
count++;
data += next + 1;
len -= next + 1;
}
return count;
}
/*
* Make sure we're at the start of the right section.
*
* Returns the length of the token line, or -1 if something is wrong.
*/
int32_t checkToken(const char* data, int32_t len, const char* cmpStr) {
int32_t cmpLen = strlen(cmpStr);
int32_t next;
if (*data != TOKEN_CHAR) {
fprintf(stderr, "ERROR: not at start of %s (found '%.10s')\n", cmpStr, data);
return -1;
}
next = findNextChar(data, len, '\n');
if (next < cmpLen + 1) return -1;
if (strncmp(data + 1, cmpStr, cmpLen) != 0) {
fprintf(stderr, "ERROR: '%s' not found (got '%.7s')\n", cmpStr, data + 1);
return -1;
}
return next + 1;
}
/*
* Parse the "*version" section.
*/
int64_t parseVersion(DataKeys* pKeys, int64_t offset, int32_t verbose) {
if (offset < 0) return -1;
char* data = pKeys->fileData + offset;
char* dataEnd = pKeys->fileData + pKeys->fileLen;
int32_t next = checkToken(data, dataEnd - data, "version");
if (next <= 0) return -1;
data += next;
/*
* Count the number of items in the "version" section.
*/
int32_t count = countLinesToToken(data, dataEnd - data);
if (count <= 0) {
fprintf(stderr, "ERROR: failed while reading version (found %d)\n", count);
return -1;
}
/* find the end of the line */
next = findNextChar(data, dataEnd - data, '\n');
if (next < 0) return -1;
data[next] = '\0';
versionNumber = strtoul(data, nullptr, 0);
if (verbose) printf("VERSION: %d\n", versionNumber);
data += next + 1;
/* skip over the rest of the stuff, which is "name=value" lines */
for (int32_t i = 1; i < count; i++) {
next = findNextChar(data, dataEnd - data, '\n');
if (next < 0) return -1;
// data[next] = '\0';
// printf("IGNORING: '%s'\n", data);
data += next + 1;
}
return data - pKeys->fileData;
}
/*
* Parse the "*threads" section.
*/
int64_t parseThreads(DataKeys* pKeys, int64_t offset) {
if (offset < 0) return -1;
char* data = pKeys->fileData + offset;
char* dataEnd = pKeys->fileData + pKeys->fileLen;
int32_t next = checkToken(data, dataEnd - data, "threads");
data += next;
/*
* Count the number of thread entries (one per line).
*/
int32_t count = countLinesToToken(data, dataEnd - data);
if (count <= 0) {
fprintf(stderr, "ERROR: failed while reading threads (found %d)\n", count);
return -1;
}
// printf("+++ found %d threads\n", count);
pKeys->threads = new ThreadEntry[count];
if (pKeys->threads == nullptr) return -1;
/*
* Extract all entries.
*/
for (int32_t i = 0; i < count; i++) {
next = findNextChar(data, dataEnd - data, '\n');
assert(next > 0);
data[next] = '\0';
int32_t tab = findNextChar(data, next, '\t');
data[tab] = '\0';
pKeys->threads[i].threadId = atoi(data);
pKeys->threads[i].threadName = data + tab + 1;
data += next + 1;
}
pKeys->numThreads = count;
return data - pKeys->fileData;
}
/*
* Parse the "*methods" section.
*/
int64_t parseMethods(DataKeys* pKeys, int64_t offset) {
if (offset < 0) return -1;
char* data = pKeys->fileData + offset;
char* dataEnd = pKeys->fileData + pKeys->fileLen;
int32_t next = checkToken(data, dataEnd - data, "methods");
if (next < 0) return -1;
data += next;
/*
* Count the number of method entries (one per line).
*/
int32_t count = countLinesToToken(data, dataEnd - data);
if (count <= 0) {
fprintf(stderr, "ERROR: failed while reading methods (found %d)\n", count);
return -1;
}
/* Reserve an extra method at location 0 for the "toplevel" method,
* and another extra method for all other "unknown" methods.
*/
count += 2;
pKeys->methods = new MethodEntry[count];
if (pKeys->methods == nullptr) return -1;
initMethodEntry(&pKeys->methods[TOPLEVEL_INDEX], -2, "(toplevel)", nullptr, nullptr,
nullptr, nullptr);
initMethodEntry(&pKeys->methods[UNKNOWN_INDEX], -1, "(unknown)", nullptr, nullptr,
nullptr, nullptr);
/*
* Extract all entries, starting with index 2.
*/
for (int32_t i = UNKNOWN_INDEX + 1; i < count; i++) {
next = findNextChar(data, dataEnd - data, '\n');
assert(next > 0);
data[next] = '\0';
int32_t tab1 = findNextChar(data, next, '\t');
int32_t tab2 = findNextChar(data + (tab1 + 1), next - (tab1 + 1), '\t');
int32_t tab3 = findNextChar(data + (tab1 + tab2 + 2), next - (tab1 + tab2 + 2), '\t');
int32_t tab4 = findNextChar(data + (tab1 + tab2 + tab3 + 3),
next - (tab1 + tab2 + tab3 + 3), '\t');
int32_t tab5 = findNextChar(data + (tab1 + tab2 + tab3 + tab4 + 4),
next - (tab1 + tab2 + tab3 + tab4 + 4), '\t');
if (tab1 < 0) {
fprintf(stderr, "ERROR: missing field on method line: '%s'\n", data);
return -1;
}
assert(data[tab1] == '\t');
data[tab1] = '\0';
char* endptr;
int64_t id = strtoul(data, &endptr, 0);
if (*endptr != '\0') {
fprintf(stderr, "ERROR: bad method ID '%s'\n", data);
return -1;
}
// Allow files that specify just a function name, instead of requiring
// "class \t method \t signature"
if (tab2 > 0 && tab3 > 0) {
tab2 += tab1 + 1;
tab3 += tab2 + 1;
assert(data[tab2] == '\t');
assert(data[tab3] == '\t');
data[tab2] = data[tab3] = '\0';
// This is starting to get awkward. Allow filename and line #.
if (tab4 > 0 && tab5 > 0) {
tab4 += tab3 + 1;
tab5 += tab4 + 1;
assert(data[tab4] == '\t');
assert(data[tab5] == '\t');
data[tab4] = data[tab5] = '\0';
initMethodEntry(&pKeys->methods[i], id, data + tab1 + 1,
data + tab2 + 1, data + tab3 + 1, data + tab4 + 1,
data + tab5 + 1);
} else {
initMethodEntry(&pKeys->methods[i], id, data + tab1 + 1,
data + tab2 + 1, data + tab3 + 1, nullptr, nullptr);
}
} else {
initMethodEntry(&pKeys->methods[i], id, data + tab1 + 1, nullptr, nullptr, nullptr,
nullptr);
}
data += next + 1;
}
pKeys->numMethods = count;
return data - pKeys->fileData;
}
/*
* Parse the "*end" section.
*/
int64_t parseEnd(DataKeys* pKeys, int64_t offset) {
if (offset < 0) return -1;
char* data = pKeys->fileData + offset;
char* dataEnd = pKeys->fileData + pKeys->fileLen;
int32_t next = checkToken(data, dataEnd - data, "end");
if (next < 0) return -1;
data += next;
return data - pKeys->fileData;
}
/*
* Sort the thread list entries.
*/
static int32_t compareThreads(const void* thread1, const void* thread2) {
return ((const ThreadEntry*) thread1)->threadId -
((const ThreadEntry*) thread2)->threadId;
}
void sortThreadList(DataKeys* pKeys) {
qsort(pKeys->threads, pKeys->numThreads, sizeof(pKeys->threads[0]), compareThreads);
}
/*
* Sort the method list entries.
*/
static int32_t compareMethods(const void* meth1, const void* meth2) {
int64_t id1 = ((const MethodEntry*) meth1)->methodId;
int64_t id2 = ((const MethodEntry*) meth2)->methodId;
if (id1 < id2) return -1;
if (id1 > id2) return 1;
return 0;
}
void sortMethodList(DataKeys* pKeys) {
qsort(pKeys->methods, pKeys->numMethods, sizeof(MethodEntry), compareMethods);
}
/*
* Parse the key section, and return a copy of the parsed contents.
*/
DataKeys* parseKeys(FILE* fp, int32_t verbose) {
int64_t offset;
DataKeys* pKeys = new DataKeys();
memset(pKeys, 0, sizeof(DataKeys));
if (pKeys == nullptr) return nullptr;
/*
* We load the entire file into memory. We do this, rather than memory-
* mapping it, because we want to change some whitespace to NULs.
*/
if (fseek(fp, 0L, SEEK_END) != 0) {
perror("fseek");
freeDataKeys(pKeys);
return nullptr;
}
pKeys->fileLen = ftell(fp);
if (pKeys->fileLen == 0) {
fprintf(stderr, "Key file is empty.\n");
freeDataKeys(pKeys);
return nullptr;
}
rewind(fp);
pKeys->fileData = new char[pKeys->fileLen];
if (pKeys->fileData == nullptr) {
fprintf(stderr, "ERROR: unable to alloc %" PRIu64 " bytes\n", pKeys->fileLen);
freeDataKeys(pKeys);
return nullptr;
}
if (fread(pKeys->fileData, 1, pKeys->fileLen, fp) != (size_t)pKeys->fileLen) {
fprintf(stderr, "ERROR: unable to read %" PRIu64 " bytes from trace file\n", pKeys->fileLen);
freeDataKeys(pKeys);
return nullptr;
}
offset = 0;
offset = parseVersion(pKeys, offset, verbose);
offset = parseThreads(pKeys, offset);
offset = parseMethods(pKeys, offset);
offset = parseEnd(pKeys, offset);
if (offset < 0) {
freeDataKeys(pKeys);
return nullptr;
}
/* Reduce our allocation now that we know where the end of the key section is. */
pKeys->fileData = reinterpret_cast<char*>(realloc(pKeys->fileData, offset));
pKeys->fileLen = offset;
/* Leave fp pointing to the beginning of the data section. */
fseek(fp, offset, SEEK_SET);
sortThreadList(pKeys);
sortMethodList(pKeys);
/*
* Dump list of threads.
*/
if (verbose) {
printf("Threads (%d):\n", pKeys->numThreads);
for (int32_t i = 0; i < pKeys->numThreads; i++) {
printf("%2d %s\n", pKeys->threads[i].threadId, pKeys->threads[i].threadName);
}
}
#if 0
/*
* Dump list of methods.
*/
if (verbose) {
printf("Methods (%d):\n", pKeys->numMethods);
for (int32_t i = 0; i < pKeys->numMethods; i++) {
printf("0x%08x %s : %s : %s\n",
pKeys->methods[i].methodId, pKeys->methods[i].className,
pKeys->methods[i].methodName, pKeys->methods[i].signature);
}
}
#endif
return pKeys;
}
/*
* Read values from the binary data file.
*/
/*
* Make the return value "uint32_t" instead of "uint16_t" so that we can detect EOF.
*/
uint32_t read2LE(FILE* fp) {
uint32_t val = getc(fp);
val |= getc(fp) << 8;
return val;
}
uint32_t read4LE(FILE* fp) {
uint32_t val = getc(fp);
val |= getc(fp) << 8;
val |= getc(fp) << 16;
val |= getc(fp) << 24;
return val;
}
uint64_t read8LE(FILE* fp) {
uint64_t val = getc(fp);
val |= (uint64_t) getc(fp) << 8;
val |= (uint64_t) getc(fp) << 16;
val |= (uint64_t) getc(fp) << 24;
val |= (uint64_t) getc(fp) << 32;
val |= (uint64_t) getc(fp) << 40;
val |= (uint64_t) getc(fp) << 48;
val |= (uint64_t) getc(fp) << 56;
return val;
}
/*
* Parse the header of the data section.
*
* Returns with the file positioned at the start of the record data.
*/
int32_t parseDataHeader(FILE* fp, DataHeader* pHeader) {
pHeader->magic = read4LE(fp);
pHeader->version = read2LE(fp);
pHeader->offsetToData = read2LE(fp);
pHeader->startWhen = read8LE(fp);
int32_t bytesToRead = pHeader->offsetToData - 16;
if (pHeader->version == 1) {
pHeader->recordSize = 9;
} else if (pHeader->version == 2) {
pHeader->recordSize = 10;
} else if (pHeader->version == 3) {
pHeader->recordSize = read2LE(fp);
bytesToRead -= 2;
} else {
fprintf(stderr, "Unsupported trace file version: %d\n", pHeader->version);
return -1;
}
if (fseek(fp, bytesToRead, SEEK_CUR) != 0) {
return -1;
}
return 0;
}
/*
* Look up a method by it's method ID.
*
* Returns nullptr if no matching method was found.
*/
MethodEntry* lookupMethod(DataKeys* pKeys, int64_t methodId) {
int32_t lo = 0;
int32_t hi = pKeys->numMethods - 1;
while (hi >= lo) {
int32_t mid = (hi + lo) / 2;
int64_t id = pKeys->methods[mid].methodId;
if (id == methodId) /* match */
return &pKeys->methods[mid];
else if (id < methodId) /* too low */
lo = mid + 1;
else /* too high */
hi = mid - 1;
}
return nullptr;
}
/*
* Reads the next data record, and assigns the data values to threadId,
* methodVal and elapsedTime. On end-of-file, the threadId, methodVal,
* and elapsedTime are unchanged. Returns 1 on end-of-file, otherwise
* returns 0.
*/
int32_t readDataRecord(FILE* dataFp, DataHeader* dataHeader, int32_t* threadId,
uint32_t* methodVal, uint64_t* elapsedTime) {
int32_t id;
int32_t bytesToRead = dataHeader->recordSize;
if (dataHeader->version == 1) {
id = getc(dataFp);
bytesToRead -= 1;
} else {
id = read2LE(dataFp);
bytesToRead -= 2;
}
if (id == EOF) return 1;
*threadId = id;
*methodVal = read4LE(dataFp);
*elapsedTime = read4LE(dataFp);
bytesToRead -= 8;
while (bytesToRead-- > 0) {
getc(dataFp);
}
if (feof(dataFp)) {
fprintf(stderr, "WARNING: hit EOF mid-record\n");
return 1;
}
return 0;
}
/*
* Read the key file and use it to produce formatted output from the
* data file.
*/
void dumpTrace() {
static const char* actionStr[] = {"ent", "xit", "unr", "???"};
MethodEntry bogusMethod = {
0, "???", "???", "???", "???", -1, 0, 0,
0, 0, {nullptr, nullptr}, {nullptr, nullptr}, {0, 0}, 0, 0, -1};
char bogusBuf[80];
TraceData traceData;
// printf("Dumping '%s' '%s'\n", dataFileName, keyFileName);
char spaces[MAX_STACK_DEPTH + 1];
memset(spaces, '.', MAX_STACK_DEPTH);
spaces[MAX_STACK_DEPTH] = '\0';
for (int32_t i = 0; i < MAX_THREADS; i++)
traceData.depth[i] = 2; // adjust for return from start function
FILE* dataFp = fopen(gOptions.traceFileName, "rb");
if (dataFp == nullptr) return;
DataKeys* pKeys = parseKeys(dataFp, 1);
if (pKeys == nullptr) {
fclose(dataFp);
return;
}
DataHeader dataHeader;
if (parseDataHeader(dataFp, &dataHeader) < 0) {
fclose(dataFp);
freeDataKeys(pKeys);
return;
}
printf("Trace (threadID action usecs class.method signature):\n");
while (1) {
/*
* Extract values from file.
*/
int32_t threadId;
uint32_t methodVal;
uint64_t elapsedTime;
if (readDataRecord(dataFp, &dataHeader, &threadId, &methodVal, &elapsedTime))
break;
int32_t action = METHOD_ACTION(methodVal);
int64_t methodId = METHOD_ID(methodVal);
/*
* Generate a line of output.
*/
int64_t lastEnter = 0;
int32_t mismatch = 0;
if (action == METHOD_TRACE_ENTER) {
traceData.depth[threadId]++;
lastEnter = methodId;
} else {
/* quick test for mismatched adjacent enter/exit */
if (lastEnter != 0 && lastEnter != methodId) mismatch = 1;
}
int32_t printDepth = traceData.depth[threadId];
char depthNote = ' ';
if (printDepth < 0) {
printDepth = 0;
depthNote = '-';
} else if (printDepth > MAX_STACK_DEPTH) {
printDepth = MAX_STACK_DEPTH;
depthNote = '+';
}
MethodEntry* method = lookupMethod(pKeys, methodId);
if (method == nullptr) {
method = &bogusMethod;
sprintf(bogusBuf, "methodId: %#" PRIx64 "", methodId);
method->signature = bogusBuf;
}
if (method->methodName) {
printf("%2d %s%c %8" PRIu64 "%c%s%s.%s %s\n", threadId, actionStr[action],
mismatch ? '!' : ' ', elapsedTime, depthNote,
spaces + (MAX_STACK_DEPTH - printDepth), method->className,
method->methodName, method->signature);
} else {
printf("%2d %s%c %8" PRIu64 "%c%s%s\n", threadId, actionStr[action],
mismatch ? '!' : ' ', elapsedTime, depthNote,
spaces + (MAX_STACK_DEPTH - printDepth), method->className);
}
if (action != METHOD_TRACE_ENTER) {
traceData.depth[threadId]--; /* METHOD_TRACE_EXIT or METHOD_TRACE_UNROLL */
lastEnter = 0;
}
mismatch = 0;
}
fclose(dataFp);
freeDataKeys(pKeys);
}
/* This routine adds the given time to the parent and child methods.
* This is called when the child routine exits, after the child has
* been popped from the stack. The elapsedTime parameter is the
* duration of the child routine, including time spent in called routines.
*/
void addInclusiveTime(MethodEntry* parent, MethodEntry* child, uint64_t elapsedTime) {
#if 0
bool verbose = false;
if (strcmp(child->className, debugClassName) == 0)
verbose = true;
#endif
int32_t childIsRecursive = (child->recursiveEntries > 0);
int32_t parentIsRecursive = (parent->recursiveEntries > 1);
if (child->recursiveEntries == 0) {
child->elapsedInclusive += elapsedTime;
} else if (child->recursiveEntries == 1) {
child->recursiveInclusive += elapsedTime;
}
child->numCalls[childIsRecursive] += 1;
#if 0
if (verbose) {
fprintf(stderr,
"%s %d elapsedTime: %lld eI: %lld, rI: %lld\n",
child->className, child->recursiveEntries,
elapsedTime, child->elapsedInclusive,
child->recursiveInclusive);
}
#endif
/* Find the child method in the parent */
TimedMethod* pTimed;
TimedMethod* children = parent->children[parentIsRecursive];
for (pTimed = children; pTimed; pTimed = pTimed->next) {
if (pTimed->method == child) {
pTimed->elapsedInclusive += elapsedTime;
pTimed->numCalls += 1;
break;
}
}
if (pTimed == nullptr) {
/* Allocate a new TimedMethod */
pTimed = new TimedMethod();
pTimed->elapsedInclusive = elapsedTime;
pTimed->numCalls = 1;
pTimed->method = child;
/* Add it to the front of the list */
pTimed->next = children;
parent->children[parentIsRecursive] = pTimed;
}
/* Find the parent method in the child */
TimedMethod* parents = child->parents[childIsRecursive];
for (pTimed = parents; pTimed; pTimed = pTimed->next) {
if (pTimed->method == parent) {
pTimed->elapsedInclusive += elapsedTime;
pTimed->numCalls += 1;
break;
}
}
if (pTimed == nullptr) {
/* Allocate a new TimedMethod */
pTimed = new TimedMethod();
pTimed->elapsedInclusive = elapsedTime;
pTimed->numCalls = 1;
pTimed->method = parent;
/* Add it to the front of the list */
pTimed->next = parents;
child->parents[childIsRecursive] = pTimed;
}
#if 0
if (verbose) {
fprintf(stderr,
" %s %d eI: %lld\n",
parent->className, parent->recursiveEntries,
pTimed->elapsedInclusive);
}
#endif
}
/* Sorts a linked list and returns a newly allocated array containing
* the sorted entries.
*/
TimedMethod* sortTimedMethodList(TimedMethod* list, int32_t* num) {
/* Count the elements */
TimedMethod* pTimed;
int32_t num_entries = 0;
for (pTimed = list; pTimed; pTimed = pTimed->next) num_entries += 1;
*num = num_entries;
if (num_entries == 0) return nullptr;
/* Copy all the list elements to a new array and sort them */
int32_t ii;
TimedMethod* sorted = new TimedMethod[num_entries];
for (ii = 0, pTimed = list; pTimed; pTimed = pTimed->next, ++ii)
memcpy(&sorted[ii], pTimed, sizeof(TimedMethod));
qsort(sorted, num_entries, sizeof(TimedMethod), compareTimedMethod);
/* Fix up the "next" pointers so that they work. */
for (ii = 0; ii < num_entries - 1; ++ii) sorted[ii].next = &sorted[ii + 1];
sorted[num_entries - 1].next = nullptr;
return sorted;
}
/* Define flag values for printInclusiveMethod() */
static const int32_t kIsRecursive = 1;
/* This prints the inclusive stats for all the parents or children of a
* method, depending on the list that is passed in.
*/
void printInclusiveMethod(MethodEntry* method, TimedMethod* list, int32_t numCalls, int32_t flags) {
char buf[80];
const char* anchor_close = "";
const char* spaces = " "; /* 6 spaces */
int32_t num_spaces = strlen(spaces);
const char* space_ptr = &spaces[num_spaces];
char classBuf[HTML_BUFSIZE], methodBuf[HTML_BUFSIZE];
char signatureBuf[HTML_BUFSIZE];
if (gOptions.outputHtml) anchor_close = "</a>";
int32_t num;
TimedMethod* sorted = sortTimedMethodList(list, &num);
double methodTotal = method->elapsedInclusive;
for (TimedMethod* pTimed = sorted; pTimed; pTimed = pTimed->next) {
MethodEntry* relative = pTimed->method;
const char* className = relative->className;
const char* methodName = relative->methodName;
const char* signature = relative->signature;
double per = 100.0 * pTimed->elapsedInclusive / methodTotal;
sprintf(buf, "[%d]", relative->index);
if (gOptions.outputHtml) {
int32_t len = strlen(buf);
if (len > num_spaces) len = num_spaces;
sprintf(buf, "<a href=\"#m%d\">[%d]", relative->index, relative->index);
space_ptr = &spaces[len];
className = htmlEscape(className, classBuf, HTML_BUFSIZE);
methodName = htmlEscape(methodName, methodBuf, HTML_BUFSIZE);
signature = htmlEscape(signature, signatureBuf, HTML_BUFSIZE);
}
int32_t nCalls = numCalls;
if (nCalls == 0) nCalls = relative->numCalls[0] + relative->numCalls[1];
if (relative->methodName) {
if (flags & kIsRecursive) {
// Don't display percentages for recursive functions
printf("%6s %5s %6s %s%6s%s %6d/%-6d %9" PRIu64 " %s.%s %s\n", "", "",
"", space_ptr, buf, anchor_close, pTimed->numCalls, nCalls,
pTimed->elapsedInclusive, className, methodName, signature);
} else {
printf("%6s %5s %5.1f%% %s%6s%s %6d/%-6d %9" PRIu64 " %s.%s %s\n", "",
"", per, space_ptr, buf, anchor_close, pTimed->numCalls, nCalls,
pTimed->elapsedInclusive, className, methodName, signature);
}
} else {
if (flags & kIsRecursive) {
// Don't display percentages for recursive functions
printf("%6s %5s %6s %s%6s%s %6d/%-6d %9" PRIu64 " %s\n", "", "", "",
space_ptr, buf, anchor_close, pTimed->numCalls, nCalls,
pTimed->elapsedInclusive, className);
} else {
printf("%6s %5s %5.1f%% %s%6s%s %6d/%-6d %9" PRIu64 " %s\n", "", "",
per, space_ptr, buf, anchor_close, pTimed->numCalls, nCalls,
pTimed->elapsedInclusive, className);
}
}
}
}
void countRecursiveEntries(CallStack* pStack, int32_t top, MethodEntry* method) {
method->recursiveEntries = 0;
for (int32_t ii = 0; ii < top; ++ii) {
if (pStack->calls[ii].method == method) method->recursiveEntries += 1;
}
}
void stackDump(CallStack* pStack, int32_t top) {
for (int32_t ii = 0; ii < top; ++ii) {
MethodEntry* method = pStack->calls[ii].method;
uint64_t entryTime = pStack->calls[ii].entryTime;
if (method->methodName) {
fprintf(stderr, " %2d: %8" PRIu64 " %s.%s %s\n", ii, entryTime,
method->className, method->methodName, method->signature);
} else {
fprintf(stderr, " %2d: %8" PRIu64 " %s\n", ii, entryTime, method->className);
}
}
}
void outputTableOfContents() {
printf("<a name=\"contents\"></a>\n");
printf("<h2>Table of Contents</h2>\n");
printf("<ul>\n");
printf(" <li><a href=\"#exclusive\">Exclusive profile</a></li>\n");
printf(" <li><a href=\"#inclusive\">Inclusive profile</a></li>\n");
printf(" <li><a href=\"#class\">Class/method profile</a></li>\n");
printf(" <li><a href=\"#method\">Method/class profile</a></li>\n");
printf("</ul>\n\n");
}
void outputNavigationBar() {
printf("<a href=\"#contents\">[Top]</a>\n");
printf("<a href=\"#exclusive\">[Exclusive]</a>\n");
printf("<a href=\"#inclusive\">[Inclusive]</a>\n");
printf("<a href=\"#class\">[Class]</a>\n");
printf("<a href=\"#method\">[Method]</a>\n");
printf("<br><br>\n");
}
void printExclusiveProfile(MethodEntry** pMethods, int32_t numMethods, uint64_t sumThreadTime) {
char classBuf[HTML_BUFSIZE], methodBuf[HTML_BUFSIZE];
char signatureBuf[HTML_BUFSIZE];
const char* anchor_close = "";
char anchor_buf[80];
anchor_buf[0] = 0;
if (gOptions.outputHtml) {
anchor_close = "</a>";
printf("<a name=\"exclusive\"></a>\n");
printf("<hr>\n");
outputNavigationBar();
} else {
printf("\n%s\n", profileSeparator);
}
/* First, sort the methods into decreasing order of inclusive
* elapsed time so that we can assign the method indices.
*/
qsort(pMethods, numMethods, sizeof(MethodEntry*), compareElapsedInclusive);
for (int32_t ii = 0; ii < numMethods; ++ii) pMethods[ii]->index = ii;
/* Sort the methods into decreasing order of exclusive elapsed time. */
qsort(pMethods, numMethods, sizeof(MethodEntry*), compareElapsedExclusive);
printf("Total cycles: %" PRIu64 "\n\n", sumThreadTime);
if (gOptions.outputHtml) {
printf("<br><br>\n");
}
printf("Exclusive elapsed times for each method, not including time spent in\n");
printf("children, sorted by exclusive time.\n\n");
if (gOptions.outputHtml) {
printf("<br><br>\n<pre>\n");
}
printf(" Usecs self %% sum %% Method\n");
double sum = 0;
double total = sumThreadTime;
for (int32_t ii = 0; ii < numMethods; ++ii) {
MethodEntry* method = pMethods[ii];
/* Don't show methods with zero cycles */
if (method->elapsedExclusive == 0) break;
const char* className = method->className;
const char* methodName = method->methodName;
const char* signature = method->signature;
sum += method->elapsedExclusive;
double per = 100.0 * method->elapsedExclusive / total;
double sum_per = 100.0 * sum / total;
if (gOptions.outputHtml) {
sprintf(anchor_buf, "<a href=\"#m%d\">", method->index);
className = htmlEscape(className, classBuf, HTML_BUFSIZE);
methodName = htmlEscape(methodName, methodBuf, HTML_BUFSIZE);
signature = htmlEscape(signature, signatureBuf, HTML_BUFSIZE);
}
if (method->methodName) {
printf("%9" PRIu64 " %6.2f %6.2f %s[%d]%s %s.%s %s\n",
method->elapsedExclusive, per, sum_per, anchor_buf, method->index,
anchor_close, className, methodName, signature);
} else {
printf("%9" PRIu64 " %6.2f %6.2f %s[%d]%s %s\n",
method->elapsedExclusive, per, sum_per, anchor_buf, method->index,
anchor_close, className);
}
}
if (gOptions.outputHtml) {
printf("</pre>\n");
}
}
/* check to make sure that the child method meets the threshold of the parent */
int32_t checkThreshold(MethodEntry* parent, MethodEntry* child) {
double parentTime = parent->elapsedInclusive;
double childTime = child->elapsedInclusive;
int64_t percentage = (childTime / parentTime) * 100.0;
return (percentage < gOptions.threshold) ? 0 : 1;
}
void createLabels(FILE* file, MethodEntry* method) {
fprintf(file,
"node%d[label = \"[%d] %s.%s (%" PRIu64 ", %" PRIu64 ", %d)\"]\n",
method->index, method->index, method->className, method->methodName,
method->elapsedInclusive / 1000, method->elapsedExclusive / 1000,
method->numCalls[0]);
method->graphState = GRAPH_LABEL_VISITED;
for (TimedMethod* child = method->children[0]; child; child = child->next) {
MethodEntry* childMethod = child->method;
if ((childMethod->graphState & GRAPH_LABEL_VISITED) == 0 &&
checkThreshold(method, childMethod)) {
createLabels(file, child->method);
}
}
}
void createLinks(FILE* file, MethodEntry* method) {
method->graphState |= GRAPH_NODE_VISITED;
for (TimedMethod* child = method->children[0]; child; child = child->next) {
MethodEntry* childMethod = child->method;
if (checkThreshold(method, child->method)) {
fprintf(file, "node%d -> node%d\n", method->index, child->method->index);
// only visit children that haven't been visited before
if ((childMethod->graphState & GRAPH_NODE_VISITED) == 0) {
createLinks(file, child->method);
}
}
}
}
void createInclusiveProfileGraphNew(DataKeys* dataKeys) {
// create a temporary file in /tmp
char path[FILENAME_MAX];
if (gOptions.keepDotFile) {
snprintf(path, FILENAME_MAX, "%s.dot", gOptions.graphFileName);
} else {
snprintf(path, FILENAME_MAX, "dot-%d-%d.dot", (int32_t)time(nullptr), rand());
}
FILE* file = fopen(path, "w+");
fprintf(file, "digraph g {\nnode [shape = record,height=.1];\n");
createLabels(file, dataKeys->methods);
createLinks(file, dataKeys->methods);
fprintf(file, "}");
fclose(file);
// now that we have the dot file generate the image
char command[1024];
snprintf(command, 1024, "dot -Tpng -o \"%s\" \"%s\"", gOptions.graphFileName, path);
system(command);
if (!gOptions.keepDotFile) {
remove(path);
}
}
void printInclusiveProfile(MethodEntry** pMethods, int32_t numMethods, uint64_t sumThreadTime) {
char classBuf[HTML_BUFSIZE], methodBuf[HTML_BUFSIZE];
char signatureBuf[HTML_BUFSIZE];
char anchor_buf[80];
const char* anchor_close = "";
anchor_buf[0] = 0;
if (gOptions.outputHtml) {
anchor_close = "</a>";
printf("<a name=\"inclusive\"></a>\n");
printf("<hr>\n");
outputNavigationBar();
} else {
printf("\n%s\n", profileSeparator);
}
/* Sort the methods into decreasing order of inclusive elapsed time. */
qsort(pMethods, numMethods, sizeof(MethodEntry*), compareElapsedInclusive);
printf("\nInclusive elapsed times for each method and its parents and children,\n");
printf("sorted by inclusive time.\n\n");
if (gOptions.outputHtml) {
printf("<br><br>\n<pre>\n");
}
printf("index %%/total %%/self index calls usecs name\n");
double total = sumThreadTime;
for (int32_t ii = 0; ii < numMethods; ++ii) {
char buf[40];
MethodEntry* method = pMethods[ii];
/* Don't show methods with zero cycles */
if (method->elapsedInclusive == 0) break;
const char* className = method->className;
const char* methodName = method->methodName;
const char* signature = method->signature;
if (gOptions.outputHtml) {
printf("<a name=\"m%d\"></a>", method->index);
className = htmlEscape(className, classBuf, HTML_BUFSIZE);
methodName = htmlEscape(methodName, methodBuf, HTML_BUFSIZE);
signature = htmlEscape(signature, signatureBuf, HTML_BUFSIZE);
}
printf("----------------------------------------------------\n");
/* Sort and print the parents */
int32_t numCalls = method->numCalls[0] + method->numCalls[1];
printInclusiveMethod(method, method->parents[0], numCalls, 0);
if (method->parents[1]) {
printf(" +++++++++++++++++++++++++\n");
printInclusiveMethod(method, method->parents[1], numCalls, kIsRecursive);
}
double per = 100.0 * method->elapsedInclusive / total;
sprintf(buf, "[%d]", ii);
if (method->methodName) {
printf("%-6s %5.1f%% %5s %6s %6d+%-6d %9" PRIu64 " %s.%s %s\n", buf,
per, "", "", method->numCalls[0], method->numCalls[1],
method->elapsedInclusive, className, methodName, signature);
} else {
printf("%-6s %5.1f%% %5s %6s %6d+%-6d %9" PRIu64 " %s\n", buf, per, "",
"", method->numCalls[0], method->numCalls[1],
method->elapsedInclusive, className);
}
double excl_per = 100.0 * method->topExclusive / method->elapsedInclusive;
printf("%6s %5s %5.1f%% %6s %6s %6s %9" PRIu64 "\n", "", "", excl_per,
"excl", "", "", method->topExclusive);
/* Sort and print the children */
printInclusiveMethod(method, method->children[0], 0, 0);
if (method->children[1]) {
printf(" +++++++++++++++++++++++++\n");
printInclusiveMethod(method, method->children[1], 0, kIsRecursive);
}
}
if (gOptions.outputHtml) {
printf("</pre>\n");
}
}
void createClassList(TraceData* traceData, MethodEntry** pMethods, int32_t numMethods) {
/* Sort the methods into alphabetical order to find the unique class
* names.
*/
qsort(pMethods, numMethods, sizeof(MethodEntry*), compareClassNames);
/* Count the number of unique class names. */
const char* currentClassName = "";
const char* firstClassName = nullptr;
traceData->numClasses = 0;
for (int32_t ii = 0; ii < numMethods; ++ii) {
if (pMethods[ii]->methodName == nullptr) {
continue;
}
if (strcmp(pMethods[ii]->className, currentClassName) != 0) {
// Remember the first one
if (firstClassName == nullptr) {
firstClassName = pMethods[ii]->className;
}
traceData->numClasses += 1;
currentClassName = pMethods[ii]->className;
}
}
if (traceData->numClasses == 0) {
traceData->classes = nullptr;
return;
}
/* Allocate space for all of the unique class names */
traceData->classes = new ClassEntry[traceData->numClasses];
/* Initialize the classes array */
memset(traceData->classes, 0, sizeof(ClassEntry) * traceData->numClasses);
ClassEntry* pClass = traceData->classes;
pClass->className = currentClassName = firstClassName;
int32_t prevNumMethods = 0;
for (int32_t ii = 0; ii < numMethods; ++ii) {
if (pMethods[ii]->methodName == nullptr) {
continue;
}
if (strcmp(pMethods[ii]->className, currentClassName) != 0) {
pClass->numMethods = prevNumMethods;
(++pClass)->className = currentClassName = pMethods[ii]->className;
prevNumMethods = 0;
}
prevNumMethods += 1;
}
pClass->numMethods = prevNumMethods;
/* Create the array of MethodEntry pointers for each class */
pClass = nullptr;
currentClassName = "";
int32_t nextMethod = 0;
for (int32_t ii = 0; ii < numMethods; ++ii) {
if (pMethods[ii]->methodName == nullptr) {
continue;
}
if (strcmp(pMethods[ii]->className, currentClassName) != 0) {
currentClassName = pMethods[ii]->className;
if (pClass == nullptr)
pClass = traceData->classes;
else
pClass++;
/* Allocate space for the methods array */
pClass->methods = new MethodEntry*[pClass->numMethods];
nextMethod = 0;
}
pClass->methods[nextMethod++] = pMethods[ii];
}
}
/* Prints a number of html non-breaking spaces according so that the length
* of the string "buf" is at least "width" characters wide. If width is
* negative, then trailing spaces are added instead of leading spaces.
*/
void printHtmlField(char* buf, int32_t width) {
int32_t leadingSpaces = 1;
if (width < 0) {
width = -width;
leadingSpaces = 0;
}
int32_t len = strlen(buf);
int32_t numSpaces = width - len;
if (numSpaces <= 0) {
printf("%s", buf);
return;
}
if (leadingSpaces == 0) printf("%s", buf);
for (int32_t ii = 0; ii < numSpaces; ++ii) printf(" ");
if (leadingSpaces == 1) printf("%s", buf);
}
void printClassProfiles(TraceData* traceData, uint64_t sumThreadTime) {
char classBuf[HTML_BUFSIZE];
char methodBuf[HTML_BUFSIZE];
char signatureBuf[HTML_BUFSIZE];
if (gOptions.outputHtml) {
printf("<a name=\"class\"></a>\n");
printf("<hr>\n");
outputNavigationBar();
} else {
printf("\n%s\n", profileSeparator);
}
if (traceData->numClasses == 0) {
printf("\nNo classes.\n");
if (gOptions.outputHtml) {
printf("<br><br>\n");
}
return;
}
printf("\nExclusive elapsed time for each class, summed over all the methods\n");
printf("in the class.\n\n");
if (gOptions.outputHtml) {
printf("<br><br>\n");
}
/* For each class, sum the exclusive times in all of the methods
* in that class. Also sum the number of method calls. Also
* sort the methods so the most expensive appear at the top.
*/
ClassEntry* pClass = traceData->classes;
for (int32_t ii = 0; ii < traceData->numClasses; ++ii, ++pClass) {
// printf("%s %d methods\n", pClass->className, pClass->numMethods);
int32_t numMethods = pClass->numMethods;
for (int32_t jj = 0; jj < numMethods; ++jj) {
MethodEntry* method = pClass->methods[jj];
pClass->elapsedExclusive += method->elapsedExclusive;
pClass->numCalls[0] += method->numCalls[0];
pClass->numCalls[1] += method->numCalls[1];
}
/* Sort the methods into decreasing order of exclusive time */
qsort(pClass->methods, numMethods, sizeof(MethodEntry*), compareElapsedExclusive);
}
/* Allocate an array of pointers to the classes for more efficient sorting. */
ClassEntry** pClasses = new ClassEntry*[traceData->numClasses];
for (int32_t ii = 0; ii < traceData->numClasses; ++ii)
pClasses[ii] = &traceData->classes[ii];
/* Sort the classes into decreasing order of exclusive time */
qsort(pClasses, traceData->numClasses, sizeof(ClassEntry*), compareClassExclusive);
if (gOptions.outputHtml) {
printf(
"<div class=\"header\"><span "
"class=\"parent\"> </span> ");
printf("Cycles %%/total Cumul.%% Calls+Recur Class</div>\n");
} else {
printf(" Cycles %%/total Cumul.%% Calls+Recur Class\n");
}
double sum = 0;
double total = sumThreadTime;
for (int32_t ii = 0; ii < traceData->numClasses; ++ii) {
/* Skip classes with zero cycles */
pClass = pClasses[ii];
if (pClass->elapsedExclusive == 0) break;
sum += pClass->elapsedExclusive;
double per = 100.0 * pClass->elapsedExclusive / total;
double sum_per = 100.0 * sum / total;
const char* className = pClass->className;
if (gOptions.outputHtml) {
char buf[80];
className = htmlEscape(className, classBuf, HTML_BUFSIZE);
printf(
"<div class=\"link\" onClick=\"javascript:toggle('d%d')\" "
"onMouseOver=\"javascript:onMouseOver(this)\" "
"onMouseOut=\"javascript:onMouseOut(this)\"><span class=\"parent\" "
"id=\"xd%d\">+</span>",
ii, ii);
sprintf(buf, "%" PRIu64, pClass->elapsedExclusive);
printHtmlField(buf, 9);
printf(" ");
sprintf(buf, "%.1f", per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%.1f", sum_per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%d", pClass->numCalls[0]);
printHtmlField(buf, 6);
printf("+");
sprintf(buf, "%d", pClass->numCalls[1]);
printHtmlField(buf, -6);
printf(" ");
printf("%s", className);
printf("</div>\n");
printf("<div class=\"parent\" id=\"d%d\">\n", ii);
} else {
printf("---------------------------------------------\n");
printf("%9" PRIu64 " %7.1f %7.1f %6d+%-6d %s\n", pClass->elapsedExclusive,
per, sum_per, pClass->numCalls[0], pClass->numCalls[1], className);
}
int32_t numMethods = pClass->numMethods;
double classExclusive = pClass->elapsedExclusive;
double sumMethods = 0;
for (int32_t jj = 0; jj < numMethods; ++jj) {
MethodEntry* method = pClass->methods[jj];
const char* methodName = method->methodName;
const char* signature = method->signature;
per = 100.0 * method->elapsedExclusive / classExclusive;
sumMethods += method->elapsedExclusive;
sum_per = 100.0 * sumMethods / classExclusive;
if (gOptions.outputHtml) {
char buf[80];
methodName = htmlEscape(methodName, methodBuf, HTML_BUFSIZE);
signature = htmlEscape(signature, signatureBuf, HTML_BUFSIZE);
printf("<div class=\"leaf\"><span class=\"leaf\"> </span>");
sprintf(buf, "%" PRIu64, method->elapsedExclusive);
printHtmlField(buf, 9);
printf(" ");
sprintf(buf, "%" PRIu64, method->elapsedInclusive);
printHtmlField(buf, 9);
printf(" ");
sprintf(buf, "%.1f", per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%.1f", sum_per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%d", method->numCalls[0]);
printHtmlField(buf, 6);
printf("+");
sprintf(buf, "%d", method->numCalls[1]);
printHtmlField(buf, -6);
printf(" ");
printf("<a href=\"#m%d\">[%d]</a> %s %s", method->index,
method->index, methodName, signature);
printf("</div>\n");
} else {
printf("%9" PRIu64 " %9" PRIu64 " %7.1f %7.1f %6d+%-6d [%d] %s %s\n",
method->elapsedExclusive, method->elapsedInclusive, per, sum_per,
method->numCalls[0], method->numCalls[1], method->index,
methodName, signature);
}
}
if (gOptions.outputHtml) {
printf("</div>\n");
}
}
}
void createUniqueMethodList(TraceData* traceData, MethodEntry** pMethods, int32_t numMethods) {
/* Sort the methods into alphabetical order of method names
* to find the unique method names.
*/
qsort(pMethods, numMethods, sizeof(MethodEntry*), compareMethodNames);
/* Count the number of unique method names, ignoring class and signature. */
const char* currentMethodName = "";
traceData->numUniqueMethods = 0;
for (int32_t ii = 0; ii < numMethods; ++ii) {
if (pMethods[ii]->methodName == nullptr) continue;
if (strcmp(pMethods[ii]->methodName, currentMethodName) != 0) {
traceData->numUniqueMethods += 1;
currentMethodName = pMethods[ii]->methodName;
}
}
if (traceData->numUniqueMethods == 0) return;
/* Allocate space for pointers to all of the unique methods */
traceData->uniqueMethods = new UniqueMethodEntry[traceData->numUniqueMethods];
/* Initialize the uniqueMethods array */
memset(traceData->uniqueMethods, 0, sizeof(UniqueMethodEntry) * traceData->numUniqueMethods);
UniqueMethodEntry* pUnique = traceData->uniqueMethods;
currentMethodName = nullptr;
int32_t prevNumMethods = 0;
for (int32_t ii = 0; ii < numMethods; ++ii) {
if (pMethods[ii]->methodName == nullptr) continue;
if (currentMethodName == nullptr) currentMethodName = pMethods[ii]->methodName;
if (strcmp(pMethods[ii]->methodName, currentMethodName) != 0) {
currentMethodName = pMethods[ii]->methodName;
pUnique->numMethods = prevNumMethods;
pUnique++;
prevNumMethods = 0;
}
prevNumMethods += 1;
}
pUnique->numMethods = prevNumMethods;
/* Create the array of MethodEntry pointers for each unique method */
pUnique = nullptr;
currentMethodName = "";
int32_t nextMethod = 0;
for (int32_t ii = 0; ii < numMethods; ++ii) {
if (pMethods[ii]->methodName == nullptr) continue;
if (strcmp(pMethods[ii]->methodName, currentMethodName) != 0) {
currentMethodName = pMethods[ii]->methodName;
if (pUnique == nullptr)
pUnique = traceData->uniqueMethods;
else
pUnique++;
/* Allocate space for the methods array */
pUnique->methods = new MethodEntry*[pUnique->numMethods];
nextMethod = 0;
}
pUnique->methods[nextMethod++] = pMethods[ii];
}
}
void printMethodProfiles(TraceData* traceData, uint64_t sumThreadTime) {
char classBuf[HTML_BUFSIZE], methodBuf[HTML_BUFSIZE];
char signatureBuf[HTML_BUFSIZE];
if (traceData->numUniqueMethods == 0) return;
if (gOptions.outputHtml) {
printf("<a name=\"method\"></a>\n");
printf("<hr>\n");
outputNavigationBar();
} else {
printf("\n%s\n", profileSeparator);
}
printf("\nExclusive elapsed time for each method, summed over all the classes\n");
printf("that contain a method with the same name.\n\n");
if (gOptions.outputHtml) {
printf("<br><br>\n");
}
/* For each unique method, sum the exclusive times in all of the methods
* with the same name. Also sum the number of method calls. Also
* sort the methods so the most expensive appear at the top.
*/
UniqueMethodEntry* pUnique = traceData->uniqueMethods;
for (int32_t ii = 0; ii < traceData->numUniqueMethods; ++ii, ++pUnique) {
int32_t numMethods = pUnique->numMethods;
for (int32_t jj = 0; jj < numMethods; ++jj) {
MethodEntry* method = pUnique->methods[jj];
pUnique->elapsedExclusive += method->elapsedExclusive;
pUnique->numCalls[0] += method->numCalls[0];
pUnique->numCalls[1] += method->numCalls[1];
}
/* Sort the methods into decreasing order of exclusive time */
qsort(pUnique->methods, numMethods, sizeof(MethodEntry*), compareElapsedExclusive);
}
/* Allocate an array of pointers to the methods for more efficient sorting. */
UniqueMethodEntry** pUniqueMethods = new UniqueMethodEntry*[traceData->numUniqueMethods];
for (int32_t ii = 0; ii < traceData->numUniqueMethods; ++ii)
pUniqueMethods[ii] = &traceData->uniqueMethods[ii];
/* Sort the methods into decreasing order of exclusive time */
qsort(pUniqueMethods, traceData->numUniqueMethods, sizeof(UniqueMethodEntry*),
compareUniqueExclusive);
if (gOptions.outputHtml) {
printf(
"<div class=\"header\"><span "
"class=\"parent\"> </span> ");
printf("Cycles %%/total Cumul.%% Calls+Recur Method</div>\n");
} else {
printf(" Cycles %%/total Cumul.%% Calls+Recur Method\n");
}
double sum = 0;
double total = sumThreadTime;
for (int32_t ii = 0; ii < traceData->numUniqueMethods; ++ii) {
/* Skip methods with zero cycles */
pUnique = pUniqueMethods[ii];
if (pUnique->elapsedExclusive == 0) break;
sum += pUnique->elapsedExclusive;
double per = 100.0 * pUnique->elapsedExclusive / total;
double sum_per = 100.0 * sum / total;
const char* methodName = pUnique->methods[0]->methodName;
if (gOptions.outputHtml) {
char buf[80];
methodName = htmlEscape(methodName, methodBuf, HTML_BUFSIZE);
printf(
"<div class=\"link\" onClick=\"javascript:toggle('e%d')\" "
"onMouseOver=\"javascript:onMouseOver(this)\" "
"onMouseOut=\"javascript:onMouseOut(this)\"><span class=\"parent\" "
"id=\"xe%d\">+</span>",
ii, ii);
sprintf(buf, "%" PRIu64, pUnique->elapsedExclusive);
printHtmlField(buf, 9);
printf(" ");
sprintf(buf, "%.1f", per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%.1f", sum_per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%d", pUnique->numCalls[0]);
printHtmlField(buf, 6);
printf("+");
sprintf(buf, "%d", pUnique->numCalls[1]);
printHtmlField(buf, -6);
printf(" ");
printf("%s", methodName);
printf("</div>\n");
printf("<div class=\"parent\" id=\"e%d\">\n", ii);
} else {
printf("---------------------------------------------\n");
printf("%9" PRIu64 " %7.1f %7.1f %6d+%-6d %s\n",
pUnique->elapsedExclusive, per, sum_per, pUnique->numCalls[0],
pUnique->numCalls[1], methodName);
}
int32_t numMethods = pUnique->numMethods;
double methodExclusive = pUnique->elapsedExclusive;
double sumMethods = 0;
for (int32_t jj = 0; jj < numMethods; ++jj) {
MethodEntry* method = pUnique->methods[jj];
const char* className = method->className;
const char* signature = method->signature;
per = 100.0 * method->elapsedExclusive / methodExclusive;
sumMethods += method->elapsedExclusive;
sum_per = 100.0 * sumMethods / methodExclusive;
if (gOptions.outputHtml) {
char buf[80];
className = htmlEscape(className, classBuf, HTML_BUFSIZE);
signature = htmlEscape(signature, signatureBuf, HTML_BUFSIZE);
printf("<div class=\"leaf\"><span class=\"leaf\"> </span>");
sprintf(buf, "%" PRIu64, method->elapsedExclusive);
printHtmlField(buf, 9);
printf(" ");
sprintf(buf, "%" PRIu64, method->elapsedInclusive);
printHtmlField(buf, 9);
printf(" ");
sprintf(buf, "%.1f", per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%.1f", sum_per);
printHtmlField(buf, 7);
printf(" ");
sprintf(buf, "%d", method->numCalls[0]);
printHtmlField(buf, 6);
printf("+");
sprintf(buf, "%d", method->numCalls[1]);
printHtmlField(buf, -6);
printf(" ");
printf("<a href=\"#m%d\">[%d]</a> %s.%s %s", method->index,
method->index, className, methodName, signature);
printf("</div>\n");
} else {
printf("%9" PRIu64 " %9" PRIu64 " %7.1f %7.1f %6d+%-6d [%d] %s.%s %s\n",
method->elapsedExclusive, method->elapsedInclusive, per, sum_per,
method->numCalls[0], method->numCalls[1], method->index,
className, methodName, signature);
}
}
if (gOptions.outputHtml) {
printf("</div>\n");
}
}
}
/*
* Read the key and data files and return the MethodEntries for those files
*/
DataKeys* parseDataKeys(TraceData* traceData, const char* traceFileName, uint64_t* threadTime) {
MethodEntry* caller;
FILE* dataFp = fopen(traceFileName, "rb");
if (dataFp == nullptr) return nullptr;
DataKeys* dataKeys = parseKeys(dataFp, 0);
if (dataKeys == nullptr) {
fclose(dataFp);
return nullptr;
}
DataHeader dataHeader;
if (parseDataHeader(dataFp, &dataHeader) < 0) {
fclose(dataFp);
return dataKeys;
}
#if 0
FILE* dumpStream = fopen("debug", "w");
#endif
while (1) {
/*
* Extract values from file.
*/
int32_t threadId;
uint32_t methodVal;
uint64_t currentTime;
if (readDataRecord(dataFp, &dataHeader, &threadId, &methodVal, ¤tTime))
break;
int32_t action = METHOD_ACTION(methodVal);
int64_t methodId = METHOD_ID(methodVal);
/* Get the call stack for this thread */
CallStack* pStack = traceData->stacks[threadId];
/* If there is no call stack yet for this thread, then allocate one */
if (pStack == nullptr) {
pStack = new CallStack();
pStack->top = 0;
pStack->lastEventTime = currentTime;
pStack->threadStartTime = currentTime;
traceData->stacks[threadId] = pStack;
}
/* Lookup the current method */
MethodEntry* method = lookupMethod(dataKeys, methodId);
if (method == nullptr) method = &dataKeys->methods[UNKNOWN_INDEX];
#if 0
if (method->methodName) {
fprintf(dumpStream, "%2d %-8llu %d %8llu r %d c %d %s.%s %s\n",
threadId, currentTime, action, pStack->threadStartTime,
method->recursiveEntries,
pStack->top, method->className, method->methodName,
method->signature);
} else {
fprintf(dumpStream, "%2d %-8llu %d %8llu r %d c %d %s\n",
threadId, currentTime, action, pStack->threadStartTime,
method->recursiveEntries,
pStack->top, method->className);
}
#endif
if (action == METHOD_TRACE_ENTER) {
/* This is a method entry */
if (pStack->top >= MAX_STACK_DEPTH) {
fprintf(stderr, "Stack overflow (exceeded %d frames)\n",
MAX_STACK_DEPTH);
exit(1);
}
/* Get the caller method */
if (pStack->top >= 1)
caller = pStack->calls[pStack->top - 1].method;
else
caller = &dataKeys->methods[TOPLEVEL_INDEX];
countRecursiveEntries(pStack, pStack->top, caller);
caller->elapsedExclusive += currentTime - pStack->lastEventTime;
#if 0
if (caller->elapsedExclusive > 10000000)
fprintf(dumpStream, "%llu current %llu last %llu diff %llu\n",
caller->elapsedExclusive, currentTime,
pStack->lastEventTime,
currentTime - pStack->lastEventTime);
#endif
if (caller->recursiveEntries <= 1) {
caller->topExclusive += currentTime - pStack->lastEventTime;
}
/* Push the method on the stack for this thread */
pStack->calls[pStack->top].method = method;
pStack->calls[pStack->top++].entryTime = currentTime;
} else {
/* This is a method exit */
uint64_t entryTime = 0;
/* Pop the method off the stack for this thread */
if (pStack->top > 0) {
pStack->top -= 1;
entryTime = pStack->calls[pStack->top].entryTime;
if (method != pStack->calls[pStack->top].method) {
if (method->methodName) {
fprintf(stderr, "Exit from method %s.%s %s does not match stack:\n",
method->className, method->methodName, method->signature);
} else {
fprintf(stderr, "Exit from method %s does not match stack:\n",
method->className);
}
stackDump(pStack, pStack->top + 1);
exit(1);
}
}
/* Get the caller method */
if (pStack->top >= 1)
caller = pStack->calls[pStack->top - 1].method;
else
caller = &dataKeys->methods[TOPLEVEL_INDEX];
countRecursiveEntries(pStack, pStack->top, caller);
countRecursiveEntries(pStack, pStack->top, method);
uint64_t elapsed = currentTime - entryTime;
addInclusiveTime(caller, method, elapsed);
method->elapsedExclusive += currentTime - pStack->lastEventTime;
if (method->recursiveEntries == 0) {
method->topExclusive += currentTime - pStack->lastEventTime;
}
}
/* Remember the time of the last entry or exit event */
pStack->lastEventTime = currentTime;
}
/* If we have calls on the stack when the trace ends, then clean
* up the stack and add time to the callers by pretending that we
* are exiting from their methods now.
*/
uint64_t sumThreadTime = 0;
for (int32_t threadId = 0; threadId < MAX_THREADS; ++threadId) {
CallStack* pStack = traceData->stacks[threadId];
/* If this thread never existed, then continue with next thread */
if (pStack == nullptr) continue;
/* Also, add up the time taken by all of the threads */
sumThreadTime += pStack->lastEventTime - pStack->threadStartTime;
for (int32_t ii = 0; ii < pStack->top; ++ii) {
if (ii == 0)
caller = &dataKeys->methods[TOPLEVEL_INDEX];
else
caller = pStack->calls[ii - 1].method;
MethodEntry* method = pStack->calls[ii].method;
countRecursiveEntries(pStack, ii, caller);
countRecursiveEntries(pStack, ii, method);
uint64_t entryTime = pStack->calls[ii].entryTime;
uint64_t elapsed = pStack->lastEventTime - entryTime;
addInclusiveTime(caller, method, elapsed);
}
}
caller = &dataKeys->methods[TOPLEVEL_INDEX];
caller->elapsedInclusive = sumThreadTime;
#if 0
fclose(dumpStream);
#endif
if (threadTime != nullptr) {
*threadTime = sumThreadTime;
}
fclose(dataFp);
return dataKeys;
}
MethodEntry** parseMethodEntries(DataKeys* dataKeys) {
/* Create a new array of pointers to the methods and sort the pointers
* instead of the actual MethodEntry structs. We need to do this
* because there are other lists that contain pointers to the
* MethodEntry structs.
*/
MethodEntry** pMethods = new MethodEntry*[dataKeys->numMethods];
for (int32_t ii = 0; ii < dataKeys->numMethods; ++ii) {
MethodEntry* entry = &dataKeys->methods[ii];
pMethods[ii] = entry;
}
return pMethods;
}
/*
* Produce a function profile from the following methods
*/
void profileTrace(TraceData* traceData, MethodEntry** pMethods, int32_t numMethods,
uint64_t sumThreadTime) {
/* Print the html header, if necessary */
if (gOptions.outputHtml) {
printf(htmlHeader, gOptions.sortableUrl);
outputTableOfContents();
}
printExclusiveProfile(pMethods, numMethods, sumThreadTime);
printInclusiveProfile(pMethods, numMethods, sumThreadTime);
createClassList(traceData, pMethods, numMethods);
printClassProfiles(traceData, sumThreadTime);
createUniqueMethodList(traceData, pMethods, numMethods);
printMethodProfiles(traceData, sumThreadTime);
if (gOptions.outputHtml) {
printf("%s", htmlFooter);
}
}
int32_t compareMethodNamesForDiff(const void* a, const void* b) {
const MethodEntry* methodA = *(const MethodEntry**) a;
const MethodEntry* methodB = *(const MethodEntry**) b;
if (methodA->methodName == nullptr || methodB->methodName == nullptr) {
return compareClassNames(a, b);
}
int32_t result = strcmp(methodA->methodName, methodB->methodName);
if (result == 0) {
result = strcmp(methodA->signature, methodB->signature);
if (result == 0) {
return strcmp(methodA->className, methodB->className);
}
}
return result;
}
int32_t findMatch(MethodEntry** methods, int32_t size, MethodEntry* matchThis) {
for (int32_t i = 0; i < size; i++) {
MethodEntry* method = methods[i];
if (method != nullptr && !compareMethodNamesForDiff(&method, &matchThis)) {
// printf("%s.%s == %s.%s<br>\n", matchThis->className, matchThis->methodName,
// method->className, method->methodName);
return i;
// if (!compareMethodNames(&method, &matchThis)) return i;
}
}
return -1;
}
int32_t compareDiffEntriesExculsive(const void* a, const void* b) {
const DiffEntry* entryA = (const DiffEntry*) a;
const DiffEntry* entryB = (const DiffEntry*) b;
if (entryA->differenceExclusive < entryB->differenceExclusive) {
return 1;
} else if (entryA->differenceExclusive > entryB->differenceExclusive) {
return -1;
}
return 0;
}
int32_t compareDiffEntriesInculsive(const void* a, const void* b) {
const DiffEntry* entryA = (const DiffEntry*) a;
const DiffEntry* entryB = (const DiffEntry*) b;
if (entryA->differenceInclusive < entryB->differenceInclusive) {
return 1;
} else if (entryA->differenceInclusive > entryB->differenceInclusive) {
return -1;
}
return 0;
}
void printMissingMethod(MethodEntry* method) {
char classBuf[HTML_BUFSIZE];
char methodBuf[HTML_BUFSIZE];
char* className = htmlEscape(method->className, classBuf, HTML_BUFSIZE);
char* methodName = htmlEscape(method->methodName, methodBuf, HTML_BUFSIZE);
if (gOptions.outputHtml) printf("<tr><td>\n");
printf("%s.%s ", className, methodName);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", method->elapsedExclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", method->elapsedInclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%d\n", method->numCalls[0]);
if (gOptions.outputHtml) printf("</td><td>\n");
}
void createDiff(DataKeys* d1, DataKeys* d2) {
MethodEntry** methods1 = parseMethodEntries(d1);
MethodEntry** methods2 = parseMethodEntries(d2);
// sort and assign the indicies
qsort(methods1, d1->numMethods, sizeof(MethodEntry*), compareElapsedInclusive);
for (int32_t i = 0; i < d1->numMethods; ++i) {
methods1[i]->index = i;
}
qsort(methods2, d2->numMethods, sizeof(MethodEntry*), compareElapsedInclusive);
for (int32_t i = 0; i < d2->numMethods; ++i) {
methods2[i]->index = i;
}
int32_t max = (d1->numMethods < d2->numMethods) ? d2->numMethods : d1->numMethods;
max++;
DiffEntry* diffs = new DiffEntry[max];
memset(diffs, 0, max * sizeof(DiffEntry));
DiffEntry* ptr = diffs;
// printf("<br>d1->numMethods: %d d1->numMethods: %d<br>\n",
// d1->numMethods, d2->numMethods);
int32_t matches = 0;
for (int32_t i = 0; i < d1->numMethods; i++) {
int32_t match = findMatch(methods2, d2->numMethods, methods1[i]);
if (match >= 0) {
ptr->method1 = methods1[i];
ptr->method2 = methods2[match];
uint64_t e1 = ptr->method1->elapsedExclusive;
uint64_t e2 = ptr->method2->elapsedExclusive;
if (e1 > 0) {
ptr->differenceExclusive = e2 - e1;
ptr->differenceExclusivePercentage = (static_cast<double>(e2) /
static_cast<double>(e1)) * 100.0;
}
uint64_t i1 = ptr->method1->elapsedInclusive;
uint64_t i2 = ptr->method2->elapsedInclusive;
if (i1 > 0) {
ptr->differenceInclusive = i2 - i1;
ptr->differenceInclusivePercentage = (static_cast<double>(i2) /
static_cast<double>(i1)) * 100.0;
}
// clear these out so we don't find them again and we know which ones
// we have left over
methods1[i] = nullptr;
methods2[match] = nullptr;
ptr++;
matches++;
}
}
ptr->method1 = nullptr;
ptr->method2 = nullptr;
qsort(diffs, matches, sizeof(DiffEntry), compareDiffEntriesExculsive);
ptr = diffs;
if (gOptions.outputHtml) {
printf(htmlHeader, gOptions.sortableUrl);
printf("<h3>Table of Contents</h3>\n");
printf("<ul>\n");
printf("<li><a href='#exclusive'>Exclusive</a>\n");
printf("<li><a href='#inclusive'>Inclusive</a>\n");
printf("</ul>\n");
printf("Run 1: %s<br>\n", gOptions.diffFileName);
printf("Run 2: %s<br>\n", gOptions.traceFileName);
printf("<a name=\"exclusive\"></a><h3 id=\"exclusive\">Exclusive</h3>\n");
printf(tableHeader, "exclusive_table");
}
char classBuf[HTML_BUFSIZE];
char methodBuf[HTML_BUFSIZE];
while (ptr->method1 != nullptr && ptr->method2 != nullptr) {
if (gOptions.outputHtml) printf("<tr><td>\n");
char* className = htmlEscape(ptr->method1->className, classBuf, HTML_BUFSIZE);
char* methodName = htmlEscape(ptr->method1->methodName, methodBuf, HTML_BUFSIZE);
printf("%s.%s ", className, methodName);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", ptr->method1->elapsedExclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", ptr->method2->elapsedExclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", ptr->differenceExclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%.2f\n", ptr->differenceExclusivePercentage);
if (gOptions.outputHtml) printf("</td><td>\n");
printf("%d\n", ptr->method1->numCalls[0]);
if (gOptions.outputHtml) printf("</td><td>\n");
printf("%d\n", ptr->method2->numCalls[0]);
if (gOptions.outputHtml) printf("</td></tr>\n");
ptr++;
}
if (gOptions.outputHtml) printf("</table>\n");
if (gOptions.outputHtml) {
printf(htmlHeader, gOptions.sortableUrl);
printf("Run 1: %s<br>\n", gOptions.diffFileName);
printf("Run 2: %s<br>\n", gOptions.traceFileName);
printf("<a name=\"inclusive\"></a><h3 id=\"inculisve\">Inclusive</h3>\n");
printf(tableHeader, "inclusive_table");
}
qsort(diffs, matches, sizeof(DiffEntry), compareDiffEntriesInculsive);
ptr = diffs;
while (ptr->method1 != nullptr && ptr->method2 != nullptr) {
if (gOptions.outputHtml) printf("<tr><td>\n");
char* className = htmlEscape(ptr->method1->className, classBuf, HTML_BUFSIZE);
char* methodName = htmlEscape(ptr->method1->methodName, methodBuf, HTML_BUFSIZE);
printf("%s.%s ", className, methodName);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", ptr->method1->elapsedInclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", ptr->method2->elapsedInclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%" PRIu64 " ", ptr->differenceInclusive);
if (gOptions.outputHtml) printf("</td><td>");
printf("%.2f\n", ptr->differenceInclusivePercentage);
if (gOptions.outputHtml) printf("</td><td>\n");
printf("%d\n", ptr->method1->numCalls[0]);
if (gOptions.outputHtml) printf("</td><td>\n");
printf("%d\n", ptr->method2->numCalls[0]);
if (gOptions.outputHtml) printf("</td></tr>\n");
ptr++;
}
if (gOptions.outputHtml) {
printf("</table>\n");
printf("<h3>Run 1 methods not found in Run 2</h3>");
printf(tableHeaderMissing, "?");
}
for (int32_t i = 0; i < d1->numMethods; ++i) {
if (methods1[i] != nullptr) {
printMissingMethod(methods1[i]);
}
}
if (gOptions.outputHtml) {
printf("</table>\n");
printf("<h3>Run 2 methods not found in Run 1</h3>");
printf(tableHeaderMissing, "?");
}
for (int32_t i = 0; i < d2->numMethods; ++i) {
if (methods2[i] != nullptr) {
printMissingMethod(methods2[i]);
}
}
if (gOptions.outputHtml) printf("</body></html\n");
}
int32_t usage(const char* program) {
fprintf(stderr, "Copyright (C) 2006 The Android Open Source Project\n\n");
fprintf(stderr,
"usage: %s [-ho] [-s sortable] [-d trace-file-name] [-g outfile] "
"trace-file-name\n",
program);
fprintf(stderr, " -d trace-file-name - Diff with this trace\n");
fprintf(stderr, " -g outfile - Write graph to 'outfile'\n");
fprintf(stderr,
" -k - When writing a graph, keep the intermediate "
"DOT file\n");
fprintf(stderr, " -h - Turn on HTML output\n");
fprintf(
stderr,
" -o - Dump the dmtrace file instead of profiling\n");
fprintf(stderr,
" -s - URL base to where the sortable javascript "
"file\n");
fprintf(stderr,
" -t threshold - Threshold percentage for including nodes in "
"the graph\n");
return 2;
}
// Returns true if there was an error
int32_t parseOptions(int32_t argc, char** argv) {
while (1) {
int32_t opt = getopt(argc, argv, "d:hg:kos:t:");
if (opt == -1) break;
switch (opt) {
case 'd':
gOptions.diffFileName = optarg;
break;
case 'g':
gOptions.graphFileName = optarg;
break;
case 'k':
gOptions.keepDotFile = 1;
break;
case 'h':
gOptions.outputHtml = 1;
break;
case 'o':
gOptions.dump = 1;
break;
case 's':
gOptions.sortableUrl = optarg;
break;
case 't':
gOptions.threshold = atoi(optarg);
break;
default:
return 1;
}
}
return 0;
}
/*
* Parse args.
*/
int32_t main(int32_t argc, char** argv) {
gOptions.threshold = -1;
// Parse the options
if (parseOptions(argc, argv) || argc - optind != 1) return usage(argv[0]);
gOptions.traceFileName = argv[optind];
if (gOptions.threshold < 0 || 100 <= gOptions.threshold) {
gOptions.threshold = 20;
}
if (gOptions.dump) {
dumpTrace();
return 0;
}
uint64_t sumThreadTime = 0;
TraceData data1;
DataKeys* dataKeys = parseDataKeys(&data1, gOptions.traceFileName, &sumThreadTime);
if (dataKeys == nullptr) {
fprintf(stderr, "Cannot read \"%s\".\n", gOptions.traceFileName);
exit(1);
}
if (gOptions.diffFileName != nullptr) {
uint64_t sum2;
TraceData data2;
DataKeys* d2 = parseDataKeys(&data2, gOptions.diffFileName, &sum2);
if (d2 == nullptr) {
fprintf(stderr, "Cannot read \"%s\".\n", gOptions.diffFileName);
exit(1);
}
createDiff(d2, dataKeys);
freeDataKeys(d2);
} else {
MethodEntry** methods = parseMethodEntries(dataKeys);
profileTrace(&data1, methods, dataKeys->numMethods, sumThreadTime);
if (gOptions.graphFileName != nullptr) {
createInclusiveProfileGraphNew(dataKeys);
}
free(methods);
}
freeDataKeys(dataKeys);
return 0;
}
|
#include <iostream>
int main()
{
int x = 0;
std::cin >> x;
std::cout << "Unesena vrijednost je: " << x << std::endl;
}
|
#include "Level/Enemies/DragonWhelpEnemy.h"
#include "Level/MOBBehavior/MovingBehaviors/AggressiveFlyingBehavior.h"
#include "Level/MOBBehavior/MovingBehaviors/AllyFlyingBehavior.h"
#include "Level/MOBBehavior/AttackingBehaviors/AggressiveBehavior.h"
#include "Level/MOBBehavior/AttackingBehaviors/AllyBehavior.h"
#include "GameObjectComponents/LightComponent.h"
#include "Registrar.h"
REGISTER_ENEMY(EnemyID::Dragonwhelp, DragonWhelpEnemy)
void DragonWhelpEnemy::insertDefaultLoot(std::map<std::string, int>& loot, int& gold) const {
gold = rand() % 3 + 1;
if (rand() % 2 > 0)
loot.insert({ "mi_teeth", 1 });
if (rand() % 2 > 0)
loot.insert({ "mi_dragonskull", 1 });
}
void DragonWhelpEnemy::insertRespawnLoot(std::map<std::string, int>& loot, int& gold) const {
gold = rand() % 3 + 1;
}
float DragonWhelpEnemy::getConfiguredDistanceToHPBar() const {
return 30.f;
}
DragonWhelpEnemy::DragonWhelpEnemy(const Level* level, Screen* screen) :
LevelMovableGameObject(level),
Enemy(level, screen) {
}
void DragonWhelpEnemy::loadAttributes() {
if (m_skinNr == 2 || m_skinNr == 3) {
// purple whelp
m_attributes.setHealth(100);
}
else {
// default whelp
m_attributes.setHealth(50);
}
m_attributes.critical = 10;
m_attributes.resistancePhysical = 150;
m_attributes.resistanceFire = 5000;
m_attributes.calculateAttributes();
}
void DragonWhelpEnemy::loadSpells() {
SpellData fireBallSpell = SpellData::getSpellData(SpellID::FireBall);
fireBallSpell.damage = 20;
fireBallSpell.damagePerSecond = 10;
fireBallSpell.duration = sf::seconds(2);
fireBallSpell.cooldown = sf::seconds(4.f);
fireBallSpell.speed = 200.f;
fireBallSpell.castingTime = sf::milliseconds(6 * 50);
fireBallSpell.fightingTime = sf::milliseconds(4 * 50);
fireBallSpell.count = 2;
if (m_skinNr == 2 || m_skinNr == 3) {
// purple whelp has purple fire
fireBallSpell.damage = 40;
fireBallSpell.skinNr = 2;
fireBallSpell.damageType = DamageType::Shadow;
}
m_spellManager->addSpell(fireBallSpell);
m_spellManager->setCurrentSpell(0);
}
void DragonWhelpEnemy::update(const sf::Time& frameTime) {
Enemy::update(frameTime);
switch (m_dragonState)
{
case DragonWhelpState::Egg:
if (fastIntersect(m_boundingBox, *m_mainChar->getBoundingBox())) {
setHatching();
}
for (auto go : *m_screen->getObjects(_Enemy)) {
auto e = dynamic_cast<Enemy*>(go);
if (e->isAlly() && fastIntersect(m_boundingBox, *e->getBoundingBox())) {
setHatching();
}
}
break;
case DragonWhelpState::Hatching:
updateTime(m_hatchingTime, frameTime);
if (m_hatchingTime == sf::Time::Zero) {
setActive();
}
break;
case DragonWhelpState::Active:
default:
break;
}
}
MovingBehavior* DragonWhelpEnemy::createMovingBehavior(bool asAlly) {
FlyingBehavior* behavior;
if (asAlly) {
behavior = new AllyFlyingBehavior(this);
}
else {
behavior = new AggressiveFlyingBehavior(this);
}
behavior->setApproachingDistance(100.f);
m_movingBehavior = behavior;
// initial values
if (m_skinNr % 2 == 1 || asAlly) {
setActive();
}
else {
setInactive();
}
playCurrentAnimation(true);
return behavior;
}
AttackingBehavior* DragonWhelpEnemy::createAttackingBehavior(bool asAlly) {
EnemyAttackingBehavior* behavior;
if (asAlly) {
behavior = new AllyBehavior(this);
}
else {
behavior = new AggressiveBehavior(this);
}
behavior->setAggroRange(300.f);
behavior->setAttackInput(std::bind(&DragonWhelpEnemy::handleAttackInput, this));
return behavior;
}
void DragonWhelpEnemy::onHit(Spell* spell) {
Enemy::onHit(spell);
setActive();
}
void DragonWhelpEnemy::setDead() {
if (m_isDead) return;
m_dragonState = DragonWhelpState::Active;
m_movingBehavior->setMaxVelocityYUp(100.f);
m_movingBehavior->setMaxVelocityYDown(200.f);
m_movingBehavior->setMaxVelocityX(100.f);
unlockAnimation();
Enemy::setDead();
}
void DragonWhelpEnemy::setHatching() {
if (m_isDead) {
return;
}
m_dragonState = DragonWhelpState::Hatching;
setState(GameObjectState::Hatching);
setCurrentAnimation(getAnimation(GameObjectState::Hatching), false, true);
m_hatchingTime = getAnimation(GameObjectState::Hatching)->getAnimationTime();
}
void DragonWhelpEnemy::setActive() {
if (m_isDead) {
return;
}
m_dragonState = DragonWhelpState::Active;
m_movingBehavior->setMaxVelocityYUp(100.f);
m_movingBehavior->setMaxVelocityYDown(100.f);
m_movingBehavior->setMaxVelocityX(100.f);
unlockAnimation();
setState(GameObjectState::Idle);
}
void DragonWhelpEnemy::setInactive() {
if (m_isDead) {
return;
}
m_dragonState = DragonWhelpState::Egg;
m_movingBehavior->setMaxVelocityYUp(0.f);
m_movingBehavior->setMaxVelocityYDown(0.f);
m_movingBehavior->setMaxVelocityX(0.f);
setState(GameObjectState::Inactive);
setCurrentAnimation(getAnimation(GameObjectState::Inactive), false, true);
}
void DragonWhelpEnemy::handleAttackInput() {
if (m_dragonState != DragonWhelpState::Active) return;
if (m_enemyState != EnemyState::Chasing) return;
if (getCurrentTarget() == nullptr) return;
m_spellManager->executeCurrentSpell(getCurrentTarget());
}
sf::Time DragonWhelpEnemy::getConfiguredWaitingTime() const {
return sf::seconds(static_cast<float>(rand() % 2 + 1));
}
sf::Time DragonWhelpEnemy::getConfiguredChasingTime() const {
return sf::seconds(static_cast<float>(rand() % 4 + 2));
}
void DragonWhelpEnemy::loadAnimation(int skinNr) {
setBoundingBox(sf::FloatRect(0.f, 0.f, 40.f, 30.f));
setSpriteOffset(sf::Vector2f(-15.f, -35.f));
LightData data(sf::Vector2f(m_boundingBox.width * 0.5f, m_boundingBox.height * 0.5f), 150.f, 0.5f);
addComponent(new LightComponent(data, this));
const sf::Texture* tex = g_resourceManager->getTexture(getSpritePath());
int width = 70;
int height = 90;
skinNr = skinNr / 2; // because we always do have egged and hatched skins
Animation* flyingAnimation = new Animation(sf::milliseconds(50));
flyingAnimation->setSpriteSheet(tex);
for (int i = 0; i < 10; ++i) {
flyingAnimation->addFrame(sf::IntRect(i * width, (height * 4) * skinNr, width, height));
}
addAnimation(GameObjectState::Flying, flyingAnimation);
Animation* idleAnimation = new Animation(sf::milliseconds(50));
idleAnimation->setSpriteSheet(tex);
for (int i = 0; i < 10; ++i) {
idleAnimation->addFrame(sf::IntRect(i * width, (height * 4) * skinNr, width, height));
}
addAnimation(GameObjectState::Idle, idleAnimation);
Animation* castingAnimation = new Animation(sf::milliseconds(50));
castingAnimation->setSpriteSheet(tex);
for (int i = 0; i < 6; ++i) {
castingAnimation->addFrame(sf::IntRect(i * width, (height * 4) * skinNr + height, width, height));
}
addAnimation(GameObjectState::Casting, castingAnimation);
Animation* fightingAnimation = new Animation(sf::milliseconds(50));
fightingAnimation->setSpriteSheet(tex);
for (int i = 6; i < 10; ++i) {
fightingAnimation->addFrame(sf::IntRect(i * width, (height * 4) * skinNr + height, width, height));
}
addAnimation(GameObjectState::Fighting, fightingAnimation);
Animation* deadAnimation = new Animation(sf::milliseconds(80));
deadAnimation->setSpriteSheet(tex);
for (int i = 0; i < 6; ++i) {
deadAnimation->addFrame(sf::IntRect(i * width, (height * 4) * skinNr + 2 * height, width, height));
}
deadAnimation->setLooped(false);
addAnimation(GameObjectState::Dead, deadAnimation);
Animation* inactiveAnimation = new Animation(sf::seconds(10.f));
inactiveAnimation->setSpriteSheet(tex);
inactiveAnimation->addFrame(sf::IntRect(6 * width, (height * 4) * skinNr + 2 * height, width, height));
inactiveAnimation->setLooped(false);
addAnimation(GameObjectState::Inactive, inactiveAnimation);
Animation* hatchingAnimation = new Animation(sf::milliseconds(50));
hatchingAnimation->setSpriteSheet(tex);
for (int i = 6; i < 10; ++i) {
hatchingAnimation->addFrame(sf::IntRect(i * width, (height * 4) * skinNr + 2 * height, width, height));
}
for (int i = 0; i < 10; ++i) {
hatchingAnimation->addFrame(sf::IntRect(i * width, (height * 4) * skinNr + 3 * height, width, height));
}
hatchingAnimation->setLooped(false);
addAnimation(GameObjectState::Hatching, hatchingAnimation);
}
std::string DragonWhelpEnemy::getSpritePath() const {
return "res/texture/enemies/spritesheet_enemy_dragonwhelp.png";
}
std::string DragonWhelpEnemy::getDeathSoundPath() const {
return "res/sound/mob/dragon_death.ogg";
}
|
#include "SimpleJSON.h"
#include "logger.h"
#include <sstream>
#include <algorithm>
using namespace std;
/*****************************************************************************
* Writers
*****************************************************************************/
SimpleJSONBuilderCompactWriter::SimpleJSONBuilderCompactWriter()
: rapidjson::Writer<rapidjson::StringBuffer>(
static_cast<rapidjson::StringBuffer&>(*this))
{
}
void SimpleJSONBuilderCompactWriter::ResetAndClear() {
rapidjson::StringBuffer::Clear();
rapidjson::Writer<rapidjson::StringBuffer>::Reset(
static_cast<rapidjson::StringBuffer&>(*this));
}
SimpleJSONBuilderPrettyWriter::SimpleJSONBuilderPrettyWriter()
: rapidjson::PrettyWriter<rapidjson::StringBuffer>(
static_cast<rapidjson::StringBuffer&>(*this))
{
}
void SimpleJSONBuilderPrettyWriter::ResetAndClear() {
rapidjson::StringBuffer::Clear();
rapidjson::PrettyWriter<rapidjson::StringBuffer>::Reset(
static_cast<rapidjson::StringBuffer&>(*this));
}
/*****************************************************************************
* Base Scalar Field
*****************************************************************************/
FieldBase::FieldBase()
: supplied(false)
{
}
void FieldBase::Clear() {
supplied = false;
}
FieldBase * FieldBase::StartObject() {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::EndObject(rapidjson::SizeType memberCount) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::String(const char* str, rapidjson::SizeType length, bool copy) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Key(const char* str, rapidjson::SizeType length, bool copy) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Int(int i) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Int64(int64_t i) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Uint(unsigned u) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Uint64(uint64_t u) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Double(double d) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Bool(bool b) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::StartArray() {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::EndArray(rapidjson::SizeType elementCount) {
throw spJSON::WrongTypeError{Name()};
}
bool FieldBase::Null() {
supplied = false;
return true;
}
/*****************************************************************************
* SimpleParsedJSON - Auto-generate
*****************************************************************************/
class SimpleParsedJSON_Generator {
private:
class IFieldType {
public:
virtual ~IFieldType() {}
virtual string GetDefinition() = 0;
virtual std::shared_ptr<SimpleParsedJSON_Generator> ObjectDefn() {
return nullptr;
}
};
class BaseField: public IFieldType {
public:
BaseField(
const std::string& type,
const std::string& name,
const std::string& indent)
: type(type)
, name(name)
, indent(indent) { }
virtual string GetDefinition() {
std::string def = indent + type + "(" + name + ");";
return def;
}
static std::unique_ptr<BaseField> I64Type(
bool isArray,
const std::string& name,
const std::string& indent) {
return std::make_unique<BaseField>(
isArray? "NewI64ArrayField" : "NewI64Field",
name,
indent);
}
static std::unique_ptr<BaseField> UI64Type(
bool isArray,
const std::string& name,
const std::string& indent) {
return std::make_unique<BaseField>(
isArray? "NewUI64ArrayField" : "NewUI64Field",
name,
indent);
}
static std::unique_ptr<BaseField> IntType(
bool isArray,
const std::string& name,
const std::string& indent) {
return std::make_unique<BaseField>(
isArray? "NewIntArrayField" : "NewIntField",
name,
indent);
}
static std::unique_ptr<BaseField> UIntType(
bool isArray,
const std::string& name,
const std::string& indent) {
return std::make_unique<BaseField>(
isArray? "NewUIntArrayField" : "NewUIntField",
name,
indent);
}
static std::unique_ptr<BaseField> BoolType(
bool isArray,
const std::string& name,
const std::string& indent) {
return std::make_unique<BaseField>(
isArray? "NewBoolArrayField" : "NewBoolField",
name,
indent);
}
static std::unique_ptr<BaseField> DoubleType(
bool isArray,
const std::string& name,
const std::string& indent) {
return std::make_unique<BaseField>(
isArray ? "NewDoubleArrayField" : "NewDoubleField",
name,
indent);
}
static std::unique_ptr<BaseField> StringType(
bool isArray,
const std::string& name,
const std::string& indent) {
return std::make_unique<BaseField>(
isArray ? "NewStringArrayField" : "NewStringField",
name,
indent);
}
private:
std::string type;
std::string name;
std::string indent;
};
class ObjectField: public IFieldType {
public:
ObjectField(bool isArray,
const std::string& name,
const std::string& indent,
const spJSON::GeneratorOptions& options)
: isArray(isArray)
, indent(indent)
, name(name)
{
string childNamespace = name + "_fields";
objDefn = std::make_shared<SimpleParsedJSON_Generator>(
childNamespace,
indent + " ",
options);
}
virtual string GetDefinition() {
string jsonName = name + "_fields::JSON";
stringstream buf;
buf << endl;
buf << objDefn->GetCode("JSON");
if (isArray) {
buf << indent << "NewObjectArray(";
} else {
buf << indent << "NewEmbededObject(";
}
buf << name << ", " << jsonName << ");";
return buf.str();
}
static std::unique_ptr<ObjectField> ObjectType(
bool isArray,
const std::string& name,
const std::string& indent,
const spJSON::GeneratorOptions& options)
{
return std::make_unique<ObjectField>(isArray, name, indent, options);
}
virtual std::shared_ptr<SimpleParsedJSON_Generator> ObjectDefn() override {
return objDefn;
}
public:
bool isArray;
std::string indent;
std::string name;
shared_ptr<SimpleParsedJSON_Generator> objDefn;
};
public:
SimpleParsedJSON_Generator(
const std::string _namespaceName = "",
const std::string _indent = " ",
spJSON::GeneratorOptions opts = spJSON::GeneratorOptions())
: started(false),
isArray(false),
childObject(nullptr),
pendingObject(nullptr),
indent(_indent),
namespaceName(_namespaceName),
options(opts) {
int nsIndentSize = indent.length() - 4;
if (nsIndentSize < 0) {
nsIndentSize = 0;
}
nsIndent = indent.substr(0, nsIndentSize);
}
SimpleParsedJSON_Generator &ActiveObject() {
SimpleParsedJSON_Generator *obj = childObject.get();
if (obj) {
return obj->ActiveObject();
} else {
return *this;
}
}
/*
* Check if the parser is currently parsing an object that is a child of this
* parsed object.
*
* NOTE: This does NOT guarentee that childObject is not null, since we may
* be ignoring the object.
*/
bool ParsingChildObject() {
bool parserIsBelowUs = false;
if (childObject.get()) {
// Yup - directly in an object below us.
parserIsBelowUs = true;
} else if ( isArray) {
// Yup - We have an unclosed array, must be below us...
parserIsBelowUs = true;
}
return parserIsBelowUs;
}
bool KnownType() {
return (current->second.get() != nullptr);
}
bool Key(const char *str, rapidjson::SizeType length, bool copy) {
auto &active = ActiveObject();
if (active.ParsingChildObject()) {
// The parser is below the current "active" level, which means
// we are not interested in the field...
//
// (For this to have happened we must have actively decided to
// ignore a descent. This may happen for example when parsing
// arrays of objects).
} else {
string field = str;
auto it = active.keys.find(field);
if (it == active.keys.end()) {
it = active.keys.emplace(field, unique_ptr<IFieldType>(nullptr)).first;
}
active.current = it;
}
return true;
}
bool String(const char *str, rapidjson::SizeType length, bool copy) {
auto &active = ActiveObject();
if (active.KnownType()) {
// We already know what this is...
} else {
active.current->second = BaseField::StringType(active.isArray, active.current->first, active.indent);
}
return true;
}
bool Double(double d) {
auto &active = ActiveObject();
if (active.KnownType()) {
// We already know what this is...
} else {
active.current->second = BaseField::DoubleType(active.isArray, active.current->first, active.indent);
}
return true;
}
bool Int(int i) {
auto &active = ActiveObject();
if (active.KnownType()) {
// We already know what this is...
} else {
active.current->second = BaseField::IntType(active.isArray, active.current->first, active.indent);
}
return true;
}
bool Int64(int64_t i) {
auto &active = ActiveObject();
if (active.KnownType()) {
// We already know what this is...
} else {
active.current->second = BaseField::I64Type(active.isArray, active.current->first, active.indent);
}
return true;
}
bool Uint(unsigned u) {
auto &active = ActiveObject();
if (active.KnownType()) {
// We already know what this is...
} else {
active.current->second = BaseField::UIntType(active.isArray, active.current->first, active.indent);
}
return true;
}
bool Uint64(uint64_t u) {
auto &active = ActiveObject();
if (active.KnownType()) {
// We already know what this is...
} else {
active.current->second = BaseField::UI64Type(active.isArray, active.current->first, active.indent);
}
return true;
}
bool Bool(bool b) {
auto &active = ActiveObject();
if (active.KnownType()) {
// We already know what this is...
} else {
active.current->second = BaseField::BoolType(active.isArray, active.current->first, active.indent);
}
return true;
}
virtual bool StartArray() {
auto &active = ActiveObject();
active.isArray = true;
return true;
}
virtual bool EndArray(rapidjson::SizeType elementCount) {
auto &active = ActiveObject();
active.isArray = false;
return true;
}
bool StartObject() {
if (started == false) {
LOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::StartObject",
"Starting initial object");
started = true;
} else if (childObject.get()) {
LOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::StartObject",
"forwarding to existing child object...");
childObject->StartObject();
} else if (KnownType() && options.mergeFields == false) {
SLOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::StartObject",
"Skipping object, we already know the type: "
<< namespaceName << "::" << current->first)
} else if (KnownType() && options.mergeFields == true) {
SLOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::StartObject",
"Resuming known object: "
<< namespaceName << "::" << current->first)
childObject = current->second->ObjectDefn();
} else {
SLOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::StartObject",
"Starting a new child object: " << current->first);
auto objPtr = ObjectField::ObjectType(isArray, current->first, indent, options);
childObject = objPtr->ObjectDefn();
childObject->StartObject();
pendingObject = std::move(objPtr);
}
return true;
}
bool EndObject(rapidjson::SizeType memberCount) {
if (started == false) {
SLOG_FROM(
LOG_VERBOSE,
"SimpleParsedJSON_Generator::EndObject",
"End of non-existent object!");
}
else if (childObject.get() == nullptr) {
LOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::EndObject",
"Terminated the object itself");
} else if (childObject->ParsingChildObject()) {
LOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::EndObject",
"Forwarding to child object...");
childObject->EndObject(memberCount);
} else if (KnownType() && options.mergeFields == false) {
SLOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::EndObject",
"Skipping end object, for object of known type..."
<< namespaceName << "::" << current->first)
} else if (KnownType() && options.mergeFields == true) {
SLOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::EndObject",
"Completed object, again: "
<< namespaceName << "::" << current->first)
childObject.reset((SimpleParsedJSON_Generator*)nullptr);
} else {
SLOG_FROM(
LOG_VERY_VERBOSE,
"SimpleParsedJSON_Generator::EndObject",
"Finished processing child object, " << current->first);
childObject->EndObject(memberCount);
if (pendingObject.get()) {
current->second.reset(pendingObject.release());
pendingObject.reset(nullptr);
}
childObject.reset((SimpleParsedJSON_Generator*)nullptr);
}
return true;
}
bool Null() {
if (options.ignoreNull == false) {
throw "TODO!";
} else {
// Ignore the null - there might be another type to come...
}
return true;
}
bool RawNumber(const char *str, size_t len, bool copy) {
return this->String(str, len, copy);
}
string GetCode(const std::string &jsonName) {
stringstream result;
stringstream fields;
if (namespaceName != "") {
result << nsIndent << "namespace " << namespaceName << " {" << endl;
}
auto it = keys.begin();
while (it != keys.end()) {
if (it->second.get() == nullptr) {
it = keys.erase(it);
} else {
++it;
}
}
it = keys.begin();
while (it != keys.end()) {
result << it->second->GetDefinition() << endl;
fields << indent << " " << it->first;
++it;
if (it == keys.end()) {
fields << endl;
} else {
fields << "," << endl;
}
}
result << endl;
result << indent << "typedef SimpleParsedJSON<" << endl;
result << fields.str();
result << indent << "> " << jsonName << ";" << endl;
if (namespaceName != "") {
result << nsIndent << "}" << endl;
}
return result.str();
}
private:
bool started; // Indicates if we have found the start of the outer object yet
bool isArray; // Indicates if the field currently being scanned is an array
shared_ptr<SimpleParsedJSON_Generator> childObject;
std::unique_ptr<ObjectField> pendingObject;
typedef std::map<std::string,std::unique_ptr<IFieldType>> Keys;
Keys keys;
Keys::iterator current;
std::string indent;
std::string nsIndent;
std::string namespaceName;
spJSON::GeneratorOptions options;
};
std::string spJSON::Gen(
const string& className,
const string& exampleJson,
spJSON::GeneratorOptions options )
{
SimpleParsedJSON_Generator gen("", " ", options);
rapidjson::StringStream ss(exampleJson.c_str());
rapidjson::Reader reader;
reader.Parse(ss,gen);
return gen.GetCode(className);
}
|
/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "codemodel.h"
// ---------------------------------------------------------------------------
CodeModel::CodeModel()
: _M_creation_id(0)
{
_M_globalNamespace = create<NamespaceModelItem>();
}
CodeModel::~CodeModel()
{
}
void CodeModel::wipeout()
{
_M_globalNamespace = create<NamespaceModelItem>();
_M_files.clear();
}
FileList CodeModel::files() const
{
return _M_files.values();
}
NamespaceModelItem CodeModel::globalNamespace() const
{
return _M_globalNamespace;
}
void CodeModel::addFile(FileModelItem item)
{
_M_creation_id = 0; // reset the creation id
_M_files.insert(item->name(), item);
}
void CodeModel::removeFile(FileModelItem item)
{
QHash<QString, FileModelItem>::Iterator it = _M_files.find(item->name());
if (it != _M_files.end() && it.value() == item)
_M_files.erase(it);
}
FileModelItem CodeModel::findFile(const QString &name) const
{
return _M_files.value(name);
}
QHash<QString, FileModelItem> CodeModel::fileMap() const
{
return _M_files;
}
CodeModelItem CodeModel::findItem(const QStringList &qualifiedName, CodeModelItem scope) const
{
for (int i=0; i<qualifiedName.size(); ++i) {
// ### Extend to look for members etc too.
const QString &name = qualifiedName.at(i);
if (NamespaceModelItem ns = model_dynamic_cast<NamespaceModelItem>(scope))
{
if (NamespaceModelItem tmp_ns = ns->findNamespace(name)) {
scope = tmp_ns;
continue;
}
}
if (ScopeModelItem ss = model_dynamic_cast<ScopeModelItem>(scope))
{
if (ClassModelItem cs = ss->findClass(name))
{
scope = cs;
}
else if (EnumModelItem es = ss->findEnum(name))
{
if (i == qualifiedName.size () - 1)
return es->toItem();
}
else if (TypeAliasModelItem tp = ss->findTypeAlias(name))
{
if (i == qualifiedName.size () - 1)
return tp->toItem ();
}
else
{
// If we don't find the name in the scope chain we
// need to return an empty item to indicate failure...
return CodeModelItem();
}
}
}
return scope;
}
// ---------------------------------------------------------------------------
TypeInfo TypeInfo::combine (const TypeInfo &__lhs, const TypeInfo &__rhs)
{
TypeInfo __result = __lhs;
__result.setConstant (__result.isConstant () || __rhs.isConstant ());
__result.setVolatile (__result.isVolatile () || __rhs.isVolatile ());
__result.setReference (__result.isReference () || __rhs.isReference ());
__result.setRvalueReference (__result.isRvalueReference () || __rhs.isRvalueReference ());
__result.setIndirections (__result.indirections () + __rhs.indirections ());
__result.setArrayElements (__result.arrayElements () + __rhs.arrayElements ());
return __result;
}
TypeInfo TypeInfo::resolveType (TypeInfo const &__type, CodeModelItem __scope)
{
CodeModel *__model = __scope->model ();
Q_ASSERT (__model != 0);
CodeModelItem __item = __model->findItem (__type.qualifiedName (), __scope);
// Copy the type and replace with the proper qualified name. This
// only makes sence to do if we're actually getting a resolved
// type with a namespace. We only get this if the returned type
// has more than 2 entries in the qualified name... This test
// could be improved by returning if the type was found or not.
TypeInfo otherType(__type);
if (__item && __item->qualifiedName().size() > 1) {
otherType.setQualifiedName(__item->qualifiedName());
}
if (TypeAliasModelItem __alias = model_dynamic_cast<TypeAliasModelItem> (__item))
return resolveType (TypeInfo::combine (__alias->type (), otherType), __scope);
return otherType;
}
QString TypeInfo::toString() const
{
QString tmp;
tmp += m_qualifiedName.join("::");
if (isConstant())
tmp += QLatin1String(" const");
if (isVolatile())
tmp += QLatin1String(" volatile");
if (indirections())
tmp += QString(indirections(), QLatin1Char('*'));
if (isRvalueReference())
tmp += QLatin1String("&&");
else if (isReference())
tmp += QLatin1Char('&');
if (isFunctionPointer())
{
tmp += QLatin1String(" (*)(");
for (int i=0; i<m_arguments.count(); ++i)
{
if (i != 0)
tmp += QLatin1String(", ");
tmp += m_arguments.at(i).toString();
}
tmp += QLatin1String(")");
}
foreach (QString elt, arrayElements ())
{
tmp += QLatin1String ("[");
tmp += elt;
tmp += QLatin1String ("]");
}
return tmp;
}
bool TypeInfo::operator==(const TypeInfo &other)
{
if (arrayElements().count() != other.arrayElements().count())
return false;
#if defined (RXX_CHECK_ARRAY_ELEMENTS) // ### it'll break
for (int i=0; i<arrayElements().count(); ++i)
{
QString elt1 = arrayElements ().at (i).trimmed ();
QString elt2 = other.arrayElements ().at (i).trimmed ();
if (elt1 != elt2)
return false;
}
#endif
return flags == other.flags
&& m_qualifiedName == other.m_qualifiedName
&& (!m_functionPointer || m_arguments == other.m_arguments);
}
// ---------------------------------------------------------------------------
_CodeModelItem::_CodeModelItem(CodeModel *model, int kind)
: _M_model(model),
_M_kind(kind),
_M_startLine(0),
_M_startColumn(0),
_M_endLine(0),
_M_endColumn(0),
_M_creation_id(0)
{
}
_CodeModelItem::~_CodeModelItem()
{
}
CodeModelItem _CodeModelItem::toItem() const
{
return CodeModelItem(const_cast<_CodeModelItem*>(this));
}
int _CodeModelItem::kind() const
{
return _M_kind;
}
void _CodeModelItem::setKind(int kind)
{
_M_kind = kind;
}
QStringList _CodeModelItem::qualifiedName() const
{
QStringList q = scope();
if (!name().isEmpty())
q += name();
return q;
}
QString _CodeModelItem::name() const
{
return _M_name;
}
void _CodeModelItem::setName(const QString &name)
{
_M_name = name;
}
QStringList _CodeModelItem::scope() const
{
return _M_scope;
}
void _CodeModelItem::setScope(const QStringList &scope)
{
_M_scope = scope;
}
QString _CodeModelItem::fileName() const
{
return _M_fileName;
}
void _CodeModelItem::setFileName(const QString &fileName)
{
_M_fileName = fileName;
}
FileModelItem _CodeModelItem::file() const
{
return model()->findFile(fileName());
}
void _CodeModelItem::getStartPosition(int *line, int *column) const
{
*line = _M_startLine;
*column = _M_startColumn;
}
void _CodeModelItem::setStartPosition(int line, int column)
{
_M_startLine = line;
_M_startColumn = column;
}
void _CodeModelItem::getEndPosition(int *line, int *column) const
{
*line = _M_endLine;
*column = _M_endColumn;
}
void _CodeModelItem::setEndPosition(int line, int column)
{
_M_endLine = line;
_M_endColumn = column;
}
// ---------------------------------------------------------------------------
QStringList _ClassModelItem::baseClasses() const
{
return _M_baseClasses;
}
void _ClassModelItem::setBaseClasses(const QStringList &baseClasses)
{
_M_baseClasses = baseClasses;
}
TemplateParameterList _ClassModelItem::templateParameters() const
{
return _M_templateParameters;
}
void _ClassModelItem::setTemplateParameters(const TemplateParameterList &templateParameters)
{
_M_templateParameters = templateParameters;
}
void _ClassModelItem::addBaseClass(const QString &baseClass)
{
_M_baseClasses.append(baseClass);
}
void _ClassModelItem::removeBaseClass(const QString &baseClass)
{
_M_baseClasses.removeAt(_M_baseClasses.indexOf(baseClass));
}
bool _ClassModelItem::extendsClass(const QString &name) const
{
return _M_baseClasses.contains(name);
}
void _ClassModelItem::setClassType(CodeModel::ClassType type)
{
_M_classType = type;
}
CodeModel::ClassType _ClassModelItem::classType() const
{
return _M_classType;
}
void _ClassModelItem::addPropertyDeclaration(const QString &propertyDeclaration)
{
_M_propertyDeclarations << propertyDeclaration;
}
// ---------------------------------------------------------------------------
FunctionModelItem _ScopeModelItem::declaredFunction(FunctionModelItem item)
{
FunctionList function_list = findFunctions(item->name());
foreach (FunctionModelItem fun, function_list)
{
if (fun->isSimilar(item))
return fun;
}
return FunctionModelItem();
}
ClassList _ScopeModelItem::classes() const
{
return _M_classes.values();
}
TypeAliasList _ScopeModelItem::typeAliases() const
{
return _M_typeAliases.values();
}
VariableList _ScopeModelItem::variables() const
{
return _M_variables.values();
}
FunctionList _ScopeModelItem::functions() const
{
return _M_functions.values();
}
void _ScopeModelItem::addEnumsDeclaration(const QString &enumsDeclaration)
{
_M_enumsDeclarations << enumsDeclaration;
}
FunctionDefinitionList _ScopeModelItem::functionDefinitions() const
{
return _M_functionDefinitions.values();
}
EnumList _ScopeModelItem::enums() const
{
return _M_enums.values();
}
void _ScopeModelItem::addClass(ClassModelItem item)
{
QString name = item->name();
int idx = name.indexOf("<");
if (idx > 0)
_M_classes.insert(name.left(idx), item);
_M_classes.insert(name, item);
}
void _ScopeModelItem::addFunction(FunctionModelItem item)
{
_M_functions.insert(item->name(), item);
}
void _ScopeModelItem::addFunctionDefinition(FunctionDefinitionModelItem item)
{
_M_functionDefinitions.insert(item->name(), item);
}
void _ScopeModelItem::addVariable(VariableModelItem item)
{
_M_variables.insert(item->name(), item);
}
void _ScopeModelItem::addTypeAlias(TypeAliasModelItem item)
{
_M_typeAliases.insert(item->name(), item);
}
void _ScopeModelItem::addEnum(EnumModelItem item)
{
_M_enums.insert(item->name(), item);
}
void _ScopeModelItem::removeClass(ClassModelItem item)
{
QHash<QString, ClassModelItem>::Iterator it = _M_classes.find(item->name());
if (it != _M_classes.end() && it.value() == item)
_M_classes.erase(it);
}
void _ScopeModelItem::removeFunction(FunctionModelItem item)
{
QMultiHash<QString, FunctionModelItem>::Iterator it = _M_functions.find(item->name());
while (it != _M_functions.end() && it.key() == item->name()
&& it.value() != item)
{
++it;
}
if (it != _M_functions.end() && it.value() == item)
{
_M_functions.erase(it);
}
}
void _ScopeModelItem::removeFunctionDefinition(FunctionDefinitionModelItem item)
{
QMultiHash<QString, FunctionDefinitionModelItem>::Iterator it = _M_functionDefinitions.find(item->name());
while (it != _M_functionDefinitions.end() && it.key() == item->name()
&& it.value() != item)
{
++it;
}
if (it != _M_functionDefinitions.end() && it.value() == item)
{
_M_functionDefinitions.erase(it);
}
}
void _ScopeModelItem::removeVariable(VariableModelItem item)
{
QHash<QString, VariableModelItem>::Iterator it = _M_variables.find(item->name());
if (it != _M_variables.end() && it.value() == item)
_M_variables.erase(it);
}
void _ScopeModelItem::removeTypeAlias(TypeAliasModelItem item)
{
QHash<QString, TypeAliasModelItem>::Iterator it = _M_typeAliases.find(item->name());
if (it != _M_typeAliases.end() && it.value() == item)
_M_typeAliases.erase(it);
}
void _ScopeModelItem::removeEnum(EnumModelItem item)
{
QHash<QString, EnumModelItem>::Iterator it = _M_enums.find(item->name());
if (it != _M_enums.end() && it.value() == item)
_M_enums.erase(it);
}
ClassModelItem _ScopeModelItem::findClass(const QString &name) const
{
return _M_classes.value(name);
}
VariableModelItem _ScopeModelItem::findVariable(const QString &name) const
{
return _M_variables.value(name);
}
TypeAliasModelItem _ScopeModelItem::findTypeAlias(const QString &name) const
{
return _M_typeAliases.value(name);
}
EnumModelItem _ScopeModelItem::findEnum(const QString &name) const
{
return _M_enums.value(name);
}
FunctionList _ScopeModelItem::findFunctions(const QString &name) const
{
return _M_functions.values(name);
}
FunctionDefinitionList _ScopeModelItem::findFunctionDefinitions(const QString &name) const
{
return _M_functionDefinitions.values(name);
}
// ---------------------------------------------------------------------------
NamespaceList _NamespaceModelItem::namespaces() const
{
return _M_namespaces.values();
}
void _NamespaceModelItem::addNamespace(NamespaceModelItem item)
{
_M_namespaces.insert(item->name(), item);
}
void _NamespaceModelItem::removeNamespace(NamespaceModelItem item)
{
QHash<QString, NamespaceModelItem>::Iterator it = _M_namespaces.find(item->name());
if (it != _M_namespaces.end() && it.value() == item)
_M_namespaces.erase(it);
}
NamespaceModelItem _NamespaceModelItem::findNamespace(const QString &name) const
{
return _M_namespaces.value(name);
}
// ---------------------------------------------------------------------------
TypeInfo _ArgumentModelItem::type() const
{
return _M_type;
}
void _ArgumentModelItem::setType(const TypeInfo &type)
{
_M_type = type;
}
bool _ArgumentModelItem::defaultValue() const
{
return _M_defaultValue;
}
void _ArgumentModelItem::setDefaultValue(bool defaultValue)
{
_M_defaultValue = defaultValue;
}
// ---------------------------------------------------------------------------
bool _FunctionModelItem::isSimilar(FunctionModelItem other) const
{
if (name() != other->name())
return false;
if (isConstant() != other->isConstant())
return false;
if (isVariadics() != other->isVariadics())
return false;
if (arguments().count() != other->arguments().count())
return false;
// ### check the template parameters
for (int i=0; i<arguments().count(); ++i)
{
ArgumentModelItem arg1 = arguments().at(i);
ArgumentModelItem arg2 = other->arguments().at(i);
if (arg1->type() != arg2->type())
return false;
}
return true;
}
ArgumentList _FunctionModelItem::arguments() const
{
return _M_arguments;
}
void _FunctionModelItem::addArgument(ArgumentModelItem item)
{
_M_arguments.append(item);
}
void _FunctionModelItem::removeArgument(ArgumentModelItem item)
{
_M_arguments.removeAt(_M_arguments.indexOf(item));
}
CodeModel::FunctionType _FunctionModelItem::functionType() const
{
return _M_functionType;
}
void _FunctionModelItem::setFunctionType(CodeModel::FunctionType functionType)
{
_M_functionType = functionType;
}
QString _FunctionModelItem::exception() const
{
return _M_exception;
}
void _FunctionModelItem::setException(const QString &exception)
{
_M_exception = exception;
}
bool _FunctionModelItem::isVariadics() const
{
return _M_isVariadics;
}
void _FunctionModelItem::setVariadics(bool isVariadics)
{
_M_isVariadics = isVariadics;
}
bool _FunctionModelItem::isVirtual() const
{
return _M_isVirtual;
}
void _FunctionModelItem::setVirtual(bool isVirtual)
{
_M_isVirtual = isVirtual;
}
bool _FunctionModelItem::isInline() const
{
return _M_isInline;
}
void _FunctionModelItem::setInline(bool isInline)
{
_M_isInline = isInline;
}
bool _FunctionModelItem::isExplicit() const
{
return _M_isExplicit;
}
void _FunctionModelItem::setExplicit(bool isExplicit)
{
_M_isExplicit = isExplicit;
}
bool _FunctionModelItem::isAbstract() const
{
return _M_isAbstract;
}
void _FunctionModelItem::setAbstract(bool isAbstract)
{
_M_isAbstract = isAbstract;
}
// Qt
bool _FunctionModelItem::isInvokable() const
{
return _M_isInvokable;
}
void _FunctionModelItem::setInvokable(bool isInvokable)
{
_M_isInvokable = isInvokable;
}
// ---------------------------------------------------------------------------
TypeInfo _TypeAliasModelItem::type() const
{
return _M_type;
}
void _TypeAliasModelItem::setType(const TypeInfo &type)
{
_M_type = type;
}
// ---------------------------------------------------------------------------
CodeModel::AccessPolicy _EnumModelItem::accessPolicy() const
{
return _M_accessPolicy;
}
void _EnumModelItem::setAccessPolicy(CodeModel::AccessPolicy accessPolicy)
{
_M_accessPolicy = accessPolicy;
}
EnumeratorList _EnumModelItem::enumerators() const
{
return _M_enumerators;
}
void _EnumModelItem::addEnumerator(EnumeratorModelItem item)
{
_M_enumerators.append(item);
}
void _EnumModelItem::removeEnumerator(EnumeratorModelItem item)
{
_M_enumerators.removeAt(_M_enumerators.indexOf(item));
}
// ---------------------------------------------------------------------------
QString _EnumeratorModelItem::value() const
{
return _M_value;
}
void _EnumeratorModelItem::setValue(const QString &value)
{
_M_value = value;
}
// ---------------------------------------------------------------------------
TypeInfo _TemplateParameterModelItem::type() const
{
return _M_type;
}
void _TemplateParameterModelItem::setType(const TypeInfo &type)
{
_M_type = type;
}
bool _TemplateParameterModelItem::defaultValue() const
{
return _M_defaultValue;
}
void _TemplateParameterModelItem::setDefaultValue(bool defaultValue)
{
_M_defaultValue = defaultValue;
}
// ---------------------------------------------------------------------------
ScopeModelItem _ScopeModelItem::create(CodeModel *model)
{
ScopeModelItem item(new _ScopeModelItem(model));
return item;
}
ClassModelItem _ClassModelItem::create(CodeModel *model)
{
ClassModelItem item(new _ClassModelItem(model));
return item;
}
NamespaceModelItem _NamespaceModelItem::create(CodeModel *model)
{
NamespaceModelItem item(new _NamespaceModelItem(model));
return item;
}
FileModelItem _FileModelItem::create(CodeModel *model)
{
FileModelItem item(new _FileModelItem(model));
return item;
}
ArgumentModelItem _ArgumentModelItem::create(CodeModel *model)
{
ArgumentModelItem item(new _ArgumentModelItem(model));
return item;
}
FunctionModelItem _FunctionModelItem::create(CodeModel *model)
{
FunctionModelItem item(new _FunctionModelItem(model));
return item;
}
FunctionDefinitionModelItem _FunctionDefinitionModelItem::create(CodeModel *model)
{
FunctionDefinitionModelItem item(new _FunctionDefinitionModelItem(model));
return item;
}
VariableModelItem _VariableModelItem::create(CodeModel *model)
{
VariableModelItem item(new _VariableModelItem(model));
return item;
}
TypeAliasModelItem _TypeAliasModelItem::create(CodeModel *model)
{
TypeAliasModelItem item(new _TypeAliasModelItem(model));
return item;
}
EnumModelItem _EnumModelItem::create(CodeModel *model)
{
EnumModelItem item(new _EnumModelItem(model));
return item;
}
EnumeratorModelItem _EnumeratorModelItem::create(CodeModel *model)
{
EnumeratorModelItem item(new _EnumeratorModelItem(model));
return item;
}
TemplateParameterModelItem _TemplateParameterModelItem::create(CodeModel *model)
{
TemplateParameterModelItem item(new _TemplateParameterModelItem(model));
return item;
}
// ---------------------------------------------------------------------------
TypeInfo _MemberModelItem::type() const
{
return _M_type;
}
void _MemberModelItem::setType(const TypeInfo &type)
{
_M_type = type;
}
CodeModel::AccessPolicy _MemberModelItem::accessPolicy() const
{
return _M_accessPolicy;
}
void _MemberModelItem::setAccessPolicy(CodeModel::AccessPolicy accessPolicy)
{
_M_accessPolicy = accessPolicy;
}
bool _MemberModelItem::isStatic() const
{
return _M_isStatic;
}
void _MemberModelItem::setStatic(bool isStatic)
{
_M_isStatic = isStatic;
}
bool _MemberModelItem::isConstant() const
{
return _M_isConstant;
}
void _MemberModelItem::setConstant(bool isConstant)
{
_M_isConstant = isConstant;
}
bool _MemberModelItem::isVolatile() const
{
return _M_isVolatile;
}
void _MemberModelItem::setVolatile(bool isVolatile)
{
_M_isVolatile = isVolatile;
}
bool _MemberModelItem::isAuto() const
{
return _M_isAuto;
}
void _MemberModelItem::setAuto(bool isAuto)
{
_M_isAuto = isAuto;
}
bool _MemberModelItem::isFriend() const
{
return _M_isFriend;
}
void _MemberModelItem::setFriend(bool isFriend)
{
_M_isFriend = isFriend;
}
bool _MemberModelItem::isRegister() const
{
return _M_isRegister;
}
void _MemberModelItem::setRegister(bool isRegister)
{
_M_isRegister = isRegister;
}
bool _MemberModelItem::isExtern() const
{
return _M_isExtern;
}
void _MemberModelItem::setExtern(bool isExtern)
{
_M_isExtern = isExtern;
}
bool _MemberModelItem::isMutable() const
{
return _M_isMutable;
}
void _MemberModelItem::setMutable(bool isMutable)
{
_M_isMutable = isMutable;
}
// kate: space-indent on; indent-width 2; replace-tabs on;
|
#include <ossim/elevation/ossimDtedElevationDatabase.h>
#include <ossim/base/ossimDirectory.h>
#include <ossim/base/ossimGeoidManager.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimPreferences.h>
#include <ossim/base/ossimTrace.h>
#include <sstream>
#include <iomanip>
#include <cstdlib> /* for abs(int) */
static ossimTrace traceDebug("ossimDtedElevationDatabase:debug");
RTTI_DEF1(ossimDtedElevationDatabase, "ossimDtedElevationDatabase", ossimElevationCellDatabase);
using namespace std;
ossimDtedElevationDatabase::ossimDtedElevationDatabase()
: ossimElevationCellDatabase(),
m_extension(""),
m_upcase(false),
m_lastHandler(0),
m_mutex()
{
}
ossimDtedElevationDatabase::ossimDtedElevationDatabase(const ossimDtedElevationDatabase& rhs)
: ossimElevationCellDatabase(rhs),
m_extension(rhs.m_extension),
m_upcase(rhs.m_upcase),
m_lastHandler(0), // Do not copy this to get a unique handler for thread.
m_mutex()
{
}
ossimDtedElevationDatabase::~ossimDtedElevationDatabase()
{
}
ossimObject* ossimDtedElevationDatabase::dup() const
{
ossimDtedElevationDatabase* duped = new ossimDtedElevationDatabase(*this);
return duped;
}
double ossimDtedElevationDatabase::getHeightAboveMSL(const ossimGpt& gpt)
{
if(!isSourceEnabled())
return ossim::nan();
std::lock_guard<std::mutex> lock(m_mutex);
double result = ossim::nan();
if(m_lastHandler.valid() && m_lastHandler->pointHasCoverage(gpt))
{
result = m_lastHandler->getHeightAboveMSL(gpt);
}
else
{
m_lastHandler = getOrCreateCellHandler(gpt);
if(m_lastHandler.valid())
result = m_lastHandler->getHeightAboveMSL(gpt);
}
return result;
}
double ossimDtedElevationDatabase::getHeightAboveEllipsoid(const ossimGpt& gpt)
{
double h = getHeightAboveMSL(gpt);
if(!ossim::isnan(h))
{
double offset = getOffsetFromEllipsoid(gpt);
h += offset;
}
return h;
}
bool ossimDtedElevationDatabase::open(const ossimString& connectionString)
{
bool result = false;
ossimFilename file = ossimFilename(connectionString);
result = openDtedDirectory(file);
return result;
}
bool ossimDtedElevationDatabase::openDtedDirectory(const ossimFilename& dir)
{
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimDtedElevationDatabase::open entered ...\n"
<< "dir: " << dir << "\n";
}
bool result = dir.isDir();
if(result)
{
if ( m_extension.size() == 0 )
{
//---
// This sets extension by doing a directory scan for files with "dt*".
// Use "extension" key in preferences to avoid this. Example:
// elevation_manager.elevation_source0.extension: dt2.
//---
result = inititializeExtension( dir );
if ( !result && traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimDtedElevationDatabase::open: WARNING "
<< "Scan for dted extension failed!\n"
<< "Can be set in ossim preferences. Example:\n"
<< "elevation_manager.elevation_source0.extension: .dt2\n";
}
}
// Set the geoid:
if( !m_geoid.valid() )
{
m_geoid = ossimGeoidManager::instance()->findGeoidByShortName("geoid1996", false);
if(!m_geoid.valid()&&traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimDtedElevationDatabase::open: WARNING "
<< "Unable to load goeid grid 1996 for DTED database\n";
}
}
}
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimDtedElevationDatabase::open result:" << (result?"true":"false") << "\n";
}
return result;
}
bool ossimDtedElevationDatabase::getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const
{
bool result = false;
m_mutex.lock();
ossimDtedElevationDatabase* thisPtr = const_cast<ossimDtedElevationDatabase*>(this);
ossimRefPtr<ossimElevCellHandler> tempHandler = thisPtr->getOrCreateCellHandler(gpt);
m_mutex.unlock();
if(tempHandler.valid())
{
result = tempHandler->getAccuracyInfo(info, gpt);
}
return result;
}
void ossimDtedElevationDatabase::createRelativePath(ossimFilename& file, const ossimGpt& gpt)const
{
ossimFilename lon, lat;
int ilon = static_cast<int>(floor(gpt.lond()));
if (ilon < 0)
{
lon = m_upcase?"W":"w";
}
else
{
lon = m_upcase?"E":"e";
}
ilon = abs(ilon);
std::ostringstream s1;
s1 << std::setfill('0') << std::setw(3)<< ilon;
lon += s1.str().c_str();//ossimString::toString(ilon);
int ilat = static_cast<int>(floor(gpt.latd()));
if (ilat < 0)
{
lat += m_upcase?"S":"s";
}
else
{
lat += m_upcase?"N":"n";
}
ilat = abs(ilat);
std::ostringstream s2;
s2<< std::setfill('0') << std::setw(2)<< ilat;
lat += s2.str().c_str();
file = lon.dirCat(lat+m_extension);
}
ossimRefPtr<ossimElevCellHandler> ossimDtedElevationDatabase::createCell(const ossimGpt& gpt)
{
ossimRefPtr<ossimElevCellHandler> result = 0;
ossimFilename f;
createFullPath(f, gpt);
if(f.exists())
{
ossimRefPtr<ossimDtedHandler> h = new ossimDtedHandler(f, m_memoryMapCellsFlag);
if (!(h->getErrorStatus()))
{
result = h.get();
}
}
return result;
}
bool ossimDtedElevationDatabase::loadState(const ossimKeywordlist& kwl, const char* prefix )
{
bool result = ossimElevationCellDatabase::loadState(kwl, prefix);
if(result)
{
if(!m_connectionString.empty()&&ossimFilename(m_connectionString).exists())
{
// Look for "extension" keyword.
std::string pref = (prefix?prefix:"");
std::string key = "extension";
ossimString val = ossimPreferences::instance()->preferencesKWL().findKey( pref, key );
if ( val.size() )
{
if ( val.string()[0] != '.' )
{
m_extension = ".";
m_extension += val;
ossimNotify(ossimNotifyLevel_WARN)
<< "\nossimDtedElevationDatabase::loadState: WARNING\n"
<< "Key value for \"extension\" does not start with a dot!\n"
<< "Consider changing \"" << val << "\" to \"" << m_extension << "\"\n"
<< std::endl;
}
else
{
m_extension = val;
}
}
else if ( traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "\nossimDtedElevationDatabase::loadState: NOTICE\n"
<< "Key lookup for \"extension\" failed!\n"
<< "Can be set in ossim preferences. Example:\n"
<< pref << key << ": .dt2\n\n";
}
key = "upcase";
val = ossimPreferences::instance()->preferencesKWL().findKey( pref, key );
if ( val.size() )
{
m_upcase = val.toBool();
}
else if ( traceDebug() )
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "\nossimDtedElevationDatabase::loadState: NOTICE\n"
<< "Key lookup for \"upcase\" failed!\n"
<< "Can be set in ossim preferences. Example:\n"
<< pref << key << ": false\n\n";
}
result = open(m_connectionString);
}
else
{
// can't open the connection because it does not exists or empty
result = false;
}
}
return result;
}
bool ossimDtedElevationDatabase::saveState(ossimKeywordlist& kwl, const char* prefix)const
{
kwl.add(prefix, "extension", m_extension, true);
kwl.add(prefix, "upcase", m_upcase, true);
bool result = ossimElevationCellDatabase::saveState(kwl, prefix);
return result;
}
std::ostream& ossimDtedElevationDatabase::print(ostream& out) const
{
ossimKeywordlist kwl;
saveState(kwl);
out << "\nossimDtedElevationDatabase @ "<< (ossim_uint64) this << "\n"
<< kwl <<ends;
return out;
}
bool ossimDtedElevationDatabase::inititializeExtension( const ossimFilename& dir )
{
ossim_uint32 count = 0;
ossim_uint32 maxCount = 10;
ossimDirectory od;
bool result = od.open(dir);
if(result)
{
result = false;
ossimFilename f;
// Get the first directory.
od.getFirst(f, ossimDirectory::OSSIM_DIR_DIRS);
do
{
++count;
// Must be a directory.
if (f.isDir())
{
// Discard any full path.
ossimFilename fileOnly = f.file();
// Downcase it. Note have sites with upper case. (drb)
// fileOnly.downcase();
//---
// Longitude subdir check:
// Must start with 'e', 'E', 'w' or 'W'.
//---
bool foundCell = ( ( (fileOnly.c_str()[0] == 'e') ||
(fileOnly.c_str()[0] == 'w') ||
(fileOnly.c_str()[0] == 'E') ||
(fileOnly.c_str()[0] == 'W') ) &&
(fileOnly.size() == 4));
if(foundCell)
{
ossim_uint32 maxCount2 = 10;
ossim_uint32 count2 = 0;
ossimDirectory d2;
// Open the longitude subdir:
if(d2.open(f))
{
d2.getFirst(f, ossimDirectory::OSSIM_DIR_FILES);
do
{
// The DTED directory may be polluted with cell statistics files and other
// non-DEM items. Skip if not of the expected extension (OLK 10/2017):
if (f.ext().match("[dD][tT][0-9]").empty())
continue;
ossimRefPtr<ossimDtedHandler> dtedHandler = new ossimDtedHandler();
if(dtedHandler->open(f, false))
{
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimDtedElevationDatabase::open: Found dted file " << f << "\n";
}
result = true;
m_extension = "."+f.ext();
m_connectionString = dir;
m_meanSpacing = dtedHandler->getMeanSpacingMeters();
}
dtedHandler->close();
dtedHandler = 0;
++count2;
} while(!result&&d2.getNext(f)&&(count2 < maxCount2));
}
}
}
} while(!result&&(od.getNext(f))&&(count < maxCount));
}
return result;
} // End: ossimDtedElevationDatabase::inititializeExtension( dir )
|
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE Main
#else
#ifndef _WIN32
# define BOOST_TEST_MODULE ParserIfTests
#endif
#endif
#include "toslang_parser_fixture.h"
BOOST_FIXTURE_TEST_SUITE( ParseTestSuite, TosLangParserFixture )
//////////////////// CORRECT USE CASES ////////////////////
BOOST_AUTO_TEST_CASE( ParseIfLiteralCondTest )
{
auto& cNodes = GetProgramAST("../sources/if/if_literal_cond.tos");
BOOST_REQUIRE_EQUAL(cNodes.size(), 1);
BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::FUNCTION_DECL);
const FunctionDecl* fDecl = static_cast<const FunctionDecl*>(cNodes[0].get());
BOOST_REQUIRE(fDecl != nullptr);
const CompoundStmt* body = fDecl->GetBody();
BOOST_REQUIRE(body != nullptr);
auto& bStmts = body->GetStatements();
BOOST_REQUIRE_EQUAL(bStmts.size(), 2);
BOOST_REQUIRE(bStmts[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);
const VarDecl* vDecl = static_cast<const VarDecl*>(bStmts[0].get());
BOOST_REQUIRE(vDecl != nullptr);
BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), "BoolVar");
BOOST_REQUIRE(bStmts[1]->GetKind() == ASTNode::NodeKind::IF_STMT);
const IfStmt* iStmt = static_cast<const IfStmt*>(bStmts[1].get());
BOOST_REQUIRE(iStmt != nullptr);
const Expr* cExpr = iStmt->GetCondExpr();
BOOST_REQUIRE(cExpr != nullptr);
BOOST_REQUIRE(cExpr->GetKind() == ASTNode::NodeKind::BOOLEAN_EXPR);
const BooleanExpr* bExpr = static_cast<const BooleanExpr*>(cExpr);
BOOST_REQUIRE_EQUAL(bExpr->GetValue(), true);
const CompoundStmt* iBody = iStmt->GetBody();
BOOST_REQUIRE(iBody != nullptr);
auto& bodyStmts = iBody->GetStatements();
BOOST_REQUIRE_EQUAL(bodyStmts.size(), 1);
}
BOOST_AUTO_TEST_CASE( ParseIfSimpleCondTest )
{
auto& cNodes = GetProgramAST("../sources/if/if_simple_cond.tos");
BOOST_REQUIRE_EQUAL(cNodes.size(), 1);
BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::FUNCTION_DECL);
const FunctionDecl* fDecl = static_cast<const FunctionDecl*>(cNodes[0].get());
BOOST_REQUIRE(fDecl != nullptr);
const CompoundStmt* body = fDecl->GetBody();
BOOST_REQUIRE(body != nullptr);
auto& bStmts = body->GetStatements();
BOOST_REQUIRE_EQUAL(bStmts.size(), 2);
BOOST_REQUIRE(bStmts[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);
const VarDecl* vDecl = static_cast<const VarDecl*>(bStmts[0].get());
BOOST_REQUIRE(vDecl != nullptr);
BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), "BoolVar");
BOOST_REQUIRE(bStmts[1]->GetKind() == ASTNode::NodeKind::IF_STMT);
const IfStmt* iStmt = static_cast<const IfStmt*>(bStmts[1].get());
BOOST_REQUIRE(iStmt != nullptr);
const Expr* cExpr = iStmt->GetCondExpr();
BOOST_REQUIRE(cExpr != nullptr);
BOOST_REQUIRE(cExpr->GetKind() == ASTNode::NodeKind::IDENTIFIER_EXPR);
const IdentifierExpr* iExpr = static_cast<const IdentifierExpr*>(cExpr);
BOOST_REQUIRE_EQUAL(iExpr->GetName(), "BoolVar");
const CompoundStmt* iBody = iStmt->GetBody();
BOOST_REQUIRE(iBody != nullptr);
auto& bodyStmts = iBody->GetStatements();
BOOST_REQUIRE_EQUAL(bodyStmts.size(), 1);
}
BOOST_AUTO_TEST_CASE( ParseIfMultiCondTest )
{
auto& cNodes = GetProgramAST("../sources/if/if_bin_bool_cond.tos");
BOOST_REQUIRE_EQUAL(cNodes.size(), 1);
BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::FUNCTION_DECL);
const FunctionDecl* fDecl = static_cast<const FunctionDecl*>(cNodes[0].get());
BOOST_REQUIRE(fDecl != nullptr);
const CompoundStmt* body = fDecl->GetBody();
BOOST_REQUIRE(body != nullptr);
auto& bStmts = body->GetStatements();
BOOST_REQUIRE_EQUAL(bStmts.size(), 2);
BOOST_REQUIRE(bStmts[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);
const VarDecl* vDecl = static_cast<const VarDecl*>(bStmts[0].get());
BOOST_REQUIRE(vDecl != nullptr);
BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), "BoolVar");
BOOST_REQUIRE(bStmts[1]->GetKind() == ASTNode::NodeKind::IF_STMT);
const IfStmt* iStmt = static_cast<const IfStmt*>(bStmts[1].get());
BOOST_REQUIRE(iStmt != nullptr);
const Expr* cExpr = iStmt->GetCondExpr();
BOOST_REQUIRE(cExpr != nullptr);
BOOST_REQUIRE(cExpr->GetKind() == ASTNode::NodeKind::BINARY_EXPR);
const BinaryOpExpr* bExpr = static_cast<const BinaryOpExpr*>(cExpr);
BOOST_REQUIRE(bExpr != nullptr);
const CompoundStmt* iBody = iStmt->GetBody();
BOOST_REQUIRE(iBody != nullptr);
auto& bodyStmts = iBody->GetStatements();
BOOST_REQUIRE_EQUAL(bodyStmts.size(), 1);
}
//////////////////// ERROR USE CASES ////////////////////
BOOST_AUTO_TEST_CASE( ParseBadIfNoCondTest )
{
auto& cNodes = GetProgramAST("../sources/if/if_no_cond.tos");
BOOST_REQUIRE_EQUAL(cNodes.size(), 1);
BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::FUNCTION_DECL);
const FunctionDecl* fDecl = static_cast<const FunctionDecl*>(cNodes[0].get());
BOOST_REQUIRE(fDecl != nullptr);
const CompoundStmt* body = fDecl->GetBody();
BOOST_REQUIRE(body != nullptr);
auto& bStmts = body->GetStatements();
BOOST_REQUIRE_EQUAL(bStmts.size(), 3);
// Check that we only have one error statement
BOOST_REQUIRE_EQUAL(std::count_if(bStmts.begin(), bStmts.end(), [](const std::unique_ptr<ASTNode>& node) { return node->GetKind() == ASTNode::NodeKind::ERROR; }), 1);
// Check if the correct error messages got printed
std::vector<std::string> messages{ GetErrorMessages() };
BOOST_REQUIRE_EQUAL(messages.size(), 4); // TODO: We might need to introduce a ParenExpr...
//BOOST_REQUIRE_EQUAL(messages[0], "IF ERROR: Missing if condition at line 6, column 2");
}
BOOST_AUTO_TEST_CASE( ParseBadIfNoBodyTest )
{
auto& cNodes = GetProgramAST("../sources/if/if_no_body.tos");
BOOST_REQUIRE_EQUAL(cNodes.size(), 1);
BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::FUNCTION_DECL);
const FunctionDecl* fDecl = static_cast<const FunctionDecl*>(cNodes[0].get());
BOOST_REQUIRE(fDecl != nullptr);
const CompoundStmt* body = fDecl->GetBody();
BOOST_REQUIRE(body != nullptr);
auto& bStmts = body->GetStatements();
BOOST_REQUIRE_EQUAL(bStmts.size(), 2);
// Check that we only have one error statement
BOOST_REQUIRE_EQUAL(std::count_if(bStmts.begin(), bStmts.end(), [](const std::unique_ptr<ASTNode>& node) { return node->GetKind() == ASTNode::NodeKind::ERROR; }), 1);
// Check if the correct error messages got printed
std::vector<std::string> messages{ GetErrorMessages() };
BOOST_REQUIRE_EQUAL(messages.size(), 3);
BOOST_REQUIRE_EQUAL(messages[0], "SYNTAX ERROR: Expected '{' at line 5, column 1");
BOOST_REQUIRE_EQUAL(messages[1], "IF ERROR: Missing if body at line 5, column 1");
BOOST_REQUIRE_EQUAL(messages[2], "SYNTAX ERROR: Expected '}' at line 5, column 1");
}
BOOST_AUTO_TEST_CASE( ParseBadIfGlobalScopeTest )
{
auto& cNodes = GetProgramAST("../sources/if/if_global_scope.tos");
BOOST_REQUIRE_EQUAL(cNodes.size(), 1);
BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::ERROR);
// Check if the correct error message got printed
std::vector<std::string> messages{ GetErrorMessages() };
BOOST_REQUIRE_EQUAL(messages.size(), 1);
BOOST_REQUIRE_EQUAL(messages[0], "ERROR: Expected a declaration at line 1, column 2");
}
BOOST_AUTO_TEST_SUITE_END()
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:20 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: UnityEngine.Analytics.DataPrivacy
#include "UnityEngine/Analytics/DataPrivacy.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: UnityEngine.Analytics
namespace UnityEngine::Analytics {
// Autogenerated type: UnityEngine.Analytics.DataPrivacy/UserPostData
struct DataPrivacy::UserPostData : public System::ValueType {
public:
// public System.String appid
// Offset: 0x0
::Il2CppString* appid;
// public System.String userid
// Offset: 0x8
::Il2CppString* userid;
// public System.Int64 sessionid
// Offset: 0x10
int64_t sessionid;
// public System.String platform
// Offset: 0x18
::Il2CppString* platform;
// public System.UInt32 platformid
// Offset: 0x20
uint platformid;
// public System.String sdk_ver
// Offset: 0x28
::Il2CppString* sdk_ver;
// public System.Boolean debug_device
// Offset: 0x30
bool debug_device;
// public System.String deviceid
// Offset: 0x38
::Il2CppString* deviceid;
// public System.String plugin_ver
// Offset: 0x40
::Il2CppString* plugin_ver;
// Creating value type constructor for type: UserPostData
UserPostData(::Il2CppString* appid_ = {}, ::Il2CppString* userid_ = {}, int64_t sessionid_ = {}, ::Il2CppString* platform_ = {}, uint platformid_ = {}, ::Il2CppString* sdk_ver_ = {}, bool debug_device_ = {}, ::Il2CppString* deviceid_ = {}, ::Il2CppString* plugin_ver_ = {}) : appid{appid_}, userid{userid_}, sessionid{sessionid_}, platform{platform_}, platformid{platformid_}, sdk_ver{sdk_ver_}, debug_device{debug_device_}, deviceid{deviceid_}, plugin_ver{plugin_ver_} {}
}; // UnityEngine.Analytics.DataPrivacy/UserPostData
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Analytics::DataPrivacy::UserPostData, "UnityEngine.Analytics", "DataPrivacy/UserPostData");
#pragma pack(pop)
|
//===- DataBlock.hpp --------------------------------------------*- C++ -*-===//
//
// Copyright (C) 2020 GrammaTech, Inc.
//
// This code is licensed under the MIT license. See the LICENSE file in the
// project root for license terms.
//
// This project is sponsored by the Office of Naval Research, One Liberty
// Center, 875 N. Randolph Street, Arlington, VA 22203 under contract #
// N68335-17-C-0700. The content of the information does not necessarily
// reflect the position or policy of the Government and no official
// endorsement should be inferred.
//
//===----------------------------------------------------------------------===//
#ifndef GTIRB_DataBlock_H
#define GTIRB_DataBlock_H
#include <gtirb/Addr.hpp>
#include <gtirb/ByteInterval.hpp>
#include <gtirb/Node.hpp>
#include <cstdint>
#include <functional>
#include <optional>
#include <vector>
/// \file DataBlock.hpp
/// \brief Class gtirb::DataBlock.
namespace gtirb {
namespace proto {
class DataBlock;
}
///
/// \class DataBlock
///
/// \brief Represents a data object, possibly symbolic.
///
/// Does not directly store the data bytes, which are kept in the
/// \ref ImageByteMap.
///
class GTIRB_EXPORT_API DataBlock : public Node {
DataBlock(Context& C) : Node(C, Kind::DataBlock) {}
DataBlock(Context& C, uint64_t S, const UUID& U)
: Node(C, Kind::DataBlock, U), Size(S) {}
DataBlock(Context& C, uint64_t S) : Node(C, Kind::DataBlock), Size(S) {}
static DataBlock* Create(Context& C, uint64_t S, const UUID& U) {
return C.Create<DataBlock>(C, S, U);
}
public:
/// \brief Create an unitialized DataBlock object.
/// \param C The Context in which this DataBlock will be held.
/// \return The newly created DataBlock.
static DataBlock* Create(Context& C) { return C.Create<DataBlock>(C); }
/// \brief Create a DataBlock object.
///
/// \param C The Context in which the newly-created DataBlock will be
/// \param Size The size of the object in bytes.
/// \return The newly created DataBlock.
static DataBlock* Create(Context& C, uint64_t Size) {
return C.Create<DataBlock>(C, Size);
}
/// \brief Get the \ref ByteInterval this block belongs to.
ByteInterval* getByteInterval() { return Parent; }
/// \brief Get the \ref ByteInterval this block belongs to.
const ByteInterval* getByteInterval() const { return Parent; }
/// \brief Get the size of a DataBlock.
///
/// \return The size.
///
uint64_t getSize() const { return Size; }
/// \brief Get the offset from the beginning of the \ref ByteInterval this
/// block belongs to.
uint64_t getOffset() const;
/// \brief Get the address of this block, if present. See \ref
/// ByteInterval.getAddress for details on why this address may not be
/// present.
std::optional<Addr> getAddress() const;
/// \brief Set the size of this block.
///
/// Note that this does not automatically update any \ref ByteInterval's size,
/// bytes, or symbolic expressions. This simply changes the extents of a block
/// in its \ref ByteInterval.
void setSize(uint64_t S) {
if (Observer) {
std::swap(S, Size);
[[maybe_unused]] ChangeStatus Status =
Observer->sizeChange(this, S, Size);
assert(Status != ChangeStatus::Rejected &&
"recovering from rejected size change is not implemented yet");
} else {
Size = S;
}
}
/// \brief Iterator over bytes in this block.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> using bytes_iterator = ByteInterval::bytes_iterator<T>;
/// \brief Range over bytes in this block.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> using bytes_range = ByteInterval::bytes_range<T>;
/// \brief Const iterator over bytes in this block.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T>
using const_bytes_iterator = ByteInterval::const_bytes_iterator<T>;
/// \brief Const range over bytes in this block.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T>
using const_bytes_range = ByteInterval::const_bytes_range<T>;
/// \brief Get an iterator to the first byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> bytes_iterator<T> bytes_begin() {
assert(Parent && "Block has no byte interval!");
return bytes_begin<T>(Parent->getBoostEndianOrder());
}
/// \brief Get an iterator to the first byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
///
/// \param InputOrder The endianness of the data in the block.
/// \param OutputOrder The endianness you wish to read out from the block.
template <typename T>
bytes_iterator<T>
bytes_begin(boost::endian::order InputOrder,
boost::endian::order OutputOrder = boost::endian::order::native) {
assert(Parent && "Block has no byte interval!");
return Parent->bytes_begin<T>(InputOrder, OutputOrder) + getOffset();
}
/// \brief Get an iterator past the last byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> bytes_iterator<T> bytes_end() {
assert(Parent && "Block has no byte interval!");
return bytes_end<T>(Parent->getBoostEndianOrder());
}
/// \brief Get an iterator past the last byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
///
/// \param InputOrder The endianness of the data in the block.
/// \param OutputOrder The endianness you wish to read out from the block.
template <typename T>
bytes_iterator<T>
bytes_end(boost::endian::order InputOrder,
boost::endian::order OutputOrder = boost::endian::order::native) {
assert(Parent && "Block has no byte interval!");
return Parent->bytes_begin<T>(InputOrder, OutputOrder) + getOffset() + Size;
}
/// \brief Get a range of the bytes in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> bytes_range<T> bytes() {
assert(Parent && "Block has no byte interval!");
return bytes<T>(Parent->getBoostEndianOrder());
}
/// \brief Get a range of the bytes in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
///
/// \param InputOrder The endianness of the data in the block.
/// \param OutputOrder The endianness you wish to read out from the block.
template <typename T>
bytes_range<T>
bytes(boost::endian::order InputOrder,
boost::endian::order OutputOrder = boost::endian::order::native) {
assert(Parent && "Block has no byte interval!");
return bytes_range<T>(bytes_begin<T>(InputOrder, OutputOrder),
bytes_end<T>(InputOrder, OutputOrder));
}
/// \brief Get an iterator to the first byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> const_bytes_iterator<T> bytes_begin() const {
assert(Parent && "Block has no byte interval!");
return bytes_begin<T>(Parent->getBoostEndianOrder());
}
/// \brief Get an iterator to the first byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
///
/// \param InputOrder The endianness of the data in the block.
/// \param OutputOrder The endianness you wish to read out from the block.
template <typename T>
const_bytes_iterator<T> bytes_begin(
boost::endian::order InputOrder,
boost::endian::order OutputOrder = boost::endian::order::native) const {
assert(Parent && "Block has no byte interval!");
return Parent->bytes_begin<T>(InputOrder, OutputOrder) + getOffset();
}
/// \brief Get an iterator past the last byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> const_bytes_iterator<T> bytes_end() const {
assert(Parent && "Block has no byte interval!");
return bytes_end<T>(Parent->getBoostEndianOrder());
}
/// \brief Get an iterator past the last byte in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
///
/// \param InputOrder The endianness of the data in the block.
/// \param OutputOrder The endianness you wish to read out from the block.
template <typename T>
const_bytes_iterator<T> bytes_end(
boost::endian::order InputOrder,
boost::endian::order OutputOrder = boost::endian::order::native) const {
assert(Parent && "Block has no byte interval!");
return Parent->bytes_begin<T>(InputOrder, OutputOrder) + getOffset() + Size;
}
/// \brief Get a range of the bytes in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
template <typename T> const_bytes_range<T> bytes() const {
assert(Parent && "Block has no byte interval!");
return bytes<T>(Parent->getBoostEndianOrder());
}
/// \brief Get a range of the bytes in this block.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type that satisfies Boost's EndianReversible concept.
///
/// \param InputOrder The endianness of the data in the block.
/// \param OutputOrder The endianness you wish to read out from the block.
template <typename T>
const_bytes_range<T>
bytes(boost::endian::order InputOrder,
boost::endian::order OutputOrder = boost::endian::order::native) const {
assert(Parent && "Block has no byte interval!");
return const_bytes_range<T>(bytes_begin<T>(InputOrder, OutputOrder),
bytes_end<T>(InputOrder, OutputOrder));
}
/// \brief Return the raw data underlying this block's byte vector.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// Much like \ref std::vector::data, this function is low-level and
/// potentially unsafe. This pointer refers to valid memory only where an
/// iterator would be valid to point to. Modifying the size of the byte
/// vector may invalidate this pointer. Any endian conversions will not be
/// performed.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type.
///
/// \retrurn A pointer to raw data.
template <typename T> T* rawBytes() {
assert(Parent && "Block has no byte interval!");
return reinterpret_cast<T*>(Parent->rawBytes<uint8_t>() + getOffset());
}
/// \brief Return the raw data underlying this block's byte vector.
///
/// If this block is not associated with any \ref ByteInterval, than the
/// behavior of this function is undefined.
///
/// Much like \ref std::vector::data, this function is low-level and
/// potentially unsafe. This pointer refers to valid memory only where an
/// iterator would be valid to point to. Modifying the size of the byte
/// vector may invalidate this pointer. Any endian conversions will not be
/// performed.
///
/// \tparam T The type of data stored in this block's byte vector. Must be
/// a POD type.
///
/// \retrurn A pointer to raw data.
template <typename T> const T* rawBytes() const {
assert(Parent && "Block has no byte interval!");
return reinterpret_cast<const T*>(Parent->rawBytes<uint8_t>() +
getOffset());
}
/// @cond INTERNAL
static bool classof(const Node* N) { return N->getKind() == Kind::DataBlock; }
/// @endcond
private:
ByteInterval* Parent{nullptr};
DataBlockObserver* Observer{nullptr};
uint64_t Size{0};
void setParent(ByteInterval* BI, DataBlockObserver* O) {
Parent = BI;
Observer = O;
}
/// \brief The protobuf message type used for serializing DataBlock.
using MessageType = proto::DataBlock;
/// \brief Serialize into a protobuf message.
///
/// \param[out] Message Serialize into this message.
///
/// \return void
void toProtobuf(MessageType* Message) const;
/// \brief Construct a DataBlock from a protobuf message.
///
/// \param C The Context in which the deserialized DataBlock will be held.
/// \param Message The protobuf message from which to deserialize.
///
/// \return The deserialized DataBlock object, or null on failure.
static DataBlock* fromProtobuf(Context& C, const MessageType& Message);
// Present for testing purposes only.
void save(std::ostream& Out) const;
// Present for testing purposes only.
static DataBlock* load(Context& C, std::istream& In);
friend class Context; // Enables Context::Create
friend class ByteInterval; // Enables to/fromProtobuf, setByteInterval
friend class SerializationTestHarness; // Testing support.
};
} // namespace gtirb
#endif // GTIRB_DataBlock_H
|
#include "movingbody.h"
MovingBody::MovingBody()
{
}
MovingBody::~MovingBody()
{
}
void MovingBody::Update(float delta)
{
}
|
/**
* @file pointPolygonTest.cpp
* @brief mex interface for cv::pointPolygonTest
* @ingroup imgproc
* @author Kota Yamaguchi
* @date 2013
*/
#include "mexopencv.hpp"
#include "opencv2/imgproc.hpp"
using namespace std;
using namespace cv;
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs>=2 && (nrhs%2)==0 && nlhs<=1);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
// Option processing
bool measureDist = false;
for (int i=2; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "MeasureDist")
measureDist = rhs[i+1].toBool();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Mat contour;
vector<Point2f> contour_; // defined here, to allow data sharing w/o copy
if (rhs[0].isCell()) {
contour_ = rhs[0].toVector<Point2f>();
contour = Mat(contour_,false).reshape(1,0); // Nx2
}
else
contour = rhs[0].toMat(rhs[0].isInt32() ? CV_32S : CV_32F);
// Process
vector<double> results;
vector<Point2f> pts(rhs[1].toVector<Point2f>());
results.reserve(pts.size());
for (size_t i = 0; i < pts.size(); ++i)
results.push_back(pointPolygonTest(contour, pts[i], measureDist));
plhs[0] = MxArray(results);
}
|
/* -*- c++ -*- */
/*
* Copyright 2004,2010,2012 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "iir_filter_ffd_impl.h"
#include <gnuradio/io_signature.h>
namespace gr {
namespace filter {
iir_filter_ffd::sptr
iir_filter_ffd::make(const std::vector<double> &fftaps,
const std::vector<double> &fbtaps,
bool oldstyle)
{
return gnuradio::get_initial_sptr
(new iir_filter_ffd_impl(fftaps, fbtaps, oldstyle));
}
iir_filter_ffd_impl::iir_filter_ffd_impl(const std::vector<double> &fftaps,
const std::vector<double> &fbtaps,
bool oldstyle)
: sync_block("iir_filter_ffd",
io_signature::make(1, 1, sizeof (float)),
io_signature::make(1, 1, sizeof (float))),
d_updated(false)
{
d_iir = new kernel::iir_filter<float,float,double,double>(fftaps, fbtaps, oldstyle);
}
iir_filter_ffd_impl::~iir_filter_ffd_impl()
{
delete d_iir;
}
void
iir_filter_ffd_impl::set_taps(const std::vector<double> &fftaps,
const std::vector<double> &fbtaps)
{
d_new_fftaps = fftaps;
d_new_fbtaps = fbtaps;
d_updated = true;
}
int
iir_filter_ffd_impl::work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const float *in = (const float*)input_items[0];
float *out = (float*)output_items[0];
if(d_updated) {
d_iir->set_taps(d_new_fftaps, d_new_fbtaps);
d_updated = false;
}
d_iir->filter_n(out, in, noutput_items);
return noutput_items;
};
} /* namespace filter */
} /* namespace gr */
|
/*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
static bool exeIsAvailable (const char* const executable)
{
ChildProcess child;
const bool ok = child.start ("which " + String (executable))
&& child.readAllProcessOutput().trim().isNotEmpty();
child.waitForProcessToFinish (60 * 1000);
return ok;
}
bool FileChooser::isPlatformDialogAvailable()
{
return exeIsAvailable ("zenity") || exeIsAvailable ("kdialog");
}
void FileChooser::showPlatformDialog (Array<File>& results,
const String& title,
const File& file,
const String& filters,
bool isDirectory,
bool selectsFiles,
bool isSave,
bool warnAboutOverwritingExistingFiles,
bool selectMultipleFiles,
FilePreviewComponent* previewComponent)
{
String separator;
StringArray args;
const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
const bool isKdeFullSession = SystemStats::getEnvironmentVariable ("KDE_FULL_SESSION", String::empty)
.equalsIgnoreCase ("true");
if (exeIsAvailable ("kdialog") && (isKdeFullSession || ! exeIsAvailable ("zenity")))
{
// use kdialog for KDE sessions or if zenity is missing
args.add ("kdialog");
if (title.isNotEmpty())
args.add ("--title=" + title);
if (selectMultipleFiles)
{
separator = "\n";
args.add ("--multiple");
args.add ("--separate-output");
args.add ("--getopenfilename");
}
else
{
if (isSave) args.add ("--getsavefilename");
else if (isDirectory) args.add ("--getexistingdirectory");
else args.add ("--getopenfilename");
}
String startPath;
if (file.exists() || file.getParentDirectory().exists())
{
startPath = file.getFullPathName();
}
else
{
startPath = File::getSpecialLocation (File::userHomeDirectory).getFullPathName();
if (isSave)
startPath += "/" + file.getFileName();
}
args.add (startPath);
}
else
{
// zenity
args.add ("zenity");
args.add ("--file-selection");
if (title.isNotEmpty())
args.add ("--title=" + title);
if (selectMultipleFiles)
{
separator = ":";
args.add ("--multiple");
args.add ("--separator=" + separator);
}
else
{
if (isDirectory) args.add ("--directory");
if (isSave) args.add ("--save");
}
if (file.isDirectory())
file.setAsCurrentWorkingDirectory();
else if (file.getParentDirectory().exists())
file.getParentDirectory().setAsCurrentWorkingDirectory();
else
File::getSpecialLocation (File::userHomeDirectory).setAsCurrentWorkingDirectory();
if (! file.getFileName().isEmpty())
args.add ("--filename=" + file.getFileName());
}
ChildProcess child;
if (child.start (args))
{
const String result (child.readAllProcessOutput().trim());
if (result.isNotEmpty())
{
StringArray tokens;
if (selectMultipleFiles)
tokens.addTokens (result, separator, "\"");
else
tokens.add (result);
for (int i = 0; i < tokens.size(); i++)
results.add (File (tokens[i]));
}
child.waitForProcessToFinish (60 * 1000);
}
previousWorkingDirectory.setAsCurrentWorkingDirectory();
}
|
#pragma once
#include <fstream>
#include <iostream>
#include <map>
#include <string>
namespace param {
typedef std::map<std::string, std::string> ptype;
class parameter {
private:
ptype params;
bool valid;
bool contains(std::string &key) const {
return params.find(key) != params.end();
}
public:
parameter(const std::string filename) : valid(true) {
loadFromFile(filename);
}
explicit operator bool() const {
return valid;
};
void loadFromFile(const std::string filename) {
std::ifstream is(filename);
if (is.fail()) {
std::cerr << "Could not open file " << filename << std::endl;
valid = false;
}
readfromstream(is);
}
void readfromstream(std::istream &is) {
std::string line;
while (getline(is, line)) {
if (line.length() > 0 && line[0] == '#') {
continue;
}
size_t index = line.find("=");
if (std::string::npos != index) {
std::string key = line.substr(0, index);
std::string value = line.substr(index + 1, line.length());
params.insert(ptype::value_type(key, value));
}
}
}
void check_key(std::string &key) const {
if (!contains(key)) {
std::cerr << "No such key: " << key << std::endl;
std::abort();
}
}
template <class T>
T get(std::string) {
}
template <class T>
T get(std::string, T value) {
return value;
}
};
template <>
bool parameter::get<bool>(std::string key, bool value) {
if (!contains(key)) {
return value;
}
if ("yes" == params[key] || "Yes" == params[key]) {
return true;
} else {
return false;
}
}
template <>
bool parameter::get(std::string key) {
check_key(key);
return get<bool>(key, false);
}
template <>
int parameter::get(std::string key, int value) {
if (!contains(key)) {
return value;
}
return std::stoi(params[key]);
}
template <>
int parameter::get(std::string key) {
check_key(key);
return get<int>(key, 0);
}
template <>
double parameter::get(std::string key, double value) {
if (!contains(key)) {
return value;
}
return std::stod(params[key]);
}
template <>
double parameter::get(std::string key) {
check_key(key);
return get<double>(key, 0.0);
}
} // namespace param
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/dms/model/Filter.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace DatabaseMigrationService
{
namespace Model
{
Filter::Filter() :
m_nameHasBeenSet(false),
m_valuesHasBeenSet(false)
{
}
Filter::Filter(const JsonValue& jsonValue) :
m_nameHasBeenSet(false),
m_valuesHasBeenSet(false)
{
*this = jsonValue;
}
Filter& Filter::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("Values"))
{
Array<JsonValue> valuesJsonList = jsonValue.GetArray("Values");
for(unsigned valuesIndex = 0; valuesIndex < valuesJsonList.GetLength(); ++valuesIndex)
{
m_values.push_back(valuesJsonList[valuesIndex].AsString());
}
m_valuesHasBeenSet = true;
}
return *this;
}
JsonValue Filter::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_valuesHasBeenSet)
{
Array<JsonValue> valuesJsonList(m_values.size());
for(unsigned valuesIndex = 0; valuesIndex < valuesJsonList.GetLength(); ++valuesIndex)
{
valuesJsonList[valuesIndex].AsString(m_values[valuesIndex]);
}
payload.WithArray("Values", std::move(valuesJsonList));
}
return payload;
}
} // namespace Model
} // namespace DatabaseMigrationService
} // namespace Aws
|
/*************************************************************************/
/* space_sw.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "space_sw.h"
#include "collision_solver_sw.h"
#include "globals.h"
#include "physics_server_sw.h"
_FORCE_INLINE_ static bool _match_object_type_query(CollisionObjectSW *p_object, uint32_t p_layer_mask, uint32_t p_type_mask) {
if ((p_object->get_layer_mask() & p_layer_mask) == 0)
return false;
if (p_object->get_type() == CollisionObjectSW::TYPE_AREA)
return p_type_mask & PhysicsDirectSpaceState::TYPE_MASK_AREA;
BodySW *body = static_cast<BodySW *>(p_object);
return (1 << body->get_mode()) & p_type_mask;
}
bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, bool p_pick_ray) {
ERR_FAIL_COND_V(space->locked, false);
Vector3 begin, end;
Vector3 normal;
begin = p_from;
end = p_to;
normal = (end - begin).normalized();
int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
//todo, create another array tha references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision
bool collided = false;
Vector3 res_point, res_normal;
int res_shape;
const CollisionObjectSW *res_obj;
real_t min_d = 1e10;
for (int i = 0; i < amount; i++) {
if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
if (p_pick_ray && !(static_cast<CollisionObjectSW *>(space->intersection_query_results[i])->is_ray_pickable()))
continue;
if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue;
const CollisionObjectSW *col_obj = space->intersection_query_results[i];
int shape_idx = space->intersection_query_subindex_results[i];
Transform inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
Vector3 local_from = inv_xform.xform(begin);
Vector3 local_to = inv_xform.xform(end);
const ShapeSW *shape = col_obj->get_shape(shape_idx);
Vector3 shape_point, shape_normal;
if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
Transform xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
shape_point = xform.xform(shape_point);
real_t ld = normal.dot(shape_point);
if (ld < min_d) {
min_d = ld;
res_point = shape_point;
res_normal = inv_xform.basis.xform_inv(shape_normal).normalized();
res_shape = shape_idx;
res_obj = col_obj;
collided = true;
}
}
}
if (!collided)
return false;
r_result.collider_id = res_obj->get_instance_id();
if (r_result.collider_id != 0)
r_result.collider = ObjectDB::get_instance(r_result.collider_id);
else
r_result.collider = NULL;
r_result.normal = res_normal;
r_result.position = res_point;
r_result.rid = res_obj->get_self();
r_result.shape = res_shape;
return true;
}
int PhysicsDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform &p_xform, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
if (p_result_max <= 0)
return 0;
ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
ERR_FAIL_COND_V(!shape, 0);
AABB aabb = p_xform.xform(shape->get_aabb());
int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
int cc = 0;
//Transform ai = p_xform.affine_inverse();
for (int i = 0; i < amount; i++) {
if (cc >= p_result_max)
break;
if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
//area cant be picked by ray (default)
if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue;
const CollisionObjectSW *col_obj = space->intersection_query_results[i];
int shape_idx = space->intersection_query_subindex_results[i];
if (!CollisionSolverSW::solve_static(shape, p_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), NULL, NULL, NULL, p_margin, 0))
continue;
if (r_results) {
r_results[cc].collider_id = col_obj->get_instance_id();
if (r_results[cc].collider_id != 0)
r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
else
r_results[cc].collider = NULL;
r_results[cc].rid = col_obj->get_self();
r_results[cc].shape = shape_idx;
}
cc++;
}
return cc;
}
bool PhysicsDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &p_closest_safe, float &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, ShapeRestInfo *r_info) {
ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
ERR_FAIL_COND_V(!shape, false);
AABB aabb = p_xform.xform(shape->get_aabb());
aabb = aabb.merge(AABB(aabb.pos + p_motion, aabb.size)); //motion
aabb = aabb.grow(p_margin);
//if (p_motion!=Vector3())
// print_line(p_motion);
int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
float best_safe = 1;
float best_unsafe = 1;
Transform xform_inv = p_xform.affine_inverse();
MotionShapeSW mshape;
mshape.shape = shape;
mshape.motion = xform_inv.basis.xform(p_motion);
bool best_first = true;
Vector3 closest_A, closest_B;
for (int i = 0; i < amount; i++) {
if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue; //ignore excluded
const CollisionObjectSW *col_obj = space->intersection_query_results[i];
int shape_idx = space->intersection_query_subindex_results[i];
Vector3 point_A, point_B;
Vector3 sep_axis = p_motion.normalized();
Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
//test initial overlap, does it collide if going all the way?
if (CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
//print_line("failed motion cast (no collision)");
continue;
}
//test initial overlap
#if 0
if (CollisionSolverSW::solve_static(shape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,NULL,NULL,&sep_axis)) {
print_line("failed initial cast (collision at begining)");
return false;
}
#else
sep_axis = p_motion.normalized();
if (!CollisionSolverSW::solve_distance(shape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
//print_line("failed motion cast (no collision)");
return false;
}
#endif
//just do kinematic solving
float low = 0;
float hi = 1;
Vector3 mnormal = p_motion.normalized();
for (int i = 0; i < 8; i++) { //steps should be customizable..
float ofs = (low + hi) * 0.5;
Vector3 sep = mnormal; //important optimization for this to work fast enough
mshape.motion = xform_inv.basis.xform(p_motion * ofs);
Vector3 lA, lB;
bool collided = !CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, lA, lB, aabb, &sep);
if (collided) {
//print_line(itos(i)+": "+rtos(ofs));
hi = ofs;
} else {
point_A = lA;
point_B = lB;
low = ofs;
}
}
if (low < best_safe) {
best_first = true; //force reset
best_safe = low;
best_unsafe = hi;
}
if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low <= best_safe))) {
closest_A = point_A;
closest_B = point_B;
r_info->collider_id = col_obj->get_instance_id();
r_info->rid = col_obj->get_self();
r_info->shape = shape_idx;
r_info->point = closest_B;
r_info->normal = (closest_A - closest_B).normalized();
best_first = false;
if (col_obj->get_type() == CollisionObjectSW::TYPE_BODY) {
const BodySW *body = static_cast<const BodySW *>(col_obj);
r_info->linear_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B);
}
}
}
p_closest_safe = best_safe;
p_closest_unsafe = best_unsafe;
return true;
}
bool PhysicsDirectSpaceStateSW::collide_shape(RID p_shape, const Transform &p_shape_xform, float p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
if (p_result_max <= 0)
return 0;
ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
ERR_FAIL_COND_V(!shape, 0);
AABB aabb = p_shape_xform.xform(shape->get_aabb());
aabb = aabb.grow(p_margin);
int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
bool collided = false;
r_result_count = 0;
PhysicsServerSW::CollCbkData cbk;
cbk.max = p_result_max;
cbk.amount = 0;
cbk.ptr = r_results;
CollisionSolverSW::CallbackResult cbkres = NULL;
PhysicsServerSW::CollCbkData *cbkptr = NULL;
if (p_result_max > 0) {
cbkptr = &cbk;
cbkres = PhysicsServerSW::_shape_col_cbk;
}
for (int i = 0; i < amount; i++) {
if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
const CollisionObjectSW *col_obj = space->intersection_query_results[i];
int shape_idx = space->intersection_query_subindex_results[i];
if (p_exclude.has(col_obj->get_self())) {
continue;
}
//print_line("AGAINST: "+itos(col_obj->get_self().get_id())+":"+itos(shape_idx));
//print_line("THE ABBB: "+(col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).xform(col_obj->get_shape(shape_idx)->get_aabb()));
if (CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, NULL, p_margin)) {
collided = true;
}
}
r_result_count = cbk.amount;
return collided;
}
struct _RestCallbackData {
const CollisionObjectSW *object;
const CollisionObjectSW *best_object;
int shape;
int best_shape;
Vector3 best_contact;
Vector3 best_normal;
float best_len;
};
static void _rest_cbk_result(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) {
_RestCallbackData *rd = (_RestCallbackData *)p_userdata;
Vector3 contact_rel = p_point_B - p_point_A;
float len = contact_rel.length();
if (len <= rd->best_len)
return;
rd->best_len = len;
rd->best_contact = p_point_B;
rd->best_normal = contact_rel / len;
rd->best_object = rd->object;
rd->best_shape = rd->shape;
}
bool PhysicsDirectSpaceStateSW::rest_info(RID p_shape, const Transform &p_shape_xform, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
ERR_FAIL_COND_V(!shape, 0);
AABB aabb = p_shape_xform.xform(shape->get_aabb());
aabb = aabb.grow(p_margin);
int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
_RestCallbackData rcd;
rcd.best_len = 0;
rcd.best_object = NULL;
rcd.best_shape = 0;
for (int i = 0; i < amount; i++) {
if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
const CollisionObjectSW *col_obj = space->intersection_query_results[i];
int shape_idx = space->intersection_query_subindex_results[i];
if (p_exclude.has(col_obj->get_self()))
continue;
rcd.object = col_obj;
rcd.shape = shape_idx;
bool sc = CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, NULL, p_margin);
if (!sc)
continue;
}
if (rcd.best_len == 0)
return false;
r_info->collider_id = rcd.best_object->get_instance_id();
r_info->shape = rcd.best_shape;
r_info->normal = rcd.best_normal;
r_info->point = rcd.best_contact;
r_info->rid = rcd.best_object->get_self();
if (rcd.best_object->get_type() == CollisionObjectSW::TYPE_BODY) {
const BodySW *body = static_cast<const BodySW *>(rcd.best_object);
r_info->linear_velocity = body->get_linear_velocity() +
(body->get_angular_velocity()).cross(body->get_transform().origin - rcd.best_contact); // * mPos);
} else {
r_info->linear_velocity = Vector3();
}
return true;
}
PhysicsDirectSpaceStateSW::PhysicsDirectSpaceStateSW() {
space = NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void *SpaceSW::_broadphase_pair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_self) {
CollisionObjectSW::Type type_A = A->get_type();
CollisionObjectSW::Type type_B = B->get_type();
if (type_A > type_B) {
SWAP(A, B);
SWAP(p_subindex_A, p_subindex_B);
SWAP(type_A, type_B);
}
SpaceSW *self = (SpaceSW *)p_self;
self->collision_pairs++;
if (type_A == CollisionObjectSW::TYPE_AREA) {
AreaSW *area = static_cast<AreaSW *>(A);
if (type_B == CollisionObjectSW::TYPE_AREA) {
AreaSW *area_b = static_cast<AreaSW *>(B);
Area2PairSW *area2_pair = memnew(Area2PairSW(area_b, p_subindex_B, area, p_subindex_A));
return area2_pair;
} else {
BodySW *body = static_cast<BodySW *>(B);
AreaPairSW *area_pair = memnew(AreaPairSW(body, p_subindex_B, area, p_subindex_A));
return area_pair;
}
} else {
BodyPairSW *b = memnew(BodyPairSW((BodySW *)A, p_subindex_A, (BodySW *)B, p_subindex_B));
return b;
}
return NULL;
}
void SpaceSW::_broadphase_unpair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_self) {
SpaceSW *self = (SpaceSW *)p_self;
self->collision_pairs--;
ConstraintSW *c = (ConstraintSW *)p_data;
memdelete(c);
}
const SelfList<BodySW>::List &SpaceSW::get_active_body_list() const {
return active_list;
}
void SpaceSW::body_add_to_active_list(SelfList<BodySW> *p_body) {
active_list.add(p_body);
}
void SpaceSW::body_remove_from_active_list(SelfList<BodySW> *p_body) {
active_list.remove(p_body);
}
void SpaceSW::body_add_to_inertia_update_list(SelfList<BodySW> *p_body) {
inertia_update_list.add(p_body);
}
void SpaceSW::body_remove_from_inertia_update_list(SelfList<BodySW> *p_body) {
inertia_update_list.remove(p_body);
}
BroadPhaseSW *SpaceSW::get_broadphase() {
return broadphase;
}
void SpaceSW::add_object(CollisionObjectSW *p_object) {
ERR_FAIL_COND(objects.has(p_object));
objects.insert(p_object);
}
void SpaceSW::remove_object(CollisionObjectSW *p_object) {
ERR_FAIL_COND(!objects.has(p_object));
objects.erase(p_object);
}
const Set<CollisionObjectSW *> &SpaceSW::get_objects() const {
return objects;
}
void SpaceSW::body_add_to_state_query_list(SelfList<BodySW> *p_body) {
state_query_list.add(p_body);
}
void SpaceSW::body_remove_from_state_query_list(SelfList<BodySW> *p_body) {
state_query_list.remove(p_body);
}
void SpaceSW::area_add_to_monitor_query_list(SelfList<AreaSW> *p_area) {
monitor_query_list.add(p_area);
}
void SpaceSW::area_remove_from_monitor_query_list(SelfList<AreaSW> *p_area) {
monitor_query_list.remove(p_area);
}
void SpaceSW::area_add_to_moved_list(SelfList<AreaSW> *p_area) {
area_moved_list.add(p_area);
}
void SpaceSW::area_remove_from_moved_list(SelfList<AreaSW> *p_area) {
area_moved_list.remove(p_area);
}
const SelfList<AreaSW>::List &SpaceSW::get_moved_area_list() const {
return area_moved_list;
}
void SpaceSW::call_queries() {
while (state_query_list.first()) {
BodySW *b = state_query_list.first()->self();
b->call_queries();
state_query_list.remove(state_query_list.first());
}
while (monitor_query_list.first()) {
AreaSW *a = monitor_query_list.first()->self();
a->call_queries();
monitor_query_list.remove(monitor_query_list.first());
}
}
void SpaceSW::setup() {
contact_debug_count = 0;
while (inertia_update_list.first()) {
inertia_update_list.first()->self()->update_inertias();
inertia_update_list.remove(inertia_update_list.first());
}
}
void SpaceSW::update() {
broadphase->update();
}
void SpaceSW::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
switch (p_param) {
case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break;
case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break;
case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break;
case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_threshold = p_value; break;
case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_threshold = p_value; break;
case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break;
case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: body_angular_velocity_damp_ratio = p_value; break;
case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break;
}
}
real_t SpaceSW::get_param(PhysicsServer::SpaceParameter p_param) const {
switch (p_param) {
case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius;
case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation;
case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: return contact_max_allowed_penetration;
case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: return body_linear_velocity_sleep_threshold;
case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: return body_angular_velocity_sleep_threshold;
case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: return body_time_to_sleep;
case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: return body_angular_velocity_damp_ratio;
case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: return constraint_bias;
}
return 0;
}
void SpaceSW::lock() {
locked = true;
}
void SpaceSW::unlock() {
locked = false;
}
bool SpaceSW::is_locked() const {
return locked;
}
PhysicsDirectSpaceStateSW *SpaceSW::get_direct_state() {
return direct_access;
}
SpaceSW::SpaceSW() {
collision_pairs = 0;
active_objects = 0;
island_count = 0;
contact_debug_count = 0;
locked = false;
contact_recycle_radius = 0.01;
contact_max_separation = 0.05;
contact_max_allowed_penetration = 0.01;
constraint_bias = 0.01;
body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/sleep_threshold_linear", 0.1);
body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/sleep_threshold_angular", (8.0 / 180.0 * Math_PI));
body_time_to_sleep = GLOBAL_DEF("physics/time_before_sleep", 0.5);
body_angular_velocity_damp_ratio = 10;
broadphase = BroadPhaseSW::create_func();
broadphase->set_pair_callback(_broadphase_pair, this);
broadphase->set_unpair_callback(_broadphase_unpair, this);
area = NULL;
direct_access = memnew(PhysicsDirectSpaceStateSW);
direct_access->space = this;
for (int i = 0; i < ELAPSED_TIME_MAX; i++)
elapsed_time[i] = 0;
}
SpaceSW::~SpaceSW() {
memdelete(broadphase);
memdelete(direct_access);
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/policy/cloud/cloud_policy_invalidator.h"
#include <utility>
#include "base/bind.h"
#include "base/hash.h"
#include "base/location.h"
#include "base/metrics/histogram.h"
#include "base/rand_util.h"
#include "base/sequenced_task_runner.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/invalidation/public/invalidation_service.h"
#include "components/invalidation/public/object_id_invalidation_map.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h"
#include "components/policy/core/common/cloud/enterprise_metrics.h"
#include "policy/policy_constants.h"
namespace policy {
const int CloudPolicyInvalidator::kMissingPayloadDelay = 5;
const int CloudPolicyInvalidator::kMaxFetchDelayDefault = 10000;
const int CloudPolicyInvalidator::kMaxFetchDelayMin = 1000;
const int CloudPolicyInvalidator::kMaxFetchDelayMax = 300000;
const int CloudPolicyInvalidator::kInvalidationGracePeriod = 10;
const int CloudPolicyInvalidator::kUnknownVersionIgnorePeriod = 30;
const int CloudPolicyInvalidator::kMaxInvalidationTimeDelta = 300;
CloudPolicyInvalidator::CloudPolicyInvalidator(
enterprise_management::DeviceRegisterRequest::Type type,
CloudPolicyCore* core,
const scoped_refptr<base::SequencedTaskRunner>& task_runner,
scoped_ptr<base::Clock> clock,
int64_t highest_handled_invalidation_version)
: state_(UNINITIALIZED),
type_(type),
core_(core),
task_runner_(task_runner),
clock_(std::move(clock)),
invalidation_service_(NULL),
invalidations_enabled_(false),
invalidation_service_enabled_(false),
is_registered_(false),
invalid_(false),
invalidation_version_(0),
unknown_version_invalidation_count_(0),
highest_handled_invalidation_version_(
highest_handled_invalidation_version),
max_fetch_delay_(kMaxFetchDelayDefault),
policy_hash_value_(0),
weak_factory_(this) {
DCHECK(core);
DCHECK(task_runner.get());
// |highest_handled_invalidation_version_| indicates the highest actual
// invalidation version handled. Since actual invalidations can have only
// positive versions, this member may be zero (no versioned invalidation
// handled yet) or positive. Negative values are not allowed:
//
// Negative version numbers are used internally by CloudPolicyInvalidator to
// keep track of unversioned invalidations. When such an invalidation is
// handled, |highest_handled_invalidation_version_| remains unchanged and does
// not become negative.
DCHECK_LE(0, highest_handled_invalidation_version_);
}
CloudPolicyInvalidator::~CloudPolicyInvalidator() {
DCHECK(state_ == SHUT_DOWN);
}
void CloudPolicyInvalidator::Initialize(
invalidation::InvalidationService* invalidation_service) {
DCHECK(state_ == UNINITIALIZED);
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(invalidation_service);
invalidation_service_ = invalidation_service;
state_ = STOPPED;
core_->AddObserver(this);
if (core_->refresh_scheduler())
OnRefreshSchedulerStarted(core_);
}
void CloudPolicyInvalidator::Shutdown() {
DCHECK(state_ != SHUT_DOWN);
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ == STARTED) {
if (is_registered_)
invalidation_service_->UnregisterInvalidationHandler(this);
core_->store()->RemoveObserver(this);
weak_factory_.InvalidateWeakPtrs();
}
if (state_ != UNINITIALIZED)
core_->RemoveObserver(this);
state_ = SHUT_DOWN;
}
void CloudPolicyInvalidator::OnInvalidatorStateChange(
syncer::InvalidatorState state) {
DCHECK(state_ == STARTED);
DCHECK(thread_checker_.CalledOnValidThread());
invalidation_service_enabled_ = state == syncer::INVALIDATIONS_ENABLED;
UpdateInvalidationsEnabled();
}
void CloudPolicyInvalidator::OnIncomingInvalidation(
const syncer::ObjectIdInvalidationMap& invalidation_map) {
DCHECK(state_ == STARTED);
DCHECK(thread_checker_.CalledOnValidThread());
const syncer::SingleObjectInvalidationSet& list =
invalidation_map.ForObject(object_id_);
if (list.IsEmpty()) {
NOTREACHED();
return;
}
// Acknowledge all except the invalidation with the highest version.
syncer::SingleObjectInvalidationSet::const_reverse_iterator it =
list.rbegin();
++it;
for ( ; it != list.rend(); ++it) {
it->Acknowledge();
}
// Handle the highest version invalidation.
HandleInvalidation(list.back());
}
std::string CloudPolicyInvalidator::GetOwnerName() const { return "Cloud"; }
void CloudPolicyInvalidator::OnCoreConnected(CloudPolicyCore* core) {}
void CloudPolicyInvalidator::OnRefreshSchedulerStarted(CloudPolicyCore* core) {
DCHECK(state_ == STOPPED);
DCHECK(thread_checker_.CalledOnValidThread());
state_ = STARTED;
OnStoreLoaded(core_->store());
core_->store()->AddObserver(this);
}
void CloudPolicyInvalidator::OnCoreDisconnecting(CloudPolicyCore* core) {
DCHECK(state_ == STARTED || state_ == STOPPED);
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ == STARTED) {
Unregister();
core_->store()->RemoveObserver(this);
state_ = STOPPED;
}
}
void CloudPolicyInvalidator::OnStoreLoaded(CloudPolicyStore* store) {
DCHECK(state_ == STARTED);
DCHECK(thread_checker_.CalledOnValidThread());
bool policy_changed = IsPolicyChanged(store->policy());
if (is_registered_) {
// Update the kMetricDevicePolicyRefresh/kMetricUserPolicyRefresh histogram.
if (type_ == enterprise_management::DeviceRegisterRequest::DEVICE) {
UMA_HISTOGRAM_ENUMERATION(kMetricDevicePolicyRefresh,
GetPolicyRefreshMetric(policy_changed),
METRIC_POLICY_REFRESH_SIZE);
} else {
UMA_HISTOGRAM_ENUMERATION(kMetricUserPolicyRefresh,
GetPolicyRefreshMetric(policy_changed),
METRIC_POLICY_REFRESH_SIZE);
}
const int64_t store_invalidation_version = store->invalidation_version();
// If the policy was invalid and the version stored matches the latest
// invalidation version, acknowledge the latest invalidation.
if (invalid_ && store_invalidation_version == invalidation_version_)
AcknowledgeInvalidation();
// Update the highest invalidation version that was handled already.
if (store_invalidation_version > highest_handled_invalidation_version_)
highest_handled_invalidation_version_ = store_invalidation_version;
}
UpdateRegistration(store->policy());
UpdateMaxFetchDelay(store->policy_map());
}
void CloudPolicyInvalidator::OnStoreError(CloudPolicyStore* store) {}
void CloudPolicyInvalidator::HandleInvalidation(
const syncer::Invalidation& invalidation) {
// Ignore old invalidations.
if (invalid_ &&
!invalidation.is_unknown_version() &&
invalidation.version() <= invalidation_version_) {
return;
}
if (!invalidation.is_unknown_version() &&
invalidation.version() <= highest_handled_invalidation_version_) {
// If this invalidation version was handled already, acknowledge the
// invalidation but ignore it otherwise.
invalidation.Acknowledge();
return;
}
// If there is still a pending invalidation, acknowledge it, since we only
// care about the latest invalidation.
if (invalid_)
AcknowledgeInvalidation();
// Get the version and payload from the invalidation.
// When an invalidation with unknown version is received, use negative
// numbers based on the number of such invalidations received. This
// ensures that the version numbers do not collide with "real" versions
// (which are positive) or previous invalidations with unknown version.
int64_t version;
std::string payload;
if (invalidation.is_unknown_version()) {
version = -(++unknown_version_invalidation_count_);
} else {
version = invalidation.version();
payload = invalidation.payload();
}
// Ignore the invalidation if it is expired.
bool is_expired = IsInvalidationExpired(version);
if (type_ == enterprise_management::DeviceRegisterRequest::DEVICE) {
UMA_HISTOGRAM_ENUMERATION(
kMetricDevicePolicyInvalidations,
GetInvalidationMetric(payload.empty(), is_expired),
POLICY_INVALIDATION_TYPE_SIZE);
} else {
UMA_HISTOGRAM_ENUMERATION(
kMetricUserPolicyInvalidations,
GetInvalidationMetric(payload.empty(), is_expired),
POLICY_INVALIDATION_TYPE_SIZE);
}
if (is_expired) {
invalidation.Acknowledge();
return;
}
// Update invalidation state.
invalid_ = true;
invalidation_.reset(new syncer::Invalidation(invalidation));
invalidation_version_ = version;
// In order to prevent the cloud policy server from becoming overwhelmed when
// a policy with many users is modified, delay for a random period of time
// before fetching the policy. Delay for at least 20ms so that if multiple
// invalidations are received in quick succession, only one fetch will be
// performed.
base::TimeDelta delay = base::TimeDelta::FromMilliseconds(
base::RandInt(20, max_fetch_delay_));
// If there is a payload, the policy can be refreshed at any time, so set
// the version and payload on the client immediately. Otherwise, the refresh
// must only run after at least kMissingPayloadDelay minutes.
if (!payload.empty())
core_->client()->SetInvalidationInfo(version, payload);
else
delay += base::TimeDelta::FromMinutes(kMissingPayloadDelay);
// Schedule the policy to be refreshed.
task_runner_->PostDelayedTask(
FROM_HERE,
base::Bind(
&CloudPolicyInvalidator::RefreshPolicy,
weak_factory_.GetWeakPtr(),
payload.empty() /* is_missing_payload */),
delay);
}
void CloudPolicyInvalidator::UpdateRegistration(
const enterprise_management::PolicyData* policy) {
// Create the ObjectId based on the policy data.
// If the policy does not specify an the ObjectId, then unregister.
if (!policy ||
!policy->has_invalidation_source() ||
!policy->has_invalidation_name()) {
Unregister();
return;
}
invalidation::ObjectId object_id(
policy->invalidation_source(),
policy->invalidation_name());
// If the policy object id in the policy data is different from the currently
// registered object id, update the object registration.
if (!is_registered_ || !(object_id == object_id_))
Register(object_id);
}
void CloudPolicyInvalidator::Register(const invalidation::ObjectId& object_id) {
// Register this handler with the invalidation service if needed.
if (!is_registered_) {
OnInvalidatorStateChange(invalidation_service_->GetInvalidatorState());
invalidation_service_->RegisterInvalidationHandler(this);
}
// Update internal state.
if (invalid_)
AcknowledgeInvalidation();
is_registered_ = true;
object_id_ = object_id;
UpdateInvalidationsEnabled();
// Update registration with the invalidation service.
syncer::ObjectIdSet ids;
ids.insert(object_id);
CHECK(invalidation_service_->UpdateRegisteredInvalidationIds(this, ids));
}
void CloudPolicyInvalidator::Unregister() {
if (is_registered_) {
if (invalid_)
AcknowledgeInvalidation();
CHECK(invalidation_service_->UpdateRegisteredInvalidationIds(
this, syncer::ObjectIdSet()));
invalidation_service_->UnregisterInvalidationHandler(this);
is_registered_ = false;
UpdateInvalidationsEnabled();
}
}
void CloudPolicyInvalidator::UpdateMaxFetchDelay(const PolicyMap& policy_map) {
int delay;
// Try reading the delay from the policy.
const base::Value* delay_policy_value =
policy_map.GetValue(key::kMaxInvalidationFetchDelay);
if (delay_policy_value && delay_policy_value->GetAsInteger(&delay)) {
set_max_fetch_delay(delay);
return;
}
set_max_fetch_delay(kMaxFetchDelayDefault);
}
void CloudPolicyInvalidator::set_max_fetch_delay(int delay) {
if (delay < kMaxFetchDelayMin)
max_fetch_delay_ = kMaxFetchDelayMin;
else if (delay > kMaxFetchDelayMax)
max_fetch_delay_ = kMaxFetchDelayMax;
else
max_fetch_delay_ = delay;
}
void CloudPolicyInvalidator::UpdateInvalidationsEnabled() {
bool invalidations_enabled = invalidation_service_enabled_ && is_registered_;
if (invalidations_enabled_ != invalidations_enabled) {
invalidations_enabled_ = invalidations_enabled;
if (invalidations_enabled)
invalidations_enabled_time_ = clock_->Now();
core_->refresh_scheduler()->SetInvalidationServiceAvailability(
invalidations_enabled);
}
}
void CloudPolicyInvalidator::RefreshPolicy(bool is_missing_payload) {
DCHECK(thread_checker_.CalledOnValidThread());
// In the missing payload case, the invalidation version has not been set on
// the client yet, so set it now that the required time has elapsed.
if (is_missing_payload)
core_->client()->SetInvalidationInfo(invalidation_version_, std::string());
core_->refresh_scheduler()->RefreshSoon();
}
void CloudPolicyInvalidator::AcknowledgeInvalidation() {
DCHECK(invalid_);
invalid_ = false;
core_->client()->SetInvalidationInfo(0, std::string());
invalidation_->Acknowledge();
invalidation_.reset();
// Cancel any scheduled policy refreshes.
weak_factory_.InvalidateWeakPtrs();
}
bool CloudPolicyInvalidator::IsPolicyChanged(
const enterprise_management::PolicyData* policy) {
// Determine if the policy changed by comparing its hash value to the
// previous policy's hash value.
uint32_t new_hash_value = 0;
if (policy && policy->has_policy_value())
new_hash_value = base::Hash(policy->policy_value());
bool changed = new_hash_value != policy_hash_value_;
policy_hash_value_ = new_hash_value;
return changed;
}
bool CloudPolicyInvalidator::IsInvalidationExpired(int64_t version) {
base::Time last_fetch_time = base::Time::UnixEpoch() +
base::TimeDelta::FromMilliseconds(core_->store()->policy()->timestamp());
// If the version is unknown, consider the invalidation invalid if the
// policy was fetched very recently.
if (version < 0) {
base::TimeDelta elapsed = clock_->Now() - last_fetch_time;
return elapsed.InSeconds() < kUnknownVersionIgnorePeriod;
}
// The invalidation version is the timestamp in microseconds. If the
// invalidation occurred before the last policy fetch, then the invalidation
// is expired. Time is added to the invalidation to err on the side of not
// expired.
base::Time invalidation_time = base::Time::UnixEpoch() +
base::TimeDelta::FromMicroseconds(version) +
base::TimeDelta::FromSeconds(kMaxInvalidationTimeDelta);
return invalidation_time < last_fetch_time;
}
int CloudPolicyInvalidator::GetPolicyRefreshMetric(bool policy_changed) {
if (policy_changed) {
if (invalid_)
return METRIC_POLICY_REFRESH_INVALIDATED_CHANGED;
if (GetInvalidationsEnabled())
return METRIC_POLICY_REFRESH_CHANGED;
return METRIC_POLICY_REFRESH_CHANGED_NO_INVALIDATIONS;
}
if (invalid_)
return METRIC_POLICY_REFRESH_INVALIDATED_UNCHANGED;
return METRIC_POLICY_REFRESH_UNCHANGED;
}
int CloudPolicyInvalidator::GetInvalidationMetric(bool is_missing_payload,
bool is_expired) {
if (is_expired) {
if (is_missing_payload)
return POLICY_INVALIDATION_TYPE_NO_PAYLOAD_EXPIRED;
return POLICY_INVALIDATION_TYPE_EXPIRED;
}
if (is_missing_payload)
return POLICY_INVALIDATION_TYPE_NO_PAYLOAD;
return POLICY_INVALIDATION_TYPE_NORMAL;
}
bool CloudPolicyInvalidator::GetInvalidationsEnabled() {
if (!invalidations_enabled_)
return false;
// If invalidations have been enabled for less than the grace period, then
// consider invalidations to be disabled for metrics reporting.
base::TimeDelta elapsed = clock_->Now() - invalidations_enabled_time_;
return elapsed.InSeconds() >= kInvalidationGracePeriod;
}
} // namespace policy
|
//
// $Id$
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2008 Spielberg Family Center for Applied Proteomics
// Cedars Sinai Medical Center, Los Angeles, California 90048
// Copyright 2008 Vanderbilt University - Nashville, TN 37232
//
// 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 "MSData.hpp"
#include "pwiz/data/msdata/SpectrumListBase.hpp"
#include "pwiz/data/msdata/ChromatogramListBase.hpp"
using System::Exception;
using System::String;
using boost::shared_ptr;
namespace b = pwiz::msdata;
namespace pwiz {
namespace CLI {
namespace msdata {
/// <summary>
/// version information for the msdata namespace
/// </summary>
public ref class Version
{
public:
static int Major() {return pwiz::msdata::Version::Major();}
static int Minor() {return pwiz::msdata::Version::Minor();}
static int Revision() {return pwiz::msdata::Version::Revision();}
static System::String^ LastModified() {return ToSystemString(pwiz::msdata::Version::LastModified());}
static System::String^ ToString() {return ToSystemString(pwiz::msdata::Version::str());}
};
FileContent::FileContent()
: ParamContainer(new b::FileContent())
{owner_ = nullptr; base_ = static_cast<b::FileContent*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
SourceFile::SourceFile()
: ParamContainer(new b::SourceFile())
{base_ = new boost::shared_ptr<b::SourceFile>(static_cast<b::SourceFile*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
SourceFile::SourceFile(System::String^ _id)
: ParamContainer(new b::SourceFile(ToStdString(_id)))
{base_ = new boost::shared_ptr<b::SourceFile>(static_cast<b::SourceFile*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
SourceFile::SourceFile(System::String^ _id, System::String^ _name)
: ParamContainer(new b::SourceFile(ToStdString(_id), ToStdString(_name)))
{base_ = new boost::shared_ptr<b::SourceFile>(static_cast<b::SourceFile*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
SourceFile::SourceFile(System::String^ _id, System::String^ _name, System::String^ _location)
: ParamContainer(new b::SourceFile(ToStdString(_id), ToStdString(_name), ToStdString(_location)))
{base_ = new boost::shared_ptr<b::SourceFile>(static_cast<b::SourceFile*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
System::String^ SourceFile::id::get() {return ToSystemString((*base_)->id);}
void SourceFile::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
System::String^ SourceFile::name::get() {return ToSystemString((*base_)->name);}
void SourceFile::name::set(System::String^ value) {(*base_)->name = ToStdString(value);}
System::String^ SourceFile::location::get() {return ToSystemString((*base_)->location);}
void SourceFile::location::set(System::String^ value) {(*base_)->location = ToStdString(value);}
bool SourceFile::empty()
{
return (*base_)->empty();
}
Contact::Contact()
: ParamContainer(new b::Contact())
{owner_ = nullptr; base_ = static_cast<b::Contact*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
FileDescription::FileDescription()
: base_(new b::FileDescription())
{owner_ = nullptr; LOG_CONSTRUCT(__FUNCTION__)}
FileContent^ FileDescription::fileContent::get() {return gcnew FileContent(&base_->fileContent, this);}
SourceFileList^ FileDescription::sourceFiles::get() {return gcnew SourceFileList(&base_->sourceFilePtrs, this);}
ContactList^ FileDescription::contacts::get() {return gcnew ContactList(&base_->contacts, this);}
bool FileDescription::empty()
{
return base_->empty();
}
Sample::Sample()
: ParamContainer(new b::Sample())
{base_ = new boost::shared_ptr<b::Sample>(static_cast<b::Sample*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
Sample::Sample(System::String^ _id)
: ParamContainer(new b::Sample(ToStdString(_id)))
{base_ = new boost::shared_ptr<b::Sample>(static_cast<b::Sample*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
Sample::Sample(System::String^ _id, System::String^ _name)
: ParamContainer(new b::Sample(ToStdString(_id), ToStdString(_name)))
{base_ = new boost::shared_ptr<b::Sample>(static_cast<b::Sample*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
System::String^ Sample::id::get() {return ToSystemString((*base_)->id);}
void Sample::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
System::String^ Sample::name::get() {return ToSystemString((*base_)->name);}
void Sample::name::set(System::String^ value) {(*base_)->name = ToStdString(value);}
bool Sample::empty()
{
return (*base_)->empty();
}
Component::Component()
: ParamContainer(new b::Component())
{owner_ = nullptr; base_ = static_cast<b::Component*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
Component::Component(ComponentType type, int order)
: ParamContainer(new b::Component((b::ComponentType) type, order))
{owner_ = nullptr; base_ = static_cast<b::Component*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
Component::Component(CVID cvid, int order)
: ParamContainer(new b::Component((pwiz::cv::CVID) cvid, order))
{owner_ = nullptr; base_ = static_cast<b::Component*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
ComponentType Component::type::get() {return (ComponentType) base_->type;}
void Component::type::set(ComponentType value) {base_->type = (pwiz::msdata::ComponentType) value;}
int Component::order::get() {return base_->order;}
void Component::order::set(int value) {base_->order = value;}
void Component::define(CVID cvid, int order)
{
base_->define((pwiz::cv::CVID) cvid, order);
}
bool Component::empty()
{
return base_->empty();
}
ComponentList::ComponentList()
: ComponentBaseList(new b::ComponentList())
{owner_ = nullptr; base_ = static_cast<b::ComponentList*>(ComponentBaseList::base_); LOG_CONSTRUCT(__FUNCTION__)}
Component^ ComponentList::source(int index)
{
return gcnew Component(&base_->source((size_t) index), this);
}
Component^ ComponentList::analyzer(int index)
{
return gcnew Component(&base_->analyzer((size_t) index), this);
}
Component^ ComponentList::detector(int index)
{
return gcnew Component(&base_->detector((size_t) index), this);
}
Software::Software()
: base_(new boost::shared_ptr<b::Software>(new b::Software()))
{LOG_CONSTRUCT(__FUNCTION__)}
Software::Software(System::String^ _id)
: base_(new boost::shared_ptr<b::Software>(new b::Software(ToStdString(_id))))
{LOG_CONSTRUCT(__FUNCTION__)}
Software::Software(System::String^ _id, CVParam^ _softwareParam, System::String^ _softwareParamVersion)
: base_(new boost::shared_ptr<b::Software>(new b::Software(ToStdString(_id), _softwareParam->base(), ToStdString(_softwareParamVersion))))
{LOG_CONSTRUCT(__FUNCTION__)}
System::String^ Software::id::get() {return ToSystemString((*base_)->id);}
void Software::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
System::String^ Software::version::get() {return ToSystemString((*base_)->version);}
void Software::version::set(System::String^ value) {(*base_)->version = ToStdString(value);}
bool Software::empty()
{
return (*base_)->empty();
}
InstrumentConfiguration::InstrumentConfiguration()
: ParamContainer(new b::InstrumentConfiguration())
{base_ = new boost::shared_ptr<b::InstrumentConfiguration>(static_cast<b::InstrumentConfiguration*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
InstrumentConfiguration::InstrumentConfiguration(System::String^ _id)
: ParamContainer(new b::InstrumentConfiguration(ToStdString(_id)))
{base_ = new boost::shared_ptr<b::InstrumentConfiguration>(static_cast<b::InstrumentConfiguration*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
System::String^ InstrumentConfiguration::id::get() {return ToSystemString((*base_)->id);}
void InstrumentConfiguration::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
ComponentList^ InstrumentConfiguration::componentList::get() {return gcnew ComponentList(&(*base_)->componentList, this);}
Software^ InstrumentConfiguration::software::get() {return NATIVE_SHARED_PTR_TO_CLI(pwiz::msdata::SoftwarePtr, Software, (*base_)->softwarePtr);}
bool InstrumentConfiguration::empty()
{
return (*base_)->empty();
}
ProcessingMethod::ProcessingMethod()
: ParamContainer(new b::ProcessingMethod())
{owner_ = nullptr; base_ = static_cast<b::ProcessingMethod*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
int ProcessingMethod::order::get() {return base_->order;}
void ProcessingMethod::order::set(int value) {base_->order = value;}
Software^ ProcessingMethod::software::get() {return NATIVE_SHARED_PTR_TO_CLI(pwiz::msdata::SoftwarePtr, Software, base_->softwarePtr);}
bool ProcessingMethod::empty()
{
return base_->empty();
}
DataProcessing::DataProcessing()
: base_(new boost::shared_ptr<b::DataProcessing>(new b::DataProcessing()))
{LOG_CONSTRUCT(__FUNCTION__)}
DataProcessing::DataProcessing(System::String^ _id)
: base_(new boost::shared_ptr<b::DataProcessing>(new b::DataProcessing(ToStdString(_id))))
{LOG_CONSTRUCT(__FUNCTION__)}
System::String^ DataProcessing::id::get() {return ToSystemString((*base_)->id);}
void DataProcessing::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
ProcessingMethodList^ DataProcessing::processingMethods::get() {return gcnew ProcessingMethodList(&(*base_)->processingMethods, this);}
bool DataProcessing::empty()
{
return (*base_)->empty();
}
Target::Target()
: ParamContainer(new b::Target())
{owner_ = nullptr; base_ = static_cast<b::Target*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
ScanSettings::ScanSettings()
: base_(new boost::shared_ptr<b::ScanSettings>(new b::ScanSettings()))
{LOG_CONSTRUCT(__FUNCTION__)}
ScanSettings::ScanSettings(System::String^ _id)
: base_(new boost::shared_ptr<b::ScanSettings>(new b::ScanSettings(ToStdString(_id))))
{LOG_CONSTRUCT(__FUNCTION__)}
System::String^ ScanSettings::id::get() {return ToSystemString((*base_)->id);}
void ScanSettings::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
SourceFileList^ ScanSettings::sourceFiles::get() {return gcnew SourceFileList(&(*base_)->sourceFilePtrs, this);}
TargetList^ ScanSettings::targets::get() {return gcnew TargetList(&(*base_)->targets, this);}
bool ScanSettings::empty()
{
return (*base_)->empty();
}
ScanWindowList^ Scan::scanWindows::get() {return gcnew ScanWindowList(&base_->scanWindows, this);}
ScanWindow::ScanWindow()
: ParamContainer(new b::ScanWindow())
{owner_ = nullptr; base_ = static_cast<b::ScanWindow*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
ScanWindow::ScanWindow(double low, double high, CVID unit)
: ParamContainer(new b::ScanWindow(low, high, (pwiz::cv::CVID) unit))
{owner_ = nullptr; base_ = static_cast<b::ScanWindow*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
Scan::Scan()
: ParamContainer(new b::Scan())
{owner_ = nullptr; base_ = static_cast<b::Scan*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
SourceFile^ Scan::sourceFile::get() {return NATIVE_SHARED_PTR_TO_CLI(b::SourceFilePtr, SourceFile, base_->sourceFilePtr);}
void Scan::sourceFile::set(SourceFile^ value) {base_->sourceFilePtr = CLI_TO_NATIVE_SHARED_PTR(b::SourceFilePtr, value);}
System::String^ Scan::spectrumID::get() {return ToSystemString(base_->spectrumID);}
void Scan::spectrumID::set(System::String^ value) {base_->spectrumID = ToStdString(value);}
System::String^ Scan::externalSpectrumID::get() {return ToSystemString(base_->externalSpectrumID);}
void Scan::externalSpectrumID::set(System::String^ value) {base_->externalSpectrumID = ToStdString(value);}
InstrumentConfiguration^ Scan::instrumentConfiguration::get() {return NATIVE_SHARED_PTR_TO_CLI(pwiz::msdata::InstrumentConfigurationPtr, InstrumentConfiguration, base_->instrumentConfigurationPtr);}
void Scan::instrumentConfiguration::set(InstrumentConfiguration^ value) {base_->instrumentConfigurationPtr = CLI_TO_NATIVE_SHARED_PTR(b::InstrumentConfigurationPtr, value);}
bool Scan::empty()
{
return base_->empty();
}
ScanList::ScanList()
: ParamContainer(new b::ScanList())
{owner_ = nullptr; base_ = static_cast<b::ScanList*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
Scans^ ScanList::scans::get() {return gcnew Scans(&base_->scans, this);}
bool ScanList::empty()
{
return base_->empty();
}
IsolationWindow::IsolationWindow()
: ParamContainer(new b::IsolationWindow())
{owner_ = nullptr; base_ = static_cast<b::IsolationWindow*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
SelectedIon::SelectedIon()
: ParamContainer(new b::SelectedIon())
{owner_ = nullptr; base_ = static_cast<b::SelectedIon*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
Activation::Activation()
: ParamContainer(new b::Activation())
{owner_ = nullptr; base_ = static_cast<b::Activation*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
Precursor::Precursor()
: ParamContainer(new b::Precursor())
{owner_ = nullptr; base_ = static_cast<b::Precursor*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
SourceFile^ Precursor::sourceFile::get() {return NATIVE_SHARED_PTR_TO_CLI(b::SourceFilePtr, SourceFile, base_->sourceFilePtr);}
void Precursor::sourceFile::set(SourceFile^ value) {base_->sourceFilePtr = CLI_TO_NATIVE_SHARED_PTR(b::SourceFilePtr, value);}
System::String^ Precursor::spectrumID::get() {return ToSystemString(base_->spectrumID);}
void Precursor::spectrumID::set(System::String^ value) {base_->spectrumID = ToStdString(value);}
System::String^ Precursor::externalSpectrumID::get() {return ToSystemString(base_->externalSpectrumID);}
void Precursor::externalSpectrumID::set(System::String^ value) {base_->externalSpectrumID = ToStdString(value);}
IsolationWindow^ Precursor::isolationWindow::get() {return gcnew IsolationWindow(&base_->isolationWindow, this);}
void Precursor::isolationWindow::set(IsolationWindow^ value) {base_->isolationWindow = *value->base_;}
SelectedIonList^ Precursor::selectedIons::get() {return gcnew SelectedIonList(&base_->selectedIons, this);}
Activation^ Precursor::activation::get() {return gcnew Activation(&base_->activation, this);}
void Precursor::activation::set(Activation^ value) {base_->activation = *value->base_;}
bool Precursor::empty()
{
return base_->empty();
}
Product::Product()
: base_(new b::Product())
{owner_ = nullptr; LOG_CONSTRUCT(__FUNCTION__)}
IsolationWindow^ Product::isolationWindow::get() {return gcnew IsolationWindow(&base_->isolationWindow, this);}
void Product::isolationWindow::set(IsolationWindow^ value) {base_->isolationWindow = *value->base_;}
bool Product::empty()
{
return base_->empty();
}
BinaryDataArray::BinaryDataArray()
: ParamContainer(new b::BinaryDataArray())
{base_ = new boost::shared_ptr<b::BinaryDataArray>(static_cast<b::BinaryDataArray*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
DataProcessing^ BinaryDataArray::dataProcessing::get() {return NATIVE_SHARED_PTR_TO_CLI(b::DataProcessingPtr, DataProcessing, (*base_)->dataProcessingPtr);}
void BinaryDataArray::dataProcessing::set(DataProcessing^ value) {(*base_)->dataProcessingPtr = CLI_TO_NATIVE_SHARED_PTR(b::DataProcessingPtr, value);}
pwiz::CLI::util::BinaryData^ BinaryDataArray::data::get() {return gcnew pwiz::CLI::util::BinaryData(base_, this);}
void BinaryDataArray::data::set(pwiz::CLI::util::BinaryData^ value) {(*base_)->data = (*value->base_)->data;}
bool BinaryDataArray::empty()
{
return (*base_)->empty();
}
MZIntensityPair::MZIntensityPair()
: base_(new pwiz::msdata::MZIntensityPair()) {LOG_CONSTRUCT(__FUNCTION__)}
MZIntensityPair::MZIntensityPair(double mz, double intensity)
: base_(new pwiz::msdata::MZIntensityPair(mz, intensity)) {LOG_CONSTRUCT(__FUNCTION__)}
double MZIntensityPair::mz::get() {return base_->mz;}
void MZIntensityPair::mz::set(double value) {base_->mz = value;}
double MZIntensityPair::intensity::get() {return base_->intensity;}
void MZIntensityPair::intensity::set(double value) {base_->intensity = value;}
TimeIntensityPair::TimeIntensityPair()
: base_(new pwiz::msdata::TimeIntensityPair()) {LOG_CONSTRUCT(__FUNCTION__)}
TimeIntensityPair::TimeIntensityPair(double mz, double intensity)
: base_(new pwiz::msdata::TimeIntensityPair(mz, intensity)) {LOG_CONSTRUCT(__FUNCTION__)}
double TimeIntensityPair::time::get() {return base_->time;}
void TimeIntensityPair::time::set(double value) {base_->time = value;}
double TimeIntensityPair::intensity::get() {return base_->intensity;}
void TimeIntensityPair::intensity::set(double value) {base_->intensity = value;}
SpectrumIdentity::SpectrumIdentity()
: base_(new pwiz::msdata::SpectrumIdentity()) {LOG_CONSTRUCT(__FUNCTION__)}
int SpectrumIdentity::index::get() {return (int) base_->index;}
void SpectrumIdentity::index::set(int value) {base_->index = (size_t) value;}
System::String^ SpectrumIdentity::id::get() {return ToSystemString(base_->id);}
void SpectrumIdentity::id::set(System::String^ value) {base_->id = ToStdString(value);}
System::String^ SpectrumIdentity::spotID::get() {return ToSystemString(base_->spotID);}
void SpectrumIdentity::spotID::set(System::String^ value) {base_->spotID = ToStdString(value);}
System::UInt64 SpectrumIdentity::sourceFilePosition::get() {return (System::UInt64) base_->sourceFilePosition;}
void SpectrumIdentity::sourceFilePosition::set(System::UInt64 value) {base_->sourceFilePosition = (size_t) value;}
ChromatogramIdentity::ChromatogramIdentity()
: base_(new pwiz::msdata::ChromatogramIdentity()) {LOG_CONSTRUCT(__FUNCTION__)}
int ChromatogramIdentity::index::get() {return (int) base_->index;}
void ChromatogramIdentity::index::set(int value) {base_->index = (size_t) value;}
System::String^ ChromatogramIdentity::id::get() {return ToSystemString(base_->id);}
void ChromatogramIdentity::id::set(System::String^ value) {base_->id = ToStdString(value);}
System::UInt64 ChromatogramIdentity::sourceFilePosition::get() {return (System::UInt64) base_->sourceFilePosition;}
void ChromatogramIdentity::sourceFilePosition::set(System::UInt64 value) {base_->sourceFilePosition = (size_t) value;}
Spectrum::Spectrum()
: ParamContainer(new b::Spectrum())
{base_ = new boost::shared_ptr<b::Spectrum>(static_cast<b::Spectrum*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
int Spectrum::index::get() {return (int) (*base_)->index;}
void Spectrum::index::set(int value) {(*base_)->index = (size_t) value;}
System::String^ Spectrum::id::get() {return ToSystemString((*base_)->id);}
void Spectrum::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
System::String^ Spectrum::spotID::get() {return ToSystemString((*base_)->spotID);}
void Spectrum::spotID::set(System::String^ value) {(*base_)->spotID = ToStdString(value);}
System::UInt64 Spectrum::sourceFilePosition::get() {return (System::UInt64) (*base_)->sourceFilePosition;}
void Spectrum::sourceFilePosition::set(System::UInt64 value) {(*base_)->sourceFilePosition = (size_t) value;}
System::UInt64 Spectrum::defaultArrayLength::get() {return (System::UInt64) (*base_)->defaultArrayLength;}
void Spectrum::defaultArrayLength::set(System::UInt64 value) {(*base_)->defaultArrayLength = (size_t) value;}
DataProcessing^ Spectrum::dataProcessing::get() {return NATIVE_SHARED_PTR_TO_CLI(b::DataProcessingPtr, DataProcessing, (*base_)->dataProcessingPtr);}
void Spectrum::dataProcessing::set(DataProcessing^ value) {(*base_)->dataProcessingPtr = CLI_TO_NATIVE_SHARED_PTR(b::DataProcessingPtr, value);}
SourceFile^ Spectrum::sourceFile::get() {return NATIVE_SHARED_PTR_TO_CLI(b::SourceFilePtr, SourceFile, (*base_)->sourceFilePtr);}
void Spectrum::sourceFile::set(SourceFile^ value) {(*base_)->sourceFilePtr = CLI_TO_NATIVE_SHARED_PTR(b::SourceFilePtr, value);}
ScanList^ Spectrum::scanList::get() {return gcnew ScanList(&(*base_)->scanList, this);}
PrecursorList^ Spectrum::precursors::get() {return gcnew PrecursorList(&(*base_)->precursors, this);}
ProductList^ Spectrum::products::get() {return gcnew ProductList(&(*base_)->products, this);}
BinaryDataArrayList^ Spectrum::binaryDataArrays::get() {return gcnew BinaryDataArrayList(&(*base_)->binaryDataArrayPtrs, this);}
void Spectrum::binaryDataArrays::set(BinaryDataArrayList^ value) {(*base_)->binaryDataArrayPtrs = *value->base_;}
void Spectrum::getMZIntensityPairs(MZIntensityPairList^% output)
{
try
{
std::vector<b::MZIntensityPair>* p = new std::vector<b::MZIntensityPair>();
(*base_)->getMZIntensityPairs(*p);
output = gcnew MZIntensityPairList(p);
}
CATCH_AND_FORWARD
}
BinaryDataArray^ Spectrum::getMZArray()
{
try
{
auto arrayPtr = (*base_)->getMZArray();
return arrayPtr ? gcnew BinaryDataArray(new b::BinaryDataArrayPtr(arrayPtr)) : nullptr;
}
CATCH_AND_FORWARD
}
BinaryDataArray^ Spectrum::getIntensityArray()
{
try
{
auto arrayPtr = (*base_)->getIntensityArray();
return arrayPtr ? gcnew BinaryDataArray(new b::BinaryDataArrayPtr(arrayPtr)) : nullptr;
}
CATCH_AND_FORWARD
}
BinaryDataArray^ Spectrum::getArrayByCVID(CVID arrayType)
{
try
{
auto arrayPtr = (*base_)->getArrayByCVID((pwiz::cv::CVID) arrayType);
return arrayPtr ? gcnew BinaryDataArray(new b::BinaryDataArrayPtr(arrayPtr)) : nullptr;
}
CATCH_AND_FORWARD
}
void Spectrum::setMZIntensityPairs(MZIntensityPairList^ input)
{
(*base_)->setMZIntensityPairs(*input->base_, (pwiz::cv::CVID) CVID::CVID_Unknown);
}
void Spectrum::setMZIntensityPairs(MZIntensityPairList^ input, CVID intensityUnits)
{
(*base_)->setMZIntensityPairs(*input->base_, (pwiz::cv::CVID) intensityUnits);
}
void Spectrum::setMZIntensityArrays(System::Collections::Generic::List<double>^ mzArray,
System::Collections::Generic::List<double>^ intensityArray)
{
setMZIntensityArrays(mzArray, intensityArray, CVID::CVID_Unknown);
}
void Spectrum::setMZIntensityArrays(System::Collections::Generic::List<double>^ mzArray,
System::Collections::Generic::List<double>^ intensityArray,
CVID intensityUnits)
{
std::vector<double> mzVector;
if (mzArray->Count > 0)
{
cli::array<double>^ mzArray2 = mzArray->ToArray();
pin_ptr<double> mzArrayPinPtr = &mzArray2[0];
double* mzArrayBegin = (double*) mzArrayPinPtr;
mzVector.assign(mzArrayBegin, mzArrayBegin + mzArray2->Length);
}
std::vector<double> intensityVector;
if (intensityArray->Count > 0)
{
cli::array<double>^ intensityArray2 = intensityArray->ToArray();
pin_ptr<double> intensityArrayPinPtr = &intensityArray2[0];
double* intensityArrayBegin = (double*) intensityArrayPinPtr;
intensityVector.assign(intensityArrayBegin, intensityArrayBegin + intensityArray2->Length);
}
(*base_)->setMZIntensityArrays(mzVector, intensityVector, (pwiz::cv::CVID) intensityUnits);
}
bool Spectrum::empty()
{
return (*base_)->empty();
}
Chromatogram::Chromatogram()
: ParamContainer(new b::Chromatogram())
{base_ = new boost::shared_ptr<b::Chromatogram>(static_cast<b::Chromatogram*>(ParamContainer::base_)); LOG_CONSTRUCT(__FUNCTION__)}
int Chromatogram::index::get() {return (int) (*base_)->index;}
void Chromatogram::index::set(int value) {(*base_)->index = (size_t) value;}
System::String^ Chromatogram::id::get() {return ToSystemString((*base_)->id);}
void Chromatogram::id::set(System::String^ value) {(*base_)->id = ToStdString(value);}
System::UInt64 Chromatogram::sourceFilePosition::get() {return (System::UInt64) (*base_)->sourceFilePosition;}
void Chromatogram::sourceFilePosition::set(System::UInt64 value) {(*base_)->sourceFilePosition = (size_t) value;}
System::UInt64 Chromatogram::defaultArrayLength::get() {return (*base_)->defaultArrayLength;}
void Chromatogram::defaultArrayLength::set(System::UInt64 value) {(*base_)->defaultArrayLength = (size_t) value;}
DataProcessing^ Chromatogram::dataProcessing::get() {return NATIVE_SHARED_PTR_TO_CLI(pwiz::msdata::DataProcessingPtr, DataProcessing, (*base_)->dataProcessingPtr);}
//void set(DataProcessing^ value) {(*base_)->dataProcessingPtr = *value->base_;}
Precursor^ Chromatogram::precursor::get() {return gcnew Precursor(&(*base_)->precursor);}
void Chromatogram::precursor::set(Precursor^ value) {(*base_)->precursor = *value->base_;}
Product^ Chromatogram::product::get() {return gcnew Product(&(*base_)->product);}
void Chromatogram::product::set(Product^ value) {(*base_)->product = *value->base_;}
BinaryDataArrayList^ Chromatogram::binaryDataArrays::get() {return gcnew BinaryDataArrayList(&(*base_)->binaryDataArrayPtrs, this);}
void Chromatogram::binaryDataArrays::set(BinaryDataArrayList^ value) {(*base_)->binaryDataArrayPtrs = *value->base_;}
void Chromatogram::getTimeIntensityPairs(TimeIntensityPairList^% output)
{
try
{
std::vector<b::TimeIntensityPair>* p = new std::vector<b::TimeIntensityPair>();
(*base_)->getTimeIntensityPairs(*p);
output = gcnew TimeIntensityPairList(p);
}
CATCH_AND_FORWARD
}
void Chromatogram::setTimeIntensityPairs(TimeIntensityPairList^ input, CVID timeUnits, CVID intensityUnits)
{
try {(*base_)->setTimeIntensityPairs(*input->base_, (pwiz::cv::CVID) timeUnits, (pwiz::cv::CVID) intensityUnits);} CATCH_AND_FORWARD
}
BinaryDataArray^ Chromatogram::getTimeArray()
{
try
{
auto arrayPtr = (*base_)->getTimeArray();
return arrayPtr ? gcnew BinaryDataArray(new b::BinaryDataArrayPtr(arrayPtr)) : nullptr;
}
CATCH_AND_FORWARD
}
BinaryDataArray^ Chromatogram::getIntensityArray()
{
try
{
auto arrayPtr = (*base_)->getIntensityArray();
return arrayPtr ? gcnew BinaryDataArray(new b::BinaryDataArrayPtr(arrayPtr)) : nullptr;
}
CATCH_AND_FORWARD
}
bool Chromatogram::empty()
{
return (*base_)->empty();
}
int SpectrumList::size()
{
try{return (int) (*base_)->size();} CATCH_AND_FORWARD
}
bool SpectrumList::empty()
{
try{return (*base_)->empty();} CATCH_AND_FORWARD
}
SpectrumIdentity^ SpectrumList::spectrumIdentity(int index)
{
try {return gcnew SpectrumIdentity(&const_cast<b::SpectrumIdentity&>((*base_)->spectrumIdentity((size_t) index)), this);} CATCH_AND_FORWARD
}
int SpectrumList::find(System::String^ id)
{
try {return (int) (*base_)->find(ToStdString(id));} CATCH_AND_FORWARD
}
int SpectrumList::findAbbreviated(System::String^ abbreviatedId)
{
return findAbbreviated(abbreviatedId, '.');
}
int SpectrumList::findAbbreviated(System::String^ abbreviatedId, char delimiter)
{
try {return (int) (*base_)->findAbbreviated(ToStdString(abbreviatedId), delimiter);} CATCH_AND_FORWARD
}
IndexList^ SpectrumList::findNameValue(System::String^ name, System::String^ value)
{
try
{
b::IndexList indexList = (*base_)->findNameValue(ToStdString(name), ToStdString(value));
std::vector<size_t>* ownedIndexListPtr = new std::vector<size_t>();
ownedIndexListPtr->swap(indexList);
return gcnew IndexList(ownedIndexListPtr);
}
CATCH_AND_FORWARD
}
Spectrum^ SpectrumList::spectrum(int index)
{
return spectrum(index, false);
}
Spectrum^ SpectrumList::spectrum(int index, bool getBinaryData)
{
try {return gcnew Spectrum(new b::SpectrumPtr((*base_)->spectrum((size_t) index, getBinaryData)));} CATCH_AND_FORWARD
}
Spectrum^ SpectrumList::spectrum(int index, DetailLevel detailLevel)
{
try {return gcnew Spectrum(new b::SpectrumPtr((*base_)->spectrum((size_t) index, (b::DetailLevel)detailLevel)));} CATCH_AND_FORWARD
}
DataProcessing^ SpectrumList::dataProcessing()
{
const shared_ptr<const b::DataProcessing> cdp = (*base_)->dataProcessingPtr();
if (!cdp.get())
return nullptr;
b::DataProcessingPtr dp = boost::const_pointer_cast<b::DataProcessing>(cdp);
return NATIVE_SHARED_PTR_TO_CLI(b::DataProcessingPtr, DataProcessing, dp);
}
void SpectrumList::setDataProcessing(DataProcessing^ dp)
{
b::SpectrumListBase* sl = dynamic_cast<b::SpectrumListBase*>((*base_).get());
if (sl) sl->setDataProcessingPtr(CLI_TO_NATIVE_SHARED_PTR(b::DataProcessingPtr, dp));
}
SpectrumListSimple::SpectrumListSimple()
: SpectrumList(new boost::shared_ptr<b::SpectrumList>(new b::SpectrumListSimple()))
{base_ = reinterpret_cast<boost::shared_ptr<b::SpectrumListSimple>*>(SpectrumList::base_); LOG_CONSTRUCT(__FUNCTION__)}
Spectra^ SpectrumListSimple::spectra::get() {return gcnew Spectra(&(*base_)->spectra, this);}
void SpectrumListSimple::spectra::set(Spectra^ value) {(*base_)->spectra = *value->base_;}
int SpectrumListSimple::size()
{
try {return (*base_)->size();} CATCH_AND_FORWARD
}
bool SpectrumListSimple::empty()
{
try {return (*base_)->empty();} CATCH_AND_FORWARD
}
SpectrumIdentity^ SpectrumListSimple::spectrumIdentity(int index)
{
try {return gcnew SpectrumIdentity(&const_cast<b::SpectrumIdentity&>((*base_)->spectrumIdentity((size_t) index)), this);} CATCH_AND_FORWARD
}
Spectrum^ SpectrumListSimple::spectrum(int index)
{
return spectrum(index, false);
}
Spectrum^ SpectrumListSimple::spectrum(int index, bool getBinaryData)
{
try {return gcnew Spectrum(new b::SpectrumPtr((*base_)->spectrum((size_t) index, getBinaryData)));} CATCH_AND_FORWARD
}
int ChromatogramList::size()
{
try {return (int) (*base_)->size();} CATCH_AND_FORWARD
}
bool ChromatogramList::empty()
{
try {return (*base_)->empty();} CATCH_AND_FORWARD
}
ChromatogramIdentity^ ChromatogramList::chromatogramIdentity(int index)
{
try {return gcnew ChromatogramIdentity(&const_cast<b::ChromatogramIdentity&>((*base_)->chromatogramIdentity((size_t) index)), this);} CATCH_AND_FORWARD
}
int ChromatogramList::find(System::String^ id)
{
try {return (int) (*base_)->find(ToStdString(id));} CATCH_AND_FORWARD
}
Chromatogram^ ChromatogramList::chromatogram(int index)
{
return chromatogram(index, false);
}
Chromatogram^ ChromatogramList::chromatogram(int index, bool getBinaryData)
{
try {return gcnew Chromatogram(new b::ChromatogramPtr((*base_)->chromatogram((size_t) index, getBinaryData)));} CATCH_AND_FORWARD
}
Chromatogram^ ChromatogramList::chromatogram(int index, DetailLevel detailLevel)
{
try { return gcnew Chromatogram(new b::ChromatogramPtr((*base_)->chromatogram((size_t)index, (b::DetailLevel) detailLevel))); } CATCH_AND_FORWARD
}
DataProcessing^ ChromatogramList::dataProcessing()
{
const shared_ptr<const b::DataProcessing> cdp = (*base_)->dataProcessingPtr();
if (!cdp.get())
return nullptr;
b::DataProcessingPtr dp = boost::const_pointer_cast<b::DataProcessing>(cdp);
return NATIVE_SHARED_PTR_TO_CLI(b::DataProcessingPtr, DataProcessing, dp);
}
void ChromatogramList::setDataProcessing(DataProcessing^ dp)
{
b::ChromatogramListBase* cl = dynamic_cast<b::ChromatogramListBase*>((*base_).get());
if (cl) cl->setDataProcessingPtr(CLI_TO_NATIVE_SHARED_PTR(b::DataProcessingPtr, dp));
}
ChromatogramListSimple::ChromatogramListSimple()
: ChromatogramList(new boost::shared_ptr<b::ChromatogramList>(new b::ChromatogramListSimple()))
{base_ = reinterpret_cast<boost::shared_ptr<b::ChromatogramListSimple>*>(ChromatogramList::base_); LOG_CONSTRUCT(__FUNCTION__)}
Chromatograms^ ChromatogramListSimple::chromatograms::get() {return gcnew Chromatograms(&(*base_)->chromatograms, this);}
void ChromatogramListSimple::chromatograms::set(Chromatograms^ value) {(*base_)->chromatograms = *value->base_;}
int ChromatogramListSimple::size()
{
try {return (*base_)->size();} CATCH_AND_FORWARD
}
bool ChromatogramListSimple::empty()
{
try {return (*base_)->empty();} CATCH_AND_FORWARD
}
ChromatogramIdentity^ ChromatogramListSimple::chromatogramIdentity(int index)
{
try {return gcnew ChromatogramIdentity(&const_cast<b::ChromatogramIdentity&>((*base_)->chromatogramIdentity((size_t) index)), this);} CATCH_AND_FORWARD
}
Chromatogram^ ChromatogramListSimple::chromatogram(int index)
{
return chromatogram(index, false);
}
Chromatogram^ ChromatogramListSimple::chromatogram(int index, bool getBinaryData)
{
try {return gcnew Chromatogram(new b::ChromatogramPtr((*base_)->chromatogram((size_t) index, getBinaryData)));} CATCH_AND_FORWARD
}
Run::Run()
: ParamContainer(new b::Run())
{owner_ = nullptr; base_ = static_cast<b::Run*>(ParamContainer::base_); LOG_CONSTRUCT(__FUNCTION__)}
System::String^ Run::id::get() {return ToSystemString(base_->id);}
void Run::id::set(System::String^ value) {base_->id = ToStdString(value);}
InstrumentConfiguration^ Run::defaultInstrumentConfiguration::get() {return NATIVE_SHARED_PTR_TO_CLI(b::InstrumentConfigurationPtr, InstrumentConfiguration, base_->defaultInstrumentConfigurationPtr);}
void Run::defaultInstrumentConfiguration::set(InstrumentConfiguration^ value) {base_->defaultInstrumentConfigurationPtr = CLI_TO_NATIVE_SHARED_PTR(b::InstrumentConfigurationPtr, value);}
Sample^ Run::sample::get() {return NATIVE_SHARED_PTR_TO_CLI(b::SamplePtr, Sample, base_->samplePtr);}
void Run::sample::set(Sample^ value) {base_->samplePtr = CLI_TO_NATIVE_SHARED_PTR(b::SamplePtr, value);}
System::String^ Run::startTimeStamp::get() {return ToSystemString(base_->startTimeStamp);}
void Run::startTimeStamp::set(System::String^ value) {base_->startTimeStamp = ToStdString(value);}
SourceFile^ Run::defaultSourceFile::get() {return NATIVE_SHARED_PTR_TO_CLI(b::SourceFilePtr, SourceFile, base_->defaultSourceFilePtr);}
void Run::defaultSourceFile::set(SourceFile^ value) {base_->defaultSourceFilePtr = CLI_TO_NATIVE_SHARED_PTR(b::SourceFilePtr, value);}
SpectrumList^ Run::spectrumList::get() {return NATIVE_OWNED_SHARED_PTR_TO_CLI(b::SpectrumListPtr, SpectrumList, base_->spectrumListPtr, this);}
void Run::spectrumList::set(SpectrumList^ value) {base_->spectrumListPtr = *value->base_;}
ChromatogramList^ Run::chromatogramList::get() {return NATIVE_OWNED_SHARED_PTR_TO_CLI(b::ChromatogramListPtr, ChromatogramList, base_->chromatogramListPtr, this);}
void Run::chromatogramList::set(ChromatogramList^ value) {base_->chromatogramListPtr = *value->base_;}
bool Run::empty()
{
return base_->empty();
}
MSData::MSData(boost::shared_ptr<b::MSData>* base)
: base_(base)
{LOG_CONSTRUCT("MSData")}
MSData::~MSData()
{
LOG_DESTRUCT("MSData", true) SAFEDELETE(base_);
// MCC: forcing garbage collection is the best way I know of to try to clean up
// reclaimable SpectrumList handles which hold on to SpectrumListPtrs
System::GC::Collect();
System::GC::WaitForPendingFinalizers();
}
MSData::!MSData() {LOG_FINALIZE("MSData") delete this;}
b::MSData& MSData::base() {return **base_;}
MSData::MSData()
: base_(new boost::shared_ptr<b::MSData>(new b::MSData))
{LOG_CONSTRUCT(__FUNCTION__)}
System::String^ MSData::accession::get() {return ToSystemString(base().accession);}
void MSData::accession::set(System::String^ value) {base().accession = ToStdString(value);}
System::String^ MSData::id::get() {return ToSystemString(base().id);}
void MSData::id::set(System::String^ value) {base().id = ToStdString(value);}
CVList^ MSData::cvs::get() {return gcnew CVList(&base().cvs, this);}
void MSData::cvs::set(CVList^ value) {cvs->assign(value);}
FileDescription^ MSData::fileDescription::get() {return gcnew FileDescription(&base().fileDescription, this);}
void MSData::fileDescription::set(FileDescription^ value) {base().fileDescription = *value->base_;}
ParamGroupList^ MSData::paramGroups::get() {return gcnew ParamGroupList(&base().paramGroupPtrs, this);}
void MSData::paramGroups::set(ParamGroupList^ value) {paramGroups->assign(value);}
SampleList^ MSData::samples::get() {return gcnew SampleList(&base().samplePtrs, this);}
void MSData::samples::set(SampleList^ value) {samples->assign(value);}
InstrumentConfigurationList^ MSData::instrumentConfigurationList::get() {return gcnew InstrumentConfigurationList(&base().instrumentConfigurationPtrs, this);}
void MSData::instrumentConfigurationList::set(InstrumentConfigurationList^ value) {instrumentConfigurationList->assign(value);}
SoftwareList^ MSData::softwareList::get() {return gcnew SoftwareList(&base().softwarePtrs, this);}
void MSData::softwareList::set(SoftwareList^ value) {softwareList->assign(value);}
DataProcessingList^ MSData::dataProcessingList::get() {return gcnew DataProcessingList(&base().dataProcessingPtrs, this);}
void MSData::dataProcessingList::set(DataProcessingList^ value) {dataProcessingList->assign(value);}
ScanSettingsList^ MSData::scanSettingsList::get() {return gcnew ScanSettingsList(&base().scanSettingsPtrs, this);}
void MSData::scanSettingsList::set(ScanSettingsList^ value) {scanSettingsList->assign(value);}
Run^ MSData::run::get() {return gcnew Run(&base().run, this);}
//void set(Run^ value) {(*base_)->run = *value->base_;}
bool MSData::empty() {return base().empty();}
System::String^ MSData::version() {return ToSystemString(base().version());}
System::String^ id::value(System::String^ id, System::String^ name)
{
try {return ToSystemString(b::id::value(ToStdString(id), ToStdString(name)));} CATCH_AND_FORWARD
}
CVID id::getDefaultNativeIDFormat(MSData^ msd)
{
try {return (CVID) b::id::getDefaultNativeIDFormat(msd->base());} CATCH_AND_FORWARD
}
System::String^ id::translateScanNumberToNativeID(CVID nativeIDFormat, System::String^ scanNumber)
{
try {return ToSystemString(b::id::translateScanNumberToNativeID((b::CVID) nativeIDFormat, ToStdString(scanNumber)));} CATCH_AND_FORWARD
}
System::String^ id::translateNativeIDToScanNumber(CVID nativeIDFormat, System::String^ id)
{
try {return ToSystemString(b::id::translateNativeIDToScanNumber((b::CVID) nativeIDFormat, ToStdString(id)));} CATCH_AND_FORWARD
}
System::String^ id::abbreviate(System::String^ id)
{
try {return ToSystemString(b::id::abbreviate(ToStdString(id)));} CATCH_AND_FORWARD
}
System::String^ id::abbreviate(System::String^ id, char delimiter)
{
try {return ToSystemString(b::id::abbreviate(ToStdString(id), delimiter));} CATCH_AND_FORWARD
}
} // namespace msdata
} // namespace CLI
} // namespace pwiz
|
// -*- mode: c++ -*-
/**************************************************************************
* Copyright(c) 1998-1999, 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 *
* appear 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. *
**************************************************************************/
//#include "AliCDBManager.h"
#include "AliEMCALRawUtils.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliAltroBuffer.h"
#include "AliRawReader.h"
#include "AliCaloRawStreamV3.h"
#include "AliDAQ.h"
#include "AliEMCALRecParam.h"
#include "AliEMCALLoader.h"
#include "AliEMCALGeometry.h"
#include "AliEMCALDigit.h"
#include "AliEMCALRawDigit.h"
#include "AliEMCAL.h"
#include "AliCaloCalibPedestal.h"
#include "AliCaloBunchInfo.h"
#include "AliCaloFitResults.h"
#include "AliEMCALTriggerRawDigitMaker.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliEMCALTriggerData.h"
#include "AliCaloConstants.h"
#include "AliCaloRawAnalyzer.h"
#include "AliCaloRawAnalyzerFactory.h"
#include "AliEMCALRawResponse.h"
using namespace CALO;
using namespace EMCAL;
using std::vector;
/// \cond CLASSIMP
ClassImp(AliEMCALRawUtils) ;
/// \endcond
///
/// Constructor. Set up fitting algorightm, geometry
/// and default parameter values.
///
AliEMCALRawUtils::AliEMCALRawUtils( Algo::fitAlgorithm fitAlgo) : fNoiseThreshold(3),
fNPedSamples(4),
fGeom(0),
fOption(""),
fRemoveBadChannels(kFALSE),
fFittingAlgorithm(fitAlgo),
fTimeMin(-1.),
fTimeMax(1.),
fUseFALTRO(kTRUE),
fUseL1Phase(kTRUE),
fRawAnalyzer(0),
fTriggerRawDigitMaker(0x0)
{
SetFittingAlgorithm(fitAlgo);
const TObjArray* maps = AliEMCALRecParam::GetMappings();
if(!maps) AliFatal("Cannot retrieve ALTRO mappings!!");
for(Int_t i = 0; i < 4; i++)
{
fMapping[i] = (AliAltroMapping*)maps->At(i);
}
AliRunLoader *rl = AliRunLoader::Instance();
if (rl && rl->GetAliRun())
{
AliEMCAL * emcal = dynamic_cast<AliEMCAL*>(rl->GetAliRun()->GetDetector("EMCAL"));
if(emcal)
{
fGeom = emcal->GetGeometry();
}
else
{
AliDebug(1, Form("Using default geometry in raw reco"));
fGeom = AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
}
}
else
{
AliDebug(1, Form("Using default geometry in raw reco"));
fGeom = AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
}
if(!fGeom) AliFatal(Form("Could not get geometry!"));
fTriggerRawDigitMaker = new AliEMCALTriggerRawDigitMaker();
}
///
/// Destructor.
///
AliEMCALRawUtils::~AliEMCALRawUtils()
{
delete fRawAnalyzer;
delete fTriggerRawDigitMaker;
}
///
/// Convert digits of the current event to raw data.
///
void AliEMCALRawUtils::Digits2Raw()
{
AliRunLoader *rl = AliRunLoader::Instance();
AliEMCALLoader *loader = dynamic_cast<AliEMCALLoader*>(rl->GetDetectorLoader("EMCAL"));
loader->LoadDigits("EMCAL");
loader->GetEvent();
TClonesArray* digits = loader->Digits() ;
if (!digits)
{
AliWarning("No digits found !");
return;
}
static const Int_t nDDL = 20*2; // 20 SM for EMCal + DCal hardcoded for now. Buffers allocated dynamically, when needed, so just need an upper limit here
AliAltroBuffer* buffers[nDDL];
for (Int_t i=0; i < nDDL; i++)
buffers[i] = 0;
TArrayI adcValuesLow ( TIMEBINS );
TArrayI adcValuesHigh( TIMEBINS );
// Loop over digits (assume ordered digits)
for (Int_t iDigit = 0; iDigit < digits->GetEntries(); iDigit++)
{
AliEMCALDigit* digit = dynamic_cast<AliEMCALDigit *>(digits->At(iDigit)) ;
if(!digit)
{
AliFatal("NULL Digit");
}
else
{
if (digit->GetAmplitude() < AliEMCALRawResponse::GetRawFormatThreshold() )
{
continue;
}
// Get cell indices
Int_t nSM = 0;
Int_t nIphi = 0;
Int_t nIeta = 0;
Int_t iphi = 0;
Int_t ieta = 0;
Int_t nModule = 0;
fGeom->GetCellIndex(digit->GetId(), nSM, nModule, nIphi, nIeta);
fGeom->GetCellPhiEtaIndexInSModule(nSM, nModule, nIphi, nIeta,iphi, ieta) ;
//----------------------------------------------------------------------
//
// Online mapping and numbering is the same for EMCal and DCal SMs but:
// - DCal odd SM (13,15,17) has online cols: 16-47; offline cols 0-31.
// - Even DCal SMs have the same numbering online and offline 0-31.
// - DCal 1/3 SM (18,19), online rows 16-23; offline rows 0-7
//
// In the next lines shift the online cols or rows depending on the
// SM to match the offline mapping.
// Apply the shifts (inverse to those in Raw2Digits):
fGeom->ShiftOfflineToOnlineCellIndexes(nSM, iphi, ieta);
//
//----------------------------------------------------------------------
// Check which is the RCU, 0 or 1, of the cell.
// *** RCU corresponds to DDL in a SuperModule ***
Int_t iRCU = -111;
if ( 0<=iphi&&iphi< 8 ) iRCU=0; // first cable row
else if ( 8<=iphi&&iphi<16 && 0<=ieta&&ieta<24 ) iRCU=0; // first half;
else if ( 8<=iphi&&iphi<16 && 24<=ieta&&ieta<48 ) iRCU=1; // second half;
else if ( 16<=iphi&&iphi<24 ) iRCU=1; // third cable row
if (nSM%2==1) iRCU = 1 - iRCU; // swap for odd=C side, to allow us to cable both sides the same
if (iRCU<0)
Fatal("Digits2Raw()","Non-existent RCU/DDL number: %d", iRCU);
// Which DDL?
Int_t iDDL = NRCUSPERMODULE*nSM + iRCU;
if (iDDL < 0 || iDDL >= nDDL)
{
Fatal("Digits2Raw()","Non-existent DDL board number: %d", iDDL);
}
else
{
if (buffers[iDDL] == 0)
{
// open new file and write dummy header
TString fileName = AliDAQ::DdlFileName("EMCAL",iDDL);
//Select mapping file RCU0A, RCU0C, RCU1A, RCU1C
Int_t iRCUside=iRCU+(nSM%2)*2;
//iRCU=0 and even (0) SM -> RCU0A.data 0
//iRCU=1 and even (0) SM -> RCU1A.data 1
//iRCU=0 and odd (1) SM -> RCU0C.data 2
//iRCU=1 and odd (1) SM -> RCU1C.data 3
buffers[iDDL] = new AliAltroBuffer(fileName.Data(),fMapping[iRCUside]);
buffers[iDDL]->WriteDataHeader(kTRUE, kFALSE); //Dummy;
}
// out of time range signal (?)
if ( digit->GetTime() > TIMEBINMAX )
{
AliInfo("Signal is out of time range.\n");
buffers[iDDL]->FillBuffer((Int_t)digit->GetAmplitude());
buffers[iDDL]->FillBuffer( TIMEBINS ); // time bin
buffers[iDDL]->FillBuffer(3); // bunch length
buffers[iDDL]->WriteTrailer(3, ieta, iphi, nSM); // trailer
// calculate the time response function
}
else
{
Bool_t lowgain = AliEMCALRawResponse::RawSampledResponse(digit->GetTime(), digit->GetAmplitude(),
adcValuesHigh.GetArray(), adcValuesLow.GetArray()) ;
buffers[iDDL]->WriteChannel(ieta, iphi, 1, TIMEBINS, adcValuesHigh.GetArray(), AliEMCALRawResponse::GetRawFormatThreshold() );
if (lowgain)
buffers[iDDL]->WriteChannel(ieta, iphi, 0, TIMEBINS, adcValuesLow .GetArray(), AliEMCALRawResponse::GetRawFormatThreshold() );
}
}// iDDL under the limits
}// Digit exists
}// Digit loop
// Write headers and close files
for (Int_t i=0; i < nDDL; i++)
{
if (buffers[i])
{
buffers[i]->Flush();
buffers[i]->WriteDataHeader(kFALSE, kFALSE);
delete buffers[i];
}
}
loader->UnloadDigits();
}
///
/// Create the digit from raw fit and add it to the list of digits
///
void AliEMCALRawUtils::AddDigit(TClonesArray *digitsArr, Int_t id, Int_t lowGain,
Float_t amp, Float_t time, Float_t chi2, Int_t ndf)
{
AliEMCALDigit *digit = 0, *tmpdigit = 0;
TIter nextdigit(digitsArr);
while (digit == 0 && (tmpdigit = (AliEMCALDigit*) nextdigit()))
{
if (tmpdigit->GetId() == id) digit = tmpdigit;
}
// No digit existed for this tower; create one.
if (!digit)
{
Int_t type = AliEMCALDigit::kHG; // use enum in AliEMCALDigit
if (lowGain)
{
amp *= HGLGFACTOR;
type = AliEMCALDigit::kLGnoHG;
}
Int_t idigit = digitsArr->GetEntries();
new((*digitsArr)[idigit]) AliEMCALDigit( -1, -1, id, amp, time, type, idigit, chi2, ndf);
AliDebug(2,Form("Add digit Id %d for the first time, type %d", id, type));
}// digit added first time.
// A digit already exists, check range
// (use high gain if signal < cut value, otherwise low gain)
else
{
if (lowGain)
{
// New digit is low gain
if ( digit->GetAmplitude() > OVERFLOWCUT )
{
// Use if previously stored (HG) digit is out of range
digit->SetAmplitude( HGLGFACTOR * amp);
digit->SetTime(time);
digit->SetType(AliEMCALDigit::kLG);
AliDebug(2,Form("Add LG digit ID %d for the second time, type %d", digit->GetId(), digit->GetType()));
}
} // New low gain digit
else
{
// New digit is high gain
if ( amp < OVERFLOWCUT )
{
// New digit is high gain; use if not out of range
digit->SetAmplitude(amp);
digit->SetTime(time);
digit->SetType(AliEMCALDigit::kHG);
AliDebug(2,Form("Add HG digit ID %d for the second time, type %d", digit->GetId(), digit->GetType()));
}
else
{
// HG out of range, just change flag value to show that HG did exist
digit->SetType(AliEMCALDigit::kLG);
AliDebug(2,Form("Change LG digit to HG, ID %d, type %d", digit->GetId(), digit->GetType()));
}
} // New high gain digit
}// Digit existed replace it
}
///
/// Conversion of raw data to digits.
///
void AliEMCALRawUtils::Raw2Digits(AliRawReader* reader,TClonesArray *digitsArr, const AliCaloCalibPedestal* pedbadmap,
TClonesArray *digitsTRG, TClonesArray *trgData)
{
if ( digitsArr) digitsArr->Clear("C");
if (!digitsArr) { Error("Raw2Digits", "no digits found !") ; return ; }
if (!reader) { Error("Raw2Digits", "no raw reader found !"); return ; }
AliEMCALTriggerSTURawStream inSTU(reader);
AliCaloRawStreamV3 in(reader,"EMCAL",fMapping);
reader->Select("EMCAL",0,AliDAQ::GetFirstSTUDDL()-1);
fTriggerRawDigitMaker->Reset();
fTriggerRawDigitMaker->SetIO(reader, in, inSTU, digitsTRG, trgData);
fRawAnalyzer->SetIsZeroSuppressed(true); // TMP - should use stream->IsZeroSuppressed(), or altro cfg registers later
Int_t lowGain = 0;
Int_t caloFlag = 0; // low, high gain, or TRU, or LED ref.
Float_t bcTimePhaseCorr = 0; // for BC-based L1 phase correction, Run1 data
Int_t bcMod4 = (reader->GetBCID() % 4); // LHC uses 40 MHz, EMCal uses 10 MHz clock
//AliCDBManager* man = AliCDBManager::Instance();
//Int_t runNumber = man->GetRun();
Int_t runNumber = reader->GetRunNumber();
// Apply this shift for Run1 data
if ((runNumber > 130850 && runNumber < 200000) && (bcMod4==0 || bcMod4==1))
bcTimePhaseCorr = -1e-7; // subtract 100 ns for certain BC values
while (in.NextDDL())
{
while (in.NextChannel())
{
caloFlag = in.GetCaloFlag();
if ( caloFlag > 2 ) continue; // Work with ALTRO and FALTRO
Int_t sm = in.GetModule() ;
Int_t row = in.GetRow () ;
Int_t column = in.GetColumn() ;
//----------------------------------------------------------------------
//
// Online mapping and numbering is the same for EMCal and DCal SMs but:
// - DCal odd SM (13,15,17) has online cols: 16-47; offline cols 0-31.
// - Even DCal SMs have the same numbering online and offline 0-31.
// - DCal 1/3 SM (18,19), online rows 16-23; offline rows 0-7
//
// In the next lines shift the online cols or rows depending on the
// SM to match the offline mapping.
//
fGeom->ShiftOnlineToOfflineCellIndexes(sm, row, column);
//
//---------------------------------------------------------------------
if ( caloFlag < 2 && fRemoveBadChannels && pedbadmap->IsBadChannel(sm, column, row) )
{
continue;
}
vector<AliCaloBunchInfo> bunchlist;
while (in.NextBunch())
{
bunchlist.push_back( AliCaloBunchInfo(in.GetStartTimeBin(), in.GetBunchLength(), in.GetSignals() ) );
}
if (bunchlist.size() == 0) continue;
if ( caloFlag < 2 )
{
// ALTRO
Int_t id = fGeom->GetAbsCellIdFromCellIndexes(sm, row, column) ;
lowGain = in.IsLowGain();
if(fUseL1Phase)
fRawAnalyzer->SetL1Phase( in.GetL1Phase() );
else
fRawAnalyzer->SetL1Phase( 0 );
AliCaloFitResults res = fRawAnalyzer->Evaluate( bunchlist, in.GetAltroCFG1(), in.GetAltroCFG2());
if(res.GetAmp() >= fNoiseThreshold )
{
AddDigit(digitsArr, id, lowGain, res.GetAmp(), res.GetTime()+bcTimePhaseCorr, res.GetChi2(), res.GetNdf() );
}
}// ALTRO
else if ( fUseFALTRO )
{// Fake ALTRO
fTriggerRawDigitMaker->Add( bunchlist );
}// Fake ALTRO
} // End while over channel
} // End while over DDL's, of input stream
fTriggerRawDigitMaker->PostProcess();
TrimDigits(digitsArr);
}
///
/// Remove entries with LGnoHG (unphysical), out of time window, and too bad chi2.
///
void AliEMCALRawUtils::TrimDigits(TClonesArray *digitsArr)
{
AliEMCALDigit *digit = 0;
Int_t n = 0;
Int_t nDigits = digitsArr->GetEntriesFast();
TIter nextdigit(digitsArr);
while ((digit = (AliEMCALDigit*) nextdigit()))
{
if (digit->GetType() == AliEMCALDigit::kLGnoHG)
{
AliDebug(1,Form("Remove digit with id %d, LGnoHG",digit->GetId()));
digitsArr->Remove(digit);
}
else if(fTimeMin > digit->GetTime() || fTimeMax < digit->GetTime())
{
digitsArr->Remove(digit);
AliDebug(1,Form("Remove digit with id %d, Bad Time %e",digit->GetId(), digit->GetTime()));
}
else if (0 > digit->GetChi2())
{
digitsArr->Remove(digit);
AliDebug(1,Form("Remove digit with id %d, Bad Chi2 %e",digit->GetId(), digit->GetChi2()));
}
else
{
digit->SetIndexInList(n);
n++;
}
}//while
digitsArr->Compress();
AliDebug(1,Form("N Digits before trimming : %d; after array compression %d",nDigits,digitsArr->GetEntriesFast()));
}
///
/// Select which fitting algo should be used.
///
void AliEMCALRawUtils::SetFittingAlgorithm(Int_t fitAlgo)
{
delete fRawAnalyzer; // delete doesn't do anything if the pointer is 0x0
fRawAnalyzer = AliCaloRawAnalyzerFactory::CreateAnalyzer( fitAlgo );
fRawAnalyzer->SetNsampleCut(5); // requirement for fits to be done, for the new methods
fRawAnalyzer->SetOverflowCut ( OVERFLOWCUT );
fRawAnalyzer->SetAmpCut(fNoiseThreshold);
fRawAnalyzer->SetFitArrayCut(fNoiseThreshold);
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include <string>
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "content/browser/download/save_file_manager.h"
#include "content/browser/download/save_package.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/public/common/url_constants.h"
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
#include "net/test/url_request/url_request_mock_http_job.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace content {
#define FPL FILE_PATH_LITERAL
#define HTML_EXTENSION ".html"
#if defined(OS_WIN)
#define FPL_HTML_EXTENSION L".html"
#else
#define FPL_HTML_EXTENSION ".html"
#endif
namespace {
// This constant copied from save_package.cc.
#if defined(OS_WIN)
const uint32_t kMaxFilePathLength = MAX_PATH - 1;
const uint32_t kMaxFileNameLength = MAX_PATH - 1;
#elif defined(OS_POSIX)
const uint32_t kMaxFilePathLength = PATH_MAX - 1;
const uint32_t kMaxFileNameLength = NAME_MAX;
#endif
bool HasOrdinalNumber(const base::FilePath::StringType& filename) {
base::FilePath::StringType::size_type r_paren_index =
filename.rfind(FPL(')'));
base::FilePath::StringType::size_type l_paren_index =
filename.rfind(FPL('('));
if (l_paren_index >= r_paren_index)
return false;
for (base::FilePath::StringType::size_type i = l_paren_index + 1;
i != r_paren_index; ++i) {
if (!base::IsAsciiDigit(filename[i]))
return false;
}
return true;
}
} // namespace
class SavePackageTest : public RenderViewHostImplTestHarness {
public:
bool GetGeneratedFilename(bool need_success_generate_filename,
const std::string& disposition,
const std::string& url,
bool need_htm_ext,
base::FilePath::StringType* generated_name) {
SavePackage* save_package;
if (need_success_generate_filename)
save_package = save_package_success_.get();
else
save_package = save_package_fail_.get();
return save_package->GenerateFileName(disposition, GURL(url), need_htm_ext,
generated_name);
}
base::FilePath EnsureHtmlExtension(const base::FilePath& name) {
return SavePackage::EnsureHtmlExtension(name);
}
base::FilePath EnsureMimeExtension(const base::FilePath& name,
const std::string& content_mime_type) {
return SavePackage::EnsureMimeExtension(name, content_mime_type);
}
GURL GetUrlToBeSaved() {
return SavePackage::GetUrlToBeSaved(save_package_success_->web_contents());
}
protected:
void SetUp() override {
RenderViewHostImplTestHarness::SetUp();
// Do the initialization in SetUp so contents() is initialized by
// RenderViewHostImplTestHarness::SetUp.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
save_package_success_ = new SavePackage(
contents(), SAVE_PAGE_TYPE_AS_COMPLETE_HTML,
temp_dir_.GetPath().AppendASCII("testfile" HTML_EXTENSION),
temp_dir_.GetPath().AppendASCII("testfile_files"));
base::FilePath::StringType long_file_name = GetLongFileName();
save_package_fail_ = new SavePackage(
contents(), SAVE_PAGE_TYPE_AS_COMPLETE_HTML,
temp_dir_.GetPath().Append(long_file_name + FPL_HTML_EXTENSION),
temp_dir_.GetPath().Append(long_file_name + FPL("_files")));
}
BrowserContext* CreateBrowserContext() override {
// This method is invoked after the browser threads have been created and
// obviously before the BrowserContext is created. This is the correct time
// to create a ResourceDispatcherHostImpl so that our SavePackage objects
// can initialize correctly.
rdh_.reset(new ResourceDispatcherHostImpl);
// Initialize the SaveFileManager instance which we will use for the tests.
save_file_manager_ = new SaveFileManager();
return RenderViewHostImplTestHarness::CreateBrowserContext();
}
void TearDown() override {
DeleteContents();
base::RunLoop().RunUntilIdle();
save_package_success_ = nullptr;
save_package_fail_ = nullptr;
rdh_.reset();
RenderViewHostImplTestHarness::TearDown();
}
// Returns a path that is *almost* kMaxFilePathLength long
base::FilePath::StringType GetLongFileName() const {
size_t target_length =
kMaxFilePathLength - 9 - temp_dir_.GetPath().value().length();
return base::FilePath::StringType(target_length, FPL('a'));
}
private:
// SavePackage for successfully generating file name.
scoped_refptr<SavePackage> save_package_success_;
// SavePackage for failed generating file name.
scoped_refptr<SavePackage> save_package_fail_;
base::ScopedTempDir temp_dir_;
std::unique_ptr<ResourceDispatcherHostImpl> rdh_;
scoped_refptr<SaveFileManager> save_file_manager_;
};
static const struct {
const char* disposition;
const char* url;
const base::FilePath::CharType* expected_name;
bool need_htm_ext;
} kGeneratedFiles[] = {
// We mainly focus on testing duplicated names here, since retrieving file
// name from disposition and url has been tested in DownloadManagerTest.
// No useful information in disposition or URL, use default.
{"1.html", "http://www.savepage.com/",
FPL("saved_resource") FPL_HTML_EXTENSION, true},
// No duplicate occurs.
{"filename=1.css", "http://www.savepage.com", FPL("1.css"), false},
// No duplicate occurs.
{"filename=1.js", "http://www.savepage.com", FPL("1.js"), false},
// Append numbers for duplicated names.
{"filename=1.css", "http://www.savepage.com", FPL("1(1).css"), false},
// No duplicate occurs.
{"filename=1(1).js", "http://www.savepage.com", FPL("1(1).js"), false},
// Append numbers for duplicated names.
{"filename=1.css", "http://www.savepage.com", FPL("1(2).css"), false},
// Change number for duplicated names.
{"filename=1(1).css", "http://www.savepage.com", FPL("1(3).css"), false},
// No duplicate occurs.
{"filename=1(11).css", "http://www.savepage.com", FPL("1(11).css"), false},
// Test for case-insensitive file names.
{"filename=readme.txt", "http://www.savepage.com",
FPL("readme.txt"), false},
{"filename=readme.TXT", "http://www.savepage.com",
FPL("readme(1).TXT"), false},
{"filename=READme.txt", "http://www.savepage.com",
FPL("readme(2).txt"), false},
{"filename=Readme(1).txt", "http://www.savepage.com",
FPL("readme(3).txt"), false},
};
TEST_F(SavePackageTest, TestSuccessfullyGenerateSavePackageFilename) {
for (size_t i = 0; i < arraysize(kGeneratedFiles); ++i) {
base::FilePath::StringType file_name;
bool ok = GetGeneratedFilename(true,
kGeneratedFiles[i].disposition,
kGeneratedFiles[i].url,
kGeneratedFiles[i].need_htm_ext,
&file_name);
ASSERT_TRUE(ok);
EXPECT_EQ(kGeneratedFiles[i].expected_name, file_name);
}
}
TEST_F(SavePackageTest, TestUnSuccessfullyGenerateSavePackageFilename) {
for (size_t i = 0; i < arraysize(kGeneratedFiles); ++i) {
base::FilePath::StringType file_name;
bool ok = GetGeneratedFilename(false,
kGeneratedFiles[i].disposition,
kGeneratedFiles[i].url,
kGeneratedFiles[i].need_htm_ext,
&file_name);
ASSERT_FALSE(ok);
}
}
// Crashing on Windows, see http://crbug.com/79365
#if defined(OS_WIN)
#define MAYBE_TestLongSavePackageFilename DISABLED_TestLongSavePackageFilename
#else
#define MAYBE_TestLongSavePackageFilename TestLongSavePackageFilename
#endif
TEST_F(SavePackageTest, MAYBE_TestLongSavePackageFilename) {
const std::string base_url("http://www.google.com/");
const base::FilePath::StringType long_file_name =
GetLongFileName() + FPL(".css");
const std::string url =
base_url + base::FilePath(long_file_name).AsUTF8Unsafe();
base::FilePath::StringType filename;
// Test that the filename is successfully shortened to fit.
ASSERT_TRUE(GetGeneratedFilename(true, std::string(), url, false, &filename));
EXPECT_TRUE(filename.length() < long_file_name.length());
EXPECT_FALSE(HasOrdinalNumber(filename));
// Test that the filename is successfully shortened to fit, and gets an
// an ordinal appended.
ASSERT_TRUE(GetGeneratedFilename(true, std::string(), url, false, &filename));
EXPECT_TRUE(filename.length() < long_file_name.length());
EXPECT_TRUE(HasOrdinalNumber(filename));
// Test that the filename is successfully shortened to fit, and gets a
// different ordinal appended.
base::FilePath::StringType filename2;
ASSERT_TRUE(
GetGeneratedFilename(true, std::string(), url, false, &filename2));
EXPECT_TRUE(filename2.length() < long_file_name.length());
EXPECT_TRUE(HasOrdinalNumber(filename2));
EXPECT_NE(filename, filename2);
}
// Crashing on Windows, see http://crbug.com/79365
#if defined(OS_WIN)
#define MAYBE_TestLongSafePureFilename DISABLED_TestLongSafePureFilename
#else
#define MAYBE_TestLongSafePureFilename TestLongSafePureFilename
#endif
TEST_F(SavePackageTest, MAYBE_TestLongSafePureFilename) {
const base::FilePath save_dir(FPL("test_dir"));
const base::FilePath::StringType ext(FPL_HTML_EXTENSION);
base::FilePath::StringType filename = GetLongFileName();
// Test that the filename + extension doesn't exceed kMaxFileNameLength
uint32_t max_path = SavePackage::GetMaxPathLengthForDirectory(save_dir);
ASSERT_TRUE(SavePackage::TruncateBaseNameToFitPathConstraints(
save_dir, ext, max_path, &filename));
EXPECT_TRUE(filename.length() <= kMaxFileNameLength-ext.length());
}
static const struct {
const base::FilePath::CharType* page_title;
const base::FilePath::CharType* expected_name;
} kExtensionTestCases[] = {
// Extension is preserved if it is already proper for HTML.
{FPL("filename.html"), FPL("filename.html")},
{FPL("filename.HTML"), FPL("filename.HTML")},
{FPL("filename.XHTML"), FPL("filename.XHTML")},
{FPL("filename.xhtml"), FPL("filename.xhtml")},
{FPL("filename.htm"), FPL("filename.htm")},
// ".htm" is added if the extension is improper for HTML.
{FPL("hello.world"), FPL("hello.world") FPL_HTML_EXTENSION},
{FPL("hello.txt"), FPL("hello.txt") FPL_HTML_EXTENSION},
{FPL("is.html.good"), FPL("is.html.good") FPL_HTML_EXTENSION},
// ".htm" is added if the name doesn't have an extension.
{FPL("helloworld"), FPL("helloworld") FPL_HTML_EXTENSION},
{FPL("helloworld."), FPL("helloworld.") FPL_HTML_EXTENSION},
};
// Crashing on Windows, see http://crbug.com/79365
#if defined(OS_WIN)
#define MAYBE_TestEnsureHtmlExtension DISABLED_TestEnsureHtmlExtension
#else
#define MAYBE_TestEnsureHtmlExtension TestEnsureHtmlExtension
#endif
TEST_F(SavePackageTest, MAYBE_TestEnsureHtmlExtension) {
for (size_t i = 0; i < arraysize(kExtensionTestCases); ++i) {
base::FilePath original = base::FilePath(kExtensionTestCases[i].page_title);
base::FilePath expected =
base::FilePath(kExtensionTestCases[i].expected_name);
base::FilePath actual = EnsureHtmlExtension(original);
EXPECT_EQ(expected.value(), actual.value()) << "Failed for page title: " <<
kExtensionTestCases[i].page_title;
}
}
// Crashing on Windows, see http://crbug.com/79365
#if defined(OS_WIN)
#define MAYBE_TestEnsureMimeExtension DISABLED_TestEnsureMimeExtension
#else
#define MAYBE_TestEnsureMimeExtension TestEnsureMimeExtension
#endif
TEST_F(SavePackageTest, MAYBE_TestEnsureMimeExtension) {
static const struct {
const base::FilePath::CharType* page_title;
const base::FilePath::CharType* expected_name;
const char* contents_mime_type;
} kExtensionTests[] = {
{ FPL("filename.html"), FPL("filename.html"), "text/html" },
{ FPL("filename.htm"), FPL("filename.htm"), "text/html" },
{ FPL("filename.xhtml"), FPL("filename.xhtml"), "text/html" },
#if defined(OS_WIN)
{ FPL("filename"), FPL("filename.htm"), "text/html" },
#else // defined(OS_WIN)
{ FPL("filename"), FPL("filename.html"), "text/html" },
#endif // defined(OS_WIN)
{ FPL("filename.html"), FPL("filename.html"), "text/xml" },
{ FPL("filename.xml"), FPL("filename.xml"), "text/xml" },
{ FPL("filename"), FPL("filename.xml"), "text/xml" },
{ FPL("filename.xhtml"), FPL("filename.xhtml"),
"application/xhtml+xml" },
{ FPL("filename.html"), FPL("filename.html"),
"application/xhtml+xml" },
{ FPL("filename"), FPL("filename.xhtml"), "application/xhtml+xml" },
{ FPL("filename.txt"), FPL("filename.txt"), "text/plain" },
{ FPL("filename"), FPL("filename.txt"), "text/plain" },
{ FPL("filename.css"), FPL("filename.css"), "text/css" },
{ FPL("filename"), FPL("filename.css"), "text/css" },
{ FPL("filename.abc"), FPL("filename.abc"), "unknown/unknown" },
{ FPL("filename"), FPL("filename"), "unknown/unknown" },
};
for (uint32_t i = 0; i < arraysize(kExtensionTests); ++i) {
base::FilePath original = base::FilePath(kExtensionTests[i].page_title);
base::FilePath expected = base::FilePath(kExtensionTests[i].expected_name);
std::string mime_type(kExtensionTests[i].contents_mime_type);
base::FilePath actual = EnsureMimeExtension(original, mime_type);
EXPECT_EQ(expected.value(), actual.value()) << "Failed for page title: " <<
kExtensionTests[i].page_title << " MIME:" << mime_type;
}
}
// Test that the suggested names generated by SavePackage are reasonable:
// If the name is a URL, retrieve only the path component since the path name
// generation code will turn the entire URL into the file name leading to bad
// extension names. For example, a page with no title and a URL:
// http://www.foo.com/a/path/name.txt will turn into file:
// "http www.foo.com a path name.txt", when we want to save it as "name.txt".
static const struct SuggestedSaveNameTestCase {
const char* page_url;
const base::string16 page_title;
const base::FilePath::CharType* expected_name;
bool ensure_html_extension;
} kSuggestedSaveNames[] = {
// Title overrides the URL.
{ "http://foo.com",
base::ASCIIToUTF16("A page title"),
FPL("A page title") FPL_HTML_EXTENSION,
true
},
// Extension is preserved.
{ "http://foo.com",
base::ASCIIToUTF16("A page title with.ext"),
FPL("A page title with.ext"),
false
},
// If the title matches the URL, use the last component of the URL.
{ "http://foo.com/bar",
base::ASCIIToUTF16("foo.com/bar"),
FPL("bar"),
false
},
// If the title matches the URL, but there is no "filename" component,
// use the domain.
{ "http://foo.com",
base::ASCIIToUTF16("foo.com"),
FPL("foo.com"),
false
},
// Make sure fuzzy matching works.
{ "http://foo.com/bar",
base::ASCIIToUTF16("foo.com/bar"),
FPL("bar"),
false
},
// A URL-like title that does not match the title is respected in full.
{ "http://foo.com",
base::ASCIIToUTF16("http://www.foo.com/path/title.txt"),
FPL("http___www.foo.com_path_title.txt"),
false
},
};
// Crashing on Windows, see http://crbug.com/79365
#if defined(OS_WIN)
#define MAYBE_TestSuggestedSaveNames DISABLED_TestSuggestedSaveNames
#else
#define MAYBE_TestSuggestedSaveNames TestSuggestedSaveNames
#endif
TEST_F(SavePackageTest, MAYBE_TestSuggestedSaveNames) {
GURL url = net::URLRequestMockHTTPJob::GetMockUrl("save_page/a.htm");
NavigateAndCommit(url);
for (size_t i = 0; i < arraysize(kSuggestedSaveNames); ++i) {
base::FilePath save_name = SavePackage::GetSuggestedNameForSaveAs(
kSuggestedSaveNames[i].page_title,
GURL(kSuggestedSaveNames[i].page_url),
kSuggestedSaveNames[i].ensure_html_extension, std::string());
EXPECT_EQ(kSuggestedSaveNames[i].expected_name, save_name.value()) <<
"Test case " << i;
}
}
// GetUrlToBeSaved method should return correct url to be saved.
TEST_F(SavePackageTest, TestGetUrlToBeSaved) {
GURL url = net::URLRequestMockHTTPJob::GetMockUrl("save_page/a.htm");
NavigateAndCommit(url);
EXPECT_EQ(url, GetUrlToBeSaved());
}
// GetUrlToBeSaved method sould return actual url to be saved,
// instead of the displayed url used to view source of a page.
// Ex:GetUrlToBeSaved method should return http://www.google.com
// when user types view-source:http://www.google.com
TEST_F(SavePackageTest, TestGetUrlToBeSavedViewSource) {
GURL mock_url = net::URLRequestMockHTTPJob::GetMockUrl("save_page/a.htm");
GURL view_source_url =
GURL(kViewSourceScheme + std::string(":") + mock_url.spec());
GURL actual_url = net::URLRequestMockHTTPJob::GetMockUrl("save_page/a.htm");
NavigateAndCommit(view_source_url);
EXPECT_EQ(actual_url, GetUrlToBeSaved());
EXPECT_EQ(view_source_url, contents()->GetLastCommittedURL());
}
} // namespace content
|
/*
Drive.h - Library for controlling Robot Car with L298x bridge series
Created by Oladapo E. Ajala, November 13, 2018.
Released into the public domain.
Copy right InvenTech llc.
*/
#include "Arduino.h"
#include "analogWrite.h"
#include "Drive.h"
#define LOW 0
Drive::Drive(int IN1, int IN2, int IN3, int IN4)
{
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
_IN1 = IN1;
_IN2 = IN2;
_IN3 = IN3;
_IN4 = IN4;
}
bool Drive::moveForward(int speed)
{
analogWrite(_IN1, speed);
analogWrite(_IN2, LOW);
analogWrite(_IN3, speed);
analogWrite(_IN4, LOW);
return true;
}
bool Drive::moveBackward(int speed)
{
analogWrite(_IN1, LOW);
analogWrite(_IN2, speed);
analogWrite(_IN3, LOW);
analogWrite(_IN4, speed);
return true;
}
bool Drive::turnLeft(int speed)
{
analogWrite(_IN1, speed);
analogWrite(_IN2, LOW);
analogWrite(_IN3, LOW);
analogWrite(_IN4, speed);
return true;
}
bool Drive::turnRight(int speed)
{
analogWrite(_IN1, LOW);
analogWrite(_IN2, speed);
analogWrite(_IN3, speed);
analogWrite(_IN4, LOW);
return true;
}
bool Drive::stopMoving()
{
analogWrite(_IN1, LOW);
analogWrite(_IN2, LOW);
analogWrite(_IN3, LOW);
analogWrite(_IN4, LOW);
return true;
}
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_AMETSUCHI_FIXTURE_HPP
#define IROHA_AMETSUCHI_FIXTURE_HPP
#include <gtest/gtest.h>
#include <soci/postgresql/soci-postgresql.h>
#include <soci/soci.h>
#include <boost/filesystem.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "ametsuchi/impl/in_memory_block_storage_factory.hpp"
#include "ametsuchi/impl/k_times_reconnection_strategy.hpp"
#include "ametsuchi/impl/storage_impl.hpp"
#include "backend/protobuf/common_objects/proto_common_objects_factory.hpp"
#include "backend/protobuf/proto_block_json_converter.hpp"
#include "backend/protobuf/proto_permission_to_string.hpp"
#include "common/files.hpp"
#include "framework/config_helper.hpp"
#include "framework/sql_query.hpp"
#include "framework/test_logger.hpp"
#include "logger/logger.hpp"
#include "logger/logger_manager.hpp"
#include "module/irohad/common/validators_config.hpp"
#include "validators/field_validator.hpp"
namespace iroha {
namespace ametsuchi {
/**
* Class with ametsuchi initialization
*/
class AmetsuchiTest : public ::testing::Test {
public:
static void SetUpTestCase() {
ASSERT_FALSE(boost::filesystem::exists(block_store_path))
<< "Temporary block store " << block_store_path
<< " directory already exists";
factory =
std::make_shared<shared_model::proto::ProtoCommonObjectsFactory<
shared_model::validation::FieldValidator>>(
iroha::test::kTestsValidatorsConfig);
perm_converter_ =
std::make_shared<shared_model::proto::ProtoPermissionToString>();
auto converter =
std::make_shared<shared_model::proto::ProtoBlockJsonConverter>();
auto block_storage_factory =
std::make_unique<InMemoryBlockStorageFactory>();
auto reconnection_strategy_factory = std::make_unique<
iroha::ametsuchi::KTimesReconnectionStrategyFactory>(0);
StorageImpl::create(block_store_path,
pgopt_,
factory,
converter,
perm_converter_,
std::move(block_storage_factory),
std::move(reconnection_strategy_factory),
getTestLoggerManager()->getChild("Storage"))
.match([&](const auto &_storage) { storage = _storage.value; },
[](const auto &error) {
storage_logger_->error(
"Storage initialization has failed: {}", error.error);
// TODO: 2019-05-29 @muratovv find assert workaround IR-522
std::terminate();
});
sql = std::make_shared<soci::session>(*soci::factory_postgresql(),
pgopt_);
sql_query =
std::make_unique<framework::ametsuchi::SqlQuery>(*sql, factory);
}
static void TearDownTestCase() {
sql->close();
storage->dropStorage();
boost::filesystem::remove_all(block_store_path);
}
void TearDown() override {
storage->reset();
}
protected:
static std::shared_ptr<soci::session> sql;
static std::shared_ptr<shared_model::proto::ProtoCommonObjectsFactory<
shared_model::validation::FieldValidator>>
factory;
/* Since
* - both the storage and the logger config it uses are static
* - storage uses the logger at destruction
* we need to ensure the static logger config is destroyed after the
* static storage
*/
static logger::LoggerPtr storage_logger_;
static std::shared_ptr<StorageImpl> storage;
static std::unique_ptr<framework::ametsuchi::SqlQuery> sql_query;
static std::shared_ptr<shared_model::interface::PermissionToString>
perm_converter_;
// generate random valid dbname
static std::string dbname_;
static std::string pgopt_;
static std::string block_store_path;
// TODO(warchant): IR-1019 hide SQLs under some interface
// TODO igor-egorov 24-05-2019 IR-517 Refactor SQL in test
// (remove sql from here and use it from the application init funcs)
const std::string init_ = R"(
CREATE TABLE IF NOT EXISTS role (
role_id character varying(32),
PRIMARY KEY (role_id)
);
CREATE TABLE IF NOT EXISTS domain (
domain_id character varying(255),
default_role character varying(32) NOT NULL REFERENCES role(role_id),
PRIMARY KEY (domain_id)
);
CREATE TABLE IF NOT EXISTS signatory (
public_key varchar NOT NULL,
PRIMARY KEY (public_key)
);
CREATE TABLE IF NOT EXISTS account (
account_id character varying(288),
domain_id character varying(255) NOT NULL REFERENCES domain,
quorum int NOT NULL,
data JSONB,
PRIMARY KEY (account_id)
);
CREATE TABLE IF NOT EXISTS account_has_signatory (
account_id character varying(288) NOT NULL REFERENCES account,
public_key varchar NOT NULL REFERENCES signatory,
PRIMARY KEY (account_id, public_key)
);
CREATE TABLE IF NOT EXISTS peer (
public_key varchar NOT NULL,
address character varying(261) NOT NULL UNIQUE,
PRIMARY KEY (public_key)
);
CREATE TABLE IF NOT EXISTS asset (
asset_id character varying(288),
domain_id character varying(255) NOT NULL REFERENCES domain,
precision int NOT NULL,
data json,
PRIMARY KEY (asset_id)
);
CREATE TABLE IF NOT EXISTS account_has_asset (
account_id character varying(288) NOT NULL REFERENCES account,
asset_id character varying(288) NOT NULL REFERENCES asset,
amount decimal NOT NULL,
PRIMARY KEY (account_id, asset_id)
);
CREATE TABLE IF NOT EXISTS role_has_permissions (
role_id character varying(32) NOT NULL REFERENCES role,
permission_id character varying(45),
PRIMARY KEY (role_id, permission_id)
);
CREATE TABLE IF NOT EXISTS account_has_roles (
account_id character varying(288) NOT NULL REFERENCES account,
role_id character varying(32) NOT NULL REFERENCES role,
PRIMARY KEY (account_id, role_id)
);
CREATE TABLE IF NOT EXISTS account_has_grantable_permissions (
permittee_account_id character varying(288) NOT NULL REFERENCES account,
account_id character varying(288) NOT NULL REFERENCES account,
permission_id character varying(45),
PRIMARY KEY (permittee_account_id, account_id, permission_id)
);
CREATE TABLE IF NOT EXISTS position_by_hash (
hash varchar,
height bigint,
index bigint
);
CREATE TABLE IF NOT EXISTS tx_status_by_hash (
hash varchar,
status boolean
);
CREATE INDEX IF NOT EXISTS tx_status_by_hash_hash_index ON tx_status_by_hash USING hash (hash);
CREATE TABLE IF NOT EXISTS height_by_account_set (
account_id text,
height bigint
);
CREATE TABLE IF NOT EXISTS index_by_creator_height (
id serial,
creator_id text,
height bigint,
index bigint
);
CREATE TABLE IF NOT EXISTS index_by_id_height_asset (
id text,
height bigint,
asset_id text,
index bigint
);
)";
};
std::shared_ptr<shared_model::proto::ProtoCommonObjectsFactory<
shared_model::validation::FieldValidator>>
AmetsuchiTest::factory = nullptr;
std::string AmetsuchiTest::block_store_path =
(boost::filesystem::temp_directory_path()
/ boost::filesystem::unique_path())
.string();
std::string AmetsuchiTest::dbname_ = "d"
+ boost::uuids::to_string(boost::uuids::random_generator()())
.substr(0, 8);
std::string AmetsuchiTest::pgopt_ = "dbname=" + AmetsuchiTest::dbname_ + " "
+ integration_framework::getPostgresCredsOrDefault();
std::shared_ptr<shared_model::interface::PermissionToString>
AmetsuchiTest::perm_converter_ = nullptr;
std::shared_ptr<soci::session> AmetsuchiTest::sql = nullptr;
// hold the storage static logger while the static storage is alive
logger::LoggerPtr AmetsuchiTest::storage_logger_ =
getTestLoggerManager()->getChild("Storage")->getLogger();
std::shared_ptr<StorageImpl> AmetsuchiTest::storage = nullptr;
std::unique_ptr<framework::ametsuchi::SqlQuery> AmetsuchiTest::sql_query =
nullptr;
} // namespace ametsuchi
} // namespace iroha
#endif // IROHA_AMETSUCHI_FIXTURE_HPP
|
// Copyright (c) 2017-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP
#define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP
#include <cassert>
#include <memory>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <utility>
#include <vector>
#include "../config.hpp"
#include "../memory_input.hpp"
#include "../normal.hpp"
#include "../nothing.hpp"
#include "../parse.hpp"
#include "../analysis/counted.hpp"
#include "../analysis/generic.hpp"
#include "../internal/demangle.hpp"
#include "../internal/iterator.hpp"
namespace TAO_PEGTL_NAMESPACE::parse_tree
{
template< typename T >
struct basic_node
{
using node_t = T;
using children_t = std::vector< std::unique_ptr< node_t > >;
children_t children;
std::string_view type;
std::string source;
TAO_PEGTL_NAMESPACE::internal::iterator m_begin;
TAO_PEGTL_NAMESPACE::internal::iterator m_end;
// each node will be default constructed
basic_node() = default;
// no copy/move is necessary
// (nodes are always owned/handled by a std::unique_ptr)
basic_node( const basic_node& ) = delete;
basic_node( basic_node&& ) = delete;
~basic_node() = default;
// no assignment either
basic_node& operator=( const basic_node& ) = delete;
basic_node& operator=( basic_node&& ) = delete;
[[nodiscard]] bool is_root() const noexcept
{
return type.empty();
}
template< typename U >
[[nodiscard]] bool is_type() const noexcept
{
return type == TAO_PEGTL_NAMESPACE::internal::demangle< U >();
}
template< typename U >
void set_type() noexcept
{
type = TAO_PEGTL_NAMESPACE::internal::demangle< U >();
}
[[nodiscard]] position begin() const
{
return position( m_begin, source );
}
[[nodiscard]] position end() const
{
return position( m_end, source );
}
[[nodiscard]] bool has_content() const noexcept
{
return m_end.data != nullptr;
}
[[nodiscard]] std::string_view string_view() const noexcept
{
assert( has_content() );
return std::string_view( m_begin.data, m_end.data - m_begin.data );
}
[[nodiscard]] std::string string() const
{
assert( has_content() );
return std::string( m_begin.data, m_end.data );
}
template< tracking_mode P = tracking_mode::eager, typename Eol = eol::lf_crlf >
[[nodiscard]] memory_input< P, Eol > as_memory_input() const
{
assert( has_content() );
return { m_begin.data, m_end.data, source, m_begin.byte, m_begin.line, m_begin.byte_in_line };
}
template< typename... States >
void remove_content( States&&... /*unused*/ ) noexcept
{
m_end.reset();
}
// all non-root nodes are initialized by calling this method
template< typename Rule, typename Input, typename... States >
void start( const Input& in, States&&... /*unused*/ )
{
set_type< Rule >();
source = in.source();
m_begin = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() );
}
// if parsing of the rule succeeded, this method is called
template< typename Rule, typename Input, typename... States >
void success( const Input& in, States&&... /*unused*/ ) noexcept
{
m_end = TAO_PEGTL_NAMESPACE::internal::iterator( in.iterator() );
}
// if parsing of the rule failed, this method is called
template< typename Rule, typename Input, typename... States >
void failure( const Input& /*unused*/, States&&... /*unused*/ ) noexcept
{
}
// if parsing succeeded and the (optional) transform call
// did not discard the node, it is appended to its parent.
// note that "child" is the node whose Rule just succeeded
// and "*this" is the parent where the node should be appended.
template< typename... States >
void emplace_back( std::unique_ptr< node_t >&& child, States&&... /*unused*/ )
{
assert( child );
children.emplace_back( std::move( child ) );
}
};
struct node
: basic_node< node >
{
};
namespace internal
{
template< typename Node >
struct state
{
std::vector< std::unique_ptr< Node > > stack;
state()
{
emplace_back();
}
void emplace_back()
{
stack.emplace_back( std::make_unique< Node >() );
}
[[nodiscard]] std::unique_ptr< Node >& back() noexcept
{
assert( !stack.empty() );
return stack.back();
}
void pop_back() noexcept
{
assert( !stack.empty() );
return stack.pop_back();
}
};
template< typename Selector, typename... Parameters >
void transform( Parameters&&... /*unused*/ ) noexcept
{
}
// this one, if applicable, is more specialized than the above
template< typename Selector, typename Node, typename... States >
auto transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( n, st... ) ) )
-> decltype( Selector::transform( n, st... ), void() )
{
Selector::transform( n, st... );
}
template< unsigned Level, typename Analyse, template< typename... > class Selector >
struct is_leaf
: std::false_type
{
};
template< analysis::rule_type Type, template< typename... > class Selector >
struct is_leaf< 0, analysis::generic< Type >, Selector >
: std::true_type
{
};
template< analysis::rule_type Type, unsigned Count, template< typename... > class Selector >
struct is_leaf< 0, analysis::counted< Type, Count >, Selector >
: std::true_type
{
};
template< analysis::rule_type Type, typename... Rules, template< typename... > class Selector >
struct is_leaf< 0, analysis::generic< Type, Rules... >, Selector >
: std::false_type
{
};
template< analysis::rule_type Type, unsigned Count, typename... Rules, template< typename... > class Selector >
struct is_leaf< 0, analysis::counted< Type, Count, Rules... >, Selector >
: std::false_type
{
};
template< unsigned Level, typename Rule, template< typename... > class Selector >
inline constexpr bool is_unselected_leaf = !Selector< Rule >::value && is_leaf< Level, typename Rule::analyze_t, Selector >::value;
template< unsigned Level, analysis::rule_type Type, typename... Rules, template< typename... > class Selector >
struct is_leaf< Level, analysis::generic< Type, Rules... >, Selector >
: std::bool_constant< ( is_unselected_leaf< Level - 1, Rules, Selector > && ... ) >
{
};
template< unsigned Level, analysis::rule_type Type, unsigned Count, typename... Rules, template< typename... > class Selector >
struct is_leaf< Level, analysis::counted< Type, Count, Rules... >, Selector >
: std::bool_constant< ( is_unselected_leaf< Level - 1, Rules, Selector > && ... ) >
{
};
template< typename T >
struct control
{
template< typename Input, typename Tuple, std::size_t... Is >
static void start_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::start( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ) ) )
{
T::start( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... );
}
template< typename Input, typename... States >
static void start( const Input& in, States&&... st ) noexcept( noexcept( start_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) )
{
start_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() );
}
template< typename Input, typename Tuple, std::size_t... Is >
static void success_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::success( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ) ) )
{
T::success( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... );
}
template< typename Input, typename... States >
static void success( const Input& in, States&&... st ) noexcept( noexcept( success_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) )
{
success_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() );
}
template< typename Input, typename Tuple, std::size_t... Is >
static void failure_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::failure( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... ) ) )
{
T::failure( in, std::get< sizeof...( Is ) >( t ), std::get< Is >( t )... );
}
template< typename Input, typename... States >
static void failure( const Input& in, States&&... st ) noexcept( noexcept( failure_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) )
{
failure_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() );
}
template< typename Input, typename Tuple, std::size_t... Is >
static void raise_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::raise( in, std::get< Is >( t )... ) ) )
{
T::raise( in, std::get< Is >( t )... );
}
template< typename Input, typename... States >
static void raise( const Input& in, States&&... st ) noexcept( noexcept( raise_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) )
{
raise_impl( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() );
}
template< template< typename... > class Action, typename Iterator, typename Input, typename Tuple, std::size_t... Is >
static auto apply_impl( const Iterator& begin, const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::template apply< Action >( begin, in, std::get< Is >( t )... ) ) )
-> decltype( T::template apply< Action >( begin, in, std::get< Is >( t )... ) )
{
return T::template apply< Action >( begin, in, std::get< Is >( t )... );
}
template< template< typename... > class Action, typename Iterator, typename Input, typename... States >
static auto apply( const Iterator& begin, const Input& in, States&&... st ) noexcept( noexcept( apply_impl< Action >( begin, in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) )
-> decltype( apply_impl< Action >( begin, in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) )
{
return apply_impl< Action >( begin, in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() );
}
template< template< typename... > class Action, typename Input, typename Tuple, std::size_t... Is >
static auto apply0_impl( const Input& in, const Tuple& t, std::index_sequence< Is... > /*unused*/ ) noexcept( noexcept( T::template apply0< Action >( in, std::get< Is >( t )... ) ) )
-> decltype( T::template apply0< Action >( in, std::get< Is >( t )... ) )
{
return T::template apply0< Action >( in, std::get< Is >( t )... );
}
template< template< typename... > class Action, typename Input, typename... States >
static auto apply0( const Input& in, States&&... st ) noexcept( noexcept( apply0_impl< Action >( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) ) )
-> decltype( apply0_impl< Action >( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() ) )
{
return apply0_impl< Action >( in, std::tie( st... ), std::make_index_sequence< sizeof...( st ) - 1 >() );
}
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... st )
{
return T::template match< A, M, Action, Control >( in, st... );
}
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
struct make_control
{
template< typename Rule, bool, bool >
struct state_handler;
template< typename Rule >
using type = control< state_handler< Rule, Selector< Rule >::value, is_leaf< 8, typename Rule::analyze_t, Selector >::value > >;
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule >
struct make_control< Node, Selector, Control >::state_handler< Rule, false, true >
: Control< Rule >
{
template< typename Input, typename... States >
static void start( const Input& in, state< Node >& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::start( in, st... ) ) )
{
Control< Rule >::start( in, st... );
}
template< typename Input, typename... States >
static void success( const Input& in, state< Node >& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::success( in, st... ) ) )
{
Control< Rule >::success( in, st... );
}
template< typename Input, typename... States >
static void failure( const Input& in, state< Node >& /*unused*/, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) )
{
Control< Rule >::failure( in, st... );
}
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule >
struct make_control< Node, Selector, Control >::state_handler< Rule, false, false >
: Control< Rule >
{
template< typename Input, typename... States >
static void start( const Input& in, state< Node >& state, States&&... st )
{
Control< Rule >::start( in, st... );
state.emplace_back();
}
template< typename Input, typename... States >
static void success( const Input& in, state< Node >& state, States&&... st )
{
Control< Rule >::success( in, st... );
auto n = std::move( state.back() );
state.pop_back();
for( auto& c : n->children ) {
state.back()->children.emplace_back( std::move( c ) );
}
}
template< typename Input, typename... States >
static void failure( const Input& in, state< Node >& state, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) )
{
Control< Rule >::failure( in, st... );
state.pop_back();
}
};
template< typename Node, template< typename... > class Selector, template< typename... > class Control >
template< typename Rule, bool B >
struct make_control< Node, Selector, Control >::state_handler< Rule, true, B >
: Control< Rule >
{
template< typename Input, typename... States >
static void start( const Input& in, state< Node >& state, States&&... st )
{
Control< Rule >::start( in, st... );
state.emplace_back();
state.back()->template start< Rule >( in, st... );
}
template< typename Input, typename... States >
static void success( const Input& in, state< Node >& state, States&&... st )
{
Control< Rule >::success( in, st... );
auto n = std::move( state.back() );
state.pop_back();
n->template success< Rule >( in, st... );
transform< Selector< Rule > >( n, st... );
if( n ) {
state.back()->emplace_back( std::move( n ), st... );
}
}
template< typename Input, typename... States >
static void failure( const Input& in, state< Node >& state, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) && noexcept( std::declval< Node& >().template failure< Rule >( in, st... ) ) )
{
Control< Rule >::failure( in, st... );
state.back()->template failure< Rule >( in, st... );
state.pop_back();
}
};
template< typename >
using store_all = std::true_type;
template< typename >
struct selector;
template< typename T >
struct selector< std::tuple< T > >
{
using type = typename T::type;
};
template< typename... Ts >
struct selector< std::tuple< Ts... > >
{
static_assert( sizeof...( Ts ) == 0, "multiple matches found" );
using type = std::false_type;
};
template< typename T >
using selector_t = typename selector< T >::type;
template< typename Rule, typename Collection >
using select_tuple = std::conditional_t< Collection::template contains< Rule >, std::tuple< Collection >, std::tuple<> >;
} // namespace internal
template< typename Rule, typename... Collections >
using selector = internal::selector_t< decltype( std::tuple_cat( std::declval< internal::select_tuple< Rule, Collections > >()... ) ) >;
template< typename Base >
struct apply
: std::true_type
{
template< typename... Rules >
struct on
{
using type = Base;
template< typename Rule >
static constexpr bool contains = ( std::is_same_v< Rule, Rules > || ... );
};
};
struct store_content
: apply< store_content >
{};
// some nodes don't need to store their content
struct remove_content
: apply< remove_content >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->Node::remove_content( st... ) ) )
{
n->remove_content( st... );
}
};
// if a node has only one child, replace the node with its child, otherwise remove content
struct fold_one
: apply< fold_one >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.size(), n->Node::remove_content( st... ) ) )
{
if( n->children.size() == 1 ) {
n = std::move( n->children.front() );
}
else {
n->remove_content( st... );
}
}
};
// if a node has no children, discard the node, otherwise remove content
struct discard_empty
: apply< discard_empty >
{
template< typename Node, typename... States >
static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.empty(), n->Node::remove_content( st... ) ) )
{
if( n->children.empty() ) {
n.reset();
}
else {
n->remove_content( st... );
}
}
};
template< typename Rule,
typename Node,
template< typename... > class Selector = internal::store_all,
template< typename... > class Action = nothing,
template< typename... > class Control = normal,
typename Input,
typename... States >
[[nodiscard]] std::unique_ptr< Node > parse( Input&& in, States&&... st )
{
internal::state< Node > state;
if( !TAO_PEGTL_NAMESPACE::parse< Rule, Action, internal::make_control< Node, Selector, Control >::template type >( in, st..., state ) ) {
return nullptr;
}
assert( state.stack.size() == 1 );
return std::move( state.back() );
}
template< typename Rule,
template< typename... > class Selector = internal::store_all,
template< typename... > class Action = nothing,
template< typename... > class Control = normal,
typename Input,
typename... States >
[[nodiscard]] std::unique_ptr< node > parse( Input&& in, States&&... st )
{
return parse< Rule, node, Selector, Action, Control >( in, st... );
}
} // namespace TAO_PEGTL_NAMESPACE::parse_tree
#endif
|
//
// Copyright (c) 2008-2019 the Urho3D project.
//
// 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 "../Precompiled.h"
#include "../Core/Context.h"
#include "../Input/InputEvents.h"
#include "../UI/CheckBox.h"
#include "../UI/UIEvents.h"
#include "../DebugNew.h"
namespace Craft
{
extern const char* UI_CATEGORY;
CheckBox::CheckBox(Context* context) :
BorderImage(context),
checkedOffset_(IntVector2::ZERO),
checked_(false)
{
SetEnabled(true);
focusMode_ = FM_FOCUSABLE_DEFOCUSABLE;
}
CheckBox::~CheckBox() = default;
void CheckBox::RegisterObject(Context* context)
{
context->RegisterFactory<CheckBox>(UI_CATEGORY);
CRAFT_COPY_BASE_ATTRIBUTES(BorderImage);
CRAFT_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Is Enabled", true);
CRAFT_UPDATE_ATTRIBUTE_DEFAULT_VALUE("Focus Mode", FM_FOCUSABLE_DEFOCUSABLE);
CRAFT_ACCESSOR_ATTRIBUTE("Is Checked", IsChecked, SetChecked, bool, false, AM_FILE);
CRAFT_ACCESSOR_ATTRIBUTE("Checked Image Offset", GetCheckedOffset, SetCheckedOffset, IntVector2, IntVector2::ZERO, AM_FILE);
}
void CheckBox::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
{
IntVector2 offset(IntVector2::ZERO);
if (hovering_ || selected_ || HasFocus())
offset += hoverOffset_;
if (checked_)
offset += checkedOffset_;
BorderImage::GetBatches(batches, vertexData, currentScissor, offset);
}
void CheckBox::OnClickBegin(const IntVector2& position, const IntVector2& screenPosition, int button, int buttons, int qualifiers,
Cursor* cursor)
{
if (button == MOUSEB_LEFT && editable_)
SetChecked(!checked_);
}
void CheckBox::OnKey(Key key, MouseButtonFlags buttons, QualifierFlags qualifiers)
{
if (HasFocus() && key == KEY_SPACE)
{
// Simulate LMB click
OnClickBegin(IntVector2(), IntVector2(), MOUSEB_LEFT, 0, 0, nullptr);
}
}
void CheckBox::SetChecked(bool enable)
{
if (enable != checked_)
{
checked_ = enable;
using namespace Toggled;
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
eventData[P_STATE] = checked_;
SendEvent(E_TOGGLED, eventData);
}
}
void CheckBox::SetCheckedOffset(const IntVector2& offset)
{
checkedOffset_ = offset;
}
void CheckBox::SetCheckedOffset(int x, int y)
{
checkedOffset_ = IntVector2(x, y);
}
}
|
/*
* This is the source code of thread_highways library
*
* Copyright (c) Dmitriy Bondarenko
* feel free to contact me: bondarenkoda@gmail.com
*/
#include <thread_highways/include_all.h>
#include <gtest/gtest.h>
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <set>
#include <vector>
namespace hi
{
using namespace std::chrono_literals;
struct CustomFreeTimeLogic
{
enum class HRstrategy
{
DecreaseWorkers,
FreezeNumberOfWorkers,
IncreaseWorkers
};
std::chrono::milliseconds operator()(
HighWayBundle &,
const std::uint32_t,
const std::chrono::milliseconds work_time)
{
switch (hr_strategy_)
{
case HRstrategy::DecreaseWorkers:
return work_time + std::chrono::milliseconds{1000000};
case HRstrategy::FreezeNumberOfWorkers:
return work_time;
case HRstrategy::IncreaseWorkers:
return {};
}
return {};
}
std::string get_code_filename()
{
return __FILE__;
}
unsigned int get_code_line()
{
return __LINE__;
}
std::atomic<HRstrategy> hr_strategy_{HRstrategy::IncreaseWorkers};
};
using highway_types =
::testing::Types<ConcurrentHighWay<CustomFreeTimeLogic>, ConcurrentHighWayDebug<CustomFreeTimeLogic>>;
template <class T>
struct TestMultithreading : public ::testing::Test
{
};
TYPED_TEST_SUITE(TestMultithreading, highway_types);
TYPED_TEST(TestMultithreading, IncreaseDecreaseWorkers)
{
auto test = [&]
{
std::string log;
std::mutex log_protector;
std::set<std::thread::id> threads;
std::mutex threads_protector;
auto publisher = hi::make_self_shared<hi::PublishOneForMany<std::int32_t>>();
auto publish = [&]
{
auto start = std::chrono::steady_clock::now();
while (std::chrono::steady_clock::now() - start < 300ms)
{
publisher->publish(0);
std::this_thread::sleep_for(1ms);
}
};
{
RAIIdestroy highway{hi::make_self_shared<TypeParam>(
"HighWay",
hi::create_default_logger(
[&](std::string msg)
{
std::lock_guard lg{log_protector};
log = std::move(msg);
}),
10ms, // max_task_execution_time
1ms // workers_change_period
)};
highway.object_->set_max_concurrent_workers(2);
publisher->subscribe(
[&](std::int32_t)
{
{
std::lock_guard lg{threads_protector};
threads.insert(std::this_thread::get_id());
}
std::this_thread::sleep_for(10ms);
},
highway.object_->protector_for_tests_only(),
highway.object_->mailbox());
// save thread id's
publish();
std::uint32_t last_size{0};
{
std::lock_guard lg{threads_protector};
last_size = static_cast<std::uint32_t>(threads.size());
EXPECT_GT(last_size, 1);
}
highway.object_->free_time_logic().hr_strategy_ = CustomFreeTimeLogic::HRstrategy::DecreaseWorkers;
highway.object_->flush_tasks();
// wait for decreasing
publish();
{
std::lock_guard lg{threads_protector};
threads.clear();
}
// save thread id's
publish();
{
std::lock_guard lg{threads_protector};
EXPECT_GT(last_size, static_cast<std::uint32_t>(threads.size()));
}
} // scope
EXPECT_NE(log.find("destroyed"), std::string::npos);
};
for (int i = 0; i < 10; ++i)
{
test();
}
}
} // namespace hi
|
/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "problems/cvrp/operators/intra_exchange.h"
#include "utils/helpers.h"
namespace vroom {
namespace cvrp {
IntraExchange::IntraExchange(const Input& input,
const utils::SolutionState& sol_state,
RawRoute& s_route,
Index s_vehicle,
Index s_rank,
Index t_rank)
: Operator(input,
sol_state,
s_route,
s_vehicle,
s_rank,
s_route,
s_vehicle,
t_rank) {
// Assume s_rank < t_rank for symmetry reasons. Set aside cases
// where t_rank = s_rank + 1, as the move is also an intra_relocate.
assert(0 < t_rank);
assert(s_rank < t_rank - 1);
assert(s_route.size() >= 3);
assert(t_rank < s_route.size());
}
void IntraExchange::compute_gain() {
const auto& m = _input.get_matrix();
const auto& v = _input.vehicles[s_vehicle];
// Consider the cost of replacing job at rank s_rank with target
// job. Part of that cost (for adjacent edges) is stored in
// _sol_state.edge_costs_around_node.
Index s_index = _input.jobs[s_route[s_rank]].index();
Index t_index = _input.jobs[t_route[t_rank]].index();
// Determine costs added with target job.
Gain new_previous_cost = 0;
if (s_rank == 0) {
if (v.has_start()) {
auto p_index = v.start.get().index();
new_previous_cost = m[p_index][t_index];
}
} else {
auto p_index = _input.jobs[s_route[s_rank - 1]].index();
new_previous_cost = m[p_index][t_index];
}
auto n_index = _input.jobs[s_route[s_rank + 1]].index();
Gain new_next_cost = m[t_index][n_index];
Gain s_gain = _sol_state.edge_costs_around_node[s_vehicle][s_rank] -
new_previous_cost - new_next_cost;
// Consider the cost of replacing job at rank t_rank with source
// job. Part of that cost (for adjacent edges) is stored in
// _sol_state.edge_costs_around_node.
// Determine costs added with source job.
new_next_cost = 0;
auto p_index = _input.jobs[t_route[t_rank - 1]].index();
new_previous_cost = m[p_index][s_index];
if (t_rank == t_route.size() - 1) {
if (v.has_end()) {
auto n_index = v.end.get().index();
new_next_cost = m[s_index][n_index];
}
} else {
auto n_index = _input.jobs[t_route[t_rank + 1]].index();
new_next_cost = m[s_index][n_index];
}
Gain t_gain = _sol_state.edge_costs_around_node[s_vehicle][t_rank] -
new_previous_cost - new_next_cost;
stored_gain = s_gain + t_gain;
gain_computed = true;
}
bool IntraExchange::is_valid() {
return true;
}
void IntraExchange::apply() {
std::swap(s_route[s_rank], t_route[t_rank]);
}
std::vector<Index> IntraExchange::addition_candidates() const {
return {};
}
std::vector<Index> IntraExchange::update_candidates() const {
return {s_vehicle};
}
} // namespace cvrp
} // namespace vroom
|
//
// Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
//
#include <set>
#include <vector>
#include <tbb/atomic.h>
#include <boost/function.hpp>
#include <base/util.h>
#include "watermark.h"
WaterMarkTuple::WaterMarkTuple() :
hwater_index_(-1),
lwater_index_(-1) {
hwater_mark_set_ = false;
lwater_mark_set_ = false;
}
WaterMarkTuple::~WaterMarkTuple() {
}
void WaterMarkTuple::SetHighWaterMark(const WaterMarkInfos &high_water) {
// Eliminate duplicates and sort by converting to set
std::set<WaterMarkInfo> hwater_set(high_water.begin(),
high_water.end());
// Update both high and low water mark indexes
SetWaterMarkIndexes(-1, -1);
high_water_ = WaterMarkInfos(hwater_set.begin(), hwater_set.end());
hwater_mark_set_ = true;
}
void WaterMarkTuple::SetHighWaterMark(const WaterMarkInfo& hwm_info) {
// Eliminate duplicates and sort by converting to set
std::set<WaterMarkInfo> hwater_set(high_water_.begin(),
high_water_.end());
hwater_set.insert(hwm_info);
// Update both high and low water mark indexes
SetWaterMarkIndexes(-1, -1);
high_water_ = WaterMarkInfos(hwater_set.begin(), hwater_set.end());
hwater_mark_set_ = true;
}
void WaterMarkTuple::ResetHighWaterMark() {
// Update both high and low water mark indexes
SetWaterMarkIndexes(-1, -1);
high_water_.clear();
hwater_mark_set_ = false;
}
WaterMarkInfos WaterMarkTuple::GetHighWaterMark() const {
return high_water_;
}
void WaterMarkTuple::SetLowWaterMark(const WaterMarkInfos &low_water) {
// Eliminate duplicates and sort by converting to set
std::set<WaterMarkInfo> lwater_set(low_water.begin(),
low_water.end());
// Update both high and low water mark indexes
SetWaterMarkIndexes(-1, -1);
low_water_ = WaterMarkInfos(lwater_set.begin(), lwater_set.end());
lwater_mark_set_ = true;
}
void WaterMarkTuple::SetLowWaterMark(const WaterMarkInfo& lwm_info) {
// Eliminate duplicates and sort by converting to set
std::set<WaterMarkInfo> lwater_set(low_water_.begin(),
low_water_.end());
lwater_set.insert(lwm_info);
// Update both high and low water mark indexes
SetWaterMarkIndexes(-1, -1);
low_water_ = WaterMarkInfos(lwater_set.begin(), lwater_set.end());
lwater_mark_set_ = true;
}
void WaterMarkTuple::ResetLowWaterMark() {
// Update both high and low water mark indexes
SetWaterMarkIndexes(-1, -1);
low_water_.clear();
lwater_mark_set_ = false;
}
WaterMarkInfos WaterMarkTuple::GetLowWaterMark() const {
return low_water_;
}
void WaterMarkTuple::GetWaterMarkIndexes(int *hwater_index,
int *lwater_index) const {
*hwater_index = hwater_index_;
*lwater_index = lwater_index_;
}
void WaterMarkTuple::SetWaterMarkIndexes(int hwater_index,
int lwater_index) {
hwater_index_ = hwater_index;
lwater_index_ = lwater_index;
}
void WaterMarkTuple::ProcessWaterMarks(size_t in_count,
size_t curr_count) {
if (in_count < curr_count)
ProcessLowWaterMarks(in_count);
else
ProcessHighWaterMarks(in_count);
}
bool WaterMarkTuple::AreWaterMarksSet() const {
return hwater_mark_set_ || lwater_mark_set_;
}
void WaterMarkTuple::ProcessHighWaterMarks(size_t count) {
if (!hwater_mark_set_ || high_water_.size() == 0) {
return;
}
// Are we crossing any new high water marks ? Assumption here is that
// the vector is sorted in ascending order of the high water
// mark counts. Upper bound finds first element that is greater than
// count.
WaterMarkInfos::const_iterator ubound(std::upper_bound(
high_water_.begin(), high_water_.end(),
WaterMarkInfo(count, NULL)));
// Get high and low water mark indexes
int hwater_index, lwater_index;
GetWaterMarkIndexes(&hwater_index, &lwater_index);
// If the first element is greater than count, then we have not
// yet crossed any water marks
if (ubound == high_water_.begin()) {
SetWaterMarkIndexes(-1, lwater_index);
return;
}
int nhwater_index(ubound - high_water_.begin() - 1);
if (hwater_index == nhwater_index) {
return;
}
// Update the high and low water indexes
SetWaterMarkIndexes(nhwater_index, nhwater_index + 1);
const WaterMarkInfo &wm_info(high_water_[nhwater_index]);
assert(count >= wm_info.count_);
wm_info.cb_(count);
}
void WaterMarkTuple::ProcessLowWaterMarks(size_t count) {
if (!lwater_mark_set_ || low_water_.size() == 0) {
return;
}
// Are we crossing any new low water marks ? Assumption here is that
// the vector is sorted in ascending order of the low water
// mark counts. Lower bound finds first element that is not less than
// count.
WaterMarkInfos::const_iterator lbound(std::lower_bound(
low_water_.begin(), low_water_.end(),
WaterMarkInfo(count, NULL)));
// If no element is not less than count we have not yet crossed
// any low water marks
if (lbound == low_water_.end()) {
return;
}
int nlwater_index(lbound - low_water_.begin());
// Get the high and low water indexes
int hwater_index, lwater_index;
GetWaterMarkIndexes(&hwater_index, &lwater_index);
if (lwater_index == nlwater_index) {
return;
}
// Update the high and low water indexes
SetWaterMarkIndexes(nlwater_index - 1, nlwater_index);
const WaterMarkInfo &wm_info(low_water_[nlwater_index]);
assert(count <= wm_info.count_);
wm_info.cb_(count);
}
|
//
// Created by YANG Zehai on 2021/11/23.
//
#include "AST/Unary.h"
using namespace pur;
using namespace pur::ast;
Unary::Unary(const pars::Location& location, Expr& expr, UnaryOp op):
Expr(ASTNodeType::kUnary, location), mExpr(&expr), mOp(op) {
/* empty */
}
Expr& Unary::GetExpr() {
return *mExpr;
}
UnaryOp Unary::GetOp() const {
return mOp;
}
void Unary::Accept(Visitor& visitor) {
return visitor.VisitUnary(*this);
}
|
/***************************************************************************
*
* $Id: StPxlHitCollection.cxx,v 2.1 2013/03/05 14:40:21 ullrich Exp $
*
* Author: X. Dong, Jan 2013
***************************************************************************
*
* Description:
*
***************************************************************************
*
* $Log: StPxlHitCollection.cxx,v $
* Revision 2.1 2013/03/05 14:40:21 ullrich
* Initial Revision.
*
**************************************************************************/
#include "StPxlHitCollection.h"
#include "StPxlSectorHitCollection.h"
#include "StPxlLadderHitCollection.h"
#include "StPxlSensorHitCollection.h"
#include "StPxlHit.h"
ClassImp(StPxlHitCollection)
StPxlHitCollection::StPxlHitCollection() { /* noop */ }
StPxlHitCollection::~StPxlHitCollection() { /* noop */}
bool
StPxlHitCollection::addHit(StPxlHit* hit)
{
unsigned int s, l, w;
if (hit &&
(s = hit->sector()-1) < mNumberOfSectors &&
(l = hit->ladder()-1) < mSectors[s].numberOfLadders() &&
(w = hit->sensor()-1) < mSectors[s].ladder(l)->numberOfSensors()) {
mSectors[s].ladder(l)->sensor(w)->hits().push_back(hit);
return true;
}
else
return false;
}
unsigned int
StPxlHitCollection::numberOfHits() const
{
unsigned int sum = 0;
for (int i=0; i<mNumberOfSectors; i++) {
for (unsigned int j=0; j<mSectors[i].numberOfLadders(); j++) {
for (unsigned int k=0; k<mSectors[i].ladder(j)->numberOfSensors(); k++) {
sum += mSectors[i].ladder(j)->sensor(k)->hits().size();
}
}
}
return sum;
}
StPxlSectorHitCollection*
StPxlHitCollection::sector(unsigned int i)
{
return (i < mNumberOfSectors) ? &(mSectors[i]) : 0;
}
const StPxlSectorHitCollection*
StPxlHitCollection::sector(unsigned int i) const
{
return (i < mNumberOfSectors) ? &(mSectors[i]) : 0;
}
|
/*
* Copyright (c) 2016-2020 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 "arm_compute/runtime/CL/functions/CLSobel5x5.h"
#include "arm_compute/core/CL/ICLTensor.h"
#include "arm_compute/core/CL/kernels/CLSobel5x5Kernel.h"
#include "arm_compute/core/PixelValue.h"
#include "arm_compute/core/TensorInfo.h"
#include "arm_compute/core/Validate.h"
#include "arm_compute/runtime/CL/CLScheduler.h"
#include "arm_compute/runtime/ITensorAllocator.h"
using namespace arm_compute;
CLSobel5x5::CLSobel5x5(std::shared_ptr<IMemoryManager> memory_manager)
: _memory_group(std::move(memory_manager)), _sobel_hor(), _sobel_vert(), _border_handler(), _tmp_x(), _tmp_y()
{
}
void CLSobel5x5::configure(ICLTensor *input, ICLTensor *output_x, ICLTensor *output_y, BorderMode border_mode, uint8_t constant_border_value)
{
configure(CLKernelLibrary::get().get_compile_context(), input, output_x, output_y, border_mode, constant_border_value);
}
void CLSobel5x5::configure(const CLCompileContext &compile_context, ICLTensor *input, ICLTensor *output_x, ICLTensor *output_y, BorderMode border_mode, uint8_t constant_border_value)
{
ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::U8);
const bool run_sobel_x = output_x != nullptr;
const bool run_sobel_y = output_y != nullptr;
TensorInfo tensor_info(input->info()->tensor_shape(), 1, DataType::S16);
if(run_sobel_x && run_sobel_y)
{
_tmp_x.allocator()->init(tensor_info);
_tmp_y.allocator()->init(tensor_info);
_memory_group.manage(&_tmp_x);
_memory_group.manage(&_tmp_y);
_sobel_hor.configure(compile_context, input, &_tmp_x, &_tmp_y, border_mode == BorderMode::UNDEFINED);
_sobel_vert.configure(compile_context, &_tmp_x, &_tmp_y, output_x, output_y, border_mode == BorderMode::UNDEFINED);
_tmp_x.allocator()->allocate();
_tmp_y.allocator()->allocate();
}
else if(run_sobel_x)
{
_tmp_x.allocator()->init(tensor_info);
_memory_group.manage(&_tmp_x);
_sobel_hor.configure(compile_context, input, &_tmp_x, nullptr, border_mode == BorderMode::UNDEFINED);
_sobel_vert.configure(compile_context, &_tmp_x, nullptr, output_x, nullptr, border_mode == BorderMode::UNDEFINED);
_tmp_x.allocator()->allocate();
}
else if(run_sobel_y)
{
_tmp_y.allocator()->init(tensor_info);
_memory_group.manage(&_tmp_y);
_sobel_hor.configure(compile_context, input, nullptr, &_tmp_y, border_mode == BorderMode::UNDEFINED);
_sobel_vert.configure(compile_context, nullptr, &_tmp_y, nullptr, output_y, border_mode == BorderMode::UNDEFINED);
_tmp_y.allocator()->allocate();
}
_border_handler.configure(compile_context, input, _sobel_hor.border_size(), border_mode, PixelValue(constant_border_value));
}
void CLSobel5x5::run()
{
CLScheduler::get().enqueue(_border_handler, false);
MemoryGroupResourceScope scope_mg(_memory_group);
CLScheduler::get().enqueue(_sobel_hor, false);
CLScheduler::get().enqueue(_sobel_vert);
}
|
//===--- GenProto.cpp - Swift IR Generation for Protocols -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for protocols in Swift.
//
// Protocols serve two masters: generic algorithms and existential
// types. In either case, the size and structure of a type is opaque
// to the code manipulating a value. Local values of the type must
// be stored in fixed-size buffers (which can overflow to use heap
// allocation), and basic operations on the type must be dynamically
// delegated to a collection of information that "witnesses" the
// truth that a particular type implements the protocol.
//
// In the comments throughout this file, three type names are used:
// 'B' is the type of a fixed-size buffer
// 'T' is the type which implements a protocol
// 'W' is the type of a witness to the protocol
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Types.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILWitnessVisitor.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "CallEmission.h"
#include "ConstantBuilder.h"
#include "EnumPayload.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "Fulfillment.h"
#include "GenArchetype.h"
#include "GenCast.h"
#include "GenClass.h"
#include "GenEnum.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenOpaque.h"
#include "GenPoly.h"
#include "GenType.h"
#include "GenericRequirement.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "MetadataPath.h"
#include "MetadataRequest.h"
#include "NecessaryBindings.h"
#include "ProtocolInfo.h"
#include "TypeInfo.h"
#include "GenProto.h"
using namespace swift;
using namespace irgen;
namespace {
/// A class for computing how to pass arguments to a polymorphic
/// function. The subclasses of this are the places which need to
/// be updated if the convention changes.
class PolymorphicConvention {
protected:
IRGenModule &IGM;
ModuleDecl &M;
CanSILFunctionType FnType;
CanGenericSignature Generics;
std::vector<MetadataSource> Sources;
FulfillmentMap Fulfillments;
GenericSignature::ConformsToArray getConformsTo(Type t) {
return Generics->getConformsTo(t);
}
CanType getSuperclassBound(Type t) {
if (auto superclassTy = Generics->getSuperclassBound(t))
return superclassTy->getCanonicalType();
return CanType();
}
public:
PolymorphicConvention(IRGenModule &IGM, CanSILFunctionType fnType);
ArrayRef<MetadataSource> getSources() const { return Sources; }
void enumerateRequirements(const RequirementCallback &callback);
void enumerateUnfulfilledRequirements(const RequirementCallback &callback);
/// Returns a Fulfillment for a type parameter requirement, or
/// nullptr if it's unfulfilled.
const Fulfillment *getFulfillmentForTypeMetadata(CanType type) const;
/// Return the source of type metadata at a particular source index.
const MetadataSource &getSource(size_t SourceIndex) const {
return Sources[SourceIndex];
}
private:
void initGenerics();
void considerNewTypeSource(MetadataSource::Kind kind, unsigned paramIndex,
CanType type, IsExact_t isExact);
bool considerType(CanType type, IsExact_t isExact,
unsigned sourceIndex, MetadataPath &&path);
/// Testify to generic parameters in the Self type of a protocol
/// witness method.
void considerWitnessSelf(CanSILFunctionType fnType);
/// Testify to generic parameters in the Self type of an @objc
/// generic or protocol method.
void considerObjCGenericSelf(CanSILFunctionType fnType);
void considerParameter(SILParameterInfo param, unsigned paramIndex,
bool isSelfParameter);
void addSelfMetadataFulfillment(CanType arg);
void addSelfWitnessTableFulfillment(CanType arg,
ProtocolConformanceRef conformance);
void addPseudogenericFulfillments();
struct FulfillmentMapCallback : FulfillmentMap::InterestingKeysCallback {
PolymorphicConvention &Self;
FulfillmentMapCallback(PolymorphicConvention &self) : Self(self) {}
bool isInterestingType(CanType type) const override {
return type->isTypeParameter();
}
bool hasInterestingType(CanType type) const override {
return type->hasTypeParameter();
}
bool hasLimitedInterestingConformances(CanType type) const override {
return true;
}
GenericSignature::ConformsToArray
getInterestingConformances(CanType type) const override {
return Self.getConformsTo(type);
}
CanType getSuperclassBound(CanType type) const override {
return Self.getSuperclassBound(type);
}
};
};
} // end anonymous namespace
PolymorphicConvention::PolymorphicConvention(IRGenModule &IGM,
CanSILFunctionType fnType)
: IGM(IGM), M(*IGM.getSwiftModule()), FnType(fnType) {
initGenerics();
auto rep = fnType->getRepresentation();
if (fnType->isPseudogeneric()) {
// Protocol witnesses still get Self metadata no matter what. The type
// parameters of Self are pseudogeneric, though.
if (rep == SILFunctionTypeRepresentation::WitnessMethod)
considerWitnessSelf(fnType);
addPseudogenericFulfillments();
return;
}
if (rep == SILFunctionTypeRepresentation::WitnessMethod) {
// Protocol witnesses always derive all polymorphic parameter information
// from the Self and Self witness table arguments. We also *cannot* consider
// other arguments; doing so would potentially make the signature
// incompatible with other witnesses for the same method.
considerWitnessSelf(fnType);
} else if (rep == SILFunctionTypeRepresentation::ObjCMethod) {
// Objective-C thunks for generic methods also always derive all
// polymorphic parameter information from the Self argument.
considerObjCGenericSelf(fnType);
} else {
// We don't need to pass anything extra as long as all of the
// archetypes (and their requirements) are producible from
// arguments.
unsigned selfIndex = ~0U;
auto params = fnType->getParameters();
// Consider 'self' first.
if (fnType->hasSelfParam()) {
selfIndex = params.size() - 1;
considerParameter(params[selfIndex], selfIndex, true);
}
// Now consider the rest of the parameters.
for (auto index : indices(params)) {
if (index != selfIndex)
considerParameter(params[index], index, false);
}
}
}
void PolymorphicConvention::addPseudogenericFulfillments() {
enumerateRequirements([&](GenericRequirement reqt) {
MetadataPath path;
path.addImpossibleComponent();
unsigned sourceIndex = 0; // unimportant, since impossible
Fulfillments.addFulfillment({reqt.TypeParameter, reqt.Protocol},
sourceIndex, std::move(path),
MetadataState::Complete);
});
}
void
irgen::enumerateGenericSignatureRequirements(CanGenericSignature signature,
const RequirementCallback &callback) {
if (!signature) return;
// Get all of the type metadata.
signature->forEachParam([&](GenericTypeParamType *gp, bool canonical) {
if (canonical)
callback({CanType(gp), nullptr});
});
// Get the protocol conformances.
for (auto &reqt : signature->getRequirements()) {
switch (reqt.getKind()) {
// Ignore these; they don't introduce extra requirements.
case RequirementKind::Superclass:
case RequirementKind::SameType:
case RequirementKind::Layout:
continue;
case RequirementKind::Conformance: {
auto type = CanType(reqt.getFirstType());
auto protocol =
cast<ProtocolType>(CanType(reqt.getSecondType()))->getDecl();
if (Lowering::TypeConverter::protocolRequiresWitnessTable(protocol)) {
callback({type, protocol});
}
continue;
}
}
llvm_unreachable("bad requirement kind");
}
}
void
PolymorphicConvention::enumerateRequirements(const RequirementCallback &callback) {
return enumerateGenericSignatureRequirements(Generics, callback);
}
void PolymorphicConvention::
enumerateUnfulfilledRequirements(const RequirementCallback &callback) {
enumerateRequirements([&](GenericRequirement requirement) {
if (requirement.Protocol) {
if (!Fulfillments.getWitnessTable(requirement.TypeParameter,
requirement.Protocol)) {
callback(requirement);
}
} else {
if (!Fulfillments.getTypeMetadata(requirement.TypeParameter)) {
callback(requirement);
}
}
});
}
void PolymorphicConvention::initGenerics() {
Generics = FnType->getGenericSignature();
}
void PolymorphicConvention::considerNewTypeSource(MetadataSource::Kind kind,
unsigned paramIndex,
CanType type,
IsExact_t isExact) {
if (!Fulfillments.isInterestingTypeForFulfillments(type)) return;
// Prospectively add a source.
Sources.emplace_back(kind, paramIndex, type);
// Consider the source.
if (!considerType(type, isExact, Sources.size() - 1, MetadataPath())) {
// If it wasn't used in any fulfillments, remove it.
Sources.pop_back();
}
}
bool PolymorphicConvention::considerType(CanType type, IsExact_t isExact,
unsigned sourceIndex,
MetadataPath &&path) {
FulfillmentMapCallback callbacks(*this);
return Fulfillments.searchTypeMetadata(IGM, type, isExact,
MetadataState::Complete, sourceIndex,
std::move(path), callbacks);
}
void PolymorphicConvention::considerWitnessSelf(CanSILFunctionType fnType) {
CanType selfTy = fnType->getSelfInstanceType();
auto conformance = fnType->getWitnessMethodConformance();
// First, bind type metadata for Self.
Sources.emplace_back(MetadataSource::Kind::SelfMetadata,
MetadataSource::InvalidSourceIndex,
selfTy);
if (fnType->getDefaultWitnessMethodProtocol() ||
fnType->getWitnessMethodClass(M)) {
// The Self type is abstract, so we can fulfill its metadata from
// the Self metadata parameter.
addSelfMetadataFulfillment(selfTy);
}
considerType(selfTy, IsInexact, Sources.size() - 1, MetadataPath());
// The witness table for the Self : P conformance can be
// fulfilled from the Self witness table parameter.
Sources.emplace_back(MetadataSource::Kind::SelfWitnessTable,
MetadataSource::InvalidSourceIndex, selfTy);
addSelfWitnessTableFulfillment(selfTy, conformance);
}
void PolymorphicConvention::considerObjCGenericSelf(CanSILFunctionType fnType) {
// If this is a static method, get the instance type.
CanType selfTy = fnType->getSelfInstanceType();
unsigned paramIndex = fnType->getParameters().size() - 1;
// Bind type metadata for Self.
Sources.emplace_back(MetadataSource::Kind::ClassPointer, paramIndex,
selfTy);
if (isa<GenericTypeParamType>(selfTy))
addSelfMetadataFulfillment(selfTy);
else
considerType(selfTy, IsInexact,
Sources.size() - 1, MetadataPath());
}
void PolymorphicConvention::considerParameter(SILParameterInfo param,
unsigned paramIndex,
bool isSelfParameter) {
auto type = param.getType();
switch (param.getConvention()) {
// Indirect parameters do give us a value we can use, but right now
// we don't bother, for no good reason. But if this is 'self',
// consider passing an extra metatype.
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_In_Constant:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable:
if (!isSelfParameter) return;
if (type->getNominalOrBoundGenericNominal()) {
considerNewTypeSource(MetadataSource::Kind::GenericLValueMetadata,
paramIndex, type, IsExact);
}
return;
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Unowned:
case ParameterConvention::Direct_Guaranteed:
// Classes are sources of metadata.
if (type->getClassOrBoundGenericClass()) {
considerNewTypeSource(MetadataSource::Kind::ClassPointer,
paramIndex, type, IsInexact);
return;
}
if (isa<GenericTypeParamType>(type)) {
if (auto superclassTy = getSuperclassBound(type)) {
considerNewTypeSource(MetadataSource::Kind::ClassPointer,
paramIndex, superclassTy, IsInexact);
return;
}
}
// Thick metatypes are sources of metadata.
if (auto metatypeTy = dyn_cast<MetatypeType>(type)) {
if (metatypeTy->getRepresentation() != MetatypeRepresentation::Thick)
return;
// Thick metatypes for Objective-C parameterized classes are not
// sources of metadata.
CanType objTy = metatypeTy.getInstanceType();
if (auto classDecl = objTy->getClassOrBoundGenericClass())
if (classDecl->usesObjCGenericsModel())
return;
considerNewTypeSource(MetadataSource::Kind::Metadata,
paramIndex, objTy, IsInexact);
return;
}
return;
}
llvm_unreachable("bad parameter convention");
}
void PolymorphicConvention::addSelfMetadataFulfillment(CanType arg) {
unsigned source = Sources.size() - 1;
Fulfillments.addFulfillment({arg, nullptr},
source, MetadataPath(), MetadataState::Complete);
}
void PolymorphicConvention::addSelfWitnessTableFulfillment(
CanType arg, ProtocolConformanceRef conformance) {
auto proto = conformance.getRequirement();
unsigned source = Sources.size() - 1;
Fulfillments.addFulfillment({arg, proto},
source, MetadataPath(), MetadataState::Complete);
if (conformance.isConcrete()) {
FulfillmentMapCallback callbacks(*this);
Fulfillments.searchConformance(IGM, conformance.getConcrete(), source,
MetadataPath(), callbacks);
}
}
const Fulfillment *
PolymorphicConvention::getFulfillmentForTypeMetadata(CanType type) const {
return Fulfillments.getTypeMetadata(type);
}
void irgen::enumerateGenericParamFulfillments(IRGenModule &IGM,
CanSILFunctionType fnType,
GenericParamFulfillmentCallback callback) {
PolymorphicConvention convention(IGM, fnType);
// Check if any requirements were fulfilled by metadata stored inside a
// captured value.
auto generics = fnType->getGenericSignature();
for (auto genericParam : generics->getGenericParams()) {
auto genericParamType = genericParam->getCanonicalType();
auto fulfillment
= convention.getFulfillmentForTypeMetadata(genericParamType);
if (fulfillment == nullptr)
continue;
auto &source = convention.getSource(fulfillment->SourceIndex);
callback(genericParamType, source, fulfillment->Path);
}
}
namespace {
/// A class for binding type parameters of a generic function.
class EmitPolymorphicParameters : public PolymorphicConvention {
IRGenFunction &IGF;
SILFunction &Fn;
public:
EmitPolymorphicParameters(IRGenFunction &IGF, SILFunction &Fn);
void emit(Explosion &in, WitnessMetadata *witnessMetadata,
const GetParameterFn &getParameter);
private:
CanType getTypeInContext(CanType type) const;
CanType getArgTypeInContext(unsigned paramIndex) const;
/// Fulfill local type data from any extra information associated with
/// the given source.
void bindExtraSource(const MetadataSource &source, Explosion &in,
WitnessMetadata *witnessMetadata);
void bindParameterSources(const GetParameterFn &getParameter);
void bindParameterSource(SILParameterInfo param, unsigned paramIndex,
const GetParameterFn &getParameter) ;
// Did the convention decide that the parameter at the given index
// was a class-pointer source?
bool isClassPointerSource(unsigned paramIndex);
};
} // end anonymous namespace
EmitPolymorphicParameters::EmitPolymorphicParameters(IRGenFunction &IGF,
SILFunction &Fn)
: PolymorphicConvention(IGF.IGM, Fn.getLoweredFunctionType()),
IGF(IGF), Fn(Fn) {}
CanType EmitPolymorphicParameters::getTypeInContext(CanType type) const {
return Fn.mapTypeIntoContext(type)->getCanonicalType();
}
CanType EmitPolymorphicParameters::getArgTypeInContext(unsigned paramIndex) const {
return getTypeInContext(FnType->getParameters()[paramIndex].getType());
}
void EmitPolymorphicParameters::bindExtraSource(const MetadataSource &source,
Explosion &in,
WitnessMetadata *witnessMetadata) {
switch (source.getKind()) {
case MetadataSource::Kind::Metadata:
case MetadataSource::Kind::ClassPointer:
// Ignore these, we'll get to them when we walk the parameter list.
return;
case MetadataSource::Kind::GenericLValueMetadata: {
CanType argTy = getArgTypeInContext(source.getParamIndex());
llvm::Value *metadata = in.claimNext();
setTypeMetadataName(IGF.IGM, metadata, argTy);
IGF.bindLocalTypeDataFromTypeMetadata(argTy, IsExact, metadata,
MetadataState::Complete);
return;
}
case MetadataSource::Kind::SelfMetadata: {
assert(witnessMetadata && "no metadata for witness method");
llvm::Value *metadata = witnessMetadata->SelfMetadata;
assert(metadata && "no Self metadata for witness method");
// Mark this as the cached metatype for Self.
auto selfTy = FnType->getSelfInstanceType();
CanType argTy = getTypeInContext(selfTy);
setTypeMetadataName(IGF.IGM, metadata, argTy);
auto *CD = selfTy.getClassOrBoundGenericClass();
// The self metadata here corresponds to the conforming type.
// For an inheritable conformance, that may be a subclass of the static
// type, and so the self metadata will be inexact. Currently, all
// conformances are inheritable.
IGF.bindLocalTypeDataFromTypeMetadata(
argTy, (!CD || CD->isFinal()) ? IsExact : IsInexact, metadata,
MetadataState::Complete);
return;
}
case MetadataSource::Kind::SelfWitnessTable: {
assert(witnessMetadata && "no metadata for witness method");
llvm::Value *selfTable = witnessMetadata->SelfWitnessTable;
assert(selfTable && "no Self witness table for witness method");
// Mark this as the cached witness table for Self.
auto conformance = FnType->getWitnessMethodConformance();
auto selfProto = conformance.getRequirement();
auto selfTy = FnType->getSelfInstanceType();
CanType argTy = getTypeInContext(selfTy);
setProtocolWitnessTableName(IGF.IGM, selfTable, argTy, selfProto);
IGF.setUnscopedLocalTypeData(
argTy,
LocalTypeDataKind::forProtocolWitnessTable(conformance),
selfTable);
if (conformance.isConcrete()) {
IGF.bindLocalTypeDataFromSelfWitnessTable(
conformance.getConcrete(),
selfTable,
[this](CanType type) {
return getTypeInContext(type);
});
}
return;
}
}
llvm_unreachable("bad source kind!");
}
void EmitPolymorphicParameters::bindParameterSources(const GetParameterFn &getParameter) {
auto params = FnType->getParameters();
// Bind things from 'self' preferentially.
if (FnType->hasSelfParam()) {
bindParameterSource(params.back(), params.size() - 1, getParameter);
params = params.drop_back();
}
for (unsigned index : indices(params)) {
bindParameterSource(params[index], index, getParameter);
}
}
void EmitPolymorphicParameters::
bindParameterSource(SILParameterInfo param, unsigned paramIndex,
const GetParameterFn &getParameter) {
// Ignore indirect parameters for now. This is potentially dumb.
if (IGF.IGM.silConv.isSILIndirect(param))
return;
CanType paramType = getArgTypeInContext(paramIndex);
// If the parameter is a thick metatype, bind it directly.
// TODO: objc metatypes?
if (auto metatype = dyn_cast<MetatypeType>(paramType)) {
if (metatype->getRepresentation() == MetatypeRepresentation::Thick) {
paramType = metatype.getInstanceType();
llvm::Value *metadata = getParameter(paramIndex);
IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
MetadataState::Complete);
}
return;
}
// If the parameter is a class type, we only consider it interesting
// if the convention decided it was actually a source.
// TODO: if the class pointer is guaranteed, we can do this lazily,
// at which point it might make sense to do it for a wider selection
// of types.
if (isClassPointerSource(paramIndex)) {
llvm::Value *instanceRef = getParameter(paramIndex);
SILType instanceType = SILType::getPrimitiveObjectType(paramType);
llvm::Value *metadata =
emitDynamicTypeOfHeapObject(IGF, instanceRef,
MetatypeRepresentation::Thick,
instanceType,
/*allow artificial subclasses*/ true);
IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
MetadataState::Complete);
return;
}
}
bool EmitPolymorphicParameters::isClassPointerSource(unsigned paramIndex) {
for (auto &source : getSources()) {
if (source.getKind() == MetadataSource::Kind::ClassPointer &&
source.getParamIndex() == paramIndex) {
return true;
}
}
return false;
}
namespace {
/// A class for binding type parameters of a generic function.
class BindPolymorphicParameter : public PolymorphicConvention {
IRGenFunction &IGF;
CanSILFunctionType &SubstFnType;
public:
BindPolymorphicParameter(IRGenFunction &IGF, CanSILFunctionType &origFnType,
CanSILFunctionType &SubstFnType)
: PolymorphicConvention(IGF.IGM, origFnType), IGF(IGF),
SubstFnType(SubstFnType) {}
void emit(Explosion &in, unsigned paramIndex);
private:
// Did the convention decide that the parameter at the given index
// was a class-pointer source?
bool isClassPointerSource(unsigned paramIndex);
};
} // end anonymous namespace
bool BindPolymorphicParameter::isClassPointerSource(unsigned paramIndex) {
for (auto &source : getSources()) {
if (source.getKind() == MetadataSource::Kind::ClassPointer &&
source.getParamIndex() == paramIndex) {
return true;
}
}
return false;
}
void BindPolymorphicParameter::emit(Explosion &nativeParam, unsigned paramIndex) {
if (!isClassPointerSource(paramIndex))
return;
assert(nativeParam.size() == 1);
auto paramType = SubstFnType->getParameters()[paramIndex].getType();
llvm::Value *instanceRef = nativeParam.getAll()[0];
SILType instanceType = SILType::getPrimitiveObjectType(paramType);
llvm::Value *metadata =
emitDynamicTypeOfHeapObject(IGF, instanceRef,
MetatypeRepresentation::Thick,
instanceType,
/* allow artificial subclasses */ true);
IGF.bindLocalTypeDataFromTypeMetadata(paramType, IsInexact, metadata,
MetadataState::Complete);
}
void irgen::bindPolymorphicParameter(IRGenFunction &IGF,
CanSILFunctionType &OrigFnType,
CanSILFunctionType &SubstFnType,
Explosion &nativeParam,
unsigned paramIndex) {
BindPolymorphicParameter(IGF, OrigFnType, SubstFnType)
.emit(nativeParam, paramIndex);
}
static bool shouldSetName(IRGenModule &IGM, llvm::Value *value, CanType type) {
// If value names are globally disabled, honor that.
if (!IGM.EnableValueNames) return false;
// Suppress value names for values with opened existentials.
if (type->hasOpenedExistential()) return false;
// If the value already has a name, honor that.
if (value->hasName()) return false;
// Only do this for local values.
return (isa<llvm::Instruction>(value) || isa<llvm::Argument>(value));
}
void irgen::setTypeMetadataName(IRGenModule &IGM, llvm::Value *metadata,
CanType type) {
if (!shouldSetName(IGM, metadata, type)) return;
SmallString<128> name; {
llvm::raw_svector_ostream out(name);
type.print(out);
}
metadata->setName(type->getString());
}
void irgen::setProtocolWitnessTableName(IRGenModule &IGM, llvm::Value *wtable,
CanType type,
ProtocolDecl *requirement) {
if (!shouldSetName(IGM, wtable, type)) return;
SmallString<128> name; {
llvm::raw_svector_ostream out(name);
type.print(out);
out << '.' << requirement->getNameStr();
}
wtable->setName(name);
}
namespace {
/// A class which lays out a witness table in the abstract.
class WitnessTableLayout : public SILWitnessVisitor<WitnessTableLayout> {
SmallVector<WitnessTableEntry, 16> Entries;
bool requirementSignatureOnly;
public:
explicit WitnessTableLayout(ProtocolInfoKind resultKind) {
switch (resultKind) {
case ProtocolInfoKind::RequirementSignature:
requirementSignatureOnly = true;
break;
case ProtocolInfoKind::Full:
requirementSignatureOnly = false;
break;
}
}
bool shouldVisitRequirementSignatureOnly() {
return requirementSignatureOnly;
}
void addProtocolConformanceDescriptor() { }
/// The next witness is an out-of-line base protocol.
void addOutOfLineBaseProtocol(ProtocolDecl *baseProto) {
Entries.push_back(WitnessTableEntry::forOutOfLineBase(baseProto));
}
void addMethod(SILDeclRef func) {
auto decl = cast<AbstractFunctionDecl>(func.getDecl());
Entries.push_back(WitnessTableEntry::forFunction(decl));
}
void addPlaceholder(MissingMemberDecl *placeholder) {
for (auto i : range(placeholder->getNumberOfVTableEntries())) {
(void)i;
Entries.push_back(WitnessTableEntry());
}
}
void addAssociatedType(AssociatedType requirement) {
Entries.push_back(WitnessTableEntry::forAssociatedType(requirement));
}
void addAssociatedConformance(const AssociatedConformance &req) {
Entries.push_back(WitnessTableEntry::forAssociatedConformance(req));
}
ArrayRef<WitnessTableEntry> getEntries() const { return Entries; }
};
/// A path through a protocol hierarchy.
class ProtocolPath {
IRGenModule &IGM;
/// The destination protocol.
ProtocolDecl *Dest;
/// The path from the selected origin down to the destination
/// protocol.
SmallVector<WitnessIndex, 8> ReversePath;
/// The origin index to use.
unsigned OriginIndex;
/// The best path length we found.
unsigned BestPathLength;
public:
/// Find a path from the given set of origins to the destination
/// protocol.
///
/// T needs to provide a couple of member functions:
/// ProtocolDecl *getProtocol() const;
/// const ProtocolInfo &getInfo() const;
template <class T>
ProtocolPath(IRGenModule &IGM, ArrayRef<T> origins, ProtocolDecl *dest)
: IGM(IGM), Dest(dest), BestPathLength(~0U) {
// Consider each of the origins in turn, breaking out if any of
// them yields a zero-length path.
for (unsigned i = 0, e = origins.size(); i != e; ++i) {
auto &origin = origins[i];
if (considerOrigin(origin.getProtocol(), origin.getInfo(), i))
break;
}
// Sanity check that we actually found a path at all.
assert(BestPathLength != ~0U);
assert(BestPathLength == ReversePath.size());
}
/// Returns the index of the origin protocol we chose.
unsigned getOriginIndex() const { return OriginIndex; }
/// Apply the path to the given witness table.
llvm::Value *apply(IRGenFunction &IGF, llvm::Value *wtable) const {
for (unsigned i = ReversePath.size(); i != 0; --i) {
wtable = emitInvariantLoadOfOpaqueWitness(IGF, wtable,
ReversePath[i-1].forProtocolWitnessTable());
wtable = IGF.Builder.CreateBitCast(wtable, IGF.IGM.WitnessTablePtrTy);
}
return wtable;
}
private:
/// Consider paths starting from a new origin protocol.
/// Returns true if there's no point in considering other origins.
bool considerOrigin(ProtocolDecl *origin, const ProtocolInfo &originInfo,
unsigned originIndex) {
assert(BestPathLength != 0);
// If the origin *is* the destination, we can stop here.
if (origin == Dest) {
OriginIndex = originIndex;
BestPathLength = 0;
ReversePath.clear();
return true;
}
// Otherwise, if the origin gives rise to a better path, that's
// also cool.
if (findBetterPath(origin, originInfo, 0)) {
OriginIndex = originIndex;
return BestPathLength == 0;
}
return false;
}
/// Consider paths starting at the given protocol.
bool findBetterPath(ProtocolDecl *proto, const ProtocolInfo &protoInfo,
unsigned lengthSoFar) {
assert(lengthSoFar < BestPathLength);
assert(proto != Dest);
// Keep track of whether we found a better path than the
// previous best.
bool foundBetter = false;
for (auto base : proto->getInheritedProtocols()) {
// ObjC protocols do not have witnesses.
if (!Lowering::TypeConverter::protocolRequiresWitnessTable(base))
continue;
auto baseIndex = protoInfo.getBaseIndex(base);
// Compute the length down to this base.
unsigned lengthToBase = lengthSoFar;
if (!baseIndex.isPrefix()) {
lengthToBase++;
// Don't consider this path if we reach a length that can't
// possibly be better than the best so far.
if (lengthToBase == BestPathLength) continue;
}
assert(lengthToBase < BestPathLength);
// If this base *is* the destination, go ahead and start
// building the path into ReversePath.
if (base == Dest) {
// Reset the collected best-path information.
BestPathLength = lengthToBase;
ReversePath.clear();
// Otherwise, if there isn't a better path through this base,
// don't accumulate anything in the path.
} else {
const ProtocolInfo &baseInfo =
IGM.getProtocolInfo(base, ProtocolInfoKind::RequirementSignature);
if (!findBetterPath(base, baseInfo, lengthToBase))
continue;
}
// Okay, we've found a better path, and ReversePath contains a
// path leading from base to Dest.
assert(BestPathLength >= lengthToBase);
foundBetter = true;
// Add the link from proto to base if necessary.
if (!baseIndex.isPrefix()) {
ReversePath.push_back(baseIndex);
// If it isn't necessary, then we might be able to
// short-circuit considering the bases of this protocol.
} else {
if (lengthSoFar == BestPathLength)
return true;
}
}
return foundBetter;
}
};
} // end anonymous namespace
/// Return true if the witness table requires runtime instantiation to
/// handle resiliently-added requirements with default implementations.
static bool isResilientConformance(const NormalProtocolConformance *conformance) {
// If the protocol is not resilient, the conformance is not resilient
// either.
if (!conformance->getProtocol()->isResilient())
return false;
// If the protocol is in the same module as the conformance, we're
// not resilient.
if (conformance->getDeclContext()->getParentModule()
== conformance->getProtocol()->getParentModule())
return false;
// We have a resilient conformance.
return true;
}
/// Whether this protocol conformance has a dependent type witness.
static bool hasDependentTypeWitness(
const NormalProtocolConformance *conformance) {
auto DC = conformance->getDeclContext();
// If the conforming type isn't dependent, the below check is never true.
if (!DC->isGenericContext())
return false;
// Check whether any of the associated types are dependent.
if (conformance->forEachTypeWitness(nullptr,
[&](AssociatedTypeDecl *requirement, Type type,
TypeDecl *explicitDecl) -> bool {
// Skip associated types that don't have witness table entries.
if (!requirement->getOverriddenDecls().empty())
return false;
// RESILIENCE: this could be an opaque conformance
return type->hasTypeParameter();
})) {
return true;
}
return false;
}
/// Is there anything about the given conformance that requires witness
/// tables to be dependently-generated?
bool irgen::isDependentConformance(const NormalProtocolConformance *conformance) {
// If the conformance is resilient, this is always true.
if (isResilientConformance(conformance))
return true;
// Check whether any of the inherited conformances are dependent.
auto proto = conformance->getProtocol();
for (const auto &req : proto->getRequirementSignature()) {
if (req.getKind() != RequirementKind::Conformance ||
!req.getFirstType()->isEqual(proto->getSelfInterfaceType()))
continue;
auto inherited = req.getSecondType()->castTo<ProtocolType>()->getDecl();
if (inherited->isObjC())
continue;
if (isDependentConformance(conformance->getInheritedConformance(inherited)
->getRootNormalConformance()))
return true;
}
if (hasDependentTypeWitness(conformance))
return true;
// Check if there are any conditional conformances. Other forms of conditional
// requirements don't exist in the witness table.
return SILWitnessTable::enumerateWitnessTableConditionalConformances(
conformance, [](unsigned, CanType, ProtocolDecl *) { return true; });
}
static llvm::Value *
emitConditionalConformancesBuffer(IRGenFunction &IGF,
const ProtocolConformance *conformance) {
// Pointers to the witness tables, in the right order, which will be included
// in the buffer that gets passed to the witness table accessor.
llvm::SmallVector<llvm::Value *, 4> tables;
auto subMap = conformance->getSubstitutions(IGF.IGM.getSwiftModule());
auto rootConformance = conformance->getRootNormalConformance();
SILWitnessTable::enumerateWitnessTableConditionalConformances(
rootConformance, [&](unsigned, CanType type, ProtocolDecl *proto) {
auto substType = type.subst(subMap)->getCanonicalType();
auto reqConformance = subMap.lookupConformance(type, proto);
assert(reqConformance && "conditional conformance must exist");
tables.push_back(emitWitnessTableRef(IGF, substType, *reqConformance));
return /*finished?*/ false;
});
// No conditional requirements means no need for a buffer.
if (tables.empty()) {
return llvm::UndefValue::get(IGF.IGM.WitnessTablePtrPtrTy);
}
auto buffer = IGF.createAlloca(
llvm::ArrayType::get(IGF.IGM.WitnessTablePtrTy, tables.size()),
IGF.IGM.getPointerAlignment(), "conditional.requirement.buffer");
buffer = IGF.Builder.CreateStructGEP(buffer, 0, Size(0));
// Write each of the conditional witness tables into the buffer.
for (auto idx : indices(tables)) {
auto slot =
IGF.Builder.CreateConstArrayGEP(buffer, idx, IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(tables[idx], slot);
}
return buffer.getAddress();
}
static llvm::Value *emitWitnessTableAccessorCall(
IRGenFunction &IGF, const ProtocolConformance *conformance,
llvm::Value **srcMetadataCache) {
auto conformanceDescriptor =
IGF.IGM.getAddrOfProtocolConformanceDescriptor(
conformance->getRootNormalConformance());
// Emit the source metadata if we haven't yet.
if (!*srcMetadataCache) {
*srcMetadataCache = IGF.emitTypeMetadataRef(
conformance->getType()->getCanonicalType());
}
auto conditionalTables =
emitConditionalConformancesBuffer(IGF, conformance);
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetWitnessTableFn(),
{conformanceDescriptor, *srcMetadataCache,
conditionalTables});
call->setCallingConv(IGF.IGM.DefaultCC);
call->setDoesNotThrow();
return call;
}
/// Fetch the lazy access function for the given conformance of the
/// given type.
static llvm::Function *
getWitnessTableLazyAccessFunction(IRGenModule &IGM,
const ProtocolConformance *conformance) {
auto conformingType = conformance->getType()->getCanonicalType();
assert(!conformingType->hasArchetype());
auto rootConformance = conformance->getRootNormalConformance();
llvm::Function *accessor = IGM.getAddrOfWitnessTableLazyAccessFunction(
rootConformance, conformingType, ForDefinition);
// If we're not supposed to define the accessor, or if we already
// have defined it, just return the pointer.
if (!accessor->empty())
return accessor;
if (IGM.getOptions().optimizeForSize())
accessor->addFnAttr(llvm::Attribute::NoInline);
// Okay, define the accessor.
auto cacheVariable =
cast<llvm::GlobalVariable>(IGM.getAddrOfWitnessTableLazyCacheVariable(
rootConformance, conformingType, ForDefinition));
emitCacheAccessFunction(IGM, accessor, cacheVariable, CacheStrategy::Lazy,
[&](IRGenFunction &IGF, Explosion ¶ms) {
llvm::Value *conformingMetadataCache = nullptr;
return MetadataResponse::forComplete(
emitWitnessTableAccessorCall(IGF, conformance,
&conformingMetadataCache));
});
return accessor;
}
static ProtocolConformance &mapConformanceIntoContext(IRGenModule &IGM,
const ProtocolConformance &conf,
DeclContext *dc) {
return *conf.subst([&](SubstitutableType *t) -> Type {
return dc->mapTypeIntoContext(t);
},
LookUpConformanceInModule(IGM.getSwiftModule()));
}
WitnessIndex ProtocolInfo::getAssociatedTypeIndex(
IRGenModule &IGM,
AssociatedType assocType) const {
assert(!IGM.isResilient(assocType.getSourceProtocol(),
ResilienceExpansion::Maximal) &&
"Cannot ask for the associated type index of non-resilient protocol");
for (auto &witness : getWitnessEntries()) {
if (witness.matchesAssociatedType(assocType))
return getNonBaseWitnessIndex(&witness);
}
llvm_unreachable("didn't find entry for associated type");
}
namespace {
/// Conformance info for a witness table that can be directly generated.
class DirectConformanceInfo : public ConformanceInfo {
friend ProtocolInfo;
const NormalProtocolConformance *RootConformance;
public:
DirectConformanceInfo(const ProtocolConformance *C)
: RootConformance(C->getRootNormalConformance()) {}
llvm::Value *getTable(IRGenFunction &IGF,
llvm::Value **conformingMetadataCache) const override {
return IGF.IGM.getAddrOfWitnessTable(RootConformance);
}
llvm::Constant *tryGetConstantTable(IRGenModule &IGM,
CanType conformingType) const override {
return IGM.getAddrOfWitnessTable(RootConformance);
}
};
/// Conformance info for a witness table that is (or may be) dependent.
class AccessorConformanceInfo : public ConformanceInfo {
friend ProtocolInfo;
const ProtocolConformance *Conformance;
public:
AccessorConformanceInfo(const ProtocolConformance *C) : Conformance(C) {}
llvm::Value *getTable(IRGenFunction &IGF,
llvm::Value **typeMetadataCache) const override {
// If we're looking up a dependent type, we can't cache the result.
if (Conformance->getType()->hasArchetype()) {
return emitWitnessTableAccessorCall(IGF, Conformance,
typeMetadataCache);
}
// Otherwise, call a lazy-cache function.
auto accessor =
getWitnessTableLazyAccessFunction(IGF.IGM, Conformance);
llvm::CallInst *call = IGF.Builder.CreateCall(accessor, {});
call->setCallingConv(IGF.IGM.DefaultCC);
call->setDoesNotAccessMemory();
call->setDoesNotThrow();
return call;
}
llvm::Constant *tryGetConstantTable(IRGenModule &IGM,
CanType conformingType) const override {
return nullptr;
}
};
/// A class which lays out a specific conformance to a protocol.
class WitnessTableBuilder : public SILWitnessVisitor<WitnessTableBuilder> {
IRGenModule &IGM;
ConstantArrayBuilder &Table;
unsigned TableSize = ~0U; // will get overwritten unconditionally
SILWitnessTable *SILWT;
CanType ConcreteType;
const NormalProtocolConformance &Conformance;
const ProtocolConformance &ConformanceInContext;
ArrayRef<SILWitnessTable::Entry> SILEntries;
ArrayRef<SILWitnessTable::ConditionalConformance>
SILConditionalConformances;
Optional<FulfillmentMap> Fulfillments;
SmallVector<std::pair<size_t, const ConformanceInfo *>, 4>
SpecializedBaseConformances;
SmallVector<size_t, 4> ConditionalRequirementPrivateDataIndices;
// Conditional conformances and metadata caches are stored at negative
// offsets, with conditional conformances closest to 0.
unsigned NextPrivateDataIndex = 0;
bool ResilientConformance;
bool RequiresSpecialization = false;
const ProtocolInfo &PI;
public:
WitnessTableBuilder(IRGenModule &IGM, ConstantArrayBuilder &table,
SILWitnessTable *SILWT)
: IGM(IGM), Table(table), SILWT(SILWT),
ConcreteType(SILWT->getConformance()->getDeclContext()
->mapTypeIntoContext(
SILWT->getConformance()->getType())
->getCanonicalType()),
Conformance(*SILWT->getConformance()),
ConformanceInContext(
mapConformanceIntoContext(IGM, Conformance,
Conformance.getDeclContext())),
SILEntries(SILWT->getEntries()),
SILConditionalConformances(SILWT->getConditionalConformances()),
ResilientConformance(isResilientConformance(&Conformance)),
PI(IGM.getProtocolInfo(SILWT->getConformance()->getProtocol(),
(ResilientConformance
? ProtocolInfoKind::RequirementSignature
: ProtocolInfoKind::Full))) {
// If the conformance is resilient, we require runtime instantiation.
if (ResilientConformance)
RequiresSpecialization = true;
}
/// The number of entries in the witness table.
unsigned getTableSize() const { return TableSize; }
/// The number of private entries in the witness table.
unsigned getTablePrivateSize() const { return NextPrivateDataIndex; }
/// Whether this witness table must be specialized at runtime.
bool requiresSpecialization() const { return RequiresSpecialization; }
/// The top-level entry point.
void build();
/// Add reference to the protocol conformance descriptor that generated
/// this table.
void addProtocolConformanceDescriptor() {
auto descriptor =
IGM.getAddrOfProtocolConformanceDescriptor(&Conformance);
Table.addBitCast(descriptor, IGM.Int8PtrTy);
}
/// A base protocol is witnessed by a pointer to the conformance
/// of this type to that protocol.
void addOutOfLineBaseProtocol(ProtocolDecl *baseProto) {
#ifndef NDEBUG
auto &entry = SILEntries.front();
assert(entry.getKind() == SILWitnessTable::BaseProtocol
&& "sil witness table does not match protocol");
assert(entry.getBaseProtocolWitness().Requirement == baseProto
&& "sil witness table does not match protocol");
auto piIndex = PI.getBaseIndex(baseProto);
assert((size_t)piIndex.getValue() ==
Table.size() - WitnessTableFirstRequirementOffset &&
"offset doesn't match ProtocolInfo layout");
#endif
SILEntries = SILEntries.slice(1);
// TODO: Use the witness entry instead of falling through here.
// Look for conformance info.
auto *astConf = ConformanceInContext.getInheritedConformance(baseProto);
assert(astConf->getType()->isEqual(ConcreteType));
const ConformanceInfo &conf = IGM.getConformanceInfo(baseProto, astConf);
// If we can emit the base witness table as a constant, do so.
llvm::Constant *baseWitness = conf.tryGetConstantTable(IGM, ConcreteType);
if (baseWitness) {
Table.addBitCast(baseWitness, IGM.Int8PtrTy);
return;
}
// Otherwise, we'll need to derive it at instantiation time.
RequiresSpecialization = true;
SpecializedBaseConformances.push_back({Table.size(), &conf});
Table.addNullPointer(IGM.Int8PtrTy);
}
void addMethod(SILDeclRef requirement) {
auto &entry = SILEntries.front();
SILEntries = SILEntries.slice(1);
// Resilient conformances get a resilient witness table.
if (ResilientConformance)
return;
#ifndef NDEBUG
assert(entry.getKind() == SILWitnessTable::Method
&& "sil witness table does not match protocol");
assert(entry.getMethodWitness().Requirement == requirement
&& "sil witness table does not match protocol");
auto piIndex =
PI.getFunctionIndex(cast<AbstractFunctionDecl>(requirement.getDecl()));
assert((size_t)piIndex.getValue() ==
Table.size() - WitnessTableFirstRequirementOffset &&
"offset doesn't match ProtocolInfo layout");
#endif
SILFunction *Func = entry.getMethodWitness().Witness;
llvm::Constant *witness = nullptr;
if (Func) {
witness = IGM.getAddrOfSILFunction(Func, NotForDefinition);
} else {
// The method is removed by dead method elimination.
// It should be never called. We add a pointer to an error function.
witness = IGM.getDeletedMethodErrorFn();
}
Table.addBitCast(witness, IGM.Int8PtrTy);
return;
}
void addPlaceholder(MissingMemberDecl *placeholder) {
llvm_unreachable("cannot emit a witness table with placeholders in it");
}
void addAssociatedType(AssociatedType requirement) {
auto &entry = SILEntries.front();
SILEntries = SILEntries.slice(1);
// Resilient conformances get a resilient witness table.
if (ResilientConformance)
return;
#ifndef NDEBUG
assert(entry.getKind() == SILWitnessTable::AssociatedType
&& "sil witness table does not match protocol");
assert(entry.getAssociatedTypeWitness().Requirement
== requirement.getAssociation()
&& "sil witness table does not match protocol");
auto piIndex = PI.getAssociatedTypeIndex(IGM, requirement);
assert((size_t)piIndex.getValue() ==
Table.size() - WitnessTableFirstRequirementOffset &&
"offset doesn't match ProtocolInfo layout");
#else
(void)entry;
#endif
auto associate =
Conformance.getTypeWitness(requirement.getAssociation(), nullptr)
->getCanonicalType();
if (associate->hasTypeParameter())
RequiresSpecialization = true;
llvm::Constant *witness =
IGM.getAssociatedTypeWitness(associate, /*inProtocolContext=*/false);
Table.addBitCast(witness, IGM.Int8PtrTy);
}
void addAssociatedConformance(AssociatedConformance requirement) {
// FIXME: Add static witness tables for type conformances.
auto &entry = SILEntries.front();
(void)entry;
SILEntries = SILEntries.slice(1);
if (ResilientConformance)
return;
auto associate =
ConformanceInContext.getAssociatedType(
requirement.getAssociation())->getCanonicalType();
ProtocolConformanceRef associatedConformance =
ConformanceInContext.getAssociatedConformance(
requirement.getAssociation(),
requirement.getAssociatedRequirement());
#ifndef NDEBUG
assert(entry.getKind() == SILWitnessTable::AssociatedTypeProtocol
&& "sil witness table does not match protocol");
auto associatedWitness = entry.getAssociatedTypeProtocolWitness();
assert(associatedWitness.Requirement == requirement.getAssociation()
&& "sil witness table does not match protocol");
assert(associatedWitness.Protocol ==
requirement.getAssociatedRequirement()
&& "sil witness table does not match protocol");
auto piIndex = PI.getAssociatedConformanceIndex(requirement);
assert((size_t)piIndex.getValue() ==
Table.size() - WitnessTableFirstRequirementOffset &&
"offset doesn't match ProtocolInfo layout");
#endif
llvm::Constant *wtableAccessFunction =
getAssociatedTypeWitnessTableAccessFunction(requirement,
associate,
associatedConformance);
Table.addBitCast(wtableAccessFunction, IGM.Int8PtrTy);
}
/// Build the instantiation function that runs at the end of witness
/// table specialization.
llvm::Constant *buildInstantiationFunction();
private:
void addConditionalConformances() {
for (auto conditional : SILConditionalConformances) {
// We don't actually need to know anything about the specific
// conformances here, just make sure we get right private data slots.
(void)conditional;
auto reqtIndex = getNextPrivateDataIndex();
ConditionalRequirementPrivateDataIndices.push_back(reqtIndex);
}
}
llvm::Constant *
getAssociatedTypeWitnessTableAccessFunction(
AssociatedConformance requirement,
CanType associatedType,
ProtocolConformanceRef conformance);
void emitReturnOfCheckedLoadFromCache(IRGenFunction &IGF,
Address destTable,
llvm::Value *selfMetadata,
llvm::function_ref<MetadataResponse()> body);
/// Allocate another word of private data storage in the conformance table.
unsigned getNextPrivateDataIndex() {
RequiresSpecialization = true;
return NextPrivateDataIndex++;
}
Address getAddressOfPrivateDataSlot(IRGenFunction &IGF, Address table,
unsigned index) {
assert(index < NextPrivateDataIndex);
return IGF.Builder.CreateConstArrayGEP(
table, privateWitnessTableIndexToTableOffset(index),
IGF.IGM.getPointerSize());
}
const FulfillmentMap &getFulfillmentMap() {
if (Fulfillments) return *Fulfillments;
Fulfillments.emplace();
if (ConcreteType->hasArchetype()) {
struct Callback : FulfillmentMap::InterestingKeysCallback {
bool isInterestingType(CanType type) const override {
return isa<ArchetypeType>(type);
}
bool hasInterestingType(CanType type) const override {
return type->hasArchetype();
}
bool hasLimitedInterestingConformances(CanType type) const override {
return false;
}
GenericSignature::ConformsToArray
getInterestingConformances(CanType type) const override {
llvm_unreachable("no limits");
}
CanType getSuperclassBound(CanType type) const override {
if (auto superclassTy = cast<ArchetypeType>(type)->getSuperclass())
return superclassTy->getCanonicalType();
return CanType();
}
} callback;
Fulfillments->searchTypeMetadata(IGM, ConcreteType, IsExact,
MetadataState::Abstract,
/*sourceIndex*/ 0, MetadataPath(),
callback);
}
return *Fulfillments;
}
public:
/// Collect the set of resilient witnesses, which will become part of the
/// protocol conformance descriptor.
void collectResilientWitnesses(
SmallVectorImpl<llvm::Constant *> &resilientWitnesses);
};
} // end anonymous namespace
/// Build the witness table.
void WitnessTableBuilder::build() {
addConditionalConformances();
visitProtocolDecl(Conformance.getProtocol());
TableSize = Table.size();
}
llvm::Constant *IRGenModule::getAssociatedTypeWitness(CanType type,
bool inProtocolContext) {
// FIXME: If we can directly reference constant type metadata, do so.
// Form a reference to the mangled name for this type.
assert(!type->hasArchetype() && "type cannot contain archetypes");
auto role = inProtocolContext
? MangledTypeRefRole::DefaultAssociatedTypeWitness
: MangledTypeRefRole::Metadata;
auto typeRef = getTypeRef(type, role);
// Set the low bit to indicate that this is a mangled name.
auto witness = llvm::ConstantExpr::getPtrToInt(typeRef, IntPtrTy);
unsigned bit = ProtocolRequirementFlags::AssociatedTypeMangledNameBit;
auto bitConstant = llvm::ConstantInt::get(IntPtrTy, bit);
witness = llvm::ConstantExpr::getAdd(witness, bitConstant);
return llvm::ConstantExpr::getIntToPtr(witness, Int8PtrTy);
}
/// Return a function which will return a particular witness table
/// conformance. The function will be passed the metadata for which
/// the conformance is being requested; it may ignore this (perhaps
/// implicitly by taking no arguments).
static llvm::Constant *
getOrCreateWitnessTableAccessFunction(IRGenModule &IGM,
ProtocolConformance *conformance) {
assert(!conformance->getType()->hasArchetype() &&
"cannot do this for dependent type");
// We always emit an access function for conformances, and in principle
// it is always possible to just use that here directly. However,
// if it's dependent, doing so won't allow us to cache the result.
// For the specific use case of an associated type conformance, we could
// use a cache in the witness table; but that wastes space per conformance
// and won't let us re-use the cache with other non-dependent uses in
// the module. Therefore, in this case, we use the address of the lazy-cache
// function.
return getWitnessTableLazyAccessFunction(IGM, conformance);
}
static void buildAssociatedTypeValueName(CanType depAssociatedType,
SmallString<128> &name) {
if (auto memberType = dyn_cast<DependentMemberType>(depAssociatedType)) {
buildAssociatedTypeValueName(memberType.getBase(), name);
name += '.';
name += memberType->getName().str();
} else {
assert(isa<GenericTypeParamType>(depAssociatedType)); // Self
}
}
llvm::Constant *WitnessTableBuilder::
getAssociatedTypeWitnessTableAccessFunction(AssociatedConformance requirement,
CanType associatedType,
ProtocolConformanceRef associatedConformance) {
bool hasArchetype = associatedType->hasArchetype();
if (!hasArchetype && !ResilientConformance) {
assert(associatedConformance.isConcrete() &&
"no concrete conformance for non-dependent type");
return getOrCreateWitnessTableAccessFunction(IGM,
associatedConformance.getConcrete());
}
// Otherwise, emit an access function.
llvm::Function *accessor =
IGM.getAddrOfAssociatedTypeWitnessTableAccessFunction(&Conformance,
requirement);
IRGenFunction IGF(IGM, accessor);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, accessor);
if (IGM.getOptions().optimizeForSize())
accessor->addFnAttr(llvm::Attribute::NoInline);
Explosion parameters = IGF.collectParameters();
llvm::Value *associatedTypeMetadata = parameters.claimNext();
// We use a non-standard name for the type that states the association
// requirement rather than the concrete type.
if (IGM.EnableValueNames) {
SmallString<128> name;
name += ConcreteType->getString();
buildAssociatedTypeValueName(requirement.getAssociation(), name);
associatedTypeMetadata->setName(name);
}
llvm::Value *self = parameters.claimNext();
setTypeMetadataName(IGM, self, ConcreteType);
Address destTable(parameters.claimNext(), IGM.getPointerAlignment());
setProtocolWitnessTableName(IGM, destTable.getAddress(), ConcreteType,
Conformance.getProtocol());
ProtocolDecl *associatedProtocol = requirement.getAssociatedRequirement();
const ConformanceInfo *conformanceI = nullptr;
if (associatedConformance.isConcrete()) {
assert(associatedType->isEqual(associatedConformance.getConcrete()->getType()));
conformanceI = &IGM.getConformanceInfo(associatedProtocol,
associatedConformance.getConcrete());
// If we can emit a constant table, do so.
// In principle, any time we can do this, we should try to re-use this
// function for other conformances. But that should typically already
// be covered by the !hasArchetype() check above.
if (auto constantTable =
conformanceI->tryGetConstantTable(IGM, associatedType)) {
IGF.Builder.CreateRet(constantTable);
return accessor;
}
}
// If there are no archetypes, return a reference to the table. There is
// no need for a cache.
if (!hasArchetype) {
auto wtable = MetadataResponse::forComplete(
conformanceI->getTable(IGF, &associatedTypeMetadata))
.getMetadata();
IGF.Builder.CreateRet(wtable);
return accessor;
}
IGF.bindLocalTypeDataFromSelfWitnessTable(
&Conformance,
destTable.getAddress(),
[&](CanType type) {
return Conformance.getDeclContext()->mapTypeIntoContext(type)
->getCanonicalType();
});
// If the witness table is directly fulfillable from the type,
// we don't need a cache entry.
// TODO: maybe we should have a cache entry anyway if the fulfillment
// is expensive.
if (auto fulfillment =
getFulfillmentMap().getWitnessTable(associatedType,
associatedProtocol)) {
// We don't know that 'self' is any better than an abstract metadata here.
auto source = MetadataResponse::forBounded(self, MetadataState::Abstract);
llvm::Value *wtable =
fulfillment->Path.followFromTypeMetadata(IGF, ConcreteType, source,
MetadataState::Complete,
/*cache*/ nullptr)
.getMetadata();
IGF.Builder.CreateRet(wtable);
return accessor;
}
// Bind local type data from the metadata arguments.
IGF.bindLocalTypeDataFromTypeMetadata(associatedType, IsExact,
associatedTypeMetadata,
MetadataState::Abstract);
IGF.bindLocalTypeDataFromTypeMetadata(ConcreteType, IsExact, self,
MetadataState::Abstract);
// For now, assume that finding an abstract conformance is always
// fast enough that it's not worth caching.
// TODO: provide an API to find the best metadata path to the conformance
// and decide whether it's expensive enough to be worth caching.
if (!conformanceI) {
assert(associatedConformance.isAbstract());
auto wtable =
emitArchetypeWitnessTableRef(IGF, cast<ArchetypeType>(associatedType),
associatedConformance.getAbstract());
IGF.Builder.CreateRet(wtable);
return accessor;
}
// Otherwise, we need a cache entry.
emitReturnOfCheckedLoadFromCache(IGF, destTable, self,
[&]() -> MetadataResponse {
// Pretend that we have a response here.
return MetadataResponse::forComplete(
conformanceI->getTable(IGF, &associatedTypeMetadata));
});
return accessor;
}
void WitnessTableBuilder::
emitReturnOfCheckedLoadFromCache(IRGenFunction &IGF, Address destTable,
llvm::Value *selfMetadata,
llvm::function_ref<MetadataResponse()> body) {
// Allocate a new cache slot and drill down to it.
auto cache =
getAddressOfPrivateDataSlot(IGF, destTable, getNextPrivateDataIndex());
llvm::Type *expectedTy = IGF.CurFn->getReturnType();
bool isReturningResponse = false;
if (expectedTy == IGF.IGM.TypeMetadataResponseTy) {
isReturningResponse = true;
expectedTy = IGF.IGM.TypeMetadataPtrTy;
}
cache = IGF.Builder.CreateBitCast(cache, expectedTy->getPointerTo());
// Load and check whether it was null.
auto cachedResult = IGF.Builder.CreateLoad(cache);
// TODO: When LLVM supports Consume, we should use it here.
if (IGF.IGM.IRGen.Opts.Sanitizers & SanitizerKind::Thread)
cachedResult->setOrdering(llvm::AtomicOrdering::Acquire);
auto cacheIsEmpty = IGF.Builder.CreateIsNull(cachedResult);
llvm::BasicBlock *fetchBB = IGF.createBasicBlock("fetch");
llvm::BasicBlock *contBB = IGF.createBasicBlock("cont");
llvm::BasicBlock *entryBB = IGF.Builder.GetInsertBlock();
IGF.Builder.CreateCondBr(cacheIsEmpty, fetchBB, contBB);
unsigned expectedPHICount = (isReturningResponse ? 3 : 2);
// Create a phi in the continuation block and use the loaded value if
// we branched directly here. Note that we arrange blocks so that we
// fall through into this.
IGF.Builder.emitBlock(contBB);
llvm::PHINode *result = IGF.Builder.CreatePHI(expectedTy, expectedPHICount);
result->addIncoming(cachedResult, entryBB);
llvm::Constant *completedState = nullptr;
llvm::PHINode *resultState = nullptr;
if (isReturningResponse) {
completedState = MetadataResponse::getCompletedState(IGF.IGM);
resultState = IGF.Builder.CreatePHI(IGF.IGM.SizeTy, expectedPHICount);
resultState->addIncoming(completedState, entryBB);
llvm::Value *returnValue =
MetadataResponse(result, resultState, MetadataState::Abstract)
.combine(IGF);
IGF.Builder.CreateRet(returnValue);
} else {
IGF.Builder.CreateRet(result);
}
// In the fetch block, evaluate the body.
IGF.Builder.emitBlock(fetchBB);
MetadataResponse response = body();
// The way we jam witness tables into this infrastructure involves
// pretending that they're statically-complete metadata.
assert(isReturningResponse || response.isStaticallyKnownComplete());
llvm::Value *fetchedState = nullptr;
if (isReturningResponse) {
response.ensureDynamicState(IGF);
fetchedState = response.getDynamicState();
}
llvm::Value *fetchedResult = response.getMetadata();
// Skip caching if we're working with responses and the fetched result
// is not complete.
if (isReturningResponse && !response.isStaticallyKnownComplete()) {
auto isCompleteBB = IGF.createBasicBlock("is_complete");
auto isComplete =
IGF.Builder.CreateICmpEQ(fetchedState, completedState);
auto fetchingBB = IGF.Builder.GetInsertBlock();
IGF.Builder.CreateCondBr(isComplete, isCompleteBB, contBB);
result->addIncoming(fetchedResult, fetchingBB);
resultState->addIncoming(fetchedState, fetchingBB);
IGF.Builder.emitBlock(isCompleteBB);
// If the fetched result is statically known to be complete, there is no
// patch which involves not returning the completed state, so destroy the
// PHI node we created for the state.
} else if (isReturningResponse) {
resultState->replaceAllUsesWith(completedState);
resultState->eraseFromParent();
resultState = nullptr;
}
// Store the fetched result back to the cache.
// We need to transitively ensure that any stores initializing the result
// that are visible to us are visible to callers.
IGF.Builder.CreateStore(fetchedResult, cache)->setOrdering(
llvm::AtomicOrdering::Release);
auto cachingBB = IGF.Builder.GetInsertBlock();
IGF.Builder.CreateBr(contBB);
result->addIncoming(fetchedResult, cachingBB);
if (resultState)
resultState->addIncoming(completedState, cachingBB);
}
void WitnessTableBuilder::collectResilientWitnesses(
SmallVectorImpl<llvm::Constant *> &resilientWitnesses) {
if (!ResilientConformance)
return;
assert(resilientWitnesses.empty());
for (auto &entry : SILWT->getEntries()) {
// Associated type witness.
if (entry.getKind() == SILWitnessTable::AssociatedType) {
// Associated type witness.
auto assocType = entry.getAssociatedTypeWitness().Requirement;
auto associate = Conformance.getTypeWitness(assocType, nullptr)
->getCanonicalType();
llvm::Constant *witness =
IGM.getAssociatedTypeWitness(associate, /*inProtocolContext=*/false);
resilientWitnesses.push_back(witness);
continue;
}
// Associated conformance access function.
if (entry.getKind() == SILWitnessTable::AssociatedTypeProtocol) {
const auto &witness = entry.getAssociatedTypeProtocolWitness();
auto associate =
ConformanceInContext.getAssociatedType(
witness.Requirement)->getCanonicalType();
ProtocolConformanceRef associatedConformance =
ConformanceInContext.getAssociatedConformance(witness.Requirement,
witness.Protocol);
AssociatedConformance requirement(SILWT->getConformance()->getProtocol(),
witness.Requirement,
witness.Protocol);
llvm::Constant *wtableAccessFunction =
getAssociatedTypeWitnessTableAccessFunction(requirement,
associate,
associatedConformance);
resilientWitnesses.push_back(wtableAccessFunction);
continue;
}
if (entry.getKind() != SILWitnessTable::Method)
continue;
SILFunction *Func = entry.getMethodWitness().Witness;
llvm::Constant *witness;
if (Func) {
witness = IGM.getAddrOfSILFunction(Func, NotForDefinition);
} else {
// The method is removed by dead method elimination.
// It should be never called. We add a null pointer.
witness = nullptr;
}
resilientWitnesses.push_back(witness);
}
}
llvm::Constant *WitnessTableBuilder::buildInstantiationFunction() {
// We need an instantiation function if the base conformance
// is non-dependent.
if (SpecializedBaseConformances.empty() &&
ConditionalRequirementPrivateDataIndices.empty())
return nullptr;
llvm::Function *fn =
IGM.getAddrOfGenericWitnessTableInstantiationFunction(&Conformance);
IRGenFunction IGF(IGM, fn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, fn);
auto PointerAlignment = IGM.getPointerAlignment();
auto PointerSize = IGM.getPointerSize();
// Break out the parameters.
Explosion params = IGF.collectParameters();
Address wtable(params.claimNext(), PointerAlignment);
llvm::Value *metadata = params.claimNext();
IGF.bindLocalTypeDataFromTypeMetadata(ConcreteType, IsExact, metadata,
MetadataState::Complete);
llvm::Value *instantiationArgs = params.claimNext();
Address conditionalTables(
IGF.Builder.CreateBitCast(instantiationArgs,
IGF.IGM.WitnessTablePtrPtrTy),
PointerAlignment);
/// Run through the conditional conformance witness tables, pulling them out
/// of the slice and putting them into the private data of the witness table.
for (auto idx : indices(ConditionalRequirementPrivateDataIndices)) {
Address conditionalTablePtr =
IGF.Builder.CreateConstArrayGEP(conditionalTables, idx, PointerSize);
Address slot = getAddressOfPrivateDataSlot(
IGF, wtable, ConditionalRequirementPrivateDataIndices[idx]);
auto conditionalTable = IGF.Builder.CreateLoad(conditionalTablePtr);
auto coercedSlot =
IGF.Builder.CreateElementBitCast(slot, conditionalTable->getType());
IGF.Builder.CreateStore(conditionalTable, coercedSlot);
// Register local type data for the conditional conformance witness table.
const auto &condConformance = SILConditionalConformances[idx];
CanType reqTypeInContext =
Conformance.getDeclContext()
->mapTypeIntoContext(condConformance.Requirement)
->getCanonicalType();
if (auto archetype = dyn_cast<ArchetypeType>(reqTypeInContext)) {
auto condProto = condConformance.Conformance.getRequirement();
IGF.setUnscopedLocalTypeData(
archetype,
LocalTypeDataKind::forAbstractProtocolWitnessTable(condProto),
conditionalTable);
}
}
// Initialize all the specialized base conformances.
for (auto &base : SpecializedBaseConformances) {
// Ask the ConformanceInfo to emit the wtable.
llvm::Value *baseWTable =
base.second->getTable(IGF, &metadata);
baseWTable = IGF.Builder.CreateBitCast(baseWTable, IGM.Int8PtrTy);
// Store that to the appropriate slot in the new witness table.
Address slot =
IGF.Builder.CreateConstArrayGEP(wtable, base.first, PointerSize);
IGF.Builder.CreateStore(baseWTable, slot);
}
IGF.Builder.CreateRetVoid();
return fn;
}
namespace {
/// Builds a protocol conformance descriptor.
class ProtocolConformanceDescriptorBuilder {
IRGenModule &IGM;
ConstantStructBuilder &B;
const NormalProtocolConformance *Conformance;
SILWitnessTable *SILWT;
ConformanceDescription Description;
ConformanceFlags Flags;
public:
ProtocolConformanceDescriptorBuilder(
IRGenModule &IGM,
ConstantStructBuilder &B,
const ConformanceDescription &description)
: IGM(IGM), B(B), Conformance(description.conformance),
SILWT(description.wtable), Description(description) { }
void layout() {
addProtocol();
addConformingType();
addWitnessTable();
addFlags();
addContext();
addConditionalRequirements();
addResilientWitnesses();
addGenericWitnessTable();
B.suggestType(IGM.ProtocolConformanceDescriptorTy);
}
void addProtocol() {
// Relative reference to the protocol descriptor.
auto protocol = Conformance->getProtocol();
auto descriptorRef = IGM.getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forProtocolDescriptor(protocol));
B.addRelativeAddress(descriptorRef);
}
void addConformingType() {
// Add a relative reference to the type, with the type reference
// kind stored in the flags.
auto ref =
IGM.getTypeEntityReference(Conformance->getType()->getAnyNominal());
B.addRelativeAddress(ref.getValue());
Flags = Flags.withTypeReferenceKind(ref.getKind());
}
void addWitnessTable() {
// Note the number of conditional requirements.
Flags = Flags.withNumConditionalRequirements(
Conformance->getConditionalRequirements().size());
// Relative reference to the witness table.
auto witnessTableRef =
ConstantReference(Description.pattern, ConstantReference::Direct);
B.addRelativeAddress(witnessTableRef);
}
void addFlags() {
// Miscellaneous flags.
Flags = Flags.withIsRetroactive(Conformance->isRetroactive());
Flags =
Flags.withIsSynthesizedNonUnique(Conformance->isSynthesizedNonUnique());
Flags = Flags.withHasResilientWitnesses(
!Description.resilientWitnesses.empty());
Flags =
Flags.withHasGenericWitnessTable(Description.requiresSpecialization);
// Add the flags.
B.addInt32(Flags.getIntValue());
}
void addContext() {
if (!Conformance->isRetroactive())
return;
auto moduleContext =
Conformance->getDeclContext()->getModuleScopeContext();
ConstantReference moduleContextRef =
IGM.getAddrOfParentContextDescriptor(moduleContext);
B.addRelativeAddress(moduleContextRef);
}
void addConditionalRequirements() {
if (Conformance->getConditionalRequirements().empty())
return;
auto nominal = Conformance->getType()->getAnyNominal();
irgen::addGenericRequirements(IGM, B,
nominal->getGenericSignatureOfContext(),
Conformance->getConditionalRequirements());
}
void addResilientWitnesses() {
if (Description.resilientWitnesses.empty())
return;
// TargetResilientWitnessesHeader
ArrayRef<llvm::Constant *> witnesses = Description.resilientWitnesses;
B.addInt32(witnesses.size());
for (const auto &entry : SILWT->getEntries()) {
// Add the requirement descriptor.
if (entry.getKind() == SILWitnessTable::AssociatedType) {
// Associated type descriptor.
auto assocType = entry.getAssociatedTypeWitness().Requirement;
auto assocTypeDescriptor =
IGM.getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forAssociatedTypeDescriptor(assocType));
B.addRelativeAddress(assocTypeDescriptor);
} else if (entry.getKind() == SILWitnessTable::AssociatedTypeProtocol) {
// Associated conformance descriptor.
const auto &witness = entry.getAssociatedTypeProtocolWitness();
AssociatedConformance requirement(
SILWT->getConformance()->getProtocol(),
witness.Requirement,
witness.Protocol);
auto assocConformanceDescriptor =
IGM.getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forAssociatedConformanceDescriptor(requirement));
B.addRelativeAddress(assocConformanceDescriptor);
} else if (entry.getKind() == SILWitnessTable::Method) {
// Method descriptor.
auto declRef = entry.getMethodWitness().Requirement;
auto requirement =
IGM.getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forMethodDescriptor(declRef));
B.addRelativeAddress(requirement);
} else {
// Not part of the resilient witness table.
continue;
}
// Add the witness.
B.addRelativeAddress(witnesses.front());
witnesses = witnesses.drop_front();
}
assert(witnesses.empty() && "Wrong # of resilient witnesses");
}
void addGenericWitnessTable() {
if (!Description.requiresSpecialization)
return;
// WitnessTableSizeInWords
B.addInt(IGM.Int16Ty, Description.witnessTableSize);
// WitnessTablePrivateSizeInWordsAndRequiresInstantiation
B.addInt(IGM.Int16Ty,
(Description.witnessTablePrivateSize << 1) |
Description.hasDependentAssociatedTypeWitnesses);
// Instantiation function
B.addRelativeAddressOrNull(Description.instantiationFn);
// Private data
{
auto privateDataTy =
llvm::ArrayType::get(IGM.Int8PtrTy,
swift::NumGenericMetadataPrivateDataWords);
auto privateDataInit = llvm::Constant::getNullValue(privateDataTy);
auto privateData =
new llvm::GlobalVariable(IGM.Module, privateDataTy,
/*constant*/ false,
llvm::GlobalVariable::InternalLinkage,
privateDataInit, "");
B.addRelativeAddress(privateData);
}
}
};
}
void IRGenModule::emitProtocolConformance(
const ConformanceDescription &record) {
auto conformance = record.conformance;
// Emit additional metadata to be used by reflection.
emitAssociatedTypeMetadataRecord(conformance);
// Form the protocol conformance descriptor.
ConstantInitBuilder initBuilder(*this);
auto init = initBuilder.beginStruct();
ProtocolConformanceDescriptorBuilder builder(*this, init, record);
builder.layout();
auto var =
cast<llvm::GlobalVariable>(
getAddrOfProtocolConformanceDescriptor(conformance,
init.finishAndCreateFuture()));
var->setConstant(true);
setTrueConstGlobal(var);
}
void IRGenModule::ensureRelativeSymbolCollocation(SILWitnessTable &wt) {
// Only resilient conformances use relative pointers for witness methods.
if (wt.isDeclaration() || isAvailableExternally(wt.getLinkage()) ||
!isResilientConformance(wt.getConformance()))
return;
for (auto &entry : wt.getEntries()) {
if (entry.getKind() != SILWitnessTable::Method)
continue;
auto *witness = entry.getMethodWitness().Witness;
if (witness)
IRGen.forceLocalEmitOfLazyFunction(witness);
}
}
/// Do a memoized witness-table layout for a protocol.
const ProtocolInfo &IRGenModule::getProtocolInfo(ProtocolDecl *protocol,
ProtocolInfoKind kind) {
// If the protocol is resilient, we cannot know the full witness table layout.
assert(!isResilient(protocol, ResilienceExpansion::Maximal) ||
kind == ProtocolInfoKind::RequirementSignature);
return Types.getProtocolInfo(protocol, kind);
}
/// Do a memoized witness-table layout for a protocol.
const ProtocolInfo &TypeConverter::getProtocolInfo(ProtocolDecl *protocol,
ProtocolInfoKind kind) {
// Check whether we've already translated this protocol.
auto it = Protocols.find(protocol);
if (it != Protocols.end() && it->getSecond()->getKind() >= kind)
return *it->getSecond();
// If not, lay out the protocol's witness table, if it needs one.
WitnessTableLayout layout(kind);
if (Lowering::TypeConverter::protocolRequiresWitnessTable(protocol))
layout.visitProtocolDecl(protocol);
// Create a ProtocolInfo object from the layout.
std::unique_ptr<ProtocolInfo> info = ProtocolInfo::create(layout.getEntries(),
kind);
// Verify that we haven't generated an incompatible layout.
if (it != Protocols.end()) {
ArrayRef<WitnessTableEntry> originalEntries =
it->second->getWitnessEntries();
ArrayRef<WitnessTableEntry> newEntries = info->getWitnessEntries();
assert(newEntries.size() >= originalEntries.size());
assert(newEntries.take_front(originalEntries.size()) == originalEntries);
(void)originalEntries;
(void)newEntries;
}
// Memoize.
std::unique_ptr<const ProtocolInfo> &cachedInfo = Protocols[protocol];
cachedInfo = std::move(info);
// Done.
return *cachedInfo;
}
/// Allocate a new ProtocolInfo.
std::unique_ptr<ProtocolInfo>
ProtocolInfo::create(ArrayRef<WitnessTableEntry> table, ProtocolInfoKind kind) {
size_t bufferSize = totalSizeToAlloc<WitnessTableEntry>(table.size());
void *buffer = ::operator new(bufferSize);
return std::unique_ptr<ProtocolInfo>(new(buffer) ProtocolInfo(table, kind));
}
// Provide a unique home for the ConformanceInfo vtable.
void ConformanceInfo::anchor() {}
/// Find the conformance information for a protocol.
const ConformanceInfo &
IRGenModule::getConformanceInfo(const ProtocolDecl *protocol,
const ProtocolConformance *conformance) {
assert(conformance->getProtocol() == protocol &&
"conformance is for wrong protocol");
auto checkCache =
[this](const ProtocolConformance *conf) -> const ConformanceInfo * {
// Check whether we've already cached this.
auto it = Conformances.find(conf);
if (it != Conformances.end())
return it->second.get();
return nullptr;
};
if (auto found = checkCache(conformance))
return *found;
// Drill down to the root normal
auto normalConformance = conformance->getRootNormalConformance();
const ConformanceInfo *info;
// If the conformance is dependent in any way, we need to unique it.
// TODO: maybe this should apply whenever it's out of the module?
// TODO: actually enable this
// FIXME: Both implementations of ConformanceInfo are trivially-destructible,
// so in theory we could allocate them on a BumpPtrAllocator. But there's not
// a good one for us to use. (The ASTContext's outlives the IRGenModule in
// batch mode.)
if (isDependentConformance(normalConformance) ||
// Foreign types need to go through the accessor to unique the witness
// table.
normalConformance->isSynthesizedNonUnique()) {
info = new AccessorConformanceInfo(conformance);
Conformances.try_emplace(conformance, info);
} else {
// Otherwise, we can use a direct-referencing conformance, which can get
// away with the non-specialized conformance.
if (auto found = checkCache(normalConformance))
return *found;
info = new DirectConformanceInfo(normalConformance);
Conformances.try_emplace(normalConformance, info);
}
return *info;
}
/// Whether the witness table will be constant.
static bool isConstantWitnessTable(SILWitnessTable *wt) {
for (const auto &entry : wt->getEntries()) {
switch (entry.getKind()) {
case SILWitnessTable::Invalid:
case SILWitnessTable::AssociatedTypeProtocol:
case SILWitnessTable::BaseProtocol:
case SILWitnessTable::Method:
continue;
case SILWitnessTable::AssociatedType:
// Associated types are cached in the witness table.
// FIXME: If we start emitting constant references to type metadata here,
// we will need to ask the witness table builder for this information.
return false;
}
}
return true;
}
void IRGenModule::emitSILWitnessTable(SILWitnessTable *wt) {
// Don't emit a witness table if it is a declaration.
if (wt->isDeclaration())
return;
// Don't emit a witness table that is available externally.
// It can end up in having duplicate symbols for generated associated type
// metadata access functions.
// Also, it is not a big benefit for LLVM to emit such witness tables.
if (isAvailableExternally(wt->getLinkage()))
return;
auto *conf = wt->getConformance();
PrettyStackTraceType stackTraceRAII(Context, "emitting witness table for",
conf->getType());
PrettyStackTraceDecl stackTraceRAII2("...conforming to", conf->getProtocol());
// Build the witness table.
ConstantInitBuilder builder(*this);
auto wtableContents = builder.beginArray(Int8PtrTy);
WitnessTableBuilder wtableBuilder(*this, wtableContents, wt);
wtableBuilder.build();
SmallVector<llvm::Constant *, 4> resilientWitnesses;
// Collect the resilient witnesses to go into the conformance descriptor.
wtableBuilder.collectResilientWitnesses(resilientWitnesses);
// Produce the initializer value.
auto initializer = wtableContents.finishAndCreateFuture();
bool isDependent = isDependentConformance(conf);
auto global = cast<llvm::GlobalVariable>(
isDependent
? getAddrOfWitnessTablePattern(conf, initializer)
: getAddrOfWitnessTable(conf, initializer));
global->setConstant(isDependent || isConstantWitnessTable(wt));
global->setAlignment(getWitnessTableAlignment().getValue());
// Collect the information that will go into the protocol conformance
// descriptor.
ConformanceDescription description(conf, wt, global,
wtableBuilder.getTableSize(),
wtableBuilder.getTablePrivateSize(),
wtableBuilder.requiresSpecialization(),
hasDependentTypeWitness(conf));
// Build the instantiation function, we if need one.
description.instantiationFn = wtableBuilder.buildInstantiationFunction();
description.resilientWitnesses = std::move(resilientWitnesses);
// Record this conformance descriptor.
addProtocolConformance(std::move(description));
// Behavior conformances can't be reflected.
if (conf->isBehaviorConformance())
return;
// Trigger the lazy emission of the foreign type metadata.
CanType conformingType = conf->getType()->getCanonicalType();
if (requiresForeignTypeMetadata(conformingType)) {
(void)getAddrOfForeignTypeMetadataCandidate(conformingType);
}
}
/// True if a function's signature in LLVM carries polymorphic parameters.
/// Generic functions and protocol witnesses carry polymorphic parameters.
bool irgen::hasPolymorphicParameters(CanSILFunctionType ty) {
switch (ty->getRepresentation()) {
case SILFunctionTypeRepresentation::Block:
// Should never be polymorphic.
assert(!ty->isPolymorphic() && "polymorphic C function?!");
return false;
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::Closure:
return ty->isPolymorphic();
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::ObjCMethod:
// May be polymorphic at the SIL level, but no type metadata is actually
// passed.
return false;
case SILFunctionTypeRepresentation::WitnessMethod:
// Always carries polymorphic parameters for the Self type.
return true;
}
llvm_unreachable("Not a valid SILFunctionTypeRepresentation.");
}
/// Emit a polymorphic parameters clause, binding all the metadata necessary.
void EmitPolymorphicParameters::emit(Explosion &in,
WitnessMetadata *witnessMetadata,
const GetParameterFn &getParameter) {
// Collect any early sources and bind local type data from them.
for (auto &source : getSources()) {
bindExtraSource(source, in, witnessMetadata);
}
auto getInContext = [&](CanType type) -> CanType {
return getTypeInContext(type);
};
// Collect any concrete type metadata that's been passed separately.
enumerateUnfulfilledRequirements([&](GenericRequirement requirement) {
auto value = in.claimNext();
bindGenericRequirement(IGF, requirement, value, MetadataState::Complete,
getInContext);
});
// Bind all the fulfillments we can from the formal parameters.
bindParameterSources(getParameter);
}
MetadataResponse
MetadataPath::followFromTypeMetadata(IRGenFunction &IGF,
CanType sourceType,
MetadataResponse source,
DynamicMetadataRequest request,
Map<MetadataResponse> *cache) const {
LocalTypeDataKey key = {
sourceType,
LocalTypeDataKind::forFormalTypeMetadata()
};
return follow(IGF, key, source, Path.begin(), Path.end(), request, cache);
}
MetadataResponse
MetadataPath::followFromWitnessTable(IRGenFunction &IGF,
CanType conformingType,
ProtocolConformanceRef conformance,
MetadataResponse source,
DynamicMetadataRequest request,
Map<MetadataResponse> *cache) const {
LocalTypeDataKey key = {
conformingType,
LocalTypeDataKind::forProtocolWitnessTable(conformance)
};
return follow(IGF, key, source, Path.begin(), Path.end(), request, cache);
}
/// Follow this metadata path.
///
/// \param sourceKey - A description of the source value. Not necessarily
/// an appropriate caching key.
/// \param cache - If given, this cache will be used to short-circuit
/// the lookup; otherwise, the global (but dominance-sensitive) cache
/// in the IRGenFunction will be used. This caching system is somewhat
/// more efficient than what IGF provides, but it's less general, and it
/// should probably be removed.
MetadataResponse MetadataPath::follow(IRGenFunction &IGF,
LocalTypeDataKey sourceKey,
MetadataResponse source,
iterator begin, iterator end,
DynamicMetadataRequest finalRequest,
Map<MetadataResponse> *cache) {
assert(source && "no source metadata value!");
// The invariant is that this iterator starts a path from source and
// that sourceKey is correctly describes it.
iterator i = begin;
// Before we begin emitting code to generate the actual path, try to find
// the latest point in the path that we've cached a value for.
// If the caller gave us a cache to use, check that. This lookup is very
// efficient and doesn't even require us to parse the prefix.
if (cache) {
auto result = cache->findPrefix(begin, end);
if (result.first) {
source = *result.first;
// If that was the end, there's no more work to do; don't bother
// adjusting the source key.
if (result.second == end)
return source;
// Advance the source key past the cached prefix.
while (i != result.second) {
Component component = *i++;
(void) followComponent(IGF, sourceKey, MetadataResponse(), component,
MetadataState::Abstract);
}
}
// Otherwise, make a pass over the path looking for available concrete
// entries in the IGF's local type data cache.
} else {
auto skipI = i;
LocalTypeDataKey skipKey = sourceKey;
while (skipI != end) {
Component component = *skipI++;
(void) followComponent(IGF, skipKey, MetadataResponse(), component,
MetadataState::Abstract);
// Check the cache for a concrete value. We don't want an abstract
// cache entry because, if one exists, we'll just end up here again
// recursively.
auto skipRequest =
(skipI == end ? finalRequest : MetadataState::Abstract);
if (auto skipResponse =
IGF.tryGetConcreteLocalTypeData(skipKey, skipRequest)) {
// Advance the baseline information for the source to the current
// point in the path, then continue the search.
sourceKey = skipKey;
source = skipResponse;
i = skipI;
}
}
}
// Drill in on the actual source value.
while (i != end) {
auto component = *i++;
auto componentRequest =
(i == end ? finalRequest : MetadataState::Abstract);
source = followComponent(IGF, sourceKey, source,
component, componentRequest);
// If we have a cache, remember this in the cache at the next position.
if (cache) {
cache->insertNew(begin, i, source);
// Otherwise, insert it into the global cache (at the updated source key).
} else {
IGF.setScopedLocalTypeData(sourceKey, source);
}
}
return source;
}
/// Call an associated-type witness table access function. Does not do
/// any caching or drill down to implied protocols.
static llvm::Value *
emitAssociatedTypeWitnessTableRef(IRGenFunction &IGF,
llvm::Value *parentMetadata,
llvm::Value *wtable,
AssociatedConformance conformance,
llvm::Value *associatedTypeMetadata) {
auto sourceProtocol = conformance.getSourceProtocol();
llvm::Value *witness;
if (IGF.IGM.isResilient(sourceProtocol, ResilienceExpansion::Maximal)) {
// For resilient protocols, use the associated conformance descriptor to
// determine the index.
auto assocConformanceDescriptor =
IGF.IGM.getAddrOfAssociatedConformanceDescriptor(conformance);
auto index =
computeResilientWitnessTableIndex(IGF, sourceProtocol,
assocConformanceDescriptor);
witness = emitInvariantLoadOfOpaqueWitness(IGF, wtable, index);
} else {
// For non-resilient protocols, the index is a constant.
auto &pi = IGF.IGM.getProtocolInfo(sourceProtocol,
ProtocolInfoKind::RequirementSignature);
auto index = pi.getAssociatedConformanceIndex(conformance);
witness = emitInvariantLoadOfOpaqueWitness(IGF, wtable,
index.forProtocolWitnessTable());
}
// Cast the witness to the appropriate function type.
auto sig = IGF.IGM.getAssociatedTypeWitnessTableAccessFunctionSignature();
auto witnessTy = sig.getType();
witness = IGF.Builder.CreateBitCast(witness, witnessTy->getPointerTo());
FunctionPointer witnessFnPtr(witness, sig);
// Call the accessor.
auto call = IGF.Builder.CreateCall(witnessFnPtr,
{ associatedTypeMetadata, parentMetadata, wtable });
return call;
}
/// Drill down on a single stage of component.
///
/// sourceType and sourceDecl will be adjusted to refer to the new
/// component. Source can be null, in which case this will be the only
/// thing done.
MetadataResponse MetadataPath::followComponent(IRGenFunction &IGF,
LocalTypeDataKey &sourceKey,
MetadataResponse source,
Component component,
DynamicMetadataRequest request) {
switch (component.getKind()) {
case Component::Kind::NominalTypeArgument:
case Component::Kind::NominalTypeArgumentConformance: {
assert(sourceKey.Kind == LocalTypeDataKind::forFormalTypeMetadata());
auto type = sourceKey.Type;
if (auto archetypeTy = dyn_cast<ArchetypeType>(type))
type = archetypeTy->getSuperclass()->getCanonicalType();
auto *nominal = type.getAnyNominal();
auto reqtIndex = component.getPrimaryIndex();
GenericTypeRequirements requirements(IGF.IGM, nominal);
auto &requirement = requirements.getRequirements()[reqtIndex];
auto module = IGF.getSwiftModule();
auto subs = sourceKey.Type->getContextSubstitutionMap(module, nominal);
auto sub = requirement.TypeParameter.subst(subs)->getCanonicalType();
// In either case, we need to change the type.
sourceKey.Type = sub;
// If this is a type argument, we've fully updated sourceKey.
if (component.getKind() == Component::Kind::NominalTypeArgument) {
assert(!requirement.Protocol && "index mismatch!");
if (!source) return MetadataResponse();
auto sourceMetadata = source.getMetadata();
auto *argMetadata =
emitArgumentMetadataRef(IGF, nominal, requirements, reqtIndex,
sourceMetadata);
setTypeMetadataName(IGF.IGM, argMetadata, sourceKey.Type);
// Assume that the argument metadata is complete if the metadata is.
auto argState = getPresumedMetadataStateForTypeArgument(
source.getStaticLowerBoundOnState());
auto response = MetadataResponse::forBounded(argMetadata, argState);
// Do a dynamic check if necessary to satisfy the request.
return emitCheckTypeMetadataState(IGF, request, response);
// Otherwise, we need to switch sourceKey.Kind to the appropriate
// conformance kind.
} else {
assert(requirement.Protocol && "index mismatch!");
auto conformance = *subs.lookupConformance(requirement.TypeParameter,
requirement.Protocol);
assert(conformance.getRequirement() == requirement.Protocol);
sourceKey.Kind = LocalTypeDataKind::forProtocolWitnessTable(conformance);
if (!source) return MetadataResponse();
auto sourceMetadata = source.getMetadata();
auto protocol = conformance.getRequirement();
auto wtable = emitArgumentWitnessTableRef(IGF, nominal,
requirements, reqtIndex,
sourceMetadata);
setProtocolWitnessTableName(IGF.IGM, wtable, sourceKey.Type, protocol);
return MetadataResponse::forComplete(wtable);
}
}
case Component::Kind::OutOfLineBaseProtocol: {
auto conformance = sourceKey.Kind.getProtocolConformance();
auto protocol = conformance.getRequirement();
auto &pi = IGF.IGM.getProtocolInfo(protocol,
ProtocolInfoKind::RequirementSignature);
auto &entry = pi.getWitnessEntries()[component.getPrimaryIndex()];
assert(entry.isOutOfLineBase());
auto inheritedProtocol = entry.getBase();
sourceKey.Kind =
LocalTypeDataKind::forAbstractProtocolWitnessTable(inheritedProtocol);
if (conformance.isConcrete()) {
auto inheritedConformance =
conformance.getConcrete()->getInheritedConformance(inheritedProtocol);
if (inheritedConformance) {
sourceKey.Kind = LocalTypeDataKind::forConcreteProtocolWitnessTable(
inheritedConformance);
}
}
if (!source) return MetadataResponse();
auto wtable = source.getMetadata();
WitnessIndex index(component.getPrimaryIndex(), /*prefix*/ false);
auto baseWTable =
emitInvariantLoadOfOpaqueWitness(IGF, wtable,
index.forProtocolWitnessTable());
baseWTable =
IGF.Builder.CreateBitCast(baseWTable, IGF.IGM.WitnessTablePtrTy);
setProtocolWitnessTableName(IGF.IGM, baseWTable, sourceKey.Type,
inheritedProtocol);
return MetadataResponse::forComplete(baseWTable);
}
case Component::Kind::AssociatedConformance: {
auto sourceType = sourceKey.Type;
auto sourceConformance = sourceKey.Kind.getProtocolConformance();
auto sourceProtocol = sourceConformance.getRequirement();
auto &pi = IGF.IGM.getProtocolInfo(sourceProtocol,
ProtocolInfoKind::RequirementSignature);
auto &entry = pi.getWitnessEntries()[component.getPrimaryIndex()];
assert(entry.isAssociatedConformance());
auto association = entry.getAssociatedConformancePath();
auto associatedRequirement = entry.getAssociatedConformanceRequirement();
CanType associatedType =
sourceConformance.getAssociatedType(sourceType, association)
->getCanonicalType();
if (sourceConformance.isConcrete() &&
isa<NormalProtocolConformance>(sourceConformance.getConcrete())) {
associatedType =
sourceConformance.getConcrete()->getDeclContext()
->mapTypeIntoContext(associatedType)
->getCanonicalType();
}
sourceKey.Type = associatedType;
auto associatedConformance =
sourceConformance.getAssociatedConformance(sourceType, association,
associatedRequirement);
sourceKey.Kind =
LocalTypeDataKind::forProtocolWitnessTable(associatedConformance);
assert((associatedConformance.isConcrete() ||
isa<ArchetypeType>(sourceKey.Type)) &&
"couldn't find concrete conformance for concrete type");
if (!source) return MetadataResponse();
auto sourceMetadata = IGF.emitTypeMetadataRef(sourceType);
auto associatedMetadata = IGF.emitTypeMetadataRef(sourceKey.Type);
auto sourceWTable = source.getMetadata();
AssociatedConformance associatedConformanceRef(sourceProtocol,
association,
associatedRequirement);
auto associatedWTable =
emitAssociatedTypeWitnessTableRef(IGF, sourceMetadata, sourceWTable,
associatedConformanceRef,
associatedMetadata);
setProtocolWitnessTableName(IGF.IGM, associatedWTable, sourceKey.Type,
associatedRequirement);
return MetadataResponse::forComplete(associatedWTable);
}
case Component::Kind::ConditionalConformance: {
auto sourceConformance = sourceKey.Kind.getProtocolConformance();
auto reqtIndex = component.getPrimaryIndex();
ProtocolDecl *conformingProto;
auto found = SILWitnessTable::enumerateWitnessTableConditionalConformances(
sourceConformance.getConcrete(),
[&](unsigned index, CanType type, ProtocolDecl *proto) {
if (reqtIndex == index) {
conformingProto = proto;
sourceKey.Type = type;
// done!
return true;
}
return /*finished?*/ false;
});
assert(found && "too many conditional conformances");
(void)found;
sourceKey.Kind =
LocalTypeDataKind::forAbstractProtocolWitnessTable(conformingProto);
if (!source) return MetadataResponse();
WitnessIndex index(privateWitnessTableIndexToTableOffset(reqtIndex),
/*prefix*/ false);
auto sourceWTable = source.getMetadata();
auto capturedWTable =
emitInvariantLoadOfOpaqueWitness(IGF, sourceWTable, index);
capturedWTable =
IGF.Builder.CreateBitCast(capturedWTable, IGF.IGM.WitnessTablePtrTy);
setProtocolWitnessTableName(IGF.IGM, capturedWTable, sourceKey.Type,
conformingProto);
return MetadataResponse::forComplete(capturedWTable);
}
case Component::Kind::Impossible:
llvm_unreachable("following an impossible path!");
}
llvm_unreachable("bad metadata path component");
}
void MetadataPath::dump() const {
auto &out = llvm::errs();
print(out);
out << '\n';
}
void MetadataPath::print(llvm::raw_ostream &out) const {
for (auto i = Path.begin(), e = Path.end(); i != e; ++i) {
if (i != Path.begin()) out << ".";
auto component = *i;
switch (component.getKind()) {
case Component::Kind::OutOfLineBaseProtocol:
out << "out_of_line_base_protocol[" << component.getPrimaryIndex() << "]";
break;
case Component::Kind::AssociatedConformance:
out << "associated_conformance[" << component.getPrimaryIndex() << "]";
break;
case Component::Kind::NominalTypeArgument:
out << "nominal_type_argument[" << component.getPrimaryIndex() << "]";
break;
case Component::Kind::NominalTypeArgumentConformance:
out << "nominal_type_argument_conformance["
<< component.getPrimaryIndex() << "]";
break;
case Component::Kind::ConditionalConformance:
out << "conditional_conformance[" << component.getPrimaryIndex() << "]";
break;
case Component::Kind::Impossible:
out << "impossible";
break;
}
}
}
/// Collect any required metadata for a witness method from the end of
/// the given parameter list.
void irgen::collectTrailingWitnessMetadata(IRGenFunction &IGF,
SILFunction &fn,
Explosion ¶ms,
WitnessMetadata &witnessMetadata) {
assert(fn.getLoweredFunctionType()->getRepresentation()
== SILFunctionTypeRepresentation::WitnessMethod);
llvm::Value *wtable = params.takeLast();
assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy &&
"parameter signature mismatch: witness metadata didn't "
"end in witness table?");
wtable->setName("SelfWitnessTable");
witnessMetadata.SelfWitnessTable = wtable;
llvm::Value *metatype = params.takeLast();
assert(metatype->getType() == IGF.IGM.TypeMetadataPtrTy &&
"parameter signature mismatch: witness metadata didn't "
"end in metatype?");
metatype->setName("Self");
witnessMetadata.SelfMetadata = metatype;
}
/// Perform all the bindings necessary to emit the given declaration.
void irgen::emitPolymorphicParameters(IRGenFunction &IGF,
SILFunction &Fn,
Explosion &in,
WitnessMetadata *witnessMetadata,
const GetParameterFn &getParameter) {
EmitPolymorphicParameters(IGF, Fn).emit(in, witnessMetadata, getParameter);
}
/// Given an array of polymorphic arguments as might be set up by
/// GenericArguments, bind the polymorphic parameters.
void irgen::emitPolymorphicParametersFromArray(IRGenFunction &IGF,
NominalTypeDecl *typeDecl,
Address array,
MetadataState state) {
GenericTypeRequirements requirements(IGF.IGM, typeDecl);
array = IGF.Builder.CreateElementBitCast(array, IGF.IGM.TypeMetadataPtrTy);
auto getInContext = [&](CanType type) -> CanType {
return typeDecl->mapTypeIntoContext(type)
->getCanonicalType();
};
// Okay, bind everything else from the context.
requirements.bindFromBuffer(IGF, array, state, getInContext);
}
Size NecessaryBindings::getBufferSize(IRGenModule &IGM) const {
// We need one pointer for each archetype or witness table.
return IGM.getPointerSize() * Requirements.size();
}
void NecessaryBindings::restore(IRGenFunction &IGF, Address buffer,
MetadataState metadataState) const {
bindFromGenericRequirementsBuffer(IGF, Requirements.getArrayRef(), buffer,
metadataState,
[&](CanType type) { return type;});
}
void NecessaryBindings::save(IRGenFunction &IGF, Address buffer) const {
emitInitOfGenericRequirementsBuffer(IGF, Requirements.getArrayRef(), buffer,
[&](GenericRequirement requirement) -> llvm::Value* {
CanType type = requirement.TypeParameter;
if (auto protocol = requirement.Protocol) {
auto wtable =
emitArchetypeWitnessTableRef(IGF, cast<ArchetypeType>(type), protocol);
return wtable;
} else {
auto metadata = IGF.emitTypeMetadataRef(type);
return metadata;
}
});
}
void NecessaryBindings::addTypeMetadata(CanType type) {
// Bindings are only necessary at all if the type is dependent.
if (!type->hasArchetype()) return;
// Break down structural types so that we don't eagerly pass metadata
// for the structural type. Future considerations for this:
// - If we have the structural type lying around in some cheap fashion,
// maybe we *should* just pass it.
// - Passing a structural type should remove the need to pass its
// components separately.
if (auto tuple = dyn_cast<TupleType>(type)) {
for (auto elt : tuple.getElementTypes())
addTypeMetadata(elt);
return;
}
if (auto fn = dyn_cast<FunctionType>(type)) {
for (const auto &elt : fn.getParams())
addTypeMetadata(elt.getOldType());
addTypeMetadata(fn.getResult());
return;
}
if (auto inout = dyn_cast<InOutType>(type)) {
addTypeMetadata(inout.getObjectType());
return;
}
if (auto metatype = dyn_cast<MetatypeType>(type)) {
addTypeMetadata(metatype.getInstanceType());
return;
}
// Generic types are trickier, because they can require conformances.
// Otherwise, just record the need for this metadata.
Requirements.insert({type, nullptr});
}
void NecessaryBindings::addProtocolConformance(CanType type,
ProtocolConformanceRef conf) {
if (!conf.isAbstract()) return;
assert(isa<ArchetypeType>(type));
// TODO: pass something about the root conformance necessary to
// reconstruct this.
Requirements.insert({type, conf.getAbstract()});
}
llvm::Value *irgen::emitImpliedWitnessTableRef(IRGenFunction &IGF,
ArrayRef<ProtocolEntry> entries,
ProtocolDecl *target,
const GetWitnessTableFn &getWitnessTable) {
ProtocolPath path(IGF.IGM, entries, target);
auto wtable = getWitnessTable(path.getOriginIndex());
wtable = path.apply(IGF, wtable);
return wtable;
}
llvm::Value *irgen::emitWitnessTableRef(IRGenFunction &IGF,
CanType srcType,
ProtocolConformanceRef conformance) {
llvm::Value *srcMetadataCache = nullptr;
return emitWitnessTableRef(IGF, srcType, &srcMetadataCache, conformance);
}
/// Emit a protocol witness table for a conformance.
llvm::Value *irgen::emitWitnessTableRef(IRGenFunction &IGF,
CanType srcType,
llvm::Value **srcMetadataCache,
ProtocolConformanceRef conformance) {
auto proto = conformance.getRequirement();
assert(Lowering::TypeConverter::protocolRequiresWitnessTable(proto)
&& "protocol does not have witness tables?!");
// If we don't have concrete conformance information, the type must be
// an archetype and the conformance must be via one of the protocol
// requirements of the archetype. Look at what's locally bound.
if (conformance.isAbstract()) {
auto archetype = cast<ArchetypeType>(srcType);
return emitArchetypeWitnessTableRef(IGF, archetype, proto);
}
// All other source types should be concrete enough that we have
// conformance info for them. However, that conformance info might be
// more concrete than we're expecting.
// TODO: make a best effort to devirtualize, maybe?
auto concreteConformance = conformance.getConcrete();
assert(concreteConformance->getProtocol() == proto);
auto cacheKind =
LocalTypeDataKind::forConcreteProtocolWitnessTable(concreteConformance);
// Check immediately for an existing cache entry.
auto wtable = IGF.tryGetLocalTypeData(srcType, cacheKind);
if (wtable) return wtable;
auto &conformanceI = IGF.IGM.getConformanceInfo(proto, concreteConformance);
wtable = conformanceI.getTable(IGF, srcMetadataCache);
IGF.setScopedLocalTypeData(srcType, cacheKind, wtable);
return wtable;
}
static CanType getSubstSelfType(CanSILFunctionType origFnType,
SubstitutionMap subs) {
// Grab the apparent 'self' type. If there isn't a 'self' type,
// we're not going to try to access this anyway.
assert(!origFnType->getParameters().empty());
auto selfParam = origFnType->getParameters().back();
CanType inputType = selfParam.getType();
// If the parameter is a direct metatype parameter, this is a static method
// of the instance type. We can assume this because:
// - metatypes cannot directly conform to protocols
// - even if they could, they would conform as a value type 'self' and thus
// be passed indirectly as an @in or @inout parameter.
if (auto meta = dyn_cast<MetatypeType>(inputType)) {
if (!selfParam.isFormalIndirect())
inputType = meta.getInstanceType();
}
// Substitute the `self` type.
// FIXME: This has to be done as a formal AST type substitution rather than
// a SIL function type substitution, because some nominal types (viz
// Optional) have type lowering recursively applied to their type parameters.
// Substituting into the original lowered function type like this is still
// problematic if we ever allow methods or protocol conformances on structural
// types; we'd really need to separately record the formal Self type in the
// SIL function type to make that work, which could be managed by having a
// "substituted generic signature" concept.
if (!subs.empty()) {
inputType = inputType.subst(subs)->getCanonicalType();
}
return inputType;
}
namespace {
class EmitPolymorphicArguments : public PolymorphicConvention {
IRGenFunction &IGF;
public:
EmitPolymorphicArguments(IRGenFunction &IGF,
CanSILFunctionType polyFn)
: PolymorphicConvention(IGF.IGM, polyFn), IGF(IGF) {}
void emit(SubstitutionMap subs,
WitnessMetadata *witnessMetadata, Explosion &out);
private:
void emitEarlySources(SubstitutionMap subs, Explosion &out) {
for (auto &source : getSources()) {
switch (source.getKind()) {
// Already accounted for in the parameters.
case MetadataSource::Kind::ClassPointer:
case MetadataSource::Kind::Metadata:
continue;
// Needs a special argument.
case MetadataSource::Kind::GenericLValueMetadata: {
out.add(IGF.emitTypeMetadataRef(getSubstSelfType(FnType, subs)));
continue;
}
// Witness 'Self' arguments are added as a special case in
// EmitPolymorphicArguments::emit.
case MetadataSource::Kind::SelfMetadata:
case MetadataSource::Kind::SelfWitnessTable:
continue;
}
llvm_unreachable("bad source kind!");
}
}
};
} // end anonymous namespace
/// Pass all the arguments necessary for the given function.
void irgen::emitPolymorphicArguments(IRGenFunction &IGF,
CanSILFunctionType origFnType,
SubstitutionMap subs,
WitnessMetadata *witnessMetadata,
Explosion &out) {
EmitPolymorphicArguments(IGF, origFnType).emit(subs, witnessMetadata, out);
}
void EmitPolymorphicArguments::emit(SubstitutionMap subs,
WitnessMetadata *witnessMetadata,
Explosion &out) {
// Add all the early sources.
emitEarlySources(subs, out);
// For now, treat all archetypes independently.
enumerateUnfulfilledRequirements([&](GenericRequirement requirement) {
llvm::Value *requiredValue =
emitGenericRequirementFromSubstitutions(IGF, Generics, M,
requirement, subs);
out.add(requiredValue);
});
// For a witness call, add the Self argument metadata arguments last.
for (auto &source : getSources()) {
switch (source.getKind()) {
case MetadataSource::Kind::Metadata:
case MetadataSource::Kind::ClassPointer:
// Already accounted for in the arguments.
continue;
case MetadataSource::Kind::GenericLValueMetadata:
// Added in the early phase.
continue;
case MetadataSource::Kind::SelfMetadata: {
assert(witnessMetadata && "no metadata structure for witness method");
auto self = IGF.emitTypeMetadataRef(getSubstSelfType(FnType, subs));
witnessMetadata->SelfMetadata = self;
continue;
}
case MetadataSource::Kind::SelfWitnessTable: {
// Added later.
continue;
}
}
llvm_unreachable("bad source kind");
}
}
NecessaryBindings
NecessaryBindings::forFunctionInvocations(IRGenModule &IGM,
CanSILFunctionType origType,
SubstitutionMap subs) {
NecessaryBindings bindings;
// Bail out early if we don't have polymorphic parameters.
if (!hasPolymorphicParameters(origType))
return bindings;
// Figure out what we're actually required to pass:
PolymorphicConvention convention(IGM, origType);
// - unfulfilled requirements
convention.enumerateUnfulfilledRequirements(
[&](GenericRequirement requirement) {
CanType type = requirement.TypeParameter.subst(subs)->getCanonicalType();
if (requirement.Protocol) {
auto conf = *subs.lookupConformance(requirement.TypeParameter,
requirement.Protocol);
bindings.addProtocolConformance(type, conf);
} else {
bindings.addTypeMetadata(type);
}
});
// - extra sources
for (auto &source : convention.getSources()) {
switch (source.getKind()) {
case MetadataSource::Kind::Metadata:
case MetadataSource::Kind::ClassPointer:
continue;
case MetadataSource::Kind::GenericLValueMetadata:
bindings.addTypeMetadata(getSubstSelfType(origType, subs));
continue;
case MetadataSource::Kind::SelfMetadata:
bindings.addTypeMetadata(getSubstSelfType(origType, subs));
continue;
case MetadataSource::Kind::SelfWitnessTable:
// We'll just pass undef in cases like this.
continue;
}
llvm_unreachable("bad source kind");
}
return bindings;
}
/// The information we need to record in generic type metadata
/// is the information in the type's generic signature. This is
/// simply the information that would be passed to a generic function
/// that takes the (thick) parent metatype as an argument.
GenericTypeRequirements::GenericTypeRequirements(IRGenModule &IGM,
NominalTypeDecl *typeDecl)
: TheDecl(typeDecl) {
// We only need to do something here if the declaration context is
// somehow generic.
auto ncGenerics = typeDecl->getGenericSignatureOfContext();
if (!ncGenerics) return;
// Construct a representative function type.
auto generics = ncGenerics->getCanonicalSignature();
CanSILFunctionType fnType = [&]() -> CanSILFunctionType {
return SILFunctionType::get(generics, SILFunctionType::ExtInfo(),
SILCoroutineKind::None,
/*callee*/ ParameterConvention::Direct_Unowned,
/*params*/ {}, /*yields*/ {},
/*results*/ {}, /*error*/ None,
IGM.Context);
}();
// Figure out what we're actually still required to pass
PolymorphicConvention convention(IGM, fnType);
convention.enumerateUnfulfilledRequirements([&](GenericRequirement reqt) {
assert(generics->isCanonicalTypeInContext(reqt.TypeParameter));
Requirements.push_back(reqt);
});
// We do not need to consider extra sources.
}
void
GenericTypeRequirements::enumerateFulfillments(IRGenModule &IGM,
SubstitutionMap subs,
FulfillmentCallback callback) {
if (empty()) return;
for (auto reqtIndex : indices(getRequirements())) {
auto &reqt = getRequirements()[reqtIndex];
CanType type = reqt.TypeParameter.subst(subs)->getCanonicalType();
if (reqt.Protocol) {
auto conformance = *subs.lookupConformance(reqt.TypeParameter,
reqt.Protocol);
callback(reqtIndex, type, conformance);
} else {
callback(reqtIndex, type, None);
}
}
}
void GenericTypeRequirements::emitInitOfBuffer(IRGenFunction &IGF,
SubstitutionMap subs,
Address buffer) {
if (Requirements.empty()) return;
auto generics =
TheDecl->getGenericSignatureOfContext()->getCanonicalSignature();
auto &module = *TheDecl->getParentModule();
emitInitOfGenericRequirementsBuffer(IGF, Requirements, buffer,
[&](GenericRequirement requirement) {
return emitGenericRequirementFromSubstitutions(IGF, generics, module,
requirement, subs);
});
}
void irgen::emitInitOfGenericRequirementsBuffer(IRGenFunction &IGF,
ArrayRef<GenericRequirement> requirements,
Address buffer,
EmitGenericRequirementFn emitRequirement) {
if (requirements.empty()) return;
// Cast the buffer to %type**.
buffer = IGF.Builder.CreateElementBitCast(buffer, IGF.IGM.TypeMetadataPtrTy);
for (auto index : indices(requirements)) {
// GEP to the appropriate slot.
Address slot = buffer;
if (index != 0) {
slot = IGF.Builder.CreateConstArrayGEP(slot, index,
IGF.IGM.getPointerSize());
}
llvm::Value *value = emitRequirement(requirements[index]);
if (requirements[index].Protocol) {
slot = IGF.Builder.CreateElementBitCast(slot, IGF.IGM.WitnessTablePtrTy);
}
IGF.Builder.CreateStore(value, slot);
}
}
llvm::Value *
irgen::emitGenericRequirementFromSubstitutions(IRGenFunction &IGF,
CanGenericSignature generics,
ModuleDecl &module,
GenericRequirement requirement,
SubstitutionMap subs) {
CanType depTy = requirement.TypeParameter;
CanType argType = depTy.subst(subs)->getCanonicalType();
if (!requirement.Protocol) {
auto argMetadata = IGF.emitTypeMetadataRef(argType);
return argMetadata;
}
auto proto = requirement.Protocol;
auto conformance = *subs.lookupConformance(depTy, proto);
assert(conformance.getRequirement() == proto);
llvm::Value *metadata = nullptr;
auto wtable = emitWitnessTableRef(IGF, argType, &metadata, conformance);
return wtable;
}
void GenericTypeRequirements::bindFromBuffer(IRGenFunction &IGF,
Address buffer,
MetadataState metadataState,
GetTypeParameterInContextFn getInContext) {
bindFromGenericRequirementsBuffer(IGF, Requirements, buffer,
metadataState, getInContext);
}
void irgen::bindFromGenericRequirementsBuffer(IRGenFunction &IGF,
ArrayRef<GenericRequirement> requirements,
Address buffer,
MetadataState metadataState,
GetTypeParameterInContextFn getInContext) {
if (requirements.empty()) return;
// Cast the buffer to %type**.
buffer = IGF.Builder.CreateElementBitCast(buffer, IGF.IGM.TypeMetadataPtrTy);
for (auto index : indices(requirements)) {
// GEP to the appropriate slot.
Address slot = buffer;
if (index != 0) {
slot = IGF.Builder.CreateConstArrayGEP(slot, index,
IGF.IGM.getPointerSize());
}
// Cast if necessary.
if (requirements[index].Protocol) {
slot = IGF.Builder.CreateElementBitCast(slot, IGF.IGM.WitnessTablePtrTy);
}
llvm::Value *value = IGF.Builder.CreateLoad(slot);
bindGenericRequirement(IGF, requirements[index], value, metadataState,
getInContext);
}
}
void irgen::bindGenericRequirement(IRGenFunction &IGF,
GenericRequirement requirement,
llvm::Value *value,
MetadataState metadataState,
GetTypeParameterInContextFn getInContext) {
// Get the corresponding context type.
auto type = getInContext(requirement.TypeParameter);
if (auto proto = requirement.Protocol) {
assert(isa<ArchetypeType>(type));
assert(value->getType() == IGF.IGM.WitnessTablePtrTy);
setProtocolWitnessTableName(IGF.IGM, value, type, proto);
auto kind = LocalTypeDataKind::forAbstractProtocolWitnessTable(proto);
IGF.setUnscopedLocalTypeData(type, kind, value);
} else {
assert(value->getType() == IGF.IGM.TypeMetadataPtrTy);
setTypeMetadataName(IGF.IGM, value, type);
IGF.bindLocalTypeDataFromTypeMetadata(type, IsExact, value, metadataState);
}
}
namespace {
/// A class for expanding a polymorphic signature.
class ExpandPolymorphicSignature : public PolymorphicConvention {
public:
ExpandPolymorphicSignature(IRGenModule &IGM, CanSILFunctionType fn)
: PolymorphicConvention(IGM, fn) {}
void expand(SmallVectorImpl<llvm::Type*> &out) {
for (auto &source : getSources())
addEarlySource(source, out);
enumerateUnfulfilledRequirements([&](GenericRequirement reqt) {
out.push_back(reqt.Protocol ? IGM.WitnessTablePtrTy
: IGM.TypeMetadataPtrTy);
});
}
private:
/// Add signature elements for the source metadata.
void addEarlySource(const MetadataSource &source,
SmallVectorImpl<llvm::Type*> &out) {
switch (source.getKind()) {
case MetadataSource::Kind::ClassPointer: return; // already accounted for
case MetadataSource::Kind::Metadata: return; // already accounted for
case MetadataSource::Kind::GenericLValueMetadata:
return out.push_back(IGM.TypeMetadataPtrTy);
case MetadataSource::Kind::SelfMetadata:
case MetadataSource::Kind::SelfWitnessTable:
return; // handled as a special case in expand()
}
llvm_unreachable("bad source kind");
}
};
} // end anonymous namespace
/// Given a generic signature, add the argument types required in order to call it.
void irgen::expandPolymorphicSignature(IRGenModule &IGM,
CanSILFunctionType polyFn,
SmallVectorImpl<llvm::Type*> &out) {
ExpandPolymorphicSignature(IGM, polyFn).expand(out);
}
void irgen::expandTrailingWitnessSignature(IRGenModule &IGM,
CanSILFunctionType polyFn,
SmallVectorImpl<llvm::Type*> &out) {
assert(polyFn->getRepresentation()
== SILFunctionTypeRepresentation::WitnessMethod);
assert(getTrailingWitnessSignatureLength(IGM, polyFn) == 2);
// A witness method always provides Self.
out.push_back(IGM.TypeMetadataPtrTy);
// A witness method always provides the witness table for Self.
out.push_back(IGM.WitnessTablePtrTy);
}
FunctionPointer
irgen::emitWitnessMethodValue(IRGenFunction &IGF,
llvm::Value *wtable,
SILDeclRef member) {
auto *fn = cast<AbstractFunctionDecl>(member.getDecl());
auto proto = cast<ProtocolDecl>(fn->getDeclContext());
assert(!IGF.IGM.isResilient(proto, ResilienceExpansion::Maximal));
// Find the witness we're interested in.
auto &fnProtoInfo = IGF.IGM.getProtocolInfo(proto, ProtocolInfoKind::Full);
auto index = fnProtoInfo.getFunctionIndex(fn);
llvm::Value *witnessFnPtr =
emitInvariantLoadOfOpaqueWitness(IGF, wtable,
index.forProtocolWitnessTable());
auto fnType = IGF.IGM.getSILTypes().getConstantFunctionType(member);
Signature signature = IGF.IGM.getSignature(fnType);
witnessFnPtr = IGF.Builder.CreateBitCast(witnessFnPtr,
signature.getType()->getPointerTo());
return FunctionPointer(witnessFnPtr, signature);
}
FunctionPointer
irgen::emitWitnessMethodValue(IRGenFunction &IGF,
CanType baseTy,
llvm::Value **baseMetadataCache,
SILDeclRef member,
ProtocolConformanceRef conformance) {
llvm::Value *wtable = emitWitnessTableRef(IGF, baseTy, baseMetadataCache,
conformance);
return emitWitnessMethodValue(IGF, wtable, member);
}
llvm::Value *irgen::computeResilientWitnessTableIndex(
IRGenFunction &IGF,
ProtocolDecl *proto,
llvm::Constant *reqtDescriptor) {
// The requirement base descriptor refers to the first requirement in the
// protocol descriptor, offset by the start of the witness table requirements.
auto requirementsBaseDescriptor =
IGF.IGM.getAddrOfProtocolRequirementsBaseDescriptor(proto);
// Subtract the two pointers to determine the offset to this particular
// requirement.
auto baseAddress = IGF.Builder.CreatePtrToInt(requirementsBaseDescriptor,
IGF.IGM.IntPtrTy);
auto reqtAddress = IGF.Builder.CreatePtrToInt(reqtDescriptor,
IGF.IGM.IntPtrTy);
auto offset = IGF.Builder.CreateSub(reqtAddress, baseAddress);
// Determine how to adjust the byte offset we have to make it a witness
// table offset.
const auto &dataLayout = IGF.IGM.Module.getDataLayout();
auto protoReqSize =
dataLayout.getTypeAllocSizeInBits(IGF.IGM.ProtocolRequirementStructTy);
auto ptrSize = dataLayout.getTypeAllocSizeInBits(IGF.IGM.Int8PtrTy);
assert(protoReqSize >= ptrSize && "> 64-bit pointers?");
assert((protoReqSize % ptrSize == 0) && "Must be evenly divisible");
(void)ptrSize;
unsigned factor = protoReqSize / 8;
auto factorConstant = llvm::ConstantInt::get(IGF.IGM.IntPtrTy, factor);
return IGF.Builder.CreateUDiv(offset, factorConstant);
}
MetadataResponse
irgen::emitAssociatedTypeMetadataRef(IRGenFunction &IGF,
llvm::Value *parentMetadata,
llvm::Value *wtable,
AssociatedType associatedType,
DynamicMetadataRequest request) {
auto &IGM = IGF.IGM;
// Extract the requirements base descriptor.
auto reqBaseDescriptor =
IGM.getAddrOfProtocolRequirementsBaseDescriptor(
associatedType.getSourceProtocol());
// Extract the associated type descriptor.
auto assocTypeDescriptor =
IGM.getAddrOfAssociatedTypeDescriptor(associatedType.getAssociation());
// Call swift_getAssociatedTypeWitness().
auto call = IGF.Builder.CreateCall(IGM.getGetAssociatedTypeWitnessFn(),
{ request.get(IGF),
wtable,
parentMetadata,
reqBaseDescriptor,
assocTypeDescriptor });
call->setDoesNotThrow();
call->setDoesNotAccessMemory();
return MetadataResponse::handle(IGF, request, call);
}
Signature
IRGenModule::getAssociatedTypeWitnessTableAccessFunctionSignature() {
auto &fnType = AssociatedTypeWitnessTableAccessFunctionTy;
if (!fnType) {
// The associated type metadata is passed first so that this function is
// CC-compatible with a conformance's witness table access function.
fnType = llvm::FunctionType::get(WitnessTablePtrTy,
{ TypeMetadataPtrTy,
TypeMetadataPtrTy,
WitnessTablePtrTy },
/*varargs*/ false);
}
auto attrs = llvm::AttributeList::get(getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind);
return Signature(fnType, attrs, SwiftCC);
}
/// \brief Load a reference to the protocol descriptor for the given protocol.
///
/// For Swift protocols, this is a constant reference to the protocol descriptor
/// symbol.
/// For ObjC protocols, descriptors are uniqued at runtime by the ObjC runtime.
/// We need to load the unique reference from a global variable fixed up at
/// startup.
///
/// The result is always a ProtocolDescriptorRefTy whose low bit will be
/// set to indicate when this is an Objective-C protocol.
llvm::Value *irgen::emitProtocolDescriptorRef(IRGenFunction &IGF,
ProtocolDecl *protocol) {
if (!protocol->isObjC()) {
return IGF.Builder.CreatePtrToInt(
IGF.IGM.getAddrOfProtocolDescriptor(protocol),
IGF.IGM.ProtocolDescriptorRefTy);
}
llvm::Value *val = emitReferenceToObjCProtocol(IGF, protocol);
val = IGF.Builder.CreatePtrToInt(val, IGF.IGM.ProtocolDescriptorRefTy);
// Set the low bit to indicate that this is an Objective-C protocol.
auto *isObjCBit = llvm::ConstantInt::get(IGF.IGM.ProtocolDescriptorRefTy, 1);
val = IGF.Builder.CreateOr(val, isObjCBit);
return val;
}
|
// MFEM modified from Example 10 and 16
//
// Compile with: make exMHD
//
// Sample runs:
// exMHD -m xperiodic-square.mesh -r 2 -o 3 -tf 3 -vs 100 -dt .001 -visit
// exMHD -r 2 -tf 10 -vs 50 -dt .004 -i 2
//
// Description: it solves a time dependent resistive MHD problem
// Author: QT
#include "mfem.hpp"
#include "myCoefficient.hpp"
#include "myIntegrator.hpp"
#include "ResistiveMHDOperator.hpp"
#include "PCSolver.hpp"
#include "InitialConditions.hpp"
#include <memory>
#include <iostream>
#include <fstream>
int main(int argc, char *argv[])
{
// 1. Parse command-line options.
const char *mesh_file = "./Meshes/xperiodic-square.mesh";
int ref_levels = 2;
int order = 2;
int ode_solver_type = 2;
double t_final = 5.0;
double dt = 0.0001;
double visc = 0.0;
double resi = 0.0;
bool visit = false;
int precision = 8;
int icase = 1;
beta = 0.001;
Lx=3.0;
lambda=5.0;
bool visualization = true;
int vis_steps = 100;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&ref_levels, "-r", "--refine",
"Number of times to refine the mesh uniformly.");
args.AddOption(&order, "-o", "--order",
"Order (degree) of the finite elements.");
args.AddOption(&ode_solver_type, "-s", "--ode-solver",
"ODE solver: 2 - Brailovskaya.");
args.AddOption(&t_final, "-tf", "--t-final",
"Final time; start time is 0.");
args.AddOption(&dt, "-dt", "--time-step",
"Time step.");
args.AddOption(&icase, "-i", "--icase",
"Icase: 1 - wave propagation; 2 - Tearing mode.");
args.AddOption(&visc, "-visc", "--viscosity",
"Viscosity coefficient.");
args.AddOption(&resi, "-resi", "--resistivity",
"Resistivity coefficient.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&vis_steps, "-vs", "--visualization-steps",
"Visualize every n-th timestep.");
args.AddOption(&visit, "-visit", "--visit-datafiles", "-no-visit",
"--no-visit-datafiles",
"Save data files for VisIt (visit.llnl.gov) visualization.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return 1;
}
if (icase==2)
{
resi=.001;
visc=.001;
resiG=resi;
}
else if (icase==3)
{
lambda=.5/M_PI;
resi=.001;
visc=.001;
resiG=resi;
}
else if (icase!=1)
{
cout <<"Unknown icase "<<icase<<endl;
return 3;
}
args.PrintOptions(cout);
// 2. Read the mesh from the given mesh file.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 3. Define the ODE solver used for time integration. Several implicit
// singly diagonal implicit Runge-Kutta (SDIRK) methods, as well as
// explicit Runge-Kutta methods are available.
PCSolver *ode_solver;
switch (ode_solver_type)
{
// Explicit methods XXX: waring: FE is not stable
//case 1: ode_solver = new ForwardEulerSolver; break;
//case 2:
// ode_solver = new ForwardEulerSolver;
// ode_predictor = new ForwardEulerSolver;
// break; //first order predictor-corrector
case 2: ode_solver = new PCSolver; break;
default:
cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
delete mesh;
return 3;
}
// 4. Refine the mesh to increase the resolution.
for (int lev = 0; lev < ref_levels; lev++)
{
mesh->UniformRefinement();
}
// 5. Define the vector finite element spaces representing
// [Psi, Phi, w, j]
// in block vector bv, with offsets given by the
// fe_offset array.
// All my fespace is 1D bu the problem is multi-dimensional!!
H1_FECollection fe_coll(order, dim);
FiniteElementSpace fespace(mesh, &fe_coll);
if (false)
{
cout <<"dim="<<dim<<endl;
cout <<"fespace dim="<<fespace.GetVDim()<<endl;
}
int fe_size = fespace.GetVSize();
cout << "Number of total scalar unknowns: " << fe_size << endl;
Array<int> fe_offset(5);
fe_offset[0] = 0;
fe_offset[1] = fe_size;
fe_offset[2] = 2*fe_size;
fe_offset[3] = 3*fe_size;
fe_offset[4] = 4*fe_size;
BlockVector vx(fe_offset);
GridFunction psi, phi, w, j, psiBack(&fespace), psiPer(&fespace);
phi.MakeRef(&fespace, vx.GetBlock(0), 0);
psi.MakeRef(&fespace, vx.GetBlock(1), 0);
w.MakeRef(&fespace, vx.GetBlock(2), 0);
j.MakeRef(&fespace, vx.GetBlock(3), 0);
// 6. Set the initial conditions, and the boundary conditions
FunctionCoefficient phiInit(InitialPhi);
phi.ProjectCoefficient(phiInit);
phi.SetTrueVector();
if (icase==1)
{
FunctionCoefficient psiInit(InitialPsi);
psi.ProjectCoefficient(psiInit);
}
else if (icase==2)
{
FunctionCoefficient psiInit2(InitialPsi2);
psi.ProjectCoefficient(psiInit2);
}
else if (icase==3)
{
FunctionCoefficient psiInit3(InitialPsi3);
psi.ProjectCoefficient(psiInit3);
}
psi.SetTrueVector();
FunctionCoefficient wInit(InitialW);
w.ProjectCoefficient(wInit);
w.SetTrueVector();
if (icase==1)
{
FunctionCoefficient jInit(InitialJ);
j.ProjectCoefficient(jInit);
}
else if (icase==2)
{
FunctionCoefficient jInit2(InitialJ2);
j.ProjectCoefficient(jInit2);
}
else if (icase==3)
{
FunctionCoefficient jInit3(InitialJ3);
j.ProjectCoefficient(jInit3);
}
j.SetTrueVector();
//Set the background psi
if (icase==1)
{
FunctionCoefficient psi0(BackPsi);
psiBack.ProjectCoefficient(psi0);
}
else if (icase==2)
{
FunctionCoefficient psi02(BackPsi2);
psiBack.ProjectCoefficient(psi02);
}
else if (icase==3)
{
FunctionCoefficient psi03(BackPsi3);
psiBack.ProjectCoefficient(psi03);
}
psiBack.SetTrueVector();
//this is a periodic boundary condition in x and Direchlet in y
Array<int> ess_bdr(fespace.GetMesh()->bdr_attributes.Max());
ess_bdr = 0;
ess_bdr[0] = 1; //set attribute 1 to Direchlet boundary fixed
if(ess_bdr.Size()!=1)
{
cout <<"ess_bdr size should be 1 but it is "<<ess_bdr.Size()<<endl;
delete ode_solver;
delete mesh;
return 2;
}
// 7. Initialize the MHD operator, the GLVis visualization
ResistiveMHDOperator oper(fespace, ess_bdr, visc, resi);
if (icase==2) //add the source term
{
FunctionCoefficient e0(E0rhs);
oper.SetRHSEfield(e0);
}
else if (icase==3)
{
FunctionCoefficient e0(E0rhs3);
oper.SetRHSEfield(e0);
}
socketstream vis_phi, vis_j;
subtract(psi,psiBack,psiPer);
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
vis_phi.open(vishost, visport);
vis_j.open(vishost, visport);
if (!vis_phi)
{
cout << "Unable to connect to GLVis server at "
<< vishost << ':' << visport << endl;
visualization = false;
cout << "GLVis visualization disabled.\n";
}
else
{
vis_phi.precision(8);
vis_phi << "solution\n" << *mesh << psiPer;
vis_phi << "window_size 800 800\n"<< "window_title '" << "psi per'" << "keys cm\n";
if (icase==2)
vis_phi << "valuerange -.001 .001\n";
vis_phi << flush;
vis_j << "solution\n" << *mesh << j;
vis_j << "window_size 800 800\n"<< "window_title '" << "current'" << "keys cm\n";
vis_j << flush;
}
}
double t = 0.0;
oper.SetTime(t);
ode_solver->Init(oper);
// Create data collection for solution output: either VisItDataCollection for
// ascii data files, or SidreDataCollection for binary data files.
DataCollection *dc = NULL;
if (visit)
{
if (icase==1)
{
dc = new VisItDataCollection("case1", mesh);
dc->RegisterField("psiPer", &psiPer);
dc->RegisterField("current", &j);
}
else
{
dc = new VisItDataCollection("case2", mesh);
dc->RegisterField("psiPer", &psiPer);
dc->RegisterField("psi", &psi);
dc->RegisterField("current", &j);
dc->RegisterField("phi", &phi);
dc->RegisterField("omega", &w);
}
dc->SetPrecision(precision);
dc->SetCycle(0);
dc->SetTime(t);
dc->Save();
}
clock_t start = clock();
// 8. Perform time-integration (looping over the time iterations, ti, with a
// time-step dt).
bool last_step = false;
for (int ti = 1; !last_step; ti++)
{
double dt_real = min(dt, t_final - t);
//---Predictor stage---
//assemble the nonlinear terms
oper.assembleNv(&phi);
oper.assembleNb(&psi);
ode_solver->StepP(vx, t, dt_real);
oper.UpdateJ(vx);
//---Corrector stage---
//assemble the nonlinear terms (only psi is updated)
oper.assembleNb(&psi);
ode_solver->Step(vx, t, dt_real);
oper.UpdateJ(vx);
oper.UpdatePhi(vx);
last_step = (t >= t_final - 1e-8*dt);
if (last_step || (ti % vis_steps) == 0)
{
cout << "step " << ti << ", t = " << t <<endl;
subtract(psi,psiBack,psiPer);
if (visualization)
{
if(icase!=3)
vis_phi << "solution\n" << *mesh << psiPer;
else
vis_phi << "solution\n" << *mesh << w;
vis_j << "solution\n" << *mesh << j;
if (icase==1)
{
vis_phi << "valuerange -.001 .001\n" << flush;
vis_j << "valuerange -.01425 .01426\n" << flush;
}
}
if (visit)
{
dc->SetCycle(ti);
dc->SetTime(t);
dc->Save();
}
}
}
clock_t end = clock();
// 9. Save the solutions.
{
ofstream omesh("refined.mesh");
omesh.precision(8);
mesh->Print(omesh);
ofstream osol("phi.sol");
osol.precision(8);
phi.Save(osol);
ofstream osol2("current.sol");
osol2.precision(8);
j.Save(osol2);
ofstream osol3("psi.sol");
osol3.precision(8);
psi.Save(osol3);
//if (icase!=3)
{
subtract(psi,psiBack,psiPer);
ofstream osol5("psiPer.sol");
osol5.precision(8);
psiPer.Save(osol5);
}
ofstream osol4("omega.sol");
osol4.precision(8);
w.Save(osol4);
}
// 10. Free the used memory.
delete ode_solver;
delete mesh;
delete dc;
cout <<"######Runtime = "<<((double)end-start)/CLOCKS_PER_SEC<<" ######"<<endl;
return 0;
}
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018-2021 Intel Corporation
#ifndef OPENCV_GAPI_GKERNEL_HPP
#define OPENCV_GAPI_GKERNEL_HPP
#include <functional>
#include <iostream>
#include <string> // string
#include <type_traits> // false_type, true_type
#include <unordered_map> // map (for GKernelPackage)
#include <utility> // tuple
#include <opencv2/gapi/gcommon.hpp> // CompileArgTag
#include <opencv2/gapi/util/util.hpp> // Seq
#include <opencv2/gapi/gcall.hpp>
#include <opencv2/gapi/garg.hpp> // GArg
#include <opencv2/gapi/gmetaarg.hpp> // GMetaArg
#include <opencv2/gapi/gtype_traits.hpp> // GTypeTraits
#include <opencv2/gapi/util/compiler_hints.hpp> //suppress_unused_warning
#include <opencv2/gapi/gtransform.hpp>
namespace cv {
struct GTypeInfo
{
GShape shape;
cv::detail::OpaqueKind kind;
detail::HostCtor ctor;
};
using GShapes = std::vector<GShape>;
using GKinds = std::vector<cv::detail::OpaqueKind>;
using GCtors = std::vector<detail::HostCtor>;
using GTypesInfo = std::vector<GTypeInfo>;
// GKernel describes kernel API to the system
// FIXME: add attributes of a kernel, (e.g. number and types
// of inputs, etc)
struct GAPI_EXPORTS GKernel
{
using M = std::function<GMetaArgs(const GMetaArgs &, const GArgs &)>;
std::string name; // kernel ID, defined by its API (signature)
std::string tag; // some (implementation-specific) tag
M outMeta; // generic adaptor to API::outMeta(...)
GShapes outShapes; // types (shapes) kernel's outputs
GKinds inKinds; // kinds of kernel's inputs (fixme: below)
GCtors outCtors; // captured constructors for template output types
};
// TODO: It's questionable if inKinds should really be here. Instead,
// this information could come from meta.
// GKernelImpl describes particular kernel implementation to the system
struct GAPI_EXPORTS GKernelImpl
{
util::any opaque; // backend-specific opaque info
GKernel::M outMeta; // for deserialized graphs, the outMeta is taken here
};
template<typename, typename> class GKernelTypeM;
namespace detail
{
////////////////////////////////////////////////////////////////////////////
// yield() is used in graph construction time as a generic method to obtain
// lazy "return value" of G-API operations
//
template<typename T> struct Yield;
template<> struct Yield<cv::GMat>
{
static inline cv::GMat yield(cv::GCall &call, int i) { return call.yield(i); }
};
template<> struct Yield<cv::GMatP>
{
static inline cv::GMatP yield(cv::GCall &call, int i) { return call.yieldP(i); }
};
template<> struct Yield<cv::GScalar>
{
static inline cv::GScalar yield(cv::GCall &call, int i) { return call.yieldScalar(i); }
};
template<typename U> struct Yield<cv::GArray<U> >
{
static inline cv::GArray<U> yield(cv::GCall &call, int i) { return call.yieldArray<U>(i); }
};
template<typename U> struct Yield<cv::GOpaque<U> >
{
static inline cv::GOpaque<U> yield(cv::GCall &call, int i) { return call.yieldOpaque<U>(i); }
};
template<> struct Yield<GFrame>
{
static inline cv::GFrame yield(cv::GCall &call, int i) { return call.yieldFrame(i); }
};
////////////////////////////////////////////////////////////////////////////
// Helper classes which brings outputMeta() marshalling to kernel
// implementations
//
// 1. MetaType establishes G#Type -> G#Meta mapping between G-API dynamic
// types and its metadata descriptor types.
// This mapping is used to transform types to call outMeta() callback.
template<typename T> struct MetaType;
template<> struct MetaType<cv::GMat> { using type = GMatDesc; };
template<> struct MetaType<cv::GMatP> { using type = GMatDesc; };
template<> struct MetaType<cv::GFrame> { using type = GFrameDesc; };
template<> struct MetaType<cv::GScalar> { using type = GScalarDesc; };
template<typename U> struct MetaType<cv::GArray<U> > { using type = GArrayDesc; };
template<typename U> struct MetaType<cv::GOpaque<U> > { using type = GOpaqueDesc; };
template<typename T> struct MetaType { using type = T; }; // opaque args passed as-is
// FIXME: Move it to type traits?
// 2. Hacky test based on MetaType to check if we operate on G-* type or not
template<typename T> using is_nongapi_type = std::is_same<T, typename MetaType<T>::type>;
// 3. Two ways to transform input arguments to its meta - for G-* and non-G* types:
template<typename T>
typename std::enable_if<!is_nongapi_type<T>::value, typename MetaType<T>::type>
::type get_in_meta(const GMetaArgs &in_meta, const GArgs &, int idx)
{
return util::get<typename MetaType<T>::type>(in_meta.at(idx));
}
template<typename T>
typename std::enable_if<is_nongapi_type<T>::value, T>
::type get_in_meta(const GMetaArgs &, const GArgs &in_args, int idx)
{
return in_args.at(idx).template get<T>();
}
// 4. The MetaHelper itself: an entity which generates outMeta() call
// based on kernel signature, with arguments properly substituted.
// 4.1 - case for multiple return values
// FIXME: probably can be simplified with std::apply or analogue.
template<typename, typename, typename>
struct MetaHelper;
template<typename K, typename... Ins, typename... Outs>
struct MetaHelper<K, std::tuple<Ins...>, std::tuple<Outs...> >
{
template<int... IIs, int... OIs>
static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta,
const GArgs &in_args,
detail::Seq<IIs...>,
detail::Seq<OIs...>)
{
// FIXME: decay?
using R = std::tuple<typename MetaType<Outs>::type...>;
const R r = K::outMeta( get_in_meta<Ins>(in_meta, in_args, IIs)... );
return GMetaArgs{ GMetaArg(std::get<OIs>(r))... };
}
// FIXME: help users identify how outMeta must look like (via default impl w/static_assert?)
static GMetaArgs getOutMeta(const GMetaArgs &in_meta,
const GArgs &in_args)
{
return getOutMeta_impl(in_meta,
in_args,
typename detail::MkSeq<sizeof...(Ins)>::type(),
typename detail::MkSeq<sizeof...(Outs)>::type());
}
};
// 4.1 - case for a single return value
// FIXME: How to avoid duplication here?
template<typename K, typename... Ins, typename Out>
struct MetaHelper<K, std::tuple<Ins...>, Out >
{
template<int... IIs>
static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta,
const GArgs &in_args,
detail::Seq<IIs...>)
{
// FIXME: decay?
using R = typename MetaType<Out>::type;
const R r = K::outMeta( get_in_meta<Ins>(in_meta, in_args, IIs)... );
return GMetaArgs{ GMetaArg(r) };
}
// FIXME: help users identify how outMeta must look like (via default impl w/static_assert?)
static GMetaArgs getOutMeta(const GMetaArgs &in_meta,
const GArgs &in_args)
{
return getOutMeta_impl(in_meta,
in_args,
typename detail::MkSeq<sizeof...(Ins)>::type());
}
};
////////////////////////////////////////////////////////////////////////////
// Helper class to introduce tags to calls. By default there's no tag
struct NoTag {
static constexpr const char *tag() { return ""; }
};
} // namespace detail
// GKernelType and GKernelTypeM are base classes which implement typed ::on()
// method based on kernel signature. GKernelTypeM stands for multiple-return-value kernels
//
// G_TYPED_KERNEL and G_TYPED_KERNEL_M macros inherit user classes from GKernelType and
// GKernelTypeM respectively.
template<typename K, typename... R, typename... Args>
class GKernelTypeM<K, std::function<std::tuple<R...>(Args...)> >
: public detail::MetaHelper<K, std::tuple<Args...>, std::tuple<R...>>
, public detail::NoTag
{
template<int... IIs>
static std::tuple<R...> yield(cv::GCall &call, detail::Seq<IIs...>)
{
return std::make_tuple(detail::Yield<R>::yield(call, IIs)...);
}
public:
using InArgs = std::tuple<Args...>;
using OutArgs = std::tuple<R...>;
// TODO: Args&&... here?
static std::tuple<R...> on(Args... args)
{
cv::GCall call(GKernel{ K::id()
, K::tag()
, &K::getOutMeta
, {detail::GTypeTraits<R>::shape...}
, {detail::GTypeTraits<Args>::op_kind...}
, {detail::GObtainCtor<R>::get()...}});
call.pass(args...); // TODO: std::forward() here?
return yield(call, typename detail::MkSeq<sizeof...(R)>::type());
}
};
template<typename, typename> class GKernelType;
template<typename K, typename R, typename... Args>
class GKernelType<K, std::function<R(Args...)> >
: public detail::MetaHelper<K, std::tuple<Args...>, R>
, public detail::NoTag
{
public:
using InArgs = std::tuple<Args...>;
using OutArgs = std::tuple<R>;
static R on(Args... args)
{
cv::GCall call(GKernel{ K::id()
, K::tag()
, &K::getOutMeta
, {detail::GTypeTraits<R>::shape}
, {detail::GTypeTraits<Args>::op_kind...}
, {detail::GObtainCtor<R>::get()}});
call.pass(args...);
return detail::Yield<R>::yield(call, 0);
}
};
namespace detail {
// This tiny class eliminates the semantic difference between
// GKernelType and GKernelTypeM.
template<typename, typename> class KernelTypeMedium;
template<typename K, typename... R, typename... Args>
class KernelTypeMedium<K, std::function<std::tuple<R...>(Args...)>> :
public cv::GKernelTypeM<K, std::function<std::tuple<R...>(Args...)>> {};
template<typename K, typename R, typename... Args>
class KernelTypeMedium<K, std::function<R(Args...)>> :
public cv::GKernelType<K, std::function<R(Args...)>> {};
} // namespace detail
} // namespace cv
// FIXME: I don't know a better way so far. Feel free to suggest one
// The problem is that every typed kernel should have ::id() but body
// of the class is defined by user (with outMeta, other stuff)
//! @cond IGNORED
#define G_ID_HELPER_CLASS(Class) Class##IdHelper
#define G_ID_HELPER_BODY(Class, Id) \
struct G_ID_HELPER_CLASS(Class) \
{ \
static constexpr const char * id() {return Id;} \
}; \
//! @endcond
#define GET_G_TYPED_KERNEL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, NAME, ...) NAME
#define COMBINE_SIGNATURE(...) __VA_ARGS__
// Ensure correct __VA_ARGS__ expansion on Windows
#define __WRAP_VAARGS(x) x
/**
* Helper for G_TYPED_KERNEL declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api)
* for more details.
*
* @param Class type name for this operation.
* @param API an `std::function<>`-like signature for the operation;
* return type is a single value or a tuple of multiple values.
* @param Id string identifier for the operation. Must be unique.
*/
#define G_TYPED_KERNEL_HELPER(Class, API, Id) \
G_ID_HELPER_BODY(Class, Id) \
struct Class final: public cv::detail::KernelTypeMedium<Class, std::function API >, \
public G_ID_HELPER_CLASS(Class)
// {body} is to be defined by user
#define G_TYPED_KERNEL_HELPER_2(Class, _1, _2, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2), Id)
#define G_TYPED_KERNEL_HELPER_3(Class, _1, _2, _3, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3), Id)
#define G_TYPED_KERNEL_HELPER_4(Class, _1, _2, _3, _4, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4), Id)
#define G_TYPED_KERNEL_HELPER_5(Class, _1, _2, _3, _4, _5, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5), Id)
#define G_TYPED_KERNEL_HELPER_6(Class, _1, _2, _3, _4, _5, _6, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6), Id)
#define G_TYPED_KERNEL_HELPER_7(Class, _1, _2, _3, _4, _5, _6, _7, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7), Id)
#define G_TYPED_KERNEL_HELPER_8(Class, _1, _2, _3, _4, _5, _6, _7, _8, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8), Id)
#define G_TYPED_KERNEL_HELPER_9(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9), Id)
#define G_TYPED_KERNEL_HELPER_10(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, Id) \
G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10), Id)
/**
* Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api)
* for more details.
*
* @param Class type name for this operation.
*/
#define G_TYPED_KERNEL(Class, ...) __WRAP_VAARGS(GET_G_TYPED_KERNEL(__VA_ARGS__, \
G_TYPED_KERNEL_HELPER_10, \
G_TYPED_KERNEL_HELPER_9, \
G_TYPED_KERNEL_HELPER_8, \
G_TYPED_KERNEL_HELPER_7, \
G_TYPED_KERNEL_HELPER_6, \
G_TYPED_KERNEL_HELPER_5, \
G_TYPED_KERNEL_HELPER_4, \
G_TYPED_KERNEL_HELPER_3, \
G_TYPED_KERNEL_HELPER_2, \
G_TYPED_KERNEL_HELPER)(Class, __VA_ARGS__)) \
/**
* Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) for more details.
*
* @deprecated This macro is deprecated in favor of `G_TYPED_KERNEL` that is used for declaring any
* G-API Operation.
*
* @param Class type name for this operation.
*/
#define G_TYPED_KERNEL_M G_TYPED_KERNEL
#define G_API_OP G_TYPED_KERNEL
#define G_API_OP_M G_API_OP
namespace cv
{
namespace gapi
{
// Prework: model "Device" API before it gets to G-API headers.
// FIXME: Don't mix with internal Backends class!
class GAPI_EXPORTS GBackend
{
public:
class Priv;
// TODO: make it template (call `new` within??)
GBackend();
explicit GBackend(std::shared_ptr<Priv> &&p);
Priv& priv();
const Priv& priv() const;
std::size_t hash() const;
bool operator== (const GBackend &rhs) const;
private:
std::shared_ptr<Priv> m_priv;
};
inline bool operator != (const GBackend &lhs, const GBackend &rhs)
{
return !(lhs == rhs);
}
} // namespace gapi
} // namespace cv
namespace std
{
template<> struct hash<cv::gapi::GBackend>
{
std::size_t operator() (const cv::gapi::GBackend &b) const
{
return b.hash();
}
};
} // namespace std
namespace cv {
namespace gapi {
class GFunctor
{
public:
virtual cv::GKernelImpl impl() const = 0;
virtual cv::gapi::GBackend backend() const = 0;
const char* id() const { return m_id; }
virtual ~GFunctor() = default;
protected:
GFunctor(const char* id) : m_id(id) { };
private:
const char* m_id;
};
/** \addtogroup gapi_compile_args
* @{
*/
// FIXME: Hide implementation
/**
* @brief A container class for heterogeneous kernel
* implementation collections and graph transformations.
*
* GKernelPackage is a special container class which stores kernel
* _implementations_ and graph _transformations_. Objects of this class
* are created and passed to cv::GComputation::compile() to specify
* which kernels to use and which transformations to apply in the
* compiled graph. GKernelPackage may contain kernels of
* different backends, e.g. be heterogeneous.
*
* The most easy way to create a kernel package is to use function
* cv::gapi::kernels(). This template functions takes kernel
* implementations in form of type list (variadic template) and
* generates a kernel package atop of that.
*
* Kernel packages can be also generated programmatically, starting
* with an empty package (created with the default constructor)
* and then by populating it with kernels via call to
* GKernelPackage::include(). Note this method is also a template
* one since G-API kernel and transformation implementations are _types_,
* not objects.
*
* Finally, two kernel packages can be combined into a new one
* with function cv::gapi::combine().
*/
class GAPI_EXPORTS_W_SIMPLE GKernelPackage
{
/// @private
using M = std::unordered_map<std::string, std::pair<GBackend, GKernelImpl>>;
/// @private
M m_id_kernels;
/// @private
std::vector<GTransform> m_transformations;
protected:
/// @private
// Remove ALL implementations of the given API (identified by ID)
void removeAPI(const std::string &id);
/// @private
// Partial include() specialization for kernels
template <typename KImpl>
typename std::enable_if<(std::is_base_of<cv::detail::KernelTag, KImpl>::value), void>::type
includeHelper()
{
auto backend = KImpl::backend();
auto kernel_id = KImpl::API::id();
auto kernel_impl = GKernelImpl{KImpl::kernel(), &KImpl::API::getOutMeta};
removeAPI(kernel_id);
m_id_kernels[kernel_id] = std::make_pair(backend, kernel_impl);
}
/// @private
// Partial include() specialization for transformations
template <typename TImpl>
typename std::enable_if<(std::is_base_of<cv::detail::TransformTag, TImpl>::value), void>::type
includeHelper()
{
m_transformations.emplace_back(TImpl::transformation());
}
public:
void include(const GFunctor& functor)
{
m_id_kernels[functor.id()] = std::make_pair(functor.backend(), functor.impl());
}
/**
* @brief Returns total number of kernels
* in the package (across all backends included)
*
* @return a number of kernels in the package
*/
std::size_t size() const;
/**
* @brief Returns vector of transformations included in the package
*
* @return vector of transformations included in the package
*/
const std::vector<GTransform>& get_transformations() const;
/**
* @brief Returns vector of kernel ids included in the package
*
* @return vector of kernel ids included in the package
*/
std::vector<std::string> get_kernel_ids() const;
/**
* @brief Test if a particular kernel _implementation_ KImpl is
* included in this kernel package.
*
* @sa includesAPI()
*
* @note cannot be applied to transformations
*
* @return true if there is such kernel, false otherwise.
*/
template<typename KImpl>
bool includes() const
{
static_assert(std::is_base_of<cv::detail::KernelTag, KImpl>::value,
"includes() can be applied to kernels only");
auto kernel_it = m_id_kernels.find(KImpl::API::id());
return kernel_it != m_id_kernels.end() &&
kernel_it->second.first == KImpl::backend();
}
/**
* @brief Remove all kernels associated with the given backend
* from the package.
*
* Does nothing if there's no kernels of this backend in the package.
*
* @param backend backend which kernels to remove
*/
void remove(const GBackend& backend);
/**
* @brief Remove all kernels implementing the given API from
* the package.
*
* Does nothing if there's no kernels implementing the given interface.
*/
template<typename KAPI>
void remove()
{
removeAPI(KAPI::id());
}
// FIXME: Rename to includes() and distinguish API/impl case by
// statically?
/**
* Check if package contains ANY implementation of a kernel API
* by API type.
*/
template<typename KAPI>
bool includesAPI() const
{
return includesAPI(KAPI::id());
}
/// @private
bool includesAPI(const std::string &id) const;
// FIXME: The below comment is wrong, and who needs this function?
/**
* @brief Find a kernel (by its API)
*
* Returns implementation corresponding id.
* Throws if nothing found.
*
* @return Backend which hosts matching kernel implementation.
*
*/
template<typename KAPI>
GBackend lookup() const
{
return lookup(KAPI::id()).first;
}
/// @private
std::pair<cv::gapi::GBackend, cv::GKernelImpl>
lookup(const std::string &id) const;
// FIXME: No overwrites allowed?
/**
* @brief Put a new kernel implementation or a new transformation
* KImpl into the package.
*/
template<typename KImpl>
void include()
{
includeHelper<KImpl>();
}
/**
* @brief Adds a new kernel based on it's backend and id into the kernel package
*
* @param backend backend associated with the kernel
* @param kernel_id a name/id of the kernel
*/
void include(const cv::gapi::GBackend& backend, const std::string& kernel_id)
{
removeAPI(kernel_id);
m_id_kernels[kernel_id] = std::make_pair(backend, GKernelImpl{{}, {}});
}
/**
* @brief Lists all backends which are included into package
*
* @return vector of backends
*/
std::vector<GBackend> backends() const;
// TODO: Doxygen bug -- it wants me to place this comment
// here, not below.
/**
* @brief Create a new package based on `lhs` and `rhs`.
*
* @param lhs "Left-hand-side" package in the process
* @param rhs "Right-hand-side" package in the process
* @return a new kernel package.
*/
friend GAPI_EXPORTS GKernelPackage combine(const GKernelPackage &lhs,
const GKernelPackage &rhs);
};
/**
* @brief Create a kernel package object containing kernels
* and transformations specified in variadic template argument.
*
* In G-API, kernel implementations and transformations are _types_.
* Every backend has its own kernel API (like GAPI_OCV_KERNEL() and
* GAPI_FLUID_KERNEL()) but all of that APIs define a new type for
* each kernel implementation.
*
* Use this function to pass kernel implementations (defined in
* either way) and transformations to the system. Example:
*
* @snippet modules/gapi/samples/api_ref_snippets.cpp kernels_snippet
*
* Note that kernels() itself is a function returning object, not
* a type, so having `()` at the end is important -- it must be a
* function call.
*/
template<typename... KK> GKernelPackage kernels()
{
// FIXME: currently there is no check that transformations' signatures are unique
// and won't be any intersection in graph compilation stage
static_assert(cv::detail::all_unique<typename KK::API...>::value, "Kernels API must be unique");
GKernelPackage pkg;
// For those who wonder - below is a trick to call a number of
// methods based on parameter pack (zeroes just help hiding these
// calls into a sequence which helps to expand this parameter pack).
// Just note that `f(),a` always equals to `a` (with f() called!)
// and parentheses are used to hide function call in the expanded sequence.
// Leading 0 helps to handle case when KK is an empty list (kernels<>()).
int unused[] = { 0, (pkg.include<KK>(), 0)... };
cv::util::suppress_unused_warning(unused);
return pkg;
};
template<typename... FF>
GKernelPackage kernels(FF&... functors)
{
GKernelPackage pkg;
int unused[] = { 0, (pkg.include(functors), 0)... };
cv::util::suppress_unused_warning(unused);
return pkg;
};
/** @} */
// FYI - this function is already commented above
GAPI_EXPORTS GKernelPackage combine(const GKernelPackage &lhs,
const GKernelPackage &rhs);
/**
* @brief Combines multiple G-API kernel packages into one
*
* @overload
*
* This function successively combines the passed kernel packages using a right fold.
* Calling `combine(a, b, c)` is equal to `combine(a, combine(b, c))`.
*
* @return The resulting kernel package
*/
template<typename... Ps>
GKernelPackage combine(const GKernelPackage &a, const GKernelPackage &b, Ps&&... rest)
{
return combine(a, combine(b, rest...));
}
/** \addtogroup gapi_compile_args
* @{
*/
/**
* @brief cv::use_only() is a special combinator which hints G-API to use only
* kernels specified in cv::GComputation::compile() (and not to extend kernels available by
* default with that package).
*/
struct GAPI_EXPORTS use_only
{
GKernelPackage pkg;
};
/** @} */
} // namespace gapi
namespace detail
{
template<> struct CompileArgTag<cv::gapi::GKernelPackage>
{
static const char* tag() { return "gapi.kernel_package"; }
};
template<> struct CompileArgTag<cv::gapi::use_only>
{
static const char* tag() { return "gapi.use_only"; }
};
} // namespace detail
} // namespace cv
#endif // OPENCV_GAPI_GKERNEL_HPP
|
/*
=============================================
*
* FileName : testError.cpp
* date: 2021-05-01 23:48
* Author: sunyi
*
==============================================
*/
#include <iostream>
#include "BtError.h"
#include "BtLogger.h"
#include "BtParse.h"
// @brief test BtError.h
int main(int argc, char* argv[]) {
// testError
std::cout<<ErrorCatcher::invalidHashError()<<std::endl;
std::cout<<ErrorCatcher::invalidMessageError()<<std::endl;
std::cout<<ErrorCatcher::invalidParameterError()<<std::endl;
std::cout<<ErrorCatcher::invalidSocketError()<<std::endl;
std::cout<<ErrorCatcher::invalidTrackerReplyError()<<std::endl;
std::cout<<ErrorCatcher::invalidTrackerUrlError()<<std::endl;
Logger logger("./test.log");
logger.log(ERROR)<<ErrorCatcher::invalidParameterError();
logger.log(ERROR)<<ErrorCatcher::invalidSocketError()<<"port:"<<45;
logger.log(INFO)<<ErrorCatcher::invalidSocketError()<<"port:"<<45;
ParseMetaFile btfile("./bt.bittorrent");
btfile.checkParse();
logger.log(TRACE)<< btfile.getAnnounce();
logger.log(TRACE)<< btfile.getPieceLength();
logger.log(TRACE)<< btfile.getInfoHash();
logger.log(TRACE)<< btfile.getFilePathAndLength();
return 0;
}
|
//
#include<iostream>
#include "arr_functions.h"
void iterate_array(int* ints, int SIZE)
{
for (int i = 0; i < SIZE; ++i)
{
std::cout << *ints << "\n";
ints++;
}
}
|
// Copyright Vladimir Prus 2004.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_DLL_HPP_VP_2004_08_24
#define BOOST_DLL_HPP_VP_2004_08_24
#include <string>
#include <stdexcept>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/type_traits/remove_pointer.hpp>
// FIXME: that's for Linux only
#include <dlfcn.h>
#include <iostream>
namespace utilmm { namespace plugin {
struct killer
{
killer(void* h) : h(h) {}
template<class T>
void operator()(T)
{
std::cout << "Killing DLL\n";
dlclose(h);
}
void* h;
};
class dll {
public:
dll() {} // TODO: should remove this or make non-public
dll(const std::string& name) : m_name(name) {}
template<typename SymbolType>
boost::shared_ptr<
typename boost::remove_pointer<SymbolType>::type>
get(const std::string& symbol_name) const
{
// TODO: static assert that SymbolType is a pointer.
typedef typename boost::remove_pointer<SymbolType>::type PointedType;
// Open the library. Yes, we do it on every access to
// a symbol, see the design discussion in the documentation.
void* handle = dlopen(m_name.c_str(), RTLD_LAZY|RTLD_GLOBAL);
if (!handle) {
throw std::logic_error("Could not open DLL");
}
// Clear the error state.
dlerror();
void* address = dlsym(handle, symbol_name.c_str());
char* error = dlerror();
if (error) {
throw std::logic_error(error);
}
// Cast the to right type.
SymbolType s = (SymbolType)(address);
boost::shared_ptr<PointedType> result(s,
//killer(handle));
boost::bind(dlclose, handle));
return result;
}
private:
std::string m_name;
};
}}
#endif
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/background-parsing-task.h"
#include "src/objects-inl.h"
#include "src/parsing/parser.h"
#include "src/vm-state-inl.h"
namespace v8 {
namespace internal {
void StreamedSource::Release() {
parser.reset();
info.reset();
}
BackgroundParsingTask::BackgroundParsingTask(
StreamedSource* source, ScriptCompiler::CompileOptions options,
int stack_size, Isolate* isolate)
: source_(source), stack_size_(stack_size), script_data_(nullptr) {
// We don't set the context to the CompilationInfo yet, because the background
// thread cannot do anything with it anyway. We set it just before compilation
// on the foreground thread.
DCHECK(options == ScriptCompiler::kProduceParserCache ||
options == ScriptCompiler::kProduceCodeCache ||
options == ScriptCompiler::kNoCompileOptions);
VMState<PARSER> state(isolate);
// Prepare the data for the internalization phase and compilation phase, which
// will happen in the main thread after parsing.
ParseInfo* info = new ParseInfo(isolate->allocator());
info->InitFromIsolate(isolate);
info->set_toplevel();
source->info.reset(info);
info->set_source_stream(source->source_stream.get());
info->set_source_stream_encoding(source->encoding);
info->set_unicode_cache(&source_->unicode_cache);
info->set_compile_options(options);
info->set_allow_lazy_parsing();
if (V8_UNLIKELY(FLAG_runtime_stats)) {
info->set_runtime_call_stats(new (info->zone()) RuntimeCallStats());
}
if (V8_UNLIKELY(info->block_coverage_enabled())) {
info->AllocateSourceRangeMap();
}
source_->info->set_cached_data(&script_data_);
// Parser needs to stay alive for finalizing the parsing on the main
// thread.
source_->parser.reset(new Parser(source_->info.get()));
source_->parser->DeserializeScopeChain(source_->info.get(),
MaybeHandle<ScopeInfo>());
}
void BackgroundParsingTask::Run() {
DisallowHeapAllocation no_allocation;
DisallowHandleAllocation no_handles;
DisallowHandleDereference no_deref;
// Reset the stack limit of the parser to reflect correctly that we're on a
// background thread.
uintptr_t stack_limit = GetCurrentStackPosition() - stack_size_ * KB;
source_->parser->set_stack_limit(stack_limit);
source_->parser->ParseOnBackground(source_->info.get());
if (script_data_ != nullptr) {
source_->cached_data.reset(new ScriptCompiler::CachedData(
script_data_->data(), script_data_->length(),
ScriptCompiler::CachedData::BufferOwned));
script_data_->ReleaseDataOwnership();
delete script_data_;
script_data_ = nullptr;
}
}
} // namespace internal
} // namespace v8
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2018 The Monkey developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget* parent) : QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
// normal Monkey address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying monkey address(es)
ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont());
ui->payTo->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->addAsLabel->setAttribute(Qt::WA_MacShowFocusRect, 0);
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if (!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec()) {
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString& address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel* model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for insecure payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for secure payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("MONK")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
if (!model->validateAddress(ui->payTo->text())) {
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate()) {
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0) {
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
return recipient;
}
QWidget* SendCoinsEntry::setupTabChain(QWidget* prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget* w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient& value)
{
recipient = value;
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, dont overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
void SendCoinsEntry::setAddress(const QString& address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if (model && model->getOptionsModel()) {
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString& address)
{
if (!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if (!associatedLabel.isEmpty()) {
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
|
#include <iostream>
#include <jni.h>
#include "SkRegion.h"
#include "interop.hh"
static void deleteRegion(SkRegion* region) {
// std::cout << "Deleting [SkRegion " << Region << "]" << std::endl;
delete region;
}
extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nMake(JNIEnv* env, jclass jclass) {
SkRegion* obj = new SkRegion();
return reinterpret_cast<jlong>(obj);
}
extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nGetFinalizer(JNIEnv* env, jclass jclass) {
return static_cast<jlong>(reinterpret_cast<uintptr_t>(&deleteRegion));
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nSet(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* other = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->set(*other);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nIsEmpty(JNIEnv* env, jclass jclass, jlong ptr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->isEmpty();
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nIsRect(JNIEnv* env, jclass jclass, jlong ptr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->isRect();
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nIsComplex(JNIEnv* env, jclass jclass, jlong ptr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->isComplex();
}
extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nGetBounds(JNIEnv* env, jclass jclass, jlong ptr, jintArray ltrbArray) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkIRect bounds = instance->getBounds();
jint ltrb[4] { bounds.left(), bounds.top(), bounds.right(), bounds.bottom() };
env->SetIntArrayRegion(ltrbArray, 0, 4, ltrb);
}
extern "C" JNIEXPORT jint JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nComputeRegionComplexity(JNIEnv* env, jclass jclass, jlong ptr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->computeRegionComplexity();
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nGetBoundaryPath(JNIEnv* env, jclass jclass, jlong ptr, jlong pathPtr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkPath* path = reinterpret_cast<SkPath*>(static_cast<uintptr_t>(pathPtr));
return instance->getBoundaryPath(path);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nSetEmpty(JNIEnv* env, jclass jclass, jlong ptr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->setEmpty();
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nSetRect(JNIEnv* env, jclass jclass, jlong ptr, jint left, jint top, jint right, jint bottom) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->setRect({left, top, right, bottom});
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nSetRects(JNIEnv* env, jclass jclass, jlong ptr, jintArray coords, jint _count) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
int len = env->GetArrayLength(coords);
std::vector<SkIRect> rects(len / 4);
jint* arr = env->GetIntArrayElements(coords, 0);
for (int i = 0; i < len; i += 4)
rects[i / 4] = {arr[i], arr[i+1], arr[i+2], arr[i+3]};
env->ReleaseIntArrayElements(coords, arr, 0);
return instance->setRects(rects.data(), len / 4);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nSetRegion(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->setRegion(*region);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nSetPath(JNIEnv* env, jclass jclass, jlong ptr, jlong pathPtr, jlong regionPtr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkPath* path = reinterpret_cast<SkPath*>(static_cast<uintptr_t>(pathPtr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->setPath(*path, *region);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nIntersectsIRect(JNIEnv* env, jclass jclass, jlong ptr, jint left, jint top, jint right, jint bottom) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->intersects({left, top, right, bottom});
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nIntersectsRegion(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->intersects(*region);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nContainsIPoint(JNIEnv* env, jclass jclass, jlong ptr, jint x, jint y) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->contains(x, y);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nContainsIRect(JNIEnv* env, jclass jclass, jlong ptr, jint left, jint top, jint right, jint bottom) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->contains({left, top, right, bottom});
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nContainsRegion(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->contains(*region);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nQuickContains(JNIEnv* env, jclass jclass, jlong ptr, jint left, jint top, jint right, jint bottom) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->quickContains({left, top, right, bottom});
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nQuickRejectIRect(JNIEnv* env, jclass jclass, jlong ptr, jint left, jint top, jint right, jint bottom) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->quickReject({left, top, right, bottom});
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nQuickRejectRegion(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtr) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->contains(*region);
}
extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nTranslate(JNIEnv* env, jclass jclass, jlong ptr, jint dx, jint dy) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
instance->translate(dx, dy);
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nOpIRect(JNIEnv* env, jclass jclass, jlong ptr, jint left, jint top, jint right, jint bottom, jint op) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
return instance->op({left, top, right, bottom}, static_cast<SkRegion::Op>(op));
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nOpRegion(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtr, jint op) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->op(*region, static_cast<SkRegion::Op>(op));
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nOpIRectRegion(JNIEnv* env, jclass jclass, jlong ptr, jint left, jint top, jint right, jint bottom, jlong regionPtr, jint op) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->op({left, top, right, bottom}, *region, static_cast<SkRegion::Op>(op));
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nOpRegionIRect(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtr, jint left, jint top, jint right, jint bottom, jint op) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* region = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtr));
return instance->op(*region, {left, top, right, bottom}, static_cast<SkRegion::Op>(op));
}
extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_RegionKt_Region_1nOpRegionRegion(JNIEnv* env, jclass jclass, jlong ptr, jlong regionPtrA, jlong regionPtrB, jint op) {
SkRegion* instance = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(ptr));
SkRegion* regionA = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtrA));
SkRegion* regionB = reinterpret_cast<SkRegion*>(static_cast<uintptr_t>(regionPtrB));
return instance->op(*regionA, *regionB, static_cast<SkRegion::Op>(op));
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/layers/picture_layer_impl.h"
#include <utility>
#include "cc/layers/append_quads_data.h"
#include "cc/layers/picture_layer.h"
#include "cc/test/fake_content_layer_client.h"
#include "cc/test/fake_impl_proxy.h"
#include "cc/test/fake_layer_tree_host_impl.h"
#include "cc/test/fake_output_surface.h"
#include "cc/test/fake_picture_layer_impl.h"
#include "cc/test/fake_picture_pile_impl.h"
#include "cc/test/geometry_test_utils.h"
#include "cc/test/impl_side_painting_settings.h"
#include "cc/test/mock_quad_culler.h"
#include "cc/test/test_web_graphics_context_3d.h"
#include "cc/trees/layer_tree_impl.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "ui/gfx/rect_conversions.h"
namespace cc {
namespace {
class MockCanvas : public SkCanvas {
public:
explicit MockCanvas(SkBaseDevice* device) : SkCanvas(device) {}
virtual void drawRect(const SkRect& rect, const SkPaint& paint) OVERRIDE {
// Capture calls before SkCanvas quickReject() kicks in.
rects_.push_back(rect);
}
std::vector<SkRect> rects_;
};
class PictureLayerImplTest : public testing::Test {
public:
PictureLayerImplTest()
: host_impl_(ImplSidePaintingSettings(), &proxy_), id_(7) {}
explicit PictureLayerImplTest(const LayerTreeSettings& settings)
: host_impl_(settings, &proxy_), id_(7) {}
virtual ~PictureLayerImplTest() {
}
virtual void SetUp() OVERRIDE {
InitializeRenderer();
}
virtual void InitializeRenderer() {
host_impl_.InitializeRenderer(
FakeOutputSurface::Create3d().PassAs<OutputSurface>());
}
void SetupDefaultTrees(const gfx::Size& layer_bounds) {
gfx::Size tile_size(100, 100);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
}
void ActivateTree() {
host_impl_.ActivatePendingTree();
CHECK(!host_impl_.pending_tree());
pending_layer_ = NULL;
active_layer_ = static_cast<FakePictureLayerImpl*>(
host_impl_.active_tree()->LayerById(id_));
}
void SetupDefaultTreesWithFixedTileSize(const gfx::Size& layer_bounds,
const gfx::Size& tile_size) {
SetupDefaultTrees(layer_bounds);
pending_layer_->set_fixed_tile_size(tile_size);
active_layer_->set_fixed_tile_size(tile_size);
}
void SetupTrees(
scoped_refptr<PicturePileImpl> pending_pile,
scoped_refptr<PicturePileImpl> active_pile) {
SetupPendingTree(active_pile);
ActivateTree();
SetupPendingTree(pending_pile);
}
void CreateHighLowResAndSetAllTilesVisible() {
// Active layer must get updated first so pending layer can share from it.
active_layer_->CreateDefaultTilingsAndTiles();
active_layer_->SetAllTilesVisible();
pending_layer_->CreateDefaultTilingsAndTiles();
pending_layer_->SetAllTilesVisible();
}
void AddDefaultTilingsWithInvalidation(const Region& invalidation) {
active_layer_->AddTiling(2.3f);
active_layer_->AddTiling(1.0f);
active_layer_->AddTiling(0.5f);
for (size_t i = 0; i < active_layer_->tilings()->num_tilings(); ++i)
active_layer_->tilings()->tiling_at(i)->CreateAllTilesForTesting();
pending_layer_->set_invalidation(invalidation);
for (size_t i = 0; i < pending_layer_->tilings()->num_tilings(); ++i)
pending_layer_->tilings()->tiling_at(i)->CreateAllTilesForTesting();
}
void SetupPendingTree(
scoped_refptr<PicturePileImpl> pile) {
host_impl_.CreatePendingTree();
LayerTreeImpl* pending_tree = host_impl_.pending_tree();
// Clear recycled tree.
pending_tree->DetachLayerTree();
scoped_ptr<FakePictureLayerImpl> pending_layer =
FakePictureLayerImpl::CreateWithPile(pending_tree, id_, pile);
pending_layer->SetDrawsContent(true);
pending_tree->SetRootLayer(pending_layer.PassAs<LayerImpl>());
pending_layer_ = static_cast<FakePictureLayerImpl*>(
host_impl_.pending_tree()->LayerById(id_));
pending_layer_->DoPostCommitInitializationIfNeeded();
}
static void VerifyAllTilesExistAndHavePile(
const PictureLayerTiling* tiling,
PicturePileImpl* pile) {
for (PictureLayerTiling::CoverageIterator
iter(tiling, tiling->contents_scale(), tiling->ContentRect());
iter;
++iter) {
EXPECT_TRUE(*iter);
EXPECT_EQ(pile, iter->picture_pile());
}
}
void SetContentsScaleOnBothLayers(float contents_scale,
float device_scale_factor,
float page_scale_factor,
bool animating_transform) {
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
pending_layer_->CalculateContentsScale(
contents_scale,
device_scale_factor,
page_scale_factor,
animating_transform,
&result_scale_x,
&result_scale_y,
&result_bounds);
active_layer_->CalculateContentsScale(
contents_scale,
device_scale_factor,
page_scale_factor,
animating_transform,
&result_scale_x,
&result_scale_y,
&result_bounds);
}
void ResetTilingsAndRasterScales() {
pending_layer_->ReleaseResources();
active_layer_->ReleaseResources();
}
void AssertAllTilesRequired(PictureLayerTiling* tiling) {
std::vector<Tile*> tiles = tiling->AllTilesForTesting();
for (size_t i = 0; i < tiles.size(); ++i)
EXPECT_TRUE(tiles[i]->required_for_activation()) << "i: " << i;
EXPECT_GT(tiles.size(), 0u);
}
void AssertNoTilesRequired(PictureLayerTiling* tiling) {
std::vector<Tile*> tiles = tiling->AllTilesForTesting();
for (size_t i = 0; i < tiles.size(); ++i)
EXPECT_FALSE(tiles[i]->required_for_activation()) << "i: " << i;
EXPECT_GT(tiles.size(), 0u);
}
protected:
void TestTileGridAlignmentCommon() {
// Layer to span 4 raster tiles in x and in y
ImplSidePaintingSettings settings;
gfx::Size layer_size(
settings.default_tile_size.width() * 7 / 2,
settings.default_tile_size.height() * 7 / 2);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(layer_size, layer_size);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(layer_size, layer_size);
SetupTrees(pending_pile, active_pile);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
active_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
// Add 1x1 rects at the centers of each tile, then re-record pile contents
active_layer_->tilings()->tiling_at(0)->CreateAllTilesForTesting();
std::vector<Tile*> tiles =
active_layer_->tilings()->tiling_at(0)->AllTilesForTesting();
EXPECT_EQ(16u, tiles.size());
std::vector<SkRect> rects;
std::vector<Tile*>::const_iterator tile_iter;
for (tile_iter = tiles.begin(); tile_iter < tiles.end(); tile_iter++) {
gfx::Point tile_center = (*tile_iter)->content_rect().CenterPoint();
gfx::Rect rect(tile_center.x(), tile_center.y(), 1, 1);
active_pile->add_draw_rect(rect);
rects.push_back(SkRect::MakeXYWH(rect.x(), rect.y(), 1, 1));
}
// Force re-record with newly injected content
active_pile->RemoveRecordingAt(0, 0);
active_pile->AddRecordingAt(0, 0);
SkBitmap store;
store.setConfig(SkBitmap::kNo_Config, 1000, 1000);
SkBitmapDevice device(store);
std::vector<SkRect>::const_iterator rect_iter = rects.begin();
for (tile_iter = tiles.begin(); tile_iter < tiles.end(); tile_iter++) {
MockCanvas mock_canvas(&device);
active_pile->RasterDirect(
&mock_canvas, (*tile_iter)->content_rect(), 1.0f, NULL);
// This test verifies that when drawing the contents of a specific tile
// at content scale 1.0, the playback canvas never receives content from
// neighboring tiles which indicates that the tile grid embedded in
// SkPicture is perfectly aligned with the compositor's tiles.
EXPECT_EQ(1u, mock_canvas.rects_.size());
EXPECT_RECT_EQ(*rect_iter, mock_canvas.rects_[0]);
rect_iter++;
}
}
FakeImplProxy proxy_;
FakeLayerTreeHostImpl host_impl_;
int id_;
FakePictureLayerImpl* pending_layer_;
FakePictureLayerImpl* active_layer_;
private:
DISALLOW_COPY_AND_ASSIGN(PictureLayerImplTest);
};
TEST_F(PictureLayerImplTest, TileGridAlignment) {
host_impl_.SetDeviceScaleFactor(1.f);
TestTileGridAlignmentCommon();
}
TEST_F(PictureLayerImplTest, TileGridAlignmentHiDPI) {
host_impl_.SetDeviceScaleFactor(2.f);
TestTileGridAlignmentCommon();
}
TEST_F(PictureLayerImplTest, CloneNoInvalidation) {
gfx::Size tile_size(100, 100);
gfx::Size layer_bounds(400, 400);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
Region invalidation;
AddDefaultTilingsWithInvalidation(invalidation);
EXPECT_EQ(pending_layer_->tilings()->num_tilings(),
active_layer_->tilings()->num_tilings());
const PictureLayerTilingSet* tilings = pending_layer_->tilings();
EXPECT_GT(tilings->num_tilings(), 0u);
for (size_t i = 0; i < tilings->num_tilings(); ++i)
VerifyAllTilesExistAndHavePile(tilings->tiling_at(i), active_pile.get());
}
TEST_F(PictureLayerImplTest, SuppressUpdateTilePriorities) {
base::TimeTicks time_ticks;
host_impl_.SetCurrentFrameTimeTicks(time_ticks);
gfx::Size tile_size(100, 100);
gfx::Size layer_bounds(400, 400);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
Region invalidation;
AddDefaultTilingsWithInvalidation(invalidation);
float dummy_contents_scale_x;
float dummy_contents_scale_y;
gfx::Size dummy_content_bounds;
active_layer_->CalculateContentsScale(1.f,
1.f,
1.f,
false,
&dummy_contents_scale_x,
&dummy_contents_scale_y,
&dummy_content_bounds);
EXPECT_TRUE(host_impl_.manage_tiles_needed());
active_layer_->UpdateTilePriorities();
host_impl_.ManageTiles();
EXPECT_FALSE(host_impl_.manage_tiles_needed());
time_ticks += base::TimeDelta::FromMilliseconds(200);
host_impl_.SetCurrentFrameTimeTicks(time_ticks);
// Setting this boolean should cause an early out in UpdateTilePriorities.
bool valid_for_tile_management = false;
host_impl_.SetExternalDrawConstraints(gfx::Transform(),
gfx::Rect(layer_bounds),
gfx::Rect(layer_bounds),
valid_for_tile_management);
active_layer_->UpdateTilePriorities();
EXPECT_FALSE(host_impl_.manage_tiles_needed());
time_ticks += base::TimeDelta::FromMilliseconds(200);
host_impl_.SetCurrentFrameTimeTicks(time_ticks);
valid_for_tile_management = true;
host_impl_.SetExternalDrawConstraints(gfx::Transform(),
gfx::Rect(layer_bounds),
gfx::Rect(layer_bounds),
valid_for_tile_management);
active_layer_->UpdateTilePriorities();
EXPECT_TRUE(host_impl_.manage_tiles_needed());
}
TEST_F(PictureLayerImplTest, ClonePartialInvalidation) {
gfx::Size tile_size(100, 100);
gfx::Size layer_bounds(400, 400);
gfx::Rect layer_invalidation(150, 200, 30, 180);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
Region invalidation(layer_invalidation);
AddDefaultTilingsWithInvalidation(invalidation);
const PictureLayerTilingSet* tilings = pending_layer_->tilings();
EXPECT_GT(tilings->num_tilings(), 0u);
for (size_t i = 0; i < tilings->num_tilings(); ++i) {
const PictureLayerTiling* tiling = tilings->tiling_at(i);
gfx::Rect content_invalidation = gfx::ScaleToEnclosingRect(
layer_invalidation,
tiling->contents_scale());
for (PictureLayerTiling::CoverageIterator
iter(tiling,
tiling->contents_scale(),
tiling->ContentRect());
iter;
++iter) {
EXPECT_TRUE(*iter);
EXPECT_FALSE(iter.geometry_rect().IsEmpty());
if (iter.geometry_rect().Intersects(content_invalidation))
EXPECT_EQ(pending_pile, iter->picture_pile());
else
EXPECT_EQ(active_pile, iter->picture_pile());
}
}
}
TEST_F(PictureLayerImplTest, CloneFullInvalidation) {
gfx::Size tile_size(90, 80);
gfx::Size layer_bounds(300, 500);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
Region invalidation((gfx::Rect(layer_bounds)));
AddDefaultTilingsWithInvalidation(invalidation);
EXPECT_EQ(pending_layer_->tilings()->num_tilings(),
active_layer_->tilings()->num_tilings());
const PictureLayerTilingSet* tilings = pending_layer_->tilings();
EXPECT_GT(tilings->num_tilings(), 0u);
for (size_t i = 0; i < tilings->num_tilings(); ++i)
VerifyAllTilesExistAndHavePile(tilings->tiling_at(i), pending_pile.get());
}
TEST_F(PictureLayerImplTest, NoInvalidationBoundsChange) {
gfx::Size tile_size(90, 80);
gfx::Size active_layer_bounds(300, 500);
gfx::Size pending_layer_bounds(400, 800);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size,
pending_layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, active_layer_bounds);
SetupTrees(pending_pile, active_pile);
pending_layer_->set_fixed_tile_size(gfx::Size(100, 100));
Region invalidation;
AddDefaultTilingsWithInvalidation(invalidation);
const PictureLayerTilingSet* tilings = pending_layer_->tilings();
EXPECT_GT(tilings->num_tilings(), 0u);
for (size_t i = 0; i < tilings->num_tilings(); ++i) {
const PictureLayerTiling* tiling = tilings->tiling_at(i);
gfx::Rect active_content_bounds = gfx::ScaleToEnclosingRect(
gfx::Rect(active_layer_bounds),
tiling->contents_scale());
for (PictureLayerTiling::CoverageIterator
iter(tiling,
tiling->contents_scale(),
tiling->ContentRect());
iter;
++iter) {
EXPECT_TRUE(*iter);
EXPECT_FALSE(iter.geometry_rect().IsEmpty());
std::vector<Tile*> active_tiles =
active_layer_->tilings()->tiling_at(i)->AllTilesForTesting();
std::vector<Tile*> pending_tiles = tiling->AllTilesForTesting();
if (iter.geometry_rect().right() >= active_content_bounds.width() ||
iter.geometry_rect().bottom() >= active_content_bounds.height() ||
active_tiles[0]->content_rect().size() !=
pending_tiles[0]->content_rect().size()) {
EXPECT_EQ(pending_pile, iter->picture_pile());
} else {
EXPECT_EQ(active_pile, iter->picture_pile());
}
}
}
}
TEST_F(PictureLayerImplTest, AddTilesFromNewRecording) {
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateEmptyPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateEmptyPile(tile_size, layer_bounds);
// Fill in some of active pile, but more of pending pile.
int hole_count = 0;
for (int x = 0; x < active_pile->tiling().num_tiles_x(); ++x) {
for (int y = 0; y < active_pile->tiling().num_tiles_y(); ++y) {
if ((x + y) % 2) {
pending_pile->AddRecordingAt(x, y);
active_pile->AddRecordingAt(x, y);
} else {
hole_count++;
if (hole_count % 2)
pending_pile->AddRecordingAt(x, y);
}
}
}
SetupTrees(pending_pile, active_pile);
Region invalidation;
AddDefaultTilingsWithInvalidation(invalidation);
const PictureLayerTilingSet* tilings = pending_layer_->tilings();
EXPECT_GT(tilings->num_tilings(), 0u);
for (size_t i = 0; i < tilings->num_tilings(); ++i) {
const PictureLayerTiling* tiling = tilings->tiling_at(i);
for (PictureLayerTiling::CoverageIterator
iter(tiling,
tiling->contents_scale(),
tiling->ContentRect());
iter;
++iter) {
EXPECT_FALSE(iter.full_tile_geometry_rect().IsEmpty());
// Ensure there is a recording for this tile.
gfx::Rect layer_rect = gfx::ScaleToEnclosingRect(
iter.full_tile_geometry_rect(), 1.f / tiling->contents_scale());
layer_rect.Intersect(gfx::Rect(layer_bounds));
bool in_pending = pending_pile->recorded_region().Contains(layer_rect);
bool in_active = active_pile->recorded_region().Contains(layer_rect);
if (in_pending && !in_active)
EXPECT_EQ(pending_pile, iter->picture_pile());
else if (in_active)
EXPECT_EQ(active_pile, iter->picture_pile());
else
EXPECT_FALSE(*iter);
}
}
}
TEST_F(PictureLayerImplTest, ManageTilingsWithNoRecording) {
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateEmptyPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateEmptyPile(tile_size, layer_bounds);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
SetupTrees(pending_pile, active_pile);
pending_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
}
TEST_F(PictureLayerImplTest, ManageTilingsCreatesTilings) {
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
SetupTrees(pending_pile, active_pile);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
EXPECT_LT(low_res_factor, 1.f);
pending_layer_->CalculateContentsScale(1.3f, // ideal contents scale
1.7f, // device scale
3.2f, // page cale
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(2u, pending_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.3f,
pending_layer_->tilings()->tiling_at(0)->contents_scale());
EXPECT_FLOAT_EQ(
1.3f * low_res_factor,
pending_layer_->tilings()->tiling_at(1)->contents_scale());
// If we change the layer's CSS scale factor, then we should not get new
// tilings.
pending_layer_->CalculateContentsScale(1.8f, // ideal contents scale
1.7f, // device scale
3.2f, // page cale
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(2u, pending_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.3f,
pending_layer_->tilings()->tiling_at(0)->contents_scale());
EXPECT_FLOAT_EQ(
1.3f * low_res_factor,
pending_layer_->tilings()->tiling_at(1)->contents_scale());
// If we change the page scale factor, then we should get new tilings.
pending_layer_->CalculateContentsScale(1.8f, // ideal contents scale
1.7f, // device scale
2.2f, // page cale
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(4u, pending_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.8f,
pending_layer_->tilings()->tiling_at(0)->contents_scale());
EXPECT_FLOAT_EQ(
1.8f * low_res_factor,
pending_layer_->tilings()->tiling_at(2)->contents_scale());
// If we change the device scale factor, then we should get new tilings.
pending_layer_->CalculateContentsScale(1.9f, // ideal contents scale
1.4f, // device scale
2.2f, // page cale
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(6u, pending_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.9f,
pending_layer_->tilings()->tiling_at(0)->contents_scale());
EXPECT_FLOAT_EQ(
1.9f * low_res_factor,
pending_layer_->tilings()->tiling_at(3)->contents_scale());
// If we change the device scale factor, but end up at the same total scale
// factor somehow, then we don't get new tilings.
pending_layer_->CalculateContentsScale(1.9f, // ideal contents scale
2.2f, // device scale
1.4f, // page cale
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(6u, pending_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.9f,
pending_layer_->tilings()->tiling_at(0)->contents_scale());
EXPECT_FLOAT_EQ(
1.9f * low_res_factor,
pending_layer_->tilings()->tiling_at(3)->contents_scale());
}
TEST_F(PictureLayerImplTest, CreateTilingsEvenIfTwinHasNone) {
// This test makes sure that if a layer can have tilings, then a commit makes
// it not able to have tilings (empty size), and then a future commit that
// makes it valid again should be able to create tilings.
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> empty_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, gfx::Size(1000, 0));
scoped_refptr<FakePicturePileImpl> valid_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
EXPECT_LT(low_res_factor, 1.f);
float high_res_scale = 1.3f;
float low_res_scale = high_res_scale * low_res_factor;
float device_scale = 1.7f;
float page_scale = 3.2f;
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
SetupPendingTree(valid_pile);
pending_layer_->CalculateContentsScale(high_res_scale,
device_scale,
page_scale,
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(2u, pending_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(high_res_scale,
pending_layer_->HighResTiling()->contents_scale());
EXPECT_FLOAT_EQ(low_res_scale,
pending_layer_->LowResTiling()->contents_scale());
ActivateTree();
SetupPendingTree(empty_pile);
pending_layer_->CalculateContentsScale(high_res_scale,
device_scale,
page_scale,
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(2u, active_layer_->tilings()->num_tilings());
ASSERT_EQ(0u, pending_layer_->tilings()->num_tilings());
ActivateTree();
active_layer_->CalculateContentsScale(high_res_scale,
device_scale,
page_scale,
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(0u, active_layer_->tilings()->num_tilings());
SetupPendingTree(valid_pile);
pending_layer_->CalculateContentsScale(high_res_scale,
device_scale,
page_scale,
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
ASSERT_EQ(2u, pending_layer_->tilings()->num_tilings());
ASSERT_EQ(0u, active_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(high_res_scale,
pending_layer_->HighResTiling()->contents_scale());
EXPECT_FLOAT_EQ(low_res_scale,
pending_layer_->LowResTiling()->contents_scale());
}
TEST_F(PictureLayerImplTest, ZoomOutCrash) {
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
// Set up the high and low res tilings before pinch zoom.
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
EXPECT_EQ(0u, active_layer_->tilings()->num_tilings());
SetContentsScaleOnBothLayers(32.0f, 1.0f, 32.0f, false);
host_impl_.PinchGestureBegin();
SetContentsScaleOnBothLayers(1.0f, 1.0f, 1.0f, false);
SetContentsScaleOnBothLayers(1.0f, 1.0f, 1.0f, false);
EXPECT_EQ(active_layer_->tilings()->NumHighResTilings(), 1);
}
TEST_F(PictureLayerImplTest, PinchGestureTilings) {
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
// Set up the high and low res tilings before pinch zoom.
SetupTrees(pending_pile, active_pile);
EXPECT_EQ(0u, active_layer_->tilings()->num_tilings());
SetContentsScaleOnBothLayers(1.0f, 1.0f, 1.0f, false);
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
EXPECT_EQ(2u, active_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.0f,
active_layer_->tilings()->tiling_at(0)->contents_scale());
EXPECT_FLOAT_EQ(
1.0f * low_res_factor,
active_layer_->tilings()->tiling_at(1)->contents_scale());
// Start a pinch gesture.
host_impl_.PinchGestureBegin();
// Zoom out by a small amount. We should create a tiling at half
// the scale (1/kMaxScaleRatioDuringPinch).
SetContentsScaleOnBothLayers(0.90f, 1.0f, 0.9f, false);
EXPECT_EQ(3u, active_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.0f,
active_layer_->tilings()->tiling_at(0)->contents_scale());
EXPECT_FLOAT_EQ(
0.5f,
active_layer_->tilings()->tiling_at(1)->contents_scale());
EXPECT_FLOAT_EQ(
1.0f * low_res_factor,
active_layer_->tilings()->tiling_at(2)->contents_scale());
// Zoom out further, close to our low-res scale factor. We should
// use that tiling as high-res, and not create a new tiling.
SetContentsScaleOnBothLayers(low_res_factor, 1.0f, low_res_factor, false);
EXPECT_EQ(3u, active_layer_->tilings()->num_tilings());
// Zoom in a lot now. Since we increase by increments of
// kMaxScaleRatioDuringPinch, this will first use 0.5, then 1.0
// and then finally create a new tiling at 2.0.
SetContentsScaleOnBothLayers(2.1f, 1.0f, 2.1f, false);
EXPECT_EQ(3u, active_layer_->tilings()->num_tilings());
SetContentsScaleOnBothLayers(2.1f, 1.0f, 2.1f, false);
EXPECT_EQ(3u, active_layer_->tilings()->num_tilings());
SetContentsScaleOnBothLayers(2.1f, 1.0f, 2.1f, false);
EXPECT_EQ(4u, active_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
2.0f,
active_layer_->tilings()->tiling_at(0)->contents_scale());
}
TEST_F(PictureLayerImplTest, CleanUpTilings) {
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
std::vector<PictureLayerTiling*> used_tilings;
SetupTrees(pending_pile, active_pile);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
EXPECT_LT(low_res_factor, 1.f);
float device_scale = 1.7f;
float page_scale = 3.2f;
SetContentsScaleOnBothLayers(1.f, device_scale, page_scale, false);
ASSERT_EQ(2u, active_layer_->tilings()->num_tilings());
// We only have ideal tilings, so they aren't removed.
used_tilings.clear();
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(2u, active_layer_->tilings()->num_tilings());
// Changing the ideal but not creating new tilings.
SetContentsScaleOnBothLayers(1.5f, device_scale, page_scale, false);
ASSERT_EQ(2u, active_layer_->tilings()->num_tilings());
// The tilings are still our target scale, so they aren't removed.
used_tilings.clear();
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(2u, active_layer_->tilings()->num_tilings());
// Create a 1.2 scale tiling. Now we have 1.0 and 1.2 tilings. Ideal = 1.2.
page_scale = 1.2f;
SetContentsScaleOnBothLayers(1.2f, device_scale, page_scale, false);
ASSERT_EQ(4u, active_layer_->tilings()->num_tilings());
EXPECT_FLOAT_EQ(
1.f,
active_layer_->tilings()->tiling_at(1)->contents_scale());
EXPECT_FLOAT_EQ(
1.f * low_res_factor,
active_layer_->tilings()->tiling_at(3)->contents_scale());
// Mark the non-ideal tilings as used. They won't be removed.
used_tilings.clear();
used_tilings.push_back(active_layer_->tilings()->tiling_at(1));
used_tilings.push_back(active_layer_->tilings()->tiling_at(3));
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(4u, active_layer_->tilings()->num_tilings());
// Now move the ideal scale to 0.5. Our target stays 1.2.
SetContentsScaleOnBothLayers(0.5f, device_scale, page_scale, false);
// The high resolution tiling is between target and ideal, so is not
// removed. The low res tiling for the old ideal=1.0 scale is removed.
used_tilings.clear();
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(3u, active_layer_->tilings()->num_tilings());
// Now move the ideal scale to 1.0. Our target stays 1.2.
SetContentsScaleOnBothLayers(1.f, device_scale, page_scale, false);
// All the tilings are between are target and the ideal, so they are not
// removed.
used_tilings.clear();
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(3u, active_layer_->tilings()->num_tilings());
// Now move the ideal scale to 1.1 on the active layer. Our target stays 1.2.
active_layer_->CalculateContentsScale(1.1f,
device_scale,
page_scale,
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
// Because the pending layer's ideal scale is still 1.0, our tilings fall
// in the range [1.0,1.2] and are kept.
used_tilings.clear();
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(3u, active_layer_->tilings()->num_tilings());
// Move the ideal scale on the pending layer to 1.1 as well. Our target stays
// 1.2 still.
pending_layer_->CalculateContentsScale(1.1f,
device_scale,
page_scale,
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
// Our 1.0 tiling now falls outside the range between our ideal scale and our
// target raster scale. But it is in our used tilings set, so nothing is
// deleted.
used_tilings.clear();
used_tilings.push_back(active_layer_->tilings()->tiling_at(1));
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(3u, active_layer_->tilings()->num_tilings());
// If we remove it from our used tilings set, it is outside the range to keep
// so it is deleted.
used_tilings.clear();
active_layer_->CleanUpTilingsOnActiveLayer(used_tilings);
ASSERT_EQ(2u, active_layer_->tilings()->num_tilings());
}
#define EXPECT_BOTH_EQ(expression, x) \
do { \
EXPECT_EQ(pending_layer_->expression, x); \
EXPECT_EQ(active_layer_->expression, x); \
} while (false)
TEST_F(PictureLayerImplTest, DontAddLowResDuringAnimation) {
// Make sure this layer covers multiple tiles, since otherwise low
// res won't get created because it is too small.
gfx::Size tile_size(host_impl_.settings().default_tile_size);
SetupDefaultTrees(gfx::Size(tile_size.width() + 1, tile_size.height() + 1));
// Avoid max untiled layer size heuristics via fixed tile size.
pending_layer_->set_fixed_tile_size(tile_size);
active_layer_->set_fixed_tile_size(tile_size);
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
float contents_scale = 1.f;
float device_scale = 1.f;
float page_scale = 1.f;
bool animating_transform = true;
// Animating, so don't create low res even if there isn't one already.
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), 1.f);
EXPECT_BOTH_EQ(num_tilings(), 1u);
// Stop animating, low res gets created.
animating_transform = false;
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), 1.f);
EXPECT_BOTH_EQ(LowResTiling()->contents_scale(), low_res_factor);
EXPECT_BOTH_EQ(num_tilings(), 2u);
// Page scale animation, new high res, but not new low res because animating.
contents_scale = 2.f;
page_scale = 2.f;
animating_transform = true;
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), 2.f);
EXPECT_BOTH_EQ(LowResTiling()->contents_scale(), low_res_factor);
EXPECT_BOTH_EQ(num_tilings(), 3u);
// Stop animating, new low res gets created for final page scale.
animating_transform = false;
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), 2.f);
EXPECT_BOTH_EQ(LowResTiling()->contents_scale(), 2.f * low_res_factor);
EXPECT_BOTH_EQ(num_tilings(), 4u);
}
TEST_F(PictureLayerImplTest, DontAddLowResForSmallLayers) {
gfx::Size tile_size(host_impl_.settings().default_tile_size);
SetupDefaultTrees(tile_size);
float low_res_factor = host_impl_.settings().low_res_contents_scale_factor;
float device_scale = 1.f;
float page_scale = 1.f;
bool animating_transform = false;
// Contents exactly fit on one tile at scale 1, no low res.
float contents_scale = 1.f;
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), contents_scale);
EXPECT_BOTH_EQ(num_tilings(), 1u);
ResetTilingsAndRasterScales();
// Contents that are smaller than one tile, no low res.
contents_scale = 0.123f;
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), contents_scale);
EXPECT_BOTH_EQ(num_tilings(), 1u);
ResetTilingsAndRasterScales();
// Any content bounds that would create more than one tile will
// generate a low res tiling.
contents_scale = 2.5f;
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), contents_scale);
EXPECT_BOTH_EQ(LowResTiling()->contents_scale(),
contents_scale * low_res_factor);
EXPECT_BOTH_EQ(num_tilings(), 2u);
ResetTilingsAndRasterScales();
// Mask layers dont create low res since they always fit on one tile.
pending_layer_->SetIsMask(true);
active_layer_->SetIsMask(true);
SetContentsScaleOnBothLayers(
contents_scale, device_scale, page_scale, animating_transform);
EXPECT_BOTH_EQ(HighResTiling()->contents_scale(), contents_scale);
EXPECT_BOTH_EQ(num_tilings(), 1u);
}
TEST_F(PictureLayerImplTest, ReleaseResources) {
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
SetupTrees(pending_pile, active_pile);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
pending_layer_->CalculateContentsScale(1.3f, // ideal contents scale
2.7f, // device scale
3.2f, // page cale
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
EXPECT_EQ(2u, pending_layer_->tilings()->num_tilings());
// All tilings should be removed when losing output surface.
active_layer_->ReleaseResources();
EXPECT_EQ(0u, active_layer_->tilings()->num_tilings());
pending_layer_->ReleaseResources();
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
// This should create new tilings.
pending_layer_->CalculateContentsScale(1.3f, // ideal contents scale
2.7f, // device scale
3.2f, // page cale
false,
&result_scale_x,
&result_scale_y,
&result_bounds);
EXPECT_EQ(2u, pending_layer_->tilings()->num_tilings());
}
TEST_F(PictureLayerImplTest, ClampTilesToToMaxTileSize) {
// The default max tile size is larger than 400x400.
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(5000, 5000);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
SetupTrees(pending_pile, active_pile);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
pending_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
ASSERT_EQ(2u, pending_layer_->tilings()->num_tilings());
pending_layer_->tilings()->tiling_at(0)->CreateAllTilesForTesting();
// The default value.
EXPECT_EQ(gfx::Size(256, 256).ToString(),
host_impl_.settings().default_tile_size.ToString());
Tile* tile = pending_layer_->tilings()->tiling_at(0)->AllTilesForTesting()[0];
EXPECT_EQ(gfx::Size(256, 256).ToString(),
tile->content_rect().size().ToString());
pending_layer_->ReleaseResources();
// Change the max texture size on the output surface context.
scoped_ptr<TestWebGraphicsContext3D> context =
TestWebGraphicsContext3D::Create();
context->set_max_texture_size(140);
host_impl_.DidLoseOutputSurface();
host_impl_.InitializeRenderer(FakeOutputSurface::Create3d(
context.Pass()).PassAs<OutputSurface>());
pending_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
ASSERT_EQ(2u, pending_layer_->tilings()->num_tilings());
pending_layer_->tilings()->tiling_at(0)->CreateAllTilesForTesting();
// Verify the tiles are not larger than the context's max texture size.
tile = pending_layer_->tilings()->tiling_at(0)->AllTilesForTesting()[0];
EXPECT_GE(140, tile->content_rect().width());
EXPECT_GE(140, tile->content_rect().height());
}
TEST_F(PictureLayerImplTest, ClampSingleTileToToMaxTileSize) {
// The default max tile size is larger than 400x400.
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(500, 500);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
SetupTrees(pending_pile, active_pile);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
pending_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
ASSERT_LE(1u, pending_layer_->tilings()->num_tilings());
pending_layer_->tilings()->tiling_at(0)->CreateAllTilesForTesting();
// The default value. The layer is smaller than this.
EXPECT_EQ(gfx::Size(512, 512).ToString(),
host_impl_.settings().max_untiled_layer_size.ToString());
// There should be a single tile since the layer is small.
PictureLayerTiling* high_res_tiling = pending_layer_->tilings()->tiling_at(0);
EXPECT_EQ(1u, high_res_tiling->AllTilesForTesting().size());
pending_layer_->ReleaseResources();
// Change the max texture size on the output surface context.
scoped_ptr<TestWebGraphicsContext3D> context =
TestWebGraphicsContext3D::Create();
context->set_max_texture_size(140);
host_impl_.DidLoseOutputSurface();
host_impl_.InitializeRenderer(FakeOutputSurface::Create3d(
context.Pass()).PassAs<OutputSurface>());
pending_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
ASSERT_LE(1u, pending_layer_->tilings()->num_tilings());
pending_layer_->tilings()->tiling_at(0)->CreateAllTilesForTesting();
// There should be more than one tile since the max texture size won't cover
// the layer.
high_res_tiling = pending_layer_->tilings()->tiling_at(0);
EXPECT_LT(1u, high_res_tiling->AllTilesForTesting().size());
// Verify the tiles are not larger than the context's max texture size.
Tile* tile = pending_layer_->tilings()->tiling_at(0)->AllTilesForTesting()[0];
EXPECT_GE(140, tile->content_rect().width());
EXPECT_GE(140, tile->content_rect().height());
}
TEST_F(PictureLayerImplTest, DisallowTileDrawQuads) {
MockQuadCuller quad_culler;
gfx::Size tile_size(400, 400);
gfx::Size layer_bounds(1300, 1900);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
active_layer_->SetContentBounds(layer_bounds);
active_layer_->draw_properties().visible_content_rect =
gfx::Rect(layer_bounds);
gfx::Rect layer_invalidation(150, 200, 30, 180);
Region invalidation(layer_invalidation);
AddDefaultTilingsWithInvalidation(invalidation);
AppendQuadsData data;
active_layer_->WillDraw(DRAW_MODE_RESOURCELESS_SOFTWARE, NULL);
active_layer_->AppendQuads(&quad_culler, &data);
active_layer_->DidDraw(NULL);
ASSERT_EQ(1U, quad_culler.quad_list().size());
EXPECT_EQ(DrawQuad::PICTURE_CONTENT, quad_culler.quad_list()[0]->material);
}
TEST_F(PictureLayerImplTest, MarkRequiredNullTiles) {
gfx::Size tile_size(100, 100);
gfx::Size layer_bounds(1000, 1000);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateEmptyPile(tile_size, layer_bounds);
// Layers with entirely empty piles can't get tilings.
pending_pile->AddRecordingAt(0, 0);
SetupPendingTree(pending_pile);
ASSERT_TRUE(pending_layer_->CanHaveTilings());
pending_layer_->AddTiling(1.0f);
pending_layer_->AddTiling(2.0f);
// It should be safe to call this (and MarkVisibleResourcesAsRequired)
// on a layer with no recordings.
host_impl_.pending_tree()->UpdateDrawProperties();
pending_layer_->MarkVisibleResourcesAsRequired();
}
TEST_F(PictureLayerImplTest, MarkRequiredOffscreenTiles) {
gfx::Size tile_size(100, 100);
gfx::Size layer_bounds(200, 200);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupPendingTree(pending_pile);
pending_layer_->set_fixed_tile_size(tile_size);
ASSERT_TRUE(pending_layer_->CanHaveTilings());
PictureLayerTiling* tiling = pending_layer_->AddTiling(1.f);
host_impl_.pending_tree()->UpdateDrawProperties();
EXPECT_EQ(tiling->resolution(), HIGH_RESOLUTION);
pending_layer_->draw_properties().visible_content_rect =
gfx::Rect(0, 0, 100, 200);
// Fake set priorities.
for (PictureLayerTiling::CoverageIterator iter(
tiling, pending_layer_->contents_scale_x(), gfx::Rect(layer_bounds));
iter;
++iter) {
if (!*iter)
continue;
Tile* tile = *iter;
TilePriority priority;
priority.resolution = HIGH_RESOLUTION;
gfx::Rect tile_bounds = iter.geometry_rect();
if (pending_layer_->visible_content_rect().Intersects(tile_bounds)) {
priority.priority_bin = TilePriority::NOW;
priority.distance_to_visible = 0.f;
} else {
priority.priority_bin = TilePriority::SOON;
priority.distance_to_visible = 1.f;
}
tile->SetPriority(PENDING_TREE, priority);
}
pending_layer_->MarkVisibleResourcesAsRequired();
int num_visible = 0;
int num_offscreen = 0;
for (PictureLayerTiling::CoverageIterator iter(
tiling, pending_layer_->contents_scale_x(), gfx::Rect(layer_bounds));
iter;
++iter) {
if (!*iter)
continue;
const Tile* tile = *iter;
if (tile->priority(PENDING_TREE).distance_to_visible == 0.f) {
EXPECT_TRUE(tile->required_for_activation());
num_visible++;
} else {
EXPECT_FALSE(tile->required_for_activation());
num_offscreen++;
}
}
EXPECT_GT(num_visible, 0);
EXPECT_GT(num_offscreen, 0);
}
TEST_F(PictureLayerImplTest, HighResRequiredWhenUnsharedActiveAllReady) {
gfx::Size layer_bounds(400, 400);
gfx::Size tile_size(100, 100);
SetupDefaultTreesWithFixedTileSize(layer_bounds, tile_size);
// No tiles shared.
pending_layer_->set_invalidation(gfx::Rect(layer_bounds));
CreateHighLowResAndSetAllTilesVisible();
active_layer_->SetAllTilesReady();
// No shared tiles and all active tiles ready, so pending can only
// activate with all high res tiles.
pending_layer_->MarkVisibleResourcesAsRequired();
AssertAllTilesRequired(pending_layer_->HighResTiling());
AssertNoTilesRequired(pending_layer_->LowResTiling());
}
TEST_F(PictureLayerImplTest, HighResRequiredWhenMissingHighResFlagOn) {
gfx::Size layer_bounds(400, 400);
gfx::Size tile_size(100, 100);
SetupDefaultTreesWithFixedTileSize(layer_bounds, tile_size);
// All tiles shared (no invalidation).
CreateHighLowResAndSetAllTilesVisible();
// Verify active tree not ready.
Tile* some_active_tile =
active_layer_->HighResTiling()->AllTilesForTesting()[0];
EXPECT_FALSE(some_active_tile->IsReadyToDraw());
// When high res are required, even if the active tree is not ready,
// the high res tiles must be ready.
host_impl_.active_tree()->SetRequiresHighResToDraw();
pending_layer_->MarkVisibleResourcesAsRequired();
AssertAllTilesRequired(pending_layer_->HighResTiling());
AssertNoTilesRequired(pending_layer_->LowResTiling());
}
TEST_F(PictureLayerImplTest, NothingRequiredIfAllHighResTilesShared) {
gfx::Size layer_bounds(400, 400);
gfx::Size tile_size(100, 100);
SetupDefaultTreesWithFixedTileSize(layer_bounds, tile_size);
CreateHighLowResAndSetAllTilesVisible();
Tile* some_active_tile =
active_layer_->HighResTiling()->AllTilesForTesting()[0];
EXPECT_FALSE(some_active_tile->IsReadyToDraw());
// All tiles shared (no invalidation), so even though the active tree's
// tiles aren't ready, there is nothing required.
pending_layer_->MarkVisibleResourcesAsRequired();
AssertNoTilesRequired(pending_layer_->HighResTiling());
AssertNoTilesRequired(pending_layer_->LowResTiling());
}
TEST_F(PictureLayerImplTest, NothingRequiredIfActiveMissingTiles) {
gfx::Size layer_bounds(400, 400);
gfx::Size tile_size(100, 100);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
// An arbitrary bogus outside the layer recording. Enough for the layer to
// think it can create tiles, but not in bounds so all tiles are null.
Region active_recorded_region;
active_recorded_region.Union(gfx::Rect(1000, 1000, 1, 1));
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreatePileWithRecordedRegion(
tile_size, layer_bounds, active_recorded_region);
SetupTrees(pending_pile, active_pile);
pending_layer_->set_fixed_tile_size(tile_size);
active_layer_->set_fixed_tile_size(tile_size);
CreateHighLowResAndSetAllTilesVisible();
// Active layer has tilings, but no tiles due to missing recordings.
EXPECT_TRUE(active_layer_->CanHaveTilings());
EXPECT_EQ(active_layer_->tilings()->num_tilings(), 2u);
EXPECT_EQ(active_layer_->HighResTiling()->AllTilesForTesting().size(), 0u);
// Since the active layer has no tiles at all, the pending layer doesn't
// need content in order to activate. This is attempting to simulate
// scrolling past the end of recorded content on the active layer.
pending_layer_->MarkVisibleResourcesAsRequired();
AssertNoTilesRequired(pending_layer_->HighResTiling());
AssertNoTilesRequired(pending_layer_->LowResTiling());
}
TEST_F(PictureLayerImplTest, HighResRequiredIfActiveCantHaveTiles) {
gfx::Size layer_bounds(400, 400);
gfx::Size tile_size(100, 100);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateEmptyPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
pending_layer_->set_fixed_tile_size(tile_size);
active_layer_->set_fixed_tile_size(tile_size);
CreateHighLowResAndSetAllTilesVisible();
// Active layer can't have tiles.
EXPECT_FALSE(active_layer_->CanHaveTilings());
// All high res tiles required. This should be considered identical
// to the case where there is no active layer, to avoid flashing content.
// This can happen if a layer exists for a while and switches from
// not being able to have content to having content.
pending_layer_->MarkVisibleResourcesAsRequired();
AssertAllTilesRequired(pending_layer_->HighResTiling());
AssertNoTilesRequired(pending_layer_->LowResTiling());
}
TEST_F(PictureLayerImplTest, ActivateUninitializedLayer) {
gfx::Size tile_size(100, 100);
gfx::Size layer_bounds(400, 400);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
host_impl_.CreatePendingTree();
LayerTreeImpl* pending_tree = host_impl_.pending_tree();
scoped_ptr<FakePictureLayerImpl> pending_layer =
FakePictureLayerImpl::CreateWithPile(pending_tree, id_, pending_pile);
pending_layer->SetDrawsContent(true);
pending_tree->SetRootLayer(pending_layer.PassAs<LayerImpl>());
pending_layer_ = static_cast<FakePictureLayerImpl*>(
host_impl_.pending_tree()->LayerById(id_));
// Set some state on the pending layer, make sure it is not clobbered
// by a sync from the active layer. This could happen because if the
// pending layer has not been post-commit initialized it will attempt
// to sync from the active layer.
bool default_lcd_text_setting = pending_layer_->is_using_lcd_text();
pending_layer_->force_set_lcd_text(!default_lcd_text_setting);
EXPECT_TRUE(pending_layer_->needs_post_commit_initialization());
host_impl_.ActivatePendingTree();
active_layer_ = static_cast<FakePictureLayerImpl*>(
host_impl_.active_tree()->LayerById(id_));
EXPECT_EQ(0u, active_layer_->num_tilings());
EXPECT_EQ(!default_lcd_text_setting, active_layer_->is_using_lcd_text());
EXPECT_FALSE(active_layer_->needs_post_commit_initialization());
}
TEST_F(PictureLayerImplTest, SyncTilingAfterReleaseResource) {
SetupDefaultTrees(gfx::Size(10, 10));
host_impl_.active_tree()->UpdateDrawProperties();
EXPECT_FALSE(host_impl_.active_tree()->needs_update_draw_properties());
// Contrived unit test of a real crash. A layer is transparent during a
// context loss, and later becomes opaque, causing active layer SyncTiling to
// be called.
const float tile_scale = 2.f;
active_layer_->ReleaseResources();
EXPECT_FALSE(active_layer_->tilings()->TilingAtScale(tile_scale));
pending_layer_->AddTiling(2.f);
EXPECT_TRUE(active_layer_->tilings()->TilingAtScale(tile_scale));
}
TEST_F(PictureLayerImplTest, TilingGpuRasterization) {
gfx::Size default_tile_size(host_impl_.settings().default_tile_size);
gfx::Size layer_bounds(default_tile_size.width() * 4,
default_tile_size.height() * 4);
float result_scale_x, result_scale_y;
gfx::Size result_bounds;
// Layers without GPU rasterization (default).
SetupDefaultTrees(layer_bounds);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
pending_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
// Should have a low-res and a high-res tiling.
ASSERT_EQ(2u, pending_layer_->tilings()->num_tilings());
// Tell the layer to use GPU rasterization.
pending_layer_->SetShouldUseGpuRasterization(true);
EXPECT_EQ(0u, pending_layer_->tilings()->num_tilings());
pending_layer_->CalculateContentsScale(
1.f, 1.f, 1.f, false, &result_scale_x, &result_scale_y, &result_bounds);
// Should only have the high-res tiling.
ASSERT_EQ(1u, pending_layer_->tilings()->num_tilings());
}
TEST_F(PictureLayerImplTest, NoTilingIfDoesNotDrawContent) {
// Set up layers with tilings.
SetupDefaultTrees(gfx::Size(10, 10));
SetContentsScaleOnBothLayers(1.f, 1.f, 1.f, false);
pending_layer_->PushPropertiesTo(active_layer_);
EXPECT_TRUE(pending_layer_->DrawsContent());
EXPECT_TRUE(pending_layer_->CanHaveTilings());
EXPECT_GE(pending_layer_->num_tilings(), 0u);
EXPECT_GE(active_layer_->num_tilings(), 0u);
// Set content to false, which should make CanHaveTilings return false.
pending_layer_->SetDrawsContent(false);
EXPECT_FALSE(pending_layer_->DrawsContent());
EXPECT_FALSE(pending_layer_->CanHaveTilings());
// No tilings should be pushed to active layer.
pending_layer_->PushPropertiesTo(active_layer_);
EXPECT_EQ(0u, active_layer_->num_tilings());
}
TEST_F(PictureLayerImplTest, FirstTilingDuringPinch) {
SetupDefaultTrees(gfx::Size(10, 10));
host_impl_.PinchGestureBegin();
float high_res_scale = 2.3f;
SetContentsScaleOnBothLayers(high_res_scale, 1.f, 1.f, false);
ASSERT_GE(pending_layer_->num_tilings(), 0u);
EXPECT_FLOAT_EQ(high_res_scale,
pending_layer_->HighResTiling()->contents_scale());
}
TEST_F(PictureLayerImplTest, FirstTilingTooSmall) {
SetupDefaultTrees(gfx::Size(10, 10));
host_impl_.PinchGestureBegin();
float high_res_scale = 0.0001f;
EXPECT_GT(pending_layer_->MinimumContentsScale(), high_res_scale);
SetContentsScaleOnBothLayers(high_res_scale, 1.f, 1.f, false);
ASSERT_GE(pending_layer_->num_tilings(), 0u);
EXPECT_FLOAT_EQ(pending_layer_->MinimumContentsScale(),
pending_layer_->HighResTiling()->contents_scale());
}
TEST_F(PictureLayerImplTest, PinchingTooSmall) {
SetupDefaultTrees(gfx::Size(10, 10));
float contents_scale = 0.15f;
SetContentsScaleOnBothLayers(contents_scale, 1.f, 1.f, false);
ASSERT_GE(pending_layer_->num_tilings(), 0u);
EXPECT_FLOAT_EQ(contents_scale,
pending_layer_->HighResTiling()->contents_scale());
host_impl_.PinchGestureBegin();
float page_scale = 0.0001f;
EXPECT_LT(page_scale * contents_scale,
pending_layer_->MinimumContentsScale());
SetContentsScaleOnBothLayers(contents_scale, 1.f, page_scale, false);
ASSERT_GE(pending_layer_->num_tilings(), 0u);
EXPECT_FLOAT_EQ(pending_layer_->MinimumContentsScale(),
pending_layer_->HighResTiling()->contents_scale());
}
class DeferredInitPictureLayerImplTest : public PictureLayerImplTest {
public:
DeferredInitPictureLayerImplTest()
: PictureLayerImplTest(ImplSidePaintingSettings()) {}
virtual void InitializeRenderer() OVERRIDE {
host_impl_.InitializeRenderer(FakeOutputSurface::CreateDeferredGL(
scoped_ptr<SoftwareOutputDevice>(new SoftwareOutputDevice))
.PassAs<OutputSurface>());
}
virtual void SetUp() OVERRIDE {
PictureLayerImplTest::SetUp();
// Create some default active and pending trees.
gfx::Size tile_size(100, 100);
gfx::Size layer_bounds(400, 400);
scoped_refptr<FakePicturePileImpl> pending_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
scoped_refptr<FakePicturePileImpl> active_pile =
FakePicturePileImpl::CreateFilledPile(tile_size, layer_bounds);
SetupTrees(pending_pile, active_pile);
}
};
// This test is really a LayerTreeHostImpl test, in that it makes sure
// that trees need update draw properties after deferred initialization.
// However, this is also a regression test for PictureLayerImpl in that
// not having this update will cause a crash.
TEST_F(DeferredInitPictureLayerImplTest,
PreventUpdateTilePrioritiesDuringLostContext) {
host_impl_.pending_tree()->UpdateDrawProperties();
host_impl_.active_tree()->UpdateDrawProperties();
EXPECT_FALSE(host_impl_.pending_tree()->needs_update_draw_properties());
EXPECT_FALSE(host_impl_.active_tree()->needs_update_draw_properties());
FakeOutputSurface* fake_output_surface =
static_cast<FakeOutputSurface*>(host_impl_.output_surface());
ASSERT_TRUE(fake_output_surface->InitializeAndSetContext3d(
TestContextProvider::Create(), NULL));
// These will crash PictureLayerImpl if this is not true.
ASSERT_TRUE(host_impl_.pending_tree()->needs_update_draw_properties());
ASSERT_TRUE(host_impl_.active_tree()->needs_update_draw_properties());
host_impl_.active_tree()->UpdateDrawProperties();
}
} // namespace
} // namespace cc
|
// Copyright 2017 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 "components/payments/core/autofill_payment_instrument.h"
#include <memory>
#include "base/macros.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/address_normalizer.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/credit_card.h"
#include "components/autofill/core/browser/payments/full_card_request.h"
#include "components/autofill/core/browser/payments/payments_client.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/test_address_normalizer.h"
#include "components/autofill/core/browser/test_autofill_client.h"
#include "components/autofill/core/browser/test_personal_data_manager.h"
#include "components/payments/core/test_payment_request_delegate.h"
#include "components/strings/grit/components_strings.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
namespace payments {
namespace {
class FakePaymentInstrumentDelegate : public PaymentInstrument::Delegate {
public:
FakePaymentInstrumentDelegate() {}
void OnInstrumentDetailsReady(
const std::string& method_name,
const std::string& stringified_details) override {
on_instrument_details_ready_called_ = true;
}
void OnInstrumentDetailsError() override {
on_instrument_details_error_called_ = true;
}
bool WasOnInstrumentDetailsReadyCalled() {
return on_instrument_details_ready_called_;
}
bool WasOnInstrumentDetailsErrorCalled() {
return on_instrument_details_error_called_;
}
private:
bool on_instrument_details_ready_called_ = false;
bool on_instrument_details_error_called_ = false;
};
class FakePaymentRequestDelegate
: public PaymentRequestDelegate,
public autofill::payments::PaymentsClientUnmaskDelegate {
public:
FakePaymentRequestDelegate()
: locale_("en-US"),
last_committed_url_("https://shop.com"),
personal_data_("en-US"),
request_context_(new net::TestURLRequestContextGetter(
base::ThreadTaskRunnerHandle::Get())),
payments_client_(request_context_.get(),
nullptr,
nullptr,
this,
nullptr),
full_card_request_(&autofill_client_,
&payments_client_,
&personal_data_) {}
void ShowDialog(PaymentRequest* request) override {}
void CloseDialog() override {}
void ShowErrorMessage() override {}
autofill::PersonalDataManager* GetPersonalDataManager() override {
return nullptr;
}
const std::string& GetApplicationLocale() const override { return locale_; }
bool IsIncognito() const override { return false; }
bool IsSslCertificateValid() override { return true; }
const GURL& GetLastCommittedURL() const override {
return last_committed_url_;
}
void DoFullCardRequest(
const autofill::CreditCard& credit_card,
base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate>
result_delegate) override {
full_card_request_card_ = credit_card;
full_card_result_delegate_ = result_delegate;
}
autofill::AddressNormalizer* GetAddressNormalizer() override {
return &address_normalizer_;
}
void CompleteFullCardRequest() {
full_card_result_delegate_->OnFullCardRequestSucceeded(
full_card_request_, full_card_request_card_, base::ASCIIToUTF16("123"));
}
autofill::RegionDataLoader* GetRegionDataLoader() override { return nullptr; }
ukm::UkmRecorder* GetUkmRecorder() override { return nullptr; }
private:
std::string locale_;
const GURL last_committed_url_;
autofill::TestAddressNormalizer address_normalizer_;
autofill::PersonalDataManager personal_data_;
scoped_refptr<net::TestURLRequestContextGetter> request_context_;
autofill::TestAutofillClient autofill_client_;
autofill::payments::PaymentsClient payments_client_;
autofill::payments::FullCardRequest full_card_request_;
autofill::CreditCard full_card_request_card_;
base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate>
full_card_result_delegate_;
DISALLOW_COPY_AND_ASSIGN(FakePaymentRequestDelegate);
};
} // namespace
class AutofillPaymentInstrumentTest : public testing::Test {
protected:
AutofillPaymentInstrumentTest()
: address_(autofill::test::GetFullProfile()),
local_card_(autofill::test::GetCreditCard()),
billing_profiles_({&address_}) {
local_card_.set_billing_address_id(address_.guid());
}
autofill::CreditCard& local_credit_card() { return local_card_; }
const std::vector<autofill::AutofillProfile*>& billing_profiles() {
return billing_profiles_;
}
private:
autofill::AutofillProfile address_;
autofill::CreditCard local_card_;
std::vector<autofill::AutofillProfile*> billing_profiles_;
DISALLOW_COPY_AND_ASSIGN(AutofillPaymentInstrumentTest);
};
// A valid local credit card is a valid instrument for payment.
TEST_F(AutofillPaymentInstrumentTest, IsCompleteForPayment) {
AutofillPaymentInstrument instrument(
"visa", local_credit_card(),
/*matches_merchant_card_type_exactly=*/true, billing_profiles(), "en-US",
nullptr);
EXPECT_TRUE(instrument.IsCompleteForPayment());
EXPECT_TRUE(instrument.GetMissingInfoLabel().empty());
}
// An expired local card is still a valid instrument for payment.
TEST_F(AutofillPaymentInstrumentTest, IsCompleteForPayment_Expired) {
autofill::CreditCard& card = local_credit_card();
card.SetExpirationYear(2016); // Expired.
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_TRUE(instrument.IsCompleteForPayment());
EXPECT_EQ(base::string16(), instrument.GetMissingInfoLabel());
}
// A local card with no name is not a valid instrument for payment.
TEST_F(AutofillPaymentInstrumentTest, IsCompleteForPayment_NoName) {
autofill::CreditCard& card = local_credit_card();
card.SetInfo(autofill::AutofillType(autofill::CREDIT_CARD_NAME_FULL),
base::ASCIIToUTF16(""), "en-US");
base::string16 missing_info;
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_FALSE(instrument.IsCompleteForPayment());
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_PAYMENTS_NAME_ON_CARD_REQUIRED),
instrument.GetMissingInfoLabel());
}
// A local card with no name is not a valid instrument for payment.
TEST_F(AutofillPaymentInstrumentTest, IsCompleteForPayment_NoNumber) {
autofill::CreditCard& card = local_credit_card();
card.SetNumber(base::ASCIIToUTF16(""));
base::string16 missing_info;
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_FALSE(instrument.IsCompleteForPayment());
EXPECT_EQ(l10n_util::GetStringUTF16(
IDS_PAYMENTS_CARD_NUMBER_INVALID_VALIDATION_MESSAGE),
instrument.GetMissingInfoLabel());
}
// A local card with no billing address id is not a valid instrument for
// payment.
TEST_F(AutofillPaymentInstrumentTest, IsCompleteForPayment_NoBillinbAddressId) {
autofill::CreditCard& card = local_credit_card();
card.set_billing_address_id("");
base::string16 missing_info;
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_FALSE(instrument.IsCompleteForPayment());
EXPECT_EQ(
l10n_util::GetStringUTF16(IDS_PAYMENTS_CARD_BILLING_ADDRESS_REQUIRED),
instrument.GetMissingInfoLabel());
}
// A local card with an invalid billing address id is not a valid instrument for
// payment.
TEST_F(AutofillPaymentInstrumentTest,
IsCompleteForPayment_InvalidBillinbAddressId) {
autofill::CreditCard& card = local_credit_card();
card.set_billing_address_id("InvalidBillingAddressId");
base::string16 missing_info;
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_FALSE(instrument.IsCompleteForPayment());
EXPECT_EQ(
l10n_util::GetStringUTF16(IDS_PAYMENTS_CARD_BILLING_ADDRESS_REQUIRED),
instrument.GetMissingInfoLabel());
}
// A local card with no name and no number is not a valid instrument for
// payment.
TEST_F(AutofillPaymentInstrumentTest,
IsCompleteForPayment_MultipleThingsMissing) {
autofill::CreditCard& card = local_credit_card();
card.SetNumber(base::ASCIIToUTF16(""));
card.SetInfo(autofill::AutofillType(autofill::CREDIT_CARD_NAME_FULL),
base::ASCIIToUTF16(""), "en-US");
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_FALSE(instrument.IsCompleteForPayment());
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_PAYMENTS_MORE_INFORMATION_REQUIRED),
instrument.GetMissingInfoLabel());
}
// A Masked (server) card is a valid instrument for payment.
TEST_F(AutofillPaymentInstrumentTest, IsCompleteForPayment_MaskedCard) {
autofill::CreditCard card = autofill::test::GetMaskedServerCard();
ASSERT_GT(billing_profiles().size(), 0UL);
card.set_billing_address_id(billing_profiles()[0]->guid());
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_TRUE(instrument.IsCompleteForPayment());
EXPECT_TRUE(instrument.GetMissingInfoLabel().empty());
}
// An expired masked (server) card is still a valid instrument for payment.
TEST_F(AutofillPaymentInstrumentTest, IsCompleteForPayment_ExpiredMaskedCard) {
autofill::CreditCard card = autofill::test::GetMaskedServerCard();
ASSERT_GT(billing_profiles().size(), 0UL);
card.set_billing_address_id(billing_profiles()[0]->guid());
card.SetExpirationYear(2016); // Expired.
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_TRUE(instrument.IsCompleteForPayment());
EXPECT_EQ(base::string16(), instrument.GetMissingInfoLabel());
}
// An expired card is a valid instrument for canMakePayment.
TEST_F(AutofillPaymentInstrumentTest, IsValidForCanMakePayment_Minimal) {
autofill::CreditCard& card = local_credit_card();
card.SetExpirationYear(2016); // Expired.
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_TRUE(instrument.IsValidForCanMakePayment());
}
// An expired Masked (server) card is a valid instrument for canMakePayment.
TEST_F(AutofillPaymentInstrumentTest, IsValidForCanMakePayment_MaskedCard) {
autofill::CreditCard card = autofill::test::GetMaskedServerCard();
card.SetExpirationYear(2016); // Expired.
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_TRUE(instrument.IsValidForCanMakePayment());
}
// A card with no name is not a valid instrument for canMakePayment.
TEST_F(AutofillPaymentInstrumentTest, IsValidForCanMakePayment_NoName) {
autofill::CreditCard& card = local_credit_card();
card.SetInfo(autofill::AutofillType(autofill::CREDIT_CARD_NAME_FULL),
base::ASCIIToUTF16(""), "en-US");
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_FALSE(instrument.IsValidForCanMakePayment());
}
// A card with no number is not a valid instrument for canMakePayment.
TEST_F(AutofillPaymentInstrumentTest, IsValidForCanMakePayment_NoNumber) {
autofill::CreditCard& card = local_credit_card();
card.SetNumber(base::ASCIIToUTF16(""));
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", nullptr);
EXPECT_FALSE(instrument.IsValidForCanMakePayment());
}
// Tests that the autofill instrument only calls OnInstrumentDetailsReady when
// the billing address has been normalized and the card has been unmasked.
TEST_F(AutofillPaymentInstrumentTest,
InvokePaymentApp_NormalizationBeforeUnmask) {
auto personal_data_manager =
std::make_unique<autofill::TestPersonalDataManager>();
TestPaymentRequestDelegate delegate(personal_data_manager.get());
delegate.DelayFullCardRequestCompletion();
delegate.test_address_normalizer()->DelayNormalization();
autofill::CreditCard& card = local_credit_card();
card.SetNumber(base::ASCIIToUTF16(""));
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", &delegate);
FakePaymentInstrumentDelegate instrument_delegate;
instrument.InvokePaymentApp(&instrument_delegate);
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsReadyCalled());
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsErrorCalled());
delegate.test_address_normalizer()->CompleteAddressNormalization();
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsReadyCalled());
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsErrorCalled());
delegate.CompleteFullCardRequest();
EXPECT_TRUE(instrument_delegate.WasOnInstrumentDetailsReadyCalled());
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsErrorCalled());
}
// Tests that the autofill instrument only calls OnInstrumentDetailsReady when
// the billing address has been normalized and the card has been unmasked.
TEST_F(AutofillPaymentInstrumentTest,
InvokePaymentApp_UnmaskBeforeNormalization) {
auto personal_data_manager =
std::make_unique<autofill::TestPersonalDataManager>();
TestPaymentRequestDelegate delegate(personal_data_manager.get());
delegate.DelayFullCardRequestCompletion();
delegate.test_address_normalizer()->DelayNormalization();
autofill::CreditCard& card = local_credit_card();
card.SetNumber(base::ASCIIToUTF16(""));
AutofillPaymentInstrument instrument(
"visa", card, /*matches_merchant_card_type_exactly=*/true,
billing_profiles(), "en-US", &delegate);
FakePaymentInstrumentDelegate instrument_delegate;
instrument.InvokePaymentApp(&instrument_delegate);
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsReadyCalled());
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsErrorCalled());
delegate.CompleteFullCardRequest();
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsReadyCalled());
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsErrorCalled());
delegate.test_address_normalizer()->CompleteAddressNormalization();
EXPECT_TRUE(instrument_delegate.WasOnInstrumentDetailsReadyCalled());
EXPECT_FALSE(instrument_delegate.WasOnInstrumentDetailsErrorCalled());
}
} // namespace payments
|
/*--------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2016 Great Hill Corporation
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 "parameter.h"
//---------------------------------------------------------------------------
IMPLEMENT_NODE(CParameter, CBaseNode, NO_SCHEMA);
//---------------------------------------------------------------------------
void CParameter::Format(CExportContext& ctx, const SFString& fmtIn, void *data) const
{
if (!isShowing())
return;
SFString fmt = (fmtIn.IsEmpty() ? defaultFormat() : fmtIn); //.Substitute("\n","\t");
if (handleCustomFormat(ctx, fmt, data))
return;
CParameterNotify dn(this);
while (!fmt.IsEmpty())
ctx << getNextChunk(fmt, nextParameterChunk, &dn);
}
//---------------------------------------------------------------------------
SFString nextParameterChunk(const SFString& fieldIn, SFBool& force, const void *data)
{
CParameterNotify *pa = (CParameterNotify*)data;
const CParameter *par = pa->getDataPtr();
// Give common (edit, delete, etc.) code a chance to override
SFString ret = nextChunk_common(fieldIn, getString("cmd"), par);
if (!ret.IsEmpty())
return ret;
// Now give customized code a chance to override
ret = nextParameterChunk_custom(fieldIn, force, data);
if (!ret.IsEmpty())
return ret;
switch (tolower(fieldIn[0]))
{
case 'f':
return EMPTY;
// if ( fieldIn % "func" ) return par->func;
break;
case 'h':
if ( fieldIn % "handle" ) return asString(par->handle);
break;
case 'n':
if ( fieldIn % "name" ) return par->name;
break;
case 't':
if ( fieldIn % "type" ) return par->type;
break;
}
return "<span class=warning>Field not found: [{" + fieldIn + "}]</span>\n";
}
//---------------------------------------------------------------------------------------------------
SFBool CParameter::setValueByName(const SFString& fieldName, const SFString& fieldValue)
{
switch (tolower(fieldName[0]))
{
case 'f':
return TRUE;
// if ( fieldName % "func" ) { func = fieldValue; return TRUE; }
break;
case 'h':
if ( fieldName % "handle" ) { handle = toLong(fieldValue); return TRUE; }
break;
case 'n':
if ( fieldName % "name" ) { name = fieldValue; return TRUE; }
break;
case 't':
if ( fieldName % "type" ) { type = fieldValue; return TRUE; }
break;
default:
break;
}
return FALSE;
}
//---------------------------------------------------------------------------------------------------
void CParameter::finishParse()
{
// EXISTING_CODE
// EXISTING_CODE
}
//---------------------------------------------------------------------------------------------------
void CParameter::Serialize(SFArchive& archive)
{
if (!SerializeHeader(archive))
return;
if (archive.isReading())
{
archive >> handle;
archive >> name;
archive >> type;
// archive >> func;
} else
{
archive << handle;
archive << name;
archive << type;
// archive << func;
}
}
//---------------------------------------------------------------------------
void CParameter::registerClass(void)
{
SFInt32 fieldNum=1000;
ADD_FIELD(CParameter, "schema", T_NUMBER|TS_LABEL, ++fieldNum);
ADD_FIELD(CParameter, "deleted", T_RADIO|TS_LABEL, ++fieldNum);
ADD_FIELD(CParameter, "handle", T_NUMBER|TS_LABEL, ++fieldNum);
ADD_FIELD(CParameter, "name", T_TEXT, ++fieldNum);
ADD_FIELD(CParameter, "type", T_TEXT, ++fieldNum);
ADD_FIELD(CParameter, "func", T_NONE, ++fieldNum);
// Hide our internal fields, user can turn them on if they like
HIDE_FIELD(CParameter, "schema");
HIDE_FIELD(CParameter, "deleted");
HIDE_FIELD(CParameter, "handle");
// EXISTING_CODE
// EXISTING_CODE
}
//---------------------------------------------------------------------------
int sortParameter(const SFString& f1, const SFString& f2, const void *rr1, const void *rr2)
{
CParameter *g1 = (CParameter*)rr1;
CParameter *g2 = (CParameter*)rr2;
SFString v1 = g1->getValueByName(f1);
SFString v2 = g2->getValueByName(f1);
SFInt32 s = v1.Compare(v2);
if (s || f2.IsEmpty())
return (int)s;
v1 = g1->getValueByName(f2);
v2 = g2->getValueByName(f2);
return (int)v1.Compare(v2);
}
int sortParameterByName(const void *rr1, const void *rr2) { return sortParameter("pa_Name", "", rr1, rr2); }
int sortParameterByID (const void *rr1, const void *rr2) { return sortParameter("parameterID", "", rr1, rr2); }
|
#ifndef CGE_PRIOR_TRICK_WIDGET_HPP
#define CGE_PRIOR_TRICK_WIDGET_HPP
#include "Agui/Widget.hpp"
#include "Game/Card/Card.hpp"
#include "Game/UI/GuiFontManager.hpp"
namespace cge
{
class PriorTrickWidget : public agui::Widget
{
std::vector<Card> m_cards;
agui::Image* m_heartImg;
agui::Image* m_diamondImg;
agui::Image* m_clubImg;
agui::Image* m_spadeImg;
agui::Image* m_bg;
int m_hgap;
int m_vgap;
std::string m_priorTrickText;
agui::Color m_black;
agui::Color m_red;
agui::Font* m_rankFont;
GuiFontManager* m_fontManager;
float m_scale;
float m_imgScale;
float m_shadowOffScale;
protected:
virtual void paintBackground(const agui::PaintEvent &paintEvent);
virtual void paintComponent(const agui::PaintEvent &paintEvent);
public:
PriorTrickWidget(
agui::Image* heartImg,
agui::Image* diamondImg,
agui::Image* clubImg,
agui::Image* spadeImg,
agui::Image* bg,
GuiFontManager* fontManager);
virtual ~PriorTrickWidget(void);
void setCards(const std::vector<Card>& cards);
void setPriorTrickText(std::string priorText);
void setBlack(const agui::Color& color);
void setRed(const agui::Color& color);
void setCardRankFont(agui::Font* font);
agui::Image* getSuitImage(Card::SuitEnum suit) const;
void renderCard(agui::AreaAlignmentEnum align, const Card& card,
int hgap, int vgap,
const agui::PaintEvent& paintEvent);
int alignString(const std::string& text, agui::AlignmentEnum align);
agui::Dimension getSuitImgSize(Card::SuitEnum suit) const;
virtual void setSize(const agui::Dimension &size);
};
}
#endif
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <climits>
#include <cassert>
#include <iomanip>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <complex>
#include <numeric>
#include <functional>
#include <sstream>
#include <algorithm>
//Preprocessor directives
#define gc getchar_unlocked
//macros input-output
#define si(n) scanf("%d",&n)
#define sll(n) scanf("%I64",&n)
#define sf(n) scanf("%f",&n)
#define ss(str) scanf("%s",str)
#define sd(n) scanf("%lf",&n)
#define forr(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) forr(i,0,n)
#define pn() printf("\n")
#define pi(n) printf("%d",n)
#define pll(n) printf("%I64",n)
#define pd(n) printf("%lf",n)
#define ps(str) printf("%s",str)
//macros stl
#define mp make_pair
#define pb push_back
#define fill(a,v) memset(a,v,sizeof a)
#define all(x) x.begin(),x.end()
#define uniq(v) sort(all(v));v.erase(unique(all(v)),v.end())
#define findval(arr,val) (lower_bound(all(arr)),val)-arr.begin()
#define clr(a) memset(a,0,sizeof a)
using namespace std;
//typedef
typedef long long LL;
typedef pair<int,int> pii;
#define MAX 1000010
#define MOD 1000000007
int main()
{
int t;
int n,l,k;
char str[MAX];
si(t);
while(t--)
{
scanf("%s",str);
l = strlen(str);
for(int i=0;i<l;i++)
{
if(str[i] == '[')
{
i++;
k=0;
char sub[MAX];
while(i<l && str[i]!=']')
sub[k++] = str[i++];
sub[k] = '\0';
reverse(sub,sub+k);
cout<<sub;
}
else
cout<<str[i];
}
cout<<endl;
}
return 0;
}
|
#include "submodules/svg/Rasterizer.h"
#include <iostream>
#include "core/math/Math.h"
#include "submodules/svg/Commands.h"
#include "submodules/svg/Document.h"
#include "submodules/svg/Path.h"
namespace vanadium::svg {
glm::vec2 Rasterizer::rasterizeCubicStep(const glm::vec2 &p0,
const glm::vec2 &p1,
const glm::vec2 &p2,
const glm::vec2 &p3, float t) {
glm::vec2 A = math::lerp(p0, p1, t);
glm::vec2 B = math::lerp(p1, p2, t);
glm::vec2 C = math::lerp(p2, p3, t);
glm::vec2 D = math::lerp(A, B, t);
glm::vec2 E = math::lerp(B, C, t);
glm::vec2 F = math::lerp(D, E, t); // The juicy one
return F;
}
std::vector<float> Rasterizer::rasterizeCubic(const glm::vec2 &p0,
const glm::vec2 &p1,
const glm::vec2 &p2,
const glm::vec2 &p3,
uint quality) {
std::vector<float> vertices;
vertices.reserve((2 + quality) * 2);
vertices.push_back(p0.x);
vertices.push_back(p0.y);
float delta = 1.0f / (float)quality;
for (size_t i = 0; i < quality; i++) {
float step = (float)i * delta;
glm::vec2 nextPoint = rasterizeCubicStep(p0, p1, p2, p3, step);
vertices.push_back(nextPoint.x);
vertices.push_back(nextPoint.y);
vertices.push_back(nextPoint.x);
vertices.push_back(nextPoint.y);
}
vertices.push_back(p3.x);
vertices.push_back(p3.y);
return vertices;
}
std::vector<float> Rasterizer::rasterize2D(const Path *path, uint quality) {
using VertexArray = std::vector<float>;
VertexArray result;
glm::vec2 currentCoordinates(0.0f);
glm::vec2 pathBegin(0.0f);
glm::vec2 lastCubicPoint(0.0f);
const commands::Command *previousCommand = nullptr;
glm::vec2 lastClosePoint(0.0f);
for (const commands::Command *command : path->getCommands()) {
if (command->getType() == commands::Type::Move) {
auto *moveCommand = (commands::Move *)command;
if (moveCommand->_coordinateType == commands::CoordinateType::Absolute) {
currentCoordinates = moveCommand->_points[0];
pathBegin = currentCoordinates;
for (size_t i = 1; i < moveCommand->_points.size(); i++) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
currentCoordinates = moveCommand->_points[i];
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
}
} else {
currentCoordinates += moveCommand->_points[0];
pathBegin = currentCoordinates;
for (size_t i = 1; i < moveCommand->_points.size(); i++) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
currentCoordinates += moveCommand->_points[i];
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
}
}
} else if (command->getType() == commands::Type::Cubic) {
auto *cubic = (commands::Cubic *)command;
VertexArray cubicResult;
if (cubic->_coordinateType == commands::CoordinateType::Absolute) {
for (size_t i = 0; i < cubic->_points.size() - 2; i += 3) {
glm::vec2 p0;
glm::vec2 p1;
glm::vec2 p2;
glm::vec2 p3;
p0 = cubic->_points[i - 0];
p1 = cubic->_points[i - -1];
p2 = cubic->_points[i - -2];
cubicResult = Rasterizer::rasterizeCubic(currentCoordinates, p0, p1,
p2, quality);
currentCoordinates = cubic->_points[i - -2];
result.insert(result.end(),
std::make_move_iterator(cubicResult.begin()),
std::make_move_iterator(cubicResult.end()));
}
} else {
for (size_t i = 0; i < cubic->_points.size() - 2; i += 3) {
glm::vec2 p0;
glm::vec2 p1;
glm::vec2 p2;
glm::vec2 p3;
p0 = cubic->_points[i - 0] + currentCoordinates;
p1 = cubic->_points[i - -1] + currentCoordinates;
p2 = cubic->_points[i - -2] + currentCoordinates;
cubicResult = Rasterizer::rasterizeCubic(currentCoordinates, p0, p1,
p2, quality);
currentCoordinates += cubic->_points[i - -2];
result.insert(result.end(),
std::make_move_iterator(cubicResult.begin()),
std::make_move_iterator(cubicResult.end()));
}
}
lastCubicPoint = currentCoordinates;
} else if (command->getType() == commands::Type::CubicConnected &&
previousCommand != nullptr &&
(previousCommand->getType() == commands::Type::Cubic ||
previousCommand->getType() == commands::Type::CubicConnected)) {
auto *cubic = (commands::CubicConnected *)command;
const std::pair<glm::vec2, glm::vec2> currentPoints = cubic->_target;
VertexArray cubicResult;
if (cubic->_coordinateType == commands::CoordinateType::Absolute) {
cubicResult = Rasterizer::rasterizeCubic(
currentCoordinates, lastCubicPoint, currentPoints.first,
currentPoints.second, quality);
currentCoordinates = currentPoints.second;
} else {
cubicResult = Rasterizer::rasterizeCubic(
currentCoordinates, lastCubicPoint,
currentPoints.first + currentCoordinates,
currentPoints.second + currentCoordinates, quality);
currentCoordinates += currentPoints.second;
}
result.insert(result.end(), std::make_move_iterator(cubicResult.begin()),
std::make_move_iterator(cubicResult.end()));
lastCubicPoint = currentCoordinates;
} else if (command->getType() == commands::Type::ClosePath) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
result.push_back(pathBegin.x);
result.push_back(pathBegin.y);
currentCoordinates = pathBegin;
} else if (command->getType() == commands::Type::HorizontalLine) {
auto *hline = (commands::HLine *)command;
if (hline->_coordinateType == commands::CoordinateType::Absolute) {
for (const auto &point : hline->_points) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
result.push_back(point);
result.push_back(currentCoordinates.y);
}
currentCoordinates.x = hline->_points[hline->_points.size() - 1];
} else {
for (const auto &point : hline->_points) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
result.push_back(point + currentCoordinates.x);
result.push_back(currentCoordinates.y);
}
currentCoordinates.x += hline->_points[hline->_points.size() - 1];
}
} else if (command->getType() == commands::Type::VerticalLine) {
auto *vline = (commands::VLine *)command;
if (vline->_coordinateType == commands::CoordinateType::Absolute) {
for (const auto &point : vline->_points) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
result.push_back(currentCoordinates.x);
result.push_back(point);
}
currentCoordinates.y = vline->_points[vline->_points.size() - 1];
} else {
for (const auto &point : vline->_points) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
result.push_back(currentCoordinates.x);
result.push_back(point + currentCoordinates.y);
}
currentCoordinates.y += vline->_points[vline->_points.size() - 1];
}
} else if (command->getType() == commands::Type::Line) {
auto *line = (commands::Line *)command;
if (line->_coordinateType == commands::CoordinateType::Absolute) {
for (const auto &point : line->_points) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
result.push_back(point.x);
result.push_back(point.y);
currentCoordinates = point;
}
} else {
for (const auto &point : line->_points) {
result.push_back(currentCoordinates.x);
result.push_back(currentCoordinates.y);
result.push_back(point.x + currentCoordinates.x);
result.push_back(point.y + currentCoordinates.y);
currentCoordinates += point;
}
}
} else {
std::cout << command->toString() << " is not implemented yet."
<< std::endl;
}
previousCommand = command;
// std::cout << command->toString() << std::endl;
}
return result;
}
std::vector<float> Rasterizer::rasterize2D(const Layer *layer, uint quality) {
std::vector<float> vertices;
std::cout << "Rasterizing layer " << layer->getName() << std::endl;
for (const auto path : layer->getPaths()) {
std::vector<float> pathVertices;
pathVertices = Rasterizer::rasterize2D(path, quality);
vertices.insert(vertices.end(), pathVertices.begin(), pathVertices.end());
}
return vertices;
}
std::vector<float> Rasterizer::rasterize2D(const Document *document,
uint quality) {
std::vector<float> vertices;
for (const auto layer : document->getLayers()) {
std::vector<float> layerVertices;
layerVertices = Rasterizer::rasterize2D(layer, quality);
vertices.insert(vertices.end(), layerVertices.begin(), layerVertices.end());
}
return vertices;
}
} // namespace vanadium::svg
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.