text
stringlengths 5
1.04M
|
|---|
/*
* Copyright (c) 2010-2012, 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* All rights reserved.
*
* 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 copyright holders 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.
*
* Authors: Kevin Lim
*/
#ifndef __CPU_O3_IEW_HH__
#define __CPU_O3_IEW_HH__
#include <queue>
#include <set>
#include "base/statistics.hh"
#include "cpu/o3/comm.hh"
#include "cpu/o3/lsq.hh"
#include "cpu/o3/scoreboard.hh"
#include "cpu/timebuf.hh"
#include "debug/IEW.hh"
#include "sim/probe/probe.hh"
struct DerivO3CPUParams;
class FUPool;
/**
* DefaultIEW handles both single threaded and SMT IEW
* (issue/execute/writeback). It handles the dispatching of
* instructions to the LSQ/IQ as part of the issue stage, and has the
* IQ try to issue instructions each cycle. The execute latency is
* actually tied into the issue latency to allow the IQ to be able to
* do back-to-back scheduling without having to speculatively schedule
* instructions. This happens by having the IQ have access to the
* functional units, and the IQ gets the execution latencies from the
* FUs when it issues instructions. Instructions reach the execute
* stage on the last cycle of their execution, which is when the IQ
* knows to wake up any dependent instructions, allowing back to back
* scheduling. The execute portion of IEW separates memory
* instructions from non-memory instructions, either telling the LSQ
* to execute the instruction, or executing the instruction directly.
* The writeback portion of IEW completes the instructions by waking
* up any dependents, and marking the register ready on the
* scoreboard.
*/
template<class Impl>
class DefaultIEW
{
private:
//Typedefs from Impl
typedef typename Impl::CPUPol CPUPol;
typedef typename Impl::DynInstPtr DynInstPtr;
typedef typename Impl::O3CPU O3CPU;
typedef typename CPUPol::IQ IQ;
typedef typename CPUPol::RenameMap RenameMap;
typedef typename CPUPol::LSQ LSQ;
typedef typename CPUPol::TimeStruct TimeStruct;
typedef typename CPUPol::IEWStruct IEWStruct;
typedef typename CPUPol::RenameStruct RenameStruct;
typedef typename CPUPol::IssueStruct IssueStruct;
public:
/** Overall IEW stage status. Used to determine if the CPU can
* deschedule itself due to a lack of activity.
*/
enum Status {
Active,
Inactive
};
/** Status for Issue, Execute, and Writeback stages. */
enum StageStatus {
Running,
Blocked,
Idle,
StartSquash,
Squashing,
Unblocking
};
private:
/** Overall stage status. */
Status _status;
/** Dispatch status. */
StageStatus dispatchStatus[Impl::MaxThreads];
/** Execute status. */
StageStatus exeStatus;
/** Writeback status. */
StageStatus wbStatus;
/** Probe points. */
ProbePointArg<DynInstPtr> *ppMispredict;
ProbePointArg<DynInstPtr> *ppDispatch;
/** To probe when instruction execution begins. */
ProbePointArg<DynInstPtr> *ppExecute;
/** To probe when instruction execution is complete. */
ProbePointArg<DynInstPtr> *ppToCommit;
//CleanupCache]
InstSeqNum headCommitSeqNum[Impl::MaxThreads];
public:
/** Constructs a DefaultIEW with the given parameters. */
DefaultIEW(O3CPU *_cpu, DerivO3CPUParams *params);
/** Returns the name of the DefaultIEW stage. */
std::string name() const;
/** Registers statistics. */
void regStats();
/** Registers probes. */
void regProbePoints();
/** Initializes stage; sends back the number of free IQ and LSQ entries. */
void startupStage();
/** Sets main time buffer used for backwards communication. */
void setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr);
/** Sets time buffer for getting instructions coming from rename. */
void setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr);
/** Sets time buffer to pass on instructions to commit. */
void setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr);
/** Sets pointer to list of active threads. */
void setActiveThreads(std::list<ThreadID> *at_ptr);
/** Sets pointer to the scoreboard. */
void setScoreboard(Scoreboard *sb_ptr);
/** Perform sanity checks after a drain. */
void drainSanityCheck() const;
/** Has the stage drained? */
bool isDrained() const;
/** Takes over from another CPU's thread. */
void takeOverFrom();
/** Squashes instructions in IEW for a specific thread. */
void squash(ThreadID tid);
/** Wakes all dependents of a completed instruction. */
void wakeDependents(DynInstPtr &inst);
/** Tells memory dependence unit that a memory instruction needs to be
* rescheduled. It will re-execute once replayMemInst() is called.
*/
void rescheduleMemInst(DynInstPtr &inst);
/** Re-executes all rescheduled memory instructions. */
void replayMemInst(DynInstPtr &inst);
/** Moves memory instruction onto the list of cache blocked instructions */
void blockMemInst(DynInstPtr &inst);
/** Notifies that the cache has become unblocked */
void cacheUnblocked();
/** Sends an instruction to commit through the time buffer. */
void instToCommit(DynInstPtr &inst);
/** Inserts unused instructions of a thread into the skid buffer. */
void skidInsert(ThreadID tid);
/** Returns the max of the number of entries in all of the skid buffers. */
int skidCount();
/** Returns if all of the skid buffers are empty. */
bool skidsEmpty();
/** Updates overall IEW status based on all of the stages' statuses. */
void updateStatus();
/** Resets entries of the IQ and the LSQ. */
void resetEntries();
/** Tells the CPU to wakeup if it has descheduled itself due to no
* activity. Used mainly by the LdWritebackEvent.
*/
void wakeCPU();
/** Reports to the CPU that there is activity this cycle. */
void activityThisCycle();
/** Tells CPU that the IEW stage is active and running. */
inline void activateStage();
/** Tells CPU that the IEW stage is inactive and idle. */
inline void deactivateStage();
/** Returns if the LSQ has any stores to writeback. */
bool hasStoresToWB() { return ldstQueue.hasStoresToWB(); }
/** Returns if the LSQ has any stores to writeback. */
bool hasStoresToWB(ThreadID tid) { return ldstQueue.hasStoresToWB(tid); }
/** Check misprediction */
void checkMisprediction(DynInstPtr &inst);
// [CleanupCache]
//TODO: Change this to local copy of HeadSeqNum
InstSeqNum getDoneSeqNumCommit(ThreadID tid) { return headCommitSeqNum[tid];}
private:
/** Sends commit proper information for a squash due to a branch
* mispredict.
*/
void squashDueToBranch(DynInstPtr &inst, ThreadID tid);
/** Sends commit proper information for a squash due to a memory order
* violation.
*/
void squashDueToMemOrder(DynInstPtr &inst, ThreadID tid);
/** Sets Dispatch to blocked, and signals back to other stages to block. */
void block(ThreadID tid);
/** Unblocks Dispatch if the skid buffer is empty, and signals back to
* other stages to unblock.
*/
void unblock(ThreadID tid);
/** Determines proper actions to take given Dispatch's status. */
void dispatch(ThreadID tid);
/** Dispatches instructions to IQ and LSQ. */
void dispatchInsts(ThreadID tid);
/** Executes instructions. In the case of memory operations, it informs the
* LSQ to execute the instructions. Also handles any redirects that occur
* due to the executed instructions.
*/
void executeInsts();
/** Writebacks instructions. In our model, the instruction's execute()
* function atomically reads registers, executes, and writes registers.
* Thus this writeback only wakes up dependent instructions, and informs
* the scoreboard of registers becoming ready.
*/
void writebackInsts();
/** Returns the number of valid, non-squashed instructions coming from
* rename to dispatch.
*/
unsigned validInstsFromRename();
/** Checks if any of the stall conditions are currently true. */
bool checkStall(ThreadID tid);
/** Processes inputs and changes state accordingly. */
void checkSignalsAndUpdate(ThreadID tid);
/** Removes instructions from rename from a thread's instruction list. */
void emptyRenameInsts(ThreadID tid);
/** Sorts instructions coming from rename into lists separated by thread. */
void sortInsts();
public:
/** Ticks IEW stage, causing Dispatch, the IQ, the LSQ, Execute, and
* Writeback to run for one cycle.
*/
void tick();
private:
/** Updates execution stats based on the instruction. */
void updateExeInstStats(DynInstPtr &inst);
/** Pointer to main time buffer used for backwards communication. */
TimeBuffer<TimeStruct> *timeBuffer;
/** Wire to write information heading to previous stages. */
typename TimeBuffer<TimeStruct>::wire toFetch;
/** Wire to get commit's output from backwards time buffer. */
typename TimeBuffer<TimeStruct>::wire fromCommit;
/** Wire to write information heading to previous stages. */
typename TimeBuffer<TimeStruct>::wire toRename;
/** Rename instruction queue interface. */
TimeBuffer<RenameStruct> *renameQueue;
/** Wire to get rename's output from rename queue. */
typename TimeBuffer<RenameStruct>::wire fromRename;
/** Issue stage queue. */
TimeBuffer<IssueStruct> issueToExecQueue;
/** Wire to read information from the issue stage time queue. */
typename TimeBuffer<IssueStruct>::wire fromIssue;
/**
* IEW stage time buffer. Holds ROB indices of instructions that
* can be marked as completed.
*/
TimeBuffer<IEWStruct> *iewQueue;
/** Wire to write infromation heading to commit. */
typename TimeBuffer<IEWStruct>::wire toCommit;
/** Queue of all instructions coming from rename this cycle. */
std::queue<DynInstPtr> insts[Impl::MaxThreads];
/** Skid buffer between rename and IEW. */
std::queue<DynInstPtr> skidBuffer[Impl::MaxThreads];
/** Scoreboard pointer. */
Scoreboard* scoreboard;
private:
/** CPU pointer. */
O3CPU *cpu;
/** Records if IEW has written to the time buffer this cycle, so that the
* CPU can deschedule itself if there is no activity.
*/
bool wroteToTimeBuffer;
/** Debug function to print instructions that are issued this cycle. */
void printAvailableInsts();
public:
/** Instruction queue. */
IQ instQueue;
/** Load / store queue. */
LSQ ldstQueue;
/** Pointer to the functional unit pool. */
FUPool *fuPool;
/** Records if the LSQ needs to be updated on the next cycle, so that
* IEW knows if there will be activity on the next cycle.
*/
bool updateLSQNextCycle;
private:
/** Records if there is a fetch redirect on this cycle for each thread. */
bool fetchRedirect[Impl::MaxThreads];
/** Records if the queues have been changed (inserted or issued insts),
* so that IEW knows to broadcast the updated amount of free entries.
*/
bool updatedQueues;
/** Commit to IEW delay. */
Cycles commitToIEWDelay;
/** Rename to IEW delay. */
Cycles renameToIEWDelay;
/**
* Issue to execute delay. What this actually represents is
* the amount of time it takes for an instruction to wake up, be
* scheduled, and sent to a FU for execution.
*/
Cycles issueToExecuteDelay;
/** Width of dispatch, in instructions. */
unsigned dispatchWidth;
/** Width of issue, in instructions. */
unsigned issueWidth;
/** Index into queue of instructions being written back. */
unsigned wbNumInst;
/** Cycle number within the queue of instructions being written back.
* Used in case there are too many instructions writing back at the current
* cycle and writesbacks need to be scheduled for the future. See comments
* in instToCommit().
*/
unsigned wbCycle;
/** Writeback width. */
unsigned wbWidth;
/** Number of active threads. */
ThreadID numThreads;
/** Pointer to list of active threads. */
std::list<ThreadID> *activeThreads;
/** Maximum size of the skid buffer. */
unsigned skidBufferMax;
/** Stat for total number of idle cycles. */
Stats::Scalar iewIdleCycles;
/** Stat for total number of squashing cycles. */
Stats::Scalar iewSquashCycles;
/** Stat for total number of blocking cycles. */
Stats::Scalar iewBlockCycles;
/** Stat for total number of unblocking cycles. */
Stats::Scalar iewUnblockCycles;
/** Stat for total number of instructions dispatched. */
Stats::Scalar iewDispatchedInsts;
/** Stat for total number of squashed instructions dispatch skips. */
Stats::Scalar iewDispSquashedInsts;
/** Stat for total number of dispatched load instructions. */
Stats::Scalar iewDispLoadInsts;
/** Stat for total number of dispatched store instructions. */
Stats::Scalar iewDispStoreInsts;
/** Stat for total number of dispatched non speculative instructions. */
Stats::Scalar iewDispNonSpecInsts;
/** Stat for number of times the IQ becomes full. */
Stats::Scalar iewIQFullEvents;
/** Stat for number of times the LSQ becomes full. */
Stats::Scalar iewLSQFullEvents;
/** Stat for total number of memory ordering violation events. */
Stats::Scalar memOrderViolationEvents;
/** Stat for total number of incorrect predicted taken branches. */
Stats::Scalar predictedTakenIncorrect;
/** Stat for total number of incorrect predicted not taken branches. */
Stats::Scalar predictedNotTakenIncorrect;
/** Stat for total number of mispredicted branches detected at execute. */
Stats::Formula branchMispredicts;
/** Stat for total number of executed instructions. */
Stats::Scalar iewExecutedInsts;
/** Stat for total number of executed load instructions. */
Stats::Vector iewExecLoadInsts;
/** Stat for total number of executed store instructions. */
// Stats::Scalar iewExecStoreInsts;
/** Stat for total number of squashed instructions skipped at execute. */
Stats::Scalar iewExecSquashedInsts;
/** Number of executed software prefetches. */
Stats::Vector iewExecutedSwp;
/** Number of executed nops. */
Stats::Vector iewExecutedNop;
/** Number of executed meomory references. */
Stats::Vector iewExecutedRefs;
/** Number of executed branches. */
Stats::Vector iewExecutedBranches;
/** Number of executed store instructions. */
Stats::Formula iewExecStoreInsts;
/** Number of instructions executed per cycle. */
Stats::Formula iewExecRate;
/** Number of instructions sent to commit. */
Stats::Vector iewInstsToCommit;
/** Number of instructions that writeback. */
Stats::Vector writebackCount;
/** Number of instructions that wake consumers. */
Stats::Vector producerInst;
/** Number of instructions that wake up from producers. */
Stats::Vector consumerInst;
/** Number of instructions per cycle written back. */
Stats::Formula wbRate;
/** Average number of woken instructions per writeback. */
Stats::Formula wbFanout;
};
#endif // __CPU_O3_IEW_HH__
|
/*
BIJOY
CSE-25th Batch
Shahjalal University of Science and Technology
*/
#include<bits/stdc++.h>
//#define pi 3.141592653589793238462643383
//#define pi 2*acos(0.0)
//#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c
#define p pair<int,int>
//#define ll long long int
//#define llu unsigned long long int
#define mx 1001
//#define mod 100000007
//const long long inf = 1e15;
/*----------------------Graph Moves------------------*/
//const int fx[]={+1,-1,+0,+0};
//const int fy[]={+0,+0,+1,-1};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};
//const int fx[]={-2,-2,-1,-1,+1,+1,+2,+2};
//const int fy[]={-1,+1,-2,+2,-2,+2,-1,+1};
/*---------------------------------------------------*/
/*-----------------------Bitmask---------------------*/
//int biton(int n,int pos){return n=n|(1<<pos);}
//int bitoff(int n,int pos){return n=n&~(1<<pos);}
//bool check(int n,int pos){return (bool)(n&(1<<pos));}
/*---------------------------------------------------*/
using namespace std;
vector<p >pp;
int main(){
// freopen("Input.txt","r",stdin);
// freopen("Output.txt","w",stdout);
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
int x,y;
scanf("%d %d",&x,&y);
pp.push_back(make_pair(x,y));
}
int ans=0;
for(int i=0;i<n;i++){
if(pp[i].first>ans) ans=pp[i].first;
else if(pp[i].first<=ans){
int h=pp[i].first+pp[i].second;
while(h<=ans){
h+=pp[i].second;
}
ans=h;
}
}
printf("%d\n",ans);
return 0;
}
|
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "OnBoardingLanguageWindow.hpp"
#include <common/options/OptionBellMenu.hpp>
namespace gui
{
OnBoardingLanguageWindow::OnBoardingLanguageWindow(
app::ApplicationCommon *app,
std::unique_ptr<app::OnBoarding::OnBoardingLanguageWindowPresenter::Presenter> &&presenter,
const std::string &name)
: BellOptionWindow(app, name), presenter{std::move(presenter)}
{
this->presenter->attach(this);
refreshOptions(languageOptionsList(), this->presenter->getSelectedLanguageIndex());
}
std::list<Option> OnBoardingLanguageWindow::languageOptionsList()
{
std::list<gui::Option> languageOptionList;
for (auto language : presenter->getLanguages()) {
languageOptionList.emplace_back(std::make_unique<gui::option::OptionBellMenu>(
language,
[=](gui::Item &item) {
presenter->setLanguage(language);
return true;
},
[=](gui::Item &item) {
if (item.focus) {
selectedLang = language;
}
return true;
},
this));
}
return languageOptionList;
}
std::string OnBoardingLanguageWindow::getSelectedLanguage()
{
return selectedLang;
}
} // namespace gui
|
//
// Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.
// Copyright (c) 2015-2017, University of Bremen
// All rights reserved.
//
// 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.
//
// 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.
//
#ifndef __VIZKIT_PATCHESGEODE_HPP__
#define __VIZKIT_PATCHESGEODE_HPP__
#include <osg/Geometry>
#include <osg/Geode>
#include <Eigen/Geometry>
#include <Eigen/StdVector>
#include <base-logging/Logging.hpp>
namespace vizkit3d {
class PatchesGeode : public osg::Geode
{
public:
PatchesGeode(float x_res, float y_res);
void setPosition(float x, float y)
{
xp = x; yp = y;
}
/** Draws a plane inside the box given by \c position and \c extends,
* using \c normal and \c mean (relative to the origin of the box)
* @deprecated please use drawPlane(plane, min, max, stdev)
*/
void drawPlane(
const float& z,
const float& height,
const osg::Vec3& mean,
const osg::Vec3& normal,
const float & stdev = 0.f);
/**
* Draws a plane inside the box given by \c min, \c max and the known
* grid resolution using \c plane (relative to the origin of the box).
* Note: \c plane must be defined in the cell center.
*/
void drawPlane(
const Eigen::Hyperplane<float, 3> & plane,
const float & min,
const float & max,
const float & stdev = 0.f);
/**
* Draws a plane inside the current cell at height \c z.
* The normal of this plane is always in the direction of the z-axis.
*/
void drawHorizontalPlane(
const float & z,
const float & stdev = 0.f);
/**
* Draws a box with between \c top and (\c top - \c height).
*/
void drawBox(
const float& top,
const float& height,
const osg::Vec3& c_normal,
const float & stdev = 0.f);
void setColor(const osg::Vec4& color);
void setColorHSVA(float hue, float sat, float lum, float alpha);
void showCycleColor(bool cycle_color);
void setCycleColorInterval(float cycle_color_interval);
void setUncertaintyScale(double uncertainty_scale);
void setShowPatchExtents(bool enable = true) { showPatchExtents = enable; };
void setShowNormals(bool enable = true) { showNormals = enable; };
void setShowUncertainty(bool enable = true) { showUncertainty = enable; }
void drawLines();
private:
osg::ref_ptr<osg::Vec3Array> vertices;
osg::ref_ptr<osg::Vec3Array> normals;
osg::ref_ptr<osg::Vec4Array> colors;
osg::ref_ptr<osg::Geometry> geom;
osg::ref_ptr<osg::Vec3Array> var_vertices;
size_t vertex_index;
float xp, yp; // position of current patch
float xs, ys; // grid resolution
float hue;
float sat;
float alpha;
float lum;
osg::Vec4 color;
bool showNormals;
bool showPatchExtents;
bool showUncertainty;
bool cycle_color;
float cycle_color_interval;
double uncertaintyScale;
void addVertex(const osg::Vec3& p, const osg::Vec3& n, const float & stdev = 0.f);
void updateColor();
void closePolygon();
void closeQuads();
};
}
#endif // __VIZKIT_PATCHESGEODE_HPP__
|
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2020 The BitcoinNickel Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoinnickel-config.h>
#endif
#include <clientversion.h>
#include <coins.h>
#include <consensus/consensus.h>
#include <core_io.h>
#include <key_io.h>
#include <keystore.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <univalue.h>
#include <util.h>
#include <utilmoneystr.h>
#include <utilstrencodings.h>
#include <memory>
#include <stdio.h>
#include <boost/algorithm/string.hpp>
static bool fCreateBlank;
static std::map<std::string,UniValue> registers;
static const int CONTINUE_EXECUTION=-1;
static void SetupBitcoinNickelTxArgs()
{
gArgs.AddArg("-?", "This help message", false, OptionsCategory::OPTIONS);
gArgs.AddArg("-create", "Create new, empty TX.", false, OptionsCategory::OPTIONS);
gArgs.AddArg("-json", "Select JSON output", false, OptionsCategory::OPTIONS);
gArgs.AddArg("-txid", "Output only the hex-encoded transaction id of the resultant transaction.", false, OptionsCategory::OPTIONS);
SetupChainParamsBaseOptions();
gArgs.AddArg("delin=N", "Delete input N from TX", false, OptionsCategory::COMMANDS);
gArgs.AddArg("delout=N", "Delete output N from TX", false, OptionsCategory::COMMANDS);
gArgs.AddArg("in=TXID:VOUT(:SEQUENCE_NUMBER)", "Add input to TX", false, OptionsCategory::COMMANDS);
gArgs.AddArg("locktime=N", "Set TX lock time to N", false, OptionsCategory::COMMANDS);
gArgs.AddArg("nversion=N", "Set TX version to N", false, OptionsCategory::COMMANDS);
gArgs.AddArg("outaddr=VALUE:ADDRESS", "Add address-based output to TX", false, OptionsCategory::COMMANDS);
gArgs.AddArg("outdata=[VALUE:]DATA", "Add data-based output to TX", false, OptionsCategory::COMMANDS);
gArgs.AddArg("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", "Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. "
"Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
"Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", false, OptionsCategory::COMMANDS);
gArgs.AddArg("outpubkey=VALUE:PUBKEY[:FLAGS]", "Add pay-to-pubkey output to TX. "
"Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. "
"Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", false, OptionsCategory::COMMANDS);
gArgs.AddArg("outscript=VALUE:SCRIPT[:FLAGS]", "Add raw script output to TX. "
"Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
"Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.", false, OptionsCategory::COMMANDS);
gArgs.AddArg("replaceable(=N)", "Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)", false, OptionsCategory::COMMANDS);
gArgs.AddArg("sign=SIGHASH-FLAGS", "Add zero or more signatures to transaction. "
"This command requires JSON registers:"
"prevtxs=JSON object, "
"privatekeys=JSON object. "
"See signrawtransaction docs for format of sighash flags, JSON objects.", false, OptionsCategory::COMMANDS);
gArgs.AddArg("load=NAME:FILENAME", "Load JSON file FILENAME into register NAME", false, OptionsCategory::REGISTER_COMMANDS);
gArgs.AddArg("set=NAME:JSON-STRING", "Set register NAME to given JSON-STRING", false, OptionsCategory::REGISTER_COMMANDS);
// Hidden
gArgs.AddArg("-h", "", false, OptionsCategory::HIDDEN);
gArgs.AddArg("-help", "", false, OptionsCategory::HIDDEN);
}
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRawTx(int argc, char* argv[])
{
//
// Parameters
//
SetupBitcoinNickelTxArgs();
std::string error;
if (!gArgs.ParseParameters(argc, argv, error)) {
fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(gArgs.GetChainName());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
fCreateBlank = gArgs.GetBoolArg("-create", false);
if (argc < 2 || HelpRequested(gArgs)) {
// First part of help message is specific to this utility
std::string strUsage = PACKAGE_NAME " bitcoinnickel-tx utility version " + FormatFullVersion() + "\n\n" +
"Usage: bitcoinnickel-tx [options] <hex-tx> [commands] Update hex-encoded bitcoinnickel transaction\n" +
"or: bitcoinnickel-tx [options] -create [commands] Create hex-encoded bitcoinnickel transaction\n" +
"\n";
strUsage += gArgs.GetHelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
return CONTINUE_EXECUTION;
}
static void RegisterSetJson(const std::string& key, const std::string& rawJson)
{
UniValue val;
if (!val.read(rawJson)) {
std::string strErr = "Cannot parse JSON for key " + key;
throw std::runtime_error(strErr);
}
registers[key] = val;
}
static void RegisterSet(const std::string& strInput)
{
// separate NAME:VALUE in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register input requires NAME:VALUE");
std::string key = strInput.substr(0, pos);
std::string valStr = strInput.substr(pos + 1, std::string::npos);
RegisterSetJson(key, valStr);
}
static void RegisterLoad(const std::string& strInput)
{
// separate NAME:FILENAME in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register load requires NAME:FILENAME");
std::string key = strInput.substr(0, pos);
std::string filename = strInput.substr(pos + 1, std::string::npos);
FILE *f = fopen(filename.c_str(), "r");
if (!f) {
std::string strErr = "Cannot open file " + filename;
throw std::runtime_error(strErr);
}
// load file chunks into one big buffer
std::string valStr;
while ((!feof(f)) && (!ferror(f))) {
char buf[4096];
int bread = fread(buf, 1, sizeof(buf), f);
if (bread <= 0)
break;
valStr.insert(valStr.size(), buf, bread);
}
int error = ferror(f);
fclose(f);
if (error) {
std::string strErr = "Error reading file " + filename;
throw std::runtime_error(strErr);
}
// evaluate as JSON buffer register
RegisterSetJson(key, valStr);
}
static CAmount ExtractAndValidateValue(const std::string& strValue)
{
CAmount value;
if (!ParseMoney(strValue, value))
throw std::runtime_error("invalid TX output value");
return value;
}
static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newVersion;
if (!ParseInt64(cmdVal, &newVersion) || newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)
throw std::runtime_error("Invalid TX version requested: '" + cmdVal + "'");
tx.nVersion = (int) newVersion;
}
static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newLocktime;
if (!ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL || newLocktime > 0xffffffffLL)
throw std::runtime_error("Invalid TX locktime requested: '" + cmdVal + "'");
tx.nLockTime = (unsigned int) newLocktime;
}
static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested index
int64_t inIdx;
if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.vin.size())) {
throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
}
// set the nSequence to MAX_INT - 2 (= RBF opt in flag)
int cnt = 0;
for (CTxIn& txin : tx.vin) {
if (strInIdx == "" || cnt == inIdx) {
if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
}
}
++cnt;
}
}
static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
{
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// separate TXID:VOUT in string
if (vStrInputParts.size()<2)
throw std::runtime_error("TX input missing separator");
// extract and validate TXID
std::string strTxid = vStrInputParts[0];
if ((strTxid.size() != 64) || !IsHex(strTxid))
throw std::runtime_error("invalid TX input txid");
uint256 txid(uint256S(strTxid));
static const unsigned int minTxOutSz = 9;
static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz);
// extract and validate vout
const std::string& strVout = vStrInputParts[1];
int64_t vout;
if (!ParseInt64(strVout, &vout) || vout < 0 || vout > static_cast<int64_t>(maxVout))
throw std::runtime_error("invalid TX input vout '" + strVout + "'");
// extract the optional sequence number
uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
if (vStrInputParts.size() > 2)
nSequenceIn = std::stoul(vStrInputParts[2]);
// append to transaction input list
CTxIn txin(txid, vout, CScript(), nSequenceIn);
tx.vin.push_back(txin);
}
static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:ADDRESS
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() != 2)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate ADDRESS
std::string strAddr = vStrInputParts[1];
CTxDestination destination = DecodeDestination(strAddr);
if (!IsValidDestination(destination)) {
throw std::runtime_error("invalid TX output address");
}
CScript scriptPubKey = GetScriptForDestination(destination);
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:PUBKEY[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract and validate PUBKEY
CPubKey pubkey(ParseHex(vStrInputParts[1]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
// Extract and validate FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts[2];
bSegWit = (flags.find('W') != std::string::npos);
bScriptHash = (flags.find('S') != std::string::npos);
}
if (bSegWit) {
if (!pubkey.IsCompressed()) {
throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
}
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
// Get the ID for the script, and then construct a P2SH destination for it.
scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// Check that there are enough parameters
if (vStrInputParts.size()<3)
throw std::runtime_error("Not enough multisig parameters");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract REQUIRED
uint32_t required = stoul(vStrInputParts[1]);
// Extract NUMKEYS
uint32_t numkeys = stoul(vStrInputParts[2]);
// Validate there are the correct number of pubkeys
if (vStrInputParts.size() < numkeys + 3)
throw std::runtime_error("incorrect number of multisig pubkeys");
if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
throw std::runtime_error("multisig parameter mismatch. Required " \
+ std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
// extract and validate PUBKEYs
std::vector<CPubKey> pubkeys;
for(int pos = 1; pos <= int(numkeys); pos++) {
CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
pubkeys.push_back(pubkey);
}
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == numkeys + 4) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find('W') != std::string::npos);
bScriptHash = (flags.find('S') != std::string::npos);
}
else if (vStrInputParts.size() > numkeys + 4) {
// Validate that there were no more parameters passed
throw std::runtime_error("Too many parameters");
}
CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
if (bSegWit) {
for (CPubKey& pubkey : pubkeys) {
if (!pubkey.IsCompressed()) {
throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
}
}
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
throw std::runtime_error(strprintf(
"redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
}
// Get the ID for the script, and then construct a P2SH destination for it.
scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
{
CAmount value = 0;
// separate [VALUE:]DATA in string
size_t pos = strInput.find(':');
if (pos==0)
throw std::runtime_error("TX output value not specified");
if (pos != std::string::npos) {
// Extract and validate VALUE
value = ExtractAndValidateValue(strInput.substr(0, pos));
}
// extract and validate DATA
std::string strData = strInput.substr(pos + 1, std::string::npos);
if (!IsHex(strData))
throw std::runtime_error("invalid TX output data");
std::vector<unsigned char> data = ParseHex(strData);
CTxOut txout(value, CScript() << OP_RETURN << data);
tx.vout.push_back(txout);
}
static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
{
// separate VALUE:SCRIPT[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2)
throw std::runtime_error("TX output missing separator");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate script
std::string strScript = vStrInputParts[1];
CScript scriptPubKey = ParseScript(strScript);
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find('W') != std::string::npos);
bScriptHash = (flags.find('S') != std::string::npos);
}
if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
throw std::runtime_error(strprintf(
"script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
}
if (bSegWit) {
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
throw std::runtime_error(strprintf(
"redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
}
scriptPubKey = GetScriptForDestination(CScriptID(scriptPubKey));
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested deletion index
int64_t inIdx;
if (!ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.vin.size())) {
throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
}
// delete input from transaction
tx.vin.erase(tx.vin.begin() + inIdx);
}
static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
{
// parse requested deletion index
int64_t outIdx;
if (!ParseInt64(strOutIdx, &outIdx) || outIdx < 0 || outIdx >= static_cast<int64_t>(tx.vout.size())) {
throw std::runtime_error("Invalid TX output index '" + strOutIdx + "'");
}
// delete output from transaction
tx.vout.erase(tx.vout.begin() + outIdx);
}
static const unsigned int N_SIGHASH_OPTS = 6;
static const struct {
const char *flagStr;
int flags;
} sighashOptions[N_SIGHASH_OPTS] = {
{"ALL", SIGHASH_ALL},
{"NONE", SIGHASH_NONE},
{"SINGLE", SIGHASH_SINGLE},
{"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
{"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
{"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
};
static bool findSighashFlags(int& flags, const std::string& flagStr)
{
flags = 0;
for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
if (flagStr == sighashOptions[i].flagStr) {
flags = sighashOptions[i].flags;
return true;
}
}
return false;
}
static CAmount AmountFromValue(const UniValue& value)
{
if (!value.isNum() && !value.isStr())
throw std::runtime_error("Amount is not a number or string");
CAmount amount;
if (!ParseFixedPoint(value.getValStr(), 8, &amount))
throw std::runtime_error("Invalid amount");
if (!MoneyRange(amount))
throw std::runtime_error("Amount out of range");
return amount;
}
static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
{
int nHashType = SIGHASH_ALL;
if (flagStr.size() > 0)
if (!findSighashFlags(nHashType, flagStr))
throw std::runtime_error("unknown sighash flag/sign option");
// mergedTx will end up with all the signatures; it
// starts as a clone of the raw tx:
CMutableTransaction mergedTx{tx};
const CMutableTransaction txv{tx};
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
if (!registers.count("privatekeys"))
throw std::runtime_error("privatekeys register variable must be set.");
CBasicKeyStore tempKeystore;
UniValue keysObj = registers["privatekeys"];
for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
if (!keysObj[kidx].isStr())
throw std::runtime_error("privatekey not a std::string");
CKey key = DecodeSecret(keysObj[kidx].getValStr());
if (!key.IsValid()) {
throw std::runtime_error("privatekey not valid");
}
tempKeystore.AddKey(key);
}
// Add previous txouts given in the RPC call:
if (!registers.count("prevtxs"))
throw std::runtime_error("prevtxs register variable must be set.");
UniValue prevtxsObj = registers["prevtxs"];
{
for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
UniValue prevOut = prevtxsObj[previdx];
if (!prevOut.isObject())
throw std::runtime_error("expected prevtxs internal object");
std::map<std::string, UniValue::VType> types = {
{"txid", UniValue::VSTR},
{"vout", UniValue::VNUM},
{"scriptPubKey", UniValue::VSTR},
};
if (!prevOut.checkObject(types))
throw std::runtime_error("prevtxs internal object typecheck fail");
uint256 txid = ParseHashStr(prevOut["txid"].get_str(), "txid");
const int nOut = prevOut["vout"].get_int();
if (nOut < 0)
throw std::runtime_error("vout must be positive");
COutPoint out(txid, nOut);
std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
const Coin& coin = view.AccessCoin(out);
if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw std::runtime_error(err);
}
Coin newcoin;
newcoin.out.scriptPubKey = scriptPubKey;
newcoin.out.nValue = 0;
if (prevOut.exists("amount")) {
newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
}
newcoin.nHeight = 1;
view.AddCoin(out, std::move(newcoin), true);
}
// if redeemScript given and private keys given,
// add redeemScript to the tempKeystore so it can be signed:
if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
prevOut.exists("redeemScript")) {
UniValue v = prevOut["redeemScript"];
std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
const CKeyStore& keystore = tempKeystore;
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
continue;
}
const CScript& prevPubKey = coin.out.scriptPubKey;
const CAmount& amount = coin.out.nValue;
SignatureData sigdata = DataFromTransaction(mergedTx, i, coin.out);
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
ProduceSignature(keystore, MutableTransactionSignatureCreator(&mergedTx, i, amount, nHashType), prevPubKey, sigdata);
UpdateInput(txin, sigdata);
}
tx = mergedTx;
}
class Secp256k1Init
{
ECCVerifyHandle globalVerifyHandle;
public:
Secp256k1Init() {
ECC_Start();
}
~Secp256k1Init() {
ECC_Stop();
}
};
static void MutateTx(CMutableTransaction& tx, const std::string& command,
const std::string& commandVal)
{
std::unique_ptr<Secp256k1Init> ecc;
if (command == "nversion")
MutateTxVersion(tx, commandVal);
else if (command == "locktime")
MutateTxLocktime(tx, commandVal);
else if (command == "replaceable") {
MutateTxRBFOptIn(tx, commandVal);
}
else if (command == "delin")
MutateTxDelInput(tx, commandVal);
else if (command == "in")
MutateTxAddInput(tx, commandVal);
else if (command == "delout")
MutateTxDelOutput(tx, commandVal);
else if (command == "outaddr")
MutateTxAddOutAddr(tx, commandVal);
else if (command == "outpubkey") {
ecc.reset(new Secp256k1Init());
MutateTxAddOutPubKey(tx, commandVal);
} else if (command == "outmultisig") {
ecc.reset(new Secp256k1Init());
MutateTxAddOutMultiSig(tx, commandVal);
} else if (command == "outscript")
MutateTxAddOutScript(tx, commandVal);
else if (command == "outdata")
MutateTxAddOutData(tx, commandVal);
else if (command == "sign") {
ecc.reset(new Secp256k1Init());
MutateTxSign(tx, commandVal);
}
else if (command == "load")
RegisterLoad(commandVal);
else if (command == "set")
RegisterSet(commandVal);
else
throw std::runtime_error("unknown command");
}
static void OutputTxJSON(const CTransaction& tx)
{
UniValue entry(UniValue::VOBJ);
TxToUniv(tx, uint256(), entry);
std::string jsonOutput = entry.write(4);
fprintf(stdout, "%s\n", jsonOutput.c_str());
}
static void OutputTxHash(const CTransaction& tx)
{
std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
fprintf(stdout, "%s\n", strHexHash.c_str());
}
static void OutputTxHex(const CTransaction& tx)
{
std::string strHex = EncodeHexTx(tx);
fprintf(stdout, "%s\n", strHex.c_str());
}
static void OutputTx(const CTransaction& tx)
{
if (gArgs.GetBoolArg("-json", false))
OutputTxJSON(tx);
else if (gArgs.GetBoolArg("-txid", false))
OutputTxHash(tx);
else
OutputTxHex(tx);
}
static std::string readStdin()
{
char buf[4096];
std::string ret;
while (!feof(stdin)) {
size_t bread = fread(buf, 1, sizeof(buf), stdin);
ret.append(buf, bread);
if (bread < sizeof(buf))
break;
}
if (ferror(stdin))
throw std::runtime_error("error reading stdin");
boost::algorithm::trim_right(ret);
return ret;
}
static int CommandLineRawTx(int argc, char* argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches; Permit common stdin convention "-"
while (argc > 1 && IsSwitchChar(argv[1][0]) &&
(argv[1][1] != 0)) {
argc--;
argv++;
}
CMutableTransaction tx;
int startArg;
if (!fCreateBlank) {
// require at least one param
if (argc < 2)
throw std::runtime_error("too few parameters");
// param: hex-encoded bitcoinnickel transaction
std::string strHexTx(argv[1]);
if (strHexTx == "-") // "-" implies standard input
strHexTx = readStdin();
if (!DecodeHexTx(tx, strHexTx, true))
throw std::runtime_error("invalid transaction encoding");
startArg = 2;
} else
startArg = 1;
for (int i = startArg; i < argc; i++) {
std::string arg = argv[i];
std::string key, value;
size_t eqpos = arg.find('=');
if (eqpos == std::string::npos)
key = arg;
else {
key = arg.substr(0, eqpos);
value = arg.substr(eqpos + 1);
}
MutateTx(tx, key, value);
}
OutputTx(tx);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRawTx()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try {
int ret = AppInitRawTx(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRawTx()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitRawTx()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRawTx(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRawTx()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRawTx()");
}
return ret;
}
|
#include <iostream>
#include <vector>
#include <cmath>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <tuple>
#include <list>
#include "astar.hpp"
#include "knightpath.hpp"
#include "tsp.hpp"
int main( int argc, char* argv[] )
{
clock_t start, end;
std::cout << "Nodes Expanded\tTime(ms)\tDepth" << std::endl;
// for( int i=0; i<10; ++i )
// {
// int x = rand() % 15;
// int y = rand() % 15;
//
// KnightPath kp( std::make_pair(0,0), std::make_pair(10,10) );
// AStar<KnightPath> astar( kp );
// start = clock();
// astar.solve();
// end = clock();
// int msecs = ((double)(end-start))*1000 / CLOCKS_PER_SEC;
// std::cout << astar.expandedNodes << "\t" << msecs << "\t" << astar.solutionDepth << std::endl;
// }
for( int i=3; i<11; ++i )
{
TSP tsp(i);
AStar<TSP> astar( tsp );
start = clock();
astar.solve();
end = clock();
int msecs = ((double)(end-start))*1000 / CLOCKS_PER_SEC;
std::cout << astar.expandedNodes << "\t" << msecs << "\t" << astar.solutionDepth << std::endl;
}
return 0;
}
|
// 38 Count and Say
// https://leetcode.com/problems/count-and-say
// version: 1; create time: 2020-02-01 20:50:22;
class Solution {
public:
string countAndSay(int n) {
string cur = "1";
if (n == 1) return cur;
for (int i = 2; i <= n; ++i) {
string nex;
const int m = cur.size();
int j = 0;
while (j < m) {
int s = j;
while (j + 1 < m && cur[j] == cur[j+1]) ++j;
nex += std::to_string(j - s + 1) + cur[j];
++j;
}
cur = std::move(nex);
}
return cur;
}
};
|
/**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "wrapper_callback.h"
#include "engine/cmd.h"
#include "engine/cmd.gen.h"
#include "engine/cmd_specific.gen.h"
#include "cmd_specific.gen.h"
#include "ai.h"
typedef FlagTrainedAI TrainAIType;
static AI *get_ai(const AIOptions &opt, Context::AIComm *ai_comm) {
// std::cout << "AI type = " << ai_type << " Backup AI type = " << backup_ai_type << std::endl;
if (opt.type == "AI_FLAG_SIMPLE") return new FlagSimpleAI(opt, nullptr);
else if (opt.type == "AI_FLAG_NN") return new TrainAIType(opt, nullptr, ai_comm);
else return nullptr;
}
void WrapperCallbacks::initialize_ai_comm(Context::AIComm &ai_comm) {
auto &hstate = ai_comm.info().data;
hstate.InitHist(_context_options.T);
for (auto &item : hstate.v()) {
item.Init(_game_idx, GameDef::GetNumAction());
}
}
void WrapperCallbacks::OnGameOptions(RTSGameOptions *rts_options) {
rts_options->handicap_level = _options.handicap_level;
}
void WrapperCallbacks::OnGameInit(RTSGame *game, const std::map<std::string, int> *more_params) {
// std::cout << "Initialize opponent" << std::endl;
std::vector<AI *> ais;
for (const AIOptions &ai_opt : _options.ai_options) {
Context::AIComm *ai_comm = new Context::AIComm(_game_idx, _comm);
_ai_comms.emplace_back(ai_comm);
initialize_ai_comm(*ai_comm);
ais.push_back(get_ai(ai_opt, ai_comm));
}
// std::cout << "Initialize ai" << std::endl;
// Used to pick the AI to change the parameters.
_ai = ais[0];
// Shuffle the bot.
if (_options.shuffle_player) {
std::mt19937 g(_game_idx);
std::shuffle(ais.begin(), ais.end(), g);
}
for (AI *ai : ais) game->AddBot(ai);
}
void WrapperCallbacks::OnEpisodeStart(int k, std::mt19937 *rng, RTSGame*) {
(void)k;
(void)rng;
}
|
// 4.16.1 0xbf1ff521 D2 AY R0 FARGB8888 U565 N0 SExtFlashSection
// Generated by imageconverter. Please, do not edit!
#include <touchgfx/hal/Config.hpp>
LOCATION_PRAGMA("ExtFlashSection")
KEEP extern const unsigned char image_blue_icons_next_arrow_32[] LOCATION_ATTRIBUTE("ExtFlashSection") = // 17x30 ARGB8888 pixels.
{
0x48, 0x44, 0x48, 0xd3, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xf3, 0x48, 0x48, 0x48, 0x41,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0xcb,
0x48, 0x48, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0xef, 0x48, 0x44, 0x48, 0x2c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x38, 0x40, 0x48, 0x40, 0xfb,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xe3, 0x48, 0x48, 0x48, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x86, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xc7, 0x48, 0x44, 0x48, 0x08,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x48, 0x48, 0x04, 0x40, 0x44, 0x40, 0xd3, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x44, 0x40, 0xb2, 0x48, 0x48, 0x48, 0x04,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x48, 0x48, 0x30, 0x40, 0x44, 0x40, 0xf7, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0x96, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x48, 0x48, 0x7d, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0x71, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x04,
0x48, 0x48, 0x48, 0xc7, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x48, 0x48, 0xfb, 0x48, 0x44, 0x48, 0x4d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x44, 0x40, 0x28,
0x48, 0x48, 0x48, 0xf7, 0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0xf7, 0x48, 0x48, 0x48, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x71,
0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xeb, 0x40, 0x44, 0x40, 0x24, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x48, 0x48, 0x00, 0x40, 0x48, 0x40, 0xbe,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x48, 0x48, 0xdb, 0x48, 0x48, 0x48, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x20, 0x48, 0x48, 0x48, 0xf3,
0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xbe, 0x48, 0x44, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x65, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xa2, 0x40, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x44, 0x40, 0x00, 0x48, 0x48, 0x48, 0xb6, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0x6d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x44, 0x40, 0x18, 0x48, 0x48, 0x48, 0xef, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xe7,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x48, 0x48, 0x1c,
0x48, 0x44, 0x48, 0xef, 0x40, 0x48, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff,
0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xe7, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x44, 0x48, 0x00, 0x48, 0x48, 0x48, 0xb6, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0x6d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x48, 0x48, 0x65,
0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0xa2, 0x48, 0x48, 0x48, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x44, 0x48, 0x20, 0x40, 0x48, 0x40, 0xf3, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xbe,
0x48, 0x44, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x00, 0x48, 0x48, 0x48, 0xc3,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff,
0x40, 0x48, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff,
0x40, 0x48, 0x40, 0xd7, 0x48, 0x48, 0x48, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x44, 0x48, 0x71, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xeb, 0x48, 0x44, 0x48, 0x24,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x28, 0x48, 0x48, 0x48, 0xf7,
0x40, 0x44, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xf3,
0x40, 0x44, 0x40, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x04,
0x48, 0x48, 0x48, 0xc7, 0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff,
0x48, 0x48, 0x48, 0xfb, 0x48, 0x48, 0x48, 0x4d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x7d, 0x48, 0x48, 0x48, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x48, 0x40, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x40, 0x48, 0x40, 0x71,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x30,
0x40, 0x48, 0x40, 0xf7, 0x48, 0x44, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff,
0x40, 0x48, 0x40, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x40, 0x48, 0x40, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x44, 0x48, 0x08, 0x48, 0x48, 0x48, 0xd3, 0x40, 0x48, 0x40, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xb2, 0x48, 0x44, 0x48, 0x04,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0x86,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xc7,
0x40, 0x44, 0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x48, 0x44, 0x48, 0x38, 0x40, 0x48, 0x40, 0xfb, 0x48, 0x44, 0x48, 0xff,
0x40, 0x44, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff, 0x40, 0x44, 0x40, 0xff,
0x48, 0x48, 0x48, 0xe3, 0x48, 0x48, 0x48, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x48, 0x48, 0xcf,
0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xff, 0x48, 0x48, 0x48, 0xff,
0x40, 0x44, 0x40, 0xff, 0x48, 0x44, 0x48, 0xef, 0x48, 0x48, 0x48, 0x2c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x48, 0x44, 0x48, 0xd3, 0x48, 0x44, 0x48, 0xff,
0x40, 0x48, 0x40, 0xff, 0x48, 0x48, 0x48, 0xff, 0x48, 0x44, 0x48, 0xf3,
0x48, 0x48, 0x48, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
|
#include "city.h"
CITY::CITY()
{
}
void CITY::Init(INTPOINT _size)
{
m_size = _size;
m_objects.clear();
for(int y=0;y<m_size.y;y++)
for(int x=0;x<m_size.x;x++)
{
//Add tile
m_objects.push_back(OBJECT(TILE, D3DXVECTOR3(x * TILE_SIZE, 0.0f, y * -TILE_SIZE), D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(1.0f, 1.0f, 1.0f)));
//Add house
float sca_xz = rand()%100 / 1000.0f - 0.05f;
float sca_y = rand()%500 / 1000.0f - 0.25f;
int rotation = rand()%4;
int house = rand()%2 + 1;
if(x % 3 == 0 && y % 3 == 0)house = PARK;
m_objects.push_back(OBJECT(house, D3DXVECTOR3(x * TILE_SIZE, 0.0f, y * -TILE_SIZE),
D3DXVECTOR3(0.0f, (D3DX_PI / 2.0f) * rotation, 0.0f),
D3DXVECTOR3(1.0f + sca_xz, 1.0f + sca_y, 1.0f + sca_xz)));
}
}
void CITY::Render(CAMERA *cam)
{
for(int i=0;i<(int)m_objects.size();i++)
{
if(cam == NULL)
{
if(m_objects[i].m_rendered)
m_objects[i].Render();
}
//else if(cam->Cull(m_objects[i].m_bBox)) //Box culling
else if(cam->Cull(m_objects[i].m_bSphere)) //Sphere culling
{
m_objects[i].m_rendered = false;
}
else
{
m_objects[i].Render();
m_objects[i].m_rendered = true;
}
}
}
D3DXVECTOR3 CITY::GetCenter()
{
return D3DXVECTOR3(m_size.x / 2.0f * TILE_SIZE, 0.0f, m_size.y / 2.0f * -TILE_SIZE);
}
|
/**************************************************************************************
Copyright 2015 Applied Research Associates, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the License
at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
**************************************************************************************/
#include <biogears/cdm/properties/SEScalar0To1.h>
#include <biogears/cdm/properties/SEScalarAmountPerVolume.h>
#include <biogears/cdm/properties/SEScalarElectricPotential.h>
#include <biogears/cdm/properties/SEScalarFraction.h>
#include <biogears/cdm/properties/SEScalarMass.h>
#include <biogears/cdm/properties/SEScalarMassPerVolume.h>
#include <biogears/cdm/properties/SEScalarVolume.h>
#include <biogears/cdm/properties/SEScalarVolumePerTime.h>
#include <biogears/cdm/stdafx.h>
#include <biogears/cdm/substance/SESubstanceManager.h>
#include <biogears/cdm/system/physiology/SETissueSystem.h>
#include <biogears/schema/ScalarAmountPerVolumeData.hxx>
#include <biogears/schema/ScalarElectricPotentialData.hxx>
#include <biogears/schema/ScalarFractionData.hxx>
#include <biogears/schema/ScalarMassData.hxx>
#include <biogears/schema/ScalarMassPerVolumeData.hxx>
#include <biogears/schema/ScalarVolumeData.hxx>
#include <biogears/schema/ScalarVolumePerTimeData.hxx>
SETissueSystem::SETissueSystem(Logger* logger)
: SESystem(logger)
{
m_CarbonDioxideProductionRate = nullptr;
m_DehydrationFraction = nullptr;
m_ExtracellularFluidVolume = nullptr;
m_ExtravascularFluidVolume = nullptr;
m_IntracellularFluidVolume = nullptr;
m_TotalBodyFluidVolume = nullptr;
m_IntracellularFluidPH = nullptr;
m_OxygenConsumptionRate = nullptr;
m_RespiratoryExchangeRatio = nullptr;
m_LiverInsulinSetPoint = nullptr;
m_LiverGlucagonSetPoint = nullptr;
m_MuscleInsulinSetPoint = nullptr;
m_MuscleGlucagonSetPoint = nullptr;
m_FatInsulinSetPoint = nullptr;
m_FatGlucagonSetPoint = nullptr;
m_LiverGlycogen = nullptr;
m_MuscleGlycogen = nullptr;
m_StoredProtein = nullptr;
m_StoredFat = nullptr;
}
SETissueSystem::~SETissueSystem()
{
Clear();
}
void SETissueSystem::Clear()
{
SAFE_DELETE(m_CarbonDioxideProductionRate);
SAFE_DELETE(m_DehydrationFraction);
SAFE_DELETE(m_ExtracellularFluidVolume);
SAFE_DELETE(m_ExtravascularFluidVolume);
SAFE_DELETE(m_IntracellularFluidVolume);
SAFE_DELETE(m_TotalBodyFluidVolume);
SAFE_DELETE(m_IntracellularFluidPH);
SAFE_DELETE(m_OxygenConsumptionRate);
SAFE_DELETE(m_RespiratoryExchangeRatio);
SAFE_DELETE(m_LiverInsulinSetPoint);
SAFE_DELETE(m_LiverGlucagonSetPoint);
SAFE_DELETE(m_MuscleInsulinSetPoint);
SAFE_DELETE(m_MuscleGlucagonSetPoint);
SAFE_DELETE(m_FatInsulinSetPoint);
SAFE_DELETE(m_FatGlucagonSetPoint);
SAFE_DELETE(m_LiverGlycogen);
SAFE_DELETE(m_MuscleGlycogen);
SAFE_DELETE(m_StoredProtein);
SAFE_DELETE(m_StoredFat);
}
const SEScalar* SETissueSystem::GetScalar(const std::string& name)
{
if (name.compare("CarbonDioxideProductionRate") == 0)
return &GetCarbonDioxideProductionRate();
if (name.compare("DehydrationFraction") == 0)
return &GetDehydrationFraction();
if (name.compare("ExtracellularFluidVolume") == 0)
return &GetExtracellularFluidVolume();
if (name.compare("ExtravascularFluidVolume") == 0)
return &GetExtravascularFluidVolume();
if (name.compare("IntracellularFluidPH") == 0)
return &GetIntracellularFluidPH();
if (name.compare("IntracellularFluidVolume") == 0)
return &GetIntracellularFluidVolume();
if (name.compare("TotalBodyFluidVolume") == 0)
return &GetTotalBodyFluidVolume();
if (name.compare("OxygenConsumptionRate") == 0)
return &GetOxygenConsumptionRate();
if (name.compare("RespiratoryExchangeRatio") == 0)
return &GetRespiratoryExchangeRatio();
if (name.compare("LiverInsulinSetPoint") == 0)
return &GetLiverInsulinSetPoint();
if (name.compare("LiverGlucagonSetPoint") == 0)
return &GetLiverGlucagonSetPoint();
if (name.compare("MuscleInsulinSetPoint") == 0)
return &GetMuscleInsulinSetPoint();
if (name.compare("MuscleGlucagonSetPoint") == 0)
return &GetMuscleGlucagonSetPoint();
if (name.compare("FatInsulinSetPoint") == 0)
return &GetFatInsulinSetPoint();
if (name.compare("FatGlucagonSetPoint") == 0)
return &GetFatGlucagonSetPoint();
if (name.compare("LiverGlycogen") == 0)
return &GetLiverGlycogen();
if (name.compare("MuscleGlycogen") == 0)
return &GetMuscleGlycogen();
if (name.compare("StoredProtein") == 0)
return &GetStoredProtein();
if (name.compare("StoredFat") == 0)
return &GetStoredFat();
return nullptr;
}
bool SETissueSystem::Load(const CDM::TissueSystemData& in)
{
SESystem::Load(in);
if (in.CarbonDioxideProductionRate().present())
GetCarbonDioxideProductionRate().Load(in.CarbonDioxideProductionRate().get());
if (in.DehydrationFraction().present())
GetDehydrationFraction().Load(in.DehydrationFraction().get());
if (in.ExtracellularFluidVolume().present())
GetExtracellularFluidVolume().Load(in.ExtracellularFluidVolume().get());
if (in.ExtravascularFluidVolume().present())
GetExtravascularFluidVolume().Load(in.ExtravascularFluidVolume().get());
if (in.IntracellularFluidPH().present())
GetIntracellularFluidPH().Load(in.IntracellularFluidPH().get());
if (in.IntracellularFluidVolume().present())
GetIntracellularFluidVolume().Load(in.IntracellularFluidVolume().get());
if (in.TotalBodyFluidVolume().present())
GetTotalBodyFluidVolume().Load(in.TotalBodyFluidVolume().get());
if (in.OxygenConsumptionRate().present())
GetOxygenConsumptionRate().Load(in.OxygenConsumptionRate().get());
if (in.RespiratoryExchangeRatio().present())
GetRespiratoryExchangeRatio().Load(in.RespiratoryExchangeRatio().get());
if (in.LiverInsulinSetPoint().present())
GetLiverInsulinSetPoint().Load(in.LiverInsulinSetPoint().get());
if (in.LiverGlucagonSetPoint().present())
GetLiverGlucagonSetPoint().Load(in.LiverGlucagonSetPoint().get());
if (in.MuscleInsulinSetPoint().present())
GetMuscleInsulinSetPoint().Load(in.MuscleInsulinSetPoint().get());
if (in.MuscleGlucagonSetPoint().present())
GetMuscleGlucagonSetPoint().Load(in.MuscleGlucagonSetPoint().get());
if (in.FatInsulinSetPoint().present())
GetFatInsulinSetPoint().Load(in.FatInsulinSetPoint().get());
if (in.FatGlucagonSetPoint().present())
GetFatGlucagonSetPoint().Load(in.FatGlucagonSetPoint().get());
if (in.LiverGlycogen().present())
GetLiverGlycogen().Load(in.LiverGlycogen().get());
if (in.MuscleGlycogen().present())
GetMuscleGlycogen().Load(in.MuscleGlycogen().get());
if (in.StoredProtein().present())
GetStoredProtein().Load(in.StoredProtein().get());
if (in.StoredFat().present())
GetStoredFat().Load(in.StoredFat().get());
return true;
}
CDM::TissueSystemData* SETissueSystem::Unload() const
{
CDM::TissueSystemData* data = new CDM::TissueSystemData();
Unload(*data);
return data;
}
void SETissueSystem::Unload(CDM::TissueSystemData& data) const
{
if (m_CarbonDioxideProductionRate != nullptr)
data.CarbonDioxideProductionRate(std::unique_ptr<CDM::ScalarVolumePerTimeData>(m_CarbonDioxideProductionRate->Unload()));
if (m_DehydrationFraction != nullptr)
data.DehydrationFraction(std::unique_ptr<CDM::Scalar0To1Data>(m_DehydrationFraction->Unload()));
if (m_ExtracellularFluidVolume != nullptr)
data.ExtracellularFluidVolume(std::unique_ptr<CDM::ScalarVolumeData>(m_ExtracellularFluidVolume->Unload()));
if (m_ExtravascularFluidVolume != nullptr)
data.ExtravascularFluidVolume(std::unique_ptr<CDM::ScalarVolumeData>(m_ExtravascularFluidVolume->Unload()));
if (m_IntracellularFluidPH != nullptr)
data.IntracellularFluidPH(std::unique_ptr<CDM::ScalarData>(m_IntracellularFluidPH->Unload()));
if (m_IntracellularFluidVolume != nullptr)
data.IntracellularFluidVolume(std::unique_ptr<CDM::ScalarVolumeData>(m_IntracellularFluidVolume->Unload()));
if (m_TotalBodyFluidVolume != nullptr)
data.TotalBodyFluidVolume(std::unique_ptr<CDM::ScalarVolumeData>(m_TotalBodyFluidVolume->Unload()));
if (m_OxygenConsumptionRate != nullptr)
data.OxygenConsumptionRate(std::unique_ptr<CDM::ScalarVolumePerTimeData>(m_OxygenConsumptionRate->Unload()));
if (m_RespiratoryExchangeRatio != nullptr)
data.RespiratoryExchangeRatio(std::unique_ptr<CDM::ScalarData>(m_RespiratoryExchangeRatio->Unload()));
if (m_LiverInsulinSetPoint != nullptr)
data.LiverInsulinSetPoint(std::unique_ptr<CDM::ScalarAmountPerVolumeData>(m_LiverInsulinSetPoint->Unload()));
if (m_LiverGlucagonSetPoint != nullptr)
data.LiverGlucagonSetPoint(std::unique_ptr<CDM::ScalarMassPerVolumeData>(m_LiverGlucagonSetPoint->Unload()));
if (m_MuscleInsulinSetPoint != nullptr)
data.MuscleInsulinSetPoint(std::unique_ptr<CDM::ScalarAmountPerVolumeData>(m_MuscleInsulinSetPoint->Unload()));
if (m_MuscleGlucagonSetPoint != nullptr)
data.MuscleGlucagonSetPoint(std::unique_ptr<CDM::ScalarMassPerVolumeData>(m_MuscleGlucagonSetPoint->Unload()));
if (m_FatInsulinSetPoint != nullptr)
data.FatInsulinSetPoint(std::unique_ptr<CDM::ScalarAmountPerVolumeData>(m_FatInsulinSetPoint->Unload()));
if (m_FatGlucagonSetPoint != nullptr)
data.FatGlucagonSetPoint(std::unique_ptr<CDM::ScalarMassPerVolumeData>(m_FatGlucagonSetPoint->Unload()));
if (m_LiverGlycogen != nullptr)
data.LiverGlycogen(std::unique_ptr<CDM::ScalarMassData>(m_LiverGlycogen->Unload()));
if (m_MuscleGlycogen != nullptr)
data.MuscleGlycogen(std::unique_ptr<CDM::ScalarMassData>(m_MuscleGlycogen->Unload()));
if (m_StoredProtein != nullptr)
data.StoredProtein(std::unique_ptr<CDM::ScalarMassData>(m_StoredProtein->Unload()));
if (m_StoredFat != nullptr)
data.StoredFat(std::unique_ptr<CDM::ScalarMassData>(m_StoredFat->Unload()));
SESystem::Unload(data);
}
bool SETissueSystem::HasCarbonDioxideProductionRate() const
{
return m_CarbonDioxideProductionRate == nullptr ? false : m_CarbonDioxideProductionRate->IsValid();
}
SEScalarVolumePerTime& SETissueSystem::GetCarbonDioxideProductionRate()
{
if (m_CarbonDioxideProductionRate == nullptr)
m_CarbonDioxideProductionRate = new SEScalarVolumePerTime();
return *m_CarbonDioxideProductionRate;
}
double SETissueSystem::GetCarbonDioxideProductionRate(const VolumePerTimeUnit& unit) const
{
if (m_CarbonDioxideProductionRate == nullptr)
return SEScalar::dNaN();
return m_CarbonDioxideProductionRate->GetValue(unit);
}
bool SETissueSystem::HasDehydrationFraction() const
{
return m_DehydrationFraction == nullptr ? false : m_DehydrationFraction->IsValid();
}
SEScalar0To1& SETissueSystem::GetDehydrationFraction()
{
if (m_DehydrationFraction == nullptr)
m_DehydrationFraction = new SEScalar0To1();
return *m_DehydrationFraction;
}
double SETissueSystem::GetDehydrationFraction() const
{
if (m_DehydrationFraction == nullptr)
return SEScalar::dNaN();
return m_DehydrationFraction->GetValue();
}
bool SETissueSystem::HasExtracellularFluidVolume() const
{
return m_ExtracellularFluidVolume == nullptr ? false : m_ExtracellularFluidVolume->IsValid();
}
SEScalarVolume& SETissueSystem::GetExtracellularFluidVolume()
{
if (m_ExtracellularFluidVolume == nullptr)
m_ExtracellularFluidVolume = new SEScalarVolume();
return *m_ExtracellularFluidVolume;
}
double SETissueSystem::GetExtracellularFluidVolume(const VolumeUnit& unit) const
{
if (m_ExtracellularFluidVolume == nullptr)
return SEScalar::dNaN();
return m_ExtracellularFluidVolume->GetValue(unit);
}
bool SETissueSystem::HasExtravascularFluidVolume() const
{
return m_ExtravascularFluidVolume == nullptr ? false : m_ExtravascularFluidVolume->IsValid();
}
SEScalarVolume& SETissueSystem::GetExtravascularFluidVolume()
{
if (m_ExtravascularFluidVolume == nullptr)
m_ExtravascularFluidVolume = new SEScalarVolume();
return *m_ExtravascularFluidVolume;
}
double SETissueSystem::GetExtravascularFluidVolume(const VolumeUnit& unit) const
{
if (m_ExtravascularFluidVolume == nullptr)
return SEScalar::dNaN();
return m_ExtravascularFluidVolume->GetValue(unit);
}
bool SETissueSystem::HasIntracellularFluidVolume() const
{
return m_IntracellularFluidVolume == nullptr ? false : m_IntracellularFluidVolume->IsValid();
}
SEScalarVolume& SETissueSystem::GetIntracellularFluidVolume()
{
if (m_IntracellularFluidVolume == nullptr)
m_IntracellularFluidVolume = new SEScalarVolume();
return *m_IntracellularFluidVolume;
}
double SETissueSystem::GetIntracellularFluidVolume(const VolumeUnit& unit) const
{
if (m_IntracellularFluidVolume == nullptr)
return SEScalar::dNaN();
return m_IntracellularFluidVolume->GetValue(unit);
}
bool SETissueSystem::HasTotalBodyFluidVolume() const
{
return m_TotalBodyFluidVolume == nullptr ? false : m_TotalBodyFluidVolume->IsValid();
}
SEScalarVolume& SETissueSystem::GetTotalBodyFluidVolume()
{
if (m_TotalBodyFluidVolume == nullptr)
m_TotalBodyFluidVolume = new SEScalarVolume();
return *m_TotalBodyFluidVolume;
}
double SETissueSystem::GetTotalBodyFluidVolume(const VolumeUnit& unit) const
{
if (m_TotalBodyFluidVolume == nullptr)
return SEScalar::dNaN();
return m_TotalBodyFluidVolume->GetValue(unit);
}
bool SETissueSystem::HasIntracellularFluidPH() const
{
return m_IntracellularFluidPH == nullptr ? false : m_IntracellularFluidPH->IsValid();
}
SEScalar& SETissueSystem::GetIntracellularFluidPH()
{
if (m_IntracellularFluidPH == nullptr)
m_IntracellularFluidPH = new SEScalar();
return *m_IntracellularFluidPH;
}
double SETissueSystem::GetIntracellularFluidPH() const
{
if (m_IntracellularFluidPH == nullptr)
return SEScalar::dNaN();
return m_IntracellularFluidPH->GetValue();
}
bool SETissueSystem::HasOxygenConsumptionRate() const
{
return m_OxygenConsumptionRate == nullptr ? false : m_OxygenConsumptionRate->IsValid();
}
SEScalarVolumePerTime& SETissueSystem::GetOxygenConsumptionRate()
{
if (m_OxygenConsumptionRate == nullptr)
m_OxygenConsumptionRate = new SEScalarVolumePerTime();
return *m_OxygenConsumptionRate;
}
double SETissueSystem::GetOxygenConsumptionRate(const VolumePerTimeUnit& unit) const
{
if (m_OxygenConsumptionRate == nullptr)
return SEScalar::dNaN();
return m_OxygenConsumptionRate->GetValue(unit);
}
bool SETissueSystem::HasRespiratoryExchangeRatio() const
{
return m_RespiratoryExchangeRatio == nullptr ? false : m_RespiratoryExchangeRatio->IsValid();
}
SEScalar& SETissueSystem::GetRespiratoryExchangeRatio()
{
if (m_RespiratoryExchangeRatio == nullptr)
m_RespiratoryExchangeRatio = new SEScalar();
return *m_RespiratoryExchangeRatio;
}
double SETissueSystem::GetRespiratoryExchangeRatio() const
{
if (m_RespiratoryExchangeRatio == nullptr)
return SEScalar::dNaN();
return m_RespiratoryExchangeRatio->GetValue();
}
bool SETissueSystem::HasLiverInsulinSetPoint() const
{
return m_LiverInsulinSetPoint == nullptr ? false : m_LiverInsulinSetPoint->IsValid();
}
SEScalarAmountPerVolume& SETissueSystem::GetLiverInsulinSetPoint()
{
if (m_LiverInsulinSetPoint == nullptr)
m_LiverInsulinSetPoint = new SEScalarAmountPerVolume();
return *m_LiverInsulinSetPoint;
}
double SETissueSystem::GetLiverInsulinSetPoint(const AmountPerVolumeUnit& unit) const
{
if (m_LiverInsulinSetPoint == nullptr)
return SEScalar::dNaN();
return m_LiverInsulinSetPoint->GetValue(unit);
}
bool SETissueSystem::HasLiverGlucagonSetPoint() const
{
return m_LiverGlucagonSetPoint == nullptr ? false : m_LiverGlucagonSetPoint->IsValid();
}
SEScalarMassPerVolume& SETissueSystem::GetLiverGlucagonSetPoint()
{
if (m_LiverGlucagonSetPoint == nullptr)
m_LiverGlucagonSetPoint = new SEScalarMassPerVolume();
return *m_LiverGlucagonSetPoint;
}
double SETissueSystem::GetLiverGlucagonSetPoint(const MassPerVolumeUnit& unit) const
{
if (m_LiverGlucagonSetPoint == nullptr)
return SEScalar::dNaN();
return m_LiverGlucagonSetPoint->GetValue(unit);
}
bool SETissueSystem::HasMuscleInsulinSetPoint() const
{
return m_MuscleInsulinSetPoint == nullptr ? false : m_MuscleInsulinSetPoint->IsValid();
}
SEScalarAmountPerVolume& SETissueSystem::GetMuscleInsulinSetPoint()
{
if (m_MuscleInsulinSetPoint == nullptr)
m_MuscleInsulinSetPoint = new SEScalarAmountPerVolume();
return *m_MuscleInsulinSetPoint;
}
double SETissueSystem::GetMuscleInsulinSetPoint(const AmountPerVolumeUnit& unit) const
{
if (m_MuscleInsulinSetPoint == nullptr)
return SEScalar::dNaN();
return m_MuscleInsulinSetPoint->GetValue(unit);
}
bool SETissueSystem::HasMuscleGlucagonSetPoint() const
{
return m_MuscleGlucagonSetPoint == nullptr ? false : m_MuscleGlucagonSetPoint->IsValid();
}
SEScalarMassPerVolume& SETissueSystem::GetMuscleGlucagonSetPoint()
{
if (m_MuscleGlucagonSetPoint == nullptr)
m_MuscleGlucagonSetPoint = new SEScalarMassPerVolume();
return *m_MuscleGlucagonSetPoint;
}
double SETissueSystem::GetMuscleGlucagonSetPoint(const MassPerVolumeUnit& unit) const
{
if (m_MuscleGlucagonSetPoint == nullptr)
return SEScalar::dNaN();
return m_MuscleGlucagonSetPoint->GetValue(unit);
}
bool SETissueSystem::HasFatInsulinSetPoint() const
{
return m_FatInsulinSetPoint == nullptr ? false : m_FatInsulinSetPoint->IsValid();
}
SEScalarAmountPerVolume& SETissueSystem::GetFatInsulinSetPoint()
{
if (m_FatInsulinSetPoint == nullptr)
m_FatInsulinSetPoint = new SEScalarAmountPerVolume();
return *m_FatInsulinSetPoint;
}
double SETissueSystem::GetFatInsulinSetPoint(const AmountPerVolumeUnit& unit) const
{
if (m_FatInsulinSetPoint == nullptr)
return SEScalar::dNaN();
return m_FatInsulinSetPoint->GetValue(unit);
}
bool SETissueSystem::HasFatGlucagonSetPoint() const
{
return m_FatGlucagonSetPoint == nullptr ? false : m_FatGlucagonSetPoint->IsValid();
}
SEScalarMassPerVolume& SETissueSystem::GetFatGlucagonSetPoint()
{
if (m_FatGlucagonSetPoint == nullptr)
m_FatGlucagonSetPoint = new SEScalarMassPerVolume();
return *m_FatGlucagonSetPoint;
}
double SETissueSystem::GetFatGlucagonSetPoint(const MassPerVolumeUnit& unit) const
{
if (m_FatGlucagonSetPoint == nullptr)
return SEScalar::dNaN();
return m_FatGlucagonSetPoint->GetValue(unit);
}
bool SETissueSystem::HasLiverGlycogen() const
{
return m_LiverGlycogen == nullptr ? false : m_LiverGlycogen->IsValid();
}
SEScalarMass& SETissueSystem::GetLiverGlycogen()
{
if (m_LiverGlycogen == nullptr)
m_LiverGlycogen = new SEScalarMass();
return *m_LiverGlycogen;
}
double SETissueSystem::GetLiverGlycogen(const MassUnit& unit) const
{
if (m_LiverGlycogen == nullptr)
return SEScalar::dNaN();
return m_LiverGlycogen->GetValue(unit);
}
bool SETissueSystem::HasMuscleGlycogen() const
{
return m_MuscleGlycogen == nullptr ? false : m_MuscleGlycogen->IsValid();
}
SEScalarMass& SETissueSystem::GetMuscleGlycogen()
{
if (m_MuscleGlycogen == nullptr)
m_MuscleGlycogen = new SEScalarMass();
return *m_MuscleGlycogen;
}
double SETissueSystem::GetMuscleGlycogen(const MassUnit& unit) const
{
if (m_MuscleGlycogen == nullptr)
return SEScalar::dNaN();
return m_MuscleGlycogen->GetValue(unit);
}
bool SETissueSystem::HasStoredProtein() const
{
return m_StoredProtein == nullptr ? false : m_StoredProtein->IsValid();
}
SEScalarMass& SETissueSystem::GetStoredProtein()
{
if (m_StoredProtein == nullptr)
m_StoredProtein = new SEScalarMass();
return *m_StoredProtein;
}
double SETissueSystem::GetStoredProtein(const MassUnit& unit) const
{
if (m_StoredProtein == nullptr)
return SEScalar::dNaN();
return m_StoredProtein->GetValue(unit);
}
bool SETissueSystem::HasStoredFat() const
{
return m_StoredFat == nullptr ? false : m_StoredFat->IsValid();
}
SEScalarMass& SETissueSystem::GetStoredFat()
{
if (m_StoredFat == nullptr)
m_StoredFat = new SEScalarMass();
return *m_StoredFat;
}
double SETissueSystem::GetStoredFat(const MassUnit& unit) const
{
if (m_StoredFat == nullptr)
return SEScalar::dNaN();
return m_StoredFat->GetValue(unit);
}
|
#include <cmath>
class Base { // The class
public: // Access specifier
int Q; // Total Capacity (Discharge cell 100% to 0% SOC), Ah or mAh
float charge_capacity; // 0-100% SOC
int delta_t; // Iterations of time per sample
float delta_i; // Current applied to battery, A
float C1 = delta_t_graph/(5*R1); // Capacitor in Thevenin RC Model, calculated from Graph
float v0; // Instantaneous voltage once constant current removed
float R0=v0/delta_i;
float v_inf; // Measured once Voltage stabilizes
float R1=v_inf/delta_i-R0; // Resistor in Thevenin RC Model, Calculated from graph
float delta_t_graph; // Time to reach steady state from graph
float eta=Q/charge_capacity; //Coluombic Efficieny, eta
};
// Derived class
class SOC: public Base {
public:
void SOC_calc() {
for (int k=0; k<5; k++) {
z[k+1] = z[k]-delta_t/Q*i[k];
}
void SOC_with_Coulombic_efficieny() {
for (int k=0; k<5; k++) {
z[k+1] = z[k]-i[k]*eta[k]*delta_t/Q;
}
}
void resistor_current() {
i_R1[k+1] = exp(-delta_t/(R1*C1))*i_R1[k]+(1-exp(-delta_t/(R1*C1)))*i[k];
}
void cell_terminal_voltage() {
v[k]=OCV(z[k])-R1*i_R1[k]-R0*i[k];
}
};
class Hysteresis : public Base {
// For every SOC, range of possible stable "OCV" values
public:
int gamma // rate_of_decay
void unitless_hysteresis_state() {
h[k+1] = exp(-(abs(eta*i[k]*delta_t/Q)))*h[k] - (1-exp(-abs(eta[k]*i[k]*gamma*delta_t/Q)))*sgn(i[k])
v_h[k]=Mh[k]
}
void instantaneous_hysteresis() {
h_i[k]=M_0*s[k] // Instantaneous hysteresis
v_h[k]= M_0*s[k]+M*h[k] // Overall hysteresis
}
}
|
/* Copyright (c) 2010, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QDir>
#include <QList>
#include <QHash>
#include <QPluginLoader>
#include <QMutex>
#include <QMutexLocker>
#include <TWebApplication>
#include <TMailerPlugin>
#include "tmailerfactory.h"
#include "tsmtpmailer.h"
static QMutex mutex;
static QHash<QString, int> hash;
static QList<TMailerInterface *> *ssifs = 0;
static void cleanup()
{
QMutexLocker locker(&mutex);
if (ssifs)
delete ssifs;
ssifs = 0;
}
QStringList TMailerFactory::keys()
{
QMutexLocker locker(&mutex);
loadPlugins();
QStringList ret;
ret << TSmtpMailer().key();
for (QListIterator<TMailerInterface *> i(*ssifs); i.hasNext(); ) {
ret << i.next()->keys();
}
return ret;
}
TMailer *TMailerFactory::create(const QString &key)
{
T_TRACEFUNC("key: %s", qPrintable(key));
QMutexLocker locker(&mutex);
loadPlugins();
TMailer *ret = 0;
QString k = key.toLower();
int type = hash.value(k, Invalid);
switch (type) {
case Smtp:
ret = new TSmtpMailer;
break;
case Plugin: {
for (QListIterator<TMailerInterface *> i(*ssifs); i.hasNext(); ) {
TMailerInterface *p = i.next();
if (p->keys().contains(k)) {
ret = p->create(k);
break;
}
}
break; }
default:
// do nothing
break;
}
return ret;
}
void TMailerFactory::loadPlugins()
{
if (!ssifs) {
ssifs = new QList<TMailerInterface *>();
qAddPostRoutine(cleanup);
// Init hash
hash.insert(TSmtpMailer().key().toLower(), Smtp);
QDir dir(Tf::app()->pluginsPath());
QStringList list = dir.entryList(QDir::Files);
for (QStringListIterator i(list); i.hasNext(); ) {
QPluginLoader loader(dir.absoluteFilePath(i.next()));
TMailerInterface *iface = qobject_cast<TMailerInterface *>(loader.instance());
if ( iface ) {
ssifs->append(iface);
QStringList keys = iface->keys();
for (QStringListIterator j(keys); j.hasNext(); ) {
hash.insert(j.next(), Plugin);
}
}
}
}
}
|
/** \file
* \brief String conversions and Hashing for GDF fileformat
*
* \author Łukasz Hanuszczak
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/fileformats/GDF.h>
#include <ogdf/fileformats/Utils.h>
namespace ogdf {
namespace gdf {
std::string toString(const NodeAttribute &attr)
{
switch(attr) {
case NodeAttribute::Name: return "name";
case NodeAttribute::X: return "x";
case NodeAttribute::Y: return "y";
case NodeAttribute::Z: return "z";
case NodeAttribute::FillColor: return "color";
case NodeAttribute::FillBgColor: return "fillbg";
case NodeAttribute::FillPattern: return "fillpattern";
case NodeAttribute::StrokeColor: return "strokecolor";
case NodeAttribute::StrokeType: return "stroketype";
case NodeAttribute::StrokeWidth: return "strokewidth";
case NodeAttribute::Shape: return "style";
case NodeAttribute::Width: return "width";
case NodeAttribute::Height: return "height";
case NodeAttribute::Label: return "label";
case NodeAttribute::Template: return "template";
case NodeAttribute::Weight: return "weight";
case NodeAttribute::Unknown: return "unknown";
}
return "";
}
std::string toString(const EdgeAttribute &attr)
{
switch(attr) {
case EdgeAttribute::Label: return "label";
case EdgeAttribute::Source: return "node1";
case EdgeAttribute::Target: return "node2";
case EdgeAttribute::Weight: return "weight";
case EdgeAttribute::Directed: return "directed";
case EdgeAttribute::Color: return "color";
case EdgeAttribute::Bends: return "bends";
case EdgeAttribute::Unknown: return "unknown";
}
return "";
}
std::string toString(const Shape &shape)
{
/*
* Based on official documentation:
* http://guess.wikispot.org/The_GUESS_.gdf_format
*/
switch(shape) {
case Shape::Rect: return "1";
case Shape::Ellipse: return "2";
case Shape::RoundedRect: return "3";
case Shape::Image: return "7";
default: return "1";
}
}
NodeAttribute toNodeAttribute(const std::string &str)
{
return toEnum(
str, toString,
static_cast<NodeAttribute>(0), NodeAttribute::Unknown, NodeAttribute::Unknown);
}
EdgeAttribute toEdgeAttribute(const std::string &str)
{
return toEnum(
str, toString,
static_cast<EdgeAttribute>(0), EdgeAttribute::Unknown, EdgeAttribute::Unknown);
}
Shape toShape(const std::string &str)
{
return toEnum(
str, toString,
Shape::Rect, Shape::Image, Shape::Rect);
}
}
}
|
// This file implements the IBackgroundCopyFile2 Interface for Python.
// Generated by makegw.py
#include "bits_pch.h"
#include "PyIBackgroundCopyFile.h"
#include "PyIBackgroundCopyFile2.h"
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation
PyIBackgroundCopyFile2::PyIBackgroundCopyFile2(IUnknown *pdisp) : PyIBackgroundCopyFile(pdisp) { ob_type = &type; }
PyIBackgroundCopyFile2::~PyIBackgroundCopyFile2() {}
/* static */ IBackgroundCopyFile2 *PyIBackgroundCopyFile2::GetI(PyObject *self)
{
return (IBackgroundCopyFile2 *)PyIBackgroundCopyFile::GetI(self);
}
// @pymethod |PyIBackgroundCopyFile2|GetFileRanges|Description of GetFileRanges.
PyObject *PyIBackgroundCopyFile2::GetFileRanges(PyObject *self, PyObject *args)
{
IBackgroundCopyFile2 *pIBCF2 = GetI(self);
if (pIBCF2 == NULL)
return NULL;
DWORD RangeCount;
BG_FILE_RANGE *Ranges;
if (!PyArg_ParseTuple(args, ":GetFileRanges"))
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIBCF2->GetFileRanges(&RangeCount, &Ranges);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr, pIBCF2, IID_IBackgroundCopyFile2);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |PyIBackgroundCopyFile2|SetRemoteName|Description of SetRemoteName.
PyObject *PyIBackgroundCopyFile2::SetRemoteName(PyObject *self, PyObject *args)
{
IBackgroundCopyFile2 *pIBCF2 = GetI(self);
if (pIBCF2 == NULL)
return NULL;
PyObject *obpRemoteName;
if (!PyArg_ParseTuple(args, "O:SetRemoteName", &obpRemoteName))
return NULL;
WCHAR *pRemoteName;
BOOL bPythonIsHappy = TRUE;
if (bPythonIsHappy && !PyWinObject_AsWCHAR(obpRemoteName, &pRemoteName))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIBCF2->SetRemoteName(pRemoteName);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr, pIBCF2, IID_IBackgroundCopyFile2);
Py_INCREF(Py_None);
return Py_None;
}
// @object PyIBackgroundCopyFile2|Description of the interface
static struct PyMethodDef PyIBackgroundCopyFile2_methods[] = {
{"GetFileRanges", PyIBackgroundCopyFile2::GetFileRanges, 1}, // @pymeth GetFileRanges|Description of GetFileRanges
{"SetRemoteName", PyIBackgroundCopyFile2::SetRemoteName, 1}, // @pymeth SetRemoteName|Description of SetRemoteName
{NULL}};
PyComTypeObject PyIBackgroundCopyFile2::type("PyIBackgroundCopyFile2", &PyIBackgroundCopyFile::type,
sizeof(PyIBackgroundCopyFile2), PyIBackgroundCopyFile2_methods,
GET_PYCOM_CTOR(PyIBackgroundCopyFile2));
|
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <time.h>
#include <string>
using namespace std;
class game_logic {
public:
bool standing = false;
int maxPlayers = 1;
int playersInGame = 0;
/*int getMaxPlayer() {
return maxPlayers;
}*/
string getHouseStats() {
string bust = "";
string stands = "";
if (dealerBust == true) {
bust = "Dealer has busted ";
}
if (houseStands() == true) {
stands = "House stands ";
}
return string("Dealer has: ") + to_string(dHand) + string(" ") + bust + stands;
}
string getplayerStats() {
return "Player Has " + to_string(pHand);
}
// Deals at the start of the game, by looping through the players vector and hitting twice for the indexes in the vector that are not equal to 9 (we use 9 to mark an empty slot)
// Also adds a card to the dealer hand.
string deal() {
hit();
hit();
drawHouse();
return "Dealing out cards \n" + getplayerStats() + "\n" + "Dealer now has: " + to_string(dHand) + "\n";
}
void updateGame() {
//Call functions based to update the game
genDeck();
shuffleDeck();
}
string makeMove(bool action) {
if (action == false) {
return stand();
} else {return hit();}
return "Making a move failed";
}
//Method for adding players to the game uses find to acces an empty spot represented by the value 9 in the players vector "vec" and replaces it with a player id
void addPlayer() {
if (playersInGame != maxPlayers) {
playersInGame++;
vector<int>::iterator it;
int ser = 9;
it = find(vec.begin(), vec.end(), ser);
if (it != vec.end())
{
vec.at(it - vec.begin()) = 0;
if (vec.at(it - vec.begin()) == 0) {
activePlayer = vec.at(it - vec.begin());
activePlayerPos = 0;
}
}
else
cout << "Element not found.\n\n";
}
}
//Reverse of the addPlayer method find specific player ids and changes them to the value 9
void removePlayer() {
vector<int>::iterator it;
int ser = 0;
it = find(vec.begin(), vec.end(), ser);
if (it != vec.end())
{
vec.at(it - vec.begin()) = 9;
}
else
cout << "Element not found.\n\n";
}
string doHouse() {
string s;
bool c = false;
cout << "house turn" << endl;
while (!c && !dealerBust)
{
s.string::append(drawHouse());
c = houseStands();
}
return s + compare(0);
}
private:
vector<int> vec{ 9};
int pHand;
int dHand = 0;
int cardCounter = 0;
int activePlayer;
int activePlayerPos;
int cardDeck[52];
int deckSize;
bool playerBust;
bool dealerBust = false;
//Draws for house until house stands or dealerbust is true this is intended to be run at the end of a round
//generates 52 values to simulate a deck of cards
void genDeck() {
int b = 1;
int j = 0;
for (int i = 0; i <= 51; i++) {
if (j == 4) {
b++;
j = 0;
}
if (b > 10) {
b = 10;
}
cardDeck[i] = b;
j++;
}
}
// Function used to shuffle the deck, using the random_shuffle method with a random seed based on the current time.
void shuffleDeck() {
srand(time(0));
random_shuffle(cardDeck, cardDeck + 52);
}
// Function used to "hit" a card, i.e. to add a card to the player hand.
string hit() {
pHand = pHand + cardDeck[cardCounter];
cardCounter++;
// check if the player has over 21, if they do they bust and can't hit anymore.
if (pHand > 21) {
playerBust = true;
cout << pHand << "\n";
cout << "Player busted"<<endl;
standing = true;
return "Player has over 21, player busted" + doHouse() + "\n";
}
else if (!playerBust && !dealerBust) {
cout << "Player now has: " << pHand << endl;
return "Player now has "+to_string(pHand) + "\n";
} else {return "Hit failed";}
}
string stand() {
cout << "Player is standing with: " << pHand << endl;
standing = true;
return "Player is standing with " + to_string(pHand) + "\n";
}
// Function used to check if the dealer should stand, according to blackjack rules. If the dealer reaches 17, they have to stand.
bool houseStands() {
if (dHand > 16) {
return true;
}
else {
return false;
}
}
// Function used to draw for the dealer when every player is done.
string drawHouse() {
dHand = dHand + cardDeck[cardCounter];
cardCounter++;
// First check if the dealer has over 21, to determine if they bust.
if (dHand > 21) {
dealerBust = true;
cout << "Dealer now has: " << dHand << endl;
cout << "Dealer Bust" << endl;
return "Dealer has over 21, dealer busts. \n";
}
// If they didn't bust, check if they don't have over 16 (as they have to stand on 16).
if (!dealerBust) {
if (!houseStands()) {
cout << "Dealer now has: " << dHand << endl;
return "Dealer now has: " + to_string(dHand) + "\n";
}
else
cout << "Dealer now has: " << dHand << endl;
cout << "House has 17 or higher, house stands." << endl;
return "Dealer has "+ to_string(dHand) +", house stands. \n";
}
}
// Function used at the end of the round, in order to compare the player hands with the dealer hand and decide who wins.
string compare(int i) {
// First check if neither the dealer or the player busted, so only the comparison for the sum of the cards is done.
if (!playerBust && !dealerBust) {
if (pHand > dHand) {
cout << "Player wins - player "<< i << endl;
return "Player wins - player " + to_string(i) + "\n" + reset();
}
else if (pHand < dHand) {
cout << "Dealer wins" << endl;
return "Dealer wins against player " + to_string(i)+ "\n" + reset();
}
else if (pHand == dHand) {
cout << "It's a tie " << endl;
return "It's a tie between dealer and player " + to_string(i)+ "\n" + reset();
}
}
// If the player busts, he autoloses.
else if (playerBust) {
cout << "Player busted - player "<< i << endl;
return "Player busted - player " + to_string(i)+ "\n" + reset();
}
// Else if the dealer busts, all the players that did not bust win.
else if (dealerBust) {
cout << "Dealer busted, player wins - player " << i << endl;
return "Dealer busted, player wins - player " + to_string(i)+ "\n" + reset();
}
}
// Function used for resetting the dealer hand, the player hands by looping through the player vector and rebuilding the deck so we don't run out of cards.
string reset() {
if (vec.at(0) != 9) {
pHand = 0;
playerBust = 0;
}
dHand = 0;
dealerBust = 0;
genDeck();
standing = false;
shuffleDeck();
cardCounter = 0;
return deal();
}
};
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <cpp/eval/ast/while_statement.h>
#include <cpp/eval/ast/expression.h>
#include <cpp/eval/runtime/variable_environment.h>
namespace HPHP {
namespace Eval {
///////////////////////////////////////////////////////////////////////////////
WhileStatement::WhileStatement(STATEMENT_ARGS, ExpressionPtr cond,
StatementPtr body)
: Statement(STATEMENT_PASS), m_cond(cond), m_body(body) {}
void WhileStatement::eval(VariableEnvironment &env) const {
ENTER_STMT;
while (m_cond->eval(env)) {
if (!m_body) continue;
EVAL_STMT_HANDLE_BREAK(m_body, env);
}
}
void WhileStatement::dump() const {
printf("while (");
m_cond->dump();
printf(") {");
if (m_body) m_body->dump();
printf("}");
}
///////////////////////////////////////////////////////////////////////////////
}
}
|
/*
Copyright (c) 2018 Matt Hensman <m@matt.tf>
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 "HighLevelMonitorConfigurationAPI.h"
#include "PhysicalMonitorEnumerationAPI.h"
#include "windows.h"
#include "winuser.h"
#include <iostream>
#include <map>
#include <string>
#include <argagg.hpp>
#include <json.hpp>
using json = nlohmann::json;
void
logError(const char* message)
{
std::cerr << "error: " << message << std::endl;
}
std::map<std::string, HANDLE> handles;
void
populateHandlesMap()
{
// Cleanup
if (!handles.empty()) {
for (auto const& handle : handles) {
DestroyPhysicalMonitor(handle.second);
}
handles.clear();
}
struct Monitor {
HMONITOR handle;
std::vector<HANDLE> physicalHandles;
};
auto monitorEnumProc = [](HMONITOR hMonitor,
HDC hdcMonitor,
LPRECT lprcMonitor,
LPARAM dwData) -> BOOL {
auto monitors = reinterpret_cast<std::vector<struct Monitor>*>(dwData);
monitors->push_back({ hMonitor, {} });
return TRUE;
};
std::vector<struct Monitor> monitors;
EnumDisplayMonitors(
NULL, NULL, monitorEnumProc, reinterpret_cast<LPARAM>(&monitors));
// Get physical monitor handles
for (auto& monitor : monitors) {
DWORD numPhysicalMonitors;
LPPHYSICAL_MONITOR physicalMonitors = NULL;
if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor.handle,
&numPhysicalMonitors)) {
throw std::runtime_error("Failed to get physical monitor count.");
exit(EXIT_FAILURE);
}
physicalMonitors = new PHYSICAL_MONITOR[numPhysicalMonitors];
if (physicalMonitors == NULL) {
throw std::runtime_error(
"Failed to allocate physical monitor array");
}
if (!GetPhysicalMonitorsFromHMONITOR(
monitor.handle, numPhysicalMonitors, physicalMonitors)) {
throw std::runtime_error("Failed to get physical monitors.");
}
for (DWORD i = 0; i <= numPhysicalMonitors; i++) {
monitor.physicalHandles.push_back(
physicalMonitors[(numPhysicalMonitors == 1 ? 0 : i)]
.hPhysicalMonitor);
}
delete[] physicalMonitors;
}
DISPLAY_DEVICE adapterDev;
adapterDev.cb = sizeof(DISPLAY_DEVICE);
// Loop through adapters
int adapterDevIndex = 0;
while (EnumDisplayDevices(NULL, adapterDevIndex++, &adapterDev, 0)) {
DISPLAY_DEVICE displayDev;
displayDev.cb = sizeof(DISPLAY_DEVICE);
// Loop through displays (with device ID) on each adapter
int displayDevIndex = 0;
while (EnumDisplayDevices(adapterDev.DeviceName,
displayDevIndex++,
&displayDev,
EDD_GET_DEVICE_INTERFACE_NAME)) {
// Check valid target
if (!(displayDev.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)
|| displayDev.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) {
continue;
}
for (auto const& monitor : monitors) {
MONITORINFOEX monitorInfo;
monitorInfo.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(monitor.handle, &monitorInfo);
for (size_t i = 0; i < monitor.physicalHandles.size(); i++) {
/**
* Re-create DISPLAY_DEVICE.DeviceName with
* MONITORINFOEX.szDevice and monitor index.
*/
std::string monitorName =
static_cast<std::string>(monitorInfo.szDevice)
+ "\\Monitor" + std::to_string(i);
std::string deviceName =
static_cast<std::string>(displayDev.DeviceName);
// Match and store against device ID
if (monitorName == deviceName) {
handles.insert(
{ static_cast<std::string>(displayDev.DeviceID),
monitor.physicalHandles[i] });
break;
}
}
}
}
}
}
struct MonitorBrightness {
unsigned long maximumBrightness;
unsigned long currentBrightness;
};
struct MonitorContrast {
unsigned long maximumContrast;
unsigned long currentContrast;
};
MonitorBrightness
getMonitorBrightness(HANDLE hMonitor)
{
DWORD minimumBrightness;
DWORD maximumBrightness;
DWORD currentBrightness;
if (!GetMonitorBrightness(hMonitor,
&minimumBrightness,
¤tBrightness,
&maximumBrightness)) {
throw std::runtime_error("failed to get monitor brightness");
}
MonitorBrightness brightness = {
static_cast<unsigned long>(maximumBrightness),
static_cast<unsigned long>(currentBrightness)
};
return brightness;
}
MonitorContrast
getMonitorContrast(HANDLE hMonitor)
{
DWORD minimumContrast;
DWORD maximumContrast;
DWORD currentContrast;
if (!GetMonitorContrast(
hMonitor, &minimumContrast, ¤tContrast, &maximumContrast)) {
throw std::runtime_error("failed to get monitor contrast");
}
MonitorContrast contrast = { static_cast<unsigned long>(maximumContrast),
static_cast<unsigned long>(currentContrast) };
return contrast;
}
void
setMonitorBrightness(HANDLE hMonitor, unsigned long level)
{
auto brightness = getMonitorBrightness(hMonitor);
if (level > brightness.maximumBrightness) {
throw std::runtime_error("brightness level exceeds maximum");
}
if (!SetMonitorBrightness(hMonitor, static_cast<DWORD>(level))) {
throw std::runtime_error("failed to set monitor brightness");
}
}
void
setMonitorContrast(HANDLE hMonitor, unsigned long level)
{
auto contrast = getMonitorContrast(hMonitor);
if (level > contrast.maximumContrast) {
throw std::runtime_error("contrast level exceeds maximum");
}
if (!SetMonitorContrast(hMonitor, static_cast<DWORD>(level))) {
throw std::runtime_error("failed to set monitor contrast");
}
}
int
main(int argc, char** argv)
{
argagg::parser parser{
{ { "setBrightness",
{ "-b", "--brightness" },
"Sets monitor brightness",
1 },
{ "getBrightness",
{ "-B", "--get-brightness" },
"Gets monitor brightness",
0 },
{ "setContrast", { "-c", "--contrast" }, "Sets monitor contrast", 1 },
{ "getContrast",
{ "-C", "--get-contrast" },
"Gets monitor contrast",
0 },
{ "help", { "-h", "--help" }, "Prints this help message", 0 },
{ "version", { "-v", "--version" }, "Prints the version number", 0 },
{ "list", { "-l", "--list" }, "Lists connected monitors", 0 },
{ "monitor",
{ "-m", "--monitor" },
"Selects a monitor to adjust. If not specified, actions affects all monitors.",
1 },
{ "json", { "-j", "--json" }, "Outputs action results as JSON", 0 } }
};
std::string versionString = "v0.1.0";
std::ostringstream usage;
usage << argv[0] << " " << versionString << std::endl
<< "Usage: " << argv[0] << " [options]" << std::endl;
try {
argagg::parser_results args = parser.parse(argc, argv);
// Help
if (args["help"]) {
std::cout << usage.str() << parser;
return EXIT_SUCCESS;
}
if (args["version"]) {
argagg::fmt_ostream fmt(std::cout);
fmt << "ddccli " << versionString << std::endl
<< "Copyright (c) 2021 Matt Hensman <m@matt.tf>" << std::endl
<< "MIT License" << std::endl;
return EXIT_SUCCESS;
}
bool shouldOutputJson = false;
json jsonOutput;
if (args["json"]) {
shouldOutputJson = true;
}
try {
populateHandlesMap();
if (args["list"]) {
if (shouldOutputJson) {
jsonOutput["monitorList"] = json::array();
}
for (auto const& [ id, handle ] : handles) {
if (shouldOutputJson) {
jsonOutput["monitorList"].push_back(id);
} else {
std::cout << id << std::endl;
}
}
}
if (args["monitor"]) {
std::string selectedMonitorName = args["monitor"];
// Remove all non-matching monitors from the map
for (auto const& [ id, handle ] : handles) {
if (id != selectedMonitorName) {
handles.erase(id);
}
}
if (handles.empty()) {
throw std::runtime_error("monitor doesn't exist");
}
}
if (args["setBrightness"]) {
unsigned long level = args["setBrightness"];
for (auto const& [ id, handle ] : handles) {
setMonitorBrightness(handle, level);
}
}
if (args["getBrightness"]) {
if (args["monitor"]) {
auto it = handles.find(args["monitor"]);
if (it == handles.end()) {
throw std::runtime_error("monitor not found");
}
auto brightness =
getMonitorBrightness(it->second).currentBrightness;
if (shouldOutputJson) {
jsonOutput["brightness"] = brightness;
} else {
std::cout << brightness << std::endl;
}
} else {
throw std::runtime_error(
"no monitor specified to query brightness");
}
}
if (args["setContrast"]) {
unsigned long level = args["setContrast"];
for (auto const& [ id, handle ] : handles) {
setMonitorContrast(handle, level);
}
}
if (args["getContrast"]) {
if (args["monitor"]) {
auto it = handles.find(args["monitor"]);
if (it == handles.end()) {
throw std::runtime_error("monitor not found");
}
auto contrast =
getMonitorContrast(it->second).currentContrast;
if (shouldOutputJson) {
jsonOutput["contrast"] = contrast;
} else {
std::cout << contrast << std::endl;
}
} else {
throw std::runtime_error(
"no monitor specified to query contrast");
}
}
} catch (const std::runtime_error e) {
logError(e.what());
return EXIT_FAILURE;
}
if (shouldOutputJson) {
std::cout << jsonOutput << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Error parsing arguments: " << e.what() << std::endl
<< usage.str() << parser;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2014, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// pgAggregate.cpp - Aggregate class
//
//////////////////////////////////////////////////////////////////////////
// wxWindows headers
#include <wx/wx.h>
// App headers
#include "pgAdmin3.h"
#include "utils/misc.h"
#include "schema/pgAggregate.h"
pgAggregate::pgAggregate(pgSchema *newSchema, const wxString &newName)
: pgSchemaObject(newSchema, aggregateFactory, newName)
{
}
wxString pgAggregate::GetTranslatedMessage(int kindOfMessage) const
{
wxString message = wxEmptyString;
switch (kindOfMessage)
{
case RETRIEVINGDETAILS:
message = _("Retrieving details on aggregate");
message += wxT(" ") + GetName();
break;
case REFRESHINGDETAILS:
message = _("Refreshing aggregate");
message += wxT(" ") + GetName();
break;
case DROPINCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop aggregate \"%s\" including all objects that depend on it?"),
GetFullIdentifier().c_str());
break;
case DROPEXCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop aggregate \"%s\"?"),
GetFullIdentifier().c_str());
break;
case DROPCASCADETITLE:
message = _("Drop aggregate cascaded?");
break;
case DROPTITLE:
message = _("Drop aggregate?");
break;
case PROPERTIESREPORT:
message = _("Aggregate properties report");
message += wxT(" - ") + GetName();
break;
case PROPERTIES:
message = _("Aggregate properties");
break;
case DDLREPORT:
message = _("Aggregate DDL report");
message += wxT(" - ") + GetName();
break;
case DDL:
message = _("Aggregate DDL");
break;
case DEPENDENCIESREPORT:
message = _("Aggregate dependencies report");
message += wxT(" - ") + GetName();
break;
case DEPENDENCIES:
message = _("Aggregate dependencies");
break;
case DEPENDENTSREPORT:
message = _("Aggregate dependents report");
message += wxT(" - ") + GetName();
break;
case DEPENDENTS:
message = _("Aggregate dependents");
break;
}
return message;
}
bool pgAggregate::DropObject(wxFrame *frame, ctlTree *browser, bool cascaded)
{
wxString sql = wxT("DROP AGGREGATE ") + GetSchema()->GetQuotedIdentifier() + wxT(".") + GetFullName();
if (cascaded)
sql += wxT(" CASCADE");
return GetDatabase()->ExecuteVoid(sql);
}
wxString pgAggregate::GetSql(ctlTree *browser)
{
if (sql.IsNull())
{
sql = wxT("-- Aggregate: ") + GetQuotedFullName() + wxT("\n\n")
+ wxT("-- DROP AGGREGATE ") + GetQuotedFullName() + wxT(";");
if (GetDatabase()->BackendMinimumVersion(8, 2))
{
sql += wxT("\n\nCREATE AGGREGATE ") + GetQuotedFullName() + wxT(" (");
}
else
{
sql += wxT("\n\nCREATE AGGREGATE ") + GetQuotedFullIdentifier()
+ wxT("(\n BASETYPE=") + GetInputTypesList() + wxT(",");
}
sql += wxT("\n SFUNC=") + GetStateFunction()
+ wxT(",\n STYPE=") + GetStateType();
AppendIfFilled(sql, wxT(",\n FINALFUNC="), qtIdent(GetFinalFunction()));
if (GetInitialCondition().length() > 0)
{
if (GetInitialCondition() == wxT("''"))
sql += wxT(",\n INITCOND=''");
else if (GetInitialCondition() == wxT("\\'\\'"))
sql += wxT(",\n INITCOND=''''''");
else
sql += wxT(",\n INITCOND=") + qtDbString(GetInitialCondition());
}
AppendIfFilled(sql, wxT(",\n SORTOP="), GetQuotedSortOp());
sql += wxT("\n);\n");
sql += GetOwnerSql(8, 0, wxT("AGGREGATE ") + GetQuotedFullName())
+ GetGrant(wxT("X"), wxT("FUNCTION ") + GetQuotedFullIdentifier());
if (!GetComment().IsNull())
{
sql += wxT("COMMENT ON AGGREGATE ") + GetQuotedFullName()
+ wxT(" IS ") + qtDbString(GetComment()) + wxT(";\n");
}
if (GetConnection()->BackendMinimumVersion(9, 1))
sql += GetSeqLabelsSql();
}
return sql;
}
void pgAggregate::ShowTreeDetail(ctlTree *browser, frmMain *form, ctlListView *properties, ctlSQLBox *sqlPane)
{
if (properties)
{
CreateListColumns(properties);
properties->AppendItem(_("Name"), GetName());
properties->AppendItem(_("OID"), GetOid());
properties->AppendItem(_("Owner"), GetOwner());
properties->AppendItem(_("ACL"), GetAcl());
properties->AppendItem(_("Input types"), GetInputTypesList());
properties->AppendItem(_("State type"), GetStateType());
properties->AppendItem(_("State function"), GetStateFunction());
properties->AppendItem(_("Final type"), GetFinalType());
properties->AppendItem(_("Final function"), GetFinalFunction());
if (GetConnection()->BackendMinimumVersion(8, 1))
properties->AppendItem(_("Sort operator"), GetSortOp());
if (GetInitialCondition() == wxT(""))
properties->AppendItem(_("Initial condition"), _("<null>"));
else if (GetInitialCondition() == wxT("''"))
properties->AppendItem(_("Initial condition"), _("<empty string>"));
else if (GetInitialCondition() == wxT("\\'\\'"))
properties->AppendItem(_("Initial condition"), _("''"));
else
properties->AppendItem(_("Initial condition"), GetInitialCondition());
properties->AppendYesNoItem(_("System aggregate?"), GetSystemObject());
properties->AppendItem(_("Comment"), firstLineOnly(GetComment()));
if (!GetLabels().IsEmpty())
{
wxArrayString seclabels = GetProviderLabelArray();
if (seclabels.GetCount() > 0)
{
for (unsigned int index = 0 ; index < seclabels.GetCount() - 1 ; index += 2)
{
properties->AppendItem(seclabels.Item(index), seclabels.Item(index + 1));
}
}
}
}
}
pgObject *pgAggregate::Refresh(ctlTree *browser, const wxTreeItemId item)
{
pgObject *aggregate = 0;
pgCollection *coll = browser->GetParentCollection(item);
if (coll)
aggregate = aggregateFactory.CreateObjects(coll, 0, wxT("\n AND aggfnoid::oid=") + GetOidStr());
return aggregate;
}
wxString pgAggregate::GetQuotedFullName()
{
return GetQuotedFullIdentifier() + wxT("(") + GetInputTypesList() + wxT(")");
}
wxString pgAggregate::GetFullName()
{
return GetName() + wxT("(") + GetInputTypesList() + wxT(")");
}
// Return the list of input types
wxString pgAggregate::GetInputTypesList()
{
wxString types;
for (unsigned int i = 0; i < inputTypes.Count(); i++)
{
if (i > 0)
types += wxT(", ");
types += inputTypes.Item(i);
}
return types;
}
pgObject *pgAggregateFactory::CreateObjects(pgCollection *collection, ctlTree *browser, const wxString &restriction)
{
pgAggregate *aggregate = 0;
// Build a cache of data types
pgSet *types = collection->GetDatabase()->ExecuteSet(wxT(
"SELECT oid, format_type(oid, typtypmod) AS typname FROM pg_type"));
cacheMap map;
while(!types->Eof())
{
map[types->GetVal(wxT("oid"))] = types->GetVal(wxT("typname"));
types->MoveNext();
}
delete types;
// Build the query to get all objects
wxString sql =
wxT("SELECT aggfnoid::oid, proname AS aggname, pg_get_userbyid(proowner) AS aggowner, aggtransfn,\n")
wxT( "aggfinalfn, proargtypes, aggtranstype, proacl, ")
wxT( "CASE WHEN (tt.typlen = -1 AND tt.typelem != 0) THEN (SELECT at.typname FROM pg_type at WHERE at.oid = tt.typelem) || '[]' ELSE tt.typname END as transname, ")
wxT( "prorettype AS aggfinaltype, ")
wxT( "CASE WHEN (tf.typlen = -1 AND tf.typelem != 0) THEN (SELECT at.typname FROM pg_type at WHERE at.oid = tf.typelem) || '[]' ELSE tf.typname END as finalname, ")
wxT( "agginitval, description");
if (collection->GetDatabase()->BackendMinimumVersion(9, 1))
{
sql += wxT(",\n(SELECT array_agg(label) FROM pg_seclabels sl1 WHERE sl1.objoid=aggfnoid) AS labels");
sql += wxT(",\n(SELECT array_agg(provider) FROM pg_seclabels sl2 WHERE sl2.objoid=aggfnoid) AS providers");
}
if (collection->GetDatabase()->BackendMinimumVersion(8, 1))
{
sql += wxT(", oprname, opn.nspname as oprnsp\n")
wxT(" FROM pg_aggregate ag\n")
wxT(" LEFT OUTER JOIN pg_operator op ON op.oid=aggsortop\n")
wxT(" LEFT OUTER JOIN pg_namespace opn ON opn.oid=op.oprnamespace");
}
else
sql += wxT("\n FROM pg_aggregate ag\n");
pgSet *aggregates = collection->GetDatabase()->ExecuteSet(sql +
wxT(" JOIN pg_proc pr ON pr.oid = ag.aggfnoid\n")
wxT(" JOIN pg_type tt on tt.oid=aggtranstype\n")
wxT(" JOIN pg_type tf on tf.oid=prorettype\n")
wxT(" LEFT OUTER JOIN pg_description des ON (des.objoid=aggfnoid::oid AND des.classoid='pg_aggregate'::regclass)\n")
wxT(" WHERE pronamespace = ") + collection->GetSchema()->GetOidStr()
+ restriction
+ wxT("\n ORDER BY aggname"));
if (aggregates)
{
while (!aggregates->Eof())
{
aggregate = new pgAggregate(collection->GetSchema(), aggregates->GetVal(wxT("aggname")));
aggregate->iSetOid(aggregates->GetOid(wxT("aggfnoid")));
aggregate->iSetOwner(aggregates->GetVal(wxT("aggowner")));
aggregate->iSetAcl(aggregates->GetVal(wxT("proacl")));
// Get the input type names. From 8.2 onwards there might be
// multiple types in the array. In any case, we must properly
// quote "any"
// Tokenize the arguments
wxStringTokenizer argTypes(wxEmptyString);
if (aggregates->GetVal(wxT("proargtypes")) == wxEmptyString)
{
if (collection->GetDatabase()->BackendMinimumVersion(8, 2))
aggregate->iAddInputType(wxT("*"));
else
aggregate->iAddInputType(wxT("\"any\""));
}
else
{
argTypes.SetString(aggregates->GetVal(wxT("proargtypes")));
while (argTypes.HasMoreTokens())
{
// Add the arg type. This is a type oid, so
// look it up in the hashmap
wxString type = argTypes.GetNextToken();
if (map[type] == wxT("any"))
aggregate->iAddInputType(wxT("\"any\""));
else
aggregate->iAddInputType(qtTypeIdent(map[type]));
}
}
aggregate->iSetStateType(aggregates->GetVal(wxT("transname")));
aggregate->iSetStateFunction(aggregates->GetVal(wxT("aggtransfn")));
aggregate->iSetFinalType(aggregates->GetVal(wxT("finalname")));
wxString final = aggregates->GetVal(wxT("aggfinalfn"));
if (final != wxT("-"))
aggregate->iSetFinalFunction(final);
if (!aggregates->IsNull(aggregates->ColNumber(wxT("agginitval"))))
{
if (aggregates->GetVal(wxT("agginitval")).IsEmpty())
aggregate->iSetInitialCondition(wxT("''"));
else if (aggregates->GetVal(wxT("agginitval")) == wxT("''"))
aggregate->iSetInitialCondition(wxT("\\'\\'"));
else
aggregate->iSetInitialCondition(aggregates->GetVal(wxT("agginitval")));
}
aggregate->iSetComment(aggregates->GetVal(wxT("description")));
if (collection->GetDatabase()->BackendMinimumVersion(8, 1))
{
wxString oprname = aggregates->GetVal(wxT("oprname"));
if (!oprname.IsEmpty())
{
wxString oprnsp = aggregates->GetVal(wxT("oprnsp"));
aggregate->iSetSortOp(collection->GetDatabase()->GetSchemaPrefix(oprnsp) + oprname);
aggregate->iSetQuotedSortOp(collection->GetDatabase()->GetQuotedSchemaPrefix(oprnsp)
+ qtIdent(oprname));
}
}
if (collection->GetDatabase()->BackendMinimumVersion(9, 1))
{
aggregate->iSetProviders(aggregates->GetVal(wxT("providers")));
aggregate->iSetLabels(aggregates->GetVal(wxT("labels")));
}
if (browser)
{
browser->AppendObject(collection, aggregate);
aggregates->MoveNext();
}
else
break;
}
delete aggregates;
}
return aggregate;
}
/////////////////////////////
pgAggregateCollection::pgAggregateCollection(pgaFactory *factory, pgSchema *sch)
: pgSchemaObjCollection(factory, sch)
{
}
wxString pgAggregateCollection::GetTranslatedMessage(int kindOfMessage) const
{
wxString message = wxEmptyString;
switch (kindOfMessage)
{
case RETRIEVINGDETAILS:
message = _("Retrieving details on aggregates");
break;
case REFRESHINGDETAILS:
message = _("Refreshing aggregates");
break;
case OBJECTSLISTREPORT:
message = _("Aggregates list report");
break;
}
return message;
}
/////////////////////////////
#include "images/aggregate.pngc"
#include "images/aggregate-sm.pngc"
#include "images/aggregates.pngc"
pgAggregateFactory::pgAggregateFactory()
: pgSchemaObjFactory(__("Aggregate"), __("New Aggregate..."), __("Create a new Aggregate."), aggregate_png_img, aggregate_sm_png_img)
{
}
pgCollection *pgAggregateFactory::CreateCollection(pgObject *obj)
{
return new pgAggregateCollection(GetCollectionFactory(), (pgSchema *)obj);
}
pgAggregateFactory aggregateFactory;
static pgaCollectionFactory cf(&aggregateFactory, __("Aggregates"), aggregates_png_img);
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_NDEBUG 0
#undef LOG_TAG
#define LOG_TAG "FakeHwcService"
#include <log/log.h>
#include "FakeComposerService.h"
using namespace android::hardware;
namespace sftest {
FakeComposerService::FakeComposerService(android::sp<ComposerClient>& client) : mClient(client) {}
FakeComposerService::~FakeComposerService() {
ALOGI("Maybe killing client %p", mClient.get());
// Rely on sp to kill the client.
}
Return<void> FakeComposerService::getCapabilities(getCapabilities_cb hidl_cb) {
ALOGI("FakeComposerService::getCapabilities");
hidl_cb(hidl_vec<Capability>());
return Void();
}
Return<void> FakeComposerService::dumpDebugInfo(dumpDebugInfo_cb hidl_cb) {
ALOGI("FakeComposerService::dumpDebugInfo");
hidl_cb(hidl_string());
return Void();
}
Return<void> FakeComposerService::createClient(createClient_cb hidl_cb) {
ALOGI("FakeComposerService::createClient %p", mClient.get());
if (!mClient->init()) {
LOG_ALWAYS_FATAL("failed to initialize ComposerClient");
}
hidl_cb(Error::NONE, mClient);
return Void();
}
} // namespace sftest
|
#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "dialogwindowflags.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include <string>
#include <vector>
#include <QClipboard>
#include <QKeyEvent>
SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
QWidget(parent, DIALOGWINDOWHINTS),
ui(new Ui::SignVerifyMessageDialog),
model(0)
{
ui->setupUi(this);
#if (QT_VERSION >= 0x040700)
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addressIn_SM->setPlaceholderText(tr("Enter a BitcoinTitanium address (e.g. 4Zo1ga6xuKuQ7JV7M9rGDoxdbYwV5zgQJ5)"));
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
ui->addressIn_VM->setPlaceholderText(tr("Enter a BitcoinTitanium address (e.g. 4Zo1ga6xuKuQ7JV7M9rGDoxdbYwV5zgQJ5)"));
ui->signatureIn_VM->setPlaceholderText(tr("Enter BitcoinTitanium signature"));
#endif
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(QString address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(QString address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CBitcoinAddress(key.GetPubKey().GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QWidget::eventFilter(object, event);
}
void SignVerifyMessageDialog::keyPressEvent(QKeyEvent *event)
{
#ifdef ANDROID
if(event->key() == Qt::Key_Back)
{
close();
}
#else
if(event->key() == Qt::Key_Escape)
{
close();
}
#endif
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <string>
// template<class charT, class traits, class Allocator>
// constexpr bool operator<=(const charT* lhs, basic_string_view<charT,traits> rhs);
// template<class charT, class traits, class Allocator>
// constexpr bool operator<=(basic_string_view<charT,traits> lhs, const charT* rhs);
#include <string_view>
#include <cassert>
#include "test_macros.h"
#include "constexpr_char_traits.h"
template <class S>
void
test(const typename S::value_type* lhs, const S& rhs, bool x, bool y)
{
assert((lhs <= rhs) == x);
assert((rhs <= lhs) == y);
}
int main(int, char**)
{
{
typedef std::string_view S;
test("", S(""), true, true);
test("", S("abcde"), true, false);
test("", S("abcdefghij"), true, false);
test("", S("abcdefghijklmnopqrst"), true, false);
test("abcde", S(""), false, true);
test("abcde", S("abcde"), true, true);
test("abcde", S("abcdefghij"), true, false);
test("abcde", S("abcdefghijklmnopqrst"), true, false);
test("abcdefghij", S(""), false, true);
test("abcdefghij", S("abcde"), false, true);
test("abcdefghij", S("abcdefghij"), true, true);
test("abcdefghij", S("abcdefghijklmnopqrst"), true, false);
test("abcdefghijklmnopqrst", S(""), false, true);
test("abcdefghijklmnopqrst", S("abcde"), false, true);
test("abcdefghijklmnopqrst", S("abcdefghij"), false, true);
test("abcdefghijklmnopqrst", S("abcdefghijklmnopqrst"), true, true);
}
#if TEST_STD_VER > 11
{
typedef std::basic_string_view<char, constexpr_char_traits<char>> SV;
constexpr SV sv1;
constexpr SV sv2 { "abcde", 5 };
static_assert ( sv1 <= "", "" );
static_assert ( "" <= sv1, "" );
static_assert ( sv1 <= "abcde", "" );
static_assert (!("abcde" <= sv1), "" );
static_assert (!(sv2 <= ""), "" );
static_assert ( "" <= sv2, "" );
static_assert ( sv2 <= "abcde", "" );
static_assert ( "abcde" <= sv2, "" );
static_assert ( sv2 <= "abcde0", "" );
static_assert (!("abcde0" <= sv2), "" );
}
#endif
return 0;
}
|
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//============================================================================
#ifndef vtk_m_filter_Pathline_hxx
#define vtk_m_filter_Pathline_hxx
#include <vtkm/cont/ArrayCopy.h>
#include <vtkm/cont/ArrayHandleIndex.h>
#include <vtkm/cont/ErrorFilterExecution.h>
#include <vtkm/worklet/particleadvection/GridEvaluators.h>
#include <vtkm/worklet/particleadvection/Integrators.h>
#include <vtkm/worklet/particleadvection/Particles.h>
#include <vtkm/worklet/particleadvection/TemporalGridEvaluators.h>
namespace vtkm
{
namespace filter
{
//-----------------------------------------------------------------------------
inline VTKM_CONT Pathline::Pathline()
: vtkm::filter::FilterDataSetWithField<Pathline>()
, Worklet()
{
}
//-----------------------------------------------------------------------------
inline VTKM_CONT void Pathline::SetSeeds(vtkm::cont::ArrayHandle<vtkm::Particle>& seeds)
{
this->Seeds = seeds;
}
//-----------------------------------------------------------------------------
template <typename T, typename StorageType, typename DerivedPolicy>
inline VTKM_CONT vtkm::cont::DataSet Pathline::DoExecute(
const vtkm::cont::DataSet& input,
const vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>, StorageType>& field,
const vtkm::filter::FieldMetadata& fieldMeta,
const vtkm::filter::PolicyBase<DerivedPolicy>&)
{
//Check for some basics.
if (this->Seeds.GetNumberOfValues() == 0)
{
throw vtkm::cont::ErrorFilterExecution("No seeds provided.");
}
const vtkm::cont::DynamicCellSet& cells = input.GetCellSet();
const vtkm::cont::DynamicCellSet& cells2 = this->NextDataSet.GetCellSet();
const vtkm::cont::CoordinateSystem& coords =
input.GetCoordinateSystem(this->GetActiveCoordinateSystemIndex());
const vtkm::cont::CoordinateSystem& coords2 =
this->NextDataSet.GetCoordinateSystem(this->GetActiveCoordinateSystemIndex());
auto field2 = vtkm::cont::Cast<vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>, StorageType>>(
this->NextDataSet.GetField(this->GetActiveFieldName()).GetData());
if (!fieldMeta.IsPointField())
{
throw vtkm::cont::ErrorFilterExecution("Point field expected.");
}
using FieldHandle = vtkm::cont::ArrayHandle<vtkm::Vec<T, 3>, StorageType>;
using GridEvalType = vtkm::worklet::particleadvection::TemporalGridEvaluator<FieldHandle>;
using RK4Type = vtkm::worklet::particleadvection::RK4Integrator<GridEvalType>;
GridEvalType eval(
coords, cells, field, this->PreviousTime, coords2, cells2, field2, this->NextTime);
RK4Type rk4(eval, this->StepSize);
vtkm::worklet::Streamline streamline;
vtkm::worklet::StreamlineResult res;
vtkm::cont::ArrayHandle<vtkm::Particle> seedArray;
vtkm::cont::ArrayCopy(this->Seeds, seedArray);
res = Worklet.Run(rk4, seedArray, this->NumberOfSteps);
vtkm::cont::DataSet outData;
vtkm::cont::CoordinateSystem outputCoords("coordinates", res.Positions);
outData.SetCellSet(res.PolyLines);
outData.AddCoordinateSystem(outputCoords);
return outData;
}
//-----------------------------------------------------------------------------
template <typename T, typename StorageType, typename DerivedPolicy>
inline VTKM_CONT bool Pathline::DoMapField(vtkm::cont::DataSet&,
const vtkm::cont::ArrayHandle<T, StorageType>&,
const vtkm::filter::FieldMetadata&,
vtkm::filter::PolicyBase<DerivedPolicy>)
{
return false;
}
}
} // namespace vtkm::filter
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "util.h"
#include "chainparamsbase.h"
#include "fs.h"
#include "random.h"
#include "serialize.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include <stdarg.h>
#if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
#include <pthread.h>
#include <pthread_np.h>
#endif
#ifndef WIN32
// for posix_fallocate
#ifdef __linux__
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#define _POSIX_C_SOURCE 200112L
#endif // __linux__
#include <algorithm>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#else
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include <shlobj.h>
#endif
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
#ifdef HAVE_MALLOPT_ARENA_MAX
#include <malloc.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/program_options/detail/config_file.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/conf.h>
// Application startup time (used for uptime calculation)
const int64_t nStartupTime = GetTime();
const char * const BITCOIN_CONF_FILENAME = "fartonium.conf";
const char * const BITCOIN_PID_FILENAME = "fartonium.pid";
ArgsManager gArgs;
bool fPrintToConsole = false;
bool fPrintToDebugLog = true;
bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
bool fLogIPs = DEFAULT_LOGIPS;
std::atomic<bool> fReopenDebugLog(false);
CTranslationInterface translationInterface;
/** Log categories bitfield. */
std::atomic<uint32_t> logCategories(0);
/** Init OpenSSL library multithreading support */
static std::unique_ptr<CCriticalSection[]> ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(ppmutexOpenSSL[i]);
}
}
// Singleton for wrapping OpenSSL setup/teardown.
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL.reset(new CCriticalSection[CRYPTO_num_locks()]);
CRYPTO_set_locking_callback(locking_callback);
// OpenSSL can optionally load a config file which lists optional loadable modules and engines.
// We don't use them so we don't require the config. However some of our libs may call functions
// which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
// or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
// that the config appears to have been loaded and there are no modules/engines available.
OPENSSL_no_config();
#ifdef WIN32
// Seed OpenSSL PRNG with current contents of the screen
RAND_screen();
#endif
// Seed OpenSSL PRNG with performance counter
RandAddSeed();
}
~CInit()
{
// Securely erase the memory used by the PRNG
RAND_cleanup();
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(nullptr);
// Clear the set of locks now to maintain symmetry with the constructor.
ppmutexOpenSSL.reset();
}
}
instance_of_cinit;
/**
* LogPrintf() has been broken a couple of times now
* by well-meaning people adding mutexes in the most straightforward way.
* It breaks because it may be called by global destructors during shutdown.
* Since the order of destruction of static/global objects is undefined,
* defining a mutex as a global object doesn't work (the mutex gets
* destroyed, and then some later destructor calls OutputDebugStringF,
* maybe indirectly, and you get a core dump at shutdown trying to lock
* the mutex).
*/
static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
/**
* We use boost::call_once() to make sure mutexDebugLog and
* vMsgsBeforeOpenLog are initialized in a thread-safe manner.
*
* NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog
* are leaked on exit. This is ugly, but will be cleaned up by
* the OS/libc. When the shutdown sequence is fully audited and
* tested, explicit destruction of these objects can be implemented.
*/
static FILE* fileout = nullptr;
static boost::mutex* mutexDebugLog = nullptr;
static std::list<std::string>* vMsgsBeforeOpenLog;
static int FileWriteStr(const std::string &str, FILE *fp)
{
return fwrite(str.data(), 1, str.size(), fp);
}
static void DebugPrintInit()
{
assert(mutexDebugLog == nullptr);
mutexDebugLog = new boost::mutex();
vMsgsBeforeOpenLog = new std::list<std::string>;
}
void OpenDebugLog()
{
boost::call_once(&DebugPrintInit, debugPrintInitFlag);
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
assert(fileout == nullptr);
assert(vMsgsBeforeOpenLog);
fs::path pathDebug = GetDataDir() / "debug.log";
fileout = fsbridge::fopen(pathDebug, "a");
if (fileout) {
setbuf(fileout, nullptr); // unbuffered
// dump buffered messages from before we opened the log
while (!vMsgsBeforeOpenLog->empty()) {
FileWriteStr(vMsgsBeforeOpenLog->front(), fileout);
vMsgsBeforeOpenLog->pop_front();
}
}
delete vMsgsBeforeOpenLog;
vMsgsBeforeOpenLog = nullptr;
}
struct CLogCategoryDesc
{
uint32_t flag;
std::string category;
};
const CLogCategoryDesc LogCategories[] =
{
{BCLog::NONE, "0"},
{BCLog::NET, "net"},
{BCLog::TOR, "tor"},
{BCLog::MEMPOOL, "mempool"},
{BCLog::HTTP, "http"},
{BCLog::BENCH, "bench"},
{BCLog::ZMQ, "zmq"},
{BCLog::DB, "db"},
{BCLog::RPC, "rpc"},
{BCLog::ESTIMATEFEE, "estimatefee"},
{BCLog::ADDRMAN, "addrman"},
{BCLog::SELECTCOINS, "selectcoins"},
{BCLog::REINDEX, "reindex"},
{BCLog::CMPCTBLOCK, "cmpctblock"},
{BCLog::RAND, "rand"},
{BCLog::PRUNE, "prune"},
{BCLog::PROXY, "proxy"},
{BCLog::MEMPOOLREJ, "mempoolrej"},
{BCLog::LIBEVENT, "libevent"},
{BCLog::COINDB, "coindb"},
{BCLog::QT, "qt"},
{BCLog::LEVELDB, "leveldb"},
{BCLog::ALL, "1"},
{BCLog::ALL, "all"},
};
bool GetLogCategory(uint32_t *f, const std::string *str)
{
if (f && str) {
if (*str == "") {
*f = BCLog::ALL;
return true;
}
for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) {
if (LogCategories[i].category == *str) {
*f = LogCategories[i].flag;
return true;
}
}
}
return false;
}
std::string ListLogCategories()
{
std::string ret;
int outcount = 0;
for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) {
// Omit the special cases.
if (LogCategories[i].flag != BCLog::NONE && LogCategories[i].flag != BCLog::ALL) {
if (outcount != 0) ret += ", ";
ret += LogCategories[i].category;
outcount++;
}
}
return ret;
}
std::vector<CLogCategoryActive> ListActiveLogCategories()
{
std::vector<CLogCategoryActive> ret;
for (unsigned int i = 0; i < ARRAYLEN(LogCategories); i++) {
// Omit the special cases.
if (LogCategories[i].flag != BCLog::NONE && LogCategories[i].flag != BCLog::ALL) {
CLogCategoryActive catActive;
catActive.category = LogCategories[i].category;
catActive.active = LogAcceptCategory(LogCategories[i].flag);
ret.push_back(catActive);
}
}
return ret;
}
/**
* fStartedNewLine is a state variable held by the calling context that will
* suppress printing of the timestamp when multiple calls are made that don't
* end in a newline. Initialize it to true, and hold it, in the calling context.
*/
static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fStartedNewLine)
{
std::string strStamped;
if (!fLogTimestamps)
return str;
if (*fStartedNewLine) {
int64_t nTimeMicros = GetTimeMicros();
strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000);
if (fLogTimeMicros)
strStamped += strprintf(".%06d", nTimeMicros%1000000);
int64_t mocktime = GetMockTime();
if (mocktime) {
strStamped += " (mocktime: " + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", mocktime) + ")";
}
strStamped += ' ' + str;
} else
strStamped = str;
if (!str.empty() && str[str.size()-1] == '\n')
*fStartedNewLine = true;
else
*fStartedNewLine = false;
return strStamped;
}
int LogPrintStr(const std::string &str)
{
int ret = 0; // Returns total number of characters written
static std::atomic_bool fStartedNewLine(true);
std::string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
if (fPrintToConsole)
{
// print to console
ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
fflush(stdout);
}
else if (fPrintToDebugLog)
{
boost::call_once(&DebugPrintInit, debugPrintInitFlag);
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// buffer if we haven't opened the log yet
if (fileout == nullptr) {
assert(vMsgsBeforeOpenLog);
ret = strTimestamped.length();
vMsgsBeforeOpenLog->push_back(strTimestamped);
}
else
{
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
fs::path pathDebug = GetDataDir() / "debug.log";
if (fsbridge::freopen(pathDebug,"a",fileout) != nullptr)
setbuf(fileout, nullptr); // unbuffered
}
ret = FileWriteStr(strTimestamped, fileout);
}
}
return ret;
}
/** Interpret string as boolean, for argument parsing */
static bool InterpretBool(const std::string& strValue)
{
if (strValue.empty())
return true;
return (atoi(strValue) != 0);
}
/** Turn -noX into -X=0 */
static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
{
if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o')
{
strKey = "-" + strKey.substr(3);
strValue = InterpretBool(strValue) ? "0" : "1";
}
}
void ArgsManager::ParseParameters(int argc, const char* const argv[])
{
LOCK(cs_args);
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
std::string str(argv[i]);
std::string strValue;
size_t is_index = str.find('=');
if (is_index != std::string::npos)
{
strValue = str.substr(is_index+1);
str = str.substr(0, is_index);
}
#ifdef WIN32
boost::to_lower(str);
if (boost::algorithm::starts_with(str, "/"))
str = "-" + str.substr(1);
#endif
if (str[0] != '-')
break;
// Interpret --foo as -foo.
// If both --foo and -foo are set, the last takes effect.
if (str.length() > 1 && str[1] == '-')
str = str.substr(1);
InterpretNegativeSetting(str, strValue);
mapArgs[str] = strValue;
mapMultiArgs[str].push_back(strValue);
}
}
std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg)
{
LOCK(cs_args);
if (IsArgSet(strArg))
return mapMultiArgs.at(strArg);
return {};
}
bool ArgsManager::IsArgSet(const std::string& strArg)
{
LOCK(cs_args);
return mapArgs.count(strArg);
}
std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return InterpretBool(mapArgs[strArg]);
return fDefault;
}
bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
if (mapArgs.count(strArg))
return false;
ForceSetArg(strArg, strValue);
return true;
}
bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
mapArgs[strArg] = strValue;
mapMultiArgs[strArg].clear();
mapMultiArgs[strArg].push_back(strValue);
}
static const int screenWidth = 79;
static const int optIndent = 2;
static const int msgIndent = 7;
std::string HelpMessageGroup(const std::string &message) {
return std::string(message) + std::string("\n\n");
}
std::string HelpMessageOpt(const std::string &option, const std::string &message) {
return std::string(optIndent,' ') + std::string(option) +
std::string("\n") + std::string(msgIndent,' ') +
FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
std::string("\n\n");
}
static std::string FormatException(const std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
#else
const char* pszModule = "fartonium";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
LogPrintf("\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
}
fs::path GetDefaultDataDir()
{
// Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
// Mac: ~/Library/Application Support/Bitcoin
// Unix: ~/.bitcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "Fartonium";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == nullptr || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
return pathRet / "Library/Application Support/Fartonium";
#else
// Unix
return pathRet / ".fartonium";
#endif
#endif
}
static fs::path pathCached;
static fs::path pathCachedNetSpecific;
static CCriticalSection csPathCached;
const fs::path &GetDataDir(bool fNetSpecific)
{
LOCK(csPathCached);
fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
// This can be called during exceptions by LogPrintf(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty())
return path;
if (gArgs.IsArgSet("-datadir")) {
path = fs::system_complete(gArgs.GetArg("-datadir", ""));
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific)
path /= BaseParams().DataDir();
fs::create_directories(path);
return path;
}
void ClearDatadirCache()
{
LOCK(csPathCached);
pathCached = fs::path();
pathCachedNetSpecific = fs::path();
}
fs::path GetConfigFile(const std::string& confPath)
{
fs::path pathConfigFile(confPath);
if (!pathConfigFile.is_complete())
pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ArgsManager::ReadConfigFile(const std::string& confPath)
{
fs::ifstream streamConfig(GetConfigFile(confPath));
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
{
LOCK(cs_args);
std::set<std::string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
std::string strKey = std::string("-") + it->string_key;
std::string strValue = it->value[0];
InterpretNegativeSetting(strKey, strValue);
if (mapArgs.count(strKey) == 0)
mapArgs[strKey] = strValue;
mapMultiArgs[strKey].push_back(strValue);
}
}
// If datadir is changed in .conf file:
ClearDatadirCache();
}
#ifndef WIN32
fs::path GetPidFile()
{
fs::path pathPidFile(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
void CreatePidFile(const fs::path &path, pid_t pid)
{
FILE* file = fsbridge::fopen(path, "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(fs::path src, fs::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING) != 0;
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
/**
* Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
* Specifically handles case where path p exists, but it wasn't possible for the user to
* write to the parent directory.
*/
bool TryCreateDirectories(const fs::path& p)
{
try
{
return fs::create_directories(p);
} catch (const fs::filesystem_error&) {
if (!fs::exists(p) || !fs::is_directory(p))
throw;
}
// create_directories didn't create the directory, it had to have existed already
return false;
}
void FileCommit(FILE *file)
{
fflush(file); // harmless if redundantly called
#ifdef WIN32
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
FlushFileBuffers(hFile);
#else
#if defined(__linux__) || defined(__NetBSD__)
fdatasync(fileno(file));
#elif defined(__APPLE__) && defined(F_FULLFSYNC)
fcntl(fileno(file), F_FULLFSYNC, 0);
#else
fsync(fileno(file));
#endif
#endif
}
bool TruncateFile(FILE *file, unsigned int length) {
#if defined(WIN32)
return _chsize(_fileno(file), length) == 0;
#else
return ftruncate(fileno(file), length) == 0;
#endif
}
/**
* this function tries to raise the file descriptor limit to the requested number.
* It returns the actual file descriptor limit (which may be more or less than nMinFD)
*/
int RaiseFileDescriptorLimit(int nMinFD) {
#if defined(WIN32)
return 2048;
#else
struct rlimit limitFD;
if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
if (limitFD.rlim_cur < (rlim_t)nMinFD) {
limitFD.rlim_cur = nMinFD;
if (limitFD.rlim_cur > limitFD.rlim_max)
limitFD.rlim_cur = limitFD.rlim_max;
setrlimit(RLIMIT_NOFILE, &limitFD);
getrlimit(RLIMIT_NOFILE, &limitFD);
}
return limitFD.rlim_cur;
}
return nMinFD; // getrlimit failed, assume it's fine
#endif
}
/**
* this function tries to make a particular range of a file allocated (corresponding to disk space)
* it is advisory, and the range specified in the arguments will never contain live data
*/
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#if defined(WIN32)
// Windows-specific version
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
LARGE_INTEGER nFileSize;
int64_t nEndPos = (int64_t)offset + length;
nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
nFileSize.u.HighPart = nEndPos >> 32;
SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
SetEndOfFile(hFile);
#elif defined(MAC_OSX)
// OSX specific version
fstore_t fst;
fst.fst_flags = F_ALLOCATECONTIG;
fst.fst_posmode = F_PEOFPOSMODE;
fst.fst_offset = 0;
fst.fst_length = (off_t)offset + length;
fst.fst_bytesalloc = 0;
if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
fst.fst_flags = F_ALLOCATEALL;
fcntl(fileno(file), F_PREALLOCATE, &fst);
}
ftruncate(fileno(file), fst.fst_length);
#elif defined(__linux__)
// Version using posix_fallocate
off_t nEndPos = (off_t)offset + length;
posix_fallocate(fileno(file), 0, nEndPos);
#else
// Fallback version
// TODO: just write one byte per block
static const char buf[65536] = {};
fseek(file, offset, SEEK_SET);
while (length > 0) {
unsigned int now = 65536;
if (length < now)
now = length;
fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
length -= now;
}
#endif
}
void ShrinkDebugFile()
{
// Amount of debug.log to save at end when shrinking (must fit in memory)
constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
// Scroll debug.log if it's getting too big
fs::path pathLog = GetDataDir() / "debug.log";
FILE* file = fsbridge::fopen(pathLog, "r");
// If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
// trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
if (file && fs::file_size(pathLog) > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
{
// Restart the file with some of the end
std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
fseek(file, -((long)vch.size()), SEEK_END);
int nBytes = fread(vch.data(), 1, vch.size(), file);
fclose(file);
file = fsbridge::fopen(pathLog, "w");
if (file)
{
fwrite(vch.data(), 1, nBytes, file);
fclose(file);
}
}
else if (file != nullptr)
fclose(file);
}
#ifdef WIN32
fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(nullptr, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(const std::string& strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX)
pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
void SetupEnvironment()
{
#ifdef HAVE_MALLOPT_ARENA_MAX
// glibc-specific: On 32-bit systems set the number of arenas to 1.
// By default, since glibc 2.10, the C library will create up to two heap
// arenas per core. This is known to cause excessive virtual address space
// usage in our usage. Work around it by setting the maximum number of
// arenas to 1.
if (sizeof(void*) == 4) {
mallopt(M_ARENA_MAX, 1);
}
#endif
// On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
// may be invalid, in which case the "C" locale is used as fallback.
#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
try {
std::locale(""); // Raises a runtime error if current locale is invalid
} catch (const std::runtime_error&) {
setenv("LC_ALL", "C", 1);
}
#endif
// The path locale is lazy initialized and to avoid deinitialization errors
// in multithreading environments, it is set explicitly by the main thread.
// A dummy locale is used to extract the internal default locale, used by
// fs::path, which is then used to explicitly imbue the path.
std::locale loc = fs::path::imbue(std::locale::classic());
fs::path::imbue(loc);
}
bool SetupNetworking()
{
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
return false;
#endif
return true;
}
int GetNumCores()
{
#if BOOST_VERSION >= 105600
return boost::thread::physical_concurrency();
#else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores
return boost::thread::hardware_concurrency();
#endif
}
std::string CopyrightHolders(const std::string& strPrefix)
{
std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
// Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("Bitcoin Core") == std::string::npos) {
std::string strYear = strPrefix;
strYear.replace(strYear.find("2011"), sizeof("2011")-1, "2009");
strCopyrightHolders += "\n" + strYear + "The Bitcoin Core developers";
}
return strCopyrightHolders;
}
// Obtain the application startup time (used for uptime calculation)
int64_t GetStartupTime()
{
return nStartupTime;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
// return op that is the store equivalent of the given load opcode
genTreeOps storeForm(genTreeOps loadForm)
{
switch (loadForm)
{
case GT_LCL_VAR:
return GT_STORE_LCL_VAR;
case GT_LCL_FLD:
return GT_STORE_LCL_FLD;
default:
noway_assert(!"not a data load opcode\n");
unreached();
}
}
// return op that is the addr equivalent of the given load opcode
genTreeOps addrForm(genTreeOps loadForm)
{
switch (loadForm)
{
case GT_LCL_VAR:
return GT_LCL_VAR_ADDR;
case GT_LCL_FLD:
return GT_LCL_FLD_ADDR;
default:
noway_assert(!"not a data load opcode\n");
unreached();
}
}
// return op that is the load equivalent of the given addr opcode
genTreeOps loadForm(genTreeOps addrForm)
{
switch (addrForm)
{
case GT_LCL_VAR_ADDR:
return GT_LCL_VAR;
case GT_LCL_FLD_ADDR:
return GT_LCL_FLD;
default:
noway_assert(!"not a local address opcode\n");
unreached();
}
}
// copy the flags determined by mask from src to dst
void copyFlags(GenTree* dst, GenTree* src, unsigned mask)
{
dst->gtFlags &= ~mask;
dst->gtFlags |= (src->gtFlags & mask);
}
// Rewrite a SIMD indirection as GT_IND(GT_LEA(obj.op1)), or as a simple
// lclVar if possible.
//
// Arguments:
// use - A use reference for a block node
// keepBlk - True if this should remain a block node if it is not a lclVar
//
// Return Value:
// None.
//
// TODO-1stClassStructs: These should be eliminated earlier, once we can handle
// lclVars in all the places that used to have GT_OBJ.
//
void Rationalizer::RewriteSIMDOperand(LIR::Use& use, bool keepBlk)
{
#ifdef FEATURE_SIMD
// No lowering is needed for non-SIMD nodes, so early out if SIMD types are not supported.
if (!comp->supportSIMDTypes())
{
return;
}
GenTree* tree = use.Def();
if (!tree->OperIsIndir())
{
return;
}
var_types simdType = tree->TypeGet();
if (!varTypeIsSIMD(simdType))
{
return;
}
// If we have GT_IND(GT_LCL_VAR_ADDR) and the GT_LCL_VAR_ADDR is TYP_BYREF/TYP_I_IMPL,
// and the var is a SIMD type, replace the expression by GT_LCL_VAR.
GenTree* addr = tree->AsIndir()->Addr();
if (addr->OperIsLocalAddr() && comp->isAddrOfSIMDType(addr))
{
BlockRange().Remove(tree);
addr->SetOper(loadForm(addr->OperGet()));
addr->gtType = simdType;
use.ReplaceWith(comp, addr);
}
else if ((addr->OperGet() == GT_ADDR) && (addr->gtGetOp1()->OperIsSimdOrHWintrinsic()))
{
// if we have GT_IND(GT_ADDR(GT_SIMD)), remove the GT_IND(GT_ADDR()), leaving just the GT_SIMD.
BlockRange().Remove(tree);
BlockRange().Remove(addr);
use.ReplaceWith(comp, addr->gtGetOp1());
}
else if (!keepBlk)
{
tree->SetOper(GT_IND);
tree->gtType = simdType;
}
#endif // FEATURE_SIMD
}
// RewriteNodeAsCall : Replace the given tree node by a GT_CALL.
//
// Arguments:
// ppTree - A pointer-to-a-pointer for the tree node
// fgWalkData - A pointer to tree walk data providing the context
// callHnd - The method handle of the call to be generated
// entryPoint - The method entrypoint of the call to be generated
// args - The argument list of the call to be generated
//
// Return Value:
// None.
//
void Rationalizer::RewriteNodeAsCall(GenTree** use,
ArrayStack<GenTree*>& parents,
CORINFO_METHOD_HANDLE callHnd,
#ifdef FEATURE_READYTORUN_COMPILER
CORINFO_CONST_LOOKUP entryPoint,
#endif
GenTreeArgList* args)
{
GenTree* const tree = *use;
GenTree* const treeFirstNode = comp->fgGetFirstNode(tree);
GenTree* const insertionPoint = treeFirstNode->gtPrev;
BlockRange().Remove(treeFirstNode, tree);
// Create the call node
GenTreeCall* call = comp->gtNewCallNode(CT_USER_FUNC, callHnd, tree->gtType, args);
#if DEBUG
CORINFO_SIG_INFO sig;
comp->eeGetMethodSig(callHnd, &sig);
assert(JITtype2varType(sig.retType) == tree->gtType);
#endif // DEBUG
#ifdef FEATURE_READYTORUN_COMPILER
call->gtCall.setEntryPoint(entryPoint);
#endif
call = comp->fgMorphArgs(call);
// Replace "tree" with "call"
if (parents.Height() > 1)
{
parents.Index(1)->ReplaceOperand(use, call);
}
else
{
// If there's no parent, the tree being replaced is the root of the
// statement (and no special handling is necessary).
*use = call;
}
comp->gtSetEvalOrder(call);
BlockRange().InsertAfter(insertionPoint, LIR::Range(comp->fgSetTreeSeq(call), call));
// Propagate flags of "call" to its parents.
// 0 is current node, so start at 1
for (int i = 1; i < parents.Height(); i++)
{
parents.Index(i)->gtFlags |= (call->gtFlags & GTF_ALL_EFFECT) | GTF_CALL;
}
// Since "tree" is replaced with "call", pop "tree" node (i.e the current node)
// and replace it with "call" on parent stack.
assert(parents.Top() == tree);
(void)parents.Pop();
parents.Push(call);
}
// RewriteIntrinsicAsUserCall : Rewrite an intrinsic operator as a GT_CALL to the original method.
//
// Arguments:
// ppTree - A pointer-to-a-pointer for the intrinsic node
// fgWalkData - A pointer to tree walk data providing the context
//
// Return Value:
// None.
//
// Some intrinsics, such as operation Sqrt, are rewritten back to calls, and some are not.
// The ones that are not being rewritten here must be handled in Codegen.
// Conceptually, the lower is the right place to do the rewrite. Keeping it in rationalization is
// mainly for throughput issue.
void Rationalizer::RewriteIntrinsicAsUserCall(GenTree** use, ArrayStack<GenTree*>& parents)
{
GenTreeIntrinsic* intrinsic = (*use)->AsIntrinsic();
GenTreeArgList* args;
if (intrinsic->gtOp.gtOp2 == nullptr)
{
args = comp->gtNewArgList(intrinsic->gtGetOp1());
}
else
{
args = comp->gtNewArgList(intrinsic->gtGetOp1(), intrinsic->gtGetOp2());
}
RewriteNodeAsCall(use, parents, intrinsic->gtMethodHandle,
#ifdef FEATURE_READYTORUN_COMPILER
intrinsic->gtEntryPoint,
#endif
args);
}
#ifdef DEBUG
void Rationalizer::ValidateStatement(GenTreeStmt* stmt, BasicBlock* block)
{
DBEXEC(TRUE, JitTls::GetCompiler()->fgDebugCheckNodeLinks(block, stmt));
}
// sanity checks that apply to all kinds of IR
void Rationalizer::SanityCheck()
{
// TODO: assert(!IsLIR());
BasicBlock* block;
foreach_block(comp, block)
{
for (GenTreeStmt* statement = block->firstStmt(); statement != nullptr; statement = statement->getNextStmt())
{
ValidateStatement(statement, block);
for (GenTree* tree = statement->gtStmtList; tree; tree = tree->gtNext)
{
// QMARK nodes should have been removed before this phase.
assert(tree->OperGet() != GT_QMARK);
if (tree->OperGet() == GT_ASG)
{
if (tree->gtGetOp1()->OperGet() == GT_LCL_VAR)
{
assert(tree->gtGetOp1()->gtFlags & GTF_VAR_DEF);
}
else if (tree->gtGetOp2()->OperGet() == GT_LCL_VAR)
{
assert(!(tree->gtGetOp2()->gtFlags & GTF_VAR_DEF));
}
}
}
}
}
}
void Rationalizer::SanityCheckRational()
{
// TODO-Cleanup : check that the tree is rational here
// then do normal checks
SanityCheck();
}
#endif // DEBUG
static void RewriteAssignmentIntoStoreLclCore(GenTreeOp* assignment,
GenTree* location,
GenTree* value,
genTreeOps locationOp)
{
assert(assignment != nullptr);
assert(assignment->OperGet() == GT_ASG);
assert(location != nullptr);
assert(value != nullptr);
genTreeOps storeOp = storeForm(locationOp);
#ifdef DEBUG
JITDUMP("rewriting asg(%s, X) to %s(X)\n", GenTree::OpName(locationOp), GenTree::OpName(storeOp));
#endif // DEBUG
assignment->SetOper(storeOp);
GenTreeLclVarCommon* store = assignment->AsLclVarCommon();
GenTreeLclVarCommon* var = location->AsLclVarCommon();
store->SetLclNum(var->gtLclNum);
store->SetSsaNum(var->gtSsaNum);
if (locationOp == GT_LCL_FLD)
{
store->gtLclFld.gtLclOffs = var->gtLclFld.gtLclOffs;
store->gtLclFld.gtFieldSeq = var->gtLclFld.gtFieldSeq;
}
copyFlags(store, var, GTF_LIVENESS_MASK);
store->gtFlags &= ~GTF_REVERSE_OPS;
store->gtType = var->TypeGet();
store->gtOp1 = value;
DISPNODE(store);
JITDUMP("\n");
}
void Rationalizer::RewriteAssignmentIntoStoreLcl(GenTreeOp* assignment)
{
assert(assignment != nullptr);
assert(assignment->OperGet() == GT_ASG);
GenTree* location = assignment->gtGetOp1();
GenTree* value = assignment->gtGetOp2();
RewriteAssignmentIntoStoreLclCore(assignment, location, value, location->OperGet());
}
void Rationalizer::RewriteAssignment(LIR::Use& use)
{
assert(use.IsInitialized());
GenTreeOp* assignment = use.Def()->AsOp();
assert(assignment->OperGet() == GT_ASG);
GenTree* location = assignment->gtGetOp1();
GenTree* value = assignment->gtGetOp2();
genTreeOps locationOp = location->OperGet();
if (assignment->OperIsBlkOp())
{
#ifdef FEATURE_SIMD
if (varTypeIsSIMD(location) && assignment->OperIsInitBlkOp())
{
if (location->OperGet() == GT_LCL_VAR)
{
var_types simdType = location->TypeGet();
GenTree* initVal = assignment->gtOp.gtOp2;
var_types baseType = comp->getBaseTypeOfSIMDLocal(location);
if (baseType != TYP_UNKNOWN)
{
GenTreeSIMD* simdTree = new (comp, GT_SIMD)
GenTreeSIMD(simdType, initVal, SIMDIntrinsicInit, baseType, genTypeSize(simdType));
assignment->gtOp.gtOp2 = simdTree;
value = simdTree;
initVal->gtNext = simdTree;
simdTree->gtPrev = initVal;
simdTree->gtNext = location;
location->gtPrev = simdTree;
}
}
}
#endif // FEATURE_SIMD
if ((location->TypeGet() == TYP_STRUCT) && !assignment->IsPhiDefn() && !value->IsMultiRegCall())
{
if ((location->OperGet() == GT_LCL_VAR))
{
// We need to construct a block node for the location.
// Modify lcl to be the address form.
location->SetOper(addrForm(locationOp));
LclVarDsc* varDsc = &(comp->lvaTable[location->AsLclVarCommon()->gtLclNum]);
location->gtType = TYP_BYREF;
GenTreeBlk* storeBlk = nullptr;
unsigned int size = varDsc->lvExactSize;
if (varDsc->lvStructGcCount != 0)
{
CORINFO_CLASS_HANDLE structHnd = varDsc->lvVerTypeInfo.GetClassHandle();
GenTreeObj* objNode = comp->gtNewObjNode(structHnd, location)->AsObj();
unsigned int slots = roundUp(size, TARGET_POINTER_SIZE) / TARGET_POINTER_SIZE;
objNode->SetGCInfo(varDsc->lvGcLayout, varDsc->lvStructGcCount, slots);
objNode->ChangeOper(GT_STORE_OBJ);
objNode->SetData(value);
comp->fgMorphUnsafeBlk(objNode);
storeBlk = objNode;
}
else
{
storeBlk = new (comp, GT_STORE_BLK) GenTreeBlk(GT_STORE_BLK, TYP_STRUCT, location, value, size);
}
storeBlk->gtFlags |= GTF_ASG;
storeBlk->gtFlags |= ((location->gtFlags | value->gtFlags) & GTF_ALL_EFFECT);
GenTree* insertionPoint = location->gtNext;
BlockRange().InsertBefore(insertionPoint, storeBlk);
use.ReplaceWith(comp, storeBlk);
BlockRange().Remove(assignment);
JITDUMP("After transforming local struct assignment into a block op:\n");
DISPTREERANGE(BlockRange(), use.Def());
JITDUMP("\n");
return;
}
else
{
assert(location->OperIsBlk());
}
}
}
switch (locationOp)
{
case GT_LCL_VAR:
case GT_LCL_FLD:
case GT_PHI_ARG:
RewriteAssignmentIntoStoreLclCore(assignment, location, value, locationOp);
BlockRange().Remove(location);
break;
case GT_IND:
{
GenTreeStoreInd* store =
new (comp, GT_STOREIND) GenTreeStoreInd(location->TypeGet(), location->gtGetOp1(), value);
copyFlags(store, assignment, GTF_ALL_EFFECT);
copyFlags(store, location, GTF_IND_FLAGS);
// TODO: JIT dump
// Remove the GT_IND node and replace the assignment node with the store
BlockRange().Remove(location);
BlockRange().InsertBefore(assignment, store);
use.ReplaceWith(comp, store);
BlockRange().Remove(assignment);
}
break;
case GT_CLS_VAR:
{
location->SetOper(GT_CLS_VAR_ADDR);
location->gtType = TYP_BYREF;
assignment->SetOper(GT_STOREIND);
assignment->AsStoreInd()->SetRMWStatusDefault();
// TODO: JIT dump
}
break;
case GT_BLK:
case GT_OBJ:
case GT_DYN_BLK:
{
assert(varTypeIsStruct(location));
GenTreeBlk* storeBlk = location->AsBlk();
genTreeOps storeOper;
switch (location->gtOper)
{
case GT_BLK:
storeOper = GT_STORE_BLK;
break;
case GT_OBJ:
storeOper = GT_STORE_OBJ;
break;
case GT_DYN_BLK:
storeOper = GT_STORE_DYN_BLK;
storeBlk->AsDynBlk()->gtEvalSizeFirst = false;
break;
default:
unreached();
}
JITDUMP("Rewriting GT_ASG(%s(X), Y) to %s(X,Y):\n", GenTree::OpName(location->gtOper),
GenTree::OpName(storeOper));
storeBlk->SetOperRaw(storeOper);
storeBlk->gtFlags &= ~GTF_DONT_CSE;
storeBlk->gtFlags |=
(assignment->gtFlags & (GTF_ALL_EFFECT | GTF_BLK_VOLATILE | GTF_BLK_UNALIGNED | GTF_DONT_CSE));
storeBlk->gtBlk.Data() = value;
// Remove the block node from its current position and replace the assignment node with it
// (now in its store form).
BlockRange().Remove(storeBlk);
BlockRange().InsertBefore(assignment, storeBlk);
use.ReplaceWith(comp, storeBlk);
BlockRange().Remove(assignment);
DISPTREERANGE(BlockRange(), use.Def());
JITDUMP("\n");
}
break;
default:
unreached();
break;
}
}
void Rationalizer::RewriteAddress(LIR::Use& use)
{
assert(use.IsInitialized());
GenTreeUnOp* address = use.Def()->AsUnOp();
assert(address->OperGet() == GT_ADDR);
GenTree* location = address->gtGetOp1();
genTreeOps locationOp = location->OperGet();
if (location->IsLocal())
{
// We are changing the child from GT_LCL_VAR TO GT_LCL_VAR_ADDR.
// Therefore gtType of the child needs to be changed to a TYP_BYREF
#ifdef DEBUG
if (locationOp == GT_LCL_VAR)
{
JITDUMP("Rewriting GT_ADDR(GT_LCL_VAR) to GT_LCL_VAR_ADDR:\n");
}
else
{
assert(locationOp == GT_LCL_FLD);
JITDUMP("Rewriting GT_ADDR(GT_LCL_FLD) to GT_LCL_FLD_ADDR:\n");
}
#endif // DEBUG
location->SetOper(addrForm(locationOp));
location->gtType = TYP_BYREF;
copyFlags(location, address, GTF_ALL_EFFECT);
use.ReplaceWith(comp, location);
BlockRange().Remove(address);
}
else if (locationOp == GT_CLS_VAR)
{
location->SetOper(GT_CLS_VAR_ADDR);
location->gtType = TYP_BYREF;
copyFlags(location, address, GTF_ALL_EFFECT);
use.ReplaceWith(comp, location);
BlockRange().Remove(address);
JITDUMP("Rewriting GT_ADDR(GT_CLS_VAR) to GT_CLS_VAR_ADDR:\n");
}
else if (location->OperIsIndir())
{
use.ReplaceWith(comp, location->gtGetOp1());
BlockRange().Remove(location);
BlockRange().Remove(address);
JITDUMP("Rewriting GT_ADDR(GT_IND(X)) to X:\n");
}
DISPTREERANGE(BlockRange(), use.Def());
JITDUMP("\n");
}
Compiler::fgWalkResult Rationalizer::RewriteNode(GenTree** useEdge, Compiler::GenTreeStack& parentStack)
{
assert(useEdge != nullptr);
GenTree* node = *useEdge;
assert(node != nullptr);
#ifdef DEBUG
const bool isLateArg = (node->gtFlags & GTF_LATE_ARG) != 0;
#endif
// First, remove any preceeding list nodes, which are not otherwise visited by the tree walk.
//
// NOTE: GT_FIELD_LIST head nodes, and GT_LIST nodes used by phi nodes will in fact be visited.
for (GenTree* prev = node->gtPrev; prev != nullptr && prev->OperIsAnyList() && !(prev->OperIsFieldListHead());
prev = node->gtPrev)
{
prev->gtFlags &= ~GTF_REVERSE_OPS;
BlockRange().Remove(prev);
}
// Now clear the REVERSE_OPS flag on the current node.
node->gtFlags &= ~GTF_REVERSE_OPS;
// In addition, remove the current node if it is a GT_LIST node that is not an aggregate.
if (node->OperIsAnyList())
{
GenTreeArgList* list = node->AsArgList();
if (!list->OperIsFieldListHead())
{
BlockRange().Remove(list);
}
return Compiler::WALK_CONTINUE;
}
LIR::Use use;
if (parentStack.Height() < 2)
{
use = LIR::Use::GetDummyUse(BlockRange(), *useEdge);
}
else
{
use = LIR::Use(BlockRange(), useEdge, parentStack.Index(1));
}
assert(node == use.Def());
switch (node->OperGet())
{
case GT_ASG:
RewriteAssignment(use);
break;
case GT_BOX:
// GT_BOX at this level just passes through so get rid of it
use.ReplaceWith(comp, node->gtGetOp1());
BlockRange().Remove(node);
break;
case GT_ADDR:
RewriteAddress(use);
break;
case GT_IND:
// Clear the `GTF_IND_ASG_LHS` flag, which overlaps with `GTF_IND_REQ_ADDR_IN_REG`.
node->gtFlags &= ~GTF_IND_ASG_LHS;
if (varTypeIsSIMD(node))
{
RewriteSIMDOperand(use, false);
}
else
{
// Due to promotion of structs containing fields of type struct with a
// single scalar type field, we could potentially see IR nodes of the
// form GT_IND(GT_ADD(lclvarAddr, 0)) where 0 is an offset representing
// a field-seq. These get folded here.
//
// TODO: This code can be removed once JIT implements recursive struct
// promotion instead of lying about the type of struct field as the type
// of its single scalar field.
GenTree* addr = node->AsIndir()->Addr();
if (addr->OperGet() == GT_ADD && addr->gtGetOp1()->OperGet() == GT_LCL_VAR_ADDR &&
addr->gtGetOp2()->IsIntegralConst(0))
{
GenTreeLclVarCommon* lclVarNode = addr->gtGetOp1()->AsLclVarCommon();
unsigned lclNum = lclVarNode->GetLclNum();
LclVarDsc* varDsc = comp->lvaTable + lclNum;
if (node->TypeGet() == varDsc->TypeGet())
{
JITDUMP("Rewriting GT_IND(GT_ADD(LCL_VAR_ADDR,0)) to LCL_VAR\n");
lclVarNode->SetOper(GT_LCL_VAR);
lclVarNode->gtType = node->TypeGet();
use.ReplaceWith(comp, lclVarNode);
BlockRange().Remove(addr);
BlockRange().Remove(addr->gtGetOp2());
BlockRange().Remove(node);
}
}
}
break;
case GT_NOP:
// fgMorph sometimes inserts NOP nodes between defs and uses
// supposedly 'to prevent constant folding'. In this case, remove the
// NOP.
if (node->gtGetOp1() != nullptr)
{
use.ReplaceWith(comp, node->gtGetOp1());
BlockRange().Remove(node);
node = node->gtGetOp1();
}
break;
case GT_COMMA:
{
GenTree* op1 = node->gtGetOp1();
bool isClosed = false;
unsigned sideEffects = 0;
LIR::ReadOnlyRange lhsRange = BlockRange().GetTreeRange(op1, &isClosed, &sideEffects);
if ((sideEffects & GTF_ALL_EFFECT) == 0)
{
// The LHS has no side effects. Remove it.
// None of the transforms performed herein violate tree order, so isClosed
// should always be true.
assert(isClosed);
BlockRange().Delete(comp, m_block, std::move(lhsRange));
}
else if (op1->IsValue())
{
op1->SetUnusedValue();
}
BlockRange().Remove(node);
GenTree* replacement = node->gtGetOp2();
if (!use.IsDummyUse())
{
use.ReplaceWith(comp, replacement);
node = replacement;
}
else
{
// This is a top-level comma. If the RHS has no side effects we can remove
// it as well.
bool isClosed = false;
unsigned sideEffects = 0;
LIR::ReadOnlyRange rhsRange = BlockRange().GetTreeRange(replacement, &isClosed, &sideEffects);
if ((sideEffects & GTF_ALL_EFFECT) == 0)
{
// None of the transforms performed herein violate tree order, so isClosed
// should always be true.
assert(isClosed);
BlockRange().Delete(comp, m_block, std::move(rhsRange));
}
else
{
node = replacement;
}
}
}
break;
case GT_ARGPLACE:
// Remove argplace and list nodes from the execution order.
//
// TODO: remove phi args and phi nodes as well?
BlockRange().Remove(node);
break;
#if defined(_TARGET_XARCH_) || defined(_TARGET_ARM_)
case GT_CLS_VAR:
{
// Class vars that are the target of an assignment will get rewritten into
// GT_STOREIND(GT_CLS_VAR_ADDR, val) by RewriteAssignment. This check is
// not strictly necessary--the GT_IND(GT_CLS_VAR_ADDR) pattern that would
// otherwise be generated would also be picked up by RewriteAssignment--but
// skipping the rewrite here saves an allocation and a bit of extra work.
const bool isLHSOfAssignment = (use.User()->OperGet() == GT_ASG) && (use.User()->gtGetOp1() == node);
if (!isLHSOfAssignment)
{
GenTree* ind = comp->gtNewOperNode(GT_IND, node->TypeGet(), node);
node->SetOper(GT_CLS_VAR_ADDR);
node->gtType = TYP_BYREF;
BlockRange().InsertAfter(node, ind);
use.ReplaceWith(comp, ind);
// TODO: JIT dump
}
}
break;
#endif // _TARGET_XARCH_
case GT_INTRINSIC:
// Non-target intrinsics should have already been rewritten back into user calls.
assert(comp->IsTargetIntrinsic(node->gtIntrinsic.gtIntrinsicId));
break;
case GT_BLK:
// We should only see GT_BLK for TYP_STRUCT or for InitBlocks.
assert((node->TypeGet() == TYP_STRUCT) || use.User()->OperIsInitBlkOp());
break;
case GT_OBJ:
assert(node->TypeGet() == TYP_STRUCT || !use.User()->OperIsInitBlkOp());
if (varTypeIsSIMD(node))
{
// Rewrite these as GT_IND.
RewriteSIMDOperand(use, false);
}
break;
#ifdef FEATURE_SIMD
case GT_SIMD:
{
noway_assert(comp->supportSIMDTypes());
GenTreeSIMD* simdNode = node->AsSIMD();
unsigned simdSize = simdNode->gtSIMDSize;
var_types simdType = comp->getSIMDTypeForSize(simdSize);
// TODO-1stClassStructs: This should be handled more generally for enregistered or promoted
// structs that are passed or returned in a different register type than their enregistered
// type(s).
if (simdNode->gtType == TYP_I_IMPL && simdNode->gtSIMDSize == TARGET_POINTER_SIZE)
{
// This happens when it is consumed by a GT_RET_EXPR.
// It can only be a Vector2f or Vector2i.
assert(genTypeSize(simdNode->gtSIMDBaseType) == 4);
simdNode->gtType = TYP_SIMD8;
}
// Certain SIMD trees require rationalizing.
if (simdNode->gtSIMD.gtSIMDIntrinsicID == SIMDIntrinsicInitArray)
{
// Rewrite this as an explicit load.
JITDUMP("Rewriting GT_SIMD array init as an explicit load:\n");
unsigned int baseTypeSize = genTypeSize(simdNode->gtSIMDBaseType);
GenTree* address = new (comp, GT_LEA) GenTreeAddrMode(TYP_BYREF, simdNode->gtOp1, simdNode->gtOp2,
baseTypeSize, OFFSETOF__CORINFO_Array__data);
GenTree* ind = comp->gtNewOperNode(GT_IND, simdType, address);
BlockRange().InsertBefore(simdNode, address, ind);
use.ReplaceWith(comp, ind);
BlockRange().Remove(simdNode);
DISPTREERANGE(BlockRange(), use.Def());
JITDUMP("\n");
}
else
{
// This code depends on the fact that NONE of the SIMD intrinsics take vector operands
// of a different width. If that assumption changes, we will EITHER have to make these type
// transformations during importation, and plumb the types all the way through the JIT,
// OR add a lot of special handling here.
GenTree* op1 = simdNode->gtGetOp1();
if (op1 != nullptr && op1->gtType == TYP_STRUCT)
{
op1->gtType = simdType;
}
GenTree* op2 = simdNode->gtGetOp2IfPresent();
if (op2 != nullptr && op2->gtType == TYP_STRUCT)
{
op2->gtType = simdType;
}
}
}
break;
#endif // FEATURE_SIMD
default:
// These nodes should not be present in HIR.
assert(!node->OperIs(GT_CMP, GT_SETCC, GT_JCC, GT_JCMP, GT_LOCKADD));
break;
}
// Do some extra processing on top-level nodes to remove unused local reads.
if (node->OperIsLocalRead())
{
if (use.IsDummyUse())
{
BlockRange().Remove(node);
}
else
{
// Local reads are side-effect-free; clear any flags leftover from frontend transformations.
node->gtFlags &= ~GTF_ALL_EFFECT;
}
}
else
{
if (!node->OperIsStore())
{
// Clear the GTF_ASG flag for all nodes but stores
node->gtFlags &= ~GTF_ASG;
}
if (!node->IsCall())
{
// Clear the GTF_CALL flag for all nodes but calls
node->gtFlags &= ~GTF_CALL;
}
if (node->IsValue() && use.IsDummyUse())
{
node->SetUnusedValue();
}
if (node->TypeGet() == TYP_LONG)
{
comp->compLongUsed = true;
}
}
assert(isLateArg == ((use.Def()->gtFlags & GTF_LATE_ARG) != 0));
return Compiler::WALK_CONTINUE;
}
void Rationalizer::DoPhase()
{
class RationalizeVisitor final : public GenTreeVisitor<RationalizeVisitor>
{
Rationalizer& m_rationalizer;
public:
enum
{
ComputeStack = true,
DoPreOrder = true,
DoPostOrder = true,
UseExecutionOrder = true,
};
RationalizeVisitor(Rationalizer& rationalizer)
: GenTreeVisitor<RationalizeVisitor>(rationalizer.comp), m_rationalizer(rationalizer)
{
}
// Rewrite intrinsics that are not supported by the target back into user calls.
// This needs to be done before the transition to LIR because it relies on the use
// of fgMorphArgs, which is designed to operate on HIR. Once this is done for a
// particular statement, link that statement's nodes into the current basic block.
fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
{
GenTree* const node = *use;
if (node->OperGet() == GT_INTRINSIC &&
m_rationalizer.comp->IsIntrinsicImplementedByUserCall(node->gtIntrinsic.gtIntrinsicId))
{
m_rationalizer.RewriteIntrinsicAsUserCall(use, this->m_ancestors);
}
return Compiler::WALK_CONTINUE;
}
// Rewrite HIR nodes into LIR nodes.
fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
{
return m_rationalizer.RewriteNode(use, this->m_ancestors);
}
};
DBEXEC(TRUE, SanityCheck());
comp->compCurBB = nullptr;
comp->fgOrder = Compiler::FGOrderLinear;
RationalizeVisitor visitor(*this);
for (BasicBlock* block = comp->fgFirstBB; block != nullptr; block = block->bbNext)
{
comp->compCurBB = block;
m_block = block;
block->MakeLIR(nullptr, nullptr);
// Establish the first and last nodes for the block. This is necessary in order for the LIR
// utilities that hang off the BasicBlock type to work correctly.
GenTreeStmt* firstStatement = block->firstStmt();
if (firstStatement == nullptr)
{
// No statements in this block; skip it.
continue;
}
for (GenTreeStmt* statement = firstStatement; statement != nullptr; statement = statement->getNextStmt())
{
assert(statement->gtStmtList != nullptr);
assert(statement->gtStmtList->gtPrev == nullptr);
assert(statement->gtStmtExpr != nullptr);
assert(statement->gtStmtExpr->gtNext == nullptr);
BlockRange().InsertAtEnd(LIR::Range(statement->gtStmtList, statement->gtStmtExpr));
// If this statement has correct offset information, change it into an IL offset
// node and insert it into the LIR.
if (statement->gtStmtILoffsx != BAD_IL_OFFSET)
{
assert(!statement->IsPhiDefnStmt());
GenTreeILOffset* ilOffset = new (comp, GT_IL_OFFSET) GenTreeILOffset(statement->gtStmtILoffsx);
BlockRange().InsertBefore(statement->gtStmtList, ilOffset);
}
m_block = block;
visitor.WalkTree(&statement->gtStmtExpr, nullptr);
}
block->bbStmtList = nullptr;
assert(BlockRange().CheckLIR(comp, true));
}
comp->compRationalIRForm = true;
}
|
/*
Copyright (C) 2008 Grame & RTL
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "JackEngineProfiling.h"
#include "JackGraphManager.h"
#include "JackClientControl.h"
#include "JackEngineControl.h"
#include "JackClientInterface.h"
#include "JackGlobals.h"
#include "JackTime.h"
#include <iostream>
#include <fstream>
namespace Jack
{
JackEngineProfiling::JackEngineProfiling():fAudioCycle(0),fMeasuredClient(0)
{
jack_info("Engine profiling activated, beware %ld MBytes are needed to record profiling points...", sizeof(fProfileTable) / (1024 * 1024));
// Force memory page in
memset(fProfileTable, 0, sizeof(fProfileTable));
}
JackEngineProfiling::~JackEngineProfiling()
{
std::ofstream fStream("JackEngineProfiling.log", std::ios_base::ate);
jack_info("Write server and clients timing data...");
if (!fStream.is_open()) {
jack_error("JackEngineProfiling::Save cannot open JackEngineProfiling.log file");
} else {
// For each measured point
for (int i = 2; i < TIME_POINTS; i++) {
// Driver timing values
long d1 = long(fProfileTable[i].fCurCycleBegin - fProfileTable[i - 1].fCurCycleBegin);
long d2 = long(fProfileTable[i].fPrevCycleEnd - fProfileTable[i - 1].fCurCycleBegin);
if (d1 <= 0 || fProfileTable[i].fAudioCycle <= 0)
continue; // Skip non valid cycles
// Print driver delta and end cycle
fStream << d1 << "\t" << d2 << "\t";
// For each measured client
for (unsigned int j = 0; j < fMeasuredClient; j++) {
int ref = fIntervalTable[j].fRefNum;
// Is valid client cycle
if (fProfileTable[i].fClientTable[ref].fStatus != NotTriggered) {
long d5 = long(fProfileTable[i].fClientTable[ref].fSignaledAt - fProfileTable[i - 1].fCurCycleBegin);
long d6 = long(fProfileTable[i].fClientTable[ref].fAwakeAt - fProfileTable[i - 1].fCurCycleBegin);
long d7 = long(fProfileTable[i].fClientTable[ref].fFinishedAt - fProfileTable[i - 1].fCurCycleBegin);
fStream << ref << "\t" ;
fStream << ((d5 > 0) ? d5 : 0) << "\t";
fStream << ((d6 > 0) ? d6 : 0) << "\t" ;
fStream << ((d7 > 0) ? d7 : 0) << "\t";
fStream << ((d6 > 0 && d5 > 0) ? (d6 - d5) : 0) << "\t" ;
fStream << ((d7 > 0 && d6 > 0) ? (d7 - d6) : 0) << "\t" ;
fStream << fProfileTable[i].fClientTable[ref].fStatus << "\t" ;;
} else { // Print tabs
fStream << "\t \t \t \t \t \t \t";
}
}
// Terminate line
fStream << std::endl;
}
}
// Driver period
std::ofstream fStream1("Timing1.plot", std::ios_base::ate);
if (!fStream1.is_open()) {
jack_error("JackEngineProfiling::Save cannot open Timing1.plot file");
} else {
fStream1 << "set grid\n";
fStream1 << "set title \"Audio driver timing\"\n";
fStream1 << "set xlabel \"audio cycles\"\n";
fStream1 << "set ylabel \"usec\"\n";
fStream1 << "plot \"JackEngineProfiling.log\" using 1 title \"Audio period\" with lines \n";
fStream1 << "set output 'Timing1.svg\n";
fStream1 << "set terminal svg\n";
fStream1 << "set grid\n";
fStream1 << "set title \"Audio driver timing\"\n";
fStream1 << "set xlabel \"audio cycles\"\n";
fStream1 << "set ylabel \"usec\"\n";
fStream1 << "plot \"JackEngineProfiling.log\" using 1 title \"Audio period\" with lines \n";
fStream1 << "unset output\n";
}
// Driver end date
std::ofstream fStream2("Timing2.plot", std::ios_base::ate);
if (!fStream2.is_open()) {
jack_error("JackEngineProfiling::Save cannot open Timing2.plot file");
} else {
fStream2 << "set grid\n";
fStream2 << "set title \"Driver end date\"\n";
fStream2 << "set xlabel \"audio cycles\"\n";
fStream2 << "set ylabel \"usec\"\n";
fStream2 << "plot \"JackEngineProfiling.log\" using 2 title \"Driver end date\" with lines \n";
fStream2 << "set output 'Timing2.svg\n";
fStream2 << "set terminal svg\n";
fStream2 << "set grid\n";
fStream2 << "set title \"Driver end date\"\n";
fStream2 << "set xlabel \"audio cycles\"\n";
fStream2 << "set ylabel \"usec\"\n";
fStream2 << "plot \"JackEngineProfiling.log\" using 2 title \"Driver end date\" with lines \n";
fStream2 << "unset output\n";
}
// Clients end date
if (fMeasuredClient > 0) {
std::ofstream fStream3("Timing3.plot", std::ios_base::ate);
if (!fStream3.is_open()) {
jack_error("JackEngineProfiling::Save cannot open Timing3.plot file");
} else {
fStream3 << "set multiplot\n";
fStream3 << "set grid\n";
fStream3 << "set title \"Clients end date\"\n";
fStream3 << "set xlabel \"audio cycles\"\n";
fStream3 << "set ylabel \"usec\"\n";
fStream3 << "plot ";
for (unsigned int i = 0; i < fMeasuredClient; i++) {
if (i == 0) {
if (i + 1 == fMeasuredClient) { // Last client
fStream3 << "\"JackEngineProfiling.log\" using 1 title \"Audio period\" with lines,\"JackEngineProfiling.log\" using ";
fStream3 << ((i + 1) * 7) - 1;
fStream3 << " title \"" << fIntervalTable[i].fName << "\"with lines";
} else {
fStream3 << "\"JackEngineProfiling.log\" using 1 title \"Audio period\" with lines,\"JackEngineProfiling.log\" using ";
fStream3 << ((i + 1) * 7) - 1;
fStream3 << " title \"" << fIntervalTable[i].fName << "\"with lines,";
}
} else if (i + 1 == fMeasuredClient) { // Last client
fStream3 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) - 1 << " title \"" << fIntervalTable[i].fName << "\" with lines";
} else {
fStream3 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) - 1 << " title \"" << fIntervalTable[i].fName << "\" with lines,";
}
}
fStream3 << "\n unset multiplot\n";
fStream3 << "set output 'Timing3.svg\n";
fStream3 << "set terminal svg\n";
fStream3 << "set multiplot\n";
fStream3 << "set grid\n";
fStream3 << "set title \"Clients end date\"\n";
fStream3 << "set xlabel \"audio cycles\"\n";
fStream3 << "set ylabel \"usec\"\n";
fStream3 << "plot ";
for (unsigned int i = 0; i < fMeasuredClient; i++) {
if (i == 0) {
if ((i + 1) == fMeasuredClient) { // Last client
fStream3 << "\"JackEngineProfiling.log\" using 1 title \"Audio period\" with lines,\"JackEngineProfiling.log\" using ";
fStream3 << ((i + 1) * 7) - 1;
fStream3 << " title \"" << fIntervalTable[i].fName << "\"with lines";
} else {
fStream3 << "\"JackEngineProfiling.log\" using 1 title \"Audio period\" with lines,\"JackEngineProfiling.log\" using ";
fStream3 << ((i + 1) * 7) - 1;
fStream3 << " title \"" << fIntervalTable[i].fName << "\"with lines,";
}
} else if ((i + 1) == fMeasuredClient) { // Last client
fStream3 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) - 1 << " title \"" << fIntervalTable[i].fName << "\" with lines";
} else {
fStream3 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) - 1 << " title \"" << fIntervalTable[i].fName << "\" with lines,";
}
}
fStream3 << "\nunset multiplot\n";
fStream3 << "unset output\n";
}
}
// Clients scheduling
if (fMeasuredClient > 0) {
std::ofstream fStream4("Timing4.plot", std::ios_base::ate);
if (!fStream4.is_open()) {
jack_error("JackEngineProfiling::Save cannot open Timing4.plot file");
} else {
fStream4 << "set multiplot\n";
fStream4 << "set grid\n";
fStream4 << "set title \"Clients scheduling latency\"\n";
fStream4 << "set xlabel \"audio cycles\"\n";
fStream4 << "set ylabel \"usec\"\n";
fStream4 << "plot ";
for (unsigned int i = 0; i < fMeasuredClient; i++) {
if ((i + 1) == fMeasuredClient) { // Last client
fStream4 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) << " title \"" << fIntervalTable[i].fName << "\" with lines";
} else {
fStream4 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) << " title \"" << fIntervalTable[i].fName << "\" with lines,";
}
}
fStream4 << "\n unset multiplot\n";
fStream4 << "set output 'Timing4.svg\n";
fStream4 << "set terminal svg\n";
fStream4 << "set multiplot\n";
fStream4 << "set grid\n";
fStream4 << "set title \"Clients scheduling latency\"\n";
fStream4 << "set xlabel \"audio cycles\"\n";
fStream4 << "set ylabel \"usec\"\n";
fStream4 << "plot ";
for (unsigned int i = 0; i < fMeasuredClient; i++) {
if ((i + 1) == fMeasuredClient) { // Last client
fStream4 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) << " title \"" << fIntervalTable[i].fName << "\" with lines";
} else {
fStream4 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) << " title \"" << fIntervalTable[i].fName << "\" with lines,";
}
}
fStream4 << "\nunset multiplot\n";
fStream4 << "unset output\n";
}
}
// Clients duration
if (fMeasuredClient > 0) {
std::ofstream fStream5("Timing5.plot", std::ios_base::ate);
if (!fStream5.is_open()) {
jack_error("JackEngineProfiling::Save cannot open Timing5.plot file");
} else {
fStream5 << "set multiplot\n";
fStream5 << "set grid\n";
fStream5 << "set title \"Clients duration\"\n";
fStream5 << "set xlabel \"audio cycles\"\n";
fStream5 << "set ylabel \"usec\"\n";
fStream5 << "plot ";
for (unsigned int i = 0; i < fMeasuredClient; i++) {
if ((i + 1) == fMeasuredClient) { // Last client
fStream5 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) + 1 << " title \"" << fIntervalTable[i].fName << "\" with lines";
} else {
fStream5 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) + 1 << " title \"" << fIntervalTable[i].fName << "\" with lines,";
}
}
fStream5 << "\n unset multiplot\n";
fStream5 << "set output 'Timing5.svg\n";
fStream5 << "set terminal svg\n";
fStream5 << "set multiplot\n";
fStream5 << "set grid\n";
fStream5 << "set title \"Clients duration\"\n";
fStream5 << "set xlabel \"audio cycles\"\n";
fStream5 << "set ylabel \"usec\"\n";
fStream5 << "plot ";
for (unsigned int i = 0; i < fMeasuredClient; i++) {
if ((i + 1) == fMeasuredClient) {// Last client
fStream5 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) + 1 << " title \"" << fIntervalTable[i].fName << "\" with lines";
} else {
fStream5 << "\"JackEngineProfiling.log\" using " << ((i + 1) * 7) + 1 << " title \"" << fIntervalTable[i].fName << "\" with lines,";
}
}
fStream5 << "\nunset multiplot\n";
fStream5 << "unset output\n";
}
}
std::ofstream fStream6("Timings.html", std::ios_base::ate);
if (!fStream6.is_open()) {
jack_error("JackEngineProfiling::Save cannot open Timings.html file");
} else {
fStream6 << "<?xml version='1.0' encoding='utf-8'?>\n";
fStream6 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n";
fStream6 << "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
fStream6 << "<html xmlns='http://www.w3.org/1999/xhtml' lang='en'>\n";
fStream6 << " <head>\n";
fStream6 << " <title>JACK engine profiling</title>\n";
fStream6 << " <!-- assuming that images are 600px wide -->\n";
fStream6 << " <style media='all' type='text/css'>\n";
fStream6 << " .center { margin-left:auto ; margin-right: auto; width: 650px; height: 550px }\n";
fStream6 << " </style>\n";
fStream6 << " </head>\n";
fStream6 << " <body>\n";
fStream6 << " <h2 style='text-align:center'>JACK engine profiling</h2>\n";
fStream6 << " <div class='center'><object class='center' type='image/svg+xml' data='Timing1.svg'>Timing1</object></div>";
fStream6 << " <div class='center'><object class='center' type='image/svg+xml' data='Timing2.svg'>Timing2</object></div>";
fStream6 << " <div class='center'><object class='center' type='image/svg+xml' data='Timing3.svg'>Timing3</object></div>";
fStream6 << " <div class='center'><object class='center' type='image/svg+xml' data='Timing4.svg'>Timing4</object></div>";
fStream6 << " <div class='center'><object class='center' type='image/svg+xml' data='Timing5.svg'>Timing5</object></div>";
fStream6 << " </body>\n";
fStream6 << "</html>\n";
}
std::ofstream fStream7("generate_timings", std::ios_base::ate);
if (!fStream7.is_open()) {
jack_error("JackEngineProfiling::Save cannot open generate_timings file");
} else {
fStream7 << "gnuplot -persist Timing1.plot \n";
fStream7 << "gnuplot -persist Timing2.plot\n";
fStream7 << "gnuplot -persist Timing3.plot\n";
fStream7 << "gnuplot -persist Timing4.plot\n";
fStream7 << "gnuplot -persist Timing5.plot\n";
}
}
bool JackEngineProfiling::CheckClient(const char* name, int cur_point)
{
for (int i = 0; i < MEASURED_CLIENTS; i++) {
if (strcmp(fIntervalTable[i].fName, name) == 0) {
fIntervalTable[i].fEndInterval = cur_point;
return true;
}
}
return false;
}
void JackEngineProfiling::Profile(JackClientInterface** table,
JackGraphManager* manager,
jack_time_t period_usecs,
jack_time_t cur_cycle_begin,
jack_time_t prev_cycle_end)
{
fAudioCycle = (fAudioCycle + 1) % TIME_POINTS;
// Keeps cycle data
fProfileTable[fAudioCycle].fPeriodUsecs = period_usecs;
fProfileTable[fAudioCycle].fCurCycleBegin = cur_cycle_begin;
fProfileTable[fAudioCycle].fPrevCycleEnd = prev_cycle_end;
fProfileTable[fAudioCycle].fAudioCycle = fAudioCycle;
for (int i = GetEngineControl()->fDriverNum; i < CLIENT_NUM; i++) {
JackClientInterface* client = table[i];
JackClientTiming* timing = manager->GetClientTiming(i);
if (client && client->GetClientControl()->fActive && client->GetClientControl()->fCallback[kRealTimeCallback]) {
if (!CheckClient(client->GetClientControl()->fName, fAudioCycle)) {
// Keep new measured client
fIntervalTable[fMeasuredClient].fRefNum = i;
strcpy(fIntervalTable[fMeasuredClient].fName, client->GetClientControl()->fName);
fIntervalTable[fMeasuredClient].fBeginInterval = fAudioCycle;
fIntervalTable[fMeasuredClient].fEndInterval = fAudioCycle;
fMeasuredClient++;
}
fProfileTable[fAudioCycle].fClientTable[i].fRefNum = i;
fProfileTable[fAudioCycle].fClientTable[i].fSignaledAt = timing->fSignaledAt;
fProfileTable[fAudioCycle].fClientTable[i].fAwakeAt = timing->fAwakeAt;
fProfileTable[fAudioCycle].fClientTable[i].fFinishedAt = timing->fFinishedAt;
fProfileTable[fAudioCycle].fClientTable[i].fStatus = timing->fStatus;
}
}
}
JackTimingMeasure* JackEngineProfiling::GetCurMeasure()
{
return &fProfileTable[fAudioCycle];
}
} // end of namespace
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "replica/replica_stub.h"
#include "replica/replica.h"
#include "duplication_sync_timer.h"
#include "replica_duplicator_manager.h"
#include <dsn/dist/fmt_logging.h>
#include <dsn/tool-api/command_manager.h>
#include <dsn/utility/output_utils.h>
#include <dsn/utility/string_conv.h>
namespace dsn {
namespace replication {
DEFINE_TASK_CODE(LPC_DUPLICATION_SYNC_TIMER, TASK_PRIORITY_COMMON, THREAD_POOL_DEFAULT)
void duplication_sync_timer::run()
{
// ensure duplication sync never be concurrent
if (_rpc_task) {
ddebug_f("a duplication sync is already ongoing");
return;
}
{
zauto_lock l(_stub->_state_lock);
if (_stub->_state == replica_stub::NS_Disconnected) {
ddebug_f("stop this round of duplication sync because this server is disconnected from "
"meta server");
return;
}
}
auto req = make_unique<duplication_sync_request>();
req->node = _stub->primary_address();
// collects confirm points from all primaries on this server
uint64_t pending_muts_cnt = 0;
for (const replica_ptr &r : get_all_primaries()) {
auto confirmed = r->get_duplication_manager()->get_duplication_confirms_to_update();
if (!confirmed.empty()) {
req->confirm_list[r->get_gpid()] = std::move(confirmed);
}
pending_muts_cnt += r->get_duplication_manager()->get_pending_mutations_count();
}
_stub->_counter_dup_pending_mutations_count->set(pending_muts_cnt);
duplication_sync_rpc rpc(std::move(req), RPC_CM_DUPLICATION_SYNC, 3_s);
rpc_address meta_server_address(_stub->get_meta_server_address());
ddebug_f("duplication_sync to meta({})", meta_server_address.to_string());
zauto_lock l(_lock);
_rpc_task =
rpc.call(meta_server_address, &_stub->_tracker, [this, rpc](error_code err) mutable {
on_duplication_sync_reply(err, rpc.response());
});
}
void duplication_sync_timer::on_duplication_sync_reply(error_code err,
const duplication_sync_response &resp)
{
if (err == ERR_OK && resp.err != ERR_OK) {
err = resp.err;
}
if (err != ERR_OK) {
derror_f("on_duplication_sync_reply: err({})", err.to_string());
} else {
update_duplication_map(resp.dup_map);
}
zauto_lock l(_lock);
_rpc_task = nullptr;
}
void duplication_sync_timer::update_duplication_map(
const std::map<int32_t, std::map<int32_t, duplication_entry>> &dup_map)
{
for (replica_ptr &r : get_all_replicas()) {
auto it = dup_map.find(r->get_gpid().get_app_id());
if (it == dup_map.end()) {
// no duplication is assigned to this app
r->get_duplication_manager()->update_duplication_map({});
} else {
r->get_duplication_manager()->update_duplication_map(it->second);
}
}
}
duplication_sync_timer::duplication_sync_timer(replica_stub *stub) : _stub(stub) {}
duplication_sync_timer::~duplication_sync_timer() {}
std::vector<replica_ptr> duplication_sync_timer::get_all_primaries()
{
std::vector<replica_ptr> replica_vec;
{
zauto_read_lock l(_stub->_replicas_lock);
for (auto &kv : _stub->_replicas) {
replica_ptr r = kv.second;
if (r->status() != partition_status::PS_PRIMARY) {
continue;
}
replica_vec.emplace_back(std::move(r));
}
}
return replica_vec;
}
std::vector<replica_ptr> duplication_sync_timer::get_all_replicas()
{
std::vector<replica_ptr> replica_vec;
{
zauto_read_lock l(_stub->_replicas_lock);
for (auto &kv : _stub->_replicas) {
replica_ptr r = kv.second;
replica_vec.emplace_back(std::move(r));
}
}
return replica_vec;
}
void duplication_sync_timer::close()
{
ddebug("stop duplication sync");
{
zauto_lock l(_lock);
if (_rpc_task) {
_rpc_task->cancel(true);
_rpc_task = nullptr;
}
}
if (_timer_task) {
_timer_task->cancel(true);
_timer_task = nullptr;
}
}
void duplication_sync_timer::start()
{
ddebug_f("run duplication sync periodically in {}s", DUPLICATION_SYNC_PERIOD_SECOND);
_timer_task = tasking::enqueue_timer(LPC_DUPLICATION_SYNC_TIMER,
&_stub->_tracker,
[this]() { run(); },
DUPLICATION_SYNC_PERIOD_SECOND * 1_s,
0,
DUPLICATION_SYNC_PERIOD_SECOND * 1_s);
}
std::multimap<dupid_t, duplication_sync_timer::replica_dup_state>
duplication_sync_timer::get_dup_states(int app_id, /*out*/ bool *app_found)
{
*app_found = false;
std::multimap<dupid_t, replica_dup_state> result;
for (const replica_ptr &r : get_all_primaries()) {
gpid rid = r->get_gpid();
if (rid.get_app_id() != app_id) {
continue;
}
*app_found = true;
replica_dup_state state;
state.id = rid;
auto states = r->get_duplication_manager()->get_dup_states();
decree last_committed_decree = r->last_committed_decree();
for (const auto &s : states) {
state.duplicating = s.duplicating;
state.not_confirmed = std::max(decree(0), last_committed_decree - s.confirmed_decree);
state.not_duplicated = std::max(decree(0), last_committed_decree - s.last_decree);
state.fail_mode = s.fail_mode;
result.emplace(std::make_pair(s.dupid, state));
}
}
return result;
}
} // namespace replication
} // namespace dsn
|
/*******************************************************************************
* Copyright (c) 2012-2014, The Microsystems Design Labratory (MDL)
* Department of Computer Science and Engineering, The Pennsylvania State University
* All rights reserved.
*
* This source code is part of NVMain - A cycle accurate timing, bit accurate
* energy simulator for both volatile (e.g., DRAM) and non-volatile memory
* (e.g., PCRAM). The source code is free and you can redistribute and/or
* modify it by providing that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* Author list:
* Matt Poremba ( Email: mrp5060 at psu dot edu
* Website: http://www.cse.psu.edu/~poremba/ )
*******************************************************************************/
#include <sstream>
#include <stdlib.h>
#include "traceReader/RubyTrace/RubyTraceReader.h"
using namespace NVM;
RubyTraceReader::RubyTraceReader( )
{
traceFile = "";
}
RubyTraceReader::~RubyTraceReader( )
{
/* Close the trace file if it is open. */
if( trace.is_open( ) )
trace.close( );
}
/* Set the trace file's filename. */
void RubyTraceReader::SetTraceFile( std::string file )
{
traceFile = file;
}
/* Return the trace file's filename */
std::string RubyTraceReader::GetTraceFile( )
{
return traceFile;
}
/*
* Parse the trace file and find the next access to main memory. May read
* multiple lines before a memory access is returned.
*/
bool RubyTraceReader::GetNextAccess( TraceLine *nextAccess )
{
/* If trace file is not specified, we can't know what to do. */
if( traceFile == "" )
{
std::cerr << "No trace file specified!" << std::endl;
return false;
}
/* If trace file is not opened, we can't read from it. */
if( !trace.is_open( ) )
{
trace.open( traceFile.c_str() );
if( !trace.is_open( ) )
{
std::cerr << "Could not open trace file: " << traceFile << "!" << std::endl;
return false;
}
}
/*
* Read the next few lines from the file, looking for transactions that end
* and do not end at one of the caches. Once the first one is found, return it.
*/
std::string fullLine;
/* We will break at errors / finishing points in the loop. */
while( 1 )
{
NVMDataBlock dataBlock;
NVMDataBlock oldDataBlock;
unsigned int threadId;
threadId = 0;
/*
* Read a full line from the trace, ensuring we are not at the end of
* the file
*/
if( trace.eof( ) )
{
NVMAddress nAddress;
nAddress.SetPhysicalAddress( 0xDEADC0DEDEADBEEFULL );
nextAccess->SetLine( nAddress, NOP, 0, dataBlock, oldDataBlock, 0 );
return false;
}
getline( trace, fullLine );
/*
* Insert the full ine into a string stream. We will use the string stream
* to separate the fields in the trace files into useful data we need.
*/
std::istringstream lineStream( fullLine );
std::string field;
unsigned char fieldId;
/*
* Interesting fields are the cycles, the unit issuing the trace command,
* the command being executed on the memory, the address of the memory
* operation, and the operation- such as load/store/fetch
*/
std::string cycle, unit, command, address, memory, operation;
uint64_t decAddress;
unsigned int currentCycle = 0;
unsigned int cycles = 0;
OpType memOp;
/*
* In a Ruby Trace, most of the fields are not necessary for main
* memory purposes.
* We will increment the field ID and use it as a reference to
* determine what we are interested in. In this case, the format is
* as follows:
*
* 207 1 -1 Seq Done > [0x7ba4ce80, line 0x7ba4ce80] 206 cycles NULL IFETCH No
*
* 0 1 2 3 4 5 6 7 8 9 10 11 12 13
*
* Here we are interested in fields 3, 4, 6, 11, and 12. Field 3 is
* the unit * generating the memory request. Field 4 is the unit's
* command. Field 6 is the address. Field 11 is the memory region where
* the result ends. Field 12 is the memory operation.
*/
fieldId = 0;
while( getline( lineStream, field, ' ' ) )
{
if( field != "" )
{
if( fieldId == 0 )
currentCycle = atoi( field.c_str( ) );
else if( fieldId == 3 )
unit = field;
else if( fieldId == 4 )
command = field;
else if( fieldId == 6 )
address = field.substr( 1, field.length( ) - 2 );
else if( fieldId == 9 )
cycles = atoi( field.c_str( ) );
else if( fieldId == 11 )
memory = field;
else if( fieldId == 12 )
operation = field;
fieldId++;
}
}
/*
* If the unit generating the result is "Seq," it is the GEMS sequencer
* stepping through the instructions. We want to find sequencer
* executing the "Done" command.
* If the memory is "NULL," this is main memory. Other possibilites are
* "L1Cache" or "L2Cache" for example.
*
* If it is a main memory request, we need to convert to either a read
* or write.
* Ruby uses LD for load, IFETCH for instruction fetch, and ST for store.
* Both LD and IFETCH will be mapped to a read command for the simulator.
* Stores are mapped to write commands.
*/
if( unit == "Seq" )
{
if( command == "Done" && memory == "NULL" )
{
std::stringstream fmat;
fmat << std::hex << address;
fmat >> decAddress;
if( operation == "IFETCH" || operation == "LD" )
memOp = READ;
else if( operation == "ST" || operation == "ATOMIC" )
memOp = WRITE;
else
{
memOp = NOP;
std::cout << "RubyTraceReader: Unknown memory operation! "
<< operation << std::endl;
}
NVMAddress nAddress;
nAddress.SetPhysicalAddress( decAddress );
nextAccess->SetLine( nAddress, memOp, currentCycle - cycles,
dataBlock, oldDataBlock, threadId );
break;
}
}
}
return true;
}
/*
* Get the next N accesses to main memory. Called GetNextAccess N times and
* places the return values into a vector of TraceLine pointers.
*/
int RubyTraceReader::GetNextNAccesses( unsigned int N,
std::vector<TraceLine *> *nextAccesses )
{
int successes;
class TraceLine *nextLine;
/* Keep track of the actual number of accesses returned. */
successes = 0;
/* Loop N times, calling GetNextAccess each iteration. */
for( unsigned int i = 0; i < N; i++ )
{
/* We need a new TraceLine so the old values are not overwritten. */
nextLine = new TraceLine( );
/* Get the next access and place it in "nextLine" */
if( GetNextAccess( nextLine ) )
{
/* Push next line into the vector. */
nextAccesses->push_back( nextLine );
successes++;
}
}
return successes;
}
|
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
// Copyright (c) 2016 Klemens D. Morgenstern
//
// 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_PROCESS_DETAIL_ERROR_HPP
#define BOOST_PROCESS_DETAIL_ERROR_HPP
#include <boost/process/detail/config.hpp>
#include <boost/process/detail/traits.hpp>
#if defined(BOOST_POSIX_API)
#include <boost/process/detail/posix/handler.hpp>
#elif defined(BOOST_WINDOWS_API)
#include <boost/process/detail/windows/handler.hpp>
#endif
#include <system_error>
#include <type_traits>
#include <boost/fusion/algorithm/query/find_if.hpp>
#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/sequence/intrinsic/end.hpp>
#include <boost/fusion/container/vector/convert.hpp>
#include <boost/fusion/iterator/deref.hpp>
#include <boost/fusion/sequence/comparison/equal_to.hpp>
#include <boost/fusion/container/set/convert.hpp>
#include <boost/type_index.hpp>
/** \file boost/process/error.hpp
*
* Header which provides the error properties. It allows to explicitly set the error handling, the properties are:
*
\xmlonly
<programlisting>
namespace boost {
namespace process {
<emphasis>unspecified</emphasis> <globalname alt="boost::process::ignore_error">ignore_error</globalname>;
<emphasis>unspecified</emphasis> <globalname alt="boost::process::throw_on_error">throw_on_error</globalname>;
<emphasis>unspecified</emphasis> <globalname alt="boost::process::error">error</globalname>;
<emphasis>unspecified</emphasis> <globalname alt="boost::process::error_ref">error_ref</globalname>;
<emphasis>unspecified</emphasis> <globalname alt="boost::process::error_code">error_code</globalname>;
}
}
</programlisting>
\endxmlonly
* For error there are two aliases: error_ref and error_code
*/
namespace boost { namespace process {
namespace detail {
struct throw_on_error_ : ::boost::process::detail::api::handler_base_ext
{
constexpr throw_on_error_() {};
template <class Executor>
void on_error(Executor&, const std::error_code & ec) const
{
throw process_error(ec, "process creation failed");
}
const throw_on_error_ &operator()() const {return *this;}
};
struct ignore_error_ : ::boost::process::detail::api::handler_base_ext
{
constexpr ignore_error_() {};
};
struct set_on_error : ::boost::process::detail::api::handler_base_ext
{
set_on_error(const set_on_error&) = default;
explicit set_on_error(std::error_code &ec) : ec_(ec) {}
template <class Executor>
void on_error(Executor&, const std::error_code & ec) const
{
ec_ = ec;
}
private:
std::error_code &ec_;
};
struct error_
{
constexpr error_() {}
set_on_error operator()(std::error_code &ec) const {return set_on_error(ec);}
set_on_error operator= (std::error_code &ec) const {return set_on_error(ec);}
};
template<typename T>
struct is_error_handler : std::false_type {};
template<> struct is_error_handler<set_on_error> : std::true_type {};
template<> struct is_error_handler<throw_on_error_> : std::true_type {};
template<> struct is_error_handler<ignore_error_> : std::true_type {};
template<typename Iterator, typename End>
struct has_error_handler_impl
{
typedef typename boost::fusion::result_of::deref<Iterator>::type ref_type;
typedef typename std::remove_reference<ref_type>::type res_type_;
typedef typename std::remove_cv<res_type_>::type res_type;
typedef typename is_error_handler<res_type>::type cond;
typedef typename boost::fusion::result_of::next<Iterator>::type next_itr;
typedef typename has_error_handler_impl<next_itr, End>::type next;
typedef typename boost::mpl::or_<cond, next>::type type;
};
template<typename Iterator>
struct has_error_handler_impl<Iterator, Iterator>
{
typedef boost::mpl::false_ type;
};
template<typename Sequence>
struct has_error_handler
{
typedef typename boost::fusion::result_of::as_vector<Sequence>::type vector_type;
typedef typename has_error_handler_impl<
typename boost::fusion::result_of::begin<vector_type>::type,
typename boost::fusion::result_of::end< vector_type>::type
>::type type;
};
template<typename Sequence>
struct has_ignore_error
{
typedef typename boost::fusion::result_of::as_set<Sequence>::type set_type;
typedef typename boost::fusion::result_of::has_key<set_type, ignore_error_>::type type1;
typedef typename boost::fusion::result_of::has_key<set_type, ignore_error_&>::type type2;
typedef typename boost::fusion::result_of::has_key<set_type, const ignore_error_&>::type type3;
typedef typename boost::mpl::or_<type1,type2, type3>::type type;
};
struct error_builder
{
std::error_code *err;
typedef set_on_error result_type;
set_on_error get_initializer() {return set_on_error(*err);};
void operator()(std::error_code & ec) {err = &ec;};
};
template<>
struct initializer_tag<std::error_code>
{
typedef error_tag type;
};
template<>
struct initializer_builder<error_tag>
{
typedef error_builder type;
};
}
/**The ignore_error property will disable any error handling. This can be useful
on linux, where error handling will require a pipe.*/
constexpr boost::process::detail::ignore_error_ ignore_error;
/**The throw_on_error property will enable the exception when launching a process.
It is unnecessary by default, but may be used, when an additional error_code is provided.*/
constexpr boost::process::detail::throw_on_error_ throw_on_error;
/**
The error property will set the executor to handle any errors by setting an
[std::error_code](http://en.cppreference.com/w/cpp/error/error_code).
\code{.cpp}
std::error_code ec;
system("gcc", error(ec));
\endcode
The following syntax is valid:
\code{.cpp}
error(ec);
error=ec;
\endcode
The overload version is achieved by just passing an object of
[std::error_code](http://en.cppreference.com/w/cpp/error/error_code) to the function.
*/
constexpr boost::process::detail::error_ error;
///Alias for \xmlonly <globalname alt="boost::process::error">error</globalname> \endxmlonly .
constexpr boost::process::detail::error_ error_ref;
///Alias for \xmlonly <globalname alt="boost::process::error">error</globalname> \endxmlonly .
constexpr boost::process::detail::error_ error_code;
}}
#endif
|
#include <stdio.h>
#include <iostream>
#include "mcp23017.h"
#include "serial.h"
// Test functions go here
int mcp23017_test() {
static const uint8_t test_array[16] = {0, 1, 0, 0, 1, 0, 1, 1,
0, 1, 0, 0, 0, 1, 1, 1};
// initialize the device
Mcp23017 dev = Mcp23017(2, 0x24);
// begin the device dev.begin(array of 16 bits)
if (dev.begin(test_array)) return 1;
// set two outputs on bank a, and two on bank b
// and read from pin each time it is written
dev.set_state(3, 1);
if (dev.get_state(3) != 1) return 1;
dev.set_state(2, 0);
if (dev.get_state(2) != 0) return 1;
dev.set_state(11, 1);
if (dev.get_state(11) != 1) return 1;
dev.set_state(9, 0);
if (dev.get_state(9) != 0) return 1;
return 0;
}
int main() {
Serial serial = Serial();
if (serial.openDevice(4, 9600) != 1) std::cout << "error\n";
std::cout << "Begnning MCP23017 tests\n";
serial.writeString("mcp23017");
// Test calls go here
if (mcp23017_test()) {
std::cout << "MCP23017 test failed/n";
return 1;
}
serial.closeDevice();
return 0;
}
|
// 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 "chrome/browser/ui/panels/panel_host.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_page_zoom.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/view_type_utils.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension_messages.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "ui/gfx/image/image.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_message_macros.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/rect.h"
using content::UserMetricsAction;
PanelHost::PanelHost(Panel* panel, Profile* profile)
: panel_(panel),
profile_(profile),
extension_function_dispatcher_(profile, this),
weak_factory_(this) {
}
PanelHost::~PanelHost() {
}
void PanelHost::Init(const GURL& url) {
if (url.is_empty())
return;
web_contents_.reset(content::WebContents::Create(
profile_, content::SiteInstance::CreateForURL(profile_, url),
MSG_ROUTING_NONE, NULL, NULL));
chrome::SetViewType(web_contents_.get(), chrome::VIEW_TYPE_PANEL);
web_contents_->SetDelegate(this);
content::WebContentsObserver::Observe(web_contents_.get());
favicon_tab_helper_.reset(new FaviconTabHelper(web_contents_.get()));
web_contents_->GetController().LoadURL(
url, content::Referrer(), content::PAGE_TRANSITION_LINK, std::string());
}
void PanelHost::DestroyWebContents() {
web_contents_.reset();
favicon_tab_helper_.reset();
}
SkBitmap PanelHost::GetPageIcon() const {
// TODO: Make this function return gfx::Image.
return favicon_tab_helper_.get() ?
favicon_tab_helper_->GetFavicon().AsBitmap() : SkBitmap();
}
void PanelHost::NavigationStateChanged(const content::WebContents* source,
unsigned changed_flags) {
// Only need to update the title if the title changed while not loading,
// because the title is also updated when loading state changes.
if ((changed_flags & content::INVALIDATE_TYPE_TAB) ||
((changed_flags & content::INVALIDATE_TYPE_TITLE) &&
!source->IsLoading()))
panel_->UpdateTitleBar();
}
void PanelHost::ActivateContents(content::WebContents* contents) {
panel_->Activate();
}
void PanelHost::DeactivateContents(content::WebContents* contents) {
panel_->Deactivate();
}
void PanelHost::LoadingStateChanged(content::WebContents* source) {
bool is_loading = source->IsLoading();
panel_->LoadingStateChanged(is_loading);
}
void PanelHost::CloseContents(content::WebContents* source) {
panel_->Close();
}
void PanelHost::MoveContents(content::WebContents* source,
const gfx::Rect& pos) {
panel_->SetBounds(pos);
}
bool PanelHost::IsPopupOrPanel(const content::WebContents* source) const {
return true;
}
void PanelHost::ContentsZoomChange(bool zoom_in) {
Zoom(zoom_in ? content::PAGE_ZOOM_IN : content::PAGE_ZOOM_OUT);
}
bool PanelHost::IsApplication() const {
return true;
}
bool PanelHost::HandleContextMenu(const content::ContextMenuParams& params) {
return true; // Disallow context menu.
}
void PanelHost::HandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event) {
return panel_->HandleKeyboardEvent(event);
}
void PanelHost::WebContentsFocused(content::WebContents* contents) {
panel_->WebContentsFocused(contents);
}
void PanelHost::ResizeDueToAutoResize(content::WebContents* web_contents,
const gfx::Size& new_size) {
panel_->OnContentsAutoResized(new_size);
}
void PanelHost::RenderViewGone(base::TerminationStatus status) {
CloseContents(web_contents_.get());
}
void PanelHost::WebContentsDestroyed(content::WebContents* web_contents) {
// Close the panel after we return to the message loop (not immediately,
// otherwise, it may destroy this object before the stack has a chance
// to cleanly unwind.)
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&PanelHost::ClosePanel, weak_factory_.GetWeakPtr()));
}
void PanelHost::ClosePanel() {
panel_->Close();
}
bool PanelHost::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PanelHost, message)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void PanelHost::OnRequest(const ExtensionHostMsg_Request_Params& params) {
if (!web_contents_.get())
return;
extension_function_dispatcher_.Dispatch(params,
web_contents_->GetRenderViewHost());
}
extensions::WindowController* PanelHost::GetExtensionWindowController() const {
return panel_->extension_window_controller();
}
content::WebContents* PanelHost::GetAssociatedWebContents() const {
return web_contents_.get();
}
void PanelHost::Reload() {
content::RecordAction(UserMetricsAction("Reload"));
web_contents_->GetController().Reload(true);
}
void PanelHost::ReloadIgnoringCache() {
content::RecordAction(UserMetricsAction("ReloadIgnoringCache"));
web_contents_->GetController().ReloadIgnoringCache(true);
}
void PanelHost::StopLoading() {
content::RecordAction(UserMetricsAction("Stop"));
web_contents_->Stop();
}
void PanelHost::Zoom(content::PageZoom zoom) {
chrome_page_zoom::Zoom(web_contents_.get(), zoom);
}
|
/**
* @file
* @brief Player related functions.
**/
#include "AppHdr.h"
#include "player.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include "ability.h"
#include "abyss.h"
#include "act-iter.h"
#include "areas.h"
#include "art-enum.h"
#include "attack.h"
#include "bloodspatter.h"
#include "branch.h"
#include "chardump.h"
#include "cloud.h"
#include "coordit.h"
#include "delay.h"
#include "dgn-overview.h"
#include "dgn-event.h"
#include "directn.h"
#include "english.h"
#include "env.h"
#include "tile-env.h"
#include "errors.h"
#include "exercise.h"
#include "files.h"
#include "god-abil.h"
#include "god-conduct.h"
#include "god-passive.h"
#include "god-wrath.h"
#include "hints.h"
#include "hiscores.h"
#include "invent.h"
#include "item-prop.h"
#include "items.h"
#include "item-use.h"
#include "kills.h"
#include "level-state-type.h"
#include "libutil.h"
#include "macro.h"
#include "melee-attack.h"
#include "message.h"
#include "mon-place.h"
#include "movement.h"
#include "mutation.h"
#include "nearby-danger.h"
#include "notes.h"
#include "output.h"
#include "player-equip.h"
#include "player-save-info.h"
#include "player-stats.h"
#include "prompt.h"
#include "religion.h"
#include "shout.h"
#include "skills.h"
#include "species.h" // random_starting_species
#include "spl-damage.h"
#include "spl-selfench.h"
#include "spl-summoning.h"
#include "spl-transloc.h"
#include "spl-util.h"
#include "sprint.h"
#include "stairs.h"
#include "stash.h"
#include "state.h"
#include "status.h"
#include "stepdown.h"
#include "stringutil.h"
#include "tag-version.h"
#include "terrain.h"
#ifdef USE_TILE
#include "tilepick.h"
#include "tileview.h"
#endif
#include "transform.h"
#include "traps.h"
#include "travel.h"
#include "view.h"
#include "wizard-option-type.h"
#include "xom.h"
static void _pruneify()
{
if (!you.may_pruneify())
return;
mpr("The curse of the Prune overcomes you.");
did_god_conduct(DID_CHAOS, 10);
}
static void _moveto_maybe_repel_stairs()
{
const dungeon_feature_type new_grid = env.grid(you.pos());
const command_type stair_dir = feat_stair_direction(new_grid);
if (stair_dir == CMD_NO_CMD
|| new_grid == DNGN_ENTER_SHOP
|| !you.duration[DUR_REPEL_STAIRS_MOVE])
{
return;
}
int pct = you.duration[DUR_REPEL_STAIRS_CLIMB] ? 29 : 50;
// When the effect is still strong, the chance to actually catch
// a stair is smaller. (Assuming the duration starts out at 1000.)
const int dur = max(0, you.duration[DUR_REPEL_STAIRS_MOVE] - 700);
pct += dur/10;
if (x_chance_in_y(pct, 100))
{
const string stair_str = feature_description_at(you.pos(), false,
DESC_THE);
const string prep = feat_preposition(new_grid, true, &you);
if (slide_feature_over(you.pos()))
{
mprf("%s slides away as you move %s it!", stair_str.c_str(),
prep.c_str());
if (player_in_a_dangerous_place() && one_chance_in(5))
xom_is_stimulated(25);
}
}
}
bool check_moveto_cloud(const coord_def& p, const string &move_verb,
bool *prompted)
{
if (you.confused())
return true;
const cloud_type ctype = env.map_knowledge(p).cloud();
// Don't prompt if already in a cloud of the same type.
if (is_damaging_cloud(ctype, true, cloud_is_yours_at(p))
&& ctype != cloud_type_at(you.pos())
&& !crawl_state.disables[DIS_CONFIRMATIONS])
{
// Don't prompt for steam unless we're at uncomfortably low hp.
if (ctype == CLOUD_STEAM)
{
int threshold = 20;
if (player_res_steam(false) < 0)
threshold = threshold * 3 / 2;
threshold = threshold * you.time_taken / BASELINE_DELAY;
// Do prompt if we'd lose icemail, though.
if (you.hp > threshold && !you.has_mutation(MUT_CONDENSATION_SHIELD))
return true;
}
// Don't prompt for meph if we have clarity, unless at very low HP.
if (ctype == CLOUD_MEPHITIC && you.clarity(false)
&& you.hp > 2 * you.time_taken / BASELINE_DELAY)
{
return true;
}
if (prompted)
*prompted = true;
string prompt = make_stringf("Really %s into that cloud of %s?",
move_verb.c_str(),
cloud_type_name(ctype).c_str());
learned_something_new(HINT_CLOUD_WARNING);
if (!yesno(prompt.c_str(), false, 'n'))
{
canned_msg(MSG_OK);
return false;
}
}
return true;
}
bool check_moveto_trap(const coord_def& p, const string &move_verb,
bool *prompted)
{
// Boldly go into the unknown (for shadow step and other ranged move
// prompts)
if (env.map_knowledge(p).trap() == TRAP_UNASSIGNED)
return true;
// If there's no trap, let's go.
trap_def* trap = trap_at(p);
if (!trap)
return true;
if (trap->type == TRAP_ZOT && !trap->is_safe() && !crawl_state.disables[DIS_CONFIRMATIONS])
{
string msg = "Do you really want to %s into the Zot trap?";
string prompt = make_stringf(msg.c_str(), move_verb.c_str());
if (prompted)
*prompted = true;
if (!yes_or_no("%s", prompt.c_str()))
{
canned_msg(MSG_OK);
return false;
}
}
else if (!trap->is_safe() && !crawl_state.disables[DIS_CONFIRMATIONS])
{
string prompt;
if (prompted)
*prompted = true;
prompt = make_stringf("Really %s %s that %s?", move_verb.c_str(),
(trap->type == TRAP_ALARM
|| trap->type == TRAP_PLATE) ? "onto"
: "into",
feature_description_at(p, false, DESC_BASENAME).c_str());
if (!yesno(prompt.c_str(), true, 'n'))
{
canned_msg(MSG_OK);
return false;
}
}
return true;
}
static bool _check_moveto_dangerous(const coord_def& p, const string& msg)
{
if (you.can_swim() && feat_is_water(env.grid(p))
|| you.airborne() || !is_feat_dangerous(env.grid(p)))
{
return true;
}
if (!msg.empty())
mpr(msg);
else if (species::likes_water(you.species) && feat_is_water(env.grid(p)))
{
// player normally likes water, but is in a form that doesn't
mpr("You cannot enter water in your current form.");
}
else
canned_msg(MSG_UNTHINKING_ACT);
return false;
}
bool check_moveto_terrain(const coord_def& p, const string &move_verb,
const string &msg, bool *prompted)
{
// Boldly go into the unknown (for shadow step and other ranged move
// prompts)
if (!env.map_knowledge(p).known())
return true;
if (!_check_moveto_dangerous(p, msg))
return false;
if (!you.airborne() && !you.duration[DUR_NOXIOUS_BOG]
&& env.grid(you.pos()) != DNGN_TOXIC_BOG
&& env.grid(p) == DNGN_TOXIC_BOG)
{
string prompt;
if (prompted)
*prompted = true;
if (!msg.empty())
prompt = msg + " ";
prompt += "Are you sure you want to " + move_verb
+ " into a toxic bog?";
if (!yesno(prompt.c_str(), false, 'n'))
{
canned_msg(MSG_OK);
return false;
}
}
if (!need_expiration_warning() && need_expiration_warning(p)
&& !crawl_state.disables[DIS_CONFIRMATIONS])
{
string prompt;
if (prompted)
*prompted = true;
if (!msg.empty())
prompt = msg + " ";
prompt += "Are you sure you want to " + move_verb;
if (you.ground_level())
prompt += " into ";
else
prompt += " over ";
prompt += env.grid(p) == DNGN_DEEP_WATER ? "deep water" : "lava";
prompt += need_expiration_warning(DUR_FLIGHT, p)
? " while you are losing your buoyancy?"
: " while your transformation is expiring?";
if (!yesno(prompt.c_str(), false, 'n'))
{
canned_msg(MSG_OK);
return false;
}
}
return true;
}
bool check_moveto_exclusions(const vector<coord_def> &areas,
const string &move_verb,
bool *prompted)
{
const bool you_pos_excluded = is_excluded(you.pos())
&& !is_stair_exclusion(you.pos());
if (you_pos_excluded || crawl_state.disables[DIS_CONFIRMATIONS])
return true;
int count = 0;
for (auto p : areas)
{
if (is_excluded(p) && !is_stair_exclusion(p))
count++;
}
if (count == 0)
return true;
const string prompt = make_stringf((count == (int) areas.size() ?
"Really %s into a travel-excluded area?" :
"You might %s into a travel-excluded area, are you sure?"),
move_verb.c_str());
if (prompted)
*prompted = true;
if (!yesno(prompt.c_str(), false, 'n'))
{
canned_msg(MSG_OK);
return false;
}
return true;
}
bool check_moveto_exclusion(const coord_def& p, const string &move_verb,
bool *prompted)
{
return check_moveto_exclusions({p}, move_verb, prompted);
}
/**
* Confirm that the player really does want to go to the indicated place.
* May give many prompts, or no prompts if the move is safe.
*
* @param p The location the player wants to go to
* @param move_verb The method of locomotion the player is using
* @param physically Whether the player is considered to be "walking" for the
* purposes of barbs causing damage and ice spells expiring
* @return If true, continue with the move, otherwise cancel it
*/
bool check_moveto(const coord_def& p, const string &move_verb, bool physically)
{
return !(physically && cancel_harmful_move(physically, move_verb == "rampage"))
&& check_moveto_terrain(p, move_verb, "")
&& check_moveto_cloud(p, move_verb)
&& check_moveto_trap(p, move_verb)
&& check_moveto_exclusion(p, move_verb);
}
// Returns true if this is a valid swap for this monster. If true, then
// the valid location is set in loc. (Otherwise loc becomes garbage.)
bool swap_check(monster* mons, coord_def &loc, bool quiet)
{
loc = you.pos();
if (you.is_stationary())
return false;
// Don't move onto dangerous terrain.
if (is_feat_dangerous(env.grid(mons->pos())))
{
canned_msg(MSG_UNTHINKING_ACT);
return false;
}
if (mons_is_projectile(*mons))
{
if (!quiet)
mpr("It's unwise to walk into this.");
return false;
}
if (mons->caught())
{
if (!quiet)
{
simple_monster_message(*mons,
make_stringf(" is %s!", held_status(mons)).c_str());
}
return false;
}
if (mons->is_constricted())
{
if (!quiet)
simple_monster_message(*mons, " is being constricted!");
return false;
}
if (mons->is_stationary() || mons->asleep() || mons->cannot_act())
{
if (!quiet)
simple_monster_message(*mons, " cannot move out of your way!");
return false;
}
// prompt when swapping into known zot traps
if (!quiet && trap_at(loc) && trap_at(loc)->type == TRAP_ZOT
&& !yes_or_no("Do you really want to swap %s into the Zot trap?",
mons->name(DESC_YOUR).c_str()))
{
return false;
}
// First try: move monster onto your position.
bool swap = !monster_at(loc) && monster_habitable_grid(mons, env.grid(loc));
// Choose an appropriate habitat square at random around the target.
if (!swap)
{
int num_found = 0;
for (adjacent_iterator ai(mons->pos()); ai; ++ai)
if (!monster_at(*ai) && monster_habitable_grid(mons, env.grid(*ai))
&& one_chance_in(++num_found))
{
loc = *ai;
}
if (num_found)
swap = true;
}
if (!swap && !quiet)
{
// Might not be ideal, but it's better than insta-killing
// the monster... maybe try for a short blink instead? - bwr
simple_monster_message(*mons, " cannot make way for you.");
// FIXME: activity_interrupt::hit_monster isn't ideal.
interrupt_activity(activity_interrupt::hit_monster, mons);
}
return swap;
}
static void _splash()
{
if (you.can_swim())
noisy(4, you.pos(), "Floosh!");
else if (!you.can_water_walk())
noisy(8, you.pos(), "Splash!");
}
void moveto_location_effects(dungeon_feature_type old_feat,
bool stepped, const coord_def& old_pos)
{
const dungeon_feature_type new_grid = env.grid(you.pos());
// Terrain effects.
if (is_feat_dangerous(new_grid))
fall_into_a_pool(new_grid);
// called after fall_into_a_pool, in case of emergency untransform
if (you.has_innate_mutation(MUT_MERTAIL))
merfolk_check_swimming(stepped);
if (you.ground_level())
{
if (feat_is_water(new_grid))
{
if (!stepped)
_splash();
if (!you.can_swim() && !you.can_water_walk())
{
if (!feat_is_water(old_feat))
{
if (new_grid == DNGN_TOXIC_BOG)
{
mprf("You %s the toxic bog.",
stepped ? "enter" : "fall into");
}
else
{
mprf("You %s the %s water.",
stepped ? "enter" : "fall into",
new_grid == DNGN_SHALLOW_WATER ? "shallow"
: "deep");
}
}
if (new_grid == DNGN_DEEP_WATER && old_feat != DNGN_DEEP_WATER)
mpr("You sink to the bottom.");
if (!feat_is_water(old_feat))
{
mpr("Moving in this stuff is going to be slow.");
if (you.invisible())
mpr("...and don't expect to remain undetected.");
}
}
if ((you.can_swim() || you.extra_balanced())
&& !feat_is_water(old_feat)
&& you.invisible())
{
mpr("Don't expect to remain undetected while in the water.");
}
}
else if (you.props.exists(TEMP_WATERWALK_KEY))
you.props.erase(TEMP_WATERWALK_KEY);
}
id_floor_items();
// Falling into a toxic bog, take the damage
if (old_pos == you.pos() && stepped)
actor_apply_toxic_bog(&you);
// Traps go off.
// (But not when losing flight - i.e., moving into the same tile)
trap_def* ptrap = trap_at(you.pos());
if (ptrap && old_pos != you.pos())
ptrap->trigger(you);
if (stepped)
_moveto_maybe_repel_stairs();
bool was_running = you.running;
update_monsters_in_view();
maybe_update_stashes();
if (check_for_interesting_features() && you.running.is_explore())
stop_running();
// If travel was interrupted, we need to add the last step
// to the travel trail.
if (was_running && !you.running)
env.travel_trail.push_back(you.pos());
}
// Use this function whenever the player enters (or lands and thus re-enters)
// a grid.
//
// stepped - normal walking moves
void move_player_to_grid(const coord_def& p, bool stepped)
{
ASSERT(!crawl_state.game_is_arena());
ASSERT_IN_BOUNDS(p);
// assuming that entering the same square means coming from above (flight)
const coord_def old_pos = you.pos();
const bool from_above = (old_pos == p);
const dungeon_feature_type old_grid =
(from_above) ? DNGN_FLOOR : env.grid(old_pos);
// Really must be clear.
ASSERT(you.can_pass_through_feat(env.grid(p)));
// Better not be an unsubmerged monster either.
ASSERT(!monster_at(p) || monster_at(p)->submerged()
|| fedhas_passthrough(monster_at(p))
|| mons_is_player_shadow(*monster_at(p))
|| mons_is_wrath_avatar(*monster_at(p)));
// Move the player to new location.
you.moveto(p, true);
viewwindow();
update_screen();
moveto_location_effects(old_grid, stepped, old_pos);
}
/**
* Check if the given terrain feature is safe for the player to move into.
* (Or, at least, not instantly lethal.)
*
* @param grid The type of terrain feature under consideration.
* @param permanently Whether to disregard temporary effects (non-permanent
* flight, forms, etc)
* @param ignore_flight Whether to ignore all forms of flight (including
* permanent flight)
* @return Whether the terrain is safe.
*/
bool is_feat_dangerous(dungeon_feature_type grid, bool permanently,
bool ignore_flight)
{
if (!ignore_flight
&& (you.permanent_flight() || you.airborne() && !permanently))
{
return false;
}
else if (grid == DNGN_DEEP_WATER && !player_likes_water(permanently)
|| grid == DNGN_LAVA)
{
return true;
}
else
return false;
}
bool is_map_persistent()
{
return !testbits(your_branch().branch_flags, brflag::no_map)
|| env.properties.exists(FORCE_MAPPABLE_KEY);
}
bool player_in_hell(bool vestibule)
{
return vestibule ? is_hell_branch(you.where_are_you) :
is_hell_subbranch(you.where_are_you);
}
/**
* Is the player in the slightly-special version of the abyss that AKs start
* in?
*/
bool player_in_starting_abyss()
{
return you.chapter == CHAPTER_POCKET_ABYSS
&& player_in_branch(BRANCH_ABYSS) && you.depth <= 1;
}
bool player_in_connected_branch()
{
return is_connected_branch(you.where_are_you);
}
bool player_likes_water(bool permanently)
{
return !permanently && you.can_water_walk()
|| (species::likes_water(you.species) || !permanently)
&& form_likes_water();
}
/**
* Is the player considered to be closely related, if not the same species, to
* the given monster? (See mon-data.h for species/genus info.)
*
* @param mon The type of monster to be compared.
* @return Whether the player's species is related to the one given.
*/
bool is_player_same_genus(const monster_type mon)
{
return mons_genus(mon) == mons_genus(player_mons(false));
}
void update_player_symbol()
{
you.symbol = Options.show_player_species ? player_mons() : transform_mons();
}
monster_type player_mons(bool transform)
{
monster_type mons;
if (transform)
{
mons = transform_mons();
if (mons != MONS_PLAYER)
return mons;
}
mons = you.mons_species();
if (mons == MONS_ORC)
{
if (you_worship(GOD_BEOGH))
{
mons = (you.piety >= piety_breakpoint(4)) ? MONS_ORC_HIGH_PRIEST
: MONS_ORC_PRIEST;
}
}
else if (mons == MONS_OGRE)
{
const skill_type sk = best_skill(SK_FIRST_SKILL, SK_LAST_SKILL);
if (sk >= SK_SPELLCASTING && sk <= SK_LAST_MAGIC)
mons = MONS_OGRE_MAGE;
}
return mons;
}
void update_vision_range()
{
you.normal_vision = LOS_DEFAULT_RANGE;
// Daystalker gives +1 base LOS. (currently capped to one level for
// console reasons, a modular hud might someday permit more levels)
if (you.get_mutation_level(MUT_DAYSTALKER))
you.normal_vision += you.get_mutation_level(MUT_DAYSTALKER);
// Nightstalker gives -1/-2/-3 to base LOS.
if (you.get_mutation_level(MUT_NIGHTSTALKER))
you.normal_vision -= you.get_mutation_level(MUT_NIGHTSTALKER);
// Halo and umbra radius scale with you.normal_vision, so to avoid
// penalizing players with low LOS from items, don't shrink normal_vision.
you.current_vision = you.normal_vision;
// scarf of shadows gives -1.
if (you.wearing_ego(EQ_CLOAK, SPARM_SHADOWS))
you.current_vision -= 1;
// robe of Night.
if (player_equip_unrand(UNRAND_NIGHT))
you.current_vision = you.current_vision * 3 / 4;
ASSERT(you.current_vision > 0);
set_los_radius(you.current_vision);
}
/**
* Ignoring form & most equipment, but not the UNRAND_FINGER_AMULET, can the
* player use (usually wear) a given equipment slot?
*
* @param eq The slot in question.
* @param temp Whether to consider forms.
* @return MB_FALSE if the player can never use the slot;
* MB_MAYBE if the player can only use some items for the slot;
* MB_TRUE if the player can use any (fsvo any) item for the slot.
*/
maybe_bool you_can_wear(equipment_type eq, bool temp)
{
if (temp && !get_form()->slot_available(eq))
return MB_FALSE;
// handles incorrect ring slots vs species
if (species::bans_eq(you.species, eq))
return MB_FALSE;
switch (eq)
{
case EQ_RING_EIGHT:
case EQ_LEFT_RING:
if (you.get_mutation_level(MUT_MISSING_HAND))
return MB_FALSE;
// intentional fallthrough
case EQ_RIGHT_RING:
case EQ_RING_ONE:
case EQ_RING_TWO:
case EQ_RING_THREE:
case EQ_RING_FOUR:
case EQ_RING_FIVE:
case EQ_RING_SIX:
case EQ_RING_SEVEN:
return MB_TRUE;
case EQ_WEAPON:
case EQ_STAFF:
return you.has_mutation(MUT_NO_GRASPING) ? MB_FALSE :
you.body_size(PSIZE_TORSO, !temp) < SIZE_MEDIUM ? MB_MAYBE :
MB_TRUE;
// You can always wear at least one ring (forms were already handled).
case EQ_RINGS:
case EQ_ALL_ARMOUR:
case EQ_AMULET:
return MB_TRUE;
case EQ_RING_AMULET:
return player_equip_unrand(UNRAND_FINGER_AMULET) ? MB_TRUE : MB_FALSE;
default:
break;
}
item_def dummy, alternate;
dummy.base_type = alternate.base_type = OBJ_ARMOUR;
dummy.sub_type = alternate.sub_type = NUM_ARMOURS;
// Make sure can_wear_armour doesn't think it's Lear's.
dummy.unrand_idx = alternate.unrand_idx = 0;
switch (eq)
{
case EQ_CLOAK:
dummy.sub_type = ARM_CLOAK;
alternate.sub_type = ARM_SCARF;
break;
case EQ_GLOVES:
dummy.sub_type = ARM_GLOVES;
break;
case EQ_BOOTS: // And bardings
dummy.sub_type = ARM_BOOTS;
if (you.wear_barding())
alternate.sub_type = ARM_BARDING;
break;
case EQ_BODY_ARMOUR:
// Assume that anything that can wear any armour at all can wear a robe
// and that anything that can wear CPA can wear all armour.
dummy.sub_type = ARM_CRYSTAL_PLATE_ARMOUR;
alternate.sub_type = ARM_ROBE;
break;
case EQ_SHIELD:
// Assume that anything that can use an orb can wear some kind of
// shield
dummy.sub_type = ARM_ORB;
break;
case EQ_HELMET:
dummy.sub_type = ARM_HELMET;
alternate.sub_type = ARM_HAT;
break;
default:
die("unhandled equipment type %d", eq);
break;
}
ASSERT(dummy.sub_type != NUM_ARMOURS);
if (can_wear_armour(dummy, false, !temp))
return MB_TRUE;
else if (alternate.sub_type != NUM_ARMOURS
&& can_wear_armour(alternate, false, !temp))
{
return MB_MAYBE;
}
else
return MB_FALSE;
}
bool player_has_feet(bool temp, bool include_mutations)
{
if (you.has_innate_mutation(MUT_CONSTRICTING_TAIL)
|| you.has_innate_mutation(MUT_FLOAT)
|| you.has_innate_mutation(MUT_PAWS) // paws are not feet?
|| you.has_tentacles(temp)
|| you.fishtail && temp)
{
return false;
}
if (include_mutations &&
(you.get_mutation_level(MUT_HOOVES, temp) == 3
|| you.get_mutation_level(MUT_TALONS, temp) == 3))
{
return false;
}
return true;
}
// Returns false if the player is wielding a weapon inappropriate for Berserk.
bool berserk_check_wielded_weapon()
{
const item_def * const wpn = you.weapon();
bool penance = false;
if (wpn && wpn->defined()
&& (!is_melee_weapon(*wpn)
|| needs_handle_warning(*wpn, OPER_ATTACK, penance)))
{
string prompt = "Do you really want to go berserk while wielding "
+ wpn->name(DESC_YOUR) + "?";
if (penance)
prompt += " This could place you under penance!";
if (!yesno(prompt.c_str(), true, 'n'))
{
canned_msg(MSG_OK);
return false;
}
}
return true;
}
// Looks in equipment "slot" to see if there is an equipped "sub_type".
// Returns number of matches (in the case of rings, both are checked)
int player::wearing(equipment_type slot, int sub_type) const
{
int ret = 0;
const item_def* item;
switch (slot)
{
case EQ_WEAPON:
// Hands can have more than just weapons.
if (weapon() && weapon()->is_type(OBJ_WEAPONS, sub_type))
ret++;
break;
case EQ_STAFF:
// Like above, but must be magical staff.
if (weapon() && weapon()->is_type(OBJ_STAVES, sub_type))
ret++;
break;
case EQ_AMULET:
if ((item = slot_item(static_cast<equipment_type>(EQ_AMULET)))
&& item->sub_type == sub_type)
{
ret++;
}
break;
case EQ_RINGS:
case EQ_RINGS_PLUS:
for (int slots = EQ_FIRST_JEWELLERY; slots <= EQ_LAST_JEWELLERY; slots++)
{
if (slots == EQ_AMULET)
continue;
if ((item = slot_item(static_cast<equipment_type>(slots)))
&& item->sub_type == sub_type)
{
ret += (slot == EQ_RINGS_PLUS ? item->plus : 1);
}
}
break;
case EQ_ALL_ARMOUR:
// Doesn't make much sense here... be specific. -- bwr
die("EQ_ALL_ARMOUR is not a proper slot");
break;
default:
if (!(slot >= EQ_FIRST_EQUIP && slot < NUM_EQUIP))
die("invalid slot");
if ((item = slot_item(slot)) && item->sub_type == sub_type)
ret++;
break;
}
return ret;
}
// Looks in equipment "slot" to see if equipped item has "special" ego-type
// Returns number of matches (jewellery returns zero -- no ego type).
int player::wearing_ego(equipment_type slot, int special) const
{
int ret = 0;
const item_def* item;
switch (slot)
{
case EQ_WEAPON:
// Hands can have more than just weapons.
if ((item = slot_item(EQ_WEAPON))
&& item->base_type == OBJ_WEAPONS
&& get_weapon_brand(*item) == special)
{
ret++;
}
break;
case EQ_LEFT_RING:
case EQ_RIGHT_RING:
case EQ_AMULET:
case EQ_STAFF:
case EQ_RINGS:
case EQ_RINGS_PLUS:
// no ego types for these slots
break;
case EQ_ALL_ARMOUR:
// Check all armour slots:
for (int i = EQ_MIN_ARMOUR; i <= EQ_MAX_ARMOUR; i++)
{
if ((item = slot_item(static_cast<equipment_type>(i)))
&& get_armour_ego_type(*item) == special)
{
ret++;
}
}
break;
default:
if (slot < EQ_MIN_ARMOUR || slot > EQ_MAX_ARMOUR)
die("invalid slot: %d", slot);
// Check a specific armour slot for an ego type:
if ((item = slot_item(static_cast<equipment_type>(slot)))
&& get_armour_ego_type(*item) == special)
{
ret++;
}
break;
}
return ret;
}
// Returns true if the indicated unrandart is equipped
bool player_equip_unrand(int unrand_index, bool include_melded)
{
const unrandart_entry* entry = get_unrand_entry(unrand_index);
equipment_type slot = get_item_slot(entry->base_type,
entry->sub_type);
item_def* item;
switch (slot)
{
case EQ_WEAPON:
// Hands can have more than just weapons.
if ((item = you.slot_item(slot, include_melded))
&& item->base_type == OBJ_WEAPONS
&& is_unrandom_artefact(*item)
&& item->unrand_idx == unrand_index)
{
return true;
}
break;
case EQ_RINGS:
for (int slots = EQ_FIRST_JEWELLERY; slots <= EQ_LAST_JEWELLERY; ++slots)
{
if (slots == EQ_AMULET)
continue;
if ((item = you.slot_item(static_cast<equipment_type>(slots), include_melded))
&& is_unrandom_artefact(*item)
&& item->unrand_idx == unrand_index)
{
return true;
}
}
break;
case EQ_NONE:
case EQ_STAFF:
case EQ_LEFT_RING:
case EQ_RIGHT_RING:
case EQ_RINGS_PLUS:
case EQ_ALL_ARMOUR:
// no unrandarts for these slots.
break;
default:
if (slot <= EQ_NONE || slot >= NUM_EQUIP)
die("invalid slot: %d", slot);
// Check a specific slot.
if ((item = you.slot_item(slot, include_melded))
&& is_unrandom_artefact(*item)
&& item->unrand_idx == unrand_index)
{
return true;
}
break;
}
return false;
}
bool player_can_hear(const coord_def& p, int hear_distance)
{
return !silenced(p)
&& !silenced(you.pos())
&& you.pos().distance_from(p) <= hear_distance;
}
int player_teleport()
{
ASSERT(!crawl_state.game_is_arena());
// Don't allow any form of teleportation in Sprint or Gauntlets.
if (crawl_state.game_is_sprint() || player_in_branch(BRANCH_GAUNTLET))
return 0;
// Short-circuit rings of teleport to prevent spam.
if (you.stasis())
return 0;
int tp = 0;
// artefacts
tp += 8 * you.scan_artefacts(ARTP_CAUSE_TELEPORTATION);
// mutations
tp += you.get_mutation_level(MUT_TELEPORT) * 4;
return tp;
}
// Computes bonuses to regeneration from most sources. Does not handle
// slow regeneration, vampireness, or Trog's Hand.
static int _player_bonus_regen()
{
int rr = 0;
// Amulets, troll leather armour, and artefacts.
for (int slot = EQ_MIN_ARMOUR; slot <= EQ_MAX_WORN; ++slot)
{
if (you.melded[slot] || you.equip[slot] == -1 || !you.activated[slot])
continue;
const item_def &arm = you.inv[you.equip[slot]];
if (arm.base_type == OBJ_ARMOUR
&& armour_type_prop(arm.sub_type, ARMF_REGENERATION))
{
rr += REGEN_PIP;
}
if (arm.is_type(OBJ_JEWELLERY, AMU_REGENERATION))
rr += REGEN_PIP;
if (is_artefact(arm))
rr += REGEN_PIP * artefact_property(arm, ARTP_REGENERATION);
}
// Fast heal mutation.
rr += you.get_mutation_level(MUT_REGENERATION) * REGEN_PIP;
// Powered By Death mutation, boosts regen by variable strength
// if the duration of the effect is still active.
if (you.duration[DUR_POWERED_BY_DEATH])
rr += you.props[POWERED_BY_DEATH_KEY].get_int() * 100;
return rr;
}
/// Is the player's hp regeneration inhibited by nearby monsters?
bool regeneration_is_inhibited()
{
// used mainly for resting: don't add anything here that can be waited off
if (you.get_mutation_level(MUT_INHIBITED_REGENERATION) == 1
|| you.duration[DUR_COLLAPSE]
|| (you.has_mutation(MUT_VAMPIRISM) && !you.vampire_alive))
{
for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
{
if (mons_is_threatening(**mi)
&& !mi->wont_attack()
&& !mi->neutral()
&& !mi->submerged())
{
return true;
}
}
}
return false;
}
int player_regen()
{
// Note: if some condition can set rr = 0, can't be rested off, and
// would allow travel, please update is_sufficiently_rested.
int rr = you.hp_max / 3;
if (rr > 20)
rr = 20 + ((rr - 20) / 2);
// Add in miscellaneous bonuses
rr += _player_bonus_regen();
// Before applying other effects, make sure that there's something
// to heal.
rr = max(1, rr);
// Bonus regeneration for alive vampires.
if (you.has_mutation(MUT_VAMPIRISM) && you.vampire_alive)
rr += 20;
if (you.duration[DUR_SICKNESS]
|| !player_regenerates_hp())
{
rr = 0;
}
// Trog's Hand. This circumvents sickness or inhibited regeneration.
if (you.duration[DUR_TROGS_HAND])
rr += 100;
// Jiyva's passive healing also bypasses sickness, as befits a god.
if (have_passive(passive_t::jelly_regen))
{
// One regen pip at 1* piety, scaling to two pips at 6*.
// We use piety rank to avoid leaking piety info to the player.
rr += REGEN_PIP + (REGEN_PIP * (piety_rank(you.piety) - 1)) / 5;
}
return rr;
}
int player_mp_regen()
{
if (you.has_mutation(MUT_HP_CASTING))
return 0;
int regen_amount = 7 + you.max_magic_points / 2;
if (you.get_mutation_level(MUT_MANA_REGENERATION))
regen_amount *= 2;
if (you.wearing(EQ_AMULET, AMU_MANA_REGENERATION)
&& you.props[MANA_REGEN_AMULET_ACTIVE].get_int() == 1)
{
regen_amount += 40;
}
if (player_equip_unrand(UNRAND_POWER_GLOVES))
regen_amount += 40;
if (have_passive(passive_t::jelly_regen))
{
// We use piety rank to avoid leaking piety info to the player.
regen_amount += 25 + (25 * (piety_rank(you.piety) - 1)) / 5;
}
return regen_amount;
}
/**
* How many spell levels does the player have total, including those used up
* by memorised spells?
*/
int player_total_spell_levels()
{
return you.experience_level - 1 + you.skill(SK_SPELLCASTING, 2, false, false);
}
/**
* How many spell levels does the player currently have available for
* memorising new spells?
*/
int player_spell_levels(bool floored)
{
int sl = min(player_total_spell_levels(), 99);
for (const spell_type spell : you.spells)
{
if (spell != SPELL_NO_SPELL)
sl -= spell_difficulty(spell);
}
if (sl < 0 && floored)
sl = 0;
return sl;
}
// If temp is set to false, temporary sources or resistance won't be counted.
int player_res_fire(bool allow_random, bool temp, bool items)
{
int rf = 0;
if (items)
{
// rings of fire resistance/fire
rf += you.wearing(EQ_RINGS, RING_PROTECTION_FROM_FIRE);
rf += you.wearing(EQ_RINGS, RING_FIRE);
// rings of ice
rf -= you.wearing(EQ_RINGS, RING_ICE);
// Staves
rf += you.wearing(EQ_STAFF, STAFF_FIRE);
// body armour:
const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR);
if (body_armour)
rf += armour_type_prop(body_armour->sub_type, ARMF_RES_FIRE);
// ego armours
rf += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_FIRE_RESISTANCE);
rf += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_RESISTANCE);
// randart weapons:
rf += you.scan_artefacts(ARTP_FIRE);
// dragonskin cloak: 0.5 to draconic resistances
if (allow_random && player_equip_unrand(UNRAND_DRAGONSKIN)
&& coinflip())
{
rf++;
}
}
// mutations:
rf += you.get_mutation_level(MUT_HEAT_RESISTANCE, temp);
rf -= you.get_mutation_level(MUT_HEAT_VULNERABILITY, temp);
rf -= you.get_mutation_level(MUT_TEMPERATURE_SENSITIVITY, temp);
rf += you.get_mutation_level(MUT_MOLTEN_SCALES, temp) == 3 ? 1 : 0;
// spells:
if (temp)
{
if (you.duration[DUR_RESISTANCE])
rf++;
if (you.duration[DUR_QAZLAL_FIRE_RES])
rf++;
rf += get_form()->res_fire();
}
if (have_passive(passive_t::resist_fire))
++rf;
if (rf > 3)
rf = 3;
if (rf > 0 && you.penance[GOD_IGNIS])
rf = 0;
if (temp && you.duration[DUR_FIRE_VULN])
rf--;
if (rf < -3)
rf = -3;
return rf;
}
int player_res_steam(bool allow_random, bool temp, bool items)
{
int res = 0;
const int rf = player_res_fire(allow_random, temp, items);
res += you.get_mutation_level(MUT_STEAM_RESISTANCE) * 2;
if (items)
{
const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR);
if (body_armour)
res += armour_type_prop(body_armour->sub_type, ARMF_RES_STEAM) * 2;
}
res += rf * 2;
if (res > 2)
res = 2;
return res;
}
int player_res_cold(bool allow_random, bool temp, bool items)
{
int rc = 0;
if (temp)
{
if (you.duration[DUR_RESISTANCE])
rc++;
if (you.duration[DUR_QAZLAL_COLD_RES])
rc++;
rc += get_form()->res_cold();
// XX temp?
if (you.has_mutation(MUT_VAMPIRISM) && !you.vampire_alive)
rc += 2;
}
if (items)
{
// rings of cold resistance/ice
rc += you.wearing(EQ_RINGS, RING_PROTECTION_FROM_COLD);
rc += you.wearing(EQ_RINGS, RING_ICE);
// rings of fire
rc -= you.wearing(EQ_RINGS, RING_FIRE);
// Staves
rc += you.wearing(EQ_STAFF, STAFF_COLD);
// body armour:
const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR);
if (body_armour)
rc += armour_type_prop(body_armour->sub_type, ARMF_RES_COLD);
// ego armours
rc += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_COLD_RESISTANCE);
rc += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_RESISTANCE);
// randart weapons:
rc += you.scan_artefacts(ARTP_COLD);
// dragonskin cloak: 0.5 to draconic resistances
if (allow_random && player_equip_unrand(UNRAND_DRAGONSKIN)
&& coinflip())
{
rc++;
}
}
// mutations:
rc += you.get_mutation_level(MUT_COLD_RESISTANCE, temp);
rc -= you.get_mutation_level(MUT_COLD_VULNERABILITY, temp);
rc -= you.get_mutation_level(MUT_TEMPERATURE_SENSITIVITY, temp);
rc += you.get_mutation_level(MUT_ICY_BLUE_SCALES, temp) == 3 ? 1 : 0;
rc += you.get_mutation_level(MUT_SHAGGY_FUR, temp) == 3 ? 1 : 0;
if (rc < -3)
rc = -3;
else if (rc > 3)
rc = 3;
return rc;
}
bool player::res_corr(bool allow_random, bool temp) const
{
if (temp)
{
// dragonskin cloak: 0.5 to draconic resistances
if (allow_random && player_equip_unrand(UNRAND_DRAGONSKIN)
&& coinflip())
{
return true;
}
if (get_form()->res_acid())
return true;
if (you.duration[DUR_RESISTANCE])
return true;
}
if (have_passive(passive_t::resist_corrosion))
return true;
if (get_mutation_level(MUT_ACID_RESISTANCE))
return true;
// TODO: why doesn't this use the usual form suppression mechanism?
if (form_keeps_mutations()
&& get_mutation_level(MUT_YELLOW_SCALES) >= 3)
{
return true;
}
return actor::res_corr(allow_random, temp);
}
int player_res_acid(bool items)
{
return you.res_corr(items) ? 1 : 0;
}
int player_res_electricity(bool allow_random, bool temp, bool items)
{
int re = 0;
if (items)
{
// staff
re += you.wearing(EQ_STAFF, STAFF_AIR);
// body armour:
const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR);
if (body_armour)
re += armour_type_prop(body_armour->sub_type, ARMF_RES_ELEC);
// randart weapons:
re += you.scan_artefacts(ARTP_ELECTRICITY);
// dragonskin cloak: 0.5 to draconic resistances
if (allow_random && player_equip_unrand(UNRAND_DRAGONSKIN)
&& coinflip())
{
re++;
}
}
// mutations:
re += you.get_mutation_level(MUT_THIN_METALLIC_SCALES, temp) == 3 ? 1 : 0;
re += you.get_mutation_level(MUT_SHOCK_RESISTANCE, temp);
re -= you.get_mutation_level(MUT_SHOCK_VULNERABILITY, temp);
if (temp)
{
if (you.duration[DUR_RESISTANCE])
re++;
if (you.duration[DUR_QAZLAL_ELEC_RES])
re++;
// transformations:
if (get_form()->res_elec())
re++;
}
if (re > 1)
re = 1;
return re;
}
// Kiku protects you from torment to a degree.
bool player_kiku_res_torment()
{
// no protection during pain branding weapon
return have_passive(passive_t::resist_torment)
&& !(you_worship(GOD_KIKUBAAQUDGHA) && you.gift_timeout);
}
// If temp is set to false, temporary sources or resistance won't be counted.
int player_res_poison(bool allow_random, bool temp, bool items)
{
if (you.is_nonliving(temp)
|| you.is_lifeless_undead(temp)
|| temp && get_form()->res_pois() == 3
|| items && player_equip_unrand(UNRAND_OLGREB)
|| temp && you.duration[DUR_DIVINE_STAMINA])
{
return 3;
}
int rp = 0;
if (items)
{
// rings of poison resistance
rp += you.wearing(EQ_RINGS, RING_POISON_RESISTANCE);
// Staves
rp += you.wearing(EQ_STAFF, STAFF_POISON);
// ego armour:
rp += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_POISON_RESISTANCE);
// body armour:
const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR);
if (body_armour)
rp += armour_type_prop(body_armour->sub_type, ARMF_RES_POISON);
// rPois+ artefacts
rp += you.scan_artefacts(ARTP_POISON);
// dragonskin cloak: 0.5 to draconic resistances
if (allow_random && player_equip_unrand(UNRAND_DRAGONSKIN)
&& coinflip())
{
rp++;
}
}
// mutations:
rp += you.get_mutation_level(MUT_POISON_RESISTANCE, temp);
rp += you.get_mutation_level(MUT_SLIMY_GREEN_SCALES, temp) == 3 ? 1 : 0;
if (temp)
{
// potions/cards:
if (you.duration[DUR_RESISTANCE])
rp++;
if (get_form()->res_pois() > 0)
rp++;
}
// Cap rPois at + before vulnerability effects are applied
// (so carrying multiple rPois effects is never useful)
rp = min(1, rp);
if (temp)
{
if (get_form()->res_pois() < 0)
rp--;
if (you.duration[DUR_POISON_VULN])
rp--;
}
// don't allow rPois--, etc.
rp = max(-1, rp);
return rp;
}
int player_res_sticky_flame()
{
return get_form()->res_sticky_flame();
}
int player_spec_death()
{
int sd = 0;
// Staves
sd += you.wearing(EQ_STAFF, STAFF_DEATH);
// species:
sd += you.get_mutation_level(MUT_NECRO_ENHANCER);
// transformations:
if (you.form == transformation::lich)
sd++;
return sd;
}
int player_spec_fire()
{
int sf = 0;
// staves:
sf += you.wearing(EQ_STAFF, STAFF_FIRE);
// rings of fire:
sf += you.wearing(EQ_RINGS, RING_FIRE);
if (player_equip_unrand(UNRAND_SALAMANDER))
sf++;
if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF))
sf++;
return sf;
}
int player_spec_cold()
{
int sc = 0;
// staves:
sc += you.wearing(EQ_STAFF, STAFF_COLD);
// rings of ice:
sc += you.wearing(EQ_RINGS, RING_ICE);
if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF))
sc++;
return sc;
}
int player_spec_earth()
{
int se = 0;
// Staves
se += you.wearing(EQ_STAFF, STAFF_EARTH);
if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF))
se++;
return se;
}
int player_spec_air()
{
int sa = 0;
// Staves
sa += you.wearing(EQ_STAFF, STAFF_AIR);
if (player_equip_unrand(UNRAND_ELEMENTAL_STAFF))
sa++;
if (player_equip_unrand(UNRAND_AIR))
sa++;
return sa;
}
int player_spec_conj()
{
int sc = 0;
// Staves
sc += you.wearing(EQ_STAFF, STAFF_CONJURATION);
if (player_equip_unrand(UNRAND_BATTLE))
sc++;
return sc;
}
int player_spec_hex()
{
int sh = 0;
// Demonspawn mutation
sh += you.get_mutation_level(MUT_HEX_ENHANCER);
return sh;
}
int player_spec_summ()
{
return 0;
}
int player_spec_poison()
{
int sp = 0;
// Staves
sp += you.wearing(EQ_STAFF, STAFF_POISON);
if (player_equip_unrand(UNRAND_OLGREB))
sp++;
return sp;
}
// If temp is set to false, temporary sources of resistance won't be
// counted.
int player_prot_life(bool allow_random, bool temp, bool items)
{
int pl = 0;
// XX temp?
if (you.has_mutation(MUT_VAMPIRISM) && !you.vampire_alive)
pl = 3;
// piety-based rN doesn't count as temporary (XX why)
if (you_worship(GOD_SHINING_ONE))
{
if (you.piety >= piety_breakpoint(1))
pl++;
if (you.piety >= piety_breakpoint(3))
pl++;
if (you.piety >= piety_breakpoint(5))
pl++;
}
if (temp)
{
pl += get_form()->res_neg();
// completely stoned, unlike statue which has some life force
if (you.petrified())
pl += 3;
}
if (items)
{
// rings
pl += you.wearing(EQ_RINGS, RING_LIFE_PROTECTION);
// armour (checks body armour only)
pl += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_POSITIVE_ENERGY);
// pearl dragon counts
const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR);
if (body_armour)
pl += armour_type_prop(body_armour->sub_type, ARMF_RES_NEG);
// randart wpns
pl += you.scan_artefacts(ARTP_NEGATIVE_ENERGY);
// dragonskin cloak: 0.5 to draconic resistances
if (allow_random && player_equip_unrand(UNRAND_DRAGONSKIN)
&& coinflip())
{
pl++;
}
pl += you.wearing(EQ_STAFF, STAFF_DEATH);
}
// undead/demonic power
pl += you.get_mutation_level(MUT_NEGATIVE_ENERGY_RESISTANCE, temp);
pl = min(3, pl);
return pl;
}
// Even a slight speed advantage is very good... and we certainly don't
// want to go past 6 (see below). -- bwr
int player_movement_speed()
{
int mv = you.form == transformation::none
? 10
: form_base_movespeed(you.form);
if (feat_is_water(env.grid(you.pos())))
{
if (you.get_mutation_level(MUT_NIMBLE_SWIMMER) >= 2)
mv -= 4;
else if (you.in_water() && !you.can_swim())
mv += 6; // Wading through water is very slow.
}
// moving on liquefied ground, or while maintaining the
// effect takes longer
if (you.liquefied_ground() || you.duration[DUR_LIQUEFYING])
mv += 3;
// armour
if (player_equip_unrand(UNRAND_LIGHTNING_SCALES))
mv -= 1;
mv += you.wearing_ego(EQ_ALL_ARMOUR, SPARM_PONDEROUSNESS);
// Cheibriados
if (have_passive(passive_t::slowed))
mv += 2 + min(div_rand_round(you.piety, 20), 8);
else if (player_under_penance(GOD_CHEIBRIADOS))
mv += 2 + min(div_rand_round(you.piety_max[GOD_CHEIBRIADOS], 20), 8);
// Tengu can move slightly faster when flying.
if (you.tengu_flight())
mv--;
if (you.duration[DUR_FROZEN])
mv += 3;
// Mutations: -2, -3, -4, unless innate and shapechanged.
if (int fast = you.get_mutation_level(MUT_FAST))
mv -= fast + 1;
if (int slow = you.get_mutation_level(MUT_SLOW))
{
mv *= 10 + slow * 2;
mv /= 10;
}
if (you.duration[DUR_SWIFTNESS] > 0 && !you.in_liquid())
{
if (you.attribute[ATTR_SWIFTNESS] > 0)
mv = div_rand_round(3*mv, 4);
else if (mv >= 8)
mv = div_rand_round(3*mv, 2);
else if (mv == 7)
mv = div_rand_round(7*6, 5); // balance for the cap at 6
}
// We'll use the old value of six as a minimum, with haste this could
// end up as a speed of three, which is about as fast as we want
// the player to be able to go (since 3 is 3.33x as fast and 2 is 5x,
// which is a bit of a jump, and a bit too fast) -- bwr
// Currently Haste takes 6 to 4, which is 2.5x as fast as delay 10
// and still seems plenty fast. -- elliptic
if (mv < FASTEST_PLAYER_MOVE_SPEED)
mv = FASTEST_PLAYER_MOVE_SPEED;
return mv;
}
/**
* Multiply the power of some evocation per the player's current evocations
* enhancers.
*
* @param power The base power of the evocation.
* @param enhancers Bonus enhancers to evocations (pak device surge).
* @return A modified power value.
*/
int player_adjust_evoc_power(const int power, int enhancers)
{
const int total_enhancers = you.spec_evoke() + enhancers;
return stepdown_spellpower(100 *apply_enhancement(power, total_enhancers));
}
// This function differs from the above in that it's used to set the
// initial time_taken value for the turn. Everything else (movement,
// spellcasting, combat) applies a ratio to this value.
int player_speed()
{
int ps = 10;
// When paralysed, speed is irrelevant.
if (you.cannot_act())
return ps;
if (you.duration[DUR_SLOW] || have_stat_zero())
ps = haste_mul(ps);
if (you.duration[DUR_BERSERK] && !have_passive(passive_t::no_haste))
ps = berserk_div(ps);
else if (you.duration[DUR_HASTE])
ps = haste_div(ps);
if (you.form == transformation::statue || you.duration[DUR_PETRIFYING])
{
ps *= 15;
ps /= 10;
}
return ps;
}
bool is_effectively_light_armour(const item_def *item)
{
return !item
|| (abs(property(*item, PARM_EVASION)) / 10 < 5);
}
bool player_effectively_in_light_armour()
{
const item_def *armour = you.slot_item(EQ_BODY_ARMOUR, false);
return is_effectively_light_armour(armour);
}
// This function returns true if the player has a radically different
// shape... minor changes like blade hands don't count, also note
// that lich transformation doesn't change the character's shape
// (so we end up with Naga-liches, Spriggan-liches, Minotaur-liches)
// it just makes the character undead (with the benefits that implies). - bwr
bool player_is_shapechanged()
{
if (you.form == transformation::none
|| you.form == transformation::blade_hands
|| you.form == transformation::lich
|| you.form == transformation::shadow
|| you.form == transformation::appendage)
{
return false;
}
return true;
}
void update_acrobat_status()
{
if (!you.wearing(EQ_AMULET, AMU_ACROBAT))
return;
// Acrobat duration goes slightly into the next turn, giving the
// player visual feedback of the EV bonus recieved.
// This is assignment and not increment as acrobat duration depends
// on player action.
you.duration[DUR_ACROBAT] = you.time_taken+1;
you.redraw_evasion = true;
}
// An evasion factor based on the player's body size, smaller == higher
// evasion size factor.
static int _player_evasion_size_factor(bool base = false)
{
// XXX: you.body_size() implementations are incomplete, fix.
const size_type size = you.body_size(PSIZE_BODY, base);
return 2 * (SIZE_MEDIUM - size);
}
// Determines racial shield penalties (formicids get a bonus compared to
// other medium-sized races)
int player_shield_racial_factor()
{
return you.has_mutation(MUT_QUADRUMANOUS) ? -2 // Same as trolls, etc.
: _player_evasion_size_factor(true);
}
// The total EV penalty to the player for all their worn armour items
// with a base EV penalty (i.e. EV penalty as a base armour property,
// not as a randart property).
static int _player_adjusted_evasion_penalty(const int scale)
{
int piece_armour_evasion_penalty = 0;
// Some lesser armours have small penalties now (barding).
for (int i = EQ_MIN_ARMOUR; i < EQ_MAX_ARMOUR; i++)
{
if (i == EQ_SHIELD || !you.slot_item(static_cast<equipment_type>(i)))
continue;
// [ds] Evasion modifiers for armour are negatives, change
// those to positive for penalty calc.
const int penalty = (-property(you.inv[you.equip[i]], PARM_EVASION))/3;
if (penalty > 0)
piece_armour_evasion_penalty += penalty;
}
return piece_armour_evasion_penalty * scale / 10 +
you.adjusted_body_armour_penalty(scale);
}
// Player EV bonuses for various effects and transformations. This
// does not include tengu/merfolk EV bonuses for flight/swimming.
static int _player_evasion_bonuses()
{
int evbonus = 0;
if (you.duration[DUR_AGILITY])
evbonus += AGILITY_BONUS;
evbonus += you.wearing(EQ_RINGS_PLUS, RING_EVASION);
evbonus += you.scan_artefacts(ARTP_EVASION);
// mutations
evbonus += you.get_mutation_level(MUT_GELATINOUS_BODY);
if (you.get_mutation_level(MUT_DISTORTION_FIELD))
evbonus += you.get_mutation_level(MUT_DISTORTION_FIELD) + 1;
// transformation penalties/bonuses not covered by size alone:
if (you.get_mutation_level(MUT_SLOW_REFLEXES))
evbonus -= you.get_mutation_level(MUT_SLOW_REFLEXES) * 5;
if (you.props.exists(AIRFORM_POWER_KEY))
evbonus += you.props[AIRFORM_POWER_KEY].get_int() / 10;
if (you.props.exists(WU_JIAN_HEAVENLY_STORM_KEY))
evbonus += you.props[WU_JIAN_HEAVENLY_STORM_KEY].get_int();
// If you have an active amulet of the acrobat and just moved or waited,
// get a massive EV bonus.
if (acrobat_boost_active())
evbonus += 15;
return evbonus;
}
// Player EV scaling for being flying tengu or swimming merfolk.
static int _player_scale_evasion(int prescaled_ev, const int scale)
{
if (you.duration[DUR_PETRIFYING] || you.caught())
prescaled_ev /= 2;
// Merfolk get a 25% evasion bonus near water.
if (feat_is_water(env.grid(you.pos()))
&& you.get_mutation_level(MUT_NIMBLE_SWIMMER) >= 2)
{
const int ev_bonus = max(2 * scale, prescaled_ev / 4);
return prescaled_ev + ev_bonus;
}
// Flying Tengu get a 20% evasion bonus.
if (you.tengu_flight())
{
const int ev_bonus = max(1 * scale, prescaled_ev / 5);
return prescaled_ev + ev_bonus;
}
return prescaled_ev;
}
/**
* What is the player's bonus to EV from dodging when not paralysed, after
* accounting for size & body armour penalties?
*
* First, calculate base dodge bonus (linear with dodging * dex),
* and armour dodge penalty (base armour evp, increased for small races &
* decreased for large, then with a magic "3" subtracted from it to make the
* penalties not too harsh).
*
* If the player's strength is greater than the armour dodge penalty, return
* base dodge * (1 - dodge_pen / (str*2)).
* E.g., if str is twice dodge penalty, return 3/4 of base dodge. If
* str = dodge_pen * 4, return 7/8...
*
* If str is less than dodge penalty, return
* base_dodge * str / (dodge_pen * 2).
* E.g., if str = dodge_pen / 2, return 1/4 of base dodge. if
* str = dodge_pen / 4, return 1/8...
*
* For either equation, if str = dodge_pen, the result is base_dodge/2.
*
* @param scale A scale to multiply the result by, to avoid precision loss.
* @return A bonus to EV, multiplied by the scale.
*/
static int _player_armour_adjusted_dodge_bonus(int scale)
{
const int dodge_bonus =
(800 + you.skill(SK_DODGING, 10) * you.dex() * 8) * scale
/ (20 - _player_evasion_size_factor()) / 10 / 10;
const int armour_dodge_penalty = you.unadjusted_body_armour_penalty() - 3;
if (armour_dodge_penalty <= 0)
return dodge_bonus;
const int str = max(1, you.strength());
if (armour_dodge_penalty >= str)
return dodge_bonus * str / (armour_dodge_penalty * 2);
return dodge_bonus - dodge_bonus * armour_dodge_penalty / (str * 2);
}
// Total EV for player using the revised 0.6 evasion model.
static int _player_evasion(bool ignore_helpless)
{
const int size_factor = _player_evasion_size_factor();
// Size is all that matters when paralysed or at 0 dex.
if ((you.cannot_act() || you.duration[DUR_CLUMSY]
|| you.form == transformation::tree)
&& !ignore_helpless)
{
return max(1, 2 + size_factor / 2);
}
const int scale = 100;
const int size_base_ev = (10 + size_factor) * scale;
const int vertigo_penalty = you.duration[DUR_VERTIGO] ? 5 * scale : 0;
const int natural_evasion =
size_base_ev
+ _player_armour_adjusted_dodge_bonus(scale)
- _player_adjusted_evasion_penalty(scale)
- you.adjusted_shield_penalty(scale)
- vertigo_penalty;
const int evasion_bonuses = _player_evasion_bonuses() * scale;
const int final_evasion =
_player_scale_evasion(natural_evasion, scale) + evasion_bonuses;
return unscale_round_up(final_evasion, scale);
}
// Returns the spellcasting penalty (increase in spell failure) for the
// player's worn body armour and shield.
int player_armour_shield_spell_penalty()
{
const int scale = 100;
const int body_armour_penalty =
max(19 * you.adjusted_body_armour_penalty(scale), 0);
const int total_penalty = body_armour_penalty
+ 19 * you.adjusted_shield_penalty(scale);
return max(total_penalty, 0) / scale;
}
/**
* How many spell-success-chance-boosting ('wizardry') effects can the player
* apply to the given spell?
*
* @param spell The type of spell being cast.
* @return The number of relevant wizardry effects.
*/
int player_wizardry(spell_type /*spell*/)
{
return you.wearing(EQ_RINGS, RING_WIZARDRY)
+ (you.get_mutation_level(MUT_BIG_BRAIN) == 3 ? 1 : 0);
}
static int _sh_from_shield(const item_def &item)
{
if (item.sub_type == ARM_ORB)
return 0;
int size_factor = (you.body_size(PSIZE_TORSO) - SIZE_MEDIUM)
* (item.sub_type - ARM_TOWER_SHIELD);
int base_shield = property(item, PARM_AC) * 2 + size_factor;
// bonus applied only to base, see above for effect:
int shield = base_shield * 50;
shield += base_shield * you.skill(SK_SHIELDS, 5) / 2;
shield += item.plus * 200;
shield += you.skill(SK_SHIELDS, 38)
+ min(you.skill(SK_SHIELDS, 38), 3 * 38);
shield += you.dex() * 38 * (base_shield + 13) / 26;
return shield;
}
/**
* Calculate the SH value used internally.
*
* Exactly twice the value displayed to players, for legacy reasons.
* @return The player's current SH value.
*/
int player_shield_class()
{
int shield = 0;
if (you.incapacitated())
return 0;
if (you.shield())
shield += _sh_from_shield(you.inv[you.equip[EQ_SHIELD]]);
// mutations
// +4, +6, +8 (displayed values)
shield += (you.get_mutation_level(MUT_LARGE_BONE_PLATES) > 0
? you.get_mutation_level(MUT_LARGE_BONE_PLATES) * 400 + 400
: 0);
if (you.get_mutation_level(MUT_CONDENSATION_SHIELD) > 0
&& !you.duration[DUR_ICEMAIL_DEPLETED])
{
shield += ICEMAIL_MAX * 100;
}
shield += qazlal_sh_boost() * 100;
shield += tso_sh_boost() * 100;
shield += you.wearing(EQ_AMULET, AMU_REFLECTION) * AMU_REFLECT_SH * 100;
shield += you.scan_artefacts(ARTP_SHIELDING) * 200;
return (shield + 50) / 100;
}
/**
* Calculate the SH value that should be displayed to players.
*
* Exactly half the internal value, for legacy reasons.
* @return The SH value to be displayed.
*/
int player_displayed_shield_class()
{
return player_shield_class() / 2;
}
/**
* Does the player have 'omnireflection' (the ability to reflect piercing
* effects and enchantments)?
*
* @return Whether the player has the Warlock's Mirror equipped.
*/
bool player_omnireflects()
{
return player_equip_unrand(UNRAND_WARLOCK_MIRROR);
}
void forget_map(bool rot)
{
ASSERT(!crawl_state.game_is_arena());
// If forgetting was intentional, clear the travel trail.
if (!rot)
clear_travel_trail();
const bool rot_resist = player_in_branch(BRANCH_ABYSS)
&& have_passive(passive_t::map_rot_res_abyss);
const double geometric_chance = 0.99;
const int radius = (rot_resist ? 200 : 100);
const int scalar = 0xFF;
for (rectangle_iterator ri(0); ri; ++ri)
{
const coord_def &p = *ri;
if (!env.map_knowledge(p).known() || you.see_cell(p))
continue;
if (rot)
{
const int dist = grid_distance(you.pos(), p);
int chance = pow(geometric_chance,
max(1, (dist * dist - radius) / 40)) * scalar;
if (x_chance_in_y(chance, scalar))
continue;
}
if (you.see_cell(p))
continue;
env.map_knowledge(p).clear();
if (env.map_forgotten)
(*env.map_forgotten)(p).clear();
StashTrack.update_stash(p);
#ifdef USE_TILE
tile_forget_map(p);
#endif
}
ash_detect_portals(is_map_persistent());
#ifdef USE_TILE
tiles.update_minimap_bounds();
#endif
}
static void _recover_stat()
{
FixedVector<int, NUM_STATS> recovered_stats(0);
while (you.attribute[ATTR_STAT_LOSS_XP] <= 0)
{
stat_type stat = random_lost_stat();
ASSERT(stat != NUM_STATS);
recovered_stats[stat]++;
// Very heavily drained stats recover faster.
if (you.stat(stat, false) < 0)
recovered_stats[stat] += random2(-you.stat(stat, false) / 2);
bool still_drained = false;
for (int i = 0; i < NUM_STATS; ++i)
if (you.stat_loss[i] - recovered_stats[i] > 0)
still_drained = true;
if (still_drained)
you.attribute[ATTR_STAT_LOSS_XP] += stat_loss_roll();
else
break;
}
for (int i = 0; i < NUM_STATS; ++i)
if (recovered_stats[i] > 0)
restore_stat((stat_type) i, recovered_stats[i], false, true);
}
int get_exp_progress()
{
if (you.experience_level >= you.get_max_xl())
return 0;
const int current = exp_needed(you.experience_level);
const int next = exp_needed(you.experience_level + 1);
if (next == current)
return 0;
return (you.experience - current) * 100 / (next - current);
}
static void _recharge_xp_evokers(int exp)
{
FixedVector<item_def*, NUM_MISCELLANY> evokers(nullptr);
list_charging_evokers(evokers);
int xp_factor = max(min((int)exp_needed(you.experience_level+1, 0) * 2 / 7,
you.experience_level * 425),
you.experience_level*4 + 30)
/ (3 + you.skill_rdiv(SK_EVOCATIONS, 2, 13));
for (int i = 0; i < NUM_MISCELLANY; ++i)
{
item_def* evoker = evokers[i];
if (!evoker)
continue;
int &debt = evoker_debt(evoker->sub_type);
if (debt == 0)
continue;
const int old_charges = evoker_charges(i);
debt = max(0, debt - div_rand_round(exp, xp_factor));
const int gained = evoker_charges(i) - old_charges;
if (!gained)
continue;
if (evoker_max_charges(i) == 1)
mprf("%s has recharged.", evoker->name(DESC_YOUR).c_str());
else
{
mprf("%s has regained %s charge%s.",
evoker->name(DESC_YOUR).c_str(),
number_in_words(gained).c_str(), gained > 1 ? "s" : "");
}
}
}
/// Make progress toward the abyss spawning an exit/stairs.
static void _reduce_abyss_xp_timer(int exp)
{
if (!player_in_branch(BRANCH_ABYSS))
return;
const int xp_factor =
max(min((int)exp_needed(you.experience_level+1, 0) / 7,
you.experience_level * 425),
you.experience_level*2 + 15) / 5;
if (!you.props.exists(ABYSS_STAIR_XP_KEY))
you.props[ABYSS_STAIR_XP_KEY] = EXIT_XP_COST;
const int reqd_xp = you.props[ABYSS_STAIR_XP_KEY].get_int();
const int new_req = reqd_xp - div_rand_round(exp, xp_factor);
dprf("reducing xp timer from %d to %d (factor = %d)",
reqd_xp, new_req, xp_factor);
you.props[ABYSS_STAIR_XP_KEY].get_int() = new_req;
}
/// update penance for XP based gods
static void _handle_xp_penance(int exp)
{
vector<god_type> xp_gods;
for (god_iterator it; it; ++it)
{
if (xp_penance(*it))
xp_gods.push_back(*it);
}
if (!xp_gods.empty())
{
god_type god = xp_gods[random2(xp_gods.size())];
reduce_xp_penance(god, exp);
}
}
/// update temporary mutations
static void _handle_temp_mutation(int exp)
{
if (!(you.attribute[ATTR_TEMP_MUTATIONS] > 0))
return;
you.attribute[ATTR_TEMP_MUT_XP] -= exp;
if (you.attribute[ATTR_TEMP_MUT_XP] <= 0)
temp_mutation_wanes();
}
/// update stat loss
static void _handle_stat_loss(int exp)
{
if (!(you.attribute[ATTR_STAT_LOSS_XP] > 0))
return;
int loss = div_rand_round(exp * 3 / 2,
max(1, calc_skill_cost(you.skill_cost_level) - 3));
you.attribute[ATTR_STAT_LOSS_XP] -= loss;
dprf("Stat loss points: %d", you.attribute[ATTR_STAT_LOSS_XP]);
if (you.attribute[ATTR_STAT_LOSS_XP] <= 0)
_recover_stat();
}
/// update hp drain
static void _handle_hp_drain(int exp)
{
if (!you.hp_max_adj_temp)
return;
int loss = div_rand_round(exp, 4 * calc_skill_cost(you.skill_cost_level));
// Make it easier to recover from very heavy levels of draining
// (they're nasty enough as it is)
loss = loss * (1 + (-you.hp_max_adj_temp / 25.0f));
dprf("Lost %d of %d draining points", loss, -you.hp_max_adj_temp);
you.hp_max_adj_temp += loss;
const bool drain_removed = you.hp_max_adj_temp >= 0;
if (drain_removed)
you.hp_max_adj_temp = 0;
calc_hp();
if (drain_removed)
mprf(MSGCH_RECOVERY, "Your life force feels restored.");
}
static void _handle_god_wrath(int exp)
{
for (god_iterator it; it; ++it)
{
if (active_penance(*it))
{
you.attribute[ATTR_GOD_WRATH_XP] -= exp;
while (you.attribute[ATTR_GOD_WRATH_XP] < 0)
{
you.attribute[ATTR_GOD_WRATH_COUNT]++;
set_penance_xp_timeout();
}
break;
}
}
}
unsigned int gain_exp(unsigned int exp_gained)
{
if (crawl_state.game_is_arena())
return 0;
you.experience_pool += exp_gained;
if (player_under_penance(GOD_HEPLIAKLQANA))
return 0; // no XP for you!
const unsigned int max_gain = (unsigned int)MAX_EXP_TOTAL - you.experience;
if (max_gain < exp_gained)
return max_gain;
return exp_gained;
}
void apply_exp()
{
const unsigned int exp_gained = you.experience_pool;
if (exp_gained == 0)
return;
you.experience_pool = 0;
// xp-gated effects that don't use sprint inflation
_handle_xp_penance(exp_gained);
_handle_god_wrath(exp_gained);
// evolution mutation timer
if (you.attribute[ATTR_EVOL_XP] > 0)
you.attribute[ATTR_EVOL_XP] -= exp_gained;
// modified experience due to sprint inflation
unsigned int skill_xp = exp_gained;
if (crawl_state.game_is_sprint())
skill_xp = sprint_modify_exp(skill_xp);
// xp-gated effects that use sprint inflation
_handle_stat_loss(skill_xp);
_handle_temp_mutation(skill_xp);
_recharge_xp_evokers(skill_xp);
_reduce_abyss_xp_timer(skill_xp);
_handle_hp_drain(skill_xp);
if (player_under_penance(GOD_HEPLIAKLQANA))
return; // no xp for you!
// handle actual experience gains,
// i.e. XL and skills
dprf("gain_exp: %d", exp_gained);
if (you.experience + exp_gained > (unsigned int)MAX_EXP_TOTAL)
you.experience = MAX_EXP_TOTAL;
else
you.experience += exp_gained;
you.exp_available += 10 * skill_xp;
train_skills();
while (check_selected_skills()
&& you.exp_available >= calc_skill_cost(you.skill_cost_level))
{
train_skills();
}
level_change();
}
bool will_gain_life(int lev)
{
if (lev < you.attribute[ATTR_LIFE_GAINED] - 2)
return false;
return you.lives + you.deaths < (lev - 1) / 3;
}
static void _felid_extra_life()
{
if (will_gain_life(you.max_level)
&& you.lives < 2)
{
you.lives++;
mprf(MSGCH_INTRINSIC_GAIN, "Extra life!");
you.attribute[ATTR_LIFE_GAINED] = you.max_level;
// Should play the 1UP sound from SMB...
}
}
static void _gain_and_note_hp_mp()
{
const int old_mp = you.magic_points;
const int old_maxmp = you.max_magic_points;
// recalculate for game
calc_hp(true, false);
calc_mp();
set_mp(old_maxmp > 0 ? old_mp * you.max_magic_points / old_maxmp
: you.max_magic_points);
// Get "real" values for note-taking, i.e. ignore Berserk,
// transformations or equipped items.
const int note_maxhp = get_real_hp(false, true);
const int note_maxmp = get_real_mp(false);
char buf[200];
sprintf(buf, "HP: %d/%d MP: %d/%d",
min(you.hp, note_maxhp), note_maxhp,
min(you.magic_points, note_maxmp), note_maxmp);
take_note(Note(NOTE_XP_LEVEL_CHANGE, you.experience_level, 0, buf));
}
static int _rest_trigger_level(int max)
{
return (max * Options.rest_wait_percent) / 100;
}
static bool _should_stop_resting(int cur, int max)
{
return cur == max || cur == _rest_trigger_level(max);
}
/**
* Calculate max HP changes and scale current HP accordingly.
*/
void calc_hp(bool scale, bool set)
{
// Rounding must be down or Deep Dwarves would abuse certain values.
// We can reduce errors by a factor of 100 by using partial hp we have.
int oldhp = you.hp;
int old_max = you.hp_max;
you.hp_max = get_real_hp(true, true);
if (scale)
{
int hp = you.hp * 100 + you.hit_points_regeneration;
int new_max = you.hp_max;
hp = hp * new_max / old_max;
if (hp < 100)
hp = 100;
set_hp(min(hp / 100, you.hp_max));
you.hit_points_regeneration = hp % 100;
}
if (set)
you.hp = you.hp_max;
you.hp = min(you.hp, you.hp_max);
if (oldhp != you.hp || old_max != you.hp_max)
{
if (_should_stop_resting(you.hp, you.hp_max))
interrupt_activity(activity_interrupt::full_hp);
dprf("HP changed: %d/%d -> %d/%d", oldhp, old_max, you.hp, you.hp_max);
you.redraw_hit_points = true;
}
}
int xp_to_level_diff(int xp, int scale)
{
ASSERT(xp >= 0);
const int adjusted_xp = you.experience + xp;
int projected_level = you.experience_level;
while (you.experience >= exp_needed(projected_level + 1))
projected_level++; // handle xl 27 chars
int adjusted_level = projected_level;
// closest whole number level, rounding down
while (adjusted_xp >= (int) exp_needed(adjusted_level + 1))
adjusted_level++;
if (scale > 1)
{
// TODO: what is up with all the casts here?
// decimal scaled version of current level including whatever fractional
// part scale can handle
const int cur_level_scaled = projected_level * scale
+ (you.experience - (int) exp_needed(projected_level)) * scale /
((int) exp_needed(projected_level + 1)
- (int) exp_needed(projected_level));
// decimal scaled version of what adjusted_xp would get you
const int adjusted_level_scaled = adjusted_level * scale
+ (adjusted_xp - (int) exp_needed(adjusted_level)) * scale /
((int) exp_needed(adjusted_level + 1)
- (int) exp_needed(adjusted_level));
// TODO: this would be more usable with better rounding behaviour
return adjusted_level_scaled - cur_level_scaled;
}
else
return adjusted_level - projected_level;
}
static void _gain_innate_spells()
{
auto &spell_vec = you.props[INNATE_SPELLS_KEY].get_vector();
// Gain spells at every odd XL, starting at XL 3 and continuing to XL 27.
for (int i = 0; i < spell_vec.size() && i < (you.experience_level - 1) / 2;
i++)
{
const spell_type spell = (spell_type)spell_vec[i].get_int();
if (spell == SPELL_NO_SPELL)
continue; // spell lost due to lack of slots
auto spindex = find(begin(you.spells), end(you.spells), spell);
if (spindex != end(you.spells))
continue; // already learned that one
// XXX: this shouldn't be able to happen, but rare Wanderer starts
// could give out too many spells and hit the cap.
if (you.spell_no >= MAX_KNOWN_SPELLS)
{
for (int j = 0; j < i; j++)
{
const spell_type oldspell = (spell_type)spell_vec[j].get_int();
if (oldspell == SPELL_NO_SPELL)
continue;
auto oldindex = find(begin(you.spells), end(you.spells),
oldspell);
if (oldindex != end(you.spells))
{
mpr("Your capacity for spells is full, and you lose "
"access to an earlier spell.");
del_spell_from_memory(oldspell);
spell_vec[j].get_int() = SPELL_NO_SPELL;
break;
}
}
// If somehow a slot can't be freed, give up and lose the spell.
// This extremely shouldn't happen.
if (you.spell_no >= MAX_KNOWN_SPELLS)
{
spell_vec[i].get_int() = SPELL_NO_SPELL;
continue;
}
}
mprf("The power to cast %s wells up from within.", spell_title(spell));
add_spell_to_memory(spell);
}
}
/**
* Handle the effects from a player's change in XL.
* @param aux A string describing the cause of the level
* change.
* @param skip_attribute_increase If true and XL has increased, don't process
* stat gains. Currently only used by wizmode
* commands.
*/
void level_change(bool skip_attribute_increase)
{
// necessary for the time being, as level_change() is called
// directly sometimes {dlb}
you.redraw_experience = true;
while (you.experience < exp_needed(you.experience_level))
lose_level();
while (you.experience_level < you.get_max_xl()
&& you.experience >= exp_needed(you.experience_level + 1))
{
if (!skip_attribute_increase)
{
crawl_state.cancel_cmd_all();
if (is_processing_macro())
flush_input_buffer(FLUSH_ABORT_MACRO);
}
// [ds] Make sure we increment you.experience_level and apply
// any stat/hp increases only after we've cleared all prompts
// for this experience level. If we do part of the work before
// the prompt, and a player on telnet gets disconnected, the
// SIGHUP will save Crawl in the in-between state and rob the
// player of their level-up perks.
const int new_exp = you.experience_level + 1;
// some species need to do this at a specific time; most just do it at the end
bool updated_maxhp = false;
if (new_exp <= you.max_level)
{
mprf(MSGCH_INTRINSIC_GAIN,
"Welcome back to level %d!", new_exp);
// No more prompts for this XL past this point.
you.experience_level = new_exp;
}
else // Character has gained a new level
{
// Don't want to see the dead creature at the prompt.
redraw_screen();
update_screen();
if (new_exp == 27)
mprf(MSGCH_INTRINSIC_GAIN, "You have reached level 27, the final one!");
else if (new_exp == you.get_max_xl())
mprf(MSGCH_INTRINSIC_GAIN, "You have reached level %d, the highest you will ever reach!",
you.get_max_xl());
else
{
mprf(MSGCH_INTRINSIC_GAIN, "You have reached level %d!",
new_exp);
}
const bool manual_stat_level = you.has_mutation(MUT_DIVINE_ATTRS)
? (new_exp % 3 == 0) // 3,6,9,12...
: (new_exp % 6 == 3); // 3,9,15,21,27
// Must do this before actually changing experience_level,
// so we will re-prompt on load if a hup is received.
if (manual_stat_level && !skip_attribute_increase)
if (!attribute_increase())
return; // abort level gain, the xp is still there
// Set this after printing, since a more() might clear it.
you.redraw_experience = true;
crawl_state.stat_gain_prompt = false;
you.experience_level = new_exp;
you.max_level = you.experience_level;
#ifdef USE_TILE_LOCAL
// In case of intrinsic ability changes.
tiles.layout_statcol();
redraw_screen();
update_screen();
#endif
if (!skip_attribute_increase)
species_stat_gain(you.species);
switch (you.species)
{
case SP_NAGA:
if (!(you.experience_level % 3))
{
mprf(MSGCH_INTRINSIC_GAIN, "Your skin feels tougher.");
you.redraw_armour_class = true;
}
break;
case SP_BASE_DRACONIAN:
if (you.experience_level >= 7)
{
// XX make seed stable by choosing at birth
you.species = species::random_draconian_colour();
// We just changed our aptitudes, so some skills may now
// be at the wrong level (with negative progress); if we
// print anything in this condition, we might trigger a
// --More--, a redraw, and a crash (#6376 on Mantis).
//
// Hence we first fix up our skill levels silently (passing
// do_level_up = false) but save the old values; then when
// we want the messages later, we restore the old skill
// levels and call check_skill_level_change() again, this
// time passing do_level_up = true.
uint8_t saved_skills[NUM_SKILLS];
for (skill_type sk = SK_FIRST_SKILL; sk < NUM_SKILLS; ++sk)
{
saved_skills[sk] = you.skills[sk];
check_skill_level_change(sk, false);
}
// The player symbol depends on species.
update_player_symbol();
#ifdef USE_TILE
init_player_doll();
#endif
mprf(MSGCH_INTRINSIC_GAIN,
"Your scales start taking on %s colour.",
article_a(species::scale_type(you.species)).c_str());
// Produce messages about skill increases/decreases. We
// restore one skill level at a time so that at most the
// skill being checked is at the wrong level.
for (skill_type sk = SK_FIRST_SKILL; sk < NUM_SKILLS; ++sk)
{
const int oldapt = species_apt(sk, SP_BASE_DRACONIAN);
const int newapt = species_apt(sk, you.species);
if (oldapt != newapt)
{
mprf(MSGCH_INTRINSIC_GAIN, "You learn %s %s%s.",
skill_name(sk),
abs(oldapt - newapt) > 1 ? "much " : "",
oldapt > newapt ? "slower" : "quicker");
}
you.skills[sk] = saved_skills[sk];
check_skill_level_change(sk);
}
// It's possible we passed a training target due to
// skills being rescaled to new aptitudes. Thus, we must
// check the training targets.
check_training_targets();
// Tell the player about their new species
for (auto &mut : species::fake_mutations(you.species, false))
mprf(MSGCH_INTRINSIC_GAIN, "%s", mut.c_str());
// needs to be done early here, so HP doesn't look drained
// when we redraw the screen
_gain_and_note_hp_mp();
updated_maxhp = true;
#ifdef USE_TILE_LOCAL
tiles.layout_statcol();
#endif
redraw_screen();
update_screen();
}
break;
case SP_DEMONSPAWN:
{
bool gave_message = false;
int level = 0;
mutation_type first_body_facet = NUM_MUTATIONS;
for (const player::demon_trait trait : you.demonic_traits)
{
if (is_body_facet(trait.mutation))
{
if (first_body_facet < NUM_MUTATIONS
&& trait.mutation != first_body_facet)
{
if (you.experience_level == level)
{
mprf(MSGCH_MUTATION, "You feel monstrous as "
"your demonic heritage exerts itself.");
mark_milestone("monstrous", "discovered their "
"monstrous ancestry!");
take_note(Note(NOTE_MESSAGE, 0, 0,
"Discovered your monstrous ancestry."));
}
break;
}
if (first_body_facet == NUM_MUTATIONS)
{
first_body_facet = trait.mutation;
level = trait.level_gained;
}
}
}
for (const player::demon_trait trait : you.demonic_traits)
{
if (trait.level_gained == you.experience_level)
{
if (!gave_message)
{
mprf(MSGCH_INTRINSIC_GAIN,
"Your demonic ancestry asserts itself...");
gave_message = true;
}
perma_mutate(trait.mutation, 1, "demonic ancestry");
}
}
break;
}
default:
break;
}
if (you.has_mutation(MUT_MULTILIVED))
_felid_extra_life();
give_level_mutations(you.species, you.experience_level);
}
if (species::is_draconian(you.species) && !(you.experience_level % 3))
{
mprf(MSGCH_INTRINSIC_GAIN, "Your scales feel tougher.");
you.redraw_armour_class = true;
}
if (!updated_maxhp)
_gain_and_note_hp_mp();
if (you.has_mutation(MUT_INNATE_CASTER))
_gain_innate_spells();
xom_is_stimulated(12);
if (in_good_standing(GOD_HEPLIAKLQANA))
upgrade_hepliaklqana_ancestor();
learned_something_new(HINT_NEW_LEVEL);
}
while (you.experience >= exp_needed(you.max_level + 1))
{
ASSERT(you.experience_level == you.get_max_xl());
ASSERT(you.max_level < 127); // marshalled as an 1-byte value
you.max_level++;
if (you.has_mutation(MUT_MULTILIVED))
_felid_extra_life();
}
you.redraw_title = true;
update_whereis();
// Hints mode arbitrarily ends at xp 7.
if (crawl_state.game_is_hints() && you.experience_level >= 7)
hints_finished();
}
void adjust_level(int diff, bool just_xp)
{
ASSERT((uint64_t)you.experience <= (uint64_t)MAX_EXP_TOTAL);
const int max_exp_level = you.get_max_xl();
if (you.experience_level + diff < 1)
you.experience = 0;
else if (you.experience_level + diff >= max_exp_level)
{
const unsigned needed = exp_needed(max_exp_level);
// Level gain when already at max should never reduce player XP;
// but level loss (diff < 0) should.
if (diff < 0 || you.experience < needed)
you.experience = needed;
}
else
{
while (diff < 0 && you.experience >=
exp_needed(max_exp_level))
{
// Having XP for level 53 and going back to 26 due to a single
// card would mean your felid is not going to get any extra lives
// in foreseable future.
you.experience -= exp_needed(max_exp_level)
- exp_needed(max_exp_level - 1);
diff++;
}
int old_min = exp_needed(you.experience_level);
int old_max = exp_needed(you.experience_level + 1);
int new_min = exp_needed(you.experience_level + diff);
int new_max = exp_needed(you.experience_level + 1 + diff);
dprf("XP before: %d\n", you.experience);
dprf("%4.2f of %d..%d to %d..%d",
(you.experience - old_min) * 1.0 / (old_max - old_min),
old_min, old_max, new_min, new_max);
you.experience = ((int64_t)(new_max - new_min))
* (you.experience - old_min)
/ (old_max - old_min)
+ new_min;
dprf("XP after: %d\n", you.experience);
}
ASSERT((uint64_t)you.experience <= (uint64_t)MAX_EXP_TOTAL);
if (!just_xp)
level_change();
}
/**
* Get the player's current stealth value.
*
* (Keep in mind, while tweaking this function: the order in which stealth
* modifiers are applied is significant!)
*
* @return The player's current stealth value.
*/
int player_stealth()
{
ASSERT(!crawl_state.game_is_arena());
// Extreme stealthiness can be enforced by wizmode stealth setting.
if (crawl_state.disables[DIS_MON_SIGHT])
return 1000;
// berserking, "clumsy" (0-dex), sacrifice stealth.
if (you.berserk()
|| you.duration[DUR_CLUMSY]
|| you.get_mutation_level(MUT_NO_STEALTH))
{
return 0;
}
int stealth = you.dex() * 3;
stealth += you.skill(SK_STEALTH, 15);
if (you.confused())
stealth /= 3;
const item_def *arm = you.slot_item(EQ_BODY_ARMOUR, false);
if (arm)
{
// [ds] New stealth penalty formula from rob: SP = 6 * (EP^2)
// Now 2 * EP^2 / 3 after EP rescaling.
const int evp = you.unadjusted_body_armour_penalty();
const int penalty = evp * evp * 2 / 3;
stealth -= penalty;
const int pips = armour_type_prop(arm->sub_type, ARMF_STEALTH);
stealth += pips * STEALTH_PIP;
}
stealth += STEALTH_PIP * you.scan_artefacts(ARTP_STEALTH);
stealth += STEALTH_PIP * you.wearing_ego(EQ_ALL_ARMOUR, SPARM_STEALTH);
stealth += STEALTH_PIP * you.wearing(EQ_RINGS, RING_STEALTH);
if (you.duration[DUR_STEALTH])
stealth += STEALTH_PIP * 2;
// Mutations.
stealth += (STEALTH_PIP / 3) * you.get_mutation_level(MUT_NIGHTSTALKER);
stealth += STEALTH_PIP * you.get_mutation_level(MUT_THIN_SKELETAL_STRUCTURE);
stealth += STEALTH_PIP * you.get_mutation_level(MUT_CAMOUFLAGE);
if (you.has_mutation(MUT_TRANSLUCENT_SKIN))
stealth += STEALTH_PIP;
// Radiating silence is the negative complement of shouting all the
// time... a sudden change from background noise to no noise is going
// to clue anything in to the fact that something is very wrong...
// a personal silence spell would naturally be different, but this
// silence radiates for a distance and prevents monster spellcasting,
// which pretty much gives away the stealth game.
if (you.duration[DUR_SILENCE])
stealth -= STEALTH_PIP;
// Bloodless vampires are stealthier.
if (you.has_mutation(MUT_VAMPIRISM) && !you.vampire_alive)
stealth += STEALTH_PIP * 2;
if (feat_is_water(env.grid(you.pos())))
{
if (you.has_mutation(MUT_NIMBLE_SWIMMER))
stealth += STEALTH_PIP;
else if (you.in_water() && !you.can_swim() && !you.extra_balanced())
stealth /= 2; // splashy-splashy
}
// If you've been tagged with Corona or are Glowing, the glow
// makes you extremely unstealthy.
if (you.backlit())
stealth = stealth * 2 / 5;
// On the other hand, shrouding has the reverse effect, if you know
// how to make use of it:
if (you.umbra())
{
int umbra_mul = 1, umbra_div = 1;
if (you.umbra_radius() >= 0)
{
if (have_passive(passive_t::umbra))
{
umbra_mul = you.piety + MAX_PIETY;
umbra_div = MAX_PIETY;
}
if (player_equip_unrand(UNRAND_SHADOWS)
&& 2 * umbra_mul < 3 * umbra_div)
{
umbra_mul = 3;
umbra_div = 2;
}
}
stealth *= umbra_mul;
stealth /= umbra_div;
}
if (you.form == transformation::shadow)
stealth *= 2;
// If you're surrounded by a storm, you're inherently pretty conspicuous.
if (have_passive(passive_t::storm_shield))
{
stealth = stealth
* (MAX_PIETY - min((int)you.piety, piety_breakpoint(5)))
/ (MAX_PIETY - piety_breakpoint(0));
}
// The shifting glow from the Orb, while too unstable to negate invis
// or affect to-hit, affects stealth even more than regular glow.
if (player_has_orb())
stealth /= 3;
stealth = max(0, stealth);
return stealth;
}
// Is a given duration about to expire?
bool dur_expiring(duration_type dur)
{
const int value = you.duration[dur];
if (value <= 0)
return false;
return value <= duration_expire_point(dur);
}
static void _display_char_status(int value, const char *fmt, ...)
{
va_list argp;
va_start(argp, fmt);
string msg = vmake_stringf(fmt, argp);
if (you.wizard)
mprf("%s (%d).", msg.c_str(), value);
else
mprf("%s.", msg.c_str());
va_end(argp);
}
static void _display_vampire_status()
{
string msg = "At your current blood state you ";
vector<const char *> attrib;
if (!you.vampire_alive)
{
attrib.push_back("are immune to poison");
attrib.push_back("significantly resist cold");
attrib.push_back("are immune to negative energy");
attrib.push_back("resist torment");
attrib.push_back("do not heal with monsters in sight.");
}
else
attrib.push_back("heal quickly.");
if (!attrib.empty())
{
msg += comma_separated_line(attrib.begin(), attrib.end());
mpr(msg);
}
}
static void _display_movement_speed()
{
const int move_cost = (player_speed() * player_movement_speed()) / 10;
const bool water = you.in_liquid();
const bool swim = you.swimming();
const bool fly = you.airborne();
const bool swift = (you.duration[DUR_SWIFTNESS] > 0
&& you.attribute[ATTR_SWIFTNESS] >= 0);
const bool antiswift = (you.duration[DUR_SWIFTNESS] > 0
&& you.attribute[ATTR_SWIFTNESS] < 0);
_display_char_status(move_cost, "Your %s speed is %s%s%s",
// order is important for these:
(swim) ? "swimming" :
(water) ? "wading" :
(fly) ? "flying"
: "movement",
(!water && swift) ? "aided by the wind" :
(!water && antiswift) ? "hindered by the wind" : "",
(!water && swift) ? ((move_cost >= 10) ? ", but still "
: " and ") :
(!water && antiswift) ? ((move_cost <= 10) ? ", but still "
: " and ")
: "",
(move_cost < 8) ? "very quick" :
(move_cost < 10) ? "quick" :
(move_cost == 10) ? "average" :
(move_cost < 13) ? "slow"
: "very slow");
}
static void _display_tohit()
{
#ifdef DEBUG_DIAGNOSTICS
melee_attack attk(&you, nullptr);
const int to_hit = attk.calc_to_hit(false);
dprf("To-hit: %d", to_hit);
#endif
}
/**
* Print a message indicating the player's attack delay with their current
* weapon & its ammo (if applicable).
*
* Assumes the attack speed of a ranged weapon does not depend on what
* ammunition is being used (as long as it is valid).
*/
static void _display_attack_delay()
{
const item_def* weapon = you.weapon();
int delay;
if (weapon && is_range_weapon(*weapon))
{
item_def ammo;
ammo.base_type = OBJ_MISSILES;
ammo.sub_type = fires_ammo_type(*weapon);
delay = you.attack_delay(&ammo, false).expected();
}
else
delay = you.attack_delay(nullptr, false).expected();
const bool at_min_delay = weapon
&& you.skill(item_attack_skill(*weapon))
>= weapon_min_delay_skill(*weapon);
mprf("Your attack delay is about %.1f%s%s.",
delay / 10.0f,
at_min_delay ?
" (and cannot be improved with additional weapon skill)" : "",
you.adjusted_shield_penalty() ?
" (and is slowed by your insufficient shield skill)" : "");
}
// forward declaration
static string _constriction_description();
void display_char_status()
{
const int halo_size = you.halo_radius();
if (halo_size >= 0)
{
if (halo_size > 5)
mpr("You are illuminated by a large divine halo.");
else if (halo_size > 3)
mpr("You are illuminated by a divine halo.");
else
mpr("You are illuminated by a small divine halo.");
}
else if (you.haloed())
mpr("An external divine halo illuminates you.");
if (you.has_mutation(MUT_VAMPIRISM))
_display_vampire_status();
status_info inf;
for (unsigned i = 0; i <= STATUS_LAST_STATUS; ++i)
{
if (fill_status_info(i, inf) && !inf.long_text.empty())
mpr(inf.long_text);
}
string cinfo = _constriction_description();
if (!cinfo.empty())
mpr(cinfo);
_display_movement_speed();
_display_tohit();
_display_attack_delay();
// Display base attributes, if necessary.
if (innate_stat(STAT_STR) != you.strength()
|| innate_stat(STAT_INT) != you.intel()
|| innate_stat(STAT_DEX) != you.dex())
{
mprf("Your base attributes are Str %d, Int %d, Dex %d.",
innate_stat(STAT_STR),
innate_stat(STAT_INT),
innate_stat(STAT_DEX));
}
}
bool player::clarity(bool items) const
{
if (you.get_mutation_level(MUT_CLARITY))
return true;
if (have_passive(passive_t::clarity))
return true;
return actor::clarity(items);
}
/// Does the player have permastasis?
bool player::stasis() const
{
return species == SP_FORMICID;
}
bool player::can_burrow() const
{
return species == SP_FORMICID;
}
bool player::cloud_immune(bool items) const
{
return have_passive(passive_t::cloud_immunity)
|| actor::cloud_immune(items);
}
/**
* How much XP does it take to reach the given XL from 0?
*
* @param lev The XL to reach.
* @param exp_apt The XP aptitude to use. If -99, use the current species'.
* @return The total number of XP points needed to get to the given XL.
*/
unsigned int exp_needed(int lev, int exp_apt)
{
unsigned int level = 0;
// Note: For historical reasons, all of the following numbers are for a
// species (like human) with XP aptitude 1, not 0 as one might expect.
// Basic plan:
// Section 1: levels 1- 5, second derivative goes 10-10-20-30.
// Section 2: levels 6-13, second derivative is exponential/doubling.
// Section 3: levels 14-27, second derivative is constant at 8470.
// Here's a table:
//
// level xp delta delta2
// ===== ======= ===== ======
// 1 0 0 0
// 2 10 10 10
// 3 30 20 10
// 4 70 40 20
// 5 140 70 30
// 6 270 130 60
// 7 520 250 120
// 8 1010 490 240
// 9 1980 970 480
// 10 3910 1930 960
// 11 7760 3850 1920
// 12 15450 7690 3840
// 13 26895 11445 3755
// 14 45585 18690 7245
// 15 72745 27160 8470
// 16 108375 35630 8470
// 17 152475 44100 8470
// 18 205045 52570 8470
// 19 266085 61040 8470
// 20 335595 69510 8470
// 21 413575 77980 8470
// 22 500025 86450 8470
// 23 594945 94920 8470
// 24 698335 103390 8470
// 25 810195 111860 8470
// 26 930525 120330 8470
// 27 1059325 128800 8470
// If you've sacrificed experience, XP costs are adjusted as if
// you were still your original (higher) level.
if (exp_apt == -99)
lev += RU_SAC_XP_LEVELS * you.get_mutation_level(MUT_INEXPERIENCED);
switch (lev)
{
case 1:
level = 1;
break;
case 2:
level = 10;
break;
case 3:
level = 30;
break;
case 4:
level = 70;
break;
default:
if (lev < 13)
{
lev -= 4;
level = 10 + 10 * lev + (60 << lev);
}
else
{
lev -= 12;
level = 16675 + 5985 * lev + 4235 * lev * lev;
}
break;
}
if (exp_apt == -99)
exp_apt = species::get_exp_modifier(you.species);
return (unsigned int) ((level - 1) * apt_to_factor(exp_apt - 1));
}
// returns bonuses from rings of slaying, etc.
int slaying_bonus(bool throwing)
{
int ret = 0;
ret += you.wearing(EQ_RINGS_PLUS, RING_SLAYING);
ret += you.scan_artefacts(ARTP_SLAYING);
if (you.wearing_ego(EQ_GLOVES, SPARM_HURLING) && throwing)
ret += 4;
ret += 3 * augmentation_amount();
ret += you.get_mutation_level(MUT_SHARP_SCALES);
if (you.duration[DUR_WEREBLOOD])
ret += you.props[WEREBLOOD_KEY].get_int();
if (you.duration[DUR_HORROR])
ret -= you.props[HORROR_PENALTY_KEY].get_int();
if (you.props.exists(WU_JIAN_HEAVENLY_STORM_KEY))
ret += you.props[WU_JIAN_HEAVENLY_STORM_KEY].get_int();
return ret;
}
// Checks each equip slot for a randart, and adds up all of those with
// a given property. Slow if any randarts are worn, so avoid where
// possible. If `matches' is non-nullptr, items with nonzero property are
// pushed onto *matches.
int player::scan_artefacts(artefact_prop_type which_property,
vector<const item_def *> *matches) const
{
int retval = 0;
for (int i = EQ_FIRST_EQUIP; i < NUM_EQUIP; ++i)
{
if (melded[i] || equip[i] == -1)
continue;
const int eq = equip[i];
const item_def &item = inv[eq];
// Only weapons give their effects when in our hands.
if (i == EQ_WEAPON && item.base_type != OBJ_WEAPONS)
continue;
int val = 0;
if (is_artefact(item))
val = artefact_property(item, which_property);
retval += val;
if (matches && val)
matches->push_back(&item);
}
return retval;
}
/**
* Is the player wearing an Infusion-branded piece of armour? If so, returns
* how much MP they can spend per attack, depending on their available MP (or
* HP if they're a Djinn).
*/
int player::infusion_amount() const
{
int cost = 0;
if (player_equip_unrand(UNRAND_POWER_GLOVES))
cost = you.has_mutation(MUT_HP_CASTING) ? 0 : 999;
else if (wearing_ego(EQ_GLOVES, SPARM_INFUSION))
cost = 1;
if (you.has_mutation(MUT_HP_CASTING))
return min(you.hp - 1, cost);
else
return min(you.magic_points, cost);
}
/// How much bonus damage do you get per MP spent?
int player::infusion_multiplier() const {
// Maulers are pretty fun as is, but infusion needs a buff.
return player_equip_unrand(UNRAND_POWER_GLOVES) ? 2 : 4;
}
void dec_hp(int hp_loss, bool fatal, const char *aux)
{
ASSERT(!crawl_state.game_is_arena());
if (!fatal && you.hp < 1)
you.hp = 1;
if (!fatal && hp_loss >= you.hp)
hp_loss = you.hp - 1;
if (hp_loss < 1)
return;
// If it's not fatal, use ouch() so that notes can be taken. If it IS
// fatal, somebody else is doing the bookkeeping, and we don't want to mess
// with that.
if (!fatal && aux)
ouch(hp_loss, KILLED_BY_SOMETHING, MID_NOBODY, aux);
else
you.hp -= hp_loss;
you.redraw_hit_points = true;
}
void calc_mp(bool scale)
{
int old_max = you.max_magic_points;
you.max_magic_points = get_real_mp(true);
if (scale)
{
int mp = you.magic_points * 100 + you.magic_points_regeneration;
int new_max = you.max_magic_points;
if (old_max)
mp = mp * new_max / old_max;
you.magic_points = min(mp / 100, you.max_magic_points);
}
else
you.magic_points = min(you.magic_points, you.max_magic_points);
you.redraw_magic_points = true;
}
void flush_mp()
{
if (Options.magic_point_warning
&& you.magic_points < you.max_magic_points
* Options.magic_point_warning / 100)
{
mprf(MSGCH_DANGER, "* * * LOW MAGIC WARNING * * *");
}
take_note(Note(NOTE_MP_CHANGE, you.magic_points, you.max_magic_points));
you.redraw_magic_points = true;
}
void flush_hp()
{
if (Options.hp_warning
&& you.hp <= (you.hp_max * Options.hp_warning) / 100)
{
flash_view_delay(UA_HP, RED, 50);
mprf(MSGCH_DANGER, "* * * LOW HITPOINT WARNING * * *");
dungeon_events.fire_event(DET_HP_WARNING);
}
you.redraw_hit_points = true;
}
static void _dec_mp(int mp_loss, bool silent)
{
ASSERT(!crawl_state.game_is_arena());
if (mp_loss < 1)
return;
you.magic_points -= mp_loss;
you.magic_points = max(0, you.magic_points);
if (!silent)
flush_mp();
}
void drain_mp(int mp_loss)
{
_dec_mp(mp_loss, false);
}
void pay_hp(int cost)
{
you.hp -= cost;
ASSERT(you.hp);
}
void pay_mp(int cost)
{
if (you.has_mutation(MUT_HP_CASTING))
pay_hp(cost);
else
_dec_mp(cost, true);
}
void refund_hp(int cost)
{
you.hp += cost;
}
void refund_mp(int cost)
{
if (you.has_mutation(MUT_HP_CASTING))
{
you.hp += cost;
you.redraw_hit_points = true;
}
else
{
inc_mp(cost, true);
you.redraw_magic_points = true;
}
}
void finalize_mp_cost(bool addl_hp_cost)
{
if (you.has_mutation(MUT_HP_CASTING) || addl_hp_cost)
flush_hp();
if (!you.has_mutation(MUT_HP_CASTING))
flush_mp();
}
bool enough_hp(int minimum, bool suppress_msg, bool abort_macros)
{
ASSERT(!crawl_state.game_is_arena());
if (you.duration[DUR_DEATHS_DOOR])
{
if (!suppress_msg)
mpr("You cannot pay life while functionally dead.");
if (abort_macros)
{
crawl_state.cancel_cmd_again();
crawl_state.cancel_cmd_repeat();
}
return false;
}
// We want to at least keep 1 HP. -- bwr
if (you.hp < minimum + 1)
{
if (!suppress_msg)
mpr("You don't have enough health at the moment.");
if (abort_macros)
{
crawl_state.cancel_cmd_again();
crawl_state.cancel_cmd_repeat();
}
return false;
}
return true;
}
bool enough_mp(int minimum, bool suppress_msg, bool abort_macros)
{
ASSERT(!crawl_state.game_is_arena());
if (you.has_mutation(MUT_HP_CASTING))
return enough_hp(minimum, suppress_msg, abort_macros);
if (you.magic_points < minimum)
{
if (!suppress_msg)
{
if (get_real_mp(true) < minimum)
mpr("You don't have enough magic capacity.");
else
mpr("You don't have enough magic at the moment.");
}
if (abort_macros)
{
crawl_state.cancel_cmd_again();
crawl_state.cancel_cmd_repeat();
}
return false;
}
return true;
}
void inc_mp(int mp_gain, bool silent)
{
ASSERT(!crawl_state.game_is_arena());
if (mp_gain < 1 || you.magic_points >= you.max_magic_points)
return;
you.magic_points += mp_gain;
if (you.magic_points > you.max_magic_points)
you.magic_points = you.max_magic_points;
if (!silent)
{
if (_should_stop_resting(you.magic_points, you.max_magic_points))
interrupt_activity(activity_interrupt::full_mp);
you.redraw_magic_points = true;
}
}
// Note that "max_too" refers to the base potential, the actual
// resulting max value is subject to penalties, bonuses, and scalings.
// To avoid message spam, don't take notes when HP increases.
void inc_hp(int hp_gain, bool silent)
{
ASSERT(!crawl_state.game_is_arena());
if (hp_gain < 1 || you.hp >= you.hp_max)
return;
you.hp += hp_gain;
if (you.hp > you.hp_max)
you.hp = you.hp_max;
if (!silent)
{
if (_should_stop_resting(you.hp, you.hp_max))
interrupt_activity(activity_interrupt::full_hp);
you.redraw_hit_points = true;
}
}
int undrain_hp(int hp_recovered)
{
int hp_balance = 0;
if (hp_recovered > -you.hp_max_adj_temp)
{
hp_balance = hp_recovered + you.hp_max_adj_temp;
you.hp_max_adj_temp = 0;
}
else
you.hp_max_adj_temp += hp_recovered;
calc_hp();
you.redraw_hit_points = true;
if (!player_drained())
you.redraw_magic_points = true;
return hp_balance;
}
int player_drained()
{
return -you.hp_max_adj_temp;
}
void rot_mp(int mp_loss)
{
you.mp_max_adj -= mp_loss;
calc_mp();
you.redraw_magic_points = true;
}
void dec_max_hp(int hp_loss)
{
you.hp_max_adj_perm -= hp_loss;
calc_hp();
take_note(Note(NOTE_MAXHP_CHANGE, you.hp_max));
you.redraw_hit_points = true;
}
void set_hp(int new_amount)
{
ASSERT(!crawl_state.game_is_arena());
you.hp = new_amount;
if (you.hp > you.hp_max)
you.hp = you.hp_max;
// Must remain outside conditional, given code usage. {dlb}
you.redraw_hit_points = true;
}
void set_mp(int new_amount)
{
ASSERT(!crawl_state.game_is_arena());
you.magic_points = new_amount;
if (you.magic_points > you.max_magic_points)
you.magic_points = you.max_magic_points;
take_note(Note(NOTE_MP_CHANGE, you.magic_points, you.max_magic_points));
// Must remain outside conditional, given code usage. {dlb}
you.redraw_magic_points = true;
}
/**
* Get the player's max HP
* @param trans Whether to include transformations, berserk,
* items etc.
* @param drained Whether to include the effects of draining.
* @return The player's calculated max HP.
*/
int get_real_hp(bool trans, bool drained)
{
int hitp;
hitp = you.experience_level * 11 / 2 + 8;
hitp += you.hp_max_adj_perm;
// Important: we shouldn't add Heroism boosts here.
// ^ The above is a 2011 comment from 1kb, in 2021 this isn't
// archaeologied for further explanation, but the below now adds Ash boosts
// to fighting to the HP calculation while preventing it for Heroism
// - eb
hitp += you.experience_level * you.skill(SK_FIGHTING, 5, false, false) / 70
+ (you.skill(SK_FIGHTING, 3, false, false) + 1) / 2;
// Racial modifier.
hitp *= 10 + species::get_hp_modifier(you.species);
hitp /= 10;
hitp += you.get_mutation_level(MUT_FLAT_HP) * 4;
const bool hep_frail = have_passive(passive_t::frail)
|| player_under_penance(GOD_HEPLIAKLQANA);
// Mutations that increase HP by a percentage
hitp *= 100 + (you.get_mutation_level(MUT_ROBUST) * 10)
+ (you.attribute[ATTR_DIVINE_VIGOUR] * 5)
+ (you.get_mutation_level(MUT_RUGGED_BROWN_SCALES) ?
you.get_mutation_level(MUT_RUGGED_BROWN_SCALES) * 2 + 1 : 0)
- (you.get_mutation_level(MUT_FRAIL) * 10)
- (hep_frail ? 10 : 0)
- (!you.vampire_alive ? 20 : 0);
hitp /= 100;
if (drained)
hitp += you.hp_max_adj_temp;
if (trans)
hitp += you.scan_artefacts(ARTP_HP);
// Being berserk makes you resistant to damage. I don't know why.
if (trans && you.berserk())
{
if (player_equip_unrand(UNRAND_BEAR_SPIRIT))
hitp *= 2;
else
hitp = hitp * 3 / 2;
}
// Some transformations give you extra hp.
if (trans)
hitp = hitp * form_hp_mod() / 10;
#if TAG_MAJOR_VERSION == 34
if (trans && player_equip_unrand(UNRAND_ETERNAL_TORMENT))
hitp = hitp * 4 / 5;
#endif
return max(1, hitp);
}
int get_real_mp(bool include_items)
{
if (you.has_mutation(MUT_HP_CASTING))
return 0;
const int scale = 100;
int spellcasting = you.skill(SK_SPELLCASTING, 1 * scale, false, false);
int scaled_xl = you.experience_level * scale;
// the first 4 experience levels give an extra .5 mp up to your spellcasting
// the last 4 give no mp
int enp = min(23 * scale, scaled_xl);
int spell_extra = spellcasting; // 100%
int invoc_extra = you.skill(SK_INVOCATIONS, 1 * scale, false, false) / 2; // 50%
int highest_skill = max(spell_extra, invoc_extra);
enp += highest_skill + min(8 * scale, min(highest_skill, scaled_xl)) / 2;
// Analogous to ROBUST/FRAIL
enp *= 100 + (you.get_mutation_level(MUT_HIGH_MAGIC) * 10)
+ (you.attribute[ATTR_DIVINE_VIGOUR] * 5)
- (you.get_mutation_level(MUT_LOW_MAGIC) * 10);
enp /= 100 * scale;
// enp = stepdown_value(enp, 9, 18, 45, 100)
enp += species::get_mp_modifier(you.species);
// This is our "rotted" base, applied after multipliers
enp += you.mp_max_adj;
// Now applied after scaling so that power items are more useful -- bwr
if (include_items)
{
enp += 9 * you.wearing(EQ_RINGS, RING_MAGICAL_POWER);
enp += you.scan_artefacts(ARTP_MAGICAL_POWER);
}
if (include_items && you.wearing_ego(EQ_WEAPON, SPWPN_ANTIMAGIC))
enp /= 3;
enp = max(enp, 0);
return enp;
}
/// Does the player currently regenerate hp? Used for resting.
bool player_regenerates_hp()
{
if (you.has_mutation(MUT_NO_REGENERATION) || regeneration_is_inhibited())
return false;
return true;
}
bool player_regenerates_mp()
{
// Djinn don't do the whole "mp" thing.
if (you.has_mutation(MUT_HP_CASTING))
return false;
// Don't let DD use guardian spirit for free HP, since their
// damage shaving is enough. (due, dpeg)
if (you.spirit_shield() && you.species == SP_DEEP_DWARF)
return false;
#if TAG_MAJOR_VERSION == 34
// Pakellas blocks MP regeneration.
if (have_passive(passive_t::no_mp_regen) || player_under_penance(GOD_PAKELLAS))
return false;
#endif
return true;
}
int get_contamination_level()
{
const int glow = you.magic_contamination;
if (glow > 60000)
return glow / 20000 + 4;
if (glow > 40000)
return 6;
if (glow > 25000)
return 5;
if (glow > 15000)
return 4;
if (glow > 5000)
return 3;
if (glow > 3500) // An indicator that using another contamination-causing
return 2; // ability might risk causing yellow glow.
if (glow > 0)
return 1;
return 0;
}
bool player_severe_contamination()
{
return get_contamination_level() >= SEVERE_CONTAM_LEVEL;
}
/**
* Provide a description of the given contamination 'level'.
*
* @param cont A contamination 'tier', corresponding to a nonlinear
* contamination value; generated by get_contamination_level().
*
* @return A string describing the player when in the given contamination
* level.
*/
string describe_contamination(int cont)
{
/// Mappings from contamination levels to descriptions.
static const string contam_descriptions[] =
{
"",
"You are very lightly contaminated with residual magic.",
"You are lightly contaminated with residual magic.",
"You are contaminated with residual magic.",
"You are heavily infused with residual magic.",
"You are practically glowing with residual magic!",
"Your entire body has taken on an eerie glow!",
"You are engulfed in a nimbus of crackling magics!",
};
ASSERT(cont >= 0);
return contam_descriptions[min((size_t) cont,
ARRAYSZ(contam_descriptions) - 1)];
}
// Controlled is true if the player actively did something to cause
// contamination.
void contaminate_player(int change, bool controlled, bool msg)
{
ASSERT(!crawl_state.game_is_arena());
int old_amount = you.magic_contamination;
int old_level = get_contamination_level();
bool was_glowing = player_severe_contamination();
int new_level = 0;
#if TAG_MAJOR_VERSION == 34
if (change > 0 && player_equip_unrand(UNRAND_ETHERIC_CAGE))
change *= 2;
#endif
you.magic_contamination = max(0, min(250000,
you.magic_contamination + change));
new_level = get_contamination_level();
if (you.magic_contamination != old_amount)
dprf("change: %d radiation: %d", change, you.magic_contamination);
if (new_level > old_level)
{
if (msg)
{
mprf(player_severe_contamination() ? MSGCH_WARN : MSGCH_PLAIN,
"%s", describe_contamination(new_level).c_str());
}
if (player_severe_contamination())
xom_is_stimulated(new_level * 25);
}
else if (msg && new_level < old_level)
{
if (old_level == 1 && new_level == 0)
mpr("Your magical contamination has completely faded away.");
else if (player_severe_contamination() || was_glowing)
{
mprf(MSGCH_RECOVERY,
"You feel less contaminated with magical energies.");
}
if (!player_severe_contamination() && was_glowing && you.invisible())
{
mpr("You fade completely from view now that you are no longer "
"glowing from magical contamination.");
}
}
if (you.magic_contamination > 0)
learned_something_new(HINT_GLOWING);
// Zin doesn't like mutations or mutagenic radiation.
if (you_worship(GOD_ZIN))
{
// Whenever the glow status is first reached, give a warning message.
if (!was_glowing && player_severe_contamination())
did_god_conduct(DID_CAUSE_GLOWING, 0, false);
// If the player actively did something to increase glowing,
// Zin is displeased.
else if (controlled && change > 0 && was_glowing)
did_god_conduct(DID_CAUSE_GLOWING, 1 + new_level, true);
}
}
/**
* Increase the player's confusion duration.
*
* @param amount The number of turns to increase confusion duration by.
* @param quiet Whether to suppress messaging on success/failure.
* @param force Whether to ignore resistance (used only for intentional
* self-confusion, e.g. via ambrosia).
* @return Whether confusion was successful.
*/
bool confuse_player(int amount, bool quiet, bool force)
{
ASSERT(!crawl_state.game_is_arena());
if (amount <= 0)
return false;
if (!force && you.clarity())
{
if (!quiet)
mpr("You feel momentarily confused.");
return false;
}
if (!force && you.duration[DUR_DIVINE_STAMINA] > 0)
{
if (!quiet)
mpr("Your divine stamina protects you from confusion!");
return false;
}
const int old_value = you.duration[DUR_CONF];
you.increase_duration(DUR_CONF, amount, 40);
if (you.duration[DUR_CONF] > old_value)
{
you.check_awaken(500);
if (!quiet)
{
mprf(MSGCH_WARN, "You are %sconfused.",
old_value > 0 ? "more " : "");
}
learned_something_new(HINT_YOU_ENCHANTED);
xom_is_stimulated((you.duration[DUR_CONF] - old_value)
/ BASELINE_DELAY);
}
return true;
}
void paralyse_player(string source, int amount)
{
if (!amount)
amount = 2 + random2(6 + you.duration[DUR_PARALYSIS] / BASELINE_DELAY);
you.paralyse(nullptr, amount, source);
}
bool poison_player(int amount, string source, string source_aux, bool force)
{
ASSERT(!crawl_state.game_is_arena());
if (crawl_state.disables[DIS_AFFLICTIONS])
return false;
if (you.duration[DUR_DIVINE_STAMINA] > 0)
{
mpr("Your divine stamina protects you from poison!");
return false;
}
if (player_res_poison() >= 3)
{
dprf("Cannot poison, you are immune!");
return false;
}
else if (!force && player_res_poison() > 0 && !one_chance_in(3))
return false;
const int old_value = you.duration[DUR_POISONING];
const bool was_fatal = poison_is_lethal();
if (player_res_poison() < 0)
amount *= 2;
you.duration[DUR_POISONING] += amount * 1000;
if (you.duration[DUR_POISONING] > old_value)
{
if (poison_is_lethal() && !was_fatal)
mprf(MSGCH_DANGER, "You are lethally poisoned!");
else
{
mprf(MSGCH_WARN, "You are %spoisoned.",
old_value > 0 ? "more " : "");
}
learned_something_new(HINT_YOU_POISON);
}
you.props[POISONER_KEY] = source;
you.props[POISON_AUX_KEY] = source_aux;
// Display the poisoned segment of our health, in case we take no damage
you.redraw_hit_points = true;
return amount;
}
int get_player_poisoning()
{
if (player_res_poison() < 3)
{
// Approximate the effect of damage shaving by giving the first
// 25 points of poison damage for 'free'
if (you.species == SP_DEEP_DWARF)
return max(0, (you.duration[DUR_POISONING] / 1000) - 25);
else
return you.duration[DUR_POISONING] / 1000;
}
else
return 0;
}
// Fraction of current poison removed every 10 aut.
const double poison_denom = 5.0;
// these values are stored relative to dur's scaling, which is
// poison_points * 1000;
// 0.1 HP/aut
const double poison_min_hp_aut = 100.0;
// 5.0 HP/aut
const double poison_max_hp_aut = 5000.0;
// The amount of aut needed for poison to end if
// you.duration[DUR_POISONING] == dur, assuming no Chei/DD shenanigans.
// This function gives the following behaviour:
// * 1/poison_denominator of current poison is removed every 10 aut normally
// * but speed of poison is capped between the two parameters
static double _poison_dur_to_aut(double dur)
{
const double min_speed_dur = poison_denom * poison_min_hp_aut * 10.0;
const double decay = log(poison_denom / (poison_denom - 1.0));
// Poison already at minimum speed.
if (dur < min_speed_dur)
return dur / poison_min_hp_aut;
// Poison is not at maximum speed.
if (dur < poison_denom * poison_max_hp_aut * 10.0)
return 10.0 * (poison_denom + log(dur / min_speed_dur) / decay);
return 10.0 * (poison_denom + log(poison_max_hp_aut / poison_min_hp_aut) / decay)
+ (dur - poison_denom * poison_max_hp_aut * 10.0) / poison_max_hp_aut;
}
// The inverse of the above function, i.e. the amount of poison needed
// to last for aut time.
static double _poison_aut_to_dur(double aut)
{
// Amount of time that poison lasts at minimum speed.
if (aut < poison_denom * 10.0)
return aut * poison_min_hp_aut;
const double decay = log(poison_denom / (poison_denom - 1.0));
// Amount of time that poison exactly at the maximum speed lasts.
const double aut_from_max_speed = 10.0 * (poison_denom
+ log(poison_max_hp_aut / poison_min_hp_aut) / decay);
if (aut < aut_from_max_speed)
{
return 10.0 * poison_denom * poison_min_hp_aut
* exp(decay / 10.0 * (aut - poison_denom * 10.0));
}
return poison_denom * 10.0 * poison_max_hp_aut
+ poison_max_hp_aut * (aut - aut_from_max_speed);
}
void handle_player_poison(int delay)
{
const double cur_dur = you.duration[DUR_POISONING];
const double cur_aut = _poison_dur_to_aut(cur_dur);
// If Cheibriados has slowed your life processes, poison affects you less
// quickly (you take the same total damage, but spread out over a longer
// period of time).
const double delay_scaling = have_passive(passive_t::slow_poison)
? 2.0 / 3.0 : 1.0;
const double new_aut = cur_aut - ((double) delay) * delay_scaling;
const double new_dur = _poison_aut_to_dur(new_aut);
const int decrease = you.duration[DUR_POISONING] - (int) new_dur;
// Transforming into a form with no metabolism merely suspends the poison
// but doesn't let your body get rid of it.
if (you.is_nonliving() || you.is_lifeless_undead())
return;
// Other sources of immunity (Zin, staff of Olgreb) let poison dissipate.
bool do_dmg = (player_res_poison() >= 3 ? false : true);
int dmg = (you.duration[DUR_POISONING] / 1000)
- ((you.duration[DUR_POISONING] - decrease) / 1000);
// Approximate old damage shaving by giving immunity to small amounts
// of poison. Stronger poison will do the same damage as for non-DD
// until it goes below the threshold, which is a bit weird, but
// so is damage shaving.
if (you.species == SP_DEEP_DWARF && you.duration[DUR_POISONING] - decrease < 25000)
{
dmg = (you.duration[DUR_POISONING] / 1000)
- (25000 / 1000);
if (dmg < 0)
dmg = 0;
}
msg_channel_type channel = MSGCH_PLAIN;
const char *adj = "";
if (dmg > 6)
{
channel = MSGCH_DANGER;
adj = "extremely ";
}
else if (dmg > 2)
{
channel = MSGCH_WARN;
adj = "very ";
}
if (do_dmg && dmg > 0)
{
int oldhp = you.hp;
ouch(dmg, KILLED_BY_POISON);
if (you.hp < oldhp)
mprf(channel, "You feel %ssick.", adj);
}
// Now decrease the poison in our system
reduce_player_poison(decrease);
}
void reduce_player_poison(int amount)
{
if (amount <= 0)
return;
you.duration[DUR_POISONING] -= amount;
// Less than 1 point of damage remaining, so just end the poison
if (you.duration[DUR_POISONING] < 1000)
you.duration[DUR_POISONING] = 0;
if (you.duration[DUR_POISONING] <= 0)
{
you.duration[DUR_POISONING] = 0;
you.props.erase(POISONER_KEY);
you.props.erase(POISON_AUX_KEY);
mprf(MSGCH_RECOVERY, "You are no longer poisoned.");
}
you.redraw_hit_points = true;
}
// Takes *current* regeneration rate into account. Might sometimes be
// incorrect, but hopefully if so then the player is surviving with 1 HP.
bool poison_is_lethal()
{
if (you.hp <= 0)
return get_player_poisoning();
if (get_player_poisoning() < you.hp)
return false;
return poison_survival() <= 0;
}
// Try to predict the minimum value of the player's health in the coming
// turns given the current poison amount and regen rate.
int poison_survival()
{
if (!get_player_poisoning())
return you.hp;
const int rr = player_regen();
const bool chei = have_passive(passive_t::slow_poison);
const bool dd = (you.species == SP_DEEP_DWARF);
const int amount = you.duration[DUR_POISONING];
const double full_aut = _poison_dur_to_aut(amount);
// Calculate the poison amount at which regen starts to beat poison.
double min_poison_rate = poison_min_hp_aut;
if (dd)
min_poison_rate = 25.0/poison_denom;
if (chei)
min_poison_rate /= 1.5;
int regen_beats_poison;
if (rr <= (int) min_poison_rate)
regen_beats_poison = dd ? 25000 : 0;
else
{
regen_beats_poison = poison_denom * 10.0 * rr;
if (chei)
regen_beats_poison = 3 * regen_beats_poison / 2;
}
if (rr == 0)
return min(you.hp, you.hp - amount / 1000 + regen_beats_poison / 1000);
// Calculate the amount of time until regen starts to beat poison.
double poison_duration = full_aut - _poison_dur_to_aut(regen_beats_poison);
if (poison_duration < 0)
poison_duration = 0;
if (chei)
poison_duration *= 1.5;
// Worst case scenario is right before natural regen gives you a point of
// HP, so consider the nearest two such points.
const int predicted_regen = (int) ((((double) you.hit_points_regeneration) + rr * poison_duration / 10.0) / 100.0);
double test_aut1 = (100.0 * predicted_regen - 1.0 - ((double) you.hit_points_regeneration)) / (rr / 10.0);
double test_aut2 = (100.0 * predicted_regen + 99.0 - ((double) you.hit_points_regeneration)) / (rr / 10.0);
if (chei)
{
test_aut1 /= 1.5;
test_aut2 /= 1.5;
}
// Don't do any correction if there's not much poison left
const int test_amount1 = test_aut1 < full_aut ?
_poison_aut_to_dur(full_aut - test_aut1) : 0;
const int test_amount2 = test_aut2 < full_aut ?
_poison_aut_to_dur(full_aut - test_aut2) : 0;
int prediction1 = you.hp;
int prediction2 = you.hp;
// Don't look backwards in time.
if (test_aut1 > 0.0)
prediction1 -= (amount / 1000 - test_amount1 / 1000 - (predicted_regen - 1));
prediction2 -= (amount / 1000 - test_amount2 / 1000 - predicted_regen);
return min(prediction1, prediction2);
}
bool miasma_player(actor *who, string source_aux)
{
ASSERT(!crawl_state.game_is_arena());
if (you.res_miasma() || you.duration[DUR_DEATHS_DOOR])
return false;
if (you.duration[DUR_DIVINE_STAMINA] > 0)
{
mpr("Your divine stamina protects you from the miasma!");
return false;
}
bool success = poison_player(5 + roll_dice(3, 12),
who ? who->name(DESC_A) : "",
source_aux);
if (one_chance_in(3))
{
slow_player(10 + random2(5));
success = true;
}
return success;
}
bool napalm_player(int amount, string source, string source_aux)
{
ASSERT(!crawl_state.game_is_arena());
if (player_res_sticky_flame() || amount <= 0 || you.duration[DUR_WATER_HOLD] || feat_is_watery(env.grid(you.pos())))
return false;
const int old_value = you.duration[DUR_LIQUID_FLAMES];
you.increase_duration(DUR_LIQUID_FLAMES, amount, 100);
if (you.duration[DUR_LIQUID_FLAMES] > old_value)
mprf(MSGCH_WARN, "You are covered in liquid flames!");
you.props[STICKY_FLAMER_KEY] = source;
you.props[STICKY_FLAME_AUX_KEY] = source_aux;
return true;
}
void dec_napalm_player(int delay)
{
delay = min(delay, you.duration[DUR_LIQUID_FLAMES]);
if (feat_is_watery(env.grid(you.pos())))
{
if (you.ground_level())
mprf(MSGCH_WARN, "The flames go out!");
else
mprf(MSGCH_WARN, "You dip into the water, and the flames go out!");
you.duration[DUR_LIQUID_FLAMES] = 0;
you.props.erase(STICKY_FLAMER_KEY);
you.props.erase(STICKY_FLAME_AUX_KEY);
return;
}
mprf(MSGCH_WARN, "You are covered in liquid flames!");
const int hurted = resist_adjust_damage(&you, BEAM_FIRE,
random2avg(9, 2) + 1);
you.expose_to_element(BEAM_STICKY_FLAME, 2);
maybe_melt_player_enchantments(BEAM_STICKY_FLAME, hurted * delay / BASELINE_DELAY);
ouch(hurted * delay / BASELINE_DELAY, KILLED_BY_BURNING);
you.duration[DUR_LIQUID_FLAMES] =
max(0, you.duration[DUR_LIQUID_FLAMES] - delay);
}
bool slow_player(int turns)
{
ASSERT(!crawl_state.game_is_arena());
if (turns <= 0)
return false;
if (you.stasis())
{
mpr("Your stasis prevents you from being slowed.");
return false;
}
// Multiplying these values because moving while slowed takes longer than
// the usual delay.
turns = haste_mul(turns);
int threshold = haste_mul(100);
if (you.duration[DUR_SLOW] >= threshold * BASELINE_DELAY)
mpr("You already are as slow as you could be.");
else
{
if (you.duration[DUR_SLOW] == 0)
mpr("You feel yourself slow down.");
else
mpr("You feel as though you will be slow longer.");
you.increase_duration(DUR_SLOW, turns, threshold);
learned_something_new(HINT_YOU_ENCHANTED);
}
return true;
}
void dec_slow_player(int delay)
{
if (!you.duration[DUR_SLOW])
return;
if (you.duration[DUR_SLOW] > BASELINE_DELAY)
{
// Make slowing and hasting effects last as long.
you.duration[DUR_SLOW] -= you.duration[DUR_HASTE]
? haste_mul(delay) : delay;
}
if (you.torpor_slowed())
{
you.duration[DUR_SLOW] = 1;
return;
}
if (you.props.exists(TORPOR_SLOWED_KEY))
you.props.erase(TORPOR_SLOWED_KEY);
if (you.duration[DUR_SLOW] <= BASELINE_DELAY)
{
you.duration[DUR_SLOW] = 0;
if (!have_stat_zero())
mprf(MSGCH_DURATION, "You feel yourself speed up.");
}
}
void dec_berserk_recovery_player(int delay)
{
if (!you.duration[DUR_BERSERK_COOLDOWN])
return;
if (you.duration[DUR_BERSERK_COOLDOWN] > BASELINE_DELAY)
{
you.duration[DUR_BERSERK_COOLDOWN] -= you.duration[DUR_HASTE]
? haste_mul(delay) : delay;
}
if (you.duration[DUR_BERSERK_COOLDOWN] <= BASELINE_DELAY)
{
mprf(MSGCH_DURATION, "You recover from your berserk rage.");
you.duration[DUR_BERSERK_COOLDOWN] = 0;
}
}
bool haste_player(int turns, bool rageext)
{
ASSERT(!crawl_state.game_is_arena());
if (turns <= 0)
return false;
if (you.stasis())
{
mpr("Your stasis prevents you from being hasted.");
return false;
}
// Cutting the nominal turns in half since hasted actions take half the
// usual delay.
turns = haste_div(turns);
const int threshold = 40;
if (!you.duration[DUR_HASTE])
mpr("You feel yourself speed up.");
else if (you.duration[DUR_HASTE] > threshold * BASELINE_DELAY)
mpr("You already have as much speed as you can handle.");
else if (!rageext)
mpr("You feel as though your hastened speed will last longer.");
you.increase_duration(DUR_HASTE, turns, threshold);
return true;
}
void dec_haste_player(int delay)
{
if (!you.duration[DUR_HASTE])
return;
if (you.duration[DUR_HASTE] > BASELINE_DELAY)
{
int old_dur = you.duration[DUR_HASTE];
you.duration[DUR_HASTE] -= delay;
int threshold = 6 * BASELINE_DELAY;
// message if we cross the threshold
if (old_dur > threshold && you.duration[DUR_HASTE] <= threshold)
{
mprf(MSGCH_DURATION, "Your extra speed is starting to run out.");
if (coinflip())
you.duration[DUR_HASTE] -= BASELINE_DELAY;
}
}
else if (you.duration[DUR_HASTE] <= BASELINE_DELAY)
{
if (!you.duration[DUR_BERSERK])
mprf(MSGCH_DURATION, "You feel yourself slow down.");
you.duration[DUR_HASTE] = 0;
}
}
void dec_elixir_player(int delay)
{
if (!you.duration[DUR_ELIXIR])
return;
you.duration[DUR_ELIXIR] -= delay;
if (you.duration[DUR_ELIXIR] < 0)
you.duration[DUR_ELIXIR] = 0;
const int hp = (delay * you.hp_max / 10) / BASELINE_DELAY;
if (!you.duration[DUR_DEATHS_DOOR])
inc_hp(hp);
const int mp = (delay * you.max_magic_points / 10) / BASELINE_DELAY;
inc_mp(mp);
}
void dec_ambrosia_player(int delay)
{
if (!you.duration[DUR_AMBROSIA])
return;
// ambrosia ends when confusion does.
if (!you.confused())
you.duration[DUR_AMBROSIA] = 0;
you.duration[DUR_AMBROSIA] = max(0, you.duration[DUR_AMBROSIA] - delay);
// 3-5 per turn, 9-50 over (3-10) turns
const int hp_restoration = div_rand_round(delay*(3 + random2(3)), BASELINE_DELAY);
const int mp_restoration = div_rand_round(delay*(3 + random2(3)), BASELINE_DELAY);
if (!you.duration[DUR_DEATHS_DOOR])
inc_hp(you.scale_potion_healing(hp_restoration));
inc_mp(mp_restoration);
if (!you.duration[DUR_AMBROSIA])
mpr("You feel less invigorated.");
}
void dec_channel_player(int delay)
{
if (!you.duration[DUR_CHANNEL_ENERGY])
return;
you.duration[DUR_CHANNEL_ENERGY] =
max(0, you.duration[DUR_CHANNEL_ENERGY] - delay);
// 3-5 per turn, 9-50 over (3-10) turns
const int mp_restoration = div_rand_round(delay*(3 + random2(3)),
BASELINE_DELAY);
inc_mp(mp_restoration);
if (!you.duration[DUR_CHANNEL_ENERGY])
mpr("You feel less invigorated.");
}
void dec_frozen_ramparts(int delay)
{
if (!you.duration[DUR_FROZEN_RAMPARTS])
return;
you.duration[DUR_FROZEN_RAMPARTS] =
max(0, you.duration[DUR_FROZEN_RAMPARTS] - delay);
if (!you.duration[DUR_FROZEN_RAMPARTS])
{
end_frozen_ramparts();
mpr("The frozen ramparts melt away.");
}
}
bool invis_allowed(bool quiet, string *fail_reason)
{
string msg;
bool success = true;
if (you.haloed() && you.halo_radius() != -1)
{
vector<string> sources;
if (player_equip_unrand(UNRAND_EOS))
sources.push_back("weapon");
if (you.wearing_ego(EQ_ALL_ARMOUR, SPARM_LIGHT))
sources.push_back("orb");
if (you.props.exists(WU_JIAN_HEAVENLY_STORM_KEY)
|| you.religion == GOD_SHINING_ONE)
{
sources.push_back("divine halo");
}
if (sources.empty())
die("haloed by an unknown source");
msg = "Your " + comma_separated_line(sources.begin(), sources.end())
+ " glow" + (sources.size() == 1 ? "s" : "")
+ " too brightly to become invisible.";
success = false;
}
else if (you.backlit())
{
msg = "Invisibility will do you no good right now";
if (quiet)
success = false;
else if (!quiet && !yesno((msg + "; use anyway?").c_str(), false, 'n'))
{
canned_msg(MSG_OK);
success = false;
quiet = true; // since we just said something
}
msg += ".";
}
if (!success)
{
if (fail_reason)
*fail_reason = msg;
if (!quiet)
mpr(msg);
}
return success;
}
bool flight_allowed(bool quiet, string *fail_reason)
{
string msg;
bool success = true;
if (get_form()->forbids_flight())
{
msg = you.form == transformation::tree ? "Your roots keep you in place."
: "You can't fly in this form.";
success = false;
}
if (!success)
{
if (fail_reason)
*fail_reason = msg;
if (!quiet)
mpr(msg);
}
return success;
}
void float_player()
{
if (you.fishtail)
{
mpr("Your tail turns into legs as you fly out of the water.");
merfolk_stop_swimming();
}
else if (you.tengu_flight())
mpr("You swoop lightly up into the air.");
else
mpr("You fly up into the air.");
if (you.has_mutation(MUT_TENGU_FLIGHT))
you.redraw_evasion = true;
}
void fly_player(int pow, bool already_flying)
{
if (!flight_allowed())
return;
bool standing = !you.airborne() && !already_flying;
if (!already_flying)
mprf(MSGCH_DURATION, "You feel %s buoyant.", standing ? "very" : "more");
you.increase_duration(DUR_FLIGHT, 25 + random2(pow), 100);
if (standing)
float_player();
}
void enable_emergency_flight()
{
mprf("You can't survive in this terrain! You fly above the %s, but the "
"process is draining.",
(env.grid(you.pos()) == DNGN_LAVA) ? "lava" :
(env.grid(you.pos()) == DNGN_DEEP_WATER) ? "water"
: "buggy terrain");
you.props[EMERGENCY_FLIGHT_KEY] = true;
}
/**
* Handle the player's flight ending. Apply emergency flight if needed.
*
* @param quiet Should we notify the player flight is ending?
* @return If flight was ended.
*/
bool land_player(bool quiet)
{
// re-update the equipment cache: any sources of flight from equipment?
you.attribute[ATTR_PERM_FLIGHT] = you.equip_flight() ? 1 : 0;
// there was another source keeping you aloft
if (you.airborne())
return false;
// Handle landing on (formerly) instakill terrain
if (is_feat_dangerous(env.grid(you.pos())))
{
fall_into_a_pool(env.grid(you.pos()));
return false;
}
if (!quiet)
mpr("You float gracefully downwards.");
if (you.has_mutation(MUT_TENGU_FLIGHT))
you.redraw_evasion = true;
// Re-enter the terrain.
move_player_to_grid(you.pos(), false);
return true;
}
static void _end_water_hold()
{
you.duration[DUR_WATER_HOLD] = 0;
you.props.erase(WATER_HOLDER_KEY);
you.props.erase(WATER_HOLD_SUBSTANCE_KEY);
}
bool player::clear_far_engulf(bool force)
{
if (!you.duration[DUR_WATER_HOLD])
return false;
monster * const mons = monster_by_mid(you.props[WATER_HOLDER_KEY].get_int());
if (force || !mons || !mons->alive() || !adjacent(mons->pos(), you.pos()))
{
if (you.res_water_drowning())
mprf("The %s engulfing you falls away.", water_hold_substance().c_str());
else
mpr("You gasp with relief as air once again reaches your lungs.");
_end_water_hold();
return true;
}
return false;
}
void handle_player_drowning(int delay)
{
if (you.clear_far_engulf())
return;
if (you.res_water_drowning())
{
// Reset so damage doesn't ramp up while able to breathe
you.duration[DUR_WATER_HOLD] = 10;
}
else
{
you.duration[DUR_WATER_HOLD] += delay;
int dam =
div_rand_round((28 + stepdown((float)you.duration[DUR_WATER_HOLD], 28.0))
* delay,
BASELINE_DELAY * 10);
ouch(dam, KILLED_BY_WATER, you.props[WATER_HOLDER_KEY].get_int());
mprf(MSGCH_WARN, "Your lungs strain for air!");
}
}
int count_worn_ego(int which_ego)
{
int result = 0;
for (int slot = EQ_MIN_ARMOUR; slot <= EQ_MAX_ARMOUR; ++slot)
{
if (you.equip[slot] != -1 && !you.melded[slot]
&& get_armour_ego_type(you.inv[you.equip[slot]]) == which_ego)
{
result++;
}
}
return result;
}
player::player()
{
// warning: this constructor is called for `you` in an indeterminate order
// with respect to other globals, and so anything that depends on a global
// you should not do here. This includes things like `branches`, as well as
// any const static string prop name -- any object that needs to call a
// constructor is risky, and may or may not have called it yet. E.g. strings
// could be empty, branches could have every branch set as the dungeon, etc.
// One candidate location is startup.cc:_initialize, which is nearly the
// first things called in the launch game loop.
chr_god_name.clear();
chr_species_name.clear();
chr_class_name.clear();
// Permanent data:
your_name.clear();
species = SP_UNKNOWN;
char_class = JOB_UNKNOWN;
type = MONS_PLAYER;
mid = MID_PLAYER;
position.reset();
#ifdef WIZARD
wizard = Options.wiz_mode == WIZ_YES;
explore = Options.explore_mode == WIZ_YES;
#else
wizard = false;
explore = false;
#endif
suppress_wizard = false;
birth_time = time(0);
// Long-term state:
elapsed_time = 0;
elapsed_time_at_last_input = 0;
hp = 0;
hp_max = 0;
hp_max_adj_temp = 0;
hp_max_adj_perm = 0;
magic_points = 0;
max_magic_points = 0;
mp_max_adj = 0;
stat_loss.init(0);
base_stats.init(0);
max_level = 1;
hit_points_regeneration = 0;
magic_points_regeneration = 0;
experience = 0;
total_experience = 0;
experience_level = 1;
experience_pool = 0;
gold = 0;
zigs_completed = 0;
zig_max = 0;
equip.init(-1);
melded.reset();
unrand_reacts.reset();
activated.reset();
last_unequip = -1;
symbol = MONS_PLAYER;
form = transformation::none;
for (auto &item : inv)
item.clear();
runes.reset();
obtainable_runes = 15;
spell_library.reset();
spells.init(SPELL_NO_SPELL);
old_vehumet_gifts.clear();
spell_no = 0;
vehumet_gifts.clear();
chapter = CHAPTER_ORB_HUNTING;
royal_jelly_dead = false;
transform_uncancellable = false;
fishtail = false;
vampire_alive = true;
pet_target = MHITNOT;
duration.init(0);
apply_berserk_penalty = false;
berserk_penalty = 0;
attribute.init(0);
quiver.init(ENDOFPACK);
last_timer_effect.init(0);
next_timer_effect.init(20 * BASELINE_DELAY);
pending_revival = false;
lives = 0;
deaths = 0;
wizard_vision = false;
init_skills();
skill_menu_do = SKM_NONE;
skill_menu_view = SKM_NONE;
skill_cost_level = 1;
exp_available = 0;
item_description.init(255);
unique_items.init(UNIQ_NOT_EXISTS);
unique_creatures.reset();
force_autopickup.init(0);
kills = KillMaster();
where_are_you = BRANCH_DUNGEON;
depth = 1;
religion = GOD_NO_GOD;
jiyva_second_name.clear();
piety = 0;
piety_hysteresis = 0;
gift_timeout = 0;
saved_good_god_piety = 0;
previous_good_god = GOD_NO_GOD;
penance.init(0);
worshipped.init(0);
num_current_gifts.init(0);
num_total_gifts.init(0);
one_time_ability_used.reset();
piety_max.init(0);
exp_docked.init(0);
exp_docked_total.init(0);
mutation.init(0);
innate_mutation.init(0);
temp_mutation.init(0);
demonic_traits.clear();
sacrifices.init(0);
magic_contamination = 0;
seen_weapon.init(0);
seen_armour.init(0);
seen_misc.reset();
octopus_king_rings = 0x00;
normal_vision = LOS_DEFAULT_RANGE;
current_vision = LOS_DEFAULT_RANGE;
real_time_ms = chrono::milliseconds::zero();
real_time_delta = chrono::milliseconds::zero();
num_turns = 0;
exploration = 0;
trapped = false;
triggered_spectral = false;
last_view_update = 0;
spell_letter_table.init(-1);
ability_letter_table.init(ABIL_NON_ABILITY);
uniq_map_tags.clear();
uniq_map_names.clear();
uniq_map_tags_abyss.clear();
uniq_map_names_abyss.clear();
vault_list.clear();
global_info = PlaceInfo();
global_info.assert_validity();
m_quiver_history = quiver::ammo_history();
quiver_action = quiver::action_cycler();
launcher_action = quiver::launcher_action_cycler();
props.clear();
beholders.clear();
fearmongers.clear();
dactions.clear();
level_stack.clear();
type_ids.init(false);
banished_by.clear();
banished_power = 0;
last_mid = 0;
last_cast_spell = SPELL_NO_SPELL;
// Non-saved UI state:
prev_targ = MHITNOT;
prev_grd_targ.reset();
divine_exegesis = false;
travel_x = 0;
travel_y = 0;
travel_z = level_id();
running.clear();
travel_ally_pace = false;
received_weapon_warning = false;
received_noskill_warning = false;
wizmode_teleported_into_rock = false;
skill_boost.clear();
digging = false;
delay_queue.clear();
last_keypress_time = chrono::system_clock::now();
action_count.clear();
branches_left.reset();
// Volatile (same-turn) state:
turn_is_over = false;
banished = false;
wield_change = false;
gear_change = false;
redraw_noise = false;
redraw_quiver = false;
redraw_status_lights = false;
redraw_hit_points = false;
redraw_magic_points = false;
redraw_stats.init(false);
redraw_experience = false;
redraw_armour_class = false;
redraw_evasion = false;
redraw_title = false;
flash_colour = BLACK;
flash_where = nullptr;
time_taken = 0;
shield_blocks = 0;
abyss_speed = 0;
game_seed = 0;
fully_seeded = true;
deterministic_levelgen = true;
los_noise_level = 0; ///< temporary slot for loud noise levels
los_noise_last_turn = 0;
///< loudest noise heard on the last turn, for HUD display
transit_stair = DNGN_UNSEEN;
entering_level = false;
reset_escaped_death();
on_current_level = true;
seen_portals = 0;
frame_no = 0;
save = nullptr;
prev_save_version.clear();
clear_constricted();
constricting = 0;
// Protected fields:
clear_place_info();
}
void player::init_skills()
{
auto_training = !(Options.default_manual_training);
skills.init(0);
train.init(TRAINING_DISABLED);
train_alt.init(TRAINING_DISABLED);
training.init(0);
can_currently_train.reset();
skill_points.init(0);
ct_skill_points.init(0);
skill_order.init(MAX_SKILL_ORDER);
skill_manual_points.init(0);
training_targets.init(0);
exercises.clear();
exercises_all.clear();
}
player_save_info& player_save_info::operator=(const player& rhs)
{
// TODO: maybe seed, version?
name = rhs.your_name;
experience = rhs.experience;
experience_level = rhs.experience_level;
wizard = rhs.wizard || rhs.suppress_wizard;
species = rhs.species;
species_name = rhs.chr_species_name;
class_name = rhs.chr_class_name;
religion = rhs.religion;
god_name = rhs.chr_god_name;
jiyva_second_name= rhs.jiyva_second_name;
// [ds] Perhaps we should move game type to player?
saved_game_type = crawl_state.type;
return *this;
}
bool player_save_info::operator<(const player_save_info& rhs) const
{
return experience_level > rhs.experience_level
|| (experience_level == rhs.experience_level && name < rhs.name);
}
string player_save_info::really_short_desc() const
{
ostringstream desc;
desc << name << " the " << species_name << ' ' << class_name;
return desc.str();
}
string player_save_info::short_desc(bool use_qualifier) const
{
ostringstream desc;
const string qualifier = use_qualifier
? game_state::game_type_name_for(saved_game_type)
: "";
if (!qualifier.empty())
desc << "[" << qualifier << "] ";
desc << name << ", a level " << experience_level << ' '
<< species_name << ' ' << class_name;
if (religion == GOD_JIYVA)
desc << " of " << god_name << " " << jiyva_second_name;
else if (religion != GOD_NO_GOD)
desc << " of " << god_name;
#ifdef WIZARD
if (wizard)
desc << " (WIZ)";
#endif
return desc.str();
}
player::~player()
{
if (CrawlIsCrashing && save)
{
save->abort();
delete save;
save = nullptr;
}
ASSERT(!save); // the save file should be closed or deleted
}
bool player::airborne() const
{
if (get_form()->forbids_flight())
return false;
return you.duration[DUR_FLIGHT] // potions, polar vortex
|| you.props[EMERGENCY_FLIGHT_KEY].get_bool()
|| you.duration[DUR_RISING_FLAME] // flavour
|| permanent_flight(true)
|| get_form()->enables_flight();
}
bool player::is_banished() const
{
return banished;
}
bool player::is_sufficiently_rested() const
{
// Only return false if resting will actually help.
return (!player_regenerates_hp()
|| _should_stop_resting(hp, hp_max))
&& (!player_regenerates_mp()
|| _should_stop_resting(magic_points, max_magic_points))
&& !you.duration[DUR_BARBS];
}
bool player::in_water() const
{
return ground_level() && !you.can_water_walk() && feat_is_water(env.grid(pos()));
}
bool player::in_liquid() const
{
return in_water() || liquefied_ground();
}
bool player::can_swim(bool permanently) const
{
return (species::can_swim(species)
|| body_size(PSIZE_BODY) >= SIZE_GIANT
|| !permanently)
&& form_can_swim();
}
/// Can the player do a passing imitation of a notorious Palestinian?
bool player::can_water_walk() const
{
return have_passive(passive_t::water_walk)
|| you.props.exists(TEMP_WATERWALK_KEY);
}
int player::visible_igrd(const coord_def &where) const
{
if (feat_eliminates_items(env.grid(where)))
return NON_ITEM;
return env.igrid(where);
}
bool player::has_spell(spell_type spell) const
{
return find(begin(spells), end(spells), spell) != end(spells);
}
bool player::cannot_speak() const
{
if (silenced(pos()))
return true;
if (paralysed() || petrified()) // we allow talking during sleep ;)
return true;
// No transform that prevents the player from speaking yet.
// ... yet setting this would prevent saccing junk and similar activities
// for no good reason.
return false;
}
/**
* What verb should be used to describe the player's shouting?
*
* @param directed Whether you're shouting at anyone in particular.
* @return A shouty kind of verb.
*/
string player::shout_verb(bool directed) const
{
if (!get_form()->shout_verb.empty())
return get_form()->shout_verb;
// Overrides species, but gets overridden in turn by other forms.
if (you.duration[DUR_WEREBLOOD])
return "howl";
const int screaminess = get_mutation_level(MUT_SCREAM);
return species::shout_verb(you.species, screaminess, directed);
}
/**
* How loud are the player's shouts?
*
* @return The noise produced by a single player shout.
*/
int player::shout_volume() const
{
const int base_noise = 12 + get_form()->shout_volume_modifier;
return base_noise + 2 * (get_mutation_level(MUT_SCREAM));
}
void player::god_conduct(conduct_type thing_done, int level)
{
::did_god_conduct(thing_done, level);
}
void player::banish(const actor* /*agent*/, const string &who, const int power,
bool force)
{
ASSERT(!crawl_state.game_is_arena());
if (brdepth[BRANCH_ABYSS] == -1)
return;
if (player_in_branch(BRANCH_ARENA))
{
simple_god_message(" prevents your banishment from the Arena!",
GOD_OKAWARU);
return;
}
if (elapsed_time <= attribute[ATTR_BANISHMENT_IMMUNITY])
{
mpr("You resist the pull of the Abyss.");
return;
}
if (!force && player_in_branch(BRANCH_ABYSS)
&& x_chance_in_y(you.depth, brdepth[BRANCH_ABYSS]))
{
mpr("You wobble for a moment.");
return;
}
banished = true;
banished_by = who;
banished_power = power;
}
/*
* Approximate the loudest noise the player heard in the last
* turn, possibly rescaling. This gets updated every
* `world_reacts`. If `adjusted` is set to true, this rescales
* noise on a 0-1000 scale according to some breakpoints that
* I have hand-calibrated. Otherwise, it returns the raw noise
* value (approximately from 0 to 40). The breakpoints aim to
* approximate 1x los radius, 2x los radius, and 3x los radius
* relative to an open area.
*
* @param adjusted Whether to rescale the noise level.
*
* @return The (scaled or unscaled) noise level heard by the player.
*/
int player::get_noise_perception(bool adjusted) const
{
// los_noise_last_turn is already normalized for the branch's ambient
// noise.
const int level = los_noise_last_turn;
static const int BAR_MAX = 1000; // TODO: export to output.cc & webtiles
if (!adjusted)
return (level + 500) / BAR_MAX;
static const vector<int> NOISE_BREAKPOINTS = { 0, 6000, 13000, 29000 };
const int BAR_FRAC = BAR_MAX / (NOISE_BREAKPOINTS.size() - 1);
for (size_t i = 1; i < NOISE_BREAKPOINTS.size(); ++i)
{
const int breakpoint = NOISE_BREAKPOINTS[i];
if (level > breakpoint)
continue;
// what fragment of this breakpoint does the noise fill up?
const int prev_break = NOISE_BREAKPOINTS[i-1];
const int break_width = breakpoint - prev_break;
const int in_segment = (level - prev_break) * BAR_FRAC / break_width;
// that fragment + previous breakpoints passed is our total noise.
return in_segment + (i - 1) * BAR_FRAC;
// example: 10k noise. that's 4k past the 6k breakpoint
// ((10k-6k) * 333 / (13k - 6k)) + 333, or a bit more than half the bar
}
return BAR_MAX;
}
bool player::paralysed() const
{
return duration[DUR_PARALYSIS];
}
bool player::cannot_act() const
{
return asleep() || paralysed() || petrified();
}
bool player::confused() const
{
return duration[DUR_CONF];
}
bool player::caught() const
{
return attribute[ATTR_HELD];
}
bool player::petrifying() const
{
return duration[DUR_PETRIFYING];
}
bool player::petrified() const
{
return duration[DUR_PETRIFIED];
}
bool player::liquefied_ground() const
{
return liquefied(pos())
&& ground_level() && !is_insubstantial();
}
int player::shield_block_penalty() const
{
return 5 * shield_blocks * shield_blocks;
}
/**
* Returns whether the player currently has any kind of shield.
*
* XXX: why does this function exist?
*/
bool player::shielded() const
{
return shield()
|| duration[DUR_DIVINE_SHIELD]
|| get_mutation_level(MUT_LARGE_BONE_PLATES) > 0
|| qazlal_sh_boost() > 0
|| you.wearing(EQ_AMULET, AMU_REFLECTION)
|| you.scan_artefacts(ARTP_SHIELDING)
|| (get_mutation_level(MUT_CONDENSATION_SHIELD)
&& !you.duration[DUR_ICEMAIL_DEPLETED]);
}
int player::shield_bonus() const
{
const int shield_class = player_shield_class();
if (shield_class <= 0)
return -100;
return random2avg(shield_class * 2, 2) / 3 - 1;
}
int player::shield_bypass_ability(int tohit) const
{
return 15 + tohit / 2;
}
void player::shield_block_succeeded()
{
actor::shield_block_succeeded();
shield_blocks++;
practise_shield_block();
if (shield())
count_action(CACT_BLOCK, shield()->sub_type);
else
count_action(CACT_BLOCK, -1, BLOCK_OTHER); // non-shield block
}
bool player::missile_repulsion() const
{
return get_mutation_level(MUT_DISTORTION_FIELD) == 3
|| you.wearing_ego(EQ_ALL_ARMOUR, SPARM_REPULSION)
|| scan_artefacts(ARTP_RMSL)
|| have_passive(passive_t::upgraded_storm_shield);
}
/**
* What's the base value of the penalties the player receives from their
* body armour?
*
* Used as the base for adjusted armour penalty calculations, as well as for
* stealth penalty calculations.
*
* @return The player's body armour's PARM_EVASION, if any, taking into account
* the sturdy frame mutation that reduces encumbrance.
*/
int player::unadjusted_body_armour_penalty() const
{
const item_def *body_armour = slot_item(EQ_BODY_ARMOUR, false);
if (!body_armour)
return 0;
// PARM_EVASION is always less than or equal to 0
return max(0, -property(*body_armour, PARM_EVASION) / 10
- get_mutation_level(MUT_STURDY_FRAME) * 2);
}
/**
* The encumbrance penalty to the player for their worn body armour.
*
* @param scale A scale to multiply the result by, to avoid precision loss.
* @return A penalty to EV based quadratically on body armour
* encumbrance.
*/
int player::adjusted_body_armour_penalty(int scale) const
{
const int base_ev_penalty = unadjusted_body_armour_penalty();
// New formula for effect of str on aevp: (2/5) * evp^2 / (str+3)
return 2 * base_ev_penalty * base_ev_penalty * (450 - skill(SK_ARMOUR, 10))
* scale / (5 * (strength() + 3)) / 450;
}
/**
* The encumbrance penalty to the player for their worn shield.
*
* @param scale A scale to multiply the result by, to avoid precision loss.
* @return A penalty to EV based on shield weight.
*/
int player::adjusted_shield_penalty(int scale) const
{
const item_def *shield_l = slot_item(EQ_SHIELD, false);
if (!shield_l)
return 0;
const int base_shield_penalty = -property(*shield_l, PARM_EVASION) / 10;
return 2 * base_shield_penalty * base_shield_penalty
* (270 - skill(SK_SHIELDS, 10)) * scale
/ (5 * (20 - 3 * player_shield_racial_factor())) / 270;
}
/**
* Get the player's skill level for sk.
*
* @param scale a scale factor to multiply by.
* @param real whether to return the real value, or modified value.
* @param temp whether to include modification by other temporary factors (e.g. heroism)
*/
int player::skill(skill_type sk, int scale, bool real, bool temp) const
{
// If you add another enhancement/reduction, be sure to change
// SkillMenuSwitch::get_help() to reflect that
// wizard racechange, or upgraded old save
if (is_useless_skill(sk))
return 0;
// skills[sk] might not be updated yet if this is in the middle of
// skill training, so make sure to use the correct value.
int actual_skill = skills[sk];
unsigned int effective_points = skill_points[sk];
if (!real)
effective_points += get_crosstrain_points(sk);
effective_points = min(effective_points, skill_exp_needed(MAX_SKILL_LEVEL, sk));
actual_skill = calc_skill_level_change(sk, actual_skill, effective_points);
int level = actual_skill * scale
+ get_skill_progress(sk, actual_skill, effective_points, scale);
if (real)
return level;
if (penance[GOD_ASHENZARI])
{
if (temp)
level = max(level - 4 * scale, level / 2);
}
else if (ash_has_skill_boost(sk))
level = ash_skill_boost(sk, scale);
if (temp && duration[DUR_HEROISM] && sk <= SK_LAST_MUNDANE)
level = min(level + 5 * scale, MAX_SKILL_LEVEL * scale);
return level;
}
int player_icemail_armour_class()
{
if (!you.has_mutation(MUT_ICEMAIL))
return 0;
return you.duration[DUR_ICEMAIL_DEPLETED] ? 0
: you.get_mutation_level(MUT_ICEMAIL) * ICEMAIL_MAX / 2;
}
int player_condensation_shield_class()
{
if (!you.has_mutation(MUT_CONDENSATION_SHIELD))
return 0;
return you.duration[DUR_ICEMAIL_DEPLETED] ? 0 : ICEMAIL_MAX / 2;
}
/**
* How many points of AC does the player get from their sanguine armour, if
* they have any?
*
* @return The AC bonus * 100. (For scaling.)
*/
int sanguine_armour_bonus()
{
if (!you.duration[DUR_SANGUINE_ARMOUR])
return 0;
const int mut_lev = you.get_mutation_level(MUT_SANGUINE_ARMOUR);
// like iridescent, but somewhat moreso (when active)
return 300 + mut_lev * 300;
}
/**
* How much AC does the player get from an unenchanted version of the given
* armour?
*
* @param armour The armour in question.
* @param scale A value to multiply the result by. (Used to avoid integer
* rounding.)
* @return The AC from that armour, including armour skill, mutations
* & divine blessings, but not enchantments or egos.
*/
int player::base_ac_from(const item_def &armour, int scale) const
{
const int base = property(armour, PARM_AC) * scale;
// [ds] effectively: ac_value * (22 + Arm) / 22, where Arm = Armour Skill.
const int AC = base * (440 + skill(SK_ARMOUR, 20)) / 440;
// The deformed don't fit into body armour very well.
// (This includes nagas and palentongas.)
if (get_armour_slot(armour) == EQ_BODY_ARMOUR
&& (get_mutation_level(MUT_DEFORMED)
|| get_mutation_level(MUT_PSEUDOPODS)))
{
return AC - base / 2;
}
return AC;
}
/**
* What bonus AC are you getting from your species?
*
* Does not account for any real mutations, such as scales or thick skin, that
* you may have as a result of your species.
* @param temp Whether to account for transformations.
* @returns how much AC you are getting from your species "fake mutations" * 100
*/
int player::racial_ac(bool temp) const
{
// drac scales suppressed in all serious forms, except dragon
if (species::is_draconian(species)
&& (!player_is_shapechanged() || form == transformation::dragon
|| !temp))
{
int AC = 400 + 100 * (experience_level / 3); // max 13
if (species == SP_GREY_DRACONIAN) // no breath
AC += 500;
return AC;
}
if (!(player_is_shapechanged() && temp))
{
if (species == SP_NAGA)
return 100 * experience_level / 3; // max 9
else if (species == SP_GARGOYLE)
{
return 200 + 100 * experience_level * 2 / 5 // max 20
+ 100 * max(0, experience_level - 7) * 2 / 5;
}
}
return 0;
}
// Each instance of this class stores a mutation which might change a
// player's AC and how much their AC should change if the player has
// said mutation.
class mutation_ac_changes{
public:
/**
* The AC a player gains from a given mutation. If the player
* lacks said mutation, return 0.
*
* @return How much AC to give the player for the handled
* mutation.
*/
int get_ac_change_for_mutation(){
int ac_change = 0;
int mutation_level = you.get_mutation_level(mut, mutation_activation_threshold);
switch (mutation_level){
case 0:
ac_change = 0;
break;
case 1:
case 2:
case 3:
ac_change = ac_changes[mutation_level - 1];
break;
}
// The output for this function is scaled differently than the UI.
return ac_change * 100;
}
mutation_ac_changes(mutation_type mut_aug,
mutation_activity_type mutation_activation_threshold_aug,
vector<int> ac_changes_aug)
: mut (mut_aug),
mutation_activation_threshold (mutation_activation_threshold_aug),
ac_changes (ac_changes_aug)
{
}
private:
mutation_type mut;
mutation_activity_type mutation_activation_threshold;
vector<int> ac_changes;
};
// Constant vectors for the most common mutation ac results used in
// all_mutation_ac_changes
const vector<int> ONE_TWO_THREE = {1,2,3};
const vector<int> TWO_THREE_FOUR = {2,3,4};
vector<mutation_ac_changes> all_mutation_ac_changes = {
mutation_ac_changes(MUT_GELATINOUS_BODY, mutation_activity_type::PARTIAL, ONE_TWO_THREE)
,mutation_ac_changes(MUT_TOUGH_SKIN, mutation_activity_type::PARTIAL, ONE_TWO_THREE)
,mutation_ac_changes(MUT_SHAGGY_FUR, mutation_activity_type::PARTIAL, ONE_TWO_THREE)
,mutation_ac_changes(MUT_PHYSICAL_VULNERABILITY, mutation_activity_type::PARTIAL, {-5,-10,-15})
// Scale mutations are more easily disabled (forms etc.). This appears to be for flavour reasons.
// Preserved behaviour from before mutation ac was turned to data.
,mutation_ac_changes(MUT_IRIDESCENT_SCALES, mutation_activity_type::FULL, {2, 4, 6})
,mutation_ac_changes(MUT_RUGGED_BROWN_SCALES, mutation_activity_type::FULL, ONE_TWO_THREE)
,mutation_ac_changes(MUT_ICY_BLUE_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR)
,mutation_ac_changes(MUT_MOLTEN_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR)
,mutation_ac_changes(MUT_SLIMY_GREEN_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR)
,mutation_ac_changes(MUT_THIN_METALLIC_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR)
,mutation_ac_changes(MUT_YELLOW_SCALES, mutation_activity_type::FULL, TWO_THREE_FOUR)
,mutation_ac_changes(MUT_SHARP_SCALES, mutation_activity_type::FULL, ONE_TWO_THREE)
};
/**
* The AC changes the player has from mutations.
*
* Mostly additions from things like scales, but the physical vulnerability
* mutation is also accounted for.
*
* @return The player's AC gain from mutation, with 100 scaling (i.e,
* the returned result 100 times the UI shows as of Jan 2020)
*/
int player::ac_changes_from_mutations() const
{
int AC = 0;
for (vector<mutation_ac_changes>::iterator it =
all_mutation_ac_changes.begin();
it != all_mutation_ac_changes.end(); ++it)
{
AC += it->get_ac_change_for_mutation();
}
return AC;
}
/**
* Get a vector with the items of armour the player is wearing.
*
* @return A vector of non-null pointers to all armour the player has equipped.
*/
vector<const item_def *> player::get_armour_items() const
{
vector<const item_def *> armour_items;
for (int eq = EQ_MIN_ARMOUR; eq <= EQ_MAX_ARMOUR; ++eq)
{
if (!slot_item(static_cast<equipment_type>(eq)))
continue;
armour_items.push_back(&inv[equip[eq]]);
}
return armour_items;
}
/**
* Get a vector with the items of armour the player would be wearing
* if they put on a specific piece of armour
*
* @param The item which the player would be wearing in this theoretical
* situation.
* @return A vector of non-null pointers to all armour the player would have
* equipped.
*/
vector<const item_def *> player::get_armour_items_one_sub(const item_def& sub) const
{
vector<const item_def *> armour_items = get_armour_items_one_removal(sub);
armour_items.push_back(&sub);
return armour_items;
}
/**
* Get a vector with the items of armour the player would be wearing
* if they removed a specific piece of armour
*
* @param The item which the player would be remove in this theoretical
* situation.
* @return A vector of non-null pointers to all armour the player would have
* equipped after removing the item passed in.
*/
vector<const item_def *> player::get_armour_items_one_removal(const item_def& remove) const
{
vector<const item_def *> armour_items;
for (int eq = EQ_MIN_ARMOUR; eq <= EQ_MAX_ARMOUR; ++eq)
{
if (get_armour_slot(remove) == eq)
continue;
if (!slot_item(static_cast<equipment_type>(eq)))
continue;
armour_items.push_back(&inv[equip[eq]]);
}
return armour_items;
}
/**
* Get the players "base" ac, assuming they are wearing a particular set of
* armour items (which isn't necessarily the set of armour items they are
* currently wearing.)
*
* @param A scale by which the player's base AC is multiplied.
* @param A list of items to assume the player is wearing.
* @return The player's AC, multiplied by the given scale.
*/
int player::base_ac_with_specific_items(int scale,
vector<const item_def *> armour_items) const
{
int AC = 0;
for (auto item : armour_items)
{
// Shields give SH instead of AC
if (get_armour_slot(*item) != EQ_SHIELD)
{
AC += base_ac_from(*item, 100);
AC += item->plus * 100;
}
if (get_armour_ego_type(*item) == SPARM_PROTECTION)
AC += 300;
}
AC += wearing(EQ_RINGS_PLUS, RING_PROTECTION) * 100;
//XXX: This doesn't take into account armour_items, so an unrand shield
// with +AC would have a buggy display.
AC += scan_artefacts(ARTP_AC) * 100;
AC += get_form()->get_ac_bonus();
AC += racial_ac(true);
AC += ac_changes_from_mutations();
return AC * scale / 100;
}
/**
* The player's "base" armour class, before transitory buffs are applied.
*
* (This is somewhat arbitrarily defined - forms, for example, are considered
* to be long-lived for these purposes.)
*
* @param A scale by which the player's base AC is multiplied.
* @return The player's AC, multiplied by the given scale.
*/
int player::base_ac(int scale) const
{
vector<const item_def *> armour_items = get_armour_items();
return base_ac_with_specific_items(scale, armour_items);
}
int player::armour_class() const
{
return armour_class_with_specific_items(get_armour_items());
}
int player::armour_class_with_one_sub(item_def sub) const
{
return armour_class_with_specific_items(
get_armour_items_one_sub(sub));
}
int player::armour_class_with_one_removal(item_def removed) const
{
return armour_class_with_specific_items(
get_armour_items_one_removal(removed));
}
int player::corrosion_amount() const
{
int corrosion = 0;
if (duration[DUR_CORROSION])
corrosion += you.props[CORROSION_KEY].get_int();
if (player_in_branch(BRANCH_DIS))
corrosion += 2;
return corrosion;
}
static int _meek_bonus()
{
const int scale_bottom = 27; // full bonus given at this HP and below
const int hp_per_ac = 4;
const int max_ac = 7;
const int scale_top = scale_bottom + hp_per_ac * max_ac;
return min(max(0, (scale_top - you.hp) / hp_per_ac), max_ac);
}
int player::armour_class_with_specific_items(vector<const item_def *> items) const
{
const int scale = 100;
int AC = base_ac_with_specific_items(scale, items);
if (duration[DUR_ICY_ARMOUR])
{
AC += max(0, 500 + you.props[ICY_ARMOUR_KEY].get_int() * 8
- unadjusted_body_armour_penalty() * 50);
}
if (has_mutation(MUT_ICEMAIL))
AC += 100 * player_icemail_armour_class();
if (duration[DUR_FIERY_ARMOUR])
AC += 7 * scale;
if (duration[DUR_QAZLAL_AC])
AC += 300;
if (duration[DUR_SPWPN_PROTECTION])
{
AC += 700;
if (player_equip_unrand(UNRAND_MEEK))
AC += _meek_bonus() * scale;
}
AC -= 400 * corrosion_amount();
AC += sanguine_armour_bonus();
if (you.has_mutation(MUT_CURL)
&& you.props[PALENTONGA_CURL_KEY].get_bool())
{
AC += 7 * scale;
}
return AC / scale;
}
/**
* Guaranteed damage reduction.
*
* The percentage of the damage received that is guaranteed to be reduced
* by the armour. As the AC roll is done before GDR is applied, GDR is only
* useful when the AC roll is inferior to it. Therefore a higher GDR means
* more damage reduced, but also more often.
*
* \f[ GDR = 16 \times (AC)^\frac{1}{4} \f]
*
* \return GDR as a percentage.
**/
int player::gdr_perc() const
{
return max(0, (int)(16 * sqrt(sqrt(you.armour_class()))));
}
/**
* What is the player's actual, current EV, possibly relative to an attacker,
* including various temporary penalties?
*
* @param ignore_helpless Whether to ignore helplessness for the calculation.
* @param act The creature that the player is attempting to evade,
if any. May be null.
* @return The player's relevant EV.
*/
int player::evasion(bool ignore_helpless, const actor* act) const
{
const int base_evasion = _player_evasion(ignore_helpless);
const int constrict_penalty = is_constricted() ? 3 : 0;
const bool attacker_invis = act && !act->visible_to(this);
const int invis_penalty
= attacker_invis && !ignore_helpless ? 10 : 0;
return base_evasion - constrict_penalty - invis_penalty;
}
bool player::heal(int amount)
{
int oldhp = hp;
::inc_hp(amount);
return oldhp < hp;
}
/**
* What is the player's (current) mon_holy_type category?
* Stays up to date with god for evil/unholy
* Nonliving (statues, etc), undead, or alive.
*
* @param temp Whether to consider temporary effects: forms,
* petrification...
* @return The player's holiness category.
*/
mon_holy_type player::holiness(bool temp) const
{
mon_holy_type holi;
// Lich form takes precedence over a species' base holiness
// Alive Vampires are MH_NATURAL
if (is_lifeless_undead(temp))
holi = MH_UNDEAD;
else if (species::is_nonliving(you.species))
holi = MH_NONLIVING;
else
holi = MH_NATURAL;
// Petrification takes precedence over base holiness and lich form
if (temp && (form == transformation::statue
|| form == transformation::wisp
|| form == transformation::storm
|| petrified()))
{
holi = MH_NONLIVING;
}
// possible XXX: Monsters get evil/unholy bits set on spell selection
// should players?
return holi;
}
// With temp (default true), report temporary effects such as lichform.
bool player::undead_or_demonic(bool temp) const
{
// This is only for TSO-related stuff, so demonspawn are included.
return undead_state(temp) || species == SP_DEMONSPAWN;
}
bool player::evil() const
{
return is_evil_god(religion)
|| species == SP_DEMONSPAWN
|| you.has_mutation(MUT_VAMPIRISM)
|| actor::evil();
}
bool player::is_holy() const
{
return bool(holiness() & MH_HOLY) || is_good_god(religion);
}
bool player::is_nonliving(bool temp) const
{
return bool(holiness(temp) & MH_NONLIVING);
}
// This is a stub. Check is used only for silver damage. Worship of chaotic
// gods should probably be checked in the non-existing player::is_unclean,
// which could be used for something Zin-related (such as a priestly monster).
int player::how_chaotic(bool /*check_spells_god*/) const
{
return 0;
}
/**
* Does the player need to breathe?
*
* Pretty much only matters for confusing spores and drowning damage.
*
* @return Whether the player has no need to breathe.
*/
bool player::is_unbreathing() const
{
return is_nonliving() || is_lifeless_undead()
|| form == transformation::tree;
}
bool player::is_insubstantial() const
{
return form == transformation::wisp
|| form == transformation::storm;
}
int player::res_acid() const
{
return player_res_acid();
}
int player::res_fire() const
{
return player_res_fire();
}
int player::res_steam() const
{
return player_res_steam();
}
int player::res_cold() const
{
return player_res_cold();
}
int player::res_elec() const
{
return player_res_electricity();
}
bool player::res_water_drowning() const
{
return is_unbreathing()
|| species::can_swim(species) && !form_changed_physiology()
|| form == transformation::ice_beast;
}
int player::res_poison(bool temp) const
{
return player_res_poison(true, temp);
}
bool player::res_miasma(bool temp) const
{
if (has_mutation(MUT_FOUL_STENCH)
|| is_nonliving(temp)
|| temp && get_form()->res_miasma())
{
return true;
}
const item_def *armour = slot_item(EQ_BODY_ARMOUR);
if (armour && is_unrandom_artefact(*armour, UNRAND_EMBRACE))
return true;
return is_lifeless_undead();
}
bool player::res_sticky_flame() const
{
return player_res_sticky_flame();
}
int player::res_holy_energy() const
{
if (undead_or_demonic())
return -1;
if (is_holy())
return 3;
return 0;
}
int player::res_negative_energy(bool intrinsic_only) const
{
return player_prot_life(true, true, !intrinsic_only);
}
bool player::res_torment() const
{
if (you.get_mutation_level(MUT_TORMENT_RESISTANCE) >= 2)
return true;
return get_form()->res_neg() == 3
|| you.has_mutation(MUT_VAMPIRISM) && !you.vampire_alive
|| you.petrified()
// This should probably be (you.holiness & MH_PLANT), but treeform
// doesn't currently make you a plant, and I suspect changing that
// would cause other bugs. (For example, being able to wield holy
// weapons as a demonspawn & keep them while untransformed?)
|| you.form == transformation::tree
#if TAG_MAJOR_VERSION == 34
|| player_equip_unrand(UNRAND_ETERNAL_TORMENT)
#endif
;
}
bool player::res_polar_vortex() const
{
// Full control of the winds around you can negate a hostile polar vortex.
return duration[DUR_VORTEX] ? 1 : 0;
}
bool player::res_petrify(bool temp) const
{
return get_mutation_level(MUT_PETRIFICATION_RESISTANCE)
|| temp && get_form()->res_petrify();
}
int player::res_constrict() const
{
if (is_insubstantial())
return 3;
if (get_mutation_level(MUT_SPINY))
return 3;
return 0;
}
int player::willpower() const
{
return player_willpower();
}
int player_willpower(bool temp)
{
if (temp && you.form == transformation::shadow)
return WILL_INVULN;
if (player_equip_unrand(UNRAND_FOLLY))
return 0;
int rm = you.experience_level * species::get_wl_modifier(you.species);
// randarts
rm += WL_PIP * you.scan_artefacts(ARTP_WILLPOWER);
// body armour
const item_def *body_armour = you.slot_item(EQ_BODY_ARMOUR);
if (body_armour)
rm += armour_type_prop(body_armour->sub_type, ARMF_WILLPOWER) * WL_PIP;
// ego armours
rm += WL_PIP * you.wearing_ego(EQ_ALL_ARMOUR, SPARM_WILLPOWER);
rm -= 2 * WL_PIP * you.wearing_ego(EQ_ALL_ARMOUR, SPARM_GUILE);
// rings of willpower
rm += WL_PIP * you.wearing(EQ_RINGS, RING_WILLPOWER);
// Mutations
rm += WL_PIP * you.get_mutation_level(MUT_STRONG_WILLED);
rm += WL_PIP * you.get_mutation_level(MUT_DEMONIC_WILL);
rm -= WL_PIP * you.get_mutation_level(MUT_WEAK_WILLED);
// transformations
if (you.form == transformation::lich && temp)
rm += WL_PIP;
// Trog's Hand
if (you.duration[DUR_TROGS_HAND] && temp)
rm += WL_PIP * 2;
// Enchantment/environment effect
if ((you.duration[DUR_LOWERED_WL]
|| player_in_branch(BRANCH_TARTARUS)) && temp)
{
rm /= 2;
}
if (rm < 0)
rm = 0;
return rm;
}
/**
* Is the player prevented from teleporting? If so, why?
*
* @param blinking Are you blinking or teleporting?
* @return Why the player is prevented from teleporting, if they
* are; else, the empty string.
*/
string player::no_tele_reason(bool blinking) const
{
if (!blinking)
{
if (crawl_state.game_is_sprint())
return "Long-range teleportation is disallowed in Dungeon Sprint.";
else if (player_in_branch(BRANCH_GAUNTLET))
{
return "A magic seal in the Gauntlet prevents long-range "
"teleports.";
}
}
if (stasis())
return "Your stasis prevents you from teleporting.";
vector<string> problems;
if (duration[DUR_DIMENSION_ANCHOR])
problems.emplace_back("locked down by a dimension anchor");
if (duration[DUR_LOCKED_DOWN])
problems.emplace_back("magically locked down");
if (form == transformation::tree)
problems.emplace_back("held in place by your roots");
vector<const item_def *> notele_items;
if (has_notele_item(¬ele_items))
{
vector<string> worn_notele;
bool found_nonartefact = false;
for (const auto item : notele_items)
{
if (item->base_type == OBJ_WEAPONS)
{
problems.push_back(make_stringf("wielding %s",
item->name(DESC_A).c_str()));
}
else
worn_notele.push_back(item->name(DESC_A));
}
if (worn_notele.size() > (problems.empty() ? 3 : 1))
{
problems.push_back(
make_stringf("wearing %s %s preventing teleportation",
number_in_words(worn_notele.size()).c_str(),
found_nonartefact ? "items": "artefacts"));
}
else if (!worn_notele.empty())
{
problems.push_back(
make_stringf("wearing %s",
comma_separated_line(worn_notele.begin(),
worn_notele.end()).c_str()));
}
}
if (problems.empty())
return ""; // no problem
return make_stringf("You cannot %s because you are %s.",
blinking ? "blink" : "teleport",
comma_separated_line(problems.begin(),
problems.end()).c_str());
}
/**
* Is the player prevented from teleporting/blinking right now?
*
* @param blinking Are you blinking or teleporting?
* @return Whether the player is prevented from teleportation.
*/
bool player::no_tele(bool blinking) const
{
return !no_tele_reason(blinking).empty();
}
bool player::fights_well_unarmed()
{
return x_chance_in_y(30 + skill(SK_UNARMED_COMBAT, 10), 600);
}
bool player::racial_permanent_flight() const
{
return get_mutation_level(MUT_TENGU_FLIGHT)
|| get_mutation_level(MUT_BIG_WINGS)
|| has_mutation(MUT_FLOAT);
}
/**
* Check for sources of flight from species and (optionally) equipment.
*/
bool player::permanent_flight(bool include_equip) const
{
if (get_form()->forbids_flight())
return false;
return include_equip && attribute[ATTR_PERM_FLIGHT] // equipment
|| racial_permanent_flight(); // species muts
}
/**
* Does the player get the tengu flight perks?
*/
bool player::tengu_flight() const
{
// XX could tengu just get MUT_FLOAT?
return you.has_mutation(MUT_TENGU_FLIGHT) && airborne();
}
/**
* Returns true if player spellcasting is considered unholy.
*
* Checks to see if the player is wielding the Majin-Bo.
*
* @return Whether player spellcasting is an unholy act.
*/
bool player::spellcasting_unholy() const
{
return player_equip_unrand(UNRAND_MAJIN);
}
/**
* What is the player's (current) place on the Undead Spectrum?
* (alive, semi-undead (vampire), or very dead (ghoul, mummy, lich)
*
* @param temp Whether to consider temporary effects (lichform)
* @return The player's undead state.
*/
undead_state_type player::undead_state(bool temp) const
{
if (temp && form == transformation::lich)
return US_UNDEAD;
return species::undead_type(species);
}
bool player::nightvision() const
{
return have_passive(passive_t::nightvision)
|| player_equip_unrand(UNRAND_SHADOWS);
}
reach_type player::reach_range() const
{
const item_def *wpn = weapon();
if (wpn)
return weapon_reach(*wpn);
return REACH_NONE;
}
monster_type player::mons_species(bool /*zombie_base*/) const
{
return species::to_mons_species(species);
}
bool player::poison(actor *agent, int amount, bool force)
{
return ::poison_player(amount, agent? agent->name(DESC_A, true) : "", "",
force);
}
void player::expose_to_element(beam_type element, int _strength,
bool slow_cold_blood)
{
::expose_player_to_element(element, _strength, slow_cold_blood);
}
void player::blink()
{
uncontrolled_blink();
}
void player::teleport(bool now, bool wizard_tele)
{
ASSERT(!crawl_state.game_is_arena());
if (now)
you_teleport_now(wizard_tele);
else
you_teleport();
}
int player::hurt(const actor *agent, int amount, beam_type flavour,
kill_method_type kill_type, string source, string aux,
bool /*cleanup_dead*/, bool /*attacker_effects*/)
{
// We ignore cleanup_dead here.
if (!agent)
{
// FIXME: This can happen if a deferred_damage_fineff does damage
// to a player from a dead monster. We should probably not do that,
// but it could be tricky to fix, so for now let's at least avoid
// a crash even if it does mean funny death messages.
ouch(amount, kill_type, MID_NOBODY, aux.c_str(), false, source.c_str());
}
else
{
ouch(amount, kill_type, agent->mid, aux.c_str(),
agent->visible_to(this), source.c_str());
}
if ((flavour == BEAM_DEVASTATION || flavour == BEAM_MINDBURST)
&& can_bleed())
{
blood_spray(pos(), type, amount / 5);
}
return amount;
}
void player::drain_stat(stat_type s, int amount)
{
lose_stat(s, amount);
}
bool player::corrode_equipment(const char* corrosion_source, int degree)
{
// rCorr protects against 50% of corrosion.
if (res_corr())
{
degree = binomial(degree, 50);
if (!degree)
{
dprf("rCorr protects.");
return false;
}
}
// always increase duration, but...
increase_duration(DUR_CORROSION, 10 + roll_dice(2, 4), 50,
make_stringf("%s corrodes you!",
corrosion_source).c_str());
// the more corrosion you already have, the lower the odds of more
// Static environmental corrosion doesn't factor in
int prev_corr = props[CORROSION_KEY].get_int();
bool did_corrode = false;
for (int i = 0; i < degree; i++)
if (!x_chance_in_y(prev_corr, prev_corr + 7))
{
props[CORROSION_KEY].get_int()++;
prev_corr++;
did_corrode = true;
}
if (did_corrode)
{
redraw_armour_class = true;
wield_change = true;
}
return true;
}
/**
* Attempts to apply corrosion to the player and deals acid damage.
*
* @param evildoer the cause of this acid splash.
* @param acid_strength The strength of the acid.
*/
void player::splash_with_acid(actor* evildoer, int acid_strength)
{
acid_corrode(acid_strength);
const int dam = roll_dice(4, acid_strength);
const int post_res_dam = resist_adjust_damage(&you, BEAM_ACID, dam);
mprf("You are splashed with acid%s%s",
post_res_dam > 0 ? "" : " but take no damage",
attack_strength_punctuation(post_res_dam).c_str());
if (post_res_dam > 0)
{
if (post_res_dam < dam)
canned_msg(MSG_YOU_RESIST);
ouch(post_res_dam, KILLED_BY_ACID,
evildoer ? evildoer->mid : MID_NOBODY);
}
}
void player::acid_corrode(int acid_strength)
{
if (binomial(3, acid_strength + 1, 30))
corrode_equipment();
}
bool player::drain(const actor */*who*/, bool quiet, int pow)
{
return drain_player(pow, !quiet);
}
void player::confuse(actor */*who*/, int str)
{
confuse_player(str);
}
/**
* Paralyse the player for str turns.
*
* Duration is capped at 13.
*
* @param who Pointer to the actor who paralysed the player.
* @param str The number of turns the paralysis will last.
* @param source Description of the source of the paralysis.
*/
void player::paralyse(const actor *who, int str, string source)
{
ASSERT(!crawl_state.game_is_arena());
if (stasis())
{
mpr("Your stasis prevents you from being paralysed.");
return;
}
// The who check has an effect in a few cases, most notably making
// Death's Door + Borg's paralysis unblockable.
if (who && (duration[DUR_PARALYSIS] || duration[DUR_PARALYSIS_IMMUNITY]))
{
mpr("You shrug off the repeated paralysis!");
return;
}
int ¶lysis(duration[DUR_PARALYSIS]);
const bool use_actor_name = source.empty() && who != nullptr;
if (use_actor_name)
source = who->name(DESC_A);
if (!paralysis && !source.empty())
{
take_note(Note(NOTE_PARALYSIS, str, 0, source));
// use the real name here even for invisible monsters
props[PARALYSED_BY_KEY] = use_actor_name ? who->name(DESC_A, true)
: source;
}
if (asleep())
you.awaken();
mpr("You suddenly lose the ability to move!");
_pruneify();
paralysis = min(str, 13) * BASELINE_DELAY;
stop_directly_constricting_all(false);
end_wait_spells();
redraw_armour_class = true;
redraw_evasion = true;
}
void player::petrify(const actor *who, bool force)
{
ASSERT(!crawl_state.game_is_arena());
if (res_petrify() && !force)
{
canned_msg(MSG_YOU_UNAFFECTED);
return;
}
if (duration[DUR_DIVINE_STAMINA] > 0)
{
mpr("Your divine stamina protects you from petrification!");
return;
}
// Petrification always wakes you up
if (asleep())
you.awaken();
if (petrifying())
{
mpr("Your limbs have turned to stone.");
duration[DUR_PETRIFYING] = 1;
return;
}
if (petrified())
return;
duration[DUR_PETRIFYING] = 3 * BASELINE_DELAY;
if (who)
props[PETRIFIED_BY_KEY] = who->name(DESC_A, true);
redraw_evasion = true;
mprf(MSGCH_WARN, "You are slowing down.");
}
bool player::fully_petrify(bool /*quiet*/)
{
duration[DUR_PETRIFIED] = 6 * BASELINE_DELAY
+ random2(4 * BASELINE_DELAY);
redraw_armour_class = true;
redraw_evasion = true;
mpr("You have turned to stone.");
_pruneify();
end_wait_spells();
return true;
}
void player::slow_down(actor */*foe*/, int str)
{
::slow_player(str);
}
int player::has_claws(bool allow_tran) const
{
if (allow_tran)
{
// these transformations bring claws with them
if (form == transformation::dragon)
return 3;
// blade hands override claws
if (form == transformation::blade_hands)
return 0;
}
return get_mutation_level(MUT_CLAWS, allow_tran);
}
bool player::has_usable_claws(bool allow_tran) const
{
return !slot_item(EQ_GLOVES) && has_claws(allow_tran);
}
int player::has_talons(bool allow_tran) const
{
// XXX: Do merfolk in water belong under allow_tran?
if (fishtail)
return 0;
return get_mutation_level(MUT_TALONS, allow_tran);
}
bool player::has_usable_talons(bool allow_tran) const
{
return !slot_item(EQ_BOOTS) && has_talons(allow_tran);
}
int player::has_hooves(bool allow_tran) const
{
// XXX: Do merfolk in water belong under allow_tran?
if (fishtail)
return 0;
return get_mutation_level(MUT_HOOVES, allow_tran);
}
bool player::has_usable_hooves(bool allow_tran) const
{
return has_hooves(allow_tran)
&& (!slot_item(EQ_BOOTS) || wearing(EQ_BOOTS, ARM_BARDING));
}
int player::has_fangs(bool allow_tran) const
{
if (allow_tran)
{
// these transformations bring fangs with them
if (form == transformation::dragon)
return 3;
}
return get_mutation_level(MUT_FANGS, allow_tran);
}
int player::has_usable_fangs(bool allow_tran) const
{
return has_fangs(allow_tran);
}
bool player::has_tail(bool allow_tran) const
{
if (allow_tran)
{
// these transformations bring a tail with them
if (form == transformation::dragon)
return 1;
// Most transformations suppress a tail.
if (!form_keeps_mutations())
return 0;
}
// XXX: Do merfolk in water belong under allow_tran?
if (species::is_draconian(species)
|| has_mutation(MUT_CONSTRICTING_TAIL, allow_tran)
|| fishtail // XX respect allow_tran
|| get_mutation_level(MUT_ARMOURED_TAIL, allow_tran)
|| get_mutation_level(MUT_STINGER, allow_tran)
|| get_mutation_level(MUT_WEAKNESS_STINGER, allow_tran))
{
return 1;
}
return 0;
}
// Whether the player has a usable offhand for the
// purpose of punching.
bool player::has_usable_offhand() const
{
if (get_mutation_level(MUT_MISSING_HAND))
return false;
if (shield())
return false;
const item_def* wp = slot_item(EQ_WEAPON);
return !wp || hands_reqd(*wp) != HANDS_TWO;
}
bool player::has_usable_tentacle() const
{
return usable_tentacles();
}
int player::usable_tentacles() const
{
int numtentacle = has_usable_tentacles();
if (numtentacle == 0)
return false;
int free_tentacles = numtentacle - num_constricting();
if (shield())
free_tentacles -= 2;
const item_def* wp = slot_item(EQ_WEAPON);
if (wp)
{
hands_reqd_type hands_req = hands_reqd(*wp);
free_tentacles -= 2 * hands_req + 2;
}
return free_tentacles;
}
int player::has_pseudopods(bool allow_tran) const
{
return get_mutation_level(MUT_PSEUDOPODS, allow_tran);
}
int player::has_usable_pseudopods(bool allow_tran) const
{
return has_pseudopods(allow_tran);
}
int player::arm_count() const
{
// XX transformations? arm count per se isn't used by much though.
return species::arm_count(species)
- get_mutation_level(MUT_MISSING_HAND);
}
int player::has_tentacles(bool allow_tran) const
{
// tentacles count as a mutation for these purposes. (TODO: realmut?)
if (you.has_mutation(MUT_TENTACLE_ARMS, allow_tran))
return arm_count();
return 0;
}
int player::has_usable_tentacles(bool allow_tran) const
{
return has_tentacles(allow_tran);
}
bool player::sicken(int amount)
{
ASSERT(!crawl_state.game_is_arena());
if (res_miasma() || amount <= 0)
return false;
if (duration[DUR_DIVINE_STAMINA] > 0)
{
mpr("Your divine stamina protects you from disease!");
return false;
}
mpr("You feel ill.");
increase_duration(DUR_SICKNESS, amount, 210);
return true;
}
/// Can the player see invisible things?
bool player::can_see_invisible() const
{
if (crawl_state.game_is_arena())
return true;
if (wearing(EQ_RINGS, RING_SEE_INVISIBLE)
// armour: (checks head armour only)
|| wearing_ego(EQ_HELMET, SPARM_SEE_INVISIBLE)
// randart gear
|| scan_artefacts(ARTP_SEE_INVISIBLE) > 0)
{
return true;
}
return innate_sinv();
}
/// Can the player see invisible things without needing items' help?
bool player::innate_sinv() const
{
if (has_mutation(MUT_ACUTE_VISION))
return true;
// antennae give sInvis at 3
if (get_mutation_level(MUT_ANTENNAE) == 3)
return true;
if (get_mutation_level(MUT_EYEBALLS) == 3)
return true;
if (have_passive(passive_t::sinv))
return true;
return false;
}
bool player::invisible() const
{
return (duration[DUR_INVIS] || form == transformation::shadow)
&& !backlit();
}
bool player::visible_to(const actor *looker) const
{
if (crawl_state.game_is_arena())
return false;
const bool invis_to = invisible() && !looker->can_see_invisible()
&& !in_water();
if (this == looker)
return !invis_to;
const monster* mon = looker->as_monster();
return mon->friendly()
|| (!mon->has_ench(ENCH_BLIND) && !invis_to);
}
/**
* Is the player backlit?
*
* @param self_halo If true, ignore the player's self-halo.
* @returns True if the player is backlit.
*/
bool player::backlit(bool self_halo) const
{
return player_severe_contamination()
|| duration[DUR_CORONA]
|| duration[DUR_LIQUID_FLAMES]
|| duration[DUR_QUAD_DAMAGE]
|| !umbraed() && haloed() && (self_halo || halo_radius() == -1);
}
bool player::umbra() const
{
return !backlit() && umbraed() && !haloed();
}
// This is the imperative version.
void player::backlight()
{
if (!duration[DUR_INVIS] && form != transformation::shadow)
{
if (duration[DUR_CORONA])
mpr("You glow brighter.");
else
mpr("You are outlined in light.");
increase_duration(DUR_CORONA, random_range(15, 35), 250);
}
else
{
mpr("You feel strangely conspicuous.");
increase_duration(DUR_CORONA, random_range(3, 5), 250);
}
}
bool player::can_mutate() const
{
return true;
}
/**
* Can the player be mutated without stat drain instead?
*
* @param temp Whether to consider temporary modifiers (lichform)
* @return Whether the player will mutate when mutated, instead of draining
* stats.
*/
bool player::can_safely_mutate(bool temp) const
{
if (!can_mutate())
return false;
return undead_state(temp) == US_ALIVE
|| undead_state(temp) == US_SEMI_UNDEAD;
}
// Is the player too undead to bleed, rage, or polymorph?
bool player::is_lifeless_undead(bool temp) const
{
if (temp && undead_state() == US_SEMI_UNDEAD)
return !you.vampire_alive;
else
return undead_state(temp) == US_UNDEAD;
}
bool player::can_polymorph() const
{
return !(transform_uncancellable || is_lifeless_undead());
}
bool player::can_bleed(bool temp) const
{
if (temp && !form_can_bleed(form))
return false;
return !is_lifeless_undead(temp) && !is_nonliving(temp);
}
bool player::can_drink(bool temp) const
{
if (temp && (you.form == transformation::lich
|| you.duration[DUR_NO_POTIONS]))
{
return false;
}
return !you.has_mutation(MUT_NO_DRINK);
}
bool player::is_stationary() const
{
return form == transformation::tree
|| you.duration[DUR_LOCKED_DOWN];
}
bool player::malmutate(const string &reason)
{
ASSERT(!crawl_state.game_is_arena());
if (!can_mutate())
return false;
const mutation_type mut_quality = one_chance_in(5) ? RANDOM_MUTATION
: RANDOM_BAD_MUTATION;
if (mutate(mut_quality, reason))
{
learned_something_new(HINT_YOU_MUTATED);
return true;
}
return false;
}
bool player::polymorph(int pow, bool allow_immobile)
{
ASSERT(!crawl_state.game_is_arena());
if (!can_polymorph())
return false;
transformation f = transformation::none;
vector<transformation> forms = {
transformation::bat,
transformation::wisp,
transformation::pig,
};
if (allow_immobile)
{
forms.emplace_back(transformation::tree);
forms.emplace_back(transformation::fungus);
}
for (int tries = 0; tries < 3; tries++)
{
f = forms[random2(forms.size())];
// need to do a dry run first, as Zin's protection has a random factor
if (transform(pow, f, true, true))
break;
f = transformation::none;
}
if (f != transformation::none && transform(pow, f))
{
transform_uncancellable = true;
return true;
}
return false;
}
bool player::is_icy() const
{
return form == transformation::ice_beast;
}
bool player::is_fiery() const
{
return false;
}
bool player::is_skeletal() const
{
return false;
}
void player::shiftto(const coord_def &c)
{
crawl_view.shift_player_to(c);
set_position(c);
clear_invalid_constrictions();
}
bool player::asleep() const
{
return duration[DUR_SLEEP];
}
bool player::can_feel_fear(bool include_unknown) const
{
// XXX: monsters are immune to fear when berserking.
// should players also be?
return you.holiness() & (MH_NATURAL | MH_DEMONIC | MH_HOLY)
&& (!include_unknown || !you.clarity());
}
bool player::can_throw_large_rocks() const
{
return species::can_throw_large_rocks(species);
}
bool player::can_smell() const
{
return !you.is_lifeless_undead(true);
}
bool player::can_sleep(bool holi_only) const
{
return !you.duration[DUR_SLEEP_IMMUNITY] && actor::can_sleep(holi_only);
}
/**
* Attempts to put the player to sleep.
*
* @param power The power of the effect putting the player to sleep.
* @param hibernate Whether the player is being put to sleep by 'ensorcelled
* hibernation' (doesn't affect characters with rC, ignores
* power), or by a normal sleep effect.
*/
void player::put_to_sleep(actor*, int power, bool hibernate)
{
ASSERT(!crawl_state.game_is_arena());
const bool valid_target = hibernate ? can_hibernate() : can_sleep();
if (!valid_target)
{
canned_msg(MSG_YOU_UNAFFECTED);
return;
}
if (duration[DUR_SLEEP_IMMUNITY])
{
mpr("You can't fall asleep again this soon!");
return;
}
if (duration[DUR_PARALYSIS]
|| duration[DUR_PETRIFIED]
|| duration[DUR_PETRIFYING])
{
mpr("You can't fall asleep in your current state!");
return;
}
mpr("You fall asleep.");
_pruneify();
stop_directly_constricting_all(false);
end_wait_spells();
stop_delay();
flash_view(UA_MONSTER, DARKGREY);
// As above, do this after redraw.
const int dur = hibernate ? 3 + random2avg(5, 2) :
5 + random2avg(power/10, 5);
set_duration(DUR_SLEEP, dur);
redraw_armour_class = true;
redraw_evasion = true;
}
void player::awaken()
{
ASSERT(!crawl_state.game_is_arena());
duration[DUR_SLEEP] = 0;
set_duration(DUR_SLEEP_IMMUNITY, random_range(3, 5));
mpr("You wake up.");
flash_view(UA_MONSTER, BLACK);
redraw_armour_class = true;
redraw_evasion = true;
}
void player::check_awaken(int disturbance)
{
if (asleep() && x_chance_in_y(disturbance + 1, 50))
{
awaken();
dprf("Disturbance of intensity %d awoke player", disturbance);
}
}
bool player::may_pruneify() const {
return player_equip_unrand(UNRAND_PRUNE)
&& you.undead_state() == US_ALIVE;
}
int player::beam_resists(bolt &beam, int hurted, bool doEffects, string source)
{
return check_your_resists(hurted, beam.flavour, source, &beam, doEffects);
}
bool player::shaftable(bool check_terrain) const
{
return is_valid_shaft_level()
&& (!check_terrain || feat_is_shaftable(env.grid(pos())));
}
// Used for falling into traps and other bad effects, but is a slightly
// different effect from the player invokable ability.
bool player::do_shaft(bool check_terrain)
{
if (!shaftable(check_terrain))
return false;
// Ensure altars, items, and shops discovered at the moment
// the player gets shafted are correctly registered.
maybe_update_stashes();
down_stairs(DNGN_TRAP_SHAFT);
return true;
}
bool player::can_do_shaft_ability(bool quiet) const
{
if (attribute[ATTR_HELD])
{
if (!quiet)
mprf("You can't shaft yourself while %s.", held_status());
return false;
}
if (feat_is_shaftable(env.grid(pos())))
{
if (!is_valid_shaft_level())
{
if (!quiet)
mpr("You can't shaft yourself on this level.");
return false;
}
}
else
{
if (!quiet)
mpr("You can't shaft yourself on this terrain.");
return false;
}
return true;
}
// Like do_shaft, but forced by the player.
// It has a slightly different set of rules.
bool player::do_shaft_ability()
{
if (can_do_shaft_ability(true))
{
mpr("A shaft appears beneath you!");
down_stairs(DNGN_TRAP_SHAFT, true);
return true;
}
else
{
canned_msg(MSG_NOTHING_HAPPENS);
redraw_screen();
update_screen();
return false;
}
}
bool player::did_escape_death() const
{
return escaped_death_cause != NUM_KILLBY;
}
void player::reset_escaped_death()
{
escaped_death_cause = NUM_KILLBY;
escaped_death_aux = "";
}
void player::add_gold(int delta)
{
set_gold(gold + delta);
}
void player::del_gold(int delta)
{
set_gold(gold - delta);
}
void player::set_gold(int amount)
{
ASSERT(amount >= 0);
if (amount != gold)
{
const int old_gold = gold;
gold = amount;
shopping_list.gold_changed(old_gold, gold);
// XXX: this might benefit from being in its own function
if (you_worship(GOD_GOZAG))
{
for (const auto& power : get_god_powers(you.religion))
{
const int cost = get_gold_cost(power.abil);
if (gold >= cost && old_gold < cost)
power.display(true, "You now have enough gold to %s.");
else if (old_gold >= cost && gold < cost)
power.display(false, "You no longer have enough gold to %s.");
}
you.redraw_title = true;
}
}
}
void player::increase_duration(duration_type dur, int turns, int cap,
const char* msg)
{
if (msg)
mpr(msg);
cap *= BASELINE_DELAY;
duration[dur] += turns * BASELINE_DELAY;
if (cap && duration[dur] > cap)
duration[dur] = cap;
}
void player::set_duration(duration_type dur, int turns,
int cap, const char * msg)
{
duration[dur] = 0;
increase_duration(dur, turns, cap, msg);
}
void player::goto_place(const level_id &lid)
{
where_are_you = static_cast<branch_type>(lid.branch);
depth = lid.depth;
ASSERT_RANGE(depth, 1, brdepth[where_are_you] + 1);
}
bool player::attempt_escape(int attempts)
{
monster *themonst;
if (!is_constricted())
return true;
themonst = monster_by_mid(constricted_by);
ASSERT(themonst);
escape_attempts += attempts;
const bool direct = is_directly_constricted();
const string object = direct ? themonst->name(DESC_ITS, true)
: "the roots'";
// player breaks free if (4+n)d13 >= 5d(8+HD/4)
const int escape_score = roll_dice(4 + escape_attempts, 13);
if (escape_score
>= roll_dice(5, 8 + div_rand_round(themonst->get_hit_dice(), 4)))
{
mprf("You escape %s grasp.", object.c_str());
// Stun the monster to prevent it from constricting again right away.
if (direct)
themonst->speed_increment -= 5;
stop_being_constricted(true);
return true;
}
else
{
mprf("%s grasp on you weakens, but your attempt to escape fails.",
object.c_str());
turn_is_over = true;
return false;
}
}
void player::sentinel_mark(bool trap)
{
if (duration[DUR_SENTINEL_MARK])
{
mpr("The mark upon you grows brighter.");
increase_duration(DUR_SENTINEL_MARK, random_range(20, 40), 180);
}
else
{
mprf(MSGCH_WARN, "A sentinel's mark forms upon you.");
increase_duration(DUR_SENTINEL_MARK, trap ? random_range(25, 40)
: random_range(35, 60),
250);
}
}
/*
* Is the player too terrified to move (because of fungusform)?
*
* @return true iff there is an alarming monster anywhere near a fungusform player.
*/
bool player::is_nervous()
{
if (form != transformation::fungus)
return false;
for (monster_near_iterator mi(&you); mi; ++mi)
{
if (made_nervous_by(*mi))
return true;
}
return false;
}
/*
* Does monster `mons` make the player nervous (in fungusform)?
*
* @param mons the monster to check
* @return true iff mons is non-null, player is fungal, and `mons` is a threatening monster.
*/
bool player::made_nervous_by(const monster *mons)
{
if (form != transformation::fungus)
return false;
if (!mons)
return false;
if (!mons_is_wandering(*mons)
&& !mons->asleep()
&& !mons->confused()
&& !mons->cannot_act()
&& mons_is_threatening(*mons)
&& !mons->wont_attack()
&& !mons->neutral())
{
return true;
}
return false;
}
void player::weaken(actor */*attacker*/, int pow)
{
if (!duration[DUR_WEAK])
mprf(MSGCH_WARN, "You feel your attacks grow feeble.");
else
mprf(MSGCH_WARN, "You feel as though you will be weak longer.");
increase_duration(DUR_WEAK, pow + random2(pow + 3), 50);
}
/**
* Check if the player is about to die from flight/form expiration.
*
* Check whether the player is on a cell which would be deadly if not for some
* temporary condition, and if such condition is expiring. In that case, we
* give a strong warning to the player. The actual message printing is done
* by the caller.
*
* @param dur the duration to check for dangerous expiration.
* @param p the coordinates of the cell to check. Defaults to player position.
* @return whether the player is in immediate danger.
*/
bool need_expiration_warning(duration_type dur, dungeon_feature_type feat)
{
if (!is_feat_dangerous(feat, true) || !dur_expiring(dur))
return false;
if (dur == DUR_FLIGHT)
return true;
else if (dur == DUR_TRANSFORMATION
&& (form_can_swim()) || form_can_fly())
{
return true;
}
return false;
}
bool need_expiration_warning(duration_type dur, coord_def p)
{
return need_expiration_warning(dur, env.grid(p));
}
bool need_expiration_warning(dungeon_feature_type feat)
{
return need_expiration_warning(DUR_FLIGHT, feat)
|| need_expiration_warning(DUR_TRANSFORMATION, feat);
}
bool need_expiration_warning(coord_def p)
{
return need_expiration_warning(env.grid(p));
}
static string _constriction_description()
{
string cinfo = "";
vector<string> c_name;
const int num_free_tentacles = you.usable_tentacles();
if (num_free_tentacles)
{
cinfo += make_stringf("You have %d tentacle%s available for constriction.",
num_free_tentacles,
num_free_tentacles > 1 ? "s" : "");
}
if (you.is_directly_constricted())
{
const monster * const constrictor = monster_by_mid(you.constricted_by);
ASSERT(constrictor);
if (!cinfo.empty())
cinfo += "\n";
cinfo += make_stringf("You are being %s by %s.",
constrictor->constriction_does_damage(true) ?
"held" : "constricted",
constrictor->name(DESC_A).c_str());
}
if (you.is_constricting())
{
for (const auto &entry : *you.constricting)
{
monster *whom = monster_by_mid(entry.first);
ASSERT(whom);
if (!whom->is_directly_constricted())
continue;
c_name.push_back(whom->name(DESC_A));
}
if (!c_name.empty())
{
if (!cinfo.empty())
cinfo += "\n";
cinfo += "You are constricting ";
cinfo += comma_separated_line(c_name.begin(), c_name.end());
cinfo += ".";
}
}
return cinfo;
}
/**
* The player's radius of monster detection.
* @return the radius in which a player can detect monsters.
**/
int player_monster_detect_radius()
{
int radius = you.get_mutation_level(MUT_ANTENNAE) * 2;
if (player_equip_unrand(UNRAND_HOOD_ASSASSIN))
radius = max(radius, 4);
if (have_passive(passive_t::detect_montier))
radius = max(radius, you.piety / 20);
return min(radius, LOS_MAX_RANGE);
}
/**
* Return true if the player has angered Pandemonium by picking up or moving
* the Orb of Zot.
*/
bool player_on_orb_run()
{
return you.chapter == CHAPTER_ESCAPING
|| you.chapter == CHAPTER_ANGERED_PANDEMONIUM;
}
/**
* Return true if the player has the Orb of Zot.
* @return True if the player has the Orb, false otherwise.
*/
bool player_has_orb()
{
return you.chapter == CHAPTER_ESCAPING;
}
bool player::form_uses_xl() const
{
// No body parts that translate in any way to something fisticuffs could
// matter to, the attack mode is different. Plus, it's weird to have
// users of one particular [non-]weapon be effective for this
// unintentional form while others can just run or die. I believe this
// should apply to more forms, too. [1KB]
return form == transformation::wisp || form == transformation::fungus
|| form == transformation::pig
|| form == transformation::bat
&& you.get_mutation_level(MUT_VAMPIRISM) < 2;
}
bool player::wear_barding() const
{
return species::wears_barding(species);
}
static int _get_potion_heal_factor()
{
// healing factor is expressed in halves, so default is 2/2 -- 100%.
int factor = 2;
// start with penalties
factor -= player_equip_unrand(UNRAND_VINES) ? 2 : 0;
factor -= you.mutation[MUT_NO_POTION_HEAL];
// then apply bonuses - Kryia's doubles potion healing
factor *= player_equip_unrand(UNRAND_KRYIAS) ? 2 : 1;
// make sure we don't turn healing negative.
return max(0, factor);
}
void print_potion_heal_message()
{
// Don't give multiple messages in weird cases with both enhanced
// and reduced healing.
if (_get_potion_heal_factor() > 2)
{
if (player_equip_unrand(UNRAND_KRYIAS))
{
item_def* item = you.slot_item(EQ_BODY_ARMOUR);
mprf("%s enhances the healing.",
item->name(DESC_THE, false, false, false).c_str());
}
else
mpr("The healing is enhanced."); // bad message, but this should
// never be possible anyway
}
else if (_get_potion_heal_factor() == 0)
mpr("Your system rejects the healing.");
else if (_get_potion_heal_factor() < 2)
mpr("Your system partially rejects the healing.");
}
bool player::can_potion_heal()
{
return _get_potion_heal_factor() > 0;
}
int player::scale_potion_healing(int healing_amount)
{
return div_rand_round(healing_amount * _get_potion_heal_factor(), 2);
}
void player_open_door(coord_def doorpos)
{
// Finally, open the closed door!
set<coord_def> all_door;
find_connected_identical(doorpos, all_door);
const char *adj, *noun;
get_door_description(all_door.size(), &adj, &noun);
const string door_desc_adj =
env.markers.property_at(doorpos, MAT_ANY, "door_description_adjective");
const string door_desc_noun =
env.markers.property_at(doorpos, MAT_ANY, "door_description_noun");
if (!door_desc_adj.empty())
adj = door_desc_adj.c_str();
if (!door_desc_noun.empty())
noun = door_desc_noun.c_str();
if (!you.confused())
{
string door_open_prompt =
env.markers.property_at(doorpos, MAT_ANY, "door_open_prompt");
bool ignore_exclude = false;
if (!door_open_prompt.empty())
{
door_open_prompt += " (y/N)";
if (!yesno(door_open_prompt.c_str(), true, 'n', true, false))
{
if (is_exclude_root(doorpos))
canned_msg(MSG_OK);
else
{
if (yesno("Put travel exclusion on door? (Y/n)",
true, 'y'))
{
// Zero radius exclusion right on top of door.
set_exclude(doorpos, 0);
}
}
interrupt_activity(activity_interrupt::force);
return;
}
ignore_exclude = true;
}
if (!ignore_exclude && is_exclude_root(doorpos))
{
string prompt = make_stringf("This %s%s is marked as excluded! "
"Open it anyway?", adj, noun);
if (!yesno(prompt.c_str(), true, 'n', true, false))
{
canned_msg(MSG_OK);
interrupt_activity(activity_interrupt::force);
return;
}
}
}
const int skill = 8 + you.skill_rdiv(SK_STEALTH, 4, 3);
string berserk_open = env.markers.property_at(doorpos, MAT_ANY,
"door_berserk_verb_open");
string berserk_adjective = env.markers.property_at(doorpos, MAT_ANY,
"door_berserk_adjective");
string door_open_creak = env.markers.property_at(doorpos, MAT_ANY,
"door_noisy_verb_open");
string door_airborne = env.markers.property_at(doorpos, MAT_ANY,
"door_airborne_verb_open");
string door_open_verb = env.markers.property_at(doorpos, MAT_ANY,
"door_verb_open");
if (you.berserk())
{
// XXX: Better flavour for larger doors?
if (silenced(you.pos()))
{
if (!berserk_open.empty())
{
berserk_open += ".";
mprf(berserk_open.c_str(), adj, noun);
}
else
mprf("The %s%s flies open!", adj, noun);
}
else
{
if (!berserk_open.empty())
{
if (!berserk_adjective.empty())
berserk_open += " " + berserk_adjective;
else
berserk_open += ".";
mprf(MSGCH_SOUND, berserk_open.c_str(), adj, noun);
}
else
mprf(MSGCH_SOUND, "The %s%s flies open with a bang!", adj, noun);
noisy(15, you.pos());
}
}
else if (one_chance_in(skill) && !silenced(you.pos()))
{
if (!door_open_creak.empty())
mprf(MSGCH_SOUND, door_open_creak.c_str(), adj, noun);
else
{
mprf(MSGCH_SOUND, "As you open the %s%s, it creaks loudly!",
adj, noun);
}
noisy(10, you.pos());
}
else
{
const char* verb;
if (you.airborne())
{
if (!door_airborne.empty())
verb = door_airborne.c_str();
else
verb = "You reach down and open the %s%s.";
}
else
{
if (!door_open_verb.empty())
verb = door_open_verb.c_str();
else
verb = "You open the %s%s.";
}
mprf(verb, adj, noun);
}
vector<coord_def> excludes;
for (const auto &dc : all_door)
{
if (cell_is_runed(dc))
explored_tracked_feature(env.grid(dc));
dgn_open_door(dc);
set_terrain_changed(dc);
dungeon_events.fire_position_event(DET_DOOR_OPENED, dc);
// Even if some of the door is out of LOS, we want the entire
// door to be updated. Hitting this case requires a really big
// door!
if (env.map_knowledge(dc).seen())
{
env.map_knowledge(dc).set_feature(env.grid(dc));
#ifdef USE_TILE
tile_env.bk_bg(dc) = tileidx_feature_base(env.grid(dc));
#endif
}
if (is_excluded(dc))
excludes.push_back(dc);
}
update_exclusion_los(excludes);
viewwindow();
update_screen();
you.turn_is_over = true;
}
void player_close_door(coord_def doorpos)
{
// Finally, close the opened door!
string berserk_close = env.markers.property_at(doorpos, MAT_ANY,
"door_berserk_verb_close");
const string berserk_adjective = env.markers.property_at(doorpos, MAT_ANY,
"door_berserk_adjective");
const string door_close_creak = env.markers.property_at(doorpos, MAT_ANY,
"door_noisy_verb_close");
const string door_airborne = env.markers.property_at(doorpos, MAT_ANY,
"door_airborne_verb_close");
const string door_close_verb = env.markers.property_at(doorpos, MAT_ANY,
"door_verb_close");
const string door_desc_adj = env.markers.property_at(doorpos, MAT_ANY,
"door_description_adjective");
const string door_desc_noun = env.markers.property_at(doorpos, MAT_ANY,
"door_description_noun");
set<coord_def> all_door;
find_connected_identical(doorpos, all_door);
const auto door_vec = vector<coord_def>(all_door.begin(), all_door.end());
const char *adj, *noun;
get_door_description(all_door.size(), &adj, &noun);
const string waynoun_str = make_stringf("%sway", noun);
const char *waynoun = waynoun_str.c_str();
if (!door_desc_adj.empty())
adj = door_desc_adj.c_str();
if (!door_desc_noun.empty())
{
noun = door_desc_noun.c_str();
waynoun = noun;
}
for (const coord_def& dc : all_door)
{
if (monster* mon = monster_at(dc))
{
const bool mons_unseen = !you.can_see(*mon);
if (mons_unseen || mons_is_object(mon->type))
{
mprf("Something is blocking the %s!", waynoun);
// No free detection!
if (mons_unseen)
you.turn_is_over = true;
}
else
mprf("There's a creature in the %s!", waynoun);
return;
}
if (env.igrid(dc) != NON_ITEM)
{
if (!has_push_spaces(dc, false, &door_vec))
{
mprf("There's something jamming the %s.", waynoun);
return;
}
}
// messaging with gateways will be inconsistent if this isn't last
if (you.pos() == dc)
{
mprf("There's a thick-headed creature in the %s!", waynoun);
return;
}
}
const int you_old_top_item = env.igrid(you.pos());
bool items_moved = false;
for (const coord_def& dc : all_door)
items_moved |= push_items_from(dc, &door_vec);
// TODO: if only one thing moved, use that item's name
// TODO: handle des-derived strings. (Better yet, find a way to not have
// format strings in des...)
const char *items_msg = items_moved ? ", pushing everything out of the way"
: "";
const int skill = 8 + you.skill_rdiv(SK_STEALTH, 4, 3);
if (you.berserk())
{
if (silenced(you.pos()))
{
if (!berserk_close.empty())
{
berserk_close += ".";
mprf(berserk_close.c_str(), adj, noun);
}
else
mprf("You slam the %s%s shut%s!", adj, noun, items_msg);
}
else
{
if (!berserk_close.empty())
{
if (!berserk_adjective.empty())
berserk_close += " " + berserk_adjective;
else
berserk_close += ".";
mprf(MSGCH_SOUND, berserk_close.c_str(), adj, noun);
}
else
{
mprf(MSGCH_SOUND, "You slam the %s%s shut with a bang%s!",
adj, noun, items_msg);
}
noisy(15, you.pos());
}
}
else if (one_chance_in(skill) && !silenced(you.pos()))
{
if (!door_close_creak.empty())
mprf(MSGCH_SOUND, door_close_creak.c_str(), adj, noun);
else
{
mprf(MSGCH_SOUND, "As you close the %s%s%s, it creaks loudly!",
adj, noun, items_msg);
}
noisy(10, you.pos());
}
else
{
if (you.airborne())
{
if (!door_airborne.empty())
mprf(door_airborne.c_str(), adj, noun);
else
mprf("You reach down and close the %s%s%s.", adj, noun, items_msg);
}
else
{
if (!door_close_verb.empty())
mprf(door_close_verb.c_str(), adj, noun);
else
mprf("You close the %s%s%s.", adj, noun, items_msg);
}
}
vector<coord_def> excludes;
for (const coord_def& dc : all_door)
{
// Once opened, formerly runed doors become normal doors.
dgn_close_door(dc);
set_terrain_changed(dc);
dungeon_events.fire_position_event(DET_DOOR_CLOSED, dc);
// Even if some of the door is out of LOS once it's closed
// (or even if some of it is out of LOS when it's open), we
// want the entire door to be updated.
if (env.map_knowledge(dc).seen())
{
env.map_knowledge(dc).set_feature(env.grid(dc));
#ifdef USE_TILE
tile_env.bk_bg(dc) = tileidx_feature_base(env.grid(dc));
#endif
}
if (is_excluded(dc))
excludes.push_back(dc);
}
update_exclusion_los(excludes);
// item pushing may have moved items under the player
if (env.igrid(you.pos()) != you_old_top_item)
item_check();
you.turn_is_over = true;
}
/**
* Return a string describing the player's hand(s) taking a given verb.
*
* @param plural_verb A plural-agreeing verb. ("Smoulders", "are", etc.)
* @return A string describing the action.
* E.g. "tentacles smoulder", "paw is", etc.
*/
string player::hands_verb(const string &plural_verb) const
{
bool plural;
const string hand = hand_name(true, &plural);
return hand + " " + conjugate_verb(plural_verb, plural);
}
// Is this a character that would not normally have a preceding space when
// it follows a word?
static bool _is_end_punct(char c)
{
switch (c)
{
case ' ': case '.': case '!': case '?':
case ',': case ':': case ';': case ')':
return true;
}
return false;
}
/**
* Return a string describing the player's hand(s) (or equivalent) taking the
* given action (verb).
*
* @param plural_verb The plural-agreeing verb corresponding to the action to
* take. E.g., "smoulder", "glow", "gain", etc.
* @param object The object or predicate complement of the action,
* including any sentence-final punctuation. E.g. ".",
* "new energy.", etc.
* @return A string describing the player's hands taking the
* given action. E.g. "Your tentacle gains new energy."
*/
string player::hands_act(const string &plural_verb,
const string &object) const
{
const bool space = !object.empty() && !_is_end_punct(object[0]);
return "Your " + hands_verb(plural_verb) + (space ? " " : "") + object;
}
int player::inaccuracy() const
{
int degree = 0;
if (player_equip_unrand(UNRAND_AIR))
degree++;
if (get_mutation_level(MUT_MISSING_EYE))
degree++;
return degree;
}
/**
* Handle effects that occur after the player character stops berserking.
*/
void player_end_berserk()
{
if (!you.duration[DUR_PARALYSIS] && !you.petrified())
mprf(MSGCH_WARN, "You are exhausted.");
you.berserk_penalty = 0;
int dur = 12 + roll_dice(2, 12);
// Slow durations are multiplied by haste_mul (3/2), exhaustion lasts
// slightly longer.
you.increase_duration(DUR_BERSERK_COOLDOWN, dur * 2);
// Don't trigger too many hints mode messages.
const bool hints_slow = Hints.hints_events[HINT_YOU_ENCHANTED];
Hints.hints_events[HINT_YOU_ENCHANTED] = false;
if (player_equip_unrand(UNRAND_BEAR_SPIRIT))
dur = div_rand_round(dur * 2, 3);
slow_player(dur);
//Un-apply Berserk's +50% Current/Max HP
calc_hp(true, false);
learned_something_new(HINT_POSTBERSERK);
Hints.hints_events[HINT_YOU_ENCHANTED] = hints_slow;
quiver::set_needs_redraw();
}
/**
* Does the player have the Sanguine Armour mutation (not suppressed by a form)
* while being at a low enough HP (<67%) for its benefits to trigger?
*
* @return Whether Sanguine Armour should be active.
*/
bool sanguine_armour_valid()
{
// why does this need to specify the activity type explicitly?
return you.hp <= you.hp_max * 2 / 3
&& you.get_mutation_level(MUT_SANGUINE_ARMOUR, mutation_activity_type::FULL);
}
/// Trigger sanguine armour, updating the duration & messaging as appropriate.
void activate_sanguine_armour()
{
const bool was_active = you.duration[DUR_SANGUINE_ARMOUR];
you.duration[DUR_SANGUINE_ARMOUR] = random_range(60, 100);
if (!was_active)
{
mpr("Your blood congeals into armour.");
you.redraw_armour_class = true;
}
}
/**
* Refreshes the protective aura around the player after striking with
* a weapon of protection. The duration is very short.
*/
void refresh_weapon_protection()
{
if (!you.duration[DUR_SPWPN_PROTECTION])
mpr("Your weapon exudes an aura of protection.");
you.increase_duration(DUR_SPWPN_PROTECTION, 3 + random2(2), 5);
you.redraw_armour_class = true;
}
void refresh_meek_bonus()
{
const string MEEK_KEY = "meek_ac_key";
const bool meek_possible = you.duration[DUR_SPWPN_PROTECTION]
&& player_equip_unrand(UNRAND_MEEK);
const int bonus_ac = _meek_bonus();
if (!meek_possible || !bonus_ac)
{
if (you.props.exists(MEEK_KEY))
{
you.props.erase(MEEK_KEY);
you.redraw_armour_class = true;
}
return;
}
const int last_bonus = you.props[MEEK_KEY].get_int();
if (last_bonus == bonus_ac)
return;
you.props[MEEK_KEY] = bonus_ac;
you.redraw_armour_class = true;
}
// Is the player immune to a particular hex because of their
// intrinsic properties?
bool player::immune_to_hex(const spell_type hex) const
{
switch (hex)
{
case SPELL_PARALYSIS_GAZE:
case SPELL_PARALYSE:
case SPELL_SLOW:
return stasis();
case SPELL_CONFUSE:
case SPELL_CONFUSION_GAZE:
case SPELL_MASS_CONFUSION:
return clarity() || you.duration[DUR_DIVINE_STAMINA] > 0;
case SPELL_TELEPORT_OTHER:
case SPELL_BLINK_OTHER:
case SPELL_BLINK_OTHER_CLOSE:
return no_tele();
case SPELL_MESMERISE:
case SPELL_AVATAR_SONG:
case SPELL_SIREN_SONG:
return clarity() || berserk();
case SPELL_CAUSE_FEAR:
return clarity() || !(holiness() & MH_NATURAL) || berserk();
case SPELL_PETRIFY:
return res_petrify();
case SPELL_PORKALATOR:
return is_lifeless_undead();
case SPELL_VIRULENCE:
return res_poison() == 3;
// don't include the hidden "sleep immunity" duration
case SPELL_SLEEP:
case SPELL_DREAM_DUST:
return !actor::can_sleep();
case SPELL_HIBERNATION:
return !can_hibernate();
default:
return false;
}
}
// Activate DUR_AGILE.
void player::be_agile(int pow)
{
const bool were_agile = you.duration[DUR_AGILITY] > 0;
mprf(MSGCH_DURATION, "You feel %sagile all of a sudden.",
were_agile ? "more " : "");
you.increase_duration(DUR_AGILITY, 35 + random2(pow), 80);
if (!were_agile)
you.redraw_evasion = true;
}
bool player::allies_forbidden()
{
return get_mutation_level(MUT_NO_LOVE)
|| have_passive(passive_t::no_allies);
}
|
#ifndef EVENTBUS_H_
#define EVENTBUS_H_
#include <string>
#include <vector>
#include <boost/signals2.hpp>
template<class T>
class singleton {
public:
template<typename ... Args>
static T* get_instance(Args ... args) {
if (!m_instance) {
m_instance = new T(std::forward<Args>(args)...);
}
return m_instance;
}
static
void destroy_instance() {
delete m_instance;
m_instance = nullptr;
}
private:
static T* m_instance;
};
template<class T> T* singleton<T>::m_instance = nullptr;
class event {
};
class event_bus : public singleton<event_bus> {
public:
event_bus() {
}
virtual ~event_bus() {
}
template<typename T>
boost::signals2::signal<T>* create_signal() {
typedef boost::signals2::signal<T> signal_t;
if (m_signals.find(typeid(T).name()) == m_signals.end()) {
signal_t* signal = new signal_t();
m_signals[typeid(T).name()] = signal;
return (signal);
}
return 0;
}
template<typename T>
boost::signals2::connection subscribe(const boost::function<T>& callback) {
typedef boost::signals2::signal<T> signal_t;
signal_t* signal = nullptr;
if (m_signals.find(typeid(T).name()) == m_signals.end()) {
signal = create_signal<T>();
} else {
signal = dynamic_cast<signal_t*>(m_signals[typeid(T).name()]);
}
boost::signals2::connection ret = signal->connect(callback);
m_connections[typeid(T).name()].push_back(ret);
m_shared_connections[typeid(T).name()].push_back(
boost::signals2::shared_connection_block(
m_connections[typeid(T).name()].back(), false));
// signalsChanged ();
return (ret);
}
template<typename T, typename ... Args>
void post(Args ... args) {
typedef boost::signals2::signal<T> signal_t;
if (m_signals.find(typeid(T).name()) != m_signals.end()) {
signal_t* signal = dynamic_cast<signal_t*>(m_signals[typeid(T).name()]);
signal->operator()(std::forward<Args>(args)...);
}
}
private:
std::map<std::string, boost::signals2::signal_base*> m_signals;
std::map<std::string, std::vector<boost::signals2::connection> > m_connections;
std::map<std::string, std::vector<boost::signals2::shared_connection_block> > m_shared_connections;
};
#endif /* EVENTBUS_H_ */
|
//
// basic_streambuf.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 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_BASIC_STREAMBUF_HPP
#define BOOST_ASIO_BASIC_STREAMBUF_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_NO_IOSTREAM)
#include <algorithm>
#include <cstring>
#include <stdexcept>
#include <streambuf>
#include <vector>
#include <boost/asio/basic_streambuf_fwd.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/detail/limits.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/throw_exception.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
/// Automatically resizable buffer class based on std::streambuf.
/**
* The @c basic_streambuf class is derived from @c std::streambuf to associate
* the streambuf's input and output sequences with one or more character
* arrays. These character arrays are internal to the @c basic_streambuf
* object, but direct access to the array elements is provided to permit them
* to be used efficiently with I/O operations. Characters written to the output
* sequence of a @c basic_streambuf object are appended to the input sequence
* of the same object.
*
* The @c basic_streambuf class's public interface is intended to permit the
* following implementation strategies:
*
* @li A single contiguous character array, which is reallocated as necessary
* to accommodate changes in the size of the character sequence. This is the
* implementation approach currently used in Asio.
*
* @li A sequence of one or more character arrays, where each array is of the
* same size. Additional character array objects are appended to the sequence
* to accommodate changes in the size of the character sequence.
*
* @li A sequence of one or more character arrays of varying sizes. Additional
* character array objects are appended to the sequence to accommodate changes
* in the size of the character sequence.
*
* The constructor for basic_streambuf accepts a @c size_t argument specifying
* the maximum of the sum of the sizes of the input sequence and output
* sequence. During the lifetime of the @c basic_streambuf object, the following
* invariant holds:
* @code size() <= max_size()@endcode
* Any member function that would, if successful, cause the invariant to be
* violated shall throw an exception of class @c std::length_error.
*
* The constructor for @c basic_streambuf takes an Allocator argument. A copy
* of this argument is used for any memory allocation performed, by the
* constructor and by all member functions, during the lifetime of each @c
* basic_streambuf object.
*
* @par Examples
* Writing directly from an streambuf to a socket:
* @code
* boost::asio::streambuf b;
* std::ostream os(&b);
* os << "Hello, World!\n";
*
* // try sending some data in input sequence
* size_t n = sock.send(b.data());
*
* b.consume(n); // sent data is removed from input sequence
* @endcode
*
* Reading from a socket directly into a streambuf:
* @code
* boost::asio::streambuf b;
*
* // reserve 512 bytes in output sequence
* boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);
*
* size_t n = sock.receive(bufs);
*
* // received data is "committed" from output sequence to input sequence
* b.commit(n);
*
* std::istream is(&b);
* std::string s;
* is >> s;
* @endcode
*/
#if defined(GENERATING_DOCUMENTATION)
template <typename Allocator = std::allocator<char> >
#else
template <typename Allocator>
#endif
class basic_streambuf
: public std::streambuf,
private noncopyable
{
public:
#if defined(GENERATING_DOCUMENTATION)
/// The type used to represent the input sequence as a list of buffers.
typedef implementation_defined const_buffers_type;
/// The type used to represent the output sequence as a list of buffers.
typedef implementation_defined mutable_buffers_type;
#else
typedef BOOST_ASIO_CONST_BUFFER const_buffers_type;
typedef BOOST_ASIO_MUTABLE_BUFFER mutable_buffers_type;
#endif
/// Construct a basic_streambuf object.
/**
* Constructs a streambuf with the specified maximum size. The initial size
* of the streambuf's input sequence is 0.
*/
explicit basic_streambuf(
std::size_t maximum_size = (std::numeric_limits<std::size_t>::max)(),
const Allocator& allocator = Allocator())
: max_size_(maximum_size),
buffer_(allocator)
{
std::size_t pend = (std::min<std::size_t>)(max_size_, buffer_delta);
buffer_.resize((std::max<std::size_t>)(pend, 1));
setg(&buffer_[0], &buffer_[0], &buffer_[0]);
setp(&buffer_[0], &buffer_[0] + pend);
}
/// Get the size of the input sequence.
/**
* @returns The size of the input sequence. The value is equal to that
* calculated for @c s in the following code:
* @code
* size_t s = 0;
* const_buffers_type bufs = data();
* const_buffers_type::const_iterator i = bufs.begin();
* while (i != bufs.end())
* {
* const_buffer buf(*i++);
* s += buf.size();
* }
* @endcode
*/
std::size_t size() const BOOST_ASIO_NOEXCEPT
{
return pptr() - gptr();
}
/// Get the maximum size of the basic_streambuf.
/**
* @returns The allowed maximum of the sum of the sizes of the input sequence
* and output sequence.
*/
std::size_t max_size() const BOOST_ASIO_NOEXCEPT
{
return max_size_;
}
/// Get the current capacity of the basic_streambuf.
/**
* @returns The current total capacity of the streambuf, i.e. for both the
* input sequence and output sequence.
*/
std::size_t capacity() const BOOST_ASIO_NOEXCEPT
{
return buffer_.capacity();
}
/// Get a list of buffers that represents the input sequence.
/**
* @returns An object of type @c const_buffers_type that satisfies
* ConstBufferSequence requirements, representing all character arrays in the
* input sequence.
*
* @note The returned object is invalidated by any @c basic_streambuf member
* function that modifies the input sequence or output sequence.
*/
const_buffers_type data() const BOOST_ASIO_NOEXCEPT
{
return boost::asio::buffer(boost::asio::const_buffer(gptr(),
(pptr() - gptr()) * sizeof(char_type)));
}
/// Get a list of buffers that represents the output sequence, with the given
/// size.
/**
* Ensures that the output sequence can accommodate @c n characters,
* reallocating character array objects as necessary.
*
* @returns An object of type @c mutable_buffers_type that satisfies
* MutableBufferSequence requirements, representing character array objects
* at the start of the output sequence such that the sum of the buffer sizes
* is @c n.
*
* @throws std::length_error If <tt>size() + n > max_size()</tt>.
*
* @note The returned object is invalidated by any @c basic_streambuf member
* function that modifies the input sequence or output sequence.
*/
mutable_buffers_type prepare(std::size_t n)
{
reserve(n);
return boost::asio::buffer(boost::asio::mutable_buffer(
pptr(), n * sizeof(char_type)));
}
/// Move characters from the output sequence to the input sequence.
/**
* Appends @c n characters from the start of the output sequence to the input
* sequence. The beginning of the output sequence is advanced by @c n
* characters.
*
* Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and
* no intervening operations that modify the input or output sequence.
*
* @note If @c n is greater than the size of the output sequence, the entire
* output sequence is moved to the input sequence and no error is issued.
*/
void commit(std::size_t n)
{
n = std::min<std::size_t>(n, epptr() - pptr());
pbump(static_cast<int>(n));
setg(eback(), gptr(), pptr());
}
/// Remove characters from the input sequence.
/**
* Removes @c n characters from the beginning of the input sequence.
*
* @note If @c n is greater than the size of the input sequence, the entire
* input sequence is consumed and no error is issued.
*/
void consume(std::size_t n)
{
if (egptr() < pptr())
setg(&buffer_[0], gptr(), pptr());
if (gptr() + n > pptr())
n = pptr() - gptr();
gbump(static_cast<int>(n));
}
protected:
enum { buffer_delta = 128 };
/// Override std::streambuf behaviour.
/**
* Behaves according to the specification of @c std::streambuf::underflow().
*/
int_type underflow()
{
if (gptr() < pptr())
{
setg(&buffer_[0], gptr(), pptr());
return traits_type::to_int_type(*gptr());
}
else
{
return traits_type::eof();
}
}
/// Override std::streambuf behaviour.
/**
* Behaves according to the specification of @c std::streambuf::overflow(),
* with the specialisation that @c std::length_error is thrown if appending
* the character to the input sequence would require the condition
* <tt>size() > max_size()</tt> to be true.
*/
int_type overflow(int_type c)
{
if (!traits_type::eq_int_type(c, traits_type::eof()))
{
if (pptr() == epptr())
{
std::size_t buffer_size = pptr() - gptr();
if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta)
{
reserve(max_size_ - buffer_size);
}
else
{
reserve(buffer_delta);
}
}
*pptr() = traits_type::to_char_type(c);
pbump(1);
return c;
}
return traits_type::not_eof(c);
}
void reserve(std::size_t n)
{
// Get current stream positions as offsets.
std::size_t gnext = gptr() - &buffer_[0];
std::size_t pnext = pptr() - &buffer_[0];
std::size_t pend = epptr() - &buffer_[0];
// Check if there is already enough space in the put area.
if (n <= pend - pnext)
{
return;
}
// Shift existing contents of get area to start of buffer.
if (gnext > 0)
{
pnext -= gnext;
std::memmove(&buffer_[0], &buffer_[0] + gnext, pnext);
}
// Ensure buffer is large enough to hold at least the specified size.
if (n > pend - pnext)
{
if (n <= max_size_ && pnext <= max_size_ - n)
{
pend = pnext + n;
buffer_.resize((std::max<std::size_t>)(pend, 1));
}
else
{
std::length_error ex("boost::asio::streambuf too long");
boost::asio::detail::throw_exception(ex);
}
}
// Update stream positions.
setg(&buffer_[0], &buffer_[0], &buffer_[0] + pnext);
setp(&buffer_[0] + pnext, &buffer_[0] + pend);
}
private:
std::size_t max_size_;
std::vector<char_type, Allocator> buffer_;
// Helper function to get the preferred size for reading data.
friend std::size_t read_size_helper(
basic_streambuf& sb, std::size_t max_size)
{
return std::min<std::size_t>(
std::max<std::size_t>(512, sb.buffer_.capacity() - sb.size()),
std::min<std::size_t>(max_size, sb.max_size() - sb.size()));
}
};
/// Adapts basic_streambuf to the dynamic buffer sequence type requirements.
#if defined(GENERATING_DOCUMENTATION)
template <typename Allocator = std::allocator<char> >
#else
template <typename Allocator>
#endif
class basic_streambuf_ref
{
public:
/// The type used to represent the input sequence as a list of buffers.
typedef typename basic_streambuf<Allocator>::const_buffers_type
const_buffers_type;
/// The type used to represent the output sequence as a list of buffers.
typedef typename basic_streambuf<Allocator>::mutable_buffers_type
mutable_buffers_type;
/// Construct a basic_streambuf_ref for the given basic_streambuf object.
explicit basic_streambuf_ref(basic_streambuf<Allocator>& sb)
: sb_(sb)
{
}
/// Copy construct a basic_streambuf_ref.
basic_streambuf_ref(const basic_streambuf_ref& other) BOOST_ASIO_NOEXCEPT
: sb_(other.sb_)
{
}
#if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move construct a basic_streambuf_ref.
basic_streambuf_ref(basic_streambuf_ref&& other) BOOST_ASIO_NOEXCEPT
: sb_(other.sb_)
{
}
#endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Get the size of the input sequence.
std::size_t size() const BOOST_ASIO_NOEXCEPT
{
return sb_.size();
}
/// Get the maximum size of the dynamic buffer.
std::size_t max_size() const BOOST_ASIO_NOEXCEPT
{
return sb_.max_size();
}
/// Get the current capacity of the dynamic buffer.
std::size_t capacity() const BOOST_ASIO_NOEXCEPT
{
return sb_.capacity();
}
/// Get a list of buffers that represents the input sequence.
const_buffers_type data() const BOOST_ASIO_NOEXCEPT
{
return sb_.data();
}
/// Get a list of buffers that represents the output sequence, with the given
/// size.
mutable_buffers_type prepare(std::size_t n)
{
return sb_.prepare(n);
}
/// Move bytes from the output sequence to the input sequence.
void commit(std::size_t n)
{
return sb_.commit(n);
}
/// Remove characters from the input sequence.
void consume(std::size_t n)
{
return sb_.consume(n);
}
private:
basic_streambuf<Allocator>& sb_;
};
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
#endif // BOOST_ASIO_BASIC_STREAMBUF_HPP
|
/*
* Copyright 2019 Xilinx, 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 _XF_SCHARR_HPP_
#define _XF_SCHARR_HPP_
#ifndef __cplusplus
#error C++ is needed to include this header
#endif
typedef unsigned short uint16_t;
#include "common/xf_common.hpp"
#include "common/xf_utility.hpp"
#include "hls_stream.h"
namespace xf {
namespace cv {
/********************************************************************
* xFGradientX : X-Gradient Computation
*
* -------------
* |-3 0 3|
* |-10 0 10|
* |-3 0 3|
* -------------
********************************************************************/
template <int DEPTH_SRC, int DEPTH_DST>
XF_PTNAME(DEPTH_DST)
xFGradientX(XF_PTNAME(DEPTH_SRC) vt0,
XF_PTNAME(DEPTH_SRC) vt1,
XF_PTNAME(DEPTH_SRC) vt2,
XF_PTNAME(DEPTH_SRC) vm0,
XF_PTNAME(DEPTH_SRC) vm1,
XF_PTNAME(DEPTH_SRC) vm2,
XF_PTNAME(DEPTH_SRC) vb0,
XF_PTNAME(DEPTH_SRC) vb1,
XF_PTNAME(DEPTH_SRC) vb2) {
// clang-format off
#pragma HLS INLINE off
// clang-format on
/* XF_PTNAME(DEPTH_DST) temp_g;
XF_PTNAME(DEPTH_DST) M00 = (XF_PTNAME(DEPTH_DST))vm2 << 3;
M00 = M00 + vm2 + vm2;
XF_PTNAME(DEPTH_DST) M01 = (XF_PTNAME(DEPTH_DST))vm0 << 3;
M01 = M01 + vm0 + vm0;
XF_PTNAME(DEPTH_DST) A00 = (XF_PTNAME(DEPTH_DST))vt2 << 1;
A00 = A00 + vt2;
XF_PTNAME(DEPTH_DST) A01 = (XF_PTNAME(DEPTH_DST))vb2 << 1;
A01 = A01 + vb2;
A00 = A00 + A01;
XF_PTNAME(DEPTH_DST) S00 = (XF_PTNAME(DEPTH_DST))vt0 << 1;
S00 = S00 + vt0;
XF_PTNAME(DEPTH_DST) S01 = (XF_PTNAME(DEPTH_DST))vb0 << 1;
S01 = S01 + vb0;
S00 = S00 + S01;
temp_g = M00 - M01;
temp_g = temp_g + A00;
temp_g = temp_g - S00;*/
XF_PTNAME(DEPTH_DST) g_x;
// ap_uint<8> g_x;
short int temp_g;
short int M00 = (short int)vm2 << 3;
M00 = M00 + vm2 + vm2;
short int M01 = (short int)vm0 << 3;
M01 = M01 + vm0 + vm0;
short int A00 = (short int)vt2 << 1;
A00 = A00 + vt2;
short int A01 = (short int)vb2 << 1;
A01 = A01 + vb2;
A00 = A00 + A01;
short int S00 = (short int)vt0 << 1;
S00 = S00 + vt0;
short int S01 = (short int)vb0 << 1;
S01 = S01 + vb0;
S00 = S00 + S01;
temp_g = M00 - M01;
temp_g = temp_g + A00;
temp_g = temp_g - S00;
g_x = temp_g;
if ((DEPTH_DST == XF_8UP) || (DEPTH_DST == XF_24UP)) {
if (temp_g < 0) g_x = 0;
if (temp_g > 255) g_x = 255;
}
return g_x;
}
/**********************************************************************
* xFGradientY : Y-Gradient Computation
*
* -------------
* |-3 -10 -3|
* | 0 0 0|
* | 3 10 3|
* -------------
**********************************************************************/
template <int DEPTH_SRC, int DEPTH_DST>
XF_PTNAME(DEPTH_DST)
xFGradientY(XF_PTNAME(DEPTH_SRC) vt0,
XF_PTNAME(DEPTH_SRC) vt1,
XF_PTNAME(DEPTH_SRC) vt2,
XF_PTNAME(DEPTH_SRC) vm0,
XF_PTNAME(DEPTH_SRC) vm1,
XF_PTNAME(DEPTH_SRC) vm2,
XF_PTNAME(DEPTH_SRC) vb0,
XF_PTNAME(DEPTH_SRC) vb1,
XF_PTNAME(DEPTH_SRC) vb2) {
// clang-format off
#pragma HLS INLINE off
// clang-format on
/* XF_PTNAME(DEPTH_DST) temp_g;
XF_PTNAME(DEPTH_DST) M00 = (XF_PTNAME(DEPTH_DST))vb1 << 3;
M00 = M00 + vb1 + vb1;
XF_PTNAME(DEPTH_DST) M01 = (XF_PTNAME(DEPTH_DST))vt1 << 3;
M01 = M01 + vt1 + vt1;
XF_PTNAME(DEPTH_DST) A00 = (XF_PTNAME(DEPTH_DST))vb0 << 1;
A00 = A00 + vb0;
XF_PTNAME(DEPTH_DST) A01 = (XF_PTNAME(DEPTH_DST))vb2 << 1;
A01 = A01 + vb2;
A00 = A00 + A01;
XF_PTNAME(DEPTH_DST) S00 = (XF_PTNAME(DEPTH_DST))vt0 << 1;
S00 = S00 + vt0;
XF_PTNAME(DEPTH_DST) S01 = (XF_PTNAME(DEPTH_DST))vt2 << 1;
S01 = S01 + vt2;
S00 = S00 + S01;
temp_g = M00 - M01;
temp_g = temp_g + A00;
temp_g = temp_g - S00;*/
// XF_PTNAME(DEPTH_DST) g_y;
XF_PTNAME(DEPTH_DST) g_y;
// ap_uint<8> g_y;
short int temp_g;
short int M00 = (short int)vb1 << 3;
M00 = M00 + vb1 + vb1;
short int M01 = (short int)vt1 << 3;
M01 = M01 + vt1 + vt1;
short int A00 = (short int)vb0 << 1;
A00 = A00 + vb0;
short int A01 = (short int)vb2 << 1;
A01 = A01 + vb2;
A00 = A00 + A01;
short int S00 = (short int)vt0 << 1;
S00 = S00 + vt0;
short int S01 = (short int)vt2 << 1;
S01 = S01 + vt2;
S00 = S00 + S01;
temp_g = M00 - M01;
temp_g = temp_g + A00;
temp_g = temp_g - S00;
g_y = temp_g;
if ((DEPTH_DST == XF_8UP) || (DEPTH_DST == XF_24UP)) {
if (temp_g < 0) g_y = 0;
if (temp_g > 255) g_y = 255;
}
return g_y;
}
/**
* xFScharr3x3 : Applies the mask and Computes the gradient values
*
*/
template <int NPC, int PLANES, int DEPTH_SRC, int DEPTH_DST>
void xFScharr3x3(XF_PTNAME(DEPTH_DST) GradientvaluesX[XF_NPIXPERCYCLE(NPC)],
XF_PTNAME(DEPTH_DST) GradientvaluesY[XF_NPIXPERCYCLE(NPC)],
XF_PTNAME(DEPTH_SRC) src_buf1[XF_NPIXPERCYCLE(NPC) + 2],
XF_PTNAME(DEPTH_SRC) src_buf2[XF_NPIXPERCYCLE(NPC) + 2],
XF_PTNAME(DEPTH_SRC) src_buf3[XF_NPIXPERCYCLE(NPC) + 2]) {
// clang-format off
#pragma HLS INLINE off
// clang-format on
int STEP, STEP_OUT;
if ((DEPTH_DST == XF_48SP) || (DEPTH_DST == XF_16SP)) {
STEP_OUT = 16;
STEP = 8;
} else {
STEP_OUT = 8;
STEP = 8;
}
Compute_Grad_Loop:
for (ap_uint<5> j = 0; j < XF_NPIXPERCYCLE(NPC); j++) {
int p = 0;
// clang-format off
#pragma HLS UNROLL
// clang-format on
for (ap_uint<5> c = 0, k = 0; c < PLANES; c++, k += STEP) {
GradientvaluesX[j].range(p + (STEP_OUT - 1), p) = xFGradientX<DEPTH_SRC, DEPTH_DST>(
src_buf1[j].range(k + STEP - 1, k), src_buf1[j + 1].range(k + STEP - 1, k),
src_buf1[j + 2].range(k + STEP - 1, k), src_buf2[j].range(k + STEP - 1, k),
src_buf2[j + 1].range(k + STEP - 1, k), src_buf2[j + 2].range(k + STEP - 1, k),
src_buf3[j].range(k + STEP - 1, k), src_buf3[j + 1].range(k + STEP - 1, k),
src_buf3[j + 2].range(k + STEP - 1, k));
GradientvaluesY[j].range(p + (STEP_OUT - 1), p) = xFGradientY<DEPTH_SRC, DEPTH_DST>(
src_buf1[j].range(k + STEP - 1, k), src_buf1[j + 1].range(k + STEP - 1, k),
src_buf1[j + 2].range(k + STEP - 1, k), src_buf2[j].range(k + STEP - 1, k),
src_buf2[j + 1].range(k + STEP - 1, k), src_buf2[j + 2].range(k + STEP - 1, k),
src_buf3[j].range(k + STEP - 1, k), src_buf3[j + 1].range(k + STEP - 1, k),
src_buf3[j + 2].range(k + STEP - 1, k));
p += STEP_OUT;
}
}
}
/**************************************************************************************
* ProcessScharr3x3 : Computes gradients for the column input data
**************************************************************************************/
template <int SRC_T,
int DST_T,
int ROWS,
int COLS,
int PLANES,
int DEPTH_SRC,
int DEPTH_DST,
int NPC,
int WORDWIDTH_SRC,
int WORDWIDTH_DST,
int TC>
void ProcessScharr3x3(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& _gradx_mat,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& _grady_mat,
XF_SNAME(WORDWIDTH_SRC) buf[3][(COLS >> XF_BITSHIFT(NPC))],
XF_PTNAME(DEPTH_SRC) src_buf1[XF_NPIXPERCYCLE(NPC) + 2],
XF_PTNAME(DEPTH_SRC) src_buf2[XF_NPIXPERCYCLE(NPC) + 2],
XF_PTNAME(DEPTH_SRC) src_buf3[XF_NPIXPERCYCLE(NPC) + 2],
XF_PTNAME(DEPTH_DST) GradientValuesX[XF_NPIXPERCYCLE(NPC)],
XF_PTNAME(DEPTH_DST) GradientValuesY[XF_NPIXPERCYCLE(NPC)],
XF_SNAME(WORDWIDTH_DST) & P0,
XF_SNAME(WORDWIDTH_DST) & P1,
uint16_t img_width,
uint16_t img_height,
ap_uint<13> row_ind,
uint16_t& shift_x,
uint16_t& shift_y,
ap_uint<2> tp,
ap_uint<2> mid,
ap_uint<2> bottom,
ap_uint<13> row,
int& read_index,
int& write_index) {
// clang-format off
#pragma HLS INLINE
// clang-format on
XF_SNAME(WORDWIDTH_SRC) buf0, buf1, buf2;
uint16_t npc = XF_NPIXPERCYCLE(NPC);
ap_uint<5> buf_size = XF_NPIXPERCYCLE(NPC) + 2;
Col_Loop:
for (ap_uint<13> col = 0; col < img_width; col++) {
// clang-format off
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
#pragma HLS pipeline
// clang-format on
if (row < img_height)
buf[row_ind][col] = _src_mat.read(read_index++); // Read data
else
buf[bottom][col] = 0;
buf0 = buf[tp][col];
buf1 = buf[mid][col];
buf2 = buf[bottom][col];
if (NPC == XF_NPPC8) {
xfExtractPixels<NPC, WORDWIDTH_SRC, DEPTH_SRC>(&src_buf1[2], buf0, 0);
xfExtractPixels<NPC, WORDWIDTH_SRC, DEPTH_SRC>(&src_buf2[2], buf1, 0);
xfExtractPixels<NPC, WORDWIDTH_SRC, DEPTH_SRC>(&src_buf3[2], buf2, 0);
} else {
src_buf1[2] = buf0;
src_buf2[2] = buf1;
src_buf3[2] = buf2;
}
xFScharr3x3<NPC, PLANES, DEPTH_SRC, DEPTH_DST>(GradientValuesX, GradientValuesY, src_buf1, src_buf2, src_buf3);
if (col == 0) {
shift_x = 0;
shift_y = 0;
P0 = 0;
P1 = 0;
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesX[0], P0, 1, (npc - 1), shift_x);
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesY[0], P1, 1, (npc - 1), shift_y);
} else {
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesX[0], P0, 0, 1, shift_x);
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesY[0], P1, 0, 1, shift_y);
_gradx_mat.write(write_index, P0);
_grady_mat.write(write_index++, P1);
shift_x = 0;
shift_y = 0;
P0 = 0;
P1 = 0;
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesX[0], P0, 1, (npc - 1), shift_x);
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesY[0], P1, 1, (npc - 1), shift_y);
}
src_buf1[0] = src_buf1[buf_size - 2];
src_buf1[1] = src_buf1[buf_size - 1];
src_buf2[0] = src_buf2[buf_size - 2];
src_buf2[1] = src_buf2[buf_size - 1];
src_buf3[0] = src_buf3[buf_size - 2];
src_buf3[1] = src_buf3[buf_size - 1];
} // Col_Loop
}
template <int SRC_T,
int DST_T,
int ROWS,
int COLS,
int PLANES,
int DEPTH_SRC,
int DEPTH_DST,
int NPC,
int WORDWIDTH_SRC,
int WORDWIDTH_DST,
int TC>
void xFScharrFilterKernel(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& _gradx_mat,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& _grady_mat,
uint16_t img_height,
uint16_t img_width) {
ap_uint<13> row_ind;
ap_uint<2> tp, mid, bottom;
ap_uint<8> buf_size = XF_NPIXPERCYCLE(NPC) + 2;
uint16_t shift_x = 0, shift_y = 0;
ap_uint<13> row, col;
int read_index = 0, write_index = 0;
XF_PTNAME(DEPTH_DST)
GradientValuesX[XF_NPIXPERCYCLE(NPC) * PLANES]; // X-Gradient result buffer
XF_PTNAME(DEPTH_DST)
GradientValuesY[XF_NPIXPERCYCLE(NPC) * PLANES]; // Y-Gradient result buffer
// clang-format off
#pragma HLS ARRAY_PARTITION variable=GradientValuesX complete dim=1
#pragma HLS ARRAY_PARTITION variable=GradientValuesY complete dim=1
// clang-format on
XF_PTNAME(DEPTH_SRC)
src_buf1[XF_NPIXPERCYCLE(NPC) + 2],
src_buf2[XF_NPIXPERCYCLE(NPC) + 2], // Temporary buffers to hold input data for processing
src_buf3[XF_NPIXPERCYCLE(NPC) + 2];
// clang-format off
#pragma HLS ARRAY_PARTITION variable=src_buf1 complete dim=1
#pragma HLS ARRAY_PARTITION variable=src_buf2 complete dim=1
#pragma HLS ARRAY_PARTITION variable=src_buf3 complete dim=1
// clang-format on
XF_SNAME(WORDWIDTH_DST) P0, P1; // Output data is packed
// Line buffer to hold image data
XF_SNAME(WORDWIDTH_SRC) buf[3][(COLS >> XF_BITSHIFT(NPC))]; // Line buffer
// clang-format off
#pragma HLS RESOURCE variable=buf core=RAM_S2P_BRAM
#pragma HLS ARRAY_PARTITION variable=buf complete dim=1
// clang-format on
row_ind = 1;
Clear_Row_Loop:
for (col = 0; col < img_width; col++) // Top row border care
{
// clang-format off
#pragma HLS LOOP_TRIPCOUNT min=TC max=TC
#pragma HLS pipeline
// clang-format on
buf[0][col] = 0;
// buf[row_ind][col] = _src_mat.data[read_index++];
// // Read data
buf[row_ind][col] = _src_mat.read(read_index++); // Read data
}
row_ind++;
Row_Loop: // Process complete image
for (row = 1; row < img_height + 1; row++) {
// clang-format off
#pragma HLS LOOP_TRIPCOUNT min=ROWS max=ROWS
// clang-format on
if (row_ind == 2) // Indexes to hold maintain the row index
{
tp = 0;
mid = 1;
bottom = 2;
} else if (row_ind == 0) {
tp = 1;
mid = 2;
bottom = 0;
} else if (row_ind == 1) {
tp = 2;
mid = 0;
bottom = 1;
}
src_buf1[0] = src_buf1[1] = 0;
src_buf2[0] = src_buf2[1] = 0;
src_buf3[0] = src_buf3[1] = 0;
/*********** Process complete row
* **********/
P0 = P1 = 0;
ProcessScharr3x3<SRC_T, DST_T, ROWS, COLS, PLANES, DEPTH_SRC, DEPTH_DST, NPC, WORDWIDTH_SRC, WORDWIDTH_DST, TC>(
_src_mat, _gradx_mat, _grady_mat, buf, src_buf1, src_buf2, src_buf3, GradientValuesX, GradientValuesY, P0,
P1, img_width, img_height, row_ind, shift_x, shift_y, tp, mid, bottom, row, read_index, write_index);
/* Last column border care for 8-pixel Case
*/
if ((NPC == XF_NPPC8)) {
// Compute gradient at last column
int STEP, STEP_OUT, p = 0;
if ((DEPTH_DST == XF_48SP) || (DEPTH_DST == XF_16SP)) {
STEP_OUT = 16;
STEP = 8;
} else {
STEP_OUT = 8;
STEP = 8;
}
for (ap_uint<5> c = 0, k = 0; c < PLANES; c++, k += STEP) {
GradientValuesX[0].range(p + (STEP_OUT - 1), p) = xFGradientX<DEPTH_SRC, DEPTH_DST>(
src_buf1[buf_size - 2].range(k + STEP - 1, k), src_buf1[buf_size - 1].range(k + STEP - 1, k), 0,
src_buf2[buf_size - 2].range(k + STEP - 1, k), src_buf2[buf_size - 1].range(k + STEP - 1, k), 0,
src_buf3[buf_size - 2].range(k + STEP - 1, k), src_buf3[buf_size - 1].range(k + STEP - 1, k), 0);
GradientValuesY[0].range(p + (STEP_OUT - 1), p) = xFGradientY<DEPTH_SRC, DEPTH_DST>(
src_buf1[buf_size - 2].range(k + STEP - 1, k), src_buf1[buf_size - 1].range(k + STEP - 1, k), 0,
src_buf2[buf_size - 2].range(k + STEP - 1, k), src_buf2[buf_size - 1].range(k + STEP - 1, k), 0,
src_buf3[buf_size - 2].range(k + STEP - 1, k), src_buf3[buf_size - 1].range(k + STEP - 1, k), 0);
p += STEP_OUT;
}
} else /* Last column border care for NO Case
*/
{
int STEP, STEP_OUT, q = 0;
if ((DEPTH_DST == XF_48SP) || (DEPTH_DST == XF_16SP)) {
STEP_OUT = 16;
STEP = 8;
} else {
STEP_OUT = 8;
STEP = 8;
}
for (ap_uint<7> i = 0, k = 0; i < PLANES; i++, k += STEP) {
GradientValuesX[0].range(q + (STEP_OUT - 1), q) = xFGradientX<DEPTH_SRC, DEPTH_DST>(
src_buf1[buf_size - 3].range(k + STEP - 1, k), src_buf1[buf_size - 2].range(k + STEP - 1, k), 0,
src_buf2[buf_size - 3].range(k + STEP - 1, k), src_buf2[buf_size - 2].range(k + STEP - 1, k), 0,
src_buf3[buf_size - 3].range(k + STEP - 1, k), src_buf3[buf_size - 2].range(k + STEP - 1, k), 0);
GradientValuesY[0].range(q + (STEP_OUT - 1), q) = xFGradientY<DEPTH_SRC, DEPTH_DST>(
src_buf1[buf_size - 3].range(k + STEP - 1, k), src_buf1[buf_size - 2].range(k + STEP - 1, k), 0,
src_buf2[buf_size - 3].range(k + STEP - 1, k), src_buf2[buf_size - 2].range(k + STEP - 1, k), 0,
src_buf3[buf_size - 3].range(k + STEP - 1, k), src_buf3[buf_size - 2].range(k + STEP - 1, k), 0);
q += STEP_OUT;
}
}
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesX[0], P0, 0, 1, shift_x);
xfPackPixels<NPC, WORDWIDTH_DST, DEPTH_DST>(&GradientValuesY[0], P1, 0, 1, shift_y);
//_gradx_mat.data[write_index] = P0;
//_grady_mat.data[write_index++] = P1;
_gradx_mat.write(write_index, P0);
_grady_mat.write(write_index++, P1);
shift_x = 0;
shift_y = 0;
P0 = 0;
P1 = 0;
row_ind++;
if (row_ind == 3) {
row_ind = 0;
}
} // Row_Loop
}
template <int BORDER_TYPE, int SRC_T, int DST_T, int ROWS, int COLS, int NPC = 1>
void Scharr(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& _src_mat,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& _dst_matx,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& _dst_maty) {
// clang-format off
#pragma HLS INLINE OFF
// clang-format on
uint16_t img_height = _src_mat.rows;
uint16_t img_width = (_src_mat.cols >> XF_BITSHIFT(NPC));
#ifndef __SYNTHESIS__
assert(((NPC == XF_NPPC1) || (NPC == XF_NPPC8)) && "NPC must be XF_NPPC1 or XF_NPPC8");
assert((BORDER_TYPE == XF_BORDER_CONSTANT) && "Border type must be XF_BORDER_CONSTANT ");
assert(((img_height <= ROWS) && (_src_mat.cols <= COLS)) && "ROWS and COLS should be greater than input image");
#endif
xFScharrFilterKernel<SRC_T, DST_T, ROWS, COLS, XF_CHANNELS(SRC_T, NPC), XF_DEPTH(SRC_T, NPC), XF_DEPTH(DST_T, NPC),
NPC, XF_WORDWIDTH(SRC_T, NPC), XF_WORDWIDTH(DST_T, NPC), (COLS >> XF_BITSHIFT(NPC))>(
_src_mat, _dst_matx, _dst_maty, img_height, img_width);
}
} // namespace cv
} // namespace xf
#endif // _XF_SCHARR_HPP_
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkXdmf3Writer.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkXdmf3Writer.h"
#include "vtkDataObject.h"
#include "vtkDirectedGraph.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkObjectFactory.h"
#include "vtkPointSet.h"
#include "vtkRectilinearGrid.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStructuredGrid.h"
#include "vtkXdmf3DataSet.h"
#include "XdmfDomain.hpp"
#include "XdmfGridCollection.hpp"
#include "XdmfGridCollectionType.hpp"
#include "XdmfHeavyDataWriter.hpp"
#include "XdmfWriter.hpp"
#include <stack>
//=============================================================================
class vtkXdmf3Writer::Internals {
public:
Internals()
{
}
~Internals() {};
void Init(const char *filename)
{
this->Domain = XdmfDomain::New();
this->Writer = XdmfWriter::New(filename);
this->Writer->setLightDataLimit(0);
this->Writer->getHeavyDataWriter()->setReleaseData(true);
this->NumberOfTimeSteps = 1;
this->CurrentTimeIndex = 0;
this->DestinationGroups.push(this->Domain);
this->Destination = this->DestinationGroups.top();
}
void SwitchToTemporal()
{
shared_ptr<XdmfGridCollection> dest = XdmfGridCollection::New();
dest->setType(XdmfGridCollectionType::Temporal());
this->DestinationGroups.push(dest);
this->Destination = this->DestinationGroups.top();
this->Domain->insert(dest);
}
void WriteDataObject(vtkDataObject *dataSet, bool hasTime, double time,
const char* name = 0)
{
if (!dataSet)
{
return;
}
switch (dataSet->GetDataObjectType())
{
case VTK_MULTIBLOCK_DATA_SET:
{
shared_ptr<XdmfGridCollection> group = XdmfGridCollection::New();
this->Destination->insert(group);
this->DestinationGroups.push(group);
this->Destination = this->DestinationGroups.top();
vtkMultiBlockDataSet *mbds = vtkMultiBlockDataSet::SafeDownCast(dataSet);
for (unsigned int i = 0; i< mbds->GetNumberOfBlocks(); i++)
{
vtkDataObject *next = mbds->GetBlock(i);
const char* blockName = mbds->GetMetaData(i)->Get(vtkCompositeDataSet::NAME());
this->WriteDataObject(next, hasTime, time, blockName);
}
this->DestinationGroups.pop();
this->Destination = this->DestinationGroups.top();
break;
}
case VTK_STRUCTURED_POINTS:
case VTK_IMAGE_DATA:
case VTK_UNIFORM_GRID:
{
vtkXdmf3DataSet::VTKToXdmf(
vtkImageData::SafeDownCast(dataSet),
this->Destination.get(),
hasTime, time, name);
break;
}
case VTK_RECTILINEAR_GRID:
{
vtkXdmf3DataSet::VTKToXdmf(
vtkRectilinearGrid::SafeDownCast(dataSet),
this->Destination.get(),
hasTime, time, name);
break;
}
case VTK_STRUCTURED_GRID:
{
vtkXdmf3DataSet::VTKToXdmf(
vtkStructuredGrid::SafeDownCast(dataSet),
this->Destination.get(),
hasTime, time, name);
break;
}
case VTK_POLY_DATA:
case VTK_UNSTRUCTURED_GRID:
{
vtkXdmf3DataSet::VTKToXdmf(
vtkPointSet::SafeDownCast(dataSet),
this->Destination.get(),
hasTime, time, name);
break;
}
//case VTK_GRAPH:
case VTK_DIRECTED_GRAPH:
//case VTK_UNDIRECTED_GRAPH:
{
vtkXdmf3DataSet::VTKToXdmf(
vtkDirectedGraph::SafeDownCast(dataSet),
this->Destination.get(),
hasTime, time, name);
break;
}
default:
{
}
}
this->Domain->accept(this->Writer);
}
boost::shared_ptr<XdmfDomain> Domain;
boost::shared_ptr<XdmfDomain> Destination;
boost::shared_ptr<XdmfWriter> Writer;
std::stack<boost::shared_ptr<XdmfDomain> > DestinationGroups;
int NumberOfTimeSteps;
int CurrentTimeIndex;
};
//==============================================================================
vtkStandardNewMacro(vtkXdmf3Writer);
//----------------------------------------------------------------------------
vtkXdmf3Writer::vtkXdmf3Writer()
{
this->FileName = NULL;
this->LightDataLimit = 100;
this->WriteAllTimeSteps = false;
this->Internal = new Internals();
this->SetNumberOfOutputPorts(0);
}
//----------------------------------------------------------------------------
vtkXdmf3Writer::~vtkXdmf3Writer()
{
this->SetFileName(NULL);
}
//----------------------------------------------------------------------------
void vtkXdmf3Writer::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "FileName: " <<
(this->FileName ? this->FileName : "(none)") << endl;
os << indent << "LightDataLimit: " <<
this->LightDataLimit << endl;
os << indent << "WriteAllTimeSteps: " <<
(this->WriteAllTimeSteps?"ON":"OFF") << endl;
}
//------------------------------------------------------------------------------
void vtkXdmf3Writer::SetInputData(vtkDataObject *input)
{
this->SetInputDataInternal(0,input);
}
//------------------------------------------------------------------------------
int vtkXdmf3Writer::Write()
{
// Make sure we have input.
if (this->GetNumberOfInputConnections(0) < 1)
{
vtkErrorMacro("No input provided!");
return 0;
}
// always write even if the data hasn't changed
this->Modified();
if (!this->Internal)
{
this->Internal = new Internals();
}
this->Internal->Init(this->FileName);
this->Update();
//this->Internal->Domain->accept(this->Internal->Writer);
delete this->Internal;
this->Internal = NULL;
return 1;
}
//----------------------------------------------------------------------------
int vtkXdmf3Writer::RequestInformation(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector,
vtkInformationVector* vtkNotUsed(outputVector))
{
// Does the input have timesteps?
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
if ( inInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS()) )
{
this->Internal->NumberOfTimeSteps =
inInfo->Length( vtkStreamingDemandDrivenPipeline::TIME_STEPS() );
}
else
{
this->Internal->NumberOfTimeSteps = 1;
}
//cerr << "WRITER NUM TS = " << this->Internal->NumberOfTimeSteps << endl;
return 1;
}
//----------------------------------------------------------------------------
int vtkXdmf3Writer::RequestUpdateExtent(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector,
vtkInformationVector* vtkNotUsed(outputVector))
{
double *inTimes = inputVector[0]->GetInformationObject(0)->Get(
vtkStreamingDemandDrivenPipeline::TIME_STEPS());
if (inTimes && this->WriteAllTimeSteps)
{
//TODO:? Add a user ivar to specify a particular time,
//which is different from current time. Can do it by updating
//to a particular time then writing without writealltimesteps,
//but that is annoying.
double timeReq = inTimes[this->Internal->CurrentTimeIndex];
inputVector[0]->GetInformationObject(0)->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(),
timeReq);
}
return 1;
}
//----------------------------------------------------------------------------
int vtkXdmf3Writer::RequestData(
vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* vtkNotUsed(outputVector))
{
if (!this->Internal->Domain)
{
//call Write() instead of RD() directly. Write() does setup first before it calls RD().
return 1;
}
this->Internal->Writer->setLightDataLimit(this->LightDataLimit);
if (this->Internal->CurrentTimeIndex == 0 &&
this->WriteAllTimeSteps &&
this->Internal->NumberOfTimeSteps > 1)
{
// Tell the pipeline to start looping.
this->Internal->SwitchToTemporal();
request->Set(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING(), 1);
}
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
vtkDataObject* input = inInfo->Get(vtkDataObject::DATA_OBJECT());
vtkInformation *inDataInfo = input->GetInformation();
double dataT = 0;
bool hasTime = false;
if (inDataInfo->Has(vtkDataObject::DATA_TIME_STEP()))
{
dataT = input->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP());
hasTime = true;
}
this->Internal->WriteDataObject(input, hasTime, dataT);
this->Internal->CurrentTimeIndex++;
if (this->Internal->CurrentTimeIndex >= this->Internal->NumberOfTimeSteps &&
this->WriteAllTimeSteps)
{
// Tell the pipeline to stop looping.
request->Remove(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING());
this->Internal->CurrentTimeIndex = 0;
}
return 1;
}
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdvecmult/M2x2bVDa.cpp
// \brief Source file for the M2x2bVDa dense matrix/dense vector multiplication math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'M2x2bVDa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::StaticMatrix<TypeB,2UL,2UL> M2x2b;
typedef blaze::DynamicVector<TypeA> VDa;
// Creator type definitions
typedef blazetest::Creator<M2x2b> CM2x2b;
typedef blazetest::Creator<VDa> CVDa;
// Running the tests
RUN_DMATDVECMULT_OPERATION_TEST( CM2x2b(), CVDa( 2UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense vector multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/*******************************************************************************
* Copyright 2019-2021 Intel Corporation
*
* 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 "gpu/gpu_impl_list.hpp"
#include "gpu/jit/gemm/gen_gemm.hpp"
#include "gpu/ocl/convolution_inner_product.hpp"
#include "gpu/ocl/gemm/gen9_gemm.hpp"
#include "gpu/ocl/gemm/gen9_gemm_x8x8s32.hpp"
#include "gpu/ocl/gemm/ref_gemm.hpp"
#include "gpu/ocl/gemm/xe_lp_gemm.hpp"
#include "gpu/ocl/gemm_inner_product.hpp"
#include "gpu/ocl/gemm_matmul.hpp"
#include "gpu/ocl/gemm_post_ops_inner_product.hpp"
#include "gpu/ocl/gen9_batch_normalization.hpp"
#include "gpu/ocl/gen9_binary.hpp"
#include "gpu/ocl/gen9_convolution.hpp"
#include "gpu/ocl/gen9_eltwise.hpp"
#include "gpu/ocl/gen9_pooling.hpp"
#include "gpu/ocl/gen9_reduction.hpp"
#include "gpu/ocl/gen9_softmax.hpp"
#include "gpu/ocl/gen9_wino_convolution.hpp"
#include "gpu/ocl/ref_batch_normalization.hpp"
#include "gpu/ocl/ref_binary.hpp"
#include "gpu/ocl/ref_convolution.hpp"
#include "gpu/ocl/ref_deconvolution.hpp"
#include "gpu/ocl/ref_eltwise.hpp"
#include "gpu/ocl/ref_inner_product.hpp"
#include "gpu/ocl/ref_layer_normalization.hpp"
#include "gpu/ocl/ref_lrn.hpp"
#include "gpu/ocl/ref_matmul.hpp"
#include "gpu/ocl/ref_pooling.hpp"
#include "gpu/ocl/ref_prelu.hpp"
#include "gpu/ocl/ref_reduction.hpp"
#include "gpu/ocl/ref_resampling.hpp"
#include "gpu/ocl/ref_shuffle.hpp"
#include "gpu/ocl/ref_softmax.hpp"
#include "gpu/ocl/ref_zero_pad.hpp"
#include "gpu/ocl/rnn/ref_rnn.hpp"
#include "gpu/ocl/shuffle_by_reorder.hpp"
#include "gpu/ocl/xe_lp_x8s8x_1x1_convolution.hpp"
#include "gpu/ocl/xe_lp_x8s8x_convolution.hpp"
namespace dnnl {
namespace impl {
namespace gpu {
using pd_create_f = dnnl::impl::engine_t::primitive_desc_create_f;
namespace {
#define INSTANCE(...) &primitive_desc_t::create<__VA_ARGS__::pd_t>
const pd_create_f gpu_impl_list[] = {
// Elementwise
INSTANCE(ocl::gen9_eltwise_fwd_t),
INSTANCE(ocl::gen9_eltwise_bwd_t),
INSTANCE(ocl::ref_eltwise_fwd_t),
INSTANCE(ocl::ref_eltwise_bwd_t),
// Deconvolution
INSTANCE(ocl::ref_deconvolution_fwd_t),
INSTANCE(ocl::ref_deconvolution_bwd_data_t),
INSTANCE(ocl::ref_deconvolution_bwd_weights_t),
// Convolution
INSTANCE(ocl::xe_lp_x8s8x_1x1_convolution_fwd_t),
INSTANCE(ocl::xe_lp_x8s8x_convolution_fwd_t),
INSTANCE(ocl::xe_lp_x8s8x_convolution_bwd_data_t),
INSTANCE(ocl::gen9_wino_convolution_fwd_t),
INSTANCE(ocl::gen9_convolution_fwd_t),
INSTANCE(ocl::gen9_convolution_bwd_data_t),
INSTANCE(ocl::gen9_convolution_bwd_weights_t),
INSTANCE(ocl::ref_convolution_fwd_t),
INSTANCE(ocl::ref_convolution_bwd_data_t),
INSTANCE(ocl::ref_convolution_bwd_weights_t),
// Batch Normalization
INSTANCE(ocl::gen9_batch_normalization_fwd_t),
INSTANCE(ocl::gen9_batch_normalization_bwd_t),
INSTANCE(ocl::ref_batch_normalization_fwd_t),
INSTANCE(ocl::ref_batch_normalization_bwd_t),
// Pooling
INSTANCE(ocl::gen9_pooling_fwd_t),
INSTANCE(ocl::gen9_pooling_bwd_t),
INSTANCE(ocl::ref_pooling_fwd_t),
INSTANCE(ocl::ref_pooling_bwd_t),
// Prelu
INSTANCE(ocl::ref_prelu_fwd_t),
INSTANCE(ocl::ref_prelu_bwd_t),
// LRN
INSTANCE(ocl::ref_lrn_fwd_t),
INSTANCE(ocl::ref_lrn_bwd_t),
// Inner Product
INSTANCE(ocl::gemm_inner_product_fwd_t),
INSTANCE(ocl::gemm_post_ops_inner_product_fwd_t),
INSTANCE(ocl::convolution_inner_product_fwd_t),
INSTANCE(ocl::gemm_inner_product_bwd_data_t),
INSTANCE(ocl::gemm_inner_product_bwd_weights_t),
INSTANCE(ocl::ref_inner_product_fwd_t),
INSTANCE(ocl::ref_inner_product_bwd_data_t),
INSTANCE(ocl::ref_inner_product_bwd_weights_t),
// Softmax
INSTANCE(ocl::gen9_softmax_fwd_t),
INSTANCE(ocl::ref_softmax_fwd_t),
INSTANCE(ocl::ref_softmax_bwd_t),
// GEMM (internal)
INSTANCE(jit::gen_gemm_t),
INSTANCE(ocl::xe_lp_gemm_t),
INSTANCE(ocl::gen9_gemm_x8x8s32_t),
INSTANCE(ocl::gen9_gemm_t),
INSTANCE(ocl::ref_gemm_t),
// RNN
INSTANCE(ocl::ref_rnn_fwd_t),
INSTANCE(ocl::ref_rnn_bwd_t),
// Shuffle
INSTANCE(ocl::shuffle_by_reorder_t),
INSTANCE(ocl::ref_shuffle_t),
// Layer Normalization
INSTANCE(ocl::ref_layer_normalization_fwd_t),
INSTANCE(ocl::ref_layer_normalization_bwd_t),
// Binary
INSTANCE(ocl::gen9_binary_t),
INSTANCE(ocl::ref_binary_t),
// MatMul
INSTANCE(ocl::gemm_matmul_t),
INSTANCE(ocl::ref_matmul_t),
// Reduction
INSTANCE(ocl::gen9_reduction_t),
INSTANCE(ocl::ref_reduction_t),
// Resampling
INSTANCE(ocl::ref_resampling_fwd_t),
INSTANCE(ocl::ref_resampling_bwd_t),
// Zero Pad
INSTANCE(ocl::ref_zero_pad_t),
nullptr,
};
#undef INSTANCE
} // namespace
const pd_create_f *gpu_impl_list_t::get_implementation_list() {
return gpu_impl_list;
}
} // namespace gpu
} // namespace impl
} // namespace dnnl
|
/*
* MultipleSegmentBase.cpp
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: libdash-dev@vicky.bitmovin.net
*
* @contributor Daniele Lorenzi
* @contributoremail lorenzidaniele.97@gmail.com
* @contributiondate 2021
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#include "MultipleSegmentBase.h"
using namespace dash::mpd;
MultipleSegmentBase::MultipleSegmentBase () :
bitstreamSwitching(NULL),
segmentTimeline(NULL),
duration(0),
startNumber(1),
endNumber(1)
{
}
MultipleSegmentBase::~MultipleSegmentBase ()
{
delete(this->segmentTimeline);
delete(this->bitstreamSwitching);
}
const ISegmentTimeline * MultipleSegmentBase::GetSegmentTimeline () const
{
return (ISegmentTimeline *) this->segmentTimeline;
}
void MultipleSegmentBase::SetSegmentTimeline (SegmentTimeline *segmentTimeline)
{
this->segmentTimeline = segmentTimeline;
}
const IURLType* MultipleSegmentBase::GetBitstreamSwitching () const
{
return this->bitstreamSwitching;
}
void MultipleSegmentBase::SetBitstreamSwitching (URLType *bitstreamSwitching)
{
this->bitstreamSwitching = bitstreamSwitching;
}
uint32_t MultipleSegmentBase::GetDuration () const
{
return this->duration;
}
void MultipleSegmentBase::SetDuration (uint32_t duration)
{
this->duration = duration;
}
uint32_t MultipleSegmentBase::GetStartNumber () const
{
return this->startNumber;
}
void MultipleSegmentBase::SetStartNumber (uint32_t startNumber)
{
this->startNumber = startNumber;
}
uint32_t MultipleSegmentBase::GetEndNumber () const
{
return this->endNumber;
}
void MultipleSegmentBase::SetEndNumber (uint32_t endNumber)
{
this->endNumber = endNumber;
}
|
#include "MailBox.h"
#if defined(_WIN32)
#include "win32/Win32Defs.h"
#endif
bool CMailBox::IsPending() const
{
return m_calls.size() != 0;
}
void CMailBox::WaitForCall()
{
std::unique_lock<std::mutex> callLock(m_callMutex);
while(!IsPending())
{
m_waitCondition.wait(callLock);
}
}
void CMailBox::WaitForCall(unsigned int timeOut)
{
std::unique_lock<std::mutex> callLock(m_callMutex);
if(IsPending()) return;
m_waitCondition.wait_for(callLock, std::chrono::milliseconds(timeOut));
}
void CMailBox::FlushCalls()
{
SendCall([]() {}, true);
}
void CMailBox::SendCall(const FunctionType& function, bool waitForCompletion)
{
std::unique_lock<std::mutex> callLock(m_callMutex);
{
MESSAGE message;
message.function = function;
message.sync = waitForCompletion;
m_calls.push_back(std::move(message));
}
m_waitCondition.notify_all();
if(waitForCompletion)
{
m_callDone = false;
while(!m_callDone)
{
#ifdef FRAMEWORK_WIN_DESKTOP
MSG wmmsg;
while(PeekMessage(&wmmsg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&wmmsg);
DispatchMessage(&wmmsg);
}
m_callFinished.wait_for(callLock, std::chrono::milliseconds(100));
#else
m_callFinished.wait(callLock);
#endif
}
}
}
void CMailBox::SendCall(FunctionType&& function)
{
std::lock_guard<std::mutex> callLock(m_callMutex);
{
MESSAGE message;
message.function = std::move(function);
message.sync = false;
m_calls.push_back(std::move(message));
}
m_waitCondition.notify_all();
}
void CMailBox::ReceiveCall()
{
MESSAGE message;
{
std::lock_guard<std::mutex> waitLock(m_callMutex);
if(!IsPending()) return;
message = std::move(m_calls.front());
m_calls.pop_front();
}
message.function();
if(message.sync)
{
std::lock_guard<std::mutex> waitLock(m_callMutex);
m_callDone = true;
m_callFinished.notify_all();
}
}
|
// Copyright (c) 2021 PaddlePaddle Authors. 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.
// 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 "lite/operators/write_back_op.h"
#include "lite/core/op_registry.h"
namespace paddle {
namespace lite {
namespace operators {
bool WriteBackOp::CheckShape() const {
CHECK(param_.x);
CHECK(param_.y);
return true;
}
bool WriteBackOp::InferShapeImpl() const {
param_.y->Resize(param_.x->dims());
param_.y->set_lod(param_.x->lod());
param_.y->set_precision(param_.x->precision());
param_.y->set_persistable(param_.x->persistable());
return true;
}
bool WriteBackOp::AttachImpl(const cpp::OpDesc &opdesc, lite::Scope *scope) {
param_.x = scope->FindTensor(opdesc.Input("Src_LoDTensor").front());
param_.y = scope->FindMutableTensor(opdesc.Input("Dst_LoDTensor").front());
return true;
}
} // namespace operators
} // namespace lite
} // namespace paddle
REGISTER_LITE_OP(write_back, paddle::lite::operators::WriteBackOp);
|
// Copyright (c) 2009-2012 The Dreamcoinclub developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/rand.h>
#include <openssl/obj_mac.h>
#include "key.h"
// anonymous namespace with local implementation code (OpenSSL interaction)
namespace {
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
{
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if (!eckey) return 0;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is non-zero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
// RAII Wrapper around OpenSSL's EC_KEY
class CECKey {
private:
EC_KEY *pkey;
public:
CECKey() {
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
assert(pkey != NULL);
}
~CECKey() {
EC_KEY_free(pkey);
}
void GetSecretBytes(unsigned char vch[32]) const {
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
assert(bn);
int nBytes = BN_num_bytes(bn);
int n=BN_bn2bin(bn,&vch[32 - nBytes]);
assert(n == nBytes);
memset(vch, 0, 32 - nBytes);
}
void SetSecretBytes(const unsigned char vch[32]) {
BIGNUM bn;
BN_init(&bn);
assert(BN_bin2bn(vch, 32, &bn));
assert(EC_KEY_regenerate_key(pkey, &bn));
BN_clear_free(&bn);
}
void GetPrivKey(CPrivKey &privkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2d_ECPrivateKey(pkey, NULL);
assert(nSize);
privkey.resize(nSize);
unsigned char* pbegin = &privkey[0];
int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);
assert(nSize == nSize2);
}
bool SetPrivKey(const CPrivKey &privkey) {
const unsigned char* pbegin = &privkey[0];
if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {
// d2i_ECPrivateKey returns true if parsing succeeds.
// This doesn't necessarily mean the key is valid.
if (EC_KEY_check_key(pkey))
return true;
}
return false;
}
void GetPubKey(CPubKey &pubkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2o_ECPublicKey(pkey, NULL);
assert(nSize);
assert(nSize <= 65);
unsigned char c[65];
unsigned char *pbegin = c;
int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
assert(nSize == nSize2);
pubkey.Set(&c[0], &c[nSize]);
}
bool SetPubKey(const CPubKey &pubkey) {
const unsigned char* pbegin = pubkey.begin();
return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());
}
bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) {
vchSig.clear();
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig == NULL)
return false;
if (BN_is_odd(sig->s)) {
// enforce even S values, by negating the value (modulo the order) if odd
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
const EC_GROUP *group = EC_KEY_get0_group(pkey);
BIGNUM *order = BN_CTX_get(ctx);
EC_GROUP_get_order(group, order, ctx);
BN_sub(sig->s, order, sig->s);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
unsigned char *pos = &vchSig[0];
nSize = i2d_ECDSA_SIG(sig, &pos);
ECDSA_SIG_free(sig);
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}
bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
// -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return false;
return true;
}
bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) {
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig==NULL)
return false;
memset(p64, 0, 64);
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
if (nBitsR <= 256 && nBitsS <= 256) {
CPubKey pubkey;
GetPubKey(pubkey, true);
for (int i=0; i<4; i++) {
CECKey keyRec;
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {
CPubKey pubkeyRec;
keyRec.GetPubKey(pubkeyRec, true);
if (pubkeyRec == pubkey) {
rec = i;
fOk = true;
break;
}
}
}
assert(fOk);
BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
}
ECDSA_SIG_free(sig);
return fOk;
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool Recover(const uint256 &hash, const unsigned char *p64, int rec)
{
if (rec<0 || rec>=3)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&p64[0], 32, sig->r);
BN_bin2bn(&p64[32], 32, sig->s);
bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
ECDSA_SIG_free(sig);
return ret;
}
static bool TweakSecret(unsigned char vchSecretOut[32], const unsigned char vchSecretIn[32], const unsigned char vchTweak[32])
{
bool ret = true;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM *bnSecret = BN_CTX_get(ctx);
BIGNUM *bnTweak = BN_CTX_get(ctx);
BIGNUM *bnOrder = BN_CTX_get(ctx);
EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1);
EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
BN_bin2bn(vchTweak, 32, bnTweak);
if (BN_cmp(bnTweak, bnOrder) >= 0)
ret = false; // extremely unlikely
BN_bin2bn(vchSecretIn, 32, bnSecret);
BN_add(bnSecret, bnSecret, bnTweak);
BN_nnmod(bnSecret, bnSecret, bnOrder, ctx);
if (BN_is_zero(bnSecret))
ret = false; // ridiculously unlikely
int nBits = BN_num_bits(bnSecret);
memset(vchSecretOut, 0, 32);
BN_bn2bin(bnSecret, &vchSecretOut[32-(nBits+7)/8]);
EC_GROUP_free(group);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ret;
}
bool TweakPublic(const unsigned char vchTweak[32]) {
bool ret = true;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM *bnTweak = BN_CTX_get(ctx);
BIGNUM *bnOrder = BN_CTX_get(ctx);
BIGNUM *bnOne = BN_CTX_get(ctx);
const EC_GROUP *group = EC_KEY_get0_group(pkey);
EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
BN_bin2bn(vchTweak, 32, bnTweak);
if (BN_cmp(bnTweak, bnOrder) >= 0)
ret = false; // extremely unlikely
EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
BN_one(bnOne);
EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
if (EC_POINT_is_at_infinity(group, point))
ret = false; // ridiculously unlikely
EC_KEY_set_public_key(pkey, point);
EC_POINT_free(point);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ret;
}
};
}; // end of anonymous namespace
bool CKey::Check(const unsigned char *vch) {
// Do not convert to OpenSSL's data structures for range-checking keys,
// it's easy enough to do directly.
static const unsigned char vchMax[32] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
};
bool fIsZero = true;
for (int i=0; i<32 && fIsZero; i++)
if (vch[i] != 0)
fIsZero = false;
if (fIsZero)
return false;
for (int i=0; i<32; i++) {
if (vch[i] < vchMax[i])
return true;
if (vch[i] > vchMax[i])
return false;
}
return true;
}
void CKey::MakeNewKey(bool fCompressedIn) {
do {
RAND_bytes(vch, sizeof(vch));
} while (!Check(vch));
fValid = true;
fCompressed = fCompressedIn;
}
bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
CECKey key;
if (!key.SetPrivKey(privkey))
return false;
key.GetSecretBytes(vch);
fCompressed = fCompressedIn;
fValid = true;
return true;
}
CPrivKey CKey::GetPrivKey() const {
assert(fValid);
CECKey key;
key.SetSecretBytes(vch);
CPrivKey privkey;
key.GetPrivKey(privkey, fCompressed);
return privkey;
}
CPubKey CKey::GetPubKey() const {
assert(fValid);
CECKey key;
key.SetSecretBytes(vch);
CPubKey pubkey;
key.GetPubKey(pubkey, fCompressed);
return pubkey;
}
bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
if (!fValid)
return false;
CECKey key;
key.SetSecretBytes(vch);
return key.Sign(hash, vchSig);
}
bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
if (!fValid)
return false;
CECKey key;
key.SetSecretBytes(vch);
vchSig.resize(65);
int rec = -1;
if (!key.SignCompact(hash, &vchSig[1], rec))
return false;
assert(rec != -1);
vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
return true;
}
bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
if (!key.Verify(hash, vchSig))
return false;
return true;
}
bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
if (vchSig.size() != 65)
return false;
CECKey key;
if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
return false;
key.GetPubKey(*this, (vchSig[0] - 27) & 4);
return true;
}
bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
if (vchSig.size() != 65)
return false;
CECKey key;
if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
return false;
CPubKey pubkeyRec;
key.GetPubKey(pubkeyRec, IsCompressed());
if (*this != pubkeyRec)
return false;
return true;
}
bool CPubKey::IsFullyValid() const {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
return true;
}
bool CPubKey::Decompress() {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
key.GetPubKey(*this, false);
return true;
}
void static BIP32Hash(const unsigned char chainCode[32], unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]) {
unsigned char num[4];
num[0] = (nChild >> 24) & 0xFF;
num[1] = (nChild >> 16) & 0xFF;
num[2] = (nChild >> 8) & 0xFF;
num[3] = (nChild >> 0) & 0xFF;
HMAC_SHA512_CTX ctx;
HMAC_SHA512_Init(&ctx, chainCode, 32);
HMAC_SHA512_Update(&ctx, &header, 1);
HMAC_SHA512_Update(&ctx, data, 32);
HMAC_SHA512_Update(&ctx, num, 4);
HMAC_SHA512_Final(output, &ctx);
}
bool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
assert(IsValid());
assert(IsCompressed());
unsigned char out[64];
LockObject(out);
if ((nChild >> 31) == 0) {
CPubKey pubkey = GetPubKey();
assert(pubkey.begin() + 33 == pubkey.end());
BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);
} else {
assert(begin() + 32 == end());
BIP32Hash(cc, nChild, 0, begin(), out);
}
memcpy(ccChild, out+32, 32);
bool ret = CECKey::TweakSecret((unsigned char*)keyChild.begin(), begin(), out);
UnlockObject(out);
keyChild.fCompressed = true;
keyChild.fValid = ret;
return ret;
}
bool CPubKey::Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
assert(IsValid());
assert((nChild >> 31) == 0);
assert(begin() + 33 == end());
unsigned char out[64];
BIP32Hash(cc, nChild, *begin(), begin()+1, out);
memcpy(ccChild, out+32, 32);
CECKey key;
bool ret = key.SetPubKey(*this);
ret &= key.TweakPublic(out);
key.GetPubKey(pubkeyChild, true);
return ret;
}
bool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = key.GetPubKey().GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = nChild;
return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);
}
void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
static const char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
HMAC_SHA512_CTX ctx;
HMAC_SHA512_Init(&ctx, hashkey, sizeof(hashkey));
HMAC_SHA512_Update(&ctx, seed, nSeedLen);
unsigned char out[64];
LockObject(out);
HMAC_SHA512_Final(out, &ctx);
key.Set(&out[0], &out[32], true);
memcpy(vchChainCode, &out[32], 32);
UnlockObject(out);
nDepth = 0;
nChild = 0;
memset(vchFingerprint, 0, sizeof(vchFingerprint));
}
CExtPubKey CExtKey::Neuter() const {
CExtPubKey ret;
ret.nDepth = nDepth;
memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
ret.nChild = nChild;
ret.pubkey = key.GetPubKey();
memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);
return ret;
}
void CExtKey::Encode(unsigned char code[74]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
memcpy(code+9, vchChainCode, 32);
code[41] = 0;
assert(key.size() == 32);
memcpy(code+42, key.begin(), 32);
}
void CExtKey::Decode(const unsigned char code[74]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(vchChainCode, code+9, 32);
key.Set(code+42, code+74, true);
}
void CExtPubKey::Encode(unsigned char code[74]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
memcpy(code+9, vchChainCode, 32);
assert(pubkey.size() == 33);
memcpy(code+41, pubkey.begin(), 33);
}
void CExtPubKey::Decode(const unsigned char code[74]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(vchChainCode, code+9, 32);
pubkey.Set(code+41, code+74);
}
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = pubkey.GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = nChild;
return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode);
}
|
#include <string>
#include <vector>
#include <cstdlib>
#include <CL/sycl.hpp>
#include "common.h"
#include "polybenchUtilFuncts.h"
using DATA_TYPE = float;
class Mvt1;
class Mvt2;
void init_arrays(DATA_TYPE* a, DATA_TYPE* x1, DATA_TYPE* x2, DATA_TYPE* y_1, DATA_TYPE* y_2, size_t size) {
const auto N = size;
for(size_t i = 0; i < N; i++) {
x1[i] = 0.0;
x2[i] = 0.0;
y_1[i] = 0.0;
y_2[i] = 0.0;
for(size_t j = 0; j < N; j++) {
a[i * N + j] = (DATA_TYPE)(i + j + 1.0) / N;
}
}
}
void runMvt(DATA_TYPE* a, DATA_TYPE* x1, DATA_TYPE* x2, DATA_TYPE* y1, DATA_TYPE* y2, size_t size) {
const auto N = size;
for(size_t i = 0; i < N; i++) {
for(size_t j = 0; j < N; j++) {
x1[i] = x1[i] + a[i * N + j] * y1[j];
}
}
for(size_t k = 0; k < N; k++) {
for(size_t l = 0; l < N; l++) {
x2[k] = x2[k] + a[k * N + l] * y2[l];
}
}
}
class Polybench_Mvt {
public:
Polybench_Mvt(const BenchmarkArgs& args) : args(args), size(args.problem_size) {}
void setup() {
a.resize(size * size);
x1.resize(size);
x2.resize(size);
y1.resize(size);
y2.resize(size);
init_arrays(a.data(), x1.data(), x2.data(), y1.data(), y2.data(), size);
a_buffer .initialize(args.device_queue, a.data(), cl::sycl::range<2>(size, size));
x1_buffer.initialize(args.device_queue, x1.data(), cl::sycl::range<1>(size));
x2_buffer.initialize(args.device_queue, x2.data(), cl::sycl::range<1>(size));
y1_buffer.initialize(args.device_queue, y1.data(), cl::sycl::range<1>(size));
y2_buffer.initialize(args.device_queue, y2.data(), cl::sycl::range<1>(size));
}
void run(std::vector<cl::sycl::event>& events) {
using namespace cl::sycl;
events.push_back(args.device_queue.submit([&](handler& cgh) {
auto a = a_buffer.get_access<access::mode::read>(cgh);
auto y1 = y1_buffer.get_access<access::mode::read>(cgh);
auto x1 = x1_buffer.get_access<access::mode::read_write>(cgh);
cgh.parallel_for<Mvt1>(x1_buffer.get_range(), [=, N_ = size](item<1> item) {
const auto i = item[0];
for(size_t j = 0; j < N_; j++) {
x1[i] += a[{i, j}] * y1[j];
}
});
}));
events.push_back(args.device_queue.submit([&](handler& cgh) {
auto a = a_buffer.get_access<access::mode::read>(cgh);
auto y2 = y2_buffer.get_access<access::mode::read>(cgh);
auto x2 = x2_buffer.get_access<access::mode::read_write>(cgh);
cgh.parallel_for<Mvt2>(x1_buffer.get_range(), [=, N_ = size](item<1> item) {
const auto k = item[0];
for(size_t l = 0; l < N_; l++) {
x2[k] += a[{k, l}] * y2[l];
}
});
}));
}
bool verify(VerificationSetting&) {
constexpr auto ERROR_THRESHOLD = 0.05;
std::vector<DATA_TYPE> x1_cpu(size);
std::vector<DATA_TYPE> x2_cpu(size);
init_arrays(a.data(), x1_cpu.data(), x2_cpu.data(), y1.data(), y2.data(), size);
runMvt(a.data(), x1_cpu.data(), x2_cpu.data(), y1.data(), y2.data(), size);
for(size_t i = 0; i < size; i++) {
auto diff = percentDiff(x1_cpu[i], x1[i]);
if(diff > ERROR_THRESHOLD) return false;
diff = percentDiff(x2_cpu[i], x2[i]);
if(diff > ERROR_THRESHOLD) return false;
}
return true;
}
static std::string getBenchmarkName() { return "Polybench_Mvt"; }
private:
BenchmarkArgs args;
const size_t size;
std::vector<DATA_TYPE> a;
std::vector<DATA_TYPE> x1;
std::vector<DATA_TYPE> x2;
std::vector<DATA_TYPE> y1;
std::vector<DATA_TYPE> y2;
PrefetchedBuffer<DATA_TYPE, 2> a_buffer;
PrefetchedBuffer<DATA_TYPE, 1> x1_buffer;
PrefetchedBuffer<DATA_TYPE, 1> x2_buffer;
PrefetchedBuffer<DATA_TYPE, 1> y1_buffer;
PrefetchedBuffer<DATA_TYPE, 1> y2_buffer;
};
int main(int argc, char** argv) {
BenchmarkApp app(argc, argv);
app.run<Polybench_Mvt>();
return 0;
}
|
/* Copyright 2017 The TensorFlow Authors. 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.
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 "tensorflow/lite/delegates/nnapi/nnapi_delegate.h"
#include <algorithm>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "tensorflow/lite/c/c_api_types.h"
#include "tensorflow/lite/delegates/serialization.h"
#include "tensorflow/lite/nnapi/NeuralNetworksTypes.h"
#include "tensorflow/lite/nnapi/sl/public/NeuralNetworksSupportLibraryImpl.h"
#ifdef __ANDROID__
#include <sys/system_properties.h>
#endif
#if defined __ANDROID__ || defined __unix__
#define TFLITE_NNAPI_ALLOW_MMAP_SHARING
#include <sys/mman.h>
#include <unistd.h>
#endif
#include "fp16.h" // from @FP16
#include "tensorflow/lite/allocation.h"
#include "tensorflow/lite/builtin_op_data.h"
#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/context_util.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate_kernel.h"
#include "tensorflow/lite/delegates/nnapi/quant_lstm_sup.h"
#include "tensorflow/lite/delegates/utils.h"
#include "tensorflow/lite/kernels/internal/utils/sparsity_format_converter.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/minimal_logging.h"
#include "tensorflow/lite/nnapi/nnapi_implementation.h"
#include "tensorflow/lite/nnapi/nnapi_util.h"
#include "tensorflow/lite/util.h"
#ifdef NNAPI_VERBOSE_VALIDATION
#include "tensorflow/lite/schema/schema_generated.h"
#endif
#include <farmhash.h>
namespace tflite {
namespace {
static const char kNnapiId[] = "nnapi_";
constexpr uint64_t kNoMemoryTimestamp = 0;
// Returns a string ID unique to what accelerator is run by NNAPI, based on
// user params. Assumes that the default accelerator is same across runs.
// Used for caching nodes to be delegated for a model.
std::string NnApiBackendId(
const StatefulNnApiDelegate::Options& delegate_options) {
std::string delegate_id = kNnapiId;
if (delegate_options.accelerator_name) {
delegate_id += delegate_options.accelerator_name;
}
return delegate_id;
}
// Returns the enum name corresponding to the given error code if the given
// value corresponds to an of the error codes in the enumeration above or
// an message with the unknown code.
// LINT.IfChange(NnApiErrorDescription)
std::string NnApiErrorDescription(int error_code) {
switch (error_code) {
case ANEURALNETWORKS_NO_ERROR:
return "ANEURALNETWORKS_NO_ERROR";
case ANEURALNETWORKS_OUT_OF_MEMORY:
return "ANEURALNETWORKS_OUT_OF_MEMORY";
case ANEURALNETWORKS_INCOMPLETE:
return "ANEURALNETWORKS_INCOMPLETE";
case ANEURALNETWORKS_UNEXPECTED_NULL:
return "ANEURALNETWORKS_UNEXPECTED_NULL";
case ANEURALNETWORKS_BAD_DATA:
return "ANEURALNETWORKS_BAD_DATA";
case ANEURALNETWORKS_OP_FAILED:
return "ANEURALNETWORKS_OP_FAILED";
case ANEURALNETWORKS_BAD_STATE:
return "ANEURALNETWORKS_BAD_STATE";
case ANEURALNETWORKS_UNMAPPABLE:
return "ANEURALNETWORKS_UNMAPPABLE";
case ANEURALNETWORKS_OUTPUT_INSUFFICIENT_SIZE:
return "ANEURALNETWORKS_OUTPUT_INSUFFICIENT_SIZE";
case ANEURALNETWORKS_UNAVAILABLE_DEVICE:
return "ANEURALNETWORKS_UNAVAILABLE_DEVICE";
case ANEURALNETWORKS_MISSED_DEADLINE_TRANSIENT:
return "ANEURALNETWORKS_MISSED_DEADLINE_TRANSIENT";
case ANEURALNETWORKS_MISSED_DEADLINE_PERSISTENT:
return "ANEURALNETWORKS_MISSED_DEADLINE_PERSISTENT";
case ANEURALNETWORKS_RESOURCE_EXHAUSTED_TRANSIENT:
return "ANEURALNETWORKS_RESOURCE_EXHAUSTED_TRANSIENT";
case ANEURALNETWORKS_RESOURCE_EXHAUSTED_PERSISTENT:
return "ANEURALNETWORKS_RESOURCE_EXHAUSTED_PERSISTENT";
case ANEURALNETWORKS_DEAD_OBJECT:
return "ANEURALNETWORKS_DEAD_OBJECT";
default:
return "Unknown NNAPI error code: " + std::to_string(error_code);
}
}
// LINT.ThenChange()
#define RETURN_TFLITE_ERROR_IF_NN_ERROR(context, code, call_desc, p_errno) \
do { \
const auto _code = (code); \
const auto _call_desc = (call_desc); \
if (_code != ANEURALNETWORKS_NO_ERROR) { \
const auto error_desc = NnApiErrorDescription(_code); \
TF_LITE_KERNEL_LOG(context, \
"NN API returned error %s at line %d while %s.\n", \
error_desc.c_str(), __LINE__, _call_desc); \
*p_errno = _code; \
return kTfLiteError; \
} \
} while (0)
#define RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(context, code, call_desc, \
p_tensor, p_errno) \
do { \
const auto _code = (code); \
const auto _call_desc = (call_desc); \
if (_code != ANEURALNETWORKS_NO_ERROR) { \
const auto error_desc = NnApiErrorDescription(_code); \
TF_LITE_KERNEL_LOG(context, \
"NN API returned error %s at line %d while %s " \
"for tensor '%s'.\n", \
error_desc.c_str(), __LINE__, _call_desc, \
(p_tensor)->name ? (p_tensor)->name : "no-name"); \
*p_errno = _code; \
return kTfLiteError; \
} \
} while (0)
bool IsFloat(TfLiteType type) {
switch (type) {
case kTfLiteFloat32:
return true;
default:
return false;
}
}
bool IsFloatOrUInt8(TfLiteType type) {
switch (type) {
case kTfLiteFloat32:
case kTfLiteUInt8:
return true;
default:
return false;
}
}
bool IsQuantized(TfLiteType type) {
switch (type) {
case kTfLiteUInt8:
case kTfLiteInt8:
return true;
default:
// kTfLiteInt16 isn't supported as quantized type yet.
return false;
}
}
bool IsInt32(TfLiteType type) {
switch (type) {
case kTfLiteInt32:
return true;
default:
return false;
}
}
bool IsFloatOrQuantized(TfLiteType type) {
switch (type) {
case kTfLiteFloat32:
case kTfLiteUInt8:
case kTfLiteInt8:
return true;
default:
return false;
}
}
bool IsFloatOrInt32(TfLiteType type) {
switch (type) {
case kTfLiteFloat32:
case kTfLiteInt32:
return true;
default:
return false;
}
}
bool IsFloatQuantizedOrInt32(TfLiteType type) {
switch (type) {
case kTfLiteFloat32:
case kTfLiteUInt8:
case kTfLiteInt8:
case kTfLiteInt32:
return true;
default:
return false;
}
}
bool IsScalarInputSupported(int builtin_code) {
switch (builtin_code) {
case kTfLiteBuiltinAdd:
case kTfLiteBuiltinMul:
case kTfLiteBuiltinSub:
case kTfLiteBuiltinDiv:
case kTfLiteBuiltinEqual:
case kTfLiteBuiltinNotEqual:
case kTfLiteBuiltinGreater:
case kTfLiteBuiltinGreaterEqual:
case kTfLiteBuiltinLess:
case kTfLiteBuiltinLessEqual:
case kTfLiteBuiltinPow:
case kTfLiteBuiltinMaximum:
case kTfLiteBuiltinMinimum:
case kTfLiteBuiltinPrelu:
case kTfLiteBuiltinLeakyRelu:
return true;
default:
return false;
}
}
// Check if the operation requires explicit conversion from int8 to uint8
// values.
bool NeedInt8Conversion(const TfLiteContext* context, int builtin_code,
const TfLiteNode* node) {
const int input_id = node->inputs->data[0];
const TfLiteType input_type = context->tensors[input_id].type;
switch (builtin_code) {
case kTfLiteBuiltinConv2d:
case kTfLiteBuiltinDepthwiseConv2d:
case kTfLiteBuiltinFullyConnected: {
if (input_type == kTfLiteInt8) {
const int weights_id = node->inputs->data[1];
const auto& weights_tensor = context->tensors[weights_id];
if ((weights_tensor.type == kTfLiteInt8 ||
weights_tensor.type == kTfLiteUInt8) &&
weights_tensor.quantization.type == kTfLiteAffineQuantization) {
return true;
}
}
return false;
}
case kTfLiteBuiltinTransposeConv: {
// Transpose convolution has a different order of inputs:
// 0: output_shape, 1: filter, 2: input, 3: bias.
const int input_id = 2;
const TfLiteType input_type = context->tensors[input_id].type;
if (input_type == kTfLiteInt8) {
return true;
}
return false;
}
case kTfLiteBuiltinSelect: {
const auto value_type = context->tensors[node->inputs->data[1]].type;
return value_type == kTfLiteInt8;
}
case kTfLiteBuiltinAdd:
case kTfLiteBuiltinArgMax:
case kTfLiteBuiltinArgMin:
case kTfLiteBuiltinAveragePool2d:
case kTfLiteBuiltinBatchToSpaceNd:
case kTfLiteBuiltinConcatenation:
case kTfLiteBuiltinEqual:
case kTfLiteBuiltinExpandDims:
case kTfLiteBuiltinGather:
case kTfLiteBuiltinGreater:
case kTfLiteBuiltinGreaterEqual:
case kTfLiteBuiltinHardSwish:
case kTfLiteBuiltinL2Normalization:
case kTfLiteBuiltinLeakyRelu:
case kTfLiteBuiltinLess:
case kTfLiteBuiltinLessEqual:
case kTfLiteBuiltinLogistic:
case kTfLiteBuiltinMaximum:
case kTfLiteBuiltinMaxPool2d:
case kTfLiteBuiltinMean:
case kTfLiteBuiltinMinimum:
case kTfLiteBuiltinMul:
case kTfLiteBuiltinNotEqual:
case kTfLiteBuiltinPad:
case kTfLiteBuiltinPadv2:
case kTfLiteBuiltinPrelu:
case kTfLiteBuiltinReduceMax:
case kTfLiteBuiltinReduceMin:
case kTfLiteBuiltinRelu:
case kTfLiteBuiltinReluN1To1:
case kTfLiteBuiltinRelu6:
case kTfLiteBuiltinResizeBilinear:
case kTfLiteBuiltinResizeNearestNeighbor:
case kTfLiteBuiltinReshape:
case kTfLiteBuiltinSlice:
case kTfLiteBuiltinSoftmax:
case kTfLiteBuiltinSpaceToBatchNd:
case kTfLiteBuiltinSpaceToDepth:
case kTfLiteBuiltinDepthToSpace:
case kTfLiteBuiltinStridedSlice:
case kTfLiteBuiltinSub:
case kTfLiteBuiltinTanh:
case kTfLiteBuiltinTile:
case kTfLiteBuiltinTopkV2:
case kTfLiteBuiltinTranspose: {
return input_type == kTfLiteInt8;
}
default:
return false;
}
}
constexpr int kLstmFullKernelInputSize = 24;
// The 20 input version is deprecated and kept only to
// support old model. The latest version of the LSTM Full Kernel
// is the one with 24 inputs
constexpr int kLstmFullKernelNoOptionalParamsInputSize = 20;
constexpr int kLstmBasicKernelInputSize = 5;
inline bool isLstmBasicKernel(const TfLiteNode* node) {
return node->inputs->size == kLstmBasicKernelInputSize;
}
inline bool isLstmFullKernel(const TfLiteNode* node) {
return node->inputs->size == kLstmFullKernelInputSize ||
node->inputs->size == kLstmFullKernelNoOptionalParamsInputSize;
}
bool IsMeanWithDifferentInputOutputQuantization(const TfLiteContext* context,
const TfLiteNode* node) {
const auto& input = context->tensors[node->inputs->data[0]];
const auto& output = context->tensors[node->outputs->data[0]];
return input.params.scale != output.params.scale ||
input.params.zero_point != output.params.zero_point;
}
bool IsBroadcastBatchMatMul(const TfLiteContext* context,
const TfLiteNode* node) {
const auto& input0 = context->tensors[node->inputs->data[0]];
const auto& input1 = context->tensors[node->inputs->data[1]];
if (input0.dims->size != input1.dims->size) {
return true;
}
for (int i = 0; i < input0.dims->size - 2; i++) {
if (input0.dims->data[i] != input1.dims->data[i]) {
return true;
}
}
return false;
}
bool IsHybridOperator(const TfLiteContext* context, int builtin_code,
const TfLiteNode* node) {
switch (builtin_code) {
case kTfLiteBuiltinConv2d:
case kTfLiteBuiltinFullyConnected: {
const int input_id = node->inputs->data[0];
const int filter_id = node->inputs->data[1];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType filter_type = context->tensors[filter_id].type;
return IsFloat(input_type) && IsQuantized(filter_type);
}
case kTfLiteBuiltinLstm: {
const int input_id = node->inputs->data[0];
// Input #1 is optional so use #2 to determine if hybrid.
const int weights_id = node->inputs->data[2];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return isLstmFullKernel(node) && IsFloat(input_type) &&
IsQuantized(weights_type);
}
case kTfLiteBuiltinUnidirectionalSequenceLstm: {
const int input_id = node->inputs->data[0];
// Input #1 is optional so use #2 to determine if hybrid.
const int weights_id = node->inputs->data[2];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return IsFloat(input_type) && IsQuantized(weights_type);
}
case kTfLiteBuiltinBidirectionalSequenceLstm: {
const int input_id = node->inputs->data[0];
// Input #1 is optional so use #2 to determine if hybrid.
const int weights_id = node->inputs->data[2];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return IsFloat(input_type) && IsQuantized(weights_type);
}
case kTfLiteBuiltinUnidirectionalSequenceRnn: {
const int input_id = node->inputs->data[0];
const int weights_id = node->inputs->data[1];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return IsFloat(input_type) && IsQuantized(weights_type);
}
default:
return false;
}
}
bool IsDequantizeConstFloat16(TfLiteContext* context, const TfLiteNode* node,
const TfLiteRegistration* registration) {
return registration->builtin_code == kTfLiteBuiltinDequantize &&
context->tensors[node->inputs->data[0]].type ==
TfLiteType::kTfLiteFloat16 &&
IsConstantTensor(&context->tensors[node->inputs->data[0]]);
}
bool IsDequantizeNonConstFloat16(TfLiteContext* context, const TfLiteNode* node,
const TfLiteRegistration* registration) {
return registration->builtin_code == kTfLiteBuiltinDequantize &&
context->tensors[node->inputs->data[0]].type ==
TfLiteType::kTfLiteFloat16 &&
!IsConstantTensor(&context->tensors[node->inputs->data[0]]);
}
bool IsDensifyConstTensor(TfLiteContext* context, const TfLiteNode* node,
const TfLiteRegistration* registration) {
return registration->builtin_code == kTfLiteBuiltinDensify &&
IsConstantTensor(&context->tensors[node->inputs->data[0]]);
}
ANeuralNetworksOperandType ConvertTensorTypeToNNType(
const TfLiteTensor* tensor, TfLiteType ann_type_equivalent,
bool use_int8_asymm_signed) {
int32_t nn_type = 0;
float scale = 0.0f;
int32_t zero_point = 0;
switch (tensor->type) {
case kTfLiteFloat32:
nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
break;
case kTfLiteUInt8:
nn_type = ann_type_equivalent == kTfLiteInt32
? ANEURALNETWORKS_TENSOR_INT32
: ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
scale = tensor->params.scale;
zero_point = tensor->params.zero_point;
if (scale == 0) {
// TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM
// with zero scale are not valid in NNAPI.
scale = 1;
}
break;
case kTfLiteInt8:
scale = tensor->params.scale;
zero_point = tensor->params.zero_point;
if (use_int8_asymm_signed) {
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED;
} else if (ann_type_equivalent == kTfLiteUInt8) {
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
zero_point += 128;
} else if (ann_type_equivalent == kTfLiteInt32) {
nn_type = ANEURALNETWORKS_TENSOR_INT32;
zero_point += 128;
} else {
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_SYMM;
}
if (scale == 0) {
// TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM
// with zero scale are not valid in NNAPI.
scale = 1;
}
break;
case kTfLiteInt32:
nn_type = ANEURALNETWORKS_TENSOR_INT32;
scale = tensor->params.scale;
zero_point = tensor->params.zero_point;
break;
case kTfLiteBool:
nn_type = ANEURALNETWORKS_TENSOR_BOOL8;
break;
case kTfLiteInt16:
nn_type = ANEURALNETWORKS_TENSOR_QUANT16_SYMM;
scale = tensor->params.scale;
zero_point = tensor->params.zero_point;
break;
default:
break;
}
uint32_t tensor_rank = static_cast<uint32_t>(tensor->dims->size);
uint32_t* tensor_dims = reinterpret_cast<uint32_t*>(tensor->dims->data);
static uint32_t scalar_rank = 1;
// treat scalar input as single cell tensor in NNAPI.
if (tensor_rank == 0) {
tensor_rank = scalar_rank;
tensor_dims = &scalar_rank;
}
ANeuralNetworksOperandType nn_operand_type{
.type = nn_type,
.dimensionCount = tensor_rank,
.dimensions = tensor_dims,
.scale = scale,
.zeroPoint = zero_point,
};
return nn_operand_type;
}
// NNAPI in API 31 hard-code the preferred alignment/padding with 64 bytes.
constexpr size_t kDefaultByteAlignmentForNNAPI = 64;
static size_t GetNumPaddingBytes(size_t byte_size) {
size_t num_padding_bytes = 0;
if (byte_size % kDefaultByteAlignmentForNNAPI) {
num_padding_bytes = kDefaultByteAlignmentForNNAPI -
(byte_size % kDefaultByteAlignmentForNNAPI);
}
return num_padding_bytes;
}
static size_t GetNNTensorSize(size_t tensor_size, bool allow_padding) {
size_t padding_bytes = GetNumPaddingBytes(tensor_size);
size_t nn_tensor_size = tensor_size;
if (allow_padding) {
nn_tensor_size += padding_bytes;
}
return nn_tensor_size;
}
// Return NNAPI device handle with the provided null-terminated device name.
// Returns kTfLiteError in case of any NNAPI error and if no device with the
// given name can be found.
TfLiteStatus GetDeviceHandle(const NnApi* nnapi, TfLiteContext* context,
const char* device_name_ptr,
ANeuralNetworksDevice** result, int* nnapi_errno) {
if (!device_name_ptr) return kTfLiteError;
*result = nullptr;
std::string device_name(device_name_ptr);
uint32_t num_devices = 0;
nnapi->ANeuralNetworks_getDeviceCount(&num_devices);
for (uint32_t i = 0; i < num_devices; i++) {
ANeuralNetworksDevice* device = nullptr;
const char* buffer = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworks_getDevice(i, &device),
"Searching for target device", nnapi_errno);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworksDevice_getName(device, &buffer),
"Searching for target device", nnapi_errno);
if (device_name == buffer) {
*result = device;
return kTfLiteOk;
}
}
context->ReportError(context,
"Could not find the specified NNAPI accelerator: %s. "
"Must be one of: {%s}.",
device_name_ptr,
nnapi::GetStringDeviceNamesList(nnapi).c_str());
return kTfLiteError;
}
// Compute the hash of a TfLiteIntArray.
uint64_t GetHash(const TfLiteIntArray* int_array, uint64_t combine_with = 0) {
constexpr auto kHashConst = 0x9e3779b97f4a7800ULL;
uint64_t result = combine_with;
for (auto i : TfLiteIntArrayView(int_array)) {
result = result ^ (i + kHashConst + (result << 10) + (result >> 4));
}
return result;
}
bool HasZeroes(TfLiteIntArrayView array) {
for (auto value : array) {
if (value == 0) {
return true;
}
}
return false;
}
// In SPLIT_V, it is legal to specify -1 in size_splits representing an unknown
// split size taking as many values as possible. This function computes and
// returns the actual value of this unknown size, or returns -1 if all split
// sizes are known. The caller is responsible for making sure the size_splits
// and axis tensor are constants.
int ComputeSplitVUnknownSplitSize(const TfLiteContext* context,
const TfLiteNode* node) {
const auto& input = context->tensors[node->inputs->data[0]];
const auto& size_splits_tensor = context->tensors[node->inputs->data[1]];
const auto& axis_tensor = context->tensors[node->inputs->data[2]];
const auto* size_splits = size_splits_tensor.data.i32;
int num_splits = size_splits_tensor.dims->data[0];
bool has_unknown_split_size = false;
int sum_of_known_split_sizes = 0;
for (int i = 0; i < num_splits; i++) {
if (size_splits[i] == -1) {
has_unknown_split_size = true;
} else {
sum_of_known_split_sizes += size_splits[i];
}
}
int axis = axis_tensor.data.i32[0];
axis = axis < 0 ? axis + input.dims->size : axis;
int total_size = input.dims->data[axis];
return has_unknown_split_size ? total_size - sum_of_known_split_sizes : -1;
}
// Bit mask for tensor flags.
enum {
NN_TENSOR_FLAG_SCALAR_AS_TENSOR = 1U << 0,
NN_TENSOR_FLAG_INT8_CONVERSION = 1U << 1,
NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED = 1U << 2,
NN_TENSOR_FLAG_FORCE_PER_CHANNEL = 1U << 3,
NN_TENSOR_FLAG_HALF_TO_FLOAT_CONVERSION = 1U << 4,
};
// Returns the feature level to target when delegating to the given devices.
// The feature level is the max of the ones supported by the devices or
// the current NNAPI runtime feature level if no device is present.
TfLiteStatus GetTargetFeatureLevel(
TfLiteContext* context, const NnApi* nnapi,
const std::vector<ANeuralNetworksDevice*>& device_handles,
int* target_feature_level, int* nnapi_errno) {
*target_feature_level = nnapi->nnapi_runtime_feature_level;
int64_t devices_feature_level = -1;
for (const auto* device_handle : device_handles) {
int64_t curr_device_feature_level;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi->ANeuralNetworksDevice_getFeatureLevel(
device_handle, &curr_device_feature_level),
"Searching for target device", nnapi_errno);
devices_feature_level =
std::max(curr_device_feature_level, devices_feature_level);
}
if ((devices_feature_level > 0) &&
// This second check is necessary since if the nnapi-reference device is
// in the list of target devices the devices_feature_level value will be
// 1000.
(devices_feature_level < nnapi->nnapi_runtime_feature_level)) {
TFLITE_LOG(TFLITE_LOG_INFO,
"Changing NNAPI Feature Level %lld to "
"supported by target devices: %lld",
nnapi->android_sdk_version, devices_feature_level);
*target_feature_level = devices_feature_level;
}
return kTfLiteOk;
}
// Returns true if this delegate is configured to use a specific set of devices.
// This will happen either if:
// - accelerator_name option has been specified
// - NNAPI CPU implementation has been explicitly disabled.
// If exclude_nnapi_reference is true this method will return false if the
// accelerator_name in the delegate options is equal to "nnapi-reference"
bool ShouldUseTargetDevices(StatefulNnApiDelegate::Options delegate_options,
const NnApi* nnapi,
bool exclude_nnapi_reference = false) {
const char* device_name_ptr = delegate_options.accelerator_name;
std::string nnapi_cpu("nnapi-reference");
bool has_selected_accelerator = device_name_ptr != nullptr;
if (exclude_nnapi_reference && has_selected_accelerator) {
if (nnapi_cpu == device_name_ptr) return false;
}
return (delegate_options.disallow_nnapi_cpu &&
nnapi->android_sdk_version >=
delegate::nnapi::kMinSdkVersionForNNAPI12) ||
has_selected_accelerator;
}
// Fills the given result vector with the list of devices the given delegate
// is referring to.
// There are three possible results:
// - an empty array (not the full list of available accelerators,
// for efficiency reasons) if no accelerator is chosen and the
// disallow_nnapi_cpu delegate option is false.
// - A single element array with the target processor, if an accelerator name
// is specified in the delegate options.
// - The full list of devices available on device less the nnapi reference
// implementation if the delegate option disallow_nnapi_cpu has been
// specified.
TfLiteStatus GetTargetDevices(TfLiteContext* context, TfLiteDelegate* delegate,
const NnApi* nnapi, int* nnapi_errno,
std::vector<ANeuralNetworksDevice*>* result) {
if (nnapi->android_sdk_version < delegate::nnapi::kMinSdkVersionForNNAPI12) {
return kTfLiteError;
}
const auto delegate_options = StatefulNnApiDelegate::GetOptions(delegate);
const char* device_name_ptr = delegate_options.accelerator_name;
if (device_name_ptr != nullptr) {
// User specified an accelerator to use.
ANeuralNetworksDevice* nnapi_device = nullptr;
TF_LITE_ENSURE_STATUS(GetDeviceHandle(nnapi, context, device_name_ptr,
&nnapi_device, nnapi_errno));
result->push_back(nnapi_device);
} else if (delegate_options.disallow_nnapi_cpu) {
std::string nnapi_cpu("nnapi-reference");
uint32_t num_devices = 0;
nnapi->ANeuralNetworks_getDeviceCount(&num_devices);
for (uint32_t i = 0; i < num_devices; i++) {
ANeuralNetworksDevice* device = nullptr;
const char* buffer = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworks_getDevice(i, &device),
"Getting list of available devices", nnapi_errno);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworksDevice_getName(device, &buffer),
"Getting list of available devices", nnapi_errno);
if (nnapi_cpu != buffer) {
result->push_back(device);
}
}
}
return kTfLiteOk;
}
// The context to be used with NnapiMappingUtilCInterface.
class NnapiMappingContext {
public:
// Next index of ann tensor
int next_ann_tensor_index_ = 0;
// Mapping from lite tensor index.
std::vector<int> lite_tensor_to_ann_tensor_;
// Mapping from lite index to a type which tensor must be converted to during
// the copying of the data to the memory allocated for NN API. kTfLiteNoType
// means no conversion is needed.
std::vector<int> index_to_type_conversion_;
// Mapping from lite node index.
std::vector<int> nnapi_to_tflite_op_mapping_;
};
} // namespace
namespace delegate {
namespace nnapi {
#ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING
NNMemory::NNMemory(const NnApi* nnapi, const char* name, size_t size) {
if (name && size > 0) {
nnapi_ = nnapi;
byte_size_ = size;
#ifdef __ANDROID__
fd_ = nnapi_->ASharedMemory_create(name, size);
#else
// For non-Android platforms ASharedMemory_create needs unique name to
// create a shared memory object (see nnapi_implementation.cc).
char shm_name_buffer[L_tmpnam];
if (tmpnam(shm_name_buffer) == nullptr) {
shm_name_buffer[0] = '\0';
}
// tmpnam will produce a string containing with slashes, but shm_open
// won't like that.
shm_region_name_ = std::string(name) + std::string(shm_name_buffer);
std::replace(shm_region_name_.begin(), shm_region_name_.end(), '/', '-');
fd_ = nnapi_->ASharedMemory_create(shm_region_name_.c_str(), size);
#endif
data_ptr_ = reinterpret_cast<uint8_t*>(
mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0));
nnapi_->ANeuralNetworksMemory_createFromFd(size, PROT_READ | PROT_WRITE,
fd_, 0, &nn_memory_handle_);
}
}
#else
NNMemory::NNMemory(const NnApi* /*nnapi*/, const char* /*name*/,
size_t /*size*/)
: nnapi_(nullptr) {}
#endif
NNMemory::~NNMemory() {
#ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING
if (data_ptr_) {
munmap(data_ptr_, byte_size_);
}
if (nn_memory_handle_) {
nnapi_->ANeuralNetworksMemory_free(nn_memory_handle_);
}
#ifdef __ANDROID__
if (fd_ >= 0) close(fd_);
#else
if (!shm_region_name_.empty()) shm_unlink(shm_region_name_.c_str());
#endif
#endif
}
class DequantizeMapping {
public:
int DequantizedAnnIndex(int ann_index, TfLiteType type) const {
for (const auto& element : mapping_) {
if (ann_index == std::get<0>(element) && type == std::get<1>(element)) {
return std::get<2>(element);
}
}
return -1;
}
void Add(int ann_index, TfLiteType type, int dequantized_ann_index) {
// This assumes it is not already mapped.
mapping_.emplace_back(ann_index, type, dequantized_ann_index);
}
private:
// Each tuple specifies the ANN (quantized) tensor index, the desired
// floating-point type and the matching ANN (dequantized) tensor index. This
// could use a map but instead std::vector is used to keep code size lower.
std::vector<std::tuple<int, TfLiteType, int>> mapping_;
};
// Abstract builder for building an op in the NN API graph. This handles
// the disparity between TFLite and NN API operand types. NN API has singular
// operands for both tensors and parameters, and TFLite separates the two.
class NNAPIOpBuilder {
public:
NNAPIOpBuilder(const NnApi* nnapi, TfLiteContext* context,
NnapiMappingUtilCInterface* mapping_util,
DequantizeMapping* dequantize_mapping,
std::map<const MMAPAllocation*, ANeuralNetworksMemory*>*
allocation_mapping,
ANeuralNetworksModel* nn_model, int* nnapi_errno,
bool allow_dynamic_dimensions)
: nnapi_(nnapi),
context_(context),
mapping_util_(mapping_util),
dequantize_mapping_(dequantize_mapping),
allocation_memory_mapping_(allocation_mapping),
nn_model_(nn_model),
nnapi_errno_(nnapi_errno),
allow_dynamic_dimensions_(allow_dynamic_dimensions) {}
TfLiteStatus AddScalarBoolOperand(bool value) {
return AddScalarOperand<bool>(value, ANEURALNETWORKS_BOOL);
}
TfLiteStatus AddScalarInt32Operand(int32_t value) {
return AddScalarOperand<int32_t>(value, ANEURALNETWORKS_INT32);
}
TfLiteStatus AddScalarFloat32Operand(float value) {
return AddScalarOperand<float>(value, ANEURALNETWORKS_FLOAT32);
}
TfLiteStatus AddVectorInt32Operand(const int32_t* values,
uint32_t num_values) {
return AddVectorOperand<int32_t>(values, num_values,
ANEURALNETWORKS_TENSOR_INT32,
/*scale=*/0.f, /*zero_point=*/0);
}
TfLiteStatus AddVectorInt32Operand(const int32_t* values, uint32_t num_values,
float scale, int32_t zero_point) {
return AddVectorOperand<int32_t>(
values, num_values, ANEURALNETWORKS_TENSOR_INT32, scale, zero_point);
}
TfLiteStatus AddVectorInt16Operand(const int16_t* values,
uint32_t num_values) {
return AddVectorOperand<int16_t>(values, num_values,
ANEURALNETWORKS_TENSOR_QUANT16_SYMM,
/*scale=*/1.f, /*zero_point=*/0);
}
TfLiteStatus AddVectorInt8Operand(const int8_t* values, uint32_t num_values) {
return AddVectorOperand<int8_t>(values, num_values,
ANEURALNETWORKS_TENSOR_QUANT8_SYMM,
/*scale=*/1.f, /*zero_point=*/0);
}
TfLiteStatus AddVectorFloat32Operand(const float* values,
uint32_t num_values) {
return AddVectorOperand<float>(values, num_values,
ANEURALNETWORKS_TENSOR_FLOAT32);
}
TfLiteStatus AddPoolingParams(void* data) {
auto builtin = reinterpret_cast<TfLitePoolParams*>(data);
AddScalarInt32Operand(builtin->padding);
AddScalarInt32Operand(builtin->stride_width);
AddScalarInt32Operand(builtin->stride_height);
AddScalarInt32Operand(builtin->filter_width);
AddScalarInt32Operand(builtin->filter_height);
AddScalarInt32Operand(builtin->activation);
return kTfLiteOk;
}
TfLiteStatus AddTensorInput(int tensor_index, bool hybrid_op,
int tensor_flags = 0) {
return AddTensor(tensor_index, hybrid_op, &augmented_inputs_, tensor_flags);
}
TfLiteStatus AddTensorOutput(int tensor_index, int tensor_flags = 0) {
return AddTensor(tensor_index, /*hybrid_op=*/false, &augmented_outputs_,
tensor_flags);
}
TfLiteStatus AddAdditionalFloat32OutputTensor(uint32_t dimension_count) {
std::vector<uint32_t> dims(dimension_count, 0);
return AddFloat32OutputTensor(dimension_count, dims.data(), nullptr);
}
TfLiteStatus AddStateFloat32Tensor(int tensor_index,
int* ann_tensor_index_out) {
TfLiteTensor* tensor = &context_->tensors[tensor_index];
return AddFloat32OutputTensor(
tensor->dims->size, reinterpret_cast<uint32_t*>(tensor->dims->data),
ann_tensor_index_out);
}
TfLiteStatus AddStateInt16Tensor(int tensor_index,
int* ann_tensor_index_out) {
TfLiteTensor* tensor = &context_->tensors[tensor_index];
return AddAdditionalOutputTensor(
tensor->dims->size, reinterpret_cast<uint32_t*>(tensor->dims->data),
ANEURALNETWORKS_TENSOR_QUANT16_SYMM, tensor->params.scale,
tensor->params.zero_point, ann_tensor_index_out);
}
TfLiteStatus AddStateInt8AsymTensor(int tensor_index,
int* ann_tensor_index_out) {
TfLiteTensor* tensor = &context_->tensors[tensor_index];
return AddAdditionalOutputTensor(
tensor->dims->size, reinterpret_cast<uint32_t*>(tensor->dims->data),
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED, tensor->params.scale,
tensor->params.zero_point, ann_tensor_index_out);
}
// Add a constant tensor with a single element, intended for broadcast capable
// ops.
TfLiteStatus AddSingleValueConstantTensor(float value, bool is_quantized) {
if (!is_quantized) {
return AddVectorFloat32Operand(&value, 1);
} else {
// in the case that we need to add a quantized tensor, set the value to
// 64, zero_point to be 0 and adjust scale accordingly.
const uint8_t quant8_value = 64;
return AddVectorOperand<uint8_t>(&quant8_value, 1,
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM,
value / quant8_value, 0);
}
}
// Calculate the scale and zero_point for 8-bit unsigned tensor, given float
// min and max. zero_point is clamped to [0, 255].
TfLiteStatus CalculateQuantizationParams(float min, float max, float* scale,
int* zero_point) {
if (max < min) return kTfLiteError;
*scale = (max - min) / 255.f;
if (min > 0.f) {
*zero_point = 0;
} else if (max < 0.f) {
*zero_point = 255;
} else {
*zero_point = (0.f - min) / (*scale);
}
return kTfLiteOk;
}
// Lower hardswish according to the following equation:
// hard_swish[x] = x (ReLU6(x + 3)) / 6 == x * (Relu_N1_to_1(x/3) * 3 + 3) / 6
// = 0.5x * Relu_N1_to_1(x/3) + 0.5x
TfLiteStatus TransformHardSwishIntoSupportedOps(int lite_input_index,
int lite_output_index,
bool need_int8_conversion,
int lite_node_index) {
const TfLiteTensor& tensor = context_->tensors[lite_input_index];
float input_scale = tensor.params.scale;
int input_zero_point = tensor.params.zero_point;
float input_min = 0.f;
float input_max = 0.f;
int tensor_flags = 0;
if (need_int8_conversion) {
tensor_flags = tensor_flags | NN_TENSOR_FLAG_INT8_CONVERSION;
input_zero_point += 128;
}
bool is_quantized = false;
int nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
if (tensor.type == kTfLiteInt8 || tensor.type == kTfLiteUInt8) {
is_quantized = true;
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
input_min = (0 - input_zero_point) * input_scale;
input_max = (255 - input_zero_point) * input_scale;
}
// Stage1 : s1 = Relu1(x * 1/3)
float s1_output_min = 0.f;
float s1_output_max = 0.f;
int s1_out_ann_index = 0;
{
float s1_output_scale = 0.f;
int s1_output_zero_point = 0;
if (is_quantized) {
// clamp the output range to [-1, 1] if needed.
s1_output_min = input_min / 3.f < -1.f ? -1.f : input_min / 3.f;
s1_output_max = input_max / 3.f > 1.f ? 1.f : input_max / 3.f;
CalculateQuantizationParams(s1_output_min, s1_output_max,
&s1_output_scale, &s1_output_zero_point);
}
TF_LITE_ENSURE_OK(context_,
AddTensorInput(lite_input_index, false, tensor_flags));
const float value3f = 1.f / 3.f;
TF_LITE_ENSURE_OK(context_,
AddSingleValueConstantTensor(value3f, is_quantized));
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_RELU1));
TF_LITE_ENSURE_OK(
context_,
AddAdditionalOutputTensor(
tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data),
nn_type, s1_output_scale, s1_output_zero_point,
&s1_out_ann_index));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index));
}
// Stage2 : s2 = x / 2
float s2_output_min = input_min / 2.f;
float s2_output_max = input_max / 2.f;
int s2_out_ann_index = 0;
{
float s2_output_scale = input_scale / 2.0f;
int s2_output_zero_point = input_zero_point;
TF_LITE_ENSURE_OK(context_,
AddTensorInput(lite_input_index, false, tensor_flags));
const float value2f = 0.5f;
TF_LITE_ENSURE_OK(context_,
AddSingleValueConstantTensor(value2f, is_quantized));
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
TF_LITE_ENSURE_OK(
context_,
AddAdditionalOutputTensor(
tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data),
nn_type, s2_output_scale, s2_output_zero_point,
&s2_out_ann_index));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index));
}
// Stage 3 : s3 = s1 * s2
int s3_out_ann_index = 0;
{
augmented_inputs_.push_back(s1_out_ann_index);
augmented_inputs_.push_back(s2_out_ann_index);
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
float s3_output_scale = 0.f;
int s3_output_zero_point = 0;
if (is_quantized) {
// the min for stage 3 is always 0.0f.
float s3_output_min = 0.f;
// the max for stage 3 is max(s1_min * s2_min, s1_max * s3_max).
float s3_output_max =
s1_output_max * s2_output_max > s1_output_min * s2_output_min
? s1_output_max * s2_output_max
: s1_output_min * s2_output_min;
CalculateQuantizationParams(s3_output_min, s3_output_max,
&s3_output_scale, &s3_output_zero_point);
}
TF_LITE_ENSURE_OK(
context_,
AddAdditionalOutputTensor(
tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data),
nn_type, s3_output_scale, s3_output_zero_point,
&s3_out_ann_index));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index));
}
// Stage 4: y = s3 + s2
{
augmented_inputs_.push_back(s2_out_ann_index);
augmented_inputs_.push_back(s3_out_ann_index);
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
TF_LITE_ENSURE_OK(context_,
AddTensorOutput(lite_output_index, tensor_flags));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_ADD, lite_node_index));
}
return kTfLiteOk;
}
// Adds the operation to the model and maps the operation to the originating
// TFLite one.
TfLiteStatus AddOperationToModel(ANeuralNetworksOperationType type,
uint32_t input_count, const uint32_t* inputs,
uint32_t output_count,
const uint32_t* outputs,
int lite_node_index) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperation(
nn_model_, type, input_count, inputs, output_count, outputs),
"adding operation", nnapi_errno_);
mapping_util_->AddNnapiToTfliteOpMapping(mapping_util_, lite_node_index);
return kTfLiteOk;
}
// Adds a Dequantize operator and replaces the input tensor index with the
// dequantized version. If the dequantized version of the operator already
// exists then it is not added again.
TfLiteStatus AddDequantize(int nn_input_index, int lite_tensor_index,
TfLiteType dequantized_type, int lite_node_index) {
const int ann_index =
mapping_util_->TfLiteIndexToNnIndex(mapping_util_, lite_tensor_index);
int dequantized_ann_index =
dequantize_mapping_->DequantizedAnnIndex(ann_index, dequantized_type);
if (dequantized_ann_index == -1) {
// The dequantized version does not exist yet, it has to be added: a new
// Dequantize operation is added, yielding a new tensor.
const TfLiteTensor& tensor = context_->tensors[lite_tensor_index];
ANeuralNetworksOperandType operand_type{
ANEURALNETWORKS_TENSOR_FLOAT32,
static_cast<uint32_t>(tensor.dims->size),
reinterpret_cast<uint32_t*>(tensor.dims->data), 0.f, 0};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
dequantized_ann_index =
mapping_util_->AddNewNonTensorOperand(mapping_util_);
// Add Dequantize operation.
const uint32_t dequantize_input[1] = {static_cast<uint32_t>(ann_index)};
const uint32_t dequantize_output[1] = {
static_cast<uint32_t>(dequantized_ann_index)};
TF_LITE_ENSURE_OK(
context_, AddOperationToModel(ANEURALNETWORKS_DEQUANTIZE,
/*input_count=*/1, dequantize_input,
/*output_count=*/1, dequantize_output,
lite_node_index));
dequantize_mapping_->Add(ann_index, dequantized_type,
dequantized_ann_index);
}
// The input for the original operation is modified so that the operation
// now uses the dequantized tensor as input.
augmented_inputs_[nn_input_index] = dequantized_ann_index;
return kTfLiteOk;
}
// Add a RESHAPE op which reshapes an NNAPI intermediate output to the
// dimensions of the TFLite output tensor.
TfLiteStatus AppendReshape(int nn_input_index, int lite_out_tensor_index,
int lite_node_index) {
augmented_inputs_.push_back(nn_input_index);
auto& output_tensor = context_->tensors[lite_out_tensor_index];
TF_LITE_ENSURE_STATUS(
AddVectorInt32Operand(output_tensor.dims->data,
static_cast<uint32_t>(output_tensor.dims->size)));
TF_LITE_ENSURE_OK(context_,
AddTensorOutput(lite_out_tensor_index,
NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
TF_LITE_ENSURE_STATUS(
FinalizeAddOperation(ANEURALNETWORKS_RESHAPE, lite_node_index));
return kTfLiteOk;
}
// Add a ADD op to requantize an NNAPI intermediate output to the scale and
// zero point of the TFLite output tensor.
TfLiteStatus AppendRequantize(int nn_input_index, int lite_out_tensor_index,
int lite_node_index, int tensor_flags = 0) {
augmented_inputs_.push_back(nn_input_index);
auto& output_tensor = context_->tensors[lite_out_tensor_index];
// Create a zero vector with the same type as the output type. There is only
// one single element in the vector, and it is broadcastable with any
// tensor.
TF_LITE_ENSURE(context_, IsQuantized(output_tensor.type));
bool need_int8_conversion = tensor_flags & NN_TENSOR_FLAG_INT8_CONVERSION;
int nn_type = (output_tensor.type == kTfLiteUInt8 || need_int8_conversion)
? ANEURALNETWORKS_TENSOR_QUANT8_ASYMM
: ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED;
int8_t zero = 0;
TF_LITE_ENSURE_STATUS(AddVectorOperand(&zero, /*num_values=*/1, nn_type,
/*scale=*/1.0f, /*zero_point=*/0));
TF_LITE_ENSURE_STATUS(AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
TF_LITE_ENSURE_STATUS(AddTensorOutput(lite_out_tensor_index, tensor_flags));
TF_LITE_ENSURE_STATUS(
FinalizeAddOperation(ANEURALNETWORKS_ADD, lite_node_index));
return kTfLiteOk;
}
// Lower PACK into CONCAT + RESHAPE when possible
TfLiteStatus TransformPackIntoSupportedOps(int lite_node_index,
TfLiteNode* node,
TfLiteRegistration* reg) {
// Add input tensors for CONCAT, and calculate the dimensions for the
// output.
int concat_output_ann_index = -1;
TfLitePackParams* builtin =
reinterpret_cast<TfLitePackParams*>(node->builtin_data);
auto& input_tensor = context_->tensors[node->inputs->data[0]];
int axis = builtin->axis < 0 ? input_tensor.dims->size + builtin->axis + 1
: builtin->axis;
TF_LITE_ENSURE(context_, axis < input_tensor.dims->size);
uint32_t concat_dim_size = 0;
for (int input_pos = 0; input_pos < node->inputs->size; ++input_pos) {
const auto input_index = node->inputs->data[input_pos];
concat_dim_size +=
context_->tensors[node->inputs->data[input_pos]].dims->data[axis];
TF_LITE_ENSURE_STATUS(
AddTensorInput(input_index, /*hybrid_op=*/false,
NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
}
TF_LITE_ENSURE_STATUS(AddScalarInt32Operand(axis));
std::vector<uint32_t> concat_output_shape(input_tensor.dims->size, 0);
for (int i = 0; i < concat_output_shape.size(); i++) {
if (i == axis) {
concat_output_shape[i] = concat_dim_size;
} else {
concat_output_shape[i] = input_tensor.dims->data[i];
}
}
TF_LITE_ENSURE_STATUS(AddIntermediateOutputTensor(
input_tensor.type, concat_output_shape.size(),
concat_output_shape.data(), input_tensor.params.scale,
input_tensor.params.zero_point, &concat_output_ann_index));
TF_LITE_ENSURE_STATUS(
FinalizeAddOperation(ANEURALNETWORKS_CONCATENATION, lite_node_index));
// Reshape the output tensor
TF_LITE_ENSURE_STATUS(AppendReshape(
concat_output_ann_index, node->outputs->data[0], lite_node_index));
return kTfLiteOk;
}
// Lower UNPACK into RESHAPE + SPLIT when possible.
TfLiteStatus TransformUnpackIntoSupportedOps(int lite_node_index,
TfLiteNode* node,
TfLiteRegistration* reg) {
auto& input_tensor = context_->tensors[node->inputs->data[0]];
auto* builtin = reinterpret_cast<TfLiteUnpackParams*>(node->builtin_data);
int axis = builtin->axis < 0 ? builtin->axis + input_tensor.dims->size
: builtin->axis;
TF_LITE_ENSURE(context_, axis >= 0);
TF_LITE_ENSURE(context_, axis < (input_tensor.dims->size - 1));
int num_splits = builtin->num;
TF_LITE_ENSURE(context_, num_splits == input_tensor.dims->data[axis]);
TF_LITE_ENSURE(context_, num_splits == node->outputs->size);
// Step 1: RESHAPE
std::vector<int32_t> intermediate_shape(input_tensor.dims->size - 1);
std::copy(input_tensor.dims->data, input_tensor.dims->data + axis,
intermediate_shape.begin());
intermediate_shape[axis] =
input_tensor.dims->data[axis] * input_tensor.dims->data[axis + 1];
std::copy(input_tensor.dims->data + axis + 2,
input_tensor.dims->data + input_tensor.dims->size,
intermediate_shape.begin() + axis + 1);
TF_LITE_ENSURE_STATUS(AddTensorInput(node->inputs->data[0],
/*hybrid_op=*/false,
NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
TF_LITE_ENSURE_STATUS(AddVectorInt32Operand(intermediate_shape.data(),
intermediate_shape.size()));
int reshape_output_ann_index = -1;
float scale = input_tensor.params.scale;
// Quantized tensor with zero scale is not valid in NNAPI.
if (IsQuantized(input_tensor.type) && scale == 0.0f) {
scale = 1.0f;
}
TF_LITE_ENSURE_STATUS(AddIntermediateOutputTensor(
input_tensor.type, intermediate_shape.size(),
reinterpret_cast<uint32_t*>(intermediate_shape.data()), scale,
input_tensor.params.zero_point, &reshape_output_ann_index));
TF_LITE_ENSURE_STATUS(
FinalizeAddOperation(ANEURALNETWORKS_RESHAPE, lite_node_index));
// Step 2: SPLIT
augmented_inputs_.push_back(reshape_output_ann_index);
TF_LITE_ENSURE_STATUS(AddScalarInt32Operand(axis));
TF_LITE_ENSURE_STATUS(AddScalarInt32Operand(num_splits));
for (int i = 0; i < num_splits; i++) {
int lite_output_index = node->outputs->data[i];
TF_LITE_ENSURE_STATUS(AddTensorOutput(
lite_output_index, NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
}
TF_LITE_ENSURE_STATUS(
FinalizeAddOperation(ANEURALNETWORKS_SPLIT, lite_node_index));
return kTfLiteOk;
}
// Lower SPLIT_V into SLICEs.
TfLiteStatus TransformSplitVIntoSupportedOps(int lite_node_index,
TfLiteNode* node,
TfLiteRegistration* reg) {
auto& input = context_->tensors[node->inputs->data[0]];
int input_rank = input.dims->size;
const auto& size_splits_tensor = context_->tensors[node->inputs->data[1]];
const auto* size_splits = size_splits_tensor.data.i32;
int num_splits = size_splits_tensor.dims->data[0];
int axis = context_->tensors[node->inputs->data[2]].data.i32[0];
axis = axis < 0 ? axis + input_rank : axis;
TF_LITE_ENSURE(context_, axis >= 0);
TF_LITE_ENSURE(context_, axis < input_rank);
int unknown_split_size = ComputeSplitVUnknownSplitSize(context_, node);
// Keep track of the start index of a slice.
int slice_begin_index = 0;
for (int split_index = 0; split_index < num_splits; split_index++) {
int split_size = size_splits[split_index] == -1
? unknown_split_size
: size_splits[split_index];
TF_LITE_ENSURE(context_, split_size > 0);
// Parameters of SLICE.
std::vector<int> begin_indices(input_rank);
std::vector<int> slice_sizes(input_rank);
for (int i = 0; i < input_rank; i++) {
if (i == axis) {
// Take only the splitted size.
begin_indices[i] = slice_begin_index;
slice_sizes[i] = split_size;
} else {
// Take the full size.
begin_indices[i] = 0;
slice_sizes[i] = input.dims->data[i];
}
}
slice_begin_index += split_size;
// Build NNAPI SLICE inputs and output.
TF_LITE_ENSURE_STATUS(AddTensorInput(
node->inputs->data[0],
/*hybrid_op=*/false, NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
TF_LITE_ENSURE_STATUS(
AddVectorInt32Operand(begin_indices.data(), begin_indices.size()));
TF_LITE_ENSURE_STATUS(
AddVectorInt32Operand(slice_sizes.data(), slice_sizes.size()));
int lite_output_index = node->outputs->data[split_index];
TF_LITE_ENSURE_STATUS(AddTensorOutput(
lite_output_index, NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
TF_LITE_ENSURE_STATUS(
FinalizeAddOperation(ANEURALNETWORKS_SLICE, lite_node_index));
}
return kTfLiteOk;
}
// Lower SQUARED_DIFFERENCE into SUB and MUL.
TfLiteStatus TransformSquaredDifferenceIntoSupportedOps(
int lite_node_index, TfLiteNode* node, TfLiteRegistration* reg) {
const TfLiteTensor& lhs = context_->tensors[node->inputs->data[0]];
const TfLiteTensor& output = context_->tensors[node->outputs->data[0]];
// Stage1 : diff = lhs - rhs
int diff_out_ann_index = 0;
{
// For quantized data type, choose a proper scale and zero point based on
// the output range.
float max_output = 0.f;
int diff_output_zero_point = 0;
int diff_output_nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
switch (lhs.type) {
case kTfLiteFloat32:
diff_output_nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
break;
case kTfLiteInt32:
diff_output_nn_type = ANEURALNETWORKS_TENSOR_INT32;
break;
case kTfLiteUInt8:
max_output = (255 - output.params.zero_point) * output.params.scale;
diff_output_zero_point = 128;
diff_output_nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
break;
case kTfLiteInt8:
max_output = (127 - output.params.zero_point) * output.params.scale;
diff_output_zero_point = 0;
diff_output_nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED;
break;
default:
return kTfLiteError;
}
// Final output range: [0, max_output], and output = diff^2,
// -> diff range: [-sqrt(max_output), sqrt(max_output)]
// This range corresponds to [1, 255] for uint8 with zero_point = 128,
// or [-127, 127] for int8 with zero_point = 0.
float diff_output_scale = 2.0f * std::sqrt(max_output) / 254.0f;
TF_LITE_ENSURE_OK(
context_, AddTensorInput(node->inputs->data[0], /*hybrid_op=*/false,
NN_TENSOR_FLAG_SCALAR_AS_TENSOR |
NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
TF_LITE_ENSURE_OK(
context_, AddTensorInput(node->inputs->data[1], /*hybrid_op=*/false,
NN_TENSOR_FLAG_SCALAR_AS_TENSOR |
NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
TF_LITE_ENSURE_OK(
context_,
AddAdditionalOutputTensor(
output.dims->size, reinterpret_cast<uint32_t*>(output.dims->data),
diff_output_nn_type, diff_output_scale, diff_output_zero_point,
&diff_out_ann_index));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_SUB, lite_node_index));
}
// Stage2 : out = diff * diff
{
augmented_inputs_.push_back(diff_out_ann_index);
augmented_inputs_.push_back(diff_out_ann_index);
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
TF_LITE_ENSURE_OK(context_,
AddTensorOutput(node->outputs->data[0],
NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index));
}
return kTfLiteOk;
}
// Finish emitting the op (of type `type`) into the NN API.
TfLiteStatus FinalizeAddOperation(ANeuralNetworksOperationType type,
int lite_node_index) {
// Actually add a NN API operation
TF_LITE_ENSURE_OK(context_,
AddOperationToModel(
type, static_cast<uint32_t>(augmented_inputs_.size()),
augmented_inputs_.data(),
static_cast<uint32_t>(augmented_outputs_.size()),
augmented_outputs_.data(), lite_node_index));
augmented_inputs_.clear();
augmented_outputs_.clear();
return kTfLiteOk;
}
TfLiteStatus AddSingleValueTensorAsScalarOperand(int tensor_index,
int nn_type) {
const TfLiteTensor* tensor = &context_->tensors[tensor_index];
TF_LITE_ENSURE_EQ(context_, NumElements(tensor), 1);
ANeuralNetworksOperandType operand_type{.type = nn_type};
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", tensor, nnapi_errno_);
int ann_tensor_index =
mapping_util_->TfLiteIndexToNnIndex(mapping_util_, tensor_index);
if (ann_tensor_index != -1) {
augmented_inputs_.push_back(ann_tensor_index);
return kTfLiteOk;
}
// Allocate a new tensor index
ann_tensor_index =
mapping_util_->AddNewNnTensorIndex(mapping_util_, tensor_index);
augmented_inputs_.push_back(ann_tensor_index);
const TfLiteType tensor_type = tensor->type;
TfLiteType nn_type_equivalent;
TF_LITE_ENSURE_OK(context_, GetEquivalentToANNType(context_, nn_type,
&nn_type_equivalent));
if (tensor_type != nn_type_equivalent) {
mapping_util_->AddTypeConversion(mapping_util_, tensor_index,
nn_type_equivalent);
}
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddNewInputConstantTensor(
int32_t nn_type, TfLiteType type, const TfLiteIntArray* dims,
const std::vector<T>& tensor_value,
const TfLiteQuantizationParams& quant_params, int* tensor_index) {
TF_LITE_ENSURE_OK(context_,
context_->AddTensors(context_, 1, tensor_index));
TfLiteTensor* new_tensor = &context_->tensors[*tensor_index];
new_tensor->type = type;
new_tensor->allocation_type = kTfLiteDynamic;
new_tensor->params = quant_params;
// Not removing the new tensor in case of resizing errors since it will
// be cleared by the context
TF_LITE_ENSURE_OK(
context_,
context_->ResizeTensor(
context_, new_tensor,
// Resize Tensor takes ownership of the dims array passed as param
TfLiteIntArrayCopy(dims)));
memcpy(new_tensor->data.raw,
reinterpret_cast<const char*>(tensor_value.data()),
tensor_value.size() * sizeof(T));
const uint32_t tensor_rank = static_cast<uint32_t>(dims->size);
const uint32_t* tensor_dims = reinterpret_cast<const uint32_t*>(dims->data);
ANeuralNetworksOperandType operand_type{nn_type, tensor_rank, tensor_dims,
quant_params.scale,
quant_params.zero_point};
const int ann_tensor_index =
mapping_util_->AddDelegateGeneratedInputAnnTensorOperand(mapping_util_);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
augmented_inputs_.push_back(ann_tensor_index);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_tensor_index, new_tensor->data.raw,
new_tensor->bytes),
"setting new operand value", nnapi_errno_);
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddNewInputConstantTensor(
int32_t nn_type, TfLiteType type, std::initializer_list<int> dims,
const std::vector<T>& tensor_value,
const TfLiteQuantizationParams& quant_params, int* tensor_index) {
TfLiteIntArray* dim_array = TfLiteIntArrayCreate(dims.size());
dim_array->size = dims.size();
std::copy(dims.begin(), dims.end(), dim_array->data);
const auto result = AddNewInputConstantTensor(
nn_type, type, dim_array, tensor_value, quant_params, tensor_index);
TfLiteIntArrayFree(dim_array);
return result;
}
TfLiteStatus AddIntermediateOutputTensor(TfLiteType tfl_type,
uint32_t dimension_count,
const uint32_t* dimension_data,
float scale, int32_t zero_point,
int* ann_index_out,
bool need_int8_conversion = false) {
int32_t nn_type;
switch (tfl_type) {
case kTfLiteFloat32:
nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
break;
case kTfLiteInt8:
nn_type = need_int8_conversion
? ANEURALNETWORKS_TENSOR_QUANT8_ASYMM
: ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED;
break;
case kTfLiteUInt8:
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
break;
default:
return kTfLiteError;
}
if (need_int8_conversion) {
zero_point += 128;
}
TF_LITE_ENSURE_STATUS(
AddAdditionalOutputTensor(dimension_count, dimension_data, nn_type,
scale, zero_point, ann_index_out));
return kTfLiteOk;
}
void ClearInputOuputLists() {
augmented_inputs_.clear();
augmented_outputs_.clear();
}
private:
// Returns a TF Lite type which has the same memory representation as a
// provided NN API type.
TfLiteStatus GetEquivalentToANNType(TfLiteContext* context, int nn_type,
TfLiteType* type) {
switch (nn_type) {
case ANEURALNETWORKS_INT32:
*type = kTfLiteInt32;
return kTfLiteOk;
case ANEURALNETWORKS_FLOAT32:
*type = kTfLiteFloat32;
return kTfLiteOk;
default:
context->ReportError(context,
"NN API Delegate: Can't get an equivalent TF Lite "
"type for provided NN API type: %d.\n",
nn_type);
return kTfLiteError;
}
}
template <typename T>
TfLiteStatus AddScalarOperand(T value, int32_t nn_type) {
ANeuralNetworksOperandType operand_type{.type = nn_type};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
const int ann_index = mapping_util_->AddNewNonTensorOperand(mapping_util_);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(nn_model_, ann_index,
&value, sizeof(T)),
"setting new operand value", nnapi_errno_);
augmented_inputs_.push_back(ann_index);
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddVectorOperand(const T* values, uint32_t num_values,
int32_t nn_type, float scale,
int32_t zero_point) {
ANeuralNetworksOperandType operand_type{.type = nn_type,
.dimensionCount = 1,
.dimensions = &num_values,
.scale = scale,
.zeroPoint = zero_point};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
const int ann_index = mapping_util_->AddNewNonTensorOperand(mapping_util_);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_index, values, sizeof(T) * num_values),
"settings new operand value", nnapi_errno_);
augmented_inputs_.push_back(ann_index);
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddVectorOperand(const T* values, uint32_t num_values,
int32_t nn_type) {
return AddVectorOperand(values, num_values, nn_type, /*scale=*/0.f,
/*zero_point=*/0);
}
TfLiteStatus AddFloat32OutputTensor(uint32_t dimension_count,
const uint32_t* dimension_data,
int* ann_index_out) {
return AddAdditionalOutputTensor(
dimension_count, dimension_data, ANEURALNETWORKS_TENSOR_FLOAT32,
/*scale=*/0.f, /*zero_point=*/0, ann_index_out);
}
TfLiteStatus AddAdditionalOutputTensor(uint32_t dimension_count,
const uint32_t* dimension_data,
int32_t nn_type, float scale,
int32_t zero_point,
int* ann_index_out) {
ANeuralNetworksOperandType operand_type{
.type = nn_type,
.dimensionCount = dimension_count,
.dimensions = dimension_data,
.scale = scale,
.zeroPoint = zero_point,
};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
const int ann_index = mapping_util_->AddNewNonTensorOperand(mapping_util_);
augmented_outputs_.push_back(ann_index);
if (ann_index_out) *ann_index_out = ann_index;
return kTfLiteOk;
}
// Adds a new NN API tensor that shadows the TF Lite tensor `tensor_index`.
// This returns the NN API tensor index corresponding to the created tensor.
// If another caller previously created a NN API tensor for `tensor_index`
// then the existing one is returned.
TfLiteStatus AddTensor(int tensor_index, bool hybrid_op,
std::vector<uint32_t>* indices, int tensor_flags = 0) {
const bool scalar_as_tensor =
tensor_flags & NN_TENSOR_FLAG_SCALAR_AS_TENSOR;
const bool need_int8_conversion =
tensor_flags & NN_TENSOR_FLAG_INT8_CONVERSION;
const bool use_int8_asymm_signed =
tensor_flags & NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED;
const bool force_per_channel =
tensor_flags & NN_TENSOR_FLAG_FORCE_PER_CHANNEL;
const bool need_half2float_conversion =
tensor_flags & NN_TENSOR_FLAG_HALF_TO_FLOAT_CONVERSION;
int ann_tensor_index =
mapping_util_->TfLiteIndexToNnIndex(mapping_util_, tensor_index);
if (ann_tensor_index != -1) {
indices->push_back(ann_tensor_index);
return kTfLiteOk;
}
// Allocate a new tensor index
ann_tensor_index =
mapping_util_->AddNewNnTensorIndex(mapping_util_, tensor_index);
// Parameters needed for new type.
int32_t nn_type = 0;
float scale = 0.0f;
int32_t zeroPoint = 0;
ANeuralNetworksSymmPerChannelQuantParams ann_perchannel_params;
TfLiteTensor* tensor = &context_->tensors[tensor_index];
TfLiteType tensor_type = tensor->type;
if (hybrid_op && (tensor_type == kTfLiteUInt8)) {
// For legacy reason, UINT8 weights in hybrid operators are actually INT8
// values and should be interpreted as such.
tensor_type = kTfLiteInt8;
}
switch (tensor_type) {
case kTfLiteNoType:
// Tensors added during initialization of Ops don't have a type yet and
// should not be registered with the NNAPI.
indices->push_back(-1);
return kTfLiteOk;
case kTfLiteFloat32:
nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
break;
case kTfLiteFloat16:
nn_type = ANEURALNETWORKS_TENSOR_FLOAT16;
if (need_half2float_conversion) {
nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
mapping_util_->AddTypeConversion(mapping_util_, tensor_index,
kTfLiteFloat32);
}
break;
case kTfLiteUInt8:
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
scale = tensor->params.scale;
zeroPoint = tensor->params.zero_point;
if (scale == 0) {
// ANEURALNETWORKS_TENSOR_QUANT8_ASYMM with zero scale is not valid in
// NNAPI.
scale = 1;
}
break;
case kTfLiteInt8:
// If explicit int8 conversion is needed, we still need
// ANEURALNETWORKS_TENSOR_QUANT8_ASYMM type.
if (use_int8_asymm_signed) {
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED;
} else if (need_int8_conversion) {
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
} else {
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_SYMM;
}
scale = tensor->params.scale;
zeroPoint = tensor->params.zero_point;
if (tensor->quantization.type == kTfLiteAffineQuantization) {
TfLiteAffineQuantization* quantization_params =
static_cast<TfLiteAffineQuantization*>(
tensor->quantization.params);
if (quantization_params->scale->size > 1 || force_per_channel) {
// Set up per-channel quantization.
ann_perchannel_params = {
.channelDim = static_cast<uint32_t>(
quantization_params->quantized_dimension),
.scaleCount =
static_cast<uint32_t>(quantization_params->scale->size),
.scales = quantization_params->scale->data,
};
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL;
scale = 0.0f;
zeroPoint = 0;
} else if (quantization_params->scale->size == 1) {
scale = quantization_params->scale->data[0];
zeroPoint = quantization_params->zero_point->data[0];
}
}
if (nn_type != ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) {
if (need_int8_conversion) {
zeroPoint += 128;
mapping_util_->AddTypeConversion(mapping_util_, tensor_index,
kTfLiteUInt8);
}
if (scale == 0) {
// QUANT8 tensors with zero scale are not valid in NNAPI.
scale = 1;
}
}
break;
case kTfLiteInt32:
nn_type = ANEURALNETWORKS_TENSOR_INT32;
scale = tensor->params.scale;
zeroPoint = tensor->params.zero_point;
break;
case kTfLiteBool:
nn_type = ANEURALNETWORKS_TENSOR_BOOL8;
break;
case kTfLiteInt16:
nn_type = ANEURALNETWORKS_TENSOR_QUANT16_SYMM;
scale = tensor->params.scale;
zeroPoint = tensor->params.zero_point;
break;
default:
context_->ReportError(
context_, "Failed to add NN API tensor: type %s is not supported.",
TfLiteTypeGetName(tensor_type));
return kTfLiteError;
}
bool has_unspecified_dimensions = ::tflite::HasUnspecifiedDimension(tensor);
uint32_t tensor_rank = static_cast<uint32_t>(tensor->dims->size);
std::vector<uint32_t> dims_unspecified(tensor_rank, 0);
if (has_unspecified_dimensions) {
for (int i = 0; i < tensor->dims_signature->size; i++) {
dims_unspecified[i] = tensor->dims_signature->data[i] == -1
? 0
: tensor->dims_signature->data[i];
}
}
uint32_t* tensor_dims =
has_unspecified_dimensions && allow_dynamic_dimensions_
? dims_unspecified.data()
: reinterpret_cast<uint32_t*>(tensor->dims->data);
if (scalar_as_tensor && tensor_rank == 0) {
// Use rank 1, shape {1} operand for TFLite scalar tensors.
tensor_rank = 1;
tensor_dims = &tensor_rank;
}
if (tensor_rank == 0) {
// if the tensor_rank is 0, the dimension ptr must be nullptr.
tensor_dims = nullptr;
}
ANeuralNetworksOperandType operand_type{nn_type, tensor_rank, tensor_dims,
scale, zeroPoint};
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", tensor, nnapi_errno_);
if (nn_type == ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) {
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context_,
nnapi_->ANeuralNetworksModel_setOperandSymmPerChannelQuantParams(
nn_model_, ann_tensor_index, &ann_perchannel_params),
"setting new operand per channel quantization params", tensor,
nnapi_errno_);
}
if (tensor->allocation_type == kTfLiteMmapRo) {
if (IsQuantized(tensor_type) && need_int8_conversion &&
nn_type != ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) {
// We need to add a tensor and convert the weights into uint8.
// Currently this is only needed for fully_connected. The new_tensor is
// needed for lifetime management for the converted weights.
int new_tensor_index = -1;
TF_LITE_ENSURE_OK(context_,
context_->AddTensors(context_, 1, &new_tensor_index));
TfLiteTensor* new_tensor = &context_->tensors[new_tensor_index];
new_tensor->type = kTfLiteUInt8;
new_tensor->allocation_type = kTfLiteDynamic;
new_tensor->params.scale = scale;
new_tensor->params.zero_point = zeroPoint;
// Not removing the new tensor in case of resizing errors since it will
// be cleared by the context
TF_LITE_ENSURE_OK(
context_, context_->ResizeTensor(context_, new_tensor,
// Resize Tensor takes ownership of
// the dims array passed as param
TfLiteIntArrayCopy(tensor->dims)));
// Convert the int8 value into corresponding uint8 value;
const auto num_elements = NumElements(tensor);
for (int i = 0; i < num_elements; ++i) {
new_tensor->data.uint8[i] = static_cast<const uint8_t>(
static_cast<int32_t>(tensor->data.int8[i]) + 128);
}
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_tensor_index, new_tensor->data.raw,
new_tensor->bytes),
"setting new operand value", tensor, nnapi_errno_);
} else if (tensor_type == kTfLiteFloat16 && need_half2float_conversion) {
// We need to convert the constant fp16 weights to fp32. The new_tensor
// is needed for lifetime management for the converted weights.
int new_tensor_index = -1;
TF_LITE_ENSURE_OK(context_,
context_->AddTensors(context_, 1, &new_tensor_index));
TfLiteTensor* new_tensor = &context_->tensors[new_tensor_index];
new_tensor->type = kTfLiteFloat32;
new_tensor->allocation_type = kTfLiteDynamic;
// Not removing the new tensor in case of resizing errors since it will
// be cleared by the context
TF_LITE_ENSURE_OK(
context_, context_->ResizeTensor(context_, new_tensor,
// Resize Tensor takes ownership of
// the dims array passed as param
TfLiteIntArrayCopy(tensor->dims)));
// Convert the fp16 value into corresponding fp32 value;
const auto num_elements = NumElements(tensor);
for (int i = 0; i < num_elements; ++i) {
new_tensor->data.f[i] = fp16_ieee_to_fp32_value(
reinterpret_cast<uint16_t*>(tensor->data.data)[i]);
}
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_tensor_index, new_tensor->data.data,
new_tensor->bytes),
"setting new operand value", tensor, nnapi_errno_);
#ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING
} else if (tensor->allocation &&
static_cast<const Allocation*>(tensor->allocation)->type() ==
Allocation::Type::kMMap) {
const MMAPAllocation* mmap_alloc =
static_cast<const MMAPAllocation*>(tensor->allocation);
if (allocation_memory_mapping_->count(mmap_alloc) == 0) {
ANeuralNetworksMemory* ann_memory_handle = nullptr;
nnapi_->ANeuralNetworksMemory_createFromFd(
mmap_alloc->bytes(), PROT_READ, mmap_alloc->fd(), 0,
&ann_memory_handle);
allocation_memory_mapping_->insert(
std::make_pair(mmap_alloc, ann_memory_handle));
}
ANeuralNetworksMemory* ann_memory_handle =
allocation_memory_mapping_->at(mmap_alloc);
// Compute the offset to the base pointer of the MMAPAllocation.
auto offset = reinterpret_cast<const uint8_t*>(tensor->data.raw) -
reinterpret_cast<const uint8_t*>(mmap_alloc->base());
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValueFromMemory(
nn_model_, ann_tensor_index, ann_memory_handle, offset,
tensor->bytes),
"setting new operand value from memory", tensor, nnapi_errno_);
#endif
} else {
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_tensor_index, tensor->data.data, tensor->bytes),
"setting new operand value", tensor, nnapi_errno_);
}
}
indices->push_back(ann_tensor_index);
return kTfLiteOk;
}
// Access to NNAPI.
const NnApi* const nnapi_;
// TfLiteContext for error handling.
TfLiteContext* const context_;
// Tracks relationship between indices.
NnapiMappingUtilCInterface* const mapping_util_;
// Keeps mapping of ANN quantized tensor and float data type to equivalent
// dequantized ANN tensor. For example, tensor #4 (UINT8) + FLOAT32 could map
// to tensor #10 (FLOAT32) because a DEQUANTIZE operator was added to convert
// tensor #4 to a FLOAT32 tensor.
DequantizeMapping* const dequantize_mapping_;
std::map<const MMAPAllocation*, ANeuralNetworksMemory*>* const
allocation_memory_mapping_;
// The NNAPI model.
ANeuralNetworksModel* const nn_model_;
// Inputs and outputs for the current op. These are augmented in the sense
// that NN API uses operands for all arguments, not just tensors, unlike
// TensorFlow Lite.
std::vector<uint32_t> augmented_inputs_;
std::vector<uint32_t> augmented_outputs_;
// Return status code of the latest NNAPI call.
int* nnapi_errno_;
// Whether to allow dynamic batch size without re-compilation.
bool allow_dynamic_dimensions_;
}; // namespace nnapi
namespace {
struct OpValidationContext {
bool is_valid;
std::vector<NNAPIValidationFailure>* validation_failures;
};
#define EXPECT_INPUT_TYPE_IN(actual_type, ...) \
ExpectTypeIn(actual_type, {__VA_ARGS__}, \
NNAPIValidationFailureType::kUnsupportedInputType, \
"Input type not in expected list " #__VA_ARGS__, &val_ctx)
inline void AddValidationFailure(NNAPIValidationFailureType failure_type,
const char* message,
OpValidationContext* val_ctx) {
val_ctx->is_valid = false;
#ifdef NNAPI_VERBOSE_VALIDATION
if (val_ctx->validation_failures) {
val_ctx->validation_failures->push_back({failure_type, message});
}
#endif
}
template <typename... Args>
inline void AddValidationFailureFmt(OpValidationContext* val_ctx,
NNAPIValidationFailureType failure_type,
const char* message_fmt, Args... args) {
val_ctx->is_valid = false;
#ifdef NNAPI_VERBOSE_VALIDATION
if (val_ctx->validation_failures) {
size_t req_buf_size = snprintf(nullptr, 0, message_fmt, args...) + 1;
std::unique_ptr<char[]> tmp_buf(new char[req_buf_size]);
snprintf(tmp_buf.get(), req_buf_size, message_fmt, args...);
val_ctx->validation_failures->push_back({failure_type, tmp_buf.get()});
}
#endif
}
inline bool Expect(bool condition, NNAPIValidationFailureType failure_type,
const char* message, OpValidationContext* val_ctx) {
if (!condition) {
AddValidationFailure(failure_type, message, val_ctx);
return false;
}
return true;
}
template <typename... Args>
inline bool ExpectFmt(bool condition, OpValidationContext* val_ctx,
NNAPIValidationFailureType failure_type,
const char* message_fmt, Args... args) {
if (!condition) {
AddValidationFailureFmt(val_ctx, failure_type, message_fmt, args...);
return false;
}
return true;
}
inline bool ExpectTypeIn(TfLiteType actual_type,
std::initializer_list<TfLiteType> allowed_types,
NNAPIValidationFailureType failure_type,
const char* msg, OpValidationContext* val_ctx) {
return Expect(std::find(allowed_types.begin(), allowed_types.end(),
actual_type) != allowed_types.end(),
failure_type, msg, val_ctx);
}
inline bool ExpectMinAndroidSdkVersion(int curr_version, int min_version,
OpValidationContext* val_ctx) {
return ExpectFmt(curr_version >= min_version, val_ctx,
NNAPIValidationFailureType::kUnsupportedAndroidVersion,
"Android sdk version less than %d", min_version);
}
inline bool ExpectMaxOpVersion(int curr_version, int max_version,
OpValidationContext* val_ctx) {
return ExpectFmt(curr_version <= max_version, val_ctx,
NNAPIValidationFailureType::kUnsupportedOperatorVersion,
"OP Version higher than %d", max_version);
}
inline bool ExpectOpVersion(int curr_version, int max_version,
OpValidationContext* val_ctx) {
return ExpectFmt(curr_version <= max_version, val_ctx,
NNAPIValidationFailureType::kUnsupportedOperatorVersion,
"OP Version different from %d", max_version);
}
inline bool ExpectIsFloatOperator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloat(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float", val_ctx);
}
bool ExpectIsFloatOrUint8Operator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloatOrUInt8(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float or UINT8", val_ctx);
}
bool ExpectIsFloatOrQuant8Operator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloatOrQuantized(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float or Quant8", val_ctx);
}
bool ExpectIsFloatOrInt32Operator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloatOrInt32(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float or Int32", val_ctx);
}
bool ExpectIsFloatQuant8OrInt32Operator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloatQuantizedOrInt32(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float, Quant8, or Int32", val_ctx);
}
// When using NN API version 1.0 or 1.1, the condition below must be true for
// quantized versions of the following ops:
// * CONV_2D
// * DEPTHWISE_CONV_2D
// * FULLY_CONNECTED (where filter actually stands for weights)
// The condition is relaxed and no longer required since version 1.2.
bool ExpectIsRestrictedScalesCompliant(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const int input_id = node->inputs->data[0];
const int filter_id = node->inputs->data[1];
const int output_id = node->outputs->data[0];
const float input_scale = context->tensors[input_id].params.scale;
const float filter_scale = context->tensors[filter_id].params.scale;
const float output_scale = context->tensors[output_id].params.scale;
return Expect(input_scale * filter_scale < output_scale,
NNAPIValidationFailureType::kNotRestrictedScaleCompliant,
"When using NN API version 1.0 or 1.1, input_scale * "
"filter_scale < output_scale.",
val_ctx);
}
void AppendDynamicDimensions(const TfLiteContext* context,
const TfLiteIntArray* tensor_indices,
std::vector<int>& dynamic_dimensions) {
for (int i : TfLiteIntArrayView(tensor_indices)) {
if (i == kTfLiteOptionalTensor) continue;
const auto& tensor = context->tensors[i];
if (tensor.dims_signature) {
for (int i = 0; i < tensor.dims_signature->size; i++) {
if (tensor.dims_signature->data[i] == -1) {
dynamic_dimensions.push_back(tensor.dims->data[i]);
}
}
}
}
}
NNAPIExecutionCache::Signature CreateExecutionCacheSignature(
const TfLiteContext* context, const TfLiteNode* node,
const StatefulNnApiDelegate::Options& delegate_options,
const std::vector<StatefulNnApiDelegate::MemoryRegistration>&
tensor_memory_map) {
// Tensor buffer handle timestamps.
std::vector<uint64_t> tensor_handle_timestamps(context->tensors_size);
for (int i = 0; i < tensor_handle_timestamps.size(); i++) {
auto handle = context->tensors[i].buffer_handle;
if (handle < 0 || handle >= tensor_memory_map.size()) {
tensor_handle_timestamps[i] = kNoMemoryTimestamp;
} else {
tensor_handle_timestamps[i] = tensor_memory_map[handle].timestamp;
}
}
// Dynamic dimensions.
std::vector<int> dynamic_dimensions;
if (delegate_options.allow_dynamic_dimensions) {
AppendDynamicDimensions(context, node->inputs, dynamic_dimensions);
// When using custom ops, we cannot infer output shapes, so it is not part
// of the execution request.
if (delegate_options.vendor_plugin == nullptr) {
AppendDynamicDimensions(context, node->outputs, dynamic_dimensions);
}
}
return NNAPIExecutionCache::Signature{std::move(tensor_handle_timestamps),
std::move(dynamic_dimensions)};
}
template <typename T>
std::size_t HashVector(const std::vector<T>& vec) {
std::size_t seed = vec.size();
auto hasher = std::hash<T>{};
for (const auto& i : vec) {
seed = CombineHashes({seed, hasher(i)});
}
return seed;
}
} // namespace
bool NNAPIExecutionCache::Signature::operator==(const Signature& other) const {
return tensor_handle_timestamps == other.tensor_handle_timestamps &&
dynamic_dimensions == other.dynamic_dimensions;
}
std::size_t NNAPIExecutionCache::Signature::Hasher::operator()(
const Signature& signature) const {
return CombineHashes({HashVector(signature.tensor_handle_timestamps),
HashVector(signature.dynamic_dimensions)});
}
ANeuralNetworksExecution* NNAPIExecutionCache::Get(const Signature& signature) {
auto it = lookup_.find(signature);
// Cache miss
if (it == lookup_.end()) {
return nullptr;
}
// Cache hit, put the entry to the front
auto& list_it = it->second.first;
order_.erase(list_it);
order_.push_front(signature);
// Update the iterator in the lookup_ map
list_it = order_.begin();
auto& execution = it->second.second;
return execution.get();
}
void NNAPIExecutionCache::Put(const Signature& signature,
UniqueExecution execution) {
// Release the least recently used cache if cache is full.
if (order_.size() >= max_cache_size_) {
ReleaseLRU();
}
// Register the new cache.
order_.push_front(signature);
lookup_.emplace(signature,
std::make_pair(order_.begin(), std::move(execution)));
}
void NNAPIExecutionCache::Clear() {
order_.clear();
lookup_.clear();
}
void NNAPIExecutionCache::SetMaxCacheSize(uint32_t max_cache_size) {
max_cache_size_ = max_cache_size;
while (order_.size() > max_cache_size_) {
ReleaseLRU();
}
}
void NNAPIExecutionCache::ReleaseLRU() {
lookup_.erase(order_.back());
order_.pop_back();
}
// Return a function that knows how to translate a node into its operands
// when called. You can use this function to see if a node is supported
// (i.e. if the returned MappingFn is null, then the node is not supported).
bool NNAPIDelegateKernel::Validate(
const TfLiteContext* context, const TfLiteRegistration* registration,
int android_sdk_version, const TfLiteNode* node,
bool is_accelerator_specified, NnapiDelegateVendorPlugin* vendor_plugin,
std::vector<NNAPIValidationFailure>* map_failures) {
OpValidationContext val_ctx{true, map_failures};
if (vendor_plugin) {
if (vendor_plugin->ValidateNode(context, registration, node)) {
return true;
}
}
auto builtin_code = registration->builtin_code;
auto version = registration->version;
switch (builtin_code) {
case kTfLiteBuiltinAdd: {
ExpectMaxOpVersion(version, 2, &val_ctx);
if (android_sdk_version >= kMinSdkVersionForNNAPI13) {
ExpectIsFloatQuant8OrInt32Operator(context, node, &val_ctx);
if (IsInt32(context->tensors[node->inputs->data[0]].type)) {
Expect(reinterpret_cast<TfLiteAddParams*>(node->builtin_data)
->activation == kTfLiteActNone,
NNAPIValidationFailureType::kNoActivationExpected,
"No activation function supported", &val_ctx);
}
} else {
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
}
} break;
case kTfLiteBuiltinArgMax:
case kTfLiteBuiltinArgMin: {
ExpectMaxOpVersion(version, 2, &val_ctx);
// Those operators were introduced in NNAPI 1.2.
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[(0)]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat16, kTfLiteFloat32,
kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8);
const auto& axis_tensor = context->tensors[node->inputs->data[1]];
if (axis_tensor.type == kTfLiteInt64) {
Expect(
axis_tensor.allocation_type == kTfLiteMmapRo &&
*axis_tensor.data.i64 <= std::numeric_limits<int32_t>::max() &&
*axis_tensor.data.i64 >= std::numeric_limits<int32_t>::min(),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports axis as int32. If the axis type is int64 and "
"constant we can convert it to int32 if the value isn't too "
"large.",
&val_ctx);
} else {
Expect(axis_tensor.type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Axis should be Int32", &val_ctx);
}
if (builtin_code == kTfLiteBuiltinArgMax) {
auto builtin =
reinterpret_cast<TfLiteArgMaxParams*>(node->builtin_data);
Expect(builtin->output_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI only supports int32 output.", &val_ctx);
} else {
auto builtin =
reinterpret_cast<TfLiteArgMinParams*>(node->builtin_data);
Expect(builtin->output_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI only supports int32 output.", &val_ctx);
}
} break;
case kTfLiteBuiltinMul: {
if (is_accelerator_specified) {
ExpectMaxOpVersion(version, 3, &val_ctx);
} else {
ExpectMaxOpVersion(version, 2, &val_ctx);
}
if (android_sdk_version >= kMinSdkVersionForNNAPI13) {
ExpectIsFloatQuant8OrInt32Operator(context, node, &val_ctx);
if (IsInt32(context->tensors[node->inputs->data[0]].type)) {
Expect(reinterpret_cast<TfLiteMulParams*>(node->builtin_data)
->activation == kTfLiteActNone,
NNAPIValidationFailureType::kNoActivationExpected,
"No activation function supported", &val_ctx);
}
} else {
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
}
} break;
case kTfLiteBuiltinAveragePool2d: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
auto builtin = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
// TODO(b/138756912): Large filter window would overflow on the
// quantized reference CPU path.
if (IsQuantized(context->tensors[node->inputs->data[0]].type)) {
Expect(is_accelerator_specified ||
(builtin->filter_width * builtin->filter_height <= 256),
NNAPIValidationFailureType::kUnsupportedOperandSize,
"Large filter window would overflow on the reference CPU path",
&val_ctx);
}
} break;
case kTfLiteBuiltinMaxPool2d: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinL2Pool2d: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
auto builtin = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
Expect(builtin->activation == kTfLiteActNone,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"Before NNAPI 1.2 fused activation for l2_pool may not be "
"supported.",
&val_ctx);
}
} break;
case kTfLiteBuiltinConv2d: {
ExpectMaxOpVersion(version, 5, &val_ctx);
const auto& input_tensor = context->tensors[node->inputs->data[0]];
const auto& filter_tensor = context->tensors[node->inputs->data[1]];
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid operators not supported before NNAPI 1.2", &val_ctx);
ExpectIsFloatOrUint8Operator(context, node, &val_ctx);
if (filter_tensor.quantization.type == kTfLiteAffineQuantization) {
TfLiteAffineQuantization* quantization_params =
static_cast<TfLiteAffineQuantization*>(
filter_tensor.quantization.params);
Expect(quantization_params->scale->size <= 1,
NNAPIValidationFailureType::kUnsupportedQuantizationType,
"Per-channel quantized convolution not supported before NNAPI "
"1.2.",
&val_ctx);
}
}
const auto input_type = input_tensor.type;
if (android_sdk_version < kMinSdkVersionForNNAPI12 &&
input_type == kTfLiteUInt8) {
ExpectIsRestrictedScalesCompliant(context, node, &val_ctx);
}
auto builtin = reinterpret_cast<TfLiteConvParams*>(node->builtin_data);
// TODO(b/132950584): Add support for Conv2D with omitted bias.
Expect(node->inputs->size == 3,
NNAPIValidationFailureType::kMissingRequiredOperand,
"Conv2D with omitted bias not supported", &val_ctx);
if (builtin->dilation_width_factor != 1 ||
builtin->dilation_height_factor != 1) {
Expect(android_sdk_version >= kMinSdkVersionForNNAPI12,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI supports dilated Conv2D since NNAPI 1.2.", &val_ctx);
}
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(input_tensor.dims->data[3] == filter_tensor.dims->data[3],
NNAPIValidationFailureType::kUnsupportedOperandValue,
"Grouped convolution not supported before NNAPI < 1.2",
&val_ctx);
}
} break;
case kTfLiteBuiltinDepthwiseConv2d: {
ExpectMaxOpVersion(version, 3, &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
ExpectIsFloatOrUint8Operator(context, node, &val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
if (input_type == kTfLiteUInt8) {
ExpectIsRestrictedScalesCompliant(context, node, &val_ctx);
}
auto builtin =
reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data);
Expect(builtin->dilation_width_factor == 1 &&
builtin->dilation_height_factor == 1,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"dilation_width_factor and dilation_height_factor expected to "
"be equal to 1",
&val_ctx);
}
} break;
case kTfLiteBuiltinFullyConnected: {
ExpectMaxOpVersion(version, 5, &val_ctx);
const auto output_type = context->tensors[node->outputs->data[0]].type;
Expect(output_type != kTfLiteInt16,
NNAPIValidationFailureType::kUnsupportedOutputType,
"Unsupported output of type kTfLiteInt16", &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid operators not supported before NNAPI 1.2", &val_ctx);
ExpectIsFloatOrUint8Operator(context, node, &val_ctx);
}
const auto input_type = context->tensors[node->inputs->data[0]].type;
if (android_sdk_version < kMinSdkVersionForNNAPI12 &&
input_type == kTfLiteUInt8) {
ExpectIsRestrictedScalesCompliant(context, node, &val_ctx);
}
auto builtin =
reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data);
if (builtin->keep_num_dims) {
ExpectMinAndroidSdkVersion(android_sdk_version,
kMinSdkVersionForNNAPI13, &val_ctx);
}
} break;
case kTfLiteBuiltinHardSwish: {
// Add support for hardswish. For Pre-Q devices, deconstructing it into
// basic ops. Though for some nnapi accelerators using optimized tflite
// kernels might even be faster.
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinSoftmax: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
const auto& output = context->tensors[node->outputs->data[0]];
ExpectTypeIn(output.type, {kTfLiteFloat32, kTfLiteUInt8, kTfLiteInt8},
NNAPIValidationFailureType::kUnsupportedOutputType,
"Output type should be one of kTfLiteFloat32, kTfLiteUInt8, "
"kTfLiteInt8.",
&val_ctx);
const auto& input = context->tensors[node->inputs->data[0]];
const int input_rank = input.dims->size;
Expect(input_rank <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input rank should be <= 4", &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(
input_rank == 2 || input_rank == 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Before API level 29 only 2D and 4D input tensors were supported.",
&val_ctx);
}
} break;
case kTfLiteBuiltinReshape: {
ExpectOpVersion(version, 1, &val_ctx);
if (android_sdk_version < kNNAPIRuntimeFeatureLevel6) {
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} else {
ExpectIsFloatQuant8OrInt32Operator(context, node, &val_ctx);
}
const auto& input = context->tensors[node->inputs->data[0]];
Expect(input.dims->size <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input rank should be <= 4", &val_ctx);
const auto& output = context->tensors[node->outputs->data[0]];
Expect(output.dims->size <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Output rank should be <= 4", &val_ctx);
if (node->inputs->size >= 2) {
Expect(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo,
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"The shape input tensor must be constant.", &val_ctx);
}
if (node->inputs->size == 1) {
// reject scalar reshaping
auto* params =
reinterpret_cast<TfLiteReshapeParams*>(node->builtin_data);
int num_dimensions = params->num_dimensions;
if (num_dimensions == 1 && params->shape[0] == 0) {
// Legacy tflite models use a shape parameter of [0] to indicate
// scalars.
num_dimensions = 0;
}
Expect(num_dimensions > 0,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"New shape rank should be > 0", &val_ctx);
}
} break;
case kTfLiteBuiltinResizeBilinear: {
ExpectMaxOpVersion(version, 3, &val_ctx);
const auto& input = context->tensors[node->inputs->data[0]];
const auto output_dims = context->tensors[node->outputs->data[0]].dims;
Expect(input.dims->size == 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input should have rank 4", &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
Expect(node->inputs->size >= 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expected at least 2 inputs", &val_ctx);
if (node->inputs->size >= 2) {
Expect(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo,
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"The size input tensor must be constant.", &val_ctx);
}
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(output_dims->data[1] == output_dims->data[2],
NNAPIValidationFailureType::kUnsupportedOperandValue,
"Require width == height due to driver differences in NNAPI "
"< 1.2",
&val_ctx);
}
auto builtin =
reinterpret_cast<TfLiteResizeBilinearParams*>(node->builtin_data);
if (android_sdk_version <= kMinSdkVersionForNNAPI12) {
Expect(!builtin->align_corners,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support align_corners == true.", &val_ctx);
Expect(!builtin->half_pixel_centers,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support half_pixel_centers == true.", &val_ctx);
}
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(input.type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI 1.0 & 1.1 only supports float input.", &val_ctx);
}
} break;
case kTfLiteBuiltinResizeNearestNeighbor: {
ExpectMaxOpVersion(version, 3, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
Expect(node->inputs->size >= 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expected at least 2 inputs", &val_ctx);
if (node->inputs->size >= 2) {
Expect(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo,
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"The size input tensor must be constant.", &val_ctx);
}
auto builtin = reinterpret_cast<TfLiteResizeNearestNeighborParams*>(
node->builtin_data);
if (android_sdk_version <= kMinSdkVersionForNNAPI12) {
Expect(!builtin->align_corners,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support align_corners == true.", &val_ctx);
Expect(!builtin->half_pixel_centers,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support half_pixel_centers == true.", &val_ctx);
}
} break;
case kTfLiteBuiltinSqueeze: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
auto builtin = reinterpret_cast<TfLiteSqueezeParams*>(node->builtin_data);
if (android_sdk_version == kMinSdkVersionForNNAPI11) {
Expect(builtin->num_squeeze_dims != 0,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI 1.1 does not support null squeeze_dims properly.",
&val_ctx);
}
} break;
case kTfLiteBuiltinUnidirectionalSequenceLstm: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid version of this op is not supported by NN API.", &val_ctx);
Expect(node->inputs->size == 20 || node->inputs->size == 24,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Supporting only operation with 20 or 24 inputs", &val_ctx);
} break;
case kTfLiteBuiltinL2Normalization: {
ExpectMaxOpVersion(version, 2, &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
ExpectIsFloatOperator(context, node, &val_ctx);
const auto& input = context->tensors[node->inputs->data[0]];
Expect(input.dims->size == 4,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expected 4 inputs", &val_ctx);
}
auto builtin = reinterpret_cast<TfLiteL2NormParams*>(node->builtin_data);
Expect(builtin->activation == kTfLiteActNone,
NNAPIValidationFailureType::kNoActivationExpected,
"Expected no activation", &val_ctx);
} break;
case kTfLiteBuiltinLocalResponseNormalization: {
ExpectOpVersion(version, 1, &val_ctx);
} break;
case kTfLiteBuiltinLshProjection: {
ExpectOpVersion(version, 1, &val_ctx);
if (reinterpret_cast<TfLiteLSHProjectionParams*>(node->builtin_data)
->type == kTfLiteLshProjectionSparse) {
// NNAPI does not support sparse projection correctly pre-Q
// (b/111751836).
Expect(android_sdk_version >= kMinSdkVersionForNNAPI12,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI does not support sparse projection correctly pre-Q",
&val_ctx);
Expect(node->inputs->size == 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
" NNAPI does not support weights for sparse projects.",
&val_ctx);
}
} break;
case kTfLiteBuiltinConcatenation: {
ExpectMaxOpVersion(version, 2, &val_ctx);
Expect(reinterpret_cast<TfLiteConcatenationParams*>(node->builtin_data)
->activation == kTfLiteActNone,
NNAPIValidationFailureType::kNoActivationExpected,
"No activation function supported", &val_ctx);
Expect(context->tensors[node->inputs->data[0]].dims->size <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input rank should be less than 4", &val_ctx);
const auto& input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat16, kTfLiteFloat32,
kTfLiteUInt8, kTfLiteInt8);
if (input_type == kTfLiteUInt8 &&
android_sdk_version < kMinSdkVersionForNNAPI12) {
auto first_param = context->tensors[node->inputs->data[0]].params;
for (int i = 1; i < node->inputs->size; i++) {
auto curr_param = context->tensors[node->inputs->data[i]].params;
if (!Expect(curr_param.scale == first_param.scale &&
curr_param.zero_point == first_param.zero_point,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI 1.0-1 only supported concatenating quantized "
"tensor of the same scale and offset.",
&val_ctx)) {
break;
}
}
}
} break;
case kTfLiteBuiltinDequantize: {
// Allow dequantizing fp16->fp32.
if (android_sdk_version >= kMinSdkVersionForNNAPI13 &&
context->tensors[node->inputs->data[0]].type == kTfLiteFloat16 &&
context->tensors[node->inputs->data[0]].allocation_type !=
kTfLiteMmapRo) {
return true;
}
Expect(version == 1 || version == 2,
NNAPIValidationFailureType::kUnsupportedOperatorVersion,
"Supported op versions are 1 and 2 only", &val_ctx);
const auto& input = context->tensors[node->inputs->data[0]];
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
EXPECT_INPUT_TYPE_IN(input.type, kTfLiteUInt8);
} else {
EXPECT_INPUT_TYPE_IN(input.type, kTfLiteUInt8, kTfLiteInt8);
if (android_sdk_version == kMinSdkVersionForNNAPI12 &&
input.type == kTfLiteInt8) {
const auto zero_point = input.params.zero_point;
Expect(zero_point == 0,
NNAPIValidationFailureType::kUnsupportedInputType,
"NN API supports int8 type since version 1.2 but only for "
"symmetric quantization.",
&val_ctx);
}
}
} break;
case kTfLiteBuiltinDensify: {
// Allow densifying sparse weights.
if (android_sdk_version >= kMinSdkVersionForNNAPI13 &&
context->tensors[node->inputs->data[0]].allocation_type ==
kTfLiteMmapRo) {
return true;
}
return false;
} break;
case kTfLiteBuiltinFloor: {
ExpectOpVersion(version, 1, &val_ctx);
} break;
case kTfLiteBuiltinRelu:
case kTfLiteBuiltinReluN1To1:
case kTfLiteBuiltinRelu6:
case kTfLiteBuiltinLogistic: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinTanh: {
ExpectMaxOpVersion(version, 2, &val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
Expect(IsFloat(input_type) ||
(IsQuantized(input_type) &&
android_sdk_version >= kMinSdkVersionForNNAPI12),
NNAPIValidationFailureType::kUnsupportedInputType,
" NNAPI only support float tanh.", &val_ctx);
} break;
case kTfLiteBuiltinSub: {
ExpectMaxOpVersion(version, 3, &val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
Expect((android_sdk_version >= kMinSdkVersionForNNAPI11 &&
IsFloat(input_type)) ||
(android_sdk_version >= kMinSdkVersionForNNAPI12 &&
IsQuantized(input_type)) ||
(android_sdk_version >= kMinSdkVersionForNNAPI13 &&
IsInt32(input_type)),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float sub.", &val_ctx);
if (IsInt32(input_type)) {
Expect(reinterpret_cast<TfLiteSubParams*>(node->builtin_data)
->activation == kTfLiteActNone,
NNAPIValidationFailureType::kNoActivationExpected,
"No activation function supported", &val_ctx);
}
const int input0_rank =
context->tensors[node->inputs->data[0]].dims->size;
const int input1_rank =
context->tensors[node->inputs->data[1]].dims->size;
Expect(input0_rank <= 4 && input1_rank <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input rank must be <= 4", &val_ctx);
} break;
case kTfLiteBuiltinDiv: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float div.", &val_ctx);
} break;
case kTfLiteBuiltinPad:
case kTfLiteBuiltinPadv2: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
const TfLiteIntArrayView input_shape(
context->tensors[node->inputs->data[0]].dims);
Expect(!HasZeroes(input_shape),
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NN API pad ops do not support input tensors with no elements",
&val_ctx);
Expect(node->inputs->size >= 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expecting at least 2 inputs", &val_ctx);
if (node->inputs->size == 3) {
// This is going to be mapped with a PadV2
Expect(
android_sdk_version >= kMinSdkVersionForNNAPI12,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Specification of the padding value is supported from NNAPI 1.2.",
&val_ctx);
} else { // this is going to be mapped as Pad
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Only Float32 inputs are supported before NNAPI 1.2",
&val_ctx);
}
}
} break;
case kTfLiteBuiltinUnidirectionalSequenceRnn: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid version of this op is not supported by NN API.", &val_ctx);
} break;
case kTfLiteBuiltinSpaceToBatchNd: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
} break;
case kTfLiteBuiltinBatchToSpaceNd: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
auto crops = context->tensors[node->inputs->data[2]];
auto crops_data = crops.data.i32;
Expect(crops_data && crops.bytes == 16 && crops_data[0] == 0 &&
crops_data[1] == 0 && crops_data[2] == 0 && crops_data[3] == 0,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"All crops should be 0.", &val_ctx);
} break;
case kTfLiteBuiltinStridedSlice: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
} break;
case kTfLiteBuiltinTranspose: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
// Note that the permutation input tensor value dictates the output
// dimensions.
// TODO(b/110888333): Support dynamically-sized tensors in delegates.
Expect((node->inputs->size > 1) &&
(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Dynamically-sized tensors not supported.", &val_ctx);
} break;
case kTfLiteBuiltinAbs:
case kTfLiteBuiltinExp:
case kTfLiteBuiltinLog:
case kTfLiteBuiltinPow: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinRsqrt: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
if (android_sdk_version < kNNAPIRuntimeFeatureLevel7) {
ExpectIsFloatOperator(context, node, &val_ctx);
} else {
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
}
} break;
case kTfLiteBuiltinSlice: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
const auto begin_type = context->tensors[node->inputs->data[1]].type;
const auto size_type = context->tensors[node->inputs->data[2]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8, kTfLiteInt8);
Expect(begin_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Begin type should be Int32", &val_ctx);
Expect(size_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Size type should be Int32", &val_ctx);
} break;
case kTfLiteBuiltinSin: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinTransposeConv: {
ExpectMaxOpVersion(version, 3, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect((node->inputs->size > 1) &&
(context->tensors[node->inputs->data[0]].allocation_type ==
kTfLiteMmapRo) &&
(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Dynamically-sized tensors not supported.", &val_ctx);
} break;
case kTfLiteBuiltinSqrt: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinRnn: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(node->inputs->size == 5,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expected 5 input", &val_ctx);
if (node->inputs->size >= 2) {
Expect(
context->tensors[node->inputs->data[/*kWeightsTensor*/ 1]].type ==
kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float32 weights.", &val_ctx);
}
} break;
case kTfLiteBuiltinSpaceToDepth: {
ExpectMaxOpVersion(version, 2, &val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8);
} break;
case kTfLiteBuiltinSvdf: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(node->inputs->size == 5,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Expected input of rank 5", &val_ctx);
if (node->inputs->size >= 2) {
Expect(
context->tensors[node->inputs->data[/*kWeightsTensor*/ 1]].type ==
kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float32 weights.", &val_ctx);
}
Expect(android_sdk_version >= kMinSdkVersionForNNAPI11,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"SVDF does not support rank > 1 on NNAPI 1.0.", &val_ctx);
Expect(context->tensors[node->inputs->data[/*kWeightsFeatureTensor*/ 1]]
.type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Weights should be Float32", &val_ctx);
} break;
case kTfLiteBuiltinLstm: {
ExpectMaxOpVersion(version, 3, &val_ctx);
Expect(
android_sdk_version >= kMinSdkVersionForNNAPI11,
NNAPIValidationFailureType::kUnsupportedAndroidVersion,
"NNAPI 1.0 has a bug for optional tensors which would affect LSTM.",
&val_ctx);
Expect(android_sdk_version >= kMinSdkVersionForNNAPI12 ||
!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid operators not supported before NNAPI 1.2.", &val_ctx);
const auto weight_input_index =
isLstmBasicKernel(node) ? 2 /* basic::kInputWeights */
: 4 /* full::kInputToOutputWeightsTensor */;
const TfLiteType weight_type =
context->tensors[node->inputs->data[weight_input_index]].type;
if (isLstmBasicKernel(node)) {
Expect(weight_type == kTfLiteUInt8,
NNAPIValidationFailureType::kUnsupportedInputType,
"Basic LSTM Kernels support only UINT8 weights", &val_ctx);
const auto input_quantization_params =
context->tensors[node->inputs->data[0]].params;
Expect(input_quantization_params.scale == 1. / 128. &&
input_quantization_params.zero_point == 128,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Invalid input quantization", &val_ctx);
const auto output_quantization_params =
context->tensors[node->outputs->data[0]].params;
Expect(output_quantization_params.scale == 1. / 128. &&
output_quantization_params.zero_point == 128,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Invalid output quantization", &val_ctx);
const auto cell_state_quantization_params =
context->tensors[node->outputs->data[1]].params;
Expect(cell_state_quantization_params.scale == 16. / 32768. ||
cell_state_quantization_params.zero_point == 0,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Invalid cell state quantization", &val_ctx);
auto is_const_tensor = [&node, &context](int tensor_idx) {
return context->tensors[node->inputs->data[tensor_idx]]
.allocation_type == kTfLiteMmapRo;
};
Expect(is_const_tensor(2 /* kInputWeights */),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Weights tensor should be constant", &val_ctx);
Expect(is_const_tensor(3 /* kInputBiases */),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Biases tensor should be constant", &val_ctx);
return val_ctx.is_valid;
} else {
if (node->inputs->size == 24) {
ExpectMinAndroidSdkVersion(android_sdk_version,
kMinSdkVersionForNNAPI12, &val_ctx);
}
if (android_sdk_version >= kMinSdkVersionForNNAPI13) {
Expect(weight_type == kTfLiteFloat32 || weight_type == kTfLiteUInt8 ||
weight_type == kTfLiteInt8,
NNAPIValidationFailureType::kUnsupportedInputType,
"Weight has to be Float32 or UINT8 or INT8", &val_ctx);
} else {
Expect(weight_type == kTfLiteFloat32 || weight_type == kTfLiteUInt8,
NNAPIValidationFailureType::kUnsupportedInputType,
"Weight has to be Float32 or UINT8", &val_ctx);
}
}
} break;
case kTfLiteBuiltinMean: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
if (android_sdk_version >= kMinSdkVersionForNNAPI12) {
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32 ||
IsQuantized(context->tensors[node->inputs->data[0]].type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Expected Float32 or Quantized input", &val_ctx);
} else {
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Expected Float32 input", &val_ctx);
}
Expect(context->tensors[node->outputs->data[0]].dims->size > 0,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI does not support generating a scalar as output for MEAN.",
&val_ctx);
} break;
case kTfLiteBuiltinEmbeddingLookup: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(context->tensors[node->inputs->data[1]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float32 values.", &val_ctx);
} break;
case kTfLiteBuiltinHashtableLookup: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(context->tensors[node->outputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI only support float32 output.", &val_ctx);
} break;
case kTfLiteBuiltinMaximum:
case kTfLiteBuiltinMinimum: {
ExpectMaxOpVersion(version, 3, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8, kTfLiteInt32);
const TfLiteTensor& operand0 = context->tensors[node->inputs->data[0]];
if (operand0.dims->size == 0) {
Expect(operand0.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"Scalar operand should be constant", &val_ctx);
}
const TfLiteTensor& operand1 = context->tensors[node->inputs->data[1]];
if (operand1.dims->size == 0) {
Expect(operand1.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"Scalar operand should be constant", &val_ctx);
}
} break;
case kTfLiteBuiltinCast: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
const TfLiteType output_type =
context->tensors[node->outputs->data[0]].type;
if (android_sdk_version >= kMinSdkVersionForNNAPI13) {
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8, kTfLiteInt8);
ExpectTypeIn(
output_type,
{kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8},
NNAPIValidationFailureType::kUnsupportedOutputType,
"Output type should be one of kTfLiteFloat32, kTfLiteInt32, "
"kTfLiteUInt8, kTfLiteInt8.",
&val_ctx);
} else {
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8);
ExpectTypeIn(
output_type, {kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8},
NNAPIValidationFailureType::kUnsupportedOutputType,
"Output type should be one of kTfLiteFloat32, kTfLiteInt32, "
"kTfLiteUInt8.",
&val_ctx);
}
} break;
case kTfLiteBuiltinLeakyRelu:
case kTfLiteBuiltinPrelu: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8);
} break;
case kTfLiteBuiltinTile: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt8,
kTfLiteUInt8, kTfLiteInt32);
const auto multipliers_type =
context->tensors[node->inputs->data[1]].type;
Expect(multipliers_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Multipliers should be Int32", &val_ctx);
} break;
case kTfLiteBuiltinLogicalOr:
case kTfLiteBuiltinLogicalAnd:
case kTfLiteBuiltinLogicalNot: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteBool,
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be bool", &val_ctx);
} break;
case kTfLiteBuiltinLess:
case kTfLiteBuiltinLessEqual:
case kTfLiteBuiltinGreater:
case kTfLiteBuiltinGreaterEqual:
case kTfLiteBuiltinEqual:
case kTfLiteBuiltinNotEqual: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8, kTfLiteBool, kTfLiteInt32);
} break;
case kTfLiteBuiltinNeg: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32);
} break;
case kTfLiteBuiltinTopkV2: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto& input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8, kTfLiteInt8);
const auto& k_param = context->tensors[node->inputs->data[1]];
Expect(k_param.type == kTfLiteInt32 &&
k_param.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"K param should be a constant of type Int32", &val_ctx);
} break;
case kTfLiteBuiltinSelect: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto value_type = context->tensors[node->inputs->data[1]].type;
EXPECT_INPUT_TYPE_IN(value_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8, kTfLiteInt8);
TfLiteIntArray* condition_shape =
context->tensors[node->inputs->data[0]].dims;
TfLiteIntArray* input_shape =
context->tensors[node->inputs->data[1]].dims;
Expect(TfLiteIntArrayEqual(condition_shape, input_shape),
NNAPIValidationFailureType::kUnsupportedOperandValue,
"Condition and inputs tensors should have the same shape",
&val_ctx);
} break;
case kTfLiteBuiltinGather: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
const auto& positions = context->tensors[node->inputs->data[1]];
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteFloat16,
kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8);
Expect(positions.type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Positions type should be one of kTfLiteInt32", &val_ctx);
Expect(positions.dims->size != 0,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"0-dimension args are not supported by NNAPI.", &val_ctx);
} break;
case kTfLiteBuiltinBidirectionalSequenceLstm: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid version of this op is not supported by NN API.", &val_ctx);
} break;
case kTfLiteBuiltinExpandDims: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteFloat16,
kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8);
const auto axis = context->tensors[node->inputs->data[1]];
Expect(axis.type == kTfLiteInt32 && axis.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports constant int32 axis tensor.", &val_ctx);
} break;
case kTfLiteBuiltinSplit: {
ExpectOpVersion(version, 3, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
// Tensor indices: split_dim: 0, value: 1
const TfLiteTensor& input = context->tensors[node->inputs->data[1]];
if (android_sdk_version >= kMinSdkVersionForNNAPI13) {
EXPECT_INPUT_TYPE_IN(input.type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8, kTfLiteInt32);
} else {
EXPECT_INPUT_TYPE_IN(input.type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt32);
}
const TfLiteTensor& axis = context->tensors[node->inputs->data[0]];
Expect(axis.type == kTfLiteInt32 && axis.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports constant int32 axis tensor.", &val_ctx);
} break;
case kTfLiteBuiltinSplitV: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI13,
&val_ctx);
// Tensor indices: value: 0, size_splits: 1, axis: 2
const TfLiteTensor& input = context->tensors[node->inputs->data[0]];
const TfLiteTensor& size_splits = context->tensors[node->inputs->data[1]];
const TfLiteTensor& axis = context->tensors[node->inputs->data[2]];
EXPECT_INPUT_TYPE_IN(input.type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8, kTfLiteInt32);
bool size_splits_is_int32_const_vector =
size_splits.type == kTfLiteInt32 && size_splits.dims->size == 1 &&
size_splits.allocation_type == kTfLiteMmapRo;
bool axis_is_int32_const =
axis.type == kTfLiteInt32 && axis.allocation_type == kTfLiteMmapRo;
Expect(size_splits_is_int32_const_vector,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports constant int32 size_splits vector.",
&val_ctx);
Expect(axis_is_int32_const,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports constant int32 axis tensor.", &val_ctx);
if (size_splits_is_int32_const_vector && axis_is_int32_const) {
Expect(std::all_of(size_splits.data.i32,
size_splits.data.i32 + size_splits.dims->data[0],
[](auto size) { return size != 0; }),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports non-zero split sizes.", &val_ctx);
Expect(ComputeSplitVUnknownSplitSize(context, node) != 0,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports non-zero split sizes.", &val_ctx);
}
} break;
case kTfLiteBuiltinLogSoftmax: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float32.", &val_ctx);
} break;
case kTfLiteBuiltinQuantize: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto value_type = context->tensors[node->inputs->data[0]].type;
Expect(value_type == kTfLiteFloat32 || IsQuantized(value_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Value should be quantized or Float32.", &val_ctx);
if (IsQuantized(value_type)) {
const auto quantization_params =
context->tensors[node->inputs->data[0]].params;
Expect(quantization_params.scale > 0.f,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Quantization scale should be > 0.", &val_ctx);
}
const auto output_type = context->tensors[node->outputs->data[0]].type;
if (android_sdk_version < kMinSdkVersionForNNAPI13) {
Expect(output_type == kTfLiteUInt8,
NNAPIValidationFailureType::kUnsupportedOutputType,
"Output should be kTfLiteUInt8.", &val_ctx);
} else {
ExpectTypeIn(output_type, {kTfLiteUInt8, kTfLiteInt8},
NNAPIValidationFailureType::kUnsupportedOutputType,
"Output should be kTfLiteUInt8.", &val_ctx);
}
const auto quantization_params =
context->tensors[node->outputs->data[0]].params;
Expect(quantization_params.scale > 0.f,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Quantization scale should be > 0.", &val_ctx);
} break;
case kTfLiteBuiltinReduceAny: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(context->tensors[node->outputs->data[0]].dims->size != 0,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI does not support generating a scalar as output.", &val_ctx);
} break;
case kTfLiteBuiltinReduceMin:
case kTfLiteBuiltinReduceMax: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_tensor = context->tensors[node->inputs->data[0]];
const auto input_type = input_tensor.type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8);
Expect(input_tensor.dims->size != 0,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI does not support generating a scalar as output.", &val_ctx);
} break;
case kTfLiteBuiltinDepthToSpace: {
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8);
} break;
case kTfLiteBuiltinReduceProd:
case kTfLiteBuiltinSum: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(context->tensors[node->outputs->data[0]].dims->size != 0,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI does not support generating a scalar as output", &val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports floating point input.", &val_ctx);
} break;
case kTfLiteBuiltinElu: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI13,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports floating point input.", &val_ctx);
} break;
case kTfLiteBuiltinFill: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI13,
&val_ctx);
const auto& dims_tensor = context->tensors[node->inputs->data[0]];
Expect(IsConstantTensor(&dims_tensor),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI doesn't support dynamic dimensions tensor.", &val_ctx);
EXPECT_INPUT_TYPE_IN(dims_tensor.type, kTfLiteInt32, kTfLiteInt64);
if (IsConstantTensor(&dims_tensor)) {
Expect(dims_tensor.dims->data[0] != 0,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI doesn't support generating scalars from FILL", &val_ctx);
if (dims_tensor.type == kTfLiteInt64) {
bool fit_in_int32 =
std::all_of(dims_tensor.data.i64,
dims_tensor.data.i64 + dims_tensor.dims->data[0],
[](int64_t dim) {
return std::numeric_limits<int32_t>::min() <= dim &&
dim <= std::numeric_limits<int32_t>::max();
});
Expect(fit_in_int32,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI only supports int32 dimensions tensor. If the "
"dimensions type is int64 and they are constant we can "
"convert them to int32 if the value isn't too large.",
&val_ctx);
}
}
const auto& value_tensor = context->tensors[node->inputs->data[1]];
EXPECT_INPUT_TYPE_IN(value_tensor.type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteInt64);
if (value_tensor.type == kTfLiteInt64 &&
IsConstantTensor(&value_tensor)) {
Expect(
*value_tensor.data.i64 <= std::numeric_limits<int32_t>::max() &&
*value_tensor.data.i64 >= std::numeric_limits<int32_t>::min(),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports int32 input. If the input type is int64 and "
"constant we can convert it to int32 if the value isn't too "
"large.",
&val_ctx);
}
} break;
case kTfLiteBuiltinPack: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI13,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
if (android_sdk_version >= kNNAPIRuntimeFeatureLevel6) {
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteInt32, kTfLiteFloat32,
kTfLiteInt8, kTfLiteUInt8);
} else {
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt8);
auto builtin = reinterpret_cast<TfLitePackParams*>(node->builtin_data);
Expect(builtin->axis != -1 &&
builtin->axis !=
context->tensors[node->inputs->data[0]].dims->size,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support axis being the last dimension",
&val_ctx);
}
} break;
case kTfLiteBuiltinUnpack: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI13,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8);
Expect(context->tensors[node->inputs->data[0]].dims->size > 1,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support unpacking a rank-1 tensor", &val_ctx);
Expect(context->tensors[node->inputs->data[0]].dims->size <= 4,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support unpacking a tensor with rank > 4",
&val_ctx);
const auto* builtin =
reinterpret_cast<const TfLiteUnpackParams*>(node->builtin_data);
Expect(builtin->axis != -1 &&
builtin->axis !=
context->tensors[node->inputs->data[0]].dims->size - 1,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support axis being the last dimension", &val_ctx);
} break;
case kTfLiteBuiltinSquaredDifference: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
const auto input0_type = context->tensors[node->inputs->data[0]].type;
if (android_sdk_version >= kMinSdkVersionForNNAPI13) {
EXPECT_INPUT_TYPE_IN(input0_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8, kTfLiteInt32);
} else if (android_sdk_version >= kMinSdkVersionForNNAPI12) {
EXPECT_INPUT_TYPE_IN(input0_type, kTfLiteFloat32, kTfLiteUInt8);
} else {
EXPECT_INPUT_TYPE_IN(input0_type, kTfLiteFloat32);
}
const int input0_rank =
context->tensors[node->inputs->data[0]].dims->size;
const int input1_rank =
context->tensors[node->inputs->data[1]].dims->size;
Expect(input0_rank <= 4 && input1_rank <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"NNAPI does not support input rank greater than 4", &val_ctx);
} break;
case kTfLiteBuiltinBatchMatmul: {
ExpectOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version,
kNNAPIRuntimeFeatureLevel6, &val_ctx);
const auto& input0 = context->tensors[node->inputs->data[0]];
const auto& input1 = context->tensors[node->inputs->data[1]];
EXPECT_INPUT_TYPE_IN(input0.type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteInt8);
Expect(input0.type == input1.type,
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"NNAPI does not support hybrid batch matmul", &val_ctx);
Expect(input0.dims->size <= 4 && input0.dims->size >= 2,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"NNAPI does not support input rank greater than 4 or less than 2",
&val_ctx);
Expect(!IsBroadcastBatchMatMul(context, node),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI does not support broadcast batch matmul", &val_ctx);
} break;
case kTfLiteBuiltinMirrorPad: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version,
kNNAPIRuntimeFeatureLevel7, &val_ctx);
ExpectIsFloatQuant8OrInt32Operator(context, node, &val_ctx);
const TfLiteIntArrayView input_shape(
context->tensors[node->inputs->data[0]].dims);
Expect(!HasZeroes(input_shape),
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NN API pad ops do not support input tensors with no elements",
&val_ctx);
Expect(node->inputs->size == 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expecting 2 inputs", &val_ctx);
} break;
case kTfLiteBuiltinReverseV2: {
ExpectMaxOpVersion(version, 3, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version,
kNNAPIRuntimeFeatureLevel7, &val_ctx);
ExpectIsFloatQuant8OrInt32Operator(context, node, &val_ctx);
Expect(node->inputs->size == 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expecting 2 inputs", &val_ctx);
} break;
default:
// All other operators are not mapped.
AddValidationFailure(NNAPIValidationFailureType::kUnsupportedOperator,
"Unsupported operation type.", &val_ctx);
}
return val_ctx.is_valid;
} // NOLINT(readability/fn_size)
TfLiteStatus NNAPIDelegateKernel::Map(
TfLiteContext* context, int builtin_code, int version,
int android_sdk_version, const NNAPIOpMappingArgs& mapping_args,
ANeuralNetworksOperationType* nn_op_type,
NnapiDelegateVendorPlugin* vendor_plugin) {
auto add_zero_bias = [mapping_args](int input_id, int filter_id,
int num_elements) -> void {
// NNAPI requires a bias tensor, so we allocate a new tensor to fill
// it with zeroes. It is deleted with other tensors in the context
// during subgraph destructor call.
int bias_index = -1;
mapping_args.context->AddTensors(mapping_args.context, 1, &bias_index);
TfLiteTensor* bias_tensor = &mapping_args.context->tensors[bias_index];
const auto input_type = mapping_args.context->tensors[input_id].type;
if (input_type == kTfLiteFloat32) {
bias_tensor->type = kTfLiteFloat32;
} else {
bias_tensor->type = kTfLiteInt32;
}
// Create an array with a required bias shape and resize the bias
// tensor.
TfLiteIntArray* bias_shape = TfLiteIntArrayCreate(1);
bias_shape->data[0] = num_elements;
bias_tensor->allocation_type = kTfLiteDynamic;
mapping_args.context->ResizeTensor(mapping_args.context, bias_tensor,
bias_shape);
// Set tensor's values to zeroes and add it using AddVector*, so
// that the values are copied to NNAPI. We don't use the AddTensor
// function because it doesn't copy values and the tensor we just
// created is not in the node->inputs.
if (input_type == kTfLiteFloat32) {
memset(bias_tensor->data.f, 0, num_elements * sizeof(float));
mapping_args.builder->AddVectorFloat32Operand(bias_tensor->data.f,
num_elements);
} else {
memset(bias_tensor->data.i32, 0, num_elements * sizeof(int));
const TfLiteTensor& input_tensor =
mapping_args.context->tensors[input_id];
const TfLiteTensor& filter_tensor =
mapping_args.context->tensors[filter_id];
// NNAPI requires bias scale to be a product of an input scale and
// a filter scale.
bias_tensor->params.scale =
input_tensor.params.scale * filter_tensor.params.scale;
mapping_args.builder->AddVectorInt32Operand(
bias_tensor->data.i32, num_elements, bias_tensor->params.scale,
/*zero_point=*/0);
}
};
switch (builtin_code) {
case kTfLiteBuiltinAdd: {
auto builtin =
reinterpret_cast<TfLiteAddParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_ADD;
} break;
case kTfLiteBuiltinArgMax: {
*nn_op_type = ANEURALNETWORKS_ARGMAX;
} break;
case kTfLiteBuiltinArgMin: {
*nn_op_type = ANEURALNETWORKS_ARGMIN;
} break;
case kTfLiteBuiltinMul: {
auto builtin =
reinterpret_cast<TfLiteMulParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_MUL;
} break;
case kTfLiteBuiltinAveragePool2d: {
mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data);
*nn_op_type = ANEURALNETWORKS_AVERAGE_POOL_2D;
} break;
case kTfLiteBuiltinMaxPool2d: {
mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data);
*nn_op_type = ANEURALNETWORKS_MAX_POOL_2D;
} break;
case kTfLiteBuiltinL2Pool2d: {
mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data);
*nn_op_type = ANEURALNETWORKS_L2_POOL_2D;
} break;
case kTfLiteBuiltinConv2d: {
auto builtin =
reinterpret_cast<TfLiteConvParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->padding);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
const int input_id = mapping_args.node->inputs->data[/*kInputTensor*/ 0];
const int filter_id =
mapping_args.node->inputs->data[/*kWeightsTensor*/ 1];
const int input_channels = context->tensors[input_id].dims->data[3];
const int filter_input_channels =
context->tensors[filter_id].dims->data[3];
bool is_grouped_conv = input_channels != filter_input_channels;
if (is_grouped_conv) {
mapping_args.builder->AddScalarInt32Operand(input_channels /
filter_input_channels);
}
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
// NNAPI supports dilated Conv2D since NNAPI 1.2.
if (builtin->dilation_width_factor != 1 ||
builtin->dilation_height_factor != 1) {
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_width_factor);
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_height_factor);
}
if (is_grouped_conv) {
*nn_op_type = ANEURALNETWORKS_GROUPED_CONV_2D;
} else {
*nn_op_type = ANEURALNETWORKS_CONV_2D;
}
} break;
case kTfLiteBuiltinDepthwiseConv2d: {
auto builtin = reinterpret_cast<TfLiteDepthwiseConvParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->padding);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
mapping_args.builder->AddScalarInt32Operand(builtin->depth_multiplier);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
if (builtin->dilation_width_factor != 1 ||
builtin->dilation_height_factor != 1) {
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format.
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_width_factor);
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_height_factor);
}
*nn_op_type = ANEURALNETWORKS_DEPTHWISE_CONV_2D;
} break;
case kTfLiteBuiltinFullyConnected: {
const bool is_bias_present =
mapping_args.node->inputs->size == 3 &&
mapping_args.node->inputs->data[2] != kTfLiteOptionalTensor;
if (!is_bias_present) {
const int input_tensor_id =
mapping_args.node->inputs->data[/*kInputTensor*/ 0];
const int filter_tensor_id =
mapping_args.node->inputs->data[/*kWeightsTensor*/ 1];
const int num_units =
mapping_args.context->tensors[filter_tensor_id].dims->data[0];
add_zero_bias(input_tensor_id, filter_tensor_id, num_units);
}
auto builtin = reinterpret_cast<TfLiteFullyConnectedParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_FULLY_CONNECTED;
} break;
case kTfLiteBuiltinHardSwish: {
*nn_op_type = ANEURALNETWORKS_HARD_SWISH;
} break;
case kTfLiteBuiltinSoftmax: {
auto builtin = reinterpret_cast<TfLiteSoftmaxParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarFloat32Operand(builtin->beta);
// Optional scalar specifying the dimension the activation would be
// performed on is not added. Default to -1.
*nn_op_type = ANEURALNETWORKS_SOFTMAX;
} break;
case kTfLiteBuiltinReshape: {
if (mapping_args.node->inputs->size == 1) {
// if no new_shape tensor, construct the new shape from params.
auto* params = reinterpret_cast<TfLiteReshapeParams*>(
mapping_args.node->builtin_data);
int num_dimensions = params->num_dimensions;
std::vector<int32_t> output_shape(num_dimensions);
for (int i = 0; i < num_dimensions; ++i) {
output_shape[i] = params->shape[i];
}
mapping_args.builder->AddVectorInt32Operand(
output_shape.data(), static_cast<uint32_t>(num_dimensions));
}
*nn_op_type = ANEURALNETWORKS_RESHAPE;
} break;
case kTfLiteBuiltinResizeBilinear: {
const int output_id = mapping_args.node->outputs->data[0];
auto& output = mapping_args.context->tensors[output_id];
const int output_height = output.dims->data[1];
const int output_width = output.dims->data[2];
mapping_args.builder->AddScalarInt32Operand(output_width);
mapping_args.builder->AddScalarInt32Operand(output_height);
auto builtin = reinterpret_cast<TfLiteResizeBilinearParams*>(
mapping_args.node->builtin_data);
if (builtin->align_corners == true ||
builtin->half_pixel_centers == true) {
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format
mapping_args.builder->AddScalarBoolOperand(builtin->align_corners);
mapping_args.builder->AddScalarBoolOperand(builtin->half_pixel_centers);
}
*nn_op_type = ANEURALNETWORKS_RESIZE_BILINEAR;
} break;
case kTfLiteBuiltinResizeNearestNeighbor: {
const TfLiteTensor& new_shape =
mapping_args.context->tensors[mapping_args.node->inputs->data[1]];
// NNAPI uses scalar inputs for height and width.
mapping_args.builder->AddScalarInt32Operand(new_shape.data.i32[1]);
mapping_args.builder->AddScalarInt32Operand(new_shape.data.i32[0]);
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format
auto builtin = reinterpret_cast<TfLiteResizeNearestNeighborParams*>(
mapping_args.node->builtin_data);
if (builtin->align_corners == true ||
builtin->half_pixel_centers == true) {
mapping_args.builder->AddScalarBoolOperand(builtin->align_corners);
mapping_args.builder->AddScalarBoolOperand(builtin->half_pixel_centers);
}
*nn_op_type = ANEURALNETWORKS_RESIZE_NEAREST_NEIGHBOR;
} break;
case kTfLiteBuiltinSqueeze: {
auto builtin = reinterpret_cast<TfLiteSqueezeParams*>(
mapping_args.node->builtin_data);
// Note that we add the squeeze dimensions even if the dimensions
// were unspecified (empty), as NNAPI requires the operand.
mapping_args.builder->AddVectorInt32Operand(
builtin->num_squeeze_dims ? builtin->squeeze_dims : nullptr,
static_cast<uint32_t>(builtin->num_squeeze_dims));
*nn_op_type = ANEURALNETWORKS_SQUEEZE;
} break;
case kTfLiteBuiltinUnidirectionalSequenceLstm: {
auto builtin = reinterpret_cast<TfLiteUnidirectionalSequenceLSTMParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip);
mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip);
mapping_args.builder->AddScalarBoolOperand(builtin->time_major);
const bool hybrid_op = IsHybridOperator(
mapping_args.context, kTfLiteBuiltinUnidirectionalSequenceLstm,
mapping_args.node);
if (mapping_args.node->inputs->size == 24) {
// Add layer normalization tensors if they are provided.
for (int i = 20; i < 24; ++i) {
const int input_index = mapping_args.node->inputs->data[i];
if (input_index != kTfLiteOptionalTensor) {
mapping_args.builder->AddTensorInput(input_index, hybrid_op);
} else {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
}
} else {
for (int i = 0; i < 4; ++i) {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
}
*nn_op_type = ANEURALNETWORKS_UNIDIRECTIONAL_SEQUENCE_LSTM;
} break;
case kTfLiteBuiltinL2Normalization: {
*nn_op_type = ANEURALNETWORKS_L2_NORMALIZATION;
} break;
case kTfLiteBuiltinLocalResponseNormalization: {
auto builtin = reinterpret_cast<TfLiteLocalResponseNormParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->radius);
mapping_args.builder->AddScalarFloat32Operand(builtin->bias);
mapping_args.builder->AddScalarFloat32Operand(builtin->alpha);
mapping_args.builder->AddScalarFloat32Operand(builtin->beta);
*nn_op_type = ANEURALNETWORKS_LOCAL_RESPONSE_NORMALIZATION;
} break;
case kTfLiteBuiltinLshProjection: {
auto builtin = reinterpret_cast<TfLiteLSHProjectionParams*>(
mapping_args.node->builtin_data);
int type = builtin->type;
// In Android Q+, NNAPI uses 3 to denote
// kTfLiteLshProjectionSparse.
const int kNNAPILshProjectionSparse = 3;
if (builtin->type == kTfLiteLshProjectionSparse) {
type = kNNAPILshProjectionSparse;
// Add NNAPI null weight operand.
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
mapping_args.builder->AddScalarInt32Operand(type);
*nn_op_type = ANEURALNETWORKS_LSH_PROJECTION;
} break;
case kTfLiteBuiltinConcatenation: {
auto builtin = reinterpret_cast<TfLiteConcatenationParams*>(
mapping_args.node->builtin_data);
int axis = builtin->axis < 0
? mapping_args.context
->tensors[mapping_args.node->inputs->data[0]]
.dims->size +
builtin->axis
: builtin->axis;
mapping_args.builder->AddScalarInt32Operand(axis);
*nn_op_type = ANEURALNETWORKS_CONCATENATION;
} break;
case kTfLiteBuiltinDequantize: {
*nn_op_type = ANEURALNETWORKS_DEQUANTIZE;
} break;
case kTfLiteBuiltinFloor: {
*nn_op_type = ANEURALNETWORKS_FLOOR;
} break;
case kTfLiteBuiltinRelu: {
*nn_op_type = ANEURALNETWORKS_RELU;
} break;
case kTfLiteBuiltinReluN1To1: {
*nn_op_type = ANEURALNETWORKS_RELU1;
} break;
case kTfLiteBuiltinRelu6: {
*nn_op_type = ANEURALNETWORKS_RELU6;
} break;
case kTfLiteBuiltinLogistic: {
*nn_op_type = ANEURALNETWORKS_LOGISTIC;
} break;
case kTfLiteBuiltinTanh: {
*nn_op_type = ANEURALNETWORKS_TANH;
} break;
case kTfLiteBuiltinSub: {
auto builtin =
reinterpret_cast<TfLiteSubParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_SUB;
} break;
case kTfLiteBuiltinDiv: {
auto builtin =
reinterpret_cast<TfLiteDivParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_DIV;
} break;
case kTfLiteBuiltinPad:
case kTfLiteBuiltinPadv2: {
// We want to map to PAD as much as possible since it is more widely
// supported. We map to PadV2 only when there is the need to specify
// the padding value
if (mapping_args.node->inputs->size == 2) {
*nn_op_type = ANEURALNETWORKS_PAD;
} else {
const int constant_value_id = mapping_args.node->inputs->data[2];
if (constant_value_id == kTfLiteOptionalTensor) {
*nn_op_type = ANEURALNETWORKS_PAD;
} else {
*nn_op_type = ANEURALNETWORKS_PAD_V2;
}
}
} break;
case kTfLiteBuiltinUnidirectionalSequenceRnn: {
auto builtin = reinterpret_cast<TfLiteSequenceRNNParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarInt32Operand(builtin->time_major);
*nn_op_type = ANEURALNETWORKS_UNIDIRECTIONAL_SEQUENCE_RNN;
} break;
case kTfLiteBuiltinSpaceToBatchNd: {
*nn_op_type = ANEURALNETWORKS_SPACE_TO_BATCH_ND;
} break;
case kTfLiteBuiltinBatchToSpaceNd: {
*nn_op_type = ANEURALNETWORKS_BATCH_TO_SPACE_ND;
} break;
case kTfLiteBuiltinStridedSlice: {
auto builtin = reinterpret_cast<TfLiteStridedSliceParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->begin_mask);
mapping_args.builder->AddScalarInt32Operand(builtin->end_mask);
mapping_args.builder->AddScalarInt32Operand(builtin->shrink_axis_mask);
*nn_op_type = ANEURALNETWORKS_STRIDED_SLICE;
} break;
case kTfLiteBuiltinTranspose: {
*nn_op_type = ANEURALNETWORKS_TRANSPOSE;
} break;
case kTfLiteBuiltinAbs: {
*nn_op_type = ANEURALNETWORKS_ABS;
} break;
case kTfLiteBuiltinExp: {
*nn_op_type = ANEURALNETWORKS_EXP;
} break;
case kTfLiteBuiltinLog: {
*nn_op_type = ANEURALNETWORKS_LOG;
} break;
case kTfLiteBuiltinRsqrt: {
*nn_op_type = ANEURALNETWORKS_RSQRT;
} break;
case kTfLiteBuiltinPow: {
*nn_op_type = ANEURALNETWORKS_POW;
} break;
case kTfLiteBuiltinSlice: {
*nn_op_type = ANEURALNETWORKS_SLICE;
} break;
case kTfLiteBuiltinSin: {
*nn_op_type = ANEURALNETWORKS_SIN;
} break;
case kTfLiteBuiltinTransposeConv: {
int input_tensor_flags = 0;
const int input_tensor_id =
mapping_args.node->inputs->data[/*kDataInputTensor*/ 2];
const int weight_tensor_id =
mapping_args.node->inputs->data[/*kWeightsTensor*/ 1];
// Transpose convolution doesn't have hybrid variation.
const bool hybrid_op = false;
if (android_sdk_version >= kMinSdkVersionForNNAPI13) {
mapping_args.builder->AddTensorInput(
input_tensor_id, hybrid_op,
input_tensor_flags | NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED);
} else {
mapping_args.builder->AddTensorInput(
input_tensor_id, hybrid_op,
input_tensor_flags | NN_TENSOR_FLAG_INT8_CONVERSION);
}
// Transpose convlution uses per-channel quantization with int8 inputs
// even if the number of channels in quantization parameters is equal to 1
// (as opposed to conv2d, which uses per-tensor quantization in this
// case).
mapping_args.builder->AddTensorInput(
weight_tensor_id, hybrid_op,
input_tensor_flags | NN_TENSOR_FLAG_FORCE_PER_CHANNEL);
const bool is_bias_present =
mapping_args.node->inputs->size == 4 &&
mapping_args.node->inputs->data[/*kBiasTensor*/ 3] !=
kTfLiteOptionalTensor;
if (is_bias_present) {
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[/*kBiasTensor*/ 3], hybrid_op);
} else {
const TfLiteTensor& output_shape =
mapping_args.context->tensors[mapping_args.node->inputs
->data[/*kOutputShapeTensor*/ 0]];
const int output_depth = output_shape.data.i32[3];
add_zero_bias(input_tensor_id, weight_tensor_id, output_depth);
}
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[/*kOutputShapeTensor*/ 0], hybrid_op);
auto builtin = reinterpret_cast<TfLiteTransposeConvParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->padding);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
mapping_args.builder->AddScalarInt32Operand(
/*ANEURALNETWORKS_FUSED_NONE*/ 0);
// Use NHWC layout for input and output.
mapping_args.builder->AddScalarBoolOperand(false);
*nn_op_type = ANEURALNETWORKS_TRANSPOSE_CONV;
} break;
case kTfLiteBuiltinSqrt: {
*nn_op_type = ANEURALNETWORKS_SQRT;
} break;
case kTfLiteBuiltinRnn: {
// NNAPI need both state_in and state_out.
int ann_index;
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kHiddenStateTensor*/ 4],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs->data[/*kHiddenStateTensor*/ 4]);
auto builtin =
reinterpret_cast<TfLiteRNNParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_RNN;
} break;
case kTfLiteBuiltinSpaceToDepth: {
auto builtin = reinterpret_cast<TfLiteSpaceToDepthParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->block_size);
*nn_op_type = ANEURALNETWORKS_SPACE_TO_DEPTH;
} break;
case kTfLiteBuiltinSvdf: {
// NNAPI need both state_in and state_out.
int ann_index;
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 4],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 4]);
auto builtin =
reinterpret_cast<TfLiteSVDFParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->rank);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_SVDF;
} break;
case kTfLiteBuiltinLstm: {
if (isLstmBasicKernel(mapping_args.node)) {
const auto output_dims =
mapping_args.context->tensors[mapping_args.node->outputs->data[1]]
.dims;
// Inputs kInputData
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[0 /* kInputData */],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
// The 8 weights tensors are set decomposing the
// kInputWeights param
const auto weight_tensor =
mapping_args.context->tensors[mapping_args.node->inputs
->data[2 /* kInputWeights */]];
std::vector<uint8_t> recurrent_to_input;
std::vector<uint8_t> input_to_input;
std::vector<uint8_t> recurrent_to_cell;
std::vector<uint8_t> input_to_cell;
std::vector<uint8_t> recurrent_to_forget;
std::vector<uint8_t> input_to_forget;
std::vector<uint8_t> recurrent_to_output;
std::vector<uint8_t> input_to_output;
tflite::delegate::nnapi::DecomposeQuantLstmWeightsTensor(
weight_tensor.data.uint8, weight_tensor.dims, &recurrent_to_input,
&input_to_input, &recurrent_to_cell, &input_to_cell,
&recurrent_to_forget, &input_to_forget, &recurrent_to_output,
&input_to_output);
TfLiteIntArray* recurrent_weight_dims = TfLiteIntArrayCreate(2);
TfLiteIntArray* input_weight_dims = TfLiteIntArrayCreate(2);
tflite::delegate::nnapi::SetWeightSubmatrixDims(
weight_tensor.dims, recurrent_weight_dims, input_weight_dims);
int new_tensor_index = -1;
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_input, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_forget, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_cell, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_output, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_input, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_forget, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_cell, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_output, weight_tensor.params,
&new_tensor_index);
TfLiteIntArrayFree(input_weight_dims);
TfLiteIntArrayFree(recurrent_weight_dims);
// Biases have to be split in four.
const auto bias_size = output_dims->data[1];
const TfLiteTensor& biases_tensor =
mapping_args.context->tensors[mapping_args.node->inputs
->data[3 /* kInputBiases */]];
std::vector<int32_t> input_bias;
std::vector<int32_t> cell_bias;
std::vector<int32_t> forget_bias;
std::vector<int32_t> output_bias;
delegate::nnapi::DecomposeBiasTensor(biases_tensor.data.i32, bias_size,
&input_bias, &cell_bias,
&forget_bias, &output_bias);
int input_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor<int32_t>(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, input_bias,
biases_tensor.params, &input_bias_tensor);
int forget_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size},
forget_bias, biases_tensor.params, &forget_bias_tensor);
int cell_gate_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, cell_bias,
biases_tensor.params, &cell_gate_bias_tensor);
int output_gate_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size},
output_bias, biases_tensor.params, &output_gate_bias_tensor);
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[4 /* kInputPrevState */],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
// kInputPrevActivation
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[1 /* kInputPrevActivation */],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
// Configuring the copy from the activation, state outputs
// to their associated inputs
mapping_args.feedback_loops->push_back(std::make_tuple(
mapping_args.node->outputs->data[0 /*kOutputActivation*/],
mapping_args.node->inputs->data[1 /*kInputPrevActivation*/]));
mapping_args.feedback_loops->push_back(std::make_tuple(
mapping_args.node->outputs->data[1 /*kOutputState*/],
mapping_args.node->inputs->data[4 /*kInputPrevState*/]));
// OUTPUTS
// Setting only the first two since the remaining ones are
// ignored by NNAPI
mapping_args.builder->AddTensorOutput(
mapping_args.node->outputs->data[1 /* kOutputState */], 0);
mapping_args.builder->AddTensorOutput(
mapping_args.node->outputs->data[0 /* kOutputActivation */], 0);
*nn_op_type = ANEURALNETWORKS_QUANTIZED_16BIT_LSTM;
} else {
auto builtin = reinterpret_cast<TfLiteLSTMParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip);
mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip);
// Current NNAPI implementation requires the scratch_buffer as
// output.
mapping_args.builder->AddAdditionalFloat32OutputTensor(2);
// NNAPI need both state_in and state_out for cell_state and
// output_state.
int ann_index;
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 18],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs
->data[/*kInputActivationStateTensor*/ 18]);
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kInputCellStateTensor*/ 19],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs->data[/*kInputCellStateTensor*/ 19]);
const bool hybrid_op = IsHybridOperator(
mapping_args.context, kTfLiteBuiltinLstm, mapping_args.node);
if (mapping_args.node->inputs->size == 24) {
for (int i = 20; i < 24; ++i) {
const auto input_index = mapping_args.node->inputs->data[i];
if (input_index != kTfLiteOptionalTensor) {
mapping_args.builder->AddTensorInput(input_index, hybrid_op);
} else {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
}
}
*nn_op_type = ANEURALNETWORKS_LSTM;
}
} break;
case kTfLiteBuiltinMean: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
int32_t keep_dims = 0;
if (builtin->keep_dims) keep_dims = 1;
mapping_args.builder->AddScalarInt32Operand(keep_dims);
*nn_op_type = ANEURALNETWORKS_MEAN;
} break;
case kTfLiteBuiltinEmbeddingLookup: {
*nn_op_type = ANEURALNETWORKS_EMBEDDING_LOOKUP;
} break;
case kTfLiteBuiltinHashtableLookup: {
*nn_op_type = ANEURALNETWORKS_HASHTABLE_LOOKUP;
} break;
case kTfLiteBuiltinMaximum: {
*nn_op_type = ANEURALNETWORKS_MAXIMUM;
} break;
case kTfLiteBuiltinMinimum: {
*nn_op_type = ANEURALNETWORKS_MINIMUM;
} break;
case kTfLiteBuiltinCast: {
*nn_op_type = ANEURALNETWORKS_CAST;
} break;
case kTfLiteBuiltinLeakyRelu: {
const auto input_type =
mapping_args.context->tensors[mapping_args.node->inputs->data[0]]
.type;
auto builtin = reinterpret_cast<TfLiteLeakyReluParams*>(
mapping_args.node->builtin_data);
TfLiteTensor alpha_tensor;
alpha_tensor.type = input_type;
alpha_tensor.allocation_type = kTfLiteDynamic;
alpha_tensor.dims = TfLiteIntArrayCreate(1);
alpha_tensor.dims->data[0] = 1;
alpha_tensor.params.zero_point = 0;
int new_tensor_index = -1;
if (input_type == kTfLiteFloat32) {
alpha_tensor.params.scale = 0;
std::vector<float> alpha_value = {builtin->alpha};
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_FLOAT32, kTfLiteFloat32, alpha_tensor.dims,
alpha_value, alpha_tensor.params, &new_tensor_index);
} else if (input_type == kTfLiteInt8 &&
android_sdk_version >= kMinSdkVersionForNNAPI13) {
alpha_tensor.params.scale = builtin->alpha;
std::vector<int8_t> alpha_value = {1};
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED, kTfLiteInt8,
alpha_tensor.dims, alpha_value, alpha_tensor.params,
&new_tensor_index);
} else {
alpha_tensor.params.scale = builtin->alpha;
std::vector<uint8_t> alpha_value = {1};
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
alpha_tensor.dims, alpha_value, alpha_tensor.params,
&new_tensor_index);
}
*nn_op_type = ANEURALNETWORKS_PRELU;
} break;
case kTfLiteBuiltinPrelu: {
*nn_op_type = ANEURALNETWORKS_PRELU;
} break;
case kTfLiteBuiltinTile: {
*nn_op_type = ANEURALNETWORKS_TILE;
} break;
case kTfLiteBuiltinLogicalOr: {
*nn_op_type = ANEURALNETWORKS_LOGICAL_OR;
} break;
case kTfLiteBuiltinLogicalAnd: {
*nn_op_type = ANEURALNETWORKS_LOGICAL_AND;
} break;
case kTfLiteBuiltinLogicalNot: {
*nn_op_type = ANEURALNETWORKS_LOGICAL_NOT;
} break;
case kTfLiteBuiltinLess: {
*nn_op_type = ANEURALNETWORKS_LESS;
} break;
case kTfLiteBuiltinLessEqual: {
*nn_op_type = ANEURALNETWORKS_LESS_EQUAL;
} break;
case kTfLiteBuiltinGreater: {
*nn_op_type = ANEURALNETWORKS_GREATER;
} break;
case kTfLiteBuiltinGreaterEqual: {
*nn_op_type = ANEURALNETWORKS_GREATER_EQUAL;
} break;
case kTfLiteBuiltinEqual: {
*nn_op_type = ANEURALNETWORKS_EQUAL;
} break;
case kTfLiteBuiltinNotEqual: {
*nn_op_type = ANEURALNETWORKS_NOT_EQUAL;
} break;
case kTfLiteBuiltinNeg: {
*nn_op_type = ANEURALNETWORKS_NEG;
} break;
case kTfLiteBuiltinTopkV2: {
const TfLiteTensor& k_param =
mapping_args.context->tensors[mapping_args.node->inputs->data[1]];
mapping_args.builder->AddScalarInt32Operand(*k_param.data.i32);
*nn_op_type = ANEURALNETWORKS_TOPK_V2;
} break;
case kTfLiteBuiltinSelect: {
*nn_op_type = ANEURALNETWORKS_SELECT;
} break;
case kTfLiteBuiltinGather: {
auto builtin = reinterpret_cast<TfLiteGatherParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->axis);
mapping_args.builder->AddTensorInput(mapping_args.node->inputs->data[1],
/* hybrid_op */ false,
/* tensor_flags */ 0);
*nn_op_type = ANEURALNETWORKS_GATHER;
} break;
case kTfLiteBuiltinBidirectionalSequenceLstm: {
auto builtin = reinterpret_cast<TfLiteBidirectionalSequenceLSTMParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip);
mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip);
mapping_args.builder->AddScalarBoolOperand(builtin->merge_outputs);
mapping_args.builder->AddScalarBoolOperand(builtin->time_major);
// TF Lite doesn't support layer normalization in bidirectional
// sequence LSTM, so we insert optional tensors for NNAPI.
for (int i = 0; i < 8; ++i) {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
*nn_op_type = ANEURALNETWORKS_BIDIRECTIONAL_SEQUENCE_LSTM;
} break;
case kTfLiteBuiltinExpandDims: {
const TfLiteTensor& axis_param =
mapping_args.context->tensors[mapping_args.node->inputs->data[1]];
mapping_args.builder->AddScalarInt32Operand(*axis_param.data.i32);
*nn_op_type = ANEURALNETWORKS_EXPAND_DIMS;
} break;
case kTfLiteBuiltinSplit: {
const TfLiteTensor& axis =
mapping_args.context->tensors[mapping_args.node->inputs->data[0]];
auto builtin =
reinterpret_cast<TfLiteSplitParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(*axis.data.i32);
mapping_args.builder->AddScalarInt32Operand(builtin->num_splits);
*nn_op_type = ANEURALNETWORKS_SPLIT;
} break;
case kTfLiteBuiltinLogSoftmax: {
// Scaling and axis are hardcoded to respectively 1 and -1
// in TFLite.
mapping_args.builder->AddScalarFloat32Operand(1);
mapping_args.builder->AddScalarInt32Operand(-1);
*nn_op_type = ANEURALNETWORKS_LOG_SOFTMAX;
} break;
case kTfLiteBuiltinQuantize: {
auto input_index = mapping_args.node->inputs->data[0];
// NNAPI doesn't support requantization cases but only quantizations
// from float. Dequantizing our input adding a Dequantize node before
// this one.
if (IsQuantized(mapping_args.context->tensors[input_index].type)) {
mapping_args.builder->AddDequantize(0, input_index, kTfLiteFloat32,
mapping_args.node_index);
}
*nn_op_type = ANEURALNETWORKS_QUANTIZE;
} break;
case kTfLiteBuiltinReduceAny: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_ANY;
} break;
case kTfLiteBuiltinReduceMin: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_MIN;
} break;
case kTfLiteBuiltinReduceMax: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_MAX;
} break;
case kTfLiteBuiltinDepthToSpace: {
auto builtin = reinterpret_cast<TfLiteDepthToSpaceParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->block_size);
*nn_op_type = ANEURALNETWORKS_DEPTH_TO_SPACE;
} break;
case kTfLiteBuiltinReduceProd: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_PROD;
} break;
case kTfLiteBuiltinSum: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_SUM;
} break;
case kTfLiteBuiltinElu: {
mapping_args.builder->AddScalarFloat32Operand(1.0);
*nn_op_type = ANEURALNETWORKS_ELU;
} break;
case kTfLiteBuiltinFill: {
*nn_op_type = ANEURALNETWORKS_FILL;
} break;
case kTfLiteBuiltinBatchMatmul: {
auto builtin = reinterpret_cast<TfLiteBatchMatMulParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->adj_x);
mapping_args.builder->AddScalarBoolOperand(builtin->adj_y);
*nn_op_type = ANEURALNETWORKS_BATCH_MATMUL;
} break;
case kTfLiteBuiltinPack: {
*nn_op_type = ANEURALNETWORKS_PACK;
} break;
case kTfLiteBuiltinMirrorPad: {
auto builtin = reinterpret_cast<TfLiteMirrorPaddingParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->mode);
*nn_op_type = ANEURALNETWORKS_MIRROR_PAD;
} break;
case kTfLiteBuiltinReverseV2: {
*nn_op_type = ANEURALNETWORKS_REVERSE;
} break;
default:
// All other operators are not mapped.
return kTfLiteError;
}
return kTfLiteOk;
}
// Initialize the kernel (a NN model).
TfLiteStatus NNAPIDelegateKernel::Init(TfLiteContext* context,
const TfLiteDelegateParams* params,
int* nnapi_errno) {
for (auto node_index : TfLiteIntArrayView(params->nodes_to_replace)) {
nodes_.push_back(node_index);
}
// Initialize densify map and dequantize map.
densify_output_to_node_mapping_ = std::vector<int>(context->tensors_size, -1);
non_const_dequantize_output_to_node_mapping_ =
std::vector<int>(context->tensors_size, -1);
const auto delegate_options =
StatefulNnApiDelegate::GetOptions(params->delegate);
if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI12 &&
ShouldUseTargetDevices(delegate_options, nnapi_)) {
TF_LITE_ENSURE_STATUS(GetTargetDevices(context, params->delegate, nnapi_,
nnapi_errno, &nnapi_devices_));
if (nnapi_devices_.empty()) {
context->ReportError(
context, "NNAPI delegate requested but no accelerators available.");
return kTfLiteError;
}
}
if (nnapi_->android_sdk_version < kMinSdkVersionForNNAPI12 &&
delegate_options.allow_dynamic_dimensions &&
delegate_options.vendor_plugin != nullptr) {
TF_LITE_KERNEL_LOG(context,
"Models with dynamic dimensions and vendor plugin is "
"not supported before NNAPI 1.2 (API level 29).");
return kTfLiteError;
}
// Mark the handle backed tensors.
tensor_memory_map_ =
&StatefulNnApiDelegate::GetTensorMemoryMap(params->delegate);
// Initialize tensor max size hints.
tensor_max_size_hints_.resize(context->tensors_size, 0);
for (const auto it : delegate_options.tensor_max_size_hints) {
auto tensor_index = it.first;
// Skip invalid or optional entries.
if (tensor_index >= context->tensors_size || tensor_index < 0) continue;
// Skip tensors with static shape.
if (!HasUnspecifiedDimension(&context->tensors[tensor_index])) continue;
auto max_size_hint = it.second;
tensor_max_size_hints_[tensor_index] = max_size_hint;
}
if (!nn_model_) {
ANeuralNetworksModel* model = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(context,
nnapi_->ANeuralNetworksModel_create(&model),
"creating NNAPI model", nnapi_errno);
nn_model_.reset(model);
TF_LITE_ENSURE_STATUS(BuildGraph(context, delegate_options,
params->input_tensors,
params->output_tensors, nnapi_errno));
}
auto* cache = StatefulNnApiDelegate::GetCache(params->delegate);
if (cache) {
// Compilation caching is enabled, construct the uint8 token.
uint64_t token_parts[4];
// model_token is incorporated into parition_key by TFLite Serialization.
// NNAPI uses 256-bit key, but we can just tile the unique 64-bit
// fingerprint from TFLite.
auto partition_entry = cache->GetEntryForKernel(kNnapiId, context, params);
token_parts[0] = partition_entry.GetFingerprint();
token_parts[1] = partition_entry.GetFingerprint();
token_parts[2] = partition_entry.GetFingerprint();
token_parts[3] = partition_entry.GetFingerprint();
// TODO(b/172238515): get token size from header instead of hardcoding.
// Allocate one extra 'null' byte to avoid bugs with backends that might
// be doing strlen() on the token ptr.
std::vector<uint8_t> nnapi_cache_token(33, 0);
// Copy the token bits.
uint8_t* p = reinterpret_cast<uint8_t*>(token_parts);
for (int i = 0; i < 4 * sizeof(uint64_t); i++) {
nnapi_cache_token[i] = p[i];
}
nn_compilation_cache_token_ = nnapi_cache_token;
}
nn_execution_cache_.SetMaxCacheSize(
delegate_options.max_execution_cache_size);
initialised_ = true;
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::Prepare(TfLiteContext* context,
TfLiteNode* node, int* nnapi_errno) {
if (!initialised_) {
return kTfLiteError;
}
const auto delegate_options =
StatefulNnApiDelegate::GetOptions(node->delegate);
if (nn_compilation_) {
return kTfLiteOk;
}
ANeuralNetworksCompilation* compilation = nullptr;
if (!nnapi_devices_.empty()) {
// Compile for the selected accelerator.
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksCompilation_createForDevices(
nn_model_.get(), nnapi_devices_.data(), nnapi_devices_.size(),
&compilation),
"creating NNAPI model for given devices", nnapi_errno);
} else {
// Trying to call ANeuralNetworksCompilation_create when the delegate is
// constructed from a support library would result in a crash.
if (nnapi_->ANeuralNetworksCompilation_create != nullptr) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(context,
nnapi_->ANeuralNetworksCompilation_create(
nn_model_.get(), &compilation),
"creating NNAPI compilation",
nnapi_errno);
} else {
TF_LITE_KERNEL_LOG(
context,
"Attempted to call ANeuralNetworksCompilation_create from NNAPI "
"delegate that is constructed from a support library");
return kTfLiteError;
}
}
auto preference = delegate_options.execution_preference;
if (preference !=
StatefulNnApiDelegate::Options::ExecutionPreference::kUndefined) {
const int preference_result =
nnapi_->ANeuralNetworksCompilation_setPreference(compilation,
preference);
if (preference_result != ANEURALNETWORKS_NO_ERROR) {
nnapi_->ANeuralNetworksCompilation_free(compilation);
compilation = nullptr;
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, preference_result,
"setting compilation preferences",
nnapi_errno);
}
if (!nn_compilation_cache_token_.empty()) {
const char* cache_dir = delegate_options.cache_dir;
const int set_caching_result =
nnapi_->ANeuralNetworksCompilation_setCaching(
compilation, cache_dir, nn_compilation_cache_token_.data());
if (set_caching_result != ANEURALNETWORKS_NO_ERROR) {
nnapi_->ANeuralNetworksCompilation_free(compilation);
compilation = nullptr;
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, set_caching_result,
"configuring NNAPI caching", nnapi_errno);
}
// Set compilation timeout if applicable.
if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI13) {
if (delegate_options.max_compilation_timeout_duration_ns > 0) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksCompilation_setTimeout(
compilation,
delegate_options.max_compilation_timeout_duration_ns),
"setting compilation timeout", nnapi_errno);
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksCompilation_setPriority(
compilation, delegate_options.execution_priority),
"setting compilation priority", nnapi_errno);
}
if (delegate_options.vendor_compilation_hints && vendor_plugin_) {
TF_LITE_ENSURE_STATUS(vendor_plugin_->ConfigureCompilationHints(
delegate_options.vendor_compilation_hints, compilation));
}
const int finish_result =
nnapi_->ANeuralNetworksCompilation_finish(compilation);
if (finish_result != ANEURALNETWORKS_NO_ERROR) {
nnapi_->ANeuralNetworksCompilation_free(compilation);
compilation = nullptr;
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, finish_result,
"completing NNAPI compilation", nnapi_errno);
nn_compilation_.reset(compilation);
bool should_use_burst_mode = delegate_options.use_burst_computation;
// Override should_use_burst_mode to true if the selected NNAPI devices are of
// NNAPI feature level 5 or higher.
if (!nnapi_devices_.empty() &&
target_feature_level_ >= kNNAPIRuntimeFeatureLevel5) {
should_use_burst_mode = true;
}
// Create burst object to be reused across a sequence of executions
if (should_use_burst_mode &&
nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI12 &&
nnapi_->ANeuralNetworksBurst_create) {
ANeuralNetworksBurst* burst = nullptr;
const int create_burst_result =
nnapi_->ANeuralNetworksBurst_create(nn_compilation_.get(), &burst);
if (create_burst_result != ANEURALNETWORKS_NO_ERROR) {
nnapi_->ANeuralNetworksBurst_free(burst);
burst = nullptr;
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, create_burst_result,
"creating NNAPI burst", nnapi_errno);
nn_burst_.reset(burst);
}
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::GetOperationsSupportedByTargetNnApiDevices(
TfLiteContext* context, std::vector<int>* supported_nodes,
int* nnapi_errno) {
if (!nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices) {
return kTfLiteError;
}
// Get the number of NNAPI operations mapped.
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping_util_->context);
const int nnapi_model_size =
mapping_context->nnapi_to_tflite_op_mapping_.size();
// Determine the list of operations the device actually supports
std::unique_ptr<bool[]> nnapi_ops_support_flags(new bool[nnapi_model_size]);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices(
nn_model_.get(), nnapi_devices_.data(), nnapi_devices_.size(),
nnapi_ops_support_flags.get()),
"Checking supported operations for devices", nnapi_errno);
// A TfLite op is supported only if all the associated NNAPI ones are.
auto tflite_ops_support_status = std::map<int, bool>();
std::for_each(nodes_.begin(), nodes_.end(),
[&tflite_ops_support_status](int tflite_node_index) {
tflite_ops_support_status[tflite_node_index] = true;
});
for (int nnapi_op_index = 0; nnapi_op_index < nnapi_model_size;
nnapi_op_index++) {
const auto tflite_op_index =
mapping_context->nnapi_to_tflite_op_mapping_[nnapi_op_index];
tflite_ops_support_status[tflite_op_index] &=
nnapi_ops_support_flags[nnapi_op_index];
if (!tflite_ops_support_status[tflite_op_index]) {
if (std::count(non_const_dequantize_output_to_node_mapping_.begin(),
non_const_dequantize_output_to_node_mapping_.end(), -1) <
non_const_dequantize_output_to_node_mapping_.size() ||
std::count(densify_output_to_node_mapping_.begin(),
densify_output_to_node_mapping_.end(),
-1) < densify_output_to_node_mapping_.size()) {
// Only allow full model delegation for sparse model.
return kTfLiteOk;
}
}
}
supported_nodes->clear();
std::for_each(nodes_.begin(), nodes_.end(),
[&supported_nodes, &tflite_ops_support_status](int node_index) {
if (tflite_ops_support_status[node_index]) {
supported_nodes->push_back(node_index);
}
});
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::Invoke(TfLiteContext* context,
TfLiteNode* node, int* nnapi_errno) {
const bool allow_padding =
nnapi_->nnapi_runtime_feature_level > kMinSdkVersionForNNAPI13 &&
nnapi_->ANeuralNetworksExecution_enableInputAndOutputPadding != nullptr;
const auto delegate_options =
StatefulNnApiDelegate::GetOptions(node->delegate);
// Executions are not reusable before Android API 31.
bool execution_is_reusable =
nnapi_->nnapi_runtime_feature_level > kMinSdkVersionForNNAPI13 &&
delegate_options.max_execution_cache_size > 0;
// The output dynamic dimensions cannot be inferred when using custom ops.
bool can_infer_output_shape = !delegate_options.allow_dynamic_dimensions ||
delegate_options.vendor_plugin == nullptr;
ANeuralNetworksExecution* execution = nullptr;
NNAPIExecutionCache::Signature signature;
if (execution_is_reusable) {
signature = CreateExecutionCacheSignature(context, node, delegate_options,
*tensor_memory_map_);
execution = nn_execution_cache_.Get(signature);
}
bool should_create_new_execution = execution == nullptr;
// Manages the lifetime of the new execution.
UniqueExecution unique_execution(nullptr, NNFreeExecution(nnapi_));
if (should_create_new_execution) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(context,
nnapi_->ANeuralNetworksExecution_create(
nn_compilation_.get(), &execution),
"creating NNAPI execution", nnapi_errno);
unique_execution.reset(execution);
if (nnapi_->nnapi_runtime_feature_level > kMinSdkVersionForNNAPI13) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setReusable(execution,
/*reusable=*/true),
"making execution reusable", nnapi_errno);
}
if (delegate_options.vendor_execution_hints && vendor_plugin_) {
TF_LITE_ENSURE_STATUS(vendor_plugin_->ConfigureExecutionHints(
delegate_options.vendor_execution_hints, execution));
}
// Allow padding bytes for execution inputs & outputs if applicable.
if (allow_padding) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_enableInputAndOutputPadding(
execution, /*enable=*/true),
"setting allow padding for execution intputs and outputs",
nnapi_errno);
}
// Set compilation timeout if applicable.
if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI13) {
if (delegate_options.max_execution_timeout_duration_ns > 0) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setTimeout(
execution, delegate_options.max_execution_timeout_duration_ns),
"setting execution timeout", nnapi_errno);
}
if (delegate_options.max_execution_loop_timeout_duration_ns > 0) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setLoopTimeout(
execution,
delegate_options.max_execution_loop_timeout_duration_ns),
"setting execution loop timeout", nnapi_errno);
}
}
// Check if the size of input and output memory pool needs to be resized.
if (delegate_options.allow_dynamic_dimensions) {
size_t total_input_byte_size = 0;
// Make the TensorFlow Lite inputs and outputs to ann_indices.
for (int i : TfLiteIntArrayView(node->inputs)) {
// Constant tensors are not NNAPI inputs.
if (i != kTfLiteOptionalTensor &&
context->tensors[i].allocation_type != kTfLiteMmapRo &&
// The delegate might not have mapped this input (this can
// happen if one tensor is split in several ones)
mapping_util_->TfLiteIndexToNnIndex(mapping_util_.get(), i) != -1) {
if (context->tensors[i].buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
const TfLiteType nn_type_conversion =
mapping_util_->TfLiteIndexToNnTypeConversion(mapping_util_.get(),
i);
int tensor_size = 0;
if (nn_type_conversion == kTfLiteNoType) {
tensor_size = context->tensors[i].bytes;
} else {
size_t type_size;
TF_LITE_ENSURE_OK(
context,
GetSizeOfType(context, nn_type_conversion, &type_size));
tensor_size = NumElements(&context->tensors[i]) * type_size;
}
total_input_byte_size += tensor_size;
total_input_byte_size += GetNumPaddingBytes(tensor_size);
}
}
if (total_input_byte_size > nn_input_memory_->get_byte_size()) {
nn_input_memory_.reset(
new NNMemory(nnapi_, "input_pool", total_input_byte_size));
// Reset all cached executions when the memory pool is recreated.
nn_execution_cache_.Clear();
}
size_t total_output_byte_size = 0;
for (int i : TfLiteIntArrayView(node->outputs)) {
const auto& tensor = context->tensors[i];
if (tensor.buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
size_t tensor_size = tensor.bytes;
if (!can_infer_output_shape && HasUnspecifiedDimension(&tensor)) {
if (tensor_max_size_hints_[i] == 0) {
TF_LITE_KERNEL_LOG(context,
"Missing max tensor size for tensor#%d. When a "
"vendor plugin is supplied, max tensor size is "
"required for all dynamic output tensors.",
i);
return kTfLiteError;
}
tensor_size = std::max(tensor_size, tensor_max_size_hints_[i]);
}
total_output_byte_size += tensor_size;
total_output_byte_size += GetNumPaddingBytes(tensor_size);
}
if (total_output_byte_size > nn_output_memory_->get_byte_size()) {
nn_output_memory_.reset(
new NNMemory(nnapi_, "output_pool", total_output_byte_size));
// Reset all cached executions when the memory pool is recreated.
nn_execution_cache_.Clear();
}
}
if (execution_is_reusable) {
// The execution ownership is transfered to nn_execution_cache_.
nn_execution_cache_.Put(signature, std::move(unique_execution));
unique_execution = nullptr;
}
}
// Set the input tensor buffers. Note: we access tflite tensors using
// absolute indices but NN api indices inputs by relative indices.
int relative_input_index = 0;
const bool use_int8_asymm_signed =
target_feature_level_ >= kMinSdkVersionForNNAPI13;
size_t input_offset = 0;
for (auto absolute_input_index : TfLiteIntArrayView(node->inputs)) {
if (absolute_input_index == kTfLiteOptionalTensor) {
continue;
}
ANeuralNetworksOperandType input_nn_operand_type;
ANeuralNetworksOperandType* input_nn_operand_type_ptr = nullptr;
TfLiteTensor* tensor = &context->tensors[absolute_input_index];
TfLiteType ann_type_equivalent =
mapping_util_->TfLiteIndexToNnTypeConversion(mapping_util_.get(),
absolute_input_index);
if (delegate_options.allow_dynamic_dimensions &&
::tflite::HasUnspecifiedDimension(tensor)) {
input_nn_operand_type = ConvertTensorTypeToNNType(
tensor, ann_type_equivalent, use_int8_asymm_signed);
input_nn_operand_type_ptr = &input_nn_operand_type;
}
if (tensor->allocation_type != kTfLiteMmapRo) {
if (tensor->buffer_handle != kTfLiteNullBufferHandle &&
tensor->buffer_handle < tensor_memory_map_->size()) {
if (should_create_new_execution) {
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context,
nnapi_->ANeuralNetworksExecution_setInputFromMemory(
execution, relative_input_index, input_nn_operand_type_ptr,
tensor_memory_map_->at(tensor->buffer_handle).memory, 0,
tensor->bytes),
"associating NNAPI execution input with a memory object", tensor,
nnapi_errno);
}
relative_input_index++;
continue;
}
int tensor_size = 0;
int padding_bytes = 0;
if (ann_type_equivalent != kTfLiteNoType) {
const auto num_elements = NumElements(tensor);
uint8_t* input_ptr = nn_input_memory_->get_data_ptr() + input_offset;
if (tensor->type == kTfLiteUInt8 &&
ann_type_equivalent == kTfLiteInt32) {
for (int i = 0; i < num_elements; ++i) {
reinterpret_cast<int32_t*>(input_ptr)[i] =
static_cast<const int32_t>(tensor->data.uint8[i]);
}
} else if (tensor->type == kTfLiteInt8 &&
ann_type_equivalent == kTfLiteUInt8) {
// Explicitly convert int8 values to uint8 values.
for (int i = 0; i < num_elements; ++i) {
input_ptr[i] = static_cast<const uint8_t>(
static_cast<int32_t>(tensor->data.int8[i]) + 128);
}
} else if (tensor->type == kTfLiteInt8 &&
ann_type_equivalent == kTfLiteInt32) {
if (use_int8_asymm_signed) {
for (int i = 0; i < num_elements; ++i) {
reinterpret_cast<int32_t*>(input_ptr)[i] =
static_cast<const int32_t>(tensor->data.int8[i]);
}
} else {
for (int i = 0; i < num_elements; ++i) {
reinterpret_cast<int32_t*>(input_ptr)[i] =
static_cast<const int32_t>(tensor->data.int8[i]) + 128;
}
}
} else if (tensor->type == kTfLiteInt64 &&
ann_type_equivalent == kTfLiteInt32) {
// Check that values fit into int32.
int32_t* input_ptr_i32 = reinterpret_cast<int32_t*>(input_ptr);
for (int i = 0; i < num_elements; ++i) {
if (input_ptr_i32[i] < std::numeric_limits<int32_t>::min() ||
input_ptr_i32[i] > std::numeric_limits<int32_t>::max()) {
TF_LITE_KERNEL_LOG(context,
"NN API Delegate: int64 value out of bounds "
"for int32 target NNAPI tensor\n");
return kTfLiteError;
}
input_ptr_i32[i] = static_cast<int32_t>(tensor->data.i64[i]);
}
} else {
TF_LITE_KERNEL_LOG(
context,
"NN API Delegate: unsupported tensor types conversion: "
"from type code %d to type code %d.\n",
tensor->type, ann_type_equivalent);
return kTfLiteError;
}
size_t type_size;
TF_LITE_ENSURE_OK(
context, GetSizeOfType(context, ann_type_equivalent, &type_size));
tensor_size = NumElements(tensor) * type_size;
padding_bytes = GetNumPaddingBytes(tensor_size);
if (should_create_new_execution) {
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context,
nnapi_->ANeuralNetworksExecution_setInputFromMemory(
execution, relative_input_index, input_nn_operand_type_ptr,
nn_input_memory_->get_handle(), input_offset,
GetNNTensorSize(tensor_size, allow_padding)),
"associating NNAPI execution input with a memory object", tensor,
nnapi_errno);
}
} else if (mapping_util_->TfLiteIndexToNnIndex(
mapping_util_.get(), absolute_input_index) != -1) {
// copy data to pre-allocated shared memory.
memcpy(nn_input_memory_->get_data_ptr() + input_offset,
tensor->data.raw, tensor->bytes);
tensor_size = tensor->bytes;
padding_bytes = GetNumPaddingBytes(tensor_size);
if (should_create_new_execution) {
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context,
nnapi_->ANeuralNetworksExecution_setInputFromMemory(
execution, relative_input_index, input_nn_operand_type_ptr,
nn_input_memory_->get_handle(), input_offset,
GetNNTensorSize(tensor_size, allow_padding)),
"associating NNAPI execution input with a memory object", tensor,
nnapi_errno);
}
}
input_offset += tensor_size + padding_bytes;
relative_input_index++;
}
}
// Set the output tensor buffers.
int relative_output_index = 0;
size_t output_offset = 0;
for (auto output_index : TfLiteIntArrayView(node->outputs)) {
// If the NNAPI implementation doesn't have some of the outputs
// they are left unmapped and we should not try to read their value here
if (mapping_util_->TfLiteIndexToNnIndex(mapping_util_.get(),
output_index) == -1) {
continue;
}
ANeuralNetworksOperandType output_nn_operand_type;
ANeuralNetworksOperandType* output_nn_operand_type_ptr = nullptr;
TfLiteTensor* tensor = &context->tensors[output_index];
if (delegate_options.allow_dynamic_dimensions && can_infer_output_shape &&
::tflite::HasUnspecifiedDimension(tensor)) {
TfLiteType ann_type_equivalent =
mapping_util_->TfLiteIndexToNnTypeConversion(mapping_util_.get(),
output_index);
output_nn_operand_type = ConvertTensorTypeToNNType(
tensor, ann_type_equivalent, use_int8_asymm_signed);
output_nn_operand_type_ptr = &output_nn_operand_type;
}
if (tensor->buffer_handle != kTfLiteNullBufferHandle &&
tensor->buffer_handle < tensor_memory_map_->size() &&
should_create_new_execution) {
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context,
nnapi_->ANeuralNetworksExecution_setOutputFromMemory(
execution, relative_output_index, output_nn_operand_type_ptr,
tensor_memory_map_->at(tensor->buffer_handle).memory, 0,
tensor->bytes),
"associating NNAPI execution output to a memory object", tensor,
nnapi_errno);
} else {
size_t tensor_size = tensor->bytes;
if (!can_infer_output_shape && HasUnspecifiedDimension(tensor)) {
tensor_size =
std::max(tensor->bytes, tensor_max_size_hints_[output_index]);
}
int padding_bytes = GetNumPaddingBytes(tensor_size);
if (should_create_new_execution) {
RETURN_TFLITE_ERROR_IF_NN_ERROR_FOR_TENSOR(
context,
nnapi_->ANeuralNetworksExecution_setOutputFromMemory(
execution, relative_output_index, output_nn_operand_type_ptr,
nn_output_memory_->get_handle(), output_offset,
GetNNTensorSize(tensor_size, allow_padding)),
"associating NNAPI execution output to a memory object", tensor,
nnapi_errno);
}
output_offset += tensor_size + padding_bytes;
}
relative_output_index++;
}
// Set memory for NNAPI state_outputs.
for (size_t i = 0; i < model_state_tfl_inputs_.size(); i++) {
int state_tensor_idx = model_state_tfl_inputs_[i];
TfLiteTensor* tensor = &context->tensors[state_tensor_idx];
int padding_bytes = GetNumPaddingBytes(tensor->bytes);
if (should_create_new_execution) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setOutputFromMemory(
execution, relative_output_index, nullptr,
nn_output_memory_->get_handle(), output_offset,
GetNNTensorSize(tensor->bytes, allow_padding)),
"associating NNAPI execution state output to a memory object",
nnapi_errno);
}
output_offset += tensor->bytes + padding_bytes;
relative_output_index++;
}
// Invoke ANN in blocking fashion.
if (nnapi_->android_sdk_version < kMinSdkVersionForNNAPI12) {
ANeuralNetworksEvent* event = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_startCompute(execution, &event),
"starting async computation", nnapi_errno);
const int wait_result = nnapi_->ANeuralNetworksEvent_wait(event);
nnapi_->ANeuralNetworksEvent_free(event);
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, wait_result,
"waiting for async computation completion",
nnapi_errno);
} else {
// Use Burst mode by default for NNAPI 1.2+.
if (nn_burst_) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_burstCompute(execution,
nn_burst_.get()),
"running burst computation", nnapi_errno);
} else {
// Use synchronous execution for NNAPI 1.2+ as a fallback.
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi_->ANeuralNetworksExecution_compute(execution),
"running computation", nnapi_errno);
}
}
// resize dynamic output tensors
if (!can_infer_output_shape) {
relative_output_index = 0;
for (auto output_index : TfLiteIntArrayView(node->outputs)) {
TfLiteTensor* tensor = &context->tensors[output_index];
if (HasUnspecifiedDimension(tensor)) {
auto* new_dims = TfLiteIntArrayCreate(tensor->dims->size);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_getOutputOperandDimensions(
execution, relative_output_index,
reinterpret_cast<uint32_t*>(new_dims->data)),
"get output operand dimensions", nnapi_errno);
TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, tensor, new_dims));
}
relative_output_index++;
}
}
// copy results from shared memory to the destination.
output_offset = 0;
for (auto output_index : TfLiteIntArrayView(node->outputs)) {
TfLiteTensor* tensor = &context->tensors[output_index];
if (tensor->buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
TfLiteType ann_type_equivalent =
mapping_util_->TfLiteIndexToNnTypeConversion(mapping_util_.get(),
output_index);
if (tensor->type == kTfLiteInt8 && ann_type_equivalent == kTfLiteUInt8) {
// Explicitly convert uint8 values to int8 values.
uint8_t* output_ptr = reinterpret_cast<uint8_t*>(
nn_output_memory_->get_data_ptr() + output_offset);
const auto num_elements = NumElements(tensor);
for (int i = 0; i < num_elements; ++i) {
output_ptr[i] =
static_cast<uint8_t>(static_cast<int32_t>(output_ptr[i]) - 128);
}
}
memcpy(tensor->data.raw, nn_output_memory_->get_data_ptr() + output_offset,
tensor->bytes);
size_t tensor_size = tensor->bytes;
if (!can_infer_output_shape && HasUnspecifiedDimension(tensor)) {
tensor_size =
std::max(tensor->bytes, tensor_max_size_hints_[output_index]);
}
output_offset += tensor_size;
output_offset += GetNumPaddingBytes(tensor_size);
}
// The state_out of previous invocation need to be copied to state_in of
// current invocation.
for (size_t i = 0; i < model_state_tfl_inputs_.size(); i++) {
int state_tensor_idx = model_state_tfl_inputs_[i];
TfLiteTensor* tensor = &context->tensors[state_tensor_idx];
memcpy(tensor->data.raw, nn_output_memory_->get_data_ptr() + output_offset,
tensor->bytes);
output_offset += tensor->bytes;
output_offset += GetNumPaddingBytes(tensor->bytes);
}
// copy output of all output tensors in feedback_loops_ into the
// associated input
for (auto feedback_loop : feedback_loops_) {
int output_tensor_idx;
int input_tensor_idx;
std::tie(output_tensor_idx, input_tensor_idx) = feedback_loop;
TfLiteTensor& src = context->tensors[output_tensor_idx];
TfLiteTensor& dest = context->tensors[input_tensor_idx];
memcpy(dest.data.raw, src.data.raw, src.bytes);
}
return kTfLiteOk;
}
void NNAPIDelegateKernel::AddDequantizeOperatorsWhereNeeded(
const TfLiteContext* context, int builtin_code, const TfLiteNode* node,
int tflite_node_index, NNAPIOpBuilder* builder, int* nnapi_errno) {
// Depending on the operator and the input data format, Dequantize
// operators may need to be added. For example when the input is
// floating-point but weights are quantized then the weights will first be
// dequantized to the same format as the input before being passed to the
// operator.
// The tensor determining whether the inputs should be floating-point.
int input_tensor_index = -1;
std::vector<int> inputs_to_potentially_dequantize;
switch (builtin_code) {
case kTfLiteBuiltinConv2d:
case kTfLiteBuiltinFullyConnected: {
input_tensor_index = 0;
// Weights and bias are inputs #1 and #2 respectively and may require
// dequantization.
inputs_to_potentially_dequantize = {1, 2};
break;
}
case kTfLiteBuiltinLstm: {
input_tensor_index = 0;
inputs_to_potentially_dequantize = {1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 20, 21, 22, 23};
break;
}
default:
return;
}
int tensor_id = node->inputs->data[input_tensor_index];
if (tensor_id < 0) return;
// Nothing to do if the input is not floating-point.
if (!IsFloat(context->tensors[tensor_id].type)) return;
for (int i : inputs_to_potentially_dequantize) {
if (i < 0 || i >= node->inputs->size) continue; // Ignore invalid index.
tensor_id = node->inputs->data[i];
if (tensor_id < 0) continue; // Ignore optional input.
const TfLiteType type = context->tensors[tensor_id].type;
// Nothing to do for this tensor if it's not quantized.
if (!IsQuantized(type)) continue;
// Insert Dequantize operator if it hasn't been done already and change
// the node's input accordingly.
builder->AddDequantize(i, node->inputs->data[i], type, tflite_node_index);
}
}
TfLiteStatus NNAPIDelegateKernel::DensifyAndDequantizeConstTensor(
TfLiteContext* context, int densify_node_id, bool should_dequantize,
NNAPIOpBuilder& builder) {
TfLiteNode* densify_node;
TfLiteRegistration* reg;
TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration(
context, densify_node_id, &densify_node, ®));
int sparse_weight_tid = densify_node->inputs->data[0];
auto input_tensor = context->tensors[sparse_weight_tid];
auto output_tensor = context->tensors[densify_node->outputs->data[0]];
if (input_tensor.sparsity == nullptr) {
return kTfLiteError;
}
const int dims_count = output_tensor.dims->size;
std::vector<int> vector_shape(dims_count);
for (int i = 0; i < dims_count; i++) {
vector_shape[i] = output_tensor.dims->data[i];
}
size_t dense_size;
int new_tensor_index = -1;
switch (input_tensor.type) {
case kTfLiteFloat32: {
dense_size = output_tensor.bytes / sizeof(float);
std::vector<float> output_data(dense_size);
tflite::internal::sparsity::FormatConverter<float> converter(
vector_shape, *input_tensor.sparsity);
converter.SparseToDense(static_cast<const float*>(input_tensor.data.data),
dense_size, output_data.data(), context);
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor<float>(
ANEURALNETWORKS_TENSOR_FLOAT32, kTfLiteFloat32, output_tensor.dims,
output_data, output_tensor.params, &new_tensor_index));
break;
}
case kTfLiteFloat16: {
dense_size = output_tensor.bytes / sizeof(Eigen::half);
std::vector<uint16_t> output_data(dense_size);
Eigen::half* unpacked_fp16_data =
reinterpret_cast<Eigen::half*>(output_data.data());
tflite::internal::sparsity::FormatConverter<Eigen::half> converter(
vector_shape, *input_tensor.sparsity);
converter.SparseToDense(
static_cast<const Eigen::half*>(input_tensor.data.data), dense_size,
unpacked_fp16_data, context);
if (should_dequantize) {
// we need to dequantize the fp16 dense tensor
std::vector<float> float_dense_data(dense_size);
for (int i = 0; i < dense_size; ++i) {
float_dense_data[i] = fp16_ieee_to_fp32_value(
reinterpret_cast<uint16_t*>(output_data.data())[i]);
}
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor<float>(
ANEURALNETWORKS_TENSOR_FLOAT32, kTfLiteFloat32, output_tensor.dims,
float_dense_data, output_tensor.params, &new_tensor_index));
} else {
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor<uint16_t>(
ANEURALNETWORKS_TENSOR_FLOAT16, kTfLiteFloat16, output_tensor.dims,
output_data, output_tensor.params, &new_tensor_index));
}
break;
}
case kTfLiteInt8: {
dense_size = output_tensor.bytes / sizeof(int8_t);
std::vector<int8_t> output_data(dense_size);
tflite::internal::sparsity::FormatConverter<int8_t> converter(
vector_shape, *input_tensor.sparsity);
converter.SparseToDense(
static_cast<const int8_t*>(input_tensor.data.data), dense_size,
output_data.data(), context);
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor<int8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED, kTfLiteInt8,
output_tensor.dims, output_data, output_tensor.params,
&new_tensor_index));
break;
}
default: {
return kTfLiteError;
}
}
return kTfLiteOk;
}
TfLiteIntArray* ResizeTfLiteIntArray(TfLiteIntArray* old_array, int new_size,
int init_value) {
TfLiteIntArray* ret = TfLiteIntArrayCreate(new_size);
if (ret) {
int size_to_copy = 0;
if (old_array) {
size_to_copy = new_size > old_array->size ? old_array->size : new_size;
memcpy(ret->data, old_array->data, size_to_copy * sizeof(int));
}
for (int i = size_to_copy; i < ret->size; i++) {
ret->data[i] = init_value;
}
}
TfLiteIntArrayFree(old_array);
return ret;
}
void NNFreeMappingUtil::operator()(NnapiMappingUtilCInterface* mapping_util) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping_util->context);
delete (mapping_context);
mapping_util->context = nullptr;
free(mapping_util);
}
class NnapiMappingUtilCInterfaceImpl {
public:
static int TfLiteIndexToNnIndex(NnapiMappingUtilCInterface* mapping,
int index) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping->context);
const size_t max_size = mapping_context->lite_tensor_to_ann_tensor_.size();
if (index >= 0 && index < max_size)
return mapping_context->lite_tensor_to_ann_tensor_[index];
else
return -1;
}
static int AddNewNonTensorOperand(NnapiMappingUtilCInterface* mapping) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping->context);
return mapping_context->next_ann_tensor_index_++;
}
static int AddDelegateGeneratedInputAnnTensorOperand(
NnapiMappingUtilCInterface* mapping) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping->context);
return mapping_context->next_ann_tensor_index_++;
}
static int AddNewNnTensorIndex(NnapiMappingUtilCInterface* mapping,
int tflite_index) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping->context);
const size_t current_size =
mapping_context->lite_tensor_to_ann_tensor_.size();
if (tflite_index >= current_size) {
mapping_context->lite_tensor_to_ann_tensor_.resize(tflite_index + 1, -1);
}
const int new_tensor_index = mapping_context->next_ann_tensor_index_++;
mapping_context->lite_tensor_to_ann_tensor_[tflite_index] =
new_tensor_index;
return new_tensor_index;
}
static TfLiteType TfLiteIndexToNnTypeConversion(
NnapiMappingUtilCInterface* mapping, int index) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping->context);
const size_t max_size = mapping_context->index_to_type_conversion_.size();
if (index >= 0 && index < max_size)
return static_cast<TfLiteType>(
mapping_context->index_to_type_conversion_[index]);
else
return kTfLiteNoType;
}
static void AddTypeConversion(NnapiMappingUtilCInterface* mapping,
int tflite_index, TfLiteType tflite_type) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping->context);
const size_t current_size =
mapping_context->index_to_type_conversion_.size();
if (tflite_index >= current_size) {
mapping_context->index_to_type_conversion_.resize(tflite_index + 1,
kTfLiteNoType);
}
mapping_context->index_to_type_conversion_[tflite_index] = tflite_type;
}
static void AddNnapiToTfliteOpMapping(NnapiMappingUtilCInterface* mapping,
int tflite_node_index) {
NnapiMappingContext* mapping_context =
reinterpret_cast<NnapiMappingContext*>(mapping->context);
mapping_context->nnapi_to_tflite_op_mapping_.push_back(tflite_node_index);
}
};
NnapiMappingUtilCInterface*
NNAPIDelegateKernel::NnapiMappingUtilCInterfaceCreate() {
NnapiMappingUtilCInterface* mapping =
static_cast<NnapiMappingUtilCInterface*>(
malloc(sizeof(NnapiMappingUtilCInterface)));
mapping->context = new NnapiMappingContext();
mapping->TfLiteIndexToNnIndex =
NnapiMappingUtilCInterfaceImpl::TfLiteIndexToNnIndex;
mapping->AddNewNonTensorOperand =
NnapiMappingUtilCInterfaceImpl::AddNewNonTensorOperand;
mapping->AddDelegateGeneratedInputAnnTensorOperand =
NnapiMappingUtilCInterfaceImpl::AddDelegateGeneratedInputAnnTensorOperand;
mapping->AddNewNnTensorIndex =
NnapiMappingUtilCInterfaceImpl::AddNewNnTensorIndex;
mapping->TfLiteIndexToNnTypeConversion =
NnapiMappingUtilCInterfaceImpl::TfLiteIndexToNnTypeConversion;
mapping->AddTypeConversion =
NnapiMappingUtilCInterfaceImpl::AddTypeConversion;
mapping->AddNnapiToTfliteOpMapping =
NnapiMappingUtilCInterfaceImpl::AddNnapiToTfliteOpMapping;
return mapping;
}
TfLiteStatus NNAPIDelegateKernel::AddOpsAndTensors(
TfLiteContext* context, int* nnapi_errno, bool allow_dynamic_dimensions) {
DequantizeMapping dequantize_mapping;
// The operand builder allows creating a single op. It is created outside
// the for loop to avoid reallocating the vectors.
NNAPIOpBuilder builder(nnapi_, context, mapping_util_.get(),
&dequantize_mapping, &allocation_memory_mapping_,
nn_model_.get(), nnapi_errno,
allow_dynamic_dimensions);
// If we have target accelerators the target SDK version might be
// different than the current android version.
target_feature_level_ = nnapi_->nnapi_runtime_feature_level;
if (!nnapi_devices_.empty()) {
TF_LITE_ENSURE_STATUS(GetTargetFeatureLevel(
context, nnapi_, nnapi_devices_, &target_feature_level_, nnapi_errno));
}
// First path, handle const fp16->fp32 dequantize and densify if needed.
for (auto node_index : nodes_) {
TfLiteNode* node = nullptr;
TfLiteRegistration* registration = nullptr;
TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration(
context, node_index, &node, ®istration));
if (IsDequantizeConstFloat16(context, node, registration)) {
builder.AddTensorInput(node->inputs->data[0], /*hybrid_op=*/false,
NN_TENSOR_FLAG_HALF_TO_FLOAT_CONVERSION |
NN_TENSOR_FLAG_SCALAR_AS_TENSOR);
}
if (IsDensifyConstTensor(context, node, registration)) {
densify_output_to_node_mapping_[node->outputs->data[0]] = node_index;
}
if (IsDequantizeNonConstFloat16(context, node, registration)) {
non_const_dequantize_output_to_node_mapping_[node->outputs->data[0]] =
node_index;
}
}
// Clear the input and output lists for the dequantize path.
builder.ClearInputOuputLists();
// Add other tensors.
for (auto node_index : nodes_) {
// Obtain the op and registration.
TfLiteNode* node;
TfLiteRegistration* reg;
TF_LITE_ENSURE_STATUS(
context->GetNodeAndRegistration(context, node_index, &node, ®));
// skip DENSIFY -> DEQUANTIZE as they are handled elsewhere.
if (IsDensifyConstTensor(context, node, reg) ||
IsDequantizeNonConstFloat16(context, node, reg)) {
continue;
}
// Use vendor plugin to map the node if needed.
if (vendor_plugin_ && vendor_plugin_->ValidateNode(context, reg, node)) {
TF_LITE_ENSURE_STATUS(vendor_plugin_->MapNode(
context, node, node_index, mapping_util_.get(), nn_model_.get()));
continue;
}
// Delegate PACK by lowering it into CONCAT + RESHAPE.
if (reg->builtin_code == kTfLiteBuiltinPack &&
target_feature_level_ < kNNAPIRuntimeFeatureLevel6) {
TF_LITE_ENSURE_STATUS(
builder.TransformPackIntoSupportedOps(node_index, node, reg));
continue;
}
// Delegate UNPACK by lowering it into RESHAPE + SPLIT.
if (reg->builtin_code == kTfLiteBuiltinUnpack) {
TF_LITE_ENSURE_STATUS(
builder.TransformUnpackIntoSupportedOps(node_index, node, reg));
continue;
}
// Delegate SPLIT_V by lowering it into SLICEs.
if (reg->builtin_code == kTfLiteBuiltinSplitV) {
TF_LITE_ENSURE_STATUS(
builder.TransformSplitVIntoSupportedOps(node_index, node, reg));
continue;
}
// Delegate SQUARED_DIFFERENCE by lowering it into SUB + MUL.
if (reg->builtin_code == kTfLiteBuiltinSquaredDifference) {
TF_LITE_ENSURE_STATUS(builder.TransformSquaredDifferenceIntoSupportedOps(
node_index, node, reg));
continue;
}
// Fully quantized full LSTM.
if (target_feature_level_ >= kMinSdkVersionForNNAPI13 &&
reg->builtin_code == kTfLiteBuiltinLstm && isLstmFullKernel(node) &&
context->tensors[node->inputs->data[0]].type == kTfLiteInt8) {
const auto quant8_full_lstm_op_code = ANEURALNETWORKS_QUANTIZED_LSTM;
constexpr int kInputTensor = 0;
constexpr int kInputToInputWeightsTensor = 1;
constexpr int kRecurrentToInputWeightsTensor = 5;
constexpr int kInputGateBiasTensor = 12;
constexpr int kForgetGateBiasTensor = 13;
constexpr int kCellGateBiasTensor = 14;
constexpr int kOutputGateBiasTensor = 15;
constexpr int kProjectionWeightsTensor = 16;
constexpr int kProjectionBiasTensor = 17;
constexpr int kPrevOutputTensor = 18;
// Add input tensors.
for (int input_pos = 0; input_pos < node->inputs->size; ++input_pos) {
const auto input_index = node->inputs->data[input_pos];
if (input_index == kTfLiteOptionalTensor) {
if (input_pos == kInputToInputWeightsTensor ||
input_pos == kRecurrentToInputWeightsTensor ||
input_pos == kProjectionWeightsTensor) {
TF_LITE_ENSURE_STATUS(builder.AddVectorInt8Operand(nullptr, 0));
} else if (input_pos == kInputGateBiasTensor ||
input_pos == kForgetGateBiasTensor ||
input_pos == kCellGateBiasTensor ||
input_pos == kOutputGateBiasTensor ||
input_pos == kProjectionBiasTensor) {
TF_LITE_ENSURE_STATUS(builder.AddVectorInt32Operand(nullptr, 0));
} else { // cell-to-* and layer norm weights.
TF_LITE_ENSURE_STATUS(builder.AddVectorInt16Operand(nullptr, 0));
}
} else {
// Only input and previous output use INT8_ASYM_SIGNED.
int flags =
(input_pos == kInputTensor || input_pos == kPrevOutputTensor)
? NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED
: 0;
TF_LITE_ENSURE_STATUS(
builder.AddTensorInput(input_index, /*hybrid_op=*/false, flags));
}
}
// Add clip parameters.
auto builtin = reinterpret_cast<TfLiteLSTMParams*>(node->builtin_data);
TF_LITE_ENSURE_STATUS(
builder.AddScalarFloat32Operand(builtin->cell_clip));
TF_LITE_ENSURE_STATUS(
builder.AddScalarFloat32Operand(builtin->proj_clip));
// Add quantization parameters for intermediate tensors.
TF_LITE_ENSURE_EQ(context, node->intermediates->size, 5);
for (int intermediate_pos = 0;
intermediate_pos < node->intermediates->size; ++intermediate_pos) {
const auto intermediate_index =
node->intermediates->data[intermediate_pos];
const TfLiteTensor& tensor = context->tensors[intermediate_index];
TfLiteAffineQuantization* quantization_params =
static_cast<TfLiteAffineQuantization*>(tensor.quantization.params);
if (intermediate_pos == 4) {
TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand(
quantization_params->zero_point->data[0]));
}
TF_LITE_ENSURE_STATUS(builder.AddScalarFloat32Operand(
quantization_params->scale->data[0]));
}
// Activation state output.
int ann_index;
builder.AddStateInt8AsymTensor(
node->inputs->data[/*kInputActivationStateTensor*/ 18], &ann_index);
model_state_outputs_.push_back(ann_index);
model_state_tfl_inputs_.push_back(
node->inputs->data[/*kInputActivationStateTensor*/ 18]);
// Cell state output.
builder.AddStateInt16Tensor(
node->inputs->data[/*kInputCellStateTensor*/ 19], &ann_index);
model_state_outputs_.push_back(ann_index);
model_state_tfl_inputs_.push_back(
node->inputs->data[/*kInputCellStateTensor*/ 19]);
// Add output tensors.
for (int output_pos = 0; output_pos < node->outputs->size; ++output_pos) {
const auto output_index = node->outputs->data[output_pos];
TF_LITE_ENSURE_STATUS(builder.AddTensorOutput(
output_index, NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED));
}
builder.FinalizeAddOperation(quant8_full_lstm_op_code, node_index);
continue;
}
const bool hybrid_op = IsHybridOperator(context, reg->builtin_code, node);
const bool scalar_as_tensor = IsScalarInputSupported(reg->builtin_code);
const bool need_int8_conversion =
target_feature_level_ < kMinSdkVersionForNNAPI13 &&
NeedInt8Conversion(context, reg->builtin_code, node);
const bool use_int8_asymm_signed =
target_feature_level_ >= kMinSdkVersionForNNAPI13 && !hybrid_op;
// skip DEQUANTIZE (fp16 -> fp32) as it is handled elsewhere
if (IsDequantizeConstFloat16(context, node, reg)) {
continue;
}
int input_tensor_flags = 0;
if (scalar_as_tensor) {
input_tensor_flags |= NN_TENSOR_FLAG_SCALAR_AS_TENSOR;
}
if (use_int8_asymm_signed) {
input_tensor_flags |= NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED;
}
// On SDK level less than 30, h_swish will be lowered into supported NNAPI
// operations. Since SDK level 30, h_swish is supported as a single
// operation.
if (reg->builtin_code == kTfLiteBuiltinHardSwish &&
nnapi_->android_sdk_version < kMinSdkVersionForNNAPI13) {
builder.TransformHardSwishIntoSupportedOps(
node->inputs->data[0], node->outputs->data[0], need_int8_conversion,
node_index);
continue;
}
// For PACK, NNAPI expects the axis scalar before all input tensors.
if (reg->builtin_code == kTfLiteBuiltinPack) {
const auto* builtin =
reinterpret_cast<TfLitePackParams*>(node->builtin_data);
// NNAPI only accepts non-negative axis.
auto& input_tensor = context->tensors[node->inputs->data[0]];
int axis = builtin->axis < 0 ? input_tensor.dims->size + builtin->axis + 1
: builtin->axis;
TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand(axis));
}
// Map inputs to NN API tensor indices.
for (int input_pos = 0; input_pos < node->inputs->size; ++input_pos) {
if (node->inputs->data[input_pos] != kTfLiteOptionalTensor &&
context->tensors[node->inputs->data[input_pos]].type ==
kTfLiteFloat16 &&
IsConstantTensor(&context->tensors[node->inputs->data[input_pos]])) {
input_tensor_flags |= NN_TENSOR_FLAG_HALF_TO_FLOAT_CONVERSION;
}
if (reg->builtin_code == kTfLiteBuiltinTransposeConv) {
// Everything is added during Map since input tensors
// have different order.
continue;
}
if (reg->builtin_code == kTfLiteBuiltinFullyConnected &&
node->inputs->data[input_pos] == kTfLiteOptionalTensor) {
// skip optional bias and handle it during mapping
continue;
}
const auto input_index = node->inputs->data[input_pos];
// handle sparse weights for Conv2d
if (reg->builtin_code == kTfLiteBuiltinConv2d && input_pos == 1) {
int densify_node_id = -1;
bool should_dequantize = false;
int dequantize_node_id =
non_const_dequantize_output_to_node_mapping_[input_index];
if (dequantize_node_id != -1) {
should_dequantize = true;
// Find densify->dequantize pattern.
TfLiteNode* dequant_node;
TfLiteRegistration* reg;
TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration(
context, dequantize_node_id, &dequant_node, ®));
densify_node_id =
densify_output_to_node_mapping_[dequant_node->inputs->data[0]];
} else {
densify_node_id = densify_output_to_node_mapping_[input_index];
}
if (densify_node_id != -1) {
TF_LITE_ENSURE_STATUS(DensifyAndDequantizeConstTensor(
context, densify_node_id, should_dequantize, builder));
continue;
}
}
if (need_int8_conversion &&
(input_pos == 0 ||
reg->builtin_code == kTfLiteBuiltinFullyConnected ||
reg->builtin_code == kTfLiteBuiltinConv2d ||
reg->builtin_code == kTfLiteBuiltinDepthwiseConv2d ||
reg->builtin_code == kTfLiteBuiltinAdd ||
reg->builtin_code == kTfLiteBuiltinMul ||
reg->builtin_code == kTfLiteBuiltinSub ||
reg->builtin_code == kTfLiteBuiltinConcatenation ||
reg->builtin_code == kTfLiteBuiltinMaximum ||
reg->builtin_code == kTfLiteBuiltinMinimum ||
reg->builtin_code == kTfLiteBuiltinLeakyRelu ||
reg->builtin_code == kTfLiteBuiltinLess ||
reg->builtin_code == kTfLiteBuiltinLessEqual ||
reg->builtin_code == kTfLiteBuiltinPrelu ||
reg->builtin_code == kTfLiteBuiltinGreater ||
reg->builtin_code == kTfLiteBuiltinGreaterEqual ||
reg->builtin_code == kTfLiteBuiltinEqual ||
reg->builtin_code == kTfLiteBuiltinNotEqual ||
reg->builtin_code == kTfLiteBuiltinSelect)) {
// Only selected inputs require int8 conversion.
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(
input_index, hybrid_op,
input_tensor_flags | NN_TENSOR_FLAG_INT8_CONVERSION));
continue;
}
if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmFullKernel(node) &&
input_pos >= 20) {
// Skip layer normalization weights. They are added in the Map
// function (after all the other inputs added there) since layer
// normalization weights are the last four inputs of the LSTM op in
// NNAPI.
continue;
}
if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmBasicKernel(node)) {
// Configuring all inputs in the Map function
continue;
}
if (reg->builtin_code == kTfLiteBuiltinUnidirectionalSequenceLstm) {
if (input_pos >= 20) {
// Skip layer normalization weights. They are added in the Map
// function (after all the other inputs added there) since layer
// normalization weights are the last four inputs of the
// unidirectional sequence LSTM op in NNAPI.
continue;
}
if (input_index == kTfLiteOptionalTensor) {
TF_LITE_ENSURE_STATUS(builder.AddVectorFloat32Operand(nullptr, 0));
continue;
}
}
if ((reg->builtin_code == kTfLiteBuiltinSplit) &&
(input_index == node->inputs->data[0])) {
// Skip the axis input tensor; it will be added as a scalar operand
// by the Map() mapping.
continue;
}
// Pad and Padv2 have an optional parameter for a pad value which has
// to be converted to a scalar type in NN API.
if ((reg->builtin_code == kTfLiteBuiltinPadv2 ||
reg->builtin_code == kTfLiteBuiltinPad) &&
node->inputs->size == 3 && input_pos == 2) {
const int constant_value_id = node->inputs->data[2];
if (constant_value_id == kTfLiteOptionalTensor) {
continue;
}
const TfLiteTensor constant_value = context->tensors[constant_value_id];
switch (constant_value.type) {
case kTfLiteFloat32:
if (constant_value.allocation_type == kTfLiteMmapRo) {
builder.AddScalarFloat32Operand(*constant_value.data.f);
} else {
builder.AddSingleValueTensorAsScalarOperand(
constant_value_id, ANEURALNETWORKS_FLOAT32);
}
break;
case kTfLiteUInt8:
if (constant_value.allocation_type == kTfLiteMmapRo) {
builder.AddScalarInt32Operand(
static_cast<int32_t>(*constant_value.data.uint8));
} else {
builder.AddSingleValueTensorAsScalarOperand(
constant_value_id, ANEURALNETWORKS_INT32);
}
break;
case kTfLiteInt8:
if (constant_value.allocation_type == kTfLiteMmapRo) {
if (need_int8_conversion) {
builder.AddScalarInt32Operand(
static_cast<int32_t>(*constant_value.data.int8) + 128);
} else {
builder.AddScalarInt32Operand(*constant_value.data.int8);
}
} else {
builder.AddSingleValueTensorAsScalarOperand(
constant_value_id, ANEURALNETWORKS_INT32);
}
break;
default:
context->ReportError(context,
"Unsupported type of pad value for pad_v2\n");
return kTfLiteError;
}
continue;
}
if (input_index == kTfLiteOptionalTensor &&
(reg->builtin_code == kTfLiteBuiltinLstm ||
reg->builtin_code == kTfLiteBuiltinSvdf ||
reg->builtin_code == kTfLiteBuiltinBidirectionalSequenceLstm)) {
// properly handle the optional tensor for LSTM and SVDF.
// currently only support float32.
TF_LITE_ENSURE_STATUS(builder.AddVectorFloat32Operand(nullptr, 0));
} else if (reg->builtin_code == kTfLiteBuiltinResizeBilinear ||
reg->builtin_code == kTfLiteBuiltinResizeNearestNeighbor) {
if (input_pos == 0) {
// Only the first input tensor is added. The second one,
// specifying the output height and width, is not added and
// instead the height and width will be added individually as
// scalars by the mapping function returned by Map().
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op,
input_tensor_flags));
}
} else if (reg->builtin_code == kTfLiteBuiltinTopkV2 && input_pos > 0) {
// The K parameter tensor is not handled here but by the functor
// returned by Map, the input tensor is instead added in
// the else clause below
continue;
} else if (reg->builtin_code == kTfLiteBuiltinGather) {
// Everything else is added during Map since input tensors
// have different order.
if (input_pos == 0) {
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op,
input_tensor_flags));
}
continue;
} else if (reg->builtin_code == kTfLiteBuiltinExpandDims &&
input_pos == 1) {
// The axis param is added during Map
continue;
} else if (reg->builtin_code == kTfLiteBuiltinBatchToSpaceNd &&
input_pos == 2) {
// NNAPI does not support crops.
// The Map function will check if all crops are zero.
continue;
} else if (reg->builtin_code == kTfLiteBuiltinArgMin ||
reg->builtin_code == kTfLiteBuiltinArgMax) {
// The first input tensor is added as is. The second one, specifying
// the axis, needs to be converted to a scalar since TFLite uses a
// tensor but NNAPI uses a scalar as the axis.
if (input_pos == 0) {
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op,
input_tensor_flags));
} else {
const int axis_id = node->inputs->data[1];
const TfLiteTensor& axis_tensor = context->tensors[axis_id];
switch (axis_tensor.type) {
case kTfLiteInt32:
if (axis_tensor.allocation_type == kTfLiteMmapRo) {
TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand(
static_cast<int32_t>(*axis_tensor.data.i32)));
} else {
TF_LITE_ENSURE_STATUS(
builder.AddSingleValueTensorAsScalarOperand(
axis_id, ANEURALNETWORKS_INT32));
}
break;
case kTfLiteInt64:
// Map() function already makes sure int64 input is constant.
TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand(
static_cast<int32_t>(*axis_tensor.data.i64)));
break;
default:
return kTfLiteError;
}
}
} else if (reg->builtin_code == kTfLiteBuiltinMaximum ||
reg->builtin_code == kTfLiteBuiltinMinimum) {
const TfLiteTensor& operand_tensor =
context->tensors[node->inputs->data[input_pos]];
if (operand_tensor.dims->size == 0) {
int tensor_index;
TF_LITE_ENSURE_EQ(context, operand_tensor.allocation_type,
kTfLiteMmapRo);
switch (operand_tensor.type) {
case kTfLiteFloat32:
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_FLOAT32, operand_tensor.type, {1},
std::vector<float>(1, operand_tensor.data.f[0]),
operand_tensor.params, &tensor_index));
break;
case kTfLiteUInt8:
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, operand_tensor.type, {1},
std::vector<uint8_t>(1, operand_tensor.data.uint8[0]),
operand_tensor.params, &tensor_index));
break;
case kTfLiteInt8: {
auto params = operand_tensor.params;
if (params.scale == 0.0) {
params.scale = 1.0;
}
if (use_int8_asymm_signed) {
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED,
operand_tensor.type, {1},
std::vector<int8_t>(1, operand_tensor.data.int8[0]), params,
&tensor_index));
} else {
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, operand_tensor.type,
{1},
std::vector<int8_t>(1, operand_tensor.data.int8[0] + 128),
params, &tensor_index));
}
} break;
case kTfLiteInt32:
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, operand_tensor.type, {1},
std::vector<int32_t>(1, operand_tensor.data.i32[0]),
operand_tensor.params, &tensor_index));
break;
default:
return kTfLiteError;
}
} else {
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op,
input_tensor_flags));
}
} else if ((reg->builtin_code == kTfLiteBuiltinReduceAny ||
reg->builtin_code == kTfLiteBuiltinReduceMax ||
reg->builtin_code == kTfLiteBuiltinReduceMin ||
reg->builtin_code == kTfLiteBuiltinReduceProd ||
reg->builtin_code == kTfLiteBuiltinSum ||
reg->builtin_code == kTfLiteBuiltinMean) &&
(input_pos == 1)) {
// The axis needs, be converted to a tensor if specified as scalar
const TfLiteTensor& axis_tensor =
context->tensors[node->inputs->data[input_pos]];
if (axis_tensor.dims->size == 0) {
TF_LITE_ENSURE_STATUS(
builder.AddVectorInt32Operand(axis_tensor.data.i32, 1));
} else {
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op,
input_tensor_flags));
}
} else if (reg->builtin_code == kTfLiteBuiltinFill) {
if (input_pos == 0) {
const int dims_id = node->inputs->data[0];
const TfLiteTensor& dims_tensor = context->tensors[dims_id];
switch (dims_tensor.type) {
case kTfLiteInt32:
TF_LITE_ENSURE_STATUS(
builder.AddTensorInput(input_index, hybrid_op));
break;
case kTfLiteInt64: {
// We made sure that dimensions are constant and fit into int32
// in Map(), so we can safely create a new tensor with casted
// values.
const int dims_size = dims_tensor.dims->data[0];
std::vector<int32_t> dims_int32(dims_size);
std::copy(dims_tensor.data.i64, dims_tensor.data.i64 + dims_size,
dims_int32.begin());
int new_tensor_index = -1;
builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, dims_tensor.dims,
dims_int32, dims_tensor.params, &new_tensor_index);
} break;
default:
return kTfLiteError;
}
} else {
const int value_id = node->inputs->data[1];
const TfLiteTensor& value_tensor = context->tensors[value_id];
switch (value_tensor.type) {
case kTfLiteFloat32:
if (value_tensor.allocation_type == kTfLiteMmapRo) {
TF_LITE_ENSURE_STATUS(
builder.AddScalarFloat32Operand(*value_tensor.data.f));
} else {
TF_LITE_ENSURE_STATUS(
builder.AddSingleValueTensorAsScalarOperand(
value_id, ANEURALNETWORKS_FLOAT32));
}
break;
case kTfLiteInt32:
if (value_tensor.allocation_type == kTfLiteMmapRo) {
TF_LITE_ENSURE_STATUS(
builder.AddScalarInt32Operand(*value_tensor.data.i32));
} else {
TF_LITE_ENSURE_STATUS(
builder.AddSingleValueTensorAsScalarOperand(
value_id, ANEURALNETWORKS_INT32));
}
break;
case kTfLiteInt64:
if (value_tensor.allocation_type == kTfLiteMmapRo) {
// Map() function already makes sure const int64 input fits into
// int32.
TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand(
static_cast<int32_t>(*value_tensor.data.i64)));
} else {
TF_LITE_ENSURE_STATUS(
builder.AddSingleValueTensorAsScalarOperand(
value_id, ANEURALNETWORKS_INT32));
}
break;
default:
return kTfLiteError;
}
}
} else {
TF_LITE_ENSURE_STATUS(
builder.AddTensorInput(input_index, hybrid_op, input_tensor_flags));
}
}
// Get op type and operands
// Fails if the Validate function failed
int nn_op_type;
TF_LITE_ENSURE_STATUS(
Map(context, reg->builtin_code, reg->version, target_feature_level_,
{context, &builder, node, node_index, &model_state_outputs_,
&model_state_tfl_inputs_, &feedback_loops_, nnapi_errno},
&nn_op_type));
// Map outputs to NN API tensor indices.
int output_tensor_flags = 0;
if (need_int8_conversion) {
output_tensor_flags |= NN_TENSOR_FLAG_INT8_CONVERSION;
}
if (use_int8_asymm_signed) {
output_tensor_flags |= NN_TENSOR_FLAG_USE_INT8_ASYMM_SIGNED;
}
// fc_nn_intermediate_output_index is used to indicate whether additional
// RESHAPE op is needed.
int fc_nn_intermediate_output_index = -1;
// mean_nn_intermediate_output_index is used to indicate whether additional
// re-quantization is needed.
int mean_nn_intermediate_output_index = -1;
for (int output_pos = 0; output_pos < node->outputs->size; ++output_pos) {
auto output_index = node->outputs->data[output_pos];
// Outputs for basic LSTM cell are set in the Map function since
if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmBasicKernel(node)) {
continue;
}
// Handle FC with keep_num_dims==true.
if (reg->builtin_code == kTfLiteBuiltinFullyConnected &&
reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data)
->keep_num_dims) {
auto& output_tensor = context->tensors[output_index];
int num_units = output_tensor.dims->data[output_tensor.dims->size - 1];
std::vector<uint32_t> output_dims(2);
output_dims[0] = NumElements(output_tensor.dims) / num_units;
output_dims[1] = num_units;
TF_LITE_ENSURE_STATUS(builder.AddIntermediateOutputTensor(
output_tensor.type, output_dims.size(), output_dims.data(),
output_tensor.params.scale, output_tensor.params.zero_point,
&fc_nn_intermediate_output_index));
} else if (reg->builtin_code == kTfLiteBuiltinMean &&
IsMeanWithDifferentInputOutputQuantization(context, node)) {
// Handle MEAN with different input and output quantization params.
auto& input_tensor = context->tensors[node->inputs->data[0]];
auto& output_tensor = context->tensors[output_index];
TF_LITE_ENSURE_STATUS(builder.AddIntermediateOutputTensor(
output_tensor.type, output_tensor.dims->size,
reinterpret_cast<const uint32_t*>(output_tensor.dims->data),
input_tensor.params.scale, input_tensor.params.zero_point,
&mean_nn_intermediate_output_index, need_int8_conversion));
} else {
TF_LITE_ENSURE_STATUS(
builder.AddTensorOutput(output_index, output_tensor_flags));
}
}
// Dequantize operators may have to be added in case inputs are to be
// floating-point.
AddDequantizeOperatorsWhereNeeded(context, reg->builtin_code, node,
node_index, &builder, nnapi_errno);
TF_LITE_ENSURE_OK(context_,
builder.FinalizeAddOperation(nn_op_type, node_index));
if (fc_nn_intermediate_output_index > -1) {
TF_LITE_ENSURE_STATUS(builder.AppendReshape(
fc_nn_intermediate_output_index, node->outputs->data[0], node_index));
}
if (mean_nn_intermediate_output_index > -1) {
TF_LITE_ENSURE_STATUS(builder.AppendRequantize(
mean_nn_intermediate_output_index, node->outputs->data[0], node_index,
output_tensor_flags));
}
}
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::BuildGraph(
TfLiteContext* context,
const StatefulNnApiDelegate::Options& delegate_options,
const TfLiteIntArray* input_tensors, const TfLiteIntArray* output_tensors,
int* nnapi_errno) {
// Build the ops and tensors.
TF_LITE_ENSURE_STATUS(AddOpsAndTensors(
context, nnapi_errno, delegate_options.allow_dynamic_dimensions));
// Map input and output tensor indices to ANN
std::vector<uint32_t> inputs;
inputs.reserve(input_tensors->size);
std::vector<uint32_t> outputs;
outputs.reserve(output_tensors->size);
size_t total_input_byte_size = 0;
// Make the TensorFlow Lite inputs and outputs to ann_indices.
for (int i : TfLiteIntArrayView(input_tensors)) {
// Constant tensors are not NNAPI inputs.
if (i != kTfLiteOptionalTensor &&
context->tensors[i].allocation_type != kTfLiteMmapRo &&
// The delegate might not have mapped this input (this can
// happen if one tensor is split in several ones)
mapping_util_->TfLiteIndexToNnIndex(mapping_util_.get(), i) != -1) {
inputs.push_back(
mapping_util_->TfLiteIndexToNnIndex(mapping_util_.get(), i));
if (context->tensors[i].buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
const TfLiteType nn_type_conversion =
mapping_util_->TfLiteIndexToNnTypeConversion(mapping_util_.get(), i);
int tensor_size = 0;
if (nn_type_conversion == kTfLiteNoType) {
tensor_size =
std::max(context->tensors[i].bytes, tensor_max_size_hints_[i]);
} else {
size_t type_size;
TF_LITE_ENSURE_OK(
context, GetSizeOfType(context, nn_type_conversion, &type_size));
tensor_size = NumElements(&context->tensors[i]) * type_size;
}
total_input_byte_size += tensor_size;
total_input_byte_size += GetNumPaddingBytes(tensor_size);
}
}
size_t total_output_byte_size = 0;
for (int i : TfLiteIntArrayView(output_tensors)) {
const int output_tensor_ann_index =
mapping_util_->TfLiteIndexToNnIndex(mapping_util_.get(), i);
// Unmapped outputs are not added
if (output_tensor_ann_index != -1) {
outputs.push_back(output_tensor_ann_index);
}
if (context->tensors[i].buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
size_t tensor_size =
std::max(context->tensors[i].bytes, tensor_max_size_hints_[i]);
total_output_byte_size += tensor_size;
total_output_byte_size += GetNumPaddingBytes(tensor_size);
}
// Add state output tensors as model outputs.
for (int i = 0; i < model_state_outputs_.size(); i++) {
outputs.push_back(model_state_outputs_[i]);
auto tfl_state_idx = model_state_tfl_inputs_[i];
total_output_byte_size += context->tensors[tfl_state_idx].bytes;
total_output_byte_size +=
GetNumPaddingBytes(context->tensors[tfl_state_idx].bytes);
}
// Tell ANN to declare inputs/outputs
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksModel_identifyInputsAndOutputs(
nn_model_.get(), inputs.size(), inputs.data(), outputs.size(),
outputs.data()),
"identifying model inputs and outputs", nnapi_errno);
auto allow_fp16 =
context->allow_fp32_relax_to_fp16 | delegate_options.allow_fp16;
if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI11) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksModel_relaxComputationFloat32toFloat16(
nn_model_.get(), allow_fp16),
"set relaxed computation mode for fp32 if possible", nnapi_errno);
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi_->ANeuralNetworksModel_finish(nn_model_.get()),
"finalizing the model", nnapi_errno);
// Create shared memory pool for inputs and outputs.
nn_input_memory_.reset(
new NNMemory(nnapi_, "input_pool", total_input_byte_size));
nn_output_memory_.reset(
new NNMemory(nnapi_, "output_pool", total_output_byte_size));
return kTfLiteOk;
}
} // namespace nnapi
} // namespace delegate
using ::tflite::delegate::nnapi::kMinSdkVersionForNNAPI;
using ::tflite::delegate::nnapi::kMinSdkVersionForNNAPI11;
using ::tflite::delegate::nnapi::kMinSdkVersionForNNAPI12;
using ::tflite::delegate::nnapi::NNAPIDelegateKernel;
StatefulNnApiDelegate::Data::Data(const NnApi* nnapi) : nnapi(nnapi) {}
StatefulNnApiDelegate::Data::Data(std::unique_ptr<const NnApi> nnapi)
: nnapi(nnapi.get()), owned_nnapi(std::move(nnapi)) {}
StatefulNnApiDelegate::Data::~Data() {
std::for_each(std::begin(delegate_state_cache),
std::end(delegate_state_cache),
[](const std::pair<int, NNAPIDelegateKernel*>& entry) {
delete entry.second;
});
}
void StatefulNnApiDelegate::Data::CacheDelegateKernel(
const TfLiteDelegateParams* delegate_params,
NNAPIDelegateKernel* delegate_state) {
const int cache_key = delegate_params->nodes_to_replace->data[0];
delegate_state_cache.emplace(cache_key, delegate_state);
}
NNAPIDelegateKernel* StatefulNnApiDelegate::Data::MaybeGetCachedDelegateKernel(
const TfLiteDelegateParams* delegate_params) {
const int cache_key = delegate_params->nodes_to_replace->data[0];
const auto cached_state = delegate_state_cache.find(cache_key);
if (cached_state != std::end(delegate_state_cache)) {
auto result = cached_state->second;
delegate_state_cache.erase(cached_state);
return result;
} else {
return nullptr;
}
}
void StatefulNnApiDelegate::StatefulNnApiDelegateConstructorImpl(
const Options& options) {
if (options.accelerator_name) {
delegate_data_.accelerator_name = options.accelerator_name;
}
if (options.cache_dir) {
delegate_data_.cache_dir = options.cache_dir;
}
if (options.model_token) {
delegate_data_.model_token = options.model_token;
}
delegate_data_.execution_preference = options.execution_preference;
delegate_data_.disallow_nnapi_cpu = options.disallow_nnapi_cpu;
delegate_data_.max_number_delegated_partitions =
options.max_number_delegated_partitions;
delegate_data_.allow_fp16 = options.allow_fp16;
delegate_data_.execution_priority = options.execution_priority;
delegate_data_.max_compilation_timeout_duration_ns =
options.max_compilation_timeout_duration_ns;
delegate_data_.max_execution_timeout_duration_ns =
options.max_execution_timeout_duration_ns;
delegate_data_.max_execution_loop_timeout_duration_ns =
options.max_execution_loop_timeout_duration_ns;
if (delegate_data_.nnapi->android_sdk_version >= kMinSdkVersionForNNAPI11) {
delegate_data_.allow_dynamic_dimensions = options.allow_dynamic_dimensions;
}
delegate_data_.use_burst_computation = options.use_burst_computation;
delegate_data_.vendor_compilation_hints = options.vendor_compilation_hints;
delegate_data_.vendor_execution_hints = options.vendor_execution_hints;
delegate_data_.vendor_plugin = options.vendor_plugin;
delegate_data_.max_execution_cache_size = options.max_execution_cache_size;
delegate_data_.tensor_max_size_hints = options.tensor_max_size_hints;
TFLITE_LOG_PROD_ONCE(tflite::TFLITE_LOG_INFO,
"Created TensorFlow Lite delegate for NNAPI.");
Prepare = DoPrepare;
CopyFromBufferHandle = DoCopyFromBufferHandle;
CopyToBufferHandle = DoCopyToBufferHandle;
FreeBufferHandle = DoFreeBufferHandle;
data_ = &delegate_data_;
if (delegate_data_.allow_dynamic_dimensions) {
flags |= kTfLiteDelegateFlagsAllowDynamicTensors;
// TFLite cannot propagate tensor shapes if custom operators are used.
if (!delegate_data_.vendor_plugin) {
flags |= kTfLiteDelegateFlagsRequirePropagatedShapes;
}
}
}
StatefulNnApiDelegate::StatefulNnApiDelegate(const NnApi* nnapi)
: StatefulNnApiDelegate(nnapi, Options()) {}
StatefulNnApiDelegate::StatefulNnApiDelegate(Options options)
: StatefulNnApiDelegate(NnApiImplementation(), options) {}
StatefulNnApiDelegate::StatefulNnApiDelegate(
const NnApiSLDriverImplFL5* nnapi_support_library_driver, Options options)
: TfLiteDelegate(TfLiteDelegateCreate()),
delegate_data_(
CreateNnApiFromSupportLibrary(nnapi_support_library_driver)) {
StatefulNnApiDelegateConstructorImpl(options);
}
StatefulNnApiDelegate::StatefulNnApiDelegate(const NnApi* nnapi,
Options options)
: TfLiteDelegate(TfLiteDelegateCreate()), delegate_data_(nnapi) {
StatefulNnApiDelegateConstructorImpl(options);
}
StatefulNnApiDelegate::StatefulNnApiDelegate()
: StatefulNnApiDelegate(Options()) {}
const StatefulNnApiDelegate::Options StatefulNnApiDelegate::GetOptions(
TfLiteDelegate* delegate) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
StatefulNnApiDelegate::Options options;
options.execution_preference = delegate_data->execution_preference;
options.accelerator_name = delegate_data->accelerator_name.empty()
? nullptr
: delegate_data->accelerator_name.c_str();
options.cache_dir = delegate_data->cache_dir.empty()
? nullptr
: delegate_data->cache_dir.c_str();
options.model_token = delegate_data->model_token.empty()
? nullptr
: delegate_data->model_token.c_str();
options.disallow_nnapi_cpu = delegate_data->disallow_nnapi_cpu;
options.max_number_delegated_partitions =
delegate_data->max_number_delegated_partitions;
options.allow_fp16 = delegate_data->allow_fp16;
options.execution_priority = delegate_data->execution_priority;
options.max_compilation_timeout_duration_ns =
delegate_data->max_compilation_timeout_duration_ns;
options.max_execution_timeout_duration_ns =
delegate_data->max_execution_timeout_duration_ns;
options.max_execution_loop_timeout_duration_ns =
delegate_data->max_execution_loop_timeout_duration_ns;
options.allow_dynamic_dimensions = delegate_data->allow_dynamic_dimensions;
options.use_burst_computation = delegate_data->use_burst_computation;
options.vendor_compilation_hints = delegate_data->vendor_compilation_hints;
options.vendor_execution_hints = delegate_data->vendor_execution_hints;
options.vendor_plugin = delegate_data->vendor_plugin;
options.max_execution_cache_size = delegate_data->max_execution_cache_size;
options.tensor_max_size_hints = delegate_data->tensor_max_size_hints;
return options;
}
const std::vector<StatefulNnApiDelegate::MemoryRegistration>&
StatefulNnApiDelegate::GetTensorMemoryMap(TfLiteDelegate* delegate) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
return delegate_data->tensor_memory_map;
}
delegates::Serialization* StatefulNnApiDelegate::GetCache(
TfLiteDelegate* delegate) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
return delegate_data->cache.get();
}
TfLiteBufferHandle StatefulNnApiDelegate::RegisterNnapiMemory(
ANeuralNetworksMemory* memory, CopyToHostTensorFnPtr callback,
void* callback_context) {
uint64_t timestamp = delegate_data_.next_buffer_handle_timestamp++;
int map_size = delegate_data_.tensor_memory_map.size();
for (int i = 0; i < map_size; i++) {
if (delegate_data_.tensor_memory_map[i].memory == nullptr) {
delegate_data_.tensor_memory_map[i] = {memory, callback, callback_context,
timestamp};
return i;
}
}
delegate_data_.tensor_memory_map.push_back(
{memory, callback, callback_context, timestamp});
return map_size;
}
TfLiteStatus StatefulNnApiDelegate::DoCopyFromBufferHandle(
TfLiteContext* context, TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
if (buffer_handle < 0 ||
buffer_handle >= delegate_data->tensor_memory_map.size()) {
return kTfLiteError;
}
auto memory = delegate_data->tensor_memory_map[buffer_handle].memory;
auto callback = delegate_data->tensor_memory_map[buffer_handle].callback;
auto callback_context =
delegate_data->tensor_memory_map[buffer_handle].callback_context;
if (!memory || !callback) {
return kTfLiteError;
}
return callback(tensor, memory, 0, tensor->bytes, callback_context);
}
TfLiteStatus StatefulNnApiDelegate::DoCopyToBufferHandle(
TfLiteContext* context, TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) {
return kTfLiteError;
}
void StatefulNnApiDelegate::DoFreeBufferHandle(TfLiteContext* context,
TfLiteDelegate* delegate,
TfLiteBufferHandle* handle) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
if (*handle >= 0 && *handle < delegate_data->tensor_memory_map.size()) {
delegate_data->tensor_memory_map[*handle] = {nullptr, nullptr, nullptr};
*handle = kTfLiteNullBufferHandle;
}
}
int StatefulNnApiDelegate::GetNnApiErrno() const {
return delegate_data_.nnapi_errno;
}
// static
TfLiteStatus StatefulNnApiDelegate::GetNodesSupportedByAccelerator(
TfLiteContext* context, TfLiteDelegate* delegate, const NnApi* nnapi,
const std::vector<int>& supported_nodes,
std::vector<int>* device_supported_nodes, int* num_partitions,
TfLiteDelegateParams** params_array, int* nnapi_errno) {
auto* delegate_data = static_cast<Data*>(delegate->data_);
// The first entry in the array is the element count
auto supported_nodes_int_array = BuildTfLiteIntArray(supported_nodes);
TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
context, supported_nodes_int_array.get(), params_array, num_partitions));
// For each partition check if which nodes are actually supported by the
// target accelerators.
delegate_data->delegate_state_cache.clear();
for (int idx = 0; idx < *num_partitions; idx++) {
const auto& partition_params = (*params_array)[idx];
std::unique_ptr<NNAPIDelegateKernel> kernel_state(
new NNAPIDelegateKernel(nnapi, delegate_data->vendor_plugin));
TfLiteDelegateParams params_with_delegate = partition_params;
params_with_delegate.delegate = delegate;
TF_LITE_ENSURE_STATUS(
kernel_state->Init(context, ¶ms_with_delegate, nnapi_errno));
std::vector<int> supported_partition_nodes;
TF_LITE_ENSURE_STATUS(
kernel_state->GetOperationsSupportedByTargetNnApiDevices(
context, &supported_partition_nodes, nnapi_errno));
device_supported_nodes->insert(device_supported_nodes->end(),
supported_partition_nodes.begin(),
supported_partition_nodes.end());
bool model_fully_supported = (supported_partition_nodes.size() ==
partition_params.nodes_to_replace->size);
if (model_fully_supported) {
delegate_data->CacheDelegateKernel(&partition_params,
kernel_state.release());
}
}
if (device_supported_nodes->size() != supported_nodes.size()) {
// We changed the set of nodes to delegate this will create a different
// partitioning layout.
auto device_sup_nodes_int_array =
BuildTfLiteIntArray(*device_supported_nodes);
TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
context, device_sup_nodes_int_array.get(), params_array,
num_partitions));
}
return kTfLiteOk;
}
// static
TfLiteStatus StatefulNnApiDelegate::LimitDelegatedPartitions(
int max_partitions,
std::vector<TfLiteDelegateParams> partition_params_array,
std::vector<int>* nodes_to_delegate) {
int num_partitions = partition_params_array.size();
if (max_partitions <= 0 || num_partitions <= max_partitions) {
return kTfLiteOk;
}
int number_delegated_partitions = std::count_if(
partition_params_array.begin(), partition_params_array.end(),
[nodes_to_delegate](const TfLiteDelegateParams& partition_params) {
return std::find(nodes_to_delegate->begin(), nodes_to_delegate->end(),
partition_params.nodes_to_replace->data[0]) !=
nodes_to_delegate->end();
});
if (number_delegated_partitions > max_partitions) {
std::sort(partition_params_array.begin(), partition_params_array.end(),
[](const TfLiteDelegateParams& left,
const TfLiteDelegateParams& right) -> bool {
// Reverse sort
return left.nodes_to_replace->size >
right.nodes_to_replace->size;
});
nodes_to_delegate->clear();
for (int i = 0; i < max_partitions; i++) {
const TfLiteDelegateParams& partition_params = partition_params_array[i];
nodes_to_delegate->insert(nodes_to_delegate->end(),
partition_params.nodes_to_replace->data,
partition_params.nodes_to_replace->data +
partition_params.nodes_to_replace->size);
}
}
return kTfLiteOk;
}
static std::vector<int> GetSupportedOpsWithFp16WeightRemapping(
TfLiteContext* context, int target_feature_level,
bool is_accelerator_specified, int max_number_delegated_partitions) {
std::vector<int> supported_nodes;
delegates::IsNodeSupportedFn node_supported_fn =
[=](TfLiteContext* context, TfLiteNode* node,
TfLiteRegistration* registration,
std::string* unsupported_details) -> bool {
std::vector<delegate::nnapi::NNAPIValidationFailure> map_failures;
const auto is_supported = NNAPIDelegateKernel::Validate(
context, registration, target_feature_level, node,
is_accelerator_specified, nullptr, &map_failures);
if (!is_supported) {
if (unsupported_details) {
for (auto& failure : map_failures) {
unsupported_details->append(failure.message.c_str());
}
}
return false;
}
return true;
};
delegates::FP16GraphPartitionHelper partition_helper(context,
node_supported_fn);
std::set<std::string> unsupported_nodes_info;
if (partition_helper.Partition(&unsupported_nodes_info) == kTfLiteOk) {
supported_nodes = partition_helper.GetNodesOfFirstNLargestPartitions();
}
return supported_nodes;
}
TfLiteStatus StatefulNnApiDelegate::DoPrepare(TfLiteContext* context,
TfLiteDelegate* delegate) {
auto* delegate_data = static_cast<Data*>(delegate->data_);
int* nnapi_errno = &(delegate_data->nnapi_errno);
const NnApi* nnapi = delegate_data->nnapi;
// Resetting the error code when the delegate is initialized
// by TFLite. This causes the error to be reset if reusing the same
// StatefulNnApiDelegate after a failure
*nnapi_errno = 0;
// Do not check nodes_ if NN API is unavailable.
if (nnapi->android_sdk_version < kMinSdkVersionForNNAPI ||
!nnapi->nnapi_exists) {
return kTfLiteOk;
}
int target_feature_level = nnapi->android_sdk_version;
const StatefulNnApiDelegate::Options delegate_options =
StatefulNnApiDelegate::GetOptions(delegate);
// For NNAPI 1.2+, check if there is any accelerator available.
// If not, don't delegate to NNAPI's CPU reference implementation unless
// it has been specified as target accelerator.
if (nnapi->android_sdk_version >= kMinSdkVersionForNNAPI12) {
if (ShouldUseTargetDevices(delegate_options, nnapi)) {
std::vector<ANeuralNetworksDevice*> devices;
TF_LITE_ENSURE_STATUS(
GetTargetDevices(context, delegate, nnapi, nnapi_errno, &devices));
if (devices.empty()) {
if (delegate_options.accelerator_name) {
// There was a selected device and it is not available.
return kTfLiteError;
} else {
// Only nnapi-reference is available but was disabled by the delegate
// options
return kTfLiteOk;
}
}
TF_LITE_ENSURE_STATUS(GetTargetFeatureLevel(
context, nnapi, devices, &target_feature_level, nnapi_errno));
} else {
// If no accelerator is specified, only use NNAPI if an accelerator is
// available. Any available accelerator will make the device_count larger
// than 1. More sophisticated check and allowlisting can be added later.
uint32_t device_count = 0;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworks_getDeviceCount(&device_count),
"getting number of NNAPI devices", nnapi_errno);
if (device_count <= 1) {
return kTfLiteOk;
}
}
}
std::vector<int> supported_nodes;
// We don't care about all nodes_, we only care about ones in the
// current plan.
TfLiteIntArray* execution_plan;
TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &execution_plan));
// Copy the execution plan and wrap it with unique_ptr.
std::unique_ptr<TfLiteIntArray, decltype(&TfLiteIntArrayFree)> plan(
TfLiteIntArrayCopy(execution_plan), TfLiteIntArrayFree);
// Check for every node if it is supported
const bool is_accelerator_specified = ShouldUseTargetDevices(
delegate_options, nnapi, /*exclude_nnapi_reference=*/true);
std::vector<delegate::nnapi::NNAPIValidationFailure> map_failures;
// First pass through execution plan to remember mapping of FP16->FP32
// dequantizations in the graph.
std::vector<int> fp16_to_fp32(context->tensors_size, -1);
bool should_prune_fp16_dequantize = false;
for (int i = 0; i < plan->size; ++i) {
const int node_id = plan->data[i];
TfLiteNode* node = nullptr;
TfLiteRegistration* registration = nullptr;
TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration(
context, node_id, &node, ®istration));
if (IsDequantizeConstFloat16(context, node, registration)) {
should_prune_fp16_dequantize = true;
fp16_to_fp32[node->inputs->data[0]] = node->outputs->data[0];
}
}
if (should_prune_fp16_dequantize) {
supported_nodes = GetSupportedOpsWithFp16WeightRemapping(
context, target_feature_level, is_accelerator_specified,
delegate_options.max_number_delegated_partitions);
} else {
for (int node_index : TfLiteIntArrayView(plan.get())) {
TfLiteNode* node;
TfLiteRegistration* registration;
TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration(
context, node_index, &node, ®istration));
if (NNAPIDelegateKernel::Validate(
context, registration, target_feature_level, node,
is_accelerator_specified, delegate_options.vendor_plugin,
&map_failures)) {
supported_nodes.push_back(node_index);
}
#ifdef NNAPI_VERBOSE_VALIDATION
for (auto& failure : map_failures) {
TFLITE_LOG_PROD(
TFLITE_LOG_WARNING,
"Operator %s (v%d) refused by NNAPI delegate: %s",
tflite::EnumNameBuiltinOperator(
static_cast<BuiltinOperator>(registration->builtin_code)),
registration->version, failure.message.c_str());
}
map_failures.clear();
#endif
}
}
// If there are no delegated nodes, short-circuit node replacement.
if (supported_nodes.empty()) {
return kTfLiteOk;
}
// NN API Delegate Registration (the pseudo kernel that will invoke NN
// API node sub sets)
static const TfLiteRegistration nnapi_delegate_kernel = {
.init = [](TfLiteContext* context, const char* buffer,
size_t length) -> void* {
const TfLiteDelegateParams* params =
reinterpret_cast<const TfLiteDelegateParams*>(buffer);
auto* delegate_data = static_cast<Data*>(params->delegate->data_);
int* nnapi_errno = &(delegate_data->nnapi_errno);
NNAPIDelegateKernel* kernel_state =
delegate_data->MaybeGetCachedDelegateKernel(params);
if (!kernel_state) {
kernel_state = new NNAPIDelegateKernel(delegate_data->nnapi,
delegate_data->vendor_plugin);
kernel_state->Init(context, params, nnapi_errno);
}
return kernel_state;
},
.free = [](TfLiteContext* context, void* buffer) -> void {
delete reinterpret_cast<NNAPIDelegateKernel*>(buffer);
},
.prepare = [](TfLiteContext* context, TfLiteNode* node) -> TfLiteStatus {
NNAPIDelegateKernel* state =
reinterpret_cast<NNAPIDelegateKernel*>(node->user_data);
int* nnapi_errno =
&(static_cast<Data*>(node->delegate->data_)->nnapi_errno);
return state->Prepare(context, node, nnapi_errno);
},
.invoke = [](TfLiteContext* context, TfLiteNode* node) -> TfLiteStatus {
NNAPIDelegateKernel* state =
reinterpret_cast<NNAPIDelegateKernel*>(node->user_data);
int* nnapi_errno =
&(static_cast<Data*>(node->delegate->data_)->nnapi_errno);
return state->Invoke(context, node, nnapi_errno);
},
.profiling_string = nullptr,
.builtin_code = kTfLiteBuiltinDelegate,
.custom_name = "TfLiteNnapiDelegate",
.version = 1,
};
// Initialize caching, if applicable, from Options.
const char* cache_dir = delegate_options.cache_dir;
const char* model_token = delegate_options.model_token;
delegates::SerializationParams params = {model_token, cache_dir};
if (nnapi->android_sdk_version >= kMinSdkVersionForNNAPI12 && cache_dir &&
model_token) {
delegate_data->cache.reset(new delegates::Serialization(params));
}
delegates::Serialization* cache_ptr = delegate_data->cache.get();
if (cache_ptr) {
// Reuse cached delegation decision if possible.
std::string accelerator_id = NnApiBackendId(delegate_options);
TfLiteIntArray* cached_nodes_to_delegate = nullptr;
if (delegates::GetDelegatedNodes(context, cache_ptr, accelerator_id,
&cached_nodes_to_delegate) == kTfLiteOk) {
if (cached_nodes_to_delegate->size == 0) return kTfLiteOk;
auto status = context->ReplaceNodeSubsetsWithDelegateKernels(
context, nnapi_delegate_kernel, cached_nodes_to_delegate, delegate);
TfLiteIntArrayFree(cached_nodes_to_delegate);
return status;
}
}
std::vector<int> nodes_to_delegate;
int num_partitions;
TfLiteDelegateParams* params_array;
if (is_accelerator_specified &&
nnapi->android_sdk_version >= kMinSdkVersionForNNAPI12) {
// Filtering out nodes not supported by target accelerators.
// Cannot query supported operation before NNAPI 1.2
TF_LITE_ENSURE_STATUS(GetNodesSupportedByAccelerator(
context, delegate, nnapi, supported_nodes, &nodes_to_delegate,
&num_partitions, ¶ms_array, nnapi_errno));
} else {
nodes_to_delegate = supported_nodes;
auto supported_nodes_int_array = BuildTfLiteIntArray(supported_nodes);
TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
context, supported_nodes_int_array.get(), ¶ms_array,
&num_partitions));
}
// FP16GraphPartitionHelper alters the orginal graph by remapping fp32
// dequantize output to fp16 input. In the case of accelerator backends does
// not support all the nodes of the fp16 model, We need to restore original
// graph in order for things to work.
if (should_prune_fp16_dequantize &&
supported_nodes.size() != nodes_to_delegate.size()) {
// Restore original graph
for (int execution_plan_index = 0; execution_plan_index < plan->size;
++execution_plan_index) {
int node_index = plan->data[execution_plan_index];
TfLiteNode* node = nullptr;
TfLiteRegistration* reg = nullptr;
TF_LITE_ENSURE_STATUS(
context->GetNodeAndRegistration(context, node_index, &node, ®));
if (reg->builtin_code == kTfLiteBuiltinDequantize) continue;
for (int i = 0; i < node->inputs->size; ++i) {
const int original_input_idx = node->inputs->data[i];
if (original_input_idx == kTfLiteOptionalTensor) continue;
// Use original FP32 input
if (context->tensors[original_input_idx].type == kTfLiteFloat16 &&
fp16_to_fp32[original_input_idx] != -1) {
node->inputs->data[i] = fp16_to_fp32[original_input_idx];
}
}
}
// Only allow full model delegation for fp16 model.
return kTfLiteOk;
}
TF_LITE_ENSURE_STATUS(
LimitDelegatedPartitions(delegate_options.max_number_delegated_partitions,
std::vector<TfLiteDelegateParams>(
params_array, params_array + num_partitions),
&nodes_to_delegate));
auto nodes_to_delegate_int_array = BuildTfLiteIntArray(nodes_to_delegate);
if (cache_ptr) {
// Cache list of nodes to be delegated for later.
std::string accelerator_id = NnApiBackendId(delegate_options);
if (delegates::SaveDelegatedNodes(context, cache_ptr, accelerator_id,
nodes_to_delegate_int_array.get()) !=
kTfLiteOk) {
// Not a critical error.
TF_LITE_KERNEL_LOG(context, "Could not save delegated nodes");
}
}
if (nodes_to_delegate_int_array->size == 0) {
return kTfLiteOk;
} else {
// Request TFLite to partition the graph and make kernels
// for each independent node sub set a new nnapi_delegate_kernel.
return context->ReplaceNodeSubsetsWithDelegateKernels(
context, nnapi_delegate_kernel, nodes_to_delegate_int_array.get(),
delegate);
}
}
// Returns a singleton NNAPI Delegate that can check for support of ops.
TfLiteDelegate* NnApiDelegate() {
static StatefulNnApiDelegate* delegate = new StatefulNnApiDelegate();
return delegate;
}
} // namespace tflite
|
/*
* This file is part of the CN24 semantic segmentation software,
* copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
*
* For licensing information, see the LICENSE file included with this project.
*/
#ifndef BUILD_GUI
#include "NKContext.h"
#include "Log.h"
namespace Conv {
NKContext::NKContext(unsigned int width, unsigned int height):
width_(width), height_(height) {
LOGERROR << "GUI not supported due to build options!";
}
NKContext::~NKContext() {
}
void NKContext::ProcessEvents() {
}
void NKContext::Draw() {
}
NKImage::NKImage(NKContext &context, const Tensor &tensor, unsigned int sample) :
context_(context), tensor_(tensor), sample_(sample) {
}
NKImage::~NKImage() {
}
void* NKImage::ptr() {
return nullptr;
}
void NKImage::Update() {
}
NKImage::operator struct nk_image() const {
struct nk_image t;
return t;
}
}
#endif
|
#include "gpiq_rjsxx.h"
#include "ui_gpiq_rjsxx.h"
#include <QDebug>
gpiq_rjsxx::gpiq_rjsxx(QWidget *parent) :
QDialog(parent),
ui(new Ui::gpiq_rjsxx)
{
ui->setupUi(this);
connect(ui->gpiq_rjsxx_grid_c, SIGNAL(clicked()), this, SLOT(gpiq_rjsxx_grid_cClick()));
connect(ui->gpiq_rjsxx_back_c, SIGNAL(clicked()), this, SLOT(gpiq_rjsxx_back_cClick()));
connect(ui->gpiq_rjsxx_next_c, SIGNAL(clicked()), this, SLOT(gpiq_rjsxx_next_cClick()));
connect(ui->gpiq_rjsxx_exit_c, SIGNAL(clicked()), this, SLOT(gpiq_rjsxx_exit_cClick()));
connect(ui->gpiq_rjsxx_dbn_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_dbn_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_db_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_db_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_dokk_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_dokk_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_data_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_data_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_dokn_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_dokn_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_dokd_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_dokd_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_kr_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_kr_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_krn_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_krn_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_to_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_to_eTextChanged(QString)));
connect(ui->gpiq_rjsxx_rub_e, SIGNAL(textChanged(QString)), this, SLOT(gpiq_rjsxx_rub_eTextChanged(QString)));
model.setTable("gpiq_rj");
model.select();
model.setEditStrategy(QSqlTableModel::OnFieldChange);
size = model.rowCount();
currentIndex = 0;
changeEdits(size - 1);
ui->gpiq_rjsxx_dbn_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_db_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_dokk_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_data_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_dokn_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_dokd_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_kr_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_krn_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_to_e->setStyleSheet("color: red;");
ui->gpiq_rjsxx_rub_e->setStyleSheet("color: red;");
}
gpiq_rjsxx::~gpiq_rjsxx()
{
delete ui;
}
void gpiq_rjsxx::changeEdits(int newIndex) {
if (newIndex >=0 && newIndex < size) {
currentIndex = newIndex;
QString gpiq_rj_db = model.record(currentIndex).value("Gpiq_rj_db").toString();
QString gpiq_rj_dbn = model.record(currentIndex).value("Gpiq_rj_dbn").toString();
QString gpiq_rj_dokk = model.record(currentIndex).value("Gpiq_rj_dokk").toString();
QString gpiq_rj_dokd = model.record(currentIndex).value("Gpiq_rj_dokd").toString();
QString gpiq_rj_dokn = model.record(currentIndex).value("Gpiq_rj_dokn").toString();
QString gpiq_rj_data = model.record(currentIndex).value("Gpiq_rj_data").toString();
QString gpiq_rj_to = model.record(currentIndex).value("Gpiq_rj_to").toString();
QString gpiq_rj_kr = model.record(currentIndex).value("Gpiq_rj_kr").toString();
QString gpiq_rj_krn = model.record(currentIndex).value("Gpiq_rj_krn").toString();
QString gpiq_rj_rub = model.record(currentIndex).value("Gpiq_rj_rub").toString();
ui->gpiq_rjsxx_db_e->setText(gpiq_rj_db);
ui->gpiq_rjsxx_dbn_e->setText(gpiq_rj_dbn);
ui->gpiq_rjsxx_dokk_e->setText(gpiq_rj_dokk);
ui->gpiq_rjsxx_dokd_e->setText(gpiq_rj_dokd);
ui->gpiq_rjsxx_dokn_e->setText(gpiq_rj_dokn);
ui->gpiq_rjsxx_data_e->setText(gpiq_rj_data);
ui->gpiq_rjsxx_kr_e->setText(gpiq_rj_kr);
ui->gpiq_rjsxx_krn_e->setText(gpiq_rj_krn);
ui->gpiq_rjsxx_rub_e->setText(gpiq_rj_rub);
ui->gpiq_rjsxx_to_e->setText(gpiq_rj_to);
}
}
void gpiq_rjsxx::gpiq_rjsxx_grid_cClick() {
gpiq_xxsgrid* gpiq_xxsgrid1 = new gpiq_xxsgrid(this, &model, currentIndex);
gpiq_xxsgrid1->setWindowTitle("gpiq_rjsxx viberi dokument");
gpiq_xxsgrid1->exec();
changeEdits(gpiq_xxsgrid1->currentIndex);
}
void gpiq_rjsxx::gpiq_rjsxx_back_cClick() {
changeEdits(currentIndex - 1);
}
void gpiq_rjsxx::gpiq_rjsxx_next_cClick() {
changeEdits(currentIndex + 1);
}
void gpiq_rjsxx::gpiq_rjsxx_exit_cClick() {
QDialog::reject();
}
void gpiq_rjsxx::gpiq_rjsxx_add_cClick() {
model.insertRow(size);
model.setData(model.index(size,0), 0);
if(model.submitAll()) {
model.database().commit();
} else {
model.database().rollback();
qDebug() << "Database Write Error" <<
"The database reported an error: " <<
model.lastError().text();
}
size++;
changeEdits(size - 1);
}
void gpiq_rjsxx::gpiq_rjsxx_del_cClick() {
model.removeRow(currentIndex);
if(model.submitAll()) {
model.database().commit();
} else {
model.database().rollback();
qDebug() << "Database Write Error" <<
"The database reported an error: " <<
model.lastError().text();
}
size--;
model.select();
changeEdits(currentIndex - 1);
}
void gpiq_rjsxx::gpiq_rjsxx_db_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_db")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_dbn_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_dbn")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_dokk_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_dokk")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_kr_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_kr")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_krn_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_krn")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_data_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_data")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_dokn_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_dokn")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_dokd_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_dokd")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_to_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_to")), text);
}
void gpiq_rjsxx::gpiq_rjsxx_rub_eTextChanged(QString text) {
model.setData(model.index(currentIndex, model.fieldIndex("Gpiq_rj_rub")), text);
}
|
#pragma once
#include "Sphere.h"
Sphere::Sphere(Point3 center, double radius, Material* material) :
Center(center),
Radius(radius),
m_Material(material)
{
}
std::optional<IntersectionRecord> Sphere::Intersects(const Ray& ray, const SampleBounds& sampleBounds) const
{
Vector3 distance = ray.Origin - Center;
double a = ray.Direction.GetDotProduct();
double half_b = distance.GetDotProduct(ray.Direction);
double c = distance.GetDotProduct() - Radius * Radius;
double discriminant = half_b * half_b - a * c;
// < 0 no solutions
// == 0 1 solution
// > 9 2 solutions
if (discriminant < 0)
{
return std::nullopt;
}
double discriminantRoot = std::sqrt(discriminant);
double possible_hit_point = (-half_b - discriminantRoot) / a;
if (possible_hit_point < sampleBounds.MinSample || possible_hit_point > sampleBounds.MaxSample)
{
possible_hit_point = (-half_b + discriminantRoot) / a;
if (possible_hit_point < sampleBounds.MinSample || possible_hit_point > sampleBounds.MaxSample)
{
return std::nullopt;
}
}
IntersectionRecord ray_intersection_record;
ray_intersection_record.Point = ray.Sample(possible_hit_point);
ray_intersection_record.RaySamplePoint = possible_hit_point;
// Normalizing via radius here saves determining the length later to normalize
Vector3 outward_normal = (ray_intersection_record.Point - Center) / Radius;
ray_intersection_record.FrontFace = ray.Direction.GetDotProduct(outward_normal) < 0.0;
ray_intersection_record.Normal = ray_intersection_record.FrontFace ? outward_normal : -outward_normal;
ray_intersection_record.Material = m_Material;
return ray_intersection_record;
}
|
#include "func_util.h"
#include "ast_ops/eval/eval_error.h"
#include <sstream>
namespace ast_ops::impl {
void check_arity(std::size_t expected, std::size_t provided) {
if (expected != provided) {
std::ostringstream msg;
msg << "wrong number of arguments (" << expected << " expected, "
<< provided << " provided)";
throw arity_error(msg.str(), expected, provided);
}
}
void throw_if_nonreal(std::vector<std::size_t> nonreal_args) {
if (!nonreal_args.empty()) {
std::ostringstream msg;
msg << (nonreal_args.size() > 1 ? "arguments" : "argument")
<< " must be real";
throw func_arg_error(msg.str(), std::move(nonreal_args));
}
}
void check_real(func_args args) {
std::vector<std::size_t> nonreal_args;
for (std::ptrdiff_t i = 0; i < args.size(); i++) {
if (args[i].imag() != 0) {
nonreal_args.push_back(i);
}
}
throw_if_nonreal(std::move(nonreal_args));
}
} // namespace ast_ops::impl
|
// Copyright 2018 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/ash/login/demo_mode/demo_setup_controller.h"
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/containers/flat_map.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/time/time.h"
#include "chrome/browser/ash/login/demo_mode/demo_resources.h"
#include "chrome/browser/ash/login/demo_mode/demo_session.h"
#include "chrome/browser/ash/login/enrollment/auto_enrollment_controller.h"
#include "chrome/browser/ash/login/startup_utils.h"
#include "chrome/browser/ash/login/wizard_controller.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chromeos/policy/core/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/core/device_local_account.h"
#include "chrome/browser/chromeos/policy/core/device_local_account_policy_service.h"
#include "chrome/browser/chromeos/policy/enrollment/enrollment_config.h"
#include "chrome/browser/chromeos/policy/enrollment/enrollment_requisition_manager.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/system/statistics_provider.h"
#include "chromeos/tpm/install_attributes.h"
#include "components/arc/arc_util.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "ui/base/l10n/l10n_util.h"
namespace ash {
namespace {
// TODO(https://crbug.com/1164001): remove after moving to ash::
using ::chromeos::InstallAttributes;
using ErrorCode = DemoSetupController::DemoSetupError::ErrorCode;
using RecoveryMethod = DemoSetupController::DemoSetupError::RecoveryMethod;
constexpr char kDemoRequisition[] = "cros-demo-mode";
constexpr char kOfflinePolicyDirectoryName[] = "policy";
constexpr char kOfflineDevicePolicyFileName[] = "device_policy";
constexpr char kOfflineDeviceLocalAccountPolicyFileName[] =
"local_account_policy";
constexpr char kDemoSetupDownloadDurationHistogram[] =
"DemoMode.Setup.DownloadDuration";
constexpr char kDemoSetupEnrollDurationHistogram[] =
"DemoMode.Setup.EnrollDuration";
constexpr char kDemoSetupLoadingDurationHistogram[] =
"DemoMode.Setup.LoadingDuration";
constexpr char kDemoSetupNumRetriesHistogram[] = "DemoMode.Setup.NumRetries";
struct DemoSetupStepInfo {
DemoSetupController::DemoSetupStep step;
const int step_index;
};
base::span<const DemoSetupStepInfo> GetDemoSetupStepsInfo() {
static const DemoSetupStepInfo kDemoModeSetupStepsInfo[] = {
{DemoSetupController::DemoSetupStep::kDownloadResources, 0},
{DemoSetupController::DemoSetupStep::kEnrollment, 1},
{DemoSetupController::DemoSetupStep::kComplete, 2}};
return kDemoModeSetupStepsInfo;
}
// Get the DeviceLocalAccountPolicyStore for the account_id.
policy::CloudPolicyStore* GetDeviceLocalAccountPolicyStore(
const std::string& account_id) {
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
if (!connector)
return nullptr;
policy::DeviceLocalAccountPolicyService* local_account_service =
connector->GetDeviceLocalAccountPolicyService();
if (!local_account_service)
return nullptr;
const std::string user_id = policy::GenerateDeviceLocalAccountUserId(
account_id, policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION);
policy::DeviceLocalAccountPolicyBroker* broker =
local_account_service->GetBrokerForUser(user_id);
if (!broker)
return nullptr;
return broker->core()->store();
}
// A utility function of base::ReadFileToString which returns an optional
// string.
// TODO(mukai): move this to base/files.
absl::optional<std::string> ReadFileToOptionalString(
const base::FilePath& file_path) {
std::string content;
absl::optional<std::string> result;
if (base::ReadFileToString(file_path, &content))
result = std::move(content);
return result;
}
// Returns whether online FRE check is required.
bool IsOnlineFreCheckRequired() {
AutoEnrollmentController::FRERequirement fre_requirement =
AutoEnrollmentController::GetFRERequirement();
bool enrollment_check_required =
fre_requirement !=
AutoEnrollmentController::FRERequirement::kExplicitlyNotRequired &&
fre_requirement !=
AutoEnrollmentController::FRERequirement::kNotRequired &&
AutoEnrollmentController::IsFREEnabled();
if (!enrollment_check_required)
return false;
std::string block_dev_mode_value;
system::StatisticsProvider* provider =
system::StatisticsProvider::GetInstance();
provider->GetMachineStatistic(system::kBlockDevModeKey,
&block_dev_mode_value);
return block_dev_mode_value == "1";
}
DemoSetupController::DemoSetupError CreateFromClientStatus(
policy::DeviceManagementStatus status,
const std::string& debug_message) {
switch (status) {
case policy::DM_STATUS_SUCCESS:
return DemoSetupController::DemoSetupError(
ErrorCode::kUnexpectedError, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_REQUEST_INVALID:
return DemoSetupController::DemoSetupError(
ErrorCode::kInvalidRequest, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_REQUEST_FAILED:
return DemoSetupController::DemoSetupError(
ErrorCode::kRequestNetworkError, RecoveryMethod::kCheckNetwork,
debug_message);
case policy::DM_STATUS_TEMPORARY_UNAVAILABLE:
return DemoSetupController::DemoSetupError(
ErrorCode::kTemporaryUnavailable, RecoveryMethod::kRetry,
debug_message);
case policy::DM_STATUS_HTTP_STATUS_ERROR:
case policy::DM_STATUS_REQUEST_TOO_LARGE:
return DemoSetupController::DemoSetupError(
ErrorCode::kResponseError, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_RESPONSE_DECODING_ERROR:
return DemoSetupController::DemoSetupError(
ErrorCode::kResponseDecodingError, RecoveryMethod::kUnknown,
debug_message);
case policy::DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED:
case policy::DM_STATUS_SERVICE_CONSUMER_ACCOUNT_WITH_PACKAGED_LICENSE:
case policy::DM_STATUS_SERVICE_ACTIVATION_PENDING:
case policy::DM_STATUS_SERVICE_ENTERPRISE_ACCOUNT_IS_NOT_ELIGIBLE_TO_ENROLL:
case policy::DM_STATUS_SERVICE_ENTERPRISE_TOS_HAS_NOT_BEEN_ACCEPTED:
case policy::DM_STATUS_SERVICE_ILLEGAL_ACCOUNT_FOR_PACKAGED_EDU_LICENSE:
return DemoSetupController::DemoSetupError(ErrorCode::kDemoAccountError,
RecoveryMethod::kUnknown,
debug_message);
case policy::DM_STATUS_SERVICE_DEVICE_NOT_FOUND:
return DemoSetupController::DemoSetupError(
ErrorCode::kDeviceNotFound, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID:
return DemoSetupController::DemoSetupError(
ErrorCode::kInvalidDMToken, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER:
return DemoSetupController::DemoSetupError(
ErrorCode::kInvalidSerialNumber, RecoveryMethod::kUnknown,
debug_message);
case policy::DM_STATUS_SERVICE_DEVICE_ID_CONFLICT:
return DemoSetupController::DemoSetupError(
ErrorCode::kDeviceIdError, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_SERVICE_TOO_MANY_REQUESTS:
return DemoSetupController::DemoSetupError(
ErrorCode::kTooManyRequestsError, RecoveryMethod::kRetry,
debug_message);
case policy::DM_STATUS_SERVICE_MISSING_LICENSES:
return DemoSetupController::DemoSetupError(
ErrorCode::kLicenseError, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_SERVICE_DEPROVISIONED:
return DemoSetupController::DemoSetupError(
ErrorCode::kDeviceDeprovisioned, RecoveryMethod::kUnknown,
debug_message);
case policy::DM_STATUS_SERVICE_DOMAIN_MISMATCH:
return DemoSetupController::DemoSetupError(
ErrorCode::kDomainMismatch, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_CANNOT_SIGN_REQUEST:
return DemoSetupController::DemoSetupError(
ErrorCode::kSigningError, RecoveryMethod::kPowerwash, debug_message);
case policy::DM_STATUS_SERVICE_POLICY_NOT_FOUND:
return DemoSetupController::DemoSetupError(
ErrorCode::kPolicyNotFound, RecoveryMethod::kUnknown, debug_message);
case policy::DM_STATUS_SERVICE_ARC_DISABLED:
return DemoSetupController::DemoSetupError(
ErrorCode::kArcError, RecoveryMethod::kUnknown, debug_message);
}
NOTREACHED() << "Demo mode setup received unsupported client status";
return DemoSetupController::DemoSetupError(
ErrorCode::kUnexpectedError, RecoveryMethod::kUnknown, debug_message);
}
DemoSetupController::DemoSetupError CreateFromLockStatus(
InstallAttributes::LockResult status,
const std::string& debug_message) {
switch (status) {
case InstallAttributes::LOCK_SUCCESS:
case InstallAttributes::LOCK_NOT_READY:
return DemoSetupController::DemoSetupError(
ErrorCode::kUnexpectedError, RecoveryMethod::kUnknown, debug_message);
case InstallAttributes::LOCK_TIMEOUT:
return DemoSetupController::DemoSetupError(
ErrorCode::kLockTimeout, RecoveryMethod::kReboot, debug_message);
case InstallAttributes::LOCK_BACKEND_INVALID:
case InstallAttributes::LOCK_SET_ERROR:
case InstallAttributes::LOCK_FINALIZE_ERROR:
case InstallAttributes::LOCK_READBACK_ERROR:
return DemoSetupController::DemoSetupError(
ErrorCode::kLockError, RecoveryMethod::kPowerwash, debug_message);
case InstallAttributes::LOCK_ALREADY_LOCKED:
case InstallAttributes::LOCK_WRONG_DOMAIN:
case InstallAttributes::LOCK_WRONG_MODE:
return DemoSetupController::DemoSetupError(
ErrorCode::kAlreadyLocked, RecoveryMethod::kPowerwash, debug_message);
}
NOTREACHED() << "Demo mode setup received unsupported lock status";
return DemoSetupController::DemoSetupError(
ErrorCode::kUnexpectedError, RecoveryMethod::kUnknown, debug_message);
}
} // namespace
// static
DemoSetupController::DemoSetupError
DemoSetupController::DemoSetupError::CreateFromEnrollmentStatus(
const policy::EnrollmentStatus& status) {
const std::string debug_message = base::StringPrintf(
"EnrollmentError: (status: %d, client_status: %d, store_status: %d, "
"validation_status: %d, lock_status: %d)",
status.status(), status.client_status(), status.store_status(),
status.validation_status(), status.lock_status());
switch (status.status()) {
case policy::EnrollmentStatus::SUCCESS:
return DemoSetupError(ErrorCode::kUnexpectedError,
RecoveryMethod::kUnknown, debug_message);
case policy::EnrollmentStatus::NO_STATE_KEYS:
return DemoSetupError(ErrorCode::kNoStateKeys, RecoveryMethod::kReboot,
debug_message);
case policy::EnrollmentStatus::REGISTRATION_FAILED:
return CreateFromClientStatus(status.client_status(), debug_message);
case policy::EnrollmentStatus::ROBOT_AUTH_FETCH_FAILED:
case policy::EnrollmentStatus::ROBOT_REFRESH_FETCH_FAILED:
return DemoSetupError(ErrorCode::kRobotFetchError,
RecoveryMethod::kCheckNetwork, debug_message);
case policy::EnrollmentStatus::ROBOT_REFRESH_STORE_FAILED:
return DemoSetupError(ErrorCode::kRobotStoreError,
RecoveryMethod::kReboot, debug_message);
case policy::EnrollmentStatus::REGISTRATION_BAD_MODE:
return DemoSetupError(ErrorCode::kBadMode, RecoveryMethod::kRetry,
debug_message);
case policy::EnrollmentStatus::REGISTRATION_CERT_FETCH_FAILED:
return DemoSetupError(ErrorCode::kCertFetchError, RecoveryMethod::kRetry,
debug_message);
case policy::EnrollmentStatus::POLICY_FETCH_FAILED:
return DemoSetupError(ErrorCode::kPolicyFetchError,
RecoveryMethod::kRetry, debug_message);
case policy::EnrollmentStatus::VALIDATION_FAILED:
return DemoSetupError(ErrorCode::kPolicyValidationError,
RecoveryMethod::kRetry, debug_message);
case policy::EnrollmentStatus::LOCK_ERROR:
return CreateFromLockStatus(status.lock_status(), debug_message);
case policy::EnrollmentStatus::STORE_ERROR:
return DemoSetupError(ErrorCode::kOnlineStoreError,
RecoveryMethod::kRetry, debug_message);
case policy::EnrollmentStatus::ATTRIBUTE_UPDATE_FAILED:
return DemoSetupError(ErrorCode::kUnexpectedError,
RecoveryMethod::kUnknown, debug_message);
case policy::EnrollmentStatus::NO_MACHINE_IDENTIFICATION:
return DemoSetupError(ErrorCode::kMachineIdentificationError,
RecoveryMethod::kUnknown, debug_message);
case policy::EnrollmentStatus::ACTIVE_DIRECTORY_POLICY_FETCH_FAILED:
return DemoSetupError(ErrorCode::kUnexpectedError,
RecoveryMethod::kReboot, debug_message);
case policy::EnrollmentStatus::DM_TOKEN_STORE_FAILED:
return DemoSetupError(ErrorCode::kDMTokenStoreError,
RecoveryMethod::kUnknown, debug_message);
case policy::EnrollmentStatus::OFFLINE_POLICY_LOAD_FAILED:
case policy::EnrollmentStatus::OFFLINE_POLICY_DECODING_FAILED:
return DemoSetupError(ErrorCode::kOfflinePolicyError,
RecoveryMethod::kOnlineOnly, debug_message);
}
NOTREACHED() << "Demo mode setup received unsupported enrollment status";
return DemoSetupError(ErrorCode::kUnexpectedError, RecoveryMethod::kUnknown,
debug_message);
}
// static
DemoSetupController::DemoSetupError
DemoSetupController::DemoSetupError::CreateFromOtherEnrollmentError(
EnterpriseEnrollmentHelper::OtherError error) {
const std::string debug_message =
base::StringPrintf("Other error: %d", error);
switch (error) {
case EnterpriseEnrollmentHelper::OTHER_ERROR_DOMAIN_MISMATCH:
return DemoSetupError(ErrorCode::kAlreadyLocked,
RecoveryMethod::kPowerwash, debug_message);
case EnterpriseEnrollmentHelper::OTHER_ERROR_FATAL:
return DemoSetupError(ErrorCode::kUnexpectedError,
RecoveryMethod::kUnknown, debug_message);
}
NOTREACHED() << "Demo mode setup received unsupported enrollment error";
return DemoSetupError(ErrorCode::kUnexpectedError, RecoveryMethod::kUnknown,
debug_message);
}
// static
DemoSetupController::DemoSetupError
DemoSetupController::DemoSetupError::CreateFromComponentError(
component_updater::CrOSComponentManager::Error error) {
const std::string debug_message =
"Failed to load demo resources CrOS component with error: " +
std::to_string(static_cast<int>(error));
return DemoSetupError(ErrorCode::kOnlineComponentError,
RecoveryMethod::kCheckNetwork, debug_message);
}
DemoSetupController::DemoSetupError::DemoSetupError(
DemoSetupError::ErrorCode error_code,
DemoSetupError::RecoveryMethod recovery_method)
: error_code_(error_code), recovery_method_(recovery_method) {}
DemoSetupController::DemoSetupError::DemoSetupError(
DemoSetupError::ErrorCode error_code,
DemoSetupError::RecoveryMethod recovery_method,
const std::string& debug_message)
: error_code_(error_code),
recovery_method_(recovery_method),
debug_message_(debug_message) {}
DemoSetupController::DemoSetupError::~DemoSetupError() = default;
std::u16string DemoSetupController::DemoSetupError::GetLocalizedErrorMessage()
const {
switch (error_code_) {
case ErrorCode::kOfflinePolicyError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_OFFLINE_POLICY_ERROR);
case ErrorCode::kOfflinePolicyStoreError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_OFFLINE_STORE_ERROR);
case ErrorCode::kOnlineFRECheckRequired:
return l10n_util::GetStringUTF16(
IDS_DEMO_SETUP_OFFLINE_UNAVAILABLE_ERROR);
case ErrorCode::kOnlineComponentError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_COMPONENT_ERROR);
case ErrorCode::kNoStateKeys:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_NO_STATE_KEYS_ERROR);
case ErrorCode::kInvalidRequest:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_INVALID_REQUEST_ERROR);
case ErrorCode::kRequestNetworkError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_NETWORK_ERROR);
case ErrorCode::kTemporaryUnavailable:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_TEMPORARY_ERROR);
case ErrorCode::kResponseError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RESPONSE_ERROR);
case ErrorCode::kResponseDecodingError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RESPONSE_DECODING_ERROR);
case ErrorCode::kDemoAccountError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_ACCOUNT_ERROR);
case ErrorCode::kDeviceNotFound:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_DEVICE_NOT_FOUND_ERROR);
case ErrorCode::kInvalidDMToken:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_INVALID_DM_TOKEN_ERROR);
case ErrorCode::kInvalidSerialNumber:
return l10n_util::GetStringUTF16(
IDS_DEMO_SETUP_INVALID_SERIAL_NUMBER_ERROR);
case ErrorCode::kDeviceIdError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_DEVICE_ID_ERROR);
case ErrorCode::kTooManyRequestsError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_TOO_MANY_REQUESTS_ERROR);
case ErrorCode::kLicenseError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_LICENSE_ERROR);
case ErrorCode::kDeviceDeprovisioned:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_DEPROVISIONED_ERROR);
case ErrorCode::kDomainMismatch:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_DOMAIN_MISMATCH_ERROR);
case ErrorCode::kSigningError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_SIGNING_ERROR);
case ErrorCode::kPolicyNotFound:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_POLICY_NOT_FOUND_ERROR);
case ErrorCode::kArcError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_ARC_ERROR);
case ErrorCode::kRobotFetchError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_ROBOT_ERROR);
case ErrorCode::kRobotStoreError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_ROBOT_STORE_ERROR);
case ErrorCode::kBadMode:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_BAD_MODE_ERROR);
case ErrorCode::kCertFetchError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_CERT_FETCH_ERROR);
case ErrorCode::kPolicyFetchError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_POLICY_FETCH_ERROR);
case ErrorCode::kPolicyValidationError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_POLICY_VALIDATION_ERROR);
case ErrorCode::kLockTimeout:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_LOCK_TIMEOUT_ERROR);
case ErrorCode::kLockError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_LOCK_ERROR);
case ErrorCode::kAlreadyLocked:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_ALREADY_LOCKED_ERROR);
case ErrorCode::kOnlineStoreError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_ONLINE_STORE_ERROR);
case ErrorCode::kMachineIdentificationError:
return l10n_util::GetStringUTF16(
IDS_DEMO_SETUP_NO_MACHINE_IDENTIFICATION_ERROR);
case ErrorCode::kDMTokenStoreError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_DM_TOKEN_STORE_ERROR);
case ErrorCode::kUnexpectedError:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_UNEXPECTED_ERROR);
}
NOTREACHED() << "No localized error message available for demo setup error.";
return std::u16string();
}
std::u16string
DemoSetupController::DemoSetupError::GetLocalizedRecoveryMessage() const {
switch (recovery_method_) {
case RecoveryMethod::kRetry:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RECOVERY_RETRY);
case RecoveryMethod::kReboot:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RECOVERY_REBOOT);
case RecoveryMethod::kPowerwash:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RECOVERY_POWERWASH);
case RecoveryMethod::kCheckNetwork:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RECOVERY_CHECK_NETWORK);
case RecoveryMethod::kOnlineOnly:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RECOVERY_OFFLINE_FATAL);
case RecoveryMethod::kUnknown:
return l10n_util::GetStringUTF16(IDS_DEMO_SETUP_RECOVERY_FATAL);
}
NOTREACHED()
<< "No localized error message available for demo setup recovery method.";
return std::u16string();
}
std::string DemoSetupController::DemoSetupError::GetDebugDescription() const {
return base::StringPrintf("DemoSetupError (code: %d, recovery: %d) : %s",
error_code_, recovery_method_,
debug_message_.c_str());
}
void DemoSetupController::RegisterLocalStatePrefs(
PrefRegistrySimple* registry) {
registry->RegisterIntegerPref(
prefs::kDemoModeConfig,
static_cast<int>(DemoSession::DemoModeConfig::kNone));
}
// static
void DemoSetupController::ClearDemoRequisition() {
if (policy::EnrollmentRequisitionManager::GetDeviceRequisition() ==
kDemoRequisition) {
policy::EnrollmentRequisitionManager::SetDeviceRequisition(std::string());
// If device requisition is `kDemoRequisition`, it means the sub
// organization was also set by the demo setup controller, so remove it as
// well.
policy::EnrollmentRequisitionManager::SetSubOrganization(std::string());
}
}
// static
bool DemoSetupController::IsDemoModeAllowed() {
// Demo mode is only allowed on devices that support ARC++.
return arc::IsArcAvailable();
}
// static
bool DemoSetupController::IsOobeDemoSetupFlowInProgress() {
const WizardController* const wizard_controller =
WizardController::default_controller();
return wizard_controller &&
wizard_controller->demo_setup_controller() != nullptr;
}
// static
std::string DemoSetupController::GetSubOrganizationEmail() {
const std::string country =
g_browser_process->local_state()->GetString(prefs::kDemoModeCountry);
// Exclude US as it is the default country.
if (country != "us" &&
std::find(std::begin(DemoSession::kSupportedCountries),
std::end(DemoSession::kSupportedCountries),
country) != std::end(DemoSession::kSupportedCountries)) {
return "admin-" + country + "@" + policy::kDemoModeDomain;
}
return std::string();
}
// static
base::Value DemoSetupController::GetDemoSetupSteps() {
base::Value setup_steps_dict(base::Value::Type::DICTIONARY);
for (auto entry : GetDemoSetupStepsInfo()) {
setup_steps_dict.SetIntPath(GetDemoSetupStepString(entry.step),
entry.step_index);
}
return setup_steps_dict;
}
// static
std::string DemoSetupController::GetDemoSetupStepString(
const DemoSetupStep step_enum) {
switch (step_enum) {
case DemoSetupStep::kDownloadResources:
return "downloadResources";
case DemoSetupStep::kEnrollment:
return "enrollment";
case DemoSetupStep::kComplete:
return "complete";
}
NOTREACHED();
}
DemoSetupController::DemoSetupController() {}
DemoSetupController::~DemoSetupController() {
if (device_local_account_policy_store_)
device_local_account_policy_store_->RemoveObserver(this);
}
bool DemoSetupController::IsOfflineEnrollment() const {
return demo_config_ == DemoSession::DemoModeConfig::kOffline;
}
void DemoSetupController::Enroll(
OnSetupSuccess on_setup_success,
OnSetupError on_setup_error,
const OnSetCurrentSetupStep& set_current_setup_step) {
DCHECK_NE(demo_config_, DemoSession::DemoModeConfig::kNone)
<< "Demo config needs to be explicitly set before calling Enroll()";
DCHECK(!enrollment_helper_);
set_current_setup_step_ = set_current_setup_step;
on_setup_success_ = std::move(on_setup_success);
on_setup_error_ = std::move(on_setup_error);
VLOG(1) << "Starting demo setup "
<< DemoSession::DemoConfigToString(demo_config_);
SetCurrentSetupStep(DemoSetupStep::kDownloadResources);
switch (demo_config_) {
case DemoSession::DemoModeConfig::kOnline:
LoadDemoResourcesCrOSComponent();
return;
case DemoSession::DemoModeConfig::kOffline: {
EnrollOffline();
return;
}
case DemoSession::DemoModeConfig::kNone:
NOTREACHED() << "No valid demo mode config specified";
}
}
void DemoSetupController::TryMountPreinstalledDemoResources(
HasPreinstalledDemoResourcesCallback callback) {
if (!preinstalled_demo_resources_) {
preinstalled_demo_resources_ =
std::make_unique<DemoResources>(DemoSession::DemoModeConfig::kOffline);
}
if (DBusThreadManager::Get()->IsUsingFakes()) {
preinstalled_demo_resources_
->SetPreinstalledOfflineResourcesLoadedForTesting(
preinstalled_offline_resources_path_for_tests_);
}
preinstalled_demo_resources_->EnsureLoaded(
base::BindOnce(&DemoSetupController::OnPreinstalledDemoResourcesLoaded,
base::Unretained(this), std::move(callback)));
}
base::FilePath DemoSetupController::GetPreinstalledDemoResourcesPath(
const base::FilePath& relative_path) {
if (preinstalled_demo_resources_)
return preinstalled_demo_resources_->GetAbsolutePath(relative_path);
return base::FilePath();
}
void DemoSetupController::LoadDemoResourcesCrOSComponent() {
VLOG(1) << "Loading demo resources component";
download_start_time_ = base::TimeTicks::Now();
if (!demo_resources_)
demo_resources_ = std::make_unique<DemoResources>(demo_config_);
if (DBusThreadManager::Get()->IsUsingFakes()) {
demo_resources_->SetCrOSComponentLoadedForTesting(
base::FilePath(), component_error_for_tests_);
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&DemoSetupController::OnDemoResourcesCrOSComponentLoaded,
weak_ptr_factory_.GetWeakPtr()));
return;
}
demo_resources_->EnsureLoaded(
base::BindOnce(&DemoSetupController::OnDemoResourcesCrOSComponentLoaded,
weak_ptr_factory_.GetWeakPtr()));
}
void DemoSetupController::OnDemoResourcesCrOSComponentLoaded() {
DCHECK_EQ(demo_config_, DemoSession::DemoModeConfig::kOnline);
base::TimeDelta download_duration =
base::TimeTicks::Now() - download_start_time_;
base::UmaHistogramLongTimes100(kDemoSetupDownloadDurationHistogram,
download_duration);
SetCurrentSetupStep(DemoSetupStep::kEnrollment);
if (demo_resources_->component_error().value() !=
component_updater::CrOSComponentManager::Error::NONE) {
SetupFailed(DemoSetupError::CreateFromComponentError(
demo_resources_->component_error().value()));
return;
}
VLOG(1) << "Starting online enrollment";
enroll_start_time_ = base::TimeTicks::Now();
DCHECK(policy::EnrollmentRequisitionManager::GetDeviceRequisition().empty());
policy::EnrollmentRequisitionManager::SetDeviceRequisition(kDemoRequisition);
policy::EnrollmentRequisitionManager::SetSubOrganization(
GetSubOrganizationEmail());
policy::EnrollmentConfig config;
config.mode = policy::EnrollmentConfig::MODE_ATTESTATION;
config.management_domain = policy::kDemoModeDomain;
enrollment_helper_ = EnterpriseEnrollmentHelper::Create(
this, nullptr, config, policy::kDemoModeDomain);
enrollment_helper_->EnrollUsingAttestation();
}
void DemoSetupController::OnPreinstalledDemoResourcesLoaded(
HasPreinstalledDemoResourcesCallback callback) {
std::move(callback).Run(!preinstalled_demo_resources_->path().empty());
}
void DemoSetupController::EnrollOffline() {
DCHECK_EQ(demo_config_, DemoSession::DemoModeConfig::kOffline);
DCHECK(!preinstalled_demo_resources_->path().empty());
const base::FilePath policy_dir =
preinstalled_demo_resources_->GetAbsolutePath(
base::FilePath(kOfflinePolicyDirectoryName));
if (IsOnlineFreCheckRequired()) {
SetupFailed(
DemoSetupError(DemoSetupError::ErrorCode::kOnlineFRECheckRequired,
DemoSetupError::RecoveryMethod::kOnlineOnly,
"Cannot do offline demo mode setup, because online "
"FRE check is required."));
return;
}
VLOG(1) << "Starting offline enrollment";
policy::EnrollmentConfig config;
config.mode = policy::EnrollmentConfig::MODE_OFFLINE_DEMO;
config.management_domain = policy::kDemoModeDomain;
config.offline_policy_path =
policy_dir.AppendASCII(kOfflineDevicePolicyFileName);
enrollment_helper_ = EnterpriseEnrollmentHelper::Create(
this, nullptr /* ad_join_delegate */, config, policy::kDemoModeDomain);
enrollment_helper_->EnrollForOfflineDemo();
}
void DemoSetupController::OnAuthError(const GoogleServiceAuthError& error) {
NOTREACHED();
}
void DemoSetupController::OnEnrollmentError(policy::EnrollmentStatus status) {
SetupFailed(DemoSetupError::CreateFromEnrollmentStatus(status));
}
void DemoSetupController::OnOtherError(
EnterpriseEnrollmentHelper::OtherError error) {
SetupFailed(DemoSetupError::CreateFromOtherEnrollmentError(error));
}
void DemoSetupController::OnDeviceEnrolled() {
DCHECK_NE(demo_config_, DemoSession::DemoModeConfig::kNone);
// `enroll_start_time_` is only set for online enrollment.
if (!enroll_start_time_.is_null()) {
base::TimeDelta enroll_duration =
base::TimeTicks::Now() - enroll_start_time_;
base::UmaHistogramLongTimes100(kDemoSetupEnrollDurationHistogram,
enroll_duration);
}
// Try to load the policy for the device local account.
if (demo_config_ == DemoSession::DemoModeConfig::kOffline) {
VLOG(1) << "Loading offline policy";
DCHECK(!preinstalled_demo_resources_->path().empty());
const base::FilePath file_path =
preinstalled_demo_resources_->GetAbsolutePath(
base::FilePath(kOfflinePolicyDirectoryName)
.AppendASCII(kOfflineDeviceLocalAccountPolicyFileName));
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&ReadFileToOptionalString, file_path),
base::BindOnce(&DemoSetupController::OnDeviceLocalAccountPolicyLoaded,
weak_ptr_factory_.GetWeakPtr()));
return;
}
VLOG(1) << "Marking device registered";
StartupUtils::MarkDeviceRegistered(
base::BindOnce(&DemoSetupController::OnDeviceRegistered,
weak_ptr_factory_.GetWeakPtr()));
}
void DemoSetupController::OnDeviceAttributeUploadCompleted(bool success) {
NOTREACHED();
}
void DemoSetupController::OnDeviceAttributeUpdatePermission(bool granted) {
NOTREACHED();
}
void DemoSetupController::OnRestoreAfterRollbackCompleted() {
NOTREACHED();
}
void DemoSetupController::SetCrOSComponentLoadErrorForTest(
component_updater::CrOSComponentManager::Error error) {
component_error_for_tests_ = error;
}
void DemoSetupController::SetPreinstalledOfflineResourcesPathForTesting(
const base::FilePath& path) {
preinstalled_offline_resources_path_for_tests_ = path;
}
void DemoSetupController::SetDeviceLocalAccountPolicyStoreForTest(
policy::CloudPolicyStore* store) {
device_local_account_policy_store_ = store;
}
void DemoSetupController::OnDeviceLocalAccountPolicyLoaded(
absl::optional<std::string> blob) {
if (!blob.has_value()) {
// This is very unlikely to happen since the file existence is already
// checked as CheckOfflinePolicyFilesExist.
SetupFailed(
DemoSetupError(DemoSetupError::ErrorCode::kOfflinePolicyError,
DemoSetupError::RecoveryMethod::kPowerwash,
"Policy file for the device local account not found"));
return;
}
enterprise_management::PolicyFetchResponse policy;
if (!policy.ParseFromString(blob.value())) {
SetupFailed(DemoSetupError(DemoSetupError::ErrorCode::kOfflinePolicyError,
DemoSetupError::RecoveryMethod::kPowerwash,
"Error parsing local account policy blob."));
return;
}
// Extract the account_id from the policy data.
enterprise_management::PolicyData policy_data;
if (policy.policy_data().empty() ||
!policy_data.ParseFromString(policy.policy_data())) {
SetupFailed(DemoSetupError(DemoSetupError::ErrorCode::kOfflinePolicyError,
DemoSetupError::RecoveryMethod::kPowerwash,
"Error parsing local account policy data."));
return;
}
VLOG(1) << "Storing offline policy";
// On the unittest, the device_local_account_policy_store_ is already
// initialized. Otherwise attempts to get the store.
if (!device_local_account_policy_store_) {
device_local_account_policy_store_ =
GetDeviceLocalAccountPolicyStore(policy_data.username());
}
if (!device_local_account_policy_store_) {
SetupFailed(
DemoSetupError(DemoSetupError::ErrorCode::kOfflinePolicyStoreError,
DemoSetupError::RecoveryMethod::kPowerwash,
"Can't find the store for the local account policy."));
return;
}
device_local_account_policy_store_->AddObserver(this);
device_local_account_policy_store_->Store(policy);
}
void DemoSetupController::OnDeviceRegistered() {
VLOG(1) << "Demo mode setup finished successfully.";
if (demo_config_ == DemoSession::DemoModeConfig::kOnline) {
base::TimeDelta loading_duration =
base::TimeTicks::Now() - download_start_time_;
// A similar metric can be found at OOBE.StepCompletionTime.Demo-setup,
// however this is only useful for durations up to three minutes. Demo mode
// setup typically takes longer than this, so we use a LONG_TIMES metric
// here to capture metrics of up to one hour.
base::UmaHistogramLongTimes100(kDemoSetupLoadingDurationHistogram,
loading_duration);
}
base::UmaHistogramCounts100(kDemoSetupNumRetriesHistogram,
num_setup_retries_);
SetCurrentSetupStep(DemoSetupStep::kComplete);
PrefService* prefs = g_browser_process->local_state();
prefs->SetInteger(prefs::kDemoModeConfig, static_cast<int>(demo_config_));
prefs->CommitPendingWrite();
Reset();
if (!on_setup_success_.is_null())
std::move(on_setup_success_).Run();
}
void DemoSetupController::SetCurrentSetupStep(DemoSetupStep current_step) {
if (!set_current_setup_step_.is_null())
set_current_setup_step_.Run(current_step);
}
void DemoSetupController::SetupFailed(const DemoSetupError& error) {
num_setup_retries_++;
Reset();
LOG(ERROR) << error.GetDebugDescription();
if (!on_setup_error_.is_null())
std::move(on_setup_error_).Run(error);
}
void DemoSetupController::Reset() {
DCHECK_NE(demo_config_, DemoSession::DemoModeConfig::kNone);
// `demo_config_` is not reset here, because it is needed for retrying setup.
enrollment_helper_.reset();
if (device_local_account_policy_store_) {
device_local_account_policy_store_->RemoveObserver(this);
device_local_account_policy_store_ = nullptr;
}
ClearDemoRequisition();
}
void DemoSetupController::OnStoreLoaded(policy::CloudPolicyStore* store) {
DCHECK_EQ(store, device_local_account_policy_store_);
VLOG(1) << "Marking device registered";
StartupUtils::MarkDeviceRegistered(
base::BindOnce(&DemoSetupController::OnDeviceRegistered,
weak_ptr_factory_.GetWeakPtr()));
}
void DemoSetupController::OnStoreError(policy::CloudPolicyStore* store) {
DCHECK_EQ(store, device_local_account_policy_store_);
SetupFailed(
DemoSetupError(DemoSetupError::ErrorCode::kOfflinePolicyStoreError,
DemoSetupError::RecoveryMethod::kPowerwash,
"Failed to store the local account policy"));
}
} // namespace ash
|
/*************************************************************************/
/* export.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 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 "export.h"
#include "core/io/marshalls.h"
#include "core/io/zip_io.h"
#include "core/os/file_access.h"
#include "core/os/os.h"
#include "core/project_settings.h"
#include "core/version.h"
#include "editor/editor_export.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
#include "platform/android/logo.gen.h"
#include "platform/android/run_icon.gen.h"
#include <string.h>
static const char *android_perms[] = {
"ACCESS_CHECKIN_PROPERTIES",
"ACCESS_COARSE_LOCATION",
"ACCESS_FINE_LOCATION",
"ACCESS_LOCATION_EXTRA_COMMANDS",
"ACCESS_MOCK_LOCATION",
"ACCESS_NETWORK_STATE",
"ACCESS_SURFACE_FLINGER",
"ACCESS_WIFI_STATE",
"ACCOUNT_MANAGER",
"ADD_VOICEMAIL",
"AUTHENTICATE_ACCOUNTS",
"BATTERY_STATS",
"BIND_ACCESSIBILITY_SERVICE",
"BIND_APPWIDGET",
"BIND_DEVICE_ADMIN",
"BIND_INPUT_METHOD",
"BIND_NFC_SERVICE",
"BIND_NOTIFICATION_LISTENER_SERVICE",
"BIND_PRINT_SERVICE",
"BIND_REMOTEVIEWS",
"BIND_TEXT_SERVICE",
"BIND_VPN_SERVICE",
"BIND_WALLPAPER",
"BLUETOOTH",
"BLUETOOTH_ADMIN",
"BLUETOOTH_PRIVILEGED",
"BRICK",
"BROADCAST_PACKAGE_REMOVED",
"BROADCAST_SMS",
"BROADCAST_STICKY",
"BROADCAST_WAP_PUSH",
"CALL_PHONE",
"CALL_PRIVILEGED",
"CAMERA",
"CAPTURE_AUDIO_OUTPUT",
"CAPTURE_SECURE_VIDEO_OUTPUT",
"CAPTURE_VIDEO_OUTPUT",
"CHANGE_COMPONENT_ENABLED_STATE",
"CHANGE_CONFIGURATION",
"CHANGE_NETWORK_STATE",
"CHANGE_WIFI_MULTICAST_STATE",
"CHANGE_WIFI_STATE",
"CLEAR_APP_CACHE",
"CLEAR_APP_USER_DATA",
"CONTROL_LOCATION_UPDATES",
"DELETE_CACHE_FILES",
"DELETE_PACKAGES",
"DEVICE_POWER",
"DIAGNOSTIC",
"DISABLE_KEYGUARD",
"DUMP",
"EXPAND_STATUS_BAR",
"FACTORY_TEST",
"FLASHLIGHT",
"FORCE_BACK",
"GET_ACCOUNTS",
"GET_PACKAGE_SIZE",
"GET_TASKS",
"GET_TOP_ACTIVITY_INFO",
"GLOBAL_SEARCH",
"HARDWARE_TEST",
"INJECT_EVENTS",
"INSTALL_LOCATION_PROVIDER",
"INSTALL_PACKAGES",
"INSTALL_SHORTCUT",
"INTERNAL_SYSTEM_WINDOW",
"INTERNET",
"KILL_BACKGROUND_PROCESSES",
"LOCATION_HARDWARE",
"MANAGE_ACCOUNTS",
"MANAGE_APP_TOKENS",
"MANAGE_DOCUMENTS",
"MASTER_CLEAR",
"MEDIA_CONTENT_CONTROL",
"MODIFY_AUDIO_SETTINGS",
"MODIFY_PHONE_STATE",
"MOUNT_FORMAT_FILESYSTEMS",
"MOUNT_UNMOUNT_FILESYSTEMS",
"NFC",
"PERSISTENT_ACTIVITY",
"PROCESS_OUTGOING_CALLS",
"READ_CALENDAR",
"READ_CALL_LOG",
"READ_CONTACTS",
"READ_EXTERNAL_STORAGE",
"READ_FRAME_BUFFER",
"READ_HISTORY_BOOKMARKS",
"READ_INPUT_STATE",
"READ_LOGS",
"READ_PHONE_STATE",
"READ_PROFILE",
"READ_SMS",
"READ_SOCIAL_STREAM",
"READ_SYNC_SETTINGS",
"READ_SYNC_STATS",
"READ_USER_DICTIONARY",
"REBOOT",
"RECEIVE_BOOT_COMPLETED",
"RECEIVE_MMS",
"RECEIVE_SMS",
"RECEIVE_WAP_PUSH",
"RECORD_AUDIO",
"REORDER_TASKS",
"RESTART_PACKAGES",
"SEND_RESPOND_VIA_MESSAGE",
"SEND_SMS",
"SET_ACTIVITY_WATCHER",
"SET_ALARM",
"SET_ALWAYS_FINISH",
"SET_ANIMATION_SCALE",
"SET_DEBUG_APP",
"SET_ORIENTATION",
"SET_POINTER_SPEED",
"SET_PREFERRED_APPLICATIONS",
"SET_PROCESS_LIMIT",
"SET_TIME",
"SET_TIME_ZONE",
"SET_WALLPAPER",
"SET_WALLPAPER_HINTS",
"SIGNAL_PERSISTENT_PROCESSES",
"STATUS_BAR",
"SUBSCRIBED_FEEDS_READ",
"SUBSCRIBED_FEEDS_WRITE",
"SYSTEM_ALERT_WINDOW",
"TRANSMIT_IR",
"UNINSTALL_SHORTCUT",
"UPDATE_DEVICE_STATS",
"USE_CREDENTIALS",
"USE_SIP",
"VIBRATE",
"WAKE_LOCK",
"WRITE_APN_SETTINGS",
"WRITE_CALENDAR",
"WRITE_CALL_LOG",
"WRITE_CONTACTS",
"WRITE_EXTERNAL_STORAGE",
"WRITE_GSERVICES",
"WRITE_HISTORY_BOOKMARKS",
"WRITE_PROFILE",
"WRITE_SECURE_SETTINGS",
"WRITE_SETTINGS",
"WRITE_SMS",
"WRITE_SOCIAL_STREAM",
"WRITE_SYNC_SETTINGS",
"WRITE_USER_DICTIONARY",
NULL
};
struct LauncherIcon {
const char *option_id;
const char *export_path;
};
static const LauncherIcon launcher_icons[] = {
{ "launcher_icons/xxxhdpi_192x192", "res/drawable-xxxhdpi-v4/icon.png" },
{ "launcher_icons/xxhdpi_144x144", "res/drawable-xxhdpi-v4/icon.png" },
{ "launcher_icons/xhdpi_96x96", "res/drawable-xhdpi-v4/icon.png" },
{ "launcher_icons/hdpi_72x72", "res/drawable-hdpi-v4/icon.png" },
{ "launcher_icons/mdpi_48x48", "res/drawable-mdpi-v4/icon.png" }
};
class EditorExportPlatformAndroid : public EditorExportPlatform {
GDCLASS(EditorExportPlatformAndroid, EditorExportPlatform)
Ref<ImageTexture> logo;
Ref<ImageTexture> run_icon;
struct Device {
String id;
String name;
String description;
int api_level;
};
struct APKExportData {
zipFile apk;
EditorProgress *ep;
};
Vector<Device> devices;
volatile bool devices_changed;
Mutex *device_lock;
Thread *device_thread;
volatile bool quit_request;
static void _device_poll_thread(void *ud) {
EditorExportPlatformAndroid *ea = (EditorExportPlatformAndroid *)ud;
while (!ea->quit_request) {
String adb = EditorSettings::get_singleton()->get("export/android/adb");
if (FileAccess::exists(adb)) {
String devices;
List<String> args;
args.push_back("devices");
int ec;
OS::get_singleton()->execute(adb, args, true, NULL, &devices, &ec);
Vector<String> ds = devices.split("\n");
Vector<String> ldevices;
for (int i = 1; i < ds.size(); i++) {
String d = ds[i];
int dpos = d.find("device");
if (dpos == -1)
continue;
d = d.substr(0, dpos).strip_edges();
ldevices.push_back(d);
}
ea->device_lock->lock();
bool different = false;
if (ea->devices.size() != ldevices.size()) {
different = true;
} else {
for (int i = 0; i < ea->devices.size(); i++) {
if (ea->devices[i].id != ldevices[i]) {
different = true;
break;
}
}
}
if (different) {
Vector<Device> ndevices;
for (int i = 0; i < ldevices.size(); i++) {
Device d;
d.id = ldevices[i];
for (int j = 0; j < ea->devices.size(); j++) {
if (ea->devices[j].id == ldevices[i]) {
d.description = ea->devices[j].description;
d.name = ea->devices[j].name;
d.api_level = ea->devices[j].api_level;
}
}
if (d.description == "") {
//in the oven, request!
args.clear();
args.push_back("-s");
args.push_back(d.id);
args.push_back("shell");
args.push_back("getprop");
int ec2;
String dp;
OS::get_singleton()->execute(adb, args, true, NULL, &dp, &ec2);
Vector<String> props = dp.split("\n");
String vendor;
String device;
d.description + "Device ID: " + d.id + "\n";
d.api_level = 0;
for (int j = 0; j < props.size(); j++) {
// got information by `shell cat /system/build.prop` before and its format is "property=value"
// it's now changed to use `shell getporp` because of permission issue with Android 8.0 and above
// its format is "[property]: [value]" so changed it as like build.prop
String p = props[j];
p = p.replace("]: ", "=");
p = p.replace("[", "");
p = p.replace("]", "");
if (p.begins_with("ro.product.model=")) {
device = p.get_slice("=", 1).strip_edges();
} else if (p.begins_with("ro.product.brand=")) {
vendor = p.get_slice("=", 1).strip_edges().capitalize();
} else if (p.begins_with("ro.build.display.id=")) {
d.description += "Build: " + p.get_slice("=", 1).strip_edges() + "\n";
} else if (p.begins_with("ro.build.version.release=")) {
d.description += "Release: " + p.get_slice("=", 1).strip_edges() + "\n";
} else if (p.begins_with("ro.build.version.sdk=")) {
d.api_level = p.get_slice("=", 1).to_int();
} else if (p.begins_with("ro.product.cpu.abi=")) {
d.description += "CPU: " + p.get_slice("=", 1).strip_edges() + "\n";
} else if (p.begins_with("ro.product.manufacturer=")) {
d.description += "Manufacturer: " + p.get_slice("=", 1).strip_edges() + "\n";
} else if (p.begins_with("ro.board.platform=")) {
d.description += "Chipset: " + p.get_slice("=", 1).strip_edges() + "\n";
} else if (p.begins_with("ro.opengles.version=")) {
uint32_t opengl = p.get_slice("=", 1).to_int();
d.description += "OpenGL: " + itos(opengl >> 16) + "." + itos((opengl >> 8) & 0xFF) + "." + itos((opengl)&0xFF) + "\n";
}
}
d.name = vendor + " " + device;
if (device == String()) continue;
}
ndevices.push_back(d);
}
ea->devices = ndevices;
ea->devices_changed = true;
}
ea->device_lock->unlock();
}
uint64_t sleep = OS::get_singleton()->get_power_state() == OS::POWERSTATE_ON_BATTERY ? 1000 : 100;
uint64_t wait = 3000000;
uint64_t time = OS::get_singleton()->get_ticks_usec();
while (OS::get_singleton()->get_ticks_usec() - time < wait) {
OS::get_singleton()->delay_usec(1000 * sleep);
if (ea->quit_request)
break;
}
}
if (EditorSettings::get_singleton()->get("export/android/shutdown_adb_on_exit")) {
String adb = EditorSettings::get_singleton()->get("export/android/adb");
if (!FileAccess::exists(adb)) {
return; //adb not configured
}
List<String> args;
args.push_back("kill-server");
OS::get_singleton()->execute(adb, args, true);
};
}
String get_project_name(const String &p_name) const {
String aname;
if (p_name != "") {
aname = p_name;
} else {
aname = ProjectSettings::get_singleton()->get("application/config/name");
}
if (aname == "") {
aname = VERSION_NAME;
}
return aname;
}
String get_package_name(const String &p_package) const {
String pname = p_package;
String basename = ProjectSettings::get_singleton()->get("application/config/name");
basename = basename.to_lower();
String name;
bool first = true;
for (int i = 0; i < basename.length(); i++) {
CharType c = basename[i];
if (c >= '0' && c <= '9' && first) {
continue;
}
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
name += String::chr(c);
first = false;
}
}
if (name == "")
name = "noname";
pname = pname.replace("$genname", name);
return pname;
}
bool is_package_name_valid(const String &p_package, String *r_error = NULL) const {
String pname = p_package;
if (pname.length() == 0) {
if (r_error) {
*r_error = TTR("Package name is missing.");
}
return false;
}
int segments = 0;
bool first = true;
for (int i = 0; i < pname.length(); i++) {
CharType c = pname[i];
if (first && c == '.') {
if (r_error) {
*r_error = TTR("Package segments must be of non-zero length.");
}
return false;
}
if (c == '.') {
segments++;
first = true;
continue;
}
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_')) {
if (r_error) {
*r_error = vformat(TTR("The character '%s' is not allowed in Android application package names."), String::chr(c));
}
return false;
}
if (first && (c >= '0' && c <= '9')) {
if (r_error) {
*r_error = TTR("A digit cannot be the first character in a package segment.");
}
return false;
}
if (first && c == '_') {
if (r_error) {
*r_error = vformat(TTR("The character '%s' cannot be the first character in a package segment."), String::chr(c));
}
return false;
}
first = false;
}
if (segments == 0) {
if (r_error) {
*r_error = TTR("The package must have at least one '.' separator.");
}
return false;
}
if (first) {
if (r_error) {
*r_error = TTR("Package segments must be of non-zero length.");
}
return false;
}
return true;
}
static bool _should_compress_asset(const String &p_path, const Vector<uint8_t> &p_data) {
/*
* By not compressing files with little or not benefit in doing so,
* a performance gain is expected attime. Moreover, if the APK is
* zip-aligned, assets stored as they are can be efficiently read by
* Android by memory-mapping them.
*/
// -- Unconditional uncompress to mimic AAPT plus some other
static const char *unconditional_compress_ext[] = {
// From https://github.com/android/platform_frameworks_base/blob/master/tools/aapt/Package.cpp
// These formats are already compressed, or don't compress well:
".jpg", ".jpeg", ".png", ".gif",
".wav", ".mp2", ".mp3", ".ogg", ".aac",
".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",
".rtttl", ".imy", ".xmf", ".mp4", ".m4a",
".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",
".amr", ".awb", ".wma", ".wmv",
// Godot-specific:
".webp", // Same reasoning as .png
".cfb", // Don't let small config files slow-down startup
".scn", // Binary scenes are usually already compressed
".stex", // Streamable textures are usually already compressed
// Trailer for easier processing
NULL
};
for (const char **ext = unconditional_compress_ext; *ext; ++ext) {
if (p_path.to_lower().ends_with(String(*ext))) {
return false;
}
}
// -- Compressed resource?
if (p_data.size() >= 4 && p_data[0] == 'R' && p_data[1] == 'S' && p_data[2] == 'C' && p_data[3] == 'C') {
// Already compressed
return false;
}
// --- TODO: Decide on texture resources according to their image compression setting
return true;
}
static zip_fileinfo get_zip_fileinfo() {
OS::Time time = OS::get_singleton()->get_time();
OS::Date date = OS::get_singleton()->get_date();
zip_fileinfo zipfi;
zipfi.tmz_date.tm_hour = time.hour;
zipfi.tmz_date.tm_mday = date.day;
zipfi.tmz_date.tm_min = time.min;
zipfi.tmz_date.tm_mon = date.month;
zipfi.tmz_date.tm_sec = time.sec;
zipfi.tmz_date.tm_year = date.year;
zipfi.dosDate = 0;
zipfi.external_fa = 0;
zipfi.internal_fa = 0;
return zipfi;
}
static Vector<String> get_abis() {
Vector<String> abis;
// We can still build armv6 in theory, but it doesn't make much
// sense for games, so disabling for now.
//abis.push_back("armeabi");
abis.push_back("armeabi-v7a");
abis.push_back("arm64-v8a");
abis.push_back("x86");
abis.push_back("x86_64");
return abis;
}
static Error store_in_apk(APKExportData *ed, const String &p_path, const Vector<uint8_t> &p_data, int compression_method = Z_DEFLATED) {
zip_fileinfo zipfi = get_zip_fileinfo();
zipOpenNewFileInZip(ed->apk,
p_path.utf8().get_data(),
&zipfi,
NULL,
0,
NULL,
0,
NULL,
compression_method,
Z_DEFAULT_COMPRESSION);
zipWriteInFileInZip(ed->apk, p_data.ptr(), p_data.size());
zipCloseFileInZip(ed->apk);
return OK;
}
static Error save_apk_so(void *p_userdata, const SharedObject &p_so) {
if (!p_so.path.get_file().begins_with("lib")) {
String err = "Android .so file names must start with \"lib\", but got: " + p_so.path;
ERR_PRINTS(err);
return FAILED;
}
APKExportData *ed = (APKExportData *)p_userdata;
Vector<String> abis = get_abis();
bool exported = false;
for (int i = 0; i < p_so.tags.size(); ++i) {
// shared objects can be fat (compatible with multiple ABIs)
int abi_index = abis.find(p_so.tags[i]);
if (abi_index != -1) {
exported = true;
String abi = abis[abi_index];
String dst_path = "lib/" + abi + "/" + p_so.path.get_file();
Vector<uint8_t> array = FileAccess::get_file_as_array(p_so.path);
Error store_err = store_in_apk(ed, dst_path, array);
ERR_FAIL_COND_V(store_err, store_err);
}
}
if (!exported) {
String abis_string = String(" ").join(abis);
String err = "Cannot determine ABI for library \"" + p_so.path + "\". One of the supported ABIs must be used as a tag: " + abis_string;
ERR_PRINTS(err);
return FAILED;
}
return OK;
}
static Error save_apk_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total) {
APKExportData *ed = (APKExportData *)p_userdata;
String dst_path = p_path.replace_first("res://", "assets/");
store_in_apk(ed, dst_path, p_data, _should_compress_asset(p_path, p_data) ? Z_DEFLATED : 0);
ed->ep->step("File: " + p_path, 3 + p_file * 100 / p_total);
return OK;
}
static Error ignore_apk_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total) {
return OK;
}
void _fix_manifest(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest, bool p_give_internet) {
// Leaving the unused types commented because looking these constants up
// again later would be annoying
// const int CHUNK_AXML_FILE = 0x00080003;
// const int CHUNK_RESOURCEIDS = 0x00080180;
const int CHUNK_STRINGS = 0x001C0001;
// const int CHUNK_XML_END_NAMESPACE = 0x00100101;
const int CHUNK_XML_END_TAG = 0x00100103;
// const int CHUNK_XML_START_NAMESPACE = 0x00100100;
const int CHUNK_XML_START_TAG = 0x00100102;
// const int CHUNK_XML_TEXT = 0x00100104;
const int UTF8_FLAG = 0x00000100;
Vector<String> string_table;
uint32_t ofs = 8;
uint32_t string_count = 0;
//uint32_t styles_count = 0;
uint32_t string_flags = 0;
uint32_t string_data_offset = 0;
//uint32_t styles_offset = 0;
uint32_t string_table_begins = 0;
uint32_t string_table_ends = 0;
Vector<uint8_t> stable_extra;
String version_name = p_preset->get("version/name");
int version_code = p_preset->get("version/code");
String package_name = p_preset->get("package/unique_name");
int orientation = p_preset->get("screen/orientation");
bool min_gles3 = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name") == "GLES3" &&
!ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2");
bool screen_support_small = p_preset->get("screen/support_small");
bool screen_support_normal = p_preset->get("screen/support_normal");
bool screen_support_large = p_preset->get("screen/support_large");
bool screen_support_xlarge = p_preset->get("screen/support_xlarge");
Vector<String> perms;
const char **aperms = android_perms;
while (*aperms) {
bool enabled = p_preset->get("permissions/" + String(*aperms).to_lower());
if (enabled)
perms.push_back("android.permission." + String(*aperms));
aperms++;
}
PoolStringArray user_perms = p_preset->get("permissions/custom_permissions");
for (int i = 0; i < user_perms.size(); i++) {
String user_perm = user_perms[i].strip_edges();
if (!user_perm.empty()) {
perms.push_back(user_perm);
}
}
if (p_give_internet) {
if (perms.find("android.permission.INTERNET") == -1)
perms.push_back("android.permission.INTERNET");
}
while (ofs < (uint32_t)p_manifest.size()) {
uint32_t chunk = decode_uint32(&p_manifest[ofs]);
uint32_t size = decode_uint32(&p_manifest[ofs + 4]);
switch (chunk) {
case CHUNK_STRINGS: {
int iofs = ofs + 8;
string_count = decode_uint32(&p_manifest[iofs]);
//styles_count = decode_uint32(&p_manifest[iofs + 4]);
string_flags = decode_uint32(&p_manifest[iofs + 8]);
string_data_offset = decode_uint32(&p_manifest[iofs + 12]);
//styles_offset = decode_uint32(&p_manifest[iofs + 16]);
/*
printf("string count: %i\n",string_count);
printf("flags: %i\n",string_flags);
printf("sdata ofs: %i\n",string_data_offset);
printf("styles ofs: %i\n",styles_offset);
*/
uint32_t st_offset = iofs + 20;
string_table.resize(string_count);
uint32_t string_end = 0;
string_table_begins = st_offset;
for (uint32_t i = 0; i < string_count; i++) {
uint32_t string_at = decode_uint32(&p_manifest[st_offset + i * 4]);
string_at += st_offset + string_count * 4;
ERR_EXPLAIN("Unimplemented, can't read utf8 string table.");
ERR_FAIL_COND(string_flags & UTF8_FLAG);
if (string_flags & UTF8_FLAG) {
} else {
uint32_t len = decode_uint16(&p_manifest[string_at]);
Vector<CharType> ucstring;
ucstring.resize(len + 1);
for (uint32_t j = 0; j < len; j++) {
uint16_t c = decode_uint16(&p_manifest[string_at + 2 + 2 * j]);
ucstring.write[j] = c;
}
string_end = MAX(string_at + 2 + 2 * len, string_end);
ucstring.write[len] = 0;
string_table.write[i] = ucstring.ptr();
}
}
for (uint32_t i = string_end; i < (ofs + size); i++) {
stable_extra.push_back(p_manifest[i]);
}
string_table_ends = ofs + size;
} break;
case CHUNK_XML_START_TAG: {
int iofs = ofs + 8;
uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
String tname = string_table[name];
uint32_t attrcount = decode_uint32(&p_manifest[iofs + 20]);
iofs += 28;
for (uint32_t i = 0; i < attrcount; i++) {
uint32_t attr_nspace = decode_uint32(&p_manifest[iofs]);
uint32_t attr_name = decode_uint32(&p_manifest[iofs + 4]);
uint32_t attr_value = decode_uint32(&p_manifest[iofs + 8]);
uint32_t attr_resid = decode_uint32(&p_manifest[iofs + 16]);
String value;
if (attr_value != 0xFFFFFFFF)
value = string_table[attr_value];
else
value = "Res #" + itos(attr_resid);
String attrname = string_table[attr_name];
String nspace;
if (attr_nspace != 0xFFFFFFFF)
nspace = string_table[attr_nspace];
else
nspace = "";
//replace project information
if (tname == "manifest" && attrname == "package") {
string_table.write[attr_value] = get_package_name(package_name);
}
if (tname == "manifest" && attrname == "versionCode") {
encode_uint32(version_code, &p_manifest.write[iofs + 16]);
}
if (tname == "manifest" && attrname == "versionName") {
if (attr_value == 0xFFFFFFFF) {
WARN_PRINT("Version name in a resource, should be plaintext")
} else
string_table.write[attr_value] = version_name;
}
if (tname == "activity" && attrname == "screenOrientation") {
encode_uint32(orientation == 0 ? 0 : 1, &p_manifest.write[iofs + 16]);
}
if (tname == "supports-screens") {
if (attrname == "smallScreens") {
encode_uint32(screen_support_small ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
} else if (attrname == "normalScreens") {
encode_uint32(screen_support_normal ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
} else if (attrname == "largeScreens") {
encode_uint32(screen_support_large ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
} else if (attrname == "xlargeScreens") {
encode_uint32(screen_support_xlarge ? 0xFFFFFFFF : 0, &p_manifest.write[iofs + 16]);
}
}
if (tname == "uses-feature" && attrname == "glEsVersion") {
encode_uint32(min_gles3 ? 0x00030000 : 0x00020000, &p_manifest.write[iofs + 16]);
}
iofs += 20;
}
} break;
case CHUNK_XML_END_TAG: {
int iofs = ofs + 8;
uint32_t name = decode_uint32(&p_manifest[iofs + 12]);
String tname = string_table[name];
if (tname == "manifest") {
// save manifest ending so we can restore it
Vector<uint8_t> manifest_end;
uint32_t manifest_cur_size = p_manifest.size();
manifest_end.resize(p_manifest.size() - ofs);
memcpy(manifest_end.ptrw(), &p_manifest[ofs], manifest_end.size());
int32_t attr_name_string = string_table.find("name");
ERR_EXPLAIN("Template does not have 'name' attribute");
ERR_FAIL_COND(attr_name_string == -1);
int32_t ns_android_string = string_table.find("android");
ERR_EXPLAIN("Template does not have 'android' namespace");
ERR_FAIL_COND(ns_android_string == -1);
int32_t attr_uses_permission_string = string_table.find("uses-permission");
if (attr_uses_permission_string == -1) {
string_table.push_back("uses-permission");
attr_uses_permission_string = string_table.size() - 1;
}
for (int i = 0; i < perms.size(); ++i) {
print_line("Adding permission " + perms[i]);
manifest_cur_size += 56 + 24; // node + end node
p_manifest.resize(manifest_cur_size);
// Add permission to the string pool
int32_t perm_string = string_table.find(perms[i]);
if (perm_string == -1) {
string_table.push_back(perms[i]);
perm_string = string_table.size() - 1;
}
// start tag
encode_uint16(0x102, &p_manifest.write[ofs]); // type
encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
encode_uint32(56, &p_manifest.write[ofs + 4]); // size
encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
encode_uint16(20, &p_manifest.write[ofs + 24]); // attr_start
encode_uint16(20, &p_manifest.write[ofs + 26]); // attr_size
encode_uint16(1, &p_manifest.write[ofs + 28]); // num_attrs
encode_uint16(0, &p_manifest.write[ofs + 30]); // id_index
encode_uint16(0, &p_manifest.write[ofs + 32]); // class_index
encode_uint16(0, &p_manifest.write[ofs + 34]); // style_index
// attribute
encode_uint32(ns_android_string, &p_manifest.write[ofs + 36]); // ns
encode_uint32(attr_name_string, &p_manifest.write[ofs + 40]); // 'name'
encode_uint32(perm_string, &p_manifest.write[ofs + 44]); // raw_value
encode_uint16(8, &p_manifest.write[ofs + 48]); // typedvalue_size
p_manifest.write[ofs + 50] = 0; // typedvalue_always0
p_manifest.write[ofs + 51] = 0x03; // typedvalue_type (string)
encode_uint32(perm_string, &p_manifest.write[ofs + 52]); // typedvalue reference
ofs += 56;
// end tag
encode_uint16(0x103, &p_manifest.write[ofs]); // type
encode_uint16(16, &p_manifest.write[ofs + 2]); // headersize
encode_uint32(24, &p_manifest.write[ofs + 4]); // size
encode_uint32(0, &p_manifest.write[ofs + 8]); // lineno
encode_uint32(-1, &p_manifest.write[ofs + 12]); // comment
encode_uint32(-1, &p_manifest.write[ofs + 16]); // ns
encode_uint32(attr_uses_permission_string, &p_manifest.write[ofs + 20]); // name
ofs += 24;
}
// copy footer back in
memcpy(&p_manifest.write[ofs], manifest_end.ptr(), manifest_end.size());
}
} break;
}
ofs += size;
}
//create new andriodmanifest binary
Vector<uint8_t> ret;
ret.resize(string_table_begins + string_table.size() * 4);
for (uint32_t i = 0; i < string_table_begins; i++) {
ret.write[i] = p_manifest[i];
}
ofs = 0;
for (int i = 0; i < string_table.size(); i++) {
encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
ofs += string_table[i].length() * 2 + 2 + 2;
}
ret.resize(ret.size() + ofs);
string_data_offset = ret.size() - ofs;
uint8_t *chars = &ret.write[string_data_offset];
for (int i = 0; i < string_table.size(); i++) {
String s = string_table[i];
encode_uint16(s.length(), chars);
chars += 2;
for (int j = 0; j < s.length(); j++) {
encode_uint16(s[j], chars);
chars += 2;
}
encode_uint16(0, chars);
chars += 2;
}
for (int i = 0; i < stable_extra.size(); i++) {
ret.push_back(stable_extra[i]);
}
//pad
while (ret.size() % 4)
ret.push_back(0);
uint32_t new_stable_end = ret.size();
uint32_t extra = (p_manifest.size() - string_table_ends);
ret.resize(new_stable_end + extra);
for (uint32_t i = 0; i < extra; i++)
ret.write[new_stable_end + i] = p_manifest[string_table_ends + i];
while (ret.size() % 4)
ret.push_back(0);
encode_uint32(ret.size(), &ret.write[4]); //update new file size
encode_uint32(new_stable_end - 8, &ret.write[12]); //update new string table size
encode_uint32(string_table.size(), &ret.write[16]); //update new number of strings
encode_uint32(string_data_offset - 8, &ret.write[28]); //update new string data offset
p_manifest = ret;
}
static String _parse_string(const uint8_t *p_bytes, bool p_utf8) {
uint32_t offset = 0;
uint32_t len = decode_uint16(&p_bytes[offset]);
if (p_utf8) {
//don't know how to read extended utf8, this will have to be for now
len >>= 8;
}
offset += 2;
//printf("len %i, unicode: %i\n",len,int(p_utf8));
if (p_utf8) {
Vector<uint8_t> str8;
str8.resize(len + 1);
for (uint32_t i = 0; i < len; i++) {
str8.write[i] = p_bytes[offset + i];
}
str8.write[len] = 0;
String str;
str.parse_utf8((const char *)str8.ptr());
return str;
} else {
String str;
for (uint32_t i = 0; i < len; i++) {
CharType c = decode_uint16(&p_bytes[offset + i * 2]);
if (c == 0)
break;
str += String::chr(c);
}
return str;
}
}
void _fix_resources(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &p_manifest) {
const int UTF8_FLAG = 0x00000100;
uint32_t string_block_len = decode_uint32(&p_manifest[16]);
uint32_t string_count = decode_uint32(&p_manifest[20]);
uint32_t string_flags = decode_uint32(&p_manifest[28]);
const uint32_t string_table_begins = 40;
Vector<String> string_table;
String package_name = p_preset->get("package/name");
for (uint32_t i = 0; i < string_count; i++) {
uint32_t offset = decode_uint32(&p_manifest[string_table_begins + i * 4]);
offset += string_table_begins + string_count * 4;
String str = _parse_string(&p_manifest[offset], string_flags & UTF8_FLAG);
if (str.begins_with("godot-project-name")) {
if (str == "godot-project-name") {
//project name
str = get_project_name(package_name);
} else {
String lang = str.substr(str.find_last("-") + 1, str.length()).replace("-", "_");
String prop = "application/config/name_" + lang;
if (ProjectSettings::get_singleton()->has_setting(prop)) {
str = ProjectSettings::get_singleton()->get(prop);
} else {
str = get_project_name(package_name);
}
}
}
string_table.push_back(str);
}
//write a new string table, but use 16 bits
Vector<uint8_t> ret;
ret.resize(string_table_begins + string_table.size() * 4);
for (uint32_t i = 0; i < string_table_begins; i++) {
ret.write[i] = p_manifest[i];
}
int ofs = 0;
for (int i = 0; i < string_table.size(); i++) {
encode_uint32(ofs, &ret.write[string_table_begins + i * 4]);
ofs += string_table[i].length() * 2 + 2 + 2;
}
ret.resize(ret.size() + ofs);
uint8_t *chars = &ret.write[ret.size() - ofs];
for (int i = 0; i < string_table.size(); i++) {
String s = string_table[i];
encode_uint16(s.length(), chars);
chars += 2;
for (int j = 0; j < s.length(); j++) {
encode_uint16(s[j], chars);
chars += 2;
}
encode_uint16(0, chars);
chars += 2;
}
//pad
while (ret.size() % 4)
ret.push_back(0);
//change flags to not use utf8
encode_uint32(string_flags & ~0x100, &ret.write[28]);
//change length
encode_uint32(ret.size() - 12, &ret.write[16]);
//append the rest...
int rest_from = 12 + string_block_len;
int rest_to = ret.size();
int rest_len = (p_manifest.size() - rest_from);
ret.resize(ret.size() + (p_manifest.size() - rest_from));
for (int i = 0; i < rest_len; i++) {
ret.write[rest_to + i] = p_manifest[rest_from + i];
}
//finally update the size
encode_uint32(ret.size(), &ret.write[4]);
p_manifest = ret;
//printf("end\n");
}
static Vector<String> get_enabled_abis(const Ref<EditorExportPreset> &p_preset) {
Vector<String> abis = get_abis();
Vector<String> enabled_abis;
for (int i = 0; i < abis.size(); ++i) {
bool is_enabled = p_preset->get("architectures/" + abis[i]);
if (is_enabled) {
enabled_abis.push_back(abis[i]);
}
}
return enabled_abis;
}
public:
typedef Error (*EditorExportSaveFunction)(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total);
public:
virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
String driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name");
if (driver == "GLES2") {
r_features->push_back("etc");
} else if (driver == "GLES3") {
r_features->push_back("etc2");
if (ProjectSettings::get_singleton()->get("rendering/quality/driver/fallback_to_gles2")) {
r_features->push_back("etc");
}
}
Vector<String> abis = get_enabled_abis(p_preset);
for (int i = 0; i < abis.size(); ++i) {
r_features->push_back(abis[i]);
}
}
virtual void get_export_options(List<ExportOption> *r_options) {
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "graphics/32_bits_framebuffer"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "one_click_deploy/clear_previous_install"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE, "*.apk"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "custom_package/use_custom_build"), false));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "command_line/extra_args"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "version/code", PROPERTY_HINT_RANGE, "1,4096,1,or_greater"), 1));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "version/name"), "1.0"));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/unique_name", PROPERTY_HINT_PLACEHOLDER_TEXT, "ext.domain.name"), "org.godotengine.$genname"));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "package/name", PROPERTY_HINT_PLACEHOLDER_TEXT, "Game Name [default if blank]"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "package/signed"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/immersive_mode"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "screen/orientation", PROPERTY_HINT_ENUM, "Landscape,Portrait"), 0));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_small"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/opengl_debug"), false));
for (unsigned int i = 0; i < sizeof(launcher_icons) / sizeof(launcher_icons[0]); ++i) {
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, launcher_icons[i].option_id, PROPERTY_HINT_FILE, "*.png"), ""));
}
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_user"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/debug_password"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_user"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "keystore/release_password"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "apk_expansion/enable"), false));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/SALT"), ""));
r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "apk_expansion/public_key", PROPERTY_HINT_MULTILINE_TEXT), ""));
Vector<String> abis = get_abis();
for (int i = 0; i < abis.size(); ++i) {
String abi = abis[i];
bool is_default = (abi == "armeabi-v7a" || abi == "arm64-v8a");
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "architectures/" + abi), is_default));
}
r_options->push_back(ExportOption(PropertyInfo(Variant::POOL_STRING_ARRAY, "permissions/custom_permissions"), PoolStringArray()));
const char **perms = android_perms;
while (*perms) {
r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "permissions/" + String(*perms).to_lower()), false));
perms++;
}
}
virtual String get_name() const {
return "Android";
}
virtual String get_os_name() const {
return "Android";
}
virtual Ref<Texture> get_logo() const {
return logo;
}
virtual bool poll_devices() {
bool dc = devices_changed;
if (dc) {
// don't clear unless we're reporting true, to avoid race
devices_changed = false;
}
return dc;
}
virtual int get_device_count() const {
device_lock->lock();
int dc = devices.size();
device_lock->unlock();
return dc;
}
virtual String get_device_name(int p_device) const {
ERR_FAIL_INDEX_V(p_device, devices.size(), "");
device_lock->lock();
String s = devices[p_device].name;
device_lock->unlock();
return s;
}
virtual String get_device_info(int p_device) const {
ERR_FAIL_INDEX_V(p_device, devices.size(), "");
device_lock->lock();
String s = devices[p_device].description;
device_lock->unlock();
return s;
}
virtual Error run(const Ref<EditorExportPreset> &p_preset, int p_device, int p_debug_flags) {
ERR_FAIL_INDEX_V(p_device, devices.size(), ERR_INVALID_PARAMETER);
device_lock->lock();
EditorProgress ep("run", "Running on " + devices[p_device].name, 3);
String adb = EditorSettings::get_singleton()->get("export/android/adb");
if (adb == "") {
EditorNode::add_io_error("ADB executable not configured in settings, can't run.");
device_lock->unlock();
return ERR_UNCONFIGURED;
}
//export_temp
ep.step("Exporting APK", 0);
const bool use_remote = (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) || (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT);
const bool use_reverse = devices[p_device].api_level >= 21;
if (use_reverse)
p_debug_flags |= DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST;
String export_to = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport.apk");
Error err = export_project(p_preset, true, export_to, p_debug_flags);
if (err) {
device_lock->unlock();
return err;
}
List<String> args;
int rv;
bool remove_prev = p_preset->get("one_click_deploy/clear_previous_install");
String version_name = p_preset->get("version/name");
String package_name = p_preset->get("package/unique_name");
if (remove_prev) {
ep.step("Uninstalling...", 1);
print_line("Uninstalling previous version: " + devices[p_device].name);
args.push_back("-s");
args.push_back(devices[p_device].id);
args.push_back("uninstall");
args.push_back(get_package_name(package_name));
err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
}
print_line("Installing to device (please wait...): " + devices[p_device].name);
ep.step("Installing to device (please wait...)", 2);
args.clear();
args.push_back("-s");
args.push_back(devices[p_device].id);
args.push_back("install");
args.push_back("-r");
args.push_back(export_to);
err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
if (err || rv != 0) {
EditorNode::add_io_error("Could not install to device.");
device_lock->unlock();
return ERR_CANT_CREATE;
}
if (use_remote) {
if (use_reverse) {
static const char *const msg = "** Device API >= 21; debugging over USB **";
EditorNode::get_singleton()->get_log()->add_message(msg);
print_line(String(msg).to_upper());
args.clear();
args.push_back("-s");
args.push_back(devices[p_device].id);
args.push_back("reverse");
args.push_back("--remove-all");
OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
if (p_debug_flags & DEBUG_FLAG_REMOTE_DEBUG) {
int dbg_port = EditorSettings::get_singleton()->get("network/debug/remote_port");
args.clear();
args.push_back("-s");
args.push_back(devices[p_device].id);
args.push_back("reverse");
args.push_back("tcp:" + itos(dbg_port));
args.push_back("tcp:" + itos(dbg_port));
OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
print_line("Reverse result: " + itos(rv));
}
if (p_debug_flags & DEBUG_FLAG_DUMB_CLIENT) {
int fs_port = EditorSettings::get_singleton()->get("filesystem/file_server/port");
args.clear();
args.push_back("-s");
args.push_back(devices[p_device].id);
args.push_back("reverse");
args.push_back("tcp:" + itos(fs_port));
args.push_back("tcp:" + itos(fs_port));
err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
print_line("Reverse result2: " + itos(rv));
}
} else {
static const char *const msg = "** Device API < 21; debugging over Wi-Fi **";
EditorNode::get_singleton()->get_log()->add_message(msg);
print_line(String(msg).to_upper());
}
}
ep.step("Running on Device...", 3);
args.clear();
args.push_back("-s");
args.push_back(devices[p_device].id);
args.push_back("shell");
args.push_back("am");
args.push_back("start");
if ((bool)EditorSettings::get_singleton()->get("export/android/force_system_user") && devices[p_device].api_level >= 17) { // Multi-user introduced in Android 17
args.push_back("--user");
args.push_back("0");
}
args.push_back("-a");
args.push_back("android.intent.action.MAIN");
args.push_back("-n");
args.push_back(get_package_name(package_name) + "/org.godotengine.godot.Godot");
err = OS::get_singleton()->execute(adb, args, true, NULL, NULL, &rv);
if (err || rv != 0) {
EditorNode::add_io_error("Could not execute on device.");
device_lock->unlock();
return ERR_CANT_CREATE;
}
device_lock->unlock();
return OK;
}
virtual Ref<Texture> get_run_icon() const {
return run_icon;
}
virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
String err;
if (!bool(p_preset->get("custom_package/use_custom_build"))) {
r_missing_templates = find_export_template("android_debug.apk") == String() || find_export_template("android_release.apk") == String();
if (p_preset->get("custom_package/debug") != "") {
if (FileAccess::exists(p_preset->get("custom_package/debug"))) {
r_missing_templates = false;
} else {
err += TTR("Custom debug template not found.") + "\n";
}
}
if (p_preset->get("custom_package/release") != "") {
if (FileAccess::exists(p_preset->get("custom_package/release"))) {
r_missing_templates = false;
} else {
err += TTR("Custom release template not found.") + "\n";
}
}
}
bool valid = !r_missing_templates;
String adb = EditorSettings::get_singleton()->get("export/android/adb");
if (!FileAccess::exists(adb)) {
valid = false;
err += TTR("ADB executable not configured in the Editor Settings.") + "\n";
}
String js = EditorSettings::get_singleton()->get("export/android/jarsigner");
if (!FileAccess::exists(js)) {
valid = false;
err += TTR("OpenJDK jarsigner not configured in the Editor Settings.") + "\n";
}
String dk = p_preset->get("keystore/debug");
if (!FileAccess::exists(dk)) {
dk = EditorSettings::get_singleton()->get("export/android/debug_keystore");
if (!FileAccess::exists(dk)) {
valid = false;
err += TTR("Debug keystore not configured in the Editor Settings nor in the preset.") + "\n";
}
}
if (bool(p_preset->get("custom_package/use_custom_build"))) {
String sdk_path = EditorSettings::get_singleton()->get("export/android/custom_build_sdk_path");
if (sdk_path == "") {
err += TTR("Custom build requires a valid Android SDK path in Editor Settings.") + "\n";
valid = false;
} else {
Error errn;
DirAccess *da = DirAccess::open(sdk_path.plus_file("tools"), &errn);
if (errn != OK) {
err += TTR("Invalid Android SDK path for custom build in Editor Settings.") + "\n";
valid = false;
}
if (da) {
memdelete(da);
}
}
if (!FileAccess::exists("res://android/build/build.gradle")) {
err += TTR("Android project is not installed for compiling. Install from Editor menu.") + "\n";
valid = false;
}
}
bool apk_expansion = p_preset->get("apk_expansion/enable");
if (apk_expansion) {
String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
if (apk_expansion_pkey == "") {
valid = false;
err += TTR("Invalid public key for APK expansion.") + "\n";
}
}
String pn = p_preset->get("package/unique_name");
String pn_err;
if (!is_package_name_valid(get_package_name(pn), &pn_err)) {
valid = false;
err += TTR("Invalid package name:") + " " + pn_err + "\n";
}
String etc_error = test_etc2();
if (etc_error != String()) {
valid = false;
err += etc_error;
}
r_error = err;
return valid;
}
virtual List<String> get_binary_extensions(const Ref<EditorExportPreset> &p_preset) const {
List<String> list;
list.push_back("apk");
return list;
}
void _update_custom_build_project() {
DirAccessRef da = DirAccess::open("res://android");
ERR_FAIL_COND(!da);
Map<String, List<String> > directory_paths;
Map<String, List<String> > manifest_sections;
Map<String, List<String> > gradle_sections;
da->list_dir_begin();
String d = da->get_next();
while (d != String()) {
if (!d.begins_with(".") && d != "build" && da->current_is_dir()) { //a dir and not the build dir
//add directories found
DirAccessRef ds = DirAccess::open(String("res://android").plus_file(d));
if (ds) {
ds->list_dir_begin();
String sd = ds->get_next();
while (sd != String()) {
if (!sd.begins_with(".") && ds->current_is_dir()) {
String key = sd.to_upper();
if (!directory_paths.has(key)) {
directory_paths[key] = List<String>();
}
String path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android").plus_file(d).plus_file(sd);
directory_paths[key].push_back(path);
print_line("Add: " + sd + ":" + path);
}
sd = ds->get_next();
}
ds->list_dir_end();
}
//parse manifest
{
FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("AndroidManifest.conf"), FileAccess::READ);
if (f) {
String section;
while (!f->eof_reached()) {
String l = f->get_line();
String k = l.strip_edges();
if (k.begins_with("[")) {
section = k.substr(1, k.length() - 2).strip_edges().to_upper();
print_line("Section: " + section);
} else if (k != String()) {
if (!manifest_sections.has(section)) {
manifest_sections[section] = List<String>();
}
manifest_sections[section].push_back(l);
}
}
f->close();
}
}
//parse gradle
{
FileAccessRef f = FileAccess::open(String("res://android").plus_file(d).plus_file("gradle.conf"), FileAccess::READ);
if (f) {
String section;
while (!f->eof_reached()) {
String l = f->get_line().strip_edges();
String k = l.strip_edges();
if (k.begins_with("[")) {
section = k.substr(1, k.length() - 2).strip_edges().to_upper();
print_line("Section: " + section);
} else if (k != String()) {
if (!gradle_sections.has(section)) {
gradle_sections[section] = List<String>();
}
gradle_sections[section].push_back(l);
}
}
}
}
}
d = da->get_next();
}
da->list_dir_end();
{ //fix gradle build
String new_file;
{
FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::READ);
if (f) {
while (!f->eof_reached()) {
String l = f->get_line();
if (l.begins_with("//CHUNK_")) {
String text = l.replace_first("//CHUNK_", "");
int begin_pos = text.find("_BEGIN");
if (begin_pos != -1) {
text = text.substr(0, begin_pos);
text = text.to_upper(); //just in case
String end_marker = "//CHUNK_" + text + "_END";
size_t pos = f->get_position();
bool found = false;
while (!f->eof_reached()) {
l = f->get_line();
if (l.begins_with(end_marker)) {
found = true;
break;
}
}
new_file += "//CHUNK_" + text + "_BEGIN\n";
if (!found) {
ERR_PRINTS("No end marker found in build.gradle for chunk: " + text);
f->seek(pos);
} else {
//add chunk lines
if (gradle_sections.has(text)) {
for (List<String>::Element *E = gradle_sections[text].front(); E; E = E->next()) {
new_file += E->get() + "\n";
}
}
new_file += end_marker + "\n";
}
} else {
new_file += l + "\n"; //pass line by
}
} else if (l.begins_with("//DIR_")) {
String text = l.replace_first("//DIR_", "");
int begin_pos = text.find("_BEGIN");
if (begin_pos != -1) {
text = text.substr(0, begin_pos);
text = text.to_upper(); //just in case
String end_marker = "//DIR_" + text + "_END";
size_t pos = f->get_position();
bool found = false;
while (!f->eof_reached()) {
l = f->get_line();
if (l.begins_with(end_marker)) {
found = true;
break;
}
}
new_file += "//DIR_" + text + "_BEGIN\n";
if (!found) {
ERR_PRINTS("No end marker found in build.gradle for dir: " + text);
f->seek(pos);
} else {
//add chunk lines
if (directory_paths.has(text)) {
for (List<String>::Element *E = directory_paths[text].front(); E; E = E->next()) {
new_file += ",'" + E->get().replace("'", "\'") + "'";
new_file += "\n";
}
}
new_file += end_marker + "\n";
}
} else {
new_file += l + "\n"; //pass line by
}
} else {
new_file += l + "\n";
}
}
}
}
FileAccessRef f = FileAccess::open("res://android/build/build.gradle", FileAccess::WRITE);
f->store_string(new_file);
f->close();
}
{ //fix manifest
String new_file;
{
FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::READ);
if (f) {
while (!f->eof_reached()) {
String l = f->get_line();
if (l.begins_with("<!--CHUNK_")) {
String text = l.replace_first("<!--CHUNK_", "");
int begin_pos = text.find("_BEGIN-->");
if (begin_pos != -1) {
text = text.substr(0, begin_pos);
text = text.to_upper(); //just in case
String end_marker = "<!--CHUNK_" + text + "_END-->";
size_t pos = f->get_position();
bool found = false;
while (!f->eof_reached()) {
l = f->get_line();
if (l.begins_with(end_marker)) {
found = true;
break;
}
}
new_file += "<!--CHUNK_" + text + "_BEGIN-->\n";
if (!found) {
ERR_PRINTS("No end marker found in AndroidManifest.conf for chunk: " + text);
f->seek(pos);
} else {
//add chunk lines
if (manifest_sections.has(text)) {
for (List<String>::Element *E = manifest_sections[text].front(); E; E = E->next()) {
new_file += E->get() + "\n";
}
}
new_file += end_marker + "\n";
}
} else {
new_file += l + "\n"; //pass line by
}
} else if (l.strip_edges().begins_with("<application")) {
String last_tag = "android:icon=\"@drawable/icon\"";
int last_tag_pos = l.find(last_tag);
if (last_tag_pos == -1) {
WARN_PRINTS("No adding of application tags because could not find last tag for <application: " + last_tag);
new_file += l + "\n";
} else {
String base = l.substr(0, last_tag_pos + last_tag.length());
if (manifest_sections.has("application_tags")) {
for (List<String>::Element *E = manifest_sections["application_tags"].front(); E; E = E->next()) {
String to_add = E->get().strip_edges();
base += " " + to_add + " ";
}
}
base += ">\n";
new_file += base;
}
} else {
new_file += l + "\n";
}
}
}
}
FileAccessRef f = FileAccess::open("res://android/build/AndroidManifest.xml", FileAccess::WRITE);
f->store_string(new_file);
f->close();
}
}
virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) {
ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
String src_apk;
EditorProgress ep("export", "Exporting for Android", 105);
if (bool(p_preset->get("custom_package/use_custom_build"))) { //custom build
//re-generate build.gradle and AndroidManifest.xml
{ //test that installed build version is alright
FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::READ);
if (!f) {
EditorNode::get_singleton()->show_warning(TTR("Trying to build from a custom built template, but no version info for it exists. Please reinstall from the 'Project' menu."));
return ERR_UNCONFIGURED;
}
String version = f->get_line().strip_edges();
if (version != VERSION_FULL_CONFIG) {
EditorNode::get_singleton()->show_warning(vformat(TTR("Android build version mismatch:\n Template installed: %s\n Godot Version: %s\nPlease reinstall Android build template from 'Project' menu."), version, VERSION_FULL_CONFIG));
return ERR_UNCONFIGURED;
}
}
//build project if custom build is enabled
String sdk_path = EDITOR_GET("export/android/custom_build_sdk_path");
ERR_FAIL_COND_V(sdk_path == "", ERR_UNCONFIGURED);
_update_custom_build_project();
OS::get_singleton()->set_environment("ANDROID_HOME", sdk_path); //set and overwrite if required
String build_command;
#ifdef WINDOWS_ENABLED
build_command = "gradlew.bat";
#else
build_command = "gradlew";
#endif
String build_path = ProjectSettings::get_singleton()->get_resource_path().plus_file("android/build");
build_command = build_path.plus_file(build_command);
List<String> cmdline;
cmdline.push_back("build");
cmdline.push_back("-p");
cmdline.push_back(build_path);
/*{ used for debug
int ec;
String pipe;
OS::get_singleton()->execute(build_command, cmdline, true, NULL, NULL, &ec);
print_line("exit code: " + itos(ec));
}
*/
int result = EditorNode::get_singleton()->execute_and_show_output(TTR("Building Android Project (gradle)"), build_command, cmdline);
if (result != 0) {
EditorNode::get_singleton()->show_warning(TTR("Building of Android project failed, check output for the error.\nAlternatively visit docs.godotengine.org for Android build documentation."));
return ERR_CANT_CREATE;
}
if (p_debug) {
src_apk = build_path.plus_file("build/outputs/apk/debug/build-debug-unsigned.apk");
} else {
src_apk = build_path.plus_file("build/outputs/apk/release/build-release-unsigned.apk");
}
if (!FileAccess::exists(src_apk)) {
EditorNode::get_singleton()->show_warning(TTR("No build apk generated at: ") + "\n" + src_apk);
return ERR_CANT_CREATE;
}
} else {
if (p_debug)
src_apk = p_preset->get("custom_package/debug");
else
src_apk = p_preset->get("custom_package/release");
src_apk = src_apk.strip_edges();
if (src_apk == "") {
if (p_debug) {
src_apk = find_export_template("android_debug.apk");
} else {
src_apk = find_export_template("android_release.apk");
}
if (src_apk == "") {
EditorNode::add_io_error("Package not found: " + src_apk);
return ERR_FILE_NOT_FOUND;
}
}
}
if (!DirAccess::exists(p_path.get_base_dir())) {
return ERR_FILE_BAD_PATH;
}
FileAccess *src_f = NULL;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
ep.step("Creating APK", 0);
unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io);
if (!pkg) {
EditorNode::add_io_error("Could not find template APK to export:\n" + src_apk);
return ERR_FILE_NOT_FOUND;
}
ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
int ret = unzGoToFirstFile(pkg);
zlib_filefunc_def io2 = io;
FileAccess *dst_f = NULL;
io2.opaque = &dst_f;
String unaligned_path = EditorSettings::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned.apk");
zipFile unaligned_apk = zipOpen2(unaligned_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
bool use_32_fb = p_preset->get("graphics/32_bits_framebuffer");
bool immersive = p_preset->get("screen/immersive_mode");
bool debug_opengl = p_preset->get("screen/opengl_debug");
bool _signed = p_preset->get("package/signed");
bool apk_expansion = p_preset->get("apk_expansion/enable");
String cmdline = p_preset->get("command_line/extra_args");
int version_code = p_preset->get("version/code");
String version_name = p_preset->get("version/name");
String package_name = p_preset->get("package/unique_name");
String apk_expansion_pkey = p_preset->get("apk_expansion/public_key");
String release_keystore = p_preset->get("keystore/release");
String release_username = p_preset->get("keystore/release_user");
String release_password = p_preset->get("keystore/release_password");
Vector<String> enabled_abis = get_enabled_abis(p_preset);
while (ret == UNZ_OK) {
//get filename
unz_file_info info;
char fname[16384];
ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
bool skip = false;
String file = fname;
Vector<uint8_t> data;
data.resize(info.uncompressed_size);
//read
unzOpenCurrentFile(pkg);
unzReadCurrentFile(pkg, data.ptrw(), data.size());
unzCloseCurrentFile(pkg);
//write
if (file == "AndroidManifest.xml") {
_fix_manifest(p_preset, data, p_flags & (DEBUG_FLAG_DUMB_CLIENT | DEBUG_FLAG_REMOTE_DEBUG));
}
if (file == "resources.arsc") {
_fix_resources(p_preset, data);
}
if (file == "res/drawable-nodpi-v4/icon.png") {
bool found = false;
for (unsigned int i = 0; i < sizeof(launcher_icons) / sizeof(launcher_icons[0]); ++i) {
String icon_path = String(p_preset->get(launcher_icons[i].option_id)).strip_edges();
if (icon_path != "" && icon_path.ends_with(".png")) {
FileAccess *f = FileAccess::open(icon_path, FileAccess::READ);
if (f) {
data.resize(f->get_len());
f->get_buffer(data.ptrw(), data.size());
memdelete(f);
found = true;
break;
}
}
}
if (!found) {
String appicon = ProjectSettings::get_singleton()->get("application/config/icon");
if (appicon != "" && appicon.ends_with(".png")) {
FileAccess *f = FileAccess::open(appicon, FileAccess::READ);
if (f) {
data.resize(f->get_len());
f->get_buffer(data.ptrw(), data.size());
memdelete(f);
}
}
}
}
if (file.ends_with(".so")) {
bool enabled = false;
for (int i = 0; i < enabled_abis.size(); ++i) {
if (file.begins_with("lib/" + enabled_abis[i] + "/")) {
enabled = true;
break;
}
}
if (!enabled) {
skip = true;
}
}
if (file.begins_with("META-INF") && _signed) {
skip = true;
}
if (!skip) {
print_line("ADDING: " + file);
// Respect decision on compression made by AAPT for the export template
const bool uncompressed = info.compression_method == 0;
zip_fileinfo zipfi = get_zip_fileinfo();
zipOpenNewFileInZip(unaligned_apk,
file.utf8().get_data(),
&zipfi,
NULL,
0,
NULL,
0,
NULL,
uncompressed ? 0 : Z_DEFLATED,
Z_DEFAULT_COMPRESSION);
zipWriteInFileInZip(unaligned_apk, data.ptr(), data.size());
zipCloseFileInZip(unaligned_apk);
}
ret = unzGoToNextFile(pkg);
}
ep.step("Adding Files...", 1);
Error err = OK;
Vector<String> cl = cmdline.strip_edges().split(" ");
for (int i = 0; i < cl.size(); i++) {
if (cl[i].strip_edges().length() == 0) {
cl.remove(i);
i--;
}
}
gen_export_flags(cl, p_flags);
if (p_flags & DEBUG_FLAG_DUMB_CLIENT) {
APKExportData ed;
ed.ep = &ep;
ed.apk = unaligned_apk;
err = export_project_files(p_preset, ignore_apk_file, &ed, save_apk_so);
} else {
//all files
if (apk_expansion) {
String apkfname = "main." + itos(version_code) + "." + get_package_name(package_name) + ".obb";
String fullpath = p_path.get_base_dir().plus_file(apkfname);
err = save_pack(p_preset, fullpath);
if (err != OK) {
unzClose(pkg);
EditorNode::add_io_error("Could not write expansion package file: " + apkfname);
return OK;
}
cl.push_back("--use_apk_expansion");
cl.push_back("--apk_expansion_md5");
cl.push_back(FileAccess::get_md5(fullpath));
cl.push_back("--apk_expansion_key");
cl.push_back(apk_expansion_pkey.strip_edges());
} else {
APKExportData ed;
ed.ep = &ep;
ed.apk = unaligned_apk;
err = export_project_files(p_preset, save_apk_file, &ed, save_apk_so);
}
}
if (!err) {
APKExportData ed;
ed.ep = &ep;
ed.apk = unaligned_apk;
for (unsigned int i = 0; i < sizeof(launcher_icons) / sizeof(launcher_icons[0]); ++i) {
String icon_path = String(p_preset->get(launcher_icons[i].option_id)).strip_edges();
if (icon_path != "" && icon_path.ends_with(".png") && FileAccess::exists(icon_path)) {
Vector<uint8_t> data = FileAccess::get_file_as_array(icon_path);
store_in_apk(&ed, launcher_icons[i].export_path, data);
}
}
}
if (use_32_fb)
cl.push_back("--use_depth_32");
if (immersive)
cl.push_back("--use_immersive");
if (debug_opengl)
cl.push_back("--debug_opengl");
if (cl.size()) {
//add comandline
Vector<uint8_t> clf;
clf.resize(4);
encode_uint32(cl.size(), &clf.write[0]);
for (int i = 0; i < cl.size(); i++) {
print_line(itos(i) + " param: " + cl[i]);
CharString txt = cl[i].utf8();
int base = clf.size();
int length = txt.length();
if (!length)
continue;
clf.resize(base + 4 + length);
encode_uint32(length, &clf.write[base]);
copymem(&clf.write[base + 4], txt.ptr(), length);
}
zip_fileinfo zipfi = get_zip_fileinfo();
zipOpenNewFileInZip(unaligned_apk,
"assets/_cl_",
&zipfi,
NULL,
0,
NULL,
0,
NULL,
0, // No compress (little size gain and potentially slower startup)
Z_DEFAULT_COMPRESSION);
zipWriteInFileInZip(unaligned_apk, clf.ptr(), clf.size());
zipCloseFileInZip(unaligned_apk);
}
zipClose(unaligned_apk, NULL);
unzClose(pkg);
if (err) {
return err;
}
if (_signed) {
String jarsigner = EditorSettings::get_singleton()->get("export/android/jarsigner");
if (!FileAccess::exists(jarsigner)) {
EditorNode::add_io_error("'jarsigner' could not be found.\nPlease supply a path in the Editor Settings.\nThe resulting APK is unsigned.");
return OK;
}
String keystore;
String password;
String user;
if (p_debug) {
keystore = p_preset->get("keystore/debug");
password = p_preset->get("keystore/debug_password");
user = p_preset->get("keystore/debug_user");
if (keystore.empty()) {
keystore = EditorSettings::get_singleton()->get("export/android/debug_keystore");
password = EditorSettings::get_singleton()->get("export/android/debug_keystore_pass");
user = EditorSettings::get_singleton()->get("export/android/debug_keystore_user");
}
ep.step("Signing debug APK...", 103);
} else {
keystore = release_keystore;
password = release_password;
user = release_username;
ep.step("Signing release APK...", 103);
}
if (!FileAccess::exists(keystore)) {
EditorNode::add_io_error("Could not find keystore, unable to export.");
return ERR_FILE_CANT_OPEN;
}
List<String> args;
args.push_back("-digestalg");
args.push_back("SHA-256");
args.push_back("-sigalg");
args.push_back("SHA256withRSA");
String tsa_url = EditorSettings::get_singleton()->get("export/android/timestamping_authority_url");
if (tsa_url != "") {
args.push_back("-tsa");
args.push_back(tsa_url);
}
args.push_back("-verbose");
args.push_back("-keystore");
args.push_back(keystore);
args.push_back("-storepass");
args.push_back(password);
args.push_back(unaligned_path);
args.push_back(user);
int retval;
OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
if (retval) {
EditorNode::add_io_error("'jarsigner' returned with error #" + itos(retval));
return ERR_CANT_CREATE;
}
ep.step("Verifying APK...", 104);
args.clear();
args.push_back("-verify");
args.push_back("-keystore");
args.push_back(keystore);
args.push_back(unaligned_path);
args.push_back("-verbose");
OS::get_singleton()->execute(jarsigner, args, true, NULL, NULL, &retval);
if (retval) {
EditorNode::add_io_error("'jarsigner' verification of APK failed. Make sure to use a jarsigner from OpenJDK 8.");
return ERR_CANT_CREATE;
}
}
// Let's zip-align (must be done after signing)
static const int ZIP_ALIGNMENT = 4;
ep.step("Aligning APK...", 105);
unzFile tmp_unaligned = unzOpen2(unaligned_path.utf8().get_data(), &io);
if (!tmp_unaligned) {
EditorNode::add_io_error("Could not find temp unaligned APK.");
return ERR_FILE_NOT_FOUND;
}
ERR_FAIL_COND_V(!tmp_unaligned, ERR_CANT_OPEN);
ret = unzGoToFirstFile(tmp_unaligned);
io2 = io;
dst_f = NULL;
io2.opaque = &dst_f;
zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
// Take files from the unaligned APK and write them out to the aligned one
// in raw mode, i.e. not uncompressing and recompressing, aligning them as needed,
// following what is done in https://github.com/android/platform_build/blob/master/tools/zipalign/ZipAlign.cpp
int bias = 0;
while (ret == UNZ_OK) {
unz_file_info info;
memset(&info, 0, sizeof(info));
char fname[16384];
char extra[16384];
ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, NULL, 0);
String file = fname;
Vector<uint8_t> data;
data.resize(info.compressed_size);
// read
int method, level;
unzOpenCurrentFile2(tmp_unaligned, &method, &level, 1); // raw read
long file_offset = unzGetCurrentFileZStreamPos64(tmp_unaligned);
unzReadCurrentFile(tmp_unaligned, data.ptrw(), data.size());
unzCloseCurrentFile(tmp_unaligned);
// align
int padding = 0;
if (!info.compression_method) {
// Uncompressed file => Align
long new_offset = file_offset + bias;
padding = (ZIP_ALIGNMENT - (new_offset % ZIP_ALIGNMENT)) % ZIP_ALIGNMENT;
}
memset(extra + info.size_file_extra, 0, padding);
// write
zip_fileinfo zipfi = get_zip_fileinfo();
zipOpenNewFileInZip2(final_apk,
file.utf8().get_data(),
&zipfi,
extra,
info.size_file_extra + padding,
NULL,
0,
NULL,
method,
level,
1); // raw write
zipWriteInFileInZip(final_apk, data.ptr(), data.size());
zipCloseFileInZipRaw(final_apk, info.uncompressed_size, info.crc);
bias += padding;
ret = unzGoToNextFile(tmp_unaligned);
}
zipClose(final_apk, NULL);
unzClose(tmp_unaligned);
return OK;
}
virtual void get_platform_features(List<String> *r_features) {
r_features->push_back("mobile");
r_features->push_back("Android");
}
virtual void resolve_platform_feature_priorities(const Ref<EditorExportPreset> &p_preset, Set<String> &p_features) {
}
EditorExportPlatformAndroid() {
Ref<Image> img = memnew(Image(_android_logo));
logo.instance();
logo->create_from_image(img);
img = Ref<Image>(memnew(Image(_android_run_icon)));
run_icon.instance();
run_icon->create_from_image(img);
device_lock = Mutex::create();
devices_changed = true;
quit_request = false;
device_thread = Thread::create(_device_poll_thread, this);
}
~EditorExportPlatformAndroid() {
quit_request = true;
Thread::wait_to_finish(device_thread);
memdelete(device_lock);
memdelete(device_thread);
}
};
void register_android_exporter() {
String exe_ext;
if (OS::get_singleton()->get_name() == "Windows") {
exe_ext = "*.exe";
}
EDITOR_DEF("export/android/adb", "");
EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/adb", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
EDITOR_DEF("export/android/jarsigner", "");
EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/jarsigner", PROPERTY_HINT_GLOBAL_FILE, exe_ext));
EDITOR_DEF("export/android/debug_keystore", "");
EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/debug_keystore", PROPERTY_HINT_GLOBAL_FILE, "*.keystore"));
EDITOR_DEF("export/android/debug_keystore_user", "androiddebugkey");
EDITOR_DEF("export/android/debug_keystore_pass", "android");
EDITOR_DEF("export/android/force_system_user", false);
EDITOR_DEF("export/android/custom_build_sdk_path", "");
EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "export/android/custom_build_sdk_path", PROPERTY_HINT_GLOBAL_DIR, "*.keystore"));
EDITOR_DEF("export/android/timestamping_authority_url", "");
EDITOR_DEF("export/android/shutdown_adb_on_exit", true);
Ref<EditorExportPlatformAndroid> exporter = Ref<EditorExportPlatformAndroid>(memnew(EditorExportPlatformAndroid));
EditorExport::get_singleton()->add_export_platform(exporter);
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_connect_socket_01.cpp
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__new.label.xml
Template File: sources-sinks-01.tmpl.cpp
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with new [] and check the size of the memory to be allocated
* BadSink : Allocate memory with new [], but incorrectly check the size of the memory to be allocated
* Flow Variant: 01 Baseline
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#define HELLO_STRING L"hello"
namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_connect_socket_01
{
#ifndef OMITBAD
void bad()
{
size_t data;
/* Initialize data */
data = 0;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to unsigned int */
data = strtoul(inputBuffer, NULL, 0);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
{
wchar_t * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING))
{
myString = new wchar_t[data];
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
delete [] myString;
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
size_t data;
/* Initialize data */
data = 0;
/* FIX: Use a relatively small number for memory allocation */
data = 20;
{
wchar_t * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING))
{
myString = new wchar_t[data];
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
delete [] myString;
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
size_t data;
/* Initialize data */
data = 0;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to unsigned int */
data = strtoul(inputBuffer, NULL, 0);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
{
wchar_t * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the wcscpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > wcslen(HELLO_STRING) && data < 100)
{
myString = new wchar_t[data];
/* Copy a small string into myString */
wcscpy(myString, HELLO_STRING);
printWLine(myString);
delete [] myString;
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_connect_socket_01; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
#include <bits/stdc++.h>
using namespace std;
int t,m;
int dp[100002];
int tim[10002],value[10002];
int main()
{
std::ios::sync_with_stdio(false);
cin >> t >> m;
for(int i=1;i<=m;i++) cin >> tim[i] >> value[i];
for(int i=1;i<=m;i++)
{
for(int j=tim[i];j<=t;j++)
{
dp[j]=max(dp[j],dp[j-tim[i]]+value[i]);
}
}
int max=0;
for(int i=0;i<=t;i++) if(max<dp[i]) max=dp[i];
cout << max << endl;
return 0;
}
|
#include <torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h>
#include <torch/csrc/jit/codegen/fuser/compiler.h>
#include <ATen/ATen.h>
#include <ATen/CUDAGeneratorImpl.h>
#include <ATen/cuda/CUDAContext.h>
#include <ATen/cuda/nvrtc_stub/ATenNVRTC.h>
#include <THC/THC.h>
#include <c10/cuda/CUDAGuard.h>
#include <torch/csrc/jit/resource_guard.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <stdexcept>
#include <tuple>
#include <vector>
namespace torch {
namespace jit {
namespace fuser {
namespace cuda {
// See NOTE [ USE OF NVRTC AND DRIVER API ]
const at::cuda::NVRTC& nvrtc() {
return at::globalContext().getNVRTC();
}
// query codegen output arch and target
void codegenOutputQuery(
const cudaDeviceProp* const prop,
int& major,
int& minor,
bool& compile_to_sass) {
int nvrtc_major = 0, nvrtc_minor = 0;
AT_CUDA_NVRTC_CHECK(nvrtc().nvrtcVersion(&nvrtc_major, &nvrtc_minor));
// Short-circuits if NVRTC version too low
AT_ASSERT(nvrtc_major >= 6);
// Major and minor is determined by device properties and
// possibly "downcompiled" to a lower (compatible) compute architecture
// based on the NVRTC version
major = prop->major;
minor = prop->minor;
if (nvrtc_major <= 7 && prop->major > 5) { // 7 supports 2-5.x
major = 5;
minor = 0;
} else if (nvrtc_major <= 8 && prop->major > 6) { // 8 supports 2-6.x
major = 6;
minor = 0;
// NOLINTNEXTLINE(bugprone-branch-clone)
} else if (nvrtc_major <= 9 && prop->major >= 7) { // 9 supports 3-7.2
major = 7;
minor = (prop->major == 7 && prop->minor <= 2) ? prop->minor : 0;
} else if (nvrtc_major <= 10 && prop->major >= 7) { // 10 supports 3-7.5
major = 7;
minor = (prop->major == 7 && prop->minor <= 5) ? prop->minor : 0;
} else if (
nvrtc_major == 11 && nvrtc_minor == 0 &&
prop->major >= 8) { // 11.0 supports 3.5-8.0
major = 8;
minor = 0;
}
// if we are clamping major/minor, sass is not compatible
compile_to_sass = ((major == prop->major) && (minor == prop->minor));
}
// Compiles the specified kernel and stores the metadata required to run it
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
FusedKernelCUDA::FusedKernelCUDA(
at::DeviceIndex device,
std::string name,
std::string code,
std::vector<TensorDesc> input_desc,
std::vector<TensorDesc> output_desc,
std::vector<PartitionDesc> chunk_desc,
std::vector<PartitionDesc> concat_desc,
bool has_random)
: FusedKernel(
std::move(name),
std::move(code),
std::move(input_desc),
std::move(output_desc),
std::move(chunk_desc),
std::move(concat_desc),
has_random),
device_(device) {
// Initializes driver's API context (if necessary)
CUcontext pctx = nullptr;
AT_CUDA_DRIVER_CHECK(nvrtc().cuCtxGetCurrent(&pctx));
if (!pctx) {
std::unique_lock<std::mutex> cudaFreeMutexLock(
*(c10::cuda::CUDACachingAllocator::getFreeMutex()));
cudaFree(nullptr);
}
// Note: hacked at::DeviceGuard since at::DeviceGuard was failing to work
// properly in some scenarios
const auto prior_device = at::cuda::current_device();
at::cuda::set_device(device_);
// Acquires device and NVRTC properties (for compile arch and occupancy
// calculations)
prop_ = at::cuda::getCurrentDeviceProperties();
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
int major, minor;
bool compile_to_sass = false;
codegenOutputQuery(prop_, major, minor, compile_to_sass);
// Creates the NVRTC program
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
nvrtcProgram program;
AT_CUDA_NVRTC_CHECK(nvrtc().nvrtcCreateProgram(
&program, code_.c_str(), nullptr, 0, nullptr, nullptr));
#ifdef __HIP_PLATFORM_HCC__
std::vector<const char*> args = {"--std=c++14"};
#if ROCM_VERSION >= 40200
args.push_back("-hip-pch");
#endif
#else
const std::string compute = std::string("--gpu-architecture=") +
#if CUDA_VERSION >= 11010
// CUDA 11.1 allows going directly to SASS (sm_) instead of PTX (compute_)
// which gives better backwards compatibility to work on older driver,
// (since older driver doesn't necessrily recognize PTX emitted by new
// toolkit);
// Meanwhile, for forward compatibility (future device with
// `compile_to_sass==false`), since SASS are not necessarily compatible,
// we fallback to PTX instead.
(compile_to_sass ? "sm_" : "compute_") +
#else
"compute_" +
#endif
std::to_string(major) + std::to_string(minor);
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
const std::vector<const char*> args = {
"--std=c++14", compute.c_str(), "-default-device"};
#endif
const auto result =
nvrtc().nvrtcCompileProgram(program, args.size(), args.data());
if (result != NVRTC_SUCCESS) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
size_t logsize;
AT_CUDA_NVRTC_CHECK(nvrtc().nvrtcGetProgramLogSize(program, &logsize));
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
std::vector<char> log(logsize);
AT_CUDA_NVRTC_CHECK(nvrtc().nvrtcGetProgramLog(program, log.data()));
std::stringstream cu;
cu << log.data();
throw std::runtime_error(cu.str());
}
ResourceGuard holdProgram(
[&] { AT_CUDA_NVRTC_CHECK(nvrtc().nvrtcDestroyProgram(&program)); });
AT_CUDA_NVRTC_CHECK(result);
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
size_t ptx_size;
#if CUDA_VERSION >= 11010
// compile_to_sass determines whether we are generating SASS or PTX, hence
// the different API.
const auto getSize = compile_to_sass
? at::globalContext().getNVRTC().nvrtcGetCUBINSize
: at::globalContext().getNVRTC().nvrtcGetPTXSize;
const auto getFunc = compile_to_sass
? at::globalContext().getNVRTC().nvrtcGetCUBIN
: at::globalContext().getNVRTC().nvrtcGetPTX;
#else
const auto getSize = at::globalContext().getNVRTC().nvrtcGetPTXSize;
const auto getFunc = at::globalContext().getNVRTC().nvrtcGetPTX;
#endif
AT_CUDA_NVRTC_CHECK(getSize(program, &ptx_size));
ptx_.resize(ptx_size);
AT_CUDA_NVRTC_CHECK(getFunc(program, ptx_.data()));
AT_CUDA_DRIVER_CHECK(nvrtc().cuModuleLoadData(&module_, ptx_.data()));
AT_CUDA_DRIVER_CHECK(
nvrtc().cuModuleGetFunction(&function_, module_, name_.c_str()));
// Computes max blocks
#if defined(__HIP_PLATFORM_HCC__) && HIP_VERSION < 305
// HIP function signature is not compatible yet
uint32_t max_blocks;
AT_CUDA_DRIVER_CHECK(nvrtc().hipOccupancyMaxActiveBlocksPerMultiprocessor(
&max_blocks, function_, 128, 0));
maxBlocks_ = max_blocks;
#else
AT_CUDA_DRIVER_CHECK(nvrtc().cuOccupancyMaxActiveBlocksPerMultiprocessor(
&maxBlocks_, function_, 128, 0));
#endif
maxBlocks_ *= prop_->multiProcessorCount;
// Resets device (end of hacked at::DeviceGuard)
at::cuda::set_device(prior_device);
}
static int ceilDiv(const int a, const int b) {
return (a + b - 1) / b;
}
void FusedKernelCUDA::launch_raw(
const uint32_t numel,
std::vector<void*>& arguments) const {
// NOLINTNEXTLINE(bugprone-unused-raii)
at::cuda::CUDAGuard{device_};
// Hacked at::DeviceGuard (see note above)
const auto prior_device = at::cuda::current_device();
at::cuda::set_device(device_);
const auto nBlocks = std::min(maxBlocks_, ceilDiv(numel, kBlockSize));
// Adds random state to arguments if necessary
// Note: philox_engine_inputs defined here so its lifetime extends to the
// launch
std::pair<uint64_t, uint64_t> philox_engine_inputs;
if (has_random_) {
const auto rand_offset =
4 * (std::ceil(numel / (4.0 * kBlockSize * nBlocks)) + 1);
auto gen = at::cuda::detail::getDefaultCUDAGenerator();
{
// See Note [Acquire lock when using random generators]
std::lock_guard<std::mutex> lock(gen.mutex());
philox_engine_inputs =
at::check_generator<at::CUDAGeneratorImpl>(gen)->philox_engine_inputs(
rand_offset);
}
arguments.push_back(&philox_engine_inputs.first);
arguments.push_back(&philox_engine_inputs.second);
}
// Launches kernel on current stream (device was set by executor)
auto stream = at::cuda::getCurrentCUDAStream();
AT_CUDA_DRIVER_CHECK(nvrtc().cuLaunchKernel(
function_,
nBlocks,
1,
1,
kBlockSize,
1,
1,
0,
stream,
arguments.data(),
nullptr));
// Resets device (see at::DeviceGuard notes above)
at::cuda::set_device(prior_device);
}
FusedKernelCUDA::~FusedKernelCUDA() {
nvrtc().cuModuleUnload(module_);
}
static std::shared_ptr<FusedKernel> createFusionKernel(
int16_t device,
std::string name,
std::string code,
std::vector<TensorDesc> input_desc,
std::vector<TensorDesc> output_desc,
std::vector<PartitionDesc> chunk_desc,
std::vector<PartitionDesc> concat_desc,
bool has_random) {
return std::make_shared<FusedKernelCUDA>(
static_cast<at::DeviceIndex>(device),
std::move(name),
std::move(code),
std::move(input_desc),
std::move(output_desc),
std::move(chunk_desc),
std::move(concat_desc),
has_random);
}
RegisterFusionBackend reg(DeviceType::CUDA, createFusionKernel);
} // namespace cuda
} // namespace fuser
} // namespace jit
} // namespace torch
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "Surface"
#include <stdio.h>
#include "jni.h"
#include <nativehelper/JNIHelp.h>
#include "android_os_Parcel.h"
#include "android/graphics/GraphicBuffer.h"
#include "android/graphics/GraphicsJNI.h"
#include "core_jni_helpers.h"
#include <android_runtime/android_view_Surface.h>
#include <android_runtime/android_graphics_SurfaceTexture.h>
#include <android_runtime/Log.h>
#include <binder/Parcel.h>
#include <gui/Surface.h>
#include <gui/view/Surface.h>
#include <gui/SurfaceControl.h>
#include <gui/GLConsumer.h>
#include <ui/Rect.h>
#include <ui/Region.h>
#include <SkCanvas.h>
#include <SkBitmap.h>
#include <SkImage.h>
#include <SkRegion.h>
#include <utils/misc.h>
#include <utils/Log.h>
#include <nativehelper/ScopedUtfChars.h>
#include <AnimationContext.h>
#include <FrameInfo.h>
#include <RenderNode.h>
#include <renderthread/RenderProxy.h>
// ----------------------------------------------------------------------------
namespace android {
static const char* const OutOfResourcesException =
"android/view/Surface$OutOfResourcesException";
static struct {
jclass clazz;
jfieldID mNativeObject;
jfieldID mLock;
jmethodID ctor;
} gSurfaceClassInfo;
static struct {
jfieldID left;
jfieldID top;
jfieldID right;
jfieldID bottom;
} gRectClassInfo;
// ----------------------------------------------------------------------------
// this is just a pointer we use to pass to inc/decStrong
static const void *sRefBaseOwner;
bool android_view_Surface_isInstanceOf(JNIEnv* env, jobject obj) {
return env->IsInstanceOf(obj, gSurfaceClassInfo.clazz);
}
sp<ANativeWindow> android_view_Surface_getNativeWindow(JNIEnv* env, jobject surfaceObj) {
return android_view_Surface_getSurface(env, surfaceObj);
}
sp<Surface> android_view_Surface_getSurface(JNIEnv* env, jobject surfaceObj) {
sp<Surface> sur;
jobject lock = env->GetObjectField(surfaceObj,
gSurfaceClassInfo.mLock);
if (env->MonitorEnter(lock) == JNI_OK) {
sur = reinterpret_cast<Surface *>(
env->GetLongField(surfaceObj, gSurfaceClassInfo.mNativeObject));
env->MonitorExit(lock);
}
env->DeleteLocalRef(lock);
return sur;
}
jobject android_view_Surface_createFromSurface(JNIEnv* env, const sp<Surface>& surface) {
jobject surfaceObj = env->NewObject(gSurfaceClassInfo.clazz,
gSurfaceClassInfo.ctor, (jlong)surface.get());
if (surfaceObj == NULL) {
if (env->ExceptionCheck()) {
ALOGE("Could not create instance of Surface from IGraphicBufferProducer.");
LOGE_EX(env);
env->ExceptionClear();
}
return NULL;
}
surface->incStrong(&sRefBaseOwner);
return surfaceObj;
}
jobject android_view_Surface_createFromIGraphicBufferProducer(JNIEnv* env,
const sp<IGraphicBufferProducer>& bufferProducer) {
if (bufferProducer == NULL) {
return NULL;
}
sp<Surface> surface(new Surface(bufferProducer, true));
return android_view_Surface_createFromSurface(env, surface);
}
int android_view_Surface_mapPublicFormatToHalFormat(PublicFormat f) {
switch(f) {
case PublicFormat::JPEG:
case PublicFormat::DEPTH_POINT_CLOUD:
return HAL_PIXEL_FORMAT_BLOB;
case PublicFormat::DEPTH16:
return HAL_PIXEL_FORMAT_Y16;
case PublicFormat::RAW_SENSOR:
case PublicFormat::RAW_DEPTH:
return HAL_PIXEL_FORMAT_RAW16;
default:
// Most formats map 1:1
return static_cast<int>(f);
}
}
android_dataspace android_view_Surface_mapPublicFormatToHalDataspace(
PublicFormat f) {
switch(f) {
case PublicFormat::JPEG:
return HAL_DATASPACE_V0_JFIF;
case PublicFormat::DEPTH_POINT_CLOUD:
case PublicFormat::DEPTH16:
case PublicFormat::RAW_DEPTH:
return HAL_DATASPACE_DEPTH;
case PublicFormat::RAW_SENSOR:
case PublicFormat::RAW_PRIVATE:
case PublicFormat::RAW10:
case PublicFormat::RAW12:
return HAL_DATASPACE_ARBITRARY;
case PublicFormat::YUV_420_888:
case PublicFormat::NV21:
case PublicFormat::YV12:
return HAL_DATASPACE_V0_JFIF;
default:
// Most formats map to UNKNOWN
return HAL_DATASPACE_UNKNOWN;
}
}
PublicFormat android_view_Surface_mapHalFormatDataspaceToPublicFormat(
int format, android_dataspace dataSpace) {
switch(format) {
case HAL_PIXEL_FORMAT_RGBA_8888:
case HAL_PIXEL_FORMAT_RGBX_8888:
case HAL_PIXEL_FORMAT_RGBA_FP16:
case HAL_PIXEL_FORMAT_RGBA_1010102:
case HAL_PIXEL_FORMAT_RGB_888:
case HAL_PIXEL_FORMAT_RGB_565:
case HAL_PIXEL_FORMAT_Y8:
case HAL_PIXEL_FORMAT_RAW10:
case HAL_PIXEL_FORMAT_RAW12:
case HAL_PIXEL_FORMAT_YCbCr_420_888:
case HAL_PIXEL_FORMAT_YV12:
// Enums overlap in both name and value
return static_cast<PublicFormat>(format);
case HAL_PIXEL_FORMAT_RAW16:
switch (dataSpace) {
case HAL_DATASPACE_DEPTH:
return PublicFormat::RAW_DEPTH;
default:
return PublicFormat::RAW_SENSOR;
}
case HAL_PIXEL_FORMAT_RAW_OPAQUE:
// Name differs, though value is the same
return PublicFormat::RAW_PRIVATE;
case HAL_PIXEL_FORMAT_YCbCr_422_SP:
// Name differs, though the value is the same
return PublicFormat::NV16;
case HAL_PIXEL_FORMAT_YCrCb_420_SP:
// Name differs, though the value is the same
return PublicFormat::NV21;
case HAL_PIXEL_FORMAT_YCbCr_422_I:
// Name differs, though the value is the same
return PublicFormat::YUY2;
case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
// Name differs, though the value is the same
return PublicFormat::PRIVATE;
case HAL_PIXEL_FORMAT_Y16:
// Dataspace-dependent
switch (dataSpace) {
case HAL_DATASPACE_DEPTH:
return PublicFormat::DEPTH16;
default:
// Assume non-depth Y16 is just Y16.
return PublicFormat::Y16;
}
break;
case HAL_PIXEL_FORMAT_BLOB:
// Dataspace-dependent
switch (dataSpace) {
case HAL_DATASPACE_DEPTH:
return PublicFormat::DEPTH_POINT_CLOUD;
case HAL_DATASPACE_V0_JFIF:
return PublicFormat::JPEG;
default:
// Assume otherwise-marked blobs are also JPEG
return PublicFormat::JPEG;
}
break;
case HAL_PIXEL_FORMAT_BGRA_8888:
// Not defined in public API
return PublicFormat::UNKNOWN;
default:
return PublicFormat::UNKNOWN;
}
}
// ----------------------------------------------------------------------------
static inline bool isSurfaceValid(const sp<Surface>& sur) {
return Surface::isValid(sur);
}
// ----------------------------------------------------------------------------
static jlong nativeCreateFromSurfaceTexture(JNIEnv* env, jclass clazz,
jobject surfaceTextureObj) {
sp<IGraphicBufferProducer> producer(SurfaceTexture_getProducer(env, surfaceTextureObj));
if (producer == NULL) {
jniThrowException(env, "java/lang/IllegalArgumentException",
"SurfaceTexture has already been released");
return 0;
}
sp<Surface> surface(new Surface(producer, true));
if (surface == NULL) {
jniThrowException(env, OutOfResourcesException, NULL);
return 0;
}
surface->incStrong(&sRefBaseOwner);
return jlong(surface.get());
}
static void nativeRelease(JNIEnv* env, jclass clazz, jlong nativeObject) {
sp<Surface> sur(reinterpret_cast<Surface *>(nativeObject));
sur->decStrong(&sRefBaseOwner);
}
static jboolean nativeIsValid(JNIEnv* env, jclass clazz, jlong nativeObject) {
sp<Surface> sur(reinterpret_cast<Surface *>(nativeObject));
return isSurfaceValid(sur) ? JNI_TRUE : JNI_FALSE;
}
static jboolean nativeIsConsumerRunningBehind(JNIEnv* env, jclass clazz, jlong nativeObject) {
sp<Surface> sur(reinterpret_cast<Surface *>(nativeObject));
if (!isSurfaceValid(sur)) {
doThrowIAE(env);
return JNI_FALSE;
}
int value = 0;
ANativeWindow* anw = static_cast<ANativeWindow*>(sur.get());
anw->query(anw, NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &value);
return value;
}
static inline SkColorType convertPixelFormat(PixelFormat format) {
/* note: if PIXEL_FORMAT_RGBX_8888 means that all alpha bytes are 0xFF, then
we can map to kN32_SkColorType, and optionally call
bitmap.setAlphaType(kOpaque_SkAlphaType) on the resulting SkBitmap
(as an accelerator)
*/
switch (format) {
case PIXEL_FORMAT_RGBX_8888: return kN32_SkColorType;
case PIXEL_FORMAT_RGBA_8888: return kN32_SkColorType;
case PIXEL_FORMAT_RGBA_FP16: return kRGBA_F16_SkColorType;
case PIXEL_FORMAT_RGB_565: return kRGB_565_SkColorType;
default: return kUnknown_SkColorType;
}
}
static jlong nativeLockCanvas(JNIEnv* env, jclass clazz,
jlong nativeObject, jobject canvasObj, jobject dirtyRectObj) {
sp<Surface> surface(reinterpret_cast<Surface *>(nativeObject));
if (!isSurfaceValid(surface)) {
doThrowIAE(env);
return 0;
}
Rect dirtyRect(Rect::EMPTY_RECT);
Rect* dirtyRectPtr = NULL;
if (dirtyRectObj) {
dirtyRect.left = env->GetIntField(dirtyRectObj, gRectClassInfo.left);
dirtyRect.top = env->GetIntField(dirtyRectObj, gRectClassInfo.top);
dirtyRect.right = env->GetIntField(dirtyRectObj, gRectClassInfo.right);
dirtyRect.bottom = env->GetIntField(dirtyRectObj, gRectClassInfo.bottom);
dirtyRectPtr = &dirtyRect;
}
ANativeWindow_Buffer outBuffer;
status_t err = surface->lock(&outBuffer, dirtyRectPtr);
if (err < 0) {
const char* const exception = (err == NO_MEMORY) ?
OutOfResourcesException :
"java/lang/IllegalArgumentException";
jniThrowException(env, exception, NULL);
return 0;
}
SkImageInfo info = SkImageInfo::Make(outBuffer.width, outBuffer.height,
convertPixelFormat(outBuffer.format),
outBuffer.format == PIXEL_FORMAT_RGBX_8888
? kOpaque_SkAlphaType : kPremul_SkAlphaType,
GraphicsJNI::defaultColorSpace());
SkBitmap bitmap;
ssize_t bpr = outBuffer.stride * bytesPerPixel(outBuffer.format);
bitmap.setInfo(info, bpr);
if (outBuffer.width > 0 && outBuffer.height > 0) {
bitmap.setPixels(outBuffer.bits);
} else {
// be safe with an empty bitmap.
bitmap.setPixels(NULL);
}
Canvas* nativeCanvas = GraphicsJNI::getNativeCanvas(env, canvasObj);
nativeCanvas->setBitmap(bitmap);
if (dirtyRectPtr) {
nativeCanvas->clipRect(dirtyRect.left, dirtyRect.top,
dirtyRect.right, dirtyRect.bottom, SkClipOp::kIntersect);
}
if (dirtyRectObj) {
env->SetIntField(dirtyRectObj, gRectClassInfo.left, dirtyRect.left);
env->SetIntField(dirtyRectObj, gRectClassInfo.top, dirtyRect.top);
env->SetIntField(dirtyRectObj, gRectClassInfo.right, dirtyRect.right);
env->SetIntField(dirtyRectObj, gRectClassInfo.bottom, dirtyRect.bottom);
}
// Create another reference to the surface and return it. This reference
// should be passed to nativeUnlockCanvasAndPost in place of mNativeObject,
// because the latter could be replaced while the surface is locked.
sp<Surface> lockedSurface(surface);
lockedSurface->incStrong(&sRefBaseOwner);
return (jlong) lockedSurface.get();
}
static void nativeUnlockCanvasAndPost(JNIEnv* env, jclass clazz,
jlong nativeObject, jobject canvasObj) {
sp<Surface> surface(reinterpret_cast<Surface *>(nativeObject));
if (!isSurfaceValid(surface)) {
return;
}
// detach the canvas from the surface
Canvas* nativeCanvas = GraphicsJNI::getNativeCanvas(env, canvasObj);
nativeCanvas->setBitmap(SkBitmap());
// unlock surface
status_t err = surface->unlockAndPost();
if (err < 0) {
doThrowIAE(env);
}
}
static void nativeAllocateBuffers(JNIEnv* /* env */ , jclass /* clazz */,
jlong nativeObject) {
sp<Surface> surface(reinterpret_cast<Surface *>(nativeObject));
if (!isSurfaceValid(surface)) {
return;
}
surface->allocateBuffers();
}
// ----------------------------------------------------------------------------
static jlong nativeCreateFromSurfaceControl(JNIEnv* env, jclass clazz,
jlong surfaceControlNativeObj) {
sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));
sp<Surface> surface(ctrl->createSurface());
if (surface != NULL) {
surface->incStrong(&sRefBaseOwner);
}
return reinterpret_cast<jlong>(surface.get());
}
static jlong nativeGetFromSurfaceControl(JNIEnv* env, jclass clazz,
jlong surfaceControlNativeObj) {
/*
* This is used by the WindowManagerService just after constructing
* a Surface and is necessary for returning the Surface reference to
* the caller. At this point, we should only have a SurfaceControl.
*/
sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));
sp<Surface> surface(ctrl->getSurface());
if (surface != NULL) {
surface->incStrong(&sRefBaseOwner);
}
return reinterpret_cast<jlong>(surface.get());
}
static jlong nativeReadFromParcel(JNIEnv* env, jclass clazz,
jlong nativeObject, jobject parcelObj) {
Parcel* parcel = parcelForJavaObject(env, parcelObj);
if (parcel == NULL) {
doThrowNPE(env);
return 0;
}
android::view::Surface surfaceShim;
// Calling code in Surface.java has already read the name of the Surface
// from the Parcel
surfaceShim.readFromParcel(parcel, /*nameAlreadyRead*/true);
sp<Surface> self(reinterpret_cast<Surface *>(nativeObject));
// update the Surface only if the underlying IGraphicBufferProducer
// has changed.
if (self != nullptr
&& (IInterface::asBinder(self->getIGraphicBufferProducer()) ==
IInterface::asBinder(surfaceShim.graphicBufferProducer))) {
// same IGraphicBufferProducer, return ourselves
return jlong(self.get());
}
sp<Surface> sur;
if (surfaceShim.graphicBufferProducer != nullptr) {
// we have a new IGraphicBufferProducer, create a new Surface for it
sur = new Surface(surfaceShim.graphicBufferProducer, true);
// and keep a reference before passing to java
sur->incStrong(&sRefBaseOwner);
}
if (self != NULL) {
// and loose the java reference to ourselves
self->decStrong(&sRefBaseOwner);
}
return jlong(sur.get());
}
static void nativeWriteToParcel(JNIEnv* env, jclass clazz,
jlong nativeObject, jobject parcelObj) {
Parcel* parcel = parcelForJavaObject(env, parcelObj);
if (parcel == NULL) {
doThrowNPE(env);
return;
}
sp<Surface> self(reinterpret_cast<Surface *>(nativeObject));
android::view::Surface surfaceShim;
if (self != nullptr) {
surfaceShim.graphicBufferProducer = self->getIGraphicBufferProducer();
}
// Calling code in Surface.java has already written the name of the Surface
// to the Parcel
surfaceShim.writeToParcel(parcel, /*nameAlreadyWritten*/true);
}
static jint nativeGetWidth(JNIEnv* env, jclass clazz, jlong nativeObject) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
ANativeWindow* anw = static_cast<ANativeWindow*>(surface);
int value = 0;
anw->query(anw, NATIVE_WINDOW_WIDTH, &value);
return value;
}
static jint nativeGetHeight(JNIEnv* env, jclass clazz, jlong nativeObject) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
ANativeWindow* anw = static_cast<ANativeWindow*>(surface);
int value = 0;
anw->query(anw, NATIVE_WINDOW_HEIGHT, &value);
return value;
}
static jlong nativeGetNextFrameNumber(JNIEnv *env, jclass clazz, jlong nativeObject) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
return surface->getNextFrameNumber();
}
static jint nativeSetScalingMode(JNIEnv *env, jclass clazz, jlong nativeObject, jint scalingMode) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
return surface->setScalingMode(scalingMode);
}
static jint nativeForceScopedDisconnect(JNIEnv *env, jclass clazz, jlong nativeObject) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
return surface->disconnect(-1, IGraphicBufferProducer::DisconnectMode::AllLocal);
}
static jint nativeAttachAndQueueBuffer(JNIEnv *env, jclass clazz, jlong nativeObject,
jobject graphicBuffer) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
sp<GraphicBuffer> bp = graphicBufferForJavaObject(env, graphicBuffer);
int err = Surface::attachAndQueueBuffer(surface, bp);
return err;
}
static jint nativeSetSharedBufferModeEnabled(JNIEnv* env, jclass clazz, jlong nativeObject,
jboolean enabled) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
ANativeWindow* anw = static_cast<ANativeWindow*>(surface);
return anw->perform(surface, NATIVE_WINDOW_SET_SHARED_BUFFER_MODE, int(enabled));
}
static jint nativeSetAutoRefreshEnabled(JNIEnv* env, jclass clazz, jlong nativeObject,
jboolean enabled) {
Surface* surface = reinterpret_cast<Surface*>(nativeObject);
ANativeWindow* anw = static_cast<ANativeWindow*>(surface);
return anw->perform(surface, NATIVE_WINDOW_SET_AUTO_REFRESH, int(enabled));
}
namespace uirenderer {
using namespace android::uirenderer::renderthread;
class ContextFactory : public IContextFactory {
public:
virtual AnimationContext* createAnimationContext(renderthread::TimeLord& clock) {
return new AnimationContext(clock);
}
};
static jlong create(JNIEnv* env, jclass clazz, jlong rootNodePtr, jlong surfacePtr,
jboolean isWideColorGamut) {
RenderNode* rootNode = reinterpret_cast<RenderNode*>(rootNodePtr);
sp<Surface> surface(reinterpret_cast<Surface*>(surfacePtr));
ContextFactory factory;
RenderProxy* proxy = new RenderProxy(false, rootNode, &factory);
proxy->loadSystemProperties();
if (isWideColorGamut) {
proxy->setWideGamut(true);
}
proxy->setSwapBehavior(SwapBehavior::kSwap_discardBuffer);
proxy->initialize(surface);
// Shadows can't be used via this interface, so just set the light source
// to all 0s.
proxy->setup(0, 0, 0);
proxy->setLightCenter((Vector3){0, 0, 0});
return (jlong) proxy;
}
static void setSurface(JNIEnv* env, jclass clazz, jlong rendererPtr, jlong surfacePtr) {
RenderProxy* proxy = reinterpret_cast<RenderProxy*>(rendererPtr);
sp<Surface> surface(reinterpret_cast<Surface*>(surfacePtr));
proxy->updateSurface(surface);
}
static void draw(JNIEnv* env, jclass clazz, jlong rendererPtr) {
RenderProxy* proxy = reinterpret_cast<RenderProxy*>(rendererPtr);
nsecs_t vsync = systemTime(CLOCK_MONOTONIC);
UiFrameInfoBuilder(proxy->frameInfo())
.setVsync(vsync, vsync)
.addFlag(FrameInfoFlags::SurfaceCanvas);
proxy->syncAndDrawFrame();
}
static void destroy(JNIEnv* env, jclass clazz, jlong rendererPtr) {
RenderProxy* proxy = reinterpret_cast<RenderProxy*>(rendererPtr);
delete proxy;
}
} // uirenderer
// ----------------------------------------------------------------------------
namespace hwui = android::uirenderer;
static const JNINativeMethod gSurfaceMethods[] = {
{"nativeCreateFromSurfaceTexture", "(Landroid/graphics/SurfaceTexture;)J",
(void*)nativeCreateFromSurfaceTexture },
{"nativeRelease", "(J)V",
(void*)nativeRelease },
{"nativeIsValid", "(J)Z",
(void*)nativeIsValid },
{"nativeIsConsumerRunningBehind", "(J)Z",
(void*)nativeIsConsumerRunningBehind },
{"nativeLockCanvas", "(JLandroid/graphics/Canvas;Landroid/graphics/Rect;)J",
(void*)nativeLockCanvas },
{"nativeUnlockCanvasAndPost", "(JLandroid/graphics/Canvas;)V",
(void*)nativeUnlockCanvasAndPost },
{"nativeAllocateBuffers", "(J)V",
(void*)nativeAllocateBuffers },
{"nativeCreateFromSurfaceControl", "(J)J",
(void*)nativeCreateFromSurfaceControl },
{"nativeGetFromSurfaceControl", "(J)J",
(void*)nativeGetFromSurfaceControl },
{"nativeReadFromParcel", "(JLandroid/os/Parcel;)J",
(void*)nativeReadFromParcel },
{"nativeWriteToParcel", "(JLandroid/os/Parcel;)V",
(void*)nativeWriteToParcel },
{"nativeGetWidth", "(J)I", (void*)nativeGetWidth },
{"nativeGetHeight", "(J)I", (void*)nativeGetHeight },
{"nativeGetNextFrameNumber", "(J)J", (void*)nativeGetNextFrameNumber },
{"nativeSetScalingMode", "(JI)I", (void*)nativeSetScalingMode },
{"nativeForceScopedDisconnect", "(J)I", (void*)nativeForceScopedDisconnect},
{"nativeAttachAndQueueBuffer", "(JLandroid/graphics/GraphicBuffer;)I", (void*)nativeAttachAndQueueBuffer},
{"nativeSetSharedBufferModeEnabled", "(JZ)I", (void*)nativeSetSharedBufferModeEnabled},
{"nativeSetAutoRefreshEnabled", "(JZ)I", (void*)nativeSetAutoRefreshEnabled},
// HWUI context
{"nHwuiCreate", "(JJZ)J", (void*) hwui::create },
{"nHwuiSetSurface", "(JJ)V", (void*) hwui::setSurface },
{"nHwuiDraw", "(J)V", (void*) hwui::draw },
{"nHwuiDestroy", "(J)V", (void*) hwui::destroy },
};
int register_android_view_Surface(JNIEnv* env)
{
int err = RegisterMethodsOrDie(env, "android/view/Surface",
gSurfaceMethods, NELEM(gSurfaceMethods));
jclass clazz = FindClassOrDie(env, "android/view/Surface");
gSurfaceClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
gSurfaceClassInfo.mNativeObject = GetFieldIDOrDie(env,
gSurfaceClassInfo.clazz, "mNativeObject", "J");
gSurfaceClassInfo.mLock = GetFieldIDOrDie(env,
gSurfaceClassInfo.clazz, "mLock", "Ljava/lang/Object;");
gSurfaceClassInfo.ctor = GetMethodIDOrDie(env, gSurfaceClassInfo.clazz, "<init>", "(J)V");
clazz = FindClassOrDie(env, "android/graphics/Rect");
gRectClassInfo.left = GetFieldIDOrDie(env, clazz, "left", "I");
gRectClassInfo.top = GetFieldIDOrDie(env, clazz, "top", "I");
gRectClassInfo.right = GetFieldIDOrDie(env, clazz, "right", "I");
gRectClassInfo.bottom = GetFieldIDOrDie(env, clazz, "bottom", "I");
return err;
}
};
|
//---
//
// License: MIT
//
// Description: NITF Info object.
//
//---
// $Id$
#include <ossim/support_data/ossimNitfInfo.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimIoStream.h>
#include <ossim/base/ossimStreamFactoryRegistry.h>
#include <ostream>
#include <sstream>
#include <memory>
ossimNitfInfo::ossimNitfInfo()
: m_nitfFile(0)
{
}
ossimNitfInfo::~ossimNitfInfo()
{
m_nitfFile.reset();
}
bool ossimNitfInfo::open(const ossimFilename& file)
{
bool result = false;
std::string connectionString = file.c_str();
std::shared_ptr<ossim::istream> str = ossim::StreamFactoryRegistry::instance()->
createIstream( file.c_str(), std::ios_base::in|std::ios_base::binary);
if ( str )
{
result = open(str, connectionString);
}
return result;
}
bool ossimNitfInfo::open(std::shared_ptr<ossim::istream>& str,
const std::string& connectionString)
{
bool result = false;
if ( str )
{
m_nitfFile = std::make_shared<ossimNitfFile>();
result = m_nitfFile->parseStream(ossimFilename(connectionString), *str);
}
return result;
}
std::ostream& ossimNitfInfo::print(std::ostream& out) const
{
if ( m_nitfFile )
{
std::string prefix;
m_nitfFile->print(out, prefix, getProcessOverviewFlag());
}
return out;
}
bool ossimNitfInfo::getKeywordlist(ossimKeywordlist& kwl,
ossim_uint32 entryIndex)const
{
// Do a print to a memory stream.
std::ostringstream out;
m_nitfFile->print( out, entryIndex );
std::istringstream in( out.str() );
// Give the result to the keyword list.
return kwl.parseStream( in );
}
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2009
*
* Last modified:
* $Date: 2010-10-07 20:52:01 +1100 (Thu, 07 Oct 2010) $ by $Author: schulte $
* $Revision: 11473 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include "examples/scowl.hpp"
using namespace Gecode;
// Grid data
namespace {
// Grid data
extern const int* grids[];
// Number of grids
extern const unsigned int n_grids;
}
/**
* \brief %Example: %Crossword puzzle
*
* Fill crossword grids with words, that is construct a crossword
* puzzle. For a recent paper on this classical problem, see:
* Crossword Puzzles as a Constraint Problem, Anbulagan and Adi Botea,
* CP 2008, pages 550-554, Springer Verlag.
*
* Note that "Modeling and Programming with Gecode" uses this example
* as a case study.
*
* \ingroup Example
*/
class Crossword : public Script {
protected:
/// Width of crossword grid
const int w;
/// Height of crossword grid
const int h;
/// Letters for grid
IntVarArray letters;
public:
/// Branching to use for model
enum {
BRANCH_WORDS, ///< Branch on the words
BRANCH_LETTERS ///< Branch on the letters
};
/// Actual model
Crossword(const SizeOptions& opt)
: w(grids[opt.size()][0]), h(grids[opt.size()][1]),
letters(*this,w*h,'a','z') {
// Pointer into the grid specification (width and height already skipped)
const int* g = &grids[opt.size()][2];
// Matrix for letters
Matrix<IntVarArray> ml(letters, w, h);
// Set black fields to 0
{
IntVar z(*this,0,0);
for (int n = *g++; n--; ) {
int x=*g++, y=*g++;
ml(x,y)=z;
}
}
// Array of all words
IntVarArgs allwords;
// While words of length w_l to process
while (int w_l=*g++) {
// Number of words of that length in the dictionary
int n_w = dict.words(w_l);
// Number of words of that length in the puzzle
int n=*g++;
if (n > n_w) {
fail();
} else {
// Array of all words of length w_l
IntVarArgs words(*this,n,0,n_w-1);
allwords << words;
// All words of same length must be different
distinct(*this, words, opt.icl());
for (int d=0; d<w_l; d++) {
// Array that maps words to a letter at a certain position (shared among all element constraints)
IntSharedArray w2l(n_w);
// Initialize word to letter map
for (int i=n_w; i--; )
w2l[i] = dict.word(w_l,i)[d];
// Link word to letter variable
for (int i=0; i<n; i++) {
// Get (x,y) coordinate where word begins
int x=g[3*i+0], y=g[3*i+1];
// Whether word is horizontal
bool h=(g[3*i+2] == 0);
// Constrain the letters to the words' letters
element(*this, w2l, words[i], h ? ml(x+d,y) : ml(x,y+d));
}
}
// Skip word coordinates
g += 3*n;
}
}
switch (opt.branching()) {
case BRANCH_WORDS:
// Branch by assigning words
branch(*this, allwords, INT_VAR_SIZE_AFC_MIN, INT_VAL_SPLIT_MIN);
break;
case BRANCH_LETTERS:
// Branch by assigning letters
branch(*this, letters, INT_VAR_SIZE_AFC_MIN, INT_VAL_MIN);
break;
}
}
/// Constructor for cloning \a s
Crossword(bool share, Crossword& s)
: Script(share,s), w(s.w), h(s.h) {
letters.update(*this, share, s.letters);
}
/// Copy during cloning
virtual Space*
copy(bool share) {
return new Crossword(share,*this);
}
/// Print solution
virtual void
print(std::ostream& os) const {
// Matrix for letters
Matrix<IntVarArray> ml(letters, w, h);
for (int i=0; i<h; i++) {
os << '\t';
for (int j=0; j<w; j++)
if (ml(j,i).assigned())
if (ml(j,i).val() == 0)
os << '*';
else
os << static_cast<char>(ml(j,i).val());
else
os << '?';
os << std::endl;
}
os << std::endl << std::endl;
}
};
/** \brief Main-function
* \relates WordSquare
*/
int
main(int argc, char* argv[]) {
FileSizeOptions opt("Crossword");
opt.size(10);
opt.icl(ICL_VAL);
opt.branching(Crossword::BRANCH_WORDS);
opt.branching(Crossword::BRANCH_WORDS, "words");
opt.branching(Crossword::BRANCH_LETTERS, "letters");
opt.parse(argc,argv);
dict.init(opt.file());
if (opt.size() >= n_grids) {
std::cerr << "Error: size must be between 0 and "
<< n_grids-1 << std::endl;
return 1;
}
Script::run<Crossword,DFS,SizeOptions>(opt);
return 0;
}
namespace {
/*
* The Grid data has been provided by Peter Van Beek, to
* quote the original README.txt:
*
* The files in this directory contain templates for crossword
* puzzles. Each is a two-dimensional array. A _ indicates
* that the associated square in the crossword template is
* blank, and a * indicates that it is a black square that
* does not need to have a letter inserted.
*
* The crossword puzzles templates came from the following
* sources:
*
* 15.01, ..., 15.10
* 19.01, ..., 19.10
* 21.01, ..., 21.10
* 23.01, ..., 23.10
*
* Herald Tribune Crosswords, Spring, 1999
*
* 05.01, ..., 05.10
*
* All legal 5 x 5 puzzles.
*
* puzzle01, ..., puzzle19
*
* Ginsberg, M.L., "Dynamic Backtracking,"
* Journal of Artificial Intelligence Researc (JAIR)
* Volume 1, pages 25-46, 1993.
*
* puzzle20, ..., puzzle22
*
* Ginsberg, M.L. et al., "Search Lessons Learned
* from Crossword Puzzles," AAAI-90, pages 210-215.
*
*/
/*
* Name: 05.01, 5 x 5
* (_ _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ _)
*/
const int g0[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
0,
// Black field coordinates
// Length and number of words of that length
5, 10,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,3,0, 0,4,0, 1,0,1, 2,0,1, 3,0,1, 4,0,1,
// End marker
0
};
/*
* Name: 05.02, 5 x 5
* (_ _ _ _ *)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (* _ _ _ _)
*/
const int g1[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
2,
// Black field coordinates
0,4, 4,0,
// Length and number of words of that length
5, 6,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,2,0, 0,3,0, 1,0,1, 2,0,1, 3,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 1,4,0, 4,1,1,
// End marker
0
};
/*
* Name: 05.03, 5 x 5
* (_ _ _ _ *)
* (_ _ _ _ *)
* (_ _ _ _ _)
* (* _ _ _ _)
* (* _ _ _ _)
*/
const int g2[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
4,
// Black field coordinates
0,3, 0,4, 4,0, 4,1,
// Length and number of words of that length
5, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 1,0,1, 2,0,1, 3,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 1,3,0, 1,4,0,
// Length and number of words of that length
3, 2,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 4,2,1,
// End marker
0
};
/*
* Name: 05.04, 5 x 5
* (_ _ _ * *)
* (_ _ _ _ *)
* (_ _ _ _ _)
* (* _ _ _ _)
* (* * _ _ _)
*/
const int g3[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
6,
// Black field coordinates
0,3, 0,4, 1,4, 3,0, 4,0, 4,1,
// Length and number of words of that length
5, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 1,0,1, 1,3,0, 3,1,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 2,4,0, 4,2,1,
// End marker
0
};
/*
* Name: 05.05, 5 x 5
* (_ _ _ * *)
* (_ _ _ * *)
* (_ _ _ _ _)
* (* * _ _ _)
* (* * _ _ _)
*/
const int g4[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
8,
// Black field coordinates
0,3, 0,4, 1,3, 1,4, 3,0, 3,1, 4,0, 4,1,
// Length and number of words of that length
5, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 1,0,1, 2,3,0, 2,4,0, 3,2,1, 4,2,1,
// End marker
0
};
/*
* Name: 05.06, 5 x 5
* (* _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ *)
*/
const int g5[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
2,
// Black field coordinates
0,0, 4,4,
// Length and number of words of that length
5, 6,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,2,0, 0,3,0, 1,0,1, 2,0,1, 3,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,1, 0,4,0, 1,0,0, 4,0,1,
// End marker
0
};
/*
* Name: 05.07, 5 x 5
* (* _ _ _ _)
* (* _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ *)
* (_ _ _ _ *)
*/
const int g6[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
4,
// Black field coordinates
0,0, 0,1, 4,3, 4,4,
// Length and number of words of that length
5, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 1,0,1, 2,0,1, 3,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,4,0, 1,0,0, 1,1,0,
// Length and number of words of that length
3, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,1, 4,0,1,
// End marker
0
};
/*
* Name: 05.08, 5 x 5
* (* _ _ _ *)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ _)
* (* _ _ _ *)
*/
const int g7[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
4,
// Black field coordinates
0,0, 0,4, 4,0, 4,4,
// Length and number of words of that length
5, 6,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,2,0, 0,3,0, 1,0,1, 2,0,1, 3,0,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,1, 1,0,0, 1,4,0, 4,1,1,
// End marker
0
};
/*
* Name: 05.09, 5 x 5
* (* * _ _ _)
* (* _ _ _ _)
* (_ _ _ _ _)
* (_ _ _ _ *)
* (_ _ _ * *)
*/
const int g8[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
6,
// Black field coordinates
0,0, 0,1, 1,0, 3,4, 4,3, 4,4,
// Length and number of words of that length
5, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 1,1,0, 1,1,1, 3,0,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,1, 0,4,0, 2,0,0, 4,0,1,
// End marker
0
};
/*
* Name: 05.10, 5 x 5
* (* * _ _ _)
* (* * _ _ _)
* (_ _ _ _ _)
* (_ _ _ * *)
* (_ _ _ * *)
*/
const int g9[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
8,
// Black field coordinates
0,0, 0,1, 1,0, 1,1, 3,3, 3,4, 4,3, 4,4,
// Length and number of words of that length
5, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,2,1, 0,3,0, 0,4,0, 1,2,1, 2,0,0, 2,1,0, 3,0,1, 4,0,1,
// End marker
0
};
/*
* Name: 15.01, 15 x 15
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * * _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ * * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g10[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
36,
// Black field coordinates
0,4, 0,10, 1,4, 1,10, 2,4, 3,6, 3,7, 4,0, 4,1, 4,8, 4,12, 4,13, 4,14, 5,5, 5,9, 6,4, 6,11, 7,3, 7,11, 8,3, 8,10, 9,5, 9,9, 10,0, 10,1, 10,2, 10,6, 10,13, 10,14, 11,7, 11,8, 12,10, 13,4, 13,10, 14,4, 14,10,
// Length and number of words of that length
10, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,5,1, 5,12,0, 12,0,1,
// Length and number of words of that length
7, 6,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 3,8,1, 4,7,0, 7,4,1, 8,11,0, 11,0,1,
// Length and number of words of that length
6, 12,
// Coordinates where words start and direction (0 = horizontal)
0,11,0, 2,10,0, 3,0,1, 4,2,1, 4,6,0, 5,8,0, 6,5,1, 7,4,0, 8,4,1, 9,3,0, 10,7,1, 11,9,1,
// Length and number of words of that length
5, 16,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,5,1, 0,9,0, 1,5,1, 5,0,0, 5,0,1, 5,1,0, 5,10,1, 5,13,0, 5,14,0, 9,0,1, 9,10,1, 10,5,0, 10,9,0, 13,5,1, 14,5,1,
// Length and number of words of that length
4, 24,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,8,0, 0,11,1, 0,12,0, 0,13,0, 0,14,0, 1,0,1, 1,11,1, 2,0,1, 6,0,1, 8,11,1, 11,0,0, 11,1,0, 11,2,0, 11,6,0, 11,13,0, 11,14,0, 12,11,1, 13,0,1, 13,11,1, 14,0,1, 14,11,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,7,0, 3,4,0, 4,9,1, 5,6,1, 6,5,0, 6,9,0, 6,12,1, 7,0,1, 7,12,1, 8,0,1, 9,6,1, 9,10,0, 10,3,1, 12,7,0, 12,8,0,
// End marker
0
};
/*
* Name: 15.02, 15 x 15
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ * * *)
* (* * * _ _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ _ * * *)
* (* * * _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
*/
const int g11[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
34,
// Black field coordinates
0,5, 0,10, 1,5, 1,10, 2,5, 2,10, 3,4, 3,9, 4,3, 4,8, 4,13, 4,14, 5,0, 5,7, 6,6, 6,10, 7,5, 7,9, 8,4, 8,8, 9,7, 9,14, 10,0, 10,1, 10,6, 10,11, 11,5, 11,10, 12,4, 12,9, 13,4, 13,9, 14,4, 14,9,
// Length and number of words of that length
15, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,12,0,
// Length and number of words of that length
10, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,11,0, 5,3,0, 5,13,0,
// Length and number of words of that length
7, 2,
// Coordinates where words start and direction (0 = horizontal)
5,8,1, 9,0,1,
// Length and number of words of that length
6, 6,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 5,1,1, 6,0,1, 8,9,1, 9,8,0, 9,8,1,
// Length and number of words of that length
5, 14,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,7,0, 1,0,1, 2,0,1, 3,10,1, 7,0,1, 7,10,1, 10,7,0, 10,14,0, 11,0,1, 12,10,1, 13,10,1, 14,10,1,
// Length and number of words of that length
4, 36,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,6,1, 0,8,0, 0,11,1, 0,13,0, 0,14,0, 1,6,1, 1,11,1, 2,6,1, 2,11,1, 3,0,1, 3,5,0, 3,5,1, 4,4,0, 4,4,1, 4,9,1, 5,14,0, 6,0,0, 6,11,1, 7,10,0, 8,0,1, 8,9,0, 10,2,1, 10,7,1, 11,0,0, 11,1,0, 11,6,0, 11,6,1, 11,11,0, 11,11,1, 12,0,1, 12,5,1, 13,0,1, 13,5,1, 14,0,1, 14,5,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,9,0, 3,10,0, 4,0,1, 4,9,0, 5,8,0, 6,7,0, 6,7,1, 7,6,0, 7,6,1, 8,5,0, 8,5,1, 9,4,0, 10,12,1, 12,5,0, 12,10,0,
// End marker
0
};
/*
* Name: 15.03, 15 x 15
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g12[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
36,
// Black field coordinates
0,4, 0,10, 1,4, 1,10, 2,4, 2,10, 3,8, 4,0, 4,1, 4,2, 4,7, 4,12, 4,13, 4,14, 5,6, 6,5, 6,11, 7,4, 7,10, 8,3, 8,9, 9,8, 10,0, 10,1, 10,2, 10,7, 10,12, 10,13, 10,14, 11,6, 12,4, 12,10, 13,4, 13,10, 14,4, 14,10,
// Length and number of words of that length
8, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 3,0,1, 5,7,1, 7,5,0, 7,11,0, 9,0,1, 11,7,1,
// Length and number of words of that length
6, 8,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 3,9,1, 5,0,1, 9,3,0, 9,9,0, 9,9,1, 11,0,1,
// Length and number of words of that length
5, 22,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,6,0, 1,5,1, 2,5,1, 4,8,0, 5,0,0, 5,1,0, 5,2,0, 5,7,0, 5,12,0, 5,13,0, 5,14,0, 6,0,1, 6,6,0, 6,6,1, 7,5,1, 8,4,1, 8,10,1, 10,8,0, 12,5,1, 13,5,1, 14,5,1,
// Length and number of words of that length
4, 36,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,7,0, 0,11,1, 0,12,0, 0,13,0, 0,14,0, 1,0,1, 1,11,1, 2,0,1, 2,11,1, 3,4,0, 3,10,0, 4,3,1, 4,8,1, 7,0,1, 7,11,1, 8,4,0, 8,10,0, 10,3,1, 10,8,1, 11,0,0, 11,1,0, 11,2,0, 11,7,0, 11,12,0, 11,13,0, 11,14,0, 12,0,1, 12,11,1, 13,0,1, 13,11,1, 14,0,1, 14,11,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 6,12,1, 8,0,1, 12,6,0,
// End marker
0
};
/*
* Name: 15.04, 15 x 15
* (_ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (* * * _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (* * * _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _)
*/
const int g13[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
32,
// Black field coordinates
0,4, 0,10, 1,4, 1,10, 2,4, 2,10, 3,0, 3,5, 3,11, 4,6, 5,3, 5,9, 6,4, 6,8, 6,13, 6,14, 8,0, 8,1, 8,6, 8,10, 9,5, 9,11, 10,8, 11,3, 11,9, 11,14, 12,4, 12,10, 13,4, 13,10, 14,4, 14,10,
// Length and number of words of that length
15, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,7,0, 0,12,0, 7,0,1,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 4,7,1, 7,13,0, 10,0,1,
// Length and number of words of that length
6, 8,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,13,0, 0,14,0, 4,0,1, 9,0,0, 9,1,0, 9,6,0, 10,9,1,
// Length and number of words of that length
5, 22,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,5,1, 0,9,0, 1,5,1, 2,5,1, 3,6,1, 3,10,0, 4,5,0, 4,11,0, 5,4,1, 5,10,1, 6,3,0, 6,9,0, 7,4,0, 9,0,1, 9,6,1, 10,5,0, 10,11,0, 11,4,1, 12,5,1, 13,5,1, 14,5,1,
// Length and number of words of that length
4, 22,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,6,0, 0,11,1, 1,0,1, 1,11,1, 2,0,1, 2,11,1, 3,1,1, 4,0,0, 6,0,1, 6,9,1, 7,14,0, 8,2,1, 8,11,1, 11,8,0, 11,10,1, 12,0,1, 12,11,1, 13,0,1, 13,11,1, 14,0,1, 14,11,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,5,0, 0,11,0, 3,4,0, 3,12,1, 5,0,1, 5,6,0, 6,5,1, 7,8,0, 8,7,1, 9,10,0, 9,12,1, 11,0,1, 12,3,0, 12,9,0, 12,14,0,
// End marker
0
};
/*
* Name: 15.05, 15 x 15
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (* * * * _ _ _ * * * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ * * * *)
* (_ _ _ _ _ * * _ _ _ _ _ _ _ *)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (* _ _ _ _ _ _ _ * * _ _ _ _ _)
* (* * * * _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * * * _ _ _ * * * *)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
*/
const int g14[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
44,
// Black field coordinates
0,4, 0,8, 0,9, 1,4, 1,9, 2,4, 2,9, 3,4, 3,9, 4,3, 4,11, 4,12, 4,13, 4,14, 5,0, 5,1, 5,6, 5,10, 6,5, 6,6, 6,10, 7,4, 7,10, 8,4, 8,8, 8,9, 9,4, 9,8, 9,13, 9,14, 10,0, 10,1, 10,2, 10,3, 10,11, 11,5, 11,10, 12,5, 12,10, 13,5, 13,10, 14,5, 14,6, 14,10,
// Length and number of words of that length
15, 1,
// Coordinates where words start and direction (0 = horizontal)
0,7,0,
// Length and number of words of that length
10, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 5,12,0,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
1,8,0, 4,4,1, 7,6,0, 10,4,1,
// Length and number of words of that length
6, 2,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 9,9,0,
// Length and number of words of that length
5, 21,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,6,0, 0,10,0, 0,10,1, 1,10,1, 2,10,1, 3,10,1, 5,3,0, 5,11,0, 6,0,1, 7,5,1, 8,10,1, 10,4,0, 10,8,0, 10,13,0, 10,14,0, 11,0,1, 12,0,1, 13,0,1, 14,0,1,
// Length and number of words of that length
4, 38,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,3,0, 0,11,0, 0,12,0, 0,13,0, 0,14,0, 1,0,1, 1,5,1, 2,0,1, 2,5,1, 3,0,1, 3,5,1, 4,9,0, 5,2,1, 5,11,1, 5,13,0, 5,14,0, 6,0,0, 6,1,0, 6,11,1, 7,0,1, 7,5,0, 7,11,1, 8,0,1, 9,0,1, 9,9,1, 11,0,0, 11,1,0, 11,2,0, 11,3,0, 11,6,1, 11,11,0, 11,11,1, 12,6,1, 12,11,1, 13,6,1, 13,11,1, 14,11,1,
// Length and number of words of that length
3, 10,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 4,0,1, 4,4,0, 5,7,1, 6,7,1, 8,5,1, 8,10,0, 9,5,1, 10,12,1, 14,7,1,
// End marker
0
};
/*
* Name: 15.06, 15 x 15
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (* * * _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
*/
const int g15[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
30,
// Black field coordinates
0,4, 0,10, 1,4, 1,10, 2,4, 2,10, 3,7, 4,3, 4,11, 5,8, 6,4, 6,9, 7,0, 7,1, 7,2, 7,12, 7,13, 7,14, 8,5, 8,10, 9,6, 10,3, 10,11, 11,7, 12,4, 12,10, 13,4, 13,10, 14,4, 14,10,
// Length and number of words of that length
9, 3,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 6,8,0, 7,3,1,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 5,0,1, 7,9,0, 9,7,1,
// Length and number of words of that length
7, 19,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,2,0, 0,12,0, 0,13,0, 0,14,0, 3,0,1, 3,8,1, 4,4,1, 4,7,0, 8,0,0, 8,1,0, 8,2,0, 8,12,0, 8,13,0, 8,14,0, 10,4,1, 11,0,1, 11,8,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 5,9,1, 9,0,1, 9,5,0,
// Length and number of words of that length
5, 14,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,8,0, 1,5,1, 2,5,1, 3,10,0, 5,3,0, 5,11,0, 6,10,1, 7,4,0, 8,0,1, 10,6,0, 12,5,1, 13,5,1, 14,5,1,
// Length and number of words of that length
4, 20,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,3,0, 0,11,0, 0,11,1, 1,0,1, 1,11,1, 2,0,1, 2,11,1, 6,0,1, 6,5,1, 8,6,1, 8,11,1, 11,3,0, 11,11,0, 12,0,1, 12,11,1, 13,0,1, 13,11,1, 14,0,1, 14,11,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 3,4,0, 4,0,1, 4,12,1, 9,10,0, 10,0,1, 10,12,1, 12,7,0,
// End marker
0
};
/*
* Name: 15.07, 15 x 15
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (* * _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ * * *)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (* * * _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ * *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
*/
const int g16[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
32,
// Black field coordinates
0,4, 0,9, 1,4, 1,9, 2,9, 3,7, 4,0, 4,1, 4,6, 4,10, 5,5, 5,12, 5,13, 5,14, 6,4, 7,3, 7,11, 8,10, 9,0, 9,1, 9,2, 9,9, 10,4, 10,8, 10,13, 10,14, 11,7, 12,5, 13,5, 13,10, 14,5, 14,10,
// Length and number of words of that length
10, 4,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 5,6,0, 6,5,1, 8,0,1,
// Length and number of words of that length
9, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1, 6,12,0, 12,6,1,
// Length and number of words of that length
7, 10,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,11,0, 3,0,1, 3,8,1, 4,7,0, 7,4,1, 8,3,0, 8,11,0, 11,0,1, 11,8,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
3,9,0, 5,6,1, 6,5,0, 9,3,1,
// Length and number of words of that length
5, 16,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,10,1, 0,12,0, 0,13,0, 0,14,0, 1,10,1, 2,10,1, 5,0,1, 9,10,1, 10,0,0, 10,1,0, 10,2,0, 10,9,0, 12,0,1, 13,0,1, 14,0,1,
// Length and number of words of that length
4, 28,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,5,1, 0,6,0, 0,10,0, 1,0,1, 1,5,1, 2,4,0, 4,2,1, 4,11,1, 5,0,0, 5,1,0, 6,0,1, 6,13,0, 6,14,0, 8,11,1, 9,10,0, 10,0,1, 10,9,1, 11,4,0, 11,8,0, 11,13,0, 11,14,0, 13,6,1, 13,11,1, 14,6,1, 14,11,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 4,7,1, 5,10,0, 7,0,1, 7,4,0, 7,12,1, 10,5,1, 12,7,0,
// End marker
0
};
/*
* Name: 15.08, 15 x 15
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (* * * _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ * * *)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _)
* (* * * _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ * * *)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _)
*/
const int g17[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
39,
// Black field coordinates
0,4, 0,9, 1,4, 1,9, 2,4, 2,9, 3,5, 3,11, 4,0, 4,1, 4,2, 4,6, 4,10, 5,3, 5,12, 5,13, 5,14, 6,4, 6,8, 7,7, 8,6, 8,10, 9,0, 9,1, 9,2, 9,11, 10,4, 10,8, 10,12, 10,13, 10,14, 11,3, 11,9, 12,5, 12,10, 13,5, 13,10, 14,5, 14,10,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
3,9,0, 4,5,0, 5,4,1, 9,3,1,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 7,0,1, 7,8,1, 8,7,0,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 6,9,1, 8,0,1, 9,6,0,
// Length and number of words of that length
5, 20,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,10,1, 0,12,0, 0,13,0, 0,14,0, 1,10,1, 2,10,1, 3,0,1, 3,6,1, 4,11,0, 6,3,0, 10,0,0, 10,1,0, 10,2,0, 10,11,0, 11,4,1, 11,10,1, 12,0,1, 13,0,1, 14,0,1,
// Length and number of words of that length
4, 32,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,5,1, 0,6,0, 0,10,0, 1,0,1, 1,5,1, 2,0,1, 2,5,1, 4,11,1, 5,0,0, 5,1,0, 5,2,0, 6,0,1, 6,12,0, 6,13,0, 6,14,0, 8,11,1, 10,0,1, 11,4,0, 11,8,0, 11,12,0, 11,13,0, 11,14,0, 12,6,1, 12,11,1, 13,6,1, 13,11,1, 14,6,1, 14,11,1,
// Length and number of words of that length
3, 20,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 3,4,0, 3,12,1, 4,3,1, 4,7,1, 5,0,1, 5,6,0, 5,10,0, 6,5,1, 7,4,0, 7,8,0, 8,7,1, 9,10,0, 9,12,1, 10,5,1, 10,9,1, 11,0,1, 12,3,0, 12,9,0,
// End marker
0
};
/*
* Name: 15.09, 15 x 15
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (* * * _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g18[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
38,
// Black field coordinates
0,4, 0,10, 1,4, 1,10, 2,4, 2,10, 3,7, 4,0, 4,1, 4,2, 4,6, 4,12, 4,13, 4,14, 5,5, 5,9, 6,4, 6,8, 7,3, 7,11, 8,6, 8,10, 9,5, 9,9, 10,0, 10,1, 10,2, 10,8, 10,12, 10,13, 10,14, 11,7, 12,4, 12,10, 13,4, 13,10, 14,4, 14,10,
// Length and number of words of that length
7, 10,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,11,0, 3,0,1, 3,8,1, 4,7,0, 7,4,1, 8,3,0, 8,11,0, 11,0,1, 11,8,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 6,9,1, 8,0,1, 9,6,0,
// Length and number of words of that length
5, 24,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,5,1, 0,9,0, 1,5,1, 2,5,1, 3,10,0, 4,7,1, 5,0,0, 5,0,1, 5,1,0, 5,2,0, 5,10,1, 5,12,0, 5,13,0, 5,14,0, 7,4,0, 9,0,1, 9,10,1, 10,3,1, 10,5,0, 10,9,0, 12,5,1, 13,5,1, 14,5,1,
// Length and number of words of that length
4, 28,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,6,0, 0,11,1, 0,12,0, 0,13,0, 0,14,0, 1,0,1, 1,11,1, 2,0,1, 2,11,1, 6,0,1, 8,11,1, 11,0,0, 11,1,0, 11,2,0, 11,8,0, 11,12,0, 11,13,0, 11,14,0, 12,0,1, 12,11,1, 13,0,1, 13,11,1, 14,0,1, 14,11,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 3,4,0, 4,3,1, 5,6,0, 5,6,1, 6,5,0, 6,5,1, 6,9,0, 7,0,1, 7,8,0, 7,12,1, 8,7,1, 9,6,1, 9,10,0, 10,9,1, 12,7,0,
// End marker
0
};
/*
* Name: 15.10, 15 x 15
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (* * * * _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * * _ _ _ _ _ * * *)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (* * * _ _ _ _ _ * * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ * * * *)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g19[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
35,
// Black field coordinates
0,4, 0,9, 1,4, 1,9, 2,4, 2,9, 3,4, 4,0, 4,1, 4,6, 4,11, 4,12, 4,13, 4,14, 5,5, 6,5, 6,10, 7,7, 8,4, 8,9, 9,9, 10,0, 10,1, 10,2, 10,3, 10,8, 10,13, 10,14, 11,10, 12,5, 12,10, 13,5, 13,10, 14,5, 14,10,
// Length and number of words of that length
10, 8,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,3,0, 0,8,0, 3,5,1, 5,6,0, 5,11,0, 5,12,0, 11,0,1,
// Length and number of words of that length
9, 2,
// Coordinates where words start and direction (0 = horizontal)
5,6,1, 9,0,1,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 7,0,1, 7,8,1, 8,7,0,
// Length and number of words of that length
6, 2,
// Coordinates where words start and direction (0 = horizontal)
0,10,0, 9,4,0,
// Length and number of words of that length
5, 18,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,10,1, 1,10,1, 2,10,1, 3,9,0, 5,0,0, 5,0,1, 5,1,0, 5,13,0, 5,14,0, 6,0,1, 7,5,0, 8,10,1, 9,10,1, 10,9,0, 12,0,1, 13,0,1, 14,0,1,
// Length and number of words of that length
4, 38,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,5,1, 0,6,0, 0,11,0, 0,12,0, 0,13,0, 0,14,0, 1,0,1, 1,5,1, 2,0,1, 2,5,1, 3,0,1, 4,2,1, 4,4,0, 4,7,1, 6,6,1, 6,11,1, 7,10,0, 8,0,1, 8,5,1, 10,4,1, 10,9,1, 11,0,0, 11,1,0, 11,2,0, 11,3,0, 11,8,0, 11,11,1, 11,13,0, 11,14,0, 12,6,1, 12,11,1, 13,6,1, 13,11,1, 14,6,1, 14,11,1,
// End marker
0
};
/*
* Name: 19.01, 19 x 19
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
*/
const int g20[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
60,
// Black field coordinates
0,4, 0,9, 0,14, 1,4, 1,9, 1,14, 2,4, 2,14, 3,7, 3,12, 4,0, 4,1, 4,6, 4,11, 4,17, 4,18, 5,5, 5,10, 6,4, 6,9, 6,15, 7,3, 7,8, 7,14, 8,7, 8,13, 9,0, 9,1, 9,2, 9,6, 9,12, 9,16, 9,17, 9,18, 10,5, 10,11, 11,4, 11,10, 11,15, 12,3, 12,9, 12,14, 13,8, 13,13, 14,0, 14,1, 14,7, 14,12, 14,17, 14,18, 15,6, 15,11, 16,4, 16,14, 17,4, 17,9, 17,14, 18,4, 18,9, 18,14,
// Length and number of words of that length
9, 6,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,16,0, 2,5,1, 10,2,0, 10,16,0, 16,5,1,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,13,0, 5,11,1, 11,5,0, 13,0,1,
// Length and number of words of that length
7, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,8,0, 3,0,1, 8,0,1, 10,12,1, 12,10,0, 12,15,0, 15,12,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
0,15,0, 3,13,1, 13,3,0, 15,0,1,
// Length and number of words of that length
5, 24,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,10,0, 4,12,0, 4,12,1, 5,0,1, 5,11,0, 6,10,0, 6,10,1, 7,9,0, 7,9,1, 8,8,0, 8,8,1, 8,14,1, 9,7,0, 9,7,1, 10,0,1, 10,6,0, 10,6,1, 11,5,1, 12,4,1, 13,14,1, 14,2,1, 14,8,0, 14,13,0,
// Length and number of words of that length
4, 70,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,5,1, 0,6,0, 0,10,1, 0,11,0, 0,15,1, 0,17,0, 0,18,0, 1,0,1, 1,5,1, 1,10,1, 1,15,1, 2,0,1, 2,9,0, 2,15,1, 3,8,1, 3,14,0, 4,2,1, 4,7,0, 4,7,1, 5,0,0, 5,1,0, 5,6,0, 5,6,1, 5,17,0, 5,18,0, 6,0,1, 6,5,0, 6,5,1, 7,4,0, 7,4,1, 7,15,0, 7,15,1, 8,3,0, 8,14,0, 9,13,0, 10,0,0, 10,1,0, 10,12,0, 10,17,0, 10,18,0, 11,0,1, 11,11,0, 11,11,1, 12,4,0, 12,10,1, 12,15,1, 13,9,0, 13,9,1, 14,8,1, 14,13,1, 15,0,0, 15,1,0, 15,7,0, 15,7,1, 15,12,0, 15,17,0, 15,18,0, 16,0,1, 16,15,1, 17,0,1, 17,5,1, 17,10,1, 17,15,1, 18,0,1, 18,5,1, 18,10,1, 18,15,1,
// Length and number of words of that length
3, 12,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,12,0, 3,4,0, 6,16,1, 7,0,1, 9,3,1, 9,13,1, 11,16,1, 12,0,1, 13,14,0, 16,6,0, 16,11,0,
// End marker
0
};
/*
* Name: 19.02, 19 x 19
* (_ _ _ _ _ * * _ _ _ _ _ * * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * * _ _ _ _ _ _ _)
* (* * * _ _ _ _ _ _ * _ _ _ _ _ _ _ * *)
* (_ _ _ _ _ _ _ * * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * * _ _ _ _ _ _ _ * * _ _ _)
* (_ _ _ * * _ _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * * * _ _ _ _ _ _)
* (* * _ _ _ _ _ _ _ * _ _ _ _ _ _ _ * *)
* (_ _ _ _ _ _ * * * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ _ * * _ _ _)
* (_ _ _ * * _ _ _ _ _ _ _ * * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * * _ _ _ _ _ _ _)
* (* * _ _ _ _ _ _ _ * _ _ _ _ _ _ * * *)
* (_ _ _ _ _ _ _ * * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * * _ _ _ _ _ * * _ _ _ _ _)
*/
const int g21[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
65,
// Black field coordinates
0,4, 0,9, 0,14, 1,4, 1,9, 1,14, 2,4, 3,7, 3,12, 4,3, 4,7, 4,8, 4,12, 4,13, 5,0, 5,1, 5,6, 5,11, 5,16, 5,17, 5,18, 6,0, 6,6, 6,10, 6,18, 7,5, 7,10, 7,15, 8,5, 8,10, 8,15, 9,4, 9,9, 9,14, 10,3, 10,8, 10,13, 11,3, 11,8, 11,13, 12,0, 12,8, 12,12, 12,18, 13,0, 13,1, 13,2, 13,7, 13,12, 13,17, 13,18, 14,5, 14,6, 14,10, 14,11, 14,15, 15,6, 15,11, 16,14, 17,4, 17,9, 17,14, 18,4, 18,9, 18,14,
// Length and number of words of that length
14, 2,
// Coordinates where words start and direction (0 = horizontal)
2,5,1, 16,0,1,
// Length and number of words of that length
13, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 6,16,0,
// Length and number of words of that length
8, 2,
// Coordinates where words start and direction (0 = horizontal)
5,7,0, 6,11,0,
// Length and number of words of that length
7, 16,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,15,0, 2,9,0, 2,14,0, 3,0,1, 5,12,0, 6,1,0, 6,11,1, 6,17,0, 7,6,0, 10,4,0, 10,9,0, 12,1,1, 12,3,0, 12,13,0, 15,12,1,
// Length and number of words of that length
6, 6,
// Coordinates where words start and direction (0 = horizontal)
0,10,0, 3,4,0, 3,13,1, 10,14,0, 13,8,0, 15,0,1,
// Length and number of words of that length
5, 30,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,6,0, 0,11,0, 0,16,0, 0,17,0, 0,18,0, 4,14,1, 5,3,0, 5,8,0, 5,13,0, 6,1,1, 7,0,0, 7,0,1, 7,18,0, 8,0,1, 9,5,0, 9,10,0, 9,15,0, 10,14,1, 11,14,1, 12,13,1, 14,0,0, 14,0,1, 14,1,0, 14,2,0, 14,7,0, 14,12,0, 14,17,0, 14,18,0,
// Length and number of words of that length
4, 44,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,3,0, 0,5,1, 0,8,0, 0,10,1, 0,13,0, 0,15,1, 1,0,1, 1,5,1, 1,10,1, 1,15,1, 2,0,1, 3,8,1, 5,2,1, 5,7,1, 5,12,1, 7,6,1, 7,11,1, 8,6,1, 8,11,1, 9,0,1, 9,5,1, 9,10,1, 9,15,1, 10,4,1, 10,9,1, 11,4,1, 11,9,1, 13,3,1, 13,8,1, 13,13,1, 15,5,0, 15,7,1, 15,10,0, 15,15,0, 16,15,1, 17,0,1, 17,5,1, 17,10,1, 17,15,1, 18,0,1, 18,5,1, 18,10,1, 18,15,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,12,0, 4,0,1, 4,4,1, 4,9,1, 6,7,1, 7,16,1, 8,16,1, 10,0,1, 11,0,1, 12,9,1, 14,7,1, 14,12,1, 14,16,1, 16,6,0, 16,11,0,
// End marker
0
};
/*
* Name: 19.03, 19 x 19
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ _ _ * _ _ _ _ _ _ _ * * *)
* (_ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ * * _ _ _ _ _ _ _ _ _ * * _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _)
* (* * * _ _ _ _ _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
*/
const int g22[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
54,
// Black field coordinates
0,6, 0,12, 1,6, 1,12, 2,6, 2,12, 3,3, 3,9, 3,15, 4,4, 4,9, 4,14, 5,5, 5,13, 6,0, 6,1, 6,2, 6,8, 6,16, 6,17, 6,18, 7,7, 7,11, 8,6, 8,10, 9,3, 9,4, 9,14, 9,15, 10,8, 10,12, 11,7, 11,11, 12,0, 12,1, 12,2, 12,10, 12,16, 12,17, 12,18, 13,5, 13,13, 14,4, 14,9, 14,14, 15,3, 15,9, 15,15, 16,6, 16,12, 17,6, 17,12, 18,6, 18,12,
// Length and number of words of that length
9, 2,
// Coordinates where words start and direction (0 = horizontal)
5,9,0, 9,5,1,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,10,0, 8,11,1, 10,0,1, 11,8,0,
// Length and number of words of that length
7, 16,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,11,0, 3,12,0, 5,6,1, 6,5,0, 6,9,1, 6,13,0, 7,0,1, 7,12,1, 9,6,0, 11,0,1, 11,12,1, 12,3,1, 12,7,0, 12,11,0, 13,6,1,
// Length and number of words of that length
6, 28,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,8,0, 0,13,1, 0,16,0, 0,17,0, 0,18,0, 1,0,1, 1,13,1, 2,0,1, 2,13,1, 8,0,1, 10,13,1, 13,0,0, 13,1,0, 13,2,0, 13,10,0, 13,16,0, 13,17,0, 13,18,0, 16,0,1, 16,13,1, 17,0,1, 17,13,1, 18,0,1, 18,13,1,
// Length and number of words of that length
5, 32,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,7,1, 0,13,0, 1,7,1, 2,7,1, 3,4,1, 3,6,0, 3,10,1, 4,3,0, 4,15,0, 5,0,1, 5,14,1, 6,3,1, 7,0,0, 7,1,0, 7,2,0, 7,16,0, 7,17,0, 7,18,0, 10,3,0, 10,15,0, 11,12,0, 12,11,1, 13,0,1, 13,14,1, 14,5,0, 14,13,0, 15,4,1, 15,10,1, 16,7,1, 17,7,1, 18,7,1,
// Length and number of words of that length
4, 16,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,14,0, 4,0,1, 4,5,1, 4,10,1, 4,15,1, 5,4,0, 5,14,0, 10,4,0, 10,14,0, 14,0,1, 14,5,1, 14,10,1, 14,15,1, 15,4,0, 15,14,0,
// Length and number of words of that length
3, 20,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 0,15,0, 3,0,1, 3,16,1, 7,8,0, 7,8,1, 8,7,0, 8,7,1, 8,11,0, 9,0,1, 9,10,0, 9,16,1, 10,9,1, 11,8,1, 15,0,1, 15,16,1, 16,3,0, 16,9,0, 16,15,0,
// End marker
0
};
/*
* Name: 19.04, 19 x 19
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ * * * _ _ _ * _ _ _ _)
* (* * * _ _ _ _ _ _ _ _ _ _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * * * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ _ _ _ _ _ _ _ _ _ * * *)
* (_ _ _ _ * _ _ _ * * * _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
*/
const int g23[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
65,
// Black field coordinates
0,5, 0,13, 1,5, 1,13, 2,5, 2,13, 3,3, 3,7, 3,11, 3,15, 4,4, 4,8, 4,9, 4,10, 4,14, 5,0, 5,1, 5,2, 5,16, 5,17, 5,18, 6,6, 6,12, 7,3, 7,7, 7,11, 7,15, 8,4, 8,9, 8,14, 9,4, 9,8, 9,9, 9,10, 9,14, 10,4, 10,9, 10,14, 11,3, 11,7, 11,11, 11,15, 12,6, 12,12, 13,0, 13,1, 13,2, 13,16, 13,17, 13,18, 14,4, 14,8, 14,9, 14,10, 14,14, 15,3, 15,7, 15,11, 15,15, 16,5, 16,13, 17,5, 17,13, 18,5, 18,13,
// Length and number of words of that length
13, 4,
// Coordinates where words start and direction (0 = horizontal)
3,5,0, 3,13,0, 5,3,1, 13,3,1,
// Length and number of words of that length
7, 12,
// Coordinates where words start and direction (0 = horizontal)
0,6,1, 1,6,1, 2,6,1, 6,0,0, 6,1,0, 6,2,0, 6,16,0, 6,17,0, 6,18,0, 16,6,1, 17,6,1, 18,6,1,
// Length and number of words of that length
6, 8,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,12,0, 6,0,1, 6,13,1, 12,0,1, 12,13,1, 13,6,0, 13,12,0,
// Length and number of words of that length
5, 28,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,14,1, 0,16,0, 0,17,0, 0,18,0, 1,0,1, 1,14,1, 2,0,1, 2,14,1, 6,7,1, 7,6,0, 7,12,0, 12,7,1, 14,0,0, 14,1,0, 14,2,0, 14,16,0, 14,17,0, 14,18,0, 16,0,1, 16,14,1, 17,0,1, 17,14,1, 18,0,1, 18,14,1,
// Length and number of words of that length
4, 28,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,8,0, 0,9,0, 0,10,0, 0,14,0, 4,0,1, 4,15,1, 5,8,0, 5,10,0, 8,0,1, 8,5,1, 8,10,1, 8,15,1, 9,0,1, 9,15,1, 10,0,1, 10,5,1, 10,8,0, 10,10,0, 10,10,1, 10,15,1, 14,0,1, 14,15,1, 15,4,0, 15,8,0, 15,9,0, 15,10,0, 15,14,0,
// Length and number of words of that length
3, 52,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,7,0, 0,11,0, 0,15,0, 3,0,1, 3,4,1, 3,8,1, 3,12,1, 3,16,1, 4,3,0, 4,5,1, 4,7,0, 4,11,0, 4,11,1, 4,15,0, 5,4,0, 5,9,0, 5,14,0, 7,0,1, 7,4,1, 7,8,1, 7,12,1, 7,16,1, 8,3,0, 8,7,0, 8,11,0, 8,15,0, 9,5,1, 9,11,1, 11,0,1, 11,4,0, 11,4,1, 11,8,1, 11,9,0, 11,12,1, 11,14,0, 11,16,1, 12,3,0, 12,7,0, 12,11,0, 12,15,0, 14,5,1, 14,11,1, 15,0,1, 15,4,1, 15,8,1, 15,12,1, 15,16,1, 16,3,0, 16,7,0, 16,11,0, 16,15,0,
// End marker
0
};
/*
* Name: 19.05, 19 x 19
* (_ _ _ _ * * _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ * _ _ _ _ * * *)
* (* * * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * * _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * * _ _ _ _ * _ _ _)
* (_ _ _ _ * * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * * _ _ _ _)
* (_ _ _ * _ _ _ _ * * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ * * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * * *)
* (* * * _ _ _ _ * _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ * * _ _ _ _)
*/
const int g24[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
70,
// Black field coordinates
0,4, 0,10, 0,15, 1,4, 1,10, 1,15, 2,4, 2,10, 2,15, 3,6, 3,11, 4,0, 4,1, 4,2, 4,7, 4,8, 4,12, 4,16, 4,17, 4,18, 5,0, 5,8, 5,12, 5,13, 6,5, 6,13, 7,3, 7,10, 7,15, 8,6, 8,11, 9,0, 9,1, 9,2, 9,7, 9,11, 9,16, 9,17, 9,18, 10,7, 10,12, 11,3, 11,8, 11,15, 12,5, 12,13, 13,5, 13,6, 13,10, 13,18, 14,0, 14,1, 14,2, 14,6, 14,10, 14,11, 14,16, 14,17, 14,18, 15,7, 15,12, 16,3, 16,8, 16,14, 17,3, 17,8, 17,14, 18,3, 18,8, 18,14,
// Length and number of words of that length
19, 1,
// Coordinates where words start and direction (0 = horizontal)
0,9,0,
// Length and number of words of that length
16, 2,
// Coordinates where words start and direction (0 = horizontal)
0,14,0, 3,4,0,
// Length and number of words of that length
7, 10,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 3,12,1, 5,1,1, 6,6,1, 8,12,1, 10,0,1, 12,6,1, 12,15,0, 13,11,1, 15,0,1,
// Length and number of words of that length
6, 8,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 3,0,1, 7,4,1, 8,0,1, 10,13,1, 11,9,1, 13,13,0, 15,13,1,
// Length and number of words of that length
5, 18,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,13,0, 1,5,1, 2,5,1, 5,14,1, 6,0,1, 6,8,0, 6,14,1, 7,5,0, 7,13,0, 8,10,0, 12,0,1, 12,14,1, 13,0,1, 14,5,0, 16,9,1, 17,9,1, 18,9,1,
// Length and number of words of that length
4, 62,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,7,0, 0,8,0, 0,11,1, 0,12,0, 0,16,0, 0,17,0, 0,18,0, 1,0,1, 1,11,1, 2,0,1, 2,11,1, 3,7,1, 3,10,0, 3,15,0, 4,3,1, 4,6,0, 4,11,0, 5,1,0, 5,2,0, 5,7,0, 5,16,0, 5,17,0, 5,18,0, 6,12,0, 7,11,1, 8,7,1, 9,3,1, 9,6,0, 9,12,1, 10,0,0, 10,1,0, 10,2,0, 10,8,1, 10,11,0, 10,16,0, 10,17,0, 11,4,1, 11,7,0, 11,12,0, 12,3,0, 12,8,0, 14,12,1, 15,0,0, 15,1,0, 15,2,0, 15,6,0, 15,8,1, 15,10,0, 15,11,0, 15,16,0, 15,17,0, 15,18,0, 16,4,1, 16,15,1, 17,4,1, 17,15,1, 18,4,1, 18,15,1,
// Length and number of words of that length
3, 25,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,11,0, 0,16,1, 1,16,1, 2,16,1, 4,9,1, 4,13,1, 5,9,1, 6,0,0, 7,0,1, 7,16,1, 8,3,0, 8,15,0, 9,8,1, 10,18,0, 11,0,1, 11,16,1, 13,7,1, 14,3,1, 14,7,1, 16,0,1, 16,7,0, 16,12,0, 17,0,1, 18,0,1,
// End marker
0
};
/*
* Name: 19.06, 19 x 19
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (* _ _ _ * _ _ _ _ _ _ _ _ _ _ _ * * *)
* (* * * _ _ _ * * _ _ _ * * _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ * * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * * _ _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ * * _ _ _ * * _ _ _ * * *)
* (* * * _ _ _ _ _ _ _ _ _ _ _ * _ _ _ *)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
*/
const int g25[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
74,
// Black field coordinates
0,3, 0,4, 0,9, 0,14, 0,15, 1,4, 1,9, 1,14, 1,15, 2,4, 2,15, 3,11, 3,12, 4,0, 4,1, 4,2, 4,3, 4,7, 4,11, 4,16, 4,17, 4,18, 5,5, 5,6, 5,10, 6,4, 6,9, 6,14, 7,4, 7,8, 7,14, 8,7, 8,13, 9,0, 9,1, 9,2, 9,6, 9,12, 9,16, 9,17, 9,18, 10,5, 10,11, 11,4, 11,10, 11,14, 12,4, 12,9, 12,14, 13,8, 13,12, 13,13, 14,0, 14,1, 14,2, 14,7, 14,11, 14,15, 14,16, 14,17, 14,18, 15,6, 15,7, 16,3, 16,14, 17,3, 17,4, 17,9, 17,14, 18,3, 18,4, 18,9, 18,14, 18,15,
// Length and number of words of that length
11, 4,
// Coordinates where words start and direction (0 = horizontal)
3,0,1, 3,15,0, 5,3,0, 15,8,1,
// Length and number of words of that length
10, 2,
// Coordinates where words start and direction (0 = horizontal)
2,5,1, 16,4,1,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,13,0, 5,11,1, 11,5,0, 13,0,1,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 8,0,1, 10,12,1, 12,10,0,
// Length and number of words of that length
6, 2,
// Coordinates where words start and direction (0 = horizontal)
3,13,1, 15,0,1,
// Length and number of words of that length
5, 22,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,6,0, 0,10,0, 4,12,0, 5,0,1, 5,11,0, 6,10,0, 7,9,0, 7,9,1, 8,8,0, 8,8,1, 8,14,1, 9,7,0, 9,7,1, 10,0,1, 10,6,0, 10,6,1, 11,5,1, 13,14,1, 14,8,0, 14,12,0, 14,13,0,
// Length and number of words of that length
4, 58,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,2,0, 0,5,1, 0,7,0, 0,10,1, 0,16,0, 0,17,0, 0,18,0, 1,0,1, 1,5,1, 1,10,1, 2,0,1, 2,9,0, 2,14,0, 4,12,1, 5,0,0, 5,1,0, 5,2,0, 5,16,0, 5,17,0, 5,18,0, 6,0,1, 6,5,0, 6,5,1, 6,10,1, 6,15,1, 7,0,1, 7,15,1, 9,13,0, 10,0,0, 10,1,0, 10,2,0, 10,16,0, 10,17,0, 10,18,0, 11,0,1, 11,15,1, 12,0,1, 12,5,1, 12,10,1, 12,15,1, 13,4,0, 13,9,0, 14,3,1, 15,0,0, 15,1,0, 15,2,0, 15,11,0, 15,16,0, 15,17,0, 15,18,0, 16,15,1, 17,5,1, 17,10,1, 17,15,1, 18,5,1, 18,10,1,
// Length and number of words of that length
3, 32,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,11,0, 0,12,0, 0,16,1, 1,3,0, 1,16,1, 2,16,1, 3,4,0, 4,4,1, 4,8,1, 5,7,0, 5,7,1, 6,6,0, 7,5,1, 8,4,0, 8,14,0, 9,3,1, 9,13,1, 10,12,0, 11,11,0, 11,11,1, 13,9,1, 13,14,0, 14,8,1, 14,12,1, 15,15,0, 16,0,1, 16,6,0, 16,7,0, 17,0,1, 18,0,1, 18,16,1,
// End marker
0
};
/*
* Name: 19.07, 19 x 19
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * * _ _ _ _)
* (* * * * _ _ _ * _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ * * _ _ _ * * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * * _ _ _ * * _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ * _ _ _ * * * *)
* (_ _ _ _ * * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _)
*/
const int g26[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
70,
// Black field coordinates
0,4, 0,9, 0,14, 1,4, 1,9, 1,14, 2,4, 2,9, 2,14, 3,3, 3,4, 3,16, 3,17, 3,18, 4,7, 4,11, 4,15, 5,0, 5,1, 5,6, 5,11, 5,15, 6,5, 6,10, 6,14, 7,4, 7,8, 7,9, 7,13, 8,3, 8,7, 8,12, 8,17, 8,18, 9,7, 9,11, 10,0, 10,1, 10,6, 10,11, 10,15, 11,5, 11,9, 11,10, 11,14, 12,4, 12,8, 12,13, 13,3, 13,7, 13,12, 13,17, 13,18, 14,3, 14,7, 14,11, 15,0, 15,1, 15,2, 15,14, 15,15, 16,4, 16,9, 16,14, 17,4, 17,9, 17,14, 18,4, 18,9, 18,14,
// Length and number of words of that length
15, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 4,16,0,
// Length and number of words of that length
11, 2,
// Coordinates where words start and direction (0 = horizontal)
3,5,1, 15,3,1,
// Length and number of words of that length
8, 2,
// Coordinates where words start and direction (0 = horizontal)
0,12,0, 11,6,0,
// Length and number of words of that length
7, 8,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,13,0, 4,0,1, 9,0,1, 9,12,1, 12,5,0, 12,10,0, 14,12,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,10,0, 13,8,0, 13,13,0,
// Length and number of words of that length
5, 10,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,6,0, 6,0,1, 7,14,1, 11,0,1, 12,14,1, 14,12,0, 14,17,0, 14,18,0,
// Length and number of words of that length
4, 66,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,5,1, 0,7,0, 0,10,1, 0,11,0, 0,15,0, 0,15,1, 1,0,1, 1,5,1, 1,10,1, 1,15,1, 2,0,1, 2,5,1, 2,10,1, 2,15,1, 3,9,0, 4,3,0, 4,17,0, 4,18,0, 5,2,1, 5,7,1, 6,0,0, 6,1,0, 6,6,0, 6,6,1, 6,15,0, 6,15,1, 7,0,1, 7,5,0, 7,10,0, 7,14,0, 8,4,0, 8,8,0, 8,8,1, 8,13,0, 8,13,1, 9,3,0, 9,12,0, 9,17,0, 9,18,0, 10,2,1, 10,7,1, 11,0,0, 11,1,0, 11,15,0, 11,15,1, 12,0,1, 12,9,0, 12,9,1, 13,8,1, 13,13,1, 15,3,0, 15,7,0, 15,11,0, 16,0,1, 16,5,1, 16,10,1, 16,15,1, 17,0,1, 17,5,1, 17,10,1, 17,15,1, 18,0,1, 18,5,1, 18,10,1, 18,15,1,
// Length and number of words of that length
3, 40,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,16,0, 0,17,0, 0,18,0, 3,0,1, 3,14,0, 4,4,0, 4,8,1, 4,12,1, 4,16,1, 5,7,0, 5,12,1, 5,16,1, 6,11,0, 6,11,1, 7,5,1, 7,10,1, 8,0,1, 8,4,1, 8,9,0, 9,8,1, 10,7,0, 10,12,1, 10,16,1, 11,6,1, 11,11,0, 11,11,1, 12,5,1, 12,14,0, 13,0,1, 13,4,0, 13,4,1, 14,0,1, 14,4,1, 14,8,1, 15,16,1, 16,0,0, 16,1,0, 16,2,0, 16,15,0,
// End marker
0
};
/*
* Name: 19.08, 19 x 19
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ * * _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ * * _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
*/
const int g27[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
66,
// Black field coordinates
0,4, 0,9, 0,14, 1,4, 1,9, 1,14, 2,4, 2,9, 2,14, 3,6, 4,0, 4,1, 4,2, 4,7, 4,11, 4,12, 4,16, 4,17, 4,18, 5,8, 5,13, 6,4, 6,9, 6,14, 7,4, 7,10, 8,5, 8,11, 8,15, 9,0, 9,1, 9,2, 9,6, 9,12, 9,16, 9,17, 9,18, 10,3, 10,7, 10,13, 11,8, 11,14, 12,4, 12,9, 12,14, 13,5, 13,10, 14,0, 14,1, 14,2, 14,6, 14,7, 14,11, 14,16, 14,17, 14,18, 15,12, 16,4, 16,9, 16,14, 17,4, 17,9, 17,14, 18,4, 18,9, 18,14,
// Length and number of words of that length
12, 2,
// Coordinates where words start and direction (0 = horizontal)
3,7,1, 15,0,1,
// Length and number of words of that length
10, 2,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 9,15,0,
// Length and number of words of that length
8, 8,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,15,0, 5,0,1, 7,11,1, 11,0,1, 11,3,0, 11,13,0, 13,11,1,
// Length and number of words of that length
7, 2,
// Coordinates where words start and direction (0 = horizontal)
0,10,0, 12,8,0,
// Length and number of words of that length
6, 2,
// Coordinates where words start and direction (0 = horizontal)
3,0,1, 15,13,1,
// Length and number of words of that length
5, 20,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,13,0, 4,6,0, 5,7,0, 5,14,1, 6,8,0, 7,5,1, 7,9,0, 8,0,1, 8,6,1, 8,10,0, 9,7,1, 9,11,0, 10,8,1, 10,12,0, 10,14,1, 11,9,1, 13,0,1, 14,5,0, 14,10,0,
// Length and number of words of that length
4, 74,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,5,1, 0,7,0, 0,10,1, 0,11,0, 0,12,0, 0,15,1, 0,16,0, 0,17,0, 0,18,0, 1,0,1, 1,5,1, 1,10,1, 1,15,1, 2,0,1, 2,5,1, 2,10,1, 2,15,1, 4,3,1, 5,0,0, 5,1,0, 5,2,0, 5,9,1, 5,12,0, 5,16,0, 5,17,0, 5,18,0, 6,0,1, 6,5,1, 6,10,1, 6,13,0, 6,15,1, 7,0,1, 7,14,0, 8,4,0, 9,5,0, 10,0,0, 10,1,0, 10,2,0, 10,6,0, 10,16,0, 10,17,0, 10,18,0, 11,15,1, 12,0,1, 12,5,1, 12,10,1, 12,15,1, 13,6,1, 14,12,1, 15,0,0, 15,1,0, 15,2,0, 15,6,0, 15,7,0, 15,11,0, 15,16,0, 15,17,0, 15,18,0, 16,0,1, 16,5,1, 16,10,1, 16,15,1, 17,0,1, 17,5,1, 17,10,1, 17,15,1, 18,0,1, 18,5,1, 18,10,1, 18,15,1,
// Length and number of words of that length
3, 20,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 3,4,0, 3,9,0, 3,14,0, 4,8,1, 4,13,1, 5,11,0, 8,12,1, 8,16,1, 9,3,1, 9,13,1, 10,0,1, 10,4,1, 11,7,0, 13,4,0, 13,9,0, 13,14,0, 14,3,1, 14,8,1, 16,12,0,
// End marker
0
};
/*
* Name: 19.09, 19 x 19
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _)
* (* * * _ _ _ _ * _ _ _ * * _ _ _ _ * *)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ * * _ _ _ * _ _ _ _ _ * * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * * _ _ _ _ _ * _ _ _ * * _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (* * _ _ _ _ * * _ _ _ * _ _ _ _ * * *)
* (_ _ _ * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
*/
const int g28[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
66,
// Black field coordinates
0,4, 0,9, 0,14, 1,4, 1,9, 1,14, 2,4, 3,7, 3,11, 3,15, 4,0, 4,1, 4,2, 4,7, 4,11, 4,12, 4,16, 4,17, 4,18, 5,6, 5,10, 6,5, 6,9, 6,14, 7,4, 7,8, 7,14, 8,7, 8,13, 9,0, 9,1, 9,2, 9,6, 9,12, 9,16, 9,17, 9,18, 10,5, 10,11, 11,4, 11,10, 11,14, 12,4, 12,9, 12,13, 13,8, 13,12, 14,0, 14,1, 14,2, 14,6, 14,7, 14,11, 14,16, 14,17, 14,18, 15,3, 15,7, 15,11, 16,14, 17,4, 17,9, 17,14, 18,4, 18,9, 18,14,
// Length and number of words of that length
15, 2,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 4,15,0,
// Length and number of words of that length
14, 2,
// Coordinates where words start and direction (0 = horizontal)
2,5,1, 16,0,1,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,13,0, 5,11,1, 11,5,0, 13,0,1,
// Length and number of words of that length
7, 6,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 3,0,1, 8,0,1, 10,12,1, 12,10,0, 15,12,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 5,0,1, 13,13,0, 13,13,1,
// Length and number of words of that length
5, 18,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,10,0, 5,11,0, 6,0,1, 6,10,0, 7,9,0, 7,9,1, 8,8,0, 8,8,1, 8,14,1, 9,7,0, 9,7,1, 10,0,1, 10,6,1, 11,5,1, 12,14,1, 14,8,0, 14,12,0,
// Length and number of words of that length
4, 62,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,5,1, 0,10,1, 0,12,0, 0,15,1, 0,16,0, 0,17,0, 0,18,0, 1,0,1, 1,5,1, 1,10,1, 1,15,1, 2,0,1, 2,9,0, 2,14,0, 3,4,0, 4,3,1, 5,0,0, 5,1,0, 5,2,0, 5,12,0, 5,16,0, 5,17,0, 5,18,0, 6,10,1, 6,15,1, 7,0,1, 7,15,1, 10,0,0, 10,1,0, 10,2,0, 10,6,0, 10,16,0, 10,17,0, 10,18,0, 11,0,1, 11,15,1, 12,0,1, 12,5,1, 12,14,0, 13,4,0, 13,9,0, 14,12,1, 15,0,0, 15,1,0, 15,2,0, 15,6,0, 15,16,0, 15,17,0, 15,18,0, 16,15,1, 17,0,1, 17,5,1, 17,10,1, 17,15,1, 18,0,1, 18,5,1, 18,10,1, 18,15,1,
// Length and number of words of that length
3, 32,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,11,0, 0,15,0, 3,8,1, 3,12,1, 3,16,1, 4,8,1, 4,13,1, 5,7,0, 5,7,1, 6,6,0, 6,6,1, 7,5,0, 7,5,1, 8,4,0, 8,14,0, 9,3,1, 9,13,0, 9,13,1, 10,12,0, 11,11,0, 11,11,1, 12,10,1, 13,9,1, 14,3,1, 14,8,1, 15,0,1, 15,4,1, 15,8,1, 16,3,0, 16,7,0, 16,11,0,
// End marker
0
};
/*
* Name: 19.10, 19 x 19
* (_ _ _ * * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ * * _ _ _ _ *)
* (* * * _ _ _ * _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * * _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (* _ _ _ _ _ _ * _ _ _ _ * * _ _ _ _ _)
* (* * * _ _ _ _ _ _ _ _ _ _ _ _ _ * * *)
* (_ _ _ _ _ * * _ _ _ _ * _ _ _ _ _ _ *)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ * * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ * _ _ _ * * *)
* (* _ _ _ _ * * _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * * _ _ _)
*/
const int g29[] = {
// Width and height of crossword grid
19, 19,
// Number of black fields
70,
// Black field coordinates
0,4, 0,8, 0,9, 0,14, 0,15, 1,4, 1,9, 1,14, 2,4, 2,9, 2,14, 3,0, 3,7, 3,12, 4,0, 4,1, 4,6, 4,11, 4,12, 4,17, 4,18, 5,5, 5,10, 5,15, 6,4, 6,10, 6,15, 7,3, 7,8, 7,14, 8,7, 8,13, 9,0, 9,1, 9,6, 9,12, 9,17, 9,18, 10,5, 10,11, 11,4, 11,10, 11,15, 12,3, 12,8, 12,14, 13,3, 13,8, 13,13, 14,0, 14,1, 14,6, 14,7, 14,12, 14,17, 14,18, 15,6, 15,11, 15,18, 16,4, 16,9, 16,14, 17,4, 17,9, 17,14, 18,3, 18,4, 18,9, 18,10, 18,14,
// Length and number of words of that length
19, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,16,0,
// Length and number of words of that length
13, 1,
// Coordinates where words start and direction (0 = horizontal)
3,9,0,
// Length and number of words of that length
8, 2,
// Coordinates where words start and direction (0 = horizontal)
0,13,0, 11,5,0,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 8,0,1, 10,12,1, 12,15,0,
// Length and number of words of that length
6, 6,
// Coordinates where words start and direction (0 = horizontal)
1,8,0, 3,1,1, 3,13,1, 12,10,0, 15,0,1, 15,12,1,
// Length and number of words of that length
5, 17,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,10,0, 5,0,1, 5,11,0, 6,5,1, 7,9,1, 8,8,1, 8,14,1, 9,7,0, 9,7,1, 10,0,1, 10,6,1, 11,5,1, 12,9,1, 13,14,1, 14,8,0, 14,13,0,
// Length and number of words of that length
4, 78,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,1,0, 0,6,0, 0,10,1, 0,11,0, 0,17,0, 0,18,0, 1,0,1, 1,5,1, 1,10,1, 1,15,0, 1,15,1, 2,0,1, 2,5,1, 2,10,1, 2,15,1, 3,8,1, 3,14,0, 4,2,1, 4,7,0, 4,7,1, 4,13,1, 5,0,0, 5,1,0, 5,6,0, 5,6,1, 5,11,1, 5,12,0, 5,17,0, 5,18,0, 6,0,1, 6,5,0, 6,11,1, 7,4,0, 7,4,1, 7,10,0, 7,15,0, 7,15,1, 8,3,0, 8,8,0, 8,14,0, 9,2,1, 9,13,0, 9,13,1, 10,0,0, 10,1,0, 10,6,0, 10,12,0, 10,17,0, 10,18,0, 11,0,1, 11,11,0, 11,11,1, 12,4,0, 12,4,1, 12,15,1, 13,4,1, 13,9,1, 14,2,1, 14,3,0, 14,8,1, 14,13,1, 15,0,0, 15,1,0, 15,7,0, 15,7,1, 15,12,0, 15,17,0, 16,0,1, 16,5,1, 16,10,1, 16,15,1, 17,0,1, 17,5,1, 17,10,1, 17,15,1, 18,5,1, 18,15,1,
// Length and number of words of that length
3, 18,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,5,1, 0,7,0, 0,12,0, 0,16,1, 3,4,0, 5,16,1, 6,16,1, 7,0,1, 11,16,1, 12,0,1, 13,0,1, 13,14,0, 16,6,0, 16,11,0, 16,18,0, 18,0,1, 18,11,1,
// End marker
0
};
/*
* Name: 21.01, 21 x 21
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ * * * _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * * _ _ _ _ _ _)
* (* * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * *)
* (_ _ _ _ _ _ * * _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ * * * _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g30[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
68,
// Black field coordinates
0,4, 0,10, 0,16, 1,4, 1,10, 1,16, 2,4, 2,16, 3,8, 3,14, 4,0, 4,1, 4,7, 4,13, 5,6, 5,19, 5,20, 6,5, 6,11, 6,17, 7,4, 7,10, 7,11, 7,12, 7,16, 8,3, 8,9, 8,15, 9,7, 9,13, 10,0, 10,1, 10,2, 10,7, 10,13, 10,18, 10,19, 10,20, 11,7, 11,13, 12,5, 12,11, 12,17, 13,4, 13,8, 13,9, 13,10, 13,16, 14,3, 14,9, 14,15, 15,0, 15,1, 15,14, 16,7, 16,13, 16,19, 16,20, 17,6, 17,12, 18,4, 18,16, 19,4, 19,10, 19,16, 20,4, 20,10, 20,16,
// Length and number of words of that length
12, 2,
// Coordinates where words start and direction (0 = horizontal)
5,7,1, 15,2,1,
// Length and number of words of that length
11, 4,
// Coordinates where words start and direction (0 = horizontal)
2,5,1, 4,14,0, 6,6,0, 18,5,1,
// Length and number of words of that length
10, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,18,0, 11,2,0, 11,18,0,
// Length and number of words of that length
9, 2,
// Coordinates where words start and direction (0 = horizontal)
4,8,0, 8,12,0,
// Length and number of words of that length
8, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 0,15,0, 3,0,1, 13,5,0, 13,11,0, 13,17,0, 17,13,1,
// Length and number of words of that length
7, 8,
// Coordinates where words start and direction (0 = horizontal)
0,12,0, 4,14,1, 9,0,1, 9,14,1, 11,0,1, 11,14,1, 14,8,0, 16,0,1,
// Length and number of words of that length
6, 10,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 0,17,0, 3,15,1, 5,0,1, 15,3,0, 15,9,0, 15,15,0, 15,15,1, 17,0,1,
// Length and number of words of that length
5, 50,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,6,0, 0,11,1, 0,19,0, 0,20,0, 1,5,1, 1,11,1, 2,10,0, 3,9,1, 4,2,1, 4,8,1, 5,0,0, 5,1,0, 6,0,1, 6,6,1, 6,12,1, 7,5,0, 7,5,1, 7,17,0, 8,4,0, 8,4,1, 8,10,0, 8,10,1, 8,16,0, 8,16,1, 9,3,0, 9,8,1, 9,15,0, 10,8,1, 11,8,1, 11,19,0, 11,20,0, 12,0,1, 12,6,1, 12,12,1, 13,11,1, 14,4,1, 14,10,0, 14,10,1, 14,16,1, 16,0,0, 16,1,0, 16,8,1, 16,14,0, 16,14,1, 17,7,1, 19,5,1, 19,11,1, 20,5,1, 20,11,1,
// Length and number of words of that length
4, 40,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,7,0, 0,13,0, 0,17,1, 1,0,1, 1,17,1, 2,0,1, 2,17,1, 3,4,0, 3,16,0, 5,7,0, 5,13,0, 6,19,0, 6,20,0, 7,0,1, 7,17,1, 8,11,0, 9,9,0, 10,3,1, 10,14,1, 11,0,0, 11,1,0, 12,7,0, 12,13,0, 13,0,1, 13,17,1, 14,4,0, 14,16,0, 17,7,0, 17,13,0, 17,19,0, 17,20,0, 18,0,1, 18,17,1, 19,0,1, 19,17,1, 20,0,1, 20,17,1,
// Length and number of words of that length
3, 10,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,14,0, 6,18,1, 7,13,1, 8,0,1, 12,18,1, 13,5,1, 14,0,1, 18,6,0, 18,12,0,
// End marker
0
};
/*
* Name: 21.02, 21 x 21
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ _ * _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (* * * _ _ _ _ _ * _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g31[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
72,
// Black field coordinates
0,4, 0,10, 0,16, 1,4, 1,10, 1,16, 2,4, 2,10, 2,16, 3,9, 3,15, 4,0, 4,1, 4,2, 4,8, 4,12, 4,18, 4,19, 4,20, 5,3, 5,7, 5,13, 6,6, 6,14, 7,5, 7,10, 7,15, 8,4, 8,9, 8,16, 9,8, 9,17, 10,0, 10,1, 10,2, 10,7, 10,13, 10,18, 10,19, 10,20, 11,3, 11,12, 12,4, 12,11, 12,16, 13,5, 13,10, 13,15, 14,6, 14,14, 15,7, 15,13, 15,17, 16,0, 16,1, 16,2, 16,8, 16,12, 16,18, 16,19, 16,20, 17,5, 17,11, 18,4, 18,10, 18,16, 19,4, 19,10, 19,16, 20,4, 20,10, 20,16,
// Length and number of words of that length
12, 2,
// Coordinates where words start and direction (0 = horizontal)
0,11,0, 9,9,0,
// Length and number of words of that length
9, 4,
// Coordinates where words start and direction (0 = horizontal)
0,17,0, 3,0,1, 12,3,0, 17,12,1,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
9,0,1, 9,9,1, 11,4,1, 11,13,1,
// Length and number of words of that length
7, 8,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 5,14,1, 6,7,1, 7,6,0, 7,14,0, 14,7,1, 14,15,0, 15,0,1,
// Length and number of words of that length
6, 12,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,14,0, 5,12,0, 6,0,1, 6,15,1, 8,10,1, 10,8,0, 12,5,1, 14,0,1, 14,15,1, 15,6,0, 15,14,0,
// Length and number of words of that length
5, 54,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,5,1, 0,7,0, 0,11,1, 0,13,0, 1,5,1, 1,11,1, 2,5,1, 2,11,1, 3,4,0, 3,10,1, 3,16,0, 3,16,1, 4,3,1, 4,13,1, 5,0,0, 5,1,0, 5,2,0, 5,8,1, 5,18,0, 5,19,0, 5,20,0, 6,3,0, 7,0,1, 7,16,1, 8,5,0, 8,10,0, 8,15,0, 10,8,1, 10,17,0, 11,0,0, 11,1,0, 11,2,0, 11,18,0, 11,19,0, 11,20,0, 13,0,1, 13,4,0, 13,16,0, 13,16,1, 15,8,1, 16,3,1, 16,7,0, 16,13,0, 16,13,1, 16,17,0, 17,0,1, 17,6,1, 18,5,1, 18,11,1, 19,5,1, 19,11,1, 20,5,1, 20,11,1,
// Length and number of words of that length
4, 50,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,8,0, 0,12,0, 0,17,1, 0,18,0, 0,19,0, 0,20,0, 1,0,1, 1,17,1, 2,0,1, 2,17,1, 3,10,0, 4,9,0, 5,8,0, 6,7,0, 6,13,0, 7,6,1, 7,11,1, 8,0,1, 8,5,1, 8,17,1, 10,3,1, 10,14,1, 11,7,0, 11,13,0, 12,0,1, 12,12,0, 12,12,1, 12,17,1, 13,6,1, 13,11,0, 13,11,1, 14,10,0, 17,0,0, 17,1,0, 17,2,0, 17,8,0, 17,12,0, 17,18,0, 17,19,0, 17,20,0, 18,0,1, 18,17,1, 19,0,1, 19,17,1, 20,0,1, 20,17,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 0,15,0, 4,9,1, 4,15,0, 5,0,1, 5,4,1, 9,4,0, 9,16,0, 9,18,1, 11,0,1, 14,5,0, 15,14,1, 15,18,1, 16,9,1, 18,5,0, 18,11,0,
// End marker
0
};
/*
* Name: 21.03, 21 x 21
* (_ _ _ _ * * _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ * * _ _ _ _ _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ _ _ * * _ _ _ _ * _ _ _)
* (* * _ _ _ * _ _ _ _ _ * _ _ _ _ * * _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ * _ _ _ _ _ _ *)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _ * * *)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (* * * _ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (* _ _ _ _ _ _ * _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ * * _ _ _ _ * _ _ _ _ _ * _ _ _ * *)
* (_ _ _ * _ _ _ _ * * _ _ _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ _ _ _ _ * * _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ * * _ _ _ _)
*/
const int g32[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
79,
// Black field coordinates
0,5, 0,11, 0,12, 0,17, 1,5, 1,11, 1,17, 2,11, 3,3, 3,10, 3,15, 3,16, 4,0, 4,1, 4,2, 4,8, 4,9, 4,15, 5,0, 5,4, 5,5, 5,14, 5,18, 5,19, 5,20, 6,6, 6,13, 7,7, 7,12, 8,8, 8,16, 9,0, 9,1, 9,2, 9,3, 9,9, 9,15, 9,16, 10,3, 10,10, 10,17, 11,4, 11,5, 11,11, 11,17, 11,18, 11,19, 11,20, 12,4, 12,12, 13,8, 13,13, 14,7, 14,14, 15,0, 15,1, 15,2, 15,6, 15,15, 15,16, 15,20, 16,5, 16,11, 16,12, 16,18, 16,19, 16,20, 17,4, 17,5, 17,10, 17,17, 18,9, 19,3, 19,9, 19,15, 20,3, 20,8, 20,9, 20,15,
// Length and number of words of that length
11, 2,
// Coordinates where words start and direction (0 = horizontal)
2,0,1, 18,10,1,
// Length and number of words of that length
9, 2,
// Coordinates where words start and direction (0 = horizontal)
2,12,1, 18,0,1,
// Length and number of words of that length
8, 12,
// Coordinates where words start and direction (0 = horizontal)
2,17,0, 3,11,0, 5,6,1, 6,14,0, 7,6,0, 7,13,1, 8,0,1, 10,9,0, 11,3,0, 12,13,1, 13,0,1, 15,7,1,
// Length and number of words of that length
7, 8,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 6,14,1, 7,0,1, 8,9,1, 12,5,1, 13,14,1, 14,0,1, 14,13,0,
// Length and number of words of that length
6, 18,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,13,0, 1,12,0, 3,4,1, 4,10,0, 6,0,1, 6,7,1, 7,13,0, 8,7,0, 10,4,1, 10,11,1, 11,10,0, 14,8,0, 14,8,1, 14,15,1, 15,7,0, 15,14,0, 17,11,1,
// Length and number of words of that length
5, 42,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,4,0, 0,6,1, 0,14,0, 0,18,0, 0,19,0, 0,20,0, 1,0,1, 1,6,1, 1,12,1, 4,3,0, 4,3,1, 4,10,1, 4,16,1, 6,4,0, 6,5,0, 6,18,0, 6,19,0, 6,20,0, 9,4,1, 9,10,1, 10,0,0, 10,1,0, 10,2,0, 10,15,0, 10,16,0, 11,6,1, 11,12,1, 12,17,0, 16,0,0, 16,0,1, 16,1,0, 16,2,0, 16,6,0, 16,6,1, 16,13,1, 16,16,0, 19,4,1, 19,10,1, 19,16,1, 20,10,1, 20,16,1,
// Length and number of words of that length
4, 34,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,2,0, 0,8,0, 0,9,0, 0,13,1, 3,11,1, 3,17,1, 4,16,0, 5,1,0, 5,2,0, 5,9,0, 5,15,0, 7,8,1, 8,12,0, 8,17,1, 9,8,0, 9,17,1, 11,0,1, 12,0,1, 12,5,0, 12,11,0, 12,18,0, 12,19,0, 13,4,0, 13,9,1, 17,0,1, 17,6,1, 17,11,0, 17,12,0, 17,18,0, 17,19,0, 17,20,0, 20,4,1,
// Length and number of words of that length
3, 26,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,10,0, 0,15,0, 0,16,0, 0,18,1, 1,18,1, 2,5,0, 3,0,1, 5,1,1, 5,8,0, 5,15,1, 6,0,0, 10,0,1, 10,18,1, 12,20,0, 13,12,0, 15,3,1, 15,17,1, 16,15,0, 17,18,1, 18,4,0, 18,5,0, 18,10,0, 18,17,0, 19,0,1, 20,0,1,
// End marker
0
};
/*
* Name: 21.04, 21 x 21
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
*/
const int g33[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
63,
// Black field coordinates
0,7, 0,13, 1,7, 1,13, 2,7, 2,13, 3,3, 3,11, 3,17, 4,4, 4,10, 4,16, 5,5, 5,9, 5,15, 6,8, 6,12, 7,0, 7,1, 7,2, 7,7, 7,13, 7,18, 7,19, 7,20, 8,6, 8,14, 9,5, 9,11, 9,17, 10,4, 10,10, 10,16, 11,3, 11,9, 11,15, 12,6, 12,14, 13,0, 13,1, 13,2, 13,7, 13,13, 13,18, 13,19, 13,20, 14,8, 14,12, 15,5, 15,11, 15,15, 16,4, 16,10, 16,16, 17,3, 17,9, 17,17, 18,7, 18,13, 19,7, 19,13, 20,7, 20,13,
// Length and number of words of that length
8, 8,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,14,0, 6,0,1, 6,13,1, 13,6,0, 13,14,0, 14,0,1, 14,13,1,
// Length and number of words of that length
7, 32,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,14,1, 0,18,0, 0,19,0, 0,20,0, 1,0,1, 1,14,1, 2,0,1, 2,14,1, 3,4,1, 4,3,0, 7,8,0, 7,12,0, 8,7,1, 10,17,0, 12,7,1, 14,0,0, 14,1,0, 14,2,0, 14,18,0, 14,19,0, 14,20,0, 17,10,1, 18,0,1, 18,14,1, 19,0,1, 19,14,1, 20,0,1, 20,14,1,
// Length and number of words of that length
6, 8,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,12,0, 8,0,1, 8,15,1, 12,0,1, 12,15,1, 15,8,0, 15,12,0,
// Length and number of words of that length
5, 56,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,8,1, 0,9,0, 0,15,0, 1,8,1, 2,8,1, 3,12,1, 4,5,1, 4,11,0, 4,11,1, 4,17,0, 5,0,1, 5,4,0, 5,10,0, 5,10,1, 5,16,0, 5,16,1, 6,9,0, 6,15,0, 7,8,1, 8,0,0, 8,1,0, 8,2,0, 8,7,0, 8,13,0, 8,18,0, 8,19,0, 8,20,0, 9,0,1, 9,6,1, 9,12,1, 10,5,0, 10,5,1, 10,11,0, 10,11,1, 11,4,0, 11,4,1, 11,10,0, 11,10,1, 11,16,0, 11,16,1, 12,3,0, 12,9,0, 13,8,1, 15,0,1, 15,6,1, 15,16,1, 16,5,0, 16,5,1, 16,11,0, 16,11,1, 16,15,0, 17,4,1, 18,8,1, 19,8,1, 20,8,1,
// Length and number of words of that length
4, 20,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,10,0, 0,16,0, 3,7,0, 3,13,0, 4,0,1, 4,17,1, 7,3,1, 7,14,1, 10,0,1, 10,17,1, 13,3,1, 13,14,1, 14,7,0, 14,13,0, 16,0,1, 16,17,1, 17,4,0, 17,10,0, 17,16,0,
// Length and number of words of that length
3, 20,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,11,0, 0,17,0, 3,0,1, 3,18,1, 5,6,1, 6,5,0, 6,9,1, 9,6,0, 9,14,0, 9,18,1, 11,0,1, 12,15,0, 14,9,1, 15,12,1, 17,0,1, 17,18,1, 18,3,0, 18,9,0, 18,17,0,
// End marker
0
};
/*
* Name: 21.05, 21 x 21
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ * * * _ _ _ * * * _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * * * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ * * * _ _ _ * * * _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
*/
const int g34[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
73,
// Black field coordinates
0,6, 0,14, 1,6, 1,14, 2,6, 2,14, 3,3, 3,9, 3,17, 4,4, 4,10, 4,16, 5,5, 5,11, 5,15, 6,0, 6,1, 6,2, 6,6, 6,7, 6,8, 6,12, 6,13, 6,14, 6,18, 6,19, 6,20, 7,6, 7,14, 8,6, 8,14, 9,5, 9,10, 9,17, 10,4, 10,9, 10,10, 10,11, 10,16, 11,3, 11,10, 11,15, 12,6, 12,14, 13,6, 13,14, 14,0, 14,1, 14,2, 14,6, 14,7, 14,8, 14,12, 14,13, 14,14, 14,18, 14,19, 14,20, 15,5, 15,9, 15,15, 16,4, 16,10, 16,16, 17,3, 17,11, 17,17, 18,6, 18,14, 19,6, 19,14, 20,6, 20,14,
// Length and number of words of that length
7, 24,
// Coordinates where words start and direction (0 = horizontal)
0,7,1, 1,7,1, 2,7,1, 3,10,1, 4,3,0, 7,0,0, 7,1,0, 7,2,0, 7,7,0, 7,7,1, 7,8,0, 7,12,0, 7,13,0, 7,18,0, 7,19,0, 7,20,0, 8,7,1, 10,17,0, 12,7,1, 13,7,1, 17,4,1, 18,7,1, 19,7,1, 20,7,1,
// Length and number of words of that length
6, 44,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,7,0, 0,8,0, 0,12,0, 0,13,0, 0,15,1, 0,18,0, 0,19,0, 0,20,0, 1,0,1, 1,15,1, 2,0,1, 2,15,1, 4,9,0, 7,0,1, 7,15,1, 8,0,1, 8,15,1, 9,11,1, 11,4,1, 11,11,0, 12,0,1, 12,15,1, 13,0,1, 13,15,1, 15,0,0, 15,1,0, 15,2,0, 15,7,0, 15,8,0, 15,12,0, 15,13,0, 15,18,0, 15,19,0, 15,20,0, 18,0,1, 18,15,1, 19,0,1, 19,15,1, 20,0,1, 20,15,1,
// Length and number of words of that length
5, 28,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 0,15,0, 3,4,1, 4,5,1, 4,11,1, 4,17,0, 5,0,1, 5,4,0, 5,6,1, 5,16,0, 5,16,1, 6,15,0, 9,0,1, 10,5,0, 11,4,0, 11,16,0, 11,16,1, 12,3,0, 15,0,1, 15,10,1, 15,16,1, 16,5,0, 16,5,1, 16,9,0, 16,11,1, 16,15,0, 17,12,1,
// Length and number of words of that length
4, 20,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,10,0, 0,16,0, 4,0,1, 4,17,1, 5,10,0, 6,11,0, 9,6,1, 10,0,1, 10,5,1, 10,12,1, 10,17,1, 11,9,0, 11,11,1, 12,10,0, 16,0,1, 16,17,1, 17,4,0, 17,10,0, 17,16,0,
// Length and number of words of that length
3, 28,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 0,17,0, 3,0,1, 3,6,0, 3,14,0, 3,18,1, 5,12,1, 6,3,1, 6,5,0, 6,9,1, 6,15,1, 9,6,0, 9,14,0, 9,18,1, 11,0,1, 12,15,0, 14,3,1, 14,9,1, 14,15,1, 15,6,0, 15,6,1, 15,14,0, 17,0,1, 17,18,1, 18,3,0, 18,11,0, 18,17,0,
// End marker
0
};
/*
* Name: 21.06, 21 x 21
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g35[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
68,
// Black field coordinates
0,4, 0,10, 0,16, 1,4, 1,10, 1,16, 2,4, 2,16, 3,8, 3,12, 4,0, 4,1, 4,2, 4,7, 4,13, 4,18, 4,19, 4,20, 5,6, 5,14, 6,5, 6,11, 6,15, 7,4, 7,10, 7,16, 8,3, 8,9, 8,17, 9,6, 9,12, 10,0, 10,1, 10,7, 10,13, 10,19, 10,20, 11,8, 11,14, 12,3, 12,11, 12,17, 13,4, 13,10, 13,16, 14,5, 14,9, 14,15, 15,6, 15,14, 16,0, 16,1, 16,2, 16,7, 16,13, 16,18, 16,19, 16,20, 17,8, 17,12, 18,4, 18,16, 19,4, 19,10, 19,16, 20,4, 20,10, 20,16,
// Length and number of words of that length
11, 4,
// Coordinates where words start and direction (0 = horizontal)
2,5,1, 5,2,0, 5,18,0, 18,5,1,
// Length and number of words of that length
8, 12,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 0,17,0, 3,0,1, 3,13,1, 9,13,1, 11,0,1, 13,3,0, 13,11,0, 13,17,0, 17,0,1, 17,13,1,
// Length and number of words of that length
7, 8,
// Coordinates where words start and direction (0 = horizontal)
4,8,0, 5,7,1, 7,5,0, 7,15,0, 8,10,1, 10,12,0, 12,4,1, 15,7,1,
// Length and number of words of that length
6, 12,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 0,15,0, 5,0,1, 5,15,1, 9,0,1, 11,15,1, 15,0,1, 15,5,0, 15,9,0, 15,15,0, 15,15,1,
// Length and number of words of that length
5, 54,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,6,0, 0,11,1, 0,14,0, 1,5,1, 1,11,1, 2,10,0, 4,8,1, 4,12,0, 5,0,0, 5,1,0, 5,7,0, 5,13,0, 5,19,0, 5,20,0, 6,0,1, 6,6,1, 6,14,0, 6,16,1, 7,5,1, 7,11,0, 7,11,1, 8,4,0, 8,4,1, 8,10,0, 8,16,0, 9,7,1, 9,9,0, 10,2,1, 10,6,0, 10,8,1, 10,14,1, 11,0,0, 11,1,0, 11,7,0, 11,9,1, 11,13,0, 11,19,0, 11,20,0, 12,8,0, 12,12,1, 13,5,1, 13,11,1, 14,0,1, 14,10,0, 14,10,1, 14,16,1, 16,6,0, 16,8,1, 16,14,0, 19,5,1, 19,11,1, 20,5,1, 20,11,1,
// Length and number of words of that length
4, 40,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,7,0, 0,13,0, 0,17,1, 0,18,0, 0,19,0, 0,20,0, 1,0,1, 1,17,1, 2,0,1, 2,17,1, 3,4,0, 3,16,0, 4,3,1, 4,14,1, 7,0,1, 7,17,1, 13,0,1, 13,17,1, 14,4,0, 14,16,0, 16,3,1, 16,14,1, 17,0,0, 17,1,0, 17,2,0, 17,7,0, 17,13,0, 17,18,0, 17,19,0, 17,20,0, 18,0,1, 18,17,1, 19,0,1, 19,17,1, 20,0,1, 20,17,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,12,0, 3,9,1, 6,6,0, 6,12,1, 8,0,1, 8,18,1, 9,3,0, 9,17,0, 12,0,1, 12,14,0, 12,18,1, 14,6,1, 17,9,1, 18,8,0, 18,12,0,
// End marker
0
};
/*
* Name: 21.07, 21 x 21
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ * *)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ _ _ * * * * * _ _ _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (* * _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g36[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
73,
// Black field coordinates
0,4, 0,10, 0,16, 1,4, 1,10, 1,16, 2,10, 3,5, 3,9, 3,15, 4,0, 4,1, 4,6, 4,14, 4,19, 4,20, 5,3, 5,11, 5,17, 6,4, 6,8, 6,12, 6,16, 7,7, 7,13, 8,6, 8,10, 8,14, 9,3, 9,10, 9,15, 10,0, 10,1, 10,2, 10,8, 10,9, 10,10, 10,11, 10,12, 10,18, 10,19, 10,20, 11,5, 11,10, 11,17, 12,6, 12,10, 12,14, 13,7, 13,13, 14,4, 14,8, 14,12, 14,16, 15,3, 15,9, 15,17, 16,0, 16,1, 16,6, 16,14, 16,19, 16,20, 17,5, 17,11, 17,15, 18,10, 19,4, 19,10, 19,16, 20,4, 20,10, 20,16,
// Length and number of words of that length
10, 8,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,18,0, 2,0,1, 2,11,1, 11,2,0, 11,18,0, 18,0,1, 18,11,1,
// Length and number of words of that length
7, 16,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,13,0, 4,5,0, 4,7,1, 5,4,1, 7,0,1, 7,4,0, 7,14,1, 7,16,0, 10,15,0, 13,0,1, 13,14,1, 14,7,0, 14,13,0, 15,10,1, 16,7,1,
// Length and number of words of that length
6, 12,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,12,0, 4,9,0, 8,0,1, 8,15,1, 9,4,1, 11,11,0, 11,11,1, 12,0,1, 12,15,1, 15,8,0, 15,12,0,
// Length and number of words of that length
5, 44,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,5,1, 0,11,0, 0,11,1, 0,17,0, 1,5,1, 1,11,1, 3,0,1, 3,10,0, 3,10,1, 3,16,1, 4,15,0, 5,0,0, 5,1,0, 5,12,1, 5,19,0, 5,20,0, 6,17,0, 7,8,1, 8,7,0, 8,13,0, 9,16,1, 10,3,0, 10,3,1, 10,13,1, 11,0,0, 11,0,1, 11,1,0, 11,19,0, 11,20,0, 12,5,0, 13,8,1, 13,10,0, 15,4,1, 16,3,0, 16,9,0, 16,17,0, 17,0,1, 17,6,1, 17,16,1, 19,5,1, 19,11,1, 20,5,1, 20,11,1,
// Length and number of words of that length
4, 36,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,6,0, 0,14,0, 0,17,1, 0,19,0, 0,20,0, 1,0,1, 1,17,1, 2,4,0, 2,16,0, 4,2,1, 4,15,1, 6,0,1, 6,11,0, 6,17,1, 9,11,1, 11,6,1, 11,9,0, 14,0,1, 14,17,1, 15,4,0, 15,16,0, 16,2,1, 16,15,1, 17,0,0, 17,1,0, 17,6,0, 17,14,0, 17,19,0, 17,20,0, 19,0,1, 19,17,1, 20,0,1, 20,17,1,
// Length and number of words of that length
3, 36,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,9,0, 0,15,0, 3,6,1, 5,0,1, 5,6,0, 5,14,0, 5,18,1, 6,3,0, 6,5,1, 6,9,1, 6,13,1, 7,8,0, 7,12,0, 8,7,1, 8,11,1, 9,0,1, 9,6,0, 9,14,0, 11,8,0, 11,12,0, 11,18,1, 12,7,1, 12,11,1, 12,17,0, 13,6,0, 13,14,0, 14,5,1, 14,9,1, 14,13,1, 15,0,1, 15,18,1, 17,12,1, 18,5,0, 18,11,0, 18,15,0,
// End marker
0
};
/*
* Name: 21.08, 21 x 21
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * * _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * * _ _ _ * * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ * * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g37[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
76,
// Black field coordinates
0,4, 0,10, 0,16, 1,4, 1,10, 1,16, 2,4, 2,10, 2,16, 3,8, 3,14, 4,0, 4,1, 4,2, 4,7, 4,13, 4,18, 4,19, 4,20, 5,6, 5,12, 6,5, 6,6, 6,11, 6,17, 7,4, 7,10, 7,16, 8,3, 8,10, 8,15, 9,8, 9,9, 9,14, 10,0, 10,1, 10,2, 10,7, 10,13, 10,18, 10,19, 10,20, 11,6, 11,11, 11,12, 12,5, 12,10, 12,17, 13,4, 13,10, 13,16, 14,3, 14,9, 14,14, 14,15, 15,8, 15,14, 16,0, 16,1, 16,2, 16,7, 16,13, 16,18, 16,19, 16,20, 17,6, 17,12, 18,4, 18,10, 18,16, 19,4, 19,10, 19,16, 20,4, 20,10, 20,16,
// Length and number of words of that length
9, 2,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 12,11,0,
// Length and number of words of that length
8, 10,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,15,0, 3,0,1, 5,13,1, 9,0,1, 11,13,1, 13,5,0, 13,17,0, 15,0,1, 17,13,1,
// Length and number of words of that length
6, 14,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 0,17,0, 3,15,1, 5,0,1, 8,4,1, 9,15,1, 11,0,1, 12,11,1, 15,3,0, 15,9,0, 15,15,0, 15,15,1, 17,0,1,
// Length and number of words of that length
5, 61,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,6,0, 0,11,1, 0,12,0, 1,5,1, 1,11,1, 2,5,1, 2,11,1, 3,9,1, 4,8,0, 4,8,1, 4,14,0, 5,0,0, 5,1,0, 5,2,0, 5,7,0, 5,7,1, 5,13,0, 5,18,0, 5,19,0, 5,20,0, 6,0,1, 6,12,0, 6,12,1, 7,5,0, 7,5,1, 7,11,1, 7,17,0, 8,4,0, 8,16,0, 8,16,1, 9,3,0, 9,15,0, 10,8,0, 10,8,1, 11,0,0, 11,1,0, 11,2,0, 11,7,0, 11,13,0, 11,18,0, 11,19,0, 11,20,0, 12,0,1, 12,6,0, 12,12,0, 13,5,1, 13,11,1, 14,4,1, 14,16,1, 15,9,1, 16,8,0, 16,8,1, 16,14,0, 17,7,1, 18,5,1, 18,11,1, 19,5,1, 19,11,1, 20,5,1, 20,11,1,
// Length and number of words of that length
4, 54,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,7,0, 0,13,0, 0,17,1, 0,18,0, 0,19,0, 0,20,0, 1,0,1, 1,17,1, 2,0,1, 2,17,1, 3,4,0, 3,10,0, 3,16,0, 4,3,1, 4,14,1, 6,7,1, 7,0,1, 7,6,0, 7,11,0, 7,17,1, 8,11,1, 9,10,1, 10,3,1, 10,9,0, 10,14,0, 10,14,1, 11,7,1, 12,6,1, 13,0,1, 13,17,1, 14,4,0, 14,10,0, 14,10,1, 14,16,0, 16,3,1, 16,14,1, 17,0,0, 17,1,0, 17,2,0, 17,7,0, 17,13,0, 17,18,0, 17,19,0, 17,20,0, 18,0,1, 18,17,1, 19,0,1, 19,17,1, 20,0,1, 20,17,1,
// Length and number of words of that length
3, 9,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,14,0, 6,18,1, 8,0,1, 9,10,0, 12,18,1, 14,0,1, 18,6,0, 18,12,0,
// End marker
0
};
/*
* Name: 21.09, 21 x 21
* (* * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * *)
* (* _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (* _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ *)
* (* * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * *)
*/
const int g38[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
75,
// Black field coordinates
0,0, 0,1, 0,7, 0,13, 0,19, 0,20, 1,0, 1,7, 1,13, 1,20, 2,7, 2,13, 3,3, 3,11, 3,17, 4,4, 4,10, 4,16, 5,5, 5,9, 5,15, 6,8, 6,14, 7,0, 7,1, 7,2, 7,7, 7,13, 7,18, 7,19, 7,20, 8,6, 8,12, 9,5, 9,11, 9,17, 10,4, 10,10, 10,16, 11,3, 11,9, 11,15, 12,8, 12,14, 13,0, 13,1, 13,2, 13,7, 13,13, 13,18, 13,19, 13,20, 14,6, 14,12, 15,5, 15,11, 15,15, 16,4, 16,10, 16,16, 17,3, 17,9, 17,17, 18,7, 18,13, 19,0, 19,7, 19,13, 19,20, 20,0, 20,1, 20,7, 20,13, 20,19, 20,20,
// Length and number of words of that length
8, 8,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,12,0, 6,0,1, 8,13,1, 12,0,1, 13,8,0, 13,14,0, 14,13,1,
// Length and number of words of that length
7, 12,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,18,0, 2,0,1, 2,14,1, 3,4,1, 4,3,0, 10,17,0, 14,2,0, 14,18,0, 17,10,1, 18,0,1, 18,14,1,
// Length and number of words of that length
6, 16,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,14,0, 1,1,0, 1,1,1, 1,14,1, 1,19,0, 6,15,1, 8,0,1, 12,15,1, 14,0,1, 14,1,0, 14,19,0, 15,6,0, 15,12,0, 19,1,1, 19,14,1,
// Length and number of words of that length
5, 72,
// Coordinates where words start and direction (0 = horizontal)
0,2,1, 0,5,0, 0,8,1, 0,9,0, 0,14,1, 0,15,0, 1,8,1, 2,0,0, 2,8,1, 2,20,0, 3,12,1, 4,5,1, 4,11,0, 4,11,1, 4,17,0, 5,0,1, 5,4,0, 5,10,0, 5,10,1, 5,16,0, 5,16,1, 6,9,0, 6,9,1, 6,15,0, 7,8,0, 7,8,1, 7,14,0, 8,0,0, 8,1,0, 8,2,0, 8,7,0, 8,7,1, 8,13,0, 8,18,0, 8,19,0, 8,20,0, 9,0,1, 9,6,0, 9,6,1, 9,12,0, 9,12,1, 10,5,0, 10,5,1, 10,11,0, 10,11,1, 11,4,0, 11,4,1, 11,10,0, 11,10,1, 11,16,0, 11,16,1, 12,3,0, 12,9,0, 12,9,1, 13,8,1, 14,0,0, 14,7,1, 14,20,0, 15,0,1, 15,6,1, 15,16,1, 16,5,0, 16,5,1, 16,11,0, 16,11,1, 16,15,0, 17,4,1, 18,8,1, 19,8,1, 20,2,1, 20,8,1, 20,14,1,
// Length and number of words of that length
4, 20,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,10,0, 0,16,0, 3,7,0, 3,13,0, 4,0,1, 4,17,1, 7,3,1, 7,14,1, 10,0,1, 10,17,1, 13,3,1, 13,14,1, 14,7,0, 14,13,0, 16,0,1, 16,17,1, 17,4,0, 17,10,0, 17,16,0,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,11,0, 0,17,0, 3,0,1, 3,18,1, 5,6,1, 6,5,0, 9,18,1, 11,0,1, 12,15,0, 15,12,1, 17,0,1, 17,18,1, 18,3,0, 18,9,0, 18,17,0,
// End marker
0
};
/*
* Name: 21.10, 21 x 21
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ _ _ * _ _ _ _ _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ _ _ _ _ * _ _ _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
*/
const int g39[] = {
// Width and height of crossword grid
21, 21,
// Number of black fields
58,
// Black field coordinates
0,7, 0,13, 1,7, 1,13, 2,7, 2,13, 3,3, 3,17, 4,4, 4,12, 4,16, 5,5, 5,11, 5,15, 6,6, 6,10, 6,14, 7,0, 7,1, 7,2, 7,9, 7,18, 7,19, 7,20, 8,8, 8,16, 9,7, 9,15, 10,6, 10,14, 11,5, 11,13, 12,4, 12,12, 13,0, 13,1, 13,2, 13,11, 13,18, 13,19, 13,20, 14,6, 14,10, 14,14, 15,5, 15,9, 15,15, 16,4, 16,8, 16,16, 17,3, 17,17, 18,7, 18,13, 19,7, 19,13, 20,7, 20,13,
// Length and number of words of that length
13, 4,
// Coordinates where words start and direction (0 = horizontal)
3,4,1, 4,3,0, 4,17,0, 17,4,1,
// Length and number of words of that length
8, 8,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 3,13,0, 7,10,1, 8,0,1, 10,7,0, 12,13,1, 13,3,1, 13,12,0,
// Length and number of words of that length
7, 42,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,9,0, 0,14,1, 0,18,0, 0,19,0, 0,20,0, 1,0,1, 1,14,1, 2,0,1, 2,14,1, 4,5,1, 5,4,0, 5,12,0, 6,11,0, 7,10,0, 8,9,0, 8,9,1, 9,0,1, 9,8,0, 9,8,1, 9,16,0, 10,7,1, 11,6,1, 11,14,1, 12,5,1, 14,0,0, 14,1,0, 14,2,0, 14,11,0, 14,18,0, 14,19,0, 14,20,0, 16,9,1, 18,0,1, 18,14,1, 19,0,1, 19,14,1, 20,0,1, 20,14,1,
// Length and number of words of that length
6, 16,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,10,0, 0,14,0, 3,7,0, 6,0,1, 6,15,1, 7,3,1, 10,0,1, 10,15,1, 12,13,0, 13,12,1, 14,0,1, 14,15,1, 15,6,0, 15,10,0, 15,14,0,
// Length and number of words of that length
5, 28,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,8,1, 0,11,0, 0,15,0, 1,8,1, 2,8,1, 5,0,1, 5,6,1, 5,16,1, 6,5,0, 8,0,0, 8,1,0, 8,2,0, 8,18,0, 8,19,0, 8,20,0, 9,16,1, 10,15,0, 11,0,1, 15,0,1, 15,10,1, 15,16,1, 16,5,0, 16,9,0, 16,15,0, 18,8,1, 19,8,1, 20,8,1,
// Length and number of words of that length
4, 12,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,12,0, 0,16,0, 4,0,1, 4,17,1, 8,17,1, 12,0,1, 16,0,1, 16,17,1, 17,4,0, 17,8,0, 17,16,0,
// Length and number of words of that length
3, 24,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,17,0, 3,0,1, 3,18,1, 4,13,1, 5,12,1, 5,16,0, 6,7,1, 6,11,1, 6,15,0, 7,6,0, 7,14,0, 11,6,0, 11,14,0, 12,5,0, 13,4,0, 14,7,1, 14,11,1, 15,6,1, 16,5,1, 17,0,1, 17,18,1, 18,3,0, 18,17,0,
// End marker
0
};
/*
* Name: 23.01, 23 x 23
* (_ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ * * _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ _ _ _ * * _ _ _ _ _ _)
* (* * * * _ _ _ * _ _ _ * _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ * * * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ * * _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ * _ _ _ _)
* (* * * _ _ _ _ _ _ _ * * * _ _ _ _ _ _ _ * * *)
* (_ _ _ _ * _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ * * _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * * * _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ * _ _ _ * _ _ _ * * * *)
* (_ _ _ _ _ _ * * _ _ _ _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * * _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _)
*/
const int g40[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
89,
// Black field coordinates
0,5, 0,11, 0,17, 1,5, 1,11, 1,17, 2,5, 2,11, 2,17, 3,4, 3,5, 4,3, 4,8, 4,12, 4,16, 4,21, 4,22, 5,7, 5,15, 6,0, 6,1, 6,6, 6,10, 6,14, 6,18, 7,5, 7,9, 7,13, 7,17, 7,18, 8,3, 8,8, 8,12, 8,19, 9,3, 9,8, 9,21, 9,22, 10,6, 10,11, 10,16, 11,5, 11,6, 11,7, 11,11, 11,15, 11,16, 11,17, 12,6, 12,11, 12,16, 13,0, 13,1, 13,14, 13,19, 14,3, 14,10, 14,14, 14,19, 15,4, 15,5, 15,9, 15,13, 15,17, 16,4, 16,8, 16,12, 16,16, 16,21, 16,22, 17,7, 17,15, 18,0, 18,1, 18,6, 18,10, 18,14, 18,19, 19,17, 19,18, 20,5, 20,11, 20,17, 21,5, 21,11, 21,17, 22,5, 22,11, 22,17,
// Length and number of words of that length
23, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,20,0,
// Length and number of words of that length
17, 2,
// Coordinates where words start and direction (0 = horizontal)
3,6,1, 19,0,1,
// Length and number of words of that length
12, 2,
// Coordinates where words start and direction (0 = horizontal)
9,9,1, 13,2,1,
// Length and number of words of that length
11, 2,
// Coordinates where words start and direction (0 = horizontal)
4,4,0, 8,18,0,
// Length and number of words of that length
8, 2,
// Coordinates where words start and direction (0 = horizontal)
0,19,0, 15,3,0,
// Length and number of words of that length
7, 16,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 0,13,0, 3,11,0, 5,0,1, 5,8,1, 5,16,1, 7,10,0, 8,9,0, 8,13,0, 9,12,0, 13,11,0, 16,9,0, 16,13,0, 17,0,1, 17,8,1, 17,16,1,
// Length and number of words of that length
6, 24,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,6,0, 0,10,0, 0,14,0, 0,18,0, 7,0,0, 7,1,0, 7,14,0, 8,13,1, 10,0,1, 10,8,0, 10,17,1, 10,21,0, 10,22,0, 12,0,1, 12,17,1, 14,4,1, 17,4,0, 17,8,0, 17,12,0, 17,16,0, 17,21,0, 17,22,0,
// Length and number of words of that length
5, 38,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,6,1, 0,7,0, 0,12,1, 0,15,0, 0,18,1, 1,0,1, 1,6,1, 1,12,1, 1,18,1, 2,0,1, 2,6,1, 2,12,1, 2,18,1, 5,16,0, 6,7,0, 6,15,0, 7,0,1, 11,0,1, 11,18,1, 12,7,0, 12,15,0, 13,6,0, 15,18,1, 18,7,0, 18,15,0, 20,0,1, 20,6,1, 20,12,1, 20,18,1, 21,0,1, 21,6,1, 21,12,1, 21,18,1, 22,0,1, 22,6,1, 22,12,1, 22,18,1,
// Length and number of words of that length
4, 40,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,8,0, 0,12,0, 0,16,0, 0,21,0, 0,22,0, 3,0,1, 3,17,0, 4,4,1, 4,17,1, 5,21,0, 5,22,0, 6,2,1, 6,19,1, 7,19,1, 8,4,1, 9,4,1, 9,19,0, 10,3,0, 10,7,1, 10,12,1, 12,7,1, 12,12,1, 13,15,1, 14,0,0, 14,1,0, 14,15,1, 15,0,1, 16,0,1, 16,5,0, 16,17,1, 18,2,1, 18,15,1, 19,0,0, 19,1,0, 19,6,0, 19,10,0, 19,14,0, 19,19,0, 19,19,1,
// Length and number of words of that length
3, 44,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 4,0,1, 4,5,0, 4,9,1, 4,13,1, 5,3,0, 5,8,0, 5,12,0, 6,7,1, 6,11,1, 6,15,1, 7,6,0, 7,6,1, 7,10,1, 7,14,1, 8,0,1, 8,5,0, 8,9,1, 8,17,0, 8,20,1, 9,0,1, 11,8,1, 11,12,1, 12,5,0, 12,17,0, 13,16,0, 13,20,1, 14,0,1, 14,11,1, 14,20,1, 15,6,1, 15,10,0, 15,10,1, 15,14,0, 15,14,1, 15,19,0, 16,5,1, 16,9,1, 16,13,1, 16,17,0, 18,7,1, 18,11,1, 18,20,1, 20,18,0,
// End marker
0
};
/*
* Name: 23.02, 23 x 23
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ *)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ * * _ _ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (* * * _ _ _ * _ _ _ _ * * _ _ _ * * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _)
* (* * _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ * *)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * * _ _ _ * * _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ * * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _ _ * * _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (* _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
*/
const int g41[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
94,
// Black field coordinates
0,5, 0,10, 0,16, 0,22, 1,5, 1,10, 1,16, 2,5, 2,16, 3,3, 3,9, 3,14, 3,19, 4,3, 4,7, 4,8, 4,13, 4,18, 5,0, 5,1, 5,6, 5,12, 5,17, 6,5, 6,17, 6,21, 6,22, 7,4, 7,10, 7,11, 7,15, 7,16, 8,4, 8,9, 8,19, 9,8, 9,13, 9,14, 9,18, 10,0, 10,1, 10,2, 10,6, 10,7, 10,12, 10,17, 11,5, 11,17, 12,5, 12,10, 12,15, 12,16, 12,20, 12,21, 12,22, 13,4, 13,8, 13,9, 13,14, 14,3, 14,13, 14,18, 15,6, 15,7, 15,11, 15,12, 15,18, 16,0, 16,1, 16,5, 16,17, 17,5, 17,10, 17,16, 17,21, 17,22, 18,4, 18,9, 18,14, 18,15, 18,19, 19,3, 19,8, 19,13, 19,19, 20,6, 20,17, 21,6, 21,12, 21,17, 22,0, 22,6, 22,12, 22,17,
// Length and number of words of that length
12, 2,
// Coordinates where words start and direction (0 = horizontal)
0,20,0, 11,2,0,
// Length and number of words of that length
11, 3,
// Coordinates where words start and direction (0 = horizontal)
6,6,1, 11,6,1, 16,6,1,
// Length and number of words of that length
10, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,6,1, 13,20,0, 20,7,1,
// Length and number of words of that length
9, 4,
// Coordinates where words start and direction (0 = horizontal)
5,3,0, 8,10,1, 9,19,0, 14,4,1,
// Length and number of words of that length
8, 2,
// Coordinates where words start and direction (0 = horizontal)
9,0,1, 13,15,1,
// Length and number of words of that length
7, 7,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,11,0, 0,15,0, 8,11,0, 16,7,0, 16,11,0, 16,18,0,
// Length and number of words of that length
6, 8,
// Coordinates where words start and direction (0 = horizontal)
0,21,0, 1,17,1, 2,17,1, 7,17,1, 15,0,1, 17,1,0, 20,0,1, 21,0,1,
// Length and number of words of that length
5, 48,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,6,0, 0,11,1, 0,12,0, 0,17,0, 0,17,1, 1,0,1, 1,11,1, 1,22,0, 2,0,1, 2,10,0, 3,4,1, 4,14,0, 5,7,0, 5,7,1, 5,18,1, 6,0,1, 7,5,1, 7,21,0, 7,22,0, 10,18,1, 11,0,0, 11,0,1, 11,1,0, 11,18,1, 12,0,1, 13,15,0, 14,8,0, 15,13,1, 16,12,0, 16,18,1, 17,0,0, 17,0,1, 17,11,1, 18,5,0, 18,10,0, 18,16,0, 18,21,0, 18,22,0, 19,14,1, 20,18,1, 21,7,1, 21,18,1, 22,1,1, 22,7,1, 22,18,1,
// Length and number of words of that length
4, 72,
// Coordinates where words start and direction (0 = horizontal)
0,6,1, 0,7,0, 0,8,0, 0,13,0, 0,18,0, 1,6,1, 3,10,1, 3,15,1, 3,16,0, 4,9,0, 4,9,1, 4,14,1, 4,19,0, 4,19,1, 5,2,1, 5,8,0, 5,13,0, 5,13,1, 5,18,0, 6,0,0, 6,1,0, 6,6,0, 6,12,0, 7,0,1, 7,5,0, 8,0,1, 8,5,1, 8,10,0, 8,15,0, 8,16,0, 9,4,0, 9,9,0, 9,9,1, 9,19,1, 10,8,1, 10,13,0, 10,13,1, 10,18,0, 11,6,0, 11,7,0, 11,12,0, 12,6,1, 12,11,1, 12,17,0, 13,0,1, 13,10,0, 13,10,1, 13,16,0, 13,21,0, 13,22,0, 14,4,0, 14,9,0, 14,14,0, 14,14,1, 14,19,1, 15,3,0, 15,13,0, 15,19,1, 16,6,0, 17,6,1, 17,17,1, 18,0,1, 18,5,1, 18,10,1, 19,4,0, 19,4,1, 19,9,0, 19,9,1, 19,14,0, 19,15,0, 21,13,1, 22,13,1,
// Length and number of words of that length
3, 32,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 0,14,0, 0,19,0, 3,0,1, 3,5,0, 3,20,1, 4,0,1, 4,4,1, 6,18,1, 7,12,1, 7,17,0, 8,20,1, 9,15,1, 10,3,1, 10,8,0, 10,14,0, 12,17,1, 13,5,0, 13,5,1, 14,0,1, 15,8,1, 16,2,1, 17,17,0, 18,16,1, 18,20,1, 19,0,1, 19,20,1, 20,3,0, 20,8,0, 20,13,0, 20,19,0,
// End marker
0
};
/*
* Name: 23.03, 23 x 23
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ * * _ _ _ * * * _ _ _ _ _ _ _ * _ _ _ _)
* (* * * _ _ _ _ _ _ _ * _ _ _ _ _ * * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * * _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * * _ _ _ _ _ * _ _ _ _ _ _)
* (* * _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ * * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * * _ _ _ _ _ * _ _ _ _ _ _ _ * * *)
* (_ _ _ _ * _ _ _ _ _ _ _ * * * _ _ _ * * _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
*/
const int g42[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
89,
// Black field coordinates
0,5, 0,11, 0,16, 1,5, 1,11, 1,16, 2,5, 2,16, 3,4, 3,10, 3,15, 4,4, 4,8, 4,13, 4,14, 4,18, 4,19, 5,11, 5,17, 5,21, 5,22, 6,0, 6,1, 6,6, 6,7, 6,12, 6,17, 7,3, 7,9, 7,16, 8,4, 8,9, 9,4, 9,10, 9,14, 9,19, 10,4, 10,5, 10,10, 10,15, 10,20, 10,21, 10,22, 11,6, 11,11, 11,16, 12,0, 12,1, 12,2, 12,7, 12,12, 12,17, 12,18, 13,3, 13,8, 13,12, 13,18, 14,13, 14,18, 15,6, 15,13, 15,19, 16,5, 16,10, 16,15, 16,16, 16,21, 16,22, 17,0, 17,1, 17,5, 17,11, 18,3, 18,4, 18,8, 18,9, 18,14, 18,18, 19,7, 19,12, 19,18, 20,6, 20,17, 21,6, 21,11, 21,17, 22,6, 22,11, 22,17,
// Length and number of words of that length
13, 2,
// Coordinates where words start and direction (0 = horizontal)
8,10,1, 14,0,1,
// Length and number of words of that length
12, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 11,20,0,
// Length and number of words of that length
11, 2,
// Coordinates where words start and direction (0 = horizontal)
5,0,1, 17,12,1,
// Length and number of words of that length
10, 4,
// Coordinates where words start and direction (0 = horizontal)
0,20,0, 2,6,1, 13,2,0, 20,7,1,
// Length and number of words of that length
9, 2,
// Coordinates where words start and direction (0 = horizontal)
5,13,0, 9,9,0,
// Length and number of words of that length
8, 2,
// Coordinates where words start and direction (0 = horizontal)
5,8,0, 10,14,0,
// Length and number of words of that length
7, 10,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 3,5,0, 3,16,1, 5,18,0, 11,4,0, 13,17,0, 16,13,0, 16,19,0, 19,0,1,
// Length and number of words of that length
6, 24,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,6,0, 0,7,0, 0,12,0, 0,17,1, 1,17,1, 2,17,1, 4,15,0, 7,10,1, 7,17,1, 11,0,1, 11,17,1, 13,7,0, 15,0,1, 15,7,1, 17,10,0, 17,15,0, 17,16,0, 17,21,0, 17,22,0, 20,0,1, 21,0,1, 22,0,1,
// Length and number of words of that length
5, 42,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,6,1, 0,17,0, 0,21,0, 0,22,0, 1,0,1, 1,6,1, 2,0,1, 3,5,1, 4,10,0, 5,12,1, 6,11,0, 6,18,1, 7,0,0, 7,1,0, 7,4,1, 7,7,0, 7,12,0, 7,17,0, 8,3,0, 9,5,1, 10,19,0, 11,5,0, 11,10,0, 11,15,0, 11,21,0, 11,22,0, 12,11,0, 13,13,1, 14,12,0, 15,14,1, 16,0,1, 17,6,1, 18,0,0, 18,1,0, 18,5,0, 19,13,1, 20,18,1, 21,12,1, 21,18,1, 22,12,1, 22,18,1,
// Length and number of words of that length
4, 58,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,12,1, 0,13,0, 0,14,0, 0,18,0, 0,19,0, 1,12,1, 3,0,1, 3,11,1, 3,16,0, 4,0,1, 4,9,1, 5,14,0, 5,19,0, 6,2,1, 6,8,1, 6,13,1, 6,21,0, 6,22,0, 7,6,0, 8,0,1, 8,5,1, 9,0,1, 9,15,1, 10,0,1, 10,6,1, 10,11,1, 10,16,1, 11,7,1, 11,12,1, 12,3,1, 12,8,1, 12,13,1, 12,16,0, 12,19,1, 13,0,0, 13,1,0, 13,4,1, 13,19,1, 14,3,0, 14,8,0, 14,14,1, 14,19,1, 16,6,0, 16,6,1, 16,11,1, 16,17,1, 18,10,1, 18,19,1, 19,3,0, 19,4,0, 19,8,0, 19,8,1, 19,9,0, 19,14,0, 19,19,1, 21,7,1, 22,7,1,
// Length and number of words of that length
3, 26,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,10,0, 0,15,0, 2,11,0, 4,5,1, 4,15,1, 4,20,1, 5,4,0, 5,18,1, 7,0,1, 8,16,0, 9,11,1, 9,20,1, 12,6,0, 13,0,1, 13,9,1, 15,18,0, 15,20,1, 17,2,1, 18,0,1, 18,5,1, 18,11,0, 18,15,1, 20,7,0, 20,12,0, 20,18,0,
// End marker
0
};
/*
* Name: 23.04, 23 x 23
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
*/
const int g43[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
80,
// Black field coordinates
0,5, 0,11, 0,17, 1,5, 1,11, 1,17, 2,5, 2,11, 2,17, 3,9, 3,13, 4,8, 4,14, 5,0, 5,1, 5,2, 5,7, 5,15, 5,20, 5,21, 5,22, 6,6, 6,10, 6,16, 7,5, 7,11, 7,17, 8,4, 8,12, 8,18, 9,3, 9,9, 9,13, 9,19, 10,8, 10,16, 11,0, 11,1, 11,2, 11,7, 11,15, 11,20, 11,21, 11,22, 12,6, 12,14, 13,3, 13,9, 13,13, 13,19, 14,4, 14,10, 14,18, 15,5, 15,11, 15,17, 16,6, 16,12, 16,16, 17,0, 17,1, 17,2, 17,7, 17,15, 17,20, 17,21, 17,22, 18,8, 18,14, 19,9, 19,13, 20,5, 20,11, 20,17, 21,5, 21,11, 21,17, 22,5, 22,11, 22,17,
// Length and number of words of that length
9, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,19,0, 3,0,1, 3,14,1, 14,3,0, 14,19,0, 19,0,1, 19,14,1,
// Length and number of words of that length
8, 12,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,12,0, 0,18,0, 4,0,1, 4,15,1, 10,0,1, 12,15,1, 15,4,0, 15,10,0, 15,18,0, 18,0,1, 18,15,1,
// Length and number of words of that length
7, 14,
// Coordinates where words start and direction (0 = horizontal)
5,8,1, 5,14,0, 7,10,0, 8,5,0, 8,5,1, 8,11,0, 8,17,0, 9,12,0, 10,9,1, 11,8,0, 11,8,1, 12,7,1, 14,11,1, 17,8,1,
// Length and number of words of that length
6, 12,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,10,0, 0,16,0, 6,0,1, 6,17,1, 10,17,1, 12,0,1, 16,0,1, 16,17,1, 17,6,0, 17,12,0, 17,16,0,
// Length and number of words of that length
5, 84,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,6,1, 0,7,0, 0,12,1, 0,15,0, 0,18,1, 0,20,0, 0,21,0, 0,22,0, 1,0,1, 1,6,1, 1,12,1, 1,18,1, 2,0,1, 2,6,1, 2,12,1, 2,18,1, 4,9,0, 4,9,1, 4,13,0, 5,8,0, 6,0,0, 6,1,0, 6,2,0, 6,7,0, 6,11,1, 6,15,0, 6,20,0, 6,21,0, 6,22,0, 7,0,1, 7,6,0, 7,6,1, 7,12,1, 7,18,1, 8,13,1, 9,4,0, 9,4,1, 9,14,1, 9,18,0, 11,16,0, 12,0,0, 12,1,0, 12,2,0, 12,7,0, 12,15,0, 12,20,0, 12,21,0, 12,22,0, 13,4,1, 13,14,0, 13,14,1, 14,5,1, 14,9,0, 14,13,0, 15,0,1, 15,6,1, 15,12,1, 15,18,1, 16,7,1, 18,0,0, 18,1,0, 18,2,0, 18,7,0, 18,9,1, 18,15,0, 18,20,0, 18,21,0, 18,22,0, 20,0,1, 20,6,1, 20,12,1, 20,18,1, 21,0,1, 21,6,1, 21,12,1, 21,18,1, 22,0,1, 22,6,1, 22,12,1, 22,18,1,
// Length and number of words of that length
4, 20,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,14,0, 3,5,0, 3,11,0, 3,17,0, 5,3,1, 5,16,1, 8,0,1, 8,19,1, 11,3,1, 11,16,1, 14,0,1, 14,19,1, 16,5,0, 16,11,0, 16,17,0, 17,3,1, 17,16,1, 19,8,0, 19,14,0,
// Length and number of words of that length
3, 20,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 0,13,0, 3,10,1, 6,7,1, 7,16,0, 9,0,1, 9,10,1, 9,20,1, 10,3,0, 10,9,0, 10,13,0, 10,19,0, 13,0,1, 13,6,0, 13,10,1, 13,20,1, 16,13,1, 19,10,1, 20,9,0, 20,13,0,
// End marker
0
};
/*
* Name: 23.05, 23 x 23
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
*/
const int g44[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
84,
// Black field coordinates
0,5, 0,11, 0,17, 1,5, 1,11, 1,17, 2,5, 2,11, 2,17, 3,3, 3,8, 3,14, 3,19, 4,7, 4,15, 5,0, 5,1, 5,6, 5,12, 5,16, 5,20, 5,21, 5,22, 6,5, 6,11, 6,17, 7,4, 7,10, 7,18, 8,3, 8,9, 8,14, 8,19, 9,8, 9,13, 10,7, 10,12, 10,17, 11,0, 11,1, 11,2, 11,6, 11,16, 11,20, 11,21, 11,22, 12,5, 12,10, 12,15, 13,9, 13,14, 14,3, 14,8, 14,13, 14,19, 15,4, 15,12, 15,18, 16,5, 16,11, 16,17, 17,0, 17,1, 17,2, 17,6, 17,10, 17,16, 17,21, 17,22, 18,7, 18,15, 19,3, 19,8, 19,14, 19,19, 20,5, 20,11, 20,17, 21,5, 21,11, 21,17, 22,5, 22,11, 22,17,
// Length and number of words of that length
11, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 12,20,0,
// Length and number of words of that length
9, 6,
// Coordinates where words start and direction (0 = horizontal)
0,13,0, 7,11,0, 9,14,1, 11,7,1, 13,0,1, 14,9,0,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 9,0,1, 13,15,1, 15,13,0,
// Length and number of words of that length
7, 20,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,10,0, 0,18,0, 4,0,1, 4,8,1, 4,16,1, 5,15,0, 7,11,1, 8,4,0, 8,18,0, 10,0,1, 11,7,0, 12,16,1, 15,5,1, 16,4,0, 16,12,0, 16,18,0, 18,0,1, 18,8,1, 18,16,1,
// Length and number of words of that length
5, 80,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,6,0, 0,6,1, 0,12,0, 0,12,1, 0,16,0, 0,18,1, 0,20,0, 0,21,0, 0,22,0, 1,0,1, 1,6,1, 1,12,1, 1,18,1, 2,0,1, 2,6,1, 2,12,1, 2,18,1, 3,9,1, 4,8,0, 5,7,0, 5,7,1, 6,0,0, 6,0,1, 6,1,0, 6,6,0, 6,6,1, 6,12,1, 6,16,0, 6,18,1, 6,20,0, 6,21,0, 6,22,0, 7,5,0, 7,5,1, 8,4,1, 9,3,0, 9,19,0, 10,18,1, 11,17,0, 12,0,0, 12,0,1, 12,1,0, 12,2,0, 12,6,0, 12,16,0, 12,21,0, 12,22,0, 13,15,0, 14,14,0, 14,14,1, 15,13,1, 16,0,1, 16,6,1, 16,12,1, 16,18,1, 17,11,1, 18,0,0, 18,1,0, 18,2,0, 18,6,0, 18,10,0, 18,16,0, 18,21,0, 18,22,0, 19,9,1, 20,0,1, 20,6,1, 20,12,1, 20,18,1, 21,0,1, 21,6,1, 21,12,1, 21,18,1, 22,0,1, 22,6,1, 22,12,1, 22,18,1,
// Length and number of words of that length
4, 38,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,15,0, 3,4,1, 3,15,1, 4,3,0, 4,14,0, 4,19,0, 5,2,1, 6,12,0, 7,0,1, 7,19,1, 8,10,0, 8,10,1, 8,15,1, 9,9,0, 9,9,1, 9,14,0, 10,8,0, 10,8,1, 10,13,0, 10,13,1, 11,12,0, 12,6,1, 12,11,1, 13,10,0, 13,10,1, 14,4,1, 14,9,1, 15,0,1, 15,3,0, 15,8,0, 15,19,0, 15,19,1, 17,17,1, 19,4,1, 19,7,0, 19,15,0, 19,15,1,
// Length and number of words of that length
3, 30,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,8,0, 0,14,0, 0,19,0, 3,0,1, 3,5,0, 3,11,0, 3,17,0, 3,20,1, 5,13,1, 5,17,1, 7,17,0, 8,0,1, 8,20,1, 11,3,1, 11,17,1, 13,5,0, 14,0,1, 14,20,1, 17,3,1, 17,5,0, 17,7,1, 17,11,0, 17,17,0, 19,0,1, 19,20,1, 20,3,0, 20,8,0, 20,14,0, 20,19,0,
// End marker
0
};
/*
* Name: 23.06, 23 x 23
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * * * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
*/
const int g45[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
69,
// Black field coordinates
0,7, 0,15, 1,7, 1,15, 2,7, 2,15, 3,3, 3,12, 3,19, 4,4, 4,11, 4,18, 5,5, 5,10, 5,17, 6,8, 6,14, 7,0, 7,1, 7,2, 7,7, 7,15, 7,20, 7,21, 7,22, 8,6, 8,16, 9,9, 9,13, 10,3, 10,11, 10,17, 11,4, 11,10, 11,11, 11,12, 11,18, 12,5, 12,11, 12,19, 13,9, 13,13, 14,6, 14,16, 15,0, 15,1, 15,2, 15,7, 15,15, 15,20, 15,21, 15,22, 16,8, 16,14, 17,5, 17,12, 17,17, 18,4, 18,11, 18,18, 19,3, 19,10, 19,19, 20,7, 20,15, 21,7, 21,15, 22,7, 22,15,
// Length and number of words of that length
9, 12,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 0,13,0, 7,8,0, 7,14,0, 8,7,1, 9,0,1, 9,14,1, 13,0,1, 13,14,1, 14,7,1, 14,9,0, 14,13,0,
// Length and number of words of that length
8, 12,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,16,0, 3,4,1, 4,19,0, 6,0,1, 6,15,1, 11,3,0, 15,6,0, 15,16,0, 16,0,1, 16,15,1, 19,11,1,
// Length and number of words of that length
7, 44,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,8,1, 0,16,1, 0,20,0, 0,21,0, 0,22,0, 1,0,1, 1,8,1, 1,16,1, 2,0,1, 2,8,1, 2,16,1, 4,12,0, 7,8,1, 8,0,0, 8,1,0, 8,2,0, 8,7,0, 8,15,0, 8,20,0, 8,21,0, 8,22,0, 10,4,1, 12,10,0, 12,12,1, 15,8,1, 16,0,0, 16,1,0, 16,2,0, 16,20,0, 16,21,0, 16,22,0, 20,0,1, 20,8,1, 20,16,1, 21,0,1, 21,8,1, 21,16,1, 22,0,1, 22,8,1, 22,16,1,
// Length and number of words of that length
6, 24,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,14,0, 3,13,1, 4,3,0, 4,5,1, 4,12,1, 5,4,0, 5,11,1, 5,18,0, 6,5,0, 8,0,1, 8,17,1, 11,17,0, 12,4,0, 12,18,0, 13,19,0, 14,0,1, 14,17,1, 17,6,1, 17,8,0, 17,14,0, 18,5,1, 18,12,1, 19,4,1,
// Length and number of words of that length
5, 24,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,10,0, 0,17,0, 5,0,1, 5,11,0, 5,18,1, 6,9,1, 6,10,0, 9,6,0, 9,16,0, 10,12,1, 10,18,1, 11,5,1, 11,13,1, 12,0,1, 12,6,1, 12,12,0, 13,11,0, 16,9,1, 17,0,1, 17,18,1, 18,5,0, 18,12,0, 18,17,0,
// Length and number of words of that length
4, 24,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,11,0, 0,18,0, 3,7,0, 3,15,0, 4,0,1, 4,19,1, 5,6,1, 6,17,0, 7,3,1, 7,16,1, 11,0,1, 11,19,1, 13,5,0, 15,3,1, 15,16,1, 16,7,0, 16,15,0, 17,13,1, 18,0,1, 18,19,1, 19,4,0, 19,11,0, 19,18,0,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,12,0, 0,19,0, 3,0,1, 3,20,1, 9,10,1, 10,0,1, 10,9,0, 10,13,0, 12,20,1, 13,10,1, 19,0,1, 19,20,1, 20,3,0, 20,10,0, 20,19,0,
// End marker
0
};
/*
* Name: 23.07, 23 x 23
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ *)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * * _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (* * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * *)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (* * * _ _ _ * _ _ _ _ * * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (* _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g46[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
83,
// Black field coordinates
0,4, 0,10, 0,16, 0,22, 1,4, 1,10, 1,16, 2,4, 2,16, 3,8, 3,14, 3,19, 4,0, 4,1, 4,7, 4,13, 4,18, 5,6, 5,12, 5,17, 6,5, 6,10, 6,11, 6,16, 6,21, 6,22, 7,4, 7,15, 8,3, 8,9, 8,14, 8,19, 9,8, 9,18, 10,0, 10,1, 10,2, 10,6, 10,12, 10,17, 11,6, 11,11, 11,16, 12,5, 12,10, 12,16, 12,20, 12,21, 12,22, 13,4, 13,14, 14,3, 14,8, 14,13, 14,19, 15,7, 15,18, 16,0, 16,1, 16,6, 16,11, 16,12, 16,17, 17,5, 17,10, 17,16, 18,4, 18,9, 18,15, 18,21, 18,22, 19,3, 19,8, 19,14, 20,6, 20,18, 21,6, 21,12, 21,18, 22,0, 22,6, 22,12, 22,18,
// Length and number of words of that length
12, 2,
// Coordinates where words start and direction (0 = horizontal)
0,20,0, 11,2,0,
// Length and number of words of that length
11, 2,
// Coordinates where words start and direction (0 = horizontal)
2,5,1, 20,7,1,
// Length and number of words of that length
10, 6,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 5,7,0, 7,5,1, 8,15,0, 13,20,0, 15,8,1,
// Length and number of words of that length
9, 4,
// Coordinates where words start and direction (0 = horizontal)
5,13,0, 9,9,0, 9,9,1, 13,5,1,
// Length and number of words of that length
8, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 3,0,1, 9,0,1, 13,15,1, 15,13,0, 15,19,0, 19,15,1,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
0,15,0, 7,16,1, 15,0,1, 16,7,0,
// Length and number of words of that length
6, 14,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 0,21,0, 1,17,1, 2,17,1, 5,0,1, 11,0,1, 11,17,1, 17,1,0, 17,11,0, 17,17,0, 17,17,1, 20,0,1, 21,0,1,
// Length and number of words of that length
5, 54,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,6,0, 0,11,1, 0,12,0, 0,17,0, 0,17,1, 1,5,1, 1,11,1, 1,22,0, 3,9,1, 4,2,1, 4,8,0, 4,8,1, 5,0,0, 5,1,0, 5,7,1, 5,18,1, 6,0,1, 7,5,0, 7,10,0, 7,21,0, 7,22,0, 8,4,0, 8,4,1, 9,3,0, 9,19,0, 10,7,1, 10,18,0, 10,18,1, 11,0,0, 11,1,0, 11,12,0, 11,17,0, 12,0,1, 12,11,1, 13,21,0, 13,22,0, 14,14,0, 14,14,1, 16,18,1, 17,0,0, 17,0,1, 17,11,1, 18,5,0, 18,10,0, 18,10,1, 18,16,0, 18,16,1, 19,9,1, 21,7,1, 21,13,1, 22,1,1, 22,7,1, 22,13,1,
// Length and number of words of that length
4, 64,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,7,0, 0,13,0, 0,18,0, 1,0,1, 2,0,1, 2,10,0, 3,4,0, 3,15,1, 4,14,0, 4,14,1, 4,19,0, 4,19,1, 5,13,1, 5,18,0, 6,6,0, 6,6,1, 6,12,0, 6,12,1, 6,17,0, 6,17,1, 7,0,1, 7,11,0, 7,16,0, 8,10,1, 8,15,1, 9,14,0, 9,19,1, 10,8,0, 10,13,1, 11,7,1, 11,12,1, 12,6,0, 12,6,1, 12,11,0, 13,0,1, 13,5,0, 13,10,0, 13,16,0, 14,4,0, 14,4,1, 14,9,1, 15,3,0, 15,8,0, 15,19,1, 16,2,1, 16,7,1, 16,13,1, 16,18,0, 17,6,1, 17,12,0, 18,0,1, 18,5,1, 19,4,0, 19,4,1, 19,9,0, 19,15,0, 19,21,0, 19,22,0, 20,19,1, 21,19,1, 22,19,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,14,0, 0,19,0, 3,16,0, 3,20,1, 8,0,1, 8,20,1, 10,3,1, 12,17,1, 14,0,1, 14,20,1, 17,6,0, 19,0,1, 20,3,0, 20,8,0, 20,14,0,
// End marker
0
};
/*
* Name: 23.08, 23 x 23
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * * *)
* (_ _ _ * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _)
* (* * * _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
*/
const int g47[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
75,
// Black field coordinates
0,7, 0,15, 1,7, 1,15, 2,7, 2,15, 3,3, 3,8, 3,13, 3,19, 4,4, 4,12, 4,18, 5,5, 5,10, 5,17, 6,6, 6,11, 6,16, 7,0, 7,1, 7,2, 7,9, 7,15, 7,20, 7,21, 7,22, 8,3, 8,8, 8,14, 9,7, 9,13, 9,19, 10,5, 10,12, 10,18, 11,6, 11,11, 11,16, 12,4, 12,10, 12,17, 13,3, 13,9, 13,15, 14,8, 14,14, 14,19, 15,0, 15,1, 15,2, 15,7, 15,13, 15,20, 15,21, 15,22, 16,6, 16,11, 16,16, 17,5, 17,12, 17,17, 18,4, 18,10, 18,18, 19,3, 19,9, 19,14, 19,19, 20,7, 20,15, 21,7, 21,15, 22,7, 22,15,
// Length and number of words of that length
8, 4,
// Coordinates where words start and direction (0 = horizontal)
0,14,0, 8,15,1, 14,0,1, 15,8,0,
// Length and number of words of that length
7, 44,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,8,1, 0,9,0, 0,16,1, 0,20,0, 0,21,0, 0,22,0, 1,0,1, 1,8,1, 1,16,1, 2,0,1, 2,8,1, 2,16,1, 4,5,1, 5,4,0, 8,0,0, 8,1,0, 8,2,0, 8,20,0, 8,21,0, 8,22,0, 9,0,1, 11,18,0, 13,16,1, 16,0,0, 16,1,0, 16,2,0, 16,13,0, 16,20,0, 16,21,0, 16,22,0, 18,11,1, 20,0,1, 20,8,1, 20,16,1, 21,0,1, 21,8,1, 21,16,1, 22,0,1, 22,8,1, 22,16,1,
// Length and number of words of that length
6, 24,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,11,0, 0,16,0, 3,7,0, 5,11,1, 6,0,1, 6,10,0, 6,17,0, 6,17,1, 7,3,1, 10,6,1, 11,0,1, 11,5,0, 11,12,0, 11,17,1, 12,11,1, 14,15,0, 15,14,1, 16,0,1, 16,17,1, 17,6,0, 17,6,1, 17,11,0, 17,16,0,
// Length and number of words of that length
5, 40,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,10,0, 0,17,0, 3,14,1, 4,13,0, 4,13,1, 4,19,0, 5,0,1, 5,12,0, 5,18,0, 5,18,1, 7,10,1, 8,9,0, 8,9,1, 8,15,0, 9,8,0, 9,8,1, 9,14,0, 9,14,1, 10,0,1, 10,7,0, 10,13,0, 10,13,1, 12,5,1, 12,18,1, 13,4,0, 13,4,1, 13,10,0, 13,10,1, 14,3,0, 14,9,0, 14,9,1, 15,8,1, 17,0,1, 17,18,1, 18,5,0, 18,5,1, 18,12,0, 18,17,0, 19,4,1,
// Length and number of words of that length
4, 44,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,12,0, 0,18,0, 3,4,1, 3,9,1, 3,15,0, 4,0,1, 4,3,0, 4,8,0, 4,19,1, 5,6,1, 6,5,0, 6,7,1, 6,12,1, 7,6,0, 7,11,0, 7,16,0, 7,16,1, 8,4,1, 9,3,0, 10,19,0, 10,19,1, 11,7,1, 11,12,1, 12,0,1, 12,6,0, 12,11,0, 12,16,0, 13,17,0, 14,15,1, 15,3,1, 15,14,0, 15,19,0, 16,7,0, 16,7,1, 16,12,1, 17,13,1, 18,0,1, 18,19,1, 19,4,0, 19,10,0, 19,10,1, 19,15,1, 19,18,0,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,8,0, 0,13,0, 0,19,0, 3,0,1, 3,20,1, 8,0,1, 9,20,1, 13,0,1, 14,20,1, 19,0,1, 19,20,1, 20,3,0, 20,9,0, 20,14,0, 20,19,0,
// End marker
0
};
/*
* Name: 23.09, 23 x 23
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _)
* (* * * _ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ *)
* (_ _ _ * _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _)
* (* * _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ * *)
* (_ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ * _ _ _)
* (* _ _ _ * _ _ _ * _ _ _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ * _ _ _ _ _ * _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
*/
const int g48[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
76,
// Black field coordinates
0,5, 0,11, 0,17, 1,5, 1,11, 2,5, 3,6, 3,12, 3,18, 4,3, 4,9, 4,13, 4,17, 5,0, 5,4, 5,8, 5,14, 5,20, 5,21, 5,22, 6,7, 6,15, 6,19, 7,6, 7,10, 7,16, 8,5, 8,11, 8,17, 9,4, 9,12, 9,18, 10,3, 10,9, 10,15, 11,0, 11,1, 11,8, 11,14, 11,21, 11,22, 12,7, 12,13, 12,19, 13,4, 13,10, 13,18, 14,5, 14,11, 14,17, 15,6, 15,12, 15,16, 16,3, 16,7, 16,15, 17,0, 17,1, 17,2, 17,8, 17,14, 17,18, 17,22, 18,5, 18,9, 18,13, 18,19, 19,4, 19,10, 19,16, 20,17, 21,11, 21,17, 22,5, 22,11, 22,17,
// Length and number of words of that length
17, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,6,1, 6,20,0, 20,0,1,
// Length and number of words of that length
11, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 1,12,1, 12,21,0, 21,0,1,
// Length and number of words of that length
7, 16,
// Coordinates where words start and direction (0 = horizontal)
0,10,0, 0,16,0, 5,13,0, 6,0,1, 6,8,1, 8,6,0, 8,16,0, 9,5,1, 10,16,1, 11,9,0, 12,0,1, 13,11,1, 16,6,0, 16,8,1, 16,12,0, 16,16,1,
// Length and number of words of that length
6, 16,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,15,0, 0,19,0, 2,11,0, 3,0,1, 7,0,1, 7,17,1, 11,2,1, 11,15,1, 15,0,1, 15,11,0, 15,17,1, 17,3,0, 17,7,0, 17,15,0, 19,17,1,
// Length and number of words of that length
5, 86,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,4,0, 0,6,1, 0,8,0, 0,12,1, 0,14,0, 0,18,1, 0,20,0, 0,21,0, 0,22,0, 1,0,1, 1,6,1, 2,0,1, 3,5,0, 3,7,1, 3,13,1, 4,4,1, 4,12,0, 4,18,0, 4,18,1, 5,3,0, 5,9,0, 5,9,1, 5,15,1, 6,0,0, 6,8,0, 6,14,0, 6,21,0, 6,22,0, 7,7,0, 7,11,1, 7,19,0, 8,0,1, 8,6,1, 8,10,0, 8,12,1, 8,18,1, 9,5,0, 9,11,0, 9,13,1, 9,17,0, 10,4,1, 10,10,1, 10,12,0, 11,3,0, 11,9,1, 11,15,0, 12,0,0, 12,1,0, 12,8,0, 12,8,1, 12,14,0, 12,14,1, 12,22,0, 13,5,1, 13,13,0, 13,19,0, 14,0,1, 14,4,0, 14,6,1, 14,10,0, 14,12,1, 14,18,1, 15,7,1, 15,17,0, 17,3,1, 17,9,1, 18,0,0, 18,0,1, 18,1,0, 18,2,0, 18,8,0, 18,14,0, 18,14,1, 18,18,0, 18,22,0, 19,5,1, 19,11,1, 20,18,1, 21,12,1, 21,18,1, 22,0,1, 22,6,1, 22,12,1, 22,18,1,
// Length and number of words of that length
4, 12,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 0,13,0, 3,19,1, 9,0,1, 9,19,1, 13,0,1, 13,19,1, 19,0,1, 19,9,0, 19,13,0, 19,19,0,
// Length and number of words of that length
3, 36,
// Coordinates where words start and direction (0 = horizontal)
0,6,0, 0,12,0, 0,18,0, 1,17,0, 4,0,1, 4,6,0, 4,10,1, 4,14,1, 5,1,1, 5,5,1, 5,17,0, 6,4,0, 6,16,1, 6,20,1, 7,7,1, 7,15,0, 10,0,1, 10,4,0, 10,18,0, 12,20,1, 13,7,0, 14,18,0, 15,5,0, 15,13,1, 16,0,1, 16,4,1, 16,16,0, 17,15,1, 17,19,1, 18,6,1, 18,10,1, 18,20,1, 19,5,0, 20,4,0, 20,10,0, 20,16,0,
// End marker
0
};
/*
* Name: 23.10, 23 x 23
* (_ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ *)
* (* * _ _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _)
* (* * * _ _ _ _ _ _ * _ _ _ * _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ * _ _ _ _ * *)
* (* _ _ _ * _ _ _ _ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ _ _ _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _ _ * _ _ _ _ _ _)
*/
const int g49[] = {
// Width and height of crossword grid
23, 23,
// Number of black fields
67,
// Black field coordinates
0,6, 0,13, 0,17, 1,6, 1,13, 2,13, 3,3, 3,12, 3,19, 4,5, 4,11, 4,17, 5,4, 5,10, 5,18, 5,22, 6,0, 6,1, 6,6, 6,16, 7,7, 7,15, 8,8, 8,14, 9,9, 9,13, 9,20, 9,21, 9,22, 10,5, 10,12, 10,19, 11,4, 11,11, 11,18, 12,3, 12,10, 12,17, 13,0, 13,1, 13,2, 13,9, 13,13, 14,8, 14,14, 15,7, 15,15, 16,6, 16,16, 16,21, 16,22, 17,0, 17,4, 17,12, 17,18, 18,5, 18,11, 18,17, 19,3, 19,10, 19,19, 20,9, 21,9, 21,16, 22,5, 22,9, 22,16,
// Length and number of words of that length
13, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1, 10,20,0, 20,10,1,
// Length and number of words of that length
9, 16,
// Coordinates where words start and direction (0 = horizontal)
0,9,0, 0,20,0, 0,21,0, 1,14,1, 2,14,1, 6,7,1, 7,6,0, 7,16,0, 9,0,1, 13,14,1, 14,1,0, 14,2,0, 14,13,0, 16,7,1, 20,0,1, 21,0,1,
// Length and number of words of that length
8, 12,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 0,14,0, 3,4,1, 4,3,0, 8,0,1, 8,15,1, 11,19,0, 14,0,1, 14,15,1, 15,8,0, 15,14,0, 19,11,1,
// Length and number of words of that length
7, 16,
// Coordinates where words start and direction (0 = horizontal)
0,7,0, 0,15,0, 5,11,1, 5,17,0, 7,0,1, 7,8,1, 7,16,1, 8,7,0, 8,15,0, 11,5,0, 15,0,1, 15,8,1, 15,16,1, 16,7,0, 16,15,0, 17,5,1,
// Length and number of words of that length
6, 40,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,7,1, 0,16,0, 1,0,1, 1,7,1, 3,13,0, 3,13,1, 4,12,0, 4,19,0, 5,11,0, 6,10,0, 6,17,1, 7,0,0, 7,1,0, 9,14,1, 10,6,1, 10,13,1, 10,21,0, 10,22,0, 11,5,1, 11,12,0, 11,12,1, 12,4,1, 12,11,0, 12,11,1, 13,3,0, 13,3,1, 13,10,0, 14,9,0, 16,0,1, 17,6,0, 17,21,0, 17,22,0, 19,4,1, 21,10,1, 21,17,1, 22,10,1, 22,17,1,
// Length and number of words of that length
5, 32,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,10,0, 0,18,0, 0,18,1, 0,22,0, 4,0,1, 4,6,1, 4,12,1, 4,18,1, 5,5,0, 5,5,1, 6,4,0, 6,18,0, 8,9,1, 9,8,0, 9,14,0, 10,0,1, 12,4,0, 12,18,0, 12,18,1, 13,17,0, 14,9,1, 17,13,1, 18,0,0, 18,0,1, 18,4,0, 18,6,1, 18,12,0, 18,12,1, 18,18,0, 18,18,1, 22,0,1,
// Length and number of words of that length
4, 12,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,11,0, 2,6,0, 5,0,1, 6,2,1, 11,0,1, 11,19,1, 16,17,1, 17,16,0, 17,19,1, 19,11,0, 19,17,0,
// Length and number of words of that length
3, 24,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,12,0, 0,14,1, 0,19,0, 1,17,0, 3,0,1, 3,20,1, 5,19,1, 6,22,0, 9,10,1, 10,9,0, 10,13,0, 10,20,1, 12,0,1, 13,10,1, 14,0,0, 17,1,1, 19,0,1, 19,5,0, 19,20,1, 20,3,0, 20,10,0, 20,19,0, 22,6,1,
// End marker
0
};
/*
* Name: puzzle01, 2 x 2
* (_ *)
* (_ _)
*/
const int g50[] = {
// Width and height of crossword grid
2, 2,
// Number of black fields
1,
// Black field coordinates
1,0,
// Length and number of words of that length
2, 2,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,1,0,
// Length and number of words of that length
1, 2,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 1,1,1,
// End marker
0
};
/*
* Name: puzzle02, 3 x 3
* (* _ _)
* (_ _ _)
* (_ _ _)
*/
const int g51[] = {
// Width and height of crossword grid
3, 3,
// Number of black fields
1,
// Black field coordinates
0,0,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,2,0, 1,0,1, 2,0,1,
// Length and number of words of that length
2, 2,
// Coordinates where words start and direction (0 = horizontal)
0,1,1, 1,0,0,
// End marker
0
};
/*
* Name: puzzle03, 4 x 4
* (_ _ _ *)
* (_ _ _ _)
* (_ _ _ _)
* (* _ _ _)
*/
const int g52[] = {
// Width and height of crossword grid
4, 4,
// Number of black fields
2,
// Black field coordinates
0,3, 3,0,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,2,0, 1,0,1, 2,0,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 1,3,0, 3,1,1,
// End marker
0
};
/*
* Name: puzzle04, 5 x 5
* (_ _ _ * *)
* (_ _ _ _ *)
* (_ _ _ _ _)
* (* _ _ _ _)
* (* * _ _ _)
*/
const int g53[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
6,
// Black field coordinates
0,3, 0,4, 1,4, 3,0, 4,0, 4,1,
// Length and number of words of that length
5, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 1,0,1, 1,3,0, 3,1,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 2,4,0, 4,2,1,
// End marker
0
};
/*
* Name: puzzle05, 5 x 5
* (_ _ _ _ *)
* (_ _ _ * _)
* (_ _ _ _ _)
* (_ * _ _ _)
* (* _ _ _ _)
*/
const int g54[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
4,
// Black field coordinates
0,4, 1,3, 3,1, 4,0,
// Length and number of words of that length
5, 2,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 1,4,0, 4,1,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 1,0,1, 2,3,0, 3,2,1,
// Length and number of words of that length
1, 4,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 1,4,1, 3,0,1, 4,1,0,
// End marker
0
};
/*
* Name: puzzle06, 5 x 5
* (_ _ _ _ _)
* (_ _ _ * _)
* (_ _ _ _ _)
* (_ * _ _ _)
* (_ _ _ _ _)
*/
const int g55[] = {
// Width and height of crossword grid
5, 5,
// Number of black fields
2,
// Black field coordinates
1,3, 3,1,
// Length and number of words of that length
5, 6,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,2,0, 0,4,0, 2,0,1, 4,0,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 1,0,1, 2,3,0, 3,2,1,
// Length and number of words of that length
1, 4,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 1,4,1, 3,0,1, 4,1,0,
// End marker
0
};
/*
* Name: puzzle07, 6 x 6
* (_ _ _ _ _ *)
* (_ * _ _ _ _)
* (_ _ _ * _ _)
* (_ _ * _ _ _)
* (_ _ _ _ * _)
* (* _ _ _ _ _)
*/
const int g56[] = {
// Width and height of crossword grid
6, 6,
// Number of black fields
6,
// Black field coordinates
0,5, 1,1, 2,3, 3,2, 4,4, 5,0,
// Length and number of words of that length
5, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 1,5,0, 5,1,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 1,2,1, 2,1,0, 4,0,1,
// Length and number of words of that length
3, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 2,0,1, 3,3,0, 3,3,1,
// Length and number of words of that length
2, 4,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 2,4,1, 3,0,1, 4,2,0,
// Length and number of words of that length
1, 4,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 1,0,1, 4,5,1, 5,4,0,
// End marker
0
};
/*
* Name: puzzle08, 7 x 7
* (_ _ _ _ * _ _)
* (_ _ _ * _ _ _)
* (_ _ * _ _ _ *)
* (_ _ _ _ _ _ _)
* (* _ _ _ * _ _)
* (_ _ _ * _ _ _)
* (_ _ * _ _ _ _)
*/
const int g57[] = {
// Width and height of crossword grid
7, 7,
// Number of black fields
8,
// Black field coordinates
0,4, 2,2, 2,6, 3,1, 3,5, 4,0, 4,4, 6,2,
// Length and number of words of that length
7, 3,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 1,0,1, 5,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 3,6,0, 6,3,1,
// Length and number of words of that length
3, 9,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,5,0, 1,4,0, 2,3,1, 3,2,0, 3,2,1, 4,1,0, 4,1,1, 4,5,0,
// Length and number of words of that length
2, 8,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,5,1, 0,6,0, 2,0,1, 4,5,1, 5,0,0, 5,4,0, 6,0,1,
// Length and number of words of that length
1, 2,
// Coordinates where words start and direction (0 = horizontal)
3,0,1, 3,6,1,
// End marker
0
};
/*
* Name: puzzle09, 7 x 7
* (* * _ _ _ * *)
* (* _ _ _ _ _ *)
* (_ _ _ * _ _ _)
* (_ _ _ _ _ _ _)
* (_ _ _ * _ _ _)
* (* _ _ _ _ _ *)
* (* * _ _ _ * *)
*/
const int g58[] = {
// Width and height of crossword grid
7, 7,
// Number of black fields
14,
// Black field coordinates
0,0, 0,1, 0,5, 0,6, 1,0, 1,6, 3,2, 3,4, 5,0, 5,6, 6,0, 6,1, 6,5, 6,6,
// Length and number of words of that length
7, 3,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 2,0,1, 4,0,1,
// Length and number of words of that length
5, 4,
// Coordinates where words start and direction (0 = horizontal)
1,1,0, 1,1,1, 1,5,0, 5,1,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,2,1, 0,4,0, 2,0,0, 2,6,0, 4,2,0, 4,4,0, 6,2,1,
// Length and number of words of that length
2, 2,
// Coordinates where words start and direction (0 = horizontal)
3,0,1, 3,5,1,
// Length and number of words of that length
1, 1,
// Coordinates where words start and direction (0 = horizontal)
3,3,1,
// End marker
0
};
/*
* Name: puzzle10, 7 x 7
* (_ _ _ * _ _ _)
* (_ _ _ * _ _ _)
* (_ _ _ _ _ _ _)
* (* * _ * _ * *)
* (_ _ _ _ _ _ _)
* (_ _ _ * _ _ _)
* (_ _ _ * _ _ _)
*/
const int g59[] = {
// Width and height of crossword grid
7, 7,
// Number of black fields
9,
// Black field coordinates
0,3, 1,3, 3,0, 3,1, 3,3, 3,5, 3,6, 5,3, 6,3,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,4,0, 2,0,1, 4,0,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,4,1, 0,5,0, 0,6,0, 1,0,1, 1,4,1, 4,0,0, 4,1,0, 4,5,0, 4,6,0, 5,0,1, 5,4,1, 6,0,1, 6,4,1,
// Length and number of words of that length
1, 4,
// Coordinates where words start and direction (0 = horizontal)
2,3,0, 3,2,1, 3,4,1, 4,3,0,
// End marker
0
};
/*
* Name: puzzle11, 7 x 7
* (* * _ _ _ _ *)
* (* _ _ _ _ _ _)
* (_ _ _ * _ _ _)
* (_ _ _ * _ _ _)
* (_ _ _ * _ _ _)
* (_ _ _ _ _ _ *)
* (* _ _ _ _ * *)
*/
const int g60[] = {
// Width and height of crossword grid
7, 7,
// Number of black fields
11,
// Black field coordinates
0,0, 0,1, 0,6, 1,0, 3,2, 3,3, 3,4, 5,6, 6,0, 6,5, 6,6,
// Length and number of words of that length
7, 2,
// Coordinates where words start and direction (0 = horizontal)
2,0,1, 4,0,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 1,1,0, 1,1,1, 5,0,1,
// Length and number of words of that length
4, 4,
// Coordinates where words start and direction (0 = horizontal)
0,2,1, 1,6,0, 2,0,0, 6,1,1,
// Length and number of words of that length
3, 6,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,3,0, 0,4,0, 4,2,0, 4,3,0, 4,4,0,
// Length and number of words of that length
2, 2,
// Coordinates where words start and direction (0 = horizontal)
3,0,1, 3,5,1,
// End marker
0
};
/*
* Name: puzzle12, 8 x 8
* (_ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _)
* (* * * _ _ _ _ _)
* (_ _ _ _ _ * * *)
* (_ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _)
*/
const int g61[] = {
// Width and height of crossword grid
8, 8,
// Number of black fields
12,
// Black field coordinates
0,3, 1,3, 2,3, 3,5, 3,6, 3,7, 4,0, 4,1, 4,2, 5,4, 6,4, 7,4,
// Length and number of words of that length
5, 4,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 3,0,1, 3,3,0, 4,3,1,
// Length and number of words of that length
4, 12,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,2,0, 0,4,1, 1,4,1, 2,4,1, 4,5,0, 4,6,0, 4,7,0, 5,0,1, 6,0,1, 7,0,1,
// Length and number of words of that length
3, 12,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,5,0, 0,6,0, 0,7,0, 1,0,1, 2,0,1, 5,0,0, 5,1,0, 5,2,0, 5,5,1, 6,5,1, 7,5,1,
// End marker
0
};
/*
* Name: puzzle13, 9 x 9
* (_ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _)
* (_ _ _ * * * _ _ _)
* (_ _ _ _ _ _ _ _ _)
* (* * * _ _ _ * * *)
* (_ _ _ _ _ _ _ _ _)
* (_ _ _ * * * _ _ _)
* (_ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _)
*/
const int g62[] = {
// Width and height of crossword grid
9, 9,
// Number of black fields
16,
// Black field coordinates
0,4, 1,4, 2,4, 3,2, 3,6, 4,0, 4,1, 4,2, 4,6, 4,7, 4,8, 5,2, 5,6, 6,4, 7,4, 8,4,
// Length and number of words of that length
9, 2,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,5,0,
// Length and number of words of that length
4, 20,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,5,1, 0,7,0, 0,8,0, 1,0,1, 1,5,1, 2,0,1, 2,5,1, 5,0,0, 5,1,0, 5,7,0, 5,8,0, 6,0,1, 6,5,1, 7,0,1, 7,5,1, 8,0,1, 8,5,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,6,0, 3,3,1, 3,4,0, 4,3,1, 5,3,1, 6,2,0, 6,6,0,
// Length and number of words of that length
2, 4,
// Coordinates where words start and direction (0 = horizontal)
3,0,1, 3,7,1, 5,0,1, 5,7,1,
// End marker
0
};
/*
* Name: puzzle14, 10 x 10
* (* * * _ _ _ _ * * *)
* (* * _ _ _ _ _ * * *)
* (* _ _ _ _ _ _ _ * *)
* (_ _ _ _ _ * * _ _ _)
* (_ _ _ _ * * * _ _ _)
* (_ _ _ * * * _ _ _ _)
* (_ _ _ * * _ _ _ _ _)
* (* * _ _ _ _ _ _ _ *)
* (* * * _ _ _ _ _ * *)
* (* * * _ _ _ _ * * *)
*/
const int g63[] = {
// Width and height of crossword grid
10, 10,
// Number of black fields
38,
// Black field coordinates
0,0, 0,1, 0,2, 0,7, 0,8, 0,9, 1,0, 1,1, 1,7, 1,8, 1,9, 2,0, 2,8, 2,9, 3,5, 3,6, 4,4, 4,5, 4,6, 5,3, 5,4, 5,5, 6,3, 6,4, 7,0, 7,1, 7,9, 8,0, 8,1, 8,2, 8,8, 8,9, 9,0, 9,1, 9,2, 9,7, 9,8, 9,9,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
1,2,0, 2,1,1, 2,7,0, 7,2,1,
// Length and number of words of that length
5, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 1,2,1, 2,1,0, 3,0,1, 3,8,0, 5,6,0, 6,5,1, 8,3,1,
// Length and number of words of that length
4, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,1, 0,4,0, 3,0,0, 3,9,0, 4,0,1, 5,6,1, 6,5,0, 9,3,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,6,0, 3,7,1, 4,7,1, 5,0,1, 6,0,1, 7,3,0, 7,4,0,
// End marker
0
};
/*
* Name: puzzle15, 11 x 11
* (_ _ _ _ * * * _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _)
* (* _ _ _ _ _ * _ _ _ *)
* (* * * _ _ _ _ _ * * *)
* (* _ _ _ * _ _ _ _ _ *)
* (_ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ _ _)
* (_ _ _ _ * * * _ _ _ _)
*/
const int g64[] = {
// Width and height of crossword grid
11, 11,
// Number of black fields
26,
// Black field coordinates
0,4, 0,5, 0,6, 1,5, 2,5, 3,3, 3,7, 4,0, 4,6, 4,10, 5,0, 5,1, 5,2, 5,8, 5,9, 5,10, 6,0, 6,4, 6,10, 7,3, 7,7, 8,5, 9,5, 10,4, 10,5, 10,6,
// Length and number of words of that length
5, 22,
// Coordinates where words start and direction (0 = horizontal)
0,1,0, 0,2,0, 0,8,0, 0,9,0, 1,0,1, 1,4,0, 1,6,1, 2,0,1, 2,6,1, 3,5,0, 4,1,1, 5,3,1, 5,6,0, 6,1,0, 6,2,0, 6,5,1, 6,8,0, 6,9,0, 8,0,1, 8,6,1, 9,0,1, 9,6,1,
// Length and number of words of that length
4, 8,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,7,1, 0,10,0, 7,0,0, 7,10,0, 10,0,1, 10,7,1,
// Length and number of words of that length
3, 16,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,7,0, 1,6,0, 3,0,1, 3,4,1, 3,8,1, 4,3,0, 4,7,0, 4,7,1, 6,1,1, 7,0,1, 7,4,0, 7,4,1, 7,8,1, 8,3,0, 8,7,0,
// End marker
0
};
/*
* Name: puzzle16, 13 x 13
* (_ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * * *)
* (* * * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ * * *)
* (* * * _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ * _ _ _)
*/
const int g65[] = {
// Width and height of crossword grid
13, 13,
// Number of black fields
34,
// Black field coordinates
0,4, 0,9, 1,4, 1,9, 2,4, 2,9, 3,0, 3,1, 3,2, 3,7, 4,6, 4,10, 4,11, 4,12, 5,5, 6,3, 6,4, 6,8, 6,9, 7,7, 8,0, 8,1, 8,2, 8,6, 9,5, 9,10, 9,11, 9,12, 10,3, 10,8, 11,3, 11,8, 12,3, 12,8,
// Length and number of words of that length
7, 2,
// Coordinates where words start and direction (0 = horizontal)
5,6,1, 7,0,1,
// Length and number of words of that length
6, 6,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,8,0, 4,0,1, 7,4,0, 7,9,0, 8,7,1,
// Length and number of words of that length
5, 6,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 3,8,1, 5,0,1, 7,8,1, 8,7,0, 9,0,1,
// Length and number of words of that length
4, 28,
// Coordinates where words start and direction (0 = horizontal)
0,0,1, 0,5,1, 0,6,0, 0,10,0, 0,11,0, 0,12,0, 1,0,1, 1,5,1, 2,0,1, 2,5,1, 3,3,1, 4,0,0, 4,1,0, 4,2,0, 5,10,0, 5,11,0, 5,12,0, 9,0,0, 9,1,0, 9,2,0, 9,6,0, 9,6,1, 10,4,1, 10,9,1, 11,4,1, 11,9,1, 12,4,1, 12,9,1,
// Length and number of words of that length
3, 26,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,1,0, 0,2,0, 0,7,0, 0,10,1, 1,10,1, 2,10,1, 3,4,0, 3,9,0, 4,7,0, 4,7,1, 5,6,0, 6,0,1, 6,5,0, 6,5,1, 6,10,1, 7,3,0, 7,8,0, 8,3,1, 10,0,1, 10,5,0, 10,10,0, 10,11,0, 10,12,0, 11,0,1, 12,0,1,
// End marker
0
};
/*
* Name: puzzle17, 15 x 15
* (_ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (* * _ _ _ _ * _ _ _ _ _ _ * *)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ * _ _ _)
* (* * * _ _ _ * * * _ _ _ * * *)
* (_ _ _ * _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (* * _ _ _ _ _ _ * _ _ _ _ * *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _)
*/
const int g66[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
45,
// Black field coordinates
0,3, 0,7, 0,11, 1,3, 1,7, 1,11, 2,7, 3,0, 3,1, 3,8, 3,13, 3,14, 4,5, 4,9, 5,4, 5,10, 6,3, 6,7, 7,0, 7,1, 7,2, 7,6, 7,7, 7,8, 7,12, 7,13, 7,14, 8,7, 8,11, 9,4, 9,10, 10,5, 10,9, 11,0, 11,1, 11,6, 11,13, 11,14, 12,7, 13,3, 13,7, 13,11, 14,3, 14,7, 14,11,
// Length and number of words of that length
7, 12,
// Coordinates where words start and direction (0 = horizontal)
0,2,0, 0,6,0, 0,12,0, 2,0,1, 2,8,1, 6,8,1, 8,0,1, 8,2,0, 8,8,0, 8,12,0, 12,0,1, 12,8,1,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
2,11,0, 3,2,1, 7,3,0, 11,7,1,
// Length and number of words of that length
5, 12,
// Coordinates where words start and direction (0 = horizontal)
0,4,0, 0,10,0, 4,0,1, 4,10,1, 5,5,0, 5,5,1, 5,9,0, 9,5,1, 10,0,1, 10,4,0, 10,10,0, 10,10,1,
// Length and number of words of that length
4, 12,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,9,0, 2,3,0, 3,9,1, 5,0,1, 5,11,1, 9,0,1, 9,11,0, 9,11,1, 11,2,1, 11,5,0, 11,9,0,
// Length and number of words of that length
3, 48,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,4,1, 0,8,0, 0,8,1, 0,12,1, 0,13,0, 0,14,0, 1,0,1, 1,4,1, 1,8,1, 1,12,1, 3,7,0, 4,0,0, 4,1,0, 4,6,1, 4,8,0, 4,13,0, 4,14,0, 6,0,1, 6,4,0, 6,4,1, 6,10,0, 7,3,1, 7,9,1, 8,0,0, 8,1,0, 8,6,0, 8,8,1, 8,12,1, 8,13,0, 8,14,0, 9,7,0, 10,6,1, 12,0,0, 12,1,0, 12,6,0, 12,13,0, 12,14,0, 13,0,1, 13,4,1, 13,8,1, 13,12,1, 14,0,1, 14,4,1, 14,8,1, 14,12,1,
// End marker
0
};
/*
* Name: puzzle18, 15 x 15
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * * _ _ _ _)
* (* * * * _ _ _ * * _ _ _ * * *)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * * _ _ _ * * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ * _ _ _ * _ _ _)
* (* * * _ _ _ * * _ _ _ * * * *)
* (_ _ _ _ * * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g67[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
48,
// Black field coordinates
0,4, 0,10, 1,4, 1,10, 2,4, 2,10, 3,4, 3,5, 3,9, 4,0, 4,1, 4,2, 4,6, 4,7, 4,11, 4,12, 4,13, 4,14, 5,3, 5,7, 5,11, 6,10, 7,4, 7,5, 7,9, 7,10, 8,4, 9,3, 9,7, 9,11, 10,0, 10,1, 10,2, 10,3, 10,7, 10,8, 10,12, 10,13, 10,14, 11,5, 11,9, 11,10, 12,4, 12,10, 13,4, 13,10, 14,4, 14,10,
// Length and number of words of that length
10, 4,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 5,6,0, 6,0,1, 8,5,1,
// Length and number of words of that length
5, 16,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,5,1, 1,5,1, 2,5,1, 3,10,1, 5,0,0, 5,1,0, 5,2,0, 5,12,0, 5,13,0, 5,14,0, 10,11,0, 11,0,1, 12,5,1, 13,5,1, 14,5,1,
// Length and number of words of that length
4, 36,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,6,0, 0,7,0, 0,11,0, 0,11,1, 0,12,0, 0,13,0, 0,14,0, 1,0,1, 1,11,1, 2,0,1, 2,11,1, 3,0,1, 6,11,1, 7,0,1, 7,11,1, 8,0,1, 11,0,0, 11,1,0, 11,2,0, 11,3,0, 11,7,0, 11,8,0, 11,11,1, 11,12,0, 11,13,0, 11,14,0, 12,0,1, 12,11,1, 13,0,1, 13,11,1, 14,0,1, 14,11,1,
// Length and number of words of that length
3, 30,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,9,0, 3,6,1, 3,10,0, 4,3,1, 4,4,0, 4,5,0, 4,8,1, 4,9,0, 5,0,1, 5,4,1, 5,8,1, 5,12,1, 6,3,0, 6,7,0, 6,11,0, 7,6,1, 8,5,0, 8,9,0, 8,10,0, 9,0,1, 9,4,0, 9,4,1, 9,8,1, 9,12,1, 10,4,1, 10,9,1, 11,6,1, 12,5,0, 12,9,0,
// End marker
0
};
/*
* Name: puzzle19, 15 x 15
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ _ _ * * *)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ _ * _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ * _ _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ _ * _ _ _ * _ _ _ _ _)
* (* * * _ _ _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ _ * _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ _ _ * _ _ _ _)
*/
const int g68[] = {
// Width and height of crossword grid
15, 15,
// Number of black fields
38,
// Black field coordinates
0,4, 0,10, 1,4, 1,10, 2,4, 2,10, 3,8, 4,0, 4,1, 4,2, 4,6, 4,7, 4,12, 4,13, 4,14, 5,5, 5,9, 6,4, 7,3, 7,11, 8,10, 9,5, 9,9, 10,0, 10,1, 10,2, 10,7, 10,8, 10,12, 10,13, 10,14, 11,6, 12,4, 12,10, 13,4, 13,10, 14,4, 14,10,
// Length and number of words of that length
10, 2,
// Coordinates where words start and direction (0 = horizontal)
6,5,1, 8,0,1,
// Length and number of words of that length
8, 2,
// Coordinates where words start and direction (0 = horizontal)
3,0,1, 11,7,1,
// Length and number of words of that length
7, 5,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,11,0, 7,4,1, 8,3,0, 8,11,0,
// Length and number of words of that length
6, 4,
// Coordinates where words start and direction (0 = horizontal)
3,9,1, 4,8,0, 5,6,0, 11,0,1,
// Length and number of words of that length
5, 23,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,5,1, 0,9,0, 1,5,1, 2,5,1, 3,10,0, 5,0,0, 5,0,1, 5,1,0, 5,2,0, 5,7,0, 5,10,1, 5,12,0, 5,13,0, 5,14,0, 7,4,0, 9,0,1, 9,10,1, 10,5,0, 10,9,0, 12,5,1, 13,5,1, 14,5,1,
// Length and number of words of that length
4, 32,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,6,0, 0,7,0, 0,11,1, 0,12,0, 0,13,0, 0,14,0, 1,0,1, 1,11,1, 2,0,1, 2,11,1, 4,8,1, 6,0,1, 8,11,1, 10,3,1, 11,0,0, 11,1,0, 11,2,0, 11,7,0, 11,8,0, 11,12,0, 11,13,0, 11,14,0, 12,0,1, 12,11,1, 13,0,1, 13,11,1, 14,0,1, 14,11,1,
// Length and number of words of that length
3, 12,
// Coordinates where words start and direction (0 = horizontal)
0,8,0, 3,4,0, 4,3,1, 5,6,1, 6,5,0, 6,9,0, 7,0,1, 7,12,1, 9,6,1, 9,10,0, 10,9,1, 12,6,0,
// End marker
0
};
/*
* Name: puzzle20, 9 x 9
* (* * * _ _ _ * * *)
* (* * _ _ _ _ _ * *)
* (* _ _ _ _ _ _ _ *)
* (_ _ _ _ * _ _ _ _)
* (_ _ _ * * * _ _ _)
* (_ _ _ _ * _ _ _ _)
* (* _ _ _ _ _ _ _ *)
* (* * _ _ _ _ _ * *)
* (* * * _ _ _ * * *)
*/
const int g69[] = {
// Width and height of crossword grid
9, 9,
// Number of black fields
29,
// Black field coordinates
0,0, 0,1, 0,2, 0,6, 0,7, 0,8, 1,0, 1,1, 1,7, 1,8, 2,0, 2,8, 3,4, 4,3, 4,4, 4,5, 5,4, 6,0, 6,8, 7,0, 7,1, 7,7, 7,8, 8,0, 8,1, 8,2, 8,6, 8,7, 8,8,
// Length and number of words of that length
7, 4,
// Coordinates where words start and direction (0 = horizontal)
1,2,0, 1,6,0, 2,1,1, 6,1,1,
// Length and number of words of that length
5, 4,
// Coordinates where words start and direction (0 = horizontal)
1,2,1, 2,1,0, 2,7,0, 7,2,1,
// Length and number of words of that length
4, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,5,0, 3,0,1, 3,5,1, 5,0,1, 5,3,0, 5,5,0, 5,5,1,
// Length and number of words of that length
3, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,1, 0,4,0, 3,0,0, 3,8,0, 4,0,1, 4,6,1, 6,4,0, 8,3,1,
// End marker
0
};
/*
* Name: puzzle21, 13 x 13
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ * _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ * * * _ _ _ _ _)
* (_ _ _ * * * * * * * _ _ _)
* (_ _ _ _ _ * * * _ _ _ _ _)
* (* * * _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ * _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
*/
const int g70[] = {
// Width and height of crossword grid
13, 13,
// Number of black fields
41,
// Black field coordinates
0,4, 0,8, 1,4, 1,8, 2,4, 2,8, 3,6, 4,0, 4,1, 4,2, 4,6, 4,10, 4,11, 4,12, 5,5, 5,6, 5,7, 6,3, 6,4, 6,5, 6,6, 6,7, 6,8, 6,9, 7,5, 7,6, 7,7, 8,0, 8,1, 8,2, 8,6, 8,10, 8,11, 8,12, 9,6, 10,4, 10,8, 11,4, 11,8, 12,4, 12,8,
// Length and number of words of that length
6, 8,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 3,0,1, 3,7,1, 7,3,0, 7,9,0, 9,0,1, 9,7,1,
// Length and number of words of that length
5, 8,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,7,0, 5,0,1, 5,8,1, 7,0,1, 7,8,1, 8,5,0, 8,7,0,
// Length and number of words of that length
4, 24,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,9,1, 0,10,0, 0,11,0, 0,12,0, 1,0,1, 1,9,1, 2,0,1, 2,9,1, 9,0,0, 9,1,0, 9,2,0, 9,10,0, 9,11,0, 9,12,0, 10,0,1, 10,9,1, 11,0,1, 11,9,1, 12,0,1, 12,9,1,
// Length and number of words of that length
3, 24,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 0,6,0, 1,5,1, 2,5,1, 3,4,0, 3,8,0, 4,3,1, 4,7,1, 5,0,0, 5,1,0, 5,2,0, 5,10,0, 5,11,0, 5,12,0, 6,0,1, 6,10,1, 7,4,0, 7,8,0, 8,3,1, 8,7,1, 10,5,1, 10,6,0, 11,5,1, 12,5,1,
// End marker
0
};
/*
* Name: puzzle22, 13 x 13
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ _ _ _ _ _ _ _ _ _)
* (* * * _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ * * * _ _ _ _ _)
* (_ _ _ _ * * * * * _ _ _ _)
* (_ _ _ _ _ * * * _ _ _ _ _)
* (* * * _ _ _ * _ _ _ * * *)
* (_ _ _ _ _ _ _ _ _ _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
* (_ _ _ _ * _ _ _ * _ _ _ _)
*/
const int g71[] = {
// Width and height of crossword grid
13, 13,
// Number of black fields
37,
// Black field coordinates
0,4, 0,8, 1,4, 1,8, 2,4, 2,8, 4,0, 4,1, 4,2, 4,6, 4,10, 4,11, 4,12, 5,5, 5,6, 5,7, 6,4, 6,5, 6,6, 6,7, 6,8, 7,5, 7,6, 7,7, 8,0, 8,1, 8,2, 8,6, 8,10, 8,11, 8,12, 10,4, 10,8, 11,4, 11,8, 12,4, 12,8,
// Length and number of words of that length
13, 4,
// Coordinates where words start and direction (0 = horizontal)
0,3,0, 0,9,0, 3,0,1, 9,0,1,
// Length and number of words of that length
5, 8,
// Coordinates where words start and direction (0 = horizontal)
0,5,0, 0,7,0, 5,0,1, 5,8,1, 7,0,1, 7,8,1, 8,5,0, 8,7,0,
// Length and number of words of that length
4, 28,
// Coordinates where words start and direction (0 = horizontal)
0,0,0, 0,0,1, 0,1,0, 0,2,0, 0,6,0, 0,9,1, 0,10,0, 0,11,0, 0,12,0, 1,0,1, 1,9,1, 2,0,1, 2,9,1, 6,0,1, 6,9,1, 9,0,0, 9,1,0, 9,2,0, 9,6,0, 9,10,0, 9,11,0, 9,12,0, 10,0,1, 10,9,1, 11,0,1, 11,9,1, 12,0,1, 12,9,1,
// Length and number of words of that length
3, 20,
// Coordinates where words start and direction (0 = horizontal)
0,5,1, 1,5,1, 2,5,1, 3,4,0, 3,8,0, 4,3,1, 4,7,1, 5,0,0, 5,1,0, 5,2,0, 5,10,0, 5,11,0, 5,12,0, 7,4,0, 7,8,0, 8,3,1, 8,7,1, 10,5,1, 11,5,1, 12,5,1,
// End marker
0
};
const int* grids[] = {
&g0[0], &g1[0], &g2[0], &g3[0], &g4[0], &g5[0], &g6[0], &g7[0], &g8[0],
&g9[0], &g10[0], &g11[0], &g12[0], &g13[0], &g14[0], &g15[0], &g16[0],
&g17[0], &g18[0], &g19[0], &g20[0], &g21[0], &g22[0], &g23[0], &g24[0],
&g25[0], &g26[0], &g27[0], &g28[0], &g29[0], &g30[0], &g31[0], &g32[0],
&g33[0], &g34[0], &g35[0], &g36[0], &g37[0], &g38[0], &g39[0], &g40[0],
&g41[0], &g42[0], &g43[0], &g44[0], &g45[0], &g46[0], &g47[0], &g48[0],
&g49[0], &g50[0], &g51[0], &g52[0], &g53[0], &g54[0], &g55[0], &g56[0],
&g57[0], &g58[0], &g59[0], &g60[0], &g61[0], &g62[0], &g63[0], &g64[0],
&g65[0], &g66[0], &g67[0], &g68[0], &g69[0], &g70[0], &g71[0]
};
const unsigned int n_grids = 72;
}
// STATISTICS: example-any
|
/****************************************************************************************
* @author: kzvd4729 created: 2018-08-15 23:39:50
* solution_verdict: Time limit exceeded language: C++
* run_time: memory_used:
* problem: https://vjudge.net/problem/UVA-12494
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const long mod=1e9+9;
const int N=2e2;
const int b=31;
int t;
unordered_map<long,int>mp;
long inv,bb[N+2];
string s;
long bigmod(long b,long p,long mod)
{
long ret=1;
while(p)
{
if(p&1)ret=(ret*b)%mod;
b=(b*b)%mod;
p/=2;
}
return ret;
}
int main()
{
//ofstream cout("out.txt");
ios_base::sync_with_stdio(0);
cin.tie(0);
mp.max_load_factor(0.25);
mp.reserve(512);
bb[1]=b;
for(int i=2;i<=N;i++)
bb[i]=(bb[i-1]*b)%mod;
inv=bigmod(b,mod-2,mod);
cin>>t;
while(t--)
{
cin>>s;int ans=0;
mp.clear();
for(int i=0;i<s.size();i++)
{
string tmp;long hs=0;
for(int j=i;j<s.size();j++)
{
tmp.push_back(s[j]);
hs=(hs+bb[j-i+1]*(long)s[j])%mod;
long ths=hs;int f=0;
if(mp[ths])f=1;
for(int k=0;k<tmp.size();k++)
{
ths=(ths*inv)%mod;
ths=(ths-(long)tmp[k]+mod)%mod;
ths=(ths+(long)tmp[k]*bb[j-i+1])%mod;
if(mp[ths])f=1;
if(f)break;
}
if(!f)ans++;
mp[hs]=1;
}
}
cout<<ans<<endl;
}
return 0;
}
|
#include <ncurses.h>
#include "screen.h"
Screen::Screen()
{
}
Screen::~Screen()
{
curs_set(1);
endwin();
}
bool Screen::Init()
{
initscr();
cbreak();
noecho();
clear();
start_color();
init_pair(1,COLOR_GREEN,COLOR_BLACK);
init_pair(2,COLOR_RED,COLOR_BLACK);
init_pair(3,COLOR_GREEN,COLOR_WHITE);
init_pair(4,COLOR_RED,COLOR_WHITE);
curs_set(0);
return true;
}
|
#include <wx/wx.h>
#include <wx/fontpicker.h>
namespace Examples {
class Frame : public wxFrame {
public:
Frame() : wxFrame(nullptr, wxID_ANY, "FontPickerCtrl example") {
SetClientSize(400, 400);
picker->SetSelectedFont(label->GetFont());
picker->SetSelectedColour(label->GetForegroundColour());
picker->Bind(wxEVT_FONTPICKER_CHANGED, [&](wxFontPickerEvent& event) {
label->SetFont(picker->GetSelectedFont());
label->SetForegroundColour(picker->GetSelectedColour());
});
}
private:
wxPanel* panel = new wxPanel(this);
wxStaticText* label = new wxStaticText(panel, wxID_ANY,
u8"The quick brown fox jumps over the lazy dog.\n"
u8"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.\n"
u8"0123456789+-*/%~^&|=<>≤≥±÷≠{{[()]}},;:.?¿!¡\n"
u8"àçéèêëïî@@°_#§$ù£€æœøπµ©®∞\\\"'\n"
u8"\u0400\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040a\u040b\u040c\u040d\u040e\u040f\n"
u8"\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041a\u041b\u041c\u041d\u041e\u041f\n"
u8"\u4ea0\u4ea1\u4ea2\u4ea3\u4ea4\u4ea5\u4ea6\u4ea7\u4ea8\u4ea9\u4eaa\u4eab\u4eac\u4ead\u4eae\u4eaf\n"
u8"\u4eb0\u4eb1\u4eb2\u4eb3\u4eb4\u4eb5\u4eb6\u4eb7\u4eb8\u4eb9\u4eba\u4ebb\u4ebc\u4ebd\u4ebe\u4ebf\n"
u8"\U0001F428", wxPoint(10, 50));
wxFontPickerCtrl* picker = new wxFontPickerCtrl(panel, wxID_ANY, {}, {10, 10}, wxDefaultSize, wxFNTP_FONTDESC_AS_LABEL);
};
class Application : public wxApp {
bool OnInit() override {
(new Frame())->Show();
return true;
}
};
}
wxIMPLEMENT_APP(Examples::Application);
|
// Copyright 2018 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 "third_party/blink/renderer/core/layout/layout_shift_region.h"
#include <gtest/gtest.h>
#include "third_party/blink/renderer/platform/geometry/region.h"
namespace blink {
class LayoutShiftRegionTest : public testing::Test {};
TEST_F(LayoutShiftRegionTest, Basic) {
LayoutShiftRegion region;
EXPECT_EQ(0u, region.Area());
region.AddRect(gfx::Rect(2, 1, 1, 3));
EXPECT_EQ(3u, region.Area());
region.AddRect(gfx::Rect(1, 2, 3, 1));
EXPECT_EQ(5u, region.Area());
region.AddRect(gfx::Rect(1, 2, 1, 1));
region.AddRect(gfx::Rect(3, 2, 1, 1));
region.AddRect(gfx::Rect(2, 1, 1, 1));
region.AddRect(gfx::Rect(2, 3, 1, 1));
EXPECT_EQ(5u, region.Area());
region.AddRect(gfx::Rect(1, 1, 1, 1));
EXPECT_EQ(6u, region.Area());
region.AddRect(gfx::Rect(1, 1, 3, 3));
EXPECT_EQ(9u, region.Area());
region.AddRect(gfx::Rect(0, 0, 2, 2));
EXPECT_EQ(12u, region.Area());
region.AddRect(gfx::Rect(-1, -1, 2, 2));
EXPECT_EQ(15u, region.Area());
region.Reset();
EXPECT_EQ(0u, region.Area());
}
TEST_F(LayoutShiftRegionTest, LargeRandom) {
LayoutShiftRegion region;
Region naive_region;
static const int data[] = {
52613, 38528, 20785, 40550, 29734, 48229, 37113, 3520, 66776, 26746,
20527, 11398, 27951, 50399, 37139, 17597, 20593, 57272, 12528, 5907,
18369, 6955, 50779, 41129, 66685, 46725, 30708, 32429, 140, 55034,
14770, 40886, 54560, 53666, 15350, 12692, 29354, 47388, 47542, 15474,
17770, 70300, 27992, 6731, 47459, 42205, 45231, 9398, 15606, 2238,
8387, 44579, 45222, 35626, 53932, 2907, 14899, 18234, 60609, 34125,
23985, 48145, 40247, 25215, 64427, 41207, 29742, 35282, 21390, 12640,
14653, 71326, 41293, 4593, 54114, 55398, 17797, 55637, 64133, 25985,
45213, 6428, 6496, 37832, 31291, 27955, 32967, 4134, 35992, 3226,
43190, 31310, 49828, 6737, 31847, 65511, 52287, 41393, 33728, 29813,
32425, 74095, 41857, 2537, 14073, 16177, 23053, 75553, 3570, 76482,
49801, 17920, 45628, 59408, 44788, 18020, 11607, 21027, 27095, 52992,
37770, 51722, 15857, 38088, 22031, 68391, 66615, 2592, 91, 16324,
64393, 51544, 3848, 1924, 90673, 16461, 97524, 42603, 122, 55027,
7945, 10493, 89602, 38306, 73269, 72165, 15014, 23160, 10208, 66632,
78104, 22252, 52910, 7870, 293, 61338, 54913, 48813, 3949, 6507,
82176, 60067, 13639, 13096, 71024, 52767, 20514, 4716, 15125, 14158,
24315, 46986, 62316, 95391, 8390, 1007, 9520, 67532, 69963, 20117,
51649, 42999, 1441, 34966, 17616, 16544, 51218, 72116, 1780, 12254,
52065, 67026, 88250, 39824, 1786, 22090, 14884, 41933, 46081, 25596,
89968, 51346, 2479, 36409, 11513, 36037, 19481, 4287, 33831, 28199,
56514, 52659, 54910, 14740, 43540, 45912, 44651, 4232, 15199, 45442,
45856, 19374, 17597, 50923, 24227, 17000, 47585, 61718, 48390, 37848,
23677, 2669, 49142, 37207, 30794, 11373, 41719, 40002, 39749, 39146,
39144, 59801, 23772, 17552, 26731, 7802, 29291, 40281, 82706, 9370,
7006, 75864, 94618, 75409, 5267, 5222, 47927, 19430, 4425, 14295,
16662, 22094, 33027, 48759, 42250, 5205, 5424, 70064, 36751, 60688,
45415, 24027, 37665, 88085, 16011, 8785, 12656, 1662, 68336, 62175,
2132, 66236, 5301, 5174, 9575, 42509, 41511, 44451, 59069, 43296,
3246, 11251, 37176, 25619, 60728, 36030, 40982, 33756, 46296, 4407,
84886, 59809, 8127, 34846, 44433, 4366, 4823, 52452, 4594, 69662,
59199, 18623, 29345, 36375, 20166, 12254, 30879, 84106, 29786, 7838,
35875, 32227, 34871, 31142, 71453, 74402, 3243, 4475, 1974, 62754,
80498, 26875, 22957, 25916, 74769, 66343, 18666, 28537, 41799, 54598,
32617, 73615, 51275, 20602, 10642, 57506, 72158, 38152, 12552, 36601,
29638, 28894, 67153, 27560, 1577, 67248, 65745, 53338, 4220, 20883,
72059, 33747, 11195, 47783, 21251, 92912, 25, 4257, 17625, 29683,
32964, 31019, 37510, 2205, 47755, 15187, 9769, 28377, 28890, 6955,
31621, 21088, 54431, 30372, 14567, 47483, 80553, 4324, 10574, 870,
59862, 86272, 8682, 49237, 85735, 10570, 21034, 50807, 47647, 37221,
};
uint64_t expected_area = 9201862875ul;
for (unsigned i = 0; i < 100; i++) {
const int* d = data + (i * 4);
gfx::Rect r(d[0], d[1], d[2], d[3]);
region.AddRect(r);
naive_region.Unite(Region(r));
}
EXPECT_EQ(expected_area, region.Area());
EXPECT_EQ(expected_area, naive_region.Area());
}
// Creates a region like this:
// █ █ █
// ███████
// █ █ █
// ███████
// █ █ █
// ███████
// █ █ █
TEST_F(LayoutShiftRegionTest, Waffle) {
LayoutShiftRegion region;
unsigned n = 250000;
for (unsigned i = 2; i <= n; i += 2) {
region.AddRect(gfx::Rect(i, 1, 1, n + 1));
region.AddRect(gfx::Rect(1, i, n + 1, 1));
}
uint64_t half = n >> 1;
uint64_t area = n * (half + 1) + half * half;
EXPECT_EQ(area, region.Area());
}
} // namespace blink
|
//******************************************************************************
//*
//* FULLNAME: Single-Chip Microcontroller Real-Time Operating System
//*
//* NICKNAME: scmRTOS
//*
//* Version: v5.2.0
//*
//*
//* Copyright (c) 2003-2021, scmRTOS Team
//*
//* 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.
//*
//* =================================================================
//* Project sources: https://github.com/scmrtos/scmrtos
//* Documentation: https://github.com/scmrtos/scmrtos/wiki/Documentation
//* Wiki: https://github.com/scmrtos/scmrtos/wiki
//* Sample projects: https://github.com/scmrtos/scmrtos-sample-projects
//* =================================================================
//*
//******************************************************************************
//* Recursive mutex extension by Andrey Chuykin, Copyright (c) 2015-2021
#include "recursive_mutex.h"
namespace OS
{
//------------------------------------------------------------------------------
//
void TRecursiveMutex::lock()
{
TCritSect cs;
TProcessMap curr_tag = cur_proc_prio_tag();
if ( 0 == ValueTag )
{
ValueTag = curr_tag;
NestCount = 1;
}
else if ( ValueTag == curr_tag )
{
++NestCount;
}
else
{
while ( ValueTag )
suspend(ProcessMap);
ValueTag = cur_proc_prio_tag();
NestCount = 1;
}
}
//------------------------------------------------------------------------------
//
void TRecursiveMutex::unlock()
{
TCritSect cs;
if ( ValueTag != cur_proc_prio_tag() || 0 == NestCount )
return;
if ( --NestCount == 0 )
{
ValueTag = 0;
resume_next_ready(ProcessMap);
}
}
//------------------------------------------------------------------------------
//
void TRecursiveMutex::force_unlock()
{
TCritSect cs;
if ( ValueTag != cur_proc_prio_tag() || 0 == NestCount )
return;
NestCount = 0;
ValueTag = 0;
resume_next_ready(ProcessMap);
}
//------------------------------------------------------------------------------
//
bool TRecursiveMutex::try_lock()
{
TCritSect cs;
if ( ValueTag && ValueTag != cur_proc_prio_tag() )
return false;
else
lock();
return true;
}
//------------------------------------------------------------------------------
//
bool TRecursiveMutex::try_lock(timeout_t timeout)
{
TCritSect cs;
if ( ValueTag && ValueTag != cur_proc_prio_tag() )
{
// mutex already locked by another process, suspend current process
while ( ValueTag )
{
cur_proc_timeout() = timeout;
suspend(ProcessMap);
if ( is_timeouted(ProcessMap) )
return false; // waked up by timeout or by externals
cur_proc_timeout() = 0;
}
}
lock();
return true;
}
} // ns OS
|
#include<bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll long long
#define fastoi ios::sync_with_stdio(0); cin.tie(0);
#define printNPrecision(afterDigit,value) cout << fixed << setprecision(12) << value <<endl;
#define llu unsigned long long
#define lld long long
#define U unsigned int
#define LSOne(S) (S & (-S))
#define isBitSet(S, i) ((S >> i) & 1)
const int MOD = 1000000007;
const int MAX = 1000005;
void solve(){
ll a,b;
cin>>a>>b;
cout<<max(a,b)<<" "<<a+b<<endl;
}
int main()
{
fastoi ;
int t;
cin>>t;
while(t--)
solve();
return 0;
}
|
// Copyright (c) 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 "net/url_request/url_request_http_job.h"
#include <stdint.h>
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/test/bind_test_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "net/base/auth.h"
#include "net/base/isolation_info.h"
#include "net/base/request_priority.h"
#include "net/cert/ct_policy_status.h"
#include "net/cookies/cookie_monster.h"
#include "net/cookies/cookie_store_test_callbacks.h"
#include "net/cookies/cookie_store_test_helpers.h"
#include "net/http/http_transaction_factory.h"
#include "net/http/http_transaction_test_util.h"
#include "net/log/net_log_event_type.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_util.h"
#include "net/net_buildflags.h"
#include "net/proxy_resolution/configured_proxy_resolution_service.h"
#include "net/socket/next_proto.h"
#include "net/socket/socket_test_util.h"
#include "net/test/cert_test_util.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/gtest_util.h"
#include "net/test/test_data_directory.h"
#include "net/test/test_with_task_environment.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_test_util.h"
#include "net/url_request/websocket_handshake_userdata_key.h"
#include "net/websockets/websocket_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/url_constants.h"
#if defined(OS_ANDROID)
#include "base/android/jni_android.h"
#include "net/net_test_jni_headers/AndroidNetworkLibraryTestUtil_jni.h"
#endif
using net::test::IsError;
using net::test::IsOk;
namespace net {
namespace {
using ::testing::Return;
const char kSimpleGetMockWrite[] =
"GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n"
"User-Agent: \r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: en-us,fr\r\n\r\n";
const char kSimpleHeadMockWrite[] =
"HEAD / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n"
"User-Agent: \r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: en-us,fr\r\n\r\n";
const char kTrustAnchorRequestHistogram[] =
"Net.Certificate.TrustAnchor.Request";
const char kCTComplianceHistogramName[] =
"Net.CertificateTransparency.RequestComplianceStatus";
const char kCTRequiredHistogramName[] =
"Net.CertificateTransparency.CTRequiredRequestComplianceStatus";
// Inherit from URLRequestHttpJob to expose the priority and some
// other hidden functions.
class TestURLRequestHttpJob : public URLRequestHttpJob {
public:
explicit TestURLRequestHttpJob(URLRequest* request)
: URLRequestHttpJob(request,
request->context()->network_delegate(),
request->context()->http_user_agent_settings()),
use_null_source_stream_(false) {}
~TestURLRequestHttpJob() override = default;
// URLRequestJob implementation:
std::unique_ptr<SourceStream> SetUpSourceStream() override {
if (use_null_source_stream_)
return nullptr;
return URLRequestHttpJob::SetUpSourceStream();
}
void set_use_null_source_stream(bool use_null_source_stream) {
use_null_source_stream_ = use_null_source_stream;
}
using URLRequestHttpJob::SetPriority;
using URLRequestHttpJob::Start;
using URLRequestHttpJob::Kill;
using URLRequestHttpJob::priority;
private:
bool use_null_source_stream_;
DISALLOW_COPY_AND_ASSIGN(TestURLRequestHttpJob);
};
class URLRequestHttpJobSetUpSourceTest : public TestWithTaskEnvironment {
public:
URLRequestHttpJobSetUpSourceTest() : context_(true) {
test_job_interceptor_ = new TestJobInterceptor();
EXPECT_TRUE(test_job_factory_.SetProtocolHandler(
url::kHttpScheme, base::WrapUnique(test_job_interceptor_)));
context_.set_job_factory(&test_job_factory_);
context_.set_client_socket_factory(&socket_factory_);
context_.Init();
}
protected:
MockClientSocketFactory socket_factory_;
// |test_job_interceptor_| is owned by |test_job_factory_|.
TestJobInterceptor* test_job_interceptor_;
URLRequestJobFactoryImpl test_job_factory_;
TestURLRequestContext context_;
TestDelegate delegate_;
};
// Tests that if SetUpSourceStream() returns nullptr, the request fails.
TEST_F(URLRequestHttpJobSetUpSourceTest, SetUpSourceFails) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
std::unique_ptr<URLRequest> request =
context_.CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
auto job = std::make_unique<TestURLRequestHttpJob>(request.get());
job->set_use_null_source_stream(true);
test_job_interceptor_->set_main_intercept_job(std::move(job));
request->Start();
delegate_.RunUntilComplete();
EXPECT_EQ(ERR_CONTENT_DECODING_INIT_FAILED, delegate_.request_status());
}
// Tests that if there is an unknown content-encoding type, the raw response
// body is passed through.
TEST_F(URLRequestHttpJobSetUpSourceTest, UnknownEncoding) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Encoding: foo, gzip\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
std::unique_ptr<URLRequest> request =
context_.CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
auto job = std::make_unique<TestURLRequestHttpJob>(request.get());
test_job_interceptor_->set_main_intercept_job(std::move(job));
request->Start();
delegate_.RunUntilComplete();
EXPECT_EQ(OK, delegate_.request_status());
EXPECT_EQ("Test Content", delegate_.data_received());
}
class URLRequestHttpJobWithProxy : public WithTaskEnvironment {
public:
explicit URLRequestHttpJobWithProxy(
std::unique_ptr<ProxyResolutionService> proxy_resolution_service)
: proxy_resolution_service_(std::move(proxy_resolution_service)),
context_(new TestURLRequestContext(true)) {
context_->set_client_socket_factory(&socket_factory_);
context_->set_network_delegate(&network_delegate_);
context_->set_proxy_resolution_service(proxy_resolution_service_.get());
context_->Init();
}
MockClientSocketFactory socket_factory_;
TestNetworkDelegate network_delegate_;
std::unique_ptr<ProxyResolutionService> proxy_resolution_service_;
std::unique_ptr<TestURLRequestContext> context_;
private:
DISALLOW_COPY_AND_ASSIGN(URLRequestHttpJobWithProxy);
};
// Tests that when proxy is not used, the proxy server is set correctly on the
// URLRequest.
TEST(URLRequestHttpJobWithProxy, TestFailureWithoutProxy) {
URLRequestHttpJobWithProxy http_job_with_proxy(nullptr);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET)};
StaticSocketDataProvider socket_data(reads, writes);
http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
http_job_with_proxy.context_->CreateRequest(
GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsError(ERR_CONNECTION_RESET));
EXPECT_EQ(ProxyServer::Direct(), request->proxy_server());
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
// Tests that when one proxy is in use and the connection to the proxy server
// fails, the proxy server is still set correctly on the URLRequest.
TEST(URLRequestHttpJobWithProxy, TestSuccessfulWithOneProxy) {
const char kSimpleProxyGetMockWrite[] =
"GET http://www.example.com/ HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Proxy-Connection: keep-alive\r\n"
"User-Agent: \r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: en-us,fr\r\n\r\n";
const ProxyServer proxy_server =
ProxyServer::FromURI("http://origin.net:80", ProxyServer::SCHEME_HTTP);
std::unique_ptr<ProxyResolutionService> proxy_resolution_service =
ConfiguredProxyResolutionService::CreateFixedFromPacResult(
proxy_server.ToPacString(), TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite writes[] = {MockWrite(kSimpleProxyGetMockWrite)};
MockRead reads[] = {MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET)};
StaticSocketDataProvider socket_data(reads, writes);
URLRequestHttpJobWithProxy http_job_with_proxy(
std::move(proxy_resolution_service));
http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
http_job_with_proxy.context_->CreateRequest(
GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsError(ERR_CONNECTION_RESET));
// When request fails due to proxy connection errors, the proxy server should
// still be set on the |request|.
EXPECT_EQ(proxy_server, request->proxy_server());
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(0, request->GetTotalReceivedBytes());
}
// Tests that when two proxies are in use and the connection to the first proxy
// server fails, the proxy server is set correctly on the URLRequest.
TEST(URLRequestHttpJobWithProxy,
TestContentLengthSuccessfulRequestWithTwoProxies) {
const ProxyServer proxy_server =
ProxyServer::FromURI("http://origin.net:80", ProxyServer::SCHEME_HTTP);
// Connection to |proxy_server| would fail. Request should be fetched over
// DIRECT.
std::unique_ptr<ProxyResolutionService> proxy_resolution_service =
ConfiguredProxyResolutionService::CreateFixedFromPacResult(
proxy_server.ToPacString() + "; " +
ProxyServer::Direct().ToPacString(),
TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content"), MockRead(ASYNC, OK)};
MockConnect mock_connect_1(SYNCHRONOUS, ERR_CONNECTION_RESET);
StaticSocketDataProvider connect_data_1;
connect_data_1.set_connect_data(mock_connect_1);
StaticSocketDataProvider socket_data(reads, writes);
URLRequestHttpJobWithProxy http_job_with_proxy(
std::move(proxy_resolution_service));
http_job_with_proxy.socket_factory_.AddSocketDataProvider(&connect_data_1);
http_job_with_proxy.socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
http_job_with_proxy.context_->CreateRequest(
GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(ProxyServer::Direct(), request->proxy_server());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
class URLRequestHttpJobTest : public TestWithTaskEnvironment {
protected:
URLRequestHttpJobTest() : context_(true) {
context_.set_http_transaction_factory(&network_layer_);
// The |test_job_factory_| takes ownership of the interceptor.
test_job_interceptor_ = new TestJobInterceptor();
EXPECT_TRUE(test_job_factory_.SetProtocolHandler(
url::kHttpScheme, base::WrapUnique(test_job_interceptor_)));
context_.set_job_factory(&test_job_factory_);
context_.set_net_log(&net_log_);
context_.Init();
req_ =
context_.CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
}
MockNetworkLayer network_layer_;
// |test_job_interceptor_| is owned by |test_job_factory_|.
TestJobInterceptor* test_job_interceptor_;
URLRequestJobFactoryImpl test_job_factory_;
TestURLRequestContext context_;
TestDelegate delegate_;
RecordingTestNetLog net_log_;
std::unique_ptr<URLRequest> req_;
};
class URLRequestHttpJobWithMockSocketsTest : public TestWithTaskEnvironment {
protected:
URLRequestHttpJobWithMockSocketsTest()
: context_(new TestURLRequestContext(true)) {
context_->set_client_socket_factory(&socket_factory_);
context_->set_network_delegate(&network_delegate_);
context_->Init();
}
MockClientSocketFactory socket_factory_;
TestNetworkDelegate network_delegate_;
std::unique_ptr<TestURLRequestContext> context_;
};
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestContentLengthSuccessfulRequest) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
// Tests a successful HEAD request.
TEST_F(URLRequestHttpJobWithMockSocketsTest, TestSuccessfulHead) {
MockWrite writes[] = {MockWrite(kSimpleHeadMockWrite)};
MockRead reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 0\r\n\r\n")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->set_method("HEAD");
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
// Similar to above test but tests that even if response body is there in the
// HEAD response stream, it should not be read due to HttpStreamParser's logic.
TEST_F(URLRequestHttpJobWithMockSocketsTest, TestSuccessfulHeadWithContent) {
MockWrite writes[] = {MockWrite(kSimpleHeadMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->set_method("HEAD");
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads) - 12, request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest, TestSuccessfulCachedHeadRequest) {
const url::Origin kOrigin1 =
url::Origin::Create(GURL("http://www.example.com"));
const IsolationInfo kTestIsolationInfo =
IsolationInfo::CreateForInternalRequest(kOrigin1);
// Cache the response.
{
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->set_isolation_info(kTestIsolationInfo);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
// Send a HEAD request for the cached response.
{
MockWrite writes[] = {MockWrite(kSimpleHeadMockWrite)};
MockRead reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 0\r\n\r\n")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("http://www.example.com"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
// Use the cached version.
request->SetLoadFlags(LOAD_SKIP_CACHE_VALIDATION);
request->set_method("HEAD");
request->set_isolation_info(kTestIsolationInfo);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(0, request->GetTotalSentBytes());
EXPECT_EQ(0, request->GetTotalReceivedBytes());
}
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestContentLengthSuccessfulHttp09Request) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("Test Content"),
MockRead(net::SYNCHRONOUS, net::OK)};
StaticSocketDataProvider socket_data(reads, base::span<MockWrite>());
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest, TestContentLengthFailedRequest) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 20\r\n\r\n"),
MockRead("Test Content"),
MockRead(net::SYNCHRONOUS, net::ERR_FAILED)};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsError(ERR_FAILED));
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestContentLengthCancelledRequest) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 20\r\n\r\n"),
MockRead("Test Content"),
MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
delegate.set_cancel_in_received_data(true);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestRawHeaderSizeSuccessfullRequest) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
const std::string& response_header =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n";
const std::string& content_data = "Test Content";
MockRead reads[] = {MockRead(response_header.c_str()),
MockRead(content_data.c_str()),
MockRead(net::SYNCHRONOUS, net::OK)};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_EQ(OK, delegate.request_status());
EXPECT_EQ(static_cast<int>(content_data.size()),
request->received_response_content_length());
EXPECT_EQ(static_cast<int>(response_header.size()),
request->raw_header_size());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestRawHeaderSizeSuccessfull100ContinueRequest) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
const std::string& continue_header = "HTTP/1.1 100 Continue\r\n\r\n";
const std::string& response_header =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n";
const std::string& content_data = "Test Content";
MockRead reads[] = {
MockRead(continue_header.c_str()), MockRead(response_header.c_str()),
MockRead(content_data.c_str()), MockRead(net::SYNCHRONOUS, net::OK)};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
delegate.RunUntilComplete();
EXPECT_EQ(OK, delegate.request_status());
EXPECT_EQ(static_cast<int>(content_data.size()),
request->received_response_content_length());
EXPECT_EQ(static_cast<int>(continue_header.size() + response_header.size()),
request->raw_header_size());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestRawHeaderSizeFailureTruncatedHeaders) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.0 200 OK\r\n"
"Content-Len"),
MockRead(net::SYNCHRONOUS, net::OK)};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
delegate.set_cancel_in_response_started(true);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(ERR_ABORTED, delegate.request_status());
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(28, request->raw_header_size());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestRawHeaderSizeSuccessfullContinuiousRead) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
const std::string& header_data =
"HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n";
const std::string& content_data = "Test Content";
std::string single_read_content = header_data;
single_read_content.append(content_data);
MockRead reads[] = {MockRead(single_read_content.c_str())};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_EQ(OK, delegate.request_status());
EXPECT_EQ(static_cast<int>(content_data.size()),
request->received_response_content_length());
EXPECT_EQ(static_cast<int>(header_data.size()), request->raw_header_size());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestNetworkBytesRedirectedRequest) {
MockWrite redirect_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.redirect.com\r\n"
"Connection: keep-alive\r\n"
"User-Agent: \r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: en-us,fr\r\n\r\n")};
MockRead redirect_reads[] = {
MockRead("HTTP/1.1 302 Found\r\n"
"Location: http://www.example.com\r\n\r\n"),
};
StaticSocketDataProvider redirect_socket_data(redirect_reads,
redirect_writes);
socket_factory_.AddSocketDataProvider(&redirect_socket_data);
MockWrite final_writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead final_reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider final_socket_data(final_reads, final_writes);
socket_factory_.AddSocketDataProvider(&final_socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.redirect.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
ASSERT_TRUE(request->is_pending());
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
// Should not include the redirect.
EXPECT_EQ(CountWriteBytes(final_writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(final_reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestNetworkBytesCancelledAfterHeaders) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n\r\n")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
delegate.set_cancel_in_response_started(true);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestNetworkBytesCancelledImmediately) {
StaticSocketDataProvider socket_data;
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
request->Cancel();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
EXPECT_EQ(0, request->received_response_content_length());
EXPECT_EQ(0, request->GetTotalSentBytes());
EXPECT_EQ(0, request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest, TestHttpTimeToFirstByte) {
base::HistogramTester histograms;
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
histograms.ExpectTotalCount("Net.HttpTimeToFirstByte", 0);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectTotalCount("Net.HttpTimeToFirstByte", 1);
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpTimeToFirstByteForCancelledTask) {
base::HistogramTester histograms;
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
request->Cancel();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
histograms.ExpectTotalCount("Net.HttpTimeToFirstByte", 0);
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobSuccessPriorityKeyedTotalTime) {
base::HistogramTester histograms;
for (int priority = 0; priority < net::NUM_PRIORITIES; ++priority) {
for (int request_index = 0; request_index <= priority; ++request_index) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com/"),
static_cast<net::RequestPriority>(priority),
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
}
}
for (int priority = 0; priority < net::NUM_PRIORITIES; ++priority) {
histograms.ExpectTotalCount("Net.HttpJob.TotalTimeSuccess.Priority" +
base::NumberToString(priority),
priority + 1);
}
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobRecordsTrustAnchorHistograms) {
SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
ssl_socket_data.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
// Simulate a certificate chain issued by "C=US, O=Google Trust Services LLC,
// CN=GTS Root R4". This publicly-trusted root was chosen as it was included
// in 2017 and is not anticipated to be removed from all supported platforms
// for a few decades.
// Note: The actual cert in |cert| does not matter for this testing.
SHA256HashValue leaf_hash = {{0}};
SHA256HashValue intermediate_hash = {{1}};
SHA256HashValue root_hash = {
{0x98, 0x47, 0xe5, 0x65, 0x3e, 0x5e, 0x9e, 0x84, 0x75, 0x16, 0xe5,
0xcb, 0x81, 0x86, 0x06, 0xaa, 0x75, 0x44, 0xa1, 0x9b, 0xe6, 0x7f,
0xd7, 0x36, 0x6d, 0x50, 0x69, 0x88, 0xe8, 0xd8, 0x43, 0x47}};
ssl_socket_data.ssl_info.public_key_hashes.push_back(HashValue(leaf_hash));
ssl_socket_data.ssl_info.public_key_hashes.push_back(
HashValue(intermediate_hash));
ssl_socket_data.ssl_info.public_key_hashes.push_back(HashValue(root_hash));
const base::HistogramBase::Sample kGTSRootR4HistogramID = 486;
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
base::HistogramTester histograms;
histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 1);
histograms.ExpectUniqueSample(kTrustAnchorRequestHistogram,
kGTSRootR4HistogramID, 1);
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobDoesNotRecordTrustAnchorHistogramsWhenNoNetworkLoad) {
SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
ssl_socket_data.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
// Simulate a request loaded from a non-network source, such as a disk
// cache.
ssl_socket_data.ssl_info.public_key_hashes.clear();
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
base::HistogramTester histograms;
histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
}
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobRecordsMostSpecificTrustAnchorHistograms) {
SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
ssl_socket_data.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
// Simulate a certificate chain issued by "C=US, O=Google Trust Services LLC,
// CN=GTS Root R4". This publicly-trusted root was chosen as it was included
// in 2017 and is not anticipated to be removed from all supported platforms
// for a few decades.
// Note: The actual cert in |cert| does not matter for this testing.
SHA256HashValue leaf_hash = {{0}};
SHA256HashValue intermediate_hash = {{1}};
SHA256HashValue gts_root_r3_hash = {
{0x41, 0x79, 0xed, 0xd9, 0x81, 0xef, 0x74, 0x74, 0x77, 0xb4, 0x96,
0x26, 0x40, 0x8a, 0xf4, 0x3d, 0xaa, 0x2c, 0xa7, 0xab, 0x7f, 0x9e,
0x08, 0x2c, 0x10, 0x60, 0xf8, 0x40, 0x96, 0x77, 0x43, 0x48}};
SHA256HashValue gts_root_r4_hash = {
{0x98, 0x47, 0xe5, 0x65, 0x3e, 0x5e, 0x9e, 0x84, 0x75, 0x16, 0xe5,
0xcb, 0x81, 0x86, 0x06, 0xaa, 0x75, 0x44, 0xa1, 0x9b, 0xe6, 0x7f,
0xd7, 0x36, 0x6d, 0x50, 0x69, 0x88, 0xe8, 0xd8, 0x43, 0x47}};
ssl_socket_data.ssl_info.public_key_hashes.push_back(HashValue(leaf_hash));
ssl_socket_data.ssl_info.public_key_hashes.push_back(
HashValue(intermediate_hash));
ssl_socket_data.ssl_info.public_key_hashes.push_back(
HashValue(gts_root_r3_hash));
ssl_socket_data.ssl_info.public_key_hashes.push_back(
HashValue(gts_root_r4_hash));
const base::HistogramBase::Sample kGTSRootR3HistogramID = 485;
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
base::HistogramTester histograms;
histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 0);
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectTotalCount(kTrustAnchorRequestHistogram, 1);
histograms.ExpectUniqueSample(kTrustAnchorRequestHistogram,
kGTSRootR3HistogramID, 1);
}
// Tests that the CT compliance histogram is recorded, even if CT is not
// required.
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobRecordsCTComplianceHistograms) {
SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
ssl_socket_data.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ssl_socket_data.ssl_info.is_issued_by_known_root = true;
ssl_socket_data.ssl_info.ct_policy_compliance_required = false;
ssl_socket_data.ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
base::HistogramTester histograms;
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectUniqueSample(
kCTComplianceHistogramName,
static_cast<int32_t>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS),
1);
// CTRequiredRequestComplianceStatus should *not* have been recorded because
// it is only recorded for requests which are required to be compliant.
histograms.ExpectTotalCount(kCTRequiredHistogramName, 0);
}
// Tests that the CT compliance histograms are not recorded for
// locally-installed trust anchors.
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobDoesNotRecordCTComplianceHistogramsForLocalRoot) {
SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
ssl_socket_data.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ssl_socket_data.ssl_info.is_issued_by_known_root = false;
ssl_socket_data.ssl_info.ct_policy_compliance_required = false;
ssl_socket_data.ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
base::HistogramTester histograms;
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectTotalCount(kCTComplianceHistogramName, 0);
histograms.ExpectTotalCount(kCTRequiredHistogramName, 0);
}
// Tests that the CT compliance histogram is recorded when CT is required but
// not compliant.
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobRecordsCTRequiredHistogram) {
SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
ssl_socket_data.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ssl_socket_data.ssl_info.is_issued_by_known_root = true;
ssl_socket_data.ssl_info.ct_policy_compliance_required = true;
ssl_socket_data.ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
base::HistogramTester histograms;
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectUniqueSample(
kCTComplianceHistogramName,
static_cast<int32_t>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS),
1);
histograms.ExpectUniqueSample(
kCTRequiredHistogramName,
static_cast<int32_t>(ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS),
1);
}
// Tests that the CT compliance histograms are not recorded when there is an
// unrelated certificate error.
TEST_F(URLRequestHttpJobWithMockSocketsTest,
TestHttpJobDoesNotRecordCTHistogramWithCertError) {
SSLSocketDataProvider ssl_socket_data(net::ASYNC, net::OK);
ssl_socket_data.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ssl_socket_data.ssl_info.is_issued_by_known_root = true;
ssl_socket_data.ssl_info.ct_policy_compliance_required = true;
ssl_socket_data.ssl_info.ct_policy_compliance =
ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS;
ssl_socket_data.ssl_info.cert_status = net::CERT_STATUS_DATE_INVALID;
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data);
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
base::HistogramTester histograms;
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context_->CreateRequest(
GURL("https://www.example.com/"), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsOk());
histograms.ExpectTotalCount(kCTComplianceHistogramName, 0);
histograms.ExpectTotalCount(kCTRequiredHistogramName, 0);
}
TEST_F(URLRequestHttpJobWithMockSocketsTest, EncodingAdvertisementOnRange) {
MockWrite writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n"
"User-Agent: \r\n"
"Accept-Encoding: identity\r\n"
"Accept-Language: en-us,fr\r\n"
"Range: bytes=0-1023\r\n\r\n")};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
// Make the extra header to trigger the change in "Accepted-Encoding"
HttpRequestHeaders headers;
headers.SetHeader("Range", "bytes=0-1023");
request->SetExtraRequestHeaders(headers);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithMockSocketsTest, RangeRequestOverrideEncoding) {
MockWrite writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"User-Agent: \r\n"
"Accept-Language: en-us,fr\r\n"
"Range: bytes=0-1023\r\n\r\n")};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
// Explicitly set "Accept-Encoding" to make sure it's not overridden by
// AddExtraHeaders
HttpRequestHeaders headers;
headers.SetHeader("Accept-Encoding", "gzip, deflate");
headers.SetHeader("Range", "bytes=0-1023");
request->SetExtraRequestHeaders(headers);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobTest, TestCancelWhileReadingCookies) {
DelayedCookieMonster cookie_monster;
TestURLRequestContext context(true);
context.set_cookie_store(&cookie_monster);
context.Init();
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context.CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
request->Cancel();
delegate.RunUntilComplete();
EXPECT_THAT(delegate.request_status(), IsError(ERR_ABORTED));
}
// Make sure that SetPriority actually sets the URLRequestHttpJob's
// priority, before start. Other tests handle the after start case.
TEST_F(URLRequestHttpJobTest, SetPriorityBasic) {
auto job = std::make_unique<TestURLRequestHttpJob>(req_.get());
EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
job->SetPriority(LOWEST);
EXPECT_EQ(LOWEST, job->priority());
job->SetPriority(LOW);
EXPECT_EQ(LOW, job->priority());
}
// Make sure that URLRequestHttpJob passes on its priority to its
// transaction on start.
TEST_F(URLRequestHttpJobTest, SetTransactionPriorityOnStart) {
test_job_interceptor_->set_main_intercept_job(
std::make_unique<TestURLRequestHttpJob>(req_.get()));
req_->SetPriority(LOW);
EXPECT_FALSE(network_layer_.last_transaction());
req_->Start();
ASSERT_TRUE(network_layer_.last_transaction());
EXPECT_EQ(LOW, network_layer_.last_transaction()->priority());
}
// Make sure that URLRequestHttpJob passes on its priority updates to
// its transaction.
TEST_F(URLRequestHttpJobTest, SetTransactionPriority) {
test_job_interceptor_->set_main_intercept_job(
std::make_unique<TestURLRequestHttpJob>(req_.get()));
req_->SetPriority(LOW);
req_->Start();
ASSERT_TRUE(network_layer_.last_transaction());
EXPECT_EQ(LOW, network_layer_.last_transaction()->priority());
req_->SetPriority(HIGHEST);
EXPECT_EQ(HIGHEST, network_layer_.last_transaction()->priority());
}
TEST_F(URLRequestHttpJobTest, HSTSInternalRedirectTest) {
// Setup HSTS state.
context_.transport_security_state()->AddHSTS(
"upgrade.test", base::Time::Now() + base::TimeDelta::FromSeconds(10),
true);
ASSERT_TRUE(
context_.transport_security_state()->ShouldUpgradeToSSL("upgrade.test"));
ASSERT_FALSE(context_.transport_security_state()->ShouldUpgradeToSSL(
"no-upgrade.test"));
struct TestCase {
const char* url;
bool upgrade_expected;
const char* url_expected;
} cases[] = {
{"http://upgrade.test/", true, "https://upgrade.test/"},
{"http://upgrade.test:123/", true, "https://upgrade.test:123/"},
{"http://no-upgrade.test/", false, "http://no-upgrade.test/"},
{"http://no-upgrade.test:123/", false, "http://no-upgrade.test:123/"},
#if BUILDFLAG(ENABLE_WEBSOCKETS)
{"ws://upgrade.test/", true, "wss://upgrade.test/"},
{"ws://upgrade.test:123/", true, "wss://upgrade.test:123/"},
{"ws://no-upgrade.test/", false, "ws://no-upgrade.test/"},
{"ws://no-upgrade.test:123/", false, "ws://no-upgrade.test:123/"},
#endif // BUILDFLAG(ENABLE_WEBSOCKETS)
};
for (const auto& test : cases) {
SCOPED_TRACE(test.url);
TestDelegate d;
TestNetworkDelegate network_delegate;
std::unique_ptr<URLRequest> r(context_.CreateRequest(
GURL(test.url), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
net_log_.Clear();
r->Start();
d.RunUntilComplete();
if (test.upgrade_expected) {
auto entries = net_log_.GetEntriesWithType(
net::NetLogEventType::URL_REQUEST_REDIRECT_JOB);
int redirects = entries.size();
for (const auto& entry : entries) {
EXPECT_EQ("HSTS", GetStringValueFromParams(entry, "reason"));
}
EXPECT_EQ(1, redirects);
EXPECT_EQ(1, d.received_redirect_count());
EXPECT_EQ(2u, r->url_chain().size());
} else {
EXPECT_EQ(0, d.received_redirect_count());
EXPECT_EQ(1u, r->url_chain().size());
}
EXPECT_EQ(GURL(test.url_expected), r->url());
}
}
TEST_F(URLRequestHttpJobTest, HSTSInternalRedirectCallback) {
EmbeddedTestServer https_test(EmbeddedTestServer::TYPE_HTTPS);
https_test.AddDefaultHandlers(base::FilePath());
ASSERT_TRUE(https_test.Start());
TestURLRequestContext context;
context.transport_security_state()->AddHSTS(
"127.0.0.1", base::Time::Now() + base::TimeDelta::FromSeconds(10), true);
ASSERT_TRUE(
context.transport_security_state()->ShouldUpgradeToSSL("127.0.0.1"));
GURL::Replacements replace_scheme;
replace_scheme.SetSchemeStr("http");
{
GURL url(
https_test.GetURL("/echoheader").ReplaceComponents(replace_scheme));
TestDelegate delegate;
HttpRequestHeaders extra_headers;
extra_headers.SetHeader("X-HSTS-Test", "1");
HttpRawRequestHeaders raw_req_headers;
std::unique_ptr<URLRequest> r(context.CreateRequest(
url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
r->SetExtraRequestHeaders(extra_headers);
r->SetRequestHeadersCallback(base::BindRepeating(
&HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
r->Start();
delegate.RunUntilRedirect();
EXPECT_FALSE(raw_req_headers.headers().empty());
std::string value;
EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-HSTS-Test", &value));
EXPECT_EQ("1", value);
EXPECT_EQ("GET /echoheader HTTP/1.1\r\n", raw_req_headers.request_line());
raw_req_headers = HttpRawRequestHeaders();
r->FollowDeferredRedirect(base::nullopt /* removed_headers */,
base::nullopt /* modified_headers */);
delegate.RunUntilComplete();
EXPECT_FALSE(raw_req_headers.headers().empty());
}
{
GURL url(https_test.GetURL("/echoheader?foo=bar")
.ReplaceComponents(replace_scheme));
TestDelegate delegate;
HttpRawRequestHeaders raw_req_headers;
std::unique_ptr<URLRequest> r(context.CreateRequest(
url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
r->SetRequestHeadersCallback(base::BindRepeating(
&HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
r->Start();
delegate.RunUntilRedirect();
EXPECT_EQ("GET /echoheader?foo=bar HTTP/1.1\r\n",
raw_req_headers.request_line());
}
{
GURL url(
https_test.GetURL("/echoheader#foo").ReplaceComponents(replace_scheme));
TestDelegate delegate;
HttpRawRequestHeaders raw_req_headers;
std::unique_ptr<URLRequest> r(context.CreateRequest(
url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
r->SetRequestHeadersCallback(base::BindRepeating(
&HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
r->Start();
delegate.RunUntilRedirect();
EXPECT_EQ("GET /echoheader HTTP/1.1\r\n", raw_req_headers.request_line());
}
}
class URLRequestHttpJobWithBrotliSupportTest : public TestWithTaskEnvironment {
protected:
URLRequestHttpJobWithBrotliSupportTest()
: context_(new TestURLRequestContext(true)) {
auto params = std::make_unique<HttpNetworkSession::Params>();
context_->set_enable_brotli(true);
context_->set_http_network_session_params(std::move(params));
context_->set_client_socket_factory(&socket_factory_);
context_->Init();
}
MockClientSocketFactory socket_factory_;
std::unique_ptr<TestURLRequestContext> context_;
};
TEST_F(URLRequestHttpJobWithBrotliSupportTest, NoBrotliAdvertisementOverHttp) {
MockWrite writes[] = {MockWrite(kSimpleGetMockWrite)};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("http://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
TEST_F(URLRequestHttpJobWithBrotliSupportTest, BrotliAdvertisement) {
net::SSLSocketDataProvider ssl_socket_data_provider(net::ASYNC, net::OK);
ssl_socket_data_provider.next_proto = kProtoHTTP11;
ssl_socket_data_provider.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "unittest.selfsigned.der");
ASSERT_TRUE(ssl_socket_data_provider.ssl_info.cert);
socket_factory_.AddSSLSocketDataProvider(&ssl_socket_data_provider);
MockWrite writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n"
"User-Agent: \r\n"
"Accept-Encoding: gzip, deflate, br\r\n"
"Accept-Language: en-us,fr\r\n\r\n")};
MockRead reads[] = {MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 12\r\n\r\n"),
MockRead("Test Content")};
StaticSocketDataProvider socket_data(reads, writes);
socket_factory_.AddSocketDataProvider(&socket_data);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_->CreateRequest(GURL("https://www.example.com"), DEFAULT_PRIORITY,
&delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate.request_status(), IsOk());
EXPECT_EQ(12, request->received_response_content_length());
EXPECT_EQ(CountWriteBytes(writes), request->GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(reads), request->GetTotalReceivedBytes());
}
#if defined(OS_ANDROID)
TEST_F(URLRequestHttpJobTest, AndroidCleartextPermittedTest) {
context_.set_check_cleartext_permitted(true);
static constexpr struct TestCase {
const char* url;
bool cleartext_permitted;
bool should_block;
int expected_per_host_call_count;
int expected_default_call_count;
} kTestCases[] = {
{"http://unblocked.test/", true, false, 1, 0},
{"https://unblocked.test/", true, false, 0, 0},
{"http://blocked.test/", false, true, 1, 0},
{"https://blocked.test/", false, false, 0, 0},
// If determining the per-host cleartext policy causes an
// IllegalArgumentException (because the hostname is invalid),
// the default configuration should be applied, and the
// exception should not cause a JNI error.
{"http://./", false, true, 1, 1},
{"http://./", true, false, 1, 1},
// Even if the host name would be considered invalid, https
// schemes should not trigger cleartext policy checks.
{"https://./", false, false, 0, 0},
};
JNIEnv* env = base::android::AttachCurrentThread();
for (const TestCase& test : kTestCases) {
Java_AndroidNetworkLibraryTestUtil_setUpSecurityPolicyForTesting(
env, test.cleartext_permitted);
TestDelegate delegate;
std::unique_ptr<URLRequest> request =
context_.CreateRequest(GURL(test.url), DEFAULT_PRIORITY, &delegate,
TRAFFIC_ANNOTATION_FOR_TESTS);
request->Start();
delegate.RunUntilComplete();
if (test.should_block) {
EXPECT_THAT(delegate.request_status(),
IsError(ERR_CLEARTEXT_NOT_PERMITTED));
} else {
// Should fail since there's no test server running
EXPECT_THAT(delegate.request_status(), IsError(ERR_FAILED));
}
EXPECT_EQ(
Java_AndroidNetworkLibraryTestUtil_getPerHostCleartextCheckCount(env),
test.expected_per_host_call_count);
EXPECT_EQ(
Java_AndroidNetworkLibraryTestUtil_getDefaultCleartextCheckCount(env),
test.expected_default_call_count);
}
}
#endif
#if BUILDFLAG(ENABLE_WEBSOCKETS)
class URLRequestHttpJobWebSocketTest : public TestWithTaskEnvironment {
protected:
URLRequestHttpJobWebSocketTest() : context_(true) {
context_.set_network_delegate(&network_delegate_);
context_.set_client_socket_factory(&socket_factory_);
context_.Init();
req_ =
context_.CreateRequest(GURL("ws://www.example.org"), DEFAULT_PRIORITY,
&delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
}
// A Network Delegate is required for the WebSocketHandshakeStreamBase
// object to be passed on to the HttpNetworkTransaction.
TestNetworkDelegate network_delegate_;
TestURLRequestContext context_;
MockClientSocketFactory socket_factory_;
TestDelegate delegate_;
std::unique_ptr<URLRequest> req_;
};
TEST_F(URLRequestHttpJobWebSocketTest, RejectedWithoutCreateHelper) {
req_->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate_.request_status(), IsError(ERR_DISALLOWED_URL_SCHEME));
}
TEST_F(URLRequestHttpJobWebSocketTest, CreateHelperPassedThrough) {
HttpRequestHeaders headers;
headers.SetHeader("Connection", "Upgrade");
headers.SetHeader("Upgrade", "websocket");
headers.SetHeader("Origin", "http://www.example.org");
headers.SetHeader("Sec-WebSocket-Version", "13");
req_->SetExtraRequestHeaders(headers);
MockWrite writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: Upgrade\r\n"
"Upgrade: websocket\r\n"
"Origin: http://www.example.org\r\n"
"Sec-WebSocket-Version: 13\r\n"
"User-Agent: \r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: en-us,fr\r\n"
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"Sec-WebSocket-Extensions: permessage-deflate; "
"client_max_window_bits\r\n\r\n")};
MockRead reads[] = {
MockRead("HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"),
MockRead(ASYNC, 0)};
StaticSocketDataProvider data(reads, writes);
socket_factory_.AddSocketDataProvider(&data);
auto websocket_stream_create_helper =
std::make_unique<TestWebSocketHandshakeStreamCreateHelper>();
req_->SetUserData(kWebSocketHandshakeUserDataKey,
std::move(websocket_stream_create_helper));
req_->SetLoadFlags(LOAD_DISABLE_CACHE);
req_->Start();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(delegate_.request_status(), IsOk());
EXPECT_TRUE(delegate_.response_completed());
EXPECT_TRUE(data.AllWriteDataConsumed());
EXPECT_TRUE(data.AllReadDataConsumed());
}
#endif // BUILDFLAG(ENABLE_WEBSOCKETS)
bool SetAllCookies(CookieMonster* cm, const CookieList& list) {
DCHECK(cm);
ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback;
cm->SetAllCookiesAsync(list, callback.MakeCallback());
callback.WaitUntilDone();
return callback.result().IsInclude();
}
bool CreateAndSetCookie(CookieStore* cs,
const GURL& url,
const std::string& cookie_line) {
auto cookie = CanonicalCookie::Create(url, cookie_line, base::Time::Now(),
base::nullopt);
if (!cookie)
return false;
DCHECK(cs);
ResultSavingCookieCallback<CanonicalCookie::CookieInclusionStatus> callback;
cs->SetCanonicalCookieAsync(std::move(cookie), url,
CookieOptions::MakeAllInclusive(),
callback.MakeCallback());
callback.WaitUntilDone();
return callback.result().IsInclude();
}
void RunRequest(TestURLRequestContext* context, const GURL& url) {
TestDelegate delegate;
std::unique_ptr<URLRequest> request = context->CreateRequest(
url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
// Make this a laxly same-site context to allow setting
// SameSite=Lax-by-default cookies.
request->set_site_for_cookies(SiteForCookies::FromUrl(url));
request->Start();
delegate.RunUntilComplete();
}
} // namespace
TEST_F(URLRequestHttpJobTest, CookieSchemeRequestSchemeHistogram) {
base::HistogramTester histograms;
const std::string test_histogram = "Cookie.CookieSchemeRequestScheme";
CookieMonster cm(nullptr, nullptr);
TestURLRequestContext context(true);
context.set_cookie_store(&cm);
context.Init();
// Secure set cookie marked as Unset source scheme.
// Using port 7 because it fails the transaction without sending a request and
// prevents a timeout due to the fake addresses. Because we only need the
// headers to be generated (and thus the histogram filled) and not actually
// sent this is acceptable.
GURL nonsecure_url_for_unset1("http://unset1.example:7");
GURL secure_url_for_unset1("https://unset1.example:7");
// Normally the source scheme would be set by
// CookieMonster::SetCanonicalCookie(), however we're using SetAllCookies() to
// bypass the source scheme check in order to test the kUnset state which
// would normally only happen during an existing cookie DB version upgrade.
std::unique_ptr<CanonicalCookie> unset_cookie1 = CanonicalCookie::Create(
secure_url_for_unset1, "NoSourceSchemeHttps=val", base::Time::Now(),
base::nullopt /* server_time */);
unset_cookie1->SetSourceScheme(net::CookieSourceScheme::kUnset);
CookieList list1 = {*unset_cookie1};
EXPECT_TRUE(SetAllCookies(&cm, list1));
RunRequest(&context, nonsecure_url_for_unset1);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 1);
RunRequest(&context, secure_url_for_unset1);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 2);
// Nonsecure set cookie marked as unset source scheme.
GURL nonsecure_url_for_unset2("http://unset2.example:7");
GURL secure_url_for_unset2("https://unset2.example:7");
std::unique_ptr<CanonicalCookie> unset_cookie2 = CanonicalCookie::Create(
nonsecure_url_for_unset2, "NoSourceSchemeHttp=val", base::Time::Now(),
base::nullopt /* server_time */);
unset_cookie2->SetSourceScheme(net::CookieSourceScheme::kUnset);
CookieList list2 = {*unset_cookie2};
EXPECT_TRUE(SetAllCookies(&cm, list2));
RunRequest(&context, nonsecure_url_for_unset2);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 3);
RunRequest(&context, secure_url_for_unset2);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kUnsetCookieScheme, 4);
// Secure set cookie with source scheme marked appropriately.
GURL nonsecure_url_for_secure_set("http://secureset.example:7");
GURL secure_url_for_secure_set("https://secureset.example:7");
EXPECT_TRUE(
CreateAndSetCookie(&cm, secure_url_for_secure_set, "SecureScheme=val"));
RunRequest(&context, nonsecure_url_for_secure_set);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kSecureSetNonsecureRequest, 1);
RunRequest(&context, secure_url_for_secure_set);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kSecureSetSecureRequest, 1);
// Nonsecure set cookie with source scheme marked appropriately.
GURL nonsecure_url_for_nonsecure_set("http://nonsecureset.example:7");
GURL secure_url_for_nonsecure_set("https://nonsecureset.example:7");
EXPECT_TRUE(CreateAndSetCookie(&cm, nonsecure_url_for_nonsecure_set,
"NonSecureScheme=val"));
RunRequest(&context, nonsecure_url_for_nonsecure_set);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kNonsecureSetNonsecureRequest, 1);
RunRequest(&context, secure_url_for_nonsecure_set);
histograms.ExpectBucketCount(
test_histogram,
URLRequestHttpJob::CookieRequestScheme::kNonsecureSetSecureRequest, 1);
}
} // namespace net
|
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author Created by raver119 on 24.11.17.
// @author Yurii Shyrma (iuriish@yahoo.com)
//
#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_scatter_div)
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/generic/helpers/ScatterHelper.h>
namespace sd {
namespace ops {
OP_IMPL(scatter_div, 3, 1, true) {
auto input = INPUT_VARIABLE(0);
auto indices = INPUT_VARIABLE(1);
auto updates = INPUT_VARIABLE(2);
auto output = OUTPUT_VARIABLE(0);
if (!block.isInplace())
output->assign(input);
const bool lock = block.getBArguments()->empty() ? false : B_ARG(0);
const bool checkIndices = block.getBArguments()->size() <= 1 ? false : B_ARG(1);
const int inRank = input->rankOf();
const int indRank = indices->rankOf();
const int updRank = updates->rankOf();
REQUIRE_TRUE(inRank > 0, 0, "SCATTER_DIV OP: input should not be scalar !");
if(inRank == 1) {
REQUIRE_TRUE(indices->isSameShape(updates), 0, "SCATTER_DIV OP: when input array has rank = 1 then indices and updates must have the same shapes, but got %s and %s correspondingly !", ShapeUtils::shapeAsString(indices).c_str(), ShapeUtils::shapeAsString(updates).c_str());
}
else if (inRank == updRank && indices->isVector()) {
std::vector<Nd4jLong> updShape = updates->getShapeAsVector();
std::vector<Nd4jLong> inShape = input->getShapeAsVector();
std::vector<Nd4jLong> expectedUpdShape = {indices->lengthOf()};
expectedUpdShape.insert(expectedUpdShape.end(), inShape.begin()+1, inShape.end());
REQUIRE_TRUE(expectedUpdShape == updShape, 0, "SCATTER_DIV OP: wrong shape of updates array, expected is %s, but got %s instead !", ShapeUtils::shapeAsString(expectedUpdShape).c_str(), ShapeUtils::shapeAsString(updShape).c_str());
}
else {
REQUIRE_TRUE(updRank == indRank + inRank - 1, 0, "SCATTER_DIV OP: wrong rank of updates array, expected is %i, but got %i instead !", indRank + inRank - 1 , updRank);
std::vector<Nd4jLong> updShape = updates->getShapeAsVector();
std::vector<Nd4jLong> inShape = input->getShapeAsVector();
std::vector<Nd4jLong> expectedUpdShape = indices->getShapeAsVector();
expectedUpdShape.insert(expectedUpdShape.end(), inShape.begin()+1, inShape.end());
REQUIRE_TRUE(expectedUpdShape == updShape, 0, "SCATTER_DIV OP: wrong shape of updates array, expected is %s, but got %s instead !", ShapeUtils::shapeAsString(expectedUpdShape).c_str(), ShapeUtils::shapeAsString(updShape).c_str());
}
if (!indices->isEmpty()) {
if(checkIndices) {
const Nd4jLong numOfBadIndx = helpers::checkIndices(block.launchContext(), *indices, *output, 0);
REQUIRE_TRUE(numOfBadIndx == 0, 0, "SCATTER_DIV OP: please check elements of indices-array, total number of wrong elements is %lld!", numOfBadIndx);
}
helpers::scatter(block.launchContext(), pairwise::Divide, *indices, *updates, *output, lock);
}
return Status::OK();
}
DECLARE_SYN(ScatterDiv, scatter_div);
DECLARE_TYPES(scatter_div) {
getOpDescriptor()
->setAllowedInputTypes(0, {ALL_INTS, ALL_FLOATS})
->setAllowedInputTypes(1, {ALL_INTS})
->setAllowedInputTypes(2, {ALL_INTS, ALL_FLOATS})
->setAllowedOutputTypes({ALL_INTS, ALL_FLOATS});
}
}
}
#endif
|
/****************************************************************************************
* @author: kzvd4729 created: Jul/24/2018 15:21
* solution_verdict: Wrong answer on test 9 language: GNU C++14
* run_time: 7877 ms memory_used: 17800 KB
* problem: https://codeforces.com/contest/551/problem/E
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int inf=2e9;
const int N=5e5;
int n,q,arr[N+2],sq;
int lazy[1003];
set<pair<int,int> >seg[1003];
void build(void)
{
for(int i=1;i<=n;i++)
seg[i/sq].insert({arr[i],i});
}
void upd(int lt,int rt,int xx)
{
for(int i=0;i<=n/sq;i++)
{
int st=max(1,i*sq);
int ed=min((i+1)*sq-1,n);
if(ed<lt||st>rt)continue;
else if(st>=lt&&ed<=rt)
lazy[i]+=xx;
else
{
for(int j=max(st,lt);j<=min(ed,rt);j++)
{
if(j>=lt&&j<=rt)
{
seg[i].erase({arr[j],j});
arr[j]+=xx;
seg[i].insert({arr[j],j});
}
}
}
}
}
int query(int yy)
{
int lt=inf,rt=0;
for(int i=0;i<=n/sq;i++)
{
auto it=seg[i].upper_bound({yy-lazy[i]-1,inf});
//auto it=upper_bound(seg[i].begin(),seg[i].end(),make_pair(yy-lazy[i]-1,inf));
if(it!=seg[i].end())
{
if(it->first==yy-lazy[i])
lt=min(lt,it->second);
}
//auto iit=upper_bound(seg[i].begin(),seg[i].end(),make_pair(yy-lazy[i],inf));
auto iit=seg[i].upper_bound({yy-lazy[i],inf});
if(iit==seg[i].begin())continue;
iit--;
if(it->first==yy-lazy[i])
rt=max(rt,iit->second);
}
if(lt==inf)return -1;
return rt-lt;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n>>q;
for(int i=1;i<=n;i++)
cin>>arr[i];
sq=sqrt(n);
build();
while(q--)
{
int ty,l,r,x,y;
cin>>ty;
if(ty==1)
{
cin>>l>>r>>x;
upd(l,r,x);
}
else
{
cin>>y;
cout<<query(y)<<"\n";
}
}
return 0;
}
|
/* Copyright 2013-2021 MultiServerMC Contributors
*
* 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 "Task.h"
#include <QDebug>
Task::Task(QObject *parent) : QObject(parent)
{
}
void Task::setStatus(const QString &new_status)
{
if(m_status != new_status)
{
m_status = new_status;
emit status(m_status);
}
}
void Task::setProgress(qint64 current, qint64 total)
{
m_progress = current;
m_progressTotal = total;
emit progress(m_progress, m_progressTotal);
}
void Task::start()
{
switch(m_state)
{
case State::Inactive:
{
qDebug() << "Task" << describe() << "starting for the first time";
break;
}
case State::AbortedByUser:
{
qDebug() << "Task" << describe() << "restarting for after being aborted by user";
break;
}
case State::Failed:
{
qDebug() << "Task" << describe() << "restarting for after failing at first";
break;
}
case State::Succeeded:
{
qDebug() << "Task" << describe() << "restarting for after succeeding at first";
break;
}
case State::Running:
{
qWarning() << "MultiServerMC tried to start task" << describe() << "while it was already running!";
return;
}
}
// NOTE: only fall thorugh to here in end states
m_state = State::Running;
emit started();
executeTask();
}
void Task::emitFailed(QString reason)
{
// Don't fail twice.
if (!isRunning())
{
qCritical() << "Task" << describe() << "failed while not running!!!!: " << reason;
return;
}
m_state = State::Failed;
m_failReason = reason;
qCritical() << "Task" << describe() << "failed: " << reason;
emit failed(reason);
emit finished();
}
void Task::emitAborted()
{
// Don't abort twice.
if (!isRunning())
{
qCritical() << "Task" << describe() << "aborted while not running!!!!";
return;
}
m_state = State::AbortedByUser;
m_failReason = "Aborted.";
qDebug() << "Task" << describe() << "aborted.";
emit failed(m_failReason);
emit finished();
}
void Task::emitSucceeded()
{
// Don't succeed twice.
if (!isRunning())
{
qCritical() << "Task" << describe() << "succeeded while not running!!!!";
return;
}
m_state = State::Succeeded;
qDebug() << "Task" << describe() << "succeeded";
emit succeeded();
emit finished();
}
QString Task::describe()
{
QString outStr;
QTextStream out(&outStr);
out << metaObject()->className() << QChar('(');
auto name = objectName();
if(name.isEmpty())
{
out << QString("0x%1").arg((quintptr)this, 0, 16);
}
else
{
out << name;
}
out << QChar(')');
out.flush();
return outStr;
}
bool Task::isRunning() const
{
return m_state == State::Running;
}
bool Task::isFinished() const
{
return m_state != State::Running && m_state != State::Inactive;
}
bool Task::wasSuccessful() const
{
return m_state == State::Succeeded;
}
QString Task::failReason() const
{
return m_failReason;
}
void Task::logWarning(const QString& line)
{
qWarning() << line;
m_Warnings.append(line);
}
QStringList Task::warnings() const
{
return m_Warnings;
}
|
/****************************************************************************
** Meta object code from reading C++ file 'addressbookpage.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/addressbookpage.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'addressbookpage.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.10.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_AddressBookPage_t {
QByteArrayData data[23];
char stringdata0[326];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_AddressBookPage_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_AddressBookPage_t qt_meta_stringdata_AddressBookPage = {
{
QT_MOC_LITERAL(0, 0, 15), // "AddressBookPage"
QT_MOC_LITERAL(1, 16, 11), // "signMessage"
QT_MOC_LITERAL(2, 28, 0), // ""
QT_MOC_LITERAL(3, 29, 4), // "addr"
QT_MOC_LITERAL(4, 34, 13), // "verifyMessage"
QT_MOC_LITERAL(5, 48, 4), // "done"
QT_MOC_LITERAL(6, 53, 6), // "retval"
QT_MOC_LITERAL(7, 60, 13), // "exportClicked"
QT_MOC_LITERAL(8, 74, 23), // "on_deleteButton_clicked"
QT_MOC_LITERAL(9, 98, 27), // "on_newAddressButton_clicked"
QT_MOC_LITERAL(10, 126, 26), // "on_copyToClipboard_clicked"
QT_MOC_LITERAL(11, 153, 22), // "on_signMessage_clicked"
QT_MOC_LITERAL(12, 176, 24), // "on_verifyMessage_clicked"
QT_MOC_LITERAL(13, 201, 16), // "selectionChanged"
QT_MOC_LITERAL(14, 218, 21), // "on_showQRCode_clicked"
QT_MOC_LITERAL(15, 240, 14), // "contextualMenu"
QT_MOC_LITERAL(16, 255, 5), // "point"
QT_MOC_LITERAL(17, 261, 17), // "onCopyLabelAction"
QT_MOC_LITERAL(18, 279, 12), // "onEditAction"
QT_MOC_LITERAL(19, 292, 16), // "selectNewAddress"
QT_MOC_LITERAL(20, 309, 6), // "parent"
QT_MOC_LITERAL(21, 316, 5), // "begin"
QT_MOC_LITERAL(22, 322, 3) // "end"
},
"AddressBookPage\0signMessage\0\0addr\0"
"verifyMessage\0done\0retval\0exportClicked\0"
"on_deleteButton_clicked\0"
"on_newAddressButton_clicked\0"
"on_copyToClipboard_clicked\0"
"on_signMessage_clicked\0on_verifyMessage_clicked\0"
"selectionChanged\0on_showQRCode_clicked\0"
"contextualMenu\0point\0onCopyLabelAction\0"
"onEditAction\0selectNewAddress\0parent\0"
"begin\0end"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_AddressBookPage[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
15, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 89, 2, 0x06 /* Public */,
4, 1, 92, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
5, 1, 95, 2, 0x0a /* Public */,
7, 0, 98, 2, 0x0a /* Public */,
8, 0, 99, 2, 0x08 /* Private */,
9, 0, 100, 2, 0x08 /* Private */,
10, 0, 101, 2, 0x08 /* Private */,
11, 0, 102, 2, 0x08 /* Private */,
12, 0, 103, 2, 0x08 /* Private */,
13, 0, 104, 2, 0x08 /* Private */,
14, 0, 105, 2, 0x08 /* Private */,
15, 1, 106, 2, 0x08 /* Private */,
17, 0, 109, 2, 0x08 /* Private */,
18, 0, 110, 2, 0x08 /* Private */,
19, 3, 111, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QString, 3,
QMetaType::Void, QMetaType::QString, 3,
// slots: parameters
QMetaType::Void, QMetaType::Int, 6,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QPoint, 16,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QModelIndex, QMetaType::Int, QMetaType::Int, 20, 21, 22,
0 // eod
};
void AddressBookPage::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
AddressBookPage *_t = static_cast<AddressBookPage *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->signMessage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 1: _t->verifyMessage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 2: _t->done((*reinterpret_cast< int(*)>(_a[1]))); break;
case 3: _t->exportClicked(); break;
case 4: _t->on_deleteButton_clicked(); break;
case 5: _t->on_newAddressButton_clicked(); break;
case 6: _t->on_copyToClipboard_clicked(); break;
case 7: _t->on_signMessage_clicked(); break;
case 8: _t->on_verifyMessage_clicked(); break;
case 9: _t->selectionChanged(); break;
case 10: _t->on_showQRCode_clicked(); break;
case 11: _t->contextualMenu((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 12: _t->onCopyLabelAction(); break;
case 13: _t->onEditAction(); break;
case 14: _t->selectNewAddress((*reinterpret_cast< const QModelIndex(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
typedef void (AddressBookPage::*_t)(QString );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AddressBookPage::signMessage)) {
*result = 0;
return;
}
}
{
typedef void (AddressBookPage::*_t)(QString );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&AddressBookPage::verifyMessage)) {
*result = 1;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject AddressBookPage::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_AddressBookPage.data,
qt_meta_data_AddressBookPage, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *AddressBookPage::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *AddressBookPage::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_AddressBookPage.stringdata0))
return static_cast<void*>(this);
return QDialog::qt_metacast(_clname);
}
int AddressBookPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 15)
qt_static_metacall(this, _c, _id, _a);
_id -= 15;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 15)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 15;
}
return _id;
}
// SIGNAL 0
void AddressBookPage::signMessage(QString _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void AddressBookPage::verifyMessage(QString _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
#include <iostream>
#include <thread>
#include <vector>
#include <memory>
#include <sstream>
#include <boost/asio.hpp>
using namespace boost;
class connection
{
public:
asio::ip::tcp::socket socket;
std::vector<char> buff;
connection(asio::io_service& io):socket(io)
{
buff.resize(1024);
}
void read_something()
{
socket.async_read_some(asio::buffer(buff), [this](std::error_code const& ec, std::size_t size) {
std::cout << "thread id=" << std::this_thread::get_id() << std::endl;
this->read_something();
});
}
};
class Server
{
private:
std::vector<asio::io_service> tcp_io_pool;
std::vector<std::thread> thread_pool;
std::vector<std::shared_ptr<asio::ip::tcp::socket>> sockets;
std::vector<std::shared_ptr<asio::ip::tcp::acceptor>> acceptors;
asio::ip::tcp::endpoint endpoint;
std::vector<std::shared_ptr<asio::io_service::work>> works;
int get_io_service_index = 0;
public:
Server(std::size_t size,short port):tcp_io_pool(size), works(size), endpoint(asio::ip::tcp::v4(), port)
{
init();
}
asio::io_service& get_io_service()
{
if (get_io_service_index == tcp_io_pool.size()) {
get_io_service_index = 0;
}
//std::cout << get_io_service_index << std::endl;
return tcp_io_pool[get_io_service_index++];
}
void init()
{
for (auto&iter : tcp_io_pool) {
works.push_back(std::make_shared<asio::io_service::work>(iter));
}
auto& io = get_io_service();
auto acceptor = std::make_shared<asio::ip::tcp::acceptor>(io, endpoint);
start_acceptor(acceptor);
}
void read_something(std::shared_ptr<asio::ip::tcp::socket> socket)
{
auto buff = std::make_shared<std::vector<char>>(1024);
socket->async_read_some(asio::buffer(*buff), [this, buff, socket](std::error_code const& ec, std::size_t size) {
//std::cout << "thread id=" << std::this_thread::get_id() << std::endl;
//this->read_something(socket);
});
}
void start_acceptor(std::shared_ptr<asio::ip::tcp::acceptor> acceptor)
{
auto socket = std::make_shared<asio::ip::tcp::socket>(get_io_service());
sockets.push_back(socket);
acceptor->async_accept((*socket), [this,acceptor, socket](std::error_code const& ec) {
this->write_something(socket);
start_acceptor(acceptor);
});
}
void write_something(std::shared_ptr<asio::ip::tcp::socket> socket)
{
socket->async_write_some(asio::buffer("hello"), [this, socket](std::error_code const& ec,std::size_t size) {
std::cout << "connect" << std::endl;
//std::cout << "thread id=" << std::this_thread::get_id() << std::endl;
//this->read_something(socket);
this->read_something(socket);
});
}
void run()
{
for (auto&iter : tcp_io_pool) {
thread_pool.emplace_back(std::thread([](asio::io_service* io_ptr) {
std::cout << "run" << std::endl;
io_ptr->run();
},&iter));
}
for (auto&iter : thread_pool) {
iter.join();
std::cout << "join" << std::endl;
}
}
};
int main()
{
Server seve(8, 8080);
seve.run();
std::cin.get();
return 0;
}
|
/*
* Copyright 2019-2021 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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 CGVECTOR_HPP
#define CGVECTOR_HPP
#include <vector>
#include "impl/cgInstr.hpp"
#include "impl/cgException.hpp"
#include "utils.hpp"
using namespace xf::hpc;
namespace xilinx_apps {
namespace pcg {
struct CgInputVec {
unsigned int vecBytes;
void* h_b;
void* h_diag;
};
struct CgVector {
unsigned int vecBytes;
void* h_Apk;
void* h_jacobi;
void* h_pk;
void* h_rk;
void* h_xk;
void* h_zk;
};
struct CgInstr {
unsigned int h_instrBytes;
void* h_instr;
};
template <typename t_DataType, unsigned int t_ParEntries>
class GenCgVector {
public:
GenCgVector() : m_dim(0), m_dot(0), m_rz(0){};
void loadVec(const unsigned int p_dim, const t_DataType* p_b, const t_DataType* p_diagA) {
if (p_b == nullptr || p_diagA == nullptr) {
throw CgInvalidValue("Vector is nullptr.");
}
m_diagA.clear();
m_b.clear();
m_Apk.clear();
m_jacobi.clear();
m_rk.clear();
m_xk.clear();
m_zk.clear();
m_dim = p_dim;
unsigned int l_dimAlignedBks = (p_dim + t_ParEntries - 1) / t_ParEntries;
unsigned int l_dimAligned = l_dimAlignedBks * t_ParEntries;
m_dimAligned = l_dimAligned;
m_diagA.insert(m_diagA.end(), p_diagA, p_diagA + p_dim);
m_diagA.insert(m_diagA.end(), m_dimAligned - m_dim, 1);
m_b.insert(m_b.end(), p_b, p_b + p_dim);
m_b.insert(m_b.end(), m_dimAligned - m_dim, 0);
m_Apk.assign(m_dimAligned, 0);
m_jacobi.assign(m_dimAligned, 1);
m_pk.assign(m_dimAligned, 0);
m_rk.assign(m_dimAligned, 0);
m_xk.assign(m_dimAligned, 0);
m_zk.assign(m_dimAligned, 0);
}
void updateVec(const unsigned int p_dim, const t_DataType* p_b, const t_DataType* p_diagA) {
if (p_b == nullptr || p_diagA == nullptr) {
throw CgInvalidValue("Vector is nullptr.");
}
std::copy(p_diagA, p_diagA + p_dim, m_diagA.begin());
std::copy(p_b, p_b + p_dim, m_b.begin());
std::fill(m_Apk.begin(), m_Apk.end(), 0);
std::fill(m_jacobi.begin(), m_jacobi.end(), 1);
std::fill(m_pk.begin(), m_pk.end(), 0);
std::fill(m_rk.begin(), m_rk.end(), 0);
std::fill(m_xk.begin(), m_xk.end(), 0);
std::fill(m_zk.begin(), m_zk.end(), 0);
}
CgInputVec getInputVec() {
CgInputVec l_res;
l_res.vecBytes = m_dimAligned * sizeof(t_DataType);
l_res.h_b = (void*)(m_b.data());
l_res.h_diag = (void*)(m_diagA.data());
return l_res;
}
void init() {
m_dot = 0;
m_rz = 0;
m_xk.assign(m_dimAligned, 0);
m_Apk.assign(m_dimAligned, 0);
for (unsigned int i = 0; i < m_dimAligned; ++i) {
m_rk[i] = m_b[i];
m_jacobi[i] = 1.0 / m_diagA[i];
m_zk[i] = m_jacobi[i] * m_rk[i];
m_dot += m_b[i] * m_b[i];
m_rz += m_rk[i] * m_zk[i];
m_pk[i] = m_zk[i];
}
}
CgVector getVec() {
CgVector l_vec;
l_vec.vecBytes = m_dimAligned * sizeof(t_DataType);
l_vec.h_Apk = (void*)(m_Apk.data());
l_vec.h_jacobi = (void*)(m_jacobi.data());
l_vec.h_pk = (void*)(m_pk.data());
l_vec.h_rk = (void*)(m_rk.data());
l_vec.h_xk = (void*)(m_xk.data());
l_vec.h_zk = (void*)(m_zk.data());
return l_vec;
}
t_DataType getDot() { return m_dot; }
t_DataType getRz() { return m_rz; }
void* getXk() { return (void*)(m_xk.data()); }
unsigned int getDimAligned() { return m_dimAligned; }
unsigned int getDim() { return m_dim; }
private:
unsigned int m_dim, m_dimAligned;
t_DataType m_dot, m_rz;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_diagA;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_b;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_Apk;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_jacobi;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_pk;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_rk;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_xk;
std::vector<t_DataType, alignedAllocator<t_DataType> > m_zk;
};
template <typename t_DataType, unsigned int t_InstrBytes>
class GenCgInstr {
public:
GenCgInstr(){};
void setInstr(
unsigned int p_maxIter, unsigned int p_dimAligned, t_DataType p_dot, t_DataType p_tol, t_DataType p_rz) {
unsigned int l_instrSize = t_InstrBytes * (1 + p_maxIter);
m_instr.resize(l_instrSize);
std::fill(m_instr.begin(), m_instr.end(), 0);
m_cgInstr.setMaxIter(p_maxIter);
m_cgInstr.setTols(p_dot * p_tol * p_tol);
m_cgInstr.setRes(p_dot);
m_cgInstr.setRZ(p_rz);
m_cgInstr.setVecSize(p_dimAligned);
}
void updateInstr() {
MemInstr<t_InstrBytes> l_memInstr;
m_cgInstr.store(m_instr.data(), l_memInstr);
}
CgInstr getInstrPtr() {
CgInstr l_res;
l_res.h_instrBytes = m_instr.size();
l_res.h_instr = (void*)(m_instr.data());
return l_res;
}
private:
std::vector<uint8_t, alignedAllocator<uint8_t> > m_instr;
cg::CGSolverInstr<CG_dataType> m_cgInstr;
};
}
}
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef WIN32
// for posix_fallocate
#ifdef __linux__
#define _POSIX_C_SOURCE 200112L
#endif
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/resource.h>
#endif
#include "util.h"
#include "sync.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fBloomFilters = true;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64> vTimeOffsets(200,0);
volatile bool fReopenDebugLog = false;
bool fCachedPath[2] = {false, false};
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64 nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64 nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
OPENSSL_cleanse(pdata, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64 GetRand(uint64 nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
uint64 nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
//
// OutputDebugStringF (aka printf -- there is a #define that we really
// should get rid of one day) has been broken a couple of times now
// by well-meaning people adding mutexes in the most straightforward way.
// It breaks because it may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// defining a mutex as a global object doesn't work (the mutex gets
// destroyed, and then some later destructor calls OutputDebugStringF,
// maybe indirectly, and you get a core dump at shutdown trying to lock
// the mutex).
static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
// We use boost::call_once() to make sure these are initialized in
// in a thread-safe manner the first time it is called:
static FILE* fileout = NULL;
static boost::mutex* mutexDebugLog = NULL;
static void DebugPrintInit()
{
assert(fileout == NULL);
assert(mutexDebugLog == NULL);
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
mutexDebugLog = new boost::mutex();
}
int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0; // Returns total number of characters written
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret += vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
static bool fStartedNewLine = true;
boost::call_once(&DebugPrintInit, debugPrintInitFlag);
if (fileout == NULL)
return ret;
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret += vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
ret += line_end-line_start;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
loop
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
loop
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64 n_abs = (n > 0 ? n : -n);
int64 quotient = n_abs/COIN;
int64 remainder = n_abs%COIN;
string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64& nRet)
{
string strWhole;
int64 nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64 nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64 nWhole = atoi64(strWhole);
int64 nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
// safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
// even possibly remotely dangerous like & or >
static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
string SanitizeString(const string& str)
{
string strResult;
for (std::string::size_type i = 0; i < str.size(); i++)
{
if (safeChars.find(str[i]) != std::string::npos)
strResult.push_back(str[i]);
}
return strResult;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
loop
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
std::string str(argv[i]);
std::string strValue;
size_t is_index = str.find('=');
if (is_index != std::string::npos)
{
strValue = str.substr(is_index+1);
str = str.substr(0, is_index);
}
#ifdef WIN32
boost::to_lower(str);
if (boost::algorithm::starts_with(str, "/"))
str = "-" + str.substr(1);
#endif
if (str[0] != '-')
break;
mapArgs[str] = strValue;
mapMultiArgs[str].push_back(strValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64 GetArg(const std::string& strArg, int64 nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
loop
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "Bolsocoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
// Mac: ~/Library/Application Support/Bitcoin
// Unix: ~/.bitcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "Bolsocoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "Bolsocoin";
#else
// Unix
return pathRet / ".Bolsocoin";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (fCachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet3";
fs::create_directories(path);
fCachedPath[fNetSpecific] = true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "Bolsocoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
// clear path cache after loading config file
fCachedPath[0] = fCachedPath[1] = false;
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "Bolsocoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
#if defined(__linux__) || defined(__NetBSD__)
fdatasync(fileno(fileout));
#elif defined(__APPLE__) && defined(F_FULLFSYNC)
fcntl(fileno(fileout), F_FULLFSYNC, 0);
#else
fsync(fileno(fileout));
#endif
#endif
}
int GetFilesize(FILE* file)
{
int nSavePos = ftell(file);
int nFilesize = -1;
if (fseek(file, 0, SEEK_END) == 0)
nFilesize = ftell(file);
fseek(file, nSavePos, SEEK_SET);
return nFilesize;
}
bool TruncateFile(FILE *file, unsigned int length) {
#if defined(WIN32)
return _chsize(_fileno(file), length) == 0;
#else
return ftruncate(fileno(file), length) == 0;
#endif
}
// this function tries to raise the file descriptor limit to the requested number.
// It returns the actual file descriptor limit (which may be more or less than nMinFD)
int RaiseFileDescriptorLimit(int nMinFD) {
#if defined(WIN32)
return 2048;
#else
struct rlimit limitFD;
if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
if (limitFD.rlim_cur < (rlim_t)nMinFD) {
limitFD.rlim_cur = nMinFD;
if (limitFD.rlim_cur > limitFD.rlim_max)
limitFD.rlim_cur = limitFD.rlim_max;
setrlimit(RLIMIT_NOFILE, &limitFD);
getrlimit(RLIMIT_NOFILE, &limitFD);
}
return limitFD.rlim_cur;
}
return nMinFD; // getrlimit failed, assume it's fine
#endif
}
// this function tries to make a particular range of a file allocated (corresponding to disk space)
// it is advisory, and the range specified in the arguments will never contain live data
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#if defined(WIN32)
// Windows-specific version
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
LARGE_INTEGER nFileSize;
int64 nEndPos = (int64)offset + length;
nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
nFileSize.u.HighPart = nEndPos >> 32;
SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
SetEndOfFile(hFile);
#elif defined(MAC_OSX)
// OSX specific version
fstore_t fst;
fst.fst_flags = F_ALLOCATECONTIG;
fst.fst_posmode = F_PEOFPOSMODE;
fst.fst_offset = 0;
fst.fst_length = (off_t)offset + length;
fst.fst_bytesalloc = 0;
if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
fst.fst_flags = F_ALLOCATEALL;
fcntl(fileno(file), F_PREALLOCATE, &fst);
}
ftruncate(fileno(file), fst.fst_length);
#elif defined(__linux__)
// Version using posix_fallocate
off_t nEndPos = (off_t)offset + length;
posix_fallocate(fileno(file), 0, nEndPos);
#else
// Fallback version
// TODO: just write one byte per block
static const char buf[65536] = {};
fseek(file, offset, SEEK_SET);
while (length > 0) {
unsigned int now = 65536;
if (length < now)
now = length;
fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
length -= now;
}
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && GetFilesize(file) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
else if(file != NULL)
fclose(file);
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64 nMockTime = 0; // For unit testing
int64 GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64 nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64 nTimeOffset = 0;
int64 GetTimeOffset()
{
return nTimeOffset;
}
int64 GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64 nTime)
{
int64 nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64 nMedian = vTimeOffsets.median();
std::vector<int64> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 35 * 60) // Bolsocoin: changed maximum adjust to 35 mins to avoid letting peers change our time too much in case of an attack.
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64 nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bolsocoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64 n, vSorted)
printf("%+"PRI64d" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
uint32_t insecure_rand_Rz = 11;
uint32_t insecure_rand_Rw = 11;
void seed_insecure_rand(bool fDeterministic)
{
//The seed values have some unlikely fixed points which we avoid.
if(fDeterministic)
{
insecure_rand_Rz = insecure_rand_Rw = 11;
} else {
uint32_t tmp;
do {
RAND_bytes((unsigned char*)&tmp, 4);
} while(tmp == 0 || tmp == 0x9068ffffU);
insecure_rand_Rz = tmp;
do {
RAND_bytes((unsigned char*)&tmp, 4);
} while(tmp == 0 || tmp == 0x464fffffU);
insecure_rand_Rw = tmp;
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
boost::filesystem::path GetTempPath() {
#if BOOST_FILESYSTEM_VERSION == 3
return boost::filesystem::temp_directory_path();
#else
// TODO: remove when we don't support filesystem v2 anymore
boost::filesystem::path path;
#ifdef WIN32
char pszPath[MAX_PATH] = "";
if (GetTempPathA(MAX_PATH, pszPath))
path = boost::filesystem::path(pszPath);
#else
path = boost::filesystem::path("/tmp");
#endif
if (path.empty() || !boost::filesystem::is_directory(path)) {
printf("GetTempPath(): failed to find temp path\n");
return boost::filesystem::path("");
}
return path;
#endif
}
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
// pthread_setname_np is XCode 10.6-and-later
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
pthread_setname_np(name);
#endif
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
|
/*
* Copyright (c) 2011-2019, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* 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.
* 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.
*/
#ifndef DART_DYNAMICS_FIXEDJACOBIANNODE_HPP_
#define DART_DYNAMICS_FIXEDJACOBIANNODE_HPP_
#include "dart/dynamics/detail/FixedJacobianNode.hpp"
namespace dart {
namespace dynamics {
class FixedJacobianNode : public detail::FixedJacobianNodeCompositeBase,
public AccessoryNode<FixedJacobianNode>
{
public:
/// Set the current relative transform of this Fixed Frame
void setRelativeTransform(const Eigen::Isometry3d& newRelativeTf) override;
// Documentation inherited
bool dependsOn(std::size_t _genCoordIndex) const override;
// Documentation inherited
std::size_t getNumDependentGenCoords() const override;
// Documentation inherited
std::size_t getDependentGenCoordIndex(std::size_t _arrayIndex) const override;
// Documentation inherited
const std::vector<std::size_t>& getDependentGenCoordIndices() const override;
// Documentation inherited
std::size_t getNumDependentDofs() const override;
// Documentation inherited
DegreeOfFreedom* getDependentDof(std::size_t _index) override;
// Documentation inherited
const DegreeOfFreedom* getDependentDof(std::size_t _index) const override;
// Documentation inherited
const std::vector<DegreeOfFreedom*>& getDependentDofs() override;
// Documentation inherited
const std::vector<const DegreeOfFreedom*>& getDependentDofs() const override;
// Documentation inherited
const std::vector<const DegreeOfFreedom*> getChainDofs() const override;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Jacobian Functions
//----------------------------------------------------------------------------
// Documentation inherited
const math::Jacobian& getJacobian() const override final;
// Prevent the inherited getJacobian functions from being shadowed
using TemplatedJacobianNode<FixedJacobianNode>::getJacobian;
// Documentation inherited
const math::Jacobian& getWorldJacobian() const override final;
// Prevent the inherited getWorldJacobian functions from being shadowed
using TemplatedJacobianNode<FixedJacobianNode>::getWorldJacobian;
// Documentation inherited
const math::Jacobian& getJacobianSpatialDeriv() const override final;
// Prevent the inherited getJacobianSpatialDeriv functions from being shadowed
using TemplatedJacobianNode<FixedJacobianNode>::getJacobianSpatialDeriv;
// Documentation inherited
const math::Jacobian& getJacobianClassicDeriv() const override final;
// Prevent the inherited getJacobianClassicDeriv functions from being shadowed
using TemplatedJacobianNode<FixedJacobianNode>::getJacobianClassicDeriv;
/// \}
protected:
/// Constructor
FixedJacobianNode(BodyNode* parent, const Eigen::Isometry3d& transform);
/// Tuple constructor
FixedJacobianNode(const std::tuple<BodyNode*, Eigen::Isometry3d>& args);
/// Update the Jacobian of this Fixed Frame. getJacobian() calls this function
/// if mIsBodyJacobianDirty is true.
void updateBodyJacobian() const;
/// Update the World Jacobian cache.
void updateWorldJacobian() const;
/// Update the spatial time derivative of the Fixed Frame Jacobian.
/// getJacobianSpatialDeriv() calls this function if
/// mIsBodyJacobianSpatialDerivDirty is true.
void updateBodyJacobianSpatialDeriv() const;
/// Update the classic time derivative of the Fixed Frame Jacobian.
/// getJacobianClassicDeriv() calls this function if
/// mIsWorldJacobianClassicDerivDirty is true.
void updateWorldJacobianClassicDeriv() const;
struct Cache
{
/// Cached Jacobian of this Fixed Frame
///
/// Do not use directly! Use getJacobian() to access this quantity
math::Jacobian mBodyJacobian;
/// Cached World Jacobian of this Fixed Frame
///
/// Do not use directly! Use getWorldJacobian() to access this quantity
math::Jacobian mWorldJacobian;
/// Spatial time derivative of Fixed Frame Jacobian
///
/// Do not use directly! Use getJacobianSpatialDeriv() to access this
/// quantity
math::Jacobian mBodyJacobianSpatialDeriv;
/// Classic time derivative of the Fixed Frame Jacobian
///
/// Do not use directly! Use getJacobianClassicDeriv() to access this
/// quantity
math::Jacobian mWorldJacobianClassicDeriv;
// To get byte-aligned Eigen vectors
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
mutable Cache mCache;
};
} // namespace dynamics
} // namespace dart
#endif // DART_DYNAMICS_FIXEDJACOBIANNODE_HPP_
|
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "memory.hpp"
#include <memory>
#include <vector>
namespace cldnn {
struct work_group_sizes {
std::vector<size_t> global;
std::vector<size_t> local;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Scalar
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct scalar_desc {
union ValueT {
uint8_t u8;
uint16_t u16;
uint32_t u32;
uint64_t u64;
int8_t s8;
int16_t s16;
int32_t s32;
int64_t s64;
float f32;
double f64;
};
enum class Types {
UINT8,
UINT16,
UINT32,
UINT64,
INT8,
INT16,
INT32,
INT64,
FLOAT32,
FLOAT64,
};
Types t;
ValueT v;
};
using scalars_desc = std::vector<scalar_desc>;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ArgumentDescpirtor
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct argument_desc {
enum class Types {
INPUT,
OUTPUT,
WEIGHTS,
BIAS,
SCALE_TABLE,
SLOPE,
SPLIT,
INTERNAL_BUFFER,
SCALAR,
RECURRENT, // RNN/LSTM/GRU recurrent weights
HIDDEN, // RNN/LSTM/GRU hidden input
CELL, // LSTM cell input
LSTM_PACK, // LSTM packed output
WEIGHTS_ZERO_POINTS,
ACTIVATIONS_ZERO_POINTS,
COMPENSATION,
INPUT_OF_FUSED_PRIMITIVE
};
Types t;
uint32_t index;
};
using arguments_desc = std::vector<argument_desc>;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// KernelParams
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct kernel_arguments_desc {
work_group_sizes workGroups;
arguments_desc arguments;
scalars_desc scalars;
std::string layerID;
};
struct kernel_arguments_data {
std::vector<memory::cptr> inputs;
std::vector<memory::cptr> intermediates;
memory::cptr output;
memory::cptr weights;
memory::cptr recurrent;
memory::cptr hidden;
memory::cptr cell;
memory::cptr bias;
memory::cptr weights_zero_points;
memory::cptr activations_zero_points;
memory::cptr compensation;
memory::cptr lookup_table;
memory::cptr scale_table;
memory::cptr slope;
std::vector<memory::cptr> fused_op_inputs;
int32_t split = 0;
const scalars_desc* scalars = nullptr;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// KernelString
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct kernel_string {
std::string str;
std::string jit;
std::string undefs;
std::string options;
std::string entry_point;
bool batch_compilation;
kernel_string() : str(""), jit(""), undefs(""), options(""), entry_point(""), batch_compilation(false) {}
std::string get_hash() { return str + jit + undefs + options + entry_point; }
};
} // namespace cldnn
|
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/server/NodeRegistrationHandler.h"
#include <gtest/gtest.h>
#include "logdevice/common/configuration/nodes/NodesConfigurationCodec.h"
#include "logdevice/common/settings/util.h"
#include "logdevice/common/test/InMemNodesConfigurationStore.h"
#include "logdevice/common/test/MockNodesConfigurationStore.h"
using namespace facebook::logdevice::configuration::nodes;
using namespace facebook::logdevice::membership;
using testing::_;
namespace facebook::logdevice {
namespace {
std::map<NodeServiceDiscovery::ClientNetworkPriority, std::string>
genUnixAddressesPerNetworkPriority(std::string prefix) {
return {{NodeServiceDiscovery::ClientNetworkPriority::MEDIUM,
folly::sformat("{}/medium-priority-address", prefix)},
{NodeServiceDiscovery::ClientNetworkPriority::LOW,
folly::sformat("{}/low-priority-address", prefix)}};
}
template <typename M>
decltype(auto) addressesPerNetworkPriorityToString(const M& map) {
std::map<NodeServiceDiscovery::ClientNetworkPriority, std::string> result;
for (const auto& [priority, sock_addr] : map) {
result[priority] = sock_addr.toString();
}
return result;
}
} // namespace
class NodeRegistrationHandlerTest : public ::testing::Test {
public:
NodeRegistrationHandlerTest() {
store_ = std::make_shared<InMemNodesConfigurationStore>(
"/foo", NodesConfigurationCodec::extractConfigVersion);
// Write an empty NC
auto ser_nc = NodesConfigurationCodec::serialize(NodesConfiguration{});
store_->updateConfigSync(
ser_nc, NodesConfigurationStore::Condition::overwrite());
}
ServerSettings buildServerSettings(std::string name) {
ServerSettings settings = create_default_settings<ServerSettings>();
settings.name = name;
settings.unix_socket = folly::sformat("/{}/address", name);
settings.ssl_unix_socket = folly::sformat("/{}/ssl", name);
settings.gossip_unix_socket = folly::sformat("/{}/gossip", name);
settings.server_to_server_unix_socket =
folly::sformat("/{}/server-to-server", name);
settings.server_thrift_api_unix_socket =
folly::sformat("/{}/server-thrift-api", name);
settings.client_thrift_api_unix_socket =
folly::sformat("/{}/client-thrift-api", name);
settings.unix_addresses_per_network_priority =
genUnixAddressesPerNetworkPriority(
/*prefix=*/folly::sformat("/{}", name));
settings.roles = 3 /* sequencer + storage */;
settings.sequencer_weight = 12;
settings.storage_capacity = 13;
settings.num_shards = 3;
settings.admin_enabled = true;
NodeLocation loc;
loc.fromDomainString("aa.bb.cc.dd.ee");
settings.location = loc;
return settings;
}
AdminServerSettings buildAdminServerSettings(std::string name) {
AdminServerSettings settings =
create_default_settings<AdminServerSettings>();
settings.admin_unix_socket = folly::format("/{}/admin", name).str();
return settings;
}
folly::Expected<node_index_t, E> registerNode(ServerSettings set,
AdminServerSettings admin_set) {
auto updateable_nc = std::make_shared<UpdateableNodesConfiguration>();
updateable_nc->update(getNodesConfiguration());
NodeRegistrationHandler handler{
std::move(set), std::move(admin_set), updateable_nc, store_};
return handler.registerSelf(NodeIndicesAllocator{});
}
std::shared_ptr<const NodesConfiguration> getNodesConfiguration() {
std::string ser;
ld_check_eq(Status::OK, store_->getConfigSync(&ser));
return NodesConfigurationCodec::deserialize(ser);
}
std::shared_ptr<configuration::nodes::NodesConfigurationStore> store_;
};
TEST_F(NodeRegistrationHandlerTest, testAddNode) {
auto settings = buildServerSettings("node1");
auto admin_settings = buildAdminServerSettings("node1");
auto res = registerNode(settings, admin_settings);
ASSERT_TRUE(res.hasValue());
// Get NC
auto nc = getNodesConfiguration();
auto index = res.value();
EXPECT_EQ(1, nc->getServiceDiscovery()->numNodes());
const auto& svd = nc->getNodeServiceDiscovery(index);
ASSERT_NE(nullptr, svd);
EXPECT_EQ("node1", svd->name);
EXPECT_EQ("/node1/address", svd->default_client_data_address.toString());
EXPECT_EQ("/node1/ssl", svd->ssl_address->toString());
EXPECT_EQ("/node1/gossip", svd->gossip_address->toString());
EXPECT_EQ("/node1/admin", svd->admin_address->toString());
EXPECT_EQ(
"/node1/server-to-server", svd->server_to_server_address->toString());
EXPECT_EQ(
"/node1/server-thrift-api", svd->server_thrift_api_address->toString());
EXPECT_EQ(
"/node1/client-thrift-api", svd->client_thrift_api_address->toString());
EXPECT_EQ(genUnixAddressesPerNetworkPriority("/node1"),
addressesPerNetworkPriorityToString(svd->addresses_per_priority));
EXPECT_EQ(RoleSet(3), svd->roles);
EXPECT_EQ("aa.bb.cc.dd.ee", svd->location->toString());
const auto& storage_attr = nc->getNodeStorageAttribute(index);
ASSERT_NE(nullptr, storage_attr);
EXPECT_EQ(2, storage_attr->generation);
EXPECT_EQ(13, storage_attr->capacity);
EXPECT_EQ(3, storage_attr->num_shards);
const auto& shards = nc->getStorageMembership()->getShardStates(index);
ASSERT_EQ(3, shards.size());
EXPECT_EQ(StorageState::PROVISIONING, shards.at(0).storage_state);
EXPECT_EQ(StorageState::PROVISIONING, shards.at(1).storage_state);
EXPECT_EQ(StorageState::PROVISIONING, shards.at(2).storage_state);
const auto& seq = nc->getSequencerMembership()->getNodeState(index);
ASSERT_TRUE(seq.has_value());
EXPECT_FALSE(seq->sequencer_enabled);
EXPECT_EQ(12, seq->getConfiguredWeight());
}
TEST_F(NodeRegistrationHandlerTest, testUpdate) {
auto settings = buildServerSettings("node1");
auto admin_settings = buildAdminServerSettings("node1");
auto add_res = registerNode(settings, admin_settings);
ASSERT_TRUE(add_res.hasValue());
auto index = add_res.value();
settings.unix_socket = "/new/address";
settings.ssl_unix_socket = "/new/ssl";
settings.gossip_unix_socket = "/new/gossip";
settings.server_to_server_unix_socket = "/new/s2s";
settings.server_thrift_api_unix_socket = "/new/sta";
settings.client_thrift_api_unix_socket = "/new/cta";
settings.unix_addresses_per_network_priority =
genUnixAddressesPerNetworkPriority("/new");
settings.sequencer_weight = 22;
settings.storage_capacity = 23;
settings.admin_enabled = false;
auto updateable_nc = std::make_shared<UpdateableNodesConfiguration>();
updateable_nc->update(getNodesConfiguration());
NodeRegistrationHandler handler{
settings, admin_settings, updateable_nc, store_};
auto status = handler.updateSelf(index);
ASSERT_EQ(Status::OK, status);
// Get NC
auto nc = getNodesConfiguration();
const auto& svd = nc->getNodeServiceDiscovery(index);
ASSERT_NE(nullptr, svd);
EXPECT_EQ("node1", svd->name);
EXPECT_EQ("/new/address", svd->default_client_data_address.toString());
EXPECT_EQ("/new/ssl", svd->ssl_address->toString());
EXPECT_EQ("/new/gossip", svd->gossip_address->toString());
EXPECT_EQ("/new/s2s", svd->server_to_server_address->toString());
EXPECT_EQ("/new/sta", svd->server_thrift_api_address->toString());
EXPECT_EQ("/new/cta", svd->client_thrift_api_address->toString());
EXPECT_EQ(genUnixAddressesPerNetworkPriority("/new"),
addressesPerNetworkPriorityToString(svd->addresses_per_priority));
EXPECT_FALSE(svd->admin_address.has_value());
EXPECT_EQ(RoleSet(3), svd->roles);
EXPECT_EQ("aa.bb.cc.dd.ee", svd->location->toString());
const auto& storage_attr = nc->getNodeStorageAttribute(index);
ASSERT_NE(nullptr, storage_attr);
EXPECT_EQ(2, storage_attr->generation);
EXPECT_EQ(23, storage_attr->capacity);
EXPECT_EQ(3, storage_attr->num_shards);
const auto& shards = nc->getStorageMembership()->getShardStates(index);
ASSERT_EQ(3, shards.size());
EXPECT_EQ(StorageState::PROVISIONING, shards.at(0).storage_state);
EXPECT_EQ(StorageState::PROVISIONING, shards.at(1).storage_state);
EXPECT_EQ(StorageState::PROVISIONING, shards.at(2).storage_state);
const auto& seq = nc->getSequencerMembership()->getNodeState(index);
ASSERT_TRUE(seq.has_value());
EXPECT_FALSE(seq->sequencer_enabled);
EXPECT_EQ(22, seq->getConfiguredWeight());
}
TEST_F(NodeRegistrationHandlerTest, testSameUpdateNoop) {
auto settings = buildServerSettings("node1");
auto admin_settings = buildAdminServerSettings("node1");
auto add_res = registerNode(settings, admin_settings);
ASSERT_TRUE(add_res.hasValue());
// Applying an update with the same setting should return UPTODATE.
auto updateable_nc = std::make_shared<UpdateableNodesConfiguration>();
updateable_nc->update(getNodesConfiguration());
NodeRegistrationHandler handler{
settings, admin_settings, updateable_nc, store_};
auto status = handler.updateSelf(add_res.value());
ASSERT_EQ(Status::UPTODATE, status);
}
// Makes sure that the handler bubbles up unexpected failures.
TEST_F(NodeRegistrationHandlerTest, testRegistrationBubbleUpdateFailures) {
auto settings = buildServerSettings("node1");
auto admin_settings = buildAdminServerSettings("node1");
auto store = std::make_shared<MockNodesConfigurationStore>();
EXPECT_CALL(*store, updateConfigSync(_, _, _, _))
.WillOnce(testing::Return(Status::BADMSG));
auto updateable_nc = std::make_shared<UpdateableNodesConfiguration>();
updateable_nc->update(std::make_shared<NodesConfiguration>());
NodeRegistrationHandler handler{
settings, admin_settings, std::move(updateable_nc), store};
auto res = handler.registerSelf(NodeIndicesAllocator{});
ASSERT_TRUE(res.hasError());
EXPECT_EQ(Status::BADMSG, res.error());
}
// Make sure that NCM VERSION_MISMATCH-es are retried
TEST_F(NodeRegistrationHandlerTest, testRetryOnVersionMismatch) {
auto settings = buildServerSettings("node1");
auto admin_settings = buildAdminServerSettings("node1");
auto store = std::make_shared<MockNodesConfigurationStore>();
// The expected interactions with the NCS:
// 1- Initial update fails with VERSION_MISMATCH without providing the new
// value.
// 2- The handler, will try to fetch the new version (v2).
// 3- The new update will also fail with VERSION_MISMATCH but will provide the
// new value (v3).
// 4- The update will then succeed.
testing::InSequence seq;
EXPECT_CALL(
*store,
updateConfigSync(
_, VersionedConfigStore::Condition(MembershipVersion::Type(0)), _, _))
.WillOnce(testing::Return(Status::VERSION_MISMATCH));
EXPECT_CALL(*store, getConfigSync(_, _))
.WillOnce(testing::Invoke([](auto* value_out, auto) {
auto nc = NodesConfiguration{}.withVersion(MembershipVersion::Type(1));
if (value_out) {
*value_out = NodesConfigurationCodec::serialize(std::move(*nc));
}
return Status::OK;
}));
EXPECT_CALL(
*store,
updateConfigSync(
_, VersionedConfigStore::Condition(MembershipVersion::Type(1)), _, _))
.WillOnce(
testing::Invoke([](auto, auto, auto* version_out, auto* value_out) {
auto version = MembershipVersion::Type(2);
auto nc = NodesConfiguration{}.withVersion(version);
if (version_out) {
*version_out = version;
}
if (value_out) {
*value_out = NodesConfigurationCodec::serialize(std::move(*nc));
}
return Status::VERSION_MISMATCH;
}));
EXPECT_CALL(
*store,
updateConfigSync(
_, VersionedConfigStore::Condition(MembershipVersion::Type(2)), _, _))
.WillOnce(testing::Return(Status::OK));
auto updateable_nc = std::make_shared<UpdateableNodesConfiguration>();
updateable_nc->update(std::make_shared<NodesConfiguration>());
NodeRegistrationHandler handler{
settings, admin_settings, updateable_nc, store};
auto res = handler.registerSelf(NodeIndicesAllocator{});
ASSERT_TRUE(res.hasValue());
// The updatable should have the the latest value
ASSERT_EQ(MembershipVersion::Type(2), updateable_nc->get()->getVersion());
}
} // namespace facebook::logdevice
|
/**
* Copyright (C) 2016-2017 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "xocl_plugin.h"
#include "xdp/profile/writer/base_profile.h"
#include "xdp/profile/core/rt_profile.h"
#include "xrt/util/time.h"
namespace xdp {
// XOCL XDP Plugin constructor
XoclPlugin::XoclPlugin(xocl::platform* Platform)
{
mPlatformHandle = Platform;
}
XoclPlugin::~XoclPlugin()
{
}
// **********
// Trace time
// **********
double XoclPlugin::getTraceTime()
{
// Get trace time from XRT
auto nsec = xrt::time_ns();
return getTimestampMsec(nsec);
}
// *************************
// Accelerator port metadata
// *************************
// Find arguments and memory resources for each accel port on given device
void XoclPlugin::setArgumentsBank(const std::string& deviceName)
{
const std::string numerical("0123456789");
for (auto device_id : mPlatformHandle->get_device_range()) {
std::string currDevice = device_id->get_unique_name();
XDP_LOG("setArgumentsBank: current device = %s, # CUs = %d\n",
currDevice.c_str(), device_id->get_num_cus());
if (currDevice.find(deviceName) == std::string::npos)
continue;
for (auto& cu : xocl::xocl(device_id)->get_cus()) {
auto currCU = cu->get_name();
auto currSymbol = cu->get_symbol();
// Compile set of ports on this CU
std::set<std::string> portSet;
for (auto arg : currSymbol->arguments) {
if ((arg.address_qualifier == 0)
|| (arg.atype != xocl::xclbin::symbol::arg::argtype::indexed))
continue;
auto portName = arg.port;
std::transform(portName.begin(), portName.end(), portName.begin(), ::tolower);
portSet.insert(portName);
}
// Now find all arguments for each port
for (auto portName : portSet) {
XDPPluginI::CUPortArgsBankType row;
std::get<0>(row) = currCU;
std::get<1>(row) = portName;
bool firstArg = true;
std::string memoryName;
for (auto arg : currSymbol->arguments) {
auto currPort = arg.port;
std::transform(currPort.begin(), currPort.end(), currPort.begin(), ::tolower);
// Address_Qualifier = 1 : AXI MM Port
// Address_Qualifier = 4 : AXI Stream Port
if ((currPort == portName) && (arg.address_qualifier == 1 || arg.address_qualifier == 4)
&& (arg.atype == xocl::xclbin::symbol::arg::argtype::indexed)) {
std::get<2>(row) += (firstArg) ? arg.name : ("|" + arg.name);
auto portWidth = arg.port_width;
unsigned long index = (unsigned long)std::stoi(arg.id);
try {
auto memidx_mask = cu->get_memidx(index);
// auto memidx = 0;
for (unsigned int memidx=0; memidx<memidx_mask.size(); ++memidx) {
if (memidx_mask.test(memidx)) {
// Get bank tag string from index
memoryName = "DDR";
if (device_id->is_active())
memoryName = device_id->get_xclbin().memidx_to_banktag(memidx);
XDP_LOG("setArgumentsBank: idx = %d, memory = %s\n", memidx, memoryName.c_str());
break;
}
}
}
catch (const std::runtime_error& ex) {
memoryName = "DDR";
XDP_LOG("setArgumentsBank: caught error, using default of %s\n", memoryName.c_str());
}
// Catch old bank format and report as DDR
//std::string memoryName2 = memoryName.substr(0, memoryName.find_last_of("["));
if (memoryName.find("bank0") != std::string::npos)
memoryName = "DDR[0]";
else if (memoryName.find("bank1") != std::string::npos)
memoryName = "DDR[1]";
else if (memoryName.find("bank2") != std::string::npos)
memoryName = "DDR[2]";
else if (memoryName.find("bank3") != std::string::npos)
memoryName = "DDR[3]";
std::get<3>(row) = memoryName;
std::get<4>(row) = portWidth;
firstArg = false;
}
}
XDP_LOG("setArgumentsBank: %s/%s, args = %s, memory = %s, width = %d\n",
std::get<0>(row).c_str(), std::get<1>(row).c_str(), std::get<2>(row).c_str(),
std::get<3>(row).c_str(), std::get<4>(row));
CUPortVector.push_back(row);
}
portSet.clear();
} // for cu
} // for device_id
}
// Get the arguments and memory resource for a given device/CU/port
void XoclPlugin::getArgumentsBank(const std::string& deviceName, const std::string& cuName,
const std::string& portName, std::string& argNames,
std::string& memoryName)
{
argNames = "All";
memoryName = "DDR";
bool foundMemory = false;
std::string portNameCheck = portName;
size_t index = portName.find_last_of(IP_LAYOUT_SEP);
if (index != std::string::npos) {
foundMemory = true;
portNameCheck = portName.substr(0, index);
memoryName = portName.substr(index+1);
}
std::transform(portNameCheck.begin(), portNameCheck.end(), portNameCheck.begin(), ::tolower);
// Find CU and port, then capture arguments and bank
for (auto& row : CUPortVector) {
std::string currCU = std::get<0>(row);
std::string currPort = std::get<1>(row);
if ((currCU == cuName) && (currPort == portNameCheck)) {
argNames = std::get<2>(row);
// If already found, replace it; otherwise, use it
if (foundMemory)
std::get<3>(row) = memoryName;
else
memoryName = std::get<3>(row);
break;
}
}
}
// *****************
// Guidance metadata
// *****************
// Gather statistics and put into param/value map
// NOTE: this needs to be called while the platforms and devices still exist
void XoclPlugin::getGuidanceMetadata(RTProfile *profile)
{
// 1. Device execution times (and unused devices)
getDeviceExecutionTimes(profile);
// 2. Unused CUs
getUnusedComputeUnits(profile);
// 3. Kernel counts
getKernelCounts(profile);
}
void XoclPlugin::getDeviceExecutionTimes(RTProfile *profile)
{
// NOTE: all device are assumed to support PLRAMs
setPlramDevice(true);
setHbmDevice(false);
setKdmaDevice(false);
setP2PDevice(false);
// Traverse all devices in platform
for (auto device_id : mPlatformHandle->get_device_range()) {
std::string deviceName = device_id->get_unique_name();
// Get execution time for this device
// NOTE: if unused, then this returns 0.0
double deviceExecTime = profile->getTotalKernelExecutionTime(deviceName);
mDeviceExecTimesMap[deviceName] = std::to_string(deviceExecTime);
// TODO: checks below are kludgy; are there better ways to check for device support?
// Check if device supports HBM
if (deviceName.find("280") != std::string::npos)
setHbmDevice(true);
// Check if device supports KDMA
if ((deviceName.find("xilinx_u200_xdma_201830_2") != std::string::npos)
|| (deviceName.find("xilinx_vcu1525_xdma_201830_2") != std::string::npos))
setKdmaDevice(true);
// Check if device supports P2P
if ((deviceName.find("xilinx_u200_xdma_201830_2") != std::string::npos)
|| (deviceName.find("xilinx_u250_xdma_201830_2") != std::string::npos)
|| (deviceName.find("xilinx_vcu1525_xdma_201830_2") != std::string::npos)
|| (deviceName.find("samsung") != std::string::npos))
setP2PDevice(true);
}
}
void XoclPlugin::getUnusedComputeUnits(RTProfile *profile)
{
// Traverse all devices in platform
for (auto device_id : mPlatformHandle->get_device_range()) {
std::string deviceName = device_id->get_unique_name();
// Traverse all CUs on current device
for (auto& cu : xocl::xocl(device_id)->get_cus()) {
auto cuName = cu->get_name();
// Get number of calls for current CU
int numCalls = profile->getComputeUnitCalls(deviceName, cuName);
std::string cuFullName = deviceName + "|" + cuName;
mComputeUnitCallsMap[cuFullName] = std::to_string(numCalls);
}
}
}
void XoclPlugin::getKernelCounts(RTProfile *profile)
{
// Traverse all devices in this platform
for (auto device_id : mPlatformHandle->get_device_range()) {
std::string deviceName = device_id->get_unique_name();
// Traverse all CUs on current device
for (auto& cu : xocl::xocl(device_id)->get_cus()) {
auto kernelName = cu->get_kernel_name();
if (mKernelCountsMap.find(kernelName) == mKernelCountsMap.end())
mKernelCountsMap[kernelName] = 1;
else
mKernelCountsMap[kernelName] += 1;
}
}
}
// ****************************************
// Platform Metadata required by profiler
// ****************************************
void XoclPlugin::getProfileKernelName(const std::string& deviceName, const std::string& cuName, std::string& kernelName)
{
xoclp::platform::get_profile_kernel_name(mPlatformHandle, deviceName, cuName, kernelName);
}
void XoclPlugin::getTraceStringFromComputeUnit(const std::string& deviceName,
const std::string& cuName, std::string& traceString)
{
std::string kernel;
getProfileKernelName(deviceName, cuName, kernel);
for (const auto &pair : mComputeUnitKernelTraceMap) {
if (pair.first == kernel) {
auto index = pair.second.find_last_of("|");
traceString = pair.second.substr(0,index + 1) + cuName + pair.second.substr(index);
return;
}
}
traceString = std::string();
}
void XoclPlugin::setTraceStringForComputeUnit(const std::string& cuName, std::string& traceString)
{
if (!cuName.empty() && mComputeUnitKernelTraceMap.find(cuName) == mComputeUnitKernelTraceMap.end())
mComputeUnitKernelTraceMap[cuName] = traceString;
}
size_t XoclPlugin::getDeviceTimestamp(const std::string& deviceName)
{
return xoclp::platform::get_device_timestamp(mPlatformHandle,deviceName);
}
double XoclPlugin::getReadMaxBandwidthMBps()
{
return xoclp::platform::get_device_max_read(mPlatformHandle);
}
double XoclPlugin::getWriteMaxBandwidthMBps()
{
return xoclp::platform::get_device_max_write(mPlatformHandle);
}
unsigned int XoclPlugin::getProfileNumberSlots(xclPerfMonType type, const std::string& deviceName)
{
unsigned int numSlots = xoclp::platform::get_profile_num_slots(mPlatformHandle,
deviceName, type);
return numSlots;
}
void XoclPlugin::getProfileSlotName(xclPerfMonType type, const std::string& deviceName,
unsigned int slotnum, std::string& slotName)
{
xoclp::platform::get_profile_slot_name(mPlatformHandle, deviceName,
type, slotnum, slotName);
}
unsigned int XoclPlugin::getProfileSlotProperties(xclPerfMonType type, const std::string& deviceName,
unsigned int slotnum)
{
return xoclp::platform::get_profile_slot_properties(mPlatformHandle, deviceName, type, slotnum);
}
bool XoclPlugin::isAPCtrlChain(const std::string& deviceName,
const std::string& cu)
{
return xoclp::platform::is_ap_ctrl_chain(mPlatformHandle, deviceName,cu);
}
void XoclPlugin::sendMessage(const std::string &msg)
{
xrt::message::send(xrt::message::severity_level::XRT_WARNING, msg);
}
} // xdp
|
/*
* Copyright (C) 2005 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.
*/
#include "utils/String16.h"
#include "utils/Log.h"
#include "utils/Unicode.h"
#include "utils/String8.h"
#include "utils/threads.h"
#include <memory.h>
#include <stdio.h>
#include <ctype.h>
namespace android {
static SharedBuffer* gEmptyStringBuf = NULL;
static char16_t* gEmptyString = NULL;
static inline char16_t* getEmptyString()
{
gEmptyStringBuf->acquire();
return gEmptyString;
}
void initialize_string16()
{
SharedBuffer* buf = SharedBuffer::alloc(sizeof(char16_t));
char16_t* str = (char16_t*)buf->data();
*str = 0;
gEmptyStringBuf = buf;
gEmptyString = str;
}
void terminate_string16()
{
SharedBuffer::bufferFromData(gEmptyString)->release();
gEmptyStringBuf = NULL;
gEmptyString = NULL;
}
// ---------------------------------------------------------------------------
static char16_t* allocFromUTF8(const char* u8str, size_t u8len)
{
if (u8len == 0) return getEmptyString();
const uint8_t* u8cur = (const uint8_t*) u8str;
const ssize_t u16len = utf8_to_utf16_length(u8cur, u8len);
if (u16len < 0) {
return getEmptyString();
}
SharedBuffer* buf = SharedBuffer::alloc(sizeof(char16_t)*(u16len+1));
if (buf) {
u8cur = (const uint8_t*) u8str;
char16_t* u16str = (char16_t*)buf->data();
utf8_to_utf16(u8cur, u8len, u16str);
//printf("Created UTF-16 string from UTF-8 \"%s\":", in);
//printHexData(1, str, buf->size(), 16, 1);
//printf("\n");
return u16str;
}
return getEmptyString();
}
// ---------------------------------------------------------------------------
String16::String16()
: mString(getEmptyString())
{
}
String16::String16(StaticLinkage)
: mString(0)
{
// this constructor is used when we can't rely on the static-initializers
// having run. In this case we always allocate an empty string. It's less
// efficient than using getEmptyString(), but we assume it's uncommon.
char16_t* data = static_cast<char16_t*>(
SharedBuffer::alloc(sizeof(char16_t))->data());
data[0] = 0;
mString = data;
}
String16::String16(const String16& o)
: mString(o.mString)
{
SharedBuffer::bufferFromData(mString)->acquire();
}
String16::String16(const String16& o, size_t len, size_t begin)
: mString(getEmptyString())
{
setTo(o, len, begin);
}
String16::String16(const char16_t* o)
{
size_t len = strlen16(o);
SharedBuffer* buf = SharedBuffer::alloc((len+1)*sizeof(char16_t));
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (buf) {
char16_t* str = (char16_t*)buf->data();
strcpy16(str, o);
mString = str;
return;
}
mString = getEmptyString();
}
String16::String16(const char16_t* o, size_t len)
{
SharedBuffer* buf = SharedBuffer::alloc((len+1)*sizeof(char16_t));
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (buf) {
char16_t* str = (char16_t*)buf->data();
memcpy(str, o, len*sizeof(char16_t));
str[len] = 0;
mString = str;
return;
}
mString = getEmptyString();
}
String16::String16(const String8& o)
: mString(allocFromUTF8(o.string(), o.size()))
{
}
String16::String16(const char* o)
: mString(allocFromUTF8(o, strlen(o)))
{
}
String16::String16(const char* o, size_t len)
: mString(allocFromUTF8(o, len))
{
}
String16::~String16()
{
SharedBuffer::bufferFromData(mString)->release();
}
void String16::setTo(const String16& other)
{
SharedBuffer::bufferFromData(other.mString)->acquire();
SharedBuffer::bufferFromData(mString)->release();
mString = other.mString;
}
status_t String16::setTo(const String16& other, size_t len, size_t begin)
{
const size_t N = other.size();
if (begin >= N) {
SharedBuffer::bufferFromData(mString)->release();
mString = getEmptyString();
return NO_ERROR;
}
if ((begin+len) > N) len = N-begin;
if (begin == 0 && len == N) {
setTo(other);
return NO_ERROR;
}
if (&other == this) {
LOG_ALWAYS_FATAL("Not implemented");
}
return setTo(other.string()+begin, len);
}
status_t String16::setTo(const char16_t* other)
{
return setTo(other, strlen16(other));
}
status_t String16::setTo(const char16_t* other, size_t len)
{
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
->editResize((len+1)*sizeof(char16_t));
if (buf) {
char16_t* str = (char16_t*)buf->data();
memmove(str, other, len*sizeof(char16_t));
str[len] = 0;
mString = str;
return NO_ERROR;
}
return NO_MEMORY;
}
status_t String16::append(const String16& other)
{
const size_t myLen = size();
const size_t otherLen = other.size();
if (myLen == 0) {
setTo(other);
return NO_ERROR;
} else if (otherLen == 0) {
return NO_ERROR;
}
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
->editResize((myLen+otherLen+1)*sizeof(char16_t));
if (buf) {
char16_t* str = (char16_t*)buf->data();
memcpy(str+myLen, other, (otherLen+1)*sizeof(char16_t));
mString = str;
return NO_ERROR;
}
return NO_MEMORY;
}
status_t String16::append(const char16_t* chrs, size_t otherLen)
{
const size_t myLen = size();
if (myLen == 0) {
setTo(chrs, otherLen);
return NO_ERROR;
} else if (otherLen == 0) {
return NO_ERROR;
}
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
->editResize((myLen+otherLen+1)*sizeof(char16_t));
if (buf) {
char16_t* str = (char16_t*)buf->data();
memcpy(str+myLen, chrs, otherLen*sizeof(char16_t));
str[myLen+otherLen] = 0;
mString = str;
return NO_ERROR;
}
return NO_MEMORY;
}
status_t String16::insert(size_t pos, const char16_t* chrs)
{
return insert(pos, chrs, strlen16(chrs));
}
status_t String16::insert(size_t pos, const char16_t* chrs, size_t len)
{
const size_t myLen = size();
if (myLen == 0) {
return setTo(chrs, len);
return NO_ERROR;
} else if (len == 0) {
return NO_ERROR;
}
if (pos > myLen) pos = myLen;
#if 0
printf("Insert in to %s: pos=%d, len=%d, myLen=%d, chrs=%s\n",
String8(*this).string(), pos,
len, myLen, String8(chrs, len).string());
#endif
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
->editResize((myLen+len+1)*sizeof(char16_t));
if (buf) {
char16_t* str = (char16_t*)buf->data();
if (pos < myLen) {
memmove(str+pos+len, str+pos, (myLen-pos)*sizeof(char16_t));
}
memcpy(str+pos, chrs, len*sizeof(char16_t));
str[myLen+len] = 0;
mString = str;
#if 0
printf("Result (%d chrs): %s\n", size(), String8(*this).string());
#endif
return NO_ERROR;
}
return NO_MEMORY;
}
ssize_t String16::findFirst(char16_t c) const
{
const char16_t* str = string();
const char16_t* p = str;
const char16_t* e = p + size();
while (p < e) {
if (*p == c) {
return p-str;
}
p++;
}
return -1;
}
ssize_t String16::findLast(char16_t c) const
{
const char16_t* str = string();
const char16_t* p = str;
const char16_t* e = p + size();
while (p < e) {
e--;
if (*e == c) {
return e-str;
}
}
return -1;
}
bool String16::startsWith(const String16& prefix) const
{
const size_t ps = prefix.size();
if (ps > size()) return false;
return strzcmp16(mString, ps, prefix.string(), ps) == 0;
}
bool String16::startsWith(const char16_t* prefix) const
{
const size_t ps = strlen16(prefix);
if (ps > size()) return false;
return strncmp16(mString, prefix, ps) == 0;
}
status_t String16::makeLower()
{
const size_t N = size();
const char16_t* str = string();
char16_t* edit = NULL;
for (size_t i=0; i<N; i++) {
const char16_t v = str[i];
if (v >= 'A' && v <= 'Z') {
if (!edit) {
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)->edit();
if (!buf) {
return NO_MEMORY;
}
edit = (char16_t*)buf->data();
mString = str = edit;
}
edit[i] = tolower((char)v);
}
}
return NO_ERROR;
}
status_t String16::replaceAll(char16_t replaceThis, char16_t withThis)
{
const size_t N = size();
const char16_t* str = string();
char16_t* edit = NULL;
for (size_t i=0; i<N; i++) {
if (str[i] == replaceThis) {
if (!edit) {
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)->edit();
if (!buf) {
return NO_MEMORY;
}
edit = (char16_t*)buf->data();
mString = str = edit;
}
edit[i] = withThis;
}
}
return NO_ERROR;
}
status_t String16::remove(size_t len, size_t begin)
{
const size_t N = size();
if (begin >= N) {
SharedBuffer::bufferFromData(mString)->release();
mString = getEmptyString();
return NO_ERROR;
}
if ((begin+len) > N) len = N-begin;
if (begin == 0 && len == N) {
return NO_ERROR;
}
if (begin > 0) {
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
->editResize((N+1)*sizeof(char16_t));
if (!buf) {
return NO_MEMORY;
}
char16_t* str = (char16_t*)buf->data();
memmove(str, str+begin, (N-begin+1)*sizeof(char16_t));
mString = str;
}
SharedBuffer* buf = SharedBuffer::bufferFromData(mString)
->editResize((len+1)*sizeof(char16_t));
if (buf) {
char16_t* str = (char16_t*)buf->data();
str[len] = 0;
mString = str;
return NO_ERROR;
}
return NO_MEMORY;
}
}; // namespace android
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_src_char_cpy_17.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_src.label.xml
Template File: sources-sink-17.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sink: cpy
* BadSink : Copy data to string using strcpy
* Flow Variant: 17 Control flow: for loops
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_src_char_cpy_17
{
#ifndef OMITBAD
void bad()
{
int i;
char * data;
data = new char[100];
for(i = 0; i < 1; i++)
{
/* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */
memset(data, 'A', 100-1); /* fill with 'A's */
data[100-1] = '\0'; /* null terminate */
}
{
char dest[50] = "";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
strcpy(dest, data);
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource in the for statement */
static void goodG2B()
{
int h;
char * data;
data = new char[100];
for(h = 0; h < 1; h++)
{
/* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
memset(data, 'A', 50-1); /* fill with 'A's */
data[50-1] = '\0'; /* null terminate */
}
{
char dest[50] = "";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
strcpy(dest, data);
printLine(data);
delete [] data;
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_src_char_cpy_17; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/****************************************************************************
** Copyright (c) 2019, Fougue Ltd. <http://www.fougue.pro>
** All rights reserved.
** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt
****************************************************************************/
#include "dialog_task_manager.h"
#include "ui_dialog_task_manager.h"
#include "theme.h"
#include <fougtools/qttools/task/manager.h>
#include <fougtools/qttools/task/progress.h>
#include <QtCore/QTimer>
#include <QtCore/QtDebug>
#include <QtWidgets/QLabel>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QToolButton>
namespace Mayo {
namespace Internal {
static const char TaskWidget_taskIdProp[] = "Mayo::TaskId";
class TaskWidget : public QWidget {
public:
TaskWidget(QWidget* parent = nullptr);
QLabel* m_label = nullptr;
QProgressBar* m_progress = nullptr;
QToolButton* m_interruptBtn = nullptr;
void createUnboundedProgressTimer();
void stopUnboundedProgressTimer();
bool hasUnboundedProgressTimer() const;
private:
void onUnboundedProgressTimeout();
QTimer* m_unboundedProgressTimer = nullptr;
int m_unboundedProgressValue = 0;
};
TaskWidget::TaskWidget(QWidget *parent)
: QWidget(parent),
m_label(new QLabel(this)),
m_progress(new QProgressBar(this)),
m_interruptBtn(new QToolButton(this))
{
QFont labelFont = m_label->font();
labelFont.setBold(true);
m_label->setFont(labelFont);
m_progress->setRange(0, 100);
m_progress->setValue(0);
m_interruptBtn->setIcon(mayoTheme()->icon(Theme::Icon::Stop));
m_interruptBtn->setAutoRaise(true);
auto progressLayout = new QHBoxLayout;
progressLayout->addWidget(m_progress);
progressLayout->addWidget(m_interruptBtn);
auto mainLayout = new QVBoxLayout;
mainLayout->addWidget(m_label);
mainLayout->addLayout(progressLayout);
mainLayout->setSpacing(0);
this->setLayout(mainLayout);
}
void TaskWidget::createUnboundedProgressTimer()
{
if (!this->hasUnboundedProgressTimer()) {
m_unboundedProgressTimer = new QTimer(this);
QObject::connect(
m_unboundedProgressTimer, &QTimer::timeout,
this, &TaskWidget::onUnboundedProgressTimeout);
m_unboundedProgressTimer->start(500);
}
}
void TaskWidget::stopUnboundedProgressTimer()
{
if (m_unboundedProgressTimer != nullptr)
m_unboundedProgressTimer->stop();
}
bool TaskWidget::hasUnboundedProgressTimer() const
{
return m_unboundedProgressTimer != nullptr;
}
void TaskWidget::onUnboundedProgressTimeout()
{
m_unboundedProgressValue += 5;
m_progress->setValue(m_unboundedProgressValue % 100);
}
} // namespace Internal
DialogTaskManager::DialogTaskManager(QWidget *parent)
: QDialog(parent),
m_ui(new Ui_DialogTaskManager)
{
this->setWindowFlags(
Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
m_ui->setupUi(this);
auto taskMgr = qttask::Manager::globalInstance();
QObject::connect(
taskMgr, &qttask::Manager::started,
this, &DialogTaskManager::onTaskStarted);
QObject::connect(
taskMgr, &qttask::Manager::ended,
this, &DialogTaskManager::onTaskEnded);
QObject::connect(
taskMgr, &qttask::Manager::progress,
this, &DialogTaskManager::onTaskProgress);
QObject::connect(
taskMgr, &qttask::Manager::progressStep,
this, &DialogTaskManager::onTaskProgressStep);
this->setWindowModality(Qt::WindowModal);
}
DialogTaskManager::~DialogTaskManager()
{
delete m_ui;
}
bool DialogTaskManager::isRunning() const
{
return m_isRunning;
}
void DialogTaskManager::execWithTask(quint64 taskId)
{
m_isRunning = true;
this->onTaskStarted(taskId, QString());
this->exec();
}
void DialogTaskManager::onTaskStarted(quint64 taskId, const QString& title)
{
if (!m_isRunning)
this->show();
auto widget = new Internal::TaskWidget(m_ui->scrollAreaContents);
widget->m_interruptBtn->setProperty(Internal::TaskWidget_taskIdProp, taskId);
QObject::connect(
widget->m_interruptBtn, &QToolButton::clicked,
this, &DialogTaskManager::interruptTask);
m_ui->contentsLayout->insertWidget(0, widget);
m_taskIdToWidget.insert(taskId, widget);
++m_taskCount;
if (!title.isEmpty())
this->onTaskProgressStep(taskId, QString());
}
void DialogTaskManager::onTaskEnded(quint64 taskId)
{
Internal::TaskWidget* widget = this->taskWidget(taskId);
if (widget != nullptr) {
if (widget->hasUnboundedProgressTimer())
widget->stopUnboundedProgressTimer();
m_ui->contentsLayout->removeWidget(widget);
delete widget;
m_taskIdToWidget.remove(taskId);
}
--m_taskCount;
if (m_taskCount == 0) {
m_isRunning = false;
this->accept();
}
}
void DialogTaskManager::onTaskProgress(quint64 taskId, int percent)
{
Internal::TaskWidget* widget = this->taskWidget(taskId);
if (widget != nullptr) {
if (percent >= 0) {
widget->m_progress->setValue(percent);
}
else {
widget->createUnboundedProgressTimer();
widget->m_progress->setTextVisible(false);
}
}
}
void DialogTaskManager::onTaskProgressStep(quint64 taskId, const QString& name)
{
const QString taskTitle = qttask::Manager::globalInstance()->taskTitle(taskId);
Internal::TaskWidget* widget = this->taskWidget(taskId);
if (widget) {
QString text = taskTitle;
if (!name.isEmpty()) {
if (!text.isEmpty())
text += " / ";
text += name;
}
widget->m_label->setText(text);
}
}
void DialogTaskManager::interruptTask()
{
auto interruptBtn = qobject_cast<QToolButton*>(this->sender());
if (interruptBtn != nullptr
&& interruptBtn->dynamicPropertyNames().contains(Internal::TaskWidget_taskIdProp))
{
const quint64 taskId =
interruptBtn->property(Internal::TaskWidget_taskIdProp).toULongLong();
qttask::Manager::globalInstance()->requestAbort(taskId);
}
}
Internal::TaskWidget *DialogTaskManager::taskWidget(quint64 taskId)
{
auto it = m_taskIdToWidget.find(taskId);
return it != m_taskIdToWidget.end() ? it.value() : nullptr;
}
} // namespace RondPointApp
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/nearby_sharing/transfer_metadata_builder.h"
// static
TransferMetadataBuilder TransferMetadataBuilder::Clone(
const TransferMetadata& metadata) {
TransferMetadataBuilder builder;
builder.is_original_ = metadata.is_original();
builder.progress_ = metadata.progress();
builder.status_ = metadata.status();
builder.token_ = metadata.token();
return builder;
}
TransferMetadataBuilder::TransferMetadataBuilder() = default;
TransferMetadataBuilder::TransferMetadataBuilder(TransferMetadataBuilder&&) =
default;
TransferMetadataBuilder& TransferMetadataBuilder::operator=(
TransferMetadataBuilder&&) = default;
TransferMetadataBuilder::~TransferMetadataBuilder() = default;
TransferMetadataBuilder& TransferMetadataBuilder::set_is_original(
bool is_original) {
is_original_ = is_original;
return *this;
}
TransferMetadataBuilder& TransferMetadataBuilder::set_progress(
double progress) {
progress_ = progress;
return *this;
}
TransferMetadataBuilder& TransferMetadataBuilder::set_status(
TransferMetadata::Status status) {
status_ = status;
return *this;
}
TransferMetadataBuilder& TransferMetadataBuilder::set_token(
absl::optional<std::string> token) {
token_ = std::move(token);
return *this;
}
TransferMetadata TransferMetadataBuilder::build() const {
return TransferMetadata(status_, progress_, token_, is_original_,
TransferMetadata::IsFinalStatus(status_));
}
|
/*
We keep track of last binary digits and compare.
*/
class Solution {
public:
bool hasAlternatingBits(int n) {
int last = -1;
while (n) {
int d = n % 2;
n /= 2;
if (d == last) return false;
last = d;
}
return true;
}
};
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Script/ScriptTimePoint.h>
#include <AzToolsFramework/AssetBrowser/AssetBrowserModel.h>
#include <AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntry.h>
#include <AzToolsFramework/AssetBrowser/Entries/RootAssetBrowserEntry.h>
#include <AzToolsFramework/AssetBrowser/Entries/SourceAssetBrowserEntry.h>
#include <AzToolsFramework/AssetBrowser/Entries/ProductAssetBrowserEntry.h>
#include <AzToolsFramework/AssetBrowser/Entries/AssetBrowserEntryCache.h>
#include <QMimeData>
AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 'QRegularExpression::d': class 'QExplicitlySharedDataPointer<QRegularExpressionPrivate>' needs to have dll-interface to be used by clients of class 'QRegularExpression'
#include <QRegularExpression>
AZ_POP_DISABLE_WARNING
namespace AzToolsFramework
{
namespace AssetBrowser
{
AssetBrowserModel::AssetBrowserModel(QObject* parent)
: QAbstractItemModel(parent)
, m_rootEntry(nullptr)
, m_loaded(false)
, m_addingEntry(false)
, m_removingEntry(false)
{
AssetBrowserModelRequestBus::Handler::BusConnect();
AZ::TickBus::Handler::BusConnect();
}
AssetBrowserModel::~AssetBrowserModel()
{
AssetBrowserModelRequestBus::Handler::BusDisconnect();
AZ::TickBus::Handler::BusDisconnect();
}
QModelIndex AssetBrowserModel::findIndex(const QString& absoluteAssetPath) const
{
// Split the path based on either platform's slash
QRegularExpression regex(QStringLiteral("[\\/]"));
QStringList assetPathComponents = absoluteAssetPath.split(regex);
AssetBrowserEntry* cursor = m_rootEntry.get();
if (cursor && absoluteAssetPath.contains(cursor->GetFullPath().c_str()))
{
while (true)
{
// find the child entry that contains more
bool foundChild = false;
for (int i = 0; i < cursor->GetChildCount(); i++)
{
AssetBrowserEntry* child = cursor->GetChild(i);
if (child)
{
QString newPath = child->GetFullPath().c_str();
if (absoluteAssetPath.startsWith(newPath))
{
if (absoluteAssetPath == newPath)
{
QModelIndex index;
if (GetEntryIndex(child, index))
{
return index;
}
}
// Confirm that this is a real match as opposed to a partial match.
// For instance, an asset absolute path C:/somepath/someotherpath/blah.tga will partial match with c:/somepath/some
// and get us here.
QStringList possibleMatchComponents = newPath.split(regex);
QString possibleMatchDirectory = possibleMatchComponents.last();
Q_ASSERT(assetPathComponents.count() >= possibleMatchComponents.count());
if (possibleMatchDirectory == assetPathComponents[possibleMatchComponents.count() - 1])
{
cursor = child;
foundChild = true;
break;
}
}
}
}
if (!foundChild)
{
break;
}
}
}
return QModelIndex();
}
QModelIndex AssetBrowserModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
{
return QModelIndex();
}
AssetBrowserEntry* parentEntry;
if (!parent.isValid())
{
parentEntry = m_rootEntry.get();
}
else
{
parentEntry = reinterpret_cast<AssetBrowserEntry*>(parent.internalPointer());
}
AssetBrowserEntry* childEntry = parentEntry->m_children[row];
if (!childEntry)
{
return QModelIndex();
}
QModelIndex index;
GetEntryIndex(childEntry, index);
return index;
}
int AssetBrowserModel::rowCount(const QModelIndex& parent) const
{
if (!m_rootEntry)
{
return 0;
}
if (parent.isValid())
{
if ((parent.column() != aznumeric_cast<int>(AssetBrowserEntry::Column::DisplayName)) &&
(parent.column() != aznumeric_cast<int>(AssetBrowserEntry::Column::Name)) &&
(parent.column() != aznumeric_cast<int>(AssetBrowserEntry::Column::Path)))
{
return 0;
}
}
AssetBrowserEntry* parentAssetEntry;
if (!parent.isValid())
{
parentAssetEntry = m_rootEntry.get();
}
else
{
parentAssetEntry = static_cast<AssetBrowserEntry*>(parent.internalPointer());
}
return parentAssetEntry->GetChildCount();
}
int AssetBrowserModel::columnCount(const QModelIndex& /*parent*/) const
{
return aznumeric_cast<int>(AssetBrowserEntry::Column::Count);
}
QVariant AssetBrowserModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
{
return QVariant();
}
if (role == Qt::DisplayRole)
{
const AssetBrowserEntry* item = static_cast<AssetBrowserEntry*>(index.internalPointer());
return item->GetDisplayName();
}
if (role == Roles::EntryRole)
{
const AssetBrowserEntry* item = static_cast<AssetBrowserEntry*>(index.internalPointer());
return QVariant::fromValue(item);
}
return QVariant();
}
Qt::ItemFlags AssetBrowserModel::flags(const QModelIndex& index) const
{
Qt::ItemFlags defaultFlags = QAbstractItemModel::flags(index);
if (index.isValid())
{
// allow retrieval of mimedata of sources or products only (i.e. cant drag folders or root)
AssetBrowserEntry* item = static_cast<AssetBrowserEntry*>(index.internalPointer());
if (item && (item->RTTI_IsTypeOf(ProductAssetBrowserEntry::RTTI_Type()) || item->RTTI_IsTypeOf(SourceAssetBrowserEntry::RTTI_Type())))
{
return Qt::ItemIsDragEnabled | defaultFlags;
}
}
return defaultFlags;
//return Qt::ItemFlags(~Qt::ItemIsDragEnabled & defaultFlags);
}
QMimeData* AssetBrowserModel::mimeData(const QModelIndexList& indexes) const
{
QMimeData* mimeData = new QMimeData;
for (const auto& index : indexes)
{
if (index.isValid())
{
AssetBrowserEntry* item = static_cast<AssetBrowserEntry*>(index.internalPointer());
if (item)
{
item->AddToMimeData(mimeData);
}
}
}
return mimeData;
}
QVariant AssetBrowserModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Roles::EntryRole)
{
return tr(AssetBrowserEntry::m_columnNames[section]);
}
return QAbstractItemModel::headerData(section, orientation, role);
}
void AssetBrowserModel::SourceIndexesToAssetIds(const QModelIndexList& indexes, AZStd::vector<AZ::Data::AssetId>& assetIds)
{
for (const auto& index : indexes)
{
if (index.isValid())
{
AssetBrowserEntry* item = static_cast<AssetBrowserEntry*>(index.internalPointer());
if (item->GetEntryType() == AssetBrowserEntry::AssetEntryType::Product)
{
assetIds.push_back(static_cast<ProductAssetBrowserEntry*>(item)->GetAssetId());
}
}
}
}
void AssetBrowserModel::SourceIndexesToAssetDatabaseEntries(const QModelIndexList& indexes, AZStd::vector<AssetBrowserEntry*>& entries)
{
for (const auto& index : indexes)
{
if (index.isValid())
{
AssetBrowserEntry* item = static_cast<AssetBrowserEntry*>(index.internalPointer());
entries.push_back(item);
}
}
}
AZStd::shared_ptr<RootAssetBrowserEntry> AssetBrowserModel::GetRootEntry() const
{
return m_rootEntry;
}
void AssetBrowserModel::SetRootEntry(AZStd::shared_ptr<RootAssetBrowserEntry> rootEntry)
{
m_rootEntry = rootEntry;
}
QModelIndex AssetBrowserModel::parent(const QModelIndex& child) const
{
if (!child.isValid())
{
return QModelIndex();
}
AssetBrowserEntry* childAssetEntry = static_cast<AssetBrowserEntry*>(child.internalPointer());
AssetBrowserEntry* parentEntry = childAssetEntry->GetParent();
QModelIndex parentIndex;
if (GetEntryIndex(parentEntry, parentIndex))
{
return parentIndex;
}
return QModelIndex();
}
bool AssetBrowserModel::IsLoaded() const
{
return m_loaded;
}
void AssetBrowserModel::BeginAddEntry(AssetBrowserEntry* parent)
{
QModelIndex parentIndex;
if (GetEntryIndex(parent, parentIndex))
{
m_addingEntry = true;
int row = parent->GetChildCount();
beginInsertRows(parentIndex, row, row);
}
}
void AssetBrowserModel::EndAddEntry(AssetBrowserEntry* parent)
{
if (m_addingEntry)
{
m_addingEntry = false;
endInsertRows();
// we have to also invalidate our parent all the way up the chain.
// since in this model, the children's data is actually relevant to the filtering of a parent
// since a parent "matches" the filter if its children do.
if ((m_rootEntry) && (!m_rootEntry->IsInitialUpdate()))
{
// this is only necessary if its not the initial refresh.
while (parent)
{
QModelIndex parentIndex;
if (GetEntryIndex(parent, parentIndex))
{
Q_EMIT dataChanged(parentIndex, parentIndex);
}
parent = parent->GetParent();
}
}
}
}
void AssetBrowserModel::BeginRemoveEntry(AssetBrowserEntry* entry)
{
int row = entry->row();
QModelIndex parentIndex;
if (GetEntryIndex(entry->m_parentAssetEntry, parentIndex))
{
m_removingEntry = true;
beginRemoveRows(parentIndex, row, row);
}
}
void AssetBrowserModel::EndRemoveEntry()
{
if (m_removingEntry)
{
m_removingEntry = false;
endRemoveRows();
}
}
void AssetBrowserModel::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/)
{
// if any entries changed since last tick, notify the views
if (EntryCache* cache = EntryCache::GetInstance())
{
if (!cache->m_dirtyThumbnailsSet.empty())
{
for (AssetBrowserEntry* entry : cache->m_dirtyThumbnailsSet)
{
QModelIndex index;
if (GetEntryIndex(entry, index))
{
AZ_PUSH_DISABLE_WARNING(4127, "-Wunknown-warning-option") // conditional expression is constant
Q_EMIT dataChanged(index, index, { Roles::EntryRole });
AZ_POP_DISABLE_WARNING
}
}
cache->m_dirtyThumbnailsSet.clear();
}
}
}
bool AssetBrowserModel::GetEntryIndex(AssetBrowserEntry* entry, QModelIndex& index) const
{
if (!entry)
{
return false;
}
if (azrtti_istypeof<RootAssetBrowserEntry*>(entry))
{
index = QModelIndex();
return true;
}
if (!entry->m_parentAssetEntry)
{
return false;
}
int row = entry->row();
index = createIndex(row, aznumeric_cast<int>(AssetBrowserEntry::Column::DisplayName), entry);
return true;
}
} // namespace AssetBrowser
} // namespace AzToolsFramework
#include "AssetBrowser/moc_AssetBrowserModel.cpp"
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/test/begin_frame_args_test.h"
#include "base/time/time.h"
#include "cc/output/begin_frame_args.h"
#include "ui/gfx/frame_time.h"
namespace cc {
BeginFrameArgs CreateBeginFrameArgsForTesting() {
return CreateBeginFrameArgsForTesting(gfx::FrameTime::Now());
}
BeginFrameArgs CreateBeginFrameArgsForTesting(base::TimeTicks frame_time) {
return BeginFrameArgs::Create(
frame_time, frame_time + (BeginFrameArgs::DefaultInterval() / 2),
BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL);
}
BeginFrameArgs CreateBeginFrameArgsForTesting(int64 frame_time,
int64 deadline,
int64 interval) {
return BeginFrameArgs::Create(base::TimeTicks::FromInternalValue(frame_time),
base::TimeTicks::FromInternalValue(deadline),
base::TimeDelta::FromInternalValue(interval),
BeginFrameArgs::NORMAL);
}
BeginFrameArgs CreateBeginFrameArgsForTesting(
int64 frame_time,
int64 deadline,
int64 interval,
BeginFrameArgs::BeginFrameArgsType type) {
return BeginFrameArgs::Create(base::TimeTicks::FromInternalValue(frame_time),
base::TimeTicks::FromInternalValue(deadline),
base::TimeDelta::FromInternalValue(interval),
type);
}
BeginFrameArgs CreateExpiredBeginFrameArgsForTesting() {
base::TimeTicks now = gfx::FrameTime::Now();
return BeginFrameArgs::Create(now, now - BeginFrameArgs::DefaultInterval(),
BeginFrameArgs::DefaultInterval(),
BeginFrameArgs::NORMAL);
}
BeginFrameArgs CreateBeginFrameArgsForTesting(
scoped_refptr<TestNowSource> now_src) {
base::TimeTicks now = now_src->Now();
return BeginFrameArgs::Create(
now, now + (BeginFrameArgs::DefaultInterval() / 2),
BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL);
}
BeginFrameArgs CreateExpiredBeginFrameArgsForTesting(
scoped_refptr<TestNowSource> now_src) {
base::TimeTicks now = now_src->Now();
return BeginFrameArgs::Create(now, now - BeginFrameArgs::DefaultInterval(),
BeginFrameArgs::DefaultInterval(),
BeginFrameArgs::NORMAL);
}
bool operator==(const BeginFrameArgs& lhs, const BeginFrameArgs& rhs) {
return (lhs.type == rhs.type) && (lhs.frame_time == rhs.frame_time) &&
(lhs.deadline == rhs.deadline) && (lhs.interval == rhs.interval);
}
::std::ostream& operator<<(::std::ostream& os, const BeginFrameArgs& args) {
PrintTo(args, &os);
return os;
}
void PrintTo(const BeginFrameArgs& args, ::std::ostream* os) {
*os << "BeginFrameArgs(" << BeginFrameArgs::TypeToString(args.type) << ", "
<< args.frame_time.ToInternalValue() << ", "
<< args.deadline.ToInternalValue() << ", "
<< args.interval.InMicroseconds() << "us)";
}
} // namespace cc
|
/**
* FastReport Cloud
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
*
* NOTE: This class is auto generated by OpenAPI-Generator 5.1.1.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "SubscriptionsApi.h"
#include "IHttpBody.h"
#include "JsonBody.h"
#include "MultipartFormData.h"
#include <unordered_set>
#include <boost/algorithm/string/replace.hpp>
namespace fastreport {
namespace cloud {
namespace client {
using namespace fastreport::cloud::models;
SubscriptionsApi::SubscriptionsApi( std::shared_ptr<const ApiClient> apiClient )
: m_ApiClient(apiClient)
{
}
SubscriptionsApi::~SubscriptionsApi()
{
}
pplx::task<std::shared_ptr<DefaultPermissions>> SubscriptionsApi::subscriptionsGetDefaultPermissions(utility::string_t subscriptionId) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{subscriptionId}/defaultPermissions");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("subscriptionId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(subscriptionId));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetDefaultPermissions does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetDefaultPermissions does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsGetDefaultPermissions: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetDefaultPermissions: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<DefaultPermissions> localVarResult(new DefaultPermissions());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetDefaultPermissions: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<MyPermissionsVM>> SubscriptionsApi::subscriptionsGetMyPermissions(utility::string_t subId) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{subId}/mypermissions");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("subId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(subId));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetMyPermissions does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetMyPermissions does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsGetMyPermissions: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetMyPermissions: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<MyPermissionsVM> localVarResult(new MyPermissionsVM());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetMyPermissions: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<SubscriptionPermissionsVM>> SubscriptionsApi::subscriptionsGetPermissions(utility::string_t id) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{id}/permissions");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("id") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(id));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetPermissions does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetPermissions does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsGetPermissions: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetPermissions: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<SubscriptionPermissionsVM> localVarResult(new SubscriptionPermissionsVM());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetPermissions: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<SubscriptionVM>> SubscriptionsApi::subscriptionsGetSubscription(utility::string_t id) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{id}");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("id") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(id));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetSubscription does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetSubscription does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsGetSubscription: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetSubscription: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<SubscriptionVM> localVarResult(new SubscriptionVM());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetSubscription: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<SubscriptionsVM>> SubscriptionsApi::subscriptionsGetSubscriptions(boost::optional<int32_t> skip, boost::optional<int32_t> take) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions");
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetSubscriptions does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
if (skip)
{
localVarQueryParams[utility::conversions::to_string_t("skip")] = ApiClient::parameterToString(*skip);
}
if (take)
{
localVarQueryParams[utility::conversions::to_string_t("take")] = ApiClient::parameterToString(*take);
}
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsGetSubscriptions does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("GET"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsGetSubscriptions: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetSubscriptions: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<SubscriptionsVM> localVarResult(new SubscriptionsVM());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsGetSubscriptions: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<SubscriptionVM>> SubscriptionsApi::subscriptionsRenameSubscription(utility::string_t subscriptionId, std::shared_ptr<RenameSubscriptionVM> renameSubscriptionVM) const
{
// verify the required parameter 'renameSubscriptionVM' is set
if (renameSubscriptionVM == nullptr)
{
throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'renameSubscriptionVM' when calling SubscriptionsApi->subscriptionsRenameSubscription"));
}
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{subscriptionId}/rename");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("subscriptionId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(subscriptionId));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsRenameSubscription does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("text/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/_*+json") );
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
web::json::value localVarJson;
localVarJson = ModelBase::toJson(renameSubscriptionVM);
localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);
if(renameSubscriptionVM.get())
{
renameSubscriptionVM->toMultipart(localVarMultipart, utility::conversions::to_string_t("renameSubscriptionVM"));
}
localVarHttpBody = localVarMultipart;
localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsRenameSubscription does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("PUT"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsRenameSubscription: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsRenameSubscription: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<SubscriptionVM> localVarResult(new SubscriptionVM());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsRenameSubscription: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<DefaultPermissionsVM>> SubscriptionsApi::subscriptionsUpdateDefaultPermissions(utility::string_t subscriptionId, std::shared_ptr<UpdateDefaultPermissionsVM> updateDefaultPermissionsVM) const
{
// verify the required parameter 'updateDefaultPermissionsVM' is set
if (updateDefaultPermissionsVM == nullptr)
{
throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'updateDefaultPermissionsVM' when calling SubscriptionsApi->subscriptionsUpdateDefaultPermissions"));
}
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{subscriptionId}/defaultPermissions");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("subscriptionId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(subscriptionId));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsUpdateDefaultPermissions does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("text/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/_*+json") );
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
web::json::value localVarJson;
localVarJson = ModelBase::toJson(updateDefaultPermissionsVM);
localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);
if(updateDefaultPermissionsVM.get())
{
updateDefaultPermissionsVM->toMultipart(localVarMultipart, utility::conversions::to_string_t("updateDefaultPermissionsVM"));
}
localVarHttpBody = localVarMultipart;
localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsUpdateDefaultPermissions does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("PUT"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsUpdateDefaultPermissions: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsUpdateDefaultPermissions: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<DefaultPermissionsVM> localVarResult(new DefaultPermissionsVM());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsUpdateDefaultPermissions: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<std::shared_ptr<SubscriptionVM>> SubscriptionsApi::subscriptionsUpdateLocale(utility::string_t subscriptionId, std::shared_ptr<UpdateSubscriptionLocaleVM> updateSubscriptionLocaleVM) const
{
// verify the required parameter 'updateSubscriptionLocaleVM' is set
if (updateSubscriptionLocaleVM == nullptr)
{
throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'updateSubscriptionLocaleVM' when calling SubscriptionsApi->subscriptionsUpdateLocale"));
}
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{subscriptionId}/Locale");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("subscriptionId") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(subscriptionId));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsUpdateLocale does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("text/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/_*+json") );
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
web::json::value localVarJson;
localVarJson = ModelBase::toJson(updateSubscriptionLocaleVM);
localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);
if(updateSubscriptionLocaleVM.get())
{
updateSubscriptionLocaleVM->toMultipart(localVarMultipart, utility::conversions::to_string_t("updateSubscriptionLocaleVM"));
}
localVarHttpBody = localVarMultipart;
localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsUpdateLocale does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("PUT"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsUpdateLocale: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsUpdateLocale: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
std::shared_ptr<SubscriptionVM> localVarResult(new SubscriptionVM());
if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
{
web::json::value localVarJson = web::json::value::parse(localVarResponse);
ModelBase::fromJson(localVarJson, localVarResult);
}
// else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsUpdateLocale: unsupported response type"));
}
return localVarResult;
});
}
pplx::task<void> SubscriptionsApi::subscriptionsUpdatePermissions(utility::string_t id, boost::optional<std::shared_ptr<UpdateSubscriptionPermissionsVM>> updateSubscriptionPermissionsVM) const
{
std::shared_ptr<const ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t localVarPath = utility::conversions::to_string_t("/api/manage/v1/Subscriptions/{id}/permissions");
boost::replace_all(localVarPath, utility::conversions::to_string_t("{") + utility::conversions::to_string_t("id") + utility::conversions::to_string_t("}"), ApiClient::parameterToString(id));
std::map<utility::string_t, utility::string_t> localVarQueryParams;
std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> localVarFormParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;
std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
utility::string_t localVarResponseHttpContentType;
// use JSON if possible
if ( localVarResponseHttpContentTypes.size() == 0 )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// JSON
else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
}
// multipart formdata
else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
{
localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
}
else
{
throw ApiException(400, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsUpdatePermissions does not produce any supported media type"));
}
localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;
std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("text/json") );
localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/_*+json") );
std::shared_ptr<IHttpBody> localVarHttpBody;
utility::string_t localVarRequestHttpContentType;
// use JSON if possible
if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
web::json::value localVarJson;
if (updateSubscriptionPermissionsVM)
localVarJson = ModelBase::toJson(*updateSubscriptionPermissionsVM);
localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
}
// multipart formdata
else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
{
localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);
if(updateSubscriptionPermissionsVM && (*updateSubscriptionPermissionsVM).get())
{
(*updateSubscriptionPermissionsVM)->toMultipart(localVarMultipart, utility::conversions::to_string_t("updateSubscriptionPermissionsVM"));
}
localVarHttpBody = localVarMultipart;
localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
}
else if (localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/x-www-form-urlencoded")) != localVarConsumeHttpContentTypes.end())
{
localVarRequestHttpContentType = utility::conversions::to_string_t("application/x-www-form-urlencoded");
}
else
{
throw ApiException(415, utility::conversions::to_string_t("SubscriptionsApi->subscriptionsUpdatePermissions does not consume any supported media type"));
}
// authentication (ApiKey) required
// Basic authentication is added automatically as part of the http_client_config
// authentication (JWT) required
// Basic authentication is added automatically as part of the http_client_config
return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
.then([=](web::http::http_response localVarResponse)
{
if (m_ApiClient->getResponseHandler())
{
m_ApiClient->getResponseHandler()(localVarResponse.status_code(), localVarResponse.headers());
}
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (localVarResponse.status_code() >= 400)
{
throw ApiException(localVarResponse.status_code()
, utility::conversions::to_string_t("error calling subscriptionsUpdatePermissions: ") + localVarResponse.reason_phrase()
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
// check response content type
if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
{
utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
{
throw ApiException(500
, utility::conversions::to_string_t("error calling subscriptionsUpdatePermissions: unexpected response type: ") + localVarContentType
, std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
}
}
return localVarResponse.extract_string();
})
.then([=](utility::string_t localVarResponse)
{
return void();
});
}
}
}
}
|
// Copyright (c) 2019 Álvaro Ceballos
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
#ifndef CYNODELIC_MULINUM_TEST_MAKE_FROM_TAG_HPP
#define CYNODELIC_MULINUM_TEST_MAKE_FROM_TAG_HPP
CYNODELIC_TESTER_TEST_CASE_SINGLE_SECTION(make_from_tag)
{
using namespace mln::placeholders;
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag<mln::vector_tag>,mln::vector<>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag<mln::vector_tag,unsigned>,mln::vector<unsigned>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag<mln::vector_tag,int,float,char,short,double>,mln::vector<int,float,char,short,double>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag<mln::list_tag>,mln::null_type>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag<mln::list_tag,unsigned>,mln::list_node<unsigned,mln::null_type>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag<mln::list_tag,int,float,char,short,double>,mln::list_node<int,mln::list_node<float,mln::list_node<char,mln::list_node<short,mln::list_node<double,mln::null_type>>>>>>::value));
}
CYNODELIC_TESTER_TEST_CASE_SINGLE_SECTION(make_from_tag_c)
{
using namespace mln::placeholders;
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::integer_tag<int>,105>,mln::integer_c<int,105>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::rational_tag,-221,439>,mln::rational<-221,439>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::vector_c_tag<int>>,mln::int_vector<>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::vector_c_tag<int>,5>,mln::int_vector<5>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::vector_c_tag<int>,1,1,2,3,5,8,13,21>,mln::int_vector<1,1,2,3,5,8,13,21>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::list_c_tag<int>>,mln::null_type>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::list_c_tag<int>,1>,mln::int_list<1>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::list_c_tag<int>,1,1,2,3,5,8,13,21>,mln::int_list<1,1,2,3,5,8,13,21>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::string_tag>,mln::string<>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::string_tag,'X'>,mln::string<'X'>>::value));
CYNODELIC_TESTER_CHECK_TRUE((mln::equals<mln::make_from_tag_c<mln::string_tag,'H','e','l','l','o'>,mln::string<'H','e','l','l','o'>>::value));
}
#endif
|
// Copyright 2012 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/api.h"
#include <string.h> // For memcpy, strlen.
#ifdef V8_USE_ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
#endif // V8_USE_ADDRESS_SANITIZER
#include <cmath> // For isnan.
#include "include/v8-debug.h"
#include "include/v8-profiler.h"
#include "include/v8-testing.h"
#include "src/assert-scope.h"
#include "src/background-parsing-task.h"
#include "src/base/platform/platform.h"
#include "src/base/platform/time.h"
#include "src/base/utils/random-number-generator.h"
#include "src/bootstrapper.h"
#include "src/code-stubs.h"
#include "src/compiler.h"
#include "src/conversions-inl.h"
#include "src/counters.h"
#include "src/cpu-profiler.h"
#include "src/debug.h"
#include "src/deoptimizer.h"
#include "src/execution.h"
#include "src/global-handles.h"
#include "src/heap-profiler.h"
#include "src/heap-snapshot-generator-inl.h"
#include "src/icu_util.h"
#include "src/json-parser.h"
#include "src/messages.h"
#include "src/natives.h"
#include "src/parser.h"
#include "src/profile-generator-inl.h"
#include "src/property.h"
#include "src/property-details.h"
#include "src/prototype.h"
#include "src/runtime/runtime.h"
#include "src/runtime-profiler.h"
#include "src/sampler.h"
#include "src/scanner-character-streams.h"
#include "src/simulator.h"
#include "src/snapshot.h"
#include "src/unicode-inl.h"
#include "src/v8threads.h"
#include "src/version.h"
#include "src/vm-state-inl.h"
#define LOG_API(isolate, expr) LOG(isolate, ApiEntryCall(expr))
#define ENTER_V8(isolate) \
DCHECK((isolate)->IsInitialized()); \
i::VMState<v8::OTHER> __state__((isolate))
namespace v8 {
#define ON_BAILOUT(isolate, location, code) \
if (IsExecutionTerminatingCheck(isolate)) { \
code; \
UNREACHABLE(); \
}
#define EXCEPTION_PREAMBLE(isolate) \
(isolate)->handle_scope_implementer()->IncrementCallDepth(); \
DCHECK(!(isolate)->external_caught_exception()); \
bool has_pending_exception = false
#define EXCEPTION_BAILOUT_CHECK_GENERIC(isolate, value, do_callback) \
do { \
i::HandleScopeImplementer* handle_scope_implementer = \
(isolate)->handle_scope_implementer(); \
handle_scope_implementer->DecrementCallDepth(); \
if (has_pending_exception) { \
bool call_depth_is_zero = handle_scope_implementer->CallDepthIsZero(); \
(isolate)->OptionalRescheduleException(call_depth_is_zero); \
do_callback \
return value; \
} \
do_callback \
} while (false)
#define EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, value) \
EXCEPTION_BAILOUT_CHECK_GENERIC( \
isolate, value, isolate->FireCallCompletedCallback();)
#define EXCEPTION_BAILOUT_CHECK(isolate, value) \
EXCEPTION_BAILOUT_CHECK_GENERIC(isolate, value, ;)
// --- E x c e p t i o n B e h a v i o r ---
void i::FatalProcessOutOfMemory(const char* location) {
i::V8::FatalProcessOutOfMemory(location, false);
}
// When V8 cannot allocated memory FatalProcessOutOfMemory is called.
// The default fatal error handler is called and execution is stopped.
void i::V8::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
i::HeapStats heap_stats;
int start_marker;
heap_stats.start_marker = &start_marker;
int new_space_size;
heap_stats.new_space_size = &new_space_size;
int new_space_capacity;
heap_stats.new_space_capacity = &new_space_capacity;
intptr_t old_pointer_space_size;
heap_stats.old_pointer_space_size = &old_pointer_space_size;
intptr_t old_pointer_space_capacity;
heap_stats.old_pointer_space_capacity = &old_pointer_space_capacity;
intptr_t old_data_space_size;
heap_stats.old_data_space_size = &old_data_space_size;
intptr_t old_data_space_capacity;
heap_stats.old_data_space_capacity = &old_data_space_capacity;
intptr_t code_space_size;
heap_stats.code_space_size = &code_space_size;
intptr_t code_space_capacity;
heap_stats.code_space_capacity = &code_space_capacity;
intptr_t map_space_size;
heap_stats.map_space_size = &map_space_size;
intptr_t map_space_capacity;
heap_stats.map_space_capacity = &map_space_capacity;
intptr_t cell_space_size;
heap_stats.cell_space_size = &cell_space_size;
intptr_t cell_space_capacity;
heap_stats.cell_space_capacity = &cell_space_capacity;
intptr_t property_cell_space_size;
heap_stats.property_cell_space_size = &property_cell_space_size;
intptr_t property_cell_space_capacity;
heap_stats.property_cell_space_capacity = &property_cell_space_capacity;
intptr_t lo_space_size;
heap_stats.lo_space_size = &lo_space_size;
int global_handle_count;
heap_stats.global_handle_count = &global_handle_count;
int weak_global_handle_count;
heap_stats.weak_global_handle_count = &weak_global_handle_count;
int pending_global_handle_count;
heap_stats.pending_global_handle_count = &pending_global_handle_count;
int near_death_global_handle_count;
heap_stats.near_death_global_handle_count = &near_death_global_handle_count;
int free_global_handle_count;
heap_stats.free_global_handle_count = &free_global_handle_count;
intptr_t memory_allocator_size;
heap_stats.memory_allocator_size = &memory_allocator_size;
intptr_t memory_allocator_capacity;
heap_stats.memory_allocator_capacity = &memory_allocator_capacity;
int objects_per_type[LAST_TYPE + 1] = {0};
heap_stats.objects_per_type = objects_per_type;
int size_per_type[LAST_TYPE + 1] = {0};
heap_stats.size_per_type = size_per_type;
int os_error;
heap_stats.os_error = &os_error;
int end_marker;
heap_stats.end_marker = &end_marker;
i::Isolate* isolate = i::Isolate::Current();
if (isolate->heap()->HasBeenSetUp()) {
// BUG(1718): Don't use the take_snapshot since we don't support
// HeapIterator here without doing a special GC.
isolate->heap()->RecordStats(&heap_stats, false);
}
Utils::ApiCheck(false, location, "Allocation failed - process out of memory");
// If the fatal error handler returns, we stop execution.
FATAL("API fatal error handler returned after process out of memory");
}
void Utils::ReportApiFailure(const char* location, const char* message) {
i::Isolate* isolate = i::Isolate::Current();
FatalErrorCallback callback = isolate->exception_behavior();
if (callback == NULL) {
base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
message);
base::OS::Abort();
} else {
callback(location, message);
}
isolate->SignalFatalError();
}
bool V8::IsDead() {
i::Isolate* isolate = i::Isolate::Current();
return isolate->IsDead();
}
static inline bool IsExecutionTerminatingCheck(i::Isolate* isolate) {
if (!isolate->IsInitialized()) return false;
if (isolate->has_scheduled_exception()) {
return isolate->scheduled_exception() ==
isolate->heap()->termination_exception();
}
return false;
}
StartupDataDecompressor::StartupDataDecompressor()
: raw_data(i::NewArray<char*>(V8::GetCompressedStartupDataCount())) {
for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
raw_data[i] = NULL;
}
}
StartupDataDecompressor::~StartupDataDecompressor() {
for (int i = 0; i < V8::GetCompressedStartupDataCount(); ++i) {
i::DeleteArray(raw_data[i]);
}
i::DeleteArray(raw_data);
}
int StartupDataDecompressor::Decompress() {
int compressed_data_count = V8::GetCompressedStartupDataCount();
StartupData* compressed_data =
i::NewArray<StartupData>(compressed_data_count);
V8::GetCompressedStartupData(compressed_data);
for (int i = 0; i < compressed_data_count; ++i) {
char* decompressed = raw_data[i] =
i::NewArray<char>(compressed_data[i].raw_size);
if (compressed_data[i].compressed_size != 0) {
int result = DecompressData(decompressed,
&compressed_data[i].raw_size,
compressed_data[i].data,
compressed_data[i].compressed_size);
if (result != 0) return result;
} else {
DCHECK_EQ(0, compressed_data[i].raw_size);
}
compressed_data[i].data = decompressed;
}
V8::SetDecompressedStartupData(compressed_data);
i::DeleteArray(compressed_data);
return 0;
}
StartupData::CompressionAlgorithm V8::GetCompressedStartupDataAlgorithm() {
#ifdef COMPRESS_STARTUP_DATA_BZ2
return StartupData::kBZip2;
#else
return StartupData::kUncompressed;
#endif
}
enum CompressedStartupDataItems {
kSnapshot = 0,
kSnapshotContext,
kLibraries,
kExperimentalLibraries,
kCompressedStartupDataCount
};
int V8::GetCompressedStartupDataCount() {
#ifdef COMPRESS_STARTUP_DATA_BZ2
return kCompressedStartupDataCount;
#else
return 0;
#endif
}
void V8::GetCompressedStartupData(StartupData* compressed_data) {
#ifdef COMPRESS_STARTUP_DATA_BZ2
compressed_data[kSnapshot].data =
reinterpret_cast<const char*>(i::Snapshot::data());
compressed_data[kSnapshot].compressed_size = i::Snapshot::size();
compressed_data[kSnapshot].raw_size = i::Snapshot::raw_size();
compressed_data[kSnapshotContext].data =
reinterpret_cast<const char*>(i::Snapshot::context_data());
compressed_data[kSnapshotContext].compressed_size =
i::Snapshot::context_size();
compressed_data[kSnapshotContext].raw_size = i::Snapshot::context_raw_size();
i::Vector<const i::byte> libraries_source = i::Natives::GetScriptsSource();
compressed_data[kLibraries].data =
reinterpret_cast<const char*>(libraries_source.start());
compressed_data[kLibraries].compressed_size = libraries_source.length();
compressed_data[kLibraries].raw_size = i::Natives::GetRawScriptsSize();
i::Vector<const i::byte> exp_libraries_source =
i::ExperimentalNatives::GetScriptsSource();
compressed_data[kExperimentalLibraries].data =
reinterpret_cast<const char*>(exp_libraries_source.start());
compressed_data[kExperimentalLibraries].compressed_size =
exp_libraries_source.length();
compressed_data[kExperimentalLibraries].raw_size =
i::ExperimentalNatives::GetRawScriptsSize();
#endif
}
void V8::SetDecompressedStartupData(StartupData* decompressed_data) {
#ifdef COMPRESS_STARTUP_DATA_BZ2
DCHECK_EQ(i::Snapshot::raw_size(), decompressed_data[kSnapshot].raw_size);
i::Snapshot::set_raw_data(
reinterpret_cast<const i::byte*>(decompressed_data[kSnapshot].data));
DCHECK_EQ(i::Snapshot::context_raw_size(),
decompressed_data[kSnapshotContext].raw_size);
i::Snapshot::set_context_raw_data(
reinterpret_cast<const i::byte*>(
decompressed_data[kSnapshotContext].data));
DCHECK_EQ(i::Natives::GetRawScriptsSize(),
decompressed_data[kLibraries].raw_size);
i::Vector<const char> libraries_source(
decompressed_data[kLibraries].data,
decompressed_data[kLibraries].raw_size);
i::Natives::SetRawScriptsSource(libraries_source);
DCHECK_EQ(i::ExperimentalNatives::GetRawScriptsSize(),
decompressed_data[kExperimentalLibraries].raw_size);
i::Vector<const char> exp_libraries_source(
decompressed_data[kExperimentalLibraries].data,
decompressed_data[kExperimentalLibraries].raw_size);
i::ExperimentalNatives::SetRawScriptsSource(exp_libraries_source);
#endif
}
void V8::SetNativesDataBlob(StartupData* natives_blob) {
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
i::SetNativesFromFile(natives_blob);
#else
CHECK(false);
#endif
}
void V8::SetSnapshotDataBlob(StartupData* snapshot_blob) {
#ifdef V8_USE_EXTERNAL_STARTUP_DATA
i::SetSnapshotFromFile(snapshot_blob);
#else
CHECK(false);
#endif
}
void V8::SetFatalErrorHandler(FatalErrorCallback that) {
i::Isolate* isolate = i::Isolate::Current();
isolate->set_exception_behavior(that);
}
void V8::SetAllowCodeGenerationFromStringsCallback(
AllowCodeGenerationFromStringsCallback callback) {
i::Isolate* isolate = i::Isolate::Current();
isolate->set_allow_code_gen_callback(callback);
}
void V8::SetFlagsFromString(const char* str, int length) {
i::FlagList::SetFlagsFromString(str, length);
}
void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags);
}
RegisteredExtension* RegisteredExtension::first_extension_ = NULL;
RegisteredExtension::RegisteredExtension(Extension* extension)
: extension_(extension) { }
void RegisteredExtension::Register(RegisteredExtension* that) {
that->next_ = first_extension_;
first_extension_ = that;
}
void RegisteredExtension::UnregisterAll() {
RegisteredExtension* re = first_extension_;
while (re != NULL) {
RegisteredExtension* next = re->next();
delete re;
re = next;
}
first_extension_ = NULL;
}
void RegisterExtension(Extension* that) {
RegisteredExtension* extension = new RegisteredExtension(that);
RegisteredExtension::Register(extension);
}
Extension::Extension(const char* name,
const char* source,
int dep_count,
const char** deps,
int source_length)
: name_(name),
source_length_(source_length >= 0 ?
source_length :
(source ? static_cast<int>(strlen(source)) : 0)),
source_(source, source_length_),
dep_count_(dep_count),
deps_(deps),
auto_enable_(false) {
CHECK(source != NULL || source_length_ == 0);
}
ResourceConstraints::ResourceConstraints()
: max_semi_space_size_(0),
max_old_space_size_(0),
max_executable_size_(0),
stack_limit_(NULL),
max_available_threads_(0),
code_range_size_(0) { }
void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
uint64_t virtual_memory_limit,
uint32_t number_of_processors) {
#if V8_OS_ANDROID
// Android has higher physical memory requirements before raising the maximum
// heap size limits since it has no swap space.
const uint64_t low_limit = 512ul * i::MB;
const uint64_t medium_limit = 1ul * i::GB;
const uint64_t high_limit = 2ul * i::GB;
#else
const uint64_t low_limit = 512ul * i::MB;
const uint64_t medium_limit = 768ul * i::MB;
const uint64_t high_limit = 1ul * i::GB;
#endif
if (physical_memory <= low_limit) {
set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeLowMemoryDevice);
set_max_old_space_size(i::Heap::kMaxOldSpaceSizeLowMemoryDevice);
set_max_executable_size(i::Heap::kMaxExecutableSizeLowMemoryDevice);
} else if (physical_memory <= medium_limit) {
set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeMediumMemoryDevice);
set_max_old_space_size(i::Heap::kMaxOldSpaceSizeMediumMemoryDevice);
set_max_executable_size(i::Heap::kMaxExecutableSizeMediumMemoryDevice);
} else if (physical_memory <= high_limit) {
set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHighMemoryDevice);
set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHighMemoryDevice);
set_max_executable_size(i::Heap::kMaxExecutableSizeHighMemoryDevice);
} else {
set_max_semi_space_size(i::Heap::kMaxSemiSpaceSizeHugeMemoryDevice);
set_max_old_space_size(i::Heap::kMaxOldSpaceSizeHugeMemoryDevice);
set_max_executable_size(i::Heap::kMaxExecutableSizeHugeMemoryDevice);
}
set_max_available_threads(i::Max(i::Min(number_of_processors, 4u), 1u));
if (virtual_memory_limit > 0 && i::kRequiresCodeRange) {
// Reserve no more than 1/8 of the memory for the code range, but at most
// kMaximalCodeRangeSize.
set_code_range_size(
i::Min(i::kMaximalCodeRangeSize / i::MB,
static_cast<size_t>((virtual_memory_limit >> 3) / i::MB)));
}
}
void SetResourceConstraints(i::Isolate* isolate,
const ResourceConstraints& constraints) {
int semi_space_size = constraints.max_semi_space_size();
int old_space_size = constraints.max_old_space_size();
int max_executable_size = constraints.max_executable_size();
size_t code_range_size = constraints.code_range_size();
if (semi_space_size != 0 || old_space_size != 0 ||
max_executable_size != 0 || code_range_size != 0) {
isolate->heap()->ConfigureHeap(semi_space_size, old_space_size,
max_executable_size, code_range_size);
}
if (constraints.stack_limit() != NULL) {
uintptr_t limit = reinterpret_cast<uintptr_t>(constraints.stack_limit());
isolate->stack_guard()->SetStackLimit(limit);
}
isolate->set_max_available_threads(constraints.max_available_threads());
}
i::Object** V8::GlobalizeReference(i::Isolate* isolate, i::Object** obj) {
LOG_API(isolate, "Persistent::New");
i::Handle<i::Object> result = isolate->global_handles()->Create(*obj);
#ifdef DEBUG
(*obj)->ObjectVerify();
#endif // DEBUG
return result.location();
}
i::Object** V8::CopyPersistent(i::Object** obj) {
i::Handle<i::Object> result = i::GlobalHandles::CopyGlobal(obj);
#ifdef DEBUG
(*obj)->ObjectVerify();
#endif // DEBUG
return result.location();
}
void V8::MakeWeak(i::Object** object,
void* parameters,
WeakCallback weak_callback) {
i::GlobalHandles::MakeWeak(object, parameters, weak_callback);
}
void* V8::ClearWeak(i::Object** obj) {
return i::GlobalHandles::ClearWeakness(obj);
}
void V8::DisposeGlobal(i::Object** obj) {
i::GlobalHandles::Destroy(obj);
}
void V8::Eternalize(Isolate* v8_isolate, Value* value, int* index) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
i::Object* object = *Utils::OpenHandle(value);
isolate->eternal_handles()->Create(isolate, object, index);
}
Local<Value> V8::GetEternal(Isolate* v8_isolate, int index) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
return Utils::ToLocal(isolate->eternal_handles()->Get(index));
}
// --- H a n d l e s ---
HandleScope::HandleScope(Isolate* isolate) {
Initialize(isolate);
}
void HandleScope::Initialize(Isolate* isolate) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
// We do not want to check the correct usage of the Locker class all over the
// place, so we do it only here: Without a HandleScope, an embedder can do
// almost nothing, so it is enough to check in this central place.
Utils::ApiCheck(!v8::Locker::IsActive() ||
internal_isolate->thread_manager()->IsLockedByCurrentThread(),
"HandleScope::HandleScope",
"Entering the V8 API without proper locking in place");
i::HandleScopeData* current = internal_isolate->handle_scope_data();
isolate_ = internal_isolate;
prev_next_ = current->next;
prev_limit_ = current->limit;
current->level++;
}
HandleScope::~HandleScope() {
i::HandleScope::CloseScope(isolate_, prev_next_, prev_limit_);
}
int HandleScope::NumberOfHandles(Isolate* isolate) {
return i::HandleScope::NumberOfHandles(
reinterpret_cast<i::Isolate*>(isolate));
}
i::Object** HandleScope::CreateHandle(i::Isolate* isolate, i::Object* value) {
return i::HandleScope::CreateHandle(isolate, value);
}
i::Object** HandleScope::CreateHandle(i::HeapObject* heap_object,
i::Object* value) {
DCHECK(heap_object->IsHeapObject());
return i::HandleScope::CreateHandle(heap_object->GetIsolate(), value);
}
EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
escape_slot_ = CreateHandle(isolate, isolate->heap()->the_hole_value());
Initialize(v8_isolate);
}
i::Object** EscapableHandleScope::Escape(i::Object** escape_value) {
i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
Utils::ApiCheck(*escape_slot_ == heap->the_hole_value(),
"EscapeableHandleScope::Escape",
"Escape value set twice");
if (escape_value == NULL) {
*escape_slot_ = heap->undefined_value();
return NULL;
}
*escape_slot_ = *escape_value;
return escape_slot_;
}
void Context::Enter() {
i::Handle<i::Context> env = Utils::OpenHandle(this);
i::Isolate* isolate = env->GetIsolate();
ENTER_V8(isolate);
i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
impl->EnterContext(env);
impl->SaveContext(isolate->context());
isolate->set_context(*env);
}
void Context::Exit() {
i::Handle<i::Context> env = Utils::OpenHandle(this);
i::Isolate* isolate = env->GetIsolate();
ENTER_V8(isolate);
i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
if (!Utils::ApiCheck(impl->LastEnteredContextWas(env),
"v8::Context::Exit()",
"Cannot exit non-entered context")) {
return;
}
impl->LeaveContext();
isolate->set_context(impl->RestoreContext());
}
static void* DecodeSmiToAligned(i::Object* value, const char* location) {
Utils::ApiCheck(value->IsSmi(), location, "Not a Smi");
return reinterpret_cast<void*>(value);
}
static i::Smi* EncodeAlignedAsSmi(void* value, const char* location) {
i::Smi* smi = reinterpret_cast<i::Smi*>(value);
Utils::ApiCheck(smi->IsSmi(), location, "Pointer is not aligned");
return smi;
}
static i::Handle<i::FixedArray> EmbedderDataFor(Context* context,
int index,
bool can_grow,
const char* location) {
i::Handle<i::Context> env = Utils::OpenHandle(context);
bool ok =
Utils::ApiCheck(env->IsNativeContext(),
location,
"Not a native context") &&
Utils::ApiCheck(index >= 0, location, "Negative index");
if (!ok) return i::Handle<i::FixedArray>();
i::Handle<i::FixedArray> data(env->embedder_data());
if (index < data->length()) return data;
if (!Utils::ApiCheck(can_grow, location, "Index too large")) {
return i::Handle<i::FixedArray>();
}
int new_size = i::Max(index, data->length() << 1) + 1;
data = i::FixedArray::CopySize(data, new_size);
env->set_embedder_data(*data);
return data;
}
v8::Local<v8::Value> Context::SlowGetEmbedderData(int index) {
const char* location = "v8::Context::GetEmbedderData()";
i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
if (data.is_null()) return Local<Value>();
i::Handle<i::Object> result(data->get(index), data->GetIsolate());
return Utils::ToLocal(result);
}
void Context::SetEmbedderData(int index, v8::Handle<Value> value) {
const char* location = "v8::Context::SetEmbedderData()";
i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
if (data.is_null()) return;
i::Handle<i::Object> val = Utils::OpenHandle(*value);
data->set(index, *val);
DCHECK_EQ(*Utils::OpenHandle(*value),
*Utils::OpenHandle(*GetEmbedderData(index)));
}
void* Context::SlowGetAlignedPointerFromEmbedderData(int index) {
const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, false, location);
if (data.is_null()) return NULL;
return DecodeSmiToAligned(data->get(index), location);
}
void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
i::Handle<i::FixedArray> data = EmbedderDataFor(this, index, true, location);
data->set(index, EncodeAlignedAsSmi(value, location));
DCHECK_EQ(value, GetAlignedPointerFromEmbedderData(index));
}
// --- N e a n d e r ---
// A constructor cannot easily return an error value, therefore it is necessary
// to check for a dead VM with ON_BAILOUT before constructing any Neander
// objects. To remind you about this there is no HandleScope in the
// NeanderObject constructor. When you add one to the site calling the
// constructor you should check that you ensured the VM was not dead first.
NeanderObject::NeanderObject(v8::internal::Isolate* isolate, int size) {
ENTER_V8(isolate);
value_ = isolate->factory()->NewNeanderObject();
i::Handle<i::FixedArray> elements = isolate->factory()->NewFixedArray(size);
value_->set_elements(*elements);
}
int NeanderObject::size() {
return i::FixedArray::cast(value_->elements())->length();
}
NeanderArray::NeanderArray(v8::internal::Isolate* isolate) : obj_(isolate, 2) {
obj_.set(0, i::Smi::FromInt(0));
}
int NeanderArray::length() {
return i::Smi::cast(obj_.get(0))->value();
}
i::Object* NeanderArray::get(int offset) {
DCHECK(0 <= offset);
DCHECK(offset < length());
return obj_.get(offset + 1);
}
// This method cannot easily return an error value, therefore it is necessary
// to check for a dead VM with ON_BAILOUT before calling it. To remind you
// about this there is no HandleScope in this method. When you add one to the
// site calling this method you should check that you ensured the VM was not
// dead first.
void NeanderArray::add(i::Handle<i::Object> value) {
int length = this->length();
int size = obj_.size();
if (length == size - 1) {
i::Factory* factory = i::Isolate::Current()->factory();
i::Handle<i::FixedArray> new_elms = factory->NewFixedArray(2 * size);
for (int i = 0; i < length; i++)
new_elms->set(i + 1, get(i));
obj_.value()->set_elements(*new_elms);
}
obj_.set(length + 1, *value);
obj_.set(0, i::Smi::FromInt(length + 1));
}
void NeanderArray::set(int index, i::Object* value) {
if (index < 0 || index >= this->length()) return;
obj_.set(index + 1, value);
}
// --- T e m p l a t e ---
static void InitializeTemplate(i::Handle<i::TemplateInfo> that, int type) {
that->set_tag(i::Smi::FromInt(type));
}
static void TemplateSet(i::Isolate* isolate,
v8::Template* templ,
int length,
v8::Handle<v8::Data>* data) {
i::Handle<i::Object> list(Utils::OpenHandle(templ)->property_list(), isolate);
if (list->IsUndefined()) {
list = NeanderArray(isolate).value();
Utils::OpenHandle(templ)->set_property_list(*list);
}
NeanderArray array(list);
array.add(isolate->factory()->NewNumberFromInt(length));
for (int i = 0; i < length; i++) {
i::Handle<i::Object> value = data[i].IsEmpty() ?
i::Handle<i::Object>(isolate->factory()->undefined_value()) :
Utils::OpenHandle(*data[i]);
array.add(value);
}
}
void Template::Set(v8::Handle<Name> name,
v8::Handle<Data> value,
v8::PropertyAttribute attribute) {
i::Isolate* isolate = i::Isolate::Current();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
const int kSize = 3;
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
v8::Handle<v8::Data> data[kSize] = {
name,
value,
v8::Integer::New(v8_isolate, attribute)};
TemplateSet(isolate, this, kSize, data);
}
void Template::SetAccessorProperty(
v8::Local<v8::Name> name,
v8::Local<FunctionTemplate> getter,
v8::Local<FunctionTemplate> setter,
v8::PropertyAttribute attribute,
v8::AccessControl access_control) {
// TODO(verwaest): Remove |access_control|.
DCHECK_EQ(v8::DEFAULT, access_control);
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
DCHECK(!name.IsEmpty());
DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
i::HandleScope scope(isolate);
const int kSize = 5;
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
v8::Handle<v8::Data> data[kSize] = {
name,
getter,
setter,
v8::Integer::New(v8_isolate, attribute)};
TemplateSet(isolate, this, kSize, data);
}
// --- F u n c t i o n T e m p l a t e ---
static void InitializeFunctionTemplate(
i::Handle<i::FunctionTemplateInfo> info) {
info->set_tag(i::Smi::FromInt(Consts::FUNCTION_TEMPLATE));
info->set_flag(0);
}
Local<ObjectTemplate> FunctionTemplate::PrototypeTemplate() {
i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(i_isolate);
i::Handle<i::Object> result(Utils::OpenHandle(this)->prototype_template(),
i_isolate);
if (result->IsUndefined()) {
v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(i_isolate);
result = Utils::OpenHandle(*ObjectTemplate::New(isolate));
Utils::OpenHandle(this)->set_prototype_template(*result);
}
return ToApiHandle<ObjectTemplate>(result);
}
void FunctionTemplate::Inherit(v8::Handle<FunctionTemplate> value) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
Utils::OpenHandle(this)->set_parent_template(*Utils::OpenHandle(*value));
}
static Local<FunctionTemplate> FunctionTemplateNew(
i::Isolate* isolate,
FunctionCallback callback,
v8::Handle<Value> data,
v8::Handle<Signature> signature,
int length,
bool do_not_cache) {
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE);
i::Handle<i::FunctionTemplateInfo> obj =
i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
InitializeFunctionTemplate(obj);
obj->set_do_not_cache(do_not_cache);
int next_serial_number = 0;
if (!do_not_cache) {
next_serial_number = isolate->next_serial_number() + 1;
isolate->set_next_serial_number(next_serial_number);
}
obj->set_serial_number(i::Smi::FromInt(next_serial_number));
if (callback != 0) {
if (data.IsEmpty()) {
data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
Utils::ToLocal(obj)->SetCallHandler(callback, data);
}
obj->set_length(length);
obj->set_undetectable(false);
obj->set_needs_access_check(false);
if (!signature.IsEmpty())
obj->set_signature(*Utils::OpenHandle(*signature));
return Utils::ToLocal(obj);
}
Local<FunctionTemplate> FunctionTemplate::New(
Isolate* isolate,
FunctionCallback callback,
v8::Handle<Value> data,
v8::Handle<Signature> signature,
int length) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "FunctionTemplate::New");
ENTER_V8(i_isolate);
return FunctionTemplateNew(
i_isolate, callback, data, signature, length, false);
}
Local<Signature> Signature::New(Isolate* isolate,
Handle<FunctionTemplate> receiver, int argc,
Handle<FunctionTemplate> argv[]) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "Signature::New");
ENTER_V8(i_isolate);
i::Handle<i::Struct> struct_obj =
i_isolate->factory()->NewStruct(i::SIGNATURE_INFO_TYPE);
i::Handle<i::SignatureInfo> obj =
i::Handle<i::SignatureInfo>::cast(struct_obj);
if (!receiver.IsEmpty()) obj->set_receiver(*Utils::OpenHandle(*receiver));
if (argc > 0) {
i::Handle<i::FixedArray> args = i_isolate->factory()->NewFixedArray(argc);
for (int i = 0; i < argc; i++) {
if (!argv[i].IsEmpty())
args->set(i, *Utils::OpenHandle(*argv[i]));
}
obj->set_args(*args);
}
return Utils::ToLocal(obj);
}
Local<AccessorSignature> AccessorSignature::New(
Isolate* isolate,
Handle<FunctionTemplate> receiver) {
return Utils::AccessorSignatureToLocal(Utils::OpenHandle(*receiver));
}
template<typename Operation>
static Local<Operation> NewDescriptor(
Isolate* isolate,
const i::DeclaredAccessorDescriptorData& data,
Data* previous_descriptor) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
i::Handle<i::DeclaredAccessorDescriptor> previous =
i::Handle<i::DeclaredAccessorDescriptor>();
if (previous_descriptor != NULL) {
previous = Utils::OpenHandle(
static_cast<DeclaredAccessorDescriptor*>(previous_descriptor));
}
i::Handle<i::DeclaredAccessorDescriptor> descriptor =
i::DeclaredAccessorDescriptor::Create(internal_isolate, data, previous);
return Utils::Convert<i::DeclaredAccessorDescriptor, Operation>(descriptor);
}
Local<RawOperationDescriptor>
ObjectOperationDescriptor::NewInternalFieldDereference(
Isolate* isolate,
int internal_field) {
i::DeclaredAccessorDescriptorData data;
data.type = i::kDescriptorObjectDereference;
data.object_dereference_descriptor.internal_field = internal_field;
return NewDescriptor<RawOperationDescriptor>(isolate, data, NULL);
}
Local<RawOperationDescriptor> RawOperationDescriptor::NewRawShift(
Isolate* isolate,
int16_t byte_offset) {
i::DeclaredAccessorDescriptorData data;
data.type = i::kDescriptorPointerShift;
data.pointer_shift_descriptor.byte_offset = byte_offset;
return NewDescriptor<RawOperationDescriptor>(isolate, data, this);
}
Local<DeclaredAccessorDescriptor> RawOperationDescriptor::NewHandleDereference(
Isolate* isolate) {
i::DeclaredAccessorDescriptorData data;
data.type = i::kDescriptorReturnObject;
return NewDescriptor<DeclaredAccessorDescriptor>(isolate, data, this);
}
Local<RawOperationDescriptor> RawOperationDescriptor::NewRawDereference(
Isolate* isolate) {
i::DeclaredAccessorDescriptorData data;
data.type = i::kDescriptorPointerDereference;
return NewDescriptor<RawOperationDescriptor>(isolate, data, this);
}
Local<DeclaredAccessorDescriptor> RawOperationDescriptor::NewPointerCompare(
Isolate* isolate,
void* compare_value) {
i::DeclaredAccessorDescriptorData data;
data.type = i::kDescriptorPointerCompare;
data.pointer_compare_descriptor.compare_value = compare_value;
return NewDescriptor<DeclaredAccessorDescriptor>(isolate, data, this);
}
Local<DeclaredAccessorDescriptor> RawOperationDescriptor::NewPrimitiveValue(
Isolate* isolate,
DeclaredAccessorDescriptorDataType data_type,
uint8_t bool_offset) {
i::DeclaredAccessorDescriptorData data;
data.type = i::kDescriptorPrimitiveValue;
data.primitive_value_descriptor.data_type = data_type;
data.primitive_value_descriptor.bool_offset = bool_offset;
return NewDescriptor<DeclaredAccessorDescriptor>(isolate, data, this);
}
template<typename T>
static Local<DeclaredAccessorDescriptor> NewBitmaskCompare(
Isolate* isolate,
T bitmask,
T compare_value,
RawOperationDescriptor* operation) {
i::DeclaredAccessorDescriptorData data;
data.type = i::kDescriptorBitmaskCompare;
data.bitmask_compare_descriptor.bitmask = bitmask;
data.bitmask_compare_descriptor.compare_value = compare_value;
data.bitmask_compare_descriptor.size = sizeof(T);
return NewDescriptor<DeclaredAccessorDescriptor>(isolate, data, operation);
}
Local<DeclaredAccessorDescriptor> RawOperationDescriptor::NewBitmaskCompare8(
Isolate* isolate,
uint8_t bitmask,
uint8_t compare_value) {
return NewBitmaskCompare(isolate, bitmask, compare_value, this);
}
Local<DeclaredAccessorDescriptor> RawOperationDescriptor::NewBitmaskCompare16(
Isolate* isolate,
uint16_t bitmask,
uint16_t compare_value) {
return NewBitmaskCompare(isolate, bitmask, compare_value, this);
}
Local<DeclaredAccessorDescriptor> RawOperationDescriptor::NewBitmaskCompare32(
Isolate* isolate,
uint32_t bitmask,
uint32_t compare_value) {
return NewBitmaskCompare(isolate, bitmask, compare_value, this);
}
Local<TypeSwitch> TypeSwitch::New(Handle<FunctionTemplate> type) {
Handle<FunctionTemplate> types[1] = { type };
return TypeSwitch::New(1, types);
}
Local<TypeSwitch> TypeSwitch::New(int argc, Handle<FunctionTemplate> types[]) {
i::Isolate* isolate = i::Isolate::Current();
LOG_API(isolate, "TypeSwitch::New");
ENTER_V8(isolate);
i::Handle<i::FixedArray> vector = isolate->factory()->NewFixedArray(argc);
for (int i = 0; i < argc; i++)
vector->set(i, *Utils::OpenHandle(*types[i]));
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::TYPE_SWITCH_INFO_TYPE);
i::Handle<i::TypeSwitchInfo> obj =
i::Handle<i::TypeSwitchInfo>::cast(struct_obj);
obj->set_types(*vector);
return Utils::ToLocal(obj);
}
int TypeSwitch::match(v8::Handle<Value> value) {
i::Isolate* isolate = i::Isolate::Current();
LOG_API(isolate, "TypeSwitch::match");
USE(isolate);
i::Handle<i::Object> obj = Utils::OpenHandle(*value);
i::Handle<i::TypeSwitchInfo> info = Utils::OpenHandle(this);
i::FixedArray* types = i::FixedArray::cast(info->types());
for (int i = 0; i < types->length(); i++) {
if (i::FunctionTemplateInfo::cast(types->get(i))->IsTemplateFor(*obj))
return i + 1;
}
return 0;
}
#define SET_FIELD_WRAPPED(obj, setter, cdata) do { \
i::Handle<i::Object> foreign = FromCData(obj->GetIsolate(), cdata); \
(obj)->setter(*foreign); \
} while (false)
void FunctionTemplate::SetCallHandler(FunctionCallback callback,
v8::Handle<Value> data) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
i::Handle<i::CallHandlerInfo> obj =
i::Handle<i::CallHandlerInfo>::cast(struct_obj);
SET_FIELD_WRAPPED(obj, set_callback, callback);
if (data.IsEmpty()) {
data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
obj->set_data(*Utils::OpenHandle(*data));
Utils::OpenHandle(this)->set_call_code(*obj);
}
static i::Handle<i::AccessorInfo> SetAccessorInfoProperties(
i::Handle<i::AccessorInfo> obj,
v8::Handle<Name> name,
v8::AccessControl settings,
v8::PropertyAttribute attributes,
v8::Handle<AccessorSignature> signature) {
obj->set_name(*Utils::OpenHandle(*name));
if (settings & ALL_CAN_READ) obj->set_all_can_read(true);
if (settings & ALL_CAN_WRITE) obj->set_all_can_write(true);
obj->set_property_attributes(static_cast<PropertyAttributes>(attributes));
if (!signature.IsEmpty()) {
obj->set_expected_receiver_type(*Utils::OpenHandle(*signature));
}
return obj;
}
template<typename Getter, typename Setter>
static i::Handle<i::AccessorInfo> MakeAccessorInfo(
v8::Handle<Name> name,
Getter getter,
Setter setter,
v8::Handle<Value> data,
v8::AccessControl settings,
v8::PropertyAttribute attributes,
v8::Handle<AccessorSignature> signature) {
i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate();
i::Handle<i::ExecutableAccessorInfo> obj =
isolate->factory()->NewExecutableAccessorInfo();
SET_FIELD_WRAPPED(obj, set_getter, getter);
SET_FIELD_WRAPPED(obj, set_setter, setter);
if (data.IsEmpty()) {
data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
obj->set_data(*Utils::OpenHandle(*data));
return SetAccessorInfoProperties(obj, name, settings, attributes, signature);
}
static i::Handle<i::AccessorInfo> MakeAccessorInfo(
v8::Handle<Name> name,
v8::Handle<v8::DeclaredAccessorDescriptor> descriptor,
void* setter_ignored,
void* data_ignored,
v8::AccessControl settings,
v8::PropertyAttribute attributes,
v8::Handle<AccessorSignature> signature) {
i::Isolate* isolate = Utils::OpenHandle(*name)->GetIsolate();
if (descriptor.IsEmpty()) return i::Handle<i::DeclaredAccessorInfo>();
i::Handle<i::DeclaredAccessorInfo> obj =
isolate->factory()->NewDeclaredAccessorInfo();
obj->set_descriptor(*Utils::OpenHandle(*descriptor));
return SetAccessorInfoProperties(obj, name, settings, attributes, signature);
}
Local<ObjectTemplate> FunctionTemplate::InstanceTemplate() {
i::Handle<i::FunctionTemplateInfo> handle = Utils::OpenHandle(this, true);
if (!Utils::ApiCheck(!handle.is_null(),
"v8::FunctionTemplate::InstanceTemplate()",
"Reading from empty handle")) {
return Local<ObjectTemplate>();
}
i::Isolate* isolate = handle->GetIsolate();
ENTER_V8(isolate);
if (handle->instance_template()->IsUndefined()) {
Local<ObjectTemplate> templ =
ObjectTemplate::New(isolate, ToApiHandle<FunctionTemplate>(handle));
handle->set_instance_template(*Utils::OpenHandle(*templ));
}
i::Handle<i::ObjectTemplateInfo> result(
i::ObjectTemplateInfo::cast(handle->instance_template()));
return Utils::ToLocal(result);
}
void FunctionTemplate::SetLength(int length) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
Utils::OpenHandle(this)->set_length(length);
}
void FunctionTemplate::SetClassName(Handle<String> name) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
Utils::OpenHandle(this)->set_class_name(*Utils::OpenHandle(*name));
}
void FunctionTemplate::SetHiddenPrototype(bool value) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
Utils::OpenHandle(this)->set_hidden_prototype(value);
}
void FunctionTemplate::ReadOnlyPrototype() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
Utils::OpenHandle(this)->set_read_only_prototype(true);
}
void FunctionTemplate::RemovePrototype() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
Utils::OpenHandle(this)->set_remove_prototype(true);
}
// --- O b j e c t T e m p l a t e ---
Local<ObjectTemplate> ObjectTemplate::New(Isolate* isolate) {
return New(reinterpret_cast<i::Isolate*>(isolate), Local<FunctionTemplate>());
}
Local<ObjectTemplate> ObjectTemplate::New() {
return New(i::Isolate::Current(), Local<FunctionTemplate>());
}
Local<ObjectTemplate> ObjectTemplate::New(
i::Isolate* isolate,
v8::Handle<FunctionTemplate> constructor) {
LOG_API(isolate, "ObjectTemplate::New");
ENTER_V8(isolate);
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE);
i::Handle<i::ObjectTemplateInfo> obj =
i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
if (!constructor.IsEmpty())
obj->set_constructor(*Utils::OpenHandle(*constructor));
obj->set_internal_field_count(i::Smi::FromInt(0));
return Utils::ToLocal(obj);
}
// Ensure that the object template has a constructor. If no
// constructor is available we create one.
static i::Handle<i::FunctionTemplateInfo> EnsureConstructor(
i::Isolate* isolate,
ObjectTemplate* object_template) {
i::Object* obj = Utils::OpenHandle(object_template)->constructor();
if (!obj ->IsUndefined()) {
i::FunctionTemplateInfo* info = i::FunctionTemplateInfo::cast(obj);
return i::Handle<i::FunctionTemplateInfo>(info, isolate);
}
Local<FunctionTemplate> templ =
FunctionTemplate::New(reinterpret_cast<Isolate*>(isolate));
i::Handle<i::FunctionTemplateInfo> constructor = Utils::OpenHandle(*templ);
constructor->set_instance_template(*Utils::OpenHandle(object_template));
Utils::OpenHandle(object_template)->set_constructor(*constructor);
return constructor;
}
static inline void AddPropertyToTemplate(
i::Handle<i::TemplateInfo> info,
i::Handle<i::AccessorInfo> obj) {
i::Isolate* isolate = info->GetIsolate();
i::Handle<i::Object> list(info->property_accessors(), isolate);
if (list->IsUndefined()) {
list = NeanderArray(isolate).value();
info->set_property_accessors(*list);
}
NeanderArray array(list);
array.add(obj);
}
static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
i::Isolate* isolate,
Template* template_obj) {
return Utils::OpenHandle(template_obj);
}
// TODO(dcarney): remove this with ObjectTemplate::SetAccessor
static inline i::Handle<i::TemplateInfo> GetTemplateInfo(
i::Isolate* isolate,
ObjectTemplate* object_template) {
EnsureConstructor(isolate, object_template);
return Utils::OpenHandle(object_template);
}
template<typename Getter, typename Setter, typename Data, typename Template>
static bool TemplateSetAccessor(
Template* template_obj,
v8::Local<Name> name,
Getter getter,
Setter setter,
Data data,
AccessControl settings,
PropertyAttribute attribute,
v8::Local<AccessorSignature> signature) {
i::Isolate* isolate = Utils::OpenHandle(template_obj)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::AccessorInfo> obj = MakeAccessorInfo(
name, getter, setter, data, settings, attribute, signature);
if (obj.is_null()) return false;
i::Handle<i::TemplateInfo> info = GetTemplateInfo(isolate, template_obj);
AddPropertyToTemplate(info, obj);
return true;
}
bool Template::SetDeclaredAccessor(
Local<Name> name,
Local<DeclaredAccessorDescriptor> descriptor,
PropertyAttribute attribute,
Local<AccessorSignature> signature,
AccessControl settings) {
void* null = NULL;
return TemplateSetAccessor(
this, name, descriptor, null, null, settings, attribute, signature);
}
void Template::SetNativeDataProperty(v8::Local<String> name,
AccessorGetterCallback getter,
AccessorSetterCallback setter,
v8::Handle<Value> data,
PropertyAttribute attribute,
v8::Local<AccessorSignature> signature,
AccessControl settings) {
TemplateSetAccessor(
this, name, getter, setter, data, settings, attribute, signature);
}
void Template::SetNativeDataProperty(v8::Local<Name> name,
AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter,
v8::Handle<Value> data,
PropertyAttribute attribute,
v8::Local<AccessorSignature> signature,
AccessControl settings) {
TemplateSetAccessor(
this, name, getter, setter, data, settings, attribute, signature);
}
void ObjectTemplate::SetAccessor(v8::Handle<String> name,
AccessorGetterCallback getter,
AccessorSetterCallback setter,
v8::Handle<Value> data,
AccessControl settings,
PropertyAttribute attribute,
v8::Handle<AccessorSignature> signature) {
TemplateSetAccessor(
this, name, getter, setter, data, settings, attribute, signature);
}
void ObjectTemplate::SetAccessor(v8::Handle<Name> name,
AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter,
v8::Handle<Value> data,
AccessControl settings,
PropertyAttribute attribute,
v8::Handle<AccessorSignature> signature) {
TemplateSetAccessor(
this, name, getter, setter, data, settings, attribute, signature);
}
void ObjectTemplate::SetNamedPropertyHandler(
NamedPropertyGetterCallback getter,
NamedPropertySetterCallback setter,
NamedPropertyQueryCallback query,
NamedPropertyDeleterCallback remover,
NamedPropertyEnumeratorCallback enumerator,
Handle<Value> data) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
EnsureConstructor(isolate, this);
i::FunctionTemplateInfo* constructor = i::FunctionTemplateInfo::cast(
Utils::OpenHandle(this)->constructor());
i::Handle<i::FunctionTemplateInfo> cons(constructor);
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE);
i::Handle<i::InterceptorInfo> obj =
i::Handle<i::InterceptorInfo>::cast(struct_obj);
if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
if (data.IsEmpty()) {
data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
obj->set_data(*Utils::OpenHandle(*data));
cons->set_named_property_handler(*obj);
}
void ObjectTemplate::MarkAsUndetectable() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
EnsureConstructor(isolate, this);
i::FunctionTemplateInfo* constructor =
i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
i::Handle<i::FunctionTemplateInfo> cons(constructor);
cons->set_undetectable(true);
}
void ObjectTemplate::SetAccessCheckCallbacks(
NamedSecurityCallback named_callback,
IndexedSecurityCallback indexed_callback,
Handle<Value> data,
bool turned_on_by_default) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
EnsureConstructor(isolate, this);
i::Handle<i::Struct> struct_info =
isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE);
i::Handle<i::AccessCheckInfo> info =
i::Handle<i::AccessCheckInfo>::cast(struct_info);
SET_FIELD_WRAPPED(info, set_named_callback, named_callback);
SET_FIELD_WRAPPED(info, set_indexed_callback, indexed_callback);
if (data.IsEmpty()) {
data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
info->set_data(*Utils::OpenHandle(*data));
i::FunctionTemplateInfo* constructor =
i::FunctionTemplateInfo::cast(Utils::OpenHandle(this)->constructor());
i::Handle<i::FunctionTemplateInfo> cons(constructor);
cons->set_access_check_info(*info);
cons->set_needs_access_check(turned_on_by_default);
}
void ObjectTemplate::SetIndexedPropertyHandler(
IndexedPropertyGetterCallback getter,
IndexedPropertySetterCallback setter,
IndexedPropertyQueryCallback query,
IndexedPropertyDeleterCallback remover,
IndexedPropertyEnumeratorCallback enumerator,
Handle<Value> data) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
EnsureConstructor(isolate, this);
i::FunctionTemplateInfo* constructor = i::FunctionTemplateInfo::cast(
Utils::OpenHandle(this)->constructor());
i::Handle<i::FunctionTemplateInfo> cons(constructor);
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE);
i::Handle<i::InterceptorInfo> obj =
i::Handle<i::InterceptorInfo>::cast(struct_obj);
if (getter != 0) SET_FIELD_WRAPPED(obj, set_getter, getter);
if (setter != 0) SET_FIELD_WRAPPED(obj, set_setter, setter);
if (query != 0) SET_FIELD_WRAPPED(obj, set_query, query);
if (remover != 0) SET_FIELD_WRAPPED(obj, set_deleter, remover);
if (enumerator != 0) SET_FIELD_WRAPPED(obj, set_enumerator, enumerator);
if (data.IsEmpty()) {
data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
obj->set_data(*Utils::OpenHandle(*data));
cons->set_indexed_property_handler(*obj);
}
void ObjectTemplate::SetCallAsFunctionHandler(FunctionCallback callback,
Handle<Value> data) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
EnsureConstructor(isolate, this);
i::FunctionTemplateInfo* constructor = i::FunctionTemplateInfo::cast(
Utils::OpenHandle(this)->constructor());
i::Handle<i::FunctionTemplateInfo> cons(constructor);
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE);
i::Handle<i::CallHandlerInfo> obj =
i::Handle<i::CallHandlerInfo>::cast(struct_obj);
SET_FIELD_WRAPPED(obj, set_callback, callback);
if (data.IsEmpty()) {
data = v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
obj->set_data(*Utils::OpenHandle(*data));
cons->set_instance_call_handler(*obj);
}
int ObjectTemplate::InternalFieldCount() {
return i::Smi::cast(Utils::OpenHandle(this)->internal_field_count())->value();
}
void ObjectTemplate::SetInternalFieldCount(int value) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
if (!Utils::ApiCheck(i::Smi::IsValid(value),
"v8::ObjectTemplate::SetInternalFieldCount()",
"Invalid internal field count")) {
return;
}
ENTER_V8(isolate);
if (value > 0) {
// The internal field count is set by the constructor function's
// construct code, so we ensure that there is a constructor
// function to do the setting.
EnsureConstructor(isolate, this);
}
Utils::OpenHandle(this)->set_internal_field_count(i::Smi::FromInt(value));
}
// --- S c r i p t s ---
// Internally, UnboundScript is a SharedFunctionInfo, and Script is a
// JSFunction.
ScriptCompiler::CachedData::CachedData(const uint8_t* data_, int length_,
BufferPolicy buffer_policy_)
: data(data_), length(length_), buffer_policy(buffer_policy_) {}
ScriptCompiler::CachedData::~CachedData() {
if (buffer_policy == BufferOwned) {
delete[] data;
}
}
ScriptCompiler::StreamedSource::StreamedSource(ExternalSourceStream* stream,
Encoding encoding)
: impl_(new i::StreamedSource(stream, encoding)) {}
ScriptCompiler::StreamedSource::~StreamedSource() { delete impl_; }
const ScriptCompiler::CachedData*
ScriptCompiler::StreamedSource::GetCachedData() const {
return impl_->cached_data.get();
}
Local<Script> UnboundScript::BindToCurrentContext() {
i::Handle<i::HeapObject> obj =
i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
i::Handle<i::SharedFunctionInfo>
function_info(i::SharedFunctionInfo::cast(*obj), obj->GetIsolate());
i::Handle<i::JSFunction> function =
obj->GetIsolate()->factory()->NewFunctionFromSharedFunctionInfo(
function_info, obj->GetIsolate()->global_context());
return ToApiHandle<Script>(function);
}
int UnboundScript::GetId() {
i::Handle<i::HeapObject> obj =
i::Handle<i::HeapObject>::cast(Utils::OpenHandle(this));
i::Isolate* isolate = obj->GetIsolate();
ON_BAILOUT(isolate, "v8::UnboundScript::GetId()", return -1);
LOG_API(isolate, "v8::UnboundScript::GetId");
{
i::HandleScope scope(isolate);
i::Handle<i::SharedFunctionInfo> function_info(
i::SharedFunctionInfo::cast(*obj));
i::Handle<i::Script> script(i::Script::cast(function_info->script()));
return script->id()->value();
}
}
int UnboundScript::GetLineNumber(int code_pos) {
i::Handle<i::SharedFunctionInfo> obj =
i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
i::Isolate* isolate = obj->GetIsolate();
ON_BAILOUT(isolate, "v8::UnboundScript::GetLineNumber()", return -1);
LOG_API(isolate, "UnboundScript::GetLineNumber");
if (obj->script()->IsScript()) {
i::Handle<i::Script> script(i::Script::cast(obj->script()));
return i::Script::GetLineNumber(script, code_pos);
} else {
return -1;
}
}
Handle<Value> UnboundScript::GetScriptName() {
i::Handle<i::SharedFunctionInfo> obj =
i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
i::Isolate* isolate = obj->GetIsolate();
ON_BAILOUT(isolate, "v8::UnboundScript::GetName()",
return Handle<String>());
LOG_API(isolate, "UnboundScript::GetName");
if (obj->script()->IsScript()) {
i::Object* name = i::Script::cast(obj->script())->name();
return Utils::ToLocal(i::Handle<i::Object>(name, isolate));
} else {
return Handle<String>();
}
}
Handle<Value> UnboundScript::GetSourceURL() {
i::Handle<i::SharedFunctionInfo> obj =
i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
i::Isolate* isolate = obj->GetIsolate();
ON_BAILOUT(isolate, "v8::UnboundScript::GetSourceURL()",
return Handle<String>());
LOG_API(isolate, "UnboundScript::GetSourceURL");
if (obj->script()->IsScript()) {
i::Object* url = i::Script::cast(obj->script())->source_url();
return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
} else {
return Handle<String>();
}
}
Handle<Value> UnboundScript::GetSourceMappingURL() {
i::Handle<i::SharedFunctionInfo> obj =
i::Handle<i::SharedFunctionInfo>::cast(Utils::OpenHandle(this));
i::Isolate* isolate = obj->GetIsolate();
ON_BAILOUT(isolate, "v8::UnboundScript::GetSourceMappingURL()",
return Handle<String>());
LOG_API(isolate, "UnboundScript::GetSourceMappingURL");
if (obj->script()->IsScript()) {
i::Object* url = i::Script::cast(obj->script())->source_mapping_url();
return Utils::ToLocal(i::Handle<i::Object>(url, isolate));
} else {
return Handle<String>();
}
}
Local<Value> Script::Run() {
i::Handle<i::Object> obj = Utils::OpenHandle(this, true);
// If execution is terminating, Compile(..)->Run() requires this
// check.
if (obj.is_null()) return Local<Value>();
i::Isolate* isolate = i::Handle<i::HeapObject>::cast(obj)->GetIsolate();
ON_BAILOUT(isolate, "v8::Script::Run()", return Local<Value>());
LOG_API(isolate, "Script::Run");
ENTER_V8(isolate);
i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(obj);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> receiver(isolate->global_proxy(), isolate);
i::Handle<i::Object> result;
has_pending_exception = !i::Execution::Call(
isolate, fun, receiver, 0, NULL).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, Local<Value>());
return Utils::ToLocal(scope.CloseAndEscape(result));
}
Local<UnboundScript> Script::GetUnboundScript() {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
return ToApiHandle<UnboundScript>(
i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared()));
}
Local<UnboundScript> ScriptCompiler::CompileUnbound(
Isolate* v8_isolate,
Source* source,
CompileOptions options) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ON_BAILOUT(isolate, "v8::ScriptCompiler::CompileUnbound()",
return Local<UnboundScript>());
// Support the old API for a transition period:
// - kProduceToCache -> kProduceParserCache
// - kNoCompileOptions + cached_data != NULL -> kConsumeParserCache
if (options == kProduceDataToCache) {
options = kProduceParserCache;
} else if (options == kNoCompileOptions && source->cached_data) {
options = kConsumeParserCache;
}
i::ScriptData* script_data = NULL;
if (options == kConsumeParserCache || options == kConsumeCodeCache) {
DCHECK(source->cached_data);
// ScriptData takes care of pointer-aligning the data.
script_data = new i::ScriptData(source->cached_data->data,
source->cached_data->length);
}
i::Handle<i::String> str = Utils::OpenHandle(*(source->source_string));
LOG_API(isolate, "ScriptCompiler::CompileUnbound");
ENTER_V8(isolate);
i::SharedFunctionInfo* raw_result = NULL;
{ i::HandleScope scope(isolate);
i::Handle<i::Object> name_obj;
int line_offset = 0;
int column_offset = 0;
bool is_shared_cross_origin = false;
if (!source->resource_name.IsEmpty()) {
name_obj = Utils::OpenHandle(*(source->resource_name));
}
if (!source->resource_line_offset.IsEmpty()) {
line_offset = static_cast<int>(source->resource_line_offset->Value());
}
if (!source->resource_column_offset.IsEmpty()) {
column_offset =
static_cast<int>(source->resource_column_offset->Value());
}
if (!source->resource_is_shared_cross_origin.IsEmpty()) {
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
is_shared_cross_origin =
source->resource_is_shared_cross_origin == v8::True(v8_isolate);
}
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::SharedFunctionInfo> result = i::Compiler::CompileScript(
str, name_obj, line_offset, column_offset, is_shared_cross_origin,
isolate->global_context(), NULL, &script_data, options,
i::NOT_NATIVES_CODE);
has_pending_exception = result.is_null();
if (has_pending_exception && script_data != NULL) {
// This case won't happen during normal operation; we have compiled
// successfully and produced cached data, and but the second compilation
// of the same source code fails.
delete script_data;
script_data = NULL;
}
EXCEPTION_BAILOUT_CHECK(isolate, Local<UnboundScript>());
raw_result = *result;
if ((options == kProduceParserCache || options == kProduceCodeCache) &&
script_data != NULL) {
// script_data now contains the data that was generated. source will
// take the ownership.
source->cached_data = new CachedData(
script_data->data(), script_data->length(), CachedData::BufferOwned);
script_data->ReleaseDataOwnership();
}
delete script_data;
}
i::Handle<i::SharedFunctionInfo> result(raw_result, isolate);
return ToApiHandle<UnboundScript>(result);
}
Local<Script> ScriptCompiler::Compile(
Isolate* v8_isolate,
Source* source,
CompileOptions options) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
ON_BAILOUT(isolate, "v8::ScriptCompiler::Compile()", return Local<Script>());
LOG_API(isolate, "ScriptCompiler::CompiletBound()");
ENTER_V8(isolate);
Local<UnboundScript> generic = CompileUnbound(v8_isolate, source, options);
if (generic.IsEmpty()) return Local<Script>();
return generic->BindToCurrentContext();
}
ScriptCompiler::ScriptStreamingTask* ScriptCompiler::StartStreamingScript(
Isolate* v8_isolate, StreamedSource* source, CompileOptions options) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
if (!isolate->global_context().is_null() &&
!isolate->global_context()->IsNativeContext()) {
// The context chain is non-trivial, and constructing the corresponding
// non-trivial Scope chain outside the V8 heap is not implemented. Don't
// stream the script. This will only occur if Harmony scoping is enabled and
// a previous script has introduced "let" or "const" variables. TODO(marja):
// Implement externalizing ScopeInfos and constructing non-trivial Scope
// chains independent of the V8 heap so that we can stream also in this
// case.
return NULL;
}
return new i::BackgroundParsingTask(source->impl(), options,
i::FLAG_stack_size, isolate);
}
Local<Script> ScriptCompiler::Compile(Isolate* v8_isolate,
StreamedSource* v8_source,
Handle<String> full_source_string,
const ScriptOrigin& origin) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
i::StreamedSource* source = v8_source->impl();
ON_BAILOUT(isolate, "v8::ScriptCompiler::Compile()", return Local<Script>());
LOG_API(isolate, "ScriptCompiler::Compile()");
ENTER_V8(isolate);
i::SharedFunctionInfo* raw_result = NULL;
{
i::HandleScope scope(isolate);
i::Handle<i::String> str = Utils::OpenHandle(*(full_source_string));
i::Handle<i::Script> script = isolate->factory()->NewScript(str);
if (!origin.ResourceName().IsEmpty()) {
script->set_name(*Utils::OpenHandle(*(origin.ResourceName())));
}
if (!origin.ResourceLineOffset().IsEmpty()) {
script->set_line_offset(i::Smi::FromInt(
static_cast<int>(origin.ResourceLineOffset()->Value())));
}
if (!origin.ResourceColumnOffset().IsEmpty()) {
script->set_column_offset(i::Smi::FromInt(
static_cast<int>(origin.ResourceColumnOffset()->Value())));
}
if (!origin.ResourceIsSharedCrossOrigin().IsEmpty()) {
script->set_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin() ==
v8::True(v8_isolate));
}
source->info->set_script(script);
source->info->SetContext(isolate->global_context());
EXCEPTION_PREAMBLE(isolate);
// Do the parsing tasks which need to be done on the main thread. This will
// also handle parse errors.
source->parser->Internalize();
i::Handle<i::SharedFunctionInfo> result =
i::Handle<i::SharedFunctionInfo>::null();
if (source->info->function() != NULL) {
// Parsing has succeeded.
result =
i::Compiler::CompileStreamedScript(source->info.get(), str->length());
}
has_pending_exception = result.is_null();
if (has_pending_exception) isolate->ReportPendingMessages();
EXCEPTION_BAILOUT_CHECK(isolate, Local<Script>());
raw_result = *result;
// The Handle<Script> will go out of scope soon; make sure CompilationInfo
// doesn't point to it.
source->info->set_script(i::Handle<i::Script>());
} // HandleScope goes out of scope.
i::Handle<i::SharedFunctionInfo> result(raw_result, isolate);
Local<UnboundScript> generic = ToApiHandle<UnboundScript>(result);
if (generic.IsEmpty()) {
return Local<Script>();
}
return generic->BindToCurrentContext();
}
Local<Script> Script::Compile(v8::Handle<String> source,
v8::ScriptOrigin* origin) {
i::Handle<i::String> str = Utils::OpenHandle(*source);
if (origin) {
ScriptCompiler::Source script_source(source, *origin);
return ScriptCompiler::Compile(
reinterpret_cast<v8::Isolate*>(str->GetIsolate()),
&script_source);
}
ScriptCompiler::Source script_source(source);
return ScriptCompiler::Compile(
reinterpret_cast<v8::Isolate*>(str->GetIsolate()),
&script_source);
}
Local<Script> Script::Compile(v8::Handle<String> source,
v8::Handle<String> file_name) {
ScriptOrigin origin(file_name);
return Compile(source, &origin);
}
// --- E x c e p t i o n s ---
v8::TryCatch::TryCatch()
: isolate_(i::Isolate::Current()),
next_(isolate_->try_catch_handler()),
is_verbose_(false),
can_continue_(true),
capture_message_(true),
rethrow_(false),
has_terminated_(false) {
ResetInternal();
// Special handling for simulators which have a separate JS stack.
js_stack_comparable_address_ =
reinterpret_cast<void*>(v8::internal::SimulatorStack::RegisterCTryCatch(
v8::internal::GetCurrentStackPosition()));
isolate_->RegisterTryCatchHandler(this);
}
v8::TryCatch::~TryCatch() {
DCHECK(isolate_ == i::Isolate::Current());
if (rethrow_) {
v8::Isolate* isolate = reinterpret_cast<Isolate*>(isolate_);
v8::HandleScope scope(isolate);
v8::Local<v8::Value> exc = v8::Local<v8::Value>::New(isolate, Exception());
if (HasCaught() && capture_message_) {
// If an exception was caught and rethrow_ is indicated, the saved
// message, script, and location need to be restored to Isolate TLS
// for reuse. capture_message_ needs to be disabled so that DoThrow()
// does not create a new message.
isolate_->thread_local_top()->rethrowing_message_ = true;
isolate_->RestorePendingMessageFromTryCatch(this);
}
isolate_->UnregisterTryCatchHandler(this);
v8::internal::SimulatorStack::UnregisterCTryCatch();
reinterpret_cast<Isolate*>(isolate_)->ThrowException(exc);
DCHECK(!isolate_->thread_local_top()->rethrowing_message_);
} else {
if (HasCaught() && isolate_->has_scheduled_exception()) {
// If an exception was caught but is still scheduled because no API call
// promoted it, then it is canceled to prevent it from being propagated.
// Note that this will not cancel termination exceptions.
isolate_->CancelScheduledExceptionFromTryCatch(this);
}
isolate_->UnregisterTryCatchHandler(this);
v8::internal::SimulatorStack::UnregisterCTryCatch();
}
}
bool v8::TryCatch::HasCaught() const {
return !reinterpret_cast<i::Object*>(exception_)->IsTheHole();
}
bool v8::TryCatch::CanContinue() const {
return can_continue_;
}
bool v8::TryCatch::HasTerminated() const {
return has_terminated_;
}
v8::Handle<v8::Value> v8::TryCatch::ReThrow() {
if (!HasCaught()) return v8::Local<v8::Value>();
rethrow_ = true;
return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate_));
}
v8::Local<Value> v8::TryCatch::Exception() const {
DCHECK(isolate_ == i::Isolate::Current());
if (HasCaught()) {
// Check for out of memory exception.
i::Object* exception = reinterpret_cast<i::Object*>(exception_);
return v8::Utils::ToLocal(i::Handle<i::Object>(exception, isolate_));
} else {
return v8::Local<Value>();
}
}
v8::Local<Value> v8::TryCatch::StackTrace() const {
DCHECK(isolate_ == i::Isolate::Current());
if (HasCaught()) {
i::Object* raw_obj = reinterpret_cast<i::Object*>(exception_);
if (!raw_obj->IsJSObject()) return v8::Local<Value>();
i::HandleScope scope(isolate_);
i::Handle<i::JSObject> obj(i::JSObject::cast(raw_obj), isolate_);
i::Handle<i::String> name = isolate_->factory()->stack_string();
EXCEPTION_PREAMBLE(isolate_);
Maybe<bool> maybe = i::JSReceiver::HasProperty(obj, name);
has_pending_exception = !maybe.has_value;
EXCEPTION_BAILOUT_CHECK(isolate_, v8::Local<Value>());
if (!maybe.value) return v8::Local<Value>();
i::Handle<i::Object> value;
if (!i::Object::GetProperty(obj, name).ToHandle(&value)) {
return v8::Local<Value>();
}
return v8::Utils::ToLocal(scope.CloseAndEscape(value));
} else {
return v8::Local<Value>();
}
}
v8::Local<v8::Message> v8::TryCatch::Message() const {
DCHECK(isolate_ == i::Isolate::Current());
i::Object* message = reinterpret_cast<i::Object*>(message_obj_);
DCHECK(message->IsJSMessageObject() || message->IsTheHole());
if (HasCaught() && !message->IsTheHole()) {
return v8::Utils::MessageToLocal(i::Handle<i::Object>(message, isolate_));
} else {
return v8::Local<v8::Message>();
}
}
void v8::TryCatch::Reset() {
DCHECK(isolate_ == i::Isolate::Current());
if (!rethrow_ && HasCaught() && isolate_->has_scheduled_exception()) {
// If an exception was caught but is still scheduled because no API call
// promoted it, then it is canceled to prevent it from being propagated.
// Note that this will not cancel termination exceptions.
isolate_->CancelScheduledExceptionFromTryCatch(this);
}
ResetInternal();
}
void v8::TryCatch::ResetInternal() {
i::Object* the_hole = isolate_->heap()->the_hole_value();
exception_ = the_hole;
message_obj_ = the_hole;
message_script_ = the_hole;
message_start_pos_ = 0;
message_end_pos_ = 0;
}
void v8::TryCatch::SetVerbose(bool value) {
is_verbose_ = value;
}
void v8::TryCatch::SetCaptureMessage(bool value) {
capture_message_ = value;
}
// --- M e s s a g e ---
Local<String> Message::Get() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Message::Get()", return Local<String>());
ENTER_V8(isolate);
EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::String> raw_result = i::MessageHandler::GetMessage(isolate, obj);
Local<String> result = Utils::ToLocal(raw_result);
return scope.Escape(result);
}
ScriptOrigin Message::GetScriptOrigin() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
i::Handle<i::JSMessageObject> message =
i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
i::Handle<i::Object> script_wraper =
i::Handle<i::Object>(message->script(), isolate);
i::Handle<i::JSValue> script_value =
i::Handle<i::JSValue>::cast(script_wraper);
i::Handle<i::Script> script(i::Script::cast(script_value->value()));
i::Handle<i::Object> scriptName(i::Script::GetNameOrSourceURL(script));
v8::Isolate* v8_isolate =
reinterpret_cast<v8::Isolate*>(script->GetIsolate());
v8::ScriptOrigin origin(
Utils::ToLocal(scriptName),
v8::Integer::New(v8_isolate, script->line_offset()->value()),
v8::Integer::New(v8_isolate, script->column_offset()->value()),
Handle<Boolean>(),
v8::Integer::New(v8_isolate, script->id()->value()));
return origin;
}
v8::Handle<Value> Message::GetScriptResourceName() const {
return GetScriptOrigin().ResourceName();
}
v8::Handle<v8::StackTrace> Message::GetStackTrace() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
i::Handle<i::JSMessageObject> message =
i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
i::Handle<i::Object> stackFramesObj(message->stack_frames(), isolate);
if (!stackFramesObj->IsJSArray()) return v8::Handle<v8::StackTrace>();
i::Handle<i::JSArray> stackTrace =
i::Handle<i::JSArray>::cast(stackFramesObj);
return scope.Escape(Utils::StackTraceToLocal(stackTrace));
}
MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
const char* name,
i::Handle<i::Object> recv,
int argc,
i::Handle<i::Object> argv[]) {
i::Isolate* isolate = i::Isolate::Current();
i::Handle<i::Object> object_fun =
i::Object::GetProperty(
isolate, isolate->js_builtins_object(), name).ToHandleChecked();
i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(object_fun);
return i::Execution::Call(isolate, fun, recv, argc, argv);
}
MUST_USE_RESULT static i::MaybeHandle<i::Object> CallV8HeapFunction(
const char* name,
i::Handle<i::Object> data) {
i::Handle<i::Object> argv[] = { data };
return CallV8HeapFunction(name,
i::Isolate::Current()->js_builtins_object(),
arraysize(argv),
argv);
}
int Message::GetLineNumber() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Message::GetLineNumber()", return kNoLineNumberInfo);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> result;
has_pending_exception = !CallV8HeapFunction(
"GetLineNumber", Utils::OpenHandle(this)).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, 0);
return static_cast<int>(result->Number());
}
int Message::GetStartPosition() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSMessageObject> message =
i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
return message->start_position();
}
int Message::GetEndPosition() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSMessageObject> message =
i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
return message->end_position();
}
int Message::GetStartColumn() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Message::GetStartColumn()", return kNoColumnInfo);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> start_col_obj;
has_pending_exception = !CallV8HeapFunction(
"GetPositionInLine", data_obj).ToHandle(&start_col_obj);
EXCEPTION_BAILOUT_CHECK(isolate, 0);
return static_cast<int>(start_col_obj->Number());
}
int Message::GetEndColumn() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Message::GetEndColumn()", return kNoColumnInfo);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> data_obj = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> start_col_obj;
has_pending_exception = !CallV8HeapFunction(
"GetPositionInLine", data_obj).ToHandle(&start_col_obj);
EXCEPTION_BAILOUT_CHECK(isolate, 0);
i::Handle<i::JSMessageObject> message =
i::Handle<i::JSMessageObject>::cast(data_obj);
int start = message->start_position();
int end = message->end_position();
return static_cast<int>(start_col_obj->Number()) + (end - start);
}
bool Message::IsSharedCrossOrigin() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSMessageObject> message =
i::Handle<i::JSMessageObject>::cast(Utils::OpenHandle(this));
i::Handle<i::JSValue> script =
i::Handle<i::JSValue>::cast(i::Handle<i::Object>(message->script(),
isolate));
return i::Script::cast(script->value())->is_shared_cross_origin();
}
Local<String> Message::GetSourceLine() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Message::GetSourceLine()", return Local<String>());
ENTER_V8(isolate);
EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> result;
has_pending_exception = !CallV8HeapFunction(
"GetSourceLine", Utils::OpenHandle(this)).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::String>());
if (result->IsString()) {
return scope.Escape(Utils::ToLocal(i::Handle<i::String>::cast(result)));
} else {
return Local<String>();
}
}
void Message::PrintCurrentStackTrace(Isolate* isolate, FILE* out) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
ENTER_V8(i_isolate);
i_isolate->PrintCurrentStackTrace(out);
}
// --- S t a c k T r a c e ---
Local<StackFrame> StackTrace::GetFrame(uint32_t index) const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
i::Handle<i::JSArray> self = Utils::OpenHandle(this);
i::Handle<i::Object> obj =
i::Object::GetElement(isolate, self, index).ToHandleChecked();
i::Handle<i::JSObject> jsobj = i::Handle<i::JSObject>::cast(obj);
return scope.Escape(Utils::StackFrameToLocal(jsobj));
}
int StackTrace::GetFrameCount() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
return i::Smi::cast(Utils::OpenHandle(this)->length())->value();
}
Local<Array> StackTrace::AsArray() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
return Utils::ToLocal(Utils::OpenHandle(this));
}
Local<StackTrace> StackTrace::CurrentStackTrace(
Isolate* isolate,
int frame_limit,
StackTraceOptions options) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
ENTER_V8(i_isolate);
// TODO(dcarney): remove when ScriptDebugServer is fixed.
options = static_cast<StackTraceOptions>(
static_cast<int>(options) | kExposeFramesAcrossSecurityOrigins);
i::Handle<i::JSArray> stackTrace =
i_isolate->CaptureCurrentStackTrace(frame_limit, options);
return Utils::StackTraceToLocal(stackTrace);
}
// --- S t a c k F r a m e ---
static int getIntProperty(const StackFrame* f, const char* propertyName,
int defaultValue) {
i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(f);
i::Handle<i::Object> obj =
i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
return obj->IsSmi() ? i::Smi::cast(*obj)->value() : defaultValue;
}
int StackFrame::GetLineNumber() const {
return getIntProperty(this, "lineNumber", Message::kNoLineNumberInfo);
}
int StackFrame::GetColumn() const {
return getIntProperty(this, "column", Message::kNoColumnInfo);
}
int StackFrame::GetScriptId() const {
return getIntProperty(this, "scriptId", Message::kNoScriptIdInfo);
}
static Local<String> getStringProperty(const StackFrame* f,
const char* propertyName) {
i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
ENTER_V8(isolate);
EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
i::Handle<i::JSObject> self = Utils::OpenHandle(f);
i::Handle<i::Object> obj =
i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
return obj->IsString()
? scope.Escape(Local<String>::Cast(Utils::ToLocal(obj)))
: Local<String>();
}
Local<String> StackFrame::GetScriptName() const {
return getStringProperty(this, "scriptName");
}
Local<String> StackFrame::GetScriptNameOrSourceURL() const {
return getStringProperty(this, "scriptNameOrSourceURL");
}
Local<String> StackFrame::GetFunctionName() const {
return getStringProperty(this, "functionName");
}
static bool getBoolProperty(const StackFrame* f, const char* propertyName) {
i::Isolate* isolate = Utils::OpenHandle(f)->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(f);
i::Handle<i::Object> obj =
i::Object::GetProperty(isolate, self, propertyName).ToHandleChecked();
return obj->IsTrue();
}
bool StackFrame::IsEval() const { return getBoolProperty(this, "isEval"); }
bool StackFrame::IsConstructor() const {
return getBoolProperty(this, "isConstructor");
}
// --- J S O N ---
Local<Value> JSON::Parse(Local<String> json_string) {
i::Handle<i::String> string = Utils::OpenHandle(*json_string);
i::Isolate* isolate = string->GetIsolate();
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::String> source = i::String::Flatten(string);
EXCEPTION_PREAMBLE(isolate);
i::MaybeHandle<i::Object> maybe_result =
source->IsSeqOneByteString() ? i::JsonParser<true>::Parse(source)
: i::JsonParser<false>::Parse(source);
i::Handle<i::Object> result;
has_pending_exception = !maybe_result.ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
return Utils::ToLocal(
i::Handle<i::Object>::cast(scope.CloseAndEscape(result)));
}
// --- D a t a ---
bool Value::FullIsUndefined() const {
bool result = Utils::OpenHandle(this)->IsUndefined();
DCHECK_EQ(result, QuickIsUndefined());
return result;
}
bool Value::FullIsNull() const {
bool result = Utils::OpenHandle(this)->IsNull();
DCHECK_EQ(result, QuickIsNull());
return result;
}
bool Value::IsTrue() const {
return Utils::OpenHandle(this)->IsTrue();
}
bool Value::IsFalse() const {
return Utils::OpenHandle(this)->IsFalse();
}
bool Value::IsFunction() const {
return Utils::OpenHandle(this)->IsJSFunction();
}
bool Value::IsName() const {
return Utils::OpenHandle(this)->IsName();
}
bool Value::FullIsString() const {
bool result = Utils::OpenHandle(this)->IsString();
DCHECK_EQ(result, QuickIsString());
return result;
}
bool Value::IsSymbol() const {
return Utils::OpenHandle(this)->IsSymbol();
}
bool Value::IsArray() const {
return Utils::OpenHandle(this)->IsJSArray();
}
bool Value::IsArrayBuffer() const {
return Utils::OpenHandle(this)->IsJSArrayBuffer();
}
bool Value::IsArrayBufferView() const {
return Utils::OpenHandle(this)->IsJSArrayBufferView();
}
bool Value::IsTypedArray() const {
return Utils::OpenHandle(this)->IsJSTypedArray();
}
#define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype, size) \
bool Value::Is##Type##Array() const { \
i::Handle<i::Object> obj = Utils::OpenHandle(this); \
return obj->IsJSTypedArray() && \
i::JSTypedArray::cast(*obj)->type() == kExternal##Type##Array; \
}
TYPED_ARRAYS(VALUE_IS_TYPED_ARRAY)
#undef VALUE_IS_TYPED_ARRAY
bool Value::IsDataView() const {
return Utils::OpenHandle(this)->IsJSDataView();
}
bool Value::IsObject() const {
return Utils::OpenHandle(this)->IsJSObject();
}
bool Value::IsNumber() const {
return Utils::OpenHandle(this)->IsNumber();
}
#define VALUE_IS_SPECIFIC_TYPE(Type, Class) \
bool Value::Is##Type() const { \
i::Handle<i::Object> obj = Utils::OpenHandle(this); \
if (!obj->IsHeapObject()) return false; \
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate(); \
return obj->HasSpecificClassOf(isolate->heap()->Class##_string()); \
}
VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, Arguments)
VALUE_IS_SPECIFIC_TYPE(BooleanObject, Boolean)
VALUE_IS_SPECIFIC_TYPE(NumberObject, Number)
VALUE_IS_SPECIFIC_TYPE(StringObject, String)
VALUE_IS_SPECIFIC_TYPE(SymbolObject, Symbol)
VALUE_IS_SPECIFIC_TYPE(Date, Date)
VALUE_IS_SPECIFIC_TYPE(Map, Map)
VALUE_IS_SPECIFIC_TYPE(Set, Set)
VALUE_IS_SPECIFIC_TYPE(WeakMap, WeakMap)
VALUE_IS_SPECIFIC_TYPE(WeakSet, WeakSet)
#undef VALUE_IS_SPECIFIC_TYPE
bool Value::IsBoolean() const {
return Utils::OpenHandle(this)->IsBoolean();
}
bool Value::IsExternal() const {
return Utils::OpenHandle(this)->IsExternal();
}
bool Value::IsInt32() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) return true;
if (obj->IsNumber()) {
return i::IsInt32Double(obj->Number());
}
return false;
}
bool Value::IsUint32() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) return i::Smi::cast(*obj)->value() >= 0;
if (obj->IsNumber()) {
double value = obj->Number();
return !i::IsMinusZero(value) &&
value >= 0 &&
value <= i::kMaxUInt32 &&
value == i::FastUI2D(i::FastD2UI(value));
}
return false;
}
static bool CheckConstructor(i::Isolate* isolate,
i::Handle<i::JSObject> obj,
const char* class_name) {
i::Handle<i::Object> constr(obj->map()->constructor(), isolate);
if (!constr->IsJSFunction()) return false;
i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(constr);
return func->shared()->native() && constr.is_identical_to(
i::Object::GetProperty(isolate,
isolate->js_builtins_object(),
class_name).ToHandleChecked());
}
bool Value::IsNativeError() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsJSObject()) {
i::Handle<i::JSObject> js_obj(i::JSObject::cast(*obj));
i::Isolate* isolate = js_obj->GetIsolate();
return CheckConstructor(isolate, js_obj, "$Error") ||
CheckConstructor(isolate, js_obj, "$EvalError") ||
CheckConstructor(isolate, js_obj, "$RangeError") ||
CheckConstructor(isolate, js_obj, "$ReferenceError") ||
CheckConstructor(isolate, js_obj, "$SyntaxError") ||
CheckConstructor(isolate, js_obj, "$TypeError") ||
CheckConstructor(isolate, js_obj, "$URIError");
} else {
return false;
}
}
bool Value::IsRegExp() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
return obj->IsJSRegExp();
}
bool Value::IsGeneratorFunction() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (!obj->IsJSFunction()) return false;
i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(obj);
return func->shared()->is_generator();
}
bool Value::IsGeneratorObject() const {
return Utils::OpenHandle(this)->IsJSGeneratorObject();
}
Local<String> Value::ToString() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> str;
if (obj->IsString()) {
str = obj;
} else {
i::Isolate* isolate = i::Isolate::Current();
LOG_API(isolate, "ToString");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToString(
isolate, obj).ToHandle(&str);
EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
}
return ToApiHandle<String>(str);
}
Local<String> Value::ToDetailString() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> str;
if (obj->IsString()) {
str = obj;
} else {
i::Isolate* isolate = i::Isolate::Current();
LOG_API(isolate, "ToDetailString");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToDetailString(
isolate, obj).ToHandle(&str);
EXCEPTION_BAILOUT_CHECK(isolate, Local<String>());
}
return ToApiHandle<String>(str);
}
Local<v8::Object> Value::ToObject() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> val;
if (obj->IsJSObject()) {
val = obj;
} else {
i::Isolate* isolate = i::Isolate::Current();
LOG_API(isolate, "ToObject");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToObject(
isolate, obj).ToHandle(&val);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
}
return ToApiHandle<Object>(val);
}
Local<Boolean> Value::ToBoolean() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsBoolean()) {
return ToApiHandle<Boolean>(obj);
} else {
i::Isolate* isolate = i::Isolate::Current();
LOG_API(isolate, "ToBoolean");
ENTER_V8(isolate);
i::Handle<i::Object> val =
isolate->factory()->ToBoolean(obj->BooleanValue());
return ToApiHandle<Boolean>(val);
}
}
Local<Number> Value::ToNumber() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> num;
if (obj->IsNumber()) {
num = obj;
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "ToNumber");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToNumber(
isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Number>());
}
return ToApiHandle<Number>(num);
}
Local<Integer> Value::ToInteger() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> num;
if (obj->IsSmi()) {
num = obj;
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "ToInteger");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToInteger(
isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Integer>());
}
return ToApiHandle<Integer>(num);
}
void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
Utils::ApiCheck(isolate != NULL &&
isolate->IsInitialized() &&
!isolate->IsDead(),
"v8::internal::Internals::CheckInitialized()",
"Isolate is not initialized or V8 has died");
}
void External::CheckCast(v8::Value* that) {
Utils::ApiCheck(Utils::OpenHandle(that)->IsExternal(),
"v8::External::Cast()",
"Could not convert to external");
}
void v8::Object::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSObject(),
"v8::Object::Cast()",
"Could not convert to object");
}
void v8::Function::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSFunction(),
"v8::Function::Cast()",
"Could not convert to function");
}
void v8::Name::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsName(),
"v8::Name::Cast()",
"Could not convert to name");
}
void v8::String::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsString(),
"v8::String::Cast()",
"Could not convert to string");
}
void v8::Symbol::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsSymbol(),
"v8::Symbol::Cast()",
"Could not convert to symbol");
}
void v8::Number::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsNumber(),
"v8::Number::Cast()",
"Could not convert to number");
}
void v8::Integer::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsNumber(),
"v8::Integer::Cast()",
"Could not convert to number");
}
void v8::Array::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSArray(),
"v8::Array::Cast()",
"Could not convert to array");
}
void v8::Promise::CheckCast(Value* that) {
Utils::ApiCheck(that->IsPromise(),
"v8::Promise::Cast()",
"Could not convert to promise");
}
void v8::Promise::Resolver::CheckCast(Value* that) {
Utils::ApiCheck(that->IsPromise(),
"v8::Promise::Resolver::Cast()",
"Could not convert to promise resolver");
}
void v8::ArrayBuffer::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSArrayBuffer(),
"v8::ArrayBuffer::Cast()",
"Could not convert to ArrayBuffer");
}
void v8::ArrayBufferView::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSArrayBufferView(),
"v8::ArrayBufferView::Cast()",
"Could not convert to ArrayBufferView");
}
void v8::TypedArray::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSTypedArray(),
"v8::TypedArray::Cast()",
"Could not convert to TypedArray");
}
#define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype, size) \
void v8::Type##Array::CheckCast(Value* that) { \
i::Handle<i::Object> obj = Utils::OpenHandle(that); \
Utils::ApiCheck(obj->IsJSTypedArray() && \
i::JSTypedArray::cast(*obj)->type() == \
kExternal##Type##Array, \
"v8::" #Type "Array::Cast()", \
"Could not convert to " #Type "Array"); \
}
TYPED_ARRAYS(CHECK_TYPED_ARRAY_CAST)
#undef CHECK_TYPED_ARRAY_CAST
void v8::DataView::CheckCast(Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSDataView(),
"v8::DataView::Cast()",
"Could not convert to DataView");
}
void v8::Date::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
i::Isolate* isolate = NULL;
if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
Utils::ApiCheck(isolate != NULL &&
obj->HasSpecificClassOf(isolate->heap()->Date_string()),
"v8::Date::Cast()",
"Could not convert to date");
}
void v8::StringObject::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
i::Isolate* isolate = NULL;
if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
Utils::ApiCheck(isolate != NULL &&
obj->HasSpecificClassOf(isolate->heap()->String_string()),
"v8::StringObject::Cast()",
"Could not convert to StringObject");
}
void v8::SymbolObject::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
i::Isolate* isolate = NULL;
if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
Utils::ApiCheck(isolate != NULL &&
obj->HasSpecificClassOf(isolate->heap()->Symbol_string()),
"v8::SymbolObject::Cast()",
"Could not convert to SymbolObject");
}
void v8::NumberObject::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
i::Isolate* isolate = NULL;
if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
Utils::ApiCheck(isolate != NULL &&
obj->HasSpecificClassOf(isolate->heap()->Number_string()),
"v8::NumberObject::Cast()",
"Could not convert to NumberObject");
}
void v8::BooleanObject::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
i::Isolate* isolate = NULL;
if (obj->IsHeapObject()) isolate = i::HeapObject::cast(*obj)->GetIsolate();
Utils::ApiCheck(isolate != NULL &&
obj->HasSpecificClassOf(isolate->heap()->Boolean_string()),
"v8::BooleanObject::Cast()",
"Could not convert to BooleanObject");
}
void v8::RegExp::CheckCast(v8::Value* that) {
i::Handle<i::Object> obj = Utils::OpenHandle(that);
Utils::ApiCheck(obj->IsJSRegExp(),
"v8::RegExp::Cast()",
"Could not convert to regular expression");
}
bool Value::BooleanValue() const {
return Utils::OpenHandle(this)->BooleanValue();
}
double Value::NumberValue() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> num;
if (obj->IsNumber()) {
num = obj;
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "NumberValue");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToNumber(
isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, base::OS::nan_value());
}
return num->Number();
}
int64_t Value::IntegerValue() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> num;
if (obj->IsNumber()) {
num = obj;
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "IntegerValue");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToInteger(
isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, 0);
}
if (num->IsSmi()) {
return i::Smi::cast(*num)->value();
} else {
return static_cast<int64_t>(num->Number());
}
}
Local<Int32> Value::ToInt32() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> num;
if (obj->IsSmi()) {
num = obj;
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "ToInt32");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToInt32(isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Int32>());
}
return ToApiHandle<Int32>(num);
}
Local<Uint32> Value::ToUint32() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::Object> num;
if (obj->IsSmi()) {
num = obj;
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "ToUInt32");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToUint32(
isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
}
return ToApiHandle<Uint32>(num);
}
Local<Uint32> Value::ToArrayIndex() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) {
if (i::Smi::cast(*obj)->value() >= 0) return Utils::Uint32ToLocal(obj);
return Local<Uint32>();
}
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "ToArrayIndex");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> string_obj;
has_pending_exception = !i::Execution::ToString(
isolate, obj).ToHandle(&string_obj);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Uint32>());
i::Handle<i::String> str = i::Handle<i::String>::cast(string_obj);
uint32_t index;
if (str->AsArrayIndex(&index)) {
i::Handle<i::Object> value;
if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
value = i::Handle<i::Object>(i::Smi::FromInt(index), isolate);
} else {
value = isolate->factory()->NewNumber(index);
}
return Utils::Uint32ToLocal(value);
}
return Local<Uint32>();
}
int32_t Value::Int32Value() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) {
return i::Smi::cast(*obj)->value();
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "Int32Value (slow)");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> num;
has_pending_exception = !i::Execution::ToInt32(isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, 0);
if (num->IsSmi()) {
return i::Smi::cast(*num)->value();
} else {
return static_cast<int32_t>(num->Number());
}
}
}
bool Value::Equals(Handle<Value> that) const {
i::Isolate* isolate = i::Isolate::Current();
i::Handle<i::Object> obj = Utils::OpenHandle(this, true);
if (!Utils::ApiCheck(!obj.is_null() && !that.IsEmpty(),
"v8::Value::Equals()",
"Reading from empty handle")) {
return false;
}
LOG_API(isolate, "Equals");
ENTER_V8(isolate);
i::Handle<i::Object> other = Utils::OpenHandle(*that);
// If both obj and other are JSObjects, we'd better compare by identity
// immediately when going into JS builtin. The reason is Invoke
// would overwrite global object receiver with global proxy.
if (obj->IsJSObject() && other->IsJSObject()) {
return *obj == *other;
}
i::Handle<i::Object> args[] = { other };
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> result;
has_pending_exception = !CallV8HeapFunction(
"EQUALS", obj, arraysize(args), args).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, false);
return *result == i::Smi::FromInt(i::EQUAL);
}
bool Value::StrictEquals(Handle<Value> that) const {
i::Isolate* isolate = i::Isolate::Current();
i::Handle<i::Object> obj = Utils::OpenHandle(this, true);
if (!Utils::ApiCheck(!obj.is_null() && !that.IsEmpty(),
"v8::Value::StrictEquals()",
"Reading from empty handle")) {
return false;
}
LOG_API(isolate, "StrictEquals");
i::Handle<i::Object> other = Utils::OpenHandle(*that);
// Must check HeapNumber first, since NaN !== NaN.
if (obj->IsHeapNumber()) {
if (!other->IsNumber()) return false;
double x = obj->Number();
double y = other->Number();
// Must check explicitly for NaN:s on Windows, but -0 works fine.
return x == y && !std::isnan(x) && !std::isnan(y);
} else if (*obj == *other) { // Also covers Booleans.
return true;
} else if (obj->IsSmi()) {
return other->IsNumber() && obj->Number() == other->Number();
} else if (obj->IsString()) {
return other->IsString() &&
i::String::Equals(i::Handle<i::String>::cast(obj),
i::Handle<i::String>::cast(other));
} else if (obj->IsUndefined() || obj->IsUndetectableObject()) {
return other->IsUndefined() || other->IsUndetectableObject();
} else {
return false;
}
}
bool Value::SameValue(Handle<Value> that) const {
i::Handle<i::Object> obj = Utils::OpenHandle(this, true);
if (!Utils::ApiCheck(!obj.is_null() && !that.IsEmpty(),
"v8::Value::SameValue()",
"Reading from empty handle")) {
return false;
}
i::Handle<i::Object> other = Utils::OpenHandle(*that);
return obj->SameValue(*other);
}
uint32_t Value::Uint32Value() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) {
return i::Smi::cast(*obj)->value();
} else {
i::Isolate* isolate = i::HeapObject::cast(*obj)->GetIsolate();
LOG_API(isolate, "Uint32Value");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> num;
has_pending_exception = !i::Execution::ToUint32(
isolate, obj).ToHandle(&num);
EXCEPTION_BAILOUT_CHECK(isolate, 0);
if (num->IsSmi()) {
return i::Smi::cast(*num)->value();
} else {
return static_cast<uint32_t>(num->Number());
}
}
}
bool v8::Object::Set(v8::Handle<Value> key, v8::Handle<Value> value) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::Set()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::Object> self = Utils::OpenHandle(this);
i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception =
i::Runtime::SetObjectProperty(isolate, self, key_obj, value_obj,
i::SLOPPY).is_null();
EXCEPTION_BAILOUT_CHECK(isolate, false);
return true;
}
bool v8::Object::Set(uint32_t index, v8::Handle<Value> value) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::Set()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = i::JSObject::SetElement(
self, index, value_obj, NONE, i::SLOPPY).is_null();
EXCEPTION_BAILOUT_CHECK(isolate, false);
return true;
}
bool v8::Object::ForceSet(v8::Handle<Value> key,
v8::Handle<Value> value,
v8::PropertyAttribute attribs) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::ForceSet()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = i::Runtime::DefineObjectProperty(
self,
key_obj,
value_obj,
static_cast<PropertyAttributes>(attribs)).is_null();
EXCEPTION_BAILOUT_CHECK(isolate, false);
return true;
}
bool v8::Object::SetPrivate(v8::Handle<Private> key, v8::Handle<Value> value) {
return ForceSet(v8::Handle<Value>(reinterpret_cast<Value*>(*key)),
value, DontEnum);
}
bool v8::Object::ForceDelete(v8::Handle<Value> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::ForceDelete()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
// When deleting a property on the global object using ForceDelete
// deoptimize all functions as optimized code does not check for the hole
// value with DontDelete properties. We have to deoptimize all contexts
// because of possible cross-context inlined functions.
if (self->IsJSGlobalProxy() || self->IsGlobalObject()) {
i::Deoptimizer::DeoptimizeAll(isolate);
}
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> obj;
has_pending_exception = !i::Runtime::DeleteObjectProperty(
isolate, self, key_obj, i::JSReceiver::FORCE_DELETION).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(isolate, false);
return obj->IsTrue();
}
Local<Value> v8::Object::Get(v8::Handle<Value> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::Object> self = Utils::OpenHandle(this);
i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> result;
has_pending_exception =
!i::Runtime::GetObjectProperty(isolate, self, key_obj).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
return Utils::ToLocal(result);
}
Local<Value> v8::Object::Get(uint32_t index) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::Get()", return Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> result;
has_pending_exception =
!i::Object::GetElement(isolate, self, index).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
return Utils::ToLocal(result);
}
Local<Value> v8::Object::GetPrivate(v8::Handle<Private> key) {
return Get(v8::Handle<Value>(reinterpret_cast<Value*>(*key)));
}
PropertyAttribute v8::Object::GetPropertyAttributes(v8::Handle<Value> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetPropertyAttributes()",
return static_cast<PropertyAttribute>(NONE));
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
if (!key_obj->IsName()) {
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !i::Execution::ToString(
isolate, key_obj).ToHandle(&key_obj);
EXCEPTION_BAILOUT_CHECK(isolate, static_cast<PropertyAttribute>(NONE));
}
i::Handle<i::Name> key_name = i::Handle<i::Name>::cast(key_obj);
EXCEPTION_PREAMBLE(isolate);
Maybe<PropertyAttributes> result =
i::JSReceiver::GetPropertyAttributes(self, key_name);
has_pending_exception = !result.has_value;
EXCEPTION_BAILOUT_CHECK(isolate, static_cast<PropertyAttribute>(NONE));
if (result.value == ABSENT) return static_cast<PropertyAttribute>(NONE);
return static_cast<PropertyAttribute>(result.value);
}
Local<Value> v8::Object::GetOwnPropertyDescriptor(Local<String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetOwnPropertyDescriptor()",
return Local<Value>());
ENTER_V8(isolate);
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
i::Handle<i::Name> key_name = Utils::OpenHandle(*key);
i::Handle<i::Object> args[] = { obj, key_name };
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> result;
has_pending_exception = !CallV8HeapFunction(
"ObjectGetOwnPropertyDescriptor",
isolate->factory()->undefined_value(),
arraysize(args),
args).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
return Utils::ToLocal(result);
}
Local<Value> v8::Object::GetPrototype() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetPrototype()", return Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::Object> self = Utils::OpenHandle(this);
i::PrototypeIterator iter(isolate, self);
return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
}
bool v8::Object::SetPrototype(Handle<Value> value) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::SetPrototype()", return false);
ENTER_V8(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
// We do not allow exceptions thrown while setting the prototype
// to propagate outside.
TryCatch try_catch;
EXCEPTION_PREAMBLE(isolate);
i::MaybeHandle<i::Object> result =
i::JSObject::SetPrototype(self, value_obj, false);
has_pending_exception = result.is_null();
EXCEPTION_BAILOUT_CHECK(isolate, false);
return true;
}
Local<Object> v8::Object::FindInstanceInPrototypeChain(
v8::Handle<FunctionTemplate> tmpl) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate,
"v8::Object::FindInstanceInPrototypeChain()",
return Local<v8::Object>());
ENTER_V8(isolate);
i::PrototypeIterator iter(isolate, *Utils::OpenHandle(this),
i::PrototypeIterator::START_AT_RECEIVER);
i::FunctionTemplateInfo* tmpl_info = *Utils::OpenHandle(*tmpl);
while (!tmpl_info->IsTemplateFor(iter.GetCurrent())) {
iter.Advance();
if (iter.IsAtEnd()) {
return Local<Object>();
}
}
return Utils::ToLocal(
i::handle(i::JSObject::cast(iter.GetCurrent()), isolate));
}
Local<Array> v8::Object::GetPropertyNames() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetPropertyNames()",
return Local<v8::Array>());
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::FixedArray> value;
has_pending_exception = !i::JSReceiver::GetKeys(
self, i::JSReceiver::INCLUDE_PROTOS).ToHandle(&value);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Array>());
// Because we use caching to speed up enumeration it is important
// to never change the result of the basic enumeration function so
// we clone the result.
i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
i::Handle<i::JSArray> result =
isolate->factory()->NewJSArrayWithElements(elms);
return Utils::ToLocal(scope.CloseAndEscape(result));
}
Local<Array> v8::Object::GetOwnPropertyNames() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetOwnPropertyNames()",
return Local<v8::Array>());
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::FixedArray> value;
has_pending_exception = !i::JSReceiver::GetKeys(
self, i::JSReceiver::OWN_ONLY).ToHandle(&value);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Array>());
// Because we use caching to speed up enumeration it is important
// to never change the result of the basic enumeration function so
// we clone the result.
i::Handle<i::FixedArray> elms = isolate->factory()->CopyFixedArray(value);
i::Handle<i::JSArray> result =
isolate->factory()->NewJSArrayWithElements(elms);
return Utils::ToLocal(scope.CloseAndEscape(result));
}
Local<String> v8::Object::ObjectProtoToString() {
i::Isolate* i_isolate = Utils::OpenHandle(this)->GetIsolate();
Isolate* isolate = reinterpret_cast<Isolate*>(i_isolate);
ON_BAILOUT(i_isolate, "v8::Object::ObjectProtoToString()",
return Local<v8::String>());
ENTER_V8(i_isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::Object> name(self->class_name(), i_isolate);
// Native implementation of Object.prototype.toString (v8natives.js):
// var c = %_ClassOf(this);
// if (c === 'Arguments') c = 'Object';
// return "[object " + c + "]";
if (!name->IsString()) {
return v8::String::NewFromUtf8(isolate, "[object ]");
} else {
i::Handle<i::String> class_name = i::Handle<i::String>::cast(name);
if (i::String::Equals(class_name,
i_isolate->factory()->Arguments_string())) {
return v8::String::NewFromUtf8(isolate, "[object Object]");
} else {
const char* prefix = "[object ";
Local<String> str = Utils::ToLocal(class_name);
const char* postfix = "]";
int prefix_len = i::StrLength(prefix);
int str_len = str->Utf8Length();
int postfix_len = i::StrLength(postfix);
int buf_len = prefix_len + str_len + postfix_len;
i::ScopedVector<char> buf(buf_len);
// Write prefix.
char* ptr = buf.start();
i::MemCopy(ptr, prefix, prefix_len * v8::internal::kCharSize);
ptr += prefix_len;
// Write real content.
str->WriteUtf8(ptr, str_len);
ptr += str_len;
// Write postfix.
i::MemCopy(ptr, postfix, postfix_len * v8::internal::kCharSize);
// Copy the buffer into a heap-allocated string and return it.
Local<String> result = v8::String::NewFromUtf8(
isolate, buf.start(), String::kNormalString, buf_len);
return result;
}
}
}
Local<String> v8::Object::GetConstructorName() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetConstructorName()",
return Local<v8::String>());
ENTER_V8(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::String> name(self->constructor_name());
return Utils::ToLocal(name);
}
bool v8::Object::Delete(v8::Handle<Value> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::Delete()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> obj;
has_pending_exception = !i::Runtime::DeleteObjectProperty(
isolate, self, key_obj, i::JSReceiver::NORMAL_DELETION).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(isolate, false);
return obj->IsTrue();
}
bool v8::Object::DeletePrivate(v8::Handle<Private> key) {
return Delete(v8::Handle<Value>(reinterpret_cast<Value*>(*key)));
}
bool v8::Object::Has(v8::Handle<Value> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::Has()", return false);
ENTER_V8(isolate);
i::Handle<i::JSReceiver> self = Utils::OpenHandle(this);
i::Handle<i::Object> key_obj = Utils::OpenHandle(*key);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> obj;
has_pending_exception = !i::Runtime::HasObjectProperty(
isolate, self, key_obj).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(isolate, false);
return obj->IsTrue();
}
bool v8::Object::HasPrivate(v8::Handle<Private> key) {
// TODO(rossberg): this should use HasOwnProperty, but we'd need to
// generalise that to a (noy yet existant) Name argument first.
return Has(v8::Handle<Value>(reinterpret_cast<Value*>(*key)));
}
bool v8::Object::Delete(uint32_t index) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::DeleteProperty()",
return false);
ENTER_V8(isolate);
HandleScope scope(reinterpret_cast<Isolate*>(isolate));
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> obj;
has_pending_exception =
!i::JSReceiver::DeleteElement(self, index).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(isolate, false);
return obj->IsTrue();
}
bool v8::Object::Has(uint32_t index) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::HasProperty()", return false);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
Maybe<bool> maybe = i::JSReceiver::HasElement(self, index);
has_pending_exception = !maybe.has_value;
EXCEPTION_BAILOUT_CHECK(isolate, false);
return maybe.value;
}
template<typename Getter, typename Setter, typename Data>
static inline bool ObjectSetAccessor(Object* obj,
Handle<Name> name,
Getter getter,
Setter setter,
Data data,
AccessControl settings,
PropertyAttribute attributes) {
i::Isolate* isolate = Utils::OpenHandle(obj)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::SetAccessor()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
v8::Handle<AccessorSignature> signature;
i::Handle<i::AccessorInfo> info = MakeAccessorInfo(
name, getter, setter, data, settings, attributes, signature);
if (info.is_null()) return false;
bool fast = Utils::OpenHandle(obj)->HasFastProperties();
i::Handle<i::Object> result;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, result,
i::JSObject::SetAccessor(Utils::OpenHandle(obj), info),
false);
if (result->IsUndefined()) return false;
if (fast) i::JSObject::MigrateSlowToFast(Utils::OpenHandle(obj), 0);
return true;
}
bool Object::SetAccessor(Handle<String> name,
AccessorGetterCallback getter,
AccessorSetterCallback setter,
v8::Handle<Value> data,
AccessControl settings,
PropertyAttribute attributes) {
return ObjectSetAccessor(
this, name, getter, setter, data, settings, attributes);
}
bool Object::SetAccessor(Handle<Name> name,
AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter,
v8::Handle<Value> data,
AccessControl settings,
PropertyAttribute attributes) {
return ObjectSetAccessor(
this, name, getter, setter, data, settings, attributes);
}
bool Object::SetDeclaredAccessor(Local<Name> name,
Local<DeclaredAccessorDescriptor> descriptor,
PropertyAttribute attributes,
AccessControl settings) {
void* null = NULL;
return ObjectSetAccessor(
this, name, descriptor, null, null, settings, attributes);
}
void Object::SetAccessorProperty(Local<Name> name,
Local<Function> getter,
Handle<Function> setter,
PropertyAttribute attribute,
AccessControl settings) {
// TODO(verwaest): Remove |settings|.
DCHECK_EQ(v8::DEFAULT, settings);
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::SetAccessorProperty()", return);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::Object> getter_i = v8::Utils::OpenHandle(*getter);
i::Handle<i::Object> setter_i = v8::Utils::OpenHandle(*setter, true);
if (setter_i.is_null()) setter_i = isolate->factory()->null_value();
i::JSObject::DefineAccessor(v8::Utils::OpenHandle(this),
v8::Utils::OpenHandle(*name),
getter_i,
setter_i,
static_cast<PropertyAttributes>(attribute));
}
bool v8::Object::HasOwnProperty(Handle<String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::HasOwnProperty()",
return false);
EXCEPTION_PREAMBLE(isolate);
Maybe<bool> maybe = i::JSReceiver::HasOwnProperty(Utils::OpenHandle(this),
Utils::OpenHandle(*key));
has_pending_exception = !maybe.has_value;
EXCEPTION_BAILOUT_CHECK(isolate, false);
return maybe.value;
}
bool v8::Object::HasRealNamedProperty(Handle<String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::HasRealNamedProperty()",
return false);
EXCEPTION_PREAMBLE(isolate);
Maybe<bool> maybe = i::JSObject::HasRealNamedProperty(
Utils::OpenHandle(this), Utils::OpenHandle(*key));
has_pending_exception = !maybe.has_value;
EXCEPTION_BAILOUT_CHECK(isolate, false);
return maybe.value;
}
bool v8::Object::HasRealIndexedProperty(uint32_t index) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::HasRealIndexedProperty()",
return false);
EXCEPTION_PREAMBLE(isolate);
Maybe<bool> maybe =
i::JSObject::HasRealElementProperty(Utils::OpenHandle(this), index);
has_pending_exception = !maybe.has_value;
EXCEPTION_BAILOUT_CHECK(isolate, false);
return maybe.value;
}
bool v8::Object::HasRealNamedCallbackProperty(Handle<String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate,
"v8::Object::HasRealNamedCallbackProperty()",
return false);
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
Maybe<bool> maybe = i::JSObject::HasRealNamedCallbackProperty(
Utils::OpenHandle(this), Utils::OpenHandle(*key));
has_pending_exception = !maybe.has_value;
EXCEPTION_BAILOUT_CHECK(isolate, false);
return maybe.value;
}
bool v8::Object::HasNamedLookupInterceptor() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::HasNamedLookupInterceptor()",
return false);
return Utils::OpenHandle(this)->HasNamedInterceptor();
}
bool v8::Object::HasIndexedLookupInterceptor() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::HasIndexedLookupInterceptor()",
return false);
return Utils::OpenHandle(this)->HasIndexedInterceptor();
}
static Local<Value> GetPropertyByLookup(i::LookupIterator* it) {
// If the property being looked up is a callback, it can throw an exception.
EXCEPTION_PREAMBLE(it->isolate());
i::Handle<i::Object> result;
has_pending_exception = !i::Object::GetProperty(it).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(it->isolate(), Local<Value>());
if (it->IsFound()) return Utils::ToLocal(result);
return Local<Value>();
}
Local<Value> v8::Object::GetRealNamedPropertyInPrototypeChain(
Handle<String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate,
"v8::Object::GetRealNamedPropertyInPrototypeChain()",
return Local<Value>());
ENTER_V8(isolate);
i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
i::PrototypeIterator iter(isolate, self_obj);
if (iter.IsAtEnd()) return Local<Value>();
i::Handle<i::Object> proto = i::PrototypeIterator::GetCurrent(iter);
i::LookupIterator it(self_obj, key_obj, i::Handle<i::JSReceiver>::cast(proto),
i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
return GetPropertyByLookup(&it);
}
Local<Value> v8::Object::GetRealNamedProperty(Handle<String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetRealNamedProperty()",
return Local<Value>());
ENTER_V8(isolate);
i::Handle<i::JSObject> self_obj = Utils::OpenHandle(this);
i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
i::LookupIterator it(self_obj, key_obj,
i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
return GetPropertyByLookup(&it);
}
// Turns on access checks by copying the map and setting the check flag.
// Because the object gets a new map, existing inline cache caching
// the old map of this object will fail.
void v8::Object::TurnOnAccessCheck() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::TurnOnAccessCheck()", return);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
// When turning on access checks for a global object deoptimize all functions
// as optimized code does not always handle access checks.
i::Deoptimizer::DeoptimizeGlobalObject(*obj);
i::Handle<i::Map> new_map = i::Map::Copy(i::Handle<i::Map>(obj->map()));
new_map->set_is_access_check_needed(true);
i::JSObject::MigrateToMap(obj, new_map);
}
bool v8::Object::IsDirty() {
return Utils::OpenHandle(this)->IsDirty();
}
Local<v8::Object> v8::Object::Clone() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::Clone()", return Local<Object>());
ENTER_V8(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::JSObject> result = isolate->factory()->CopyJSObject(self);
has_pending_exception = result.is_null();
EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
return Utils::ToLocal(result);
}
Local<v8::Context> v8::Object::CreationContext() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate,
"v8::Object::CreationContext()", return Local<v8::Context>());
ENTER_V8(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Context* context = self->GetCreationContext();
return Utils::ToLocal(i::Handle<i::Context>(context));
}
int v8::Object::GetIdentityHash() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetIdentityHash()", return 0);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
return i::JSReceiver::GetOrCreateIdentityHash(self)->value();
}
bool v8::Object::SetHiddenValue(v8::Handle<v8::String> key,
v8::Handle<v8::Value> value) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::SetHiddenValue()", return false);
if (value.IsEmpty()) return DeleteHiddenValue(key);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
i::Handle<i::String> key_string =
isolate->factory()->InternalizeString(key_obj);
i::Handle<i::Object> value_obj = Utils::OpenHandle(*value);
i::Handle<i::Object> result =
i::JSObject::SetHiddenProperty(self, key_string, value_obj);
return *result == *self;
}
v8::Local<v8::Value> v8::Object::GetHiddenValue(v8::Handle<v8::String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::GetHiddenValue()",
return Local<v8::Value>());
ENTER_V8(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
i::Handle<i::String> key_string =
isolate->factory()->InternalizeString(key_obj);
i::Handle<i::Object> result(self->GetHiddenProperty(key_string), isolate);
if (result->IsTheHole()) return v8::Local<v8::Value>();
return Utils::ToLocal(result);
}
bool v8::Object::DeleteHiddenValue(v8::Handle<v8::String> key) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::DeleteHiddenValue()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
i::Handle<i::String> key_obj = Utils::OpenHandle(*key);
i::Handle<i::String> key_string =
isolate->factory()->InternalizeString(key_obj);
i::JSObject::DeleteHiddenProperty(self, key_string);
return true;
}
namespace {
static i::ElementsKind GetElementsKindFromExternalArrayType(
ExternalArrayType array_type) {
switch (array_type) {
#define ARRAY_TYPE_TO_ELEMENTS_KIND(Type, type, TYPE, ctype, size) \
case kExternal##Type##Array: \
return i::EXTERNAL_##TYPE##_ELEMENTS;
TYPED_ARRAYS(ARRAY_TYPE_TO_ELEMENTS_KIND)
#undef ARRAY_TYPE_TO_ELEMENTS_KIND
}
UNREACHABLE();
return i::DICTIONARY_ELEMENTS;
}
void PrepareExternalArrayElements(i::Handle<i::JSObject> object,
void* data,
ExternalArrayType array_type,
int length) {
i::Isolate* isolate = object->GetIsolate();
i::Handle<i::ExternalArray> array =
isolate->factory()->NewExternalArray(length, array_type, data);
i::Handle<i::Map> external_array_map =
i::JSObject::GetElementsTransitionMap(
object,
GetElementsKindFromExternalArrayType(array_type));
i::JSObject::SetMapAndElements(object, external_array_map, array);
}
} // namespace
void v8::Object::SetIndexedPropertiesToPixelData(uint8_t* data, int length) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::SetElementsToPixelData()", return);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
if (!Utils::ApiCheck(length >= 0 &&
length <= i::ExternalUint8ClampedArray::kMaxLength,
"v8::Object::SetIndexedPropertiesToPixelData()",
"length exceeds max acceptable value")) {
return;
}
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
if (!Utils::ApiCheck(!self->IsJSArray(),
"v8::Object::SetIndexedPropertiesToPixelData()",
"JSArray is not supported")) {
return;
}
PrepareExternalArrayElements(self, data, kExternalUint8ClampedArray, length);
}
bool v8::Object::HasIndexedPropertiesInPixelData() {
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
ON_BAILOUT(self->GetIsolate(), "v8::HasIndexedPropertiesInPixelData()",
return false);
return self->HasExternalUint8ClampedElements();
}
uint8_t* v8::Object::GetIndexedPropertiesPixelData() {
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelData()",
return NULL);
if (self->HasExternalUint8ClampedElements()) {
return i::ExternalUint8ClampedArray::cast(self->elements())->
external_uint8_clamped_pointer();
} else {
return NULL;
}
}
int v8::Object::GetIndexedPropertiesPixelDataLength() {
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
ON_BAILOUT(self->GetIsolate(), "v8::GetIndexedPropertiesPixelDataLength()",
return -1);
if (self->HasExternalUint8ClampedElements()) {
return i::ExternalUint8ClampedArray::cast(self->elements())->length();
} else {
return -1;
}
}
void v8::Object::SetIndexedPropertiesToExternalArrayData(
void* data,
ExternalArrayType array_type,
int length) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::SetIndexedPropertiesToExternalArrayData()", return);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
if (!Utils::ApiCheck(length >= 0 && length <= i::ExternalArray::kMaxLength,
"v8::Object::SetIndexedPropertiesToExternalArrayData()",
"length exceeds max acceptable value")) {
return;
}
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
if (!Utils::ApiCheck(!self->IsJSArray(),
"v8::Object::SetIndexedPropertiesToExternalArrayData()",
"JSArray is not supported")) {
return;
}
PrepareExternalArrayElements(self, data, array_type, length);
}
bool v8::Object::HasIndexedPropertiesInExternalArrayData() {
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
ON_BAILOUT(self->GetIsolate(),
"v8::HasIndexedPropertiesInExternalArrayData()",
return false);
return self->HasExternalArrayElements();
}
void* v8::Object::GetIndexedPropertiesExternalArrayData() {
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
ON_BAILOUT(self->GetIsolate(),
"v8::GetIndexedPropertiesExternalArrayData()",
return NULL);
if (self->HasExternalArrayElements()) {
return i::ExternalArray::cast(self->elements())->external_pointer();
} else {
return NULL;
}
}
ExternalArrayType v8::Object::GetIndexedPropertiesExternalArrayDataType() {
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
ON_BAILOUT(self->GetIsolate(),
"v8::GetIndexedPropertiesExternalArrayDataType()",
return static_cast<ExternalArrayType>(-1));
switch (self->elements()->map()->instance_type()) {
#define INSTANCE_TYPE_TO_ARRAY_TYPE(Type, type, TYPE, ctype, size) \
case i::EXTERNAL_##TYPE##_ARRAY_TYPE: \
return kExternal##Type##Array;
TYPED_ARRAYS(INSTANCE_TYPE_TO_ARRAY_TYPE)
#undef INSTANCE_TYPE_TO_ARRAY_TYPE
default:
return static_cast<ExternalArrayType>(-1);
}
}
int v8::Object::GetIndexedPropertiesExternalArrayDataLength() {
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
ON_BAILOUT(self->GetIsolate(),
"v8::GetIndexedPropertiesExternalArrayDataLength()",
return 0);
if (self->HasExternalArrayElements()) {
return i::ExternalArray::cast(self->elements())->length();
} else {
return -1;
}
}
bool v8::Object::IsCallable() {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::IsCallable()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
return obj->IsCallable();
}
Local<v8::Value> Object::CallAsFunction(v8::Handle<v8::Value> recv,
int argc,
v8::Handle<v8::Value> argv[]) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::CallAsFunction()",
return Local<v8::Value>());
LOG_API(isolate, "Object::CallAsFunction");
ENTER_V8(isolate);
i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>();
if (obj->IsJSFunction()) {
fun = i::Handle<i::JSFunction>::cast(obj);
} else {
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> delegate;
has_pending_exception = !i::Execution::TryGetFunctionDelegate(
isolate, obj).ToHandle(&delegate);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
fun = i::Handle<i::JSFunction>::cast(delegate);
recv_obj = obj;
}
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> returned;
has_pending_exception = !i::Execution::Call(
isolate, fun, recv_obj, argc, args, true).ToHandle(&returned);
EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, Local<Value>());
return Utils::ToLocal(scope.CloseAndEscape(returned));
}
Local<v8::Value> Object::CallAsConstructor(int argc,
v8::Handle<v8::Value> argv[]) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Object::CallAsConstructor()",
return Local<v8::Object>());
LOG_API(isolate, "Object::CallAsConstructor");
ENTER_V8(isolate);
i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
if (obj->IsJSFunction()) {
i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(obj);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> returned;
has_pending_exception = !i::Execution::New(
fun, argc, args).ToHandle(&returned);
EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, Local<v8::Object>());
return Utils::ToLocal(scope.CloseAndEscape(
i::Handle<i::JSObject>::cast(returned)));
}
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> delegate;
has_pending_exception = !i::Execution::TryGetConstructorDelegate(
isolate, obj).ToHandle(&delegate);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
if (!delegate->IsUndefined()) {
i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(delegate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> returned;
has_pending_exception = !i::Execution::Call(
isolate, fun, obj, argc, args).ToHandle(&returned);
EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, Local<v8::Object>());
DCHECK(!delegate->IsUndefined());
return Utils::ToLocal(scope.CloseAndEscape(returned));
}
return Local<v8::Object>();
}
Local<Function> Function::New(Isolate* v8_isolate,
FunctionCallback callback,
Local<Value> data,
int length) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
LOG_API(isolate, "Function::New");
ENTER_V8(isolate);
return FunctionTemplateNew(
isolate, callback, data, Local<Signature>(), length, true)->
GetFunction();
}
Local<v8::Object> Function::NewInstance() const {
return NewInstance(0, NULL);
}
Local<v8::Object> Function::NewInstance(int argc,
v8::Handle<v8::Value> argv[]) const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Function::NewInstance()",
return Local<v8::Object>());
LOG_API(isolate, "Function::NewInstance");
ENTER_V8(isolate);
i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
i::Handle<i::JSFunction> function = Utils::OpenHandle(this);
STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> returned;
has_pending_exception = !i::Execution::New(
function, argc, args).ToHandle(&returned);
EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, Local<v8::Object>());
return scope.Escape(Utils::ToLocal(i::Handle<i::JSObject>::cast(returned)));
}
Local<v8::Value> Function::Call(v8::Handle<v8::Value> recv, int argc,
v8::Handle<v8::Value> argv[]) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Function::Call()", return Local<v8::Value>());
LOG_API(isolate, "Function::Call");
ENTER_V8(isolate);
i::TimerEventScope<i::TimerEventExecute> timer_scope(isolate);
i::HandleScope scope(isolate);
i::Handle<i::JSFunction> fun = Utils::OpenHandle(this);
i::Handle<i::Object> recv_obj = Utils::OpenHandle(*recv);
STATIC_ASSERT(sizeof(v8::Handle<v8::Value>) == sizeof(i::Object**));
i::Handle<i::Object>* args = reinterpret_cast<i::Handle<i::Object>*>(argv);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> returned;
has_pending_exception = !i::Execution::Call(
isolate, fun, recv_obj, argc, args, true).ToHandle(&returned);
EXCEPTION_BAILOUT_CHECK_DO_CALLBACK(isolate, Local<Object>());
return Utils::ToLocal(scope.CloseAndEscape(returned));
}
void Function::SetName(v8::Handle<v8::String> name) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ENTER_V8(isolate);
USE(isolate);
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
func->shared()->set_name(*Utils::OpenHandle(*name));
}
Handle<Value> Function::GetName() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
return Utils::ToLocal(i::Handle<i::Object>(func->shared()->name(),
func->GetIsolate()));
}
Handle<Value> Function::GetInferredName() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
return Utils::ToLocal(i::Handle<i::Object>(func->shared()->inferred_name(),
func->GetIsolate()));
}
Handle<Value> Function::GetDisplayName() const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Function::GetDisplayName()",
return ToApiHandle<Primitive>(
isolate->factory()->undefined_value()));
ENTER_V8(isolate);
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
i::Handle<i::String> property_name =
isolate->factory()->InternalizeOneByteString(
STATIC_CHAR_VECTOR("displayName"));
i::Handle<i::Object> value =
i::JSObject::GetDataProperty(func, property_name);
if (value->IsString()) {
i::Handle<i::String> name = i::Handle<i::String>::cast(value);
if (name->length() > 0) return Utils::ToLocal(name);
}
return ToApiHandle<Primitive>(isolate->factory()->undefined_value());
}
ScriptOrigin Function::GetScriptOrigin() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
if (func->shared()->script()->IsScript()) {
i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
i::Handle<i::Object> scriptName = i::Script::GetNameOrSourceURL(script);
v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(func->GetIsolate());
v8::ScriptOrigin origin(
Utils::ToLocal(scriptName),
v8::Integer::New(isolate, script->line_offset()->value()),
v8::Integer::New(isolate, script->column_offset()->value()));
return origin;
}
return v8::ScriptOrigin(Handle<Value>());
}
const int Function::kLineOffsetNotFound = -1;
int Function::GetScriptLineNumber() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
if (func->shared()->script()->IsScript()) {
i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
return i::Script::GetLineNumber(script, func->shared()->start_position());
}
return kLineOffsetNotFound;
}
int Function::GetScriptColumnNumber() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
if (func->shared()->script()->IsScript()) {
i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
return i::Script::GetColumnNumber(script, func->shared()->start_position());
}
return kLineOffsetNotFound;
}
bool Function::IsBuiltin() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
return func->IsBuiltin();
}
int Function::ScriptId() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
if (!func->shared()->script()->IsScript()) {
return v8::UnboundScript::kNoScriptId;
}
i::Handle<i::Script> script(i::Script::cast(func->shared()->script()));
return script->id()->value();
}
Local<v8::Value> Function::GetBoundFunction() const {
i::Handle<i::JSFunction> func = Utils::OpenHandle(this);
if (!func->shared()->bound()) {
return v8::Undefined(reinterpret_cast<v8::Isolate*>(func->GetIsolate()));
}
i::Handle<i::FixedArray> bound_args = i::Handle<i::FixedArray>(
i::FixedArray::cast(func->function_bindings()));
i::Handle<i::Object> original(
bound_args->get(i::JSFunction::kBoundFunctionIndex),
func->GetIsolate());
return Utils::ToLocal(i::Handle<i::JSFunction>::cast(original));
}
int String::Length() const {
i::Handle<i::String> str = Utils::OpenHandle(this);
return str->length();
}
bool String::IsOneByte() const {
i::Handle<i::String> str = Utils::OpenHandle(this);
return str->HasOnlyOneByteChars();
}
// Helpers for ContainsOnlyOneByteHelper
template<size_t size> struct OneByteMask;
template<> struct OneByteMask<4> {
static const uint32_t value = 0xFF00FF00;
};
template<> struct OneByteMask<8> {
static const uint64_t value = V8_2PART_UINT64_C(0xFF00FF00, FF00FF00);
};
static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
static inline bool Unaligned(const uint16_t* chars) {
return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
}
static inline const uint16_t* Align(const uint16_t* chars) {
return reinterpret_cast<uint16_t*>(
reinterpret_cast<uintptr_t>(chars) & ~kAlignmentMask);
}
class ContainsOnlyOneByteHelper {
public:
ContainsOnlyOneByteHelper() : is_one_byte_(true) {}
bool Check(i::String* string) {
i::ConsString* cons_string = i::String::VisitFlat(this, string, 0);
if (cons_string == NULL) return is_one_byte_;
return CheckCons(cons_string);
}
void VisitOneByteString(const uint8_t* chars, int length) {
// Nothing to do.
}
void VisitTwoByteString(const uint16_t* chars, int length) {
// Accumulated bits.
uintptr_t acc = 0;
// Align to uintptr_t.
const uint16_t* end = chars + length;
while (Unaligned(chars) && chars != end) {
acc |= *chars++;
}
// Read word aligned in blocks,
// checking the return value at the end of each block.
const uint16_t* aligned_end = Align(end);
const int increment = sizeof(uintptr_t)/sizeof(uint16_t);
const int inner_loops = 16;
while (chars + inner_loops*increment < aligned_end) {
for (int i = 0; i < inner_loops; i++) {
acc |= *reinterpret_cast<const uintptr_t*>(chars);
chars += increment;
}
// Check for early return.
if ((acc & kOneByteMask) != 0) {
is_one_byte_ = false;
return;
}
}
// Read the rest.
while (chars != end) {
acc |= *chars++;
}
// Check result.
if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
}
private:
bool CheckCons(i::ConsString* cons_string) {
while (true) {
// Check left side if flat.
i::String* left = cons_string->first();
i::ConsString* left_as_cons =
i::String::VisitFlat(this, left, 0);
if (!is_one_byte_) return false;
// Check right side if flat.
i::String* right = cons_string->second();
i::ConsString* right_as_cons =
i::String::VisitFlat(this, right, 0);
if (!is_one_byte_) return false;
// Standard recurse/iterate trick.
if (left_as_cons != NULL && right_as_cons != NULL) {
if (left->length() < right->length()) {
CheckCons(left_as_cons);
cons_string = right_as_cons;
} else {
CheckCons(right_as_cons);
cons_string = left_as_cons;
}
// Check fast return.
if (!is_one_byte_) return false;
continue;
}
// Descend left in place.
if (left_as_cons != NULL) {
cons_string = left_as_cons;
continue;
}
// Descend right in place.
if (right_as_cons != NULL) {
cons_string = right_as_cons;
continue;
}
// Terminate.
break;
}
return is_one_byte_;
}
bool is_one_byte_;
DISALLOW_COPY_AND_ASSIGN(ContainsOnlyOneByteHelper);
};
bool String::ContainsOnlyOneByte() const {
i::Handle<i::String> str = Utils::OpenHandle(this);
if (str->HasOnlyOneByteChars()) return true;
ContainsOnlyOneByteHelper helper;
return helper.Check(*str);
}
class Utf8LengthHelper : public i::AllStatic {
public:
enum State {
kEndsWithLeadingSurrogate = 1 << 0,
kStartsWithTrailingSurrogate = 1 << 1,
kLeftmostEdgeIsCalculated = 1 << 2,
kRightmostEdgeIsCalculated = 1 << 3,
kLeftmostEdgeIsSurrogate = 1 << 4,
kRightmostEdgeIsSurrogate = 1 << 5
};
static const uint8_t kInitialState = 0;
static inline bool EndsWithSurrogate(uint8_t state) {
return state & kEndsWithLeadingSurrogate;
}
static inline bool StartsWithSurrogate(uint8_t state) {
return state & kStartsWithTrailingSurrogate;
}
class Visitor {
public:
Visitor() : utf8_length_(0), state_(kInitialState) {}
void VisitOneByteString(const uint8_t* chars, int length) {
int utf8_length = 0;
// Add in length 1 for each non-Latin1 character.
for (int i = 0; i < length; i++) {
utf8_length += *chars++ >> 7;
}
// Add in length 1 for each character.
utf8_length_ = utf8_length + length;
state_ = kInitialState;
}
void VisitTwoByteString(const uint16_t* chars, int length) {
int utf8_length = 0;
int last_character = unibrow::Utf16::kNoPreviousCharacter;
for (int i = 0; i < length; i++) {
uint16_t c = chars[i];
utf8_length += unibrow::Utf8::Length(c, last_character);
last_character = c;
}
utf8_length_ = utf8_length;
uint8_t state = 0;
if (unibrow::Utf16::IsTrailSurrogate(chars[0])) {
state |= kStartsWithTrailingSurrogate;
}
if (unibrow::Utf16::IsLeadSurrogate(chars[length-1])) {
state |= kEndsWithLeadingSurrogate;
}
state_ = state;
}
static i::ConsString* VisitFlat(i::String* string,
int* length,
uint8_t* state) {
Visitor visitor;
i::ConsString* cons_string = i::String::VisitFlat(&visitor, string);
*length = visitor.utf8_length_;
*state = visitor.state_;
return cons_string;
}
private:
int utf8_length_;
uint8_t state_;
DISALLOW_COPY_AND_ASSIGN(Visitor);
};
static inline void MergeLeafLeft(int* length,
uint8_t* state,
uint8_t leaf_state) {
bool edge_surrogate = StartsWithSurrogate(leaf_state);
if (!(*state & kLeftmostEdgeIsCalculated)) {
DCHECK(!(*state & kLeftmostEdgeIsSurrogate));
*state |= kLeftmostEdgeIsCalculated
| (edge_surrogate ? kLeftmostEdgeIsSurrogate : 0);
} else if (EndsWithSurrogate(*state) && edge_surrogate) {
*length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
}
if (EndsWithSurrogate(leaf_state)) {
*state |= kEndsWithLeadingSurrogate;
} else {
*state &= ~kEndsWithLeadingSurrogate;
}
}
static inline void MergeLeafRight(int* length,
uint8_t* state,
uint8_t leaf_state) {
bool edge_surrogate = EndsWithSurrogate(leaf_state);
if (!(*state & kRightmostEdgeIsCalculated)) {
DCHECK(!(*state & kRightmostEdgeIsSurrogate));
*state |= (kRightmostEdgeIsCalculated
| (edge_surrogate ? kRightmostEdgeIsSurrogate : 0));
} else if (edge_surrogate && StartsWithSurrogate(*state)) {
*length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
}
if (StartsWithSurrogate(leaf_state)) {
*state |= kStartsWithTrailingSurrogate;
} else {
*state &= ~kStartsWithTrailingSurrogate;
}
}
static inline void MergeTerminal(int* length,
uint8_t state,
uint8_t* state_out) {
DCHECK((state & kLeftmostEdgeIsCalculated) &&
(state & kRightmostEdgeIsCalculated));
if (EndsWithSurrogate(state) && StartsWithSurrogate(state)) {
*length -= unibrow::Utf8::kBytesSavedByCombiningSurrogates;
}
*state_out = kInitialState |
(state & kLeftmostEdgeIsSurrogate ? kStartsWithTrailingSurrogate : 0) |
(state & kRightmostEdgeIsSurrogate ? kEndsWithLeadingSurrogate : 0);
}
static int Calculate(i::ConsString* current, uint8_t* state_out) {
using namespace internal;
int total_length = 0;
uint8_t state = kInitialState;
while (true) {
i::String* left = current->first();
i::String* right = current->second();
uint8_t right_leaf_state;
uint8_t left_leaf_state;
int leaf_length;
ConsString* left_as_cons =
Visitor::VisitFlat(left, &leaf_length, &left_leaf_state);
if (left_as_cons == NULL) {
total_length += leaf_length;
MergeLeafLeft(&total_length, &state, left_leaf_state);
}
ConsString* right_as_cons =
Visitor::VisitFlat(right, &leaf_length, &right_leaf_state);
if (right_as_cons == NULL) {
total_length += leaf_length;
MergeLeafRight(&total_length, &state, right_leaf_state);
if (left_as_cons != NULL) {
// 1 Leaf node. Descend in place.
current = left_as_cons;
continue;
} else {
// Terminal node.
MergeTerminal(&total_length, state, state_out);
return total_length;
}
} else if (left_as_cons == NULL) {
// 1 Leaf node. Descend in place.
current = right_as_cons;
continue;
}
// Both strings are ConsStrings.
// Recurse on smallest.
if (left->length() < right->length()) {
total_length += Calculate(left_as_cons, &left_leaf_state);
MergeLeafLeft(&total_length, &state, left_leaf_state);
current = right_as_cons;
} else {
total_length += Calculate(right_as_cons, &right_leaf_state);
MergeLeafRight(&total_length, &state, right_leaf_state);
current = left_as_cons;
}
}
UNREACHABLE();
return 0;
}
static inline int Calculate(i::ConsString* current) {
uint8_t state = kInitialState;
return Calculate(current, &state);
}
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8LengthHelper);
};
static int Utf8Length(i::String* str, i::Isolate* isolate) {
int length = str->length();
if (length == 0) return 0;
uint8_t state;
i::ConsString* cons_string =
Utf8LengthHelper::Visitor::VisitFlat(str, &length, &state);
if (cons_string == NULL) return length;
return Utf8LengthHelper::Calculate(cons_string);
}
int String::Utf8Length() const {
i::Handle<i::String> str = Utils::OpenHandle(this);
i::Isolate* isolate = str->GetIsolate();
return v8::Utf8Length(*str, isolate);
}
class Utf8WriterVisitor {
public:
Utf8WriterVisitor(
char* buffer,
int capacity,
bool skip_capacity_check,
bool replace_invalid_utf8)
: early_termination_(false),
last_character_(unibrow::Utf16::kNoPreviousCharacter),
buffer_(buffer),
start_(buffer),
capacity_(capacity),
skip_capacity_check_(capacity == -1 || skip_capacity_check),
replace_invalid_utf8_(replace_invalid_utf8),
utf16_chars_read_(0) {
}
static int WriteEndCharacter(uint16_t character,
int last_character,
int remaining,
char* const buffer,
bool replace_invalid_utf8) {
using namespace unibrow;
DCHECK(remaining > 0);
// We can't use a local buffer here because Encode needs to modify
// previous characters in the stream. We know, however, that
// exactly one character will be advanced.
if (Utf16::IsSurrogatePair(last_character, character)) {
int written = Utf8::Encode(buffer,
character,
last_character,
replace_invalid_utf8);
DCHECK(written == 1);
return written;
}
// Use a scratch buffer to check the required characters.
char temp_buffer[Utf8::kMaxEncodedSize];
// Can't encode using last_character as gcc has array bounds issues.
int written = Utf8::Encode(temp_buffer,
character,
Utf16::kNoPreviousCharacter,
replace_invalid_utf8);
// Won't fit.
if (written > remaining) return 0;
// Copy over the character from temp_buffer.
for (int j = 0; j < written; j++) {
buffer[j] = temp_buffer[j];
}
return written;
}
// Visit writes out a group of code units (chars) of a v8::String to the
// internal buffer_. This is done in two phases. The first phase calculates a
// pesimistic estimate (writable_length) on how many code units can be safely
// written without exceeding the buffer capacity and without writing the last
// code unit (it could be a lead surrogate). The estimated number of code
// units is then written out in one go, and the reported byte usage is used
// to correct the estimate. This is repeated until the estimate becomes <= 0
// or all code units have been written out. The second phase writes out code
// units until the buffer capacity is reached, would be exceeded by the next
// unit, or all units have been written out.
template<typename Char>
void Visit(const Char* chars, const int length) {
using namespace unibrow;
DCHECK(!early_termination_);
if (length == 0) return;
// Copy state to stack.
char* buffer = buffer_;
int last_character =
sizeof(Char) == 1 ? Utf16::kNoPreviousCharacter : last_character_;
int i = 0;
// Do a fast loop where there is no exit capacity check.
while (true) {
int fast_length;
if (skip_capacity_check_) {
fast_length = length;
} else {
int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
// Need enough space to write everything but one character.
STATIC_ASSERT(Utf16::kMaxExtraUtf8BytesForOneUtf16CodeUnit == 3);
int max_size_per_char = sizeof(Char) == 1 ? 2 : 3;
int writable_length =
(remaining_capacity - max_size_per_char)/max_size_per_char;
// Need to drop into slow loop.
if (writable_length <= 0) break;
fast_length = i + writable_length;
if (fast_length > length) fast_length = length;
}
// Write the characters to the stream.
if (sizeof(Char) == 1) {
for (; i < fast_length; i++) {
buffer +=
Utf8::EncodeOneByte(buffer, static_cast<uint8_t>(*chars++));
DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
}
} else {
for (; i < fast_length; i++) {
uint16_t character = *chars++;
buffer += Utf8::Encode(buffer,
character,
last_character,
replace_invalid_utf8_);
last_character = character;
DCHECK(capacity_ == -1 || (buffer - start_) <= capacity_);
}
}
// Array is fully written. Exit.
if (fast_length == length) {
// Write state back out to object.
last_character_ = last_character;
buffer_ = buffer;
utf16_chars_read_ += length;
return;
}
}
DCHECK(!skip_capacity_check_);
// Slow loop. Must check capacity on each iteration.
int remaining_capacity = capacity_ - static_cast<int>(buffer - start_);
DCHECK(remaining_capacity >= 0);
for (; i < length && remaining_capacity > 0; i++) {
uint16_t character = *chars++;
// remaining_capacity is <= 3 bytes at this point, so we do not write out
// an umatched lead surrogate.
if (replace_invalid_utf8_ && Utf16::IsLeadSurrogate(character)) {
early_termination_ = true;
break;
}
int written = WriteEndCharacter(character,
last_character,
remaining_capacity,
buffer,
replace_invalid_utf8_);
if (written == 0) {
early_termination_ = true;
break;
}
buffer += written;
remaining_capacity -= written;
last_character = character;
}
// Write state back out to object.
last_character_ = last_character;
buffer_ = buffer;
utf16_chars_read_ += i;
}
inline bool IsDone() {
return early_termination_;
}
inline void VisitOneByteString(const uint8_t* chars, int length) {
Visit(chars, length);
}
inline void VisitTwoByteString(const uint16_t* chars, int length) {
Visit(chars, length);
}
int CompleteWrite(bool write_null, int* utf16_chars_read_out) {
// Write out number of utf16 characters written to the stream.
if (utf16_chars_read_out != NULL) {
*utf16_chars_read_out = utf16_chars_read_;
}
// Only null terminate if all of the string was written and there's space.
if (write_null &&
!early_termination_ &&
(capacity_ == -1 || (buffer_ - start_) < capacity_)) {
*buffer_++ = '\0';
}
return static_cast<int>(buffer_ - start_);
}
private:
bool early_termination_;
int last_character_;
char* buffer_;
char* const start_;
int capacity_;
bool const skip_capacity_check_;
bool const replace_invalid_utf8_;
int utf16_chars_read_;
DISALLOW_IMPLICIT_CONSTRUCTORS(Utf8WriterVisitor);
};
static bool RecursivelySerializeToUtf8(i::String* current,
Utf8WriterVisitor* writer,
int recursion_budget) {
while (!writer->IsDone()) {
i::ConsString* cons_string = i::String::VisitFlat(writer, current);
if (cons_string == NULL) return true; // Leaf node.
if (recursion_budget <= 0) return false;
// Must write the left branch first.
i::String* first = cons_string->first();
bool success = RecursivelySerializeToUtf8(first,
writer,
recursion_budget - 1);
if (!success) return false;
// Inline tail recurse for right branch.
current = cons_string->second();
}
return true;
}
int String::WriteUtf8(char* buffer,
int capacity,
int* nchars_ref,
int options) const {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
LOG_API(isolate, "String::WriteUtf8");
ENTER_V8(isolate);
i::Handle<i::String> str = Utils::OpenHandle(this);
if (options & HINT_MANY_WRITES_EXPECTED) {
str = i::String::Flatten(str); // Flatten the string for efficiency.
}
const int string_length = str->length();
bool write_null = !(options & NO_NULL_TERMINATION);
bool replace_invalid_utf8 = (options & REPLACE_INVALID_UTF8);
int max16BitCodeUnitSize = unibrow::Utf8::kMax16BitCodeUnitSize;
// First check if we can just write the string without checking capacity.
if (capacity == -1 || capacity / max16BitCodeUnitSize >= string_length) {
Utf8WriterVisitor writer(buffer, capacity, true, replace_invalid_utf8);
const int kMaxRecursion = 100;
bool success = RecursivelySerializeToUtf8(*str, &writer, kMaxRecursion);
if (success) return writer.CompleteWrite(write_null, nchars_ref);
} else if (capacity >= string_length) {
// First check that the buffer is large enough.
int utf8_bytes = v8::Utf8Length(*str, str->GetIsolate());
if (utf8_bytes <= capacity) {
// one-byte fast path.
if (utf8_bytes == string_length) {
WriteOneByte(reinterpret_cast<uint8_t*>(buffer), 0, capacity, options);
if (nchars_ref != NULL) *nchars_ref = string_length;
if (write_null && (utf8_bytes+1 <= capacity)) {
return string_length + 1;
}
return string_length;
}
if (write_null && (utf8_bytes+1 > capacity)) {
options |= NO_NULL_TERMINATION;
}
// Recurse once without a capacity limit.
// This will get into the first branch above.
// TODO(dcarney) Check max left rec. in Utf8Length and fall through.
return WriteUtf8(buffer, -1, nchars_ref, options);
}
}
// Recursive slow path can potentially be unreasonable slow. Flatten.
str = i::String::Flatten(str);
Utf8WriterVisitor writer(buffer, capacity, false, replace_invalid_utf8);
i::String::VisitFlat(&writer, *str);
return writer.CompleteWrite(write_null, nchars_ref);
}
template<typename CharType>
static inline int WriteHelper(const String* string,
CharType* buffer,
int start,
int length,
int options) {
i::Isolate* isolate = Utils::OpenHandle(string)->GetIsolate();
LOG_API(isolate, "String::Write");
ENTER_V8(isolate);
DCHECK(start >= 0 && length >= -1);
i::Handle<i::String> str = Utils::OpenHandle(string);
isolate->string_tracker()->RecordWrite(str);
if (options & String::HINT_MANY_WRITES_EXPECTED) {
// Flatten the string for efficiency. This applies whether we are
// using StringCharacterStream or Get(i) to access the characters.
str = i::String::Flatten(str);
}
int end = start + length;
if ((length == -1) || (length > str->length() - start) )
end = str->length();
if (end < 0) return 0;
i::String::WriteToFlat(*str, buffer, start, end);
if (!(options & String::NO_NULL_TERMINATION) &&
(length == -1 || end - start < length)) {
buffer[end - start] = '\0';
}
return end - start;
}
int String::WriteOneByte(uint8_t* buffer,
int start,
int length,
int options) const {
return WriteHelper(this, buffer, start, length, options);
}
int String::Write(uint16_t* buffer,
int start,
int length,
int options) const {
return WriteHelper(this, buffer, start, length, options);
}
bool v8::String::IsExternal() const {
i::Handle<i::String> str = Utils::OpenHandle(this);
return i::StringShape(*str).IsExternalTwoByte();
}
bool v8::String::IsExternalOneByte() const {
i::Handle<i::String> str = Utils::OpenHandle(this);
return i::StringShape(*str).IsExternalOneByte();
}
void v8::String::VerifyExternalStringResource(
v8::String::ExternalStringResource* value) const {
i::Handle<i::String> str = Utils::OpenHandle(this);
const v8::String::ExternalStringResource* expected;
if (i::StringShape(*str).IsExternalTwoByte()) {
const void* resource =
i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
expected = reinterpret_cast<const ExternalStringResource*>(resource);
} else {
expected = NULL;
}
CHECK_EQ(expected, value);
}
void v8::String::VerifyExternalStringResourceBase(
v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
i::Handle<i::String> str = Utils::OpenHandle(this);
const v8::String::ExternalStringResourceBase* expected;
Encoding expectedEncoding;
if (i::StringShape(*str).IsExternalOneByte()) {
const void* resource =
i::Handle<i::ExternalOneByteString>::cast(str)->resource();
expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
expectedEncoding = ONE_BYTE_ENCODING;
} else if (i::StringShape(*str).IsExternalTwoByte()) {
const void* resource =
i::Handle<i::ExternalTwoByteString>::cast(str)->resource();
expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
expectedEncoding = TWO_BYTE_ENCODING;
} else {
expected = NULL;
expectedEncoding =
str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
}
CHECK_EQ(expected, value);
CHECK_EQ(expectedEncoding, encoding);
}
const v8::String::ExternalOneByteStringResource*
v8::String::GetExternalOneByteStringResource() const {
i::Handle<i::String> str = Utils::OpenHandle(this);
if (i::StringShape(*str).IsExternalOneByte()) {
const void* resource =
i::Handle<i::ExternalOneByteString>::cast(str)->resource();
return reinterpret_cast<const ExternalOneByteStringResource*>(resource);
} else {
return NULL;
}
}
Local<Value> Symbol::Name() const {
i::Handle<i::Symbol> sym = Utils::OpenHandle(this);
i::Handle<i::Object> name(sym->name(), sym->GetIsolate());
return Utils::ToLocal(name);
}
Local<Value> Private::Name() const {
return reinterpret_cast<const Symbol*>(this)->Name();
}
double Number::Value() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
return obj->Number();
}
bool Boolean::Value() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
return obj->IsTrue();
}
int64_t Integer::Value() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) {
return i::Smi::cast(*obj)->value();
} else {
return static_cast<int64_t>(obj->Number());
}
}
int32_t Int32::Value() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) {
return i::Smi::cast(*obj)->value();
} else {
return static_cast<int32_t>(obj->Number());
}
}
uint32_t Uint32::Value() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
if (obj->IsSmi()) {
return i::Smi::cast(*obj)->value();
} else {
return static_cast<uint32_t>(obj->Number());
}
}
int v8::Object::InternalFieldCount() {
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
return obj->GetInternalFieldCount();
}
static bool InternalFieldOK(i::Handle<i::JSObject> obj,
int index,
const char* location) {
return Utils::ApiCheck(index < obj->GetInternalFieldCount(),
location,
"Internal field out of bounds");
}
Local<Value> v8::Object::SlowGetInternalField(int index) {
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
const char* location = "v8::Object::GetInternalField()";
if (!InternalFieldOK(obj, index, location)) return Local<Value>();
i::Handle<i::Object> value(obj->GetInternalField(index), obj->GetIsolate());
return Utils::ToLocal(value);
}
void v8::Object::SetInternalField(int index, v8::Handle<Value> value) {
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
const char* location = "v8::Object::SetInternalField()";
if (!InternalFieldOK(obj, index, location)) return;
i::Handle<i::Object> val = Utils::OpenHandle(*value);
obj->SetInternalField(index, *val);
DCHECK_EQ(value, GetInternalField(index));
}
void* v8::Object::SlowGetAlignedPointerFromInternalField(int index) {
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
if (!InternalFieldOK(obj, index, location)) return NULL;
return DecodeSmiToAligned(obj->GetInternalField(index), location);
}
void v8::Object::SetAlignedPointerInInternalField(int index, void* value) {
i::Handle<i::JSObject> obj = Utils::OpenHandle(this);
const char* location = "v8::Object::SetAlignedPointerInInternalField()";
if (!InternalFieldOK(obj, index, location)) return;
obj->SetInternalField(index, EncodeAlignedAsSmi(value, location));
DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
}
static void* ExternalValue(i::Object* obj) {
// Obscure semantics for undefined, but somehow checked in our unit tests...
if (obj->IsUndefined()) return NULL;
i::Object* foreign = i::JSObject::cast(obj)->GetInternalField(0);
return i::Foreign::cast(foreign)->foreign_address();
}
// --- E n v i r o n m e n t ---
void v8::V8::InitializePlatform(Platform* platform) {
i::V8::InitializePlatform(platform);
}
void v8::V8::ShutdownPlatform() {
i::V8::ShutdownPlatform();
}
bool v8::V8::Initialize() {
i::V8::Initialize();
return true;
}
void v8::V8::SetEntropySource(EntropySource entropy_source) {
base::RandomNumberGenerator::SetEntropySource(entropy_source);
}
void v8::V8::SetReturnAddressLocationResolver(
ReturnAddressLocationResolver return_address_resolver) {
i::V8::SetReturnAddressLocationResolver(return_address_resolver);
}
void v8::V8::SetArrayBufferAllocator(
ArrayBuffer::Allocator* allocator) {
if (!Utils::ApiCheck(i::V8::ArrayBufferAllocator() == NULL,
"v8::V8::SetArrayBufferAllocator",
"ArrayBufferAllocator might only be set once"))
return;
i::V8::SetArrayBufferAllocator(allocator);
}
bool v8::V8::Dispose() {
i::V8::TearDown();
return true;
}
HeapStatistics::HeapStatistics(): total_heap_size_(0),
total_heap_size_executable_(0),
total_physical_size_(0),
used_heap_size_(0),
heap_size_limit_(0) { }
void v8::V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
i::Isolate* isolate = i::Isolate::Current();
isolate->heap()->VisitExternalResources(visitor);
}
class VisitorAdapter : public i::ObjectVisitor {
public:
explicit VisitorAdapter(PersistentHandleVisitor* visitor)
: visitor_(visitor) {}
virtual void VisitPointers(i::Object** start, i::Object** end) {
UNREACHABLE();
}
virtual void VisitEmbedderReference(i::Object** p, uint16_t class_id) {
Value* value = ToApi<Value>(i::Handle<i::Object>(p));
visitor_->VisitPersistentHandle(
reinterpret_cast<Persistent<Value>*>(&value), class_id);
}
private:
PersistentHandleVisitor* visitor_;
};
void v8::V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
i::Isolate* isolate = i::Isolate::Current();
i::DisallowHeapAllocation no_allocation;
VisitorAdapter visitor_adapter(visitor);
isolate->global_handles()->IterateAllRootsWithClassIds(&visitor_adapter);
}
void v8::V8::VisitHandlesForPartialDependence(
Isolate* exported_isolate, PersistentHandleVisitor* visitor) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(exported_isolate);
DCHECK(isolate == i::Isolate::Current());
i::DisallowHeapAllocation no_allocation;
VisitorAdapter visitor_adapter(visitor);
isolate->global_handles()->IterateAllRootsInNewSpaceWithClassIds(
&visitor_adapter);
}
bool v8::V8::InitializeICU(const char* icu_data_file) {
return i::InitializeICU(icu_data_file);
}
const char* v8::V8::GetVersion() {
return i::Version::GetVersion();
}
static i::Handle<i::Context> CreateEnvironment(
i::Isolate* isolate,
v8::ExtensionConfiguration* extensions,
v8::Handle<ObjectTemplate> global_template,
v8::Handle<Value> maybe_global_proxy) {
i::Handle<i::Context> env;
// Enter V8 via an ENTER_V8 scope.
{
ENTER_V8(isolate);
v8::Handle<ObjectTemplate> proxy_template = global_template;
i::Handle<i::FunctionTemplateInfo> proxy_constructor;
i::Handle<i::FunctionTemplateInfo> global_constructor;
if (!global_template.IsEmpty()) {
// Make sure that the global_template has a constructor.
global_constructor = EnsureConstructor(isolate, *global_template);
// Create a fresh template for the global proxy object.
proxy_template = ObjectTemplate::New(
reinterpret_cast<v8::Isolate*>(isolate));
proxy_constructor = EnsureConstructor(isolate, *proxy_template);
// Set the global template to be the prototype template of
// global proxy template.
proxy_constructor->set_prototype_template(
*Utils::OpenHandle(*global_template));
// Migrate security handlers from global_template to
// proxy_template. Temporarily removing access check
// information from the global template.
if (!global_constructor->access_check_info()->IsUndefined()) {
proxy_constructor->set_access_check_info(
global_constructor->access_check_info());
proxy_constructor->set_needs_access_check(
global_constructor->needs_access_check());
global_constructor->set_needs_access_check(false);
global_constructor->set_access_check_info(
isolate->heap()->undefined_value());
}
}
i::Handle<i::Object> proxy = Utils::OpenHandle(*maybe_global_proxy, true);
i::MaybeHandle<i::JSGlobalProxy> maybe_proxy;
if (!proxy.is_null()) {
maybe_proxy = i::Handle<i::JSGlobalProxy>::cast(proxy);
}
// Create the environment.
env = isolate->bootstrapper()->CreateEnvironment(
maybe_proxy, proxy_template, extensions);
// Restore the access check info on the global template.
if (!global_template.IsEmpty()) {
DCHECK(!global_constructor.is_null());
DCHECK(!proxy_constructor.is_null());
global_constructor->set_access_check_info(
proxy_constructor->access_check_info());
global_constructor->set_needs_access_check(
proxy_constructor->needs_access_check());
}
}
// Leave V8.
return env;
}
Local<Context> v8::Context::New(
v8::Isolate* external_isolate,
v8::ExtensionConfiguration* extensions,
v8::Handle<ObjectTemplate> global_template,
v8::Handle<Value> global_object) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(external_isolate);
LOG_API(isolate, "Context::New");
ON_BAILOUT(isolate, "v8::Context::New()", return Local<Context>());
i::HandleScope scope(isolate);
ExtensionConfiguration no_extensions;
if (extensions == NULL) extensions = &no_extensions;
i::Handle<i::Context> env =
CreateEnvironment(isolate, extensions, global_template, global_object);
if (env.is_null()) return Local<Context>();
return Utils::ToLocal(scope.CloseAndEscape(env));
}
void v8::Context::SetSecurityToken(Handle<Value> token) {
i::Isolate* isolate = i::Isolate::Current();
ENTER_V8(isolate);
i::Handle<i::Context> env = Utils::OpenHandle(this);
i::Handle<i::Object> token_handle = Utils::OpenHandle(*token);
env->set_security_token(*token_handle);
}
void v8::Context::UseDefaultSecurityToken() {
i::Isolate* isolate = i::Isolate::Current();
ENTER_V8(isolate);
i::Handle<i::Context> env = Utils::OpenHandle(this);
env->set_security_token(env->global_object());
}
Handle<Value> v8::Context::GetSecurityToken() {
i::Isolate* isolate = i::Isolate::Current();
i::Handle<i::Context> env = Utils::OpenHandle(this);
i::Object* security_token = env->security_token();
i::Handle<i::Object> token_handle(security_token, isolate);
return Utils::ToLocal(token_handle);
}
v8::Isolate* Context::GetIsolate() {
i::Handle<i::Context> env = Utils::OpenHandle(this);
return reinterpret_cast<Isolate*>(env->GetIsolate());
}
v8::Local<v8::Object> Context::Global() {
i::Handle<i::Context> context = Utils::OpenHandle(this);
i::Isolate* isolate = context->GetIsolate();
i::Handle<i::Object> global(context->global_proxy(), isolate);
// TODO(dcarney): This should always return the global proxy
// but can't presently as calls to GetProtoype will return the wrong result.
if (i::Handle<i::JSGlobalProxy>::cast(
global)->IsDetachedFrom(context->global_object())) {
global = i::Handle<i::Object>(context->global_object(), isolate);
}
return Utils::ToLocal(i::Handle<i::JSObject>::cast(global));
}
void Context::DetachGlobal() {
i::Handle<i::Context> context = Utils::OpenHandle(this);
i::Isolate* isolate = context->GetIsolate();
ENTER_V8(isolate);
isolate->bootstrapper()->DetachGlobal(context);
}
void Context::AllowCodeGenerationFromStrings(bool allow) {
i::Handle<i::Context> context = Utils::OpenHandle(this);
i::Isolate* isolate = context->GetIsolate();
ENTER_V8(isolate);
context->set_allow_code_gen_from_strings(
allow ? isolate->heap()->true_value() : isolate->heap()->false_value());
}
bool Context::IsCodeGenerationFromStringsAllowed() {
i::Handle<i::Context> context = Utils::OpenHandle(this);
return !context->allow_code_gen_from_strings()->IsFalse();
}
void Context::SetErrorMessageForCodeGenerationFromStrings(
Handle<String> error) {
i::Handle<i::Context> context = Utils::OpenHandle(this);
i::Handle<i::String> error_handle = Utils::OpenHandle(*error);
context->set_error_message_for_code_gen_from_strings(*error_handle);
}
Local<v8::Object> ObjectTemplate::NewInstance() {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "v8::ObjectTemplate::NewInstance()",
return Local<v8::Object>());
LOG_API(isolate, "ObjectTemplate::NewInstance");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> obj;
has_pending_exception = !i::Execution::InstantiateObject(
Utils::OpenHandle(this)).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Object>());
return Utils::ToLocal(i::Handle<i::JSObject>::cast(obj));
}
Local<v8::Function> FunctionTemplate::GetFunction() {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "v8::FunctionTemplate::GetFunction()",
return Local<v8::Function>());
LOG_API(isolate, "FunctionTemplate::GetFunction");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> obj;
has_pending_exception = !i::Execution::InstantiateFunction(
Utils::OpenHandle(this)).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::Function>());
return Utils::ToLocal(i::Handle<i::JSFunction>::cast(obj));
}
bool FunctionTemplate::HasInstance(v8::Handle<v8::Value> value) {
ON_BAILOUT(i::Isolate::Current(), "v8::FunctionTemplate::HasInstanceOf()",
return false);
i::Object* obj = *Utils::OpenHandle(*value);
return Utils::OpenHandle(this)->IsTemplateFor(obj);
}
Local<External> v8::External::New(Isolate* isolate, void* value) {
STATIC_ASSERT(sizeof(value) == sizeof(i::Address));
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "External::New");
ENTER_V8(i_isolate);
i::Handle<i::JSObject> external = i_isolate->factory()->NewExternal(value);
return Utils::ExternalToLocal(external);
}
void* External::Value() const {
return ExternalValue(*Utils::OpenHandle(this));
}
// anonymous namespace for string creation helper functions
namespace {
inline int StringLength(const char* string) {
return i::StrLength(string);
}
inline int StringLength(const uint8_t* string) {
return i::StrLength(reinterpret_cast<const char*>(string));
}
inline int StringLength(const uint16_t* string) {
int length = 0;
while (string[length] != '\0')
length++;
return length;
}
MUST_USE_RESULT
inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
String::NewStringType type,
i::Vector<const char> string) {
if (type == String::kInternalizedString) {
return factory->InternalizeUtf8String(string);
}
return factory->NewStringFromUtf8(string);
}
MUST_USE_RESULT
inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
String::NewStringType type,
i::Vector<const uint8_t> string) {
if (type == String::kInternalizedString) {
return factory->InternalizeOneByteString(string);
}
return factory->NewStringFromOneByte(string);
}
MUST_USE_RESULT
inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
String::NewStringType type,
i::Vector<const uint16_t> string) {
if (type == String::kInternalizedString) {
return factory->InternalizeTwoByteString(string);
}
return factory->NewStringFromTwoByte(string);
}
template<typename Char>
inline Local<String> NewString(Isolate* v8_isolate,
const char* location,
const char* env,
const Char* data,
String::NewStringType type,
int length) {
i::Isolate* isolate = reinterpret_cast<internal::Isolate*>(v8_isolate);
LOG_API(isolate, env);
if (length == 0 && type != String::kUndetectableString) {
return String::Empty(v8_isolate);
}
ENTER_V8(isolate);
if (length == -1) length = StringLength(data);
// We do not expect this to fail. Change this if it does.
i::Handle<i::String> result = NewString(
isolate->factory(),
type,
i::Vector<const Char>(data, length)).ToHandleChecked();
if (type == String::kUndetectableString) {
result->MarkAsUndetectable();
}
return Utils::ToLocal(result);
}
} // anonymous namespace
Local<String> String::NewFromUtf8(Isolate* isolate,
const char* data,
NewStringType type,
int length) {
return NewString(isolate,
"v8::String::NewFromUtf8()",
"String::NewFromUtf8",
data,
type,
length);
}
Local<String> String::NewFromOneByte(Isolate* isolate,
const uint8_t* data,
NewStringType type,
int length) {
return NewString(isolate,
"v8::String::NewFromOneByte()",
"String::NewFromOneByte",
data,
type,
length);
}
Local<String> String::NewFromTwoByte(Isolate* isolate,
const uint16_t* data,
NewStringType type,
int length) {
return NewString(isolate,
"v8::String::NewFromTwoByte()",
"String::NewFromTwoByte",
data,
type,
length);
}
Local<String> v8::String::Concat(Handle<String> left, Handle<String> right) {
i::Handle<i::String> left_string = Utils::OpenHandle(*left);
i::Isolate* isolate = left_string->GetIsolate();
LOG_API(isolate, "String::New(char)");
ENTER_V8(isolate);
i::Handle<i::String> right_string = Utils::OpenHandle(*right);
// We do not expect this to fail. Change this if it does.
i::Handle<i::String> result = isolate->factory()->NewConsString(
left_string, right_string).ToHandleChecked();
return Utils::ToLocal(result);
}
static i::MaybeHandle<i::String> NewExternalStringHandle(
i::Isolate* isolate, v8::String::ExternalStringResource* resource) {
return isolate->factory()->NewExternalStringFromTwoByte(resource);
}
static i::MaybeHandle<i::String> NewExternalOneByteStringHandle(
i::Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
return isolate->factory()->NewExternalStringFromOneByte(resource);
}
Local<String> v8::String::NewExternal(
Isolate* isolate,
v8::String::ExternalStringResource* resource) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "String::NewExternal");
ENTER_V8(i_isolate);
CHECK(resource && resource->data());
EXCEPTION_PREAMBLE(i_isolate);
i::Handle<i::String> string;
has_pending_exception =
!NewExternalStringHandle(i_isolate, resource).ToHandle(&string);
EXCEPTION_BAILOUT_CHECK(i_isolate, Local<String>());
i_isolate->heap()->external_string_table()->AddString(*string);
return Utils::ToLocal(string);
}
bool v8::String::MakeExternal(v8::String::ExternalStringResource* resource) {
i::Handle<i::String> obj = Utils::OpenHandle(this);
i::Isolate* isolate = obj->GetIsolate();
if (i::StringShape(*obj).IsExternal()) {
return false; // Already an external string.
}
ENTER_V8(isolate);
if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
return false;
}
if (isolate->heap()->IsInGCPostProcessing()) {
return false;
}
CHECK(resource && resource->data());
bool result = obj->MakeExternal(resource);
// Assert that if CanMakeExternal(), then externalizing actually succeeds.
DCHECK(!CanMakeExternal() || result);
if (result) {
DCHECK(obj->IsExternalString());
isolate->heap()->external_string_table()->AddString(*obj);
}
return result;
}
Local<String> v8::String::NewExternal(
Isolate* isolate, v8::String::ExternalOneByteStringResource* resource) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "String::NewExternal");
ENTER_V8(i_isolate);
CHECK(resource && resource->data());
EXCEPTION_PREAMBLE(i_isolate);
i::Handle<i::String> string;
has_pending_exception =
!NewExternalOneByteStringHandle(i_isolate, resource).ToHandle(&string);
EXCEPTION_BAILOUT_CHECK(i_isolate, Local<String>());
i_isolate->heap()->external_string_table()->AddString(*string);
return Utils::ToLocal(string);
}
bool v8::String::MakeExternal(
v8::String::ExternalOneByteStringResource* resource) {
i::Handle<i::String> obj = Utils::OpenHandle(this);
i::Isolate* isolate = obj->GetIsolate();
if (i::StringShape(*obj).IsExternal()) {
return false; // Already an external string.
}
ENTER_V8(isolate);
if (isolate->string_tracker()->IsFreshUnusedString(obj)) {
return false;
}
if (isolate->heap()->IsInGCPostProcessing()) {
return false;
}
CHECK(resource && resource->data());
bool result = obj->MakeExternal(resource);
// Assert that if CanMakeExternal(), then externalizing actually succeeds.
DCHECK(!CanMakeExternal() || result);
if (result) {
DCHECK(obj->IsExternalString());
isolate->heap()->external_string_table()->AddString(*obj);
}
return result;
}
bool v8::String::CanMakeExternal() {
if (!internal::FLAG_clever_optimizations) return false;
i::Handle<i::String> obj = Utils::OpenHandle(this);
i::Isolate* isolate = obj->GetIsolate();
if (isolate->string_tracker()->IsFreshUnusedString(obj)) return false;
int size = obj->Size(); // Byte size of the original string.
if (size < i::ExternalString::kShortSize) return false;
i::StringShape shape(*obj);
return !shape.IsExternal();
}
Local<v8::Object> v8::Object::New(Isolate* isolate) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "Object::New");
ENTER_V8(i_isolate);
i::Handle<i::JSObject> obj =
i_isolate->factory()->NewJSObject(i_isolate->object_function());
return Utils::ToLocal(obj);
}
Local<v8::Value> v8::NumberObject::New(Isolate* isolate, double value) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "NumberObject::New");
ENTER_V8(i_isolate);
i::Handle<i::Object> number = i_isolate->factory()->NewNumber(value);
i::Handle<i::Object> obj =
i::Object::ToObject(i_isolate, number).ToHandleChecked();
return Utils::ToLocal(obj);
}
double v8::NumberObject::ValueOf() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
i::Isolate* isolate = jsvalue->GetIsolate();
LOG_API(isolate, "NumberObject::NumberValue");
return jsvalue->value()->Number();
}
Local<v8::Value> v8::BooleanObject::New(bool value) {
i::Isolate* isolate = i::Isolate::Current();
LOG_API(isolate, "BooleanObject::New");
ENTER_V8(isolate);
i::Handle<i::Object> boolean(value
? isolate->heap()->true_value()
: isolate->heap()->false_value(),
isolate);
i::Handle<i::Object> obj =
i::Object::ToObject(isolate, boolean).ToHandleChecked();
return Utils::ToLocal(obj);
}
bool v8::BooleanObject::ValueOf() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
i::Isolate* isolate = jsvalue->GetIsolate();
LOG_API(isolate, "BooleanObject::BooleanValue");
return jsvalue->value()->IsTrue();
}
Local<v8::Value> v8::StringObject::New(Handle<String> value) {
i::Handle<i::String> string = Utils::OpenHandle(*value);
i::Isolate* isolate = string->GetIsolate();
LOG_API(isolate, "StringObject::New");
ENTER_V8(isolate);
i::Handle<i::Object> obj =
i::Object::ToObject(isolate, string).ToHandleChecked();
return Utils::ToLocal(obj);
}
Local<v8::String> v8::StringObject::ValueOf() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
i::Isolate* isolate = jsvalue->GetIsolate();
LOG_API(isolate, "StringObject::StringValue");
return Utils::ToLocal(
i::Handle<i::String>(i::String::cast(jsvalue->value())));
}
Local<v8::Value> v8::SymbolObject::New(Isolate* isolate, Handle<Symbol> value) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "SymbolObject::New");
ENTER_V8(i_isolate);
i::Handle<i::Object> obj = i::Object::ToObject(
i_isolate, Utils::OpenHandle(*value)).ToHandleChecked();
return Utils::ToLocal(obj);
}
Local<v8::Symbol> v8::SymbolObject::ValueOf() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::JSValue> jsvalue = i::Handle<i::JSValue>::cast(obj);
i::Isolate* isolate = jsvalue->GetIsolate();
LOG_API(isolate, "SymbolObject::SymbolValue");
return Utils::ToLocal(
i::Handle<i::Symbol>(i::Symbol::cast(jsvalue->value())));
}
Local<v8::Value> v8::Date::New(Isolate* isolate, double time) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "Date::New");
if (std::isnan(time)) {
// Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
time = base::OS::nan_value();
}
ENTER_V8(i_isolate);
EXCEPTION_PREAMBLE(i_isolate);
i::Handle<i::Object> obj;
has_pending_exception = !i::Execution::NewDate(
i_isolate, time).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(i_isolate, Local<v8::Value>());
return Utils::ToLocal(obj);
}
double v8::Date::ValueOf() const {
i::Handle<i::Object> obj = Utils::OpenHandle(this);
i::Handle<i::JSDate> jsdate = i::Handle<i::JSDate>::cast(obj);
i::Isolate* isolate = jsdate->GetIsolate();
LOG_API(isolate, "Date::NumberValue");
return jsdate->value()->Number();
}
void v8::Date::DateTimeConfigurationChangeNotification(Isolate* isolate) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
if (!i_isolate->IsInitialized()) return;
ON_BAILOUT(i_isolate, "v8::Date::DateTimeConfigurationChangeNotification()",
return);
LOG_API(i_isolate, "Date::DateTimeConfigurationChangeNotification");
ENTER_V8(i_isolate);
i_isolate->date_cache()->ResetDateCache();
if (!i_isolate->eternal_handles()->Exists(
i::EternalHandles::DATE_CACHE_VERSION)) {
return;
}
i::Handle<i::FixedArray> date_cache_version =
i::Handle<i::FixedArray>::cast(i_isolate->eternal_handles()->GetSingleton(
i::EternalHandles::DATE_CACHE_VERSION));
DCHECK_EQ(1, date_cache_version->length());
CHECK(date_cache_version->get(0)->IsSmi());
date_cache_version->set(
0,
i::Smi::FromInt(i::Smi::cast(date_cache_version->get(0))->value() + 1));
}
static i::Handle<i::String> RegExpFlagsToString(RegExp::Flags flags) {
i::Isolate* isolate = i::Isolate::Current();
uint8_t flags_buf[3];
int num_flags = 0;
if ((flags & RegExp::kGlobal) != 0) flags_buf[num_flags++] = 'g';
if ((flags & RegExp::kMultiline) != 0) flags_buf[num_flags++] = 'm';
if ((flags & RegExp::kIgnoreCase) != 0) flags_buf[num_flags++] = 'i';
DCHECK(num_flags <= static_cast<int>(arraysize(flags_buf)));
return isolate->factory()->InternalizeOneByteString(
i::Vector<const uint8_t>(flags_buf, num_flags));
}
Local<v8::RegExp> v8::RegExp::New(Handle<String> pattern,
Flags flags) {
i::Isolate* isolate = Utils::OpenHandle(*pattern)->GetIsolate();
LOG_API(isolate, "RegExp::New");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::JSRegExp> obj;
has_pending_exception = !i::Execution::NewJSRegExp(
Utils::OpenHandle(*pattern),
RegExpFlagsToString(flags)).ToHandle(&obj);
EXCEPTION_BAILOUT_CHECK(isolate, Local<v8::RegExp>());
return Utils::ToLocal(i::Handle<i::JSRegExp>::cast(obj));
}
Local<v8::String> v8::RegExp::GetSource() const {
i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
return Utils::ToLocal(i::Handle<i::String>(obj->Pattern()));
}
// Assert that the static flags cast in GetFlags is valid.
#define REGEXP_FLAG_ASSERT_EQ(api_flag, internal_flag) \
STATIC_ASSERT(static_cast<int>(v8::RegExp::api_flag) == \
static_cast<int>(i::JSRegExp::internal_flag))
REGEXP_FLAG_ASSERT_EQ(kNone, NONE);
REGEXP_FLAG_ASSERT_EQ(kGlobal, GLOBAL);
REGEXP_FLAG_ASSERT_EQ(kIgnoreCase, IGNORE_CASE);
REGEXP_FLAG_ASSERT_EQ(kMultiline, MULTILINE);
#undef REGEXP_FLAG_ASSERT_EQ
v8::RegExp::Flags v8::RegExp::GetFlags() const {
i::Handle<i::JSRegExp> obj = Utils::OpenHandle(this);
return static_cast<RegExp::Flags>(obj->GetFlags().value());
}
Local<v8::Array> v8::Array::New(Isolate* isolate, int length) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "Array::New");
ENTER_V8(i_isolate);
int real_length = length > 0 ? length : 0;
i::Handle<i::JSArray> obj = i_isolate->factory()->NewJSArray(real_length);
i::Handle<i::Object> length_obj =
i_isolate->factory()->NewNumberFromInt(real_length);
obj->set_length(*length_obj);
return Utils::ToLocal(obj);
}
uint32_t v8::Array::Length() const {
i::Handle<i::JSArray> obj = Utils::OpenHandle(this);
i::Object* length = obj->length();
if (length->IsSmi()) {
return i::Smi::cast(length)->value();
} else {
return static_cast<uint32_t>(length->Number());
}
}
Local<Object> Array::CloneElementAt(uint32_t index) {
i::Isolate* isolate = Utils::OpenHandle(this)->GetIsolate();
ON_BAILOUT(isolate, "v8::Array::CloneElementAt()", return Local<Object>());
i::Handle<i::JSObject> self = Utils::OpenHandle(this);
if (!self->HasFastObjectElements()) {
return Local<Object>();
}
i::FixedArray* elms = i::FixedArray::cast(self->elements());
i::Object* paragon = elms->get(index);
if (!paragon->IsJSObject()) {
return Local<Object>();
}
i::Handle<i::JSObject> paragon_handle(i::JSObject::cast(paragon));
EXCEPTION_PREAMBLE(isolate);
ENTER_V8(isolate);
i::Handle<i::JSObject> result =
isolate->factory()->CopyJSObject(paragon_handle);
has_pending_exception = result.is_null();
EXCEPTION_BAILOUT_CHECK(isolate, Local<Object>());
return Utils::ToLocal(result);
}
bool Value::IsPromise() const {
i::Handle<i::Object> val = Utils::OpenHandle(this);
if (!val->IsJSObject()) return false;
i::Handle<i::JSObject> obj = i::Handle<i::JSObject>::cast(val);
i::Isolate* isolate = obj->GetIsolate();
LOG_API(isolate, "IsPromise");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> argv[] = { obj };
i::Handle<i::Object> b;
has_pending_exception = !i::Execution::Call(
isolate,
isolate->is_promise(),
isolate->factory()->undefined_value(),
arraysize(argv), argv,
false).ToHandle(&b);
EXCEPTION_BAILOUT_CHECK(isolate, false);
return b->BooleanValue();
}
Local<Promise::Resolver> Promise::Resolver::New(Isolate* v8_isolate) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
LOG_API(isolate, "Promise::Resolver::New");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> result;
has_pending_exception = !i::Execution::Call(
isolate,
isolate->promise_create(),
isolate->factory()->undefined_value(),
0, NULL,
false).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Promise::Resolver>());
return Local<Promise::Resolver>::Cast(Utils::ToLocal(result));
}
Local<Promise> Promise::Resolver::GetPromise() {
i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
return Local<Promise>::Cast(Utils::ToLocal(promise));
}
void Promise::Resolver::Resolve(Handle<Value> value) {
i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
i::Isolate* isolate = promise->GetIsolate();
LOG_API(isolate, "Promise::Resolver::Resolve");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> argv[] = { promise, Utils::OpenHandle(*value) };
has_pending_exception = i::Execution::Call(
isolate,
isolate->promise_resolve(),
isolate->factory()->undefined_value(),
arraysize(argv), argv,
false).is_null();
EXCEPTION_BAILOUT_CHECK(isolate, /* void */ ;);
}
void Promise::Resolver::Reject(Handle<Value> value) {
i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
i::Isolate* isolate = promise->GetIsolate();
LOG_API(isolate, "Promise::Resolver::Reject");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> argv[] = { promise, Utils::OpenHandle(*value) };
has_pending_exception = i::Execution::Call(
isolate,
isolate->promise_reject(),
isolate->factory()->undefined_value(),
arraysize(argv), argv,
false).is_null();
EXCEPTION_BAILOUT_CHECK(isolate, /* void */ ;);
}
Local<Promise> Promise::Chain(Handle<Function> handler) {
i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
i::Isolate* isolate = promise->GetIsolate();
LOG_API(isolate, "Promise::Chain");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
i::Handle<i::Object> result;
has_pending_exception = !i::Execution::Call(
isolate,
isolate->promise_chain(),
promise,
arraysize(argv), argv,
false).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Promise>());
return Local<Promise>::Cast(Utils::ToLocal(result));
}
Local<Promise> Promise::Catch(Handle<Function> handler) {
i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
i::Isolate* isolate = promise->GetIsolate();
LOG_API(isolate, "Promise::Catch");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
i::Handle<i::Object> result;
has_pending_exception = !i::Execution::Call(
isolate,
isolate->promise_catch(),
promise,
arraysize(argv), argv,
false).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Promise>());
return Local<Promise>::Cast(Utils::ToLocal(result));
}
Local<Promise> Promise::Then(Handle<Function> handler) {
i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
i::Isolate* isolate = promise->GetIsolate();
LOG_API(isolate, "Promise::Then");
ENTER_V8(isolate);
EXCEPTION_PREAMBLE(isolate);
i::Handle<i::Object> argv[] = { Utils::OpenHandle(*handler) };
i::Handle<i::Object> result;
has_pending_exception = !i::Execution::Call(
isolate,
isolate->promise_then(),
promise,
arraysize(argv), argv,
false).ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Promise>());
return Local<Promise>::Cast(Utils::ToLocal(result));
}
bool Promise::HasHandler() {
i::Handle<i::JSObject> promise = Utils::OpenHandle(this);
i::Isolate* isolate = promise->GetIsolate();
LOG_API(isolate, "Promise::HasRejectHandler");
ENTER_V8(isolate);
i::Handle<i::Symbol> key = isolate->factory()->promise_has_handler_symbol();
return i::JSObject::GetDataProperty(promise, key)->IsTrue();
}
bool v8::ArrayBuffer::IsExternal() const {
return Utils::OpenHandle(this)->is_external();
}
v8::ArrayBuffer::Contents v8::ArrayBuffer::Externalize() {
i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
Utils::ApiCheck(!obj->is_external(),
"v8::ArrayBuffer::Externalize",
"ArrayBuffer already externalized");
obj->set_is_external(true);
size_t byte_length = static_cast<size_t>(obj->byte_length()->Number());
Contents contents;
contents.data_ = obj->backing_store();
contents.byte_length_ = byte_length;
return contents;
}
void v8::ArrayBuffer::Neuter() {
i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
i::Isolate* isolate = obj->GetIsolate();
Utils::ApiCheck(obj->is_external(),
"v8::ArrayBuffer::Neuter",
"Only externalized ArrayBuffers can be neutered");
LOG_API(obj->GetIsolate(), "v8::ArrayBuffer::Neuter()");
ENTER_V8(isolate);
i::Runtime::NeuterArrayBuffer(obj);
}
size_t v8::ArrayBuffer::ByteLength() const {
i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(this);
return static_cast<size_t>(obj->byte_length()->Number());
}
Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, size_t byte_length) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "v8::ArrayBuffer::New(size_t)");
ENTER_V8(i_isolate);
i::Handle<i::JSArrayBuffer> obj =
i_isolate->factory()->NewJSArrayBuffer();
i::Runtime::SetupArrayBufferAllocatingData(i_isolate, obj, byte_length);
return Utils::ToLocal(obj);
}
Local<ArrayBuffer> v8::ArrayBuffer::New(Isolate* isolate, void* data,
size_t byte_length) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "v8::ArrayBuffer::New(void*, size_t)");
ENTER_V8(i_isolate);
i::Handle<i::JSArrayBuffer> obj =
i_isolate->factory()->NewJSArrayBuffer();
i::Runtime::SetupArrayBuffer(i_isolate, obj, true, data, byte_length);
return Utils::ToLocal(obj);
}
Local<ArrayBuffer> v8::ArrayBufferView::Buffer() {
i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
i::Handle<i::JSArrayBuffer> buffer;
if (obj->IsJSDataView()) {
i::Handle<i::JSDataView> data_view(i::JSDataView::cast(*obj));
DCHECK(data_view->buffer()->IsJSArrayBuffer());
buffer = i::handle(i::JSArrayBuffer::cast(data_view->buffer()));
} else {
DCHECK(obj->IsJSTypedArray());
buffer = i::JSTypedArray::cast(*obj)->GetBuffer();
}
return Utils::ToLocal(buffer);
}
size_t v8::ArrayBufferView::ByteOffset() {
i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
return static_cast<size_t>(obj->byte_offset()->Number());
}
size_t v8::ArrayBufferView::ByteLength() {
i::Handle<i::JSArrayBufferView> obj = Utils::OpenHandle(this);
return static_cast<size_t>(obj->byte_length()->Number());
}
size_t v8::TypedArray::Length() {
i::Handle<i::JSTypedArray> obj = Utils::OpenHandle(this);
return static_cast<size_t>(obj->length()->Number());
}
static inline void SetupArrayBufferView(
i::Isolate* isolate,
i::Handle<i::JSArrayBufferView> obj,
i::Handle<i::JSArrayBuffer> buffer,
size_t byte_offset,
size_t byte_length) {
DCHECK(byte_offset + byte_length <=
static_cast<size_t>(buffer->byte_length()->Number()));
obj->set_buffer(*buffer);
obj->set_weak_next(buffer->weak_first_view());
buffer->set_weak_first_view(*obj);
i::Handle<i::Object> byte_offset_object =
isolate->factory()->NewNumberFromSize(byte_offset);
obj->set_byte_offset(*byte_offset_object);
i::Handle<i::Object> byte_length_object =
isolate->factory()->NewNumberFromSize(byte_length);
obj->set_byte_length(*byte_length_object);
}
template<typename ElementType,
ExternalArrayType array_type,
i::ElementsKind elements_kind>
i::Handle<i::JSTypedArray> NewTypedArray(
i::Isolate* isolate,
Handle<ArrayBuffer> array_buffer, size_t byte_offset, size_t length) {
i::Handle<i::JSTypedArray> obj =
isolate->factory()->NewJSTypedArray(array_type);
i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
DCHECK(byte_offset % sizeof(ElementType) == 0);
CHECK(length <= (std::numeric_limits<size_t>::max() / sizeof(ElementType)));
CHECK(length <= static_cast<size_t>(i::Smi::kMaxValue));
size_t byte_length = length * sizeof(ElementType);
SetupArrayBufferView(
isolate, obj, buffer, byte_offset, byte_length);
i::Handle<i::Object> length_object =
isolate->factory()->NewNumberFromSize(length);
obj->set_length(*length_object);
i::Handle<i::ExternalArray> elements =
isolate->factory()->NewExternalArray(
static_cast<int>(length), array_type,
static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
i::Handle<i::Map> map =
i::JSObject::GetElementsTransitionMap(obj, elements_kind);
i::JSObject::SetMapAndElements(obj, map, elements);
return obj;
}
#define TYPED_ARRAY_NEW(Type, type, TYPE, ctype, size) \
Local<Type##Array> Type##Array::New(Handle<ArrayBuffer> array_buffer, \
size_t byte_offset, size_t length) { \
i::Isolate* isolate = Utils::OpenHandle(*array_buffer)->GetIsolate(); \
LOG_API(isolate, \
"v8::" #Type "Array::New(Handle<ArrayBuffer>, size_t, size_t)"); \
ENTER_V8(isolate); \
if (!Utils::ApiCheck(length <= static_cast<size_t>(i::Smi::kMaxValue), \
"v8::" #Type "Array::New(Handle<ArrayBuffer>, size_t, size_t)", \
"length exceeds max allowed value")) { \
return Local<Type##Array>(); \
} \
i::Handle<i::JSTypedArray> obj = \
NewTypedArray<ctype, v8::kExternal##Type##Array, \
i::EXTERNAL_##TYPE##_ELEMENTS>( \
isolate, array_buffer, byte_offset, length); \
return Utils::ToLocal##Type##Array(obj); \
}
TYPED_ARRAYS(TYPED_ARRAY_NEW)
#undef TYPED_ARRAY_NEW
Local<DataView> DataView::New(Handle<ArrayBuffer> array_buffer,
size_t byte_offset, size_t byte_length) {
i::Handle<i::JSArrayBuffer> buffer = Utils::OpenHandle(*array_buffer);
i::Isolate* isolate = buffer->GetIsolate();
LOG_API(isolate, "v8::DataView::New(void*, size_t, size_t)");
ENTER_V8(isolate);
i::Handle<i::JSDataView> obj = isolate->factory()->NewJSDataView();
SetupArrayBufferView(
isolate, obj, buffer, byte_offset, byte_length);
return Utils::ToLocal(obj);
}
Local<Symbol> v8::Symbol::New(Isolate* isolate, Local<String> name) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "Symbol::New()");
ENTER_V8(i_isolate);
i::Handle<i::Symbol> result = i_isolate->factory()->NewSymbol();
if (!name.IsEmpty()) result->set_name(*Utils::OpenHandle(*name));
return Utils::ToLocal(result);
}
static i::Handle<i::Symbol> SymbolFor(i::Isolate* isolate,
i::Handle<i::String> name,
i::Handle<i::String> part) {
i::Handle<i::JSObject> registry = isolate->GetSymbolRegistry();
i::Handle<i::JSObject> symbols =
i::Handle<i::JSObject>::cast(
i::Object::GetPropertyOrElement(registry, part).ToHandleChecked());
i::Handle<i::Object> symbol =
i::Object::GetPropertyOrElement(symbols, name).ToHandleChecked();
if (!symbol->IsSymbol()) {
DCHECK(symbol->IsUndefined());
symbol = isolate->factory()->NewSymbol();
i::Handle<i::Symbol>::cast(symbol)->set_name(*name);
i::JSObject::SetProperty(symbols, name, symbol, i::STRICT).Assert();
}
return i::Handle<i::Symbol>::cast(symbol);
}
Local<Symbol> v8::Symbol::For(Isolate* isolate, Local<String> name) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i::Handle<i::String> i_name = Utils::OpenHandle(*name);
i::Handle<i::String> part = i_isolate->factory()->for_string();
return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
}
Local<Symbol> v8::Symbol::ForApi(Isolate* isolate, Local<String> name) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i::Handle<i::String> i_name = Utils::OpenHandle(*name);
i::Handle<i::String> part = i_isolate->factory()->for_api_string();
return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
}
static Local<Symbol> GetWellKnownSymbol(Isolate* isolate, const char* name) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i::Handle<i::String> i_name =
Utils::OpenHandle(*String::NewFromUtf8(isolate, name));
i::Handle<i::String> part = i_isolate->factory()->for_intern_string();
return Utils::ToLocal(SymbolFor(i_isolate, i_name, part));
}
Local<Symbol> v8::Symbol::GetIterator(Isolate* isolate) {
return GetWellKnownSymbol(isolate, "Symbol.iterator");
}
Local<Symbol> v8::Symbol::GetUnscopables(Isolate* isolate) {
return GetWellKnownSymbol(isolate, "Symbol.unscopables");
}
Local<Private> v8::Private::New(Isolate* isolate, Local<String> name) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
LOG_API(i_isolate, "Private::New()");
ENTER_V8(i_isolate);
i::Handle<i::Symbol> symbol = i_isolate->factory()->NewPrivateSymbol();
if (!name.IsEmpty()) symbol->set_name(*Utils::OpenHandle(*name));
Local<Symbol> result = Utils::ToLocal(symbol);
return v8::Handle<Private>(reinterpret_cast<Private*>(*result));
}
Local<Private> v8::Private::ForApi(Isolate* isolate, Local<String> name) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i::Handle<i::String> i_name = Utils::OpenHandle(*name);
i::Handle<i::JSObject> registry = i_isolate->GetSymbolRegistry();
i::Handle<i::String> part = i_isolate->factory()->private_api_string();
i::Handle<i::JSObject> privates =
i::Handle<i::JSObject>::cast(
i::Object::GetPropertyOrElement(registry, part).ToHandleChecked());
i::Handle<i::Object> symbol =
i::Object::GetPropertyOrElement(privates, i_name).ToHandleChecked();
if (!symbol->IsSymbol()) {
DCHECK(symbol->IsUndefined());
symbol = i_isolate->factory()->NewPrivateSymbol();
i::Handle<i::Symbol>::cast(symbol)->set_name(*i_name);
i::JSObject::SetProperty(privates, i_name, symbol, i::STRICT).Assert();
}
Local<Symbol> result = Utils::ToLocal(i::Handle<i::Symbol>::cast(symbol));
return v8::Handle<Private>(reinterpret_cast<Private*>(*result));
}
Local<Number> v8::Number::New(Isolate* isolate, double value) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
DCHECK(internal_isolate->IsInitialized());
if (std::isnan(value)) {
// Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
value = base::OS::nan_value();
}
ENTER_V8(internal_isolate);
i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
return Utils::NumberToLocal(result);
}
Local<Integer> v8::Integer::New(Isolate* isolate, int32_t value) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
DCHECK(internal_isolate->IsInitialized());
if (i::Smi::IsValid(value)) {
return Utils::IntegerToLocal(i::Handle<i::Object>(i::Smi::FromInt(value),
internal_isolate));
}
ENTER_V8(internal_isolate);
i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
return Utils::IntegerToLocal(result);
}
Local<Integer> v8::Integer::NewFromUnsigned(Isolate* isolate, uint32_t value) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
DCHECK(internal_isolate->IsInitialized());
bool fits_into_int32_t = (value & (1 << 31)) == 0;
if (fits_into_int32_t) {
return Integer::New(isolate, static_cast<int32_t>(value));
}
ENTER_V8(internal_isolate);
i::Handle<i::Object> result = internal_isolate->factory()->NewNumber(value);
return Utils::IntegerToLocal(result);
}
bool V8::AddMessageListener(MessageCallback that, Handle<Value> data) {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "v8::V8::AddMessageListener()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
NeanderArray listeners(isolate->factory()->message_listeners());
NeanderObject obj(isolate, 2);
obj.set(0, *isolate->factory()->NewForeign(FUNCTION_ADDR(that)));
obj.set(1, data.IsEmpty() ? isolate->heap()->undefined_value()
: *Utils::OpenHandle(*data));
listeners.add(obj.value());
return true;
}
void V8::RemoveMessageListeners(MessageCallback that) {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "v8::V8::RemoveMessageListeners()", return);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
NeanderArray listeners(isolate->factory()->message_listeners());
for (int i = 0; i < listeners.length(); i++) {
if (listeners.get(i)->IsUndefined()) continue; // skip deleted ones
NeanderObject listener(i::JSObject::cast(listeners.get(i)));
i::Handle<i::Foreign> callback_obj(i::Foreign::cast(listener.get(0)));
if (callback_obj->foreign_address() == FUNCTION_ADDR(that)) {
listeners.set(i, isolate->heap()->undefined_value());
}
}
}
void V8::SetCaptureStackTraceForUncaughtExceptions(
bool capture,
int frame_limit,
StackTrace::StackTraceOptions options) {
i::Isolate::Current()->SetCaptureStackTraceForUncaughtExceptions(
capture,
frame_limit,
options);
}
void V8::SetFailedAccessCheckCallbackFunction(
FailedAccessCheckCallback callback) {
i::Isolate* isolate = i::Isolate::Current();
isolate->SetFailedAccessCheckCallback(callback);
}
void Isolate::CollectAllGarbage(const char* gc_reason) {
reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
i::Heap::kNoGCFlags, gc_reason);
}
HeapProfiler* Isolate::GetHeapProfiler() {
i::HeapProfiler* heap_profiler =
reinterpret_cast<i::Isolate*>(this)->heap_profiler();
return reinterpret_cast<HeapProfiler*>(heap_profiler);
}
CpuProfiler* Isolate::GetCpuProfiler() {
i::CpuProfiler* cpu_profiler =
reinterpret_cast<i::Isolate*>(this)->cpu_profiler();
return reinterpret_cast<CpuProfiler*>(cpu_profiler);
}
bool Isolate::InContext() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
return isolate->context() != NULL;
}
v8::Local<v8::Context> Isolate::GetCurrentContext() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
i::Context* context = isolate->context();
if (context == NULL) return Local<Context>();
i::Context* native_context = context->native_context();
if (native_context == NULL) return Local<Context>();
return Utils::ToLocal(i::Handle<i::Context>(native_context));
}
v8::Local<v8::Context> Isolate::GetCallingContext() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
i::Handle<i::Object> calling = isolate->GetCallingNativeContext();
if (calling.is_null()) return Local<Context>();
return Utils::ToLocal(i::Handle<i::Context>::cast(calling));
}
v8::Local<v8::Context> Isolate::GetEnteredContext() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
i::Handle<i::Object> last =
isolate->handle_scope_implementer()->LastEnteredContext();
if (last.is_null()) return Local<Context>();
return Utils::ToLocal(i::Handle<i::Context>::cast(last));
}
v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
ENTER_V8(isolate);
// If we're passed an empty handle, we throw an undefined exception
// to deal more gracefully with out of memory situations.
if (value.IsEmpty()) {
isolate->ScheduleThrow(isolate->heap()->undefined_value());
} else {
isolate->ScheduleThrow(*Utils::OpenHandle(*value));
}
return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
void Isolate::SetObjectGroupId(internal::Object** object, UniqueId id) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
internal_isolate->global_handles()->SetObjectGroupId(
v8::internal::Handle<v8::internal::Object>(object).location(),
id);
}
void Isolate::SetReferenceFromGroup(UniqueId id, internal::Object** object) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
internal_isolate->global_handles()->SetReferenceFromGroup(
id,
v8::internal::Handle<v8::internal::Object>(object).location());
}
void Isolate::SetReference(internal::Object** parent,
internal::Object** child) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(this);
i::Object** parent_location =
v8::internal::Handle<v8::internal::Object>(parent).location();
internal_isolate->global_handles()->SetReference(
reinterpret_cast<i::HeapObject**>(parent_location),
v8::internal::Handle<v8::internal::Object>(child).location());
}
void Isolate::AddGCPrologueCallback(GCPrologueCallback callback,
GCType gc_type) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->heap()->AddGCPrologueCallback(callback, gc_type);
}
void Isolate::RemoveGCPrologueCallback(GCPrologueCallback callback) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->heap()->RemoveGCPrologueCallback(callback);
}
void Isolate::AddGCEpilogueCallback(GCEpilogueCallback callback,
GCType gc_type) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->heap()->AddGCEpilogueCallback(callback, gc_type);
}
void Isolate::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->heap()->RemoveGCEpilogueCallback(callback);
}
void V8::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
i::Isolate* isolate = i::Isolate::Current();
isolate->heap()->AddGCPrologueCallback(
reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback),
gc_type,
false);
}
void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
i::Isolate* isolate = i::Isolate::Current();
isolate->heap()->RemoveGCPrologueCallback(
reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
}
void V8::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
i::Isolate* isolate = i::Isolate::Current();
isolate->heap()->AddGCEpilogueCallback(
reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback),
gc_type,
false);
}
void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
i::Isolate* isolate = i::Isolate::Current();
isolate->heap()->RemoveGCEpilogueCallback(
reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
}
void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
ObjectSpace space,
AllocationAction action) {
i::Isolate* isolate = i::Isolate::Current();
isolate->memory_allocator()->AddMemoryAllocationCallback(
callback, space, action);
}
void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
i::Isolate* isolate = i::Isolate::Current();
isolate->memory_allocator()->RemoveMemoryAllocationCallback(
callback);
}
void V8::TerminateExecution(Isolate* isolate) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i_isolate->stack_guard()->RequestTerminateExecution();
}
bool V8::IsExecutionTerminating(Isolate* isolate) {
i::Isolate* i_isolate = isolate != NULL ?
reinterpret_cast<i::Isolate*>(isolate) : i::Isolate::Current();
return IsExecutionTerminatingCheck(i_isolate);
}
void V8::CancelTerminateExecution(Isolate* isolate) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i_isolate->stack_guard()->ClearTerminateExecution();
i_isolate->CancelTerminateExecution();
}
void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
i_isolate->set_api_interrupt_callback(callback);
i_isolate->set_api_interrupt_callback_data(data);
i_isolate->stack_guard()->RequestApiInterrupt();
}
void Isolate::ClearInterrupt() {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
i_isolate->stack_guard()->ClearApiInterrupt();
i_isolate->set_api_interrupt_callback(NULL);
i_isolate->set_api_interrupt_callback_data(NULL);
}
void Isolate::RequestGarbageCollectionForTesting(GarbageCollectionType type) {
CHECK(i::FLAG_expose_gc);
if (type == kMinorGarbageCollection) {
reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
i::NEW_SPACE, "Isolate::RequestGarbageCollection",
kGCCallbackFlagForced);
} else {
DCHECK_EQ(kFullGarbageCollection, type);
reinterpret_cast<i::Isolate*>(this)->heap()->CollectAllGarbage(
i::Heap::kAbortIncrementalMarkingMask,
"Isolate::RequestGarbageCollection", kGCCallbackFlagForced);
}
}
Isolate* Isolate::GetCurrent() {
i::Isolate* isolate = i::Isolate::Current();
return reinterpret_cast<Isolate*>(isolate);
}
Isolate* Isolate::New(const Isolate::CreateParams& params) {
i::Isolate* isolate = new i::Isolate();
Isolate* v8_isolate = reinterpret_cast<Isolate*>(isolate);
if (params.entry_hook) {
isolate->set_function_entry_hook(params.entry_hook);
}
if (params.code_event_handler) {
isolate->InitializeLoggingAndCounters();
isolate->logger()->SetCodeEventHandler(kJitCodeEventDefault,
params.code_event_handler);
}
SetResourceConstraints(isolate, params.constraints);
if (params.enable_serializer) {
isolate->enable_serializer();
}
// TODO(jochen): Once we got rid of Isolate::Current(), we can remove this.
Isolate::Scope isolate_scope(v8_isolate);
if (params.entry_hook || !i::Snapshot::Initialize(isolate)) {
// If the isolate has a function entry hook, it needs to re-build all its
// code stubs with entry hooks embedded, so don't deserialize a snapshot.
isolate->Init(NULL);
}
return v8_isolate;
}
void Isolate::Dispose() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
if (!Utils::ApiCheck(!isolate->IsInUse(),
"v8::Isolate::Dispose()",
"Disposing the isolate that is entered by a thread.")) {
return;
}
isolate->TearDown();
}
void Isolate::Enter() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->Enter();
}
void Isolate::Exit() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->Exit();
}
Isolate::DisallowJavascriptExecutionScope::DisallowJavascriptExecutionScope(
Isolate* isolate,
Isolate::DisallowJavascriptExecutionScope::OnFailure on_failure)
: on_failure_(on_failure) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
if (on_failure_ == CRASH_ON_FAILURE) {
internal_ = reinterpret_cast<void*>(
new i::DisallowJavascriptExecution(i_isolate));
} else {
DCHECK_EQ(THROW_ON_FAILURE, on_failure);
internal_ = reinterpret_cast<void*>(
new i::ThrowOnJavascriptExecution(i_isolate));
}
}
Isolate::DisallowJavascriptExecutionScope::~DisallowJavascriptExecutionScope() {
if (on_failure_ == CRASH_ON_FAILURE) {
delete reinterpret_cast<i::DisallowJavascriptExecution*>(internal_);
} else {
delete reinterpret_cast<i::ThrowOnJavascriptExecution*>(internal_);
}
}
Isolate::AllowJavascriptExecutionScope::AllowJavascriptExecutionScope(
Isolate* isolate) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
internal_assert_ = reinterpret_cast<void*>(
new i::AllowJavascriptExecution(i_isolate));
internal_throws_ = reinterpret_cast<void*>(
new i::NoThrowOnJavascriptExecution(i_isolate));
}
Isolate::AllowJavascriptExecutionScope::~AllowJavascriptExecutionScope() {
delete reinterpret_cast<i::AllowJavascriptExecution*>(internal_assert_);
delete reinterpret_cast<i::NoThrowOnJavascriptExecution*>(internal_throws_);
}
Isolate::SuppressMicrotaskExecutionScope::SuppressMicrotaskExecutionScope(
Isolate* isolate)
: isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
isolate_->handle_scope_implementer()->IncrementCallDepth();
}
Isolate::SuppressMicrotaskExecutionScope::~SuppressMicrotaskExecutionScope() {
isolate_->handle_scope_implementer()->DecrementCallDepth();
}
void Isolate::GetHeapStatistics(HeapStatistics* heap_statistics) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
if (!isolate->IsInitialized()) {
heap_statistics->total_heap_size_ = 0;
heap_statistics->total_heap_size_executable_ = 0;
heap_statistics->total_physical_size_ = 0;
heap_statistics->used_heap_size_ = 0;
heap_statistics->heap_size_limit_ = 0;
return;
}
i::Heap* heap = isolate->heap();
heap_statistics->total_heap_size_ = heap->CommittedMemory();
heap_statistics->total_heap_size_executable_ =
heap->CommittedMemoryExecutable();
heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
heap_statistics->used_heap_size_ = heap->SizeOfObjects();
heap_statistics->heap_size_limit_ = heap->MaxReserved();
}
void Isolate::GetStackSample(const RegisterState& state, void** frames,
size_t frames_limit, SampleInfo* sample_info) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
i::TickSample::GetStackSample(isolate, state, frames, frames_limit,
sample_info);
}
void Isolate::SetEventLogger(LogEventCallback that) {
// Do not overwrite the event logger if we want to log explicitly.
if (i::FLAG_log_timer_events) return;
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->set_event_logger(that);
}
void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
if (callback == NULL) return;
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->AddCallCompletedCallback(callback);
}
void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->RemoveCallCompletedCallback(callback);
}
void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
if (callback == NULL) return;
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->SetPromiseRejectCallback(callback);
}
void Isolate::RunMicrotasks() {
reinterpret_cast<i::Isolate*>(this)->RunMicrotasks();
}
void Isolate::EnqueueMicrotask(Handle<Function> microtask) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->EnqueueMicrotask(Utils::OpenHandle(*microtask));
}
void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
i::HandleScope scope(isolate);
i::Handle<i::CallHandlerInfo> callback_info =
i::Handle<i::CallHandlerInfo>::cast(
isolate->factory()->NewStruct(i::CALL_HANDLER_INFO_TYPE));
SET_FIELD_WRAPPED(callback_info, set_callback, microtask);
SET_FIELD_WRAPPED(callback_info, set_data, data);
isolate->EnqueueMicrotask(callback_info);
}
void Isolate::SetAutorunMicrotasks(bool autorun) {
reinterpret_cast<i::Isolate*>(this)->set_autorun_microtasks(autorun);
}
bool Isolate::WillAutorunMicrotasks() const {
return reinterpret_cast<const i::Isolate*>(this)->autorun_microtasks();
}
void Isolate::SetUseCounterCallback(UseCounterCallback callback) {
reinterpret_cast<i::Isolate*>(this)->SetUseCounterCallback(callback);
}
void Isolate::SetCounterFunction(CounterLookupCallback callback) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->stats_table()->SetCounterFunction(callback);
isolate->InitializeLoggingAndCounters();
isolate->counters()->ResetCounters();
}
void Isolate::SetCreateHistogramFunction(CreateHistogramCallback callback) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
isolate->stats_table()->SetCreateHistogramFunction(callback);
isolate->InitializeLoggingAndCounters();
isolate->counters()->ResetHistograms();
}
void Isolate::SetAddHistogramSampleFunction(
AddHistogramSampleCallback callback) {
reinterpret_cast<i::Isolate*>(this)
->stats_table()
->SetAddHistogramSampleFunction(callback);
}
bool v8::Isolate::IdleNotification(int idle_time_in_ms) {
// Returning true tells the caller that it need not
// continue to call IdleNotification.
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
if (!i::FLAG_use_idle_notification) return true;
return isolate->heap()->IdleNotification(idle_time_in_ms);
}
void v8::Isolate::LowMemoryNotification() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
{
i::HistogramTimerScope idle_notification_scope(
isolate->counters()->gc_low_memory_notification());
isolate->heap()->CollectAllAvailableGarbage("low memory notification");
}
}
int v8::Isolate::ContextDisposedNotification() {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
return isolate->heap()->NotifyContextDisposed();
}
void v8::Isolate::SetJitCodeEventHandler(JitCodeEventOptions options,
JitCodeEventHandler event_handler) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
// Ensure that logging is initialized for our isolate.
isolate->InitializeLoggingAndCounters();
isolate->logger()->SetCodeEventHandler(options, event_handler);
}
void v8::Isolate::SetStackLimit(uintptr_t stack_limit) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
CHECK(stack_limit);
isolate->stack_guard()->SetStackLimit(stack_limit);
}
void v8::Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
if (isolate->code_range()->valid()) {
*start = isolate->code_range()->start();
*length_in_bytes = isolate->code_range()->size();
} else {
*start = NULL;
*length_in_bytes = 0;
}
}
String::Utf8Value::Utf8Value(v8::Handle<v8::Value> obj)
: str_(NULL), length_(0) {
i::Isolate* isolate = i::Isolate::Current();
if (obj.IsEmpty()) return;
ENTER_V8(isolate);
i::HandleScope scope(isolate);
TryCatch try_catch;
Handle<String> str = obj->ToString();
if (str.IsEmpty()) return;
i::Handle<i::String> i_str = Utils::OpenHandle(*str);
length_ = v8::Utf8Length(*i_str, isolate);
str_ = i::NewArray<char>(length_ + 1);
str->WriteUtf8(str_);
}
String::Utf8Value::~Utf8Value() {
i::DeleteArray(str_);
}
String::Value::Value(v8::Handle<v8::Value> obj)
: str_(NULL), length_(0) {
i::Isolate* isolate = i::Isolate::Current();
if (obj.IsEmpty()) return;
ENTER_V8(isolate);
i::HandleScope scope(isolate);
TryCatch try_catch;
Handle<String> str = obj->ToString();
if (str.IsEmpty()) return;
length_ = str->Length();
str_ = i::NewArray<uint16_t>(length_ + 1);
str->Write(str_);
}
String::Value::~Value() {
i::DeleteArray(str_);
}
#define DEFINE_ERROR(NAME) \
Local<Value> Exception::NAME(v8::Handle<v8::String> raw_message) { \
i::Isolate* isolate = i::Isolate::Current(); \
LOG_API(isolate, #NAME); \
ON_BAILOUT(isolate, "v8::Exception::" #NAME "()", return Local<Value>()); \
ENTER_V8(isolate); \
i::Object* error; \
{ \
i::HandleScope scope(isolate); \
i::Handle<i::String> message = Utils::OpenHandle(*raw_message); \
i::Handle<i::Object> result; \
EXCEPTION_PREAMBLE(isolate); \
i::MaybeHandle<i::Object> maybe_result = \
isolate->factory()->New##NAME(message); \
has_pending_exception = !maybe_result.ToHandle(&result); \
/* TODO(yangguo): crbug/403509. Return empty handle instead. */ \
EXCEPTION_BAILOUT_CHECK( \
isolate, v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate))); \
error = *result; \
} \
i::Handle<i::Object> result(error, isolate); \
return Utils::ToLocal(result); \
}
DEFINE_ERROR(RangeError)
DEFINE_ERROR(ReferenceError)
DEFINE_ERROR(SyntaxError)
DEFINE_ERROR(TypeError)
DEFINE_ERROR(Error)
#undef DEFINE_ERROR
// --- D e b u g S u p p o r t ---
bool Debug::SetDebugEventListener(EventCallback that, Handle<Value> data) {
i::Isolate* isolate = i::Isolate::Current();
ON_BAILOUT(isolate, "v8::Debug::SetDebugEventListener()", return false);
ENTER_V8(isolate);
i::HandleScope scope(isolate);
i::Handle<i::Object> foreign = isolate->factory()->undefined_value();
if (that != NULL) {
foreign = isolate->factory()->NewForeign(FUNCTION_ADDR(that));
}
isolate->debug()->SetEventListener(foreign,
Utils::OpenHandle(*data, true));
return true;
}
void Debug::DebugBreak(Isolate* isolate) {
reinterpret_cast<i::Isolate*>(isolate)->stack_guard()->RequestDebugBreak();
}
void Debug::CancelDebugBreak(Isolate* isolate) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
internal_isolate->stack_guard()->ClearDebugBreak();
}
bool Debug::CheckDebugBreak(Isolate* isolate) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
return internal_isolate->stack_guard()->CheckDebugBreak();
}
void Debug::DebugBreakForCommand(Isolate* isolate, ClientData* data) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
internal_isolate->debug()->EnqueueDebugCommand(data);
}
void Debug::SetMessageHandler(v8::Debug::MessageHandler handler) {
i::Isolate* isolate = i::Isolate::Current();
ENTER_V8(isolate);
isolate->debug()->SetMessageHandler(handler);
}
void Debug::SendCommand(Isolate* isolate,
const uint16_t* command,
int length,
ClientData* client_data) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
internal_isolate->debug()->EnqueueCommandMessage(
i::Vector<const uint16_t>(command, length), client_data);
}
Local<Value> Debug::Call(v8::Handle<v8::Function> fun,
v8::Handle<v8::Value> data) {
i::Isolate* isolate = i::Isolate::Current();
if (!isolate->IsInitialized()) return Local<Value>();
ON_BAILOUT(isolate, "v8::Debug::Call()", return Local<Value>());
ENTER_V8(isolate);
i::MaybeHandle<i::Object> maybe_result;
EXCEPTION_PREAMBLE(isolate);
if (data.IsEmpty()) {
maybe_result = isolate->debug()->Call(
Utils::OpenHandle(*fun), isolate->factory()->undefined_value());
} else {
maybe_result = isolate->debug()->Call(
Utils::OpenHandle(*fun), Utils::OpenHandle(*data));
}
i::Handle<i::Object> result;
has_pending_exception = !maybe_result.ToHandle(&result);
EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
return Utils::ToLocal(result);
}
Local<Value> Debug::GetMirror(v8::Handle<v8::Value> obj) {
i::Isolate* isolate = i::Isolate::Current();
if (!isolate->IsInitialized()) return Local<Value>();
ON_BAILOUT(isolate, "v8::Debug::GetMirror()", return Local<Value>());
ENTER_V8(isolate);
v8::EscapableHandleScope scope(reinterpret_cast<Isolate*>(isolate));
i::Debug* isolate_debug = isolate->debug();
EXCEPTION_PREAMBLE(isolate);
has_pending_exception = !isolate_debug->Load();
v8::Local<v8::Value> result;
if (!has_pending_exception) {
i::Handle<i::JSObject> debug(
isolate_debug->debug_context()->global_object());
i::Handle<i::String> name = isolate->factory()->InternalizeOneByteString(
STATIC_CHAR_VECTOR("MakeMirror"));
i::Handle<i::Object> fun_obj =
i::Object::GetProperty(debug, name).ToHandleChecked();
i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(fun_obj);
v8::Handle<v8::Function> v8_fun = Utils::ToLocal(fun);
const int kArgc = 1;
v8::Handle<v8::Value> argv[kArgc] = { obj };
result = v8_fun->Call(Utils::ToLocal(debug), kArgc, argv);
has_pending_exception = result.IsEmpty();
}
EXCEPTION_BAILOUT_CHECK(isolate, Local<Value>());
return scope.Escape(result);
}
void Debug::ProcessDebugMessages() {
i::Isolate::Current()->debug()->ProcessDebugMessages(true);
}
Local<Context> Debug::GetDebugContext() {
i::Isolate* isolate = i::Isolate::Current();
ENTER_V8(isolate);
return Utils::ToLocal(i::Isolate::Current()->debug()->GetDebugContext());
}
void Debug::SetLiveEditEnabled(Isolate* isolate, bool enable) {
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
internal_isolate->debug()->set_live_edit_enabled(enable);
}
Handle<String> CpuProfileNode::GetFunctionName() const {
i::Isolate* isolate = i::Isolate::Current();
const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
const i::CodeEntry* entry = node->entry();
i::Handle<i::String> name =
isolate->factory()->InternalizeUtf8String(entry->name());
if (!entry->has_name_prefix()) {
return ToApiHandle<String>(name);
} else {
// We do not expect this to fail. Change this if it does.
i::Handle<i::String> cons = isolate->factory()->NewConsString(
isolate->factory()->InternalizeUtf8String(entry->name_prefix()),
name).ToHandleChecked();
return ToApiHandle<String>(cons);
}
}
int CpuProfileNode::GetScriptId() const {
const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
const i::CodeEntry* entry = node->entry();
return entry->script_id();
}
Handle<String> CpuProfileNode::GetScriptResourceName() const {
i::Isolate* isolate = i::Isolate::Current();
const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
node->entry()->resource_name()));
}
int CpuProfileNode::GetLineNumber() const {
return reinterpret_cast<const i::ProfileNode*>(this)->entry()->line_number();
}
int CpuProfileNode::GetColumnNumber() const {
return reinterpret_cast<const i::ProfileNode*>(this)->
entry()->column_number();
}
const char* CpuProfileNode::GetBailoutReason() const {
const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
return node->entry()->bailout_reason();
}
unsigned CpuProfileNode::GetHitCount() const {
return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
}
unsigned CpuProfileNode::GetCallUid() const {
return reinterpret_cast<const i::ProfileNode*>(this)->entry()->GetCallUid();
}
unsigned CpuProfileNode::GetNodeId() const {
return reinterpret_cast<const i::ProfileNode*>(this)->id();
}
int CpuProfileNode::GetChildrenCount() const {
return reinterpret_cast<const i::ProfileNode*>(this)->children()->length();
}
const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
const i::ProfileNode* child =
reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
return reinterpret_cast<const CpuProfileNode*>(child);
}
void CpuProfile::Delete() {
i::Isolate* isolate = i::Isolate::Current();
i::CpuProfiler* profiler = isolate->cpu_profiler();
DCHECK(profiler != NULL);
profiler->DeleteProfile(reinterpret_cast<i::CpuProfile*>(this));
}
Handle<String> CpuProfile::GetTitle() const {
i::Isolate* isolate = i::Isolate::Current();
const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
return ToApiHandle<String>(isolate->factory()->InternalizeUtf8String(
profile->title()));
}
const CpuProfileNode* CpuProfile::GetTopDownRoot() const {
const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
}
const CpuProfileNode* CpuProfile::GetSample(int index) const {
const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
return reinterpret_cast<const CpuProfileNode*>(profile->sample(index));
}
int64_t CpuProfile::GetSampleTimestamp(int index) const {
const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
return (profile->sample_timestamp(index) - base::TimeTicks())
.InMicroseconds();
}
int64_t CpuProfile::GetStartTime() const {
const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
return (profile->start_time() - base::TimeTicks()).InMicroseconds();
}
int64_t CpuProfile::GetEndTime() const {
const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
return (profile->end_time() - base::TimeTicks()).InMicroseconds();
}
int CpuProfile::GetSamplesCount() const {
return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
}
void CpuProfiler::SetSamplingInterval(int us) {
DCHECK(us >= 0);
return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
base::TimeDelta::FromMicroseconds(us));
}
void CpuProfiler::StartProfiling(Handle<String> title, bool record_samples) {
reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
*Utils::OpenHandle(*title), record_samples);
}
void CpuProfiler::StartCpuProfiling(Handle<String> title, bool record_samples) {
StartProfiling(title, record_samples);
}
CpuProfile* CpuProfiler::StopProfiling(Handle<String> title) {
return reinterpret_cast<CpuProfile*>(
reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
*Utils::OpenHandle(*title)));
}
const CpuProfile* CpuProfiler::StopCpuProfiling(Handle<String> title) {
return StopProfiling(title);
}
void CpuProfiler::SetIdle(bool is_idle) {
i::Isolate* isolate = reinterpret_cast<i::CpuProfiler*>(this)->isolate();
v8::StateTag state = isolate->current_vm_state();
DCHECK(state == v8::EXTERNAL || state == v8::IDLE);
if (isolate->js_entry_sp() != NULL) return;
if (is_idle) {
isolate->set_current_vm_state(v8::IDLE);
} else if (state == v8::IDLE) {
isolate->set_current_vm_state(v8::EXTERNAL);
}
}
static i::HeapGraphEdge* ToInternal(const HeapGraphEdge* edge) {
return const_cast<i::HeapGraphEdge*>(
reinterpret_cast<const i::HeapGraphEdge*>(edge));
}
HeapGraphEdge::Type HeapGraphEdge::GetType() const {
return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
}
Handle<Value> HeapGraphEdge::GetName() const {
i::Isolate* isolate = i::Isolate::Current();
i::HeapGraphEdge* edge = ToInternal(this);
switch (edge->type()) {
case i::HeapGraphEdge::kContextVariable:
case i::HeapGraphEdge::kInternal:
case i::HeapGraphEdge::kProperty:
case i::HeapGraphEdge::kShortcut:
case i::HeapGraphEdge::kWeak:
return ToApiHandle<String>(
isolate->factory()->InternalizeUtf8String(edge->name()));
case i::HeapGraphEdge::kElement:
case i::HeapGraphEdge::kHidden:
return ToApiHandle<Number>(
isolate->factory()->NewNumberFromInt(edge->index()));
default: UNREACHABLE();
}
return v8::Undefined(reinterpret_cast<v8::Isolate*>(isolate));
}
const HeapGraphNode* HeapGraphEdge::GetFromNode() const {
const i::HeapEntry* from = ToInternal(this)->from();
return reinterpret_cast<const HeapGraphNode*>(from);
}
const HeapGraphNode* HeapGraphEdge::GetToNode() const {
const i::HeapEntry* to = ToInternal(this)->to();
return reinterpret_cast<const HeapGraphNode*>(to);
}
static i::HeapEntry* ToInternal(const HeapGraphNode* entry) {
return const_cast<i::HeapEntry*>(
reinterpret_cast<const i::HeapEntry*>(entry));
}
HeapGraphNode::Type HeapGraphNode::GetType() const {
return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
}
Handle<String> HeapGraphNode::GetName() const {
i::Isolate* isolate = i::Isolate::Current();
return ToApiHandle<String>(
isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
}
SnapshotObjectId HeapGraphNode::GetId() const {
return ToInternal(this)->id();
}
int HeapGraphNode::GetSelfSize() const {
size_t size = ToInternal(this)->self_size();
CHECK(size <= static_cast<size_t>(internal::kMaxInt));
return static_cast<int>(size);
}
size_t HeapGraphNode::GetShallowSize() const {
return ToInternal(this)->self_size();
}
int HeapGraphNode::GetChildrenCount() const {
return ToInternal(this)->children().length();
}
const HeapGraphEdge* HeapGraphNode::GetChild(int index) const {
return reinterpret_cast<const HeapGraphEdge*>(
ToInternal(this)->children()[index]);
}
static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
return const_cast<i::HeapSnapshot*>(
reinterpret_cast<const i::HeapSnapshot*>(snapshot));
}
void HeapSnapshot::Delete() {
i::Isolate* isolate = i::Isolate::Current();
if (isolate->heap_profiler()->GetSnapshotsCount() > 1) {
ToInternal(this)->Delete();
} else {
// If this is the last snapshot, clean up all accessory data as well.
isolate->heap_profiler()->DeleteAllSnapshots();
}
}
unsigned HeapSnapshot::GetUid() const {
return ToInternal(this)->uid();
}
Handle<String> HeapSnapshot::GetTitle() const {
i::Isolate* isolate = i::Isolate::Current();
return ToApiHandle<String>(
isolate->factory()->InternalizeUtf8String(ToInternal(this)->title()));
}
const HeapGraphNode* HeapSnapshot::GetRoot() const {
return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
}
const HeapGraphNode* HeapSnapshot::GetNodeById(SnapshotObjectId id) const {
return reinterpret_cast<const HeapGraphNode*>(
ToInternal(this)->GetEntryById(id));
}
int HeapSnapshot::GetNodesCount() const {
return ToInternal(this)->entries().length();
}
const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
return reinterpret_cast<const HeapGraphNode*>(
&ToInternal(this)->entries().at(index));
}
SnapshotObjectId HeapSnapshot::GetMaxSnapshotJSObjectId() const {
return ToInternal(this)->max_snapshot_js_object_id();
}
void HeapSnapshot::Serialize(OutputStream* stream,
HeapSnapshot::SerializationFormat format) const {
Utils::ApiCheck(format == kJSON,
"v8::HeapSnapshot::Serialize",
"Unknown serialization format");
Utils::ApiCheck(stream->GetChunkSize() > 0,
"v8::HeapSnapshot::Serialize",
"Invalid stream chunk size");
i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
serializer.Serialize(stream);
}
int HeapProfiler::GetSnapshotCount() {
return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
}
const HeapSnapshot* HeapProfiler::GetHeapSnapshot(int index) {
return reinterpret_cast<const HeapSnapshot*>(
reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
}
SnapshotObjectId HeapProfiler::GetObjectId(Handle<Value> value) {
i::Handle<i::Object> obj = Utils::OpenHandle(*value);
return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
}
Handle<Value> HeapProfiler::FindObjectById(SnapshotObjectId id) {
i::Handle<i::Object> obj =
reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
if (obj.is_null()) return Local<Value>();
return Utils::ToLocal(obj);
}
void HeapProfiler::ClearObjectIds() {
reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
}
const HeapSnapshot* HeapProfiler::TakeHeapSnapshot(
Handle<String> title,
ActivityControl* control,
ObjectNameResolver* resolver) {
return reinterpret_cast<const HeapSnapshot*>(
reinterpret_cast<i::HeapProfiler*>(this)->TakeSnapshot(
*Utils::OpenHandle(*title), control, resolver));
}
void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
track_allocations);
}
void HeapProfiler::StopTrackingHeapObjects() {
reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
}
SnapshotObjectId HeapProfiler::GetHeapStats(OutputStream* stream) {
return reinterpret_cast<i::HeapProfiler*>(this)->PushHeapObjectsStats(stream);
}
void HeapProfiler::DeleteAllHeapSnapshots() {
reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
}
void HeapProfiler::SetWrapperClassInfoProvider(uint16_t class_id,
WrapperInfoCallback callback) {
reinterpret_cast<i::HeapProfiler*>(this)->DefineWrapperClass(class_id,
callback);
}
size_t HeapProfiler::GetProfilerMemorySize() {
return reinterpret_cast<i::HeapProfiler*>(this)->
GetMemorySizeUsedByProfiler();
}
void HeapProfiler::SetRetainedObjectInfo(UniqueId id,
RetainedObjectInfo* info) {
reinterpret_cast<i::HeapProfiler*>(this)->SetRetainedObjectInfo(id, info);
}
v8::Testing::StressType internal::Testing::stress_type_ =
v8::Testing::kStressTypeOpt;
void Testing::SetStressRunType(Testing::StressType type) {
internal::Testing::set_stress_type(type);
}
int Testing::GetStressRuns() {
if (internal::FLAG_stress_runs != 0) return internal::FLAG_stress_runs;
#ifdef DEBUG
// In debug mode the code runs much slower so stressing will only make two
// runs.
return 2;
#else
return 5;
#endif
}
static void SetFlagsFromString(const char* flags) {
V8::SetFlagsFromString(flags, i::StrLength(flags));
}
void Testing::PrepareStressRun(int run) {
static const char* kLazyOptimizations =
"--prepare-always-opt "
"--max-inlined-source-size=999999 "
"--max-inlined-nodes=999999 "
"--max-inlined-nodes-cumulative=999999 "
"--noalways-opt";
static const char* kForcedOptimizations = "--always-opt";
// If deoptimization stressed turn on frequent deoptimization. If no value
// is spefified through --deopt-every-n-times use a default default value.
static const char* kDeoptEvery13Times = "--deopt-every-n-times=13";
if (internal::Testing::stress_type() == Testing::kStressTypeDeopt &&
internal::FLAG_deopt_every_n_times == 0) {
SetFlagsFromString(kDeoptEvery13Times);
}
#ifdef DEBUG
// As stressing in debug mode only make two runs skip the deopt stressing
// here.
if (run == GetStressRuns() - 1) {
SetFlagsFromString(kForcedOptimizations);
} else {
SetFlagsFromString(kLazyOptimizations);
}
#else
if (run == GetStressRuns() - 1) {
SetFlagsFromString(kForcedOptimizations);
} else if (run != GetStressRuns() - 2) {
SetFlagsFromString(kLazyOptimizations);
}
#endif
}
// TODO(svenpanne) Deprecate this.
void Testing::DeoptimizeAll() {
i::Isolate* isolate = i::Isolate::Current();
i::HandleScope scope(isolate);
internal::Deoptimizer::DeoptimizeAll(isolate);
}
namespace internal {
void HandleScopeImplementer::FreeThreadResources() {
Free();
}
char* HandleScopeImplementer::ArchiveThread(char* storage) {
HandleScopeData* current = isolate_->handle_scope_data();
handle_scope_data_ = *current;
MemCopy(storage, this, sizeof(*this));
ResetAfterArchive();
current->Initialize();
return storage + ArchiveSpacePerThread();
}
int HandleScopeImplementer::ArchiveSpacePerThread() {
return sizeof(HandleScopeImplementer);
}
char* HandleScopeImplementer::RestoreThread(char* storage) {
MemCopy(this, storage, sizeof(*this));
*isolate_->handle_scope_data() = handle_scope_data_;
return storage + ArchiveSpacePerThread();
}
void HandleScopeImplementer::IterateThis(ObjectVisitor* v) {
#ifdef DEBUG
bool found_block_before_deferred = false;
#endif
// Iterate over all handles in the blocks except for the last.
for (int i = blocks()->length() - 2; i >= 0; --i) {
Object** block = blocks()->at(i);
if (last_handle_before_deferred_block_ != NULL &&
(last_handle_before_deferred_block_ <= &block[kHandleBlockSize]) &&
(last_handle_before_deferred_block_ >= block)) {
v->VisitPointers(block, last_handle_before_deferred_block_);
DCHECK(!found_block_before_deferred);
#ifdef DEBUG
found_block_before_deferred = true;
#endif
} else {
v->VisitPointers(block, &block[kHandleBlockSize]);
}
}
DCHECK(last_handle_before_deferred_block_ == NULL ||
found_block_before_deferred);
// Iterate over live handles in the last block (if any).
if (!blocks()->is_empty()) {
v->VisitPointers(blocks()->last(), handle_scope_data_.next);
}
List<Context*>* context_lists[2] = { &saved_contexts_, &entered_contexts_};
for (unsigned i = 0; i < arraysize(context_lists); i++) {
if (context_lists[i]->is_empty()) continue;
Object** start = reinterpret_cast<Object**>(&context_lists[i]->first());
v->VisitPointers(start, start + context_lists[i]->length());
}
}
void HandleScopeImplementer::Iterate(ObjectVisitor* v) {
HandleScopeData* current = isolate_->handle_scope_data();
handle_scope_data_ = *current;
IterateThis(v);
}
char* HandleScopeImplementer::Iterate(ObjectVisitor* v, char* storage) {
HandleScopeImplementer* scope_implementer =
reinterpret_cast<HandleScopeImplementer*>(storage);
scope_implementer->IterateThis(v);
return storage + ArchiveSpacePerThread();
}
DeferredHandles* HandleScopeImplementer::Detach(Object** prev_limit) {
DeferredHandles* deferred =
new DeferredHandles(isolate()->handle_scope_data()->next, isolate());
while (!blocks_.is_empty()) {
Object** block_start = blocks_.last();
Object** block_limit = &block_start[kHandleBlockSize];
// We should not need to check for SealHandleScope here. Assert this.
DCHECK(prev_limit == block_limit ||
!(block_start <= prev_limit && prev_limit <= block_limit));
if (prev_limit == block_limit) break;
deferred->blocks_.Add(blocks_.last());
blocks_.RemoveLast();
}
// deferred->blocks_ now contains the blocks installed on the
// HandleScope stack since BeginDeferredScope was called, but in
// reverse order.
DCHECK(prev_limit == NULL || !blocks_.is_empty());
DCHECK(!blocks_.is_empty() && prev_limit != NULL);
DCHECK(last_handle_before_deferred_block_ != NULL);
last_handle_before_deferred_block_ = NULL;
return deferred;
}
void HandleScopeImplementer::BeginDeferredScope() {
DCHECK(last_handle_before_deferred_block_ == NULL);
last_handle_before_deferred_block_ = isolate()->handle_scope_data()->next;
}
DeferredHandles::~DeferredHandles() {
isolate_->UnlinkDeferredHandles(this);
for (int i = 0; i < blocks_.length(); i++) {
#ifdef ENABLE_HANDLE_ZAPPING
HandleScope::ZapRange(blocks_[i], &blocks_[i][kHandleBlockSize]);
#endif
isolate_->handle_scope_implementer()->ReturnBlock(blocks_[i]);
}
}
void DeferredHandles::Iterate(ObjectVisitor* v) {
DCHECK(!blocks_.is_empty());
DCHECK((first_block_limit_ >= blocks_.first()) &&
(first_block_limit_ <= &(blocks_.first())[kHandleBlockSize]));
v->VisitPointers(blocks_.first(), first_block_limit_);
for (int i = 1; i < blocks_.length(); i++) {
v->VisitPointers(blocks_[i], &blocks_[i][kHandleBlockSize]);
}
}
void InvokeAccessorGetterCallback(
v8::Local<v8::Name> property,
const v8::PropertyCallbackInfo<v8::Value>& info,
v8::AccessorNameGetterCallback getter) {
// Leaving JavaScript.
Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
Address getter_address = reinterpret_cast<Address>(reinterpret_cast<intptr_t>(
getter));
VMState<EXTERNAL> state(isolate);
ExternalCallbackScope call_scope(isolate, getter_address);
getter(property, info);
}
void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
v8::FunctionCallback callback) {
Isolate* isolate = reinterpret_cast<Isolate*>(info.GetIsolate());
Address callback_address =
reinterpret_cast<Address>(reinterpret_cast<intptr_t>(callback));
VMState<EXTERNAL> state(isolate);
ExternalCallbackScope call_scope(isolate, callback_address);
callback(info);
}
} } // namespace v8::internal
|
#include "GameInterface.hpp"
#include "HostInterface.hpp"
#include "GameLogic.hpp"
#include "MapTransientState.hpp"
#include <algorithm>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <unordered_map>
GlobalState *globalState;
HostInterface *hostInterface;
static MemoryZone *transientMemoryZone;
static std::unordered_map<std::string, EntityBehaviorType> EntityTypeToBehaviorType = {
# define ENTITY_BEHAVIOR_TYPE(typeName) {#typeName, EntityBehaviorType::typeName},
# include "EntityBehaviorTypes.inc"
# undef ENTITY_BEHAVIOR_TYPE
};
uint8_t *allocateTransientBytes(size_t byteCount)
{
return transientMemoryZone->allocateBytes(byteCount);
}
Entity *instatiateEntityInLayer(MapEntityLayerState *entityLayer, EntityBehaviorType type)
{
Entity *result;
if(!global.mapTransientState->freeEntities.empty())
{
result = global.mapTransientState->freeEntities.back();
// Destroy and recreate the entity, to make sure it is completely clean.
result->~Entity();
memset(result, 0, sizeof(Entity));
new (result) Entity;
global.mapTransientState->freeEntities.pop_back();
//printf("Use entity form the free list\n");
}
else
{
global.mapTransientState->entities.push_back(Entity());
result = &global.mapTransientState->entities.back();
//printf("Instantiate new entity\n");
}
result->type = type;
entityLayer->entities.push_back(result);
return result;
}
static EntityBehaviorType parseEntityTypeName(const std::string &name)
{
auto it = EntityTypeToBehaviorType.find(name);
if(it != EntityTypeToBehaviorType.end())
return it->second;
return EntityBehaviorType::Null;
}
static Entity *instantiateMapEntity(MapEntityLayerState *entityLayer, const MapFileEntity &mapEntity)
{
auto result = instatiateEntityInLayer(entityLayer, parseEntityTypeName(mapEntity.type));
result->name = mapEntity.name;
auto bbox = mapEntity.boundingBox;
result->position = (bbox.center() - Vector2F(0.0f, global.currentMap->height()))*Vector2F(UnitsPerPixel, -UnitsPerPixel);
result->halfExtent = bbox.halfExtent()*UnitsPerPixel;
result->spawn();
return result;
}
static void loadMapFileEntityLayer(const MapFileEntityLayer &layer)
{
auto entityLayer = newTransient<MapEntityLayerState> ();
global.mapTransientState->layers.push_back(entityLayer);
for(uint32_t i = 0; i < layer.entityCount; ++i)
{
instantiateMapEntity(entityLayer, layer.entities[i]);
}
}
static void loadMapFileTileLayer(const MapFileTileLayer &layer)
{
auto solidLayer = newTransient<MapSolidLayerState> ();
solidLayer->mapTileLayer = &layer;
global.mapTransientState->layers.push_back(solidLayer);
}
static void loadMapFile(const char *filename, const char *messageTitle)
{
// Do the actual map loading.
global.currentMap.reset(hostInterface->loadMapFile(filename));
transientMemoryZone->reset();
transientMemoryZone->clearAll();
global.mapTransientState = newTransient<MapTransientState> ();
global.cameraPosition = Vector2F::zeros();
// Clear the map states.
global.currentMap->layersDo([&](const MapFileLayer &layer) {
switch(layer.type)
{
case MapFileLayerType::Entities:
loadMapFileEntityLayer(reinterpret_cast<const MapFileEntityLayer &> (layer));
break;
case MapFileLayerType::Tiles:
loadMapFileTileLayer(reinterpret_cast<const MapFileTileLayer &> (layer));
break;
default:
// Ignored
break;
}
});
// Clear the special layers.
{
auto projectileLayer = newTransient<MapEntityLayerState> ();
global.mapTransientState->layers.push_back(projectileLayer);
global.mapTransientState->projectileEntityLayer = projectileLayer;
}
// Set the title message.
global.mapTransientState->currentMessage = std::string(messageTitle);
global.mapTransientState->currentMessageRemainingTime = 3.0f;
}
static void startNewMap()
{
switch(global.currentLevelID)
{
case LevelID::DonMeowth:
loadMapFile("donMeowth.map", "Escort\nDon Meowth!!!");
break;
case LevelID::MrPresident:
loadMapFile("mrPresident.map", "Protect\nMr. President!!!");
break;
case LevelID::Test:
default:
loadMapFile("test.map", "Escort the ^!!!");
break;
}
}
static LevelID nextLevelForID(LevelID oldID)
{
switch(oldID)
{
case LevelID::DonMeowth: return LevelID::MrPresident;
default: return oldID;
}
}
static void startNextMap()
{
if(global.currentLevelID == LevelID::FinalLevel)
{
global.isGameFinished = true;
return;
}
global.currentLevelID = nextLevelForID(global.currentLevelID);
startNewMap();
}
static void initializeGlobalState()
{
if(global.isInitialized)
return;
// This is the place for loading the required game assets
global.backgroundImage.reset(hostInterface->loadImage("background.png"));
global.mainTileSet.loadFrom("tileset.png");
global.hudTiles.loadFrom("hud.png");
global.itemsSprites.loadFrom("items.png");
global.robotSprites.loadFrom("robotSprites.png", 48, 64);
global.catDogsSprites.loadFrom("catDogsSprites.png", 64, 32);
global.humanLikeSprites.loadFrom("humanLikeSprites.png", 48, 80);
TileSet humanLikeSprites;
global.playerShotSample = hostInterface->loadSoundSample("laser1.wav");
global.enemyShotSample = hostInterface->loadSoundSample("laser3.wav");
global.playerJumpSample = hostInterface->loadSoundSample("player-jump.wav");
global.vipJumpSample = hostInterface->loadSoundSample("vip-jump.wav");
global.dashSample = hostInterface->loadSoundSample("dash.wav");
global.robotExplosionSample = hostInterface->loadSoundSample("robot-explosion.wav");
global.robotExplosionSample2 = hostInterface->loadSoundSample("robot-explosion2.wav");
global.healthPickupSample = hostInterface->loadSoundSample("health-pickup.wav");
global.collisionHitSample = hostInterface->loadSoundSample("wall-hit.wav");
global.damageReceivedSample = hostInterface->loadSoundSample("damage-received.wav");
// Start in a new map.
global.currentLevelID = LevelID::InitialLevel;
startNewMap();
global.isInitialized = true;
}
void Entity::kill()
{
if(isDead_)
return;
isDead_ = true;
global.mapTransientState->zombieEntities.push_back(this);
}
static void updateTransientState(float delta)
{
auto transientState = global.mapTransientState;
if(!transientState)
return;
// Pause button
if(!(transientState->isGameOver || global.isGameFinished) && global.isButtonPressed(ControllerButton::Start))
global.isPaused = !global.isPaused;
if(transientState->isGameOver &&
transientState->timeInGameOver > 0.5f &&
global.isButtonPressed(ControllerButton::Start | ControllerButton::A | ControllerButton::X))
{
startNewMap();
if(!transientState)
return;
}
if(global.isGameFinished && global.isButtonPressed(ControllerButton::Start))
{
global.currentLevelID = LevelID::InitialLevel;
global.isGameFinished = false;
startNewMap();
if(!transientState)
return;
}
if(global.isPaused)
return;
if(!transientState->isGameOver && transientState->isGoalReached && transientState->timeInGoal > 0.5f)
{
startNextMap();
if(!transientState)
return;
}
// The time of the active message
transientState->timeInMap += delta;
if(transientState->currentMessageRemainingTime > 0.0f)
transientState->currentMessageRemainingTime -= delta;
// Update the ticking entities.
for(auto entity : transientState->tickingEntitites)
entity->update(delta);
// Remove all of the dead entities.
auto areDead = [](Entity *entity){
return entity->isDead();
};
for(auto layer : transientState->layers)
{
if(layer->type != MapLayerType::Entities)
continue;
auto entityLayer = reinterpret_cast<MapEntityLayerState*> (layer);
entityLayer->entities.removeAllThat(areDead);
}
transientState->collisionEntities.removeAllThat(areDead);
transientState->tickingEntitites.removeAllThat(areDead);
if(transientState->activePlayer && transientState->activePlayer->isDead())
transientState->activePlayer = nullptr;
if(transientState->activeVIP && transientState->activeVIP->isDead())
transientState->activeVIP = nullptr;
transientState->isGameOver = !transientState->activePlayer || !transientState->activeVIP;
if(transientState->isGameOver)
transientState->timeInGameOver += delta;
// Move the zombies into the free list.
for(auto entity : transientState->zombieEntities)
transientState->freeEntities.push_back(entity);
transientState->zombieEntities.clear();
if(transientState->isGoalReached)
transientState->timeInGoal += delta;
}
void update(float delta, const ControllerState &controllerState)
{
initializeGlobalState();
global.oldControllerState = global.controllerState;
global.controllerState = controllerState;
updateTransientState(delta);
global.currentTime += delta;
}
void render(const Framebuffer &framebuffer);
class GameInterfaceImpl : public GameInterface
{
public:
virtual void setPersistentMemory(MemoryZone *zone) override;
virtual void setTransientMemory(MemoryZone *zone) override;
virtual void update(float delta, const ControllerState &controllerState) override;
virtual void render(const Framebuffer &framebuffer) override;
virtual void setHostInterface(HostInterface *theHost) override;
};
void GameInterfaceImpl::setPersistentMemory(MemoryZone *zone)
{
globalState = reinterpret_cast<GlobalState*> (zone->getData());
}
void GameInterfaceImpl::setHostInterface(HostInterface *theHost)
{
hostInterface = theHost;
}
void GameInterfaceImpl::setTransientMemory(MemoryZone *zone)
{
transientMemoryZone = zone;
}
void GameInterfaceImpl::update(float delta, const ControllerState &controllerState)
{
::update(delta, controllerState);
}
void GameInterfaceImpl::render(const Framebuffer &framebuffer)
{
::render(framebuffer);
}
static GameInterfaceImpl gameInterfaceImpl;
extern "C" GameInterface *getGameInterface()
{
return &gameInterfaceImpl;
}
|
#include "vulkanite_pipeline.hpp"
#include <fstream>
#include <stdexcept>
#include <iostream>
#include <cassert>
namespace vulkanite {
VulkanitePipeline::VulkanitePipeline(VulkaniteDevice& device, const std::string& vertFilepath, const std::string& fragFilepath, const PipelineConfigInfo& configInfo) : vulkaniteDevice{device} {
createGraphicsPipeline(vertFilepath, fragFilepath, configInfo);
}
VulkanitePipeline::~VulkanitePipeline() {
vkDestroyShaderModule(vulkaniteDevice.device(), vertShaderModule, nullptr);
vkDestroyShaderModule(vulkaniteDevice.device(), fragShaderModule, nullptr);
vkDestroyPipeline(vulkaniteDevice.device(), graphicsPipeline, nullptr);
}
std::vector<char> VulkanitePipeline::readFile(const std::string& filepath) {
std::ifstream file{ filepath, std::ios::ate | std::ios::binary };
if (!file.is_open()) {
throw std::runtime_error("Failed to open file: " + filepath);
}
size_t fileSize = static_cast<size_t>(file.tellg());
std::vector<char> buffer(fileSize);
file.seekg(0);
file.read(buffer.data(), fileSize);
file.close();
return buffer;
}
void VulkanitePipeline::createGraphicsPipeline(const std::string& vertFilepath, const std::string& fragFilepath, const PipelineConfigInfo& configInfo) {
assert(configInfo.pipelineLayout != VK_NULL_HANDLE && "Cannot create graphics pipeline: no pipelineLayout provided in configInfo");
assert(configInfo.renderPass != VK_NULL_HANDLE && "Cannot create graphics pipeline: no renderPass provided in configInfo");
auto vertCode = readFile(vertFilepath);
auto fragCode = readFile(fragFilepath);
std::cout << "Vertex Shader Code Size: " << vertCode.size() << '\n';
std::cout << "Fragment Shader Code Size: " << fragCode.size() << '\n';
VkPipelineShaderStageCreateInfo shaderStages[2];
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStages[0].module = vertShaderModule;
shaderStages[0].pName = "main";
shaderStages[0].flags = 0;
shaderStages[0].pNext = nullptr;
shaderStages[0].pSpecializationInfo = nullptr;
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStages[1].module = fragShaderModule;
shaderStages[1].pName = "main";
shaderStages[1].flags = 0;
shaderStages[1].pNext = nullptr;
shaderStages[1].pSpecializationInfo = nullptr;
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertexInputInfo.vertexAttributeDescriptionCount = 0;
vertexInputInfo.vertexBindingDescriptionCount = 0;
vertexInputInfo.pVertexAttributeDescriptions = nullptr;
vertexInputInfo.pVertexBindingDescriptions = nullptr;
VkPipelineViewportStateCreateInfo viewportInfo{};
viewportInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportInfo.viewportCount = 1;
viewportInfo.pViewports = &configInfo.viewport;
viewportInfo.scissorCount = 1;
viewportInfo.pScissors = &configInfo.scissor;
VkGraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &configInfo.inputAssemblyInfo;
pipelineInfo.pViewportState = &viewportInfo;
pipelineInfo.pRasterizationState = &configInfo.rasterizationInfo;
pipelineInfo.pMultisampleState = &configInfo.multisampleInfo;
pipelineInfo.pColorBlendState = &configInfo.colorBlendInfo;
pipelineInfo.pDepthStencilState = &configInfo.depthStencilInfo;
pipelineInfo.pDynamicState = nullptr;
pipelineInfo.layout = configInfo.pipelineLayout;
pipelineInfo.renderPass = configInfo.renderPass;
pipelineInfo.subpass = configInfo.subpass;
pipelineInfo.basePipelineIndex = -1;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
if (vkCreateGraphicsPipelines(vulkaniteDevice.device(), VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) {
throw std::runtime_error("Failed to create graphics pipeline");
}
}
void VulkanitePipeline::createShaderModule(const std::vector<char>& code, VkShaderModule* shaderModule) {
VkShaderModuleCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = code.size();
createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
if (vkCreateShaderModule(vulkaniteDevice.device(), &createInfo, nullptr, shaderModule) != VK_SUCCESS) {
throw std::runtime_error("Failed to create shader module");
}
}
PipelineConfigInfo VulkanitePipeline::defaultPipelineConfigInfo(uint32_t width, uint32_t height) {
PipelineConfigInfo configInfo{};
configInfo.inputAssemblyInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
configInfo.inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
configInfo.inputAssemblyInfo.primitiveRestartEnable = VK_FALSE;
configInfo.viewport.x = 0.0f;
configInfo.viewport.y = 0.0f;
configInfo.viewport.width = static_cast<float>(width);
configInfo.viewport.height = static_cast<float>(height);
configInfo.viewport.minDepth = 0.0f;
configInfo.viewport.maxDepth = 1.0f;
configInfo.scissor.offset = { 0, 0 };
configInfo.scissor.extent = { width, height };
configInfo.rasterizationInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
configInfo.rasterizationInfo.depthClampEnable = VK_FALSE;
configInfo.rasterizationInfo.rasterizerDiscardEnable = VK_FALSE;
configInfo.rasterizationInfo.polygonMode = VK_POLYGON_MODE_FILL;
configInfo.rasterizationInfo.lineWidth = 1.0f;
configInfo.rasterizationInfo.cullMode = VK_CULL_MODE_NONE;
configInfo.rasterizationInfo.frontFace = VK_FRONT_FACE_CLOCKWISE;
configInfo.rasterizationInfo.depthBiasEnable = VK_FALSE;
configInfo.rasterizationInfo.depthBiasConstantFactor = 0.0f; // Optional
configInfo.rasterizationInfo.depthBiasClamp = 0.0f; // Optional
configInfo.rasterizationInfo.depthBiasSlopeFactor = 0.0f; // Optional
configInfo.multisampleInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
configInfo.multisampleInfo.sampleShadingEnable = VK_FALSE;
configInfo.multisampleInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
configInfo.multisampleInfo.minSampleShading = 1.0f; // Optional
configInfo.multisampleInfo.pSampleMask = nullptr; // Optional
configInfo.multisampleInfo.alphaToCoverageEnable = VK_FALSE; // Optional
configInfo.multisampleInfo.alphaToOneEnable = VK_FALSE; // Optional
configInfo.colorBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT |
VK_COLOR_COMPONENT_A_BIT;
configInfo.colorBlendAttachment.blendEnable = VK_FALSE;
configInfo.colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
configInfo.colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
configInfo.colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // Optional
configInfo.colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
configInfo.colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
configInfo.colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
configInfo.colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
configInfo.colorBlendInfo.logicOpEnable = VK_FALSE;
configInfo.colorBlendInfo.logicOp = VK_LOGIC_OP_COPY; // Optional
configInfo.colorBlendInfo.attachmentCount = 1;
configInfo.colorBlendInfo.pAttachments = &configInfo.colorBlendAttachment;
configInfo.colorBlendInfo.blendConstants[0] = 0.0f; // Optional
configInfo.colorBlendInfo.blendConstants[1] = 0.0f; // Optional
configInfo.colorBlendInfo.blendConstants[2] = 0.0f; // Optional
configInfo.colorBlendInfo.blendConstants[3] = 0.0f; // Optional
configInfo.depthStencilInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
configInfo.depthStencilInfo.depthTestEnable = VK_TRUE;
configInfo.depthStencilInfo.depthWriteEnable = VK_TRUE;
configInfo.depthStencilInfo.depthCompareOp = VK_COMPARE_OP_LESS;
configInfo.depthStencilInfo.depthBoundsTestEnable = VK_FALSE;
configInfo.depthStencilInfo.minDepthBounds = 0.0f; // Optional
configInfo.depthStencilInfo.maxDepthBounds = 1.0f; // Optional
configInfo.depthStencilInfo.stencilTestEnable = VK_FALSE;
configInfo.depthStencilInfo.front = {}; // Optional
configInfo.depthStencilInfo.back = {}; // Optional
return configInfo;
}
}
|
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/http/server/http_server_filter.h"
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/b64.h"
#include "src/core/lib/slice/percent_encoding.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/transport/static_metadata.h"
#define EXPECTED_CONTENT_TYPE "application/grpc"
#define EXPECTED_CONTENT_TYPE_LENGTH (sizeof(EXPECTED_CONTENT_TYPE) - 1)
static void hs_recv_initial_metadata_ready(void* user_data,
grpc_error_handle err);
static void hs_recv_trailing_metadata_ready(void* user_data,
grpc_error_handle err);
static void hs_recv_message_ready(void* user_data, grpc_error_handle err);
namespace {
struct call_data {
call_data(grpc_call_element* elem, const grpc_call_element_args& args)
: call_combiner(args.call_combiner) {
GRPC_CLOSURE_INIT(&recv_initial_metadata_ready,
hs_recv_initial_metadata_ready, elem,
grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&recv_message_ready, hs_recv_message_ready, elem,
grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready,
hs_recv_trailing_metadata_ready, elem,
grpc_schedule_on_exec_ctx);
}
~call_data() {
GRPC_ERROR_UNREF(recv_initial_metadata_ready_error);
if (have_read_stream) {
read_stream->Orphan();
}
}
grpc_core::CallCombiner* call_combiner;
// Outgoing headers to add to send_initial_metadata.
grpc_linked_mdelem status;
grpc_linked_mdelem content_type;
// If we see the recv_message contents in the GET query string, we
// store it here.
grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> read_stream;
bool have_read_stream = false;
// State for intercepting recv_initial_metadata.
grpc_closure recv_initial_metadata_ready;
grpc_error_handle recv_initial_metadata_ready_error = GRPC_ERROR_NONE;
grpc_closure* original_recv_initial_metadata_ready;
grpc_metadata_batch* recv_initial_metadata = nullptr;
uint32_t* recv_initial_metadata_flags;
bool seen_recv_initial_metadata_ready = false;
// State for intercepting recv_message.
grpc_closure* original_recv_message_ready;
grpc_closure recv_message_ready;
grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message;
bool seen_recv_message_ready = false;
// State for intercepting recv_trailing_metadata
grpc_closure recv_trailing_metadata_ready;
grpc_closure* original_recv_trailing_metadata_ready;
grpc_error_handle recv_trailing_metadata_ready_error;
bool seen_recv_trailing_metadata_ready = false;
};
struct channel_data {
bool surface_user_agent;
};
} // namespace
static grpc_error_handle hs_filter_outgoing_metadata(grpc_metadata_batch* b) {
if (b->legacy_index()->named.grpc_message != nullptr) {
grpc_slice pct_encoded_msg = grpc_core::PercentEncodeSlice(
GRPC_MDVALUE(b->legacy_index()->named.grpc_message->md),
grpc_core::PercentEncodingType::Compatible);
if (grpc_slice_is_equivalent(
pct_encoded_msg,
GRPC_MDVALUE(b->legacy_index()->named.grpc_message->md))) {
grpc_slice_unref_internal(pct_encoded_msg);
} else {
grpc_metadata_batch_set_value(b->legacy_index()->named.grpc_message,
pct_encoded_msg);
}
}
return GRPC_ERROR_NONE;
}
static void hs_add_error(const char* error_name, grpc_error_handle* cumulative,
grpc_error_handle new_err) {
if (new_err == GRPC_ERROR_NONE) return;
if (*cumulative == GRPC_ERROR_NONE) {
*cumulative = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_name);
}
*cumulative = grpc_error_add_child(*cumulative, new_err);
}
// Metadata equality within this filter leverages the fact that the sender was
// likely using the gRPC chttp2 transport, in which case the encoder would emit
// indexed values, in which case the local hpack parser would intern the
// relevant metadata, allowing a simple pointer comparison.
//
// That said, if the header was transmitted sans indexing/encoding, we still
// need to do the right thing.
//
// Assumptions:
// 1) The keys for a and b_static must match
// 2) b_static must be a statically allocated metadata object.
// 3) It is assumed that the remote end is indexing, but not necessary.
// TODO(arjunroy): Revisit this method when grpc_mdelem is strongly typed.
static bool md_strict_equal(grpc_mdelem a, grpc_mdelem b_static) {
// Hpack encoder on the remote side should emit indexed values, in which case
// hpack parser on this end should pick up interned values, in which case the
// pointer comparison alone is enough.
//
if (GPR_LIKELY(GRPC_MDELEM_IS_INTERNED(a))) {
return a.payload == b_static.payload;
} else {
return grpc_slice_eq_static_interned(GRPC_MDVALUE(a),
GRPC_MDVALUE(b_static));
}
}
static grpc_error_handle hs_filter_incoming_metadata(grpc_call_element* elem,
grpc_metadata_batch* b) {
call_data* calld = static_cast<call_data*>(elem->call_data);
grpc_error_handle error = GRPC_ERROR_NONE;
static const char* error_name = "Failed processing incoming headers";
if (b->legacy_index()->named.method != nullptr) {
if (md_strict_equal(b->legacy_index()->named.method->md,
GRPC_MDELEM_METHOD_POST)) {
*calld->recv_initial_metadata_flags &=
~(GRPC_INITIAL_METADATA_CACHEABLE_REQUEST |
GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST);
} else if (md_strict_equal(b->legacy_index()->named.method->md,
GRPC_MDELEM_METHOD_PUT)) {
*calld->recv_initial_metadata_flags &=
~GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
*calld->recv_initial_metadata_flags |=
GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
} else if (md_strict_equal(b->legacy_index()->named.method->md,
GRPC_MDELEM_METHOD_GET)) {
*calld->recv_initial_metadata_flags |=
GRPC_INITIAL_METADATA_CACHEABLE_REQUEST;
*calld->recv_initial_metadata_flags &=
~GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST;
} else {
hs_add_error(error_name, &error,
grpc_attach_md_to_error(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"),
b->legacy_index()->named.method->md));
}
b->Remove(GRPC_BATCH_METHOD);
} else {
hs_add_error(error_name, &error,
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
GRPC_ERROR_STR_KEY, ":method"));
}
if (b->legacy_index()->named.te != nullptr) {
if (!grpc_mdelem_static_value_eq(b->legacy_index()->named.te->md,
GRPC_MDELEM_TE_TRAILERS)) {
hs_add_error(error_name, &error,
grpc_attach_md_to_error(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"),
b->legacy_index()->named.te->md));
}
b->Remove(GRPC_BATCH_TE);
} else {
hs_add_error(error_name, &error,
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
GRPC_ERROR_STR_KEY, "te"));
}
if (b->legacy_index()->named.scheme != nullptr) {
if (!md_strict_equal(b->legacy_index()->named.scheme->md,
GRPC_MDELEM_SCHEME_HTTP) &&
!md_strict_equal(b->legacy_index()->named.scheme->md,
GRPC_MDELEM_SCHEME_HTTPS) &&
!grpc_mdelem_static_value_eq(b->legacy_index()->named.scheme->md,
GRPC_MDELEM_SCHEME_GRPC)) {
hs_add_error(error_name, &error,
grpc_attach_md_to_error(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"),
b->legacy_index()->named.scheme->md));
}
b->Remove(GRPC_BATCH_SCHEME);
} else {
hs_add_error(error_name, &error,
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
GRPC_ERROR_STR_KEY, ":scheme"));
}
if (b->legacy_index()->named.content_type != nullptr) {
if (!grpc_mdelem_static_value_eq(
b->legacy_index()->named.content_type->md,
GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) {
if (grpc_slice_buf_start_eq(
GRPC_MDVALUE(b->legacy_index()->named.content_type->md),
EXPECTED_CONTENT_TYPE, EXPECTED_CONTENT_TYPE_LENGTH) &&
(GRPC_SLICE_START_PTR(GRPC_MDVALUE(
b->legacy_index()
->named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
'+' ||
GRPC_SLICE_START_PTR(GRPC_MDVALUE(
b->legacy_index()
->named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] ==
';')) {
/* Although the C implementation doesn't (currently) generate them,
any custom +-suffix is explicitly valid. */
/* TODO(klempner): We should consider preallocating common values such
as +proto or +json, or at least stashing them if we see them. */
/* TODO(klempner): Should we be surfacing this to application code? */
} else {
/* TODO(klempner): We're currently allowing this, but we shouldn't
see it without a proxy so log for now. */
char* val = grpc_dump_slice(
GRPC_MDVALUE(b->legacy_index()->named.content_type->md),
GPR_DUMP_ASCII);
gpr_log(GPR_INFO, "Unexpected content-type '%s'", val);
gpr_free(val);
}
}
b->Remove(GRPC_BATCH_CONTENT_TYPE);
}
if (b->legacy_index()->named.path == nullptr) {
hs_add_error(error_name, &error,
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
GRPC_ERROR_STR_KEY, ":path"));
} else if (*calld->recv_initial_metadata_flags &
GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) {
/* We have a cacheable request made with GET verb. The path contains the
* query parameter which is base64 encoded request payload. */
const char k_query_separator = '?';
grpc_slice path_slice = GRPC_MDVALUE(b->legacy_index()->named.path->md);
uint8_t* path_ptr = GRPC_SLICE_START_PTR(path_slice);
size_t path_length = GRPC_SLICE_LENGTH(path_slice);
/* offset of the character '?' */
size_t offset = 0;
for (offset = 0; offset < path_length && *path_ptr != k_query_separator;
path_ptr++, offset++) {
}
if (offset < path_length) {
grpc_slice query_slice =
grpc_slice_sub(path_slice, offset + 1, path_length);
/* substitute path metadata with just the path (not query) */
grpc_mdelem mdelem_path_without_query = grpc_mdelem_from_slices(
GRPC_MDSTR_PATH, grpc_slice_sub(path_slice, 0, offset));
b->Substitute(b->legacy_index()->named.path, mdelem_path_without_query);
/* decode payload from query and add to the slice buffer to be returned */
const int k_url_safe = 1;
grpc_slice_buffer read_slice_buffer;
grpc_slice_buffer_init(&read_slice_buffer);
grpc_slice_buffer_add(
&read_slice_buffer,
grpc_base64_decode_with_len(
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(query_slice),
GRPC_SLICE_LENGTH(query_slice), k_url_safe));
calld->read_stream.Init(&read_slice_buffer, 0);
grpc_slice_buffer_destroy_internal(&read_slice_buffer);
calld->have_read_stream = true;
grpc_slice_unref_internal(query_slice);
} else {
gpr_log(GPR_ERROR, "GET request without QUERY");
}
}
if (b->legacy_index()->named.host != nullptr &&
b->legacy_index()->named.authority == nullptr) {
grpc_linked_mdelem* el = b->legacy_index()->named.host;
grpc_mdelem md = GRPC_MDELEM_REF(el->md);
b->Remove(el);
hs_add_error(
error_name, &error,
grpc_metadata_batch_add_head(
b, el,
grpc_mdelem_from_slices(GRPC_MDSTR_AUTHORITY,
grpc_slice_ref_internal(GRPC_MDVALUE(md))),
GRPC_BATCH_AUTHORITY));
GRPC_MDELEM_UNREF(md);
}
if (b->legacy_index()->named.authority == nullptr) {
hs_add_error(error_name, &error,
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"),
GRPC_ERROR_STR_KEY, ":authority"));
}
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
if (!chand->surface_user_agent &&
b->legacy_index()->named.user_agent != nullptr) {
b->Remove(GRPC_BATCH_USER_AGENT);
}
return error;
}
static void hs_recv_initial_metadata_ready(void* user_data,
grpc_error_handle err) {
grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->seen_recv_initial_metadata_ready = true;
if (err == GRPC_ERROR_NONE) {
err = hs_filter_incoming_metadata(elem, calld->recv_initial_metadata);
calld->recv_initial_metadata_ready_error = GRPC_ERROR_REF(err);
if (calld->seen_recv_message_ready) {
// We've already seen the recv_message callback, but we previously
// deferred it, so we need to return it here.
// Replace the recv_message byte stream if needed.
if (calld->have_read_stream) {
calld->recv_message->reset(calld->read_stream.get());
calld->have_read_stream = false;
}
// Re-enter call combiner for original_recv_message_ready, since the
// surface code will release the call combiner for each callback it
// receives.
GRPC_CALL_COMBINER_START(
calld->call_combiner, calld->original_recv_message_ready,
GRPC_ERROR_REF(err),
"resuming recv_message_ready from recv_initial_metadata_ready");
}
} else {
GRPC_ERROR_REF(err);
}
if (calld->seen_recv_trailing_metadata_ready) {
GRPC_CALL_COMBINER_START(calld->call_combiner,
&calld->recv_trailing_metadata_ready,
calld->recv_trailing_metadata_ready_error,
"resuming hs_recv_trailing_metadata_ready from "
"hs_recv_initial_metadata_ready");
}
grpc_core::Closure::Run(DEBUG_LOCATION,
calld->original_recv_initial_metadata_ready, err);
}
static void hs_recv_message_ready(void* user_data, grpc_error_handle err) {
grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->seen_recv_message_ready = true;
if (calld->seen_recv_initial_metadata_ready) {
// We've already seen the recv_initial_metadata callback, so
// replace the recv_message byte stream if needed and invoke the
// original recv_message callback immediately.
if (calld->have_read_stream) {
calld->recv_message->reset(calld->read_stream.get());
calld->have_read_stream = false;
}
grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_message_ready,
GRPC_ERROR_REF(err));
} else {
// We have not yet seen the recv_initial_metadata callback, so we
// need to wait to see if this is a GET request.
// Note that we release the call combiner here, so that other
// callbacks can run.
GRPC_CALL_COMBINER_STOP(
calld->call_combiner,
"pausing recv_message_ready until recv_initial_metadata_ready");
}
}
static void hs_recv_trailing_metadata_ready(void* user_data,
grpc_error_handle err) {
grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
call_data* calld = static_cast<call_data*>(elem->call_data);
if (!calld->seen_recv_initial_metadata_ready) {
calld->recv_trailing_metadata_ready_error = GRPC_ERROR_REF(err);
calld->seen_recv_trailing_metadata_ready = true;
GRPC_CALL_COMBINER_STOP(calld->call_combiner,
"deferring hs_recv_trailing_metadata_ready until "
"ater hs_recv_initial_metadata_ready");
return;
}
err = grpc_error_add_child(
GRPC_ERROR_REF(err),
GRPC_ERROR_REF(calld->recv_initial_metadata_ready_error));
grpc_core::Closure::Run(DEBUG_LOCATION,
calld->original_recv_trailing_metadata_ready, err);
}
static grpc_error_handle hs_mutate_op(grpc_call_element* elem,
grpc_transport_stream_op_batch* op) {
/* grab pointers to our data from the call element */
call_data* calld = static_cast<call_data*>(elem->call_data);
if (op->send_initial_metadata) {
grpc_error_handle error = GRPC_ERROR_NONE;
static const char* error_name = "Failed sending initial metadata";
hs_add_error(
error_name, &error,
grpc_metadata_batch_add_head(
op->payload->send_initial_metadata.send_initial_metadata,
&calld->status, GRPC_MDELEM_STATUS_200, GRPC_BATCH_STATUS));
hs_add_error(error_name, &error,
grpc_metadata_batch_add_tail(
op->payload->send_initial_metadata.send_initial_metadata,
&calld->content_type,
GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC,
GRPC_BATCH_CONTENT_TYPE));
hs_add_error(error_name, &error,
hs_filter_outgoing_metadata(
op->payload->send_initial_metadata.send_initial_metadata));
if (error != GRPC_ERROR_NONE) return error;
}
if (op->recv_initial_metadata) {
/* substitute our callback for the higher callback */
GPR_ASSERT(op->payload->recv_initial_metadata.recv_flags != nullptr);
calld->recv_initial_metadata =
op->payload->recv_initial_metadata.recv_initial_metadata;
calld->recv_initial_metadata_flags =
op->payload->recv_initial_metadata.recv_flags;
calld->original_recv_initial_metadata_ready =
op->payload->recv_initial_metadata.recv_initial_metadata_ready;
op->payload->recv_initial_metadata.recv_initial_metadata_ready =
&calld->recv_initial_metadata_ready;
}
if (op->recv_message) {
calld->recv_message = op->payload->recv_message.recv_message;
calld->original_recv_message_ready =
op->payload->recv_message.recv_message_ready;
op->payload->recv_message.recv_message_ready = &calld->recv_message_ready;
}
if (op->recv_trailing_metadata) {
calld->original_recv_trailing_metadata_ready =
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready;
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&calld->recv_trailing_metadata_ready;
}
if (op->send_trailing_metadata) {
grpc_error_handle error = hs_filter_outgoing_metadata(
op->payload->send_trailing_metadata.send_trailing_metadata);
if (error != GRPC_ERROR_NONE) return error;
}
return GRPC_ERROR_NONE;
}
static void hs_start_transport_stream_op_batch(
grpc_call_element* elem, grpc_transport_stream_op_batch* op) {
GPR_TIMER_SCOPE("hs_start_transport_stream_op_batch", 0);
call_data* calld = static_cast<call_data*>(elem->call_data);
grpc_error_handle error = hs_mutate_op(elem, op);
if (error != GRPC_ERROR_NONE) {
grpc_transport_stream_op_batch_finish_with_failure(op, error,
calld->call_combiner);
} else {
grpc_call_next_op(elem, op);
}
}
/* Constructor for call_data */
static grpc_error_handle hs_init_call_elem(grpc_call_element* elem,
const grpc_call_element_args* args) {
new (elem->call_data) call_data(elem, *args);
return GRPC_ERROR_NONE;
}
/* Destructor for call_data */
static void hs_destroy_call_elem(grpc_call_element* elem,
const grpc_call_final_info* /*final_info*/,
grpc_closure* /*ignored*/) {
call_data* calld = static_cast<call_data*>(elem->call_data);
calld->~call_data();
}
/* Constructor for channel_data */
static grpc_error_handle hs_init_channel_elem(grpc_channel_element* elem,
grpc_channel_element_args* args) {
channel_data* chand = static_cast<channel_data*>(elem->channel_data);
GPR_ASSERT(!args->is_last);
chand->surface_user_agent = grpc_channel_arg_get_bool(
grpc_channel_args_find(args->channel_args,
const_cast<char*>(GRPC_ARG_SURFACE_USER_AGENT)),
true);
return GRPC_ERROR_NONE;
}
/* Destructor for channel data */
static void hs_destroy_channel_elem(grpc_channel_element* /*elem*/) {}
const grpc_channel_filter grpc_http_server_filter = {
hs_start_transport_stream_op_batch,
grpc_channel_next_op,
sizeof(call_data),
hs_init_call_elem,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
hs_destroy_call_elem,
sizeof(channel_data),
hs_init_channel_elem,
hs_destroy_channel_elem,
grpc_channel_next_get_info,
"http-server"};
|
//--------------------------------------------------------------------------------------
// File: GamePad.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "GamePad.h"
#include "PlatformHelpers.h"
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
const float c_XboxOneThumbDeadZone = .24f; // Recommended Xbox One controller deadzone
float ApplyLinearDeadZone(float value, float maxValue, float deadZoneSize)
{
if (value < -deadZoneSize)
{
// Increase negative values to remove the deadzone discontinuity.
value += deadZoneSize;
}
else if (value > deadZoneSize)
{
// Decrease positive values to remove the deadzone discontinuity.
value -= deadZoneSize;
}
else
{
// Values inside the deadzone come out zero.
return 0;
}
// Scale into 0-1 range.
float scaledValue = value / (maxValue - deadZoneSize);
return std::max(-1.f, std::min(scaledValue, 1.f));
}
void ApplyStickDeadZone(float x, float y, GamePad::DeadZone deadZoneMode, float maxValue, float deadZoneSize,
_Out_ float& resultX, _Out_ float& resultY)
{
switch (deadZoneMode)
{
case GamePad::DEAD_ZONE_INDEPENDENT_AXES:
resultX = ApplyLinearDeadZone(x, maxValue, deadZoneSize);
resultY = ApplyLinearDeadZone(y, maxValue, deadZoneSize);
break;
case GamePad::DEAD_ZONE_CIRCULAR:
{
float dist = sqrtf(x*x + y * y);
float wanted = ApplyLinearDeadZone(dist, maxValue, deadZoneSize);
float scale = (wanted > 0.f) ? (wanted / dist) : 0.f;
resultX = std::max(-1.f, std::min(x * scale, 1.f));
resultY = std::max(-1.f, std::min(y * scale, 1.f));
}
break;
default: // GamePad::DEAD_ZONE_NONE
resultX = ApplyLinearDeadZone(x, maxValue, 0);
resultY = ApplyLinearDeadZone(y, maxValue, 0);
break;
}
}
}
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
//======================================================================================
// Windows::Gaming::Input (Windows 10)
//======================================================================================
#pragma warning(push)
#pragma warning(disable : 4471)
#include <windows.gaming.input.h>
#pragma warning(pop)
class GamePad::Impl
{
public:
Impl(GamePad* owner) :
mOwner(owner),
mCtrlChanged(INVALID_HANDLE_VALUE),
mUserChanged(INVALID_HANDLE_VALUE),
mMostRecentGamepad(0),
mStatics{},
mGamePad{},
mUserChangeToken{},
mAddedToken{},
mRemovedToken{},
mChanged{}
{
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation;
if (s_gamePad)
{
throw std::exception("GamePad is a singleton");
}
s_gamePad = this;
mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
if (!mChanged)
{
throw std::exception("CreateEventEx");
}
ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_Gamepad).Get(), mStatics.GetAddressOf()));
typedef __FIEventHandler_1_Windows__CGaming__CInput__CGamepad AddedHandler;
ThrowIfFailed(mStatics->add_GamepadAdded(Callback<AddedHandler>(GamepadAdded).Get(), &mAddedToken));
typedef __FIEventHandler_1_Windows__CGaming__CInput__CGamepad RemovedHandler;
ThrowIfFailed(mStatics->add_GamepadRemoved(Callback<RemovedHandler>(GamepadRemoved).Get(), &mRemovedToken));
ScanGamePads();
}
~Impl()
{
using namespace ABI::Windows::Gaming::Input;
for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
{
if (mGamePad[j])
{
ComPtr<IGameController> ctrl;
HRESULT hr = mGamePad[j].As(&ctrl);
if (SUCCEEDED(hr) && ctrl)
{
(void)ctrl->remove_UserChanged(mUserChangeToken[j]);
mUserChangeToken[j].value = 0;
}
mGamePad[j].Reset();
}
}
if (mStatics)
{
(void)mStatics->remove_GamepadAdded(mAddedToken);
mAddedToken.value = 0;
(void)mStatics->remove_GamepadRemoved(mRemovedToken);
mRemovedToken.value = 0;
mStatics.Reset();
}
s_gamePad = nullptr;
}
void GetState(int player, _Out_ State& state, DeadZone deadZoneMode)
{
using namespace Microsoft::WRL;
using namespace ABI::Windows::Gaming::Input;
if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
{
ScanGamePads();
}
if (player == -1)
player = mMostRecentGamepad;
if ((player >= 0) && (player < MAX_PLAYER_COUNT))
{
if (mGamePad[player])
{
GamepadReading reading;
HRESULT hr = mGamePad[player]->GetCurrentReading(&reading);
if (SUCCEEDED(hr))
{
state.connected = true;
state.packet = reading.Timestamp;
state.buttons.a = (reading.Buttons & GamepadButtons::GamepadButtons_A) != 0;
state.buttons.b = (reading.Buttons & GamepadButtons::GamepadButtons_B) != 0;
state.buttons.x = (reading.Buttons & GamepadButtons::GamepadButtons_X) != 0;
state.buttons.y = (reading.Buttons & GamepadButtons::GamepadButtons_Y) != 0;
state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0;
state.buttons.rightStick = (reading.Buttons & GamepadButtons::GamepadButtons_RightThumbstick) != 0;
state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0;
state.buttons.rightShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_RightShoulder) != 0;
state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0;
state.buttons.start = (reading.Buttons & GamepadButtons::GamepadButtons_Menu) != 0;
state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0;
state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0;
state.dpad.right = (reading.Buttons & GamepadButtons::GamepadButtons_DPadRight) != 0;
state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0;
ApplyStickDeadZone(static_cast<float>(reading.LeftThumbstickX), static_cast<float>(reading.LeftThumbstickY),
deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
state.thumbSticks.leftX, state.thumbSticks.leftY);
ApplyStickDeadZone(static_cast<float>(reading.RightThumbstickX), static_cast<float>(reading.RightThumbstickY),
deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
state.thumbSticks.rightX, state.thumbSticks.rightY);
state.triggers.left = static_cast<float>(reading.LeftTrigger);
state.triggers.right = static_cast<float>(reading.RightTrigger);
return;
}
}
}
memset(&state, 0, sizeof(State));
}
void GetCapabilities(int player, Capabilities& caps)
{
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::System;
using namespace ABI::Windows::Gaming::Input;
if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
{
ScanGamePads();
}
if (player == -1)
player = mMostRecentGamepad;
if ((player >= 0) && (player < MAX_PLAYER_COUNT))
{
if (mGamePad[player])
{
caps.connected = true;
caps.gamepadType = Capabilities::GAMEPAD;
caps.id.clear();
caps.vid = caps.pid = 0;
ComPtr<IGameController> ctrl;
HRESULT hr = mGamePad[player].As(&ctrl);
if (SUCCEEDED(hr) && ctrl)
{
ComPtr<IUser> user;
hr = ctrl->get_User(user.GetAddressOf());
if (SUCCEEDED(hr) && user != nullptr)
{
HString str;
hr = user->get_NonRoamableId(str.GetAddressOf());
if (SUCCEEDED(hr))
{
caps.id = str.GetRawBuffer(nullptr);
}
}
// Requires the Windows 10 Creators Update SDK (15063)
#if defined(NTDDI_WIN10_RS2) && (NTDDI_VERSION >= NTDDI_WIN10_RS2)
ComPtr<IRawGameControllerStatics> rawStatics;
hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Gaming_Input_RawGameController).Get(), rawStatics.GetAddressOf());
if (SUCCEEDED(hr))
{
ComPtr<IRawGameController> raw;
hr = rawStatics->FromGameController(ctrl.Get(), raw.GetAddressOf());
if (SUCCEEDED(hr) && raw)
{
if (FAILED(raw->get_HardwareVendorId(&caps.vid)))
caps.vid = 0;
if (FAILED(raw->get_HardwareProductId(&caps.pid)))
caps.pid = 0;
}
}
#endif // NTDDI_WIN10_RS2
}
return;
}
}
caps.id.clear();
caps = {};
}
bool SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger)
{
using namespace ABI::Windows::Gaming::Input;
if (player == -1)
player = mMostRecentGamepad;
if ((player >= 0) && (player < MAX_PLAYER_COUNT))
{
if (mGamePad[player])
{
GamepadVibration vib;
vib.LeftMotor = double(leftMotor);
vib.RightMotor = double(rightMotor);
vib.LeftTrigger = double(leftTrigger);
vib.RightTrigger = double(rightTrigger);
HRESULT hr = mGamePad[player]->put_Vibration(vib);
if (SUCCEEDED(hr))
return true;
}
}
return false;
}
void Suspend()
{
for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
{
mGamePad[j].Reset();
}
}
void Resume()
{
// Make sure we rescan gamepads
SetEvent(mChanged.get());
}
GamePad* mOwner;
static GamePad::Impl* s_gamePad;
HANDLE mCtrlChanged;
HANDLE mUserChanged;
private:
int mMostRecentGamepad;
void ScanGamePads()
{
using namespace Microsoft::WRL;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Gaming::Input;
ComPtr<IVectorView<Gamepad*>> pads;
ThrowIfFailed(mStatics->get_Gamepads(pads.GetAddressOf()));
unsigned int count = 0;
ThrowIfFailed(pads->get_Size(&count));
// Check for removed gamepads
for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
{
if (mGamePad[j])
{
unsigned int k = 0;
for (; k < count; ++k)
{
ComPtr<IGamepad> pad;
HRESULT hr = pads->GetAt(k, pad.GetAddressOf());
if (SUCCEEDED(hr) && (pad == mGamePad[j]))
{
break;
}
}
if (k >= count)
{
ComPtr<IGameController> ctrl;
HRESULT hr = mGamePad[j].As(&ctrl);
if (SUCCEEDED(hr) && ctrl)
{
(void)ctrl->remove_UserChanged(mUserChangeToken[j]);
mUserChangeToken[j].value = 0;
}
mGamePad[j].Reset();
}
}
}
// Check for added gamepads
for (unsigned int j = 0; j < count; ++j)
{
ComPtr<IGamepad> pad;
HRESULT hr = pads->GetAt(j, pad.GetAddressOf());
if (SUCCEEDED(hr))
{
size_t empty = MAX_PLAYER_COUNT;
size_t k = 0;
for (; k < MAX_PLAYER_COUNT; ++k)
{
if (mGamePad[k] == pad)
{
if (j == (count - 1))
mMostRecentGamepad = static_cast<int>(k);
break;
}
else if (!mGamePad[k])
{
if (empty >= MAX_PLAYER_COUNT)
empty = k;
}
}
if (k >= MAX_PLAYER_COUNT)
{
// Silently ignore "extra" gamepads as there's no hard limit
if (empty < MAX_PLAYER_COUNT)
{
mGamePad[empty] = pad;
if (j == (count - 1))
mMostRecentGamepad = static_cast<int>(empty);
ComPtr<IGameController> ctrl;
hr = pad.As(&ctrl);
if (SUCCEEDED(hr) && ctrl)
{
typedef __FITypedEventHandler_2_Windows__CGaming__CInput__CIGameController_Windows__CSystem__CUserChangedEventArgs UserHandler;
ThrowIfFailed(ctrl->add_UserChanged(Callback<UserHandler>(UserChanged).Get(), &mUserChangeToken[empty]));
}
}
}
}
}
}
ComPtr<ABI::Windows::Gaming::Input::IGamepadStatics> mStatics;
ComPtr<ABI::Windows::Gaming::Input::IGamepad> mGamePad[MAX_PLAYER_COUNT];
EventRegistrationToken mUserChangeToken[MAX_PLAYER_COUNT];
EventRegistrationToken mAddedToken;
EventRegistrationToken mRemovedToken;
ScopedHandle mChanged;
static HRESULT GamepadAdded(IInspectable *, ABI::Windows::Gaming::Input::IGamepad*)
{
if (s_gamePad)
{
SetEvent(s_gamePad->mChanged.get());
if (s_gamePad->mCtrlChanged != INVALID_HANDLE_VALUE)
{
SetEvent(s_gamePad->mCtrlChanged);
}
}
return S_OK;
}
static HRESULT GamepadRemoved(IInspectable *, ABI::Windows::Gaming::Input::IGamepad*)
{
if (s_gamePad)
{
SetEvent(s_gamePad->mChanged.get());
if (s_gamePad->mCtrlChanged != INVALID_HANDLE_VALUE)
{
SetEvent(s_gamePad->mCtrlChanged);
}
}
return S_OK;
}
static HRESULT UserChanged(ABI::Windows::Gaming::Input::IGameController*, ABI::Windows::System::IUserChangedEventArgs*)
{
if (s_gamePad)
{
if (s_gamePad->mUserChanged != INVALID_HANDLE_VALUE)
{
SetEvent(s_gamePad->mUserChanged);
}
}
return S_OK;
}
};
GamePad::Impl* GamePad::Impl::s_gamePad = nullptr;
#elif defined(_XBOX_ONE)
//======================================================================================
// Windows::Xbox::Input (Xbox One)
//======================================================================================
#include <Windows.Xbox.Input.h>
#include <Windows.Foundation.Collections.h>
class GamePad::Impl
{
public:
class GamepadAddedListener : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
ABI::Windows::Foundation::IEventHandler<ABI::Windows::Xbox::Input::GamepadAddedEventArgs *>,
Microsoft::WRL::FtmBase>
{
public:
GamepadAddedListener(HANDLE event) : mEvent(event) {}
STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IGamepadAddedEventArgs *) override
{
SetEvent(mEvent);
auto pad = GamePad::Impl::s_gamePad;
if (pad && pad->mCtrlChanged != INVALID_HANDLE_VALUE)
{
SetEvent(pad->mCtrlChanged);
}
return S_OK;
}
private:
HANDLE mEvent;
};
class GamepadRemovedListener : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
ABI::Windows::Foundation::IEventHandler<ABI::Windows::Xbox::Input::GamepadRemovedEventArgs *>,
Microsoft::WRL::FtmBase>
{
public:
GamepadRemovedListener(HANDLE event) : mEvent(event) {}
STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IGamepadRemovedEventArgs *) override
{
SetEvent(mEvent);
auto pad = GamePad::Impl::s_gamePad;
if (pad && pad->mCtrlChanged != INVALID_HANDLE_VALUE)
{
SetEvent(pad->mCtrlChanged);
}
return S_OK;
}
private:
HANDLE mEvent;
};
class UserPairingListener : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
ABI::Windows::Foundation::IEventHandler<ABI::Windows::Xbox::Input::ControllerPairingChangedEventArgs *>,
Microsoft::WRL::FtmBase>
{
public:
UserPairingListener() noexcept {}
STDMETHOD(Invoke)(_In_ IInspectable *, _In_ ABI::Windows::Xbox::Input::IControllerPairingChangedEventArgs *) override
{
auto pad = GamePad::Impl::s_gamePad;
if (pad && pad->mUserChanged != INVALID_HANDLE_VALUE)
{
SetEvent(pad->mUserChanged);
}
return S_OK;
}
};
Impl(GamePad *owner) :
mOwner(owner),
mCtrlChanged(INVALID_HANDLE_VALUE),
mUserChanged(INVALID_HANDLE_VALUE),
mMostRecentGamepad(0),
mStatics{},
mStaticsCtrl{},
mGamePad{},
mAddedToken{},
mRemovedToken{},
mUserParingToken{},
mChanged{}
{
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation;
if (s_gamePad)
{
throw std::exception("GamePad is a singleton");
}
s_gamePad = this;
mChanged.reset(CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE));
if (!mChanged)
{
throw std::exception("CreateEventEx");
}
ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Gamepad).Get(), mStatics.GetAddressOf()));
ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_Xbox_Input_Controller).Get(), mStaticsCtrl.GetAddressOf()));
ThrowIfFailed(mStatics->add_GamepadAdded(Make<GamepadAddedListener>(mChanged.get()).Get(), &mAddedToken));
ThrowIfFailed(mStatics->add_GamepadRemoved(Make<GamepadRemovedListener>(mChanged.get()).Get(), &mRemovedToken));
ThrowIfFailed(mStaticsCtrl->add_ControllerPairingChanged(Make<UserPairingListener>().Get(), &mUserParingToken));
ScanGamePads();
}
~Impl()
{
if (mStatics)
{
(void)mStatics->remove_GamepadAdded(mAddedToken);
mAddedToken.value = 0;
(void)mStatics->remove_GamepadRemoved(mRemovedToken);
mRemovedToken.value = 0;
mStatics.Reset();
}
if (mStaticsCtrl)
{
(void)mStaticsCtrl->remove_ControllerPairingChanged(mUserParingToken);
mUserParingToken.value = 0;
mStaticsCtrl.Reset();
}
s_gamePad = nullptr;
}
void GetState(int player, _Out_ State& state, DeadZone deadZoneMode)
{
using namespace Microsoft::WRL;
using namespace ABI::Windows::Xbox::Input;
if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
{
ScanGamePads();
}
if (player == -1)
player = mMostRecentGamepad;
if ((player >= 0) && (player < MAX_PLAYER_COUNT))
{
if (mGamePad[player])
{
RawGamepadReading reading;
HRESULT hr = mGamePad[player]->GetRawCurrentReading(&reading);
if (SUCCEEDED(hr))
{
state.connected = true;
state.packet = reading.Timestamp;
state.buttons.a = (reading.Buttons & GamepadButtons::GamepadButtons_A) != 0;
state.buttons.b = (reading.Buttons & GamepadButtons::GamepadButtons_B) != 0;
state.buttons.x = (reading.Buttons & GamepadButtons::GamepadButtons_X) != 0;
state.buttons.y = (reading.Buttons & GamepadButtons::GamepadButtons_Y) != 0;
state.buttons.leftStick = (reading.Buttons & GamepadButtons::GamepadButtons_LeftThumbstick) != 0;
state.buttons.rightStick = (reading.Buttons & GamepadButtons::GamepadButtons_RightThumbstick) != 0;
state.buttons.leftShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_LeftShoulder) != 0;
state.buttons.rightShoulder = (reading.Buttons & GamepadButtons::GamepadButtons_RightShoulder) != 0;
state.buttons.back = (reading.Buttons & GamepadButtons::GamepadButtons_View) != 0;
state.buttons.start = (reading.Buttons & GamepadButtons::GamepadButtons_Menu) != 0;
state.dpad.up = (reading.Buttons & GamepadButtons::GamepadButtons_DPadUp) != 0;
state.dpad.down = (reading.Buttons & GamepadButtons::GamepadButtons_DPadDown) != 0;
state.dpad.right = (reading.Buttons & GamepadButtons::GamepadButtons_DPadRight) != 0;
state.dpad.left = (reading.Buttons & GamepadButtons::GamepadButtons_DPadLeft) != 0;
ApplyStickDeadZone(reading.LeftThumbstickX, reading.LeftThumbstickY,
deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
state.thumbSticks.leftX, state.thumbSticks.leftY);
ApplyStickDeadZone(reading.RightThumbstickX, reading.RightThumbstickY,
deadZoneMode, 1.f, c_XboxOneThumbDeadZone,
state.thumbSticks.rightX, state.thumbSticks.rightY);
state.triggers.left = reading.LeftTrigger;
state.triggers.right = reading.RightTrigger;
return;
}
}
}
memset(&state, 0, sizeof(State));
}
void GetCapabilities(int player, _Out_ Capabilities& caps)
{
using namespace Microsoft::WRL;
using namespace ABI::Windows::Xbox::Input;
if (WaitForSingleObjectEx(mChanged.get(), 0, FALSE) == WAIT_OBJECT_0)
{
ScanGamePads();
}
if (player == -1)
player = mMostRecentGamepad;
if ((player >= 0) && (player < MAX_PLAYER_COUNT))
{
if (mGamePad[player])
{
caps.connected = true;
caps.gamepadType = Capabilities::UNKNOWN;
caps.id = 0;
caps.vid = caps.pid = 0;
ComPtr<IController> ctrl;
HRESULT hr = mGamePad[player].As(&ctrl);
if (SUCCEEDED(hr) && ctrl)
{
hr = ctrl->get_Id(&caps.id);
if (FAILED(hr))
caps.id = 0;
Wrappers::HString str;
hr = ctrl->get_Type(str.GetAddressOf());
if (SUCCEEDED(hr))
{
const wchar_t* typeStr = str.GetRawBuffer(nullptr);
if (_wcsicmp(typeStr, L"Windows.Xbox.Input.Gamepad") == 0)
{
caps.gamepadType = Capabilities::GAMEPAD;
}
else if (_wcsicmp(typeStr, L"Microsoft.Xbox.Input.ArcadeStick") == 0)
{
caps.gamepadType = Capabilities::ARCADE_STICK;
}
else if (_wcsicmp(typeStr, L"Microsoft.Xbox.Input.Wheel") == 0)
{
caps.gamepadType = Capabilities::WHEEL;
}
}
}
#if _XDK_VER >= 0x42ED07E4 /* XDK Edition 180400 */
ComPtr<IController3> ctrl3;
hr = mGamePad[player].As(&ctrl3);
if (SUCCEEDED(hr) && ctrl3)
{
if (FAILED(ctrl3->get_HardwareVendorId(&caps.vid)))
caps.vid = 0;
if (FAILED(ctrl3->get_HardwareProductId(&caps.pid)))
caps.pid = 0;
}
#endif
return;
}
}
memset(&caps, 0, sizeof(Capabilities));
}
bool SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger)
{
using namespace ABI::Windows::Xbox::Input;
if (player == -1)
player = mMostRecentGamepad;
if ((player >= 0) && (player < MAX_PLAYER_COUNT))
{
if (mGamePad[player])
{
HRESULT hr;
try
{
GamepadVibration vib;
vib.LeftMotorLevel = leftMotor;
vib.RightMotorLevel = rightMotor;
vib.LeftTriggerLevel = leftTrigger;
vib.RightTriggerLevel = rightTrigger;
hr = mGamePad[player]->SetVibration(vib);
}
catch (...)
{
// Handle case where gamepad might be invalid
hr = E_FAIL;
}
if (SUCCEEDED(hr))
return true;
}
}
return false;
}
void Suspend()
{
for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
{
mGamePad[j].Reset();
}
}
void Resume()
{
// Make sure we rescan gamepads
SetEvent(mChanged.get());
}
GamePad* mOwner;
static GamePad::Impl* s_gamePad;
HANDLE mCtrlChanged;
HANDLE mUserChanged;
private:
int mMostRecentGamepad;
void ScanGamePads()
{
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Xbox::Input;
ComPtr<IVectorView<IGamepad*>> pads;
ThrowIfFailed(mStatics->get_Gamepads(pads.GetAddressOf()));
unsigned int count = 0;
ThrowIfFailed(pads->get_Size(&count));
// Check for removed gamepads
for (size_t j = 0; j < MAX_PLAYER_COUNT; ++j)
{
if (mGamePad[j])
{
unsigned int k = 0;
for (; k < count; ++k)
{
ComPtr<IGamepad> pad;
HRESULT hr = pads->GetAt(k, pad.GetAddressOf());
if (SUCCEEDED(hr) && (pad == mGamePad[j]))
{
break;
}
}
if (k >= count)
{
mGamePad[j].Reset();
}
}
}
// Check for added gamepads
for (unsigned int j = 0; j < count; ++j)
{
ComPtr<IGamepad> pad;
HRESULT hr = pads->GetAt(j, pad.GetAddressOf());
if (SUCCEEDED(hr))
{
size_t empty = MAX_PLAYER_COUNT;
size_t k = 0;
for (; k < MAX_PLAYER_COUNT; ++k)
{
if (mGamePad[k] == pad)
{
if (!j)
mMostRecentGamepad = static_cast<int>(k);
break;
}
else if (!mGamePad[k])
{
if (empty >= MAX_PLAYER_COUNT)
empty = k;
}
}
if (k >= MAX_PLAYER_COUNT)
{
if (empty >= MAX_PLAYER_COUNT)
{
throw std::exception("Too many gamepads found");
}
mGamePad[empty] = pad;
if (!j)
mMostRecentGamepad = static_cast<int>(empty);
}
}
}
}
ComPtr<ABI::Windows::Xbox::Input::IGamepadStatics> mStatics;
ComPtr<ABI::Windows::Xbox::Input::IControllerStatics> mStaticsCtrl;
ComPtr<ABI::Windows::Xbox::Input::IGamepad> mGamePad[MAX_PLAYER_COUNT];
EventRegistrationToken mAddedToken;
EventRegistrationToken mRemovedToken;
EventRegistrationToken mUserParingToken;
ScopedHandle mChanged;
};
GamePad::Impl* GamePad::Impl::s_gamePad = nullptr;
#else
//======================================================================================
// XInput
//======================================================================================
#include <Xinput.h>
static_assert(GamePad::MAX_PLAYER_COUNT == XUSER_MAX_COUNT, "xinput.h mismatch");
class GamePad::Impl
{
public:
Impl(GamePad* owner) :
mOwner(owner),
mConnected{},
mLastReadTime{}
#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
, mLeftMotor{}
, mRightMotor{}
, mSuspended(false)
#endif
{
for (int j = 0; j < XUSER_MAX_COUNT; ++j)
{
ClearSlot(j, 0);
}
if (s_gamePad)
{
throw std::exception("GamePad is a singleton");
}
s_gamePad = this;
}
~Impl()
{
s_gamePad = nullptr;
}
void GetState(int player, _Out_ State& state, DeadZone deadZoneMode)
{
if (player == -1)
player = GetMostRecent();
ULONGLONG time = GetTickCount64();
if (!ThrottleRetry(player, time))
{
#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
if (mSuspended)
{
memset(&state, 0, sizeof(State));
state.connected = mConnected[player];
return;
}
#endif
XINPUT_STATE xstate;
DWORD result = XInputGetState(DWORD(player), &xstate);
if (result == ERROR_DEVICE_NOT_CONNECTED)
{
ClearSlot(player, time);
}
else
{
if (!mConnected[player])
mLastReadTime[player] = time;
mConnected[player] = true;
state.connected = true;
state.packet = xstate.dwPacketNumber;
WORD xbuttons = xstate.Gamepad.wButtons;
state.buttons.a = (xbuttons & XINPUT_GAMEPAD_A) != 0;
state.buttons.b = (xbuttons & XINPUT_GAMEPAD_B) != 0;
state.buttons.x = (xbuttons & XINPUT_GAMEPAD_X) != 0;
state.buttons.y = (xbuttons & XINPUT_GAMEPAD_Y) != 0;
state.buttons.leftStick = (xbuttons & XINPUT_GAMEPAD_LEFT_THUMB) != 0;
state.buttons.rightStick = (xbuttons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0;
state.buttons.leftShoulder = (xbuttons & XINPUT_GAMEPAD_LEFT_SHOULDER) != 0;
state.buttons.rightShoulder = (xbuttons & XINPUT_GAMEPAD_RIGHT_SHOULDER) != 0;
state.buttons.back = (xbuttons & XINPUT_GAMEPAD_BACK) != 0;
state.buttons.start = (xbuttons & XINPUT_GAMEPAD_START) != 0;
state.dpad.up = (xbuttons & XINPUT_GAMEPAD_DPAD_UP) != 0;
state.dpad.down = (xbuttons & XINPUT_GAMEPAD_DPAD_DOWN) != 0;
state.dpad.right = (xbuttons & XINPUT_GAMEPAD_DPAD_RIGHT) != 0;
state.dpad.left = (xbuttons & XINPUT_GAMEPAD_DPAD_LEFT) != 0;
if (deadZoneMode == DEAD_ZONE_NONE)
{
state.triggers.left = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, 0.f);
state.triggers.right = ApplyLinearDeadZone(float(xstate.Gamepad.bRightTrigger), 255.f, 0.f);
}
else
{
state.triggers.left = ApplyLinearDeadZone(float(xstate.Gamepad.bLeftTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD));
state.triggers.right = ApplyLinearDeadZone(float(xstate.Gamepad.bRightTrigger), 255.f, float(XINPUT_GAMEPAD_TRIGGER_THRESHOLD));
}
ApplyStickDeadZone(float(xstate.Gamepad.sThumbLX), float(xstate.Gamepad.sThumbLY),
deadZoneMode, 32767.f, float(XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE),
state.thumbSticks.leftX, state.thumbSticks.leftY);
ApplyStickDeadZone(float(xstate.Gamepad.sThumbRX), float(xstate.Gamepad.sThumbRY),
deadZoneMode, 32767.f, float(XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE),
state.thumbSticks.rightX, state.thumbSticks.rightY);
return;
}
}
memset(&state, 0, sizeof(State));
}
void GetCapabilities(int player, _Out_ Capabilities& caps)
{
if (player == -1)
player = GetMostRecent();
ULONGLONG time = GetTickCount64();
if (!ThrottleRetry(player, time))
{
XINPUT_CAPABILITIES xcaps;
DWORD result = XInputGetCapabilities(DWORD(player), 0, &xcaps);
if (result == ERROR_DEVICE_NOT_CONNECTED)
{
ClearSlot(player, time);
}
else
{
if (!mConnected[player])
mLastReadTime[player] = time;
mConnected[player] = true;
caps.connected = true;
caps.id = uint64_t(player);
if (xcaps.Type == XINPUT_DEVTYPE_GAMEPAD)
{
static_assert(Capabilities::GAMEPAD == XINPUT_DEVSUBTYPE_GAMEPAD, "xinput.h mismatch");
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
static_assert(XINPUT_DEVSUBTYPE_WHEEL == Capabilities::WHEEL, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_ARCADE_STICK == Capabilities::ARCADE_STICK, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_FLIGHT_STICK == Capabilities::FLIGHT_STICK, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_DANCE_PAD == Capabilities::DANCE_PAD, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_GUITAR == Capabilities::GUITAR, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE == Capabilities::GUITAR_ALTERNATE, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_DRUM_KIT == Capabilities::DRUM_KIT, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_GUITAR_BASS == Capabilities::GUITAR_BASS, "xinput.h mismatch");
static_assert(XINPUT_DEVSUBTYPE_ARCADE_PAD == Capabilities::ARCADE_PAD, "xinput.h mismatch");
#endif
caps.gamepadType = Capabilities::Type(xcaps.SubType);
}
// Hard-coded VID/PID
caps.vid = 0x045E;
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
caps.pid = (xcaps.Flags & XINPUT_CAPS_WIRELESS) ? 0x0719 : 0;
#else
caps.pid = 0;
#endif
return;
}
}
memset(&caps, 0, sizeof(Capabilities));
}
bool SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger)
{
if (player == -1)
player = GetMostRecent();
ULONGLONG time = GetTickCount64();
if (ThrottleRetry(player, time))
{
return false;
}
// XInput does not provide a way to set the left/right trigger impulse motors on the Xbox One Controller,
// and these motors are not present on the Xbox 360 Common Controller
UNREFERENCED_PARAMETER(leftTrigger);
UNREFERENCED_PARAMETER(rightTrigger);
#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
mLeftMotor[player] = leftMotor;
mRightMotor[player] = rightMotor;
if (mSuspended)
return mConnected[player];
#endif
XINPUT_VIBRATION xvibration;
xvibration.wLeftMotorSpeed = WORD(leftMotor * 0xFFFF);
xvibration.wRightMotorSpeed = WORD(rightMotor * 0xFFFF);
DWORD result = XInputSetState(DWORD(player), &xvibration);
if (result == ERROR_DEVICE_NOT_CONNECTED)
{
ClearSlot(player, time);
return false;
}
else
{
if (!mConnected[player])
mLastReadTime[player] = time;
mConnected[player] = true;
return (result == ERROR_SUCCESS);
}
}
void Suspend()
{
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
XInputEnable(FALSE);
#else
// For XInput 9.1.0, we have to emulate the behavior of XInputEnable( FALSE )
if (!mSuspended)
{
for (size_t j = 0; j < XUSER_MAX_COUNT; ++j)
{
if (mConnected[j])
{
XINPUT_VIBRATION xvibration;
xvibration.wLeftMotorSpeed = xvibration.wRightMotorSpeed = 0;
(void)XInputSetState(DWORD(j), &xvibration);
}
}
mSuspended = true;
}
#endif
}
void Resume()
{
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
XInputEnable(TRUE);
#else
// For XInput 9.1.0, we have to emulate the behavior of XInputEnable( TRUE )
if (mSuspended)
{
ULONGLONG time = GetTickCount64();
for (int j = 0; j < XUSER_MAX_COUNT; ++j)
{
if (mConnected[j])
{
XINPUT_VIBRATION xvibration;
xvibration.wLeftMotorSpeed = WORD(mLeftMotor[j] * 0xFFFF);
xvibration.wRightMotorSpeed = WORD(mRightMotor[j] * 0xFFFF);
DWORD result = XInputSetState(DWORD(j), &xvibration);
if (result == ERROR_DEVICE_NOT_CONNECTED)
{
ClearSlot(j, time);
}
}
}
mSuspended = false;
}
#endif
}
GamePad* mOwner;
static GamePad::Impl* s_gamePad;
private:
bool mConnected[XUSER_MAX_COUNT];
ULONGLONG mLastReadTime[XUSER_MAX_COUNT];
#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
// Variables for emulating XInputEnable on XInput 9.1.0
float mLeftMotor[XUSER_MAX_COUNT];
float mRightMotor[XUSER_MAX_COUNT];
bool mSuspended;
#endif
bool ThrottleRetry(int player, ULONGLONG time)
{
// This function minimizes a potential performance issue with XInput on Windows when
// checking a disconnected controller slot which requires device enumeration.
// This throttling keeps checks for newly connected gamepads to about once a second
if ((player < 0) || (player >= XUSER_MAX_COUNT))
return true;
if (mConnected[player])
return false;
for (int j = 0; j < XUSER_MAX_COUNT; ++j)
{
if (!mConnected[j])
{
LONGLONG delta = LONGLONG(time) - LONGLONG(mLastReadTime[j]);
LONGLONG interval = 1000;
if (j != player)
interval /= 4;
if ((delta >= 0) && (delta < interval))
return true;
}
}
return false;
}
void ClearSlot(int player, ULONGLONG time)
{
mConnected[player] = false;
mLastReadTime[player] = time;
#if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
mLeftMotor[player] = mRightMotor[player] = 0.f;
#endif
}
int GetMostRecent()
{
int player = -1;
ULONGLONG time = 0;
for (size_t j = 0; j < XUSER_MAX_COUNT; ++j)
{
if (mConnected[j] && (mLastReadTime[j] > time))
{
time = mLastReadTime[j];
player = static_cast<int>(j);
}
}
return player;
}
};
GamePad::Impl* GamePad::Impl::s_gamePad = nullptr;
#endif
#pragma warning( disable : 4355 )
// Public constructor.
GamePad::GamePad() noexcept(false)
: pImpl(std::make_unique<Impl>(this))
{
}
// Move constructor.
GamePad::GamePad(GamePad&& moveFrom) noexcept
: pImpl(std::move(moveFrom.pImpl))
{
pImpl->mOwner = this;
}
// Move assignment.
GamePad& GamePad::operator= (GamePad&& moveFrom) noexcept
{
pImpl = std::move(moveFrom.pImpl);
pImpl->mOwner = this;
return *this;
}
// Public destructor.
GamePad::~GamePad()
{
}
GamePad::State GamePad::GetState(int player, DeadZone deadZoneMode)
{
State state;
pImpl->GetState(player, state, deadZoneMode);
return state;
}
GamePad::Capabilities GamePad::GetCapabilities(int player)
{
Capabilities caps;
pImpl->GetCapabilities(player, caps);
return caps;
}
bool GamePad::SetVibration(int player, float leftMotor, float rightMotor, float leftTrigger, float rightTrigger)
{
return pImpl->SetVibration(player, leftMotor, rightMotor, leftTrigger, rightTrigger);
}
void GamePad::Suspend()
{
pImpl->Suspend();
}
void GamePad::Resume()
{
pImpl->Resume();
}
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN10) || defined(_XBOX_ONE)
void GamePad::RegisterEvents(HANDLE ctrlChanged, HANDLE userChanged)
{
pImpl->mCtrlChanged = (!ctrlChanged) ? INVALID_HANDLE_VALUE : ctrlChanged;
pImpl->mUserChanged = (!userChanged) ? INVALID_HANDLE_VALUE : userChanged;
}
#endif
GamePad& GamePad::Get()
{
if (!Impl::s_gamePad || !Impl::s_gamePad->mOwner)
throw std::exception("GamePad is a singleton");
return *Impl::s_gamePad->mOwner;
}
//======================================================================================
// ButtonStateTracker
//======================================================================================
#define UPDATE_BUTTON_STATE(field) field = static_cast<ButtonState>( ( !!state.buttons.field ) | ( ( !!state.buttons.field ^ !!lastState.buttons.field ) << 1 ) );
void GamePad::ButtonStateTracker::Update(const GamePad::State& state)
{
UPDATE_BUTTON_STATE(a)
assert((!state.buttons.a && !lastState.buttons.a) == (a == UP));
assert((state.buttons.a && lastState.buttons.a) == (a == HELD));
assert((!state.buttons.a && lastState.buttons.a) == (a == RELEASED));
assert((state.buttons.a && !lastState.buttons.a) == (a == PRESSED));
UPDATE_BUTTON_STATE(b)
UPDATE_BUTTON_STATE(x)
UPDATE_BUTTON_STATE(y)
UPDATE_BUTTON_STATE(leftStick)
UPDATE_BUTTON_STATE(rightStick)
UPDATE_BUTTON_STATE(leftShoulder)
UPDATE_BUTTON_STATE(rightShoulder)
UPDATE_BUTTON_STATE(back)
UPDATE_BUTTON_STATE(start)
dpadUp = static_cast<ButtonState>((!!state.dpad.up) | ((!!state.dpad.up ^ !!lastState.dpad.up) << 1));
dpadDown = static_cast<ButtonState>((!!state.dpad.down) | ((!!state.dpad.down ^ !!lastState.dpad.down) << 1));
dpadLeft = static_cast<ButtonState>((!!state.dpad.left) | ((!!state.dpad.left ^ !!lastState.dpad.left) << 1));
dpadRight = static_cast<ButtonState>((!!state.dpad.right) | ((!!state.dpad.right ^ !!lastState.dpad.right) << 1));
assert((!state.dpad.up && !lastState.dpad.up) == (dpadUp == UP));
assert((state.dpad.up && lastState.dpad.up) == (dpadUp == HELD));
assert((!state.dpad.up && lastState.dpad.up) == (dpadUp == RELEASED));
assert((state.dpad.up && !lastState.dpad.up) == (dpadUp == PRESSED));
// Handle 'threshold' tests which emulate buttons
bool threshold = state.IsLeftThumbStickUp();
leftStickUp = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickUp()) << 1));
threshold = state.IsLeftThumbStickDown();
leftStickDown = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickDown()) << 1));
threshold = state.IsLeftThumbStickLeft();
leftStickLeft = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickLeft()) << 1));
threshold = state.IsLeftThumbStickRight();
leftStickRight = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftThumbStickRight()) << 1));
threshold = state.IsRightThumbStickUp();
rightStickUp = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickUp()) << 1));
threshold = state.IsRightThumbStickDown();
rightStickDown = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickDown()) << 1));
threshold = state.IsRightThumbStickLeft();
rightStickLeft = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickLeft()) << 1));
threshold = state.IsRightThumbStickRight();
rightStickRight = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightThumbStickRight()) << 1));
threshold = state.IsLeftTriggerPressed();
leftTrigger = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsLeftTriggerPressed()) << 1));
threshold = state.IsRightTriggerPressed();
rightTrigger = static_cast<ButtonState>((!!threshold) | ((!!threshold ^ !!lastState.IsRightTriggerPressed()) << 1));
lastState = state;
}
#undef UPDATE_BUTTON_STATE
void GamePad::ButtonStateTracker::Reset() noexcept
{
memset(this, 0, sizeof(ButtonStateTracker));
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: maxdesalle <mdesalle@student.s19.be> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/27 19:02:12 by maxdesall #+# #+# */
/* Updated: 2021/10/27 19:17:10 by maxdesall ### ########.fr */
/* */
/* ************************************************************************** */
#include "Scalar.hpp"
int main(int argc, char **argv)
{
if (argc != 2)
{
std::cout << "Only one argument is allowed";
std::cout << std::endl;
return (0);
}
std::string arg = argv[1];
Scalar convert(arg);
char c;
int i;
float f;
double d;
std::cout << std::fixed << std::setprecision(1);
c = static_cast<char>(convert);
i = static_cast<int>(convert);
f = static_cast<float>(convert);
d = static_cast<double>(convert);
return (0);
}
|
#include <GuiFoundationPCH.h>
#include <Foundation/IO/MemoryStream.h>
#include <Foundation/Serialization/DdlSerializer.h>
#include <GuiFoundation/Action/ActionManager.h>
#include <GuiFoundation/Action/ActionMapManager.h>
#include <GuiFoundation/Action/EditActions.h>
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
#include <ToolsFoundation/Command/TreeCommands.h>
#include <ToolsFoundation/Serialization/DocumentObjectConverter.h>
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezEditAction, 1, ezRTTINoAllocator)
EZ_END_DYNAMIC_REFLECTED_TYPE;
////////////////////////////////////////////////////////////////////////
// ezEditActions
////////////////////////////////////////////////////////////////////////
ezActionDescriptorHandle ezEditActions::s_hEditCategory;
ezActionDescriptorHandle ezEditActions::s_hCopy;
ezActionDescriptorHandle ezEditActions::s_hPaste;
ezActionDescriptorHandle ezEditActions::s_hPasteAsChild;
ezActionDescriptorHandle ezEditActions::s_hDelete;
void ezEditActions::RegisterActions()
{
s_hEditCategory = EZ_REGISTER_CATEGORY("EditCategory");
s_hCopy = EZ_REGISTER_ACTION_1("Selection.Copy", ezActionScope::Document, "Document", "Ctrl+C", ezEditAction, ezEditAction::ButtonType::Copy);
s_hPaste = EZ_REGISTER_ACTION_1("Selection.Paste", ezActionScope::Document, "Document", "Ctrl+V", ezEditAction, ezEditAction::ButtonType::Paste);
s_hPasteAsChild =
EZ_REGISTER_ACTION_1("Selection.PasteAsChild", ezActionScope::Document, "Document", "", ezEditAction, ezEditAction::ButtonType::PasteAsChild);
s_hDelete = EZ_REGISTER_ACTION_1("Selection.Delete", ezActionScope::Document, "Document", "", ezEditAction, ezEditAction::ButtonType::Delete);
}
void ezEditActions::UnregisterActions()
{
ezActionManager::UnregisterAction(s_hEditCategory);
ezActionManager::UnregisterAction(s_hCopy);
ezActionManager::UnregisterAction(s_hPaste);
ezActionManager::UnregisterAction(s_hPasteAsChild);
ezActionManager::UnregisterAction(s_hDelete);
}
void ezEditActions::MapActions(const char* szMapping, const char* szPath, bool bDeleteAction, bool bPasteAsChildAction)
{
ezActionMap* pMap = ezActionMapManager::GetActionMap(szMapping);
EZ_ASSERT_DEV(pMap != nullptr, "The given mapping ('{0}') does not exist, mapping the edit actions failed!", szMapping);
ezStringBuilder sSubPath(szPath, "/EditCategory");
pMap->MapAction(s_hEditCategory, szPath, 3.5f);
pMap->MapAction(s_hCopy, sSubPath, 1.0f);
pMap->MapAction(s_hPaste, sSubPath, 2.0f);
if (bPasteAsChildAction)
pMap->MapAction(s_hPasteAsChild, sSubPath, 2.5f);
if (bDeleteAction)
pMap->MapAction(s_hDelete, sSubPath, 3.0f);
}
void ezEditActions::MapContextMenuActions(const char* szMapping, const char* szPath)
{
ezActionMap* pMap = ezActionMapManager::GetActionMap(szMapping);
EZ_ASSERT_DEV(pMap != nullptr, "The given mapping ('{0}') does not exist, mapping the edit actions failed!", szMapping);
ezStringBuilder sSubPath(szPath, "/EditCategory");
pMap->MapAction(s_hEditCategory, szPath, 10.0f);
pMap->MapAction(s_hCopy, sSubPath, 1.0f);
pMap->MapAction(s_hPasteAsChild, sSubPath, 2.0f);
pMap->MapAction(s_hDelete, sSubPath, 3.0f);
}
void ezEditActions::MapViewContextMenuActions(const char* szMapping, const char* szPath)
{
ezActionMap* pMap = ezActionMapManager::GetActionMap(szMapping);
EZ_ASSERT_DEV(pMap != nullptr, "The given mapping ('{0}') does not exist, mapping the edit actions failed!", szMapping);
ezStringBuilder sSubPath(szPath, "/EditCategory");
pMap->MapAction(s_hEditCategory, szPath, 10.0f);
pMap->MapAction(s_hCopy, sSubPath, 1.0f);
pMap->MapAction(s_hPasteAsChild, sSubPath, 2.0f);
pMap->MapAction(s_hDelete, sSubPath, 3.0f);
}
////////////////////////////////////////////////////////////////////////
// ezEditAction
////////////////////////////////////////////////////////////////////////
ezEditAction::ezEditAction(const ezActionContext& context, const char* szName, ButtonType button)
: ezButtonAction(context, szName, false, "")
{
m_ButtonType = button;
switch (m_ButtonType)
{
case ezEditAction::ButtonType::Copy:
SetIconPath(":/GuiFoundation/Icons/Copy16.png");
break;
case ezEditAction::ButtonType::Paste:
SetIconPath(":/GuiFoundation/Icons/Paste16.png");
break;
case ezEditAction::ButtonType::PasteAsChild:
SetIconPath(":/GuiFoundation/Icons/Paste16.png"); /// \todo Icon
break;
case ezEditAction::ButtonType::Delete:
SetIconPath(":/GuiFoundation/Icons/Delete16.png");
break;
}
m_Context.m_pDocument->GetSelectionManager()->m_Events.AddEventHandler(ezMakeDelegate(&ezEditAction::SelectionEventHandler, this));
if (m_ButtonType == ButtonType::Copy || m_ButtonType == ButtonType::Delete)
{
SetEnabled(!m_Context.m_pDocument->GetSelectionManager()->IsSelectionEmpty());
}
}
ezEditAction::~ezEditAction()
{
if (m_Context.m_pDocument)
{
m_Context.m_pDocument->GetSelectionManager()->m_Events.RemoveEventHandler(ezMakeDelegate(&ezEditAction::SelectionEventHandler, this));
}
}
void ezEditAction::Execute(const ezVariant& value)
{
switch (m_ButtonType)
{
case ezEditAction::ButtonType::Copy:
{
ezStringBuilder sMimeType;
ezAbstractObjectGraph graph;
if (!m_Context.m_pDocument->CopySelectedObjects(graph, sMimeType))
break;
// Serialize to string
ezMemoryStreamStorage streamStorage;
ezMemoryStreamWriter memoryWriter(&streamStorage);
ezAbstractGraphDdlSerializer::Write(memoryWriter, &graph, nullptr, false);
memoryWriter.WriteBytes("\0", 1); // null terminate
// Write to clipboard
QClipboard* clipboard = QApplication::clipboard();
QMimeData* mimeData = new QMimeData();
QByteArray encodedData((const char*)streamStorage.GetData(), streamStorage.GetStorageSize());
mimeData->setData(sMimeType.GetData(), encodedData);
mimeData->setText(QString::fromUtf8((const char*)streamStorage.GetData()));
clipboard->setMimeData(mimeData);
}
break;
case ezEditAction::ButtonType::Paste:
case ezEditAction::ButtonType::PasteAsChild:
{
// Check for clipboard data of the correct type.
QClipboard* clipboard = QApplication::clipboard();
auto mimedata = clipboard->mimeData();
ezHybridArray<ezString, 4> MimeTypes;
m_Context.m_pDocument->GetSupportedMimeTypesForPasting(MimeTypes);
ezInt32 iFormat = -1;
{
for (ezUInt32 i = 0; i < MimeTypes.GetCount(); ++i)
{
if (mimedata->hasFormat(MimeTypes[i].GetData()))
{
iFormat = i;
break;
}
}
if (iFormat < 0)
break;
}
// Paste at current selected object.
ezPasteObjectsCommand cmd;
cmd.m_sMimeType = MimeTypes[iFormat];
QByteArray ba = mimedata->data(MimeTypes[iFormat].GetData());
cmd.m_sGraphTextFormat = ba.data();
if (m_ButtonType == ButtonType::PasteAsChild)
{
if (!m_Context.m_pDocument->GetSelectionManager()->IsSelectionEmpty())
cmd.m_Parent = m_Context.m_pDocument->GetSelectionManager()->GetSelection().PeekBack()->GetGuid();
}
auto history = m_Context.m_pDocument->GetCommandHistory();
history->StartTransaction("Paste");
if (history->AddCommand(cmd).Failed())
history->CancelTransaction();
else
history->FinishTransaction();
}
break;
case ezEditAction::ButtonType::Delete:
{
m_Context.m_pDocument->DeleteSelectedObjects();
}
break;
}
}
void ezEditAction::SelectionEventHandler(const ezSelectionManagerEvent& e)
{
if (m_ButtonType == ButtonType::Copy || m_ButtonType == ButtonType::Delete)
{
SetEnabled(!m_Context.m_pDocument->GetSelectionManager()->IsSelectionEmpty());
}
}
|
// stdafx.cpp : source file that includes just the standard includes
// vvWinSync.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// reference any additional headers you need in STDAFX.H
// and not in this file
|
/*=============================================================================
Copyright (c) 2005-2013 Joel de Guzman
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(BOOST_FUSION_MAP_IMPL_02032013_2233)
#define BOOST_FUSION_MAP_IMPL_02032013_2233
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/detail/access.hpp>
#include <boost/fusion/iterator/deref.hpp>
#include <boost/fusion/iterator/next.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/identity.hpp>
namespace boost { namespace fusion
{
struct fusion_sequence_tag;
}}
namespace boost { namespace fusion { namespace detail
{
struct map_impl_from_iterator {};
template <int index, typename ...T>
struct map_impl;
template <int index_>
struct map_impl<index_>
{
typedef fusion_sequence_tag tag;
static int const index = index_;
static int const size = 0;
BOOST_FUSION_GPU_ENABLED
map_impl() {}
template <typename Iterator>
BOOST_FUSION_GPU_ENABLED
map_impl(Iterator const& iter, map_impl_from_iterator)
{}
template <typename Iterator>
BOOST_FUSION_GPU_ENABLED
void assign(Iterator const& iter, map_impl_from_iterator)
{}
BOOST_FUSION_GPU_ENABLED
void get();
BOOST_FUSION_GPU_ENABLED
void get_val();
BOOST_FUSION_GPU_ENABLED
void get_key();
};
template <int index_, typename Pair, typename ...T>
struct map_impl<index_, Pair, T...> : map_impl<index_ + 1, T...>
{
typedef fusion_sequence_tag tag;
typedef map_impl<index_+1, T...> rest_type;
using rest_type::get;
using rest_type::get_val;
using rest_type::get_key;
static int const index = index_;
static int const size = rest_type::size + 1;
typedef Pair pair_type;
typedef typename Pair::first_type key_type;
typedef typename Pair::second_type value_type;
BOOST_FUSION_GPU_ENABLED
map_impl()
: rest_type(), element()
{}
BOOST_FUSION_GPU_ENABLED
map_impl(map_impl const& rhs)
: rest_type(rhs.get_base()), element(rhs.element)
{}
BOOST_FUSION_GPU_ENABLED
map_impl(map_impl&& rhs)
: rest_type(std::forward<rest_type>(*static_cast<rest_type*>(&rhs)))
, element(std::forward<Pair>(rhs.element))
{}
template <typename ...U>
BOOST_FUSION_GPU_ENABLED
map_impl(map_impl<index, U...> const& rhs)
: rest_type(rhs.get_base()), element(rhs.element)
{}
BOOST_FUSION_GPU_ENABLED
map_impl(typename detail::call_param<Pair>::type element_
, typename detail::call_param<T>::type... rest)
: rest_type(rest...), element(element_)
{}
BOOST_FUSION_GPU_ENABLED
map_impl(Pair&& element_, T&&... rest)
: rest_type(std::forward<T>(rest)...)
, element(std::forward<Pair>(element_))
{}
template <typename Iterator>
BOOST_FUSION_GPU_ENABLED
map_impl(Iterator const& iter, map_impl_from_iterator fi)
: rest_type(fusion::next(iter), fi)
, element(*iter)
{}
BOOST_FUSION_GPU_ENABLED
rest_type& get_base()
{
return *this;
}
BOOST_FUSION_GPU_ENABLED
rest_type const& get_base() const
{
return *this;
}
BOOST_FUSION_GPU_ENABLED
value_type get_val(mpl::identity<key_type>);
BOOST_FUSION_GPU_ENABLED
pair_type get_val(mpl::int_<index>);
BOOST_FUSION_GPU_ENABLED
value_type get_val(mpl::identity<key_type>) const;
BOOST_FUSION_GPU_ENABLED
pair_type get_val(mpl::int_<index>) const;
BOOST_FUSION_GPU_ENABLED
mpl::identity<key_type> get_key(mpl::int_<index>);
BOOST_FUSION_GPU_ENABLED
mpl::identity<key_type> get_key(mpl::int_<index>) const;
BOOST_FUSION_GPU_ENABLED
typename cref_result<value_type>::type
get(mpl::identity<key_type>) const
{
return element.second;
}
BOOST_FUSION_GPU_ENABLED
typename ref_result<value_type>::type
get(mpl::identity<key_type>)
{
return element.second;
}
BOOST_FUSION_GPU_ENABLED
typename cref_result<pair_type>::type
get(mpl::int_<index>) const
{
return element;
}
BOOST_FUSION_GPU_ENABLED
typename ref_result<pair_type>::type
get(mpl::int_<index>)
{
return element;
}
template <typename ...U>
BOOST_FUSION_GPU_ENABLED
map_impl& operator=(map_impl<index, U...> const& rhs)
{
rest_type::operator=(rhs);
element = rhs.element;
return *this;
}
BOOST_FUSION_GPU_ENABLED
map_impl& operator=(map_impl const& rhs)
{
rest_type::operator=(rhs);
element = rhs.element;
return *this;
}
BOOST_FUSION_GPU_ENABLED
map_impl& operator=(map_impl&& rhs)
{
rest_type::operator=(std::forward<map_impl>(rhs));
element = std::forward<Pair>(rhs.element);
return *this;
}
template <typename Iterator>
BOOST_FUSION_GPU_ENABLED
void assign(Iterator const& iter, map_impl_from_iterator fi)
{
rest_type::assign(fusion::next(iter), fi);
element = *iter;
}
Pair element;
};
}}}
#endif
|
#include "System.h"
#include "ros/ros.h"
#include <Task.h>
#include <csetjmp>
jmp_buf g_buf;
int main(int argc, char** argv) {
ros::init(argc, argv, "hive_connect");
std::shared_ptr<ros::NodeHandle> nodeHandle =
std::make_shared<ros::NodeHandle>(*(new ros::NodeHandle("~")));
setjmp(g_buf);
app_main();
Task::startScheduler(); // This is also done in the hidden esp main
}
|
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include "CalllogHelper.hpp"
#include <Service/Service.hpp>
#include <endpoints/Endpoint.hpp>
namespace sdesktop::endpoints
{
class CalllogEndpoint : public Endpoint
{
private:
std::unique_ptr<CalllogHelper> helper;
public:
explicit CalllogEndpoint(sys::Service *_ownerServicePtr) : Endpoint(_ownerServicePtr)
{
debugName = "CalllogEndpoint";
helper = std::make_unique<CalllogHelper>(ownerServicePtr);
}
auto handle(Context &context) -> void override;
};
} // namespace sdesktop::endpoints
|
#include "main.hpp"
// Outputs
const int pin_led = 13;
// Set up some StateMachine objects
// Pulse LED once for 200 ms immediately
Stimulus led(0, 200, digitalOn, digitalOff, pin_led);
// Wait 500 ms, then pulse LED 5 times for 50 ms each with 100 ms period
StimulusRepeating led_repeating(500, 50, digitalOn, digitalOff, pin_led, 100, 5);
// Take reading every 5 ms, 200 readings total, for 1 second of data
SensorRepeating sensor_repeat(0, takeReading, 5, 200);
// The setup routine runs once when you press reset or get reset from Serial port
void setup() {
// Initialize the digital pin as an output.
pinMode(pin_led, OUTPUT);
// Default all output pins to LOW - for some reason they were floating high on the Due before I (Shane) added this
digitalWrite(pin_led, LOW);
Serial.begin(9600);
led.start();
led_repeating.start();
sensor_repeat.start();
}
// The loop routine runs over and over again forever
// In this loop we have our StateMachines check their states and update as necessary
// The StateMachines handle their own timing
// It's critical that this loop runs fast (< 1 ms period) so don't put anything in here that takes time to execute
void loop() {
led.update();
led_repeating.update();
sensor_repeat.update();
if (sensor_repeat.checkState()==sensor_repeat.OFF) { sendSensorData(); }
}
// These functions are called by the state machine objects
void digitalOn(int pin) {
digitalWrite(pin, HIGH);
}
void digitalOff(int pin) {
digitalWrite(pin, LOW);
}
// We call by reference so we can update the local variables in "reading_function" of StateMachine object
void takeReading(timems_t &time, int32_t &reading) {
time = millis();
// Here we just generate random data but we could instead read from an analog pin or a device connected through I2C or SPI
reading = 5000-random(10000); // for testing
}
void sendSensorData() {
// You'll need to implement this yourself based on how you are interfacing with the Arduino
}
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/platform_util.h"
#include <stdio.h>
#include "base/files/file_util.h"
#include "base/process/kill.h"
#include "base/process/launch.h"
#include "url/gurl.h"
namespace {
bool XDGUtil(const std::string& util, const std::string& arg) {
std::vector<std::string> argv;
argv.push_back(util);
argv.push_back(arg);
base::LaunchOptions options;
options.allow_new_privs = true;
// xdg-open can fall back on mailcap which eventually might plumb through
// to a command that needs a terminal. Set the environment variable telling
// it that we definitely don't have a terminal available and that it should
// bring up a new terminal if necessary. See "man mailcap".
options.environ["MM_NOTTTY"] = "1";
base::Process process = base::LaunchProcess(argv, options);
if (!process.IsValid())
return false;
int exit_code = -1;
if (!process.WaitForExit(&exit_code))
return false;
return (exit_code == 0);
}
void XDGOpen(const std::string& path) {
XDGUtil("xdg-open", path);
}
void XDGEmail(const std::string& email) {
XDGUtil("xdg-email", email);
}
} // namespace
namespace platform_util {
// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
void ShowItemInFolder(const base::FilePath& full_path) {
base::FilePath dir = full_path.DirName();
if (!base::DirectoryExists(dir))
return;
XDGOpen(dir.value());
}
void OpenItem(const base::FilePath& full_path) {
XDGOpen(full_path.value());
}
void OpenExternal(const GURL& url) {
if (url.SchemeIs("mailto"))
XDGEmail(url.spec());
else
XDGOpen(url.spec());
}
bool MoveItemToTrash(const base::FilePath& full_path) {
return XDGUtil("gvfs-trash", full_path.value());
}
void Beep() {
// echo '\a' > /dev/console
FILE* console = fopen("/dev/console", "r");
if (console == NULL)
return;
fprintf(console, "\a");
fclose(console);
}
} // namespace platform_util
|
#include "common.h"
#include "ClientTesterImpl.h"
namespace tester {
using namespace sirius;
const ClientTesterImpl::TestCases ClientTesterImpl::gTestCases[] = {
{
.type = PREVIEW_NV21,
.func = &ClientTesterImpl::testPreview,
.arg = 0,
},
{
.type = PREVIEW_NV21,
.func = &ClientTesterImpl::testPreview,
.arg = 1,
},
{
.type = PREVIEW_NV21,
.func = &ClientTesterImpl::testPreview,
.arg = 2,
},
{
.type = PREVIEW_NV21,
.func = &ClientTesterImpl::testPreview,
.arg = 3,
},
{
.type = PREVIEW_NV21,
.func = &ClientTesterImpl::testPreview,
.arg = 4,
},
{
.type = PREVIEW_NV21,
.func = &ClientTesterImpl::testPreview,
.arg = 5,
},
{
.type = PREVIEW_NV21,
.func = &ClientTesterImpl::testPreview,
.arg = 6,
},
{
.type = PICTURE_NV21,
.func = &ClientTesterImpl::testNV21Picture,
.arg = 0,
},
{
.type = PICTURE_NV21,
.func = &ClientTesterImpl::testNV21Picture,
.arg = 1,
},
{
.type = PICTURE_NV21,
.func = &ClientTesterImpl::testNV21Picture,
.arg = 2,
},
{
.type = PICTURE_NV21,
.func = &ClientTesterImpl::testNV21Picture,
.arg = 3,
},
{
.type = PICTURE_NV21,
.func = &ClientTesterImpl::testNV21Picture,
.arg = 4,
},
{
.type = PICTURE_NV21,
.func = &ClientTesterImpl::testNV21Picture,
.arg = 5,
},
{
.type = PICTURE_NV21,
.func = &ClientTesterImpl::testNV21Picture,
.arg = 6,
},
{
.type = PICTURE_BAYER,
.func = &ClientTesterImpl::testBayerPicture,
.arg = 0,
},
{
.type = PICTURE_BAYER,
.func = &ClientTesterImpl::testBayerPicture,
.arg = 1,
},
{
.type = PICTURE_BAYER,
.func = &ClientTesterImpl::testBayerPicture,
.arg = 2,
},
{
.type = PICTURE_BAYER,
.func = &ClientTesterImpl::testBayerPicture,
.arg = 3,
},
{
.type = PICTURE_BAYER,
.func = &ClientTesterImpl::testBayerPicture,
.arg = 4,
},
{
.type = PICTURE_BAYER,
.func = &ClientTesterImpl::testBayerPicture,
.arg = 5,
},
{
.type = PICTURE_BAYER,
.func = &ClientTesterImpl::testBayerPicture,
.arg = 6,
},
{
.type = EXTENDED_EVENT,
.func = &ClientTesterImpl::testEvents,
.arg = 0,
},
{
.type = EXTENDED_EVENT,
.func = &ClientTesterImpl::testEvents,
.arg = 1,
},
{
.type = EXTENDED_EVENT,
.func = &ClientTesterImpl::testEvents,
.arg = 2,
},
{
.type = EXTENDED_EVENT,
.func = &ClientTesterImpl::testEvents,
.arg = 3,
},
{
.type = EXTENDED_EVENT,
.func = &ClientTesterImpl::testEvents,
.arg = 4,
},
{
.type = EXTENDED_EVENT,
.func = &ClientTesterImpl::testEvents,
.arg = 5,
},
{
.type = EXTENDED_EVENT,
.func = &ClientTesterImpl::testEvents,
.arg = 6,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 0,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 1,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 2,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 3,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 4,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 5,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 6,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 7,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 8,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 9,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 10,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 11,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 12,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 13,
},
{
.type = CUSTOM_DATA,
.func = &ClientTesterImpl::testCustomData,
.arg = 14,
},
{
.type = REQUEST_TYPE_MAX_INVALID, // Mixture
.func = &ClientTesterImpl::testMixture,
.arg = 0,
},
{
.type = REQUEST_TYPE_MAX_INVALID, // Mixture
.func = &ClientTesterImpl::testMixture,
.arg = 1,
},
};
int32_t ClientTesterImpl::getTestRounds(RequestType type)
{
int32_t result = 0;
for (uint32_t i = 0; i < ARRAYSIZE(gTestCases); i++) {
if (type == gTestCases[i].type) {
result++;
}
}
return result;
}
int32_t ClientTesterImpl::RunTest(RequestType type, int32_t round)
{
int32_t rc = NOT_FOUND;
TestFunction func = NULL;
int32_t arg = 0;
int32_t index = 0;
for (uint32_t i = 0; i < ARRAYSIZE(gTestCases); i++) {
if (type == gTestCases[i].type) {
if (index == round) {
func = gTestCases[i].func;
arg = gTestCases[i].arg;
rc = NO_ERROR;
break;
}
index++;
}
}
if (!SUCCEED(rc)) {
LOGE(mModule, "Not found test function. Request %s round %d, %d",
getRequestName(type), round, rc);
}
if (SUCCEED(rc)) {
rc = (this->*func)(arg);
if (!SUCCEED(rc)) {
LOGE(mModule, "Test failed, Request %s round %d, %d",
getRequestName(type), round, rc);
}
}
return rc;
}
};
|
// Copyright 2021 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#include <lib/memalloc/range.h>
#include <lib/stdcompat/span.h>
#include <zircon/boot/image.h>
#include <string_view>
#include <type_traits>
namespace memalloc {
using namespace std::string_view_literals;
std::string_view ToString(Type type) {
using namespace std::string_view_literals;
switch (type) {
case Type::kFreeRam:
return "free RAM"sv;
case Type::kReserved:
return "reserved"sv;
case Type::kPeripheral:
return "peripheral"sv;
case Type::kPoolBookkeeping:
return "bookkeeping"sv;
case Type::kPhysKernel:
return "phys kernel image"sv;
case Type::kKernel:
return "kernel image"sv;
case Type::kFixedAddressKernel:
return "fixed-address kernel image"sv;
case Type::kKernelStorage:
return "decompressed kernel payload"sv;
case Type::kDataZbi:
return "data ZBI"sv;
case Type::kLegacyBootData:
return "legacy boot data";
case Type::kIdentityPageTables:
return "identity page tables"sv;
case Type::kPhysScratch:
return "phys scratch"sv;
case Type::kPoolTestPayload:
return "memalloc::Pool test payload"sv;
case Type::kZbiTestPayload:
return "ZBI test payload"sv;
case Type::kTestRamReserve:
return "kernel.test.ram.reserve"sv;
case Type::kNvram:
return "ZBI_TYPE_NVRAM"sv;
case Type::kMaxExtended:
return "kMaxExtended"sv;
}
return "unknown"sv;
}
cpp20::span<Range> AsRanges(cpp20::span<zbi_mem_range_t> ranges) {
static_assert(std::is_standard_layout_v<Range>);
static_assert(std::is_standard_layout_v<zbi_mem_range_t>);
static_assert(offsetof(Range, addr) == offsetof(zbi_mem_range_t, paddr));
static_assert(offsetof(Range, size) == offsetof(zbi_mem_range_t, length));
static_assert(offsetof(Range, type) == offsetof(zbi_mem_range_t, type));
for (zbi_mem_range_t& range : ranges) {
range.reserved = 0;
}
return {reinterpret_cast<Range*>(ranges.data()), ranges.size()};
}
} // namespace memalloc
|
/*
* Copyright Andrey Semashev 2007 - 2015.
* 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)
*/
/*!
* \file support/std_regex.hpp
* \author Andrey Semashev
* \date 19.03.2014
*
* This header enables \c std::regex support for Boost.Log.
*/
#ifndef BOOST_LOG_SUPPORT_STD_REGEX_HPP_INCLUDED_
#define BOOST_LOG_SUPPORT_STD_REGEX_HPP_INCLUDED_
#include <boost/log/detail/config.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined(BOOST_NO_CXX11_HDR_REGEX)
#if defined(__GNUC__)
#pragma message "Boost.Log: This header requires support for std::regex in the standard library."
#elif defined(_MSC_VER)
#pragma message("Boost.Log: This header requires support for std::regex in the standard library.")
#endif
#else // defined(BOOST_NO_CXX11_HDR_REGEX)
#include <regex>
#include <string>
#include <boost/log/utility/functional/matches.hpp>
#include <boost/log/detail/header.hpp>
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
//! This tag type is used if an expression is recognized as \c std::regex
struct std_regex_expression_tag;
//! The metafunction detects the matching expression kind and returns a tag that is used to specialize \c match_traits
template< typename CharT, typename ReTraitsT >
struct matching_expression_kind< std::basic_regex< CharT, ReTraitsT > >
{
typedef std_regex_expression_tag type;
};
//! The matching function implementation
template< typename ExpressionT >
struct match_traits< ExpressionT, std_regex_expression_tag >
{
typedef ExpressionT compiled_type;
static compiled_type compile(ExpressionT const& expr) { return expr; }
template< typename StringT, typename CharT, typename ReTraitsT >
static bool matches(StringT const& str, std::basic_regex< CharT, ReTraitsT > const& expr, std::regex_constants::match_flag_type flags = std::regex_constants::match_default)
{
return std::regex_match(str.begin(), str.end(), expr, flags);
}
template< typename CharT, typename StringTraitsT, typename AllocatorT, typename ReTraitsT >
static bool matches(std::basic_string< CharT, StringTraitsT, AllocatorT > const& str, std::basic_regex< CharT, ReTraitsT > const& expr, std::regex_constants::match_flag_type flags = std::regex_constants::match_default)
{
const CharT* p = str.c_str();
return std::regex_match(p, p + str.size(), expr, flags);
}
};
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // defined(BOOST_NO_CXX11_HDR_REGEX)
#endif // BOOST_LOG_SUPPORT_STD_REGEX_HPP_INCLUDED_
|
// Copyright 2022, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Johannes Kalmbach <kalmbach@cs.uni-freiburg.de>
#include <gtest/gtest.h>
#include <algorithm>
#include "../src/util/Iterators.h"
auto testIterator = [](const auto& input, auto begin, auto end) {
auto it = begin;
ASSERT_EQ(input[0], *it);
ASSERT_EQ(input[0], *it++);
ASSERT_EQ(input[1], *it);
ASSERT_EQ(input[2], *++it);
ASSERT_EQ(input[2], *it);
ASSERT_EQ(input[2], *it--);
ASSERT_EQ(input[1], *it);
ASSERT_EQ(input[0], *--it);
ASSERT_EQ(input[2], it[2]);
ASSERT_EQ(input[2], *(it + 2));
ASSERT_EQ(input[2], *(2 + it));
ASSERT_EQ(input[3], *(it += 3));
ASSERT_EQ(input[2], *(it += -1));
ASSERT_EQ(input[2], *(it));
ASSERT_EQ(input[0], *(it -= 2));
ASSERT_EQ(input[2], *(it -= -2));
ASSERT_EQ(input[2], *(it));
it = end + (-1);
ASSERT_EQ(input.back(), *it);
ASSERT_EQ(static_cast<int64_t>(input.size()), end - begin);
};
TEST(RandomAccessIterator, Vector) {
std::vector<int> f{3, 62, 1023, -43817, 14, 42};
using Iterator = ad_utility::IteratorForAccessOperator<
std::vector<int>, ad_utility::AccessViaBracketOperator>;
Iterator begin = Iterator{&f, 0};
Iterator end = Iterator{&f, f.size()};
testIterator(f, begin, end);
}
TEST(RandomAccessIterator, DummyRandomAccessContainer) {
struct TestRandomAccessContainer {
uint64_t get(uint64_t index) const { return 42 * index; }
// operator[] is required for the test lambda.
uint64_t operator[](uint64_t index) const { return get(index); }
[[nodiscard]] auto front() const { return get(0); }
[[nodiscard]] auto back() const { return get(42); }
[[nodiscard]] auto size() const { return 43; }
};
auto getFromTestContainer = [](const TestRandomAccessContainer& container,
uint64_t i) { return container.get(i); };
using Iterator =
ad_utility::IteratorForAccessOperator<TestRandomAccessContainer,
decltype(getFromTestContainer)>;
TestRandomAccessContainer d;
Iterator begin = Iterator{&d, 0};
Iterator end = Iterator{&d, 43};
testIterator(d, begin, end);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.