text string | size int64 | token_count int64 |
|---|---|---|
/*
* Video mode file
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "Video/Core/VideoMode.h"
namespace Fork
{
namespace Video
{
/* --- VideoMode structure --- */
VideoMode::VideoMode(const Math::Size2ui& vmResolution, int vmColorDepth, bool vmIsFullscreen) :
resolution { vmResolution },
colorBitDepth { vmColorDepth },
isFullscreen { vmIsFullscreen }
{
}
bool VideoMode::operator == (const VideoMode& other) const
{
return
resolution == other.resolution &&
colorBitDepth == other.colorBitDepth &&
isFullscreen == other.isFullscreen;
}
bool VideoMode::operator != (const VideoMode& other) const
{
return !(*this == other);
}
bool VideoMode::operator < (const VideoMode& other) const
{
if (resolution < other.resolution)
return true;
if (resolution > other.resolution)
return false;
if (colorBitDepth < other.colorBitDepth)
return true;
if (colorBitDepth > other.colorBitDepth)
return false;
return !isFullscreen && other.isFullscreen;
}
bool VideoMode::operator <= (const VideoMode& other) const
{
return *this < other || *this == other;
}
bool VideoMode::operator > (const VideoMode& other) const
{
if (resolution > other.resolution)
return true;
if (resolution < other.resolution)
return false;
if (colorBitDepth > other.colorBitDepth)
return true;
if (colorBitDepth < other.colorBitDepth)
return false;
return isFullscreen && !other.isFullscreen;
}
bool VideoMode::operator >= (const VideoMode& other) const
{
return *this > other || *this == other;
}
Math::Size2ui VideoMode::HDReady()
{
return { 1280, 720 };
}
Math::Size2ui VideoMode::FullHD()
{
return { 1920, 1080 };
}
Math::Size2ui VideoMode::UltraHD()
{
return { 3840, 2160 };
}
/* --- DisplayDevice structure --- */
DisplayDevice::DisplayDevice(const std::wstring& videoController, const std::wstring& monitor) :
videoControllerID { videoController },
monitorID { monitor }
{
}
} // /namespace Video
} // /namespace Fork
// ======================== | 2,260 | 735 |
#include "Bullet.h"
#include "Game.h"
Bullet::Bullet(glm::vec3 position, glm::vec3 rotation, glm::vec3 direction) : Object("arrow.bmf")
{
this->setType(ObjectType::Object_Bullet);
this->position = position;
this->rotation = rotation;
this->movement = glm::normalize(direction) * speed;
this->name = "Bullet";
this->setCollisionBoxType(CollisionBoxType::cube);
}
void Bullet::fall()
{
this->Object::fall();
if (movement == glm::vec3(0, 0, 0)) return;
if (position.y < 0.5) { movement=glm::vec3(0, 0, 0); return; }
float gegk = movement.y;
float ank = sqrt(pow(movement.x, 2) + pow(movement.z, 2));
rotation.z = atan(gegk / ank) * 180 / 3.14;
rotation.z += 270;
}
void Bullet::checkHit()
{
if (movement.x == 0 && movement.z == 0) return;
CollisionResult collisionresult = checkCollision(); //doubled with the normal collision detection. this can be improved
if (!collisionresult.collided) return;
for (CollidedObject* collidedObject : collisionresult.collidedObjectList)
{
if (collidedObject->object->getType() == ObjectType::Object_Bullet) return;
if (collidedObject->object->getType() == ObjectType::Object_Environment) return;
//if (collidedObject->object->getType() == ObjectType::Object_Player) return;
if (collidedObject->object->getType() == ObjectType::Object_Entity) return;
this->registerHit();
collidedObject->object->registerHit();
Logger::log(collidedObject->object->printObject() + " was hit");
}
}
void Bullet::registerHit()
{
this->health = 0;
}
| 1,511 | 576 |
/*
Copyright 2015 Esri
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.
A local copy of the license and additional notices are located with the
source distribution at:
http://github.com/Esri/lerc/
Contributors: Thomas Maurer
*/
#include "BitStuffer2.h"
#include <algorithm>
#include <cstring>
using namespace std;
NAMESPACE_LERC_START
// -------------------------------------------------------------------------- ;
// if you change Encode(...) / Decode(...), don't forget to update ComputeNumBytesNeeded(...)
bool BitStuffer2::EncodeSimple(Byte** ppByte, const vector<unsigned int>& dataVec)
{
if (!ppByte || dataVec.empty())
return false;
unsigned int maxElem = *max_element(dataVec.begin(), dataVec.end());
int numBits = 0;
while ((numBits < 32) && (maxElem >> numBits))
numBits++;
if (numBits >= 32)
return false;
Byte numBitsByte = (Byte)numBits;
unsigned int numElements = (unsigned int)dataVec.size();
unsigned int numUInts = (numElements * numBits + 31) / 32;
// use the upper 2 bits to encode the type used for numElements: Byte, ushort, or uint
int n = NumBytesUInt(numElements);
int bits67 = (n == 4) ? 0 : 3 - n;
numBitsByte |= bits67 << 6;
// bit5 = 0 means simple mode
**ppByte = numBitsByte;
(*ppByte)++;
if (!EncodeUInt(ppByte, numElements, n))
return false;
if (numUInts > 0) // numBits can be 0, then we only write the header
BitStuff(ppByte, dataVec, numBits);
return true;
}
// -------------------------------------------------------------------------- ;
bool BitStuffer2::EncodeLut(Byte** ppByte,
const vector<Quant>& sortedDataVec) const
{
if (!ppByte || sortedDataVec.empty())
return false;
if (sortedDataVec[0].first != 0) // corresponds to min
return false;
// collect the different values for the lut
unsigned int numElem = (unsigned int)sortedDataVec.size();
unsigned int indexLut = 0;
m_tmpLutVec.resize(0); // omit the 0 throughout that corresponds to min
m_tmpIndexVec.assign(numElem, 0);
for (unsigned int i = 1; i < numElem; i++)
{
unsigned int prev = static_cast<unsigned int>(sortedDataVec[i - 1].first);
m_tmpIndexVec[sortedDataVec[i - 1].second] = indexLut;
if (sortedDataVec[i].first != prev)
{
m_tmpLutVec.push_back(static_cast<unsigned int>(sortedDataVec[i].first));
indexLut++;
}
}
m_tmpIndexVec[sortedDataVec[numElem - 1].second] = indexLut; // don't forget the last one
// write first 2 data elements same as simple, but bit5 set to 1
unsigned int maxElem = m_tmpLutVec.back();
int numBits = 0;
while ((numBits < 32) && (maxElem >> numBits))
numBits++;
if (numBits >= 32)
return false;
Byte numBitsByte = (Byte)numBits;
// use the upper 2 bits to encode the type used for numElem: byte, ushort, or uint
int n = NumBytesUInt(numElem);
int bits67 = (n == 4) ? 0 : 3 - n;
numBitsByte |= bits67 << 6;
numBitsByte |= (1 << 5); // bit 5 = 1 means lut mode
**ppByte = numBitsByte;
(*ppByte)++;
if (!EncodeUInt(ppByte, numElem, n)) // numElements = numIndexes to lut
return false;
unsigned int nLut = (unsigned int)m_tmpLutVec.size();
if (nLut < 1 || nLut >= 255)
return false;
**ppByte = (Byte)nLut + 1; // size of lut, incl the 0
(*ppByte)++;
BitStuff(ppByte, m_tmpLutVec, numBits); // lut
int nBitsLut = 0;
while (nLut >> nBitsLut)
nBitsLut++;
BitStuff(ppByte, m_tmpIndexVec, nBitsLut); // indexes
return true;
}
// -------------------------------------------------------------------------- ;
// if you change Encode(...) / Decode(...), don't forget to update ComputeNumBytesNeeded(...)
bool BitStuffer2::Decode(const Byte** ppByte, vector<unsigned int>& dataVec) const
{
if (!ppByte)
return false;
Byte numBitsByte = **ppByte;
(*ppByte)++;
int bits67 = numBitsByte >> 6;
int n = (bits67 == 0) ? 4 : 3 - bits67;
bool doLut = (numBitsByte & (1 << 5)) ? true : false; // bit 5
numBitsByte &= 31; // bits 0-4;
unsigned int numElements = 0;
if (!DecodeUInt(ppByte, numElements, n))
return false;
int numBits = numBitsByte;
dataVec.resize(numElements, 0); // init with 0
if (!doLut)
{
if (numBits > 0) // numBits can be 0
BitUnStuff(ppByte, dataVec, numElements, numBits);
}
else
{
Byte nLutByte = **ppByte;
(*ppByte)++;
int nLut = nLutByte - 1;
BitUnStuff(ppByte, m_tmpLutVec, nLut, numBits); // unstuff lut w/o the 0
int nBitsLut = 0;
while (nLut >> nBitsLut)
nBitsLut++;
BitUnStuff(ppByte, dataVec, numElements, nBitsLut); // unstuff indexes
// replace indexes by values
m_tmpLutVec.insert(m_tmpLutVec.begin(), 0); // put back in the 0
for (unsigned int i = 0; i < numElements; i++)
dataVec[i] = m_tmpLutVec[dataVec[i]];
}
return true;
}
// -------------------------------------------------------------------------- ;
unsigned int BitStuffer2::ComputeNumBytesNeededLut(const vector<Quant >& sortedDataVec,
bool& doLut)
{
unsigned int maxElem = static_cast<unsigned int>(sortedDataVec.back().first);
unsigned int numElem = (unsigned int)sortedDataVec.size();
int numBits = 0;
while ((numBits < 32) && (maxElem >> numBits))
numBits++;
unsigned int numBytes = 1 + NumBytesUInt(numElem) + ((numElem * numBits + 7) >> 3);
// go through and count how often the value changes
int nLut = 0;
for (unsigned int i = 1; i < numElem; i++)
if (sortedDataVec[i].first != sortedDataVec[i - 1].first)
nLut++;
int nBitsLut = 0;
while (nLut >> nBitsLut)
nBitsLut++;
unsigned int numBitsTotalLut = nLut * numBits; // num bits w/o the 0
unsigned int numBytesLut = 1 + NumBytesUInt(numElem) + 1 + ((numBitsTotalLut + 7) >> 3) + ((numElem * nBitsLut + 7) >> 3);
doLut = numBytesLut < numBytes;
return min(numBytesLut, numBytes);
}
// -------------------------------------------------------------------------- ;
// -------------------------------------------------------------------------- ;
void BitStuffer2::BitStuff(Byte** ppByte, const vector<unsigned int>& dataVec, int numBits)
{
unsigned int numElements = (unsigned int)dataVec.size();
unsigned int numUInts = (numElements * numBits + 31) / 32;
unsigned int numBytes = numUInts * sizeof(unsigned int);
unsigned int* arr = (unsigned int*)(*ppByte);
memset(arr, 0, numBytes);
// do the stuffing
const unsigned int* srcPtr = &dataVec[0];
unsigned int* dstPtr = arr;
int bitPos = 0;
for (unsigned int i = 0; i < numElements; i++)
{
if (32 - bitPos >= numBits)
{
unsigned int dstValue;
memcpy(&dstValue, dstPtr, sizeof(unsigned int));
dstValue |= (*srcPtr++) << (32 - bitPos - numBits);
memcpy(dstPtr, &dstValue, sizeof(unsigned int));
bitPos += numBits;
if (bitPos == 32) // shift >= 32 is undefined
{
bitPos = 0;
dstPtr++;
}
}
else
{
unsigned int dstValue;
int n = numBits - (32 - bitPos);
memcpy(&dstValue, dstPtr, sizeof(unsigned int));
dstValue |= (*srcPtr ) >> n;
memcpy(dstPtr, &dstValue, sizeof(unsigned int));
dstPtr ++;
memcpy(&dstValue, dstPtr, sizeof(unsigned int));
dstValue |= (*srcPtr++) << (32 - n);
memcpy(dstPtr, &dstValue, sizeof(unsigned int));
bitPos = n;
}
}
// save the 0-3 bytes not used in the last UInt
unsigned int numBytesNotNeeded = NumTailBytesNotNeeded(numElements, numBits);
unsigned int n = numBytesNotNeeded;
while (n--)
{
unsigned int dstValue;
memcpy(&dstValue, dstPtr, sizeof(unsigned int));
dstValue >>= 8;
memcpy(dstPtr, &dstValue, sizeof(unsigned int));
}
*ppByte += numBytes - numBytesNotNeeded;
}
// -------------------------------------------------------------------------- ;
void BitStuffer2::BitUnStuff(const Byte** ppByte, vector<unsigned int>& dataVec,
unsigned int numElements, int numBits) const
{
dataVec.resize(numElements, 0); // init with 0
unsigned int numUInts = (numElements * numBits + 31) / 32;
unsigned int numBytes = numUInts * sizeof(unsigned int);
unsigned int* arr = (unsigned int*)(*ppByte);
unsigned int* srcPtr = arr;
srcPtr += numUInts;
// needed to save the 0-3 bytes not used in the last UInt
srcPtr--;
unsigned int lastUInt;
memcpy(&lastUInt, srcPtr, sizeof(unsigned int));
unsigned int numBytesNotNeeded = NumTailBytesNotNeeded(numElements, numBits);
unsigned int n = numBytesNotNeeded;
while (n--)
{
unsigned int srcValue;
memcpy(&srcValue, srcPtr, sizeof(unsigned int));
srcValue <<= 8;
memcpy(srcPtr, &srcValue, sizeof(unsigned int));
}
// do the un-stuffing
srcPtr = arr;
unsigned int* dstPtr = &dataVec[0];
int bitPos = 0;
for (unsigned int i = 0; i < numElements; i++)
{
if (32 - bitPos >= numBits)
{
unsigned int srcValue;
memcpy(&srcValue, srcPtr, sizeof(unsigned int));
unsigned int n2 = srcValue << bitPos;
*dstPtr++ = n2 >> (32 - numBits);
bitPos += numBits;
// cppcheck-suppress shiftTooManyBits
if (bitPos == 32) // shift >= 32 is undefined
{
bitPos = 0;
srcPtr++;
}
}
else
{
unsigned int srcValue;
memcpy(&srcValue, srcPtr, sizeof(unsigned int));
srcPtr ++;
unsigned int n2 = srcValue << bitPos;
*dstPtr = n2 >> (32 - numBits);
bitPos -= (32 - numBits);
memcpy(&srcValue, srcPtr, sizeof(unsigned int));
*dstPtr++ |= srcValue >> (32 - bitPos);
}
}
if (numBytesNotNeeded > 0)
{
memcpy(srcPtr, &lastUInt, sizeof(unsigned int)); // restore the last UInt
}
*ppByte += numBytes - numBytesNotNeeded;
}
// -------------------------------------------------------------------------- ;
NAMESPACE_LERC_END
| 10,414 | 3,683 |
#include <bits/stdc++.h>
using namespace std;
#define le 1003
vector <int> v[le];
vector<int> ct;
int dis[le];
bool vis[le];
void bfs(int a){
memset(vis, false, sizeof(vis));
vis[a] = true;
dis[a]++;
queue<int> q;
q.push(a);
while(!q.empty()){
int p = q.front();
q.pop();
for(int i = 0; i < v[p].size(); i++){
int e = v[p][i];
if(vis[e] == false){
vis[e] = true;
dis[e]++;
q.push(e);
}
}
}
}
int main(){
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int t, k, n, m, a, b, co = 0;
for(scanf("%d", &t); t--; ){
scanf("%d %d %d", &k, &n, &m);
for(int i = 0; i < le; dis[i] = 0, v[i].clear(), i++);
for(int i = 0; i < k; scanf("%d", &a), ct.push_back(a), i++);
for(int i = 0; i < m; scanf("%d %d", &a, &b), v[a].push_back(b), i++);
for(int i = 0; i < ct.size(); bfs(ct[i]), i++);
int ans = 0;
for(int i = 1; i < n + 1; i++) if(dis[i] == ct.size()) ans++;
printf("Case %d: %d\n", ++co, ans);
ct.clear();
}
return 0;
}
| 1,061 | 510 |
// Copyright 2008 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Tested by search_test.cc.
//
// Prog::SearchOnePass is an efficient implementation of
// regular expression search with submatch tracking for
// what I call "one-pass regular expressions". (An alternate
// name might be "backtracking-free regular expressions".)
//
// One-pass regular expressions have the property that
// at each input byte during an anchored match, there may be
// multiple alternatives but only one can proceed for any
// given input byte.
//
// For example, the regexp /x*yx*/ is one-pass: you read
// x's until a y, then you read the y, then you keep reading x's.
// At no point do you have to guess what to do or back up
// and try a different guess.
//
// On the other hand, /x*x/ is not one-pass: when you're
// looking at an input "x", it's not clear whether you should
// use it to extend the x* or as the final x.
//
// More examples: /([^ ]*) (.*)/ is one-pass; /(.*) (.*)/ is not.
// /(\d+)-(\d+)/ is one-pass; /(\d+).(\d+)/ is not.
//
// A simple intuition for identifying one-pass regular expressions
// is that it's always immediately obvious when a repetition ends.
// It must also be immediately obvious which branch of an | to take:
//
// /x(y|z)/ is one-pass, but /(xy|xz)/ is not.
//
// The NFA-based search in nfa.cc does some bookkeeping to
// avoid the need for backtracking and its associated exponential blowup.
// But if we have a one-pass regular expression, there is no
// possibility of backtracking, so there is no need for the
// extra bookkeeping. Hence, this code.
//
// On a one-pass regular expression, the NFA code in nfa.cc
// runs at about 1/20 of the backtracking-based PCRE speed.
// In contrast, the code in this file runs at about the same
// speed as PCRE.
//
// One-pass regular expressions get used a lot when RE is
// used for parsing simple strings, so it pays off to
// notice them and handle them efficiently.
//
// See also Anne Brüggemann-Klein and Derick Wood,
// "One-unambiguous regular languages", Information and Computation 142(2).
#include <stdint.h>
#include <string.h>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#if COCOAPODS==1
#include "third_party/re2/util/util.h"
#else
#include "util/util.h"
#endif
#if COCOAPODS==1
#include "third_party/re2/util/logging.h"
#else
#include "util/logging.h"
#endif
#if COCOAPODS==1
#include "third_party/re2/util/strutil.h"
#else
#include "util/strutil.h"
#endif
#if COCOAPODS==1
#include "third_party/re2/util/utf.h"
#else
#include "util/utf.h"
#endif
#if COCOAPODS==1
#include "third_party/re2/re2/pod_array.h"
#else
#include "re2/pod_array.h"
#endif
#if COCOAPODS==1
#include "third_party/re2/re2/prog.h"
#else
#include "re2/prog.h"
#endif
#if COCOAPODS==1
#include "third_party/re2/re2/sparse_set.h"
#else
#include "re2/sparse_set.h"
#endif
#if COCOAPODS==1
#include "third_party/re2/re2/stringpiece.h"
#else
#include "re2/stringpiece.h"
#endif
// Silence "zero-sized array in struct/union" warning for OneState::action.
#ifdef _MSC_VER
#pragma warning(disable: 4200)
#endif
namespace re2 {
static const bool ExtraDebug = false;
// The key insight behind this implementation is that the
// non-determinism in an NFA for a one-pass regular expression
// is contained. To explain what that means, first a
// refresher about what regular expression programs look like
// and how the usual NFA execution runs.
//
// In a regular expression program, only the kInstByteRange
// instruction processes an input byte c and moves on to the
// next byte in the string (it does so if c is in the given range).
// The kInstByteRange instructions correspond to literal characters
// and character classes in the regular expression.
//
// The kInstAlt instructions are used as wiring to connect the
// kInstByteRange instructions together in interesting ways when
// implementing | + and *.
// The kInstAlt instruction forks execution, like a goto that
// jumps to ip->out() and ip->out1() in parallel. Each of the
// resulting computation paths is called a thread.
//
// The other instructions -- kInstEmptyWidth, kInstMatch, kInstCapture --
// are interesting in their own right but like kInstAlt they don't
// advance the input pointer. Only kInstByteRange does.
//
// The automaton execution in nfa.cc runs all the possible
// threads of execution in lock-step over the input. To process
// a particular byte, each thread gets run until it either dies
// or finds a kInstByteRange instruction matching the byte.
// If the latter happens, the thread stops just past the
// kInstByteRange instruction (at ip->out()) and waits for
// the other threads to finish processing the input byte.
// Then, once all the threads have processed that input byte,
// the whole process repeats. The kInstAlt state instruction
// might create new threads during input processing, but no
// matter what, all the threads stop after a kInstByteRange
// and wait for the other threads to "catch up".
// Running in lock step like this ensures that the NFA reads
// the input string only once.
//
// Each thread maintains its own set of capture registers
// (the string positions at which it executed the kInstCapture
// instructions corresponding to capturing parentheses in the
// regular expression). Repeated copying of the capture registers
// is the main performance bottleneck in the NFA implementation.
//
// A regular expression program is "one-pass" if, no matter what
// the input string, there is only one thread that makes it
// past a kInstByteRange instruction at each input byte. This means
// that there is in some sense only one active thread throughout
// the execution. Other threads might be created during the
// processing of an input byte, but they are ephemeral: only one
// thread is left to start processing the next input byte.
// This is what I meant above when I said the non-determinism
// was "contained".
//
// To execute a one-pass regular expression program, we can build
// a DFA (no non-determinism) that has at most as many states as
// the NFA (compare this to the possibly exponential number of states
// in the general case). Each state records, for each possible
// input byte, the next state along with the conditions required
// before entering that state -- empty-width flags that must be true
// and capture operations that must be performed. It also records
// whether a set of conditions required to finish a match at that
// point in the input rather than process the next byte.
// A state in the one-pass NFA - just an array of actions indexed
// by the bytemap_[] of the next input byte. (The bytemap
// maps next input bytes into equivalence classes, to reduce
// the memory footprint.)
struct OneState {
uint32_t matchcond; // conditions to match right now.
uint32_t action[];
};
// The uint32_t conditions in the action are a combination of
// condition and capture bits and the next state. The bottom 16 bits
// are the condition and capture bits, and the top 16 are the index of
// the next state.
//
// Bits 0-5 are the empty-width flags from prog.h.
// Bit 6 is kMatchWins, which means the match takes
// priority over moving to next in a first-match search.
// The remaining bits mark capture registers that should
// be set to the current input position. The capture bits
// start at index 2, since the search loop can take care of
// cap[0], cap[1] (the overall match position).
// That means we can handle up to 5 capturing parens: $1 through $4, plus $0.
// No input position can satisfy both kEmptyWordBoundary
// and kEmptyNonWordBoundary, so we can use that as a sentinel
// instead of needing an extra bit.
static const int kIndexShift = 16; // number of bits below index
static const int kEmptyShift = 6; // number of empty flags in prog.h
static const int kRealCapShift = kEmptyShift + 1;
static const int kRealMaxCap = (kIndexShift - kRealCapShift) / 2 * 2;
// Parameters used to skip over cap[0], cap[1].
static const int kCapShift = kRealCapShift - 2;
static const int kMaxCap = kRealMaxCap + 2;
static const uint32_t kMatchWins = 1 << kEmptyShift;
static const uint32_t kCapMask = ((1 << kRealMaxCap) - 1) << kRealCapShift;
static const uint32_t kImpossible = kEmptyWordBoundary | kEmptyNonWordBoundary;
// Check, at compile time, that prog.h agrees with math above.
// This function is never called.
void OnePass_Checks() {
static_assert((1<<kEmptyShift)-1 == kEmptyAllFlags,
"kEmptyShift disagrees with kEmptyAllFlags");
// kMaxCap counts pointers, kMaxOnePassCapture counts pairs.
static_assert(kMaxCap == Prog::kMaxOnePassCapture*2,
"kMaxCap disagrees with kMaxOnePassCapture");
}
static bool Satisfy(uint32_t cond, const StringPiece& context, const char* p) {
uint32_t satisfied = Prog::EmptyFlags(context, p);
if (cond & kEmptyAllFlags & ~satisfied)
return false;
return true;
}
// Apply the capture bits in cond, saving p to the appropriate
// locations in cap[].
static void ApplyCaptures(uint32_t cond, const char* p,
const char** cap, int ncap) {
for (int i = 2; i < ncap; i++)
if (cond & (1 << kCapShift << i))
cap[i] = p;
}
// Computes the OneState* for the given nodeindex.
static inline OneState* IndexToNode(uint8_t* nodes, int statesize,
int nodeindex) {
return reinterpret_cast<OneState*>(nodes + statesize*nodeindex);
}
bool Prog::SearchOnePass(const StringPiece& text,
const StringPiece& const_context,
Anchor anchor, MatchKind kind,
StringPiece* match, int nmatch) {
if (anchor != kAnchored && kind != kFullMatch) {
LOG(DFATAL) << "Cannot use SearchOnePass for unanchored matches.";
return false;
}
// Make sure we have at least cap[1],
// because we use it to tell if we matched.
int ncap = 2*nmatch;
if (ncap < 2)
ncap = 2;
const char* cap[kMaxCap];
for (int i = 0; i < ncap; i++)
cap[i] = NULL;
const char* matchcap[kMaxCap];
for (int i = 0; i < ncap; i++)
matchcap[i] = NULL;
StringPiece context = const_context;
if (context.data() == NULL)
context = text;
if (anchor_start() && context.begin() != text.begin())
return false;
if (anchor_end() && context.end() != text.end())
return false;
if (anchor_end())
kind = kFullMatch;
uint8_t* nodes = onepass_nodes_.data();
int statesize = sizeof(OneState) + bytemap_range()*sizeof(uint32_t);
// start() is always mapped to the zeroth OneState.
OneState* state = IndexToNode(nodes, statesize, 0);
uint8_t* bytemap = bytemap_;
const char* bp = text.data();
const char* ep = text.data() + text.size();
const char* p;
bool matched = false;
matchcap[0] = bp;
cap[0] = bp;
uint32_t nextmatchcond = state->matchcond;
for (p = bp; p < ep; p++) {
int c = bytemap[*p & 0xFF];
uint32_t matchcond = nextmatchcond;
uint32_t cond = state->action[c];
// Determine whether we can reach act->next.
// If so, advance state and nextmatchcond.
if ((cond & kEmptyAllFlags) == 0 || Satisfy(cond, context, p)) {
uint32_t nextindex = cond >> kIndexShift;
state = IndexToNode(nodes, statesize, nextindex);
nextmatchcond = state->matchcond;
} else {
state = NULL;
nextmatchcond = kImpossible;
}
// This code section is carefully tuned.
// The goto sequence is about 10% faster than the
// obvious rewrite as a large if statement in the
// ASCIIMatchRE2 and DotMatchRE2 benchmarks.
// Saving the match capture registers is expensive.
// Is this intermediate match worth thinking about?
// Not if we want a full match.
if (kind == kFullMatch)
goto skipmatch;
// Not if it's impossible.
if (matchcond == kImpossible)
goto skipmatch;
// Not if the possible match is beaten by the certain
// match at the next byte. When this test is useless
// (e.g., HTTPPartialMatchRE2) it slows the loop by
// about 10%, but when it avoids work (e.g., DotMatchRE2),
// it cuts the loop execution by about 45%.
if ((cond & kMatchWins) == 0 && (nextmatchcond & kEmptyAllFlags) == 0)
goto skipmatch;
// Finally, the match conditions must be satisfied.
if ((matchcond & kEmptyAllFlags) == 0 || Satisfy(matchcond, context, p)) {
for (int i = 2; i < 2*nmatch; i++)
matchcap[i] = cap[i];
if (nmatch > 1 && (matchcond & kCapMask))
ApplyCaptures(matchcond, p, matchcap, ncap);
matchcap[1] = p;
matched = true;
// If we're in longest match mode, we have to keep
// going and see if we find a longer match.
// In first match mode, we can stop if the match
// takes priority over the next state for this input byte.
// That bit is per-input byte and thus in cond, not matchcond.
if (kind == kFirstMatch && (cond & kMatchWins))
goto done;
}
skipmatch:
if (state == NULL)
goto done;
if ((cond & kCapMask) && nmatch > 1)
ApplyCaptures(cond, p, cap, ncap);
}
// Look for match at end of input.
{
uint32_t matchcond = state->matchcond;
if (matchcond != kImpossible &&
((matchcond & kEmptyAllFlags) == 0 || Satisfy(matchcond, context, p))) {
if (nmatch > 1 && (matchcond & kCapMask))
ApplyCaptures(matchcond, p, cap, ncap);
for (int i = 2; i < ncap; i++)
matchcap[i] = cap[i];
matchcap[1] = p;
matched = true;
}
}
done:
if (!matched)
return false;
for (int i = 0; i < nmatch; i++)
match[i] =
StringPiece(matchcap[2 * i],
static_cast<size_t>(matchcap[2 * i + 1] - matchcap[2 * i]));
return true;
}
// Analysis to determine whether a given regexp program is one-pass.
// If ip is not on workq, adds ip to work queue and returns true.
// If ip is already on work queue, does nothing and returns false.
// If ip is NULL, does nothing and returns true (pretends to add it).
typedef SparseSet Instq;
static bool AddQ(Instq *q, int id) {
if (id == 0)
return true;
if (q->contains(id))
return false;
q->insert(id);
return true;
}
struct InstCond {
int id;
uint32_t cond;
};
// Returns whether this is a one-pass program; that is,
// returns whether it is safe to use SearchOnePass on this program.
// These conditions must be true for any instruction ip:
//
// (1) for any other Inst nip, there is at most one input-free
// path from ip to nip.
// (2) there is at most one kInstByte instruction reachable from
// ip that matches any particular byte c.
// (3) there is at most one input-free path from ip to a kInstMatch
// instruction.
//
// This is actually just a conservative approximation: it might
// return false when the answer is true, when kInstEmptyWidth
// instructions are involved.
// Constructs and saves corresponding one-pass NFA on success.
bool Prog::IsOnePass() {
if (did_onepass_)
return onepass_nodes_.data() != NULL;
did_onepass_ = true;
if (start() == 0) // no match
return false;
// Steal memory for the one-pass NFA from the overall DFA budget.
// Willing to use at most 1/4 of the DFA budget (heuristic).
// Limit max node count to 65000 as a conservative estimate to
// avoid overflowing 16-bit node index in encoding.
int maxnodes = 2 + inst_count(kInstByteRange);
int statesize = sizeof(OneState) + bytemap_range()*sizeof(uint32_t);
if (maxnodes >= 65000 || dfa_mem_ / 4 / statesize < maxnodes)
return false;
// Flood the graph starting at the start state, and check
// that in each reachable state, each possible byte leads
// to a unique next state.
int stacksize = inst_count(kInstCapture) +
inst_count(kInstEmptyWidth) +
inst_count(kInstNop) + 1; // + 1 for start inst
PODArray<InstCond> stack(stacksize);
int size = this->size();
PODArray<int> nodebyid(size); // indexed by ip
memset(nodebyid.data(), 0xFF, size*sizeof nodebyid[0]);
// Originally, nodes was a uint8_t[maxnodes*statesize], but that was
// unnecessarily optimistic: why allocate a large amount of memory
// upfront for a large program when it is unlikely to be one-pass?
std::vector<uint8_t> nodes;
Instq tovisit(size), workq(size);
AddQ(&tovisit, start());
nodebyid[start()] = 0;
int nalloc = 1;
nodes.insert(nodes.end(), statesize, 0);
for (Instq::iterator it = tovisit.begin(); it != tovisit.end(); ++it) {
int id = *it;
int nodeindex = nodebyid[id];
OneState* node = IndexToNode(nodes.data(), statesize, nodeindex);
// Flood graph using manual stack, filling in actions as found.
// Default is none.
for (int b = 0; b < bytemap_range_; b++)
node->action[b] = kImpossible;
node->matchcond = kImpossible;
workq.clear();
bool matched = false;
int nstack = 0;
stack[nstack].id = id;
stack[nstack++].cond = 0;
while (nstack > 0) {
int id = stack[--nstack].id;
uint32_t cond = stack[nstack].cond;
Loop:
Prog::Inst* ip = inst(id);
switch (ip->opcode()) {
default:
LOG(DFATAL) << "unhandled opcode: " << ip->opcode();
break;
case kInstAltMatch:
// TODO(rsc): Ignoring kInstAltMatch optimization.
// Should implement it in this engine, but it's subtle.
DCHECK(!ip->last());
// If already on work queue, (1) is violated: bail out.
if (!AddQ(&workq, id+1))
goto fail;
id = id+1;
goto Loop;
case kInstByteRange: {
int nextindex = nodebyid[ip->out()];
if (nextindex == -1) {
if (nalloc >= maxnodes) {
if (ExtraDebug)
LOG(ERROR) << StringPrintf(
"Not OnePass: hit node limit %d >= %d", nalloc, maxnodes);
goto fail;
}
nextindex = nalloc;
AddQ(&tovisit, ip->out());
nodebyid[ip->out()] = nalloc;
nalloc++;
nodes.insert(nodes.end(), statesize, 0);
// Update node because it might have been invalidated.
node = IndexToNode(nodes.data(), statesize, nodeindex);
}
for (int c = ip->lo(); c <= ip->hi(); c++) {
int b = bytemap_[c];
// Skip any bytes immediately after c that are also in b.
while (c < 256-1 && bytemap_[c+1] == b)
c++;
uint32_t act = node->action[b];
uint32_t newact = (nextindex << kIndexShift) | cond;
if (matched)
newact |= kMatchWins;
if ((act & kImpossible) == kImpossible) {
node->action[b] = newact;
} else if (act != newact) {
if (ExtraDebug)
LOG(ERROR) << StringPrintf(
"Not OnePass: conflict on byte %#x at state %d", c, *it);
goto fail;
}
}
if (ip->foldcase()) {
Rune lo = std::max<Rune>(ip->lo(), 'a') + 'A' - 'a';
Rune hi = std::min<Rune>(ip->hi(), 'z') + 'A' - 'a';
for (int c = lo; c <= hi; c++) {
int b = bytemap_[c];
// Skip any bytes immediately after c that are also in b.
while (c < 256-1 && bytemap_[c+1] == b)
c++;
uint32_t act = node->action[b];
uint32_t newact = (nextindex << kIndexShift) | cond;
if (matched)
newact |= kMatchWins;
if ((act & kImpossible) == kImpossible) {
node->action[b] = newact;
} else if (act != newact) {
if (ExtraDebug)
LOG(ERROR) << StringPrintf(
"Not OnePass: conflict on byte %#x at state %d", c, *it);
goto fail;
}
}
}
if (ip->last())
break;
// If already on work queue, (1) is violated: bail out.
if (!AddQ(&workq, id+1))
goto fail;
id = id+1;
goto Loop;
}
case kInstCapture:
case kInstEmptyWidth:
case kInstNop:
if (!ip->last()) {
// If already on work queue, (1) is violated: bail out.
if (!AddQ(&workq, id+1))
goto fail;
stack[nstack].id = id+1;
stack[nstack++].cond = cond;
}
if (ip->opcode() == kInstCapture && ip->cap() < kMaxCap)
cond |= (1 << kCapShift) << ip->cap();
if (ip->opcode() == kInstEmptyWidth)
cond |= ip->empty();
// kInstCapture and kInstNop always proceed to ip->out().
// kInstEmptyWidth only sometimes proceeds to ip->out(),
// but as a conservative approximation we assume it always does.
// We could be a little more precise by looking at what c
// is, but that seems like overkill.
// If already on work queue, (1) is violated: bail out.
if (!AddQ(&workq, ip->out())) {
if (ExtraDebug)
LOG(ERROR) << StringPrintf(
"Not OnePass: multiple paths %d -> %d", *it, ip->out());
goto fail;
}
id = ip->out();
goto Loop;
case kInstMatch:
if (matched) {
// (3) is violated
if (ExtraDebug)
LOG(ERROR) << StringPrintf(
"Not OnePass: multiple matches from %d", *it);
goto fail;
}
matched = true;
node->matchcond = cond;
if (ip->last())
break;
// If already on work queue, (1) is violated: bail out.
if (!AddQ(&workq, id+1))
goto fail;
id = id+1;
goto Loop;
case kInstFail:
break;
}
}
}
if (ExtraDebug) { // For debugging, dump one-pass NFA to LOG(ERROR).
LOG(ERROR) << "bytemap:\n" << DumpByteMap();
LOG(ERROR) << "prog:\n" << Dump();
std::map<int, int> idmap;
for (int i = 0; i < size; i++)
if (nodebyid[i] != -1)
idmap[nodebyid[i]] = i;
std::string dump;
for (Instq::iterator it = tovisit.begin(); it != tovisit.end(); ++it) {
int id = *it;
int nodeindex = nodebyid[id];
if (nodeindex == -1)
continue;
OneState* node = IndexToNode(nodes.data(), statesize, nodeindex);
dump += StringPrintf("node %d id=%d: matchcond=%#x\n",
nodeindex, id, node->matchcond);
for (int i = 0; i < bytemap_range_; i++) {
if ((node->action[i] & kImpossible) == kImpossible)
continue;
dump += StringPrintf(" %d cond %#x -> %d id=%d\n",
i, node->action[i] & 0xFFFF,
node->action[i] >> kIndexShift,
idmap[node->action[i] >> kIndexShift]);
}
}
LOG(ERROR) << "nodes:\n" << dump;
}
dfa_mem_ -= nalloc*statesize;
onepass_nodes_ = PODArray<uint8_t>(nalloc*statesize);
memmove(onepass_nodes_.data(), nodes.data(), nalloc*statesize);
return true;
fail:
return false;
}
} // namespace re2
| 23,481 | 7,394 |
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#if (defined HAVE_CONFIG_H) && (!defined TARGET_WINDOWS)
#include "config.h"
#endif
#include "AEUtil.h"
#include "TimeUtils.h"
#include <cassert>
extern "C" {
#include "libavutil/channel_layout.h"
}
NS_KRMOVIE_BEGIN
/* declare the rng seed and initialize it */
unsigned int CAEUtil::m_seed = (unsigned int)(CurrentHostCounter() / 1000.0f);
#if defined(HAVE_SSE2) && defined(__SSE2__)
/* declare the SSE seed and initialize it */
MEMALIGN(16, __m128i CAEUtil::m_sseSeed) = _mm_set_epi32(CAEUtil::m_seed, CAEUtil::m_seed+1, CAEUtil::m_seed, CAEUtil::m_seed+1);
#endif
void AEDelayStatus::SetDelay(double d)
{
delay = d;
maxcorrection = d;
tick = CurrentHostCounter();
}
double AEDelayStatus::GetDelay()
{
double d = 0;
if (tick)
d = (double)(CurrentHostCounter() - tick) / CurrentHostFrequency();
if (d > maxcorrection)
d = maxcorrection;
return delay - d;
}
#if 0
CAEChannelInfo CAEUtil::GuessChLayout(const unsigned int channels)
{
CLog::Log(LOGWARNING, "CAEUtil::GuessChLayout - "
"This method should really never be used, please fix the code that called this");
CAEChannelInfo result;
if (channels < 1 || channels > 8)
return result;
switch (channels)
{
case 1: result = AE_CH_LAYOUT_1_0; break;
case 2: result = AE_CH_LAYOUT_2_0; break;
case 3: result = AE_CH_LAYOUT_3_0; break;
case 4: result = AE_CH_LAYOUT_4_0; break;
case 5: result = AE_CH_LAYOUT_5_0; break;
case 6: result = AE_CH_LAYOUT_5_1; break;
case 7: result = AE_CH_LAYOUT_7_0; break;
case 8: result = AE_CH_LAYOUT_7_1; break;
}
return result;
}
#endif
const char* CAEUtil::GetStdChLayoutName(const enum AEStdChLayout layout)
{
if (layout < 0 || layout >= AE_CH_LAYOUT_MAX)
return "UNKNOWN";
static const char* layouts[AE_CH_LAYOUT_MAX] =
{
"1.0",
"2.0", "2.1", "3.0", "3.1", "4.0",
"4.1", "5.0", "5.1", "7.0", "7.1"
};
return layouts[layout];
}
const unsigned int CAEUtil::DataFormatToBits(const enum AEDataFormat dataFormat)
{
if (dataFormat < 0 || dataFormat >= AE_FMT_MAX)
return 0;
static const unsigned int formats[AE_FMT_MAX] =
{
8, /* U8 */
16, /* S16BE */
16, /* S16LE */
16, /* S16NE */
32, /* S32BE */
32, /* S32LE */
32, /* S32NE */
32, /* S24BE */
32, /* S24LE */
32, /* S24NE */
32, /* S24NER */
24, /* S24BE3 */
24, /* S24LE3 */
24, /* S24NE3 */
sizeof(double) << 3, /* DOUBLE */
sizeof(float ) << 3, /* FLOAT */
8, /* RAW */
8, /* U8P */
16, /* S16NEP */
32, /* S32NEP */
32, /* S24NEP */
32, /* S24NERP*/
24, /* S24NE3P*/
sizeof(double) << 3, /* DOUBLEP */
sizeof(float ) << 3 /* FLOATP */
};
return formats[dataFormat];
}
const unsigned int CAEUtil::DataFormatToUsedBits(const enum AEDataFormat dataFormat)
{
if (dataFormat == AE_FMT_S24BE4 || dataFormat == AE_FMT_S24LE4 ||
dataFormat == AE_FMT_S24NE4 || dataFormat == AE_FMT_S24NE4MSB)
return 24;
else
return DataFormatToBits(dataFormat);
}
const unsigned int CAEUtil::DataFormatToDitherBits(const enum AEDataFormat dataFormat)
{
if (dataFormat == AE_FMT_S24NE4MSB)
return 8;
if (dataFormat == AE_FMT_S24NE3)
return -8;
else
return 0;
}
const char* CAEUtil::StreamTypeToStr(const enum CAEStreamInfo::DataType dataType)
{
switch (dataType)
{
case CAEStreamInfo::STREAM_TYPE_AC3:
return "STREAM_TYPE_AC3";
case CAEStreamInfo::STREAM_TYPE_DTSHD:
return "STREAM_TYPE_DTSHD";
case CAEStreamInfo::STREAM_TYPE_DTSHD_CORE:
return "STREAM_TYPE_DTSHD_CORE";
case CAEStreamInfo::STREAM_TYPE_DTS_1024:
return "STREAM_TYPE_DTS_1024";
case CAEStreamInfo::STREAM_TYPE_DTS_2048:
return "STREAM_TYPE_DTS_2048";
case CAEStreamInfo::STREAM_TYPE_DTS_512:
return "STREAM_TYPE_DTS_512";
case CAEStreamInfo::STREAM_TYPE_EAC3:
return "STREAM_TYPE_EAC3";
case CAEStreamInfo::STREAM_TYPE_MLP:
return "STREAM_TYPE_MLP";
case CAEStreamInfo::STREAM_TYPE_TRUEHD:
return "STREAM_TYPE_TRUEHD";
default:
return "STREAM_TYPE_NULL";
}
}
const char* CAEUtil::DataFormatToStr(const enum AEDataFormat dataFormat)
{
if (dataFormat < 0 || dataFormat >= AE_FMT_MAX)
return "UNKNOWN";
static const char *formats[AE_FMT_MAX] =
{
"AE_FMT_U8",
"AE_FMT_S16BE",
"AE_FMT_S16LE",
"AE_FMT_S16NE",
"AE_FMT_S32BE",
"AE_FMT_S32LE",
"AE_FMT_S32NE",
"AE_FMT_S24BE4",
"AE_FMT_S24LE4",
"AE_FMT_S24NE4", /* S24 in 4 bytes */
"AE_FMT_S24NE4MSB",
"AE_FMT_S24BE3",
"AE_FMT_S24LE3",
"AE_FMT_S24NE3", /* S24 in 3 bytes */
"AE_FMT_DOUBLE",
"AE_FMT_FLOAT",
"AE_FMT_RAW",
/* planar formats */
"AE_FMT_U8P",
"AE_FMT_S16NEP",
"AE_FMT_S32NEP",
"AE_FMT_S24NE4P",
"AE_FMT_S24NE4MSBP",
"AE_FMT_S24NE3P",
"AE_FMT_DOUBLEP",
"AE_FMT_FLOATP"
};
return formats[dataFormat];
}
#if defined(HAVE_SSE) && defined(__SSE__)
void CAEUtil::SSEMulArray(float *data, const float mul, uint32_t count)
{
const __m128 m = _mm_set_ps1(mul);
/* work around invalid alignment */
while (((uintptr_t)data & 0xF) && count > 0)
{
data[0] *= mul;
++data;
--count;
}
uint32_t even = count & ~0x3;
for (uint32_t i = 0; i < even; i+=4, data+=4)
{
__m128 to = _mm_load_ps(data);
*(__m128*)data = _mm_mul_ps (to, m);
}
if (even != count)
{
uint32_t odd = count - even;
if (odd == 1)
data[0] *= mul;
else
{
__m128 to;
if (odd == 2)
{
to = _mm_setr_ps(data[0], data[1], 0, 0);
__m128 ou = _mm_mul_ps(to, m);
data[0] = ((float*)&ou)[0];
data[1] = ((float*)&ou)[1];
}
else
{
to = _mm_setr_ps(data[0], data[1], data[2], 0);
__m128 ou = _mm_mul_ps(to, m);
data[0] = ((float*)&ou)[0];
data[1] = ((float*)&ou)[1];
data[2] = ((float*)&ou)[2];
}
}
}
}
void CAEUtil::SSEMulAddArray(float *data, float *add, const float mul, uint32_t count)
{
const __m128 m = _mm_set_ps1(mul);
/* work around invalid alignment */
while ((((uintptr_t)data & 0xF) || ((uintptr_t)add & 0xF)) && count > 0)
{
data[0] += add[0] * mul;
++add;
++data;
--count;
}
uint32_t even = count & ~0x3;
for (uint32_t i = 0; i < even; i+=4, data+=4, add+=4)
{
__m128 ad = _mm_load_ps(add );
__m128 to = _mm_load_ps(data);
*(__m128*)data = _mm_add_ps (to, _mm_mul_ps(ad, m));
}
if (even != count)
{
uint32_t odd = count - even;
if (odd == 1)
data[0] += add[0] * mul;
else
{
__m128 ad;
__m128 to;
if (odd == 2)
{
ad = _mm_setr_ps(add [0], add [1], 0, 0);
to = _mm_setr_ps(data[0], data[1], 0, 0);
__m128 ou = _mm_add_ps(to, _mm_mul_ps(ad, m));
data[0] = ((float*)&ou)[0];
data[1] = ((float*)&ou)[1];
}
else
{
ad = _mm_setr_ps(add [0], add [1], add [2], 0);
to = _mm_setr_ps(data[0], data[1], data[2], 0);
__m128 ou = _mm_add_ps(to, _mm_mul_ps(ad, m));
data[0] = ((float*)&ou)[0];
data[1] = ((float*)&ou)[1];
data[2] = ((float*)&ou)[2];
}
}
}
}
#endif
inline float CAEUtil::SoftClamp(const float x)
{
#if 1
/*
This is a rational function to approximate a tanh-like soft clipper.
It is based on the pade-approximation of the tanh function with tweaked coefficients.
See: http://www.musicdsp.org/showone.php?id=238
*/
if (x < -3.0f)
return -1.0f;
else if (x > 3.0f)
return 1.0f;
float y = x * x;
return x * (27.0f + y) / (27.0f + 9.0f * y);
#else
/* slower method using tanh, but more accurate */
static const double k = 0.9f;
/* perform a soft clamp */
if (x > k)
x = (float) (tanh((x - k) / (1 - k)) * (1 - k) + k);
else if (x < -k)
x = (float) (tanh((x + k) / (1 - k)) * (1 - k) - k);
/* hard clamp anything still outside the bounds */
if (x > 1.0f)
return 1.0f;
if (x < -1.0f)
return -1.0f;
/* return the final sample */
return x;
#endif
}
void CAEUtil::ClampArray(float *data, uint32_t count)
{
#if !defined(HAVE_SSE) || !defined(__SSE__)
for (uint32_t i = 0; i < count; ++i)
data[i] = SoftClamp(data[i]);
#else
const __m128 c1 = _mm_set_ps1(27.0f);
const __m128 c2 = _mm_set_ps1(27.0f + 9.0f);
/* work around invalid alignment */
while (((uintptr_t)data & 0xF) && count > 0)
{
data[0] = SoftClamp(data[0]);
++data;
--count;
}
uint32_t even = count & ~0x3;
for (uint32_t i = 0; i < even; i+=4, data+=4)
{
/* tanh approx clamp */
__m128 dt = _mm_load_ps(data);
__m128 tmp = _mm_mul_ps(dt, dt);
*(__m128*)data = _mm_div_ps(
_mm_mul_ps(
dt,
_mm_add_ps(c1, tmp)
),
_mm_add_ps(c2, tmp)
);
}
if (even != count)
{
uint32_t odd = count - even;
if (odd == 1)
data[0] = SoftClamp(data[0]);
else
{
__m128 dt;
__m128 tmp;
__m128 out;
if (odd == 2)
{
/* tanh approx clamp */
dt = _mm_setr_ps(data[0], data[1], 0, 0);
tmp = _mm_mul_ps(dt, dt);
out = _mm_div_ps(
_mm_mul_ps(
dt,
_mm_add_ps(c1, tmp)
),
_mm_add_ps(c2, tmp)
);
data[0] = ((float*)&out)[0];
data[1] = ((float*)&out)[1];
}
else
{
/* tanh approx clamp */
dt = _mm_setr_ps(data[0], data[1], data[2], 0);
tmp = _mm_mul_ps(dt, dt);
out = _mm_div_ps(
_mm_mul_ps(
dt,
_mm_add_ps(c1, tmp)
),
_mm_add_ps(c2, tmp)
);
data[0] = ((float*)&out)[0];
data[1] = ((float*)&out)[1];
data[2] = ((float*)&out)[2];
}
}
}
#endif
}
/*
Rand implementations based on:
http://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor/
This is NOT safe for crypto work, but perfectly fine for audio usage (dithering)
*/
float CAEUtil::FloatRand1(const float min, const float max)
{
const float delta = (max - min) / 2;
const float factor = delta / (float)INT32_MAX;
return ((float)(m_seed = (214013 * m_seed + 2531011)) * factor) - delta;
}
void CAEUtil::FloatRand4(const float min, const float max, float result[4], __m128 *sseresult/* = NULL */)
{
#if defined(HAVE_SSE2) && defined(__SSE2__)
/*
this method may be called from other SSE code, we need
to calculate the delta & factor using SSE as the FPU
state is unknown and _mm_clear() is expensive.
*/
MEMALIGN(16, static const __m128 point5 ) = _mm_set_ps1(0.5f);
MEMALIGN(16, static const __m128 int32max) = _mm_set_ps1((const float)INT32_MAX);
MEMALIGN(16, __m128 f) = _mm_div_ps(
_mm_mul_ps(
_mm_sub_ps(
_mm_set_ps1(max),
_mm_set_ps1(min)
),
point5
),
int32max
);
MEMALIGN(16, __m128i cur_seed_split);
MEMALIGN(16, __m128i multiplier);
MEMALIGN(16, __m128i adder);
MEMALIGN(16, __m128i mod_mask);
MEMALIGN(16, __m128 res);
MEMALIGN(16, static const unsigned int mult [4]) = {214013, 17405, 214013, 69069};
MEMALIGN(16, static const unsigned int gadd [4]) = {2531011, 10395331, 13737667, 1};
MEMALIGN(16, static const unsigned int mask [4]) = {0xFFFFFFFF, 0, 0xFFFFFFFF, 0};
adder = _mm_load_si128((__m128i*)gadd);
multiplier = _mm_load_si128((__m128i*)mult);
mod_mask = _mm_load_si128((__m128i*)mask);
cur_seed_split = _mm_shuffle_epi32(m_sseSeed, _MM_SHUFFLE(2, 3, 0, 1));
m_sseSeed = _mm_mul_epu32(m_sseSeed, multiplier);
multiplier = _mm_shuffle_epi32(multiplier, _MM_SHUFFLE(2, 3, 0, 1));
cur_seed_split = _mm_mul_epu32(cur_seed_split, multiplier);
m_sseSeed = _mm_and_si128(m_sseSeed, mod_mask);
cur_seed_split = _mm_and_si128(cur_seed_split, mod_mask);
cur_seed_split = _mm_shuffle_epi32(cur_seed_split, _MM_SHUFFLE(2, 3, 0, 1));
m_sseSeed = _mm_or_si128(m_sseSeed, cur_seed_split);
m_sseSeed = _mm_add_epi32(m_sseSeed, adder);
/* adjust the value to the range requested */
res = _mm_cvtepi32_ps(m_sseSeed);
if (sseresult)
*sseresult = _mm_mul_ps(res, f);
else
{
res = _mm_mul_ps(res, f);
_mm_storeu_ps(result, res);
/* returning a float array, so cleanup */
_mm_empty();
}
#else
const float delta = (max - min) / 2.0f;
const float factor = delta / (float)INT32_MAX;
/* cant return sseresult if we are not using SSE intrinsics */
assert(result && !sseresult);
result[0] = ((float)(m_seed = (214013 * m_seed + 2531011)) * factor) - delta;
result[1] = ((float)(m_seed = (214013 * m_seed + 2531011)) * factor) - delta;
result[2] = ((float)(m_seed = (214013 * m_seed + 2531011)) * factor) - delta;
result[3] = ((float)(m_seed = (214013 * m_seed + 2531011)) * factor) - delta;
#endif
}
bool CAEUtil::S16NeedsByteSwap(AEDataFormat in, AEDataFormat out)
{
const AEDataFormat nativeFormat =
#ifdef WORDS_BIGENDIAN
AE_FMT_S16BE;
#else
AE_FMT_S16LE;
#endif
if (in == AE_FMT_S16NE || (in == AE_FMT_RAW))
in = nativeFormat;
if (out == AE_FMT_S16NE || (out == AE_FMT_RAW))
out = nativeFormat;
return in != out;
}
uint64_t CAEUtil::GetAVChannelLayout(const CAEChannelInfo &info)
{
uint64_t channelLayout = 0;
if (info.HasChannel(AE_CH_FL)) channelLayout |= AV_CH_FRONT_LEFT;
if (info.HasChannel(AE_CH_FR)) channelLayout |= AV_CH_FRONT_RIGHT;
if (info.HasChannel(AE_CH_FC)) channelLayout |= AV_CH_FRONT_CENTER;
if (info.HasChannel(AE_CH_LFE)) channelLayout |= AV_CH_LOW_FREQUENCY;
if (info.HasChannel(AE_CH_BL)) channelLayout |= AV_CH_BACK_LEFT;
if (info.HasChannel(AE_CH_BR)) channelLayout |= AV_CH_BACK_RIGHT;
if (info.HasChannel(AE_CH_FLOC)) channelLayout |= AV_CH_FRONT_LEFT_OF_CENTER;
if (info.HasChannel(AE_CH_FROC)) channelLayout |= AV_CH_FRONT_RIGHT_OF_CENTER;
if (info.HasChannel(AE_CH_BC)) channelLayout |= AV_CH_BACK_CENTER;
if (info.HasChannel(AE_CH_SL)) channelLayout |= AV_CH_SIDE_LEFT;
if (info.HasChannel(AE_CH_SR)) channelLayout |= AV_CH_SIDE_RIGHT;
if (info.HasChannel(AE_CH_TC)) channelLayout |= AV_CH_TOP_CENTER;
if (info.HasChannel(AE_CH_TFL)) channelLayout |= AV_CH_TOP_FRONT_LEFT;
if (info.HasChannel(AE_CH_TFC)) channelLayout |= AV_CH_TOP_FRONT_CENTER;
if (info.HasChannel(AE_CH_TFR)) channelLayout |= AV_CH_TOP_FRONT_RIGHT;
if (info.HasChannel(AE_CH_TBL)) channelLayout |= AV_CH_TOP_BACK_LEFT;
if (info.HasChannel(AE_CH_TBC)) channelLayout |= AV_CH_TOP_BACK_CENTER;
if (info.HasChannel(AE_CH_TBR)) channelLayout |= AV_CH_TOP_BACK_RIGHT;
return channelLayout;
}
CAEChannelInfo CAEUtil::GetAEChannelLayout(uint64_t layout)
{
CAEChannelInfo channelLayout;
channelLayout.Reset();
if (layout & AV_CH_FRONT_LEFT) channelLayout += AE_CH_FL;
if (layout & AV_CH_FRONT_RIGHT) channelLayout += AE_CH_FR;
if (layout & AV_CH_FRONT_CENTER) channelLayout += AE_CH_FC;
if (layout & AV_CH_LOW_FREQUENCY) channelLayout += AE_CH_LFE;
if (layout & AV_CH_BACK_LEFT) channelLayout += AE_CH_BL;
if (layout & AV_CH_BACK_RIGHT) channelLayout += AE_CH_BR;
if (layout & AV_CH_FRONT_LEFT_OF_CENTER) channelLayout += AE_CH_FLOC;
if (layout & AV_CH_FRONT_RIGHT_OF_CENTER) channelLayout += AE_CH_FROC;
if (layout & AV_CH_BACK_CENTER) channelLayout += AE_CH_BC;
if (layout & AV_CH_SIDE_LEFT) channelLayout += AE_CH_SL;
if (layout & AV_CH_SIDE_RIGHT) channelLayout += AE_CH_SR;
if (layout & AV_CH_TOP_CENTER) channelLayout += AE_CH_TC;
if (layout & AV_CH_TOP_FRONT_LEFT) channelLayout += AE_CH_TFL;
if (layout & AV_CH_TOP_FRONT_CENTER) channelLayout += AE_CH_TFC;
if (layout & AV_CH_TOP_FRONT_RIGHT) channelLayout += AE_CH_TFR;
if (layout & AV_CH_TOP_BACK_LEFT) channelLayout += AE_CH_BL;
if (layout & AV_CH_TOP_BACK_CENTER) channelLayout += AE_CH_BC;
if (layout & AV_CH_TOP_BACK_RIGHT) channelLayout += AE_CH_BR;
return channelLayout;
}
AVSampleFormat CAEUtil::GetAVSampleFormat(AEDataFormat format)
{
switch (format)
{
case AEDataFormat::AE_FMT_U8:
return AV_SAMPLE_FMT_U8;
case AEDataFormat::AE_FMT_S16NE:
return AV_SAMPLE_FMT_S16;
case AEDataFormat::AE_FMT_S32NE:
return AV_SAMPLE_FMT_S32;
case AEDataFormat::AE_FMT_S24NE4:
return AV_SAMPLE_FMT_S32;
case AEDataFormat::AE_FMT_S24NE4MSB:
return AV_SAMPLE_FMT_S32;
case AEDataFormat::AE_FMT_S24NE3:
return AV_SAMPLE_FMT_S32;
case AEDataFormat::AE_FMT_FLOAT:
return AV_SAMPLE_FMT_FLT;
case AEDataFormat::AE_FMT_DOUBLE:
return AV_SAMPLE_FMT_DBL;
case AEDataFormat::AE_FMT_U8P:
return AV_SAMPLE_FMT_U8P;
case AEDataFormat::AE_FMT_S16NEP:
return AV_SAMPLE_FMT_S16P;
case AEDataFormat::AE_FMT_S32NEP:
return AV_SAMPLE_FMT_S32P;
case AEDataFormat::AE_FMT_S24NE4P:
return AV_SAMPLE_FMT_S32P;
case AEDataFormat::AE_FMT_S24NE4MSBP:
return AV_SAMPLE_FMT_S32P;
case AEDataFormat::AE_FMT_S24NE3P:
return AV_SAMPLE_FMT_S32P;
case AEDataFormat::AE_FMT_FLOATP:
return AV_SAMPLE_FMT_FLTP;
case AEDataFormat::AE_FMT_DOUBLEP:
return AV_SAMPLE_FMT_DBLP;
case AEDataFormat::AE_FMT_RAW:
return AV_SAMPLE_FMT_U8;
default:
{
if (AE_IS_PLANAR(format))
return AV_SAMPLE_FMT_FLTP;
else
return AV_SAMPLE_FMT_FLT;
}
}
}
uint64_t CAEUtil::GetAVChannel(enum AEChannel aechannel)
{
switch (aechannel)
{
case AE_CH_FL: return AV_CH_FRONT_LEFT;
case AE_CH_FR: return AV_CH_FRONT_RIGHT;
case AE_CH_FC: return AV_CH_FRONT_CENTER;
case AE_CH_LFE: return AV_CH_LOW_FREQUENCY;
case AE_CH_BL: return AV_CH_BACK_LEFT;
case AE_CH_BR: return AV_CH_BACK_RIGHT;
case AE_CH_FLOC: return AV_CH_FRONT_LEFT_OF_CENTER;
case AE_CH_FROC: return AV_CH_FRONT_RIGHT_OF_CENTER;
case AE_CH_BC: return AV_CH_BACK_CENTER;
case AE_CH_SL: return AV_CH_SIDE_LEFT;
case AE_CH_SR: return AV_CH_SIDE_RIGHT;
case AE_CH_TC: return AV_CH_TOP_CENTER;
case AE_CH_TFL: return AV_CH_TOP_FRONT_LEFT;
case AE_CH_TFC: return AV_CH_TOP_FRONT_CENTER;
case AE_CH_TFR: return AV_CH_TOP_FRONT_RIGHT;
case AE_CH_TBL: return AV_CH_TOP_BACK_LEFT;
case AE_CH_TBC: return AV_CH_TOP_BACK_CENTER;
case AE_CH_TBR: return AV_CH_TOP_BACK_RIGHT;
default:
return 0;
}
}
int CAEUtil::GetAVChannelIndex(enum AEChannel aechannel, uint64_t layout)
{
return av_get_channel_layout_channel_index(layout, GetAVChannel(aechannel));
}
NS_KRMOVIE_END | 19,303 | 8,635 |
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// define some itksys* things to make ShareForward.h happy
#define itksys_SHARED_FORWARD_DIR_BUILD ""
#define itksys_SHARED_FORWARD_PATH_BUILD ""
#define itksys_SHARED_FORWARD_PATH_INSTALL ""
#define itksys_SHARED_FORWARD_EXE_BUILD ""
#define itksys_SHARED_FORWARD_EXE_INSTALL ""
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include "itksys/SystemTools.hxx"
#include "itkMacro.h"
// include SharedForward to avoid duplicating the code which find the library path variable
// name and the path separator
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#include "itksys/SharedForward.h"
#pragma GCC diagnostic pop
#else
#include "itksys/SharedForward.h"
#endif
#include "itksys/Process.h"
// Temporary definition of otbTestMain
int otbTestMain(int arc, char* arv[]);
/** Display usage */
void usage()
{
std::cerr << "usage: otbTestDriver [global_options] [non_regression_commands] Execute prg [args]" << std::endl;
std::cerr << std::endl;
std::cerr << "otbTestDriver alter the environment, run a test program and does regression testing based on capabilities provided by otbTestMain.h"
<< std::endl;
std::cerr << std::endl;
std::cerr << "Global options:" << std::endl;
std::cerr << " --add-before-libpath PATH" << std::endl;
std::cerr << " Add a path to the library path environment. This option take care of" << std::endl;
std::cerr << " choosing the right environment variable for your system." << std::endl;
std::cerr << " This option can be used several times." << std::endl;
std::cerr << std::endl;
std::cerr << " --add-before-env NAME VALUE" << std::endl;
std::cerr << " Add a VALUE to the variable name in the environment." << std::endl;
std::cerr << " This option can be used several times." << std::endl;
std::cerr << std::endl;
std::cerr << " --help" << std::endl;
std::cerr << " Display this message and exit." << std::endl;
std::cerr << std::endl;
}
/** This function parses the command line and process everything
* related to the --add-before-libpath, --add-before-env and --help.
* Every other args are added to the remainingArgs vector */
int parseCommandLine(int ac, char* av[], std::vector<char*>& remainingArgs)
{
// parse the command line
int i = 1;
bool skip = false;
while (i < ac)
{
if (!skip && strcmp(av[i], "--add-before-libpath") == 0)
{
if (i + 1 >= ac)
{
usage();
return 1;
}
std::string libpath = KWSYS_SHARED_FORWARD_LDPATH;
libpath += "=";
libpath += av[i + 1];
char* oldenv = getenv(KWSYS_SHARED_FORWARD_LDPATH);
if (oldenv)
{
libpath += KWSYS_SHARED_FORWARD_PATH_SEP;
libpath += oldenv;
}
itksys::SystemTools::PutEnv(libpath);
// on some 64 bit systems, LD_LIBRARY_PATH_64 is used before
// LD_LIBRARY_PATH if it is set. It can lead the test to load
// the system library instead of the expected one, so this
// var must also be set
if (std::string(KWSYS_SHARED_FORWARD_LDPATH) == "LD_LIBRARY_PATH")
{
std::string libpath64 = "LD_LIBRARY_PATH_64";
libpath64 += "=";
libpath64 += av[i + 1];
char* oldenv2 = getenv("LD_LIBRARY_PATH_64");
if (oldenv2)
{
libpath64 += KWSYS_SHARED_FORWARD_PATH_SEP;
libpath64 += oldenv2;
}
itksys::SystemTools::PutEnv(libpath64);
}
i += 2;
}
else if (!skip && strcmp(av[i], "--add-before-env") == 0)
{
if (i + 2 >= ac)
{
usage();
return 1;
}
std::string env = av[i + 1];
env += "=";
env += av[i + 2];
char* oldenv = getenv(av[i + 1]);
if (oldenv)
{
env += KWSYS_SHARED_FORWARD_PATH_SEP;
env += oldenv;
}
itksys::SystemTools::PutEnv(env);
i += 3;
}
else if (!skip && strcmp(av[i], "--help") == 0)
{
usage();
return 0;
}
else
{
remainingArgs.push_back(av[i]);
i += 1;
}
}
return 0;
}
int main(int ac, char* av[])
{
// A vector to store remaining args
std::vector<char*> remainingArgs;
// First parse the command line for system wide options
int ret = parseCommandLine(ac, av, remainingArgs);
// Check for the return code
if (ret)
{
std::cerr << "Error while parsing arguments, exiting ..." << std::endl;
return 1;
}
// Check if there are remaining args
if (remainingArgs.empty())
{
usage();
return 1;
}
// a NULL is required at the end of the table
char** argv = new char*[remainingArgs.size() + 2];
for (int i = 0; i < static_cast<int>(remainingArgs.size()); ++i)
{
argv[i + 1] = remainingArgs[i];
}
argv[remainingArgs.size() + 1] = nullptr;
/** Call to the otbTestMain */
return otbTestMain(static_cast<int>(remainingArgs.size()), argv);
}
// This is a dummy main to be registered as a test for the otbTestMain
int Execute(int, char* argv[])
{
argv += 1;
// Create the appropriate itk process
itksysProcess* process = itksysProcess_New();
itksysProcess_SetCommand(process, argv);
itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDOUT, true);
itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDERR, true);
itksysProcess_Execute(process);
itksysProcess_WaitForExit(process, nullptr);
int retCode = itksysProcess_GetExitValue(process);
itksysProcess_Delete(process);
return retCode;
}
// Include otbTestMain and switch otbTestMain with main definition in otbTestMain.h
#undef otbTestMain
#undef main
#define main otbTestMain
#include "otbTestMain.h"
void RegisterTests()
{
REGISTER_TEST(Execute);
}
| 6,500 | 2,270 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
/* Haar features calculation */
#include "precomp.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/objdetect/objdetect_c.h"
#include <stdio.h>
#if CV_SSE2
# if 1 /*!CV_SSE4_1 && !CV_SSE4_2*/
# define _mm_blendv_pd(a, b, m) _mm_xor_pd(a, _mm_and_pd(_mm_xor_pd(b, a), m))
# define _mm_blendv_ps(a, b, m) _mm_xor_ps(a, _mm_and_ps(_mm_xor_ps(b, a), m))
# endif
#endif
#if 0 /*CV_AVX*/
# define CV_HAAR_USE_AVX 1
# if defined _MSC_VER
# pragma warning( disable : 4752 )
# endif
#else
# if CV_SSE2
# define CV_HAAR_USE_SSE 1
# endif
#endif
/* these settings affect the quality of detection: change with care */
#define CV_ADJUST_FEATURES 1
#define CV_ADJUST_WEIGHTS 0
typedef int sumtype;
typedef double sqsumtype;
typedef struct CvHidHaarFeature
{
struct
{
sumtype *p0, *p1, *p2, *p3;
float weight;
}
rect[CV_HAAR_FEATURE_MAX];
} CvHidHaarFeature;
typedef struct CvHidHaarTreeNode
{
CvHidHaarFeature feature;
float threshold;
int left;
int right;
} CvHidHaarTreeNode;
typedef struct CvHidHaarClassifier
{
int count;
//CvHaarFeature* orig_feature;
CvHidHaarTreeNode* node;
float* alpha;
} CvHidHaarClassifier;
typedef struct CvHidHaarStageClassifier
{
int count;
float threshold;
CvHidHaarClassifier* classifier;
int two_rects;
struct CvHidHaarStageClassifier* next;
struct CvHidHaarStageClassifier* child;
struct CvHidHaarStageClassifier* parent;
} CvHidHaarStageClassifier;
typedef struct CvHidHaarClassifierCascade
{
int count;
int isStumpBased;
int has_tilted_features;
int is_tree;
double inv_window_area;
CvMat sum, sqsum, tilted;
CvHidHaarStageClassifier* stage_classifier;
sqsumtype *pq0, *pq1, *pq2, *pq3;
sumtype *p0, *p1, *p2, *p3;
void** ipp_stages;
} CvHidHaarClassifierCascade;
const int icv_object_win_border = 1;
const float icv_stage_threshold_bias = 0.0001f;
static CvHaarClassifierCascade*
icvCreateHaarClassifierCascade( int stage_count )
{
CvHaarClassifierCascade* cascade = 0;
int block_size = sizeof(*cascade) + stage_count*sizeof(*cascade->stage_classifier);
if( stage_count <= 0 )
CV_Error( CV_StsOutOfRange, "Number of stages should be positive" );
cascade = (CvHaarClassifierCascade*)cvAlloc( block_size );
memset( cascade, 0, block_size );
cascade->stage_classifier = (CvHaarStageClassifier*)(cascade + 1);
cascade->flags = CV_HAAR_MAGIC_VAL;
cascade->count = stage_count;
return cascade;
}
static void
icvReleaseHidHaarClassifierCascade( CvHidHaarClassifierCascade** _cascade )
{
if( _cascade && *_cascade )
{
#ifdef HAVE_IPP
CvHidHaarClassifierCascade* cascade = *_cascade;
if( cascade->ipp_stages )
{
int i;
for( i = 0; i < cascade->count; i++ )
{
if( cascade->ipp_stages[i] )
ippiHaarClassifierFree_32f( (IppiHaarClassifier_32f*)cascade->ipp_stages[i] );
}
}
cvFree( &cascade->ipp_stages );
#endif
cvFree( _cascade );
}
}
/* create more efficient internal representation of haar classifier cascade */
static CvHidHaarClassifierCascade*
icvCreateHidHaarClassifierCascade( CvHaarClassifierCascade* cascade )
{
CvRect* ipp_features = 0;
float *ipp_weights = 0, *ipp_thresholds = 0, *ipp_val1 = 0, *ipp_val2 = 0;
int* ipp_counts = 0;
CvHidHaarClassifierCascade* out = 0;
int i, j, k, l;
int datasize;
int total_classifiers = 0;
int total_nodes = 0;
char errorstr[1000];
CvHidHaarClassifier* haar_classifier_ptr;
CvHidHaarTreeNode* haar_node_ptr;
CvSize orig_window_size;
int has_tilted_features = 0;
int max_count = 0;
if( !CV_IS_HAAR_CLASSIFIER(cascade) )
CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
if( cascade->hid_cascade )
CV_Error( CV_StsError, "hid_cascade has been already created" );
if( !cascade->stage_classifier )
CV_Error( CV_StsNullPtr, "" );
if( cascade->count <= 0 )
CV_Error( CV_StsOutOfRange, "Negative number of cascade stages" );
orig_window_size = cascade->orig_window_size;
/* check input structure correctness and calculate total memory size needed for
internal representation of the classifier cascade */
for( i = 0; i < cascade->count; i++ )
{
CvHaarStageClassifier* stage_classifier = cascade->stage_classifier + i;
if( !stage_classifier->classifier ||
stage_classifier->count <= 0 )
{
sprintf( errorstr, "header of the stage classifier #%d is invalid "
"(has null pointers or non-positive classfier count)", i );
CV_Error( CV_StsError, errorstr );
}
max_count = MAX( max_count, stage_classifier->count );
total_classifiers += stage_classifier->count;
for( j = 0; j < stage_classifier->count; j++ )
{
CvHaarClassifier* classifier = stage_classifier->classifier + j;
total_nodes += classifier->count;
for( l = 0; l < classifier->count; l++ )
{
for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
{
if( classifier->haar_feature[l].rect[k].r.width )
{
CvRect r = classifier->haar_feature[l].rect[k].r;
int tilted = classifier->haar_feature[l].tilted;
has_tilted_features |= tilted != 0;
if( r.width < 0 || r.height < 0 || r.y < 0 ||
r.x + r.width > orig_window_size.width
||
(!tilted &&
(r.x < 0 || r.y + r.height > orig_window_size.height))
||
(tilted && (r.x - r.height < 0 ||
r.y + r.width + r.height > orig_window_size.height)))
{
sprintf( errorstr, "rectangle #%d of the classifier #%d of "
"the stage classifier #%d is not inside "
"the reference (original) cascade window", k, j, i );
CV_Error( CV_StsNullPtr, errorstr );
}
}
}
}
}
}
// this is an upper boundary for the whole hidden cascade size
datasize = sizeof(CvHidHaarClassifierCascade) +
sizeof(CvHidHaarStageClassifier)*cascade->count +
sizeof(CvHidHaarClassifier) * total_classifiers +
sizeof(CvHidHaarTreeNode) * total_nodes +
sizeof(void*)*(total_nodes + total_classifiers);
out = (CvHidHaarClassifierCascade*)cvAlloc( datasize );
memset( out, 0, sizeof(*out) );
/* init header */
out->count = cascade->count;
out->stage_classifier = (CvHidHaarStageClassifier*)(out + 1);
haar_classifier_ptr = (CvHidHaarClassifier*)(out->stage_classifier + cascade->count);
haar_node_ptr = (CvHidHaarTreeNode*)(haar_classifier_ptr + total_classifiers);
out->isStumpBased = 1;
out->has_tilted_features = has_tilted_features;
out->is_tree = 0;
/* initialize internal representation */
for( i = 0; i < cascade->count; i++ )
{
CvHaarStageClassifier* stage_classifier = cascade->stage_classifier + i;
CvHidHaarStageClassifier* hid_stage_classifier = out->stage_classifier + i;
hid_stage_classifier->count = stage_classifier->count;
hid_stage_classifier->threshold = stage_classifier->threshold - icv_stage_threshold_bias;
hid_stage_classifier->classifier = haar_classifier_ptr;
hid_stage_classifier->two_rects = 1;
haar_classifier_ptr += stage_classifier->count;
hid_stage_classifier->parent = (stage_classifier->parent == -1)
? NULL : out->stage_classifier + stage_classifier->parent;
hid_stage_classifier->next = (stage_classifier->next == -1)
? NULL : out->stage_classifier + stage_classifier->next;
hid_stage_classifier->child = (stage_classifier->child == -1)
? NULL : out->stage_classifier + stage_classifier->child;
out->is_tree |= hid_stage_classifier->next != NULL;
for( j = 0; j < stage_classifier->count; j++ )
{
CvHaarClassifier* classifier = stage_classifier->classifier + j;
CvHidHaarClassifier* hid_classifier = hid_stage_classifier->classifier + j;
int node_count = classifier->count;
float* alpha_ptr = (float*)(haar_node_ptr + node_count);
hid_classifier->count = node_count;
hid_classifier->node = haar_node_ptr;
hid_classifier->alpha = alpha_ptr;
for( l = 0; l < node_count; l++ )
{
CvHidHaarTreeNode* node = hid_classifier->node + l;
CvHaarFeature* feature = classifier->haar_feature + l;
memset( node, -1, sizeof(*node) );
node->threshold = classifier->threshold[l];
node->left = classifier->left[l];
node->right = classifier->right[l];
if( fabs(feature->rect[2].weight) < DBL_EPSILON ||
feature->rect[2].r.width == 0 ||
feature->rect[2].r.height == 0 )
memset( &(node->feature.rect[2]), 0, sizeof(node->feature.rect[2]) );
else
hid_stage_classifier->two_rects = 0;
}
memcpy( alpha_ptr, classifier->alpha, (node_count+1)*sizeof(alpha_ptr[0]));
haar_node_ptr =
(CvHidHaarTreeNode*)cvAlignPtr(alpha_ptr+node_count+1, sizeof(void*));
out->isStumpBased &= node_count == 1;
}
}
/*
#ifdef HAVE_IPP
int can_use_ipp = !out->has_tilted_features && !out->is_tree && out->isStumpBased;
if( can_use_ipp )
{
int ipp_datasize = cascade->count*sizeof(out->ipp_stages[0]);
float ipp_weight_scale=(float)(1./((orig_window_size.width-icv_object_win_border*2)*
(orig_window_size.height-icv_object_win_border*2)));
out->ipp_stages = (void**)cvAlloc( ipp_datasize );
memset( out->ipp_stages, 0, ipp_datasize );
ipp_features = (CvRect*)cvAlloc( max_count*3*sizeof(ipp_features[0]) );
ipp_weights = (float*)cvAlloc( max_count*3*sizeof(ipp_weights[0]) );
ipp_thresholds = (float*)cvAlloc( max_count*sizeof(ipp_thresholds[0]) );
ipp_val1 = (float*)cvAlloc( max_count*sizeof(ipp_val1[0]) );
ipp_val2 = (float*)cvAlloc( max_count*sizeof(ipp_val2[0]) );
ipp_counts = (int*)cvAlloc( max_count*sizeof(ipp_counts[0]) );
for( i = 0; i < cascade->count; i++ )
{
CvHaarStageClassifier* stage_classifier = cascade->stage_classifier + i;
for( j = 0, k = 0; j < stage_classifier->count; j++ )
{
CvHaarClassifier* classifier = stage_classifier->classifier + j;
int rect_count = 2 + (classifier->haar_feature->rect[2].r.width != 0);
ipp_thresholds[j] = classifier->threshold[0];
ipp_val1[j] = classifier->alpha[0];
ipp_val2[j] = classifier->alpha[1];
ipp_counts[j] = rect_count;
for( l = 0; l < rect_count; l++, k++ )
{
ipp_features[k] = classifier->haar_feature->rect[l].r;
//ipp_features[k].y = orig_window_size.height - ipp_features[k].y - ipp_features[k].height;
ipp_weights[k] = classifier->haar_feature->rect[l].weight*ipp_weight_scale;
}
}
if( ippiHaarClassifierInitAlloc_32f( (IppiHaarClassifier_32f**)&out->ipp_stages[i],
(const IppiRect*)ipp_features, ipp_weights, ipp_thresholds,
ipp_val1, ipp_val2, ipp_counts, stage_classifier->count ) < 0 )
break;
}
if( i < cascade->count )
{
for( j = 0; j < i; j++ )
if( out->ipp_stages[i] )
ippiHaarClassifierFree_32f( (IppiHaarClassifier_32f*)out->ipp_stages[i] );
cvFree( &out->ipp_stages );
}
}
#endif
*/
cascade->hid_cascade = out;
assert( (char*)haar_node_ptr - (char*)out <= datasize );
cvFree( &ipp_features );
cvFree( &ipp_weights );
cvFree( &ipp_thresholds );
cvFree( &ipp_val1 );
cvFree( &ipp_val2 );
cvFree( &ipp_counts );
return out;
}
#define sum_elem_ptr(sum,row,col) \
((sumtype*)CV_MAT_ELEM_PTR_FAST((sum),(row),(col),sizeof(sumtype)))
#define sqsum_elem_ptr(sqsum,row,col) \
((sqsumtype*)CV_MAT_ELEM_PTR_FAST((sqsum),(row),(col),sizeof(sqsumtype)))
#define calc_sum(rect,offset) \
((rect).p0[offset] - (rect).p1[offset] - (rect).p2[offset] + (rect).p3[offset])
#define calc_sumf(rect,offset) \
static_cast<float>((rect).p0[offset] - (rect).p1[offset] - (rect).p2[offset] + (rect).p3[offset])
CV_IMPL void
cvSetImagesForHaarClassifierCascade( CvHaarClassifierCascade* _cascade,
const CvArr* _sum,
const CvArr* _sqsum,
const CvArr* _tilted_sum,
double scale )
{
CvMat sum_stub, *sum = (CvMat*)_sum;
CvMat sqsum_stub, *sqsum = (CvMat*)_sqsum;
CvMat tilted_stub, *tilted = (CvMat*)_tilted_sum;
CvHidHaarClassifierCascade* cascade;
int coi0 = 0, coi1 = 0;
int i;
CvRect equRect;
double weight_scale;
if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier pointer" );
if( scale <= 0 )
CV_Error( CV_StsOutOfRange, "Scale must be positive" );
sum = cvGetMat( sum, &sum_stub, &coi0 );
sqsum = cvGetMat( sqsum, &sqsum_stub, &coi1 );
if( coi0 || coi1 )
CV_Error( CV_BadCOI, "COI is not supported" );
if( !CV_ARE_SIZES_EQ( sum, sqsum ))
CV_Error( CV_StsUnmatchedSizes, "All integral images must have the same size" );
if( CV_MAT_TYPE(sqsum->type) != CV_64FC1 ||
CV_MAT_TYPE(sum->type) != CV_32SC1 )
CV_Error( CV_StsUnsupportedFormat,
"Only (32s, 64f, 32s) combination of (sum,sqsum,tilted_sum) formats is allowed" );
if( !_cascade->hid_cascade )
icvCreateHidHaarClassifierCascade(_cascade);
cascade = _cascade->hid_cascade;
if( cascade->has_tilted_features )
{
tilted = cvGetMat( tilted, &tilted_stub, &coi1 );
if( CV_MAT_TYPE(tilted->type) != CV_32SC1 )
CV_Error( CV_StsUnsupportedFormat,
"Only (32s, 64f, 32s) combination of (sum,sqsum,tilted_sum) formats is allowed" );
if( sum->step != tilted->step )
CV_Error( CV_StsUnmatchedSizes,
"Sum and tilted_sum must have the same stride (step, widthStep)" );
if( !CV_ARE_SIZES_EQ( sum, tilted ))
CV_Error( CV_StsUnmatchedSizes, "All integral images must have the same size" );
cascade->tilted = *tilted;
}
_cascade->scale = scale;
_cascade->real_window_size.width = cvRound( _cascade->orig_window_size.width * scale );
_cascade->real_window_size.height = cvRound( _cascade->orig_window_size.height * scale );
cascade->sum = *sum;
cascade->sqsum = *sqsum;
equRect.x = equRect.y = cvRound(scale);
equRect.width = cvRound((_cascade->orig_window_size.width-2)*scale);
equRect.height = cvRound((_cascade->orig_window_size.height-2)*scale);
weight_scale = 1./(equRect.width*equRect.height);
cascade->inv_window_area = weight_scale;
cascade->p0 = sum_elem_ptr(*sum, equRect.y, equRect.x);
cascade->p1 = sum_elem_ptr(*sum, equRect.y, equRect.x + equRect.width );
cascade->p2 = sum_elem_ptr(*sum, equRect.y + equRect.height, equRect.x );
cascade->p3 = sum_elem_ptr(*sum, equRect.y + equRect.height,
equRect.x + equRect.width );
cascade->pq0 = sqsum_elem_ptr(*sqsum, equRect.y, equRect.x);
cascade->pq1 = sqsum_elem_ptr(*sqsum, equRect.y, equRect.x + equRect.width );
cascade->pq2 = sqsum_elem_ptr(*sqsum, equRect.y + equRect.height, equRect.x );
cascade->pq3 = sqsum_elem_ptr(*sqsum, equRect.y + equRect.height,
equRect.x + equRect.width );
/* init pointers in haar features according to real window size and
given image pointers */
for( i = 0; i < _cascade->count; i++ )
{
int j, k, l;
for( j = 0; j < cascade->stage_classifier[i].count; j++ )
{
for( l = 0; l < cascade->stage_classifier[i].classifier[j].count; l++ )
{
CvHaarFeature* feature =
&_cascade->stage_classifier[i].classifier[j].haar_feature[l];
/* CvHidHaarClassifier* classifier =
cascade->stage_classifier[i].classifier + j; */
CvHidHaarFeature* hidfeature =
&cascade->stage_classifier[i].classifier[j].node[l].feature;
double sum0 = 0, area0 = 0;
CvRect r[3];
int base_w = -1, base_h = -1;
int new_base_w = 0, new_base_h = 0;
int kx, ky;
int flagx = 0, flagy = 0;
int x0 = 0, y0 = 0;
int nr;
/* align blocks */
for( k = 0; k < CV_HAAR_FEATURE_MAX; k++ )
{
if( !hidfeature->rect[k].p0 )
break;
r[k] = feature->rect[k].r;
base_w = (int)CV_IMIN( (unsigned)base_w, (unsigned)(r[k].width-1) );
base_w = (int)CV_IMIN( (unsigned)base_w, (unsigned)(r[k].x - r[0].x-1) );
base_h = (int)CV_IMIN( (unsigned)base_h, (unsigned)(r[k].height-1) );
base_h = (int)CV_IMIN( (unsigned)base_h, (unsigned)(r[k].y - r[0].y-1) );
}
nr = k;
base_w += 1;
base_h += 1;
kx = r[0].width / base_w;
ky = r[0].height / base_h;
if( kx <= 0 )
{
flagx = 1;
new_base_w = cvRound( r[0].width * scale ) / kx;
x0 = cvRound( r[0].x * scale );
}
if( ky <= 0 )
{
flagy = 1;
new_base_h = cvRound( r[0].height * scale ) / ky;
y0 = cvRound( r[0].y * scale );
}
for( k = 0; k < nr; k++ )
{
CvRect tr;
double correction_ratio;
if( flagx )
{
tr.x = (r[k].x - r[0].x) * new_base_w / base_w + x0;
tr.width = r[k].width * new_base_w / base_w;
}
else
{
tr.x = cvRound( r[k].x * scale );
tr.width = cvRound( r[k].width * scale );
}
if( flagy )
{
tr.y = (r[k].y - r[0].y) * new_base_h / base_h + y0;
tr.height = r[k].height * new_base_h / base_h;
}
else
{
tr.y = cvRound( r[k].y * scale );
tr.height = cvRound( r[k].height * scale );
}
#if CV_ADJUST_WEIGHTS
{
// RAINER START
const float orig_feature_size = (float)(feature->rect[k].r.width)*feature->rect[k].r.height;
const float orig_norm_size = (float)(_cascade->orig_window_size.width)*(_cascade->orig_window_size.height);
const float feature_size = float(tr.width*tr.height);
//const float normSize = float(equRect.width*equRect.height);
float target_ratio = orig_feature_size / orig_norm_size;
//float isRatio = featureSize / normSize;
//correctionRatio = targetRatio / isRatio / normSize;
correction_ratio = target_ratio / feature_size;
// RAINER END
}
#else
correction_ratio = weight_scale * (!feature->tilted ? 1 : 0.5);
#endif
if( !feature->tilted )
{
hidfeature->rect[k].p0 = sum_elem_ptr(*sum, tr.y, tr.x);
hidfeature->rect[k].p1 = sum_elem_ptr(*sum, tr.y, tr.x + tr.width);
hidfeature->rect[k].p2 = sum_elem_ptr(*sum, tr.y + tr.height, tr.x);
hidfeature->rect[k].p3 = sum_elem_ptr(*sum, tr.y + tr.height, tr.x + tr.width);
}
else
{
hidfeature->rect[k].p2 = sum_elem_ptr(*tilted, tr.y + tr.width, tr.x + tr.width);
hidfeature->rect[k].p3 = sum_elem_ptr(*tilted, tr.y + tr.width + tr.height,
tr.x + tr.width - tr.height);
hidfeature->rect[k].p0 = sum_elem_ptr(*tilted, tr.y, tr.x);
hidfeature->rect[k].p1 = sum_elem_ptr(*tilted, tr.y + tr.height, tr.x - tr.height);
}
hidfeature->rect[k].weight = (float)(feature->rect[k].weight * correction_ratio);
if( k == 0 )
area0 = tr.width * tr.height;
else
sum0 += hidfeature->rect[k].weight * tr.width * tr.height;
}
hidfeature->rect[0].weight = (float)(-sum0/area0);
} /* l */
} /* j */
}
}
// AVX version icvEvalHidHaarClassifier. Process 8 CvHidHaarClassifiers per call. Check AVX support before invocation!!
#ifdef CV_HAAR_USE_AVX
CV_INLINE
double icvEvalHidHaarClassifierAVX( CvHidHaarClassifier* classifier,
double variance_norm_factor, size_t p_offset )
{
int CV_DECL_ALIGNED(32) idxV[8] = {0,0,0,0,0,0,0,0};
uchar flags[8] = {0,0,0,0,0,0,0,0};
CvHidHaarTreeNode* nodes[8];
double res = 0;
uchar exitConditionFlag = 0;
for(;;)
{
float CV_DECL_ALIGNED(32) tmp[8] = {0,0,0,0,0,0,0,0};
nodes[0] = (classifier+0)->node + idxV[0];
nodes[1] = (classifier+1)->node + idxV[1];
nodes[2] = (classifier+2)->node + idxV[2];
nodes[3] = (classifier+3)->node + idxV[3];
nodes[4] = (classifier+4)->node + idxV[4];
nodes[5] = (classifier+5)->node + idxV[5];
nodes[6] = (classifier+6)->node + idxV[6];
nodes[7] = (classifier+7)->node + idxV[7];
__m256 t = _mm256_set1_ps(static_cast<float>(variance_norm_factor));
t = _mm256_mul_ps(t, _mm256_set_ps(nodes[7]->threshold,
nodes[6]->threshold,
nodes[5]->threshold,
nodes[4]->threshold,
nodes[3]->threshold,
nodes[2]->threshold,
nodes[1]->threshold,
nodes[0]->threshold));
__m256 offset = _mm256_set_ps(calc_sumf(nodes[7]->feature.rect[0], p_offset),
calc_sumf(nodes[6]->feature.rect[0], p_offset),
calc_sumf(nodes[5]->feature.rect[0], p_offset),
calc_sumf(nodes[4]->feature.rect[0], p_offset),
calc_sumf(nodes[3]->feature.rect[0], p_offset),
calc_sumf(nodes[2]->feature.rect[0], p_offset),
calc_sumf(nodes[1]->feature.rect[0], p_offset),
calc_sumf(nodes[0]->feature.rect[0], p_offset));
__m256 weight = _mm256_set_ps(nodes[7]->feature.rect[0].weight,
nodes[6]->feature.rect[0].weight,
nodes[5]->feature.rect[0].weight,
nodes[4]->feature.rect[0].weight,
nodes[3]->feature.rect[0].weight,
nodes[2]->feature.rect[0].weight,
nodes[1]->feature.rect[0].weight,
nodes[0]->feature.rect[0].weight);
__m256 sum = _mm256_mul_ps(offset, weight);
offset = _mm256_set_ps(calc_sumf(nodes[7]->feature.rect[1], p_offset),
calc_sumf(nodes[6]->feature.rect[1], p_offset),
calc_sumf(nodes[5]->feature.rect[1], p_offset),
calc_sumf(nodes[4]->feature.rect[1], p_offset),
calc_sumf(nodes[3]->feature.rect[1], p_offset),
calc_sumf(nodes[2]->feature.rect[1], p_offset),
calc_sumf(nodes[1]->feature.rect[1], p_offset),
calc_sumf(nodes[0]->feature.rect[1], p_offset));
weight = _mm256_set_ps(nodes[7]->feature.rect[1].weight,
nodes[6]->feature.rect[1].weight,
nodes[5]->feature.rect[1].weight,
nodes[4]->feature.rect[1].weight,
nodes[3]->feature.rect[1].weight,
nodes[2]->feature.rect[1].weight,
nodes[1]->feature.rect[1].weight,
nodes[0]->feature.rect[1].weight);
sum = _mm256_add_ps(sum, _mm256_mul_ps(offset, weight));
if( nodes[0]->feature.rect[2].p0 )
tmp[0] = calc_sumf(nodes[0]->feature.rect[2], p_offset) * nodes[0]->feature.rect[2].weight;
if( nodes[1]->feature.rect[2].p0 )
tmp[1] = calc_sumf(nodes[1]->feature.rect[2], p_offset) * nodes[1]->feature.rect[2].weight;
if( nodes[2]->feature.rect[2].p0 )
tmp[2] = calc_sumf(nodes[2]->feature.rect[2], p_offset) * nodes[2]->feature.rect[2].weight;
if( nodes[3]->feature.rect[2].p0 )
tmp[3] = calc_sumf(nodes[3]->feature.rect[2], p_offset) * nodes[3]->feature.rect[2].weight;
if( nodes[4]->feature.rect[2].p0 )
tmp[4] = calc_sumf(nodes[4]->feature.rect[2], p_offset) * nodes[4]->feature.rect[2].weight;
if( nodes[5]->feature.rect[2].p0 )
tmp[5] = calc_sumf(nodes[5]->feature.rect[2], p_offset) * nodes[5]->feature.rect[2].weight;
if( nodes[6]->feature.rect[2].p0 )
tmp[6] = calc_sumf(nodes[6]->feature.rect[2], p_offset) * nodes[6]->feature.rect[2].weight;
if( nodes[7]->feature.rect[2].p0 )
tmp[7] = calc_sumf(nodes[7]->feature.rect[2], p_offset) * nodes[7]->feature.rect[2].weight;
sum = _mm256_add_ps(sum,_mm256_load_ps(tmp));
__m256 left = _mm256_set_ps(static_cast<float>(nodes[7]->left), static_cast<float>(nodes[6]->left),
static_cast<float>(nodes[5]->left), static_cast<float>(nodes[4]->left),
static_cast<float>(nodes[3]->left), static_cast<float>(nodes[2]->left),
static_cast<float>(nodes[1]->left), static_cast<float>(nodes[0]->left));
__m256 right = _mm256_set_ps(static_cast<float>(nodes[7]->right),static_cast<float>(nodes[6]->right),
static_cast<float>(nodes[5]->right),static_cast<float>(nodes[4]->right),
static_cast<float>(nodes[3]->right),static_cast<float>(nodes[2]->right),
static_cast<float>(nodes[1]->right),static_cast<float>(nodes[0]->right));
_mm256_store_si256((__m256i*)idxV, _mm256_cvttps_epi32(_mm256_blendv_ps(right, left, _mm256_cmp_ps(sum, t, _CMP_LT_OQ))));
for(int i = 0; i < 8; i++)
{
if(idxV[i]<=0)
{
if(!flags[i])
{
exitConditionFlag++;
flags[i] = 1;
res += (classifier+i)->alpha[-idxV[i]];
}
idxV[i]=0;
}
}
if(exitConditionFlag == 8)
return res;
}
}
#endif //CV_HAAR_USE_AVX
CV_INLINE
double icvEvalHidHaarClassifier( CvHidHaarClassifier* classifier,
double variance_norm_factor,
size_t p_offset )
{
int idx = 0;
/*#if CV_HAAR_USE_SSE && !CV_HAAR_USE_AVX
if(cv::checkHardwareSupport(CV_CPU_SSE2))//based on old SSE variant. Works slow
{
double CV_DECL_ALIGNED(16) temp[2];
__m128d zero = _mm_setzero_pd();
do
{
CvHidHaarTreeNode* node = classifier->node + idx;
__m128d t = _mm_set1_pd((node->threshold)*variance_norm_factor);
__m128d left = _mm_set1_pd(node->left);
__m128d right = _mm_set1_pd(node->right);
double _sum = calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight;
_sum += calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight;
if( node->feature.rect[2].p0 )
_sum += calc_sum(node->feature.rect[2],p_offset) * node->feature.rect[2].weight;
__m128d sum = _mm_set1_pd(_sum);
t = _mm_cmplt_sd(sum, t);
sum = _mm_blendv_pd(right, left, t);
_mm_store_pd(temp, sum);
idx = (int)temp[0];
}
while(idx > 0 );
}
else
#endif*/
{
do
{
CvHidHaarTreeNode* node = classifier->node + idx;
double t = node->threshold * variance_norm_factor;
double sum = calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight;
sum += calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight;
if( node->feature.rect[2].p0 )
sum += calc_sum(node->feature.rect[2],p_offset) * node->feature.rect[2].weight;
idx = sum < t ? node->left : node->right;
}
while( idx > 0 );
}
return classifier->alpha[-idx];
}
static int
cvRunHaarClassifierCascadeSum( const CvHaarClassifierCascade* _cascade,
CvPoint pt, double& stage_sum, int start_stage )
{
#ifdef CV_HAAR_USE_AVX
bool haveAVX = false;
if(cv::checkHardwareSupport(CV_CPU_AVX))
if(__xgetbv()&0x6)// Check if the OS will save the YMM registers
haveAVX = true;
#else
# ifdef CV_HAAR_USE_SSE
bool haveSSE2 = cv::checkHardwareSupport(CV_CPU_SSE2);
# endif
#endif
int p_offset, pq_offset;
int i, j;
double mean, variance_norm_factor;
CvHidHaarClassifierCascade* cascade;
if( !CV_IS_HAAR_CLASSIFIER(_cascade) )
CV_Error( !_cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid cascade pointer" );
cascade = _cascade->hid_cascade;
if( !cascade )
CV_Error( CV_StsNullPtr, "Hidden cascade has not been created.\n"
"Use cvSetImagesForHaarClassifierCascade" );
if( pt.x < 0 || pt.y < 0 ||
pt.x + _cascade->real_window_size.width >= cascade->sum.width ||
pt.y + _cascade->real_window_size.height >= cascade->sum.height )
return -1;
p_offset = pt.y * (cascade->sum.step/sizeof(sumtype)) + pt.x;
pq_offset = pt.y * (cascade->sqsum.step/sizeof(sqsumtype)) + pt.x;
mean = calc_sum(*cascade,p_offset)*cascade->inv_window_area;
variance_norm_factor = cascade->pq0[pq_offset] - cascade->pq1[pq_offset] -
cascade->pq2[pq_offset] + cascade->pq3[pq_offset];
variance_norm_factor = variance_norm_factor*cascade->inv_window_area - mean*mean;
if( variance_norm_factor >= 0. )
variance_norm_factor = std::sqrt(variance_norm_factor);
else
variance_norm_factor = 1.;
if( cascade->is_tree )
{
CvHidHaarStageClassifier* ptr = cascade->stage_classifier;
assert( start_stage == 0 );
while( ptr )
{
stage_sum = 0.0;
j = 0;
#ifdef CV_HAAR_USE_AVX
if(haveAVX)
{
for( ; j <= ptr->count - 8; j += 8 )
{
stage_sum += icvEvalHidHaarClassifierAVX(
ptr->classifier + j,
variance_norm_factor, p_offset );
}
}
#endif
for( ; j < ptr->count; j++ )
{
stage_sum += icvEvalHidHaarClassifier( ptr->classifier + j, variance_norm_factor, p_offset );
}
if( stage_sum >= ptr->threshold )
{
ptr = ptr->child;
}
else
{
while( ptr && ptr->next == NULL ) ptr = ptr->parent;
if( ptr == NULL )
return 0;
ptr = ptr->next;
}
}
}
else if( cascade->isStumpBased )
{
#ifdef CV_HAAR_USE_AVX
if(haveAVX)
{
CvHidHaarClassifier* classifiers[8];
CvHidHaarTreeNode* nodes[8];
for( i = start_stage; i < cascade->count; i++ )
{
stage_sum = 0.0;
j = 0;
float CV_DECL_ALIGNED(32) buf[8];
if( cascade->stage_classifier[i].two_rects )
{
for( ; j <= cascade->stage_classifier[i].count - 8; j += 8 )
{
classifiers[0] = cascade->stage_classifier[i].classifier + j;
nodes[0] = classifiers[0]->node;
classifiers[1] = cascade->stage_classifier[i].classifier + j + 1;
nodes[1] = classifiers[1]->node;
classifiers[2] = cascade->stage_classifier[i].classifier + j + 2;
nodes[2] = classifiers[2]->node;
classifiers[3] = cascade->stage_classifier[i].classifier + j + 3;
nodes[3] = classifiers[3]->node;
classifiers[4] = cascade->stage_classifier[i].classifier + j + 4;
nodes[4] = classifiers[4]->node;
classifiers[5] = cascade->stage_classifier[i].classifier + j + 5;
nodes[5] = classifiers[5]->node;
classifiers[6] = cascade->stage_classifier[i].classifier + j + 6;
nodes[6] = classifiers[6]->node;
classifiers[7] = cascade->stage_classifier[i].classifier + j + 7;
nodes[7] = classifiers[7]->node;
__m256 t = _mm256_set1_ps(static_cast<float>(variance_norm_factor));
t = _mm256_mul_ps(t, _mm256_set_ps(nodes[7]->threshold,
nodes[6]->threshold,
nodes[5]->threshold,
nodes[4]->threshold,
nodes[3]->threshold,
nodes[2]->threshold,
nodes[1]->threshold,
nodes[0]->threshold));
__m256 offset = _mm256_set_ps(calc_sumf(nodes[7]->feature.rect[0], p_offset),
calc_sumf(nodes[6]->feature.rect[0], p_offset),
calc_sumf(nodes[5]->feature.rect[0], p_offset),
calc_sumf(nodes[4]->feature.rect[0], p_offset),
calc_sumf(nodes[3]->feature.rect[0], p_offset),
calc_sumf(nodes[2]->feature.rect[0], p_offset),
calc_sumf(nodes[1]->feature.rect[0], p_offset),
calc_sumf(nodes[0]->feature.rect[0], p_offset));
__m256 weight = _mm256_set_ps(nodes[7]->feature.rect[0].weight,
nodes[6]->feature.rect[0].weight,
nodes[5]->feature.rect[0].weight,
nodes[4]->feature.rect[0].weight,
nodes[3]->feature.rect[0].weight,
nodes[2]->feature.rect[0].weight,
nodes[1]->feature.rect[0].weight,
nodes[0]->feature.rect[0].weight);
__m256 sum = _mm256_mul_ps(offset, weight);
offset = _mm256_set_ps(calc_sumf(nodes[7]->feature.rect[1], p_offset),
calc_sumf(nodes[6]->feature.rect[1], p_offset),
calc_sumf(nodes[5]->feature.rect[1], p_offset),
calc_sumf(nodes[4]->feature.rect[1], p_offset),
calc_sumf(nodes[3]->feature.rect[1], p_offset),
calc_sumf(nodes[2]->feature.rect[1], p_offset),
calc_sumf(nodes[1]->feature.rect[1], p_offset),
calc_sumf(nodes[0]->feature.rect[1], p_offset));
weight = _mm256_set_ps(nodes[7]->feature.rect[1].weight,
nodes[6]->feature.rect[1].weight,
nodes[5]->feature.rect[1].weight,
nodes[4]->feature.rect[1].weight,
nodes[3]->feature.rect[1].weight,
nodes[2]->feature.rect[1].weight,
nodes[1]->feature.rect[1].weight,
nodes[0]->feature.rect[1].weight);
sum = _mm256_add_ps(sum, _mm256_mul_ps(offset,weight));
__m256 alpha0 = _mm256_set_ps(classifiers[7]->alpha[0],
classifiers[6]->alpha[0],
classifiers[5]->alpha[0],
classifiers[4]->alpha[0],
classifiers[3]->alpha[0],
classifiers[2]->alpha[0],
classifiers[1]->alpha[0],
classifiers[0]->alpha[0]);
__m256 alpha1 = _mm256_set_ps(classifiers[7]->alpha[1],
classifiers[6]->alpha[1],
classifiers[5]->alpha[1],
classifiers[4]->alpha[1],
classifiers[3]->alpha[1],
classifiers[2]->alpha[1],
classifiers[1]->alpha[1],
classifiers[0]->alpha[1]);
_mm256_store_ps(buf, _mm256_blendv_ps(alpha0, alpha1, _mm256_cmp_ps(t, sum, _CMP_LE_OQ)));
stage_sum += (buf[0]+buf[1]+buf[2]+buf[3]+buf[4]+buf[5]+buf[6]+buf[7]);
}
for( ; j < cascade->stage_classifier[i].count; j++ )
{
CvHidHaarClassifier* classifier = cascade->stage_classifier[i].classifier + j;
CvHidHaarTreeNode* node = classifier->node;
double t = node->threshold*variance_norm_factor;
double sum = calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight;
sum += calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight;
stage_sum += classifier->alpha[sum >= t];
}
}
else
{
for( ; j <= (cascade->stage_classifier[i].count)-8; j+=8 )
{
float CV_DECL_ALIGNED(32) tmp[8] = {0,0,0,0,0,0,0,0};
classifiers[0] = cascade->stage_classifier[i].classifier + j;
nodes[0] = classifiers[0]->node;
classifiers[1] = cascade->stage_classifier[i].classifier + j + 1;
nodes[1] = classifiers[1]->node;
classifiers[2] = cascade->stage_classifier[i].classifier + j + 2;
nodes[2] = classifiers[2]->node;
classifiers[3] = cascade->stage_classifier[i].classifier + j + 3;
nodes[3] = classifiers[3]->node;
classifiers[4] = cascade->stage_classifier[i].classifier + j + 4;
nodes[4] = classifiers[4]->node;
classifiers[5] = cascade->stage_classifier[i].classifier + j + 5;
nodes[5] = classifiers[5]->node;
classifiers[6] = cascade->stage_classifier[i].classifier + j + 6;
nodes[6] = classifiers[6]->node;
classifiers[7] = cascade->stage_classifier[i].classifier + j + 7;
nodes[7] = classifiers[7]->node;
__m256 t = _mm256_set1_ps(static_cast<float>(variance_norm_factor));
t = _mm256_mul_ps(t, _mm256_set_ps(nodes[7]->threshold,
nodes[6]->threshold,
nodes[5]->threshold,
nodes[4]->threshold,
nodes[3]->threshold,
nodes[2]->threshold,
nodes[1]->threshold,
nodes[0]->threshold));
__m256 offset = _mm256_set_ps(calc_sumf(nodes[7]->feature.rect[0], p_offset),
calc_sumf(nodes[6]->feature.rect[0], p_offset),
calc_sumf(nodes[5]->feature.rect[0], p_offset),
calc_sumf(nodes[4]->feature.rect[0], p_offset),
calc_sumf(nodes[3]->feature.rect[0], p_offset),
calc_sumf(nodes[2]->feature.rect[0], p_offset),
calc_sumf(nodes[1]->feature.rect[0], p_offset),
calc_sumf(nodes[0]->feature.rect[0], p_offset));
__m256 weight = _mm256_set_ps(nodes[7]->feature.rect[0].weight,
nodes[6]->feature.rect[0].weight,
nodes[5]->feature.rect[0].weight,
nodes[4]->feature.rect[0].weight,
nodes[3]->feature.rect[0].weight,
nodes[2]->feature.rect[0].weight,
nodes[1]->feature.rect[0].weight,
nodes[0]->feature.rect[0].weight);
__m256 sum = _mm256_mul_ps(offset, weight);
offset = _mm256_set_ps(calc_sumf(nodes[7]->feature.rect[1], p_offset),
calc_sumf(nodes[6]->feature.rect[1], p_offset),
calc_sumf(nodes[5]->feature.rect[1], p_offset),
calc_sumf(nodes[4]->feature.rect[1], p_offset),
calc_sumf(nodes[3]->feature.rect[1], p_offset),
calc_sumf(nodes[2]->feature.rect[1], p_offset),
calc_sumf(nodes[1]->feature.rect[1], p_offset),
calc_sumf(nodes[0]->feature.rect[1], p_offset));
weight = _mm256_set_ps(nodes[7]->feature.rect[1].weight,
nodes[6]->feature.rect[1].weight,
nodes[5]->feature.rect[1].weight,
nodes[4]->feature.rect[1].weight,
nodes[3]->feature.rect[1].weight,
nodes[2]->feature.rect[1].weight,
nodes[1]->feature.rect[1].weight,
nodes[0]->feature.rect[1].weight);
sum = _mm256_add_ps(sum, _mm256_mul_ps(offset, weight));
if( nodes[0]->feature.rect[2].p0 )
tmp[0] = calc_sumf(nodes[0]->feature.rect[2],p_offset) * nodes[0]->feature.rect[2].weight;
if( nodes[1]->feature.rect[2].p0 )
tmp[1] = calc_sumf(nodes[1]->feature.rect[2],p_offset) * nodes[1]->feature.rect[2].weight;
if( nodes[2]->feature.rect[2].p0 )
tmp[2] = calc_sumf(nodes[2]->feature.rect[2],p_offset) * nodes[2]->feature.rect[2].weight;
if( nodes[3]->feature.rect[2].p0 )
tmp[3] = calc_sumf(nodes[3]->feature.rect[2],p_offset) * nodes[3]->feature.rect[2].weight;
if( nodes[4]->feature.rect[2].p0 )
tmp[4] = calc_sumf(nodes[4]->feature.rect[2],p_offset) * nodes[4]->feature.rect[2].weight;
if( nodes[5]->feature.rect[2].p0 )
tmp[5] = calc_sumf(nodes[5]->feature.rect[2],p_offset) * nodes[5]->feature.rect[2].weight;
if( nodes[6]->feature.rect[2].p0 )
tmp[6] = calc_sumf(nodes[6]->feature.rect[2],p_offset) * nodes[6]->feature.rect[2].weight;
if( nodes[7]->feature.rect[2].p0 )
tmp[7] = calc_sumf(nodes[7]->feature.rect[2],p_offset) * nodes[7]->feature.rect[2].weight;
sum = _mm256_add_ps(sum, _mm256_load_ps(tmp));
__m256 alpha0 = _mm256_set_ps(classifiers[7]->alpha[0],
classifiers[6]->alpha[0],
classifiers[5]->alpha[0],
classifiers[4]->alpha[0],
classifiers[3]->alpha[0],
classifiers[2]->alpha[0],
classifiers[1]->alpha[0],
classifiers[0]->alpha[0]);
__m256 alpha1 = _mm256_set_ps(classifiers[7]->alpha[1],
classifiers[6]->alpha[1],
classifiers[5]->alpha[1],
classifiers[4]->alpha[1],
classifiers[3]->alpha[1],
classifiers[2]->alpha[1],
classifiers[1]->alpha[1],
classifiers[0]->alpha[1]);
__m256 outBuf = _mm256_blendv_ps(alpha0, alpha1, _mm256_cmp_ps(t, sum, _CMP_LE_OQ ));
outBuf = _mm256_hadd_ps(outBuf, outBuf);
outBuf = _mm256_hadd_ps(outBuf, outBuf);
_mm256_store_ps(buf, outBuf);
stage_sum += (buf[0] + buf[4]);
}
for( ; j < cascade->stage_classifier[i].count; j++ )
{
CvHidHaarClassifier* classifier = cascade->stage_classifier[i].classifier + j;
CvHidHaarTreeNode* node = classifier->node;
double t = node->threshold*variance_norm_factor;
double sum = calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight;
sum += calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight;
if( node->feature.rect[2].p0 )
sum += calc_sum(node->feature.rect[2],p_offset) * node->feature.rect[2].weight;
stage_sum += classifier->alpha[sum >= t];
}
}
if( stage_sum < cascade->stage_classifier[i].threshold )
return -i;
}
}
else
#elif defined CV_HAAR_USE_SSE //old SSE optimization
if(haveSSE2)
{
for( i = start_stage; i < cascade->count; i++ )
{
__m128d vstage_sum = _mm_setzero_pd();
if( cascade->stage_classifier[i].two_rects )
{
for( j = 0; j < cascade->stage_classifier[i].count; j++ )
{
CvHidHaarClassifier* classifier = cascade->stage_classifier[i].classifier + j;
CvHidHaarTreeNode* node = classifier->node;
// ayasin - NHM perf optim. Avoid use of costly flaky jcc
__m128d t = _mm_set_sd(node->threshold*variance_norm_factor);
__m128d a = _mm_set_sd(classifier->alpha[0]);
__m128d b = _mm_set_sd(classifier->alpha[1]);
__m128d sum = _mm_set_sd(calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight +
calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight);
t = _mm_cmpgt_sd(t, sum);
vstage_sum = _mm_add_sd(vstage_sum, _mm_blendv_pd(b, a, t));
}
}
else
{
for( j = 0; j < cascade->stage_classifier[i].count; j++ )
{
CvHidHaarClassifier* classifier = cascade->stage_classifier[i].classifier + j;
CvHidHaarTreeNode* node = classifier->node;
// ayasin - NHM perf optim. Avoid use of costly flaky jcc
__m128d t = _mm_set_sd(node->threshold*variance_norm_factor);
__m128d a = _mm_set_sd(classifier->alpha[0]);
__m128d b = _mm_set_sd(classifier->alpha[1]);
double _sum = calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight;
_sum += calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight;
if( node->feature.rect[2].p0 )
_sum += calc_sum(node->feature.rect[2],p_offset) * node->feature.rect[2].weight;
__m128d sum = _mm_set_sd(_sum);
t = _mm_cmpgt_sd(t, sum);
vstage_sum = _mm_add_sd(vstage_sum, _mm_blendv_pd(b, a, t));
}
}
__m128d i_threshold = _mm_set1_pd(cascade->stage_classifier[i].threshold);
if( _mm_comilt_sd(vstage_sum, i_threshold) )
return -i;
}
}
else
#endif // AVX or SSE
{
for( i = start_stage; i < cascade->count; i++ )
{
stage_sum = 0.0;
if( cascade->stage_classifier[i].two_rects )
{
for( j = 0; j < cascade->stage_classifier[i].count; j++ )
{
CvHidHaarClassifier* classifier = cascade->stage_classifier[i].classifier + j;
CvHidHaarTreeNode* node = classifier->node;
double t = node->threshold*variance_norm_factor;
double sum = calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight;
sum += calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight;
stage_sum += classifier->alpha[sum >= t];
}
}
else
{
for( j = 0; j < cascade->stage_classifier[i].count; j++ )
{
CvHidHaarClassifier* classifier = cascade->stage_classifier[i].classifier + j;
CvHidHaarTreeNode* node = classifier->node;
double t = node->threshold*variance_norm_factor;
double sum = calc_sum(node->feature.rect[0],p_offset) * node->feature.rect[0].weight;
sum += calc_sum(node->feature.rect[1],p_offset) * node->feature.rect[1].weight;
if( node->feature.rect[2].p0 )
sum += calc_sum(node->feature.rect[2],p_offset) * node->feature.rect[2].weight;
stage_sum += classifier->alpha[sum >= t];
}
}
if( stage_sum < cascade->stage_classifier[i].threshold )
return -i;
}
}
}
else
{
for( i = start_stage; i < cascade->count; i++ )
{
stage_sum = 0.0;
int k = 0;
#ifdef CV_HAAR_USE_AVX
if(haveAVX)
{
for( ; k < cascade->stage_classifier[i].count - 8; k += 8 )
{
stage_sum += icvEvalHidHaarClassifierAVX(
cascade->stage_classifier[i].classifier + k,
variance_norm_factor, p_offset );
}
}
#endif
for(; k < cascade->stage_classifier[i].count; k++ )
{
stage_sum += icvEvalHidHaarClassifier(
cascade->stage_classifier[i].classifier + k,
variance_norm_factor, p_offset );
}
if( stage_sum < cascade->stage_classifier[i].threshold )
return -i;
}
}
return 1;
}
CV_IMPL int
cvRunHaarClassifierCascade( const CvHaarClassifierCascade* _cascade,
CvPoint pt, int start_stage )
{
double stage_sum;
return cvRunHaarClassifierCascadeSum(_cascade, pt, stage_sum, start_stage);
}
namespace cv
{
class HaarDetectObjects_ScaleImage_Invoker : public ParallelLoopBody
{
public:
HaarDetectObjects_ScaleImage_Invoker( const CvHaarClassifierCascade* _cascade,
int _stripSize, double _factor,
const Mat& _sum1, const Mat& _sqsum1, Mat* _norm1,
Mat* _mask1, Rect _equRect, std::vector<Rect>& _vec,
std::vector<int>& _levels, std::vector<double>& _weights,
bool _outputLevels, Mutex *_mtx )
{
cascade = _cascade;
stripSize = _stripSize;
factor = _factor;
sum1 = _sum1;
sqsum1 = _sqsum1;
norm1 = _norm1;
mask1 = _mask1;
equRect = _equRect;
vec = &_vec;
rejectLevels = _outputLevels ? &_levels : 0;
levelWeights = _outputLevels ? &_weights : 0;
mtx = _mtx;
}
void operator()( const Range& range ) const
{
Size winSize0 = cascade->orig_window_size;
Size winSize(cvRound(winSize0.width*factor), cvRound(winSize0.height*factor));
int y1 = range.start*stripSize, y2 = std::min(range.end*stripSize, sum1.rows - 1 - winSize0.height);
if (y2 <= y1 || sum1.cols <= 1 + winSize0.width)
return;
Size ssz(sum1.cols - 1 - winSize0.width, y2 - y1);
int x, y, ystep = factor > 2 ? 1 : 2;
#ifdef HAVE_IPP
if( cascade->hid_cascade->ipp_stages )
{
IppiRect iequRect = {equRect.x, equRect.y, equRect.width, equRect.height};
ippiRectStdDev_32f_C1R(sum1.ptr<float>(y1), (int)sum1.step,
sqsum1.ptr<double>(y1), (int)sqsum1.step,
norm1->ptr<float>(y1), (int)norm1->step,
ippiSize(ssz.width, ssz.height), iequRect );
int positive = (ssz.width/ystep)*((ssz.height + ystep-1)/ystep);
if( ystep == 1 )
(*mask1) = Scalar::all(1);
else
for( y = y1; y < y2; y++ )
{
uchar* mask1row = mask1->ptr(y);
memset( mask1row, 0, ssz.width );
if( y % ystep == 0 )
for( x = 0; x < ssz.width; x += ystep )
mask1row[x] = (uchar)1;
}
for( int j = 0; j < cascade->count; j++ )
{
if( ippiApplyHaarClassifier_32f_C1R(
sum1.ptr<float>(y1), (int)sum1.step,
norm1->ptr<float>(y1), (int)norm1->step,
mask1->ptr<uchar>(y1), (int)mask1->step,
ippiSize(ssz.width, ssz.height), &positive,
cascade->hid_cascade->stage_classifier[j].threshold,
(IppiHaarClassifier_32f*)cascade->hid_cascade->ipp_stages[j]) < 0 )
positive = 0;
if( positive <= 0 )
break;
}
if( positive > 0 )
for( y = y1; y < y2; y += ystep )
{
uchar* mask1row = mask1->ptr(y);
for( x = 0; x < ssz.width; x += ystep )
if( mask1row[x] != 0 )
{
mtx->lock();
vec->push_back(Rect(cvRound(x*factor), cvRound(y*factor),
winSize.width, winSize.height));
mtx->unlock();
if( --positive == 0 )
break;
}
if( positive == 0 )
break;
}
}
else
#endif // IPP
for( y = y1; y < y2; y += ystep )
for( x = 0; x < ssz.width; x += ystep )
{
double gypWeight;
int result = cvRunHaarClassifierCascadeSum( cascade, cvPoint(x,y), gypWeight, 0 );
if( rejectLevels )
{
if( result == 1 )
result = -1*cascade->count;
if( cascade->count + result < 4 )
{
mtx->lock();
vec->push_back(Rect(cvRound(x*factor), cvRound(y*factor),
winSize.width, winSize.height));
rejectLevels->push_back(-result);
levelWeights->push_back(gypWeight);
mtx->unlock();
}
}
else
{
if( result > 0 )
{
mtx->lock();
vec->push_back(Rect(cvRound(x*factor), cvRound(y*factor),
winSize.width, winSize.height));
mtx->unlock();
}
}
}
}
const CvHaarClassifierCascade* cascade;
int stripSize;
double factor;
Mat sum1, sqsum1, *norm1, *mask1;
Rect equRect;
std::vector<Rect>* vec;
std::vector<int>* rejectLevels;
std::vector<double>* levelWeights;
Mutex* mtx;
};
class HaarDetectObjects_ScaleCascade_Invoker : public ParallelLoopBody
{
public:
HaarDetectObjects_ScaleCascade_Invoker( const CvHaarClassifierCascade* _cascade,
Size _winsize, const Range& _xrange, double _ystep,
size_t _sumstep, const int** _p, const int** _pq,
std::vector<Rect>& _vec, Mutex* _mtx )
{
cascade = _cascade;
winsize = _winsize;
xrange = _xrange;
ystep = _ystep;
sumstep = _sumstep;
p = _p; pq = _pq;
vec = &_vec;
mtx = _mtx;
}
void operator()( const Range& range ) const
{
int iy, startY = range.start, endY = range.end;
const int *p0 = p[0], *p1 = p[1], *p2 = p[2], *p3 = p[3];
const int *pq0 = pq[0], *pq1 = pq[1], *pq2 = pq[2], *pq3 = pq[3];
bool doCannyPruning = p0 != 0;
int sstep = (int)(sumstep/sizeof(p0[0]));
for( iy = startY; iy < endY; iy++ )
{
int ix, y = cvRound(iy*ystep), ixstep = 1;
for( ix = xrange.start; ix < xrange.end; ix += ixstep )
{
int x = cvRound(ix*ystep); // it should really be ystep, not ixstep
if( doCannyPruning )
{
int offset = y*sstep + x;
int s = p0[offset] - p1[offset] - p2[offset] + p3[offset];
int sq = pq0[offset] - pq1[offset] - pq2[offset] + pq3[offset];
if( s < 100 || sq < 20 )
{
ixstep = 2;
continue;
}
}
int result = cvRunHaarClassifierCascade( cascade, cvPoint(x, y), 0 );
if( result > 0 )
{
mtx->lock();
vec->push_back(Rect(x, y, winsize.width, winsize.height));
mtx->unlock();
}
ixstep = result != 0 ? 1 : 2;
}
}
}
const CvHaarClassifierCascade* cascade;
double ystep;
size_t sumstep;
Size winsize;
Range xrange;
const int** p;
const int** pq;
std::vector<Rect>* vec;
Mutex* mtx;
};
}
CvSeq*
cvHaarDetectObjectsForROC( const CvArr* _img,
CvHaarClassifierCascade* cascade, CvMemStorage* storage,
std::vector<int>& rejectLevels, std::vector<double>& levelWeights,
double scaleFactor, int minNeighbors, int flags,
CvSize minSize, CvSize maxSize, bool outputRejectLevels )
{
const double GROUP_EPS = 0.2;
CvMat stub, *img = (CvMat*)_img;
cv::Ptr<CvMat> temp, sum, tilted, sqsum, normImg, sumcanny, imgSmall;
CvSeq* result_seq = 0;
cv::Ptr<CvMemStorage> temp_storage;
std::vector<cv::Rect> allCandidates;
std::vector<cv::Rect> rectList;
std::vector<int> rweights;
double factor;
int coi;
bool doCannyPruning = (flags & CV_HAAR_DO_CANNY_PRUNING) != 0;
bool findBiggestObject = (flags & CV_HAAR_FIND_BIGGEST_OBJECT) != 0;
bool roughSearch = (flags & CV_HAAR_DO_ROUGH_SEARCH) != 0;
cv::Mutex mtx;
if( !CV_IS_HAAR_CLASSIFIER(cascade) )
CV_Error( !cascade ? CV_StsNullPtr : CV_StsBadArg, "Invalid classifier cascade" );
if( !storage )
CV_Error( CV_StsNullPtr, "Null storage pointer" );
img = cvGetMat( img, &stub, &coi );
if( coi )
CV_Error( CV_BadCOI, "COI is not supported" );
if( CV_MAT_DEPTH(img->type) != CV_8U )
CV_Error( CV_StsUnsupportedFormat, "Only 8-bit images are supported" );
if( scaleFactor <= 1 )
CV_Error( CV_StsOutOfRange, "scale factor must be > 1" );
if( findBiggestObject )
flags &= ~CV_HAAR_SCALE_IMAGE;
if( maxSize.height == 0 || maxSize.width == 0 )
{
maxSize.height = img->rows;
maxSize.width = img->cols;
}
temp.reset(cvCreateMat( img->rows, img->cols, CV_8UC1 ));
sum.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 ));
sqsum.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_64FC1 ));
if( !cascade->hid_cascade )
icvCreateHidHaarClassifierCascade(cascade);
if( cascade->hid_cascade->has_tilted_features )
tilted.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 ));
result_seq = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvAvgComp), storage );
if( CV_MAT_CN(img->type) > 1 )
{
cvCvtColor( img, temp, CV_BGR2GRAY );
img = temp;
}
if( findBiggestObject )
flags &= ~(CV_HAAR_SCALE_IMAGE|CV_HAAR_DO_CANNY_PRUNING);
if( flags & CV_HAAR_SCALE_IMAGE )
{
CvSize winSize0 = cascade->orig_window_size;
#ifdef HAVE_IPP
int use_ipp = cascade->hid_cascade->ipp_stages != 0;
if( use_ipp )
normImg.reset(cvCreateMat( img->rows, img->cols, CV_32FC1));
#endif
imgSmall.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_8UC1 ));
for( factor = 1; ; factor *= scaleFactor )
{
CvSize winSize(cvRound(winSize0.width*factor),
cvRound(winSize0.height*factor));
CvSize sz(cvRound( img->cols/factor ), cvRound( img->rows/factor ));
CvSize sz1(sz.width - winSize0.width + 1, sz.height - winSize0.height + 1);
CvRect equRect(icv_object_win_border, icv_object_win_border,
winSize0.width - icv_object_win_border*2,
winSize0.height - icv_object_win_border*2);
CvMat img1, sum1, sqsum1, norm1, tilted1, mask1;
CvMat* _tilted = 0;
if( sz1.width <= 0 || sz1.height <= 0 )
break;
if( winSize.width > maxSize.width || winSize.height > maxSize.height )
break;
if( winSize.width < minSize.width || winSize.height < minSize.height )
continue;
img1 = cvMat( sz.height, sz.width, CV_8UC1, imgSmall->data.ptr );
sum1 = cvMat( sz.height+1, sz.width+1, CV_32SC1, sum->data.ptr );
sqsum1 = cvMat( sz.height+1, sz.width+1, CV_64FC1, sqsum->data.ptr );
if( tilted )
{
tilted1 = cvMat( sz.height+1, sz.width+1, CV_32SC1, tilted->data.ptr );
_tilted = &tilted1;
}
norm1 = cvMat( sz1.height, sz1.width, CV_32FC1, normImg ? normImg->data.ptr : 0 );
mask1 = cvMat( sz1.height, sz1.width, CV_8UC1, temp->data.ptr );
cvResize( img, &img1, CV_INTER_LINEAR );
cvIntegral( &img1, &sum1, &sqsum1, _tilted );
int ystep = factor > 2 ? 1 : 2;
const int LOCS_PER_THREAD = 1000;
int stripCount = ((sz1.width/ystep)*(sz1.height + ystep-1)/ystep + LOCS_PER_THREAD/2)/LOCS_PER_THREAD;
stripCount = std::min(std::max(stripCount, 1), 100);
#ifdef HAVE_IPP
if( use_ipp )
{
cv::Mat fsum(sum1.rows, sum1.cols, CV_32F, sum1.data.ptr, sum1.step);
cv::cvarrToMat(&sum1).convertTo(fsum, CV_32F, 1, -(1<<24));
}
else
#endif
cvSetImagesForHaarClassifierCascade( cascade, &sum1, &sqsum1, _tilted, 1. );
cv::Mat _norm1 = cv::cvarrToMat(&norm1), _mask1 = cv::cvarrToMat(&mask1);
cv::parallel_for_(cv::Range(0, stripCount),
cv::HaarDetectObjects_ScaleImage_Invoker(cascade,
(((sz1.height + stripCount - 1)/stripCount + ystep-1)/ystep)*ystep,
factor, cv::cvarrToMat(&sum1), cv::cvarrToMat(&sqsum1), &_norm1, &_mask1,
cv::Rect(equRect), allCandidates, rejectLevels, levelWeights, outputRejectLevels, &mtx));
}
}
else
{
int n_factors = 0;
cv::Rect scanROI;
cvIntegral( img, sum, sqsum, tilted );
if( doCannyPruning )
{
sumcanny.reset(cvCreateMat( img->rows + 1, img->cols + 1, CV_32SC1 ));
cvCanny( img, temp, 0, 50, 3 );
cvIntegral( temp, sumcanny );
}
for( n_factors = 0, factor = 1;
factor*cascade->orig_window_size.width < img->cols - 10 &&
factor*cascade->orig_window_size.height < img->rows - 10;
n_factors++, factor *= scaleFactor )
;
if( findBiggestObject )
{
scaleFactor = 1./scaleFactor;
factor *= scaleFactor;
}
else
factor = 1;
for( ; n_factors-- > 0; factor *= scaleFactor )
{
const double ystep = std::max( 2., factor );
CvSize winSize(cvRound( cascade->orig_window_size.width * factor ),
cvRound( cascade->orig_window_size.height * factor ));
CvRect equRect;
int *p[4] = {0,0,0,0};
int *pq[4] = {0,0,0,0};
int startX = 0, startY = 0;
int endX = cvRound((img->cols - winSize.width) / ystep);
int endY = cvRound((img->rows - winSize.height) / ystep);
if( winSize.width < minSize.width || winSize.height < minSize.height )
{
if( findBiggestObject )
break;
continue;
}
if ( winSize.width > maxSize.width || winSize.height > maxSize.height )
{
if( !findBiggestObject )
break;
continue;
}
cvSetImagesForHaarClassifierCascade( cascade, sum, sqsum, tilted, factor );
cvZero( temp );
if( doCannyPruning )
{
equRect.x = cvRound(winSize.width*0.15);
equRect.y = cvRound(winSize.height*0.15);
equRect.width = cvRound(winSize.width*0.7);
equRect.height = cvRound(winSize.height*0.7);
p[0] = (int*)(sumcanny->data.ptr + equRect.y*sumcanny->step) + equRect.x;
p[1] = (int*)(sumcanny->data.ptr + equRect.y*sumcanny->step)
+ equRect.x + equRect.width;
p[2] = (int*)(sumcanny->data.ptr + (equRect.y + equRect.height)*sumcanny->step) + equRect.x;
p[3] = (int*)(sumcanny->data.ptr + (equRect.y + equRect.height)*sumcanny->step)
+ equRect.x + equRect.width;
pq[0] = (int*)(sum->data.ptr + equRect.y*sum->step) + equRect.x;
pq[1] = (int*)(sum->data.ptr + equRect.y*sum->step)
+ equRect.x + equRect.width;
pq[2] = (int*)(sum->data.ptr + (equRect.y + equRect.height)*sum->step) + equRect.x;
pq[3] = (int*)(sum->data.ptr + (equRect.y + equRect.height)*sum->step)
+ equRect.x + equRect.width;
}
if( scanROI.area() > 0 )
{
//adjust start_height and stop_height
startY = cvRound(scanROI.y / ystep);
endY = cvRound((scanROI.y + scanROI.height - winSize.height) / ystep);
startX = cvRound(scanROI.x / ystep);
endX = cvRound((scanROI.x + scanROI.width - winSize.width) / ystep);
}
cv::parallel_for_(cv::Range(startY, endY),
cv::HaarDetectObjects_ScaleCascade_Invoker(cascade, winSize, cv::Range(startX, endX),
ystep, sum->step, (const int**)p,
(const int**)pq, allCandidates, &mtx ));
if( findBiggestObject && !allCandidates.empty() && scanROI.area() == 0 )
{
rectList.resize(allCandidates.size());
std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
groupRectangles(rectList, std::max(minNeighbors, 1), GROUP_EPS);
if( !rectList.empty() )
{
size_t i, sz = rectList.size();
cv::Rect maxRect;
for( i = 0; i < sz; i++ )
{
if( rectList[i].area() > maxRect.area() )
maxRect = rectList[i];
}
allCandidates.push_back(maxRect);
scanROI = maxRect;
int dx = cvRound(maxRect.width*GROUP_EPS);
int dy = cvRound(maxRect.height*GROUP_EPS);
scanROI.x = std::max(scanROI.x - dx, 0);
scanROI.y = std::max(scanROI.y - dy, 0);
scanROI.width = std::min(scanROI.width + dx*2, img->cols-1-scanROI.x);
scanROI.height = std::min(scanROI.height + dy*2, img->rows-1-scanROI.y);
double minScale = roughSearch ? 0.6 : 0.4;
minSize.width = cvRound(maxRect.width*minScale);
minSize.height = cvRound(maxRect.height*minScale);
}
}
}
}
rectList.resize(allCandidates.size());
if(!allCandidates.empty())
std::copy(allCandidates.begin(), allCandidates.end(), rectList.begin());
if( minNeighbors != 0 || findBiggestObject )
{
if( outputRejectLevels )
{
groupRectangles(rectList, rejectLevels, levelWeights, minNeighbors, GROUP_EPS );
}
else
{
groupRectangles(rectList, rweights, std::max(minNeighbors, 1), GROUP_EPS);
}
}
else
rweights.resize(rectList.size(),0);
if( findBiggestObject && rectList.size() )
{
CvAvgComp result_comp = {CvRect(),0};
for( size_t i = 0; i < rectList.size(); i++ )
{
cv::Rect r = rectList[i];
if( r.area() > cv::Rect(result_comp.rect).area() )
{
result_comp.rect = r;
result_comp.neighbors = rweights[i];
}
}
cvSeqPush( result_seq, &result_comp );
}
else
{
for( size_t i = 0; i < rectList.size(); i++ )
{
CvAvgComp c;
c.rect = rectList[i];
c.neighbors = !rweights.empty() ? rweights[i] : 0;
cvSeqPush( result_seq, &c );
}
}
return result_seq;
}
CV_IMPL CvSeq*
cvHaarDetectObjects( const CvArr* _img,
CvHaarClassifierCascade* cascade, CvMemStorage* storage,
double scaleFactor,
int minNeighbors, int flags, CvSize minSize, CvSize maxSize )
{
std::vector<int> fakeLevels;
std::vector<double> fakeWeights;
return cvHaarDetectObjectsForROC( _img, cascade, storage, fakeLevels, fakeWeights,
scaleFactor, minNeighbors, flags, minSize, maxSize, false );
}
static CvHaarClassifierCascade*
icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size )
{
int i;
CvHaarClassifierCascade* cascade = icvCreateHaarClassifierCascade(n);
cascade->orig_window_size = orig_window_size;
for( i = 0; i < n; i++ )
{
int j, count, l;
float threshold = 0;
const char* stage = input_cascade[i];
int dl = 0;
/* tree links */
int parent = -1;
int next = -1;
sscanf( stage, "%d%n", &count, &dl );
stage += dl;
assert( count > 0 );
cascade->stage_classifier[i].count = count;
cascade->stage_classifier[i].classifier =
(CvHaarClassifier*)cvAlloc( count*sizeof(cascade->stage_classifier[i].classifier[0]));
for( j = 0; j < count; j++ )
{
CvHaarClassifier* classifier = cascade->stage_classifier[i].classifier + j;
int k, rects = 0;
char str[100];
sscanf( stage, "%d%n", &classifier->count, &dl );
stage += dl;
classifier->haar_feature = (CvHaarFeature*) cvAlloc(
classifier->count * ( sizeof( *classifier->haar_feature ) +
sizeof( *classifier->threshold ) +
sizeof( *classifier->left ) +
sizeof( *classifier->right ) ) +
(classifier->count + 1) * sizeof( *classifier->alpha ) );
classifier->threshold = (float*) (classifier->haar_feature+classifier->count);
classifier->left = (int*) (classifier->threshold + classifier->count);
classifier->right = (int*) (classifier->left + classifier->count);
classifier->alpha = (float*) (classifier->right + classifier->count);
for( l = 0; l < classifier->count; l++ )
{
sscanf( stage, "%d%n", &rects, &dl );
stage += dl;
assert( rects >= 2 && rects <= CV_HAAR_FEATURE_MAX );
for( k = 0; k < rects; k++ )
{
CvRect r;
int band = 0;
sscanf( stage, "%d%d%d%d%d%f%n",
&r.x, &r.y, &r.width, &r.height, &band,
&(classifier->haar_feature[l].rect[k].weight), &dl );
stage += dl;
classifier->haar_feature[l].rect[k].r = r;
}
sscanf( stage, "%s%n", str, &dl );
stage += dl;
classifier->haar_feature[l].tilted = strncmp( str, "tilted", 6 ) == 0;
for( k = rects; k < CV_HAAR_FEATURE_MAX; k++ )
{
memset( classifier->haar_feature[l].rect + k, 0,
sizeof(classifier->haar_feature[l].rect[k]) );
}
sscanf( stage, "%f%d%d%n", &(classifier->threshold[l]),
&(classifier->left[l]),
&(classifier->right[l]), &dl );
stage += dl;
}
for( l = 0; l <= classifier->count; l++ )
{
sscanf( stage, "%f%n", &(classifier->alpha[l]), &dl );
stage += dl;
}
}
sscanf( stage, "%f%n", &threshold, &dl );
stage += dl;
cascade->stage_classifier[i].threshold = threshold;
/* load tree links */
if( sscanf( stage, "%d%d%n", &parent, &next, &dl ) != 2 )
{
parent = i - 1;
next = -1;
}
stage += dl;
cascade->stage_classifier[i].parent = parent;
cascade->stage_classifier[i].next = next;
cascade->stage_classifier[i].child = -1;
if( parent != -1 && cascade->stage_classifier[parent].child == -1 )
{
cascade->stage_classifier[parent].child = i;
}
}
return cascade;
}
#ifndef _MAX_PATH
#define _MAX_PATH 1024
#endif
CV_IMPL CvHaarClassifierCascade*
cvLoadHaarClassifierCascade( const char* directory, CvSize orig_window_size )
{
if( !directory )
CV_Error( CV_StsNullPtr, "Null path is passed" );
char name[_MAX_PATH];
int n = (int)strlen(directory)-1;
const char* slash = directory[n] == '\\' || directory[n] == '/' ? "" : "/";
int size = 0;
/* try to read the classifier from directory */
for( n = 0; ; n++ )
{
sprintf( name, "%s%s%d/AdaBoostCARTHaarClassifier.txt", directory, slash, n );
FILE* f = fopen( name, "rb" );
if( !f )
break;
fseek( f, 0, SEEK_END );
size += ftell( f ) + 1;
fclose(f);
}
if( n == 0 && slash[0] )
return (CvHaarClassifierCascade*)cvLoad( directory );
if( n == 0 )
CV_Error( CV_StsBadArg, "Invalid path" );
size += (n+1)*sizeof(char*);
const char** input_cascade = (const char**)cvAlloc( size );
if( !input_cascade )
CV_Error( CV_StsNoMem, "Could not allocate memory for input_cascade" );
char* ptr = (char*)(input_cascade + n + 1);
for( int i = 0; i < n; i++ )
{
sprintf( name, "%s/%d/AdaBoostCARTHaarClassifier.txt", directory, i );
FILE* f = fopen( name, "rb" );
if( !f )
CV_Error( CV_StsError, "" );
fseek( f, 0, SEEK_END );
size = ftell( f );
fseek( f, 0, SEEK_SET );
size_t elements_read = fread( ptr, 1, size, f );
CV_Assert(elements_read == (size_t)(size));
fclose(f);
input_cascade[i] = ptr;
ptr += size;
*ptr++ = '\0';
}
input_cascade[n] = 0;
CvHaarClassifierCascade* cascade = icvLoadCascadeCART( input_cascade, n, orig_window_size );
if( input_cascade )
cvFree( &input_cascade );
return cascade;
}
CV_IMPL void
cvReleaseHaarClassifierCascade( CvHaarClassifierCascade** _cascade )
{
if( _cascade && *_cascade )
{
int i, j;
CvHaarClassifierCascade* cascade = *_cascade;
for( i = 0; i < cascade->count; i++ )
{
for( j = 0; j < cascade->stage_classifier[i].count; j++ )
cvFree( &cascade->stage_classifier[i].classifier[j].haar_feature );
cvFree( &cascade->stage_classifier[i].classifier );
}
icvReleaseHidHaarClassifierCascade( &cascade->hid_cascade );
cvFree( _cascade );
}
}
/****************************************************************************************\
* Persistence functions *
\****************************************************************************************/
/* field names */
#define ICV_HAAR_SIZE_NAME "size"
#define ICV_HAAR_STAGES_NAME "stages"
#define ICV_HAAR_TREES_NAME "trees"
#define ICV_HAAR_FEATURE_NAME "feature"
#define ICV_HAAR_RECTS_NAME "rects"
#define ICV_HAAR_TILTED_NAME "tilted"
#define ICV_HAAR_THRESHOLD_NAME "threshold"
#define ICV_HAAR_LEFT_NODE_NAME "left_node"
#define ICV_HAAR_LEFT_VAL_NAME "left_val"
#define ICV_HAAR_RIGHT_NODE_NAME "right_node"
#define ICV_HAAR_RIGHT_VAL_NAME "right_val"
#define ICV_HAAR_STAGE_THRESHOLD_NAME "stage_threshold"
#define ICV_HAAR_PARENT_NAME "parent"
#define ICV_HAAR_NEXT_NAME "next"
static int
icvIsHaarClassifier( const void* struct_ptr )
{
return CV_IS_HAAR_CLASSIFIER( struct_ptr );
}
static void*
icvReadHaarClassifier( CvFileStorage* fs, CvFileNode* node )
{
CvHaarClassifierCascade* cascade = NULL;
char buf[256];
CvFileNode* seq_fn = NULL; /* sequence */
CvFileNode* fn = NULL;
CvFileNode* stages_fn = NULL;
CvSeqReader stages_reader;
int n;
int i, j, k, l;
int parent, next;
stages_fn = cvGetFileNodeByName( fs, node, ICV_HAAR_STAGES_NAME );
if( !stages_fn || !CV_NODE_IS_SEQ( stages_fn->tag) )
CV_Error( CV_StsError, "Invalid stages node" );
n = stages_fn->data.seq->total;
cascade = icvCreateHaarClassifierCascade(n);
/* read size */
seq_fn = cvGetFileNodeByName( fs, node, ICV_HAAR_SIZE_NAME );
if( !seq_fn || !CV_NODE_IS_SEQ( seq_fn->tag ) || seq_fn->data.seq->total != 2 )
CV_Error( CV_StsError, "size node is not a valid sequence." );
fn = (CvFileNode*) cvGetSeqElem( seq_fn->data.seq, 0 );
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i <= 0 )
CV_Error( CV_StsError, "Invalid size node: width must be positive integer" );
cascade->orig_window_size.width = fn->data.i;
fn = (CvFileNode*) cvGetSeqElem( seq_fn->data.seq, 1 );
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i <= 0 )
CV_Error( CV_StsError, "Invalid size node: height must be positive integer" );
cascade->orig_window_size.height = fn->data.i;
cvStartReadSeq( stages_fn->data.seq, &stages_reader );
for( i = 0; i < n; ++i )
{
CvFileNode* stage_fn;
CvFileNode* trees_fn;
CvSeqReader trees_reader;
stage_fn = (CvFileNode*) stages_reader.ptr;
if( !CV_NODE_IS_MAP( stage_fn->tag ) )
{
sprintf( buf, "Invalid stage %d", i );
CV_Error( CV_StsError, buf );
}
trees_fn = cvGetFileNodeByName( fs, stage_fn, ICV_HAAR_TREES_NAME );
if( !trees_fn || !CV_NODE_IS_SEQ( trees_fn->tag )
|| trees_fn->data.seq->total <= 0 )
{
sprintf( buf, "Trees node is not a valid sequence. (stage %d)", i );
CV_Error( CV_StsError, buf );
}
cascade->stage_classifier[i].classifier =
(CvHaarClassifier*) cvAlloc( trees_fn->data.seq->total
* sizeof( cascade->stage_classifier[i].classifier[0] ) );
for( j = 0; j < trees_fn->data.seq->total; ++j )
{
cascade->stage_classifier[i].classifier[j].haar_feature = NULL;
}
cascade->stage_classifier[i].count = trees_fn->data.seq->total;
cvStartReadSeq( trees_fn->data.seq, &trees_reader );
for( j = 0; j < trees_fn->data.seq->total; ++j )
{
CvFileNode* tree_fn;
CvSeqReader tree_reader;
CvHaarClassifier* classifier;
int last_idx;
classifier = &cascade->stage_classifier[i].classifier[j];
tree_fn = (CvFileNode*) trees_reader.ptr;
if( !CV_NODE_IS_SEQ( tree_fn->tag ) || tree_fn->data.seq->total <= 0 )
{
sprintf( buf, "Tree node is not a valid sequence."
" (stage %d, tree %d)", i, j );
CV_Error( CV_StsError, buf );
}
classifier->count = tree_fn->data.seq->total;
classifier->haar_feature = (CvHaarFeature*) cvAlloc(
classifier->count * ( sizeof( *classifier->haar_feature ) +
sizeof( *classifier->threshold ) +
sizeof( *classifier->left ) +
sizeof( *classifier->right ) ) +
(classifier->count + 1) * sizeof( *classifier->alpha ) );
classifier->threshold = (float*) (classifier->haar_feature+classifier->count);
classifier->left = (int*) (classifier->threshold + classifier->count);
classifier->right = (int*) (classifier->left + classifier->count);
classifier->alpha = (float*) (classifier->right + classifier->count);
cvStartReadSeq( tree_fn->data.seq, &tree_reader );
for( k = 0, last_idx = 0; k < tree_fn->data.seq->total; ++k )
{
CvFileNode* node_fn;
CvFileNode* feature_fn;
CvFileNode* rects_fn;
CvSeqReader rects_reader;
node_fn = (CvFileNode*) tree_reader.ptr;
if( !CV_NODE_IS_MAP( node_fn->tag ) )
{
sprintf( buf, "Tree node %d is not a valid map. (stage %d, tree %d)",
k, i, j );
CV_Error( CV_StsError, buf );
}
feature_fn = cvGetFileNodeByName( fs, node_fn, ICV_HAAR_FEATURE_NAME );
if( !feature_fn || !CV_NODE_IS_MAP( feature_fn->tag ) )
{
sprintf( buf, "Feature node is not a valid map. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
rects_fn = cvGetFileNodeByName( fs, feature_fn, ICV_HAAR_RECTS_NAME );
if( !rects_fn || !CV_NODE_IS_SEQ( rects_fn->tag )
|| rects_fn->data.seq->total < 1
|| rects_fn->data.seq->total > CV_HAAR_FEATURE_MAX )
{
sprintf( buf, "Rects node is not a valid sequence. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
cvStartReadSeq( rects_fn->data.seq, &rects_reader );
for( l = 0; l < rects_fn->data.seq->total; ++l )
{
CvFileNode* rect_fn;
CvRect r;
rect_fn = (CvFileNode*) rects_reader.ptr;
if( !CV_NODE_IS_SEQ( rect_fn->tag ) || rect_fn->data.seq->total != 5 )
{
sprintf( buf, "Rect %d is not a valid sequence. "
"(stage %d, tree %d, node %d)", l, i, j, k );
CV_Error( CV_StsError, buf );
}
fn = CV_SEQ_ELEM( rect_fn->data.seq, CvFileNode, 0 );
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i < 0 )
{
sprintf( buf, "x coordinate must be non-negative integer. "
"(stage %d, tree %d, node %d, rect %d)", i, j, k, l );
CV_Error( CV_StsError, buf );
}
r.x = fn->data.i;
fn = CV_SEQ_ELEM( rect_fn->data.seq, CvFileNode, 1 );
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i < 0 )
{
sprintf( buf, "y coordinate must be non-negative integer. "
"(stage %d, tree %d, node %d, rect %d)", i, j, k, l );
CV_Error( CV_StsError, buf );
}
r.y = fn->data.i;
fn = CV_SEQ_ELEM( rect_fn->data.seq, CvFileNode, 2 );
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i <= 0
|| r.x + fn->data.i > cascade->orig_window_size.width )
{
sprintf( buf, "width must be positive integer and "
"(x + width) must not exceed window width. "
"(stage %d, tree %d, node %d, rect %d)", i, j, k, l );
CV_Error( CV_StsError, buf );
}
r.width = fn->data.i;
fn = CV_SEQ_ELEM( rect_fn->data.seq, CvFileNode, 3 );
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i <= 0
|| r.y + fn->data.i > cascade->orig_window_size.height )
{
sprintf( buf, "height must be positive integer and "
"(y + height) must not exceed window height. "
"(stage %d, tree %d, node %d, rect %d)", i, j, k, l );
CV_Error( CV_StsError, buf );
}
r.height = fn->data.i;
fn = CV_SEQ_ELEM( rect_fn->data.seq, CvFileNode, 4 );
if( !CV_NODE_IS_REAL( fn->tag ) )
{
sprintf( buf, "weight must be real number. "
"(stage %d, tree %d, node %d, rect %d)", i, j, k, l );
CV_Error( CV_StsError, buf );
}
classifier->haar_feature[k].rect[l].weight = (float) fn->data.f;
classifier->haar_feature[k].rect[l].r = r;
CV_NEXT_SEQ_ELEM( sizeof( *rect_fn ), rects_reader );
} /* for each rect */
for( l = rects_fn->data.seq->total; l < CV_HAAR_FEATURE_MAX; ++l )
{
classifier->haar_feature[k].rect[l].weight = 0;
classifier->haar_feature[k].rect[l].r = cvRect( 0, 0, 0, 0 );
}
fn = cvGetFileNodeByName( fs, feature_fn, ICV_HAAR_TILTED_NAME);
if( !fn || !CV_NODE_IS_INT( fn->tag ) )
{
sprintf( buf, "tilted must be 0 or 1. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
classifier->haar_feature[k].tilted = ( fn->data.i != 0 );
fn = cvGetFileNodeByName( fs, node_fn, ICV_HAAR_THRESHOLD_NAME);
if( !fn || !CV_NODE_IS_REAL( fn->tag ) )
{
sprintf( buf, "threshold must be real number. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
classifier->threshold[k] = (float) fn->data.f;
fn = cvGetFileNodeByName( fs, node_fn, ICV_HAAR_LEFT_NODE_NAME);
if( fn )
{
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i <= k
|| fn->data.i >= tree_fn->data.seq->total )
{
sprintf( buf, "left node must be valid node number. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
/* left node */
classifier->left[k] = fn->data.i;
}
else
{
fn = cvGetFileNodeByName( fs, node_fn, ICV_HAAR_LEFT_VAL_NAME );
if( !fn )
{
sprintf( buf, "left node or left value must be specified. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
if( !CV_NODE_IS_REAL( fn->tag ) )
{
sprintf( buf, "left value must be real number. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
/* left value */
if( last_idx >= classifier->count + 1 )
{
sprintf( buf, "Tree structure is broken: too many values. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
classifier->left[k] = -last_idx;
classifier->alpha[last_idx++] = (float) fn->data.f;
}
fn = cvGetFileNodeByName( fs, node_fn,ICV_HAAR_RIGHT_NODE_NAME);
if( fn )
{
if( !CV_NODE_IS_INT( fn->tag ) || fn->data.i <= k
|| fn->data.i >= tree_fn->data.seq->total )
{
sprintf( buf, "right node must be valid node number. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
/* right node */
classifier->right[k] = fn->data.i;
}
else
{
fn = cvGetFileNodeByName( fs, node_fn, ICV_HAAR_RIGHT_VAL_NAME );
if( !fn )
{
sprintf( buf, "right node or right value must be specified. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
if( !CV_NODE_IS_REAL( fn->tag ) )
{
sprintf( buf, "right value must be real number. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
/* right value */
if( last_idx >= classifier->count + 1 )
{
sprintf( buf, "Tree structure is broken: too many values. "
"(stage %d, tree %d, node %d)", i, j, k );
CV_Error( CV_StsError, buf );
}
classifier->right[k] = -last_idx;
classifier->alpha[last_idx++] = (float) fn->data.f;
}
CV_NEXT_SEQ_ELEM( sizeof( *node_fn ), tree_reader );
} /* for each node */
if( last_idx != classifier->count + 1 )
{
sprintf( buf, "Tree structure is broken: too few values. "
"(stage %d, tree %d)", i, j );
CV_Error( CV_StsError, buf );
}
CV_NEXT_SEQ_ELEM( sizeof( *tree_fn ), trees_reader );
} /* for each tree */
fn = cvGetFileNodeByName( fs, stage_fn, ICV_HAAR_STAGE_THRESHOLD_NAME);
if( !fn || !CV_NODE_IS_REAL( fn->tag ) )
{
sprintf( buf, "stage threshold must be real number. (stage %d)", i );
CV_Error( CV_StsError, buf );
}
cascade->stage_classifier[i].threshold = (float) fn->data.f;
parent = i - 1;
next = -1;
fn = cvGetFileNodeByName( fs, stage_fn, ICV_HAAR_PARENT_NAME );
if( !fn || !CV_NODE_IS_INT( fn->tag )
|| fn->data.i < -1 || fn->data.i >= cascade->count )
{
sprintf( buf, "parent must be integer number. (stage %d)", i );
CV_Error( CV_StsError, buf );
}
parent = fn->data.i;
fn = cvGetFileNodeByName( fs, stage_fn, ICV_HAAR_NEXT_NAME );
if( !fn || !CV_NODE_IS_INT( fn->tag )
|| fn->data.i < -1 || fn->data.i >= cascade->count )
{
sprintf( buf, "next must be integer number. (stage %d)", i );
CV_Error( CV_StsError, buf );
}
next = fn->data.i;
cascade->stage_classifier[i].parent = parent;
cascade->stage_classifier[i].next = next;
cascade->stage_classifier[i].child = -1;
if( parent != -1 && cascade->stage_classifier[parent].child == -1 )
{
cascade->stage_classifier[parent].child = i;
}
CV_NEXT_SEQ_ELEM( sizeof( *stage_fn ), stages_reader );
} /* for each stage */
return cascade;
}
static void
icvWriteHaarClassifier( CvFileStorage* fs, const char* name, const void* struct_ptr,
CvAttrList attributes )
{
int i, j, k, l;
char buf[256];
const CvHaarClassifierCascade* cascade = (const CvHaarClassifierCascade*) struct_ptr;
/* TODO: parameters check */
cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_HAAR, attributes );
cvStartWriteStruct( fs, ICV_HAAR_SIZE_NAME, CV_NODE_SEQ | CV_NODE_FLOW );
cvWriteInt( fs, NULL, cascade->orig_window_size.width );
cvWriteInt( fs, NULL, cascade->orig_window_size.height );
cvEndWriteStruct( fs ); /* size */
cvStartWriteStruct( fs, ICV_HAAR_STAGES_NAME, CV_NODE_SEQ );
for( i = 0; i < cascade->count; ++i )
{
cvStartWriteStruct( fs, NULL, CV_NODE_MAP );
sprintf( buf, "stage %d", i );
cvWriteComment( fs, buf, 1 );
cvStartWriteStruct( fs, ICV_HAAR_TREES_NAME, CV_NODE_SEQ );
for( j = 0; j < cascade->stage_classifier[i].count; ++j )
{
CvHaarClassifier* tree = &cascade->stage_classifier[i].classifier[j];
cvStartWriteStruct( fs, NULL, CV_NODE_SEQ );
sprintf( buf, "tree %d", j );
cvWriteComment( fs, buf, 1 );
for( k = 0; k < tree->count; ++k )
{
CvHaarFeature* feature = &tree->haar_feature[k];
cvStartWriteStruct( fs, NULL, CV_NODE_MAP );
if( k )
{
sprintf( buf, "node %d", k );
}
else
{
sprintf( buf, "root node" );
}
cvWriteComment( fs, buf, 1 );
cvStartWriteStruct( fs, ICV_HAAR_FEATURE_NAME, CV_NODE_MAP );
cvStartWriteStruct( fs, ICV_HAAR_RECTS_NAME, CV_NODE_SEQ );
for( l = 0; l < CV_HAAR_FEATURE_MAX && feature->rect[l].r.width != 0; ++l )
{
cvStartWriteStruct( fs, NULL, CV_NODE_SEQ | CV_NODE_FLOW );
cvWriteInt( fs, NULL, feature->rect[l].r.x );
cvWriteInt( fs, NULL, feature->rect[l].r.y );
cvWriteInt( fs, NULL, feature->rect[l].r.width );
cvWriteInt( fs, NULL, feature->rect[l].r.height );
cvWriteReal( fs, NULL, feature->rect[l].weight );
cvEndWriteStruct( fs ); /* rect */
}
cvEndWriteStruct( fs ); /* rects */
cvWriteInt( fs, ICV_HAAR_TILTED_NAME, feature->tilted );
cvEndWriteStruct( fs ); /* feature */
cvWriteReal( fs, ICV_HAAR_THRESHOLD_NAME, tree->threshold[k]);
if( tree->left[k] > 0 )
{
cvWriteInt( fs, ICV_HAAR_LEFT_NODE_NAME, tree->left[k] );
}
else
{
cvWriteReal( fs, ICV_HAAR_LEFT_VAL_NAME,
tree->alpha[-tree->left[k]] );
}
if( tree->right[k] > 0 )
{
cvWriteInt( fs, ICV_HAAR_RIGHT_NODE_NAME, tree->right[k] );
}
else
{
cvWriteReal( fs, ICV_HAAR_RIGHT_VAL_NAME,
tree->alpha[-tree->right[k]] );
}
cvEndWriteStruct( fs ); /* split */
}
cvEndWriteStruct( fs ); /* tree */
}
cvEndWriteStruct( fs ); /* trees */
cvWriteReal( fs, ICV_HAAR_STAGE_THRESHOLD_NAME, cascade->stage_classifier[i].threshold);
cvWriteInt( fs, ICV_HAAR_PARENT_NAME, cascade->stage_classifier[i].parent );
cvWriteInt( fs, ICV_HAAR_NEXT_NAME, cascade->stage_classifier[i].next );
cvEndWriteStruct( fs ); /* stage */
} /* for each stage */
cvEndWriteStruct( fs ); /* stages */
cvEndWriteStruct( fs ); /* root */
}
static void*
icvCloneHaarClassifier( const void* struct_ptr )
{
CvHaarClassifierCascade* cascade = NULL;
int i, j, k, n;
const CvHaarClassifierCascade* cascade_src =
(const CvHaarClassifierCascade*) struct_ptr;
n = cascade_src->count;
cascade = icvCreateHaarClassifierCascade(n);
cascade->orig_window_size = cascade_src->orig_window_size;
for( i = 0; i < n; ++i )
{
cascade->stage_classifier[i].parent = cascade_src->stage_classifier[i].parent;
cascade->stage_classifier[i].next = cascade_src->stage_classifier[i].next;
cascade->stage_classifier[i].child = cascade_src->stage_classifier[i].child;
cascade->stage_classifier[i].threshold = cascade_src->stage_classifier[i].threshold;
cascade->stage_classifier[i].count = 0;
cascade->stage_classifier[i].classifier =
(CvHaarClassifier*) cvAlloc( cascade_src->stage_classifier[i].count
* sizeof( cascade->stage_classifier[i].classifier[0] ) );
cascade->stage_classifier[i].count = cascade_src->stage_classifier[i].count;
for( j = 0; j < cascade->stage_classifier[i].count; ++j )
cascade->stage_classifier[i].classifier[j].haar_feature = NULL;
for( j = 0; j < cascade->stage_classifier[i].count; ++j )
{
const CvHaarClassifier* classifier_src =
&cascade_src->stage_classifier[i].classifier[j];
CvHaarClassifier* classifier =
&cascade->stage_classifier[i].classifier[j];
classifier->count = classifier_src->count;
classifier->haar_feature = (CvHaarFeature*) cvAlloc(
classifier->count * ( sizeof( *classifier->haar_feature ) +
sizeof( *classifier->threshold ) +
sizeof( *classifier->left ) +
sizeof( *classifier->right ) ) +
(classifier->count + 1) * sizeof( *classifier->alpha ) );
classifier->threshold = (float*) (classifier->haar_feature+classifier->count);
classifier->left = (int*) (classifier->threshold + classifier->count);
classifier->right = (int*) (classifier->left + classifier->count);
classifier->alpha = (float*) (classifier->right + classifier->count);
for( k = 0; k < classifier->count; ++k )
{
classifier->haar_feature[k] = classifier_src->haar_feature[k];
classifier->threshold[k] = classifier_src->threshold[k];
classifier->left[k] = classifier_src->left[k];
classifier->right[k] = classifier_src->right[k];
classifier->alpha[k] = classifier_src->alpha[k];
}
classifier->alpha[classifier->count] =
classifier_src->alpha[classifier->count];
}
}
return cascade;
}
CvType haar_type( CV_TYPE_NAME_HAAR, icvIsHaarClassifier,
(CvReleaseFunc)cvReleaseHaarClassifierCascade,
icvReadHaarClassifier, icvWriteHaarClassifier,
icvCloneHaarClassifier );
/* End of file. */
| 109,583 | 34,907 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// -*- c++ -*-
#include <faiss/utils/distances.h>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <faiss/impl/FaissAssert.h>
#include <faiss/impl/platform_macros.h>
#include <faiss/utils/simdlib.h>
#ifdef __SSE3__
#include <immintrin.h>
#endif
#ifdef __aarch64__
#include <arm_neon.h>
#endif
namespace faiss {
#ifdef __AVX__
#define USE_AVX
#endif
/*********************************************************
* Optimized distance computations
*********************************************************/
/* Functions to compute:
- L2 distance between 2 vectors
- inner product between 2 vectors
- L2 norm of a vector
The functions should probably not be invoked when a large number of
vectors are be processed in batch (in which case Matrix multiply
is faster), but may be useful for comparing vectors isolated in
memory.
Works with any vectors of any dimension, even unaligned (in which
case they are slower).
*/
/*********************************************************
* Reference implementations
*/
float fvec_L2sqr_ref(const float* x, const float* y, size_t d) {
size_t i;
float res = 0;
for (i = 0; i < d; i++) {
const float tmp = x[i] - y[i];
res += tmp * tmp;
}
return res;
}
float fvec_L1_ref(const float* x, const float* y, size_t d) {
size_t i;
float res = 0;
for (i = 0; i < d; i++) {
const float tmp = x[i] - y[i];
res += fabs(tmp);
}
return res;
}
float fvec_Linf_ref(const float* x, const float* y, size_t d) {
size_t i;
float res = 0;
for (i = 0; i < d; i++) {
res = fmax(res, fabs(x[i] - y[i]));
}
return res;
}
float fvec_inner_product_ref(const float* x, const float* y, size_t d) {
size_t i;
float res = 0;
for (i = 0; i < d; i++)
res += x[i] * y[i];
return res;
}
float fvec_norm_L2sqr_ref(const float* x, size_t d) {
size_t i;
double res = 0;
for (i = 0; i < d; i++)
res += x[i] * x[i];
return res;
}
void fvec_L2sqr_ny_ref(
float* dis,
const float* x,
const float* y,
size_t d,
size_t ny) {
for (size_t i = 0; i < ny; i++) {
dis[i] = fvec_L2sqr(x, y, d);
y += d;
}
}
void fvec_inner_products_ny_ref(
float* ip,
const float* x,
const float* y,
size_t d,
size_t ny) {
// BLAS slower for the use cases here
#if 0
{
FINTEGER di = d;
FINTEGER nyi = ny;
float one = 1.0, zero = 0.0;
FINTEGER onei = 1;
sgemv_ ("T", &di, &nyi, &one, y, &di, x, &onei, &zero, ip, &onei);
}
#endif
for (size_t i = 0; i < ny; i++) {
ip[i] = fvec_inner_product(x, y, d);
y += d;
}
}
/*********************************************************
* SSE and AVX implementations
*/
#ifdef __SSE3__
// reads 0 <= d < 4 floats as __m128
static inline __m128 masked_read(int d, const float* x) {
assert(0 <= d && d < 4);
ALIGNED(16) float buf[4] = {0, 0, 0, 0};
switch (d) {
case 3:
buf[2] = x[2];
case 2:
buf[1] = x[1];
case 1:
buf[0] = x[0];
}
return _mm_load_ps(buf);
// cannot use AVX2 _mm_mask_set1_epi32
}
float fvec_norm_L2sqr(const float* x, size_t d) {
__m128 mx;
__m128 msum1 = _mm_setzero_ps();
while (d >= 4) {
mx = _mm_loadu_ps(x);
x += 4;
msum1 = _mm_add_ps(msum1, _mm_mul_ps(mx, mx));
d -= 4;
}
mx = masked_read(d, x);
msum1 = _mm_add_ps(msum1, _mm_mul_ps(mx, mx));
msum1 = _mm_hadd_ps(msum1, msum1);
msum1 = _mm_hadd_ps(msum1, msum1);
return _mm_cvtss_f32(msum1);
}
namespace {
/// Function that does a component-wise operation between x and y
/// to compute L2 distances. ElementOp can then be used in the fvec_op_ny
/// functions below
struct ElementOpL2 {
static float op(float x, float y) {
float tmp = x - y;
return tmp * tmp;
}
static __m128 op(__m128 x, __m128 y) {
__m128 tmp = _mm_sub_ps(x, y);
return _mm_mul_ps(tmp, tmp);
}
};
/// Function that does a component-wise operation between x and y
/// to compute inner products
struct ElementOpIP {
static float op(float x, float y) {
return x * y;
}
static __m128 op(__m128 x, __m128 y) {
return _mm_mul_ps(x, y);
}
};
template <class ElementOp>
void fvec_op_ny_D1(float* dis, const float* x, const float* y, size_t ny) {
float x0s = x[0];
__m128 x0 = _mm_set_ps(x0s, x0s, x0s, x0s);
size_t i;
for (i = 0; i + 3 < ny; i += 4) {
__m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
y += 4;
dis[i] = _mm_cvtss_f32(accu);
__m128 tmp = _mm_shuffle_ps(accu, accu, 1);
dis[i + 1] = _mm_cvtss_f32(tmp);
tmp = _mm_shuffle_ps(accu, accu, 2);
dis[i + 2] = _mm_cvtss_f32(tmp);
tmp = _mm_shuffle_ps(accu, accu, 3);
dis[i + 3] = _mm_cvtss_f32(tmp);
}
while (i < ny) { // handle non-multiple-of-4 case
dis[i++] = ElementOp::op(x0s, *y++);
}
}
template <class ElementOp>
void fvec_op_ny_D2(float* dis, const float* x, const float* y, size_t ny) {
__m128 x0 = _mm_set_ps(x[1], x[0], x[1], x[0]);
size_t i;
for (i = 0; i + 1 < ny; i += 2) {
__m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
y += 4;
accu = _mm_hadd_ps(accu, accu);
dis[i] = _mm_cvtss_f32(accu);
accu = _mm_shuffle_ps(accu, accu, 3);
dis[i + 1] = _mm_cvtss_f32(accu);
}
if (i < ny) { // handle odd case
dis[i] = ElementOp::op(x[0], y[0]) + ElementOp::op(x[1], y[1]);
}
}
template <class ElementOp>
void fvec_op_ny_D4(float* dis, const float* x, const float* y, size_t ny) {
__m128 x0 = _mm_loadu_ps(x);
for (size_t i = 0; i < ny; i++) {
__m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
y += 4;
accu = _mm_hadd_ps(accu, accu);
accu = _mm_hadd_ps(accu, accu);
dis[i] = _mm_cvtss_f32(accu);
}
}
template <class ElementOp>
void fvec_op_ny_D8(float* dis, const float* x, const float* y, size_t ny) {
__m128 x0 = _mm_loadu_ps(x);
__m128 x1 = _mm_loadu_ps(x + 4);
for (size_t i = 0; i < ny; i++) {
__m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
y += 4;
accu = _mm_add_ps(accu, ElementOp::op(x1, _mm_loadu_ps(y)));
y += 4;
accu = _mm_hadd_ps(accu, accu);
accu = _mm_hadd_ps(accu, accu);
dis[i] = _mm_cvtss_f32(accu);
}
}
template <class ElementOp>
void fvec_op_ny_D12(float* dis, const float* x, const float* y, size_t ny) {
__m128 x0 = _mm_loadu_ps(x);
__m128 x1 = _mm_loadu_ps(x + 4);
__m128 x2 = _mm_loadu_ps(x + 8);
for (size_t i = 0; i < ny; i++) {
__m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
y += 4;
accu = _mm_add_ps(accu, ElementOp::op(x1, _mm_loadu_ps(y)));
y += 4;
accu = _mm_add_ps(accu, ElementOp::op(x2, _mm_loadu_ps(y)));
y += 4;
accu = _mm_hadd_ps(accu, accu);
accu = _mm_hadd_ps(accu, accu);
dis[i] = _mm_cvtss_f32(accu);
}
}
} // anonymous namespace
void fvec_L2sqr_ny(
float* dis,
const float* x,
const float* y,
size_t d,
size_t ny) {
// optimized for a few special cases
#define DISPATCH(dval) \
case dval: \
fvec_op_ny_D##dval<ElementOpL2>(dis, x, y, ny); \
return;
switch (d) {
DISPATCH(1)
DISPATCH(2)
DISPATCH(4)
DISPATCH(8)
DISPATCH(12)
default:
fvec_L2sqr_ny_ref(dis, x, y, d, ny);
return;
}
#undef DISPATCH
}
void fvec_inner_products_ny(
float* dis,
const float* x,
const float* y,
size_t d,
size_t ny) {
#define DISPATCH(dval) \
case dval: \
fvec_op_ny_D##dval<ElementOpIP>(dis, x, y, ny); \
return;
switch (d) {
DISPATCH(1)
DISPATCH(2)
DISPATCH(4)
DISPATCH(8)
DISPATCH(12)
default:
fvec_inner_products_ny_ref(dis, x, y, d, ny);
return;
}
#undef DISPATCH
}
#endif
#ifdef USE_AVX
// reads 0 <= d < 8 floats as __m256
static inline __m256 masked_read_8(int d, const float* x) {
assert(0 <= d && d < 8);
if (d < 4) {
__m256 res = _mm256_setzero_ps();
res = _mm256_insertf128_ps(res, masked_read(d, x), 0);
return res;
} else {
__m256 res = _mm256_setzero_ps();
res = _mm256_insertf128_ps(res, _mm_loadu_ps(x), 0);
res = _mm256_insertf128_ps(res, masked_read(d - 4, x + 4), 1);
return res;
}
}
float fvec_inner_product(const float* x, const float* y, size_t d) {
__m256 msum1 = _mm256_setzero_ps();
while (d >= 8) {
__m256 mx = _mm256_loadu_ps(x);
x += 8;
__m256 my = _mm256_loadu_ps(y);
y += 8;
msum1 = _mm256_add_ps(msum1, _mm256_mul_ps(mx, my));
d -= 8;
}
__m128 msum2 = _mm256_extractf128_ps(msum1, 1);
msum2 = _mm_add_ps(msum2, _mm256_extractf128_ps(msum1, 0));
if (d >= 4) {
__m128 mx = _mm_loadu_ps(x);
x += 4;
__m128 my = _mm_loadu_ps(y);
y += 4;
msum2 = _mm_add_ps(msum2, _mm_mul_ps(mx, my));
d -= 4;
}
if (d > 0) {
__m128 mx = masked_read(d, x);
__m128 my = masked_read(d, y);
msum2 = _mm_add_ps(msum2, _mm_mul_ps(mx, my));
}
msum2 = _mm_hadd_ps(msum2, msum2);
msum2 = _mm_hadd_ps(msum2, msum2);
return _mm_cvtss_f32(msum2);
}
float fvec_L2sqr(const float* x, const float* y, size_t d) {
__m256 msum1 = _mm256_setzero_ps();
while (d >= 8) {
__m256 mx = _mm256_loadu_ps(x);
x += 8;
__m256 my = _mm256_loadu_ps(y);
y += 8;
const __m256 a_m_b1 = _mm256_sub_ps(mx, my);
msum1 = _mm256_add_ps(msum1, _mm256_mul_ps(a_m_b1, a_m_b1));
d -= 8;
}
__m128 msum2 = _mm256_extractf128_ps(msum1, 1);
msum2 = _mm_add_ps(msum2, _mm256_extractf128_ps(msum1, 0));
if (d >= 4) {
__m128 mx = _mm_loadu_ps(x);
x += 4;
__m128 my = _mm_loadu_ps(y);
y += 4;
const __m128 a_m_b1 = _mm_sub_ps(mx, my);
msum2 = _mm_add_ps(msum2, _mm_mul_ps(a_m_b1, a_m_b1));
d -= 4;
}
if (d > 0) {
__m128 mx = masked_read(d, x);
__m128 my = masked_read(d, y);
__m128 a_m_b1 = _mm_sub_ps(mx, my);
msum2 = _mm_add_ps(msum2, _mm_mul_ps(a_m_b1, a_m_b1));
}
msum2 = _mm_hadd_ps(msum2, msum2);
msum2 = _mm_hadd_ps(msum2, msum2);
return _mm_cvtss_f32(msum2);
}
float fvec_L1(const float* x, const float* y, size_t d) {
__m256 msum1 = _mm256_setzero_ps();
__m256 signmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffffUL));
while (d >= 8) {
__m256 mx = _mm256_loadu_ps(x);
x += 8;
__m256 my = _mm256_loadu_ps(y);
y += 8;
const __m256 a_m_b = _mm256_sub_ps(mx, my);
msum1 = _mm256_add_ps(msum1, _mm256_and_ps(signmask, a_m_b));
d -= 8;
}
__m128 msum2 = _mm256_extractf128_ps(msum1, 1);
msum2 = _mm_add_ps(msum2, _mm256_extractf128_ps(msum1, 0));
__m128 signmask2 = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffUL));
if (d >= 4) {
__m128 mx = _mm_loadu_ps(x);
x += 4;
__m128 my = _mm_loadu_ps(y);
y += 4;
const __m128 a_m_b = _mm_sub_ps(mx, my);
msum2 = _mm_add_ps(msum2, _mm_and_ps(signmask2, a_m_b));
d -= 4;
}
if (d > 0) {
__m128 mx = masked_read(d, x);
__m128 my = masked_read(d, y);
__m128 a_m_b = _mm_sub_ps(mx, my);
msum2 = _mm_add_ps(msum2, _mm_and_ps(signmask2, a_m_b));
}
msum2 = _mm_hadd_ps(msum2, msum2);
msum2 = _mm_hadd_ps(msum2, msum2);
return _mm_cvtss_f32(msum2);
}
float fvec_Linf(const float* x, const float* y, size_t d) {
__m256 msum1 = _mm256_setzero_ps();
__m256 signmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffffUL));
while (d >= 8) {
__m256 mx = _mm256_loadu_ps(x);
x += 8;
__m256 my = _mm256_loadu_ps(y);
y += 8;
const __m256 a_m_b = _mm256_sub_ps(mx, my);
msum1 = _mm256_max_ps(msum1, _mm256_and_ps(signmask, a_m_b));
d -= 8;
}
__m128 msum2 = _mm256_extractf128_ps(msum1, 1);
msum2 = _mm_max_ps(msum2, _mm256_extractf128_ps(msum1, 0));
__m128 signmask2 = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffUL));
if (d >= 4) {
__m128 mx = _mm_loadu_ps(x);
x += 4;
__m128 my = _mm_loadu_ps(y);
y += 4;
const __m128 a_m_b = _mm_sub_ps(mx, my);
msum2 = _mm_max_ps(msum2, _mm_and_ps(signmask2, a_m_b));
d -= 4;
}
if (d > 0) {
__m128 mx = masked_read(d, x);
__m128 my = masked_read(d, y);
__m128 a_m_b = _mm_sub_ps(mx, my);
msum2 = _mm_max_ps(msum2, _mm_and_ps(signmask2, a_m_b));
}
msum2 = _mm_max_ps(_mm_movehl_ps(msum2, msum2), msum2);
msum2 = _mm_max_ps(msum2, _mm_shuffle_ps(msum2, msum2, 1));
return _mm_cvtss_f32(msum2);
}
#elif defined(__SSE3__) // But not AVX
float fvec_L1(const float* x, const float* y, size_t d) {
return fvec_L1_ref(x, y, d);
}
float fvec_Linf(const float* x, const float* y, size_t d) {
return fvec_Linf_ref(x, y, d);
}
float fvec_L2sqr(const float* x, const float* y, size_t d) {
__m128 msum1 = _mm_setzero_ps();
while (d >= 4) {
__m128 mx = _mm_loadu_ps(x);
x += 4;
__m128 my = _mm_loadu_ps(y);
y += 4;
const __m128 a_m_b1 = _mm_sub_ps(mx, my);
msum1 = _mm_add_ps(msum1, _mm_mul_ps(a_m_b1, a_m_b1));
d -= 4;
}
if (d > 0) {
// add the last 1, 2 or 3 values
__m128 mx = masked_read(d, x);
__m128 my = masked_read(d, y);
__m128 a_m_b1 = _mm_sub_ps(mx, my);
msum1 = _mm_add_ps(msum1, _mm_mul_ps(a_m_b1, a_m_b1));
}
msum1 = _mm_hadd_ps(msum1, msum1);
msum1 = _mm_hadd_ps(msum1, msum1);
return _mm_cvtss_f32(msum1);
}
float fvec_inner_product(const float* x, const float* y, size_t d) {
__m128 mx, my;
__m128 msum1 = _mm_setzero_ps();
while (d >= 4) {
mx = _mm_loadu_ps(x);
x += 4;
my = _mm_loadu_ps(y);
y += 4;
msum1 = _mm_add_ps(msum1, _mm_mul_ps(mx, my));
d -= 4;
}
// add the last 1, 2, or 3 values
mx = masked_read(d, x);
my = masked_read(d, y);
__m128 prod = _mm_mul_ps(mx, my);
msum1 = _mm_add_ps(msum1, prod);
msum1 = _mm_hadd_ps(msum1, msum1);
msum1 = _mm_hadd_ps(msum1, msum1);
return _mm_cvtss_f32(msum1);
}
#elif defined(__aarch64__)
float fvec_L2sqr(const float* x, const float* y, size_t d) {
if (d & 3)
return fvec_L2sqr_ref(x, y, d);
float32x4_t accu = vdupq_n_f32(0);
for (size_t i = 0; i < d; i += 4) {
float32x4_t xi = vld1q_f32(x + i);
float32x4_t yi = vld1q_f32(y + i);
float32x4_t sq = vsubq_f32(xi, yi);
accu = vfmaq_f32(accu, sq, sq);
}
float32x4_t a2 = vpaddq_f32(accu, accu);
return vdups_laneq_f32(a2, 0) + vdups_laneq_f32(a2, 1);
}
float fvec_inner_product(const float* x, const float* y, size_t d) {
if (d & 3)
return fvec_inner_product_ref(x, y, d);
float32x4_t accu = vdupq_n_f32(0);
for (size_t i = 0; i < d; i += 4) {
float32x4_t xi = vld1q_f32(x + i);
float32x4_t yi = vld1q_f32(y + i);
accu = vfmaq_f32(accu, xi, yi);
}
float32x4_t a2 = vpaddq_f32(accu, accu);
return vdups_laneq_f32(a2, 0) + vdups_laneq_f32(a2, 1);
}
float fvec_norm_L2sqr(const float* x, size_t d) {
if (d & 3)
return fvec_norm_L2sqr_ref(x, d);
float32x4_t accu = vdupq_n_f32(0);
for (size_t i = 0; i < d; i += 4) {
float32x4_t xi = vld1q_f32(x + i);
accu = vfmaq_f32(accu, xi, xi);
}
float32x4_t a2 = vpaddq_f32(accu, accu);
return vdups_laneq_f32(a2, 0) + vdups_laneq_f32(a2, 1);
}
// not optimized for ARM
void fvec_L2sqr_ny(
float* dis,
const float* x,
const float* y,
size_t d,
size_t ny) {
fvec_L2sqr_ny_ref(dis, x, y, d, ny);
}
float fvec_L1(const float* x, const float* y, size_t d) {
return fvec_L1_ref(x, y, d);
}
float fvec_Linf(const float* x, const float* y, size_t d) {
return fvec_Linf_ref(x, y, d);
}
void fvec_inner_products_ny(
float* dis,
const float* x,
const float* y,
size_t d,
size_t ny) {
fvec_inner_products_ny_ref(dis, x, y, d, ny);
}
#else
// scalar implementation
float fvec_L2sqr(const float* x, const float* y, size_t d) {
return fvec_L2sqr_ref(x, y, d);
}
float fvec_L1(const float* x, const float* y, size_t d) {
return fvec_L1_ref(x, y, d);
}
float fvec_Linf(const float* x, const float* y, size_t d) {
return fvec_Linf_ref(x, y, d);
}
float fvec_inner_product(const float* x, const float* y, size_t d) {
return fvec_inner_product_ref(x, y, d);
}
float fvec_norm_L2sqr(const float* x, size_t d) {
return fvec_norm_L2sqr_ref(x, d);
}
void fvec_L2sqr_ny(
float* dis,
const float* x,
const float* y,
size_t d,
size_t ny) {
fvec_L2sqr_ny_ref(dis, x, y, d, ny);
}
void fvec_inner_products_ny(
float* dis,
const float* x,
const float* y,
size_t d,
size_t ny) {
fvec_inner_products_ny_ref(dis, x, y, d, ny);
}
#endif
/***************************************************************************
* heavily optimized table computations
***************************************************************************/
static inline void fvec_madd_ref(
size_t n,
const float* a,
float bf,
const float* b,
float* c) {
for (size_t i = 0; i < n; i++)
c[i] = a[i] + bf * b[i];
}
#ifdef __SSE3__
static inline void fvec_madd_sse(
size_t n,
const float* a,
float bf,
const float* b,
float* c) {
n >>= 2;
__m128 bf4 = _mm_set_ps1(bf);
__m128* a4 = (__m128*)a;
__m128* b4 = (__m128*)b;
__m128* c4 = (__m128*)c;
while (n--) {
*c4 = _mm_add_ps(*a4, _mm_mul_ps(bf4, *b4));
b4++;
a4++;
c4++;
}
}
void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c) {
if ((n & 3) == 0 && ((((long)a) | ((long)b) | ((long)c)) & 15) == 0)
fvec_madd_sse(n, a, bf, b, c);
else
fvec_madd_ref(n, a, bf, b, c);
}
#else
void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c) {
fvec_madd_ref(n, a, bf, b, c);
}
#endif
static inline int fvec_madd_and_argmin_ref(
size_t n,
const float* a,
float bf,
const float* b,
float* c) {
float vmin = 1e20;
int imin = -1;
for (size_t i = 0; i < n; i++) {
c[i] = a[i] + bf * b[i];
if (c[i] < vmin) {
vmin = c[i];
imin = i;
}
}
return imin;
}
#ifdef __SSE3__
static inline int fvec_madd_and_argmin_sse(
size_t n,
const float* a,
float bf,
const float* b,
float* c) {
n >>= 2;
__m128 bf4 = _mm_set_ps1(bf);
__m128 vmin4 = _mm_set_ps1(1e20);
__m128i imin4 = _mm_set1_epi32(-1);
__m128i idx4 = _mm_set_epi32(3, 2, 1, 0);
__m128i inc4 = _mm_set1_epi32(4);
__m128* a4 = (__m128*)a;
__m128* b4 = (__m128*)b;
__m128* c4 = (__m128*)c;
while (n--) {
__m128 vc4 = _mm_add_ps(*a4, _mm_mul_ps(bf4, *b4));
*c4 = vc4;
__m128i mask = _mm_castps_si128(_mm_cmpgt_ps(vmin4, vc4));
// imin4 = _mm_blendv_epi8 (imin4, idx4, mask); // slower!
imin4 = _mm_or_si128(
_mm_and_si128(mask, idx4), _mm_andnot_si128(mask, imin4));
vmin4 = _mm_min_ps(vmin4, vc4);
b4++;
a4++;
c4++;
idx4 = _mm_add_epi32(idx4, inc4);
}
// 4 values -> 2
{
idx4 = _mm_shuffle_epi32(imin4, 3 << 2 | 2);
__m128 vc4 = _mm_shuffle_ps(vmin4, vmin4, 3 << 2 | 2);
__m128i mask = _mm_castps_si128(_mm_cmpgt_ps(vmin4, vc4));
imin4 = _mm_or_si128(
_mm_and_si128(mask, idx4), _mm_andnot_si128(mask, imin4));
vmin4 = _mm_min_ps(vmin4, vc4);
}
// 2 values -> 1
{
idx4 = _mm_shuffle_epi32(imin4, 1);
__m128 vc4 = _mm_shuffle_ps(vmin4, vmin4, 1);
__m128i mask = _mm_castps_si128(_mm_cmpgt_ps(vmin4, vc4));
imin4 = _mm_or_si128(
_mm_and_si128(mask, idx4), _mm_andnot_si128(mask, imin4));
// vmin4 = _mm_min_ps (vmin4, vc4);
}
return _mm_cvtsi128_si32(imin4);
}
int fvec_madd_and_argmin(
size_t n,
const float* a,
float bf,
const float* b,
float* c) {
if ((n & 3) == 0 && ((((long)a) | ((long)b) | ((long)c)) & 15) == 0)
return fvec_madd_and_argmin_sse(n, a, bf, b, c);
else
return fvec_madd_and_argmin_ref(n, a, bf, b, c);
}
#else
int fvec_madd_and_argmin(
size_t n,
const float* a,
float bf,
const float* b,
float* c) {
return fvec_madd_and_argmin_ref(n, a, bf, b, c);
}
#endif
/***************************************************************************
* PQ tables computations
***************************************************************************/
namespace {
/// compute the IP for dsub = 2 for 8 centroids and 4 sub-vectors at a time
template <bool is_inner_product>
void pq2_8cents_table(
const simd8float32 centroids[8],
const simd8float32 x,
float* out,
size_t ldo,
size_t nout = 4) {
simd8float32 ips[4];
for (int i = 0; i < 4; i++) {
simd8float32 p1, p2;
if (is_inner_product) {
p1 = x * centroids[2 * i];
p2 = x * centroids[2 * i + 1];
} else {
p1 = (x - centroids[2 * i]);
p1 = p1 * p1;
p2 = (x - centroids[2 * i + 1]);
p2 = p2 * p2;
}
ips[i] = hadd(p1, p2);
}
simd8float32 ip02a = geteven(ips[0], ips[1]);
simd8float32 ip02b = geteven(ips[2], ips[3]);
simd8float32 ip0 = getlow128(ip02a, ip02b);
simd8float32 ip2 = gethigh128(ip02a, ip02b);
simd8float32 ip13a = getodd(ips[0], ips[1]);
simd8float32 ip13b = getodd(ips[2], ips[3]);
simd8float32 ip1 = getlow128(ip13a, ip13b);
simd8float32 ip3 = gethigh128(ip13a, ip13b);
switch (nout) {
case 4:
ip3.storeu(out + 3 * ldo);
case 3:
ip2.storeu(out + 2 * ldo);
case 2:
ip1.storeu(out + 1 * ldo);
case 1:
ip0.storeu(out);
}
}
simd8float32 load_simd8float32_partial(const float* x, int n) {
ALIGNED(32) float tmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
float* wp = tmp;
for (int i = 0; i < n; i++) {
*wp++ = *x++;
}
return simd8float32(tmp);
}
} // anonymous namespace
void compute_PQ_dis_tables_dsub2(
size_t d,
size_t ksub,
const float* all_centroids,
size_t nx,
const float* x,
bool is_inner_product,
float* dis_tables) {
size_t M = d / 2;
FAISS_THROW_IF_NOT(ksub % 8 == 0);
for (size_t m0 = 0; m0 < M; m0 += 4) {
int m1 = std::min(M, m0 + 4);
for (int k0 = 0; k0 < ksub; k0 += 8) {
simd8float32 centroids[8];
for (int k = 0; k < 8; k++) {
ALIGNED(32) float centroid[8];
size_t wp = 0;
size_t rp = (m0 * ksub + k + k0) * 2;
for (int m = m0; m < m1; m++) {
centroid[wp++] = all_centroids[rp];
centroid[wp++] = all_centroids[rp + 1];
rp += 2 * ksub;
}
centroids[k] = simd8float32(centroid);
}
for (size_t i = 0; i < nx; i++) {
simd8float32 xi;
if (m1 == m0 + 4) {
xi.loadu(x + i * d + m0 * 2);
} else {
xi = load_simd8float32_partial(
x + i * d + m0 * 2, 2 * (m1 - m0));
}
if (is_inner_product) {
pq2_8cents_table<true>(
centroids,
xi,
dis_tables + (i * M + m0) * ksub + k0,
ksub,
m1 - m0);
} else {
pq2_8cents_table<false>(
centroids,
xi,
dis_tables + (i * M + m0) * ksub + k0,
ksub,
m1 - m0);
}
}
}
}
}
} // namespace faiss
| 25,380 | 11,499 |
/*
* expr/detail/driver.cpp
* solver
*
* Created by Alexandre Martin on 03/02/2016.
* Copyright © 2016 scalexm. All rights reserved.
*
*/
#include "driver.hpp"
#include <sstream>
namespace expr { namespace detail {
result<generic_expr> driver::parse(const std::string & str) {
begin_scan(str);
parser p(*this);
p.parse();
return std::move(m_root);
}
/*
if an error occurs, we want to use the string part of expr_result
as a return value for parse()
*/
void driver::error(const location & l, const std::string & m) {
std::ostringstream ss;
ss << l << ": " << m;
m_root = result<generic_expr> { ss.str() };
}
} } | 720 | 241 |
//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
#include "ac/common.h"
#include "ac/view.h"
#include "ac/audiochannel.h"
#include "ac/character.h"
#include "ac/charactercache.h"
#include "ac/characterextras.h"
#include "ac/dialogtopic.h"
#include "ac/draw.h"
#include "ac/dynamicsprite.h"
#include "ac/event.h"
#include "ac/game.h"
#include "ac/gamesetup.h"
#include "ac/gamesetupstruct.h"
#include "ac/gamestate.h"
#include "ac/global_audio.h"
#include "ac/global_character.h"
#include "ac/global_display.h"
#include "ac/global_game.h"
#include "ac/global_gui.h"
#include "ac/global_object.h"
#include "ac/global_translation.h"
#include "ac/gui.h"
#include "ac/hotspot.h"
#include "ac/lipsync.h"
#include "ac/mouse.h"
#include "ac/movelist.h"
#include "ac/objectcache.h"
#include "ac/overlay.h"
#include "ac/path_helper.h"
#include "ac/record.h"
#include "ac/region.h"
#include "ac/richgamemedia.h"
#include "ac/room.h"
#include "ac/roomobject.h"
#include "ac/roomstatus.h"
#include "ac/runtime_defines.h"
#include "ac/screenoverlay.h"
#include "ac/spritecache.h"
#include "ac/string.h"
#include "ac/system.h"
#include "ac/timer.h"
#include "ac/translation.h"
#include "ac/dynobj/all_dynamicclasses.h"
#include "ac/dynobj/all_scriptclasses.h"
#include "ac/dynobj/cc_audiochannel.h"
#include "ac/dynobj/cc_audioclip.h"
#include "ac/statobj/staticgame.h"
#include "debug/debug_log.h"
#include "debug/out.h"
#include "device/mousew32.h"
#include "font/fonts.h"
#include "game/savegame.h"
#include "game/savegame_internal.h"
#include "gui/animatingguibutton.h"
#include "gfx/graphicsdriver.h"
#include "gfx/gfxfilter.h"
#include "gui/guidialog.h"
#include "main/graphics_mode.h"
#include "main/main.h"
#include "media/audio/audio.h"
#include "media/audio/soundclip.h"
#include "plugin/agsplugin.h"
#include "plugin/plugin_engine.h"
#include "script/cc_error.h"
#include "script/runtimescriptvalue.h"
#include "script/script.h"
#include "script/script_runtime.h"
#include "util/alignedstream.h"
#include "util/directory.h"
#include "util/filestream.h" // TODO: needed only because plugins expect file handle
#include "util/path.h"
#include "util/string_utils.h"
using namespace AGS::Common;
using namespace AGS::Engine;
extern ScriptAudioChannel scrAudioChannel[MAX_SOUND_CHANNELS + 1];
extern int time_between_timers;
extern Bitmap *virtual_screen;
extern int cur_mode,cur_cursor;
extern SpeechLipSyncLine *splipsync;
extern int numLipLines, curLipLine, curLipLinePhoneme;
extern CharacterExtras *charextra;
extern DialogTopic *dialog;
extern int ifacepopped; // currently displayed pop-up GUI (-1 if none)
extern int mouse_on_iface; // mouse cursor is over this interface
extern int mouse_ifacebut_xoffs,mouse_ifacebut_yoffs;
extern AnimatingGUIButton animbuts[MAX_ANIMATING_BUTTONS];
extern int numAnimButs;
extern ScreenOverlay screenover[MAX_SCREEN_OVERLAYS];
extern int numscreenover;
extern int is_complete_overlay,is_text_overlay;
#if defined(IOS_VERSION) || defined(ANDROID_VERSION)
extern int psp_gfx_renderer;
#endif
extern int obj_lowest_yp, char_lowest_yp;
extern int actSpsCount;
extern Bitmap **actsps;
extern IDriverDependantBitmap* *actspsbmp;
// temporary cache of walk-behind for this actsps image
extern Bitmap **actspswb;
extern IDriverDependantBitmap* *actspswbbmp;
extern CachedActSpsData* actspswbcache;
extern Bitmap **guibg;
extern IDriverDependantBitmap **guibgbmp;
extern char transFileName[MAX_PATH];
extern color palette[256];
extern int offsetx,offsety;
extern unsigned int loopcounter;
extern Bitmap *raw_saved_screen;
extern Bitmap *dynamicallyCreatedSurfaces[MAX_DYNAMIC_SURFACES];
extern IGraphicsDriver *gfxDriver;
//=============================================================================
GameState play;
GameSetup usetup;
GameSetupStruct game;
RoomStatus troom; // used for non-saveable rooms, eg. intro
RoomObject*objs;
RoomStatus*croom=NULL;
RoomStruct thisroom;
volatile int switching_away_from_game = 0;
volatile bool switched_away = false;
volatile char want_exit = 0, abort_engine = 0;
GameDataVersion loaded_game_file_version = kGameVersion_Undefined;
int frames_per_second=40;
int displayed_room=-10,starting_room = -1;
int in_new_room=0, new_room_was = 0; // 1 in new room, 2 first time in new room, 3 loading saved game
int new_room_pos=0;
int new_room_x = SCR_NO_VALUE, new_room_y = SCR_NO_VALUE;
int new_room_loop = SCR_NO_VALUE;
// initially size 1, this will be increased by the initFile function
SpriteCache spriteset(1, game.SpriteInfos);
int proper_exit=0,our_eip=0;
std::vector<GUIMain> guis;
CCGUIObject ccDynamicGUIObject;
CCCharacter ccDynamicCharacter;
CCHotspot ccDynamicHotspot;
CCRegion ccDynamicRegion;
CCInventory ccDynamicInv;
CCGUI ccDynamicGUI;
CCObject ccDynamicObject;
CCDialog ccDynamicDialog;
CCAudioClip ccDynamicAudioClip;
CCAudioChannel ccDynamicAudio;
ScriptString myScriptStringImpl;
// TODO: IMPORTANT!!
// we cannot simply replace these arrays with vectors, or other C++ containers,
// until we implement safe management of such containers in script exports
// system. Noteably we would need an alternate to StaticArray class to track
// access to their elements.
ScriptObject scrObj[MAX_ROOM_OBJECTS];
ScriptGUI *scrGui = NULL;
ScriptHotspot scrHotspot[MAX_ROOM_HOTSPOTS];
ScriptRegion scrRegion[MAX_ROOM_REGIONS];
ScriptInvItem scrInv[MAX_INV];
ScriptDialog *scrDialog;
ViewStruct*views=NULL;
CharacterCache *charcache = NULL;
ObjectCache objcache[MAX_ROOM_OBJECTS];
MoveList *mls = NULL;
//=============================================================================
char saveGameDirectory[260] = "./";
// Custom save game parent directory
String saveGameParent;
const char* sgnametemplate = "agssave.%03d";
String saveGameSuffix;
int game_paused=0;
char pexbuf[STD_BUFFER_SIZE];
unsigned int load_new_game = 0;
int load_new_game_restore = -1;
int getloctype_index = 0, getloctype_throughgui = 0;
//=============================================================================
// Audio
//=============================================================================
void Game_StopAudio(int audioType)
{
if (((audioType < 0) || (audioType >= game.audioClipTypeCount)) && (audioType != SCR_NO_VALUE))
quitprintf("!Game.StopAudio: invalid audio type %d", audioType);
int aa;
for (aa = 0; aa < MAX_SOUND_CHANNELS; aa++)
{
if (audioType == SCR_NO_VALUE)
{
stop_or_fade_out_channel(aa);
}
else
{
ScriptAudioClip *clip = AudioChannel_GetPlayingClip(&scrAudioChannel[aa]);
if ((clip != NULL) && (clip->type == audioType))
stop_or_fade_out_channel(aa);
}
}
remove_clips_of_type_from_queue(audioType);
}
int Game_IsAudioPlaying(int audioType)
{
if (((audioType < 0) || (audioType >= game.audioClipTypeCount)) && (audioType != SCR_NO_VALUE))
quitprintf("!Game.IsAudioPlaying: invalid audio type %d", audioType);
if (play.fast_forward)
return 0;
for (int aa = 0; aa < MAX_SOUND_CHANNELS; aa++)
{
ScriptAudioClip *clip = AudioChannel_GetPlayingClip(&scrAudioChannel[aa]);
if (clip != NULL)
{
if ((clip->type == audioType) || (audioType == SCR_NO_VALUE))
{
return 1;
}
}
}
return 0;
}
void Game_SetAudioTypeSpeechVolumeDrop(int audioType, int volumeDrop)
{
if ((audioType < 0) || (audioType >= game.audioClipTypeCount))
quitprintf("!Game.SetAudioTypeVolume: invalid audio type: %d", audioType);
Debug::Printf("Game.SetAudioTypeSpeechVolumeDrop: type: %d, drop: %d", audioType, volumeDrop);
game.audioClipTypes[audioType].volume_reduction_while_speech_playing = volumeDrop;
update_volume_drop_if_voiceover();
}
void Game_SetAudioTypeVolume(int audioType, int volume, int changeType)
{
if ((volume < 0) || (volume > 100))
quitprintf("!Game.SetAudioTypeVolume: volume %d is not between 0..100", volume);
if ((audioType < 0) || (audioType >= game.audioClipTypeCount))
quitprintf("!Game.SetAudioTypeVolume: invalid audio type: %d", audioType);
int aa;
Debug::Printf("Game.SetAudioTypeVolume: type: %d, volume: %d, change: %d", audioType, volume, changeType);
if ((changeType == VOL_CHANGEEXISTING) ||
(changeType == VOL_BOTH))
{
for (aa = 0; aa < MAX_SOUND_CHANNELS; aa++)
{
ScriptAudioClip *clip = AudioChannel_GetPlayingClip(&scrAudioChannel[aa]);
if ((clip != NULL) && (clip->type == audioType))
{
channels[aa]->set_volume_percent(volume);
}
}
}
if ((changeType == VOL_SETFUTUREDEFAULT) ||
(changeType == VOL_BOTH))
{
play.default_audio_type_volumes[audioType] = volume;
// update queued clip volumes
update_queued_clips_volume(audioType, volume);
}
}
int Game_GetMODPattern() {
if (current_music_type == MUS_MOD && channels[SCHAN_MUSIC]) {
return channels[SCHAN_MUSIC]->get_pos();
}
return -1;
}
//=============================================================================
// ---
//=============================================================================
int Game_GetDialogCount()
{
return game.numdialog;
}
void set_debug_mode(bool on)
{
play.debug_mode = on ? 1 : 0;
debug_set_console(on);
}
void set_game_speed(int fps) {
frames_per_second = fps;
time_between_timers = 1000 / fps;
install_int_ex(dj_timer_handler,MSEC_TO_TIMER(time_between_timers));
}
extern int cbuttfont;
extern int acdialog_font;
extern char buffer2[60];
int oldmouse;
void setup_for_dialog() {
cbuttfont = play.normal_font;
acdialog_font = play.normal_font;
SetVirtualScreen(virtual_screen);
if (!play.mouse_cursor_hidden)
domouse(1);
oldmouse=cur_cursor; set_mouse_cursor(CURS_ARROW);
}
void restore_after_dialog() {
set_mouse_cursor(oldmouse);
if (!play.mouse_cursor_hidden)
domouse(2);
construct_virtual_screen(true);
}
String get_save_game_path(int slotNum) {
String filename;
filename.Format(sgnametemplate, slotNum);
String path = saveGameDirectory;
path.Append(filename);
path.Append(saveGameSuffix);
return path;
}
// Convert a path possibly containing path tags into acceptable save path
String MakeSaveGameDir(const char *newFolder)
{
// don't allow absolute paths
if (!is_relative_filename(newFolder))
return "";
String newSaveGameDir = FixSlashAfterToken(newFolder);
if (newSaveGameDir.CompareLeft(UserSavedgamesRootToken, UserSavedgamesRootToken.GetLength()) == 0)
{
if (saveGameParent.IsEmpty())
{
newSaveGameDir.ReplaceMid(0, UserSavedgamesRootToken.GetLength(),
PathOrCurDir(platform->GetUserSavedgamesDirectory()));
}
else
{
// If there is a custom save parent directory, then replace
// not only root token, but also first subdirectory
newSaveGameDir.ClipSection('/', 0, 1);
if (!newSaveGameDir.IsEmpty())
newSaveGameDir.PrependChar('/');
newSaveGameDir.Prepend(saveGameParent);
}
}
else
{
// Convert the path relative to installation folder into path relative to the
// safe save path with default name
if (saveGameParent.IsEmpty())
newSaveGameDir.Format("%s/%s/%s", PathOrCurDir(platform->GetUserSavedgamesDirectory()),
game.saveGameFolderName, newFolder);
else
newSaveGameDir.Format("%s/%s", saveGameParent.GetCStr(), newFolder);
// For games made in the safe-path-aware versions of AGS, report a warning
if (game.options[OPT_SAFEFILEPATHS])
{
debug_script_warn("Attempt to explicitly set savegame location relative to the game installation directory ('%s') denied;\nPath will be remapped to the user documents directory: '%s'",
newFolder, newSaveGameDir.GetCStr());
}
}
return newSaveGameDir;
}
bool SetCustomSaveParent(const String &path)
{
if (SetSaveGameDirectoryPath(path, true))
{
saveGameParent = path;
return true;
}
return false;
}
bool SetSaveGameDirectoryPath(const char *newFolder, bool explicit_path)
{
if (!newFolder || newFolder[0] == 0)
newFolder = ".";
String newSaveGameDir = explicit_path ? String(newFolder) : MakeSaveGameDir(newFolder);
if (newSaveGameDir.IsEmpty())
return false;
if (!Directory::CreateDirectory(newSaveGameDir))
return false;
newSaveGameDir.AppendChar('/');
char newFolderTempFile[260];
strcpy(newFolderTempFile, newSaveGameDir);
strcat(newFolderTempFile, "agstmp.tmp");
if (!Common::File::TestCreateFile(newFolderTempFile))
return false;
// copy the Restart Game file, if applicable
char restartGamePath[260];
sprintf(restartGamePath, "%s""agssave.%d%s", saveGameDirectory, RESTART_POINT_SAVE_GAME_NUMBER, saveGameSuffix.GetCStr());
Stream *restartGameFile = Common::File::OpenFileRead(restartGamePath);
if (restartGameFile != NULL)
{
long fileSize = restartGameFile->GetLength();
char *mbuffer = (char*)malloc(fileSize);
restartGameFile->Read(mbuffer, fileSize);
delete restartGameFile;
sprintf(restartGamePath, "%s""agssave.%d%s", newSaveGameDir.GetCStr(), RESTART_POINT_SAVE_GAME_NUMBER, saveGameSuffix.GetCStr());
restartGameFile = Common::File::CreateFile(restartGamePath);
restartGameFile->Write(mbuffer, fileSize);
delete restartGameFile;
free(mbuffer);
}
strcpy(saveGameDirectory, newSaveGameDir);
return true;
}
int Game_SetSaveGameDirectory(const char *newFolder)
{
return SetSaveGameDirectoryPath(newFolder, false) ? 1 : 0;
}
const char* Game_GetSaveSlotDescription(int slnum) {
String description;
if (read_savedgame_description(get_save_game_path(slnum), description))
{
return CreateNewScriptString(description);
}
return NULL;
}
void restore_game_dialog() {
can_run_delayed_command();
if (thisroom.Options.SaveLoadDisabled == 1) {
DisplayMessage (983);
return;
}
if (inside_script) {
curscript->queue_action(ePSARestoreGameDialog, 0, "RestoreGameDialog");
return;
}
setup_for_dialog();
int toload=loadgamedialog();
restore_after_dialog();
if (toload>=0) {
try_restore_save(toload);
}
}
void save_game_dialog() {
if (thisroom.Options.SaveLoadDisabled == 1) {
DisplayMessage (983);
return;
}
if (inside_script) {
curscript->queue_action(ePSASaveGameDialog, 0, "SaveGameDialog");
return;
}
setup_for_dialog();
int toload=savegamedialog();
restore_after_dialog();
if (toload>=0)
save_game(toload,buffer2);
}
void free_do_once_tokens()
{
for (int i = 0; i < play.num_do_once_tokens; i++)
{
free(play.do_once_tokens[i]);
}
if (play.do_once_tokens != NULL)
{
free(play.do_once_tokens);
play.do_once_tokens = NULL;
}
play.num_do_once_tokens = 0;
}
// Free all the memory associated with the game
void unload_game_file() {
int bb, ee;
for (bb = 0; bb < game.numcharacters; bb++) {
if (game.charScripts != NULL)
delete game.charScripts[bb];
}
characterScriptObjNames.clear();
free(charextra);
free(mls);
free(actsps);
free(actspsbmp);
free(actspswb);
free(actspswbbmp);
free(actspswbcache);
game.charProps.clear();
for (bb = 1; bb < game.numinvitems; bb++) {
if (game.invScripts != NULL)
delete game.invScripts[bb];
}
if (game.charScripts != NULL)
{
delete game.charScripts;
delete game.invScripts;
game.charScripts = NULL;
game.invScripts = NULL;
}
if (game.dict != NULL) {
game.dict->free_memory();
free (game.dict);
game.dict = NULL;
}
if ((gameinst != NULL) && (gameinst->pc != 0))
quit("Error: unload_game called while script still running");
//->AbortAndDestroy (gameinst);
else {
delete gameinstFork;
delete gameinst;
gameinstFork = NULL;
gameinst = NULL;
}
gamescript.reset();
if ((dialogScriptsInst != NULL) && (dialogScriptsInst->pc != 0))
quit("Error: unload_game called while dialog script still running");
else if (dialogScriptsInst != NULL)
{
delete dialogScriptsInst;
dialogScriptsInst = NULL;
}
dialogScriptsScript.reset();
for (ee = 0; ee < numScriptModules; ee++) {
delete moduleInstFork[ee];
delete moduleInst[ee];
scriptModules[ee].reset();
}
moduleInstFork.resize(0);
moduleInst.resize(0);
scriptModules.resize(0);
repExecAlways.moduleHasFunction.resize(0);
lateRepExecAlways.moduleHasFunction.resize(0);
getDialogOptionsDimensionsFunc.moduleHasFunction.resize(0);
renderDialogOptionsFunc.moduleHasFunction.resize(0);
getDialogOptionUnderCursorFunc.moduleHasFunction.resize(0);
runDialogOptionMouseClickHandlerFunc.moduleHasFunction.resize(0);
runDialogOptionKeyPressHandlerFunc.moduleHasFunction.resize(0);
runDialogOptionRepExecFunc.moduleHasFunction.resize(0);
numScriptModules = 0;
if (game.audioClipCount > 0)
{
free(game.audioClips);
game.audioClipCount = 0;
free(game.audioClipTypes);
game.audioClipTypeCount = 0;
}
game.viewNames.clear();
free (views);
views = NULL;
free (game.chars);
game.chars = NULL;
free (charcache);
charcache = NULL;
if (splipsync != NULL)
{
for (ee = 0; ee < numLipLines; ee++)
{
free(splipsync[ee].endtimeoffs);
free(splipsync[ee].frame);
}
free(splipsync);
splipsync = NULL;
numLipLines = 0;
curLipLine = -1;
}
for (ee=0;ee < MAXGLOBALMES;ee++) {
if (game.messages[ee]==NULL) continue;
free (game.messages[ee]);
game.messages[ee] = NULL;
}
for (ee = 0; ee < game.roomCount; ee++)
{
free(game.roomNames[ee]);
}
if (game.roomCount > 0)
{
free(game.roomNames);
free(game.roomNumbers);
game.roomCount = 0;
}
for (ee=0;ee<game.numdialog;ee++) {
if (dialog[ee].optionscripts!=NULL)
free (dialog[ee].optionscripts);
dialog[ee].optionscripts = NULL;
}
free (dialog);
dialog = NULL;
delete [] scrDialog;
scrDialog = NULL;
for (ee = 0; ee < game.numgui; ee++) {
free (guibg[ee]);
guibg[ee] = NULL;
}
guiScriptObjNames.clear();
free(guibg);
guis.clear();
free(scrGui);
pl_stop_plugins();
ccRemoveAllSymbols();
ccUnregisterAllObjects();
for (ee=0;ee<game.numfonts;ee++)
wfreefont(ee);
free_do_once_tokens();
free(play.gui_draw_order);
resetRoomStatuses();
}
/*
// [DEPRECATED]
const char* Game_GetGlobalStrings(int index) {
if ((index < 0) || (index >= MAXGLOBALSTRINGS))
quit("!Game.GlobalStrings: invalid index");
return CreateNewScriptString(play.globalstrings[index]);
}
*/
char gamefilenamebuf[200];
// ** GetGameParameter replacement functions
int Game_GetInventoryItemCount() {
// because of the dummy item 0, this is always one higher than it should be
return game.numinvitems - 1;
}
int Game_GetFontCount() {
return game.numfonts;
}
int Game_GetMouseCursorCount() {
return game.numcursors;
}
int Game_GetCharacterCount() {
return game.numcharacters;
}
int Game_GetGUICount() {
return game.numgui;
}
int Game_GetViewCount() {
return game.numviews;
}
int Game_GetSpriteWidth(int spriteNum) {
if (spriteNum < 0)
return 0;
if (!spriteset.DoesSpriteExist(spriteNum))
return 0;
return game.SpriteInfos[spriteNum].Width;
}
int Game_GetSpriteHeight(int spriteNum) {
if (spriteNum < 0)
return 0;
if (!spriteset.DoesSpriteExist(spriteNum))
return 0;
return game.SpriteInfos[spriteNum].Height;
}
int Game_GetLoopCountForView(int viewNumber) {
if ((viewNumber < 1) || (viewNumber > game.numviews))
quit("!GetGameParameter: invalid view specified");
return views[viewNumber - 1].numLoops;
}
int Game_GetRunNextSettingForLoop(int viewNumber, int loopNumber) {
if ((viewNumber < 1) || (viewNumber > game.numviews))
quit("!GetGameParameter: invalid view specified");
if ((loopNumber < 0) || (loopNumber >= views[viewNumber - 1].numLoops))
quit("!GetGameParameter: invalid loop specified");
return (views[viewNumber - 1].loops[loopNumber].RunNextLoop()) ? 1 : 0;
}
int Game_GetFrameCountForLoop(int viewNumber, int loopNumber) {
if ((viewNumber < 1) || (viewNumber > game.numviews))
quit("!GetGameParameter: invalid view specified");
if ((loopNumber < 0) || (loopNumber >= views[viewNumber - 1].numLoops))
quit("!GetGameParameter: invalid loop specified");
return views[viewNumber - 1].loops[loopNumber].numFrames;
}
ScriptViewFrame* Game_GetViewFrame(int viewNumber, int loopNumber, int frame) {
if ((viewNumber < 1) || (viewNumber > game.numviews))
quit("!GetGameParameter: invalid view specified");
if ((loopNumber < 0) || (loopNumber >= views[viewNumber - 1].numLoops))
quit("!GetGameParameter: invalid loop specified");
if ((frame < 0) || (frame >= views[viewNumber - 1].loops[loopNumber].numFrames))
quit("!GetGameParameter: invalid frame specified");
ScriptViewFrame *sdt = new ScriptViewFrame(viewNumber - 1, loopNumber, frame);
ccRegisterManagedObject(sdt, sdt);
return sdt;
}
int Game_DoOnceOnly(const char *token)
{
if (strlen(token) > 199)
quit("!Game.DoOnceOnly: token length cannot be more than 200 chars");
for (int i = 0; i < play.num_do_once_tokens; i++)
{
if (strcmp(play.do_once_tokens[i], token) == 0)
{
return 0;
}
}
play.do_once_tokens = (char**)realloc(play.do_once_tokens, sizeof(char*) * (play.num_do_once_tokens + 1));
play.do_once_tokens[play.num_do_once_tokens] = (char*)malloc(strlen(token) + 1);
strcpy(play.do_once_tokens[play.num_do_once_tokens], token);
play.num_do_once_tokens++;
return 1;
}
int Game_GetTextReadingSpeed()
{
return play.text_speed;
}
void Game_SetTextReadingSpeed(int newTextSpeed)
{
if (newTextSpeed < 1)
quitprintf("!Game.TextReadingSpeed: %d is an invalid speed", newTextSpeed);
play.text_speed = newTextSpeed;
}
int Game_GetMinimumTextDisplayTimeMs()
{
return play.text_min_display_time_ms;
}
void Game_SetMinimumTextDisplayTimeMs(int newTextMinTime)
{
play.text_min_display_time_ms = newTextMinTime;
}
int Game_GetIgnoreUserInputAfterTextTimeoutMs()
{
return play.ignore_user_input_after_text_timeout_ms;
}
void Game_SetIgnoreUserInputAfterTextTimeoutMs(int newValueMs)
{
play.ignore_user_input_after_text_timeout_ms = newValueMs;
}
const char *Game_GetFileName() {
return CreateNewScriptString(usetup.main_data_filename);
}
const char *Game_GetName() {
return CreateNewScriptString(play.game_name);
}
void Game_SetName(const char *newName) {
strncpy(play.game_name, newName, 99);
play.game_name[99] = 0;
#if (ALLEGRO_DATE > 19990103)
set_window_title(play.game_name);
#endif
}
int Game_GetSkippingCutscene()
{
if (play.fast_forward)
{
return 1;
}
return 0;
}
int Game_GetInSkippableCutscene()
{
if (play.in_cutscene)
{
return 1;
}
return 0;
}
int Game_GetColorFromRGB(int red, int grn, int blu) {
if ((red < 0) || (red > 255) || (grn < 0) || (grn > 255) ||
(blu < 0) || (blu > 255))
quit("!GetColorFromRGB: colour values must be 0-255");
if (game.color_depth == 1)
{
return makecol8(red, grn, blu);
}
int agscolor = ((blu >> 3) & 0x1f);
agscolor += ((grn >> 2) & 0x3f) << 5;
agscolor += ((red >> 3) & 0x1f) << 11;
return agscolor;
}
const char* Game_InputBox(const char *msg) {
char buffer[STD_BUFFER_SIZE];
sc_inputbox(msg, buffer);
return CreateNewScriptString(buffer);
}
const char* Game_GetLocationName(int x, int y) {
char buffer[STD_BUFFER_SIZE];
GetLocationName(x, y, buffer);
return CreateNewScriptString(buffer);
}
const char* Game_GetGlobalMessages(int index) {
if ((index < 500) || (index >= MAXGLOBALMES + 500)) {
return NULL;
}
char buffer[STD_BUFFER_SIZE];
buffer[0] = 0;
replace_tokens(get_translation(get_global_message(index)), buffer, STD_BUFFER_SIZE);
return CreateNewScriptString(buffer);
}
int Game_GetSpeechFont() {
return play.speech_font;
}
int Game_GetNormalFont() {
return play.normal_font;
}
const char* Game_GetTranslationFilename() {
char buffer[STD_BUFFER_SIZE];
GetTranslationName(buffer);
return CreateNewScriptString(buffer);
}
int Game_ChangeTranslation(const char *newFilename)
{
if ((newFilename == NULL) || (newFilename[0] == 0))
{
close_translation();
strcpy(transFileName, "");
return 1;
}
String oldTransFileName;
oldTransFileName = transFileName;
if (!init_translation(newFilename, oldTransFileName.LeftSection('.'), false))
{
strcpy(transFileName, oldTransFileName);
return 0;
}
return 1;
}
ScriptAudioClip *Game_GetAudioClip(int index)
{
if (index < 0 || index >= game.audioClipCount)
return NULL;
return &game.audioClips[index];
}
//=============================================================================
// save game functions
void serialize_bitmap(const Common::Bitmap *thispic, Stream *out) {
if (thispic != NULL) {
out->WriteInt32(thispic->GetWidth());
out->WriteInt32(thispic->GetHeight());
out->WriteInt32(thispic->GetColorDepth());
for (int cc=0;cc<thispic->GetHeight();cc++)
{
switch (thispic->GetColorDepth())
{
case 8:
// CHECKME: originally, AGS does not use real BPP here, but simply divides color depth by 8;
// therefore 15-bit bitmaps are saved only partially? is this a bug? or?
case 15:
out->WriteArray(&thispic->GetScanLine(cc)[0], thispic->GetWidth(), 1);
break;
case 16:
out->WriteArrayOfInt16((const int16_t*)&thispic->GetScanLine(cc)[0], thispic->GetWidth());
break;
case 32:
out->WriteArrayOfInt32((const int32_t*)&thispic->GetScanLine(cc)[0], thispic->GetWidth());
break;
}
}
}
}
// On Windows we could just use IIDFromString but this is platform-independant
void convert_guid_from_text_to_binary(const char *guidText, unsigned char *buffer)
{
guidText++; // skip {
for (int bytesDone = 0; bytesDone < 16; bytesDone++)
{
if (*guidText == '-')
guidText++;
char tempString[3];
tempString[0] = guidText[0];
tempString[1] = guidText[1];
tempString[2] = 0;
int thisByte = 0;
sscanf(tempString, "%X", &thisByte);
buffer[bytesDone] = thisByte;
guidText += 2;
}
// Swap bytes to give correct GUID order
unsigned char temp;
temp = buffer[0]; buffer[0] = buffer[3]; buffer[3] = temp;
temp = buffer[1]; buffer[1] = buffer[2]; buffer[2] = temp;
temp = buffer[4]; buffer[4] = buffer[5]; buffer[5] = temp;
temp = buffer[6]; buffer[6] = buffer[7]; buffer[7] = temp;
}
Bitmap *read_serialized_bitmap(Stream *in) {
Bitmap *thispic;
int picwid = in->ReadInt32();
int pichit = in->ReadInt32();
int piccoldep = in->ReadInt32();
thispic = BitmapHelper::CreateBitmap(picwid,pichit,piccoldep);
if (thispic == NULL)
return NULL;
for (int vv=0; vv < pichit; vv++)
{
switch (piccoldep)
{
case 8:
// CHECKME: originally, AGS does not use real BPP here, but simply divides color depth by 8
case 15:
in->ReadArray(thispic->GetScanLineForWriting(vv), picwid, 1);
break;
case 16:
in->ReadArrayOfInt16((int16_t*)thispic->GetScanLineForWriting(vv), picwid);
break;
case 32:
in->ReadArrayOfInt32((int32_t*)thispic->GetScanLineForWriting(vv), picwid);
break;
}
}
return thispic;
}
void skip_serialized_bitmap(Stream *in)
{
int picwid = in->ReadInt32();
int pichit = in->ReadInt32();
int piccoldep = in->ReadInt32();
// CHECKME: originally, AGS does not use real BPP here, but simply divides color depth by 8
int bpp = piccoldep / 8;
in->Seek(picwid * pichit * bpp);
}
long write_screen_shot_for_vista(Stream *out, Bitmap *screenshot)
{
long fileSize = 0;
char tempFileName[MAX_PATH];
sprintf(tempFileName, "%s""_tmpscht.bmp", saveGameDirectory);
screenshot->SaveToFile(tempFileName, palette);
update_polled_stuff_if_runtime();
if (exists(tempFileName))
{
fileSize = file_size_ex(tempFileName);
char *buffer = (char*)malloc(fileSize);
Stream *temp_in = Common::File::OpenFileRead(tempFileName);
temp_in->Read(buffer, fileSize);
delete temp_in;
unlink(tempFileName);
out->Write(buffer, fileSize);
free(buffer);
}
return fileSize;
}
void WriteGameSetupStructBase_Aligned(Stream *out)
{
AlignedStream align_s(out, Common::kAligned_Write);
game.GameSetupStructBase::WriteToFile(&align_s);
}
#define MAGICNUMBER 0xbeefcafe
void create_savegame_screenshot(Bitmap *&screenShot)
{
if (game.options[OPT_SAVESCREENSHOT]) {
int usewid = play.screenshot_width;
int usehit = play.screenshot_height;
if (usewid > virtual_screen->GetWidth())
usewid = virtual_screen->GetWidth();
if (usehit > virtual_screen->GetHeight())
usehit = virtual_screen->GetHeight();
if ((play.screenshot_width < 16) || (play.screenshot_height < 16))
quit("!Invalid game.screenshot_width/height, must be from 16x16 to screen res");
if (gfxDriver->UsesMemoryBackBuffer())
{
screenShot = BitmapHelper::CreateBitmap(usewid, usehit, virtual_screen->GetColorDepth());
screenShot->StretchBlt(virtual_screen,
RectWH(0, 0, virtual_screen->GetWidth(), virtual_screen->GetHeight()),
RectWH(0, 0, screenShot->GetWidth(), screenShot->GetHeight()));
}
else
{
// FIXME this weird stuff! (related to incomplete OpenGL renderer)
#if defined(IOS_VERSION) || defined(ANDROID_VERSION)
int color_depth = (psp_gfx_renderer > 0) ? 32 : game.GetColorDepth();
#else
int color_depth = game.GetColorDepth();
#endif
Bitmap *tempBlock = BitmapHelper::CreateBitmap(virtual_screen->GetWidth(), virtual_screen->GetHeight(), color_depth);
gfxDriver->GetCopyOfScreenIntoBitmap(tempBlock);
screenShot = BitmapHelper::CreateBitmap(usewid, usehit, color_depth);
screenShot->StretchBlt(tempBlock,
RectWH(0, 0, tempBlock->GetWidth(), tempBlock->GetHeight()),
RectWH(0, 0, screenShot->GetWidth(), screenShot->GetHeight()));
delete tempBlock;
}
}
}
void save_game(int slotn, const char*descript) {
// dont allow save in rep_exec_always, because we dont save
// the state of blocked scripts
can_run_delayed_command();
if (inside_script) {
strcpy(curscript->postScriptSaveSlotDescription[curscript->queue_action(ePSASaveGame, slotn, "SaveGameSlot")], descript);
return;
}
if (platform->GetDiskFreeSpaceMB() < 2) {
Display("ERROR: There is not enough disk space free to save the game. Clear some disk space and try again.");
return;
}
VALIDATE_STRING(descript);
String nametouse;
nametouse = get_save_game_path(slotn);
Bitmap *screenShot = NULL;
// Screenshot
create_savegame_screenshot(screenShot);
Common::PStream out = StartSavegame(nametouse, descript, screenShot);
if (out == NULL)
quit("save_game: unable to open savegame file for writing");
update_polled_stuff_if_runtime();
// Actual dynamic game data is saved here
SaveGameState(out);
if (screenShot != NULL)
{
int screenShotOffset = out->GetPosition() - sizeof(RICH_GAME_MEDIA_HEADER);
int screenShotSize = write_screen_shot_for_vista(out.get(), screenShot);
update_polled_stuff_if_runtime();
out.reset(Common::File::OpenFile(nametouse, Common::kFile_Open, Common::kFile_ReadWrite));
out->Seek(12, kSeekBegin);
out->WriteInt32(screenShotOffset);
out->Seek(4);
out->WriteInt32(screenShotSize);
}
if (screenShot != NULL)
delete screenShot;
}
char rbuffer[200];
HSaveError restore_game_head_dynamic_values(Stream *in, RestoredData &r_data)
{
r_data.FPS = in->ReadInt32();
r_data.CursorMode = in->ReadInt32();
r_data.CursorID = in->ReadInt32();
offsetx = in->ReadInt32();
offsety = in->ReadInt32();
loopcounter = in->ReadInt32();
return HSaveError::None();
}
void restore_game_spriteset(Stream *in)
{
// ensure the sprite set is at least as large as it was
// when the game was saved
spriteset.EnlargeTo(in->ReadInt32());
// get serialized dynamic sprites
int sprnum = in->ReadInt32();
while (sprnum) {
unsigned char spriteflag = in->ReadByte();
add_dynamic_sprite(sprnum, read_serialized_bitmap(in));
game.SpriteInfos[sprnum].Flags = spriteflag;
sprnum = in->ReadInt32();
}
}
HSaveError restore_game_scripts(Stream *in, const PreservedParams &pp, RestoredData &r_data)
{
// read the global script data segment
int gdatasize = in->ReadInt32();
if (pp.GlScDataSize != gdatasize)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching size of global script data.");
}
r_data.GlobalScript.Len = gdatasize;
r_data.GlobalScript.Data.reset(new char[gdatasize]);
in->Read(r_data.GlobalScript.Data.get(), gdatasize);
if (in->ReadInt32() != numScriptModules)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of script modules.");
}
r_data.ScriptModules.resize(numScriptModules);
for (int i = 0; i < numScriptModules; ++i)
{
size_t module_size = in->ReadInt32();
if (pp.ScMdDataSize[i] != module_size)
{
return new SavegameError(kSvgErr_GameContentAssertion, String::FromFormat("Mismatching size of script module data, module %d.", i));
}
r_data.ScriptModules[i].Len = module_size;
r_data.ScriptModules[i].Data.reset(new char[module_size]);
in->Read(r_data.ScriptModules[i].Data.get(), module_size);
}
return HSaveError::None();
}
void ReadRoomStatus_Aligned(RoomStatus *roomstat, Stream *in)
{
AlignedStream align_s(in, Common::kAligned_Read);
roomstat->ReadFromFile_v321(&align_s);
}
void restore_game_room_state(Stream *in)
{
int vv;
displayed_room = in->ReadInt32();
// read the room state for all the rooms the player has been in
RoomStatus* roomstat;
int beenhere;
for (vv=0;vv<MAX_ROOMS;vv++)
{
beenhere = in->ReadByte();
if (beenhere)
{
roomstat = getRoomStatus(vv);
roomstat->beenhere = beenhere;
if (roomstat->beenhere)
{
ReadRoomStatus_Aligned(roomstat, in);
if (roomstat->tsdatasize > 0)
{
roomstat->tsdata=(char*)malloc(roomstat->tsdatasize + 8); // JJS: Why allocate 8 additional bytes?
in->Read(&roomstat->tsdata[0], roomstat->tsdatasize);
}
}
}
}
}
void ReadGameState_Aligned(Stream *in)
{
AlignedStream align_s(in, Common::kAligned_Read);
play.ReadFromSavegame(&align_s, true);
}
void restore_game_play_ex_data(Stream *in)
{
if (play.num_do_once_tokens > 0)
{
play.do_once_tokens = (char**)malloc(sizeof(char*) * play.num_do_once_tokens);
for (int bb = 0; bb < play.num_do_once_tokens; bb++)
{
fgetstring_limit(rbuffer, in, 200);
play.do_once_tokens[bb] = (char*)malloc(strlen(rbuffer) + 1);
strcpy(play.do_once_tokens[bb], rbuffer);
}
}
in->ReadArrayOfInt32(&play.gui_draw_order[0], game.numgui);
}
void restore_game_play(Stream *in)
{
// preserve the replay settings
int playback_was = play.playback, recording_was = play.recording;
int gamestep_was = play.gamestep;
int screenfadedout_was = play.screen_is_faded_out;
int roomchanges_was = play.room_changes;
// make sure the pointer is preserved
int *gui_draw_order_was = play.gui_draw_order;
ReadGameState_Aligned(in);
play.screen_is_faded_out = screenfadedout_was;
play.playback = playback_was;
play.recording = recording_was;
play.gamestep = gamestep_was;
play.room_changes = roomchanges_was;
play.gui_draw_order = gui_draw_order_was;
restore_game_play_ex_data(in);
}
void ReadMoveList_Aligned(Stream *in)
{
AlignedStream align_s(in, Common::kAligned_Read);
for (int i = 0; i < game.numcharacters + MAX_ROOM_OBJECTS + 1; ++i)
{
mls[i].ReadFromFile_Legacy(&align_s);
align_s.Reset();
}
}
void ReadGameSetupStructBase_Aligned(Stream *in)
{
AlignedStream align_s(in, Common::kAligned_Read);
game.GameSetupStructBase::ReadFromFile(&align_s);
}
void ReadCharacterExtras_Aligned(Stream *in)
{
AlignedStream align_s(in, Common::kAligned_Read);
for (int i = 0; i < game.numcharacters; ++i)
{
charextra[i].ReadFromFile(&align_s);
align_s.Reset();
}
}
void restore_game_palette(Stream *in)
{
in->ReadArray(&palette[0],sizeof(color),256);
}
void restore_game_dialogs(Stream *in)
{
for (int vv=0;vv<game.numdialog;vv++)
in->ReadArrayOfInt32(&dialog[vv].optionflags[0],MAXTOPICOPTIONS);
}
void restore_game_more_dynamic_values(Stream *in)
{
mouse_on_iface=in->ReadInt32();
in->ReadInt32(); // mouse_on_iface_button
in->ReadInt32(); // mouse_pushed_iface
ifacepopped = in->ReadInt32();
game_paused=in->ReadInt32();
}
void ReadAnimatedButtons_Aligned(Stream *in)
{
AlignedStream align_s(in, Common::kAligned_Read);
for (int i = 0; i < numAnimButs; ++i)
{
animbuts[i].ReadFromFile(&align_s);
align_s.Reset();
}
}
HSaveError restore_game_gui(Stream *in, int numGuisWas)
{
GUI::ReadGUI(guis, in);
game.numgui = guis.size();
if (numGuisWas != game.numgui)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of GUI.");
}
numAnimButs = in->ReadInt32();
ReadAnimatedButtons_Aligned(in);
return HSaveError::None();
}
HSaveError restore_game_audiocliptypes(Stream *in)
{
if (in->ReadInt32() != game.audioClipTypeCount)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Audio Clip Types.");
}
for (int i = 0; i < game.audioClipTypeCount; ++i)
{
game.audioClipTypes[i].ReadFromFile(in);
}
return HSaveError::None();
}
void restore_game_thisroom(Stream *in, RestoredData &r_data)
{
in->ReadArrayOfInt16(r_data.RoomLightLevels, MAX_ROOM_REGIONS);
in->ReadArrayOfInt32(r_data.RoomTintLevels, MAX_ROOM_REGIONS);
in->ReadArrayOfInt16(r_data.RoomZoomLevels1, MAX_WALK_AREAS + 1);
in->ReadArrayOfInt16(r_data.RoomZoomLevels2, MAX_WALK_AREAS + 1);
}
void restore_game_ambientsounds(Stream *in, RestoredData &r_data)
{
int bb;
for (int i = 0; i < MAX_SOUND_CHANNELS; ++i)
{
ambient[i].ReadFromFile(in);
}
for (bb = 1; bb < MAX_SOUND_CHANNELS; bb++) {
if (ambient[bb].channel == 0)
r_data.DoAmbient[bb] = 0;
else {
r_data.DoAmbient[bb] = ambient[bb].num;
ambient[bb].channel = 0;
}
}
}
void ReadOverlays_Aligned(Stream *in)
{
AlignedStream align_s(in, Common::kAligned_Read);
for (int i = 0; i < numscreenover; ++i)
{
screenover[i].ReadFromFile(&align_s);
align_s.Reset();
}
}
void restore_game_overlays(Stream *in)
{
numscreenover = in->ReadInt32();
ReadOverlays_Aligned(in);
for (int bb=0;bb<numscreenover;bb++) {
if (screenover[bb].hasSerializedBitmap)
screenover[bb].pic = read_serialized_bitmap(in);
}
}
void restore_game_dynamic_surfaces(Stream *in, RestoredData &r_data)
{
// load into a temp array since ccUnserialiseObjects will destroy
// it otherwise
r_data.DynamicSurfaces.resize(MAX_DYNAMIC_SURFACES);
for (int i = 0; i < MAX_DYNAMIC_SURFACES; ++i)
{
if (in->ReadInt8() == 0)
{
r_data.DynamicSurfaces[i] = NULL;
}
else
{
r_data.DynamicSurfaces[i] = read_serialized_bitmap(in);
}
}
}
void restore_game_displayed_room_status(Stream *in, RestoredData &r_data)
{
int bb;
for (bb = 0; bb < MAX_ROOM_BGFRAMES; bb++)
r_data.RoomBkgScene[bb].reset();
if (displayed_room >= 0) {
for (bb = 0; bb < MAX_ROOM_BGFRAMES; bb++) {
r_data.RoomBkgScene[bb] = NULL;
if (play.raw_modified[bb]) {
r_data.RoomBkgScene[bb].reset(read_serialized_bitmap(in));
}
}
bb = in->ReadInt32();
if (bb)
raw_saved_screen = read_serialized_bitmap(in);
// get the current troom, in case they save in room 600 or whatever
ReadRoomStatus_Aligned(&troom, in);
if (troom.tsdatasize > 0) {
troom.tsdata=(char*)malloc(troom.tsdatasize+5);
in->Read(&troom.tsdata[0],troom.tsdatasize);
}
else
troom.tsdata = NULL;
}
}
HSaveError restore_game_globalvars(Stream *in)
{
if (in->ReadInt32() != numGlobalVars)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Restore game error: mismatching number of Global Variables.");
}
for (int i = 0; i < numGlobalVars; ++i)
{
globalvars[i].Read(in);
}
return HSaveError::None();
}
HSaveError restore_game_views(Stream *in)
{
if (in->ReadInt32() != game.numviews)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Views.");
}
for (int bb = 0; bb < game.numviews; bb++) {
for (int cc = 0; cc < views[bb].numLoops; cc++) {
for (int dd = 0; dd < views[bb].loops[cc].numFrames; dd++)
{
views[bb].loops[cc].frames[dd].sound = in->ReadInt32();
views[bb].loops[cc].frames[dd].pic = in->ReadInt32();
}
}
}
return HSaveError::None();
}
HSaveError restore_game_audioclips_and_crossfade(Stream *in, RestoredData &r_data)
{
if (in->ReadInt32() != game.audioClipCount)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Audio Clips.");
}
for (int i = 0; i <= MAX_SOUND_CHANNELS; ++i)
{
RestoredData::ChannelInfo &chan_info = r_data.AudioChans[i];
chan_info.Pos = 0;
chan_info.ClipID = in->ReadInt32();
if (chan_info.ClipID >= 0)
{
if (chan_info.ClipID >= game.audioClipCount)
{
return new SavegameError(kSvgErr_GameObjectInitFailed, "Invalid audio clip index.");
}
chan_info.Pos = in->ReadInt32();
if (chan_info.Pos < 0)
chan_info.Pos = 0;
chan_info.Priority = in->ReadInt32();
chan_info.Repeat = in->ReadInt32();
chan_info.Vol = in->ReadInt32();
chan_info.Pan = in->ReadInt32();
chan_info.VolAsPercent = in->ReadInt32();
chan_info.PanAsPercent = in->ReadInt32();
chan_info.Speed = 1000;
chan_info.Speed = in->ReadInt32();
}
}
crossFading = in->ReadInt32();
crossFadeVolumePerStep = in->ReadInt32();
crossFadeStep = in->ReadInt32();
crossFadeVolumeAtStart = in->ReadInt32();
return HSaveError::None();
}
HSaveError restore_game_data(Stream *in, SavegameVersion svg_version, const PreservedParams &pp, RestoredData &r_data)
{
int vv;
HSaveError err = restore_game_head_dynamic_values(in, r_data);
if (!err)
return err;
restore_game_spriteset(in);
update_polled_stuff_if_runtime();
err = restore_game_scripts(in, pp, r_data);
if (!err)
return err;
restore_game_room_state(in);
restore_game_play(in);
ReadMoveList_Aligned(in);
// save pointer members before reading
char* gswas=game.globalscript;
ccScript* compsc=game.CompiledScript;
CharacterInfo* chwas=game.chars;
WordsDictionary *olddict = game.dict;
char* mesbk[MAXGLOBALMES];
int numchwas = game.numcharacters;
for (vv=0;vv<MAXGLOBALMES;vv++) mesbk[vv]=game.messages[vv];
int numdiwas = game.numdialog;
int numinvwas = game.numinvitems;
int numviewswas = game.numviews;
int numGuisWas = game.numgui;
ReadGameSetupStructBase_Aligned(in);
// Delete unneeded data
// TODO: reorganize this (may be solved by optimizing safe format too)
delete [] game.load_messages;
game.load_messages = NULL;
if (game.numdialog!=numdiwas)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Dialogs.");
}
if (numchwas != game.numcharacters)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Characters.");
}
if (numinvwas != game.numinvitems)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Inventory Items.");
}
if (game.numviews != numviewswas)
{
return new SavegameError(kSvgErr_GameContentAssertion, "Mismatching number of Views.");
}
game.ReadFromSaveGame_v321(in, gswas, compsc, chwas, olddict, mesbk);
// Modified custom properties are read separately to keep existing save format
play.ReadCustomProperties_v340(in);
ReadCharacterExtras_Aligned(in);
restore_game_palette(in);
restore_game_dialogs(in);
restore_game_more_dynamic_values(in);
err = restore_game_gui(in, numGuisWas);
if (!err)
return err;
err = restore_game_audiocliptypes(in);
if (!err)
return err;
restore_game_thisroom(in, r_data);
restore_game_ambientsounds(in, r_data);
restore_game_overlays(in);
update_polled_stuff_if_runtime();
restore_game_dynamic_surfaces(in, r_data);
update_polled_stuff_if_runtime();
restore_game_displayed_room_status(in, r_data);
err = restore_game_globalvars(in);
if (!err)
return err;
err = restore_game_views(in);
if (!err)
return err;
if (in->ReadInt32() != MAGICNUMBER+1)
{
return new SavegameError(kSvgErr_InconsistentFormat, "MAGICNUMBER not found before Audio Clips.");
}
err = restore_game_audioclips_and_crossfade(in, r_data);
if (!err)
return err;
// [IKM] Plugins expect FILE pointer! // TODO something with this later
pl_run_plugin_hooks(AGSE_RESTOREGAME, (long)((Common::FileStream*)in)->GetHandle());
if (in->ReadInt32() != (unsigned)MAGICNUMBER)
return new SavegameError(kSvgErr_InconsistentPlugin);
// save the new room music vol for later use
r_data.RoomVolume = (RoomVolumeMod)in->ReadInt32();
if (ccUnserializeAllObjects(in, &ccUnserializer))
{
return new SavegameError(kSvgErr_GameObjectInitFailed,
String::FromFormat("Managed pool deserialization failed: %s.", ccErrorString));
}
// preserve legacy music type setting
current_music_type = in->ReadInt32();
return HSaveError::None();
}
int gameHasBeenRestored = 0;
int oldeip;
bool read_savedgame_description(const String &savedgame, String &description)
{
SavegameDescription desc;
if (OpenSavegame(savedgame, desc, kSvgDesc_UserText))
{
description = desc.UserText;
return true;
}
return false;
}
bool read_savedgame_screenshot(const String &savedgame, int &want_shot)
{
want_shot = 0;
SavegameDescription desc;
HSaveError err = OpenSavegame(savedgame, desc, kSvgDesc_UserImage);
if (!err)
return false;
if (desc.UserImage.get())
{
int slot = spriteset.AddNewSprite();
if (slot > 0)
{
// add it into the sprite set
add_dynamic_sprite(slot, ReplaceBitmapWithSupportedFormat(desc.UserImage.release()));
want_shot = slot;
}
}
return true;
}
HSaveError load_game(const String &path, int slotNumber, bool &data_overwritten)
{
data_overwritten = false;
gameHasBeenRestored++;
oldeip = our_eip;
our_eip = 2050;
HSaveError err;
SavegameSource src;
SavegameDescription desc;
err = OpenSavegame(path, src, desc, kSvgDesc_EnvInfo);
// saved in incompatible enviroment
if (!err)
return err;
// CHECKME: is this color depth test still essential? if yes, is there possible workaround?
else if (desc.ColorDepth != game.GetColorDepth())
return new SavegameError(kSvgErr_DifferentColorDepth, String::FromFormat("Running: %d-bit, saved in: %d-bit.", game.GetColorDepth(), desc.ColorDepth));
// saved with different game file
if (Path::ComparePaths(desc.MainDataFilename, usetup.main_data_filename))
{
// [IKM] 2012-11-26: this is a workaround, indeed.
// Try to find wanted game's executable; if it does not exist,
// continue loading savedgame in current game, and pray for the best
get_install_dir_path(gamefilenamebuf, desc.MainDataFilename);
if (Common::File::TestReadFile(gamefilenamebuf))
{
RunAGSGame (desc.MainDataFilename, 0, 0);
load_new_game_restore = slotNumber;
return HSaveError::None();
}
Common::Debug::Printf(kDbgMsg_Warn, "WARNING: the saved game '%s' references game file '%s', but it cannot be found in the current directory. Trying to restore in the running game instead.",
path.GetCStr(), desc.MainDataFilename.GetCStr());
}
// do the actual restore
err = RestoreGameState(src.InputStream, src.Version);
data_overwritten = true;
if (!err)
return err;
src.InputStream.reset();
our_eip = oldeip;
// ensure keyboard buffer is clean
// use the raw versions rather than the rec_ versions so we don't
// interfere with the replay sync
while (keypressed()) readkey();
// call "After Restore" event callback
run_on_event(GE_RESTORE_GAME, RuntimeScriptValue().SetInt32(slotNumber));
return HSaveError::None();
}
bool try_restore_save(int slot)
{
return try_restore_save(get_save_game_path(slot), slot);
}
bool try_restore_save(const Common::String &path, int slot)
{
bool data_overwritten;
HSaveError err = load_game(path, slot, data_overwritten);
if (!err)
{
String error = String::FromFormat("Unable to restore the saved game.\n%s",
err->FullMessage().GetCStr());
// currently AGS cannot properly revert to stable state if some of the
// game data was released or overwritten by the data from save file,
// this is why we tell engine to shutdown if that happened.
if (data_overwritten)
quitprintf(error);
else
Display(error);
return false;
}
return true;
}
void start_skipping_cutscene () {
play.fast_forward = 1;
// if a drop-down icon bar is up, remove it as it will pause the game
if (ifacepopped>=0)
remove_popup_interface(ifacepopped);
// if a text message is currently displayed, remove it
if (is_text_overlay > 0)
remove_screen_overlay(OVER_TEXTMSG);
}
void check_skip_cutscene_keypress (int kgn) {
if ((play.in_cutscene > 0) && (play.in_cutscene != 3)) {
if ((kgn != 27) && ((play.in_cutscene == 1) || (play.in_cutscene == 5)))
;
else
start_skipping_cutscene();
}
}
// Helper functions used by StartCutscene/EndCutscene, but also
// by SkipUntilCharacterStops
void initialize_skippable_cutscene() {
play.end_cutscene_music = -1;
}
void stop_fast_forwarding() {
// when the skipping of a cutscene comes to an end, update things
play.fast_forward = 0;
setpal();
if (play.end_cutscene_music >= 0)
newmusic(play.end_cutscene_music);
// Restore actual volume of sounds
for (int aa = 0; aa < MAX_SOUND_CHANNELS; aa++)
{
if ((channels[aa] != NULL) && (!channels[aa]->done))
{
channels[aa]->set_mute(false);
}
}
update_music_volume();
}
// allowHotspot0 defines whether Hotspot 0 returns LOCTYPE_HOTSPOT
// or whether it returns 0
int __GetLocationType(int xxx,int yyy, int allowHotspot0) {
getloctype_index = 0;
// If it's not in ProcessClick, then return 0 when over a GUI
if ((GetGUIAt(xxx, yyy) >= 0) && (getloctype_throughgui == 0))
return 0;
getloctype_throughgui = 0;
xxx += offsetx;
yyy += offsety;
if ((xxx>=thisroom.Width) | (xxx<0) | (yyy<0) | (yyy>=thisroom.Height))
return 0;
// check characters, objects and walkbehinds, work out which is
// foremost visible to the player
int charat = is_pos_on_character(xxx,yyy);
int hsat = get_hotspot_at(xxx,yyy);
int objat = GetObjectAt(xxx - offsetx, yyy - offsety);
int wbat = thisroom.WalkBehindMask->GetPixel(xxx, yyy);
if (wbat <= 0) wbat = 0;
else wbat = croom->walkbehind_base[wbat];
int winner = 0;
// if it's an Ignore Walkbehinds object, then ignore the walkbehind
if ((objat >= 0) && ((objs[objat].flags & OBJF_NOWALKBEHINDS) != 0))
wbat = 0;
if ((charat >= 0) && ((game.chars[charat].flags & CHF_NOWALKBEHINDS) != 0))
wbat = 0;
if ((charat >= 0) && (objat >= 0)) {
if ((wbat > obj_lowest_yp) && (wbat > char_lowest_yp))
winner = LOCTYPE_HOTSPOT;
else if (obj_lowest_yp > char_lowest_yp)
winner = LOCTYPE_OBJ;
else
winner = LOCTYPE_CHAR;
}
else if (charat >= 0) {
if (wbat > char_lowest_yp)
winner = LOCTYPE_HOTSPOT;
else
winner = LOCTYPE_CHAR;
}
else if (objat >= 0) {
if (wbat > obj_lowest_yp)
winner = LOCTYPE_HOTSPOT;
else
winner = LOCTYPE_OBJ;
}
if (winner == 0) {
if (hsat >= 0)
winner = LOCTYPE_HOTSPOT;
}
if ((winner == LOCTYPE_HOTSPOT) && (!allowHotspot0) && (hsat == 0))
winner = 0;
if (winner == LOCTYPE_HOTSPOT)
getloctype_index = hsat;
else if (winner == LOCTYPE_CHAR)
getloctype_index = charat;
else if (winner == LOCTYPE_OBJ)
getloctype_index = objat;
return winner;
}
// Called whenever game looses input focus
void display_switch_out()
{
switched_away = true;
clear_input_buffer();
// Always unlock mouse when switching out from the game
Mouse::UnlockFromWindow();
platform->DisplaySwitchOut();
platform->ExitFullscreenMode();
}
void display_switch_out_suspend()
{
// this is only called if in SWITCH_PAUSE mode
//debug_script_warn("display_switch_out");
display_switch_out();
switching_away_from_game++;
platform->PauseApplication();
// allow background running temporarily to halt the sound
if (set_display_switch_mode(SWITCH_BACKGROUND) == -1)
set_display_switch_mode(SWITCH_BACKAMNESIA);
// stop the sound stuttering
for (int i = 0; i <= MAX_SOUND_CHANNELS; i++) {
if ((channels[i] != NULL) && (channels[i]->done == 0)) {
channels[i]->pause();
}
}
rest(1000);
// restore the callbacks
SetMultitasking(0);
switching_away_from_game--;
}
// Called whenever game gets input focus
void display_switch_in()
{
switched_away = false;
if (gfxDriver)
{
DisplayMode mode = gfxDriver->GetDisplayMode();
if (!mode.Windowed)
platform->EnterFullscreenMode(mode);
}
platform->DisplaySwitchIn();
clear_input_buffer();
// If auto lock option is set, lock mouse to the game window
if (usetup.mouse_auto_lock && scsystem.windowed)
Mouse::TryLockToWindow();
}
void display_switch_in_resume()
{
display_switch_in();
for (int i = 0; i <= MAX_SOUND_CHANNELS; i++) {
if ((channels[i] != NULL) && (channels[i]->done == 0)) {
channels[i]->resume();
}
}
// This can cause a segfault on Linux
#if !defined (LINUX_VERSION)
if (gfxDriver->UsesMemoryBackBuffer()) // make sure all borders are cleared
gfxDriver->ClearRectangle(0, 0, game.size.Width - 1, game.size.Height - 1, NULL);
#endif
platform->ResumeApplication();
}
void replace_tokens(const char*srcmes,char*destm, int maxlen) {
int indxdest=0,indxsrc=0;
const char*srcp;
char *destp;
while (srcmes[indxsrc]!=0) {
srcp=&srcmes[indxsrc];
destp=&destm[indxdest];
if ((strncmp(srcp,"@IN",3)==0) | (strncmp(srcp,"@GI",3)==0)) {
int tokentype=0;
if (srcp[1]=='I') tokentype=1;
else tokentype=2;
int inx=atoi(&srcp[3]);
srcp++;
indxsrc+=2;
while (srcp[0]!='@') {
if (srcp[0]==0) quit("!Display: special token not terminated");
srcp++;
indxsrc++;
}
char tval[10];
if (tokentype==1) {
if ((inx<1) | (inx>=game.numinvitems))
quit("!Display: invalid inv item specified in @IN@");
sprintf(tval,"%d",playerchar->inv[inx]);
}
else {
if ((inx<0) | (inx>=MAXGSVALUES))
quit("!Display: invalid global int index speicifed in @GI@");
sprintf(tval,"%d",GetGlobalInt(inx));
}
strcpy(destp,tval);
indxdest+=strlen(tval);
}
else {
destp[0]=srcp[0];
indxdest++;
indxsrc++;
}
if (indxdest >= maxlen - 3)
break;
}
destm[indxdest]=0;
}
const char *get_global_message (int msnum) {
if (game.messages[msnum-500] == NULL)
return "";
return get_translation(game.messages[msnum-500]);
}
void get_message_text (int msnum, char *buffer, char giveErr) {
int maxlen = 9999;
if (!giveErr)
maxlen = MAX_MAXSTRLEN;
if (msnum>=500) { //quit("global message requseted, nto yet supported");
if ((msnum >= MAXGLOBALMES + 500) || (game.messages[msnum-500]==NULL)) {
if (giveErr)
quit("!DisplayGlobalMessage: message does not exist");
buffer[0] = 0;
return;
}
buffer[0] = 0;
replace_tokens(get_translation(game.messages[msnum-500]), buffer, maxlen);
return;
}
else if (msnum < 0 || (size_t)msnum >= thisroom.MessageCount) {
if (giveErr)
quit("!DisplayMessage: Invalid message number to display");
buffer[0] = 0;
return;
}
buffer[0]=0;
replace_tokens(get_translation(thisroom.Messages[msnum]), buffer, maxlen);
}
bool unserialize_audio_script_object(int index, const char *objectType, const char *serializedData, int dataSize)
{
if (strcmp(objectType, "AudioChannel") == 0)
{
ccDynamicAudio.Unserialize(index, serializedData, dataSize);
}
else if (strcmp(objectType, "AudioClip") == 0)
{
ccDynamicAudioClip.Unserialize(index, serializedData, dataSize);
}
else
{
return false;
}
return true;
}
//=============================================================================
//
// Script API Functions
//
//=============================================================================
#include "debug/out.h"
#include "script/script_api.h"
#include "script/script_runtime.h"
// int (int audioType);
RuntimeScriptValue Sc_Game_IsAudioPlaying(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_PINT(Game_IsAudioPlaying);
}
// void (int audioType, int volumeDrop)
RuntimeScriptValue Sc_Game_SetAudioTypeSpeechVolumeDrop(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT2(Game_SetAudioTypeSpeechVolumeDrop);
}
// void (int audioType, int volume, int changeType)
RuntimeScriptValue Sc_Game_SetAudioTypeVolume(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT3(Game_SetAudioTypeVolume);
}
// void (int audioType)
RuntimeScriptValue Sc_Game_StopAudio(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT(Game_StopAudio);
}
// int (const char *newFilename)
RuntimeScriptValue Sc_Game_ChangeTranslation(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_POBJ(Game_ChangeTranslation, const char);
}
// int (const char *token)
RuntimeScriptValue Sc_Game_DoOnceOnly(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_POBJ(Game_DoOnceOnly, const char);
}
// int (int red, int grn, int blu)
RuntimeScriptValue Sc_Game_GetColorFromRGB(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_PINT3(Game_GetColorFromRGB);
}
// int (int viewNumber, int loopNumber)
RuntimeScriptValue Sc_Game_GetFrameCountForLoop(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_PINT2(Game_GetFrameCountForLoop);
}
// const char* (int x, int y)
RuntimeScriptValue Sc_Game_GetLocationName(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ_PINT2(const char, myScriptStringImpl, Game_GetLocationName);
}
// int (int viewNumber)
RuntimeScriptValue Sc_Game_GetLoopCountForView(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_PINT(Game_GetLoopCountForView);
}
// int ()
RuntimeScriptValue Sc_Game_GetMODPattern(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetMODPattern);
}
// int (int viewNumber, int loopNumber)
RuntimeScriptValue Sc_Game_GetRunNextSettingForLoop(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_PINT2(Game_GetRunNextSettingForLoop);
}
// const char* (int slnum)
RuntimeScriptValue Sc_Game_GetSaveSlotDescription(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetSaveSlotDescription);
}
// ScriptViewFrame* (int viewNumber, int loopNumber, int frame)
RuntimeScriptValue Sc_Game_GetViewFrame(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJAUTO_PINT3(ScriptViewFrame, Game_GetViewFrame);
}
// const char* (const char *msg)
RuntimeScriptValue Sc_Game_InputBox(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ_POBJ(const char, myScriptStringImpl, Game_InputBox, const char);
}
// int (const char *newFolder)
RuntimeScriptValue Sc_Game_SetSaveGameDirectory(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_POBJ(Game_SetSaveGameDirectory, const char);
}
// void (int evenAmbient);
RuntimeScriptValue Sc_StopAllSounds(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT(StopAllSounds);
}
// int ()
RuntimeScriptValue Sc_Game_GetCharacterCount(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetCharacterCount);
}
// int ()
RuntimeScriptValue Sc_Game_GetDialogCount(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetDialogCount);
}
// const char *()
RuntimeScriptValue Sc_Game_GetFileName(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ(const char, myScriptStringImpl, Game_GetFileName);
}
// int ()
RuntimeScriptValue Sc_Game_GetFontCount(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetFontCount);
}
// const char* (int index)
RuntimeScriptValue Sc_Game_GetGlobalMessages(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetGlobalMessages);
}
/*
// [DEPRECATED] const char* (int index)
RuntimeScriptValue Sc_Game_GetGlobalStrings(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ_PINT(const char, myScriptStringImpl, Game_GetGlobalStrings);
}
*/
/*
// [DEPRECATED] void (int index, char *newval);
RuntimeScriptValue Sc_SetGlobalString(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT_POBJ(SetGlobalString, const char);
}
*/
// int ()
RuntimeScriptValue Sc_Game_GetGUICount(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetGUICount);
}
// int ()
RuntimeScriptValue Sc_Game_GetIgnoreUserInputAfterTextTimeoutMs(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetIgnoreUserInputAfterTextTimeoutMs);
}
// void (int newValueMs)
RuntimeScriptValue Sc_Game_SetIgnoreUserInputAfterTextTimeoutMs(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT(Game_SetIgnoreUserInputAfterTextTimeoutMs);
}
// int ()
RuntimeScriptValue Sc_Game_GetInSkippableCutscene(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetInSkippableCutscene);
}
// int ()
RuntimeScriptValue Sc_Game_GetInventoryItemCount(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetInventoryItemCount);
}
// int ()
RuntimeScriptValue Sc_Game_GetMinimumTextDisplayTimeMs(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetMinimumTextDisplayTimeMs);
}
// void (int newTextMinTime)
RuntimeScriptValue Sc_Game_SetMinimumTextDisplayTimeMs(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT(Game_SetMinimumTextDisplayTimeMs);
}
// int ()
RuntimeScriptValue Sc_Game_GetMouseCursorCount(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetMouseCursorCount);
}
// const char *()
RuntimeScriptValue Sc_Game_GetName(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ(const char, myScriptStringImpl, Game_GetName);
}
// void (const char *newName)
RuntimeScriptValue Sc_Game_SetName(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_POBJ(Game_SetName, const char);
}
// int ()
RuntimeScriptValue Sc_Game_GetNormalFont(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetNormalFont);
}
// void (int fontnum);
RuntimeScriptValue Sc_SetNormalFont(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT(SetNormalFont);
}
// int ()
RuntimeScriptValue Sc_Game_GetSkippingCutscene(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetSkippingCutscene);
}
// int ()
RuntimeScriptValue Sc_Game_GetSpeechFont(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetSpeechFont);
}
// void (int fontnum);
RuntimeScriptValue Sc_SetSpeechFont(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT(SetSpeechFont);
}
// int (int spriteNum)
RuntimeScriptValue Sc_Game_GetSpriteWidth(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_PINT(Game_GetSpriteWidth);
}
// int (int spriteNum)
RuntimeScriptValue Sc_Game_GetSpriteHeight(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT_PINT(Game_GetSpriteHeight);
}
// int ()
RuntimeScriptValue Sc_Game_GetTextReadingSpeed(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetTextReadingSpeed);
}
// void (int newTextSpeed)
RuntimeScriptValue Sc_Game_SetTextReadingSpeed(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_VOID_PINT(Game_SetTextReadingSpeed);
}
// const char* ()
RuntimeScriptValue Sc_Game_GetTranslationFilename(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ(const char, myScriptStringImpl, Game_GetTranslationFilename);
}
// int ()
RuntimeScriptValue Sc_Game_GetViewCount(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_INT(Game_GetViewCount);
}
RuntimeScriptValue Sc_Game_GetAudioClipCount(const RuntimeScriptValue *params, int32_t param_count)
{
API_VARGET_INT(game.audioClipCount);
}
RuntimeScriptValue Sc_Game_GetAudioClip(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_OBJ_PINT(ScriptAudioClip, ccDynamicAudioClip, Game_GetAudioClip);
}
RuntimeScriptValue Sc_Game_IsPluginLoaded(const RuntimeScriptValue *params, int32_t param_count)
{
API_SCALL_BOOL_OBJ(pl_is_plugin_loaded, const char);
}
void RegisterGameAPI()
{
ccAddExternalStaticFunction("Game::IsAudioPlaying^1", Sc_Game_IsAudioPlaying);
ccAddExternalStaticFunction("Game::SetAudioTypeSpeechVolumeDrop^2", Sc_Game_SetAudioTypeSpeechVolumeDrop);
ccAddExternalStaticFunction("Game::SetAudioTypeVolume^3", Sc_Game_SetAudioTypeVolume);
ccAddExternalStaticFunction("Game::StopAudio^1", Sc_Game_StopAudio);
ccAddExternalStaticFunction("Game::ChangeTranslation^1", Sc_Game_ChangeTranslation);
ccAddExternalStaticFunction("Game::DoOnceOnly^1", Sc_Game_DoOnceOnly);
ccAddExternalStaticFunction("Game::GetColorFromRGB^3", Sc_Game_GetColorFromRGB);
ccAddExternalStaticFunction("Game::GetFrameCountForLoop^2", Sc_Game_GetFrameCountForLoop);
ccAddExternalStaticFunction("Game::GetLocationName^2", Sc_Game_GetLocationName);
ccAddExternalStaticFunction("Game::GetLoopCountForView^1", Sc_Game_GetLoopCountForView);
ccAddExternalStaticFunction("Game::GetMODPattern^0", Sc_Game_GetMODPattern);
ccAddExternalStaticFunction("Game::GetRunNextSettingForLoop^2", Sc_Game_GetRunNextSettingForLoop);
ccAddExternalStaticFunction("Game::GetSaveSlotDescription^1", Sc_Game_GetSaveSlotDescription);
ccAddExternalStaticFunction("Game::GetViewFrame^3", Sc_Game_GetViewFrame);
ccAddExternalStaticFunction("Game::InputBox^1", Sc_Game_InputBox);
ccAddExternalStaticFunction("Game::SetSaveGameDirectory^1", Sc_Game_SetSaveGameDirectory);
ccAddExternalStaticFunction("Game::StopSound^1", Sc_StopAllSounds);
ccAddExternalStaticFunction("Game::get_CharacterCount", Sc_Game_GetCharacterCount);
ccAddExternalStaticFunction("Game::get_DialogCount", Sc_Game_GetDialogCount);
ccAddExternalStaticFunction("Game::get_FileName", Sc_Game_GetFileName);
ccAddExternalStaticFunction("Game::get_FontCount", Sc_Game_GetFontCount);
ccAddExternalStaticFunction("Game::geti_GlobalMessages", Sc_Game_GetGlobalMessages);
//ccAddExternalStaticFunction("Game::geti_GlobalStrings", Sc_Game_GetGlobalStrings);// [DEPRECATED]
//ccAddExternalStaticFunction("Game::seti_GlobalStrings", Sc_SetGlobalString);// [DEPRECATED]
ccAddExternalStaticFunction("Game::get_GUICount", Sc_Game_GetGUICount);
ccAddExternalStaticFunction("Game::get_IgnoreUserInputAfterTextTimeoutMs", Sc_Game_GetIgnoreUserInputAfterTextTimeoutMs);
ccAddExternalStaticFunction("Game::set_IgnoreUserInputAfterTextTimeoutMs", Sc_Game_SetIgnoreUserInputAfterTextTimeoutMs);
ccAddExternalStaticFunction("Game::get_InSkippableCutscene", Sc_Game_GetInSkippableCutscene);
ccAddExternalStaticFunction("Game::get_InventoryItemCount", Sc_Game_GetInventoryItemCount);
ccAddExternalStaticFunction("Game::get_MinimumTextDisplayTimeMs", Sc_Game_GetMinimumTextDisplayTimeMs);
ccAddExternalStaticFunction("Game::set_MinimumTextDisplayTimeMs", Sc_Game_SetMinimumTextDisplayTimeMs);
ccAddExternalStaticFunction("Game::get_MouseCursorCount", Sc_Game_GetMouseCursorCount);
ccAddExternalStaticFunction("Game::get_Name", Sc_Game_GetName);
ccAddExternalStaticFunction("Game::set_Name", Sc_Game_SetName);
ccAddExternalStaticFunction("Game::get_NormalFont", Sc_Game_GetNormalFont);
ccAddExternalStaticFunction("Game::set_NormalFont", Sc_SetNormalFont);
ccAddExternalStaticFunction("Game::get_SkippingCutscene", Sc_Game_GetSkippingCutscene);
ccAddExternalStaticFunction("Game::get_SpeechFont", Sc_Game_GetSpeechFont);
ccAddExternalStaticFunction("Game::set_SpeechFont", Sc_SetSpeechFont);
ccAddExternalStaticFunction("Game::geti_SpriteWidth", Sc_Game_GetSpriteWidth);
ccAddExternalStaticFunction("Game::geti_SpriteHeight", Sc_Game_GetSpriteHeight);
ccAddExternalStaticFunction("Game::get_TextReadingSpeed", Sc_Game_GetTextReadingSpeed);
ccAddExternalStaticFunction("Game::set_TextReadingSpeed", Sc_Game_SetTextReadingSpeed);
ccAddExternalStaticFunction("Game::get_TranslationFilename", Sc_Game_GetTranslationFilename);
ccAddExternalStaticFunction("Game::get_ViewCount", Sc_Game_GetViewCount);
ccAddExternalStaticFunction("Game::get_AudioClipCount", Sc_Game_GetAudioClipCount);
ccAddExternalStaticFunction("Game::geti_AudioClips", Sc_Game_GetAudioClip);
ccAddExternalStaticFunction("Game::IsPluginLoaded", Sc_Game_IsPluginLoaded);
/* ----------------------- Registering unsafe exports for plugins -----------------------*/
ccAddExternalFunctionForPlugin("Game::IsAudioPlaying^1", (void*)Game_IsAudioPlaying);
ccAddExternalFunctionForPlugin("Game::SetAudioTypeSpeechVolumeDrop^2", (void*)Game_SetAudioTypeSpeechVolumeDrop);
ccAddExternalFunctionForPlugin("Game::SetAudioTypeVolume^3", (void*)Game_SetAudioTypeVolume);
ccAddExternalFunctionForPlugin("Game::StopAudio^1", (void*)Game_StopAudio);
ccAddExternalFunctionForPlugin("Game::ChangeTranslation^1", (void*)Game_ChangeTranslation);
ccAddExternalFunctionForPlugin("Game::DoOnceOnly^1", (void*)Game_DoOnceOnly);
ccAddExternalFunctionForPlugin("Game::GetColorFromRGB^3", (void*)Game_GetColorFromRGB);
ccAddExternalFunctionForPlugin("Game::GetFrameCountForLoop^2", (void*)Game_GetFrameCountForLoop);
ccAddExternalFunctionForPlugin("Game::GetLocationName^2", (void*)Game_GetLocationName);
ccAddExternalFunctionForPlugin("Game::GetLoopCountForView^1", (void*)Game_GetLoopCountForView);
ccAddExternalFunctionForPlugin("Game::GetMODPattern^0", (void*)Game_GetMODPattern);
ccAddExternalFunctionForPlugin("Game::GetRunNextSettingForLoop^2", (void*)Game_GetRunNextSettingForLoop);
ccAddExternalFunctionForPlugin("Game::GetSaveSlotDescription^1", (void*)Game_GetSaveSlotDescription);
ccAddExternalFunctionForPlugin("Game::GetViewFrame^3", (void*)Game_GetViewFrame);
ccAddExternalFunctionForPlugin("Game::InputBox^1", (void*)Game_InputBox);
ccAddExternalFunctionForPlugin("Game::SetSaveGameDirectory^1", (void*)Game_SetSaveGameDirectory);
ccAddExternalFunctionForPlugin("Game::StopSound^1", (void*)StopAllSounds);
ccAddExternalFunctionForPlugin("Game::get_CharacterCount", (void*)Game_GetCharacterCount);
ccAddExternalFunctionForPlugin("Game::get_DialogCount", (void*)Game_GetDialogCount);
ccAddExternalFunctionForPlugin("Game::get_FileName", (void*)Game_GetFileName);
ccAddExternalFunctionForPlugin("Game::get_FontCount", (void*)Game_GetFontCount);
ccAddExternalFunctionForPlugin("Game::geti_GlobalMessages", (void*)Game_GetGlobalMessages);
//ccAddExternalFunctionForPlugin("Game::geti_GlobalStrings", (void*)Game_GetGlobalStrings);// [DEPRECATED]
//ccAddExternalFunctionForPlugin("Game::seti_GlobalStrings", (void*)SetGlobalString);// [DEPRECATED]
ccAddExternalFunctionForPlugin("Game::get_GUICount", (void*)Game_GetGUICount);
ccAddExternalFunctionForPlugin("Game::get_IgnoreUserInputAfterTextTimeoutMs", (void*)Game_GetIgnoreUserInputAfterTextTimeoutMs);
ccAddExternalFunctionForPlugin("Game::set_IgnoreUserInputAfterTextTimeoutMs", (void*)Game_SetIgnoreUserInputAfterTextTimeoutMs);
ccAddExternalFunctionForPlugin("Game::get_InSkippableCutscene", (void*)Game_GetInSkippableCutscene);
ccAddExternalFunctionForPlugin("Game::get_InventoryItemCount", (void*)Game_GetInventoryItemCount);
ccAddExternalFunctionForPlugin("Game::get_MinimumTextDisplayTimeMs", (void*)Game_GetMinimumTextDisplayTimeMs);
ccAddExternalFunctionForPlugin("Game::set_MinimumTextDisplayTimeMs", (void*)Game_SetMinimumTextDisplayTimeMs);
ccAddExternalFunctionForPlugin("Game::get_MouseCursorCount", (void*)Game_GetMouseCursorCount);
ccAddExternalFunctionForPlugin("Game::get_Name", (void*)Game_GetName);
ccAddExternalFunctionForPlugin("Game::set_Name", (void*)Game_SetName);
ccAddExternalFunctionForPlugin("Game::get_NormalFont", (void*)Game_GetNormalFont);
ccAddExternalFunctionForPlugin("Game::set_NormalFont", (void*)SetNormalFont);
ccAddExternalFunctionForPlugin("Game::get_SkippingCutscene", (void*)Game_GetSkippingCutscene);
ccAddExternalFunctionForPlugin("Game::get_SpeechFont", (void*)Game_GetSpeechFont);
ccAddExternalFunctionForPlugin("Game::set_SpeechFont", (void*)SetSpeechFont);
ccAddExternalFunctionForPlugin("Game::geti_SpriteWidth", (void*)Game_GetSpriteWidth);
ccAddExternalFunctionForPlugin("Game::geti_SpriteHeight", (void*)Game_GetSpriteHeight);
ccAddExternalFunctionForPlugin("Game::get_TextReadingSpeed", (void*)Game_GetTextReadingSpeed);
ccAddExternalFunctionForPlugin("Game::set_TextReadingSpeed", (void*)Game_SetTextReadingSpeed);
ccAddExternalFunctionForPlugin("Game::get_TranslationFilename", (void*)Game_GetTranslationFilename);
ccAddExternalFunctionForPlugin("Game::get_ViewCount", (void*)Game_GetViewCount);
}
void RegisterStaticObjects()
{
ccAddExternalStaticObject("game",&play, &GameStaticManager);
ccAddExternalStaticObject("mouse",&scmouse, &scmouse);
ccAddExternalStaticObject("palette",&palette[0], &GlobalStaticManager); // TODO: proper manager
ccAddExternalStaticObject("system",&scsystem, &scsystem);
// [OBSOLETE] legacy arrays
ccAddExternalStaticObject("gs_globals", &play.globalvars[0], &GlobalStaticManager);
ccAddExternalStaticObject("savegameindex",&play.filenumbers[0], &GlobalStaticManager);
}
| 80,934 | 26,988 |
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <chrono>
#ifdef MEM_STATS
#include <string>
#endif
#include <wasi/libc-environ.h>
// TODO: remove these once the warnings are fixed
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#include "js/CompilationAndEvaluation.h"
#include "js/ContextOptions.h"
#include "js/Initialization.h"
#include "js/SourceText.h"
#pragma clang diagnostic pop
#include "js-compute-builtins.h"
#include "wizer.h"
#ifdef MEM_STATS
#include "memory-reporting.h"
#endif
using std::chrono::duration_cast;
using std::chrono::microseconds;
using std::chrono::system_clock;
using JS::Value;
using JS::RootedValue;
using JS::RootedObject;
using JS::RootedString;
using JS::HandleValue;
using JS::HandleValueArray;
using JS::HandleObject;
using JS::MutableHandleValue;
using JS::PersistentRooted;
using JS::PersistentRootedVector;
#ifdef MEM_STATS
size_t size_of_cb(const void* ptr) {
return ptr ? sizeof(ptr) : 0;
}
static bool dump_mem_stats(JSContext* cx) {
SimpleJSRuntimeStats rtStats(&size_of_cb);
if (!JS::CollectRuntimeStats(cx, &rtStats, nullptr, false))
return false;
std::string rtPath = "rt";
size_t rtTotal;
ReportJSRuntimeExplicitTreeStats(rtStats, rtPath, nullptr, false, &rtTotal);
printf("compartment counts: %zu sys, %zu usr\n", JS::SystemCompartmentCount(cx), JS::UserCompartmentCount(cx));
printf("GC heap total: %zu\n", size_t(JS_GetGCParameter(cx, JSGC_TOTAL_CHUNKS)) * js::gc::ChunkSize);
printf("GC heap unused: %zu\n", size_t(JS_GetGCParameter(cx, JSGC_UNUSED_CHUNKS)) * js::gc::ChunkSize);
return true;
}
#endif // MEM_STATS
/* The class of the global object. */
static JSClass global_class = {
"global",
JSCLASS_GLOBAL_FLAGS,
&JS::DefaultGlobalClassOps
};
bool INITIALIZED = false;
JSContext* CONTEXT = nullptr;
JS::PersistentRootedObject GLOBAL;
JS::PersistentRootedObject unhandledRejectedPromises;
static JS::PersistentRootedObjectVector* FETCH_HANDLERS;
void gc_callback(JSContext* cx, JSGCStatus status, JS::GCReason reason, void* data) {
if (debug_logging_enabled())
printf("gc for reason %s, %s\n", JS::ExplainGCReason(reason), status ? "end" : "start");
}
static void rejection_tracker(JSContext* cx, bool mutedErrors, JS::HandleObject promise,
JS::PromiseRejectionHandlingState state, void* data)
{
RootedValue promiseVal(cx, JS::ObjectValue(*promise));
switch (state) {
case JS::PromiseRejectionHandlingState::Unhandled: {
if (!JS::SetAdd(cx, unhandledRejectedPromises, promiseVal)) {
// Note: we unconditionally print these, since they almost always indicate serious bugs.
fprintf(stderr, "Adding an unhandled rejected promise to the promise "
"rejection tracker failed");
}
return;
}
case JS::PromiseRejectionHandlingState::Handled: {
bool deleted = false;
if (!JS::SetDelete(cx, unhandledRejectedPromises, promiseVal, &deleted)) {
// Note: we unconditionally print these, since they almost always indicate serious bugs.
fprintf(stderr, "Removing an handled rejected promise from the promise "
"rejection tracker failed");
}
}
}
}
bool init_js() {
JS_Init();
JSContext *cx = JS_NewContext(JS::DefaultHeapMaxBytes);
if (!cx)
return false;
if (!js::UseInternalJobQueues(cx) || !JS::InitSelfHostedCode(cx))
return false;
JS::ContextOptionsRef(cx)
.setPrivateClassFields(true)
.setPrivateClassMethods(true)
.setErgnomicBrandChecks(true);
// TODO: check if we should set a different creation zone.
JS::RealmOptions options;
options.creationOptions()
.setStreamsEnabled(true)
.setReadableByteStreamsEnabled(true)
.setBYOBStreamReadersEnabled(true)
.setReadableStreamPipeToEnabled(true)
.setWritableStreamsEnabled(true)
.setIteratorHelpersEnabled(true)
.setWeakRefsEnabled(JS::WeakRefSpecifier::EnabledWithoutCleanupSome);
JS::DisableIncrementalGC(cx);
// JS_SetGCParameter(cx, JSGC_MAX_EMPTY_CHUNK_COUNT, 1);
RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::FireOnNewGlobalHook,
options));
if (!global)
return false;
JSAutoRealm ar(cx, global);
if (!JS::InitRealmStandardClasses(cx))
return false;
JS::SetPromiseRejectionTrackerCallback(cx, rejection_tracker);
CONTEXT = cx;
GLOBAL.init(cx, global);
unhandledRejectedPromises.init(cx, JS::NewSetObject(cx));
if (!unhandledRejectedPromises)
return false;
return true;
}
static bool report_unhandled_promise_rejections(JSContext* cx) {
RootedValue iterable(cx);
if (!JS::SetValues(cx, unhandledRejectedPromises, &iterable))
return false;
JS::ForOfIterator it(cx);
if (!it.init(iterable))
return false;
RootedValue promise_val(cx);
RootedObject promise(cx);
while (true) {
bool done;
if (!it.next(&promise_val, &done))
return false;
if (done)
break;
promise = &promise_val.toObject();
// Note: we unconditionally print these, since they almost always indicate serious bugs.
fprintf(stderr, "Promise rejected but never handled: ");
RootedValue result(cx, JS::GetPromiseResult(promise));
dump_promise_rejection(cx, result, promise, stderr);
}
return true;
}
static void DumpPendingException(JSContext* cx, const char* description) {
JS::ExceptionStack exception(cx);
if (!JS::GetPendingExceptionStack(cx, &exception)) {
fprintf(stderr, "Error: exception pending after %s, but got another error "
"when trying to retrieve it. Aborting.\n", description);
} else {
fprintf(stderr, "Exception while %s: ", description);
dump_value(cx, exception.exception(), stderr);
print_stack(cx, exception.stack(), stderr);
}
}
static void abort(JSContext* cx, const char* description) {
// Note: we unconditionally print messages here, since they almost always indicate serious bugs.
if (JS_IsExceptionPending(cx)) {
DumpPendingException(cx, description);
} else {
fprintf(stderr, "Error while %s, but no exception is pending. "
"Aborting, since that doesn't seem recoverable at all.\n", description);
}
if (JS::SetSize(cx, unhandledRejectedPromises) > 0) {
fprintf(stderr,
"Additionally, some promises were rejected, but the rejection never handled:\n");
report_unhandled_promise_rejections(cx);
}
// Respond with status `500` if no response was ever sent.
HandleObject fetch_event = FetchEvent::instance();
if (INITIALIZED && !FetchEvent::response_started(fetch_event))
FetchEvent::respondWithError(cx, fetch_event);
fflush(stderr);
exit(1);
}
bool eval_stdin(JSContext* cx, MutableHandleValue result) {
char* code = NULL;
size_t len = 0;
if (getdelim(&code, &len, EOF, stdin) < 0) {
return false;
}
JS::CompileOptions opts(cx);
opts.setForceFullParse();
// TODO: investigate passing a filename to Wizer and using that here to improve diagnostics.
// TODO: furthermore, investigate whether Wizer by now allows us to pass an actual path
// and open that, instead of having to redirect `stdin` for a subprocess of `js-compute-runtime`.
opts.setFileAndLine("<stdin>", 1);
JS::SourceText<mozilla::Utf8Unit> srcBuf;
if (!srcBuf.init(cx, code, strlen(code), JS::SourceOwnership::TakeOwnership)) {
return false;
}
JS::RootedScript script(cx);
{
// Disabling GGC during compilation seems to slightly reduce the number of
// pages touched post-deploy.
// (Whereas disabling it during execution below meaningfully increases it,
// which is why this is scoped to just compilation.)
JS::AutoDisableGenerationalGC noGGC(cx);
script = JS::Compile(cx, opts, srcBuf);
if (!script) return false;
}
// TODO: verify that it's better to perform a shrinking GC here, as manual testing
// indicates. Running a shrinking GC here causes *fewer* 4kb pages to be written to when
// processing a request, at least for one fairly large input script.
//
// A hypothesis for why this is the case could be that the objects allocated by parsing
// the script (but not evaluating it) tend to be read-only, so optimizing them for
// compactness makes sense and doesn't fragment writes later on.
JS::PrepareForFullGC(cx);
JS::NonIncrementalGC(cx, JS::GCOptions::Shrink, JS::GCReason::API);
// Execute the top-level script.
if (!JS_ExecuteScript(cx, script, result))
return false;
// Ensure that any pending promise reactions are run before taking the snapshot.
while (js::HasJobsPending(cx)) {
js::RunJobs(cx);
if (JS_IsExceptionPending(cx))
abort(cx, "running Promise reactions");
}
// Report any promise rejections that weren't handled before snapshotting.
// TODO: decide whether we should abort in this case, instead of just reporting.
if (JS::SetSize(cx, unhandledRejectedPromises) > 0) {
report_unhandled_promise_rejections(cx);
}
// TODO: check if it makes sense to increase the empty chunk count *before* running GC like this.
// The working theory is that otherwise the engine might mark chunk pages as free that then later
// the allocator doesn't turn into chunks without further fragmentation. But that might be wrong.
// JS_SetGCParameter(cx, JSGC_MAX_EMPTY_CHUNK_COUNT, 10);
// TODO: verify that it's better to *not* perform a shrinking GC here, as manual testing
// indicates. Running a shrinking GC here causes *more* 4kb pages to be written to when
// processing a request, at least for one fairly large input script.
//
// A hypothesis for why this is the case could be that most writes are to object kinds that are
// initially allocated in the same vicinity, but that the shrinking GC causes them to be
// intermingled with other objects. I.e., writes become more fragmented due to the shrinking GC.
JS::PrepareForFullGC(cx);
JS::NonIncrementalGC(cx, JS::GCOptions::Normal, JS::GCReason::API);
// Ignore the first GC, but then print all others, because ideally GCs
// should be rare, and developers should know about them.
// TODO: consider exposing a way to parameterize this, and/or specifying a dedicated log target
// for telemetry messages like this.
JS_SetGCCallback(cx, gc_callback, nullptr);
return true;
}
static bool addEventListener(JSContext* cx, unsigned argc, Value* vp) {
JS::CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, "addEventListener", 2))
return false;
size_t event_len;
JS::UniqueChars event_chars = encode(cx, args[0], &event_len);
if (!event_chars) return false;
if (strncmp(event_chars.get(), "fetch", event_len)) {
fprintf(stderr, "Error: addEventListener only supports the event 'fetch' right now, "
"but got event '%s'\n", event_chars.get());
exit(1);
}
RootedValue val(cx, args[1]);
if (!val.isObject() || !JS_ObjectIsFunction(&val.toObject())) {
fprintf(stderr, "Error: addEventListener: Argument 2 is not a function.\n");
exit(1);
}
return FETCH_HANDLERS->append(&val.toObject());
}
void init() {
assert(!INITIALIZED);
if (!init_js())
exit(1);
JSContext* cx = CONTEXT;
RootedObject global(cx, GLOBAL);
JSAutoRealm ar(cx, global);
FETCH_HANDLERS = new JS::PersistentRootedObjectVector(cx);
define_fastly_sys(cx, global);
if (!JS_DefineFunction(cx, global, "addEventListener", addEventListener, 2, 0))
exit(1);
RootedValue result(cx);
if (!eval_stdin(cx, &result))
abort(cx, "evaluating JS");
if (!FetchEvent::create(cx))
exit(1);
if (FETCH_HANDLERS->length() == 0) {
RootedValue val(cx);
if (!JS_GetProperty(cx, global, "onfetch", &val) ||
!val.isObject() || !JS_ObjectIsFunction(&val.toObject()))
{
// The error message only mentions `addEventListener`, even though we also support
// an `onfetch` top-level function as an alternative. We're treating the latter
// as undocumented functionality for the time being.
fprintf(stderr, "Error: no `fetch` event handler registered during initialization. "
"Make sure to call `addEventListener('fetch', your_handler)`.\n");
exit(1);
}
if (!FETCH_HANDLERS->append(&val.toObject()))
abort(cx, "Adding onfetch as a fetch event handler");
}
fflush(stdout);
fflush(stderr);
// Define this to print a simple memory usage report.
#ifdef MEM_STATS
dump_mem_stats(cx);
#endif
INITIALIZED = true;
}
WIZER_INIT(init);
static void dispatch_fetch_event(JSContext* cx, HandleObject event, double* total_compute) {
auto pre_handler = system_clock::now();
FetchEvent::start_dispatching(event);
RootedValue result(cx);
RootedValue event_val(cx, JS::ObjectValue(*event));
HandleValueArray argsv = HandleValueArray(event_val);
RootedValue handler(cx);
RootedValue rval(cx);
for (size_t i = 0; i < FETCH_HANDLERS->length(); i++) {
handler.setObject(*(*FETCH_HANDLERS)[i]);
if (!JS_CallFunctionValue(cx, GLOBAL, handler, argsv, &rval)) {
DumpPendingException(cx, "dispatching FetchEvent\n");
JS_ClearPendingException(cx);
}
if (FetchEvent::state(event) != FetchEvent::State::unhandled)
break;
}
FetchEvent::stop_dispatching(event);
double diff = duration_cast<microseconds>(system_clock::now() - pre_handler).count();
*total_compute += diff;
if (debug_logging_enabled())
printf("Request handler took %fms\n", diff / 1000);
}
static void process_pending_jobs(JSContext* cx, double* total_compute) {
auto pre_reactions = system_clock::now();
if (debug_logging_enabled()) {
printf("Running promise reactions\n");
fflush(stdout);
}
while (js::HasJobsPending(cx)) {
js::RunJobs(cx);
if (JS_IsExceptionPending(cx))
abort(cx, "running Promise reactions");
}
double diff = duration_cast<microseconds>(system_clock::now() - pre_reactions).count();
*total_compute += diff;
if (debug_logging_enabled())
printf("Running promise reactions took %fms\n", diff / 1000);
}
static void wait_for_backends(JSContext* cx, double* total_compute) {
if (!has_pending_requests())
return;
auto pre_requests = system_clock::now();
if (debug_logging_enabled()) {
printf("Waiting for backends ...\n");
fflush(stdout);
}
if (!process_network_io(cx))
abort(cx, "processing network requests");
double diff = duration_cast<microseconds>(system_clock::now() - pre_requests).count();
if (debug_logging_enabled())
printf("Done, waited for %fms\n", diff / 1000);
}
int main(int argc, const char *argv[]) {
if (!INITIALIZED) {
init();
assert(INITIALIZED);
// fprintf(stderr, "js.wasm must be initialized with a JS source file using Wizer\n");
// exit(-1);
}
double total_compute = 0;
auto start = system_clock::now();
__wasilibc_initialize_environ();
if (debug_logging_enabled()) {
printf("Running JS handleRequest function for C@E service version %s\n",
getenv("FASTLY_SERVICE_VERSION"));
fflush(stdout);
}
JSContext* cx = CONTEXT;
JSAutoRealm ar(cx, GLOBAL);
js::ResetMathRandomSeed(cx);
HandleObject fetch_event = FetchEvent::instance();
FetchEvent::init_request(cx, fetch_event);
dispatch_fetch_event(cx, fetch_event, &total_compute);
// Loop until no more resolved promises or backend requests are pending.
if (debug_logging_enabled()) {
printf("Start processing async jobs ...\n");
fflush(stdout);
}
do {
// First, drain the promise reactions queue.
process_pending_jobs(cx, &total_compute);
// Then, check if the fetch event is still active, i.e. had pending promises
// added to it using `respondWith` or `waitUntil`.
if (!FetchEvent::is_active(fetch_event))
break;
// Process async tasks.
wait_for_backends(cx, &total_compute);
} while (js::HasJobsPending(cx) || has_pending_requests());
if (debug_logging_enabled() && has_pending_requests()) {
fprintf(stderr, "Service terminated with async tasks pending. "
"Use FetchEvent#waitUntil to extend the service's lifetime if needed.\n");
}
if (JS::SetSize(cx, unhandledRejectedPromises) > 0) {
report_unhandled_promise_rejections(cx);
// Respond with status `500` if any promise rejections were left unhandled
// and no response was ever sent.
if (!FetchEvent::response_started(fetch_event))
FetchEvent::respondWithError(cx, fetch_event);
}
auto end = system_clock::now();
double diff = duration_cast<microseconds>(end - start).count();
if (debug_logging_enabled()) {
printf("Done. Total request processing time: %fms. Total compute time: %fms\n",
diff / 1000, total_compute / 1000);
}
// Note: we deliberately skip shutdown, because it takes quite a while,
// and serves no purpose for us.
// TODO: investigate also skipping the destructors deliberately run in wizer.h.
// GLOBAL = nullptr;
// CONTEXT = nullptr;
// JS_DestroyContext(cx);
// JS_ShutDown();
return 0;
}
| 17,161 | 5,600 |
#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
vector<float> v(n + k + 10, 0.0);
vector<float> s(n + k + 10, 0.0);
vector<float> dp(n + k + 10, 0.0);
float tmp;
for (int i = 1; i <= n; i++)
{ //1オリジン
cin >> tmp;
v[i] = (1.0 + tmp) / 2.0;
}
//初期化
v[0] = 0.0;
if (k > 1)
{
for (int i = 1; i < k; i++)
{ //0番目からk-1番目までの和
s[0] += v[i];
}
}
else
{
s[0] = 0.0;
}
dp[0] = s[0];
for (int i = 1; i <= n; i++)
{ //余分に回して0を入れる
s[i] = s[i - 1] - v[i - 1] + v[i + k - 1]; //n+10の範囲を超えてる可能性があるので余裕もって配列を作る
if (s[i] > dp[i - 1])
{ //最大値を更新
dp[i] = s[i];
}
else
{ //更新しなかった
dp[i] = dp[i - 1];
}
}
cout << dp[n] << "\n";
return 0;
} | 1,003 | 506 |
/*
* BM3D denoising filter - VapourSynth plugin
* Copyright (C) 2015 mawen1250
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef VAGGREGATE_HPP_
#define VAGGREGATE_HPP_
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Template functions of class VAggregate_Process
template < typename _Dt1 >
void VAggregate_Process::process_core()
{
if (fi->colorFamily == cmGray || (
(fi->colorFamily == cmYUV || fi->colorFamily == cmYCoCg)
&& !process_plane[1] && !process_plane[2]
))
{
process_core_gray<_Dt1>();
}
else if (fi->colorFamily == cmYUV || fi->colorFamily == cmYCoCg)
{
process_core_yuv<_Dt1>();
}
}
template < typename _Dt1 >
void VAggregate_Process::process_core_gray()
{
FLType *dstYd;
std::vector<const FLType *> ResNumY, ResDenY;
// Get write pointer
auto dstY = reinterpret_cast<_Dt1 *>(vsapi->getWritePtr(dst, 0));
for (int i = 0, o = d.radius + f_offset; i < frames; ++i, --o)
{
// Get read pointer
auto srcY = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 0));
// Store pointer to floating point intermediate Y data into corresponding result vector
ResNumY.push_back(srcY + src_pcount[0] * (o * 2));
ResDenY.push_back(srcY + src_pcount[0] * (o * 2 + 1));
}
// Allocate memory for floating point Y data
AlignedMalloc(dstYd, dst_pcount[0]);
// Execute kernel
Kernel(dstYd, ResNumY, ResDenY);
// Convert dst from floating point Y data to integer Y data
Float2Int(dstY, dstYd, dst_height[0], dst_width[0], dst_stride[0], dst_stride[0], false, full, !isFloat(_Dt1));
// Free memory for floating point YUV data
AlignedFree(dstYd);
}
template <>
inline void VAggregate_Process::process_core_gray<FLType>()
{
std::vector<const FLType *> ResNumY, ResDenY;
// Get write pointer
auto dstY = reinterpret_cast<FLType *>(vsapi->getWritePtr(dst, 0));
for (int i = 0, o = d.radius + f_offset; i < frames; ++i, --o)
{
// Get read pointer
auto srcY = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 0));
// Store pointer to floating point intermediate Y data into corresponding result vector
ResNumY.push_back(srcY + src_pcount[0] * (o * 2));
ResDenY.push_back(srcY + src_pcount[0] * (o * 2 + 1));
}
// Execute kernel
Kernel(dstY, ResNumY, ResDenY);
}
template < typename _Dt1 >
void VAggregate_Process::process_core_yuv()
{
FLType *dstYd = nullptr, *dstUd = nullptr, *dstVd = nullptr;
std::vector<const FLType *> ResNumY, ResDenY;
std::vector<const FLType *> ResNumU, ResDenU;
std::vector<const FLType *> ResNumV, ResDenV;
// Get write pointer
auto dstY = reinterpret_cast<_Dt1 *>(vsapi->getWritePtr(dst, 0));
auto dstU = reinterpret_cast<_Dt1 *>(vsapi->getWritePtr(dst, 1));
auto dstV = reinterpret_cast<_Dt1 *>(vsapi->getWritePtr(dst, 2));
for (int i = 0, o = d.radius - b_offset; i < frames; ++i, --o)
{
// Get read pointer
auto srcY = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 0));
auto srcU = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 1));
auto srcV = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 2));
// Store pointer to floating point intermediate YUV data into corresponding result vector
ResNumY.push_back(srcY + src_pcount[0] * (o * 2));
ResNumU.push_back(srcU + src_pcount[1] * (o * 2));
ResNumV.push_back(srcV + src_pcount[2] * (o * 2));
ResDenY.push_back(srcY + src_pcount[0] * (o * 2 + 1));
ResDenU.push_back(srcU + src_pcount[1] * (o * 2 + 1));
ResDenV.push_back(srcV + src_pcount[2] * (o * 2 + 1));
}
// Allocate memory for floating point YUV data
if (process_plane[0]) AlignedMalloc(dstYd, dst_pcount[0]);
if (process_plane[1]) AlignedMalloc(dstUd, dst_pcount[1]);
if (process_plane[2]) AlignedMalloc(dstVd, dst_pcount[2]);
// Execute kernel
Kernel(dstYd, dstUd, dstVd, ResNumY, ResDenY, ResNumU, ResDenU, ResNumV, ResDenV);
// Convert dst from floating point YUV data to integer YUV data
if (process_plane[0]) Float2Int(dstY, dstYd, dst_height[0], dst_width[0], dst_stride[0], dst_stride[0], false, full, !isFloat(_Dt1));
if (process_plane[1]) Float2Int(dstU, dstUd, dst_height[1], dst_width[1], dst_stride[1], dst_stride[1], true, full, !isFloat(_Dt1));
if (process_plane[2]) Float2Int(dstV, dstVd, dst_height[2], dst_width[2], dst_stride[2], dst_stride[2], true, full, !isFloat(_Dt1));
// Free memory for floating point YUV data
if (process_plane[0]) AlignedFree(dstYd);
if (process_plane[1]) AlignedFree(dstUd);
if (process_plane[2]) AlignedFree(dstVd);
}
template <>
inline void VAggregate_Process::process_core_yuv<FLType>()
{
std::vector<const FLType *> ResNumY, ResDenY;
std::vector<const FLType *> ResNumU, ResDenU;
std::vector<const FLType *> ResNumV, ResDenV;
// Get write pointer
auto dstY = reinterpret_cast<FLType *>(vsapi->getWritePtr(dst, 0));
auto dstU = reinterpret_cast<FLType *>(vsapi->getWritePtr(dst, 1));
auto dstV = reinterpret_cast<FLType *>(vsapi->getWritePtr(dst, 2));
for (int i = 0, o = d.radius + f_offset; i < frames; ++i, --o)
{
// Get read pointer
auto srcY = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 0));
auto srcU = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 1));
auto srcV = reinterpret_cast<const FLType *>(vsapi->getReadPtr(v_src[i], 2));
// Store pointer to floating point intermediate YUV data into corresponding result vector
ResNumY.push_back(srcY + src_pcount[0] * (o * 2));
ResNumU.push_back(srcU + src_pcount[1] * (o * 2));
ResNumV.push_back(srcV + src_pcount[2] * (o * 2));
ResDenY.push_back(srcY + src_pcount[0] * (o * 2 + 1));
ResDenU.push_back(srcU + src_pcount[1] * (o * 2 + 1));
ResDenV.push_back(srcV + src_pcount[2] * (o * 2 + 1));
}
// Execute kernel
Kernel(dstY, dstU, dstV, ResNumY, ResDenY, ResNumU, ResDenU, ResNumV, ResDenV);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif
| 7,034 | 2,609 |
#include "MemBuffer.h"
//--------------------------------------------------------------------------------------------
// MemBufferDynamic
//--------------------------------------------------------------------------------------------
MemBufferDynamic::MemBufferDynamic()
: m_cursor(0)
, m_memblock(s_defaultSize)
, m_alignment(s_defaultAlignment)
{
}
MemBufferDynamic::MemBufferDynamic(size_t a_initialSize, size_t a_alignment)
: m_cursor(0)
, m_memblock(a_initialSize)
, m_alignment(a_alignment)
{
}
MemBufferDynamic::~MemBufferDynamic()
{
}
MemBufferDynamic::MemBufferDynamic(MemBufferDynamic const& a_other)
: m_cursor(a_other.m_cursor)
, m_memblock(a_other.m_memblock)
, m_alignment(a_other.m_alignment)
{
}
MemBufferDynamic& MemBufferDynamic::operator=(MemBufferDynamic const& a_other)
{
if (this != &a_other)
{
m_cursor = a_other.m_cursor;
m_memblock = a_other.m_memblock;
m_alignment = a_other.m_alignment;
}
return *this;
}
typename MemBufferDynamic::Index
MemBufferDynamic::Allocate(size_t a_size)
{
size_t newCursor = Dg::ForwardAlign<size_t>(m_cursor + a_size, m_alignment);
if (newCursor > m_memblock.size())
m_memblock.resize(newCursor);
size_t oldCursor = m_cursor;
m_cursor = newCursor;
return oldCursor;
}
void* MemBufferDynamic::GetAddress(Index a_index)
{
return m_memblock.data() + a_index;
}
void MemBufferDynamic::clear()
{
m_cursor = 0;
}
size_t MemBufferDynamic::size() const
{
return m_cursor;
}
//--------------------------------------------------------------------------------------------
// MemBuffer
//--------------------------------------------------------------------------------------------
MemBuffer::MemBuffer()
: m_memblock(nullptr)
, m_cursor(0)
, m_alignment(s_defaultAlignment)
, m_size(s_defaultSize)
{
m_memblock = (unsigned char*)malloc(m_size);
if (m_memblock == nullptr)
throw std::exception("MemBuffer failed to allocate!");
}
MemBuffer::MemBuffer(size_t a_size)
: m_memblock(nullptr)
, m_cursor(0)
, m_alignment(s_defaultAlignment)
, m_size(a_size)
{
m_memblock = (unsigned char*)malloc(m_size);
if (m_memblock == nullptr)
throw std::exception("MemBuffer failed to allocate!");
}
MemBuffer::MemBuffer(size_t a_size, size_t a_alignment)
: m_memblock(nullptr)
, m_cursor(0)
, m_alignment(a_alignment)
, m_size(a_size)
{
m_memblock = (unsigned char*)malloc(m_size);
if (m_memblock == nullptr)
throw std::exception("MemBuffer failed to allocate!");
}
MemBuffer::~MemBuffer()
{
free(m_memblock);
}
void* MemBuffer::Allocate(size_t a_size)
{
BSR_ASSERT(m_cursor + a_size < m_size, "MemBuffer out of memory!");
void* mem = &m_memblock[m_cursor];
m_cursor += a_size;
m_cursor = Dg::ForwardAlign<size_t>(m_cursor, m_alignment);
return mem;
}
void MemBuffer::clear()
{
m_cursor = 0;
}
size_t MemBuffer::size() const
{
return m_cursor;
} | 2,912 | 1,032 |
/*
-- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
@generated from zpotrf_mgpu.cpp normal z -> c, Fri Jan 30 19:00:13 2015
*/
#include "common_magma.h"
/**
Purpose
-------
CPOTRF computes the Cholesky factorization of a complex Hermitian
positive definite matrix dA.
The factorization has the form
dA = U**H * U, if UPLO = MagmaUpper, or
dA = L * L**H, if UPLO = MagmaLower,
where U is an upper triangular matrix and L is lower triangular.
This is the block version of the algorithm, calling Level 3 BLAS.
Arguments
---------
@param[in]
ngpu INTEGER
Number of GPUs to use. ngpu > 0.
@param[in]
uplo magma_uplo_t
- = MagmaUpper: Upper triangle of dA is stored;
- = MagmaLower: Lower triangle of dA is stored.
@param[in]
n INTEGER
The order of the matrix dA. N >= 0.
@param[in,out]
d_lA COMPLEX array of pointers on the GPU, dimension (ngpu)
On entry, the Hermitian matrix dA distributed over GPUs
(d_lA[d] points to the local matrix on the d-th GPU).
It is distributed in 1D block column or row cyclic (with the
block size of nb) if UPLO = MagmaUpper or MagmaLower, respectively.
If UPLO = MagmaUpper, the leading N-by-N upper triangular
part of dA contains the upper triangular part of the matrix dA,
and the strictly lower triangular part of dA is not referenced.
If UPLO = MagmaLower, the leading N-by-N lower triangular part
of dA contains the lower triangular part of the matrix dA, and
the strictly upper triangular part of dA is not referenced.
\n
On exit, if INFO = 0, the factor U or L from the Cholesky
factorization dA = U**H * U or dA = L * L**H.
@param[in]
ldda INTEGER
The leading dimension of the array d_lA. LDDA >= max(1,N).
To benefit from coalescent memory accesses LDDA must be
divisible by 16.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
- > 0: if INFO = i, the leading minor of order i is not
positive definite, and the factorization could not be
completed.
@ingroup magma_cposv_comp
********************************************************************/
extern "C" magma_int_t
magma_cpotrf_mgpu(
magma_int_t ngpu,
magma_uplo_t uplo, magma_int_t n,
magmaFloatComplex_ptr d_lA[], magma_int_t ldda,
magma_int_t *info)
{
magma_int_t j, nb, d, lddp, h;
const char* uplo_ = lapack_uplo_const( uplo );
magmaFloatComplex *work;
int upper = (uplo == MagmaUpper);
magmaFloatComplex *dwork[MagmaMaxGPUs];
magma_queue_t stream[MagmaMaxGPUs][3];
magma_event_t event[MagmaMaxGPUs][5];
*info = 0;
nb = magma_get_cpotrf_nb(n);
if (! upper && uplo != MagmaLower) {
*info = -1;
} else if (n < 0) {
*info = -2;
} else if (!upper) {
lddp = nb*(n/(nb*ngpu));
if ( n%(nb*ngpu) != 0 ) lddp += min(nb, n-ngpu*lddp);
if ( ldda < lddp ) *info = -4;
} else if ( ldda < n ) {
*info = -4;
}
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
magma_device_t orig_dev;
magma_getdevice( &orig_dev );
if (ngpu == 1 && ((nb <= 1) || (nb >= n)) ) {
/* Use unblocked code. */
magma_setdevice(0);
if (MAGMA_SUCCESS != magma_cmalloc_pinned( &work, n*nb )) {
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
magma_cgetmatrix( n, n, d_lA[0], ldda, work, n );
lapackf77_cpotrf(uplo_, &n, work, &n, info);
magma_csetmatrix( n, n, work, n, d_lA[0], ldda );
magma_free_pinned( work );
}
else {
lddp = nb*((n+nb-1)/nb);
for( d=0; d < ngpu; d++ ) {
magma_setdevice(d);
if (MAGMA_SUCCESS != magma_cmalloc( &dwork[d], ngpu*nb*lddp )) {
for( j=0; j < d; j++ ) {
magma_setdevice(j);
magma_free( dwork[j] );
}
*info = MAGMA_ERR_DEVICE_ALLOC;
return *info;
}
for( j=0; j < 3; j++ )
magma_queue_create( &stream[d][j] );
for( j=0; j < 5; j++ )
magma_event_create( &event[d][j] );
}
magma_setdevice(0);
h = 1; //ngpu; //(n+nb-1)/nb;
if (MAGMA_SUCCESS != magma_cmalloc_pinned( &work, n*nb*h )) {
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
if (upper) {
/* with three streams */
magma_cpotrf3_mgpu(ngpu, uplo, n, n, 0, 0, nb, d_lA, ldda, dwork, lddp, work, n,
h, stream, event, info);
} else {
/* with three streams */
magma_cpotrf3_mgpu(ngpu, uplo, n, n, 0, 0, nb, d_lA, ldda, dwork, lddp, work, nb*h,
h, stream, event, info);
}
/* clean up */
for( d=0; d < ngpu; d++ ) {
magma_setdevice(d);
for( j=0; j < 3; j++ ) {
magma_queue_sync( stream[d][j] );
magma_queue_destroy( stream[d][j] );
}
for( j=0; j < 5; j++ )
magma_event_destroy( event[d][j] );
magma_free( dwork[d] );
}
magma_free_pinned( work );
} /* end of not lapack */
magma_setdevice( orig_dev );
return *info;
} /* magma_cpotrf_mgpu */
| 5,880 | 2,120 |
#include <stdio.h>
#include <string.h>
#include "wrect.h"
#include "cl_dll.h"
#include "cl_util.h"
#include "cl_entity.h"
#include "const.h"
#include "parsemsg.h" // BEGIN_READ(), ...
#include "voice_status.h"
static CVoiceStatus *g_pInternalVoiceStatus = NULL;
// ---------------------------------------------------------------------- //
// The voice manager for the client.
// ---------------------------------------------------------------------- //
CVoiceStatus g_VoiceStatus;
CVoiceStatus* GetClientVoice()
{
return &g_VoiceStatus;
}
int __MsgFunc_VoiceMask(const char *pszName, int iSize, void *pbuf)
{
if(g_pInternalVoiceStatus)
g_pInternalVoiceStatus->HandleVoiceMaskMsg(iSize, pbuf);
return 1;
}
int __MsgFunc_ReqState(const char *pszName, int iSize, void *pbuf)
{
if(g_pInternalVoiceStatus)
g_pInternalVoiceStatus->HandleReqStateMsg(iSize, pbuf);
return 1;
}
int g_BannedPlayerPrintCount;
void ForEachBannedPlayer(char id[16])
{
char str[256];
sprintf(str, "Ban %d: %2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x\n",
g_BannedPlayerPrintCount++,
id[0], id[1], id[2], id[3],
id[4], id[5], id[6], id[7],
id[8], id[9], id[10], id[11],
id[12], id[13], id[14], id[15]
);
#ifdef _WIN32
strupr(str);
#endif
gEngfuncs.pfnConsolePrint(str);
}
void ShowBannedCallback()
{
if(g_pInternalVoiceStatus)
{
g_BannedPlayerPrintCount = 0;
gEngfuncs.pfnConsolePrint("------- BANNED PLAYERS -------\n");
g_pInternalVoiceStatus->GetBanMgr()->ForEachBannedPlayer(ForEachBannedPlayer);
gEngfuncs.pfnConsolePrint("------------------------------\n");
}
}
CVoiceStatus::CVoiceStatus()
{
m_bBanMgrInitialized = false;
m_LastUpdateServerState = 0;
m_bTalking = m_bServerAcked = false;
m_bServerModEnable = -1;
m_pchGameDir = NULL;
}
CVoiceStatus::~CVoiceStatus()
{
g_pInternalVoiceStatus = NULL;
if(m_pchGameDir)
{
if(m_bBanMgrInitialized)
{
m_BanMgr.SaveState(m_pchGameDir);
}
free(m_pchGameDir);
}
}
void CVoiceStatus::Init( IVoiceStatusHelper *pHelper)
{
// Setup the voice_modenable cvar.
gEngfuncs.pfnRegisterVariable("voice_modenable", "1", FCVAR_ARCHIVE);
gEngfuncs.pfnRegisterVariable("voice_clientdebug", "0", 0);
gEngfuncs.pfnAddCommand("voice_showbanned", ShowBannedCallback);
// Cache the game directory for use when we shut down
const char *pchGameDirT = gEngfuncs.pfnGetGameDirectory();
m_pchGameDir = (char *)malloc(strlen(pchGameDirT) + 1);
if(m_pchGameDir)
{
strcpy(m_pchGameDir, pchGameDirT);
}
if(m_pchGameDir)
{
m_BanMgr.Init(m_pchGameDir);
m_bBanMgrInitialized = true;
}
assert(!g_pInternalVoiceStatus);
g_pInternalVoiceStatus = this;
m_bInSquelchMode = false;
m_pHelper = pHelper;
HOOK_MESSAGE(VoiceMask);
HOOK_MESSAGE(ReqState);
GetClientVoiceHud()->Init(pHelper,this);
}
void CVoiceStatus::Frame(double frametime)
{
// check server banned players once per second
if(gEngfuncs.GetClientTime() - m_LastUpdateServerState > 1)
{
UpdateServerState(false);
}
}
void CVoiceStatus::StartSquelchMode()
{
if(m_bInSquelchMode)
return;
m_bInSquelchMode = true;
}
void CVoiceStatus::StopSquelchMode()
{
m_bInSquelchMode = false;
}
bool CVoiceStatus::IsInSquelchMode()
{
return m_bInSquelchMode;
}
void CVoiceStatus::UpdateServerState(bool bForce)
{
// Can't do anything when we're not in a level.
char const *pLevelName = gEngfuncs.pfnGetLevelName();
if( pLevelName[0] == 0 )
{
if( gEngfuncs.pfnGetCvarFloat("voice_clientdebug") )
{
gEngfuncs.pfnConsolePrint( "CVoiceStatus::UpdateServerState: pLevelName[0]==0\n" );
}
return;
}
int bCVarModEnable = !!gEngfuncs.pfnGetCvarFloat("voice_modenable");
if(bForce || m_bServerModEnable != bCVarModEnable)
{
m_bServerModEnable = bCVarModEnable;
char str[256];
_snprintf(str, sizeof(str), "VModEnable %d", m_bServerModEnable);
ServerCmd(str);
if(gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
char msg[256];
sprintf(msg, "CVoiceStatus::UpdateServerState: Sending '%s'\n", str);
gEngfuncs.pfnConsolePrint(msg);
}
}
char str[2048];
sprintf(str, "vban");
bool bChange = false;
for(uint32 dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++)
{
uint32 serverBanMask = 0;
uint32 banMask = 0;
for(uint32 i=0; i < 32; i++)
{
char playerID[16];
if(!gEngfuncs.GetPlayerUniqueID(i+1, playerID))
continue;
if(m_BanMgr.GetPlayerBan(playerID))
banMask |= 1 << i;
if(m_ServerBannedPlayers[dw*32 + i])
serverBanMask |= 1 << i;
}
if(serverBanMask != banMask)
bChange = true;
// Ok, the server needs to be updated.
char numStr[512];
sprintf(numStr, " %x", banMask);
strcat(str, numStr);
}
if(bChange || bForce)
{
if(gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
char msg[256];
sprintf(msg, "CVoiceStatus::UpdateServerState: Sending '%s'\n", str);
gEngfuncs.pfnConsolePrint(msg);
}
gEngfuncs.pfnServerCmdUnreliable(str); // Tell the server..
}
else
{
if (gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
gEngfuncs.pfnConsolePrint( "CVoiceStatus::UpdateServerState: no change\n" );
}
}
m_LastUpdateServerState = gEngfuncs.GetClientTime();
}
int CVoiceStatus::GetSpeakerStatus(int iPlayer)
{
bool bTalking = static_cast<bool>(m_VoicePlayers[iPlayer]);
char playerID[16];
qboolean id = gEngfuncs.GetPlayerUniqueID( iPlayer+1, playerID );
if(!id)
return VOICE_NEVERSPOKEN;
bool bBanned = m_BanMgr.GetPlayerBan( playerID );
bool bNeverSpoken = !m_VoiceEnabledPlayers[iPlayer];
if(bBanned)
{
return VOICE_BANNED;
}
else if(bNeverSpoken)
{
return VOICE_NEVERSPOKEN;
}
else if(bTalking)
{
return VOICE_TALKING;
}
else
return VOICE_NOTTALKING;
}
void CVoiceStatus::HandleVoiceMaskMsg(int iSize, void *pbuf)
{
BEGIN_READ( pbuf, iSize );
uint32 dw;
for(dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++)
{
m_AudiblePlayers.SetDWord(dw, (uint32)READ_LONG());
m_ServerBannedPlayers.SetDWord(dw, (uint32)READ_LONG());
if(gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
char str[256];
gEngfuncs.pfnConsolePrint("CVoiceStatus::HandleVoiceMaskMsg\n");
sprintf(str, " - m_AudiblePlayers[%d] = %lu\n", dw, m_AudiblePlayers.GetDWord(dw));
gEngfuncs.pfnConsolePrint(str);
sprintf(str, " - m_ServerBannedPlayers[%d] = %lu\n", dw, m_ServerBannedPlayers.GetDWord(dw));
gEngfuncs.pfnConsolePrint(str);
}
}
m_bServerModEnable = READ_BYTE();
}
void CVoiceStatus::HandleReqStateMsg(int iSize, void *pbuf)
{
if(gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
gEngfuncs.pfnConsolePrint("CVoiceStatus::HandleReqStateMsg\n");
}
UpdateServerState(true);
}
void CVoiceStatus::UpdateSpeakerStatus(int entindex, bool bTalking)
{
const char *levelName = gEngfuncs.pfnGetLevelName();
if (levelName && levelName[0])
{
if( gEngfuncs.pfnGetCvarFloat("voice_clientdebug") )
{
char msg[256];
_snprintf( msg, sizeof(msg), "CVoiceStatus::UpdateSpeakerStatus: ent %d talking = %d\n", entindex, bTalking );
gEngfuncs.pfnConsolePrint( msg );
}
// Is it the local player talking?
if( entindex == -1 )
{
m_bTalking = bTalking;
if( bTalking )
{
// Enable voice for them automatically if they try to talk.
gEngfuncs.pfnClientCmd( "voice_modenable 1" );
}
if ( !gEngfuncs.GetLocalPlayer() )
{
return;
}
int entindex = gEngfuncs.GetLocalPlayer()->index;
GetClientVoiceHud()->UpdateSpeakerStatus(-2,bTalking);
m_VoicePlayers[entindex-1] = m_bTalking;
m_VoiceEnabledPlayers[entindex-1]= true;
}
else if( entindex == -2 )
{
m_bServerAcked = bTalking;
}
else if(entindex >= 0 && entindex <= VOICE_MAX_PLAYERS)
{
int iClient = entindex - 1;
if(iClient < 0)
return;
GetClientVoiceHud()->UpdateSpeakerStatus(entindex,bTalking);
if(bTalking)
{
m_VoicePlayers[iClient] = true;
m_VoiceEnabledPlayers[iClient] = true;
}
else
{
m_VoicePlayers[iClient] = false;
}
}
GetClientVoiceHud()->RepositionLabels();
}
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the target client has been banned
// Input : playerID -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CVoiceStatus::IsPlayerBlocked(int iPlayer)
{
char playerID[16];
if (!gEngfuncs.GetPlayerUniqueID(iPlayer, playerID))
return false;
return m_BanMgr.GetPlayerBan(playerID);
}
//-----------------------------------------------------------------------------
// Purpose: returns true if the player can't hear the other client due to game rules (eg. the other team)
// Input : playerID -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CVoiceStatus::IsPlayerAudible(int iPlayer)
{
return !!m_AudiblePlayers[iPlayer-1];
}
//-----------------------------------------------------------------------------
// Purpose: blocks/unblocks the target client from being heard
// Input : playerID -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
void CVoiceStatus::SetPlayerBlockedState(int iPlayer, bool blocked)
{
if (gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
gEngfuncs.pfnConsolePrint( "CVoiceStatus::SetPlayerBlockedState part 1\n" );
}
char playerID[16];
if (!gEngfuncs.GetPlayerUniqueID(iPlayer, playerID))
return;
if (gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
gEngfuncs.pfnConsolePrint( "CVoiceStatus::SetPlayerBlockedState part 2\n" );
}
// Squelch or (try to) unsquelch this player.
if (gEngfuncs.pfnGetCvarFloat("voice_clientdebug"))
{
char str[256];
sprintf(str, "CVoiceStatus::SetPlayerBlockedState: setting player %d ban to %d\n", iPlayer, !m_BanMgr.GetPlayerBan(playerID));
gEngfuncs.pfnConsolePrint(str);
}
m_BanMgr.SetPlayerBan( playerID, blocked );
UpdateServerState(false);
}
| 10,031 | 4,306 |
/***************************************************************************
* Copyright 1998-2020 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 <memory>
#include "slg/bsdf/bsdf.h"
#include "slg/scene/scene.h"
#include "slg/lights/infinitelight.h"
using namespace std;
using namespace luxrays;
using namespace slg;
//------------------------------------------------------------------------------
// InfiniteLight
//------------------------------------------------------------------------------
InfiniteLight::InfiniteLight() :
imageMap(NULL), imageMapDistribution(nullptr), visibilityMapCache(nullptr) {
}
InfiniteLight::~InfiniteLight() {
delete imageMapDistribution;
delete visibilityMapCache;
}
void InfiniteLight::Preprocess() {
EnvLightSource::Preprocess();
const ImageMapStorage *imageMapStorage = imageMap->GetStorage();
vector<float> data(imageMap->GetWidth() * imageMap->GetHeight());
//float maxVal = -INFINITY;
//float minVal = INFINITY;
for (u_int y = 0; y < imageMap->GetHeight(); ++y) {
for (u_int x = 0; x < imageMap->GetWidth(); ++x) {
const u_int index = x + y * imageMap->GetWidth();
if (sampleUpperHemisphereOnly && (y > imageMap->GetHeight() / 2))
data[index] = 0.f;
else
data[index] = imageMapStorage->GetFloat(index);
if (!IsValid(data[index]))
throw runtime_error("Pixel (" + ToString(x) + ", " + ToString(y) + ") in infinite light has an invalid value: " + ToString(data[index]));
//maxVal = Max(data[index], maxVal);
//minVal = Min(data[index], minVal);
}
}
//SLG_LOG("InfiniteLight luminance Max=" << maxVal << " Min=" << minVal);
imageMapDistribution = new Distribution2D(&data[0], imageMap->GetWidth(), imageMap->GetHeight());
}
void InfiniteLight::GetPreprocessedData(const Distribution2D **imageMapDistributionData,
const EnvLightVisibilityCache **elvc) const {
if (imageMapDistributionData)
*imageMapDistributionData = imageMapDistribution;
if (elvc)
*elvc = visibilityMapCache;
}
float InfiniteLight::GetPower(const Scene &scene) const {
const float envRadius = GetEnvRadius(scene);
// TODO: I should consider sampleUpperHemisphereOnly here
return temperatureScale.Y() * gain.Y() * imageMap->GetSpectrumMeanY() *
(4.f * M_PI * M_PI * envRadius * envRadius);
}
UV InfiniteLight::GetEnvUV(const luxrays::Vector &dir) const {
UV uv;
const Vector localDir = Normalize(Inverse(lightToWorld) * -dir);
ToLatLongMapping(localDir, &uv.u, &uv.v);
return uv;
}
Spectrum InfiniteLight::GetRadiance(const Scene &scene,
const BSDF *bsdf, const Vector &dir,
float *directPdfA, float *emissionPdfW) const {
const Vector localDir = Normalize(Inverse(lightToWorld) * -dir);
float u, v, latLongMappingPdf;
ToLatLongMapping(localDir, &u, &v, &latLongMappingPdf);
if (latLongMappingPdf == 0.f)
return Spectrum();
const float distPdf = imageMapDistribution->Pdf(u, v);
if (directPdfA) {
if (!bsdf)
*directPdfA = 0.f;
else if (visibilityMapCache && visibilityMapCache->IsCacheEnabled(*bsdf)) {
*directPdfA = visibilityMapCache->Pdf(*bsdf, u, v) * latLongMappingPdf;
} else
*directPdfA = distPdf * latLongMappingPdf;
}
if (emissionPdfW) {
const float envRadius = GetEnvRadius(scene);
*emissionPdfW = distPdf * latLongMappingPdf / (M_PI * envRadius * envRadius);
}
return temperatureScale * gain * imageMap->GetSpectrum(UV(u, v));
}
Spectrum InfiniteLight::Emit(const Scene &scene,
const float time, const float u0, const float u1,
const float u2, const float u3, const float passThroughEvent,
Ray &ray, float &emissionPdfW,
float *directPdfA, float *cosThetaAtLight) const {
float uv[2];
float distPdf;
imageMapDistribution->SampleContinuous(u0, u1, uv, &distPdf);
if (distPdf == 0.f)
return Spectrum();
Vector localDir;
float latLongMappingPdf;
FromLatLongMapping(uv[0], uv[1], &localDir, &latLongMappingPdf);
if (latLongMappingPdf == 0.f)
return Spectrum();
// Compute the ray direction
const Vector rayDir = -Normalize(lightToWorld * localDir);
// Compute the ray origin
Vector x, y;
CoordinateSystem(-rayDir, &x, &y);
float d1, d2;
ConcentricSampleDisk(u2, u3, &d1, &d2);
const Point worldCenter = scene.dataSet->GetBSphere().center;
const float envRadius = GetEnvRadius(scene);
const Point pDisk = worldCenter + envRadius * (d1 * x + d2 * y);
const Point rayOrig = pDisk - envRadius * rayDir;
// Compute InfiniteLight ray weight
emissionPdfW = distPdf * latLongMappingPdf / (M_PI * envRadius * envRadius);
if (directPdfA)
*directPdfA = distPdf * latLongMappingPdf;
if (cosThetaAtLight)
*cosThetaAtLight = Dot(Normalize(worldCenter - rayOrig), rayDir);
const Spectrum result = temperatureScale * gain * imageMap->GetSpectrum(uv);
assert (!result.IsNaN() && !result.IsInf() && !result.IsNeg());
ray.Update(rayOrig, rayDir, time);
return result;
}
Spectrum InfiniteLight::Illuminate(const Scene &scene, const BSDF &bsdf,
const float time, const float u0, const float u1, const float passThroughEvent,
Ray &shadowRay, float &directPdfW,
float *emissionPdfW, float *cosThetaAtLight) const {
float uv[2];
float distPdf;
if (visibilityMapCache && visibilityMapCache->IsCacheEnabled(bsdf))
visibilityMapCache->Sample(bsdf, u0, u1, uv, &distPdf);
else
imageMapDistribution->SampleContinuous(u0, u1, uv, &distPdf);
if (distPdf == 0.f)
return Spectrum();
Vector localDir;
float latLongMappingPdf;
FromLatLongMapping(uv[0], uv[1], &localDir, &latLongMappingPdf);
if (latLongMappingPdf == 0.f)
return Spectrum();
const Vector shadowRayDir = Normalize(lightToWorld * localDir);
const Point worldCenter = scene.dataSet->GetBSphere().center;
const float envRadius = GetEnvRadius(scene);
const Point shadowRayOrig = bsdf.GetRayOrigin(shadowRayDir);
const Vector toCenter(worldCenter - shadowRayOrig);
const float centerDistanceSquared = Dot(toCenter, toCenter);
const float approach = Dot(toCenter, shadowRayDir);
const float shadowRayDistance = approach + sqrtf(Max(0.f, envRadius * envRadius -
centerDistanceSquared + approach * approach));
const Point emisPoint(shadowRayOrig + shadowRayDistance * shadowRayDir);
const Normal emisNormal(Normalize(worldCenter - emisPoint));
const float cosAtLight = Dot(emisNormal, -shadowRayDir);
if (cosAtLight < DEFAULT_COS_EPSILON_STATIC)
return Spectrum();
if (cosThetaAtLight)
*cosThetaAtLight = cosAtLight;
directPdfW = distPdf * latLongMappingPdf;
assert (!isnan(directPdfW) && !isinf(directPdfW) && (directPdfW > 0.f));
if (emissionPdfW)
*emissionPdfW = distPdf * latLongMappingPdf / (M_PI * envRadius * envRadius);
const Spectrum result = temperatureScale * gain * imageMap->GetSpectrum(UV(uv[0], uv[1]));
assert (!result.IsNaN() && !result.IsInf() && !result.IsNeg());
shadowRay = Ray(shadowRayOrig, shadowRayDir, 0.f, shadowRayDistance, time);
return result;
}
void InfiniteLight::UpdateVisibilityMap(const Scene *scene, const bool useRTMode) {
delete visibilityMapCache;
visibilityMapCache = nullptr;
if (useRTMode)
return;
if (useVisibilityMapCache) {
// Scale the infinitelight image map to the requested size
unique_ptr<ImageMap> luminanceMapImage(imageMap->Copy());
// Select the image luminance
luminanceMapImage->SelectChannel(ImageMapStorage::WEIGHTED_MEAN);
luminanceMapImage->Preprocess();
visibilityMapCache = new EnvLightVisibilityCache(scene, this,
luminanceMapImage.get(), visibilityMapCacheParams);
visibilityMapCache->Build();
}
}
Properties InfiniteLight::ToProperties(const ImageMapCache &imgMapCache, const bool useRealFileName) const {
const string prefix = "scene.lights." + GetName();
Properties props = EnvLightSource::ToProperties(imgMapCache, useRealFileName);
props.Set(Property(prefix + ".type")("infinite"));
const string fileName = useRealFileName ?
imageMap->GetName() : imgMapCache.GetSequenceFileName(imageMap);
props.Set(Property(prefix + ".file")(fileName));
props.Set(imageMap->ToProperties(prefix, false));
props.Set(Property(prefix + ".gamma")(1.f));
props.Set(Property(prefix + ".sampleupperhemisphereonly")(sampleUpperHemisphereOnly));
props.Set(Property(prefix + ".visibilitymapcache.enable")(useVisibilityMapCache));
if (useVisibilityMapCache)
props << EnvLightVisibilityCache::Params2Props(prefix, visibilityMapCacheParams);
return props;
}
| 9,514 | 3,178 |
/**
* \file PnlWzskShtDetail.cpp
* job handler for job PnlWzskShtDetail (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Emily Johnson (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#ifdef WZSKCMBD
#include <Wzskcmbd.h>
#else
#include <Wzskd.h>
#endif
#include "PnlWzskShtDetail.h"
#include "PnlWzskShtDetail_blks.cpp"
#include "PnlWzskShtDetail_evals.cpp"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
// IP ns.cust --- INSERT
/******************************************************************************
class PnlWzskShtDetail
******************************************************************************/
PnlWzskShtDetail::PnlWzskShtDetail(
XchgWzsk* xchg
, DbsWzsk* dbswzsk
, const ubigint jrefSup
, const uint ixWzskVLocale
) :
JobWzsk(xchg, VecWzskVJob::PNLWZSKSHTDETAIL, jrefSup, ixWzskVLocale)
{
jref = xchg->addJob(dbswzsk, this, jrefSup);
// IP constructor.cust1 --- INSERT
dirty = false;
// IP constructor.cust2 --- INSERT
xchg->addClstn(VecWzskVCall::CALLWZSKSHT_SESEQ, jref, Clstn::VecVJobmask::TREE, 0, false, Arg(), 0, Clstn::VecVJactype::LOCK);
xchg->addClstn(VecWzskVCall::CALLWZSKSHT_OBJEQ, jref, Clstn::VecVJobmask::TREE, 0, false, Arg(), 0, Clstn::VecVJactype::LOCK);
// IP constructor.cust3 --- INSERT
updatePreset(dbswzsk, VecWzskVPreset::PREWZSKREFSHT, jref);
};
PnlWzskShtDetail::~PnlWzskShtDetail() {
// IP destructor.spec --- INSERT
// IP destructor.cust --- INSERT
xchg->removeJobByJref(jref);
};
// IP cust --- INSERT
DpchEngWzsk* PnlWzskShtDetail::getNewDpchEng(
set<uint> items
) {
DpchEngWzsk* dpcheng = NULL;
if (items.empty()) {
dpcheng = new DpchEngWzskConfirm(true, jref, "");
} else {
insert(items, DpchEngData::JREF);
dpcheng = new DpchEngData(jref, &contiac, &continf, &statshr, items);
};
return dpcheng;
};
void PnlWzskShtDetail::refreshRecSht(
DbsWzsk* dbswzsk
, set<uint>& moditems
) {
ContIac oldContiac(contiac);
ContInf oldContinf(continf);
StatShr oldStatshr(statshr);
WzskMShot* _recSht = NULL;
if (dbswzsk->tblwzskmshot->loadRecByRef(recSht.ref, &_recSht)) {
recSht = *_recSht;
delete _recSht;
} else recSht = WzskMShot();
dirty = false;
continf.TxtSes = StubWzsk::getStubSesStd(dbswzsk, recSht.refWzskMSession, ixWzskVLocale, Stub::VecVNonetype::FULL);
continf.TxtObj = StubWzsk::getStubObjStd(dbswzsk, recSht.refWzskMObject, ixWzskVLocale, Stub::VecVNonetype::FULL);
contiac.TxfSta = Ftm::stamp(recSht.start);
contiac.TxfCmt = recSht.Comment;
statshr.TxtSesActive = evalTxtSesActive(dbswzsk);
statshr.ButSesViewAvail = evalButSesViewAvail(dbswzsk);
statshr.ButSesViewActive = evalButSesViewActive(dbswzsk);
statshr.TxtObjActive = evalTxtObjActive(dbswzsk);
statshr.ButObjViewAvail = evalButObjViewAvail(dbswzsk);
statshr.ButObjViewActive = evalButObjViewActive(dbswzsk);
statshr.TxfStaActive = evalTxfStaActive(dbswzsk);
statshr.TxfCmtActive = evalTxfCmtActive(dbswzsk);
if (contiac.diff(&oldContiac).size() != 0) insert(moditems, DpchEngData::CONTIAC);
if (continf.diff(&oldContinf).size() != 0) insert(moditems, DpchEngData::CONTINF);
if (statshr.diff(&oldStatshr).size() != 0) insert(moditems, DpchEngData::STATSHR);
};
void PnlWzskShtDetail::refresh(
DbsWzsk* dbswzsk
, set<uint>& moditems
, const bool unmute
) {
if (muteRefresh && !unmute) return;
muteRefresh = true;
StatShr oldStatshr(statshr);
// IP refresh --- BEGIN
// statshr
statshr.ButSaveAvail = evalButSaveAvail(dbswzsk);
statshr.ButSaveActive = evalButSaveActive(dbswzsk);
// IP refresh --- END
if (statshr.diff(&oldStatshr).size() != 0) insert(moditems, DpchEngData::STATSHR);
muteRefresh = false;
};
void PnlWzskShtDetail::updatePreset(
DbsWzsk* dbswzsk
, const uint ixWzskVPreset
, const ubigint jrefTrig
, const bool notif
) {
// IP updatePreset --- BEGIN
set<uint> moditems;
if (ixWzskVPreset == VecWzskVPreset::PREWZSKREFSHT) {
recSht.ref = xchg->getRefPreset(VecWzskVPreset::PREWZSKREFSHT, jref);
refreshRecSht(dbswzsk, moditems);
if (notif && !moditems.empty()) xchg->submitDpch(getNewDpchEng(moditems));
};
// IP updatePreset --- END
};
void PnlWzskShtDetail::handleRequest(
DbsWzsk* dbswzsk
, ReqWzsk* req
) {
if (req->ixVBasetype == ReqWzsk::VecVBasetype::CMD) {
reqCmd = req;
if (req->cmd == "cmdset") {
} else {
cout << "\tinvalid command!" << endl;
};
if (!req->retain) reqCmd = NULL;
} else if (req->ixVBasetype == ReqWzsk::VecVBasetype::DPCHAPP) {
if (req->dpchapp->ixWzskVDpch == VecWzskVDpch::DPCHAPPWZSKINIT) {
handleDpchAppWzskInit(dbswzsk, (DpchAppWzskInit*) (req->dpchapp), &(req->dpcheng));
} else if (req->dpchapp->ixWzskVDpch == VecWzskVDpch::DPCHAPPWZSKSHTDETAILDATA) {
DpchAppData* dpchappdata = (DpchAppData*) (req->dpchapp);
if (dpchappdata->has(DpchAppData::CONTIAC)) {
handleDpchAppDataContiac(dbswzsk, &(dpchappdata->contiac), &(req->dpcheng));
};
} else if (req->dpchapp->ixWzskVDpch == VecWzskVDpch::DPCHAPPWZSKSHTDETAILDO) {
DpchAppDo* dpchappdo = (DpchAppDo*) (req->dpchapp);
if (dpchappdo->ixVDo != 0) {
if (dpchappdo->ixVDo == VecVDo::BUTSAVECLICK) {
handleDpchAppDoButSaveClick(dbswzsk, &(req->dpcheng));
} else if (dpchappdo->ixVDo == VecVDo::BUTSESVIEWCLICK) {
handleDpchAppDoButSesViewClick(dbswzsk, &(req->dpcheng));
} else if (dpchappdo->ixVDo == VecVDo::BUTOBJVIEWCLICK) {
handleDpchAppDoButObjViewClick(dbswzsk, &(req->dpcheng));
};
};
};
};
};
void PnlWzskShtDetail::handleDpchAppWzskInit(
DbsWzsk* dbswzsk
, DpchAppWzskInit* dpchappwzskinit
, DpchEngWzsk** dpcheng
) {
*dpcheng = getNewDpchEng({DpchEngData::ALL});
};
void PnlWzskShtDetail::handleDpchAppDataContiac(
DbsWzsk* dbswzsk
, ContIac* _contiac
, DpchEngWzsk** dpcheng
) {
set<uint> diffitems;
set<uint> moditems;
diffitems = _contiac->diff(&contiac);
if (hasAny(diffitems, {ContIac::TXFSTA, ContIac::TXFCMT})) {
if (has(diffitems, ContIac::TXFSTA)) contiac.TxfSta = _contiac->TxfSta;
if (has(diffitems, ContIac::TXFCMT)) contiac.TxfCmt = _contiac->TxfCmt;
};
insert(moditems, DpchEngData::CONTIAC);
*dpcheng = getNewDpchEng(moditems);
};
void PnlWzskShtDetail::handleDpchAppDoButSaveClick(
DbsWzsk* dbswzsk
, DpchEngWzsk** dpcheng
) {
// IP handleDpchAppDoButSaveClick --- INSERT
};
void PnlWzskShtDetail::handleDpchAppDoButSesViewClick(
DbsWzsk* dbswzsk
, DpchEngWzsk** dpcheng
) {
ubigint jrefNew = 0;
string sref;
if (statshr.ButSesViewAvail && statshr.ButSesViewActive) {
if (xchg->getIxPreset(VecWzskVPreset::PREWZSKIXCRDACCSES, jref)) {
sref = "CrdWzskSes";
xchg->triggerIxRefSrefIntvalToRefCall(dbswzsk, VecWzskVCall::CALLWZSKCRDOPEN, jref, 0, 0, sref, recSht.refWzskMSession, jrefNew);
};
if (jrefNew == 0) *dpcheng = new DpchEngWzskConfirm(false, 0, "");
else *dpcheng = new DpchEngWzskConfirm(true, jrefNew, sref);
};
};
void PnlWzskShtDetail::handleDpchAppDoButObjViewClick(
DbsWzsk* dbswzsk
, DpchEngWzsk** dpcheng
) {
ubigint jrefNew = 0;
string sref;
if (statshr.ButObjViewAvail && statshr.ButObjViewActive) {
if (xchg->getIxPreset(VecWzskVPreset::PREWZSKIXCRDACCOBJ, jref)) {
sref = "CrdWzskObj";
xchg->triggerIxRefSrefIntvalToRefCall(dbswzsk, VecWzskVCall::CALLWZSKCRDOPEN, jref, 0, 0, sref, recSht.refWzskMObject, jrefNew);
};
if (jrefNew == 0) *dpcheng = new DpchEngWzskConfirm(false, 0, "");
else *dpcheng = new DpchEngWzskConfirm(true, jrefNew, sref);
};
};
void PnlWzskShtDetail::handleCall(
DbsWzsk* dbswzsk
, Call* call
) {
if (call->ixVCall == VecWzskVCall::CALLWZSKSHTUPD_REFEQ) {
call->abort = handleCallWzskShtUpd_refEq(dbswzsk, call->jref);
} else if (call->ixVCall == VecWzskVCall::CALLWZSKSHT_SESEQ) {
call->abort = handleCallWzskSht_sesEq(dbswzsk, call->jref, call->argInv.ref, call->argRet.boolval);
} else if (call->ixVCall == VecWzskVCall::CALLWZSKSHT_OBJEQ) {
call->abort = handleCallWzskSht_objEq(dbswzsk, call->jref, call->argInv.ref, call->argRet.boolval);
};
};
bool PnlWzskShtDetail::handleCallWzskShtUpd_refEq(
DbsWzsk* dbswzsk
, const ubigint jrefTrig
) {
bool retval = false;
// IP handleCallWzskShtUpd_refEq --- INSERT
return retval;
};
bool PnlWzskShtDetail::handleCallWzskSht_sesEq(
DbsWzsk* dbswzsk
, const ubigint jrefTrig
, const ubigint refInv
, bool& boolvalRet
) {
bool retval = false;
boolvalRet = (recSht.refWzskMSession == refInv); // IP handleCallWzskSht_sesEq --- LINE
return retval;
};
bool PnlWzskShtDetail::handleCallWzskSht_objEq(
DbsWzsk* dbswzsk
, const ubigint jrefTrig
, const ubigint refInv
, bool& boolvalRet
) {
bool retval = false;
boolvalRet = (recSht.refWzskMObject == refInv); // IP handleCallWzskSht_objEq --- LINE
return retval;
};
| 8,854 | 4,228 |
//==- UnreachableCodeChecker.cpp - Generalized dead code checker -*- C++ -*-==//
//
// The LLVM37 Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This file implements a generalized unreachable code checker using a
// path-sensitive analysis. We mark any path visited, and then walk the CFG as a
// post-analysis to determine what was never visited.
//
// A similar flow-sensitive only check exists in Analysis/ReachableCode.cpp
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/AST/ParentMap.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/SourceManager.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
#include "llvm37/ADT/SmallSet.h"
// The number of CFGBlock pointers we want to reserve memory for. This is used
// once for each function we analyze.
#define DEFAULT_CFGBLOCKS 256
using namespace clang;
using namespace ento;
namespace {
class UnreachableCodeChecker : public Checker<check::EndAnalysis> {
public:
void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
ExprEngine &Eng) const;
private:
typedef llvm37::SmallSet<unsigned, DEFAULT_CFGBLOCKS> CFGBlocksSet;
static inline const Stmt *getUnreachableStmt(const CFGBlock *CB);
static void FindUnreachableEntryPoints(const CFGBlock *CB,
CFGBlocksSet &reachable,
CFGBlocksSet &visited);
static bool isInvalidPath(const CFGBlock *CB, const ParentMap &PM);
static inline bool isEmptyCFGBlock(const CFGBlock *CB);
};
}
void UnreachableCodeChecker::checkEndAnalysis(ExplodedGraph &G,
BugReporter &B,
ExprEngine &Eng) const {
CFGBlocksSet reachable, visited;
if (Eng.hasWorkRemaining())
return;
const Decl *D = nullptr;
CFG *C = nullptr;
ParentMap *PM = nullptr;
const LocationContext *LC = nullptr;
// Iterate over ExplodedGraph
for (ExplodedGraph::node_iterator I = G.nodes_begin(), E = G.nodes_end();
I != E; ++I) {
const ProgramPoint &P = I->getLocation();
LC = P.getLocationContext();
if (!LC->inTopFrame())
continue;
if (!D)
D = LC->getAnalysisDeclContext()->getDecl();
// Save the CFG if we don't have it already
if (!C)
C = LC->getAnalysisDeclContext()->getUnoptimizedCFG();
if (!PM)
PM = &LC->getParentMap();
if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
const CFGBlock *CB = BE->getBlock();
reachable.insert(CB->getBlockID());
}
}
// Bail out if we didn't get the CFG or the ParentMap.
if (!D || !C || !PM)
return;
// Don't do anything for template instantiations. Proving that code
// in a template instantiation is unreachable means proving that it is
// unreachable in all instantiations.
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
if (FD->isTemplateInstantiation())
return;
// Find CFGBlocks that were not covered by any node
for (CFG::const_iterator I = C->begin(), E = C->end(); I != E; ++I) {
const CFGBlock *CB = *I;
// Check if the block is unreachable
if (reachable.count(CB->getBlockID()))
continue;
// Check if the block is empty (an artificial block)
if (isEmptyCFGBlock(CB))
continue;
// Find the entry points for this block
if (!visited.count(CB->getBlockID()))
FindUnreachableEntryPoints(CB, reachable, visited);
// This block may have been pruned; check if we still want to report it
if (reachable.count(CB->getBlockID()))
continue;
// Check for false positives
if (CB->size() > 0 && isInvalidPath(CB, *PM))
continue;
// It is good practice to always have a "default" label in a "switch", even
// if we should never get there. It can be used to detect errors, for
// instance. Unreachable code directly under a "default" label is therefore
// likely to be a false positive.
if (const Stmt *label = CB->getLabel())
if (label->getStmtClass() == Stmt::DefaultStmtClass)
continue;
// Special case for __builtin_unreachable.
// FIXME: This should be extended to include other unreachable markers,
// such as llvm37_unreachable.
if (!CB->empty()) {
bool foundUnreachable = false;
for (CFGBlock::const_iterator ci = CB->begin(), ce = CB->end();
ci != ce; ++ci) {
if (Optional<CFGStmt> S = (*ci).getAs<CFGStmt>())
if (const CallExpr *CE = dyn_cast<CallExpr>(S->getStmt())) {
if (CE->getBuiltinCallee() == Builtin::BI__builtin_unreachable) {
foundUnreachable = true;
break;
}
}
}
if (foundUnreachable)
continue;
}
// We found a block that wasn't covered - find the statement to report
SourceRange SR;
PathDiagnosticLocation DL;
SourceLocation SL;
if (const Stmt *S = getUnreachableStmt(CB)) {
SR = S->getSourceRange();
DL = PathDiagnosticLocation::createBegin(S, B.getSourceManager(), LC);
SL = DL.asLocation();
if (SR.isInvalid() || !SL.isValid())
continue;
}
else
continue;
// Check if the SourceLocation is in a system header
const SourceManager &SM = B.getSourceManager();
if (SM.isInSystemHeader(SL) || SM.isInExternCSystemHeader(SL))
continue;
B.EmitBasicReport(D, this, "Unreachable code", "Dead code",
"This statement is never executed", DL, SR);
}
}
// Recursively finds the entry point(s) for this dead CFGBlock.
void UnreachableCodeChecker::FindUnreachableEntryPoints(const CFGBlock *CB,
CFGBlocksSet &reachable,
CFGBlocksSet &visited) {
visited.insert(CB->getBlockID());
for (CFGBlock::const_pred_iterator I = CB->pred_begin(), E = CB->pred_end();
I != E; ++I) {
if (!*I)
continue;
if (!reachable.count((*I)->getBlockID())) {
// If we find an unreachable predecessor, mark this block as reachable so
// we don't report this block
reachable.insert(CB->getBlockID());
if (!visited.count((*I)->getBlockID()))
// If we haven't previously visited the unreachable predecessor, recurse
FindUnreachableEntryPoints(*I, reachable, visited);
}
}
}
// Find the Stmt* in a CFGBlock for reporting a warning
const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) {
for (CFGBlock::const_iterator I = CB->begin(), E = CB->end(); I != E; ++I) {
if (Optional<CFGStmt> S = I->getAs<CFGStmt>())
return S->getStmt();
}
if (const Stmt *S = CB->getTerminator())
return S;
else
return nullptr;
}
// Determines if the path to this CFGBlock contained an element that infers this
// block is a false positive. We assume that FindUnreachableEntryPoints has
// already marked only the entry points to any dead code, so we need only to
// find the condition that led to this block (the predecessor of this block.)
// There will never be more than one predecessor.
bool UnreachableCodeChecker::isInvalidPath(const CFGBlock *CB,
const ParentMap &PM) {
// We only expect a predecessor size of 0 or 1. If it is >1, then an external
// condition has broken our assumption (for example, a sink being placed by
// another check). In these cases, we choose not to report.
if (CB->pred_size() > 1)
return true;
// If there are no predecessors, then this block is trivially unreachable
if (CB->pred_size() == 0)
return false;
const CFGBlock *pred = *CB->pred_begin();
if (!pred)
return false;
// Get the predecessor block's terminator conditon
const Stmt *cond = pred->getTerminatorCondition();
//assert(cond && "CFGBlock's predecessor has a terminator condition");
// The previous assertion is invalid in some cases (eg do/while). Leaving
// reporting of these situations on at the moment to help triage these cases.
if (!cond)
return false;
// Run each of the checks on the conditions
if (containsMacro(cond) || containsEnum(cond)
|| containsStaticLocal(cond) || containsBuiltinOffsetOf(cond)
|| containsStmt<UnaryExprOrTypeTraitExpr>(cond))
return true;
return false;
}
// Returns true if the given CFGBlock is empty
bool UnreachableCodeChecker::isEmptyCFGBlock(const CFGBlock *CB) {
return CB->getLabel() == nullptr // No labels
&& CB->size() == 0 // No statements
&& !CB->getTerminator(); // No terminator
}
void ento::registerUnreachableCodeChecker(CheckerManager &mgr) {
mgr.registerChecker<UnreachableCodeChecker>();
}
| 9,377 | 2,952 |
# Python program for implementation of heap Sort
# To heapify subtree rooted at index i.
# n is size of heap
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and arr[i] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# Driver code to test above
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
# This code is contributed by Mohit Kumra
| 1,134 | 504 |
/*!
* Copyright (c) 2018 by Contributors
* \file random/sgx_random_engine.h
* \brief SGX trusted random engine
*/
#include <dmlc/logging.h>
#include <sgx_trts.h>
#include <algorithm>
#include <cmath>
#include "../../runtime/sgx/common.h"
namespace tvm {
namespace contrib {
/*!
* \brief An interface for generating [tensors of] random numbers.
*/
class RandomEngine {
public:
/*!
* \brief Creates a RandomEngine, suggesting the use of a provided seed.
*/
explicit RandomEngine(unsigned seed) {
LOG(WARNING) << "SGX RandomEngine does not support seeding.";
}
/*!
* \brief Seeds the underlying RNG, if possible.
*/
inline void Seed(unsigned seed) {
LOG(WARNING) << "SGX RandomEngine does not support seeding.";
}
/*!
* \return the seed associated with the underlying RNG.
*/
inline unsigned GetSeed() const {
LOG(WARNING) << "SGX RandomEngine does not support seeding.";
return 0;
}
/*!
* \return a random integer sampled from the RNG.
*/
inline unsigned GetRandInt() {
int rand_int;
TVM_SGX_CHECKED_CALL(
sgx_read_rand(reinterpret_cast<unsigned char*>(&rand_int), sizeof(int)));
return rand_int;
}
/*!
* \return a random integer sampled from Unif(low, high).
*/
inline float GetUniform(float low, float high) {
float max_int = static_cast<float>(std::numeric_limits<unsigned>::max());
float unif01 = GetRandInt() / max_int;
return low + unif01 * (high - low);
}
/*!
* \return a random value sampled from Normal(loc, scale**2).
*/
inline float GetNormal(float loc, float scale) {
float sign = GetUniform(-1, 1);
float sample = GetStandardNormalOneside();
return loc + (sign > 0 ? scale : -scale) * sample;
}
/*!
* \brief Fills a tensor with values drawn from Unif(low, high)
*/
void SampleUniform(DLTensor* data, float low, float high) {
CHECK_GT(high, low) << "high must be bigger than low";
CHECK(data->strides == nullptr);
DLDataType dtype = data->dtype;
int64_t size = 1;
for (int i = 0; i < data->ndim; ++i) {
size *= data->shape[i];
}
CHECK(dtype.code == kDLFloat && dtype.bits == 32 && dtype.lanes == 1);
std::generate_n(static_cast<float*>(data->data), size, [&] () {
float max_int = static_cast<float>(std::numeric_limits<unsigned>::max());
float unif01 = GetRandInt() / max_int;
return low + unif01 * (high - low);
});
}
/*!
* \brief Fills a tensor with values drawn from Normal(loc, scale)
*/
void SampleNormal(DLTensor* data, float loc, float scale) {
CHECK_GT(scale, 0) << "scale must be positive";
CHECK(data->strides == nullptr);
DLDataType dtype = data->dtype;
int64_t size = 1;
for (int i = 0; i < data->ndim; ++i) {
size *= data->shape[i];
}
CHECK(dtype.code == kDLFloat && dtype.bits == 32 && dtype.lanes == 1);
std::generate_n(static_cast<float*>(data->data), size, [&] () {
return GetNormal(loc, scale);
});
}
private:
/*!
* \return a random value sampled from Normal(0, 1) such that the
* sampled value is greater than tail
*/
inline float GetStandardNormalTail(float tail) {
while (true) {
float u1 = GetUniform(0, 1);
float u2 = GetUniform(0, 1);
float x = - log(u1) / tail;
float y = - log(u2);
if (2 * y < x * x) {
return x + tail;
}
}
}
/*!
* \return a random positive value sampled from Normal(0, 1).
*/
inline float GetStandardNormalOneside() {
while (true) {
unsigned i = GetRandInt() & 255;
float x = GetUniform(0, ZIG_NORM_X[i]);
if (x < ZIG_NORM_X[i+1]) {
return x;
}
if (i == 0) {
return GetStandardNormalTail(ZIG_NORM_X[1]);
}
float y = GetUniform(ZIG_NORM_F[i], ZIG_NORM_F[i+1]);
if (y < exp(-0.5 * x * x)) {
return x;
}
}
}
/*!
* Tables for normal distribution which is sampled using the ziggurat algorithm.
*/
static constexpr float ZIG_NORM_X[257] =
{3.910757959537090045, 3.654152885361008796, 3.449278298560964462, 3.320244733839166074,
3.224575052047029100, 3.147889289517149969, 3.083526132001233044, 3.027837791768635434,
2.978603279880844834, 2.934366867207854224, 2.894121053612348060, 2.857138730872132548,
2.822877396825325125, 2.790921174000785765, 2.760944005278822555, 2.732685359042827056,
2.705933656121858100, 2.680514643284522158, 2.656283037575502437, 2.633116393630324570,
2.610910518487548515, 2.589575986706995181, 2.569035452680536569, 2.549221550323460761,
2.530075232158516929, 2.511544441625342294, 2.493583041269680667, 2.476149939669143318,
2.459208374333311298, 2.442725318198956774, 2.426670984935725972, 2.411018413899685520,
2.395743119780480601, 2.380822795170626005, 2.366237056715818632, 2.351967227377659952,
2.337996148795031370, 2.324308018869623016, 2.310888250599850036, 2.297723348901329565,
2.284800802722946056, 2.272108990226823888, 2.259637095172217780, 2.247375032945807760,
2.235313384928327984, 2.223443340090905718, 2.211756642882544366, 2.200245546609647995,
2.188902771624720689, 2.177721467738641614, 2.166695180352645966, 2.155817819875063268,
2.145083634046203613, 2.134487182844320152, 2.124023315687815661, 2.113687150684933957,
2.103474055713146829, 2.093379631137050279, 2.083399693996551783, 2.073530263516978778,
2.063767547809956415, 2.054107931648864849, 2.044547965215732788, 2.035084353727808715,
2.025713947862032960, 2.016433734904371722, 2.007240830558684852, 1.998132471356564244,
1.989106007615571325, 1.980158896898598364, 1.971288697931769640, 1.962493064942461896,
1.953769742382734043, 1.945116560006753925, 1.936531428273758904, 1.928012334050718257,
1.919557336591228847, 1.911164563769282232, 1.902832208548446369, 1.894558525668710081,
1.886341828534776388, 1.878180486290977669, 1.870072921069236838, 1.862017605397632281,
1.854013059758148119, 1.846057850283119750, 1.838150586580728607, 1.830289919680666566,
1.822474540091783224, 1.814703175964167636, 1.806974591348693426, 1.799287584547580199,
1.791640986550010028, 1.784033659547276329, 1.776464495522344977, 1.768932414909077933,
1.761436365316706665, 1.753975320315455111, 1.746548278279492994, 1.739154261283669012,
1.731792314050707216, 1.724461502945775715, 1.717160915015540690, 1.709889657069006086,
1.702646854797613907, 1.695431651932238548, 1.688243209434858727, 1.681080704722823338,
1.673943330923760353, 1.666830296159286684, 1.659740822855789499, 1.652674147080648526,
1.645629517902360339, 1.638606196773111146, 1.631603456932422036, 1.624620582830568427,
1.617656869570534228, 1.610711622367333673, 1.603784156023583041, 1.596873794420261339,
1.589979870021648534, 1.583101723393471438, 1.576238702733332886, 1.569390163412534456,
1.562555467528439657, 1.555733983466554893, 1.548925085471535512, 1.542128153226347553,
1.535342571438843118, 1.528567729435024614, 1.521803020758293101, 1.515047842773992404,
1.508301596278571965, 1.501563685112706548, 1.494833515777718391, 1.488110497054654369,
1.481394039625375747, 1.474683555695025516, 1.467978458615230908, 1.461278162507407830,
1.454582081885523293, 1.447889631277669675, 1.441200224845798017, 1.434513276002946425,
1.427828197027290358, 1.421144398672323117, 1.414461289772464658, 1.407778276843371534,
1.401094763676202559, 1.394410150925071257, 1.387723835686884621, 1.381035211072741964,
1.374343665770030531, 1.367648583594317957, 1.360949343030101844, 1.354245316759430606,
1.347535871177359290, 1.340820365893152122, 1.334098153216083604, 1.327368577624624679,
1.320630975217730096, 1.313884673146868964, 1.307128989027353860, 1.300363230327433728,
1.293586693733517645, 1.286798664489786415, 1.279998415710333237, 1.273185207661843732,
1.266358287014688333, 1.259516886060144225, 1.252660221891297887, 1.245787495544997903,
1.238897891102027415, 1.231990574742445110, 1.225064693752808020, 1.218119375481726552,
1.211153726239911244, 1.204166830140560140, 1.197157747875585931, 1.190125515422801650,
1.183069142678760732, 1.175987612011489825, 1.168879876726833800, 1.161744859441574240,
1.154581450355851802, 1.147388505416733873, 1.140164844363995789, 1.132909248648336975,
1.125620459211294389, 1.118297174115062909, 1.110938046009249502, 1.103541679420268151,
1.096106627847603487, 1.088631390649514197, 1.081114409698889389, 1.073554065787871714,
1.065948674757506653, 1.058296483326006454, 1.050595664586207123, 1.042844313139370538,
1.035040439828605274, 1.027181966030751292, 1.019266717460529215, 1.011292417434978441,
1.003256679539591412, 0.995156999629943084, 0.986990747093846266, 0.978755155288937750,
0.970447311058864615, 0.962064143217605250, 0.953602409875572654, 0.945058684462571130,
0.936429340280896860, 0.927710533396234771, 0.918898183643734989, 0.909987953490768997,
0.900975224455174528, 0.891855070726792376, 0.882622229578910122, 0.873271068082494550,
0.863795545546826915, 0.854189171001560554, 0.844444954902423661, 0.834555354079518752,
0.824512208745288633, 0.814306670128064347, 0.803929116982664893, 0.793369058833152785,
0.782615023299588763, 0.771654424216739354, 0.760473406422083165, 0.749056662009581653,
0.737387211425838629, 0.725446140901303549, 0.713212285182022732, 0.700661841097584448,
0.687767892786257717, 0.674499822827436479, 0.660822574234205984, 0.646695714884388928,
0.632072236375024632, 0.616896989996235545, 0.601104617743940417, 0.584616766093722262,
0.567338257040473026, 0.549151702313026790, 0.529909720646495108, 0.509423329585933393,
0.487443966121754335, 0.463634336771763245, 0.437518402186662658, 0.408389134588000746,
0.375121332850465727, 0.335737519180459465, 0.286174591747260509, 0.215241895913273806,
0.000000000000000000};
static constexpr float ZIG_NORM_F[257] =
{0.000477467764586655, 0.001260285930498598, 0.002609072746106363, 0.004037972593371872,
0.005522403299264754, 0.007050875471392110, 0.008616582769422917, 0.010214971439731100,
0.011842757857943104, 0.013497450601780807, 0.015177088307982072, 0.016880083152595839,
0.018605121275783350, 0.020351096230109354, 0.022117062707379922, 0.023902203305873237,
0.025705804008632656, 0.027527235669693315, 0.029365939758230111, 0.031221417192023690,
0.033093219458688698, 0.034980941461833073, 0.036884215688691151, 0.038802707404656918,
0.040736110656078753, 0.042684144916619378, 0.044646552251446536, 0.046623094902089664,
0.048613553216035145, 0.050617723861121788, 0.052635418276973649, 0.054666461325077916,
0.056710690106399467, 0.058767952921137984, 0.060838108349751806, 0.062921024437977854,
0.065016577971470438, 0.067124653828023989, 0.069245144397250269, 0.071377949059141965,
0.073522973714240991, 0.075680130359194964, 0.077849336702372207, 0.080030515814947509,
0.082223595813495684, 0.084428509570654661, 0.086645194450867782, 0.088873592068594229,
0.091113648066700734, 0.093365311913026619, 0.095628536713353335, 0.097903279039215627,
0.100189498769172020, 0.102487158942306270, 0.104796225622867056, 0.107116667775072880,
0.109448457147210021, 0.111791568164245583, 0.114145977828255210, 0.116511665626037014,
0.118888613443345698, 0.121276805485235437, 0.123676228202051403, 0.126086870220650349,
0.128508722280473636, 0.130941777174128166, 0.133386029692162844, 0.135841476571757352,
0.138308116449064322, 0.140785949814968309, 0.143274978974047118, 0.145775208006537926,
0.148286642733128721, 0.150809290682410169, 0.153343161060837674, 0.155888264725064563,
0.158444614156520225, 0.161012223438117663, 0.163591108232982951, 0.166181285765110071,
0.168782774801850333, 0.171395595638155623, 0.174019770082499359, 0.176655321444406654,
0.179302274523530397, 0.181960655600216487, 0.184630492427504539, 0.187311814224516926,
0.190004651671193070, 0.192709036904328807, 0.195425003514885592, 0.198152586546538112,
0.200891822495431333, 0.203642749311121501, 0.206405406398679298, 0.209179834621935651,
0.211966076307852941, 0.214764175252008499, 0.217574176725178370, 0.220396127481011589,
0.223230075764789593, 0.226076071323264877, 0.228934165415577484, 0.231804410825248525,
0.234686861873252689, 0.237581574432173676, 0.240488605941449107, 0.243408015423711988,
0.246339863502238771, 0.249284212419516704, 0.252241126056943765, 0.255210669955677150,
0.258192911338648023, 0.261187919133763713, 0.264195763998317568, 0.267216518344631837,
0.270250256366959984, 0.273297054069675804, 0.276356989296781264, 0.279430141762765316,
0.282516593084849388, 0.285616426816658109, 0.288729728483353931, 0.291856585618280984,
0.294997087801162572, 0.298151326697901342, 0.301319396102034120, 0.304501391977896274,
0.307697412505553769, 0.310907558127563710, 0.314131931597630143, 0.317370638031222396,
0.320623784958230129, 0.323891482377732021, 0.327173842814958593, 0.330470981380537099,
0.333783015832108509, 0.337110066638412809, 0.340452257045945450, 0.343809713148291340,
0.347182563958251478, 0.350570941482881204, 0.353974980801569250, 0.357394820147290515,
0.360830600991175754, 0.364282468130549597, 0.367750569780596226, 0.371235057669821344,
0.374736087139491414, 0.378253817247238111, 0.381788410875031348, 0.385340034841733958,
0.388908860020464597, 0.392495061461010764, 0.396098818517547080, 0.399720314981931668,
0.403359739222868885, 0.407017284331247953, 0.410693148271983222, 0.414387534042706784,
0.418100649839684591, 0.421832709231353298, 0.425583931339900579, 0.429354541031341519,
0.433144769114574058, 0.436954852549929273, 0.440785034667769915, 0.444635565397727750,
0.448506701509214067, 0.452398706863882505, 0.456311852680773566, 0.460246417814923481,
0.464202689050278838, 0.468180961407822172, 0.472181538469883255, 0.476204732721683788,
0.480250865911249714, 0.484320269428911598, 0.488413284707712059, 0.492530263646148658,
0.496671569054796314, 0.500837575128482149, 0.505028667945828791, 0.509245245998136142,
0.513487720749743026, 0.517756517232200619, 0.522052074674794864, 0.526374847174186700,
0.530725304406193921, 0.535103932383019565, 0.539511234259544614, 0.543947731192649941,
0.548413963257921133, 0.552910490428519918, 0.557437893621486324, 0.561996775817277916,
0.566587763258951771, 0.571211506738074970, 0.575868682975210544, 0.580559996103683473,
0.585286179266300333, 0.590047996335791969, 0.594846243770991268, 0.599681752622167719,
0.604555390700549533, 0.609468064928895381, 0.614420723892076803, 0.619414360609039205,
0.624450015550274240, 0.629528779928128279, 0.634651799290960050, 0.639820277456438991,
0.645035480824251883, 0.650298743114294586, 0.655611470583224665, 0.660975147780241357,
0.666391343912380640, 0.671861719900766374, 0.677388036222513090, 0.682972161648791376,
0.688616083008527058, 0.694321916130032579, 0.700091918140490099, 0.705928501336797409,
0.711834248882358467, 0.717811932634901395, 0.723864533472881599, 0.729995264565802437,
0.736207598131266683, 0.742505296344636245, 0.748892447223726720, 0.755373506511754500,
0.761953346841546475, 0.768637315803334831, 0.775431304986138326, 0.782341832659861902,
0.789376143571198563, 0.796542330428254619, 0.803849483176389490, 0.811307874318219935,
0.818929191609414797, 0.826726833952094231, 0.834716292992930375, 0.842915653118441077,
0.851346258465123684, 0.860033621203008636, 0.869008688043793165, 0.878309655816146839,
0.887984660763399880, 0.898095921906304051, 0.908726440060562912, 0.919991505048360247,
0.932060075968990209, 0.945198953453078028, 0.959879091812415930, 0.977101701282731328,
1.000000000000000000};
};
constexpr float RandomEngine::ZIG_NORM_X[];
constexpr float RandomEngine::ZIG_NORM_F[];
} // namespace contrib
} // namespace tvm
| 16,227 | 12,981 |
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 <iostream>
#include "itkVectorImage.h"
#include "itkGradientImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
namespace
{
template <typename TInputImage>
int DoIt( const std::string &infname,
const std::string &outfname )
{
using InputImageType = TInputImage;
const unsigned int ImageDimension = InputImageType::ImageDimension;
using InputPixelType = typename InputImageType::PixelType;
using ReaderType = itk::ImageFileReader<InputImageType>;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( infname );
using FilterType = itk::GradientImageFilter<InputImageType >;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
using OutputImageType = typename FilterType::OutputImageType;
using WriterType = itk::ImageFileWriter<OutputImageType>;
typename WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( outfname );
writer->SetNumberOfStreamDivisions( 5 );
writer->Update();
std::cout << filter;
using VectorImageType = itk::VectorImage<InputPixelType, ImageDimension>;
using VectorFilterType = itk::GradientImageFilter<InputImageType, float, float, VectorImageType>;
typename VectorFilterType::Pointer vectorFilter = VectorFilterType::New();
vectorFilter->SetInput( reader->GetOutput() );
vectorFilter->Update();
filter->UpdateLargestPossibleRegion();
itk::ImageRegionConstIterator<OutputImageType> iter( filter->GetOutput(),
filter->GetOutput()->GetBufferedRegion() );
itk::ImageRegionConstIterator<VectorImageType> viter( vectorFilter->GetOutput(),
vectorFilter->GetOutput()->GetBufferedRegion() );
// Check the filter output
bool diff = false;
while( !iter.IsAtEnd() )
{
for( unsigned int i = 0; i < ImageDimension; ++i )
{
if ( ! itk::Math::FloatAlmostEqual( iter.Get()[i], viter.Get()[i] ) )
{
diff = true;
}
}
++viter;
++iter;
}
if ( diff )
{
std::cerr << "VectorImage output does not match covariant!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
}
int itkGradientImageFilterTest2(int argc, char * argv[] )
{
if ( argc < 3 )
{
std::cerr << "Missing arguments" << std::endl;
std::cerr << "Usage: " << argv[0] << " Inputimage OutputImage" << std::endl;
return EXIT_FAILURE;
}
const std::string infname = argv[1];
const std::string outfname = argv[2];
itk::ImageIOBase::Pointer iobase =
itk::ImageIOFactory::CreateImageIO( infname.c_str(), itk::ImageIOFactory::ReadMode);
if ( iobase.IsNull() )
{
itkGenericExceptionMacro( "Unable to determine ImageIO reader for \"" << infname << "\"" );
}
using TestImageType = itk::Image<short,3>;
using FilterType = itk::GradientImageFilter<TestImageType >;
FilterType::Pointer filter = FilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( filter, GradientImageFilter, ImageToImageFilter );
const unsigned int dimension = iobase->GetNumberOfDimensions();
if ( dimension == 2 )
return DoIt< itk::Image<float, 2> >( infname, outfname );
else if ( dimension == 3 )
return DoIt< itk::Image<float, 3> >( infname, outfname );
return EXIT_FAILURE;
}
| 4,120 | 1,303 |
#include <args/parser.hpp>
#include <iostream>
#include <string_view>
using namespace std::literals;
struct test {
const char* title;
int (*callback)();
int expected{0};
std::string_view output{};
};
std::vector<test> g_tests;
template <typename Test>
struct registrar {
registrar() {
::g_tests.push_back(
{Test::get_name(), Test::run, Test::expected(), Test::output()});
}
};
#define TEST_BASE(name, EXPECTED, OUTPUT) \
struct test_##name { \
static const char* get_name() noexcept { return #name; } \
static int run(); \
static int expected() noexcept { return (EXPECTED); } \
static std::string_view output() noexcept { return OUTPUT; } \
}; \
registrar<test_##name> reg_##name; \
int test_##name ::run()
#define TEST(name) TEST_BASE(name, 0, {})
#define TEST_FAIL(name) TEST_BASE(name, 1, {})
#define TEST_OUT(name, OUTPUT) TEST_BASE(name, 0, OUTPUT)
#define TEST_FAIL_OUT(name, OUTPUT) TEST_BASE(name, 1, OUTPUT)
int main(int argc, char* argv[]) {
if (argc == 1) {
for (auto const& test : g_tests) {
printf("%d:%s:", test.expected, test.title);
if (!test.output.empty())
printf("%.*s", static_cast<int>(test.output.size()),
test.output.data());
putc('\n', stdout);
}
return 0;
}
auto const int_test = atoi(argv[1]);
if (int_test < 0) return 100;
auto const test = static_cast<size_t>(int_test);
return g_tests[test].callback();
}
template <typename... CString, typename Mod>
int every_test_ever(Mod mod, CString... args) {
std::string arg_opt;
std::string arg_req;
bool starts_as_false{false};
bool starts_as_true{true};
std::vector<std::string> multi_opt;
std::vector<std::string> multi_req;
std::string positional;
char arg0[] = "args-help-test";
char* __args[] = {arg0, (const_cast<char*>(args))..., nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(arg_opt, "o", "opt").meta("VAR").help("a help for arg_opt").opt();
p.arg(arg_req, "r", "req").help("a help for arg_req");
p.set<std::true_type>(starts_as_false, "on", "1")
.help("a help for on")
.opt();
p.set<std::false_type>(starts_as_true, "off", "0")
.help("a help for off")
.opt();
p.arg(multi_opt, "first").help("zero or more").opt();
p.arg(multi_req, "second").meta("VAL").help("one or more");
p.arg(positional).meta("INPUT").help("a help for positional").opt();
mod(p);
p.parse();
return 0;
}
void noop(const args::parser&) {}
void modify(args::parser& parser) {
parser.program("another");
if (parser.program() != "another") {
fprintf(stderr, "Program not changed: %s\n", parser.program().c_str());
std::exit(1);
}
parser.usage("[OPTIONS]");
if (parser.usage() != "[OPTIONS]") {
fprintf(stderr, "Usage not changed: %s\n", parser.usage().c_str());
std::exit(1);
}
}
void enable_answers(args::parser& parser) {
parser.use_answer_file();
}
void enable_answers_dollar(args::parser& parser) {
parser.use_answer_file('$');
}
template <typename T, typename U>
void EQ_impl(T&& lhs, U&& rhs, const char* lhs_name, const char* rhs_name) {
if (lhs == rhs) return;
std::cerr << "Expected equality of these values:\n " << std::boolalpha
<< lhs_name << "\n Which is: " << lhs << "\n " << rhs_name
<< "\n Which is: " << rhs << "\n";
std::exit(1);
}
#define EQ(lhs, rhs) EQ_impl(lhs, rhs, #lhs, #rhs)
TEST(gen_usage) {
return every_test_ever(
[](args::parser& parser) {
std::string shrt;
const std::string_view expected_help =
"args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first "
"ARG "
"...] --second VAL [--second VAL ...] [INPUT]";
parser.printer_append_usage(shrt);
EQ(expected_help, shrt);
},
"-r", "x", "--second", "somsink");
}
TEST(gen_usage_no_help) {
return every_test_ever(
[](args::parser& parser) {
std::string shrt;
const std::string_view expected_no_help =
"args-help-test [-o VAR] -r ARG [--on] [--off] [--first ARG "
"...] "
"--second VAL [--second VAL ...] [INPUT]";
parser.provide_help(false);
parser.printer_append_usage(shrt);
EQ(expected_no_help, shrt);
},
"-r", "x", "--second", "somsink");
}
TEST_OUT(
short_help_argument,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\n\nprogram description\n\npositional arguments:\n INPUT a help for positional\n\noptional arguments:\n -h, --help show this help message and exit\n -o, --opt VAR a help for arg_opt\n -r, --req ARG a help for arg_req\n --on, -1 a help for on\n --off, -0 a help for off\n --first ARG zero or more\n --second VAL one or more\n)"sv) {
return every_test_ever(noop, "-h");
}
TEST_OUT(
long_help_argument,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\n\nprogram description\n\npositional arguments:\n INPUT a help for positional\n\noptional arguments:\n -h, --help show this help message and exit\n -o, --opt VAR a help for arg_opt\n -r, --req ARG a help for arg_req\n --on, -1 a help for on\n --off, -0 a help for off\n --first ARG zero or more\n --second VAL one or more\n)"sv) {
return every_test_ever(noop, "--help");
}
TEST(help_mod) {
return every_test_ever(modify, "-h");
}
TEST_FAIL_OUT(
no_req,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument -r is required\n)"sv) {
return every_test_ever(noop);
}
TEST_FAIL(no_req_mod) {
return every_test_ever(modify);
}
// TODO: used to be test_fail; regeresion or code behind fixed?
TEST(full) {
return every_test_ever(noop, "-oVALUE", "-r", "SEPARATE", "--req",
"ANOTHER ONE", "--on", "-10", "--off", "--second",
"somsink", "POSITIONAL");
}
TEST_FAIL_OUT(
missing_arg_short,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument -r: expected one argument\n)"sv) {
return every_test_ever(noop, "-r");
}
TEST_FAIL_OUT(
missing_arg,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument --req: expected one argument\n)"sv) {
return every_test_ever(noop, "--req");
}
TEST_FAIL_OUT(
missing_positional,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT] POSITIONAL [POSITIONAL ...]\nargs-help-test: error: argument POSITIONAL is required\n)"sv) {
std::vector<std::string> one_plus;
return every_test_ever(
[&](args::parser& p) {
p.arg(one_plus)
.meta("POSITIONAL")
.help("this parameter must be given at least once");
},
"-r", "x", "--second", "somsink");
}
TEST_FAIL_OUT(
unknown,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: unrecognized argument: --flag\n)"sv) {
return every_test_ever(noop, "--flag");
}
TEST_FAIL_OUT(
unknown_short,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: unrecognized argument: -f\n)"sv) {
return every_test_ever(noop, "-f");
}
TEST_FAIL_OUT(
unknown_positional,
R"(usage: args-help-test [-h]\nargs-help-test: error: unrecognized argument: POSITIONAL\n)"sv) {
#ifdef _WIN32
char arg0[] = R"(C:\Program Files\Program Name\args-help-test.exe)";
#else
char arg0[] = "/usr/bin/args-help-test";
#endif
char arg1[] = "POSITIONAL";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse();
return 0;
}
TEST(console_width) {
const auto isatty = args::detail::is_terminal(stdout);
const auto width = args::detail::terminal_width(stdout);
return isatty ? (width ? 0 : 1) : (width ? 1 : 0);
}
TEST_OUT(
width_forced,
R"(usage: args-help-test [-h] [INPUT]\n\nThis is a very long description of the\nprogram, which should span multiple\nlines in narrow consoles. This will be\ntested with forcing a console width in\nthe parse() method.\n\npositional arguments:\n INPUT This is a very long\n description of the INPUT\n param, which should span\n multiple lines in narrow\n consoles. This will be\n tested with forcing a\n console width in the\n parse() method. Also,\n here's a long word:\n supercalifragilisticexpiali\n docious\n\noptional arguments:\n -h, --help show this help message and\n exit\n)"sv) {
std::string positional;
char arg0[] = "args-help-test";
char arg1[] = "-h";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
auto prog_descr =
"This is a very long description of the program, "
"which should span multiple lines in narrow consoles. "
"This will be tested with forcing a console width in "
"the parse() method."s;
auto long_descr =
"This is a very long description of the INPUT param, "
"which should span multiple lines in narrow consoles. "
"This will be tested with forcing a console width in "
"the parse() method. Also, here's a long word: "
"supercalifragilisticexpialidocious"s;
::args::null_translator tr;
::args::parser p{std::move(prog_descr), ::args::from_main(argc, __args),
&tr};
p.arg(positional).meta("INPUT").help(std::move(long_descr)).opt();
p.parse(::args::parser::exclusive_parser, 40);
return 0;
}
TEST_FAIL(not_an_int) {
int value;
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER").opt();
p.parse();
return 0;
}
TEST_FAIL(out_of_range) {
int value;
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] =
"123456789012345678901234567890123456789012345678901234567890";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER").opt();
p.parse();
return 0;
}
TEST(optional_int_1) {
std::optional<int> value;
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER");
p.parse();
constexpr auto has_value = true;
constexpr auto the_value = 12345;
EQ(has_value, !!value);
EQ(the_value, *value);
return 0;
}
TEST(optional_int_2) {
std::optional<int> value;
char arg0[] = "args-help-test";
char* __args[] = {arg0, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER");
p.parse();
constexpr auto no_value = false;
EQ(no_value, !!value);
return 0;
}
TEST(subcmd_long) {
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse(::args::parser::allow_subcommands);
return 0;
}
TEST(subcmd_short) {
char arg0[] = "args-help-test";
char arg1[] = "-n";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse(::args::parser::allow_subcommands);
return 0;
}
TEST(subcmd_positional) {
char arg0[] = "args-help-test";
char arg1[] = "a_path";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse(::args::parser::allow_subcommands);
return 0;
}
TEST(custom_simple_1) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([] {}, "path");
p.parse();
return 0;
}
TEST(custom_simple_1_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([] { std::exit(0); }, "path");
p.parse();
return 1;
}
TEST(custom_simple_2) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](::args::parser&) {}, "path");
p.parse();
return 0;
}
TEST(custom_simple_2_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](::args::parser&) { std::exit(0); }, "path");
p.parse();
return 1;
}
TEST(custom_string_1) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](std::string const&) {}, "path");
p.parse();
return 0;
}
TEST(custom_string_1_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([=](std::string const& arg) { std::exit(arg != arg2); }, "path");
p.parse();
return 1;
}
TEST(custom_string_2) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](::args::parser&, std::string const&) {}, "path");
p.parse();
return 0;
}
TEST(custom_string_2_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([=](::args::parser&,
std::string const& arg) { std::exit(arg != arg2); },
"path");
p.parse();
return 1;
}
TEST(custom_string_view_1_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([=](std::string_view arg) { std::exit(arg != arg2); }, "path");
p.parse();
return 1;
}
TEST(custom_string_view_2_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom(
[=](::args::parser&, std::string_view arg) { std::exit(arg != arg2); },
"path");
p.parse();
return 1;
}
TEST(empty_args) {
char* __args[] = {nullptr};
auto const args = ::args::from_main(0, __args);
constexpr auto expected_prog_name = ""sv;
constexpr auto expected_args = 0u;
EQ(expected_prog_name, args.progname);
EQ(expected_args, args.args.size());
return 0;
}
TEST(additional_ctors) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
args::null_translator tr;
args::parser p1{""s, arg0, {argc - 1, __args + 1}, &tr};
args::parser p2{""s, args::arglist{argc, __args}, &tr};
return 0;
}
enum class thing { none, one, two };
ENUM_TRAITS_BEGIN(thing)
ENUM_TRAITS_NAME(one)
ENUM_TRAITS_NAME(two)
ENUM_TRAITS_END(thing)
TEST(enum_arg_one) {
char arg0[] = "args-help-test";
char arg1[] = "--thing";
char arg2[] = "one";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
thing which{thing::none};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(which, "thing");
p.parse();
return !(which == thing::one);
}
TEST(enum_arg_two) {
char arg0[] = "args-help-test";
char arg1[] = "--thing";
char arg2[] = "two";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
thing which{thing::none};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(which, "thing");
p.parse();
return !(which == thing::two);
}
TEST_FAIL_OUT(
enum_arg_three,
R"(usage: args-help-test [-h] --thing ARG\nargs-help-test: error: argument --thing: value three is not recognized\nknown values for --thing: one, two\n)"sv) {
char arg0[] = "args-help-test";
char arg1[] = "--thing";
char arg2[] = "three";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
thing which{thing::none};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(which, "thing");
p.parse();
return !(which == thing::none);
}
TEST(long_param_eq) {
return every_test_ever(noop, "-r", "x", "--second=somsink");
}
TEST_FAIL_OUT(
long_param_eq_error,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument --off: value was not expected\n)"sv) {
return every_test_ever(noop, "-r", "x", "--second", "somsink", "--off=on");
}
TEST_OUT(utf_8,
"usage: args-help-test [-h] --\xC3\xA7-arg \xC3\xB1 --c-arg n\\n"
"\\n"
"program description\\n"
"\\n"
"optional arguments:\\n"
" -h, --help show this help message and exit\\n"
" --\xC3\xA7-arg \xC3\xB1 |<----\\n"
" --c-arg n |<----\\n"sv) {
char arg0[] = "args-help-test";
char arg1[] = "--help";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
std::string argument{};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(argument, "\xC3\xA7-arg").meta("\xC3\xB1").help("|<----");
p.arg(argument, "c-arg").meta("n").help("|<----");
p.parse();
return 1;
}
TEST_FAIL_OUT(
no_answer_file_support,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...]\nargs-help-test: error: unrecognized argument: @minimal-args\n)"sv) {
std::string arg_opt;
std::string arg_req;
bool starts_as_false{false};
bool starts_as_true{true};
std::vector<std::string> multi_opt;
std::vector<std::string> multi_req;
char arg0[] = "args-help-test";
char arg1[] = "@minimal-args";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(arg_opt, "o", "opt").meta("VAR").help("a help for arg_opt").opt();
p.arg(arg_req, "r", "req").help("a help for arg_req");
p.set<std::true_type>(starts_as_false, "on", "1")
.help("a help for on")
.opt();
p.set<std::false_type>(starts_as_true, "off", "0")
.help("a help for off")
.opt();
p.arg(multi_opt, "first").help("zero or more").opt();
p.arg(multi_req, "second").meta("VAL").help("one or more");
p.parse();
return 0;
}
TEST(answer_file) {
return every_test_ever(enable_answers, "@minimal-args");
}
TEST_FAIL_OUT(
answer_file_not_found,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: cannot open no-such-file\n)"sv) {
return every_test_ever(enable_answers, "@no-such-file");
}
TEST(answer_file_before) {
char arg0[] = "args-help-test";
char arg1[] = "@minimal-args";
char arg2[] = "-r";
char arg3[] = "y";
char* __args[] = {arg0, arg1, arg2, arg3, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
std::string r{}, s{};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.use_answer_file();
p.arg(r, "r", "req").help("a help for arg_req");
p.arg(s, "second").meta("VAL").help("one or more");
p.parse();
return !(r == "y");
}
TEST(answer_file_after) {
char arg0[] = "args-help-test";
char arg1[] = "-r";
char arg2[] = "y";
char arg3[] = "@minimal-args";
char* __args[] = {arg0, arg1, arg2, arg3, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
std::string r{}, s{};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.use_answer_file();
p.arg(r, "r", "req").help("a help for arg_req");
p.arg(s, "second").meta("VAL").help("one or more");
p.parse();
return !(r == "x");
}
TEST(answer_file_alt) {
return every_test_ever(enable_answers_dollar, "$minimal-args");
}
TEST_FAIL_OUT(
answer_file_unexpected,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument --off: value was not expected\n)"sv) {
return every_test_ever(enable_answers, "@unexpected-arg-value");
}
TEST_FAIL_OUT(
answer_file_unknown,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: unrecognized argument: --unexpected\n)"sv) {
return every_test_ever(enable_answers, "@unknown-arg");
}
| 24,236 | 9,592 |
/**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define mem(a, b) memset(a, b, sizeof(a))
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 50010
#define read(a) scanf("%lld", &a)
#define root 0
#define LN 16
vector<ll> adj[NN];
ll baseArray[NN], ptr, value[NN];
ll chainNo, chainInd[NN], chainHead[NN], posInBase[NN];
ll depth[NN], par[NN][LN], subsize[NN];
ll seg[NN * 4];
void make_tree(ll node, ll low, ll high) {
if (low == high) {
seg[node] = baseArray[low];
return;
}
ll left = node << 1;
ll right = left | 1;
ll mid = (low + high) >> 1;
make_tree(left, low, mid);
make_tree(right, mid + 1, high);
seg[node] = seg[left] + seg[right];
return;
}
void update_tree(ll node, ll low, ll high, ll ind, ll val) {
if (low == ind && low == high) {
seg[node] = val;
return;
}
ll left = node << 1;
ll right = left | 1;
ll mid = (low + high) >> 1;
if (ind <= mid)
update_tree(left, low, mid, ind, val);
else
update_tree(right, mid + 1, high, ind, val);
seg[node] = seg[left] + seg[right];
return;
}
ll query_tree(ll node, ll low, ll high, ll rlow, ll rhigh) {
if (low >= rlow && high <= rhigh) {
return seg[node];
}
ll left = node << 1;
ll right = left | 1;
ll mid = (low + high) >> 1;
if (rhigh <= mid)
return query_tree(left, low, mid, rlow, rhigh);
else if (rlow > mid)
return query_tree(right, mid + 1, high, rlow, rhigh);
else {
ll L = query_tree(left, low, mid, rlow, mid);
ll R = query_tree(right, mid + 1, high, mid + 1, rhigh);
return L + R;
}
}
ll query_up(ll u, ll v) { // v is an ancestor of u
ll uchain, vchain = chainInd[v], ans = 0;
// uchain and vchain are chain numbers of u and v
while (1) {
uchain = chainInd[u];
if (uchain == vchain) {
ans += query_tree(1, 1, ptr - 1, posInBase[v], posInBase[u]);
break;
}
ans += query_tree(1, 1, ptr - 1, posInBase[chainHead[uchain]],
posInBase[u]);
u = chainHead[uchain]; // move u to u's chainHead
u = par[u][0]; // Then move to its parent, that means we changed
// chains
}
return ans;
}
ll LCA(ll u, ll v) {
if (depth[u] < depth[v])
swap(u, v);
ll diff = depth[u] - depth[v];
for (ll i = 0; i < LN; i++)
if ((diff >> i) & 1)
u = par[u][i];
if (u == v)
return u;
for (ll i = LN - 1; i >= 0; i--)
if (par[u][i] != par[v][i]) {
u = par[u][i];
v = par[v][i];
}
return par[u][0];
}
ll query(ll u, ll v) {
ll lca = LCA(u, v);
ll ans = query_up(u, lca); // One part of path
ll ans2 = query_up(v, lca); // another part of path
return ans + ans2 - query_up(lca, lca); // take the maximum of both paths
}
void change(ll u, ll val) {
update_tree(1, 1, ptr - 1, posInBase[u], val);
}
void HLD(ll curNode, ll prev) {
if (chainHead[chainNo] == -1) {
chainHead[chainNo] = curNode; // Assign chain head
}
chainInd[curNode] = chainNo;
posInBase[curNode] = ptr; // Position of this node in baseArray which we
// will use in Segtree
baseArray[ptr++] = value[curNode];
ll sc = -1, ncost;
// Loop to find special child
for (ll i = 0; i < adj[curNode].size(); i++)
if (adj[curNode][i] != prev) {
if (sc == -1 || subsize[sc] < subsize[adj[curNode][i]]) {
sc = adj[curNode][i];
}
}
if (sc != -1) {
// Expand the chain
HLD(sc, curNode);
}
for (ll i = 0; i < adj[curNode].size(); i++)
if (adj[curNode][i] != prev) {
if (sc != adj[curNode][i]) {
// New chains at each normal node
chainNo++;
HLD(adj[curNode][i], curNode);
}
}
}
void dfs(ll cur, ll prev, ll _depth = 0) {
par[cur][0] = prev;
depth[cur] = _depth;
subsize[cur] = 1;
for (ll i = 0; i < adj[cur].size(); i++)
if (adj[cur][i] != prev) {
dfs(adj[cur][i], cur, _depth + 1);
subsize[cur] += subsize[adj[cur][i]];
}
}
int main() {
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt", "r", stdin);
#endif
ll tc, t = 1;
scanf("%lld ", &tc);
while (tc--) {
ptr = 1;
ll n;
scanf("%lld", &n);
// Cleaning step, new test case
for (ll i = 0; i <= n; i++) {
adj[i].clear();
chainHead[i] = -1;
for (ll j = 0; j < LN; j++) par[i][j] = -1;
}
for (ll i = 0; i < n; i++) {
read(value[i]);
}
for (ll i = 1; i < n; i++) {
ll u, v, c;
scanf("%lld %lld", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
chainNo = 0;
dfs(root, -1); // We set up subsize, depth and parent for each node
HLD(root, -1); // We decomposed the tree and created baseArray
make_tree(
1, 1,
ptr -
1); // We use baseArray and construct the needed segment tree
// Below Dynamic programming code is for LCA.
for (ll lev = 1; lev <= LN - 1; lev++) {
for (ll i = 0; i < n; i++) {
if (par[i][lev - 1] != -1)
par[i][lev] = par[par[i][lev - 1]][lev - 1];
}
}
ll q;
scanf("%lld", &q);
printf("Case %lld:\n", t++);
while (q--) {
ll tp;
scanf("%lld", &tp);
ll a, b;
scanf("%lld %lld", &a, &b);
if (tp == 0) {
ll ans = query(a, b);
printf("%lld\n", ans);
} else {
change(a, b);
}
}
}
return 0;
}
| 6,505 | 2,433 |
/**
* Vapor Compiler Licence
*
* Copyright © 2017-2019 Michał "Griwes" Dominiak
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation is required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
**/
#include "vapor/analyzer/expressions/typeclass.h"
#include "vapor/analyzer/expressions/overload_set.h"
#include "vapor/analyzer/semantic/symbol.h"
#include "vapor/analyzer/semantic/typeclass.h"
#include "vapor/analyzer/statements/function.h"
#include "vapor/parser/expr.h"
#include "vapor/parser/typeclass.h"
#include "expressions/typeclass.pb.h"
namespace reaver::vapor::analyzer
{
inline namespace _v1
{
std::unique_ptr<typeclass_expression> preanalyze_typeclass_literal(precontext & ctx,
const parser::typeclass_literal & parse,
scope * lex_scope)
{
return std::make_unique<typeclass_expression>(
make_node(parse), make_typeclass(ctx, parse, lex_scope));
}
typeclass_expression::typeclass_expression(ast_node parse, std::unique_ptr<typeclass> tc)
: _typeclass{ std::move(tc) }
{
_set_ast_info(parse);
}
typeclass_expression::~typeclass_expression() = default;
void typeclass_expression::print(std::ostream & os, print_context ctx) const
{
os << styles::def << ctx << styles::rule_name << "typeclass-literal";
print_address_range(os, this);
os << '\n';
auto tc_ctx = ctx.make_branch(false);
os << styles::def << tc_ctx << styles::subrule_name << "defined typeclass:\n";
_typeclass->print(os, tc_ctx.make_branch(true), true);
auto params_ctx = ctx.make_branch(_typeclass->get_member_function_decls().empty());
os << styles::def << params_ctx << styles::subrule_name << "parameters:\n";
std::size_t idx = 0;
for (auto && param : _typeclass->get_parameter_expressions())
{
param->print(os, params_ctx.make_branch(++idx == _typeclass->get_parameter_expressions().size()));
}
if (_typeclass->get_member_function_decls().size())
{
auto decl_ctx = ctx.make_branch(true);
os << styles::def << decl_ctx << styles::subrule_name << "member function declarations:\n";
std::size_t idx = 0;
for (auto && member : _typeclass->get_member_function_decls())
{
member->print(
os, decl_ctx.make_branch(++idx == _typeclass->get_member_function_decls().size()));
}
}
}
void typeclass_expression::_set_name(std::u32string name)
{
_typeclass->set_name(std::move(name));
}
future<> typeclass_expression::_analyze(analysis_context & ctx)
{
return when_all(
fmap(_typeclass->get_parameters(), [&](auto && param) { return param->analyze(ctx); }))
.then([&] {
auto param_types = fmap(_typeclass->get_parameters(), [](auto && param) {
auto ret = param->get_type();
assert(ret->is_meta());
return ret;
});
_set_type(ctx.get_typeclass_type(param_types));
})
.then([&] {
return when_all(fmap(_typeclass->get_member_function_decls(),
[&](auto && decl) { return decl->analyze(ctx); }));
})
.then([&] {
// analyze possible unresolved types in function signatures
return when_all(fmap(_typeclass->get_scope()->symbols_in_order(), [&](symbol * symb) {
auto && oset = symb->get_expression()->as<overload_set_expression>();
if (oset)
{
return when_all(fmap(oset->get_overloads(), [&](function * fn) {
return fn->return_type_expression()->analyze(ctx).then([fn, &ctx] {
return when_all(fmap(
fn->parameters(), [&](auto && param) { return param->analyze(ctx); }));
});
}));
}
return make_ready_future();
}));
});
}
std::unique_ptr<expression> typeclass_expression::_clone_expr(replacements & repl) const
{
assert(0);
}
future<expression *> typeclass_expression::_simplify_expr(recursive_context ctx)
{
return when_all(fmap(_typeclass->get_member_function_decls(), [&](auto && decl) {
return decl->simplify(ctx);
})).then([&](auto &&) -> expression * { return this; });
}
statement_ir typeclass_expression::_codegen_ir(ir_generation_context & ctx) const
{
assert(0);
}
constant_init_ir typeclass_expression::_constinit_ir(ir_generation_context &) const
{
assert(0);
}
std::unique_ptr<google::protobuf::Message> typeclass_expression::_generate_interface() const
{
return _typeclass->generate_interface();
}
}
}
| 5,748 | 1,690 |
#include "cbase.h"
#include "hud.h"
#include "hud_macros.h"
#include "c_baseplayer.h"
#include "hud_hull.h"
#include "iclientmode.h"
#include "vgui/ISurface.h"
using namespace vgui;
#include "tier0/memdbgon.h"
#ifndef DBR
DECLARE_HUDELEMENT (CHudHull);
#endif
# define HULL_INIT 80
//------------------------------------------------------------------------
// Purpose: Constructor
//------------------------------------------------------------------------
CHudHull:: CHudHull (const char * pElementName) :
CHudElement (pElementName), BaseClass (NULL, "HudHull")
{
vgui:: Panel * pParent = g_pClientMode-> GetViewport ();
SetParent (pParent);
SetHiddenBits (HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT);
}
//------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------
void CHudHull:: Init()
{
Reset();
}
//------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------
void CHudHull:: Reset (void)
{
m_flHull = HULL_INIT;
m_nHullLow = -1;
SetBgColor (Color (0,0,0,0));
}
//------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------
void CHudHull:: OnThink (void)
{
float newHull = 0;
C_BasePlayer * local = C_BasePlayer:: GetLocalPlayer ();
if (!local)
return;
// Never below zero
newHull = max(local->GetHealth(), 0);
// DevMsg("Sheild at is at: %f\n",newShield);
// Only update the fade if we've changed health
if (newHull == m_flHull)
return;
m_flHull = newHull;
}
//------------------------------------------------------------------------
// Purpose: draws the power bar
//------------------------------------------------------------------------
void CHudHull::Paint()
{
// Get bar chunks
int chunkCount = m_flBarWidth / (m_flBarChunkWidth + m_flBarChunkGap);
int enabledChunks = (int)((float)chunkCount * (m_flHull / 100.0f) + 0.5f );
// Draw the suit power bar
surface()->DrawSetColor (m_HullColor);
int xpos = m_flBarInsetX, ypos = m_flBarInsetY;
for (int i = 0; i < enabledChunks; i++)
{
surface()->DrawFilledRect(xpos, ypos, xpos + m_flBarChunkWidth, ypos + m_flBarHeight);
xpos += (m_flBarChunkWidth + m_flBarChunkGap);
}
// Draw the exhausted portion of the bar.
surface()->DrawSetColor(Color(m_HullColor [0], m_HullColor [1], m_HullColor [2], m_iHullDisabledAlpha));
for (int i = enabledChunks; i < chunkCount; i++)
{
surface()->DrawFilledRect(xpos, ypos, xpos + m_flBarChunkWidth, ypos + m_flBarHeight);
xpos += (m_flBarChunkWidth + m_flBarChunkGap);
}
// Draw our name
surface()->DrawSetTextFont(m_hTextFont);
surface()->DrawSetTextColor(m_HullColor);
surface()->DrawSetTextPos(text_xpos, text_ypos);
//wchar_t *tempString = vgui::localize()->Find("#Valve_Hud_AUX_POWER");
surface()->DrawPrintText(L"HULL", wcslen(L"HULL"));
} | 3,036 | 1,078 |
/*=========================================================================
Program: Visualization Toolkit
Module: vtkVRRenderWindow.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkVRRenderWindow.h"
#include "vtkMatrix4x4.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLState.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkRendererCollection.h"
#include "vtkTransform.h"
#include "vtkVRCamera.h"
#include "vtkVRModel.h"
#include "vtkVRRenderer.h"
#include <cstring>
#include <memory>
// include what we need for the helper window
#ifdef WIN32
#include "vtkWin32OpenGLRenderWindow.h"
#endif
#ifdef VTK_USE_X
#include "vtkXOpenGLRenderWindow.h"
#endif
#ifdef VTK_USE_COCOA
#include "vtkCocoaRenderWindow.h"
#endif
#if !defined(_WIN32) || defined(__CYGWIN__)
#define stricmp strcasecmp
#endif
//------------------------------------------------------------------------------
vtkVRRenderWindow::vtkVRRenderWindow()
{
this->StereoCapableWindow = 1;
this->StereoRender = 1;
this->UseOffScreenBuffers = true;
this->Size[0] = 640;
this->Size[1] = 720;
this->Position[0] = 100;
this->Position[1] = 100;
this->HelperWindow = vtkOpenGLRenderWindow::SafeDownCast(vtkRenderWindow::New());
if (!this->HelperWindow)
{
vtkErrorMacro(<< "Failed to create render window");
}
}
//------------------------------------------------------------------------------
vtkVRRenderWindow::~vtkVRRenderWindow()
{
this->Finalize();
vtkRenderer* ren;
vtkCollectionSimpleIterator rit;
this->Renderers->InitTraversal(rit);
while ((ren = this->Renderers->GetNextRenderer(rit)))
{
ren->SetRenderWindow(nullptr);
}
if (this->HelperWindow)
{
this->HelperWindow->Delete();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ContextId: " << this->HelperWindow->GetGenericContext() << "\n";
os << indent << "Window Id: " << this->HelperWindow->GetGenericWindowId() << "\n";
os << indent << "Initialized: " << this->Initialized << "\n";
os << indent << "PhysicalViewDirection: (" << this->PhysicalViewDirection[0] << ", "
<< this->PhysicalViewDirection[1] << ", " << this->PhysicalViewDirection[2] << ")\n";
os << indent << "PhysicalViewUp: (" << this->PhysicalViewUp[0] << ", " << this->PhysicalViewUp[1]
<< ", " << this->PhysicalViewUp[2] << ")\n";
os << indent << "PhysicalTranslation: (" << this->PhysicalTranslation[0] << ", "
<< this->PhysicalTranslation[1] << ", " << this->PhysicalTranslation[2] << ")\n";
os << indent << "PhysicalScale: " << this->PhysicalScale << "\n";
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::ReleaseGraphicsResources(vtkWindow* renWin)
{
this->Superclass::ReleaseGraphicsResources(renWin);
for (FramebufferDesc& fbo : this->FramebufferDescs)
{
glDeleteFramebuffers(1, &fbo.ResolveFramebufferId);
}
for (auto& model : this->DeviceHandleToDeviceDataMap)
{
if (model.second.Model)
{
model.second.Model->ReleaseGraphicsResources(renWin);
}
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetHelperWindow(vtkOpenGLRenderWindow* win)
{
if (this->HelperWindow == win)
{
return;
}
if (this->HelperWindow)
{
this->ReleaseGraphicsResources(this);
this->HelperWindow->Delete();
}
this->HelperWindow = win;
if (win)
{
win->Register(this);
}
this->Modified();
}
void vtkVRRenderWindow::AddDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
this->DeviceHandleToDeviceDataMap[handle] = {};
}
}
void vtkVRRenderWindow::AddDeviceHandle(uint32_t handle, vtkEventDataDevice device)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
this->DeviceHandleToDeviceDataMap[handle] = {};
found = this->DeviceHandleToDeviceDataMap.find(handle);
}
found->second.Device = device;
}
void vtkVRRenderWindow::SetModelForDeviceHandle(uint32_t handle, vtkVRModel* model)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
this->DeviceHandleToDeviceDataMap[handle] = {};
found = this->DeviceHandleToDeviceDataMap.find(handle);
}
found->second.Model = model;
}
vtkVRModel* vtkVRRenderWindow::GetModelForDevice(vtkEventDataDevice idx)
{
auto handle = this->GetDeviceHandleForDevice(idx);
return this->GetModelForDeviceHandle(handle);
}
vtkVRModel* vtkVRRenderWindow::GetModelForDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
return nullptr;
}
return found->second.Model;
}
vtkMatrix4x4* vtkVRRenderWindow::GetDeviceToPhysicalMatrixForDevice(vtkEventDataDevice idx)
{
auto handle = this->GetDeviceHandleForDevice(idx);
return this->GetDeviceToPhysicalMatrixForDeviceHandle(handle);
}
vtkMatrix4x4* vtkVRRenderWindow::GetDeviceToPhysicalMatrixForDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
return nullptr;
}
return found->second.Pose;
}
uint32_t vtkVRRenderWindow::GetDeviceHandleForDevice(vtkEventDataDevice idx, uint32_t index)
{
for (auto& deviceData : this->DeviceHandleToDeviceDataMap)
{
if (deviceData.second.Device == idx && deviceData.second.Index == index)
{
return deviceData.first;
}
}
return InvalidDeviceIndex;
}
uint32_t vtkVRRenderWindow::GetNumberOfDeviceHandlesForDevice(vtkEventDataDevice dev)
{
uint32_t count = 0;
for (auto& deviceData : this->DeviceHandleToDeviceDataMap)
{
if (deviceData.second.Device == dev)
{
count++;
}
}
return count;
}
// default implementation just uses the vtkEventDataDevice
vtkEventDataDevice vtkVRRenderWindow::GetDeviceForDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
return vtkEventDataDevice::Unknown;
}
return found->second.Device;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::InitializeViewFromCamera(vtkCamera* srccam)
{
vtkRenderer* ren = vtkRenderer::SafeDownCast(this->GetRenderers()->GetItemAsObject(0));
if (!ren)
{
vtkErrorMacro("The renderer must be set prior to calling InitializeViewFromCamera");
return;
}
vtkVRCamera* cam = vtkVRCamera::SafeDownCast(ren->GetActiveCamera());
if (!cam)
{
vtkErrorMacro(
"The renderer's active camera must be set prior to calling InitializeViewFromCamera");
return;
}
// make sure the view up is reasonable based on the view up
// that was set in PV
double distance = sin(vtkMath::RadiansFromDegrees(srccam->GetViewAngle()) / 2.0) *
srccam->GetDistance() / sin(vtkMath::RadiansFromDegrees(cam->GetViewAngle()) / 2.0);
double* oldVup = srccam->GetViewUp();
int maxIdx = fabs(oldVup[0]) > fabs(oldVup[1]) ? (fabs(oldVup[0]) > fabs(oldVup[2]) ? 0 : 2)
: (fabs(oldVup[1]) > fabs(oldVup[2]) ? 1 : 2);
cam->SetViewUp((maxIdx == 0 ? (oldVup[0] > 0 ? 1 : -1) : 0.0),
(maxIdx == 1 ? (oldVup[1] > 0 ? 1 : -1) : 0.0), (maxIdx == 2 ? (oldVup[2] > 0 ? 1 : -1) : 0.0));
this->SetPhysicalViewUp((maxIdx == 0 ? (oldVup[0] > 0 ? 1 : -1) : 0.0),
(maxIdx == 1 ? (oldVup[1] > 0 ? 1 : -1) : 0.0), (maxIdx == 2 ? (oldVup[2] > 0 ? 1 : -1) : 0.0));
double* oldFP = srccam->GetFocalPoint();
double* cvup = cam->GetViewUp();
cam->SetFocalPoint(oldFP);
this->SetPhysicalTranslation(
cvup[0] * distance - oldFP[0], cvup[1] * distance - oldFP[1], cvup[2] * distance - oldFP[2]);
this->SetPhysicalScale(distance);
double* oldDOP = srccam->GetDirectionOfProjection();
int dopMaxIdx = fabs(oldDOP[0]) > fabs(oldDOP[1]) ? (fabs(oldDOP[0]) > fabs(oldDOP[2]) ? 0 : 2)
: (fabs(oldDOP[1]) > fabs(oldDOP[2]) ? 1 : 2);
this->SetPhysicalViewDirection((dopMaxIdx == 0 ? (oldDOP[0] > 0 ? 1 : -1) : 0.0),
(dopMaxIdx == 1 ? (oldDOP[1] > 0 ? 1 : -1) : 0.0),
(dopMaxIdx == 2 ? (oldDOP[2] > 0 ? 1 : -1) : 0.0));
double* idop = this->GetPhysicalViewDirection();
cam->SetPosition(
-idop[0] * distance + oldFP[0], -idop[1] * distance + oldFP[1], -idop[2] * distance + oldFP[2]);
ren->ResetCameraClippingRange();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::MakeCurrent()
{
if (this->HelperWindow)
{
this->HelperWindow->MakeCurrent();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::ReleaseCurrent()
{
if (this->HelperWindow)
{
this->HelperWindow->ReleaseCurrent();
}
}
//------------------------------------------------------------------------------
vtkOpenGLState* vtkVRRenderWindow::GetState()
{
if (this->HelperWindow)
{
return this->HelperWindow->GetState();
}
return this->Superclass::GetState();
}
//------------------------------------------------------------------------------
bool vtkVRRenderWindow::IsCurrent()
{
return this->HelperWindow ? this->HelperWindow->IsCurrent() : false;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::AddRenderer(vtkRenderer* ren)
{
if (ren && !vtkVRRenderer::SafeDownCast(ren))
{
vtkErrorMacro("vtkVRRenderWindow::AddRenderer: Failed to add renderer of type "
<< ren->GetClassName() << ": A subclass of vtkVRRenderer is expected");
return;
}
this->Superclass::AddRenderer(ren);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Start()
{
// if the renderer has not been initialized, do so now
if (this->HelperWindow && !this->Initialized)
{
this->Initialize();
}
this->Superclass::Start();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Initialize()
{
if (this->Initialized)
{
return;
}
this->GetSizeFromAPI();
this->HelperWindow->SetDisplayId(this->GetGenericDisplayId());
this->HelperWindow->SetShowWindow(false);
this->HelperWindow->Initialize();
this->MakeCurrent();
this->OpenGLInit();
// some classes override the ivar in a getter :-(
this->MaximumHardwareLineWidth = this->HelperWindow->GetMaximumHardwareLineWidth();
glDepthRange(0., 1.);
this->SetWindowName(this->GetWindowTitleFromAPI().c_str());
this->CreateFramebuffers();
this->Initialized = true;
vtkDebugMacro(<< "End of VRRenderWindow Initialization");
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Finalize()
{
this->ReleaseGraphicsResources(this);
this->DeviceHandleToDeviceDataMap.clear();
if (this->HelperWindow && this->HelperWindow->GetGenericContext())
{
this->HelperWindow->Finalize();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Render()
{
this->MakeCurrent();
this->GetState()->ResetGLViewportState();
this->Superclass::Render();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::RenderFramebuffer(FramebufferDesc& framebufferDesc)
{
this->GetState()->PushDrawFramebufferBinding();
this->GetState()->vtkglBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebufferDesc.ResolveFramebufferId);
glBlitFramebuffer(0, 0, this->Size[0], this->Size[1], 0, 0, this->Size[0], this->Size[1],
GL_COLOR_BUFFER_BIT, GL_LINEAR);
if (framebufferDesc.ResolveDepthTextureId != 0)
{
glBlitFramebuffer(0, 0, this->Size[0], this->Size[1], 0, 0, this->Size[0], this->Size[1],
GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
this->GetState()->PopDrawFramebufferBinding();
}
//------------------------------------------------------------------------------
bool vtkVRRenderWindow::GetDeviceToWorldMatrixForDevice(
vtkEventDataDevice device, vtkMatrix4x4* deviceToWorldMatrix)
{
vtkMatrix4x4* deviceToPhysicalMatrix = this->GetDeviceToPhysicalMatrixForDevice(device);
if (deviceToPhysicalMatrix)
{
// we use deviceToWorldMatrix here to temporarily store physicalToWorld
// to avoid having to use a temp matrix. We use a new pointer just to
// keep the code easier to read.
vtkMatrix4x4* physicalToWorldMatrix = deviceToWorldMatrix;
this->GetPhysicalToWorldMatrix(physicalToWorldMatrix);
vtkMatrix4x4::Multiply4x4(physicalToWorldMatrix, deviceToPhysicalMatrix, deviceToWorldMatrix);
return true;
}
return false;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewDirection(double x, double y, double z)
{
if (this->PhysicalViewDirection[0] != x || this->PhysicalViewDirection[1] != y ||
this->PhysicalViewDirection[2] != z)
{
this->PhysicalViewDirection[0] = x;
this->PhysicalViewDirection[1] = y;
this->PhysicalViewDirection[2] = z;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewDirection(double dir[3])
{
this->SetPhysicalViewDirection(dir[0], dir[1], dir[2]);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewUp(double x, double y, double z)
{
if (this->PhysicalViewUp[0] != x || this->PhysicalViewUp[1] != y || this->PhysicalViewUp[2] != z)
{
this->PhysicalViewUp[0] = x;
this->PhysicalViewUp[1] = y;
this->PhysicalViewUp[2] = z;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewUp(double dir[3])
{
this->SetPhysicalViewUp(dir[0], dir[1], dir[2]);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalTranslation(double x, double y, double z)
{
if (this->PhysicalTranslation[0] != x || this->PhysicalTranslation[1] != y ||
this->PhysicalTranslation[2] != z)
{
this->PhysicalTranslation[0] = x;
this->PhysicalTranslation[1] = y;
this->PhysicalTranslation[2] = z;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalTranslation(double trans[3])
{
this->SetPhysicalTranslation(trans[0], trans[1], trans[2]);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalScale(double scale)
{
if (this->PhysicalScale != scale)
{
this->PhysicalScale = scale;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalToWorldMatrix(vtkMatrix4x4* matrix)
{
if (!matrix)
{
return;
}
vtkNew<vtkMatrix4x4> currentPhysicalToWorldMatrix;
this->GetPhysicalToWorldMatrix(currentPhysicalToWorldMatrix);
bool matrixDifferent = false;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (fabs(matrix->GetElement(i, j) - currentPhysicalToWorldMatrix->GetElement(i, j)) >= 1e-3)
{
matrixDifferent = true;
break;
}
}
}
if (!matrixDifferent)
{
return;
}
vtkNew<vtkTransform> hmdToWorldTransform;
hmdToWorldTransform->SetMatrix(matrix);
double translation[3] = { 0.0 };
hmdToWorldTransform->GetPosition(translation);
this->PhysicalTranslation[0] = (-1.0) * translation[0];
this->PhysicalTranslation[1] = (-1.0) * translation[1];
this->PhysicalTranslation[2] = (-1.0) * translation[2];
double scale[3] = { 0.0 };
hmdToWorldTransform->GetScale(scale);
this->PhysicalScale = scale[0];
this->PhysicalViewUp[0] = matrix->GetElement(0, 1);
this->PhysicalViewUp[1] = matrix->GetElement(1, 1);
this->PhysicalViewUp[2] = matrix->GetElement(2, 1);
vtkMath::Normalize(this->PhysicalViewUp);
this->PhysicalViewDirection[0] = (-1.0) * matrix->GetElement(0, 2);
this->PhysicalViewDirection[1] = (-1.0) * matrix->GetElement(1, 2);
this->PhysicalViewDirection[2] = (-1.0) * matrix->GetElement(2, 2);
vtkMath::Normalize(this->PhysicalViewDirection);
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::GetPhysicalToWorldMatrix(vtkMatrix4x4* physicalToWorldMatrix)
{
if (!physicalToWorldMatrix)
{
return;
}
physicalToWorldMatrix->Identity();
// construct physical to non-scaled world axes (scaling is applied later)
double physicalZ_NonscaledWorld[3] = { -this->PhysicalViewDirection[0],
-this->PhysicalViewDirection[1], -this->PhysicalViewDirection[2] };
double* physicalY_NonscaledWorld = this->PhysicalViewUp;
double physicalX_NonscaledWorld[3] = { 0.0 };
vtkMath::Cross(physicalY_NonscaledWorld, physicalZ_NonscaledWorld, physicalX_NonscaledWorld);
for (int row = 0; row < 3; ++row)
{
physicalToWorldMatrix->SetElement(row, 0, physicalX_NonscaledWorld[row] * this->PhysicalScale);
physicalToWorldMatrix->SetElement(row, 1, physicalY_NonscaledWorld[row] * this->PhysicalScale);
physicalToWorldMatrix->SetElement(row, 2, physicalZ_NonscaledWorld[row] * this->PhysicalScale);
physicalToWorldMatrix->SetElement(row, 3, -this->PhysicalTranslation[row]);
}
}
//------------------------------------------------------------------------------
int* vtkVRRenderWindow::GetScreenSize()
{
if (this->GetSizeFromAPI())
{
this->ScreenSize[0] = this->Size[0];
this->ScreenSize[1] = this->Size[1];
}
return this->ScreenSize;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetSize(int width, int height)
{
if ((this->Size[0] != width) || (this->Size[1] != height))
{
this->Superclass::SetSize(width, height);
if (this->Interactor)
{
this->Interactor->SetSize(width, height);
}
}
}
| 19,308 | 6,379 |
#include "Ticker.hpp"
BEGIN_INANITY
Ticker::Ticker() :
lastTick(-1),
pauseTick(-1)
{
tickCoef = 1.0f / Time::GetTicksPerSecond();
}
void Ticker::Pause()
{
// if already paused, do nothing
if(pauseTick >= 0)
return;
// remember pause time
pauseTick = Time::GetTick();
}
float Ticker::Tick()
{
// get current time
Time::Tick currentTick = Time::GetTick();
// calculate amount of ticks from last tick
Time::Tick ticks = 0;
if(lastTick >= 0)
{
if(pauseTick >= 0)
ticks = pauseTick - lastTick;
else
ticks = currentTick - lastTick;
}
// if was paused, resume
if(pauseTick >= 0)
pauseTick = -1;
// remember current tick as last tick
lastTick = currentTick;
return ticks * tickCoef;
}
END_INANITY
| 732 | 321 |
#include "core.h"
#include "rodinbtnodeuseresource.h"
#include "configmanager.h"
#include "Components/wbcomprodinresourcemap.h"
#include "Components/wbcomprodinbehaviortree.h"
#include "wbentity.h"
RodinBTNodeUseResource::RodinBTNodeUseResource()
: m_Resource()
, m_ForceClaim( false )
{
}
RodinBTNodeUseResource::~RodinBTNodeUseResource()
{
}
void RodinBTNodeUseResource::InitializeFromDefinition( const SimpleString& DefinitionName )
{
RodinBTNodeDecorator::InitializeFromDefinition( DefinitionName );
MAKEHASH( DefinitionName );
STATICHASH( Resource );
m_Resource = ConfigManager::GetHash( sResource, HashedString::NullString, sDefinitionName );
STATICHASH( ForceClaim );
m_ForceClaim = ConfigManager::GetBool( sForceClaim, false, sDefinitionName );
}
/*virtual*/ RodinBTNode::ETickStatus RodinBTNodeUseResource::Tick( const float DeltaTime )
{
WBCompRodinResourceMap* const pResourceMap = GET_WBCOMP( GetEntity(), RodinResourceMap );
ASSERT( pResourceMap );
if( m_ChildStatus != ETS_None )
{
// We're just continuing from being woken.
return RodinBTNodeDecorator::Tick( DeltaTime );
}
if( pResourceMap->ClaimResource( this, m_Resource, m_ForceClaim ) )
{
// We got the resource, we're all good (or we're just continuing from being woken).
return RodinBTNodeDecorator::Tick( DeltaTime );
}
else
{
// We couldn't get the resource.
return ETS_Fail;
}
}
/*virtual*/ void RodinBTNodeUseResource::OnFinish()
{
RodinBTNodeDecorator::OnFinish();
WBCompRodinResourceMap* const pResourceMap = GET_WBCOMP( GetEntity(), RodinResourceMap );
ASSERT( pResourceMap );
pResourceMap->ReleaseResource( this, m_Resource );
}
/*virtual*/ bool RodinBTNodeUseResource::OnResourceStolen( const HashedString& Resource )
{
Unused( Resource );
ASSERT( Resource == m_Resource );
m_BehaviorTree->Stop( this );
return false;
} | 1,851 | 678 |
#include <power.h>
#include <pci/acpi.h>
#include <interrupts/panic.h>
#include <stivale2.h>
//#do_reboot-doc: Reboot FoxOS
void do_reboot() {
uint8_t good = 0x02;
while (good & 0x02) {
good = inb(0x64);
}
outb(0x64, 0xfe);
asm("hlt");
interrupts::Panic p = interrupts::Panic((char*) "Reboot failed!");
p.do_it(NULL);
} | 331 | 170 |
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "Calibration/Tools/interface/calibXMLwriter.h"
#include "Calibration/Tools/interface/CalibrationCluster.h"
#include "Calibration/Tools/interface/HouseholderDecomposition.h"
#include "Calibration/Tools/interface/MinL3Algorithm.h"
#include "Calibration/EcalCalibAlgos/interface/ElectronCalibrationUniv.h"
#include "FWCore/Utilities/interface/isFinite.h"
#include "TF1.h"
#include "TRandom.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>
ElectronCalibrationUniv::ElectronCalibrationUniv(const edm::ParameterSet& iConfig)
: ebRecHitLabel_(iConfig.getParameter<edm::InputTag>("ebRecHitsLabel")),
eeRecHitLabel_(iConfig.getParameter<edm::InputTag>("eeRecHitsLabel")),
electronLabel_(iConfig.getParameter<edm::InputTag>("electronLabel")),
rootfile_(iConfig.getParameter<std::string>("rootfile")),
calibAlgo_(iConfig.getParameter<std::string>("CALIBRATION_ALGO")),
miscalibfile_(iConfig.getParameter<std::string>("miscalibfile")),
miscalibfileEndCap_(iConfig.getParameter<std::string>("miscalibfileEndCap")),
keventweight_(iConfig.getParameter<int>("keventweight")),
elePt_(iConfig.getParameter<double>("ElePt")),
maxeta_(iConfig.getParameter<int>("maxeta")),
mineta_(iConfig.getParameter<int>("mineta")),
maxphi_(iConfig.getParameter<int>("maxphi")),
minphi_(iConfig.getParameter<int>("minphi")),
cut1_(iConfig.getParameter<double>("cut1")),
cut2_(iConfig.getParameter<double>("cut2")),
cut3_(iConfig.getParameter<double>("cut3")),
numevent_(iConfig.getParameter<int>("numevent")),
cutEPCalo1_(iConfig.getParameter<double>("cutEPCaloMin")),
cutEPCalo2_(iConfig.getParameter<double>("cutEPCaloMax")),
cutEPin1_(iConfig.getParameter<double>("cutEPinMin")),
cutEPin2_(iConfig.getParameter<double>("cutEPinMax")),
cutCalo1_(iConfig.getParameter<double>("cutCaloMin")),
cutCalo2_(iConfig.getParameter<double>("cutCaloMax")),
cutESeed_(iConfig.getParameter<double>("cutESeed")),
clusterSize_(iConfig.getParameter<int>("Clustersize")),
elecclass_(iConfig.getParameter<int>("elecclass")),
ebRecHitToken_(consumes<EBRecHitCollection>(ebRecHitLabel_)),
eeRecHitToken_(consumes<EERecHitCollection>(eeRecHitLabel_)),
gsfElectronToken_(consumes<reco::GsfElectronCollection>(electronLabel_)),
topologyToken_(esConsumes<edm::Transition::BeginRun>()) {}
ElectronCalibrationUniv::~ElectronCalibrationUniv() {}
//========================================================================
void ElectronCalibrationUniv::beginJob() {
//========================================================================
f = new TFile(rootfile_.c_str(), "RECREATE");
f->cd();
EventsAfterCuts = new TH1F("EventsAfterCuts", "Events After Cuts", 30, 0, 30);
// Book histograms
e9 = new TH1F("e9", "E9 energy", 300, 0., 150.);
e25 = new TH1F("e25", "E25 energy", 300, 0., 150.);
scE = new TH1F("scE", "SC energy", 300, 0., 150.);
trP = new TH1F("trP", "Trk momentum", 300, 0., 150.);
EoP = new TH1F("EoP", "EoP", 600, 0., 3.);
EoP_all = new TH1F("EoP_all", "EoP_all", 600, 0., 3.);
calibs = new TH1F("calib", "Calibration constants", 800, 0.5, 2.);
calibsEndCapMinus = new TH1F("calibEndCapMinus", "Calibration constants EE-", 800, 0.5, 2.);
calibsEndCapPlus = new TH1F("calibEndCapPlus", "Calibration constants EE+", 800, 0.5, 2.);
e25OverScE = new TH1F("e25OverscE", "E25 / SC energy", 400, 0., 2.);
E25oP = new TH1F("E25oP", "E25 / P", 750, 0., 1.5);
Map = new TH2F("Map", "Nb Events in Crystal", 173, -86, 86, 362, 0, 361);
e9Overe25 = new TH1F("e9Overe25", "E9 / E25", 400, 0., 2.);
Map3Dcalib = new TH2F("3Dcalib", "3Dcalib", 173, -86, 86, 362, 0, 361);
Map3DcalibEndCapMinus = new TH2F("3DcalibEndCapMinus", "3Dcalib EE-", 100, 0, 100, 100, 0, 100);
Map3DcalibEndCapPlus = new TH2F("3DcalibEndCapPlus", "3Dcalib EE+", 100, 0, 100, 100, 0, 100);
MapCor1 = new TH2F("MapCor1", "Correlation E25/Pcalo versus E25/Pin", 100, 0., 5., 100, 0., 5.);
MapCor2 = new TH2F("MapCor2", "Correlation E25/Pcalo versus E/P", 100, 0., 5., 100, 0., 5.);
MapCor3 = new TH2F("MapCor3", "Correlation E25/Pcalo versus Pout/Pin", 100, 0., 5., 100, 0., 5.);
MapCor4 = new TH2F("MapCor4", "Correlation E25/Pcalo versus E25/highestP", 100, 0., 5., 100, 0., 5.);
MapCor5 = new TH2F("MapCor5", "Correlation E25/Pcalo versus Pcalo/Pout", 100, 0., 5., 100, 0., 5.);
MapCor6 = new TH2F("MapCor6", "Correlation Pout/Pin versus E25/Pin", 100, 0., 5., 100, 0., 5.);
MapCor7 = new TH2F("MapCor7", "Correlation Pout/Pin versus Pcalo/Pout", 100, 0., 5., 100, 0., 5.);
MapCor8 = new TH2F("MapCor8", "Correlation E25/Pin versus Pcalo/Pout", 100, 0., 5., 100, 0., 5.);
MapCor9 = new TH2F("MapCor9", "Correlation E25/Pcalo versus Eseed/Pout", 100, 0., 5., 100, 0., 5.);
MapCor10 = new TH2F("MapCor10", "Correlation Eseed/Pout versus Pout/Pin", 100, 0., 5., 100, 0., 5.);
MapCor11 = new TH2F("MapCor11", "Correlation Eseed/Pout versus E25/Pin", 100, 0., 5., 100, 0., 5.);
// MapCorCalib = new TH2F ("MapCorCalib", "Correlation Miscalibration versus Calibration constants", 500, 0.5,1.5, 500, 0.5, 1.5);
E25oPvsEta = new TH2F("E25oPvsEta", "E/P vs Eta", 173, -86, 86, 600, 0.7, 1.3);
E25oPvsEtaEndCapMinus = new TH2F("E25oPvsEtaEndCapMinus", "E/P vs R EE-", 100, 0, 100, 600, 0.7, 1.3);
E25oPvsEtaEndCapPlus = new TH2F("E25oPvsEtaEndCapPlus", "E/P vs R EE+", 100, 0, 100, 600, 0.7, 1.3);
PinMinPout = new TH1F("PinMinPout", "(Pin - Pout)/Pin", 600, -2.0, 2.0);
calibinter = new TH1F("calibinter", "internal calibration constants", 800, 0.5, 2.);
PinOverPout = new TH1F("PinOverPout", "pinOverpout", 600, 0., 3.);
eSeedOverPout = new TH1F("eSeedOverPout", "eSeedOverpout ", 600, 0., 3.);
// MisCalibs = new TH1F("MisCalibs","Miscalibration constants",800,0.5,2.);
// RatioCalibs = new TH1F("RatioCalibs","Ratio in Calibration Constants", 800, 0.5, 2.0);
// DiffCalibs = new TH1F("DiffCalibs", "Difference in Calibration constants", 800, -1.0,1.0);
calibinterEndCapMinus = new TH1F("calibinterEndCapMinus", "internal calibration constants", 800, 0.5, 2.);
calibinterEndCapPlus = new TH1F("calibinterEndCapPlus", "internal calibration constants", 800, 0.5, 2.);
// MisCalibsEndCapMinus = new TH1F("MisCalibsEndCapMinus","Miscalibration constants",800,0.5,2.);
// MisCalibsEndCapPlus = new TH1F("MisCalibsEndCapPlus","Miscalibration constants",800,0.5,2.);
// RatioCalibsEndCapMinus = new TH1F("RatioCalibsEndCapMinus","Ratio in Calibration Constants", 800, 0.5, 2.0);
// RatioCalibsEndCapPlus = new TH1F("RatioCalibsEndCapPlus","Ratio in Calibration Constants", 800, 0.5, 2.0);
// DiffCalibsEndCapMinus = new TH1F("DiffCalibsEndCapMinus", "Difference in Calibration constants", 800, -1.0,1.0);
// DiffCalibsEndCapPlus = new TH1F("DiffCalibsEndCapPlus", "Difference in Calibration constants", 800, -1.0,1.0);
Error1 = new TH1F("Error1", "DeltaP/Pin", 800, -1.0, 1.0);
Error2 = new TH1F("Error2", "DeltaP/Pout", 800, -1.0, 1.0);
Error3 = new TH1F("Error3", "DeltaP/Pcalo", 800, -1.0, 1.0);
eSeedOverPout2 = new TH1F("eSeedOverPout2", "eSeedOverpout (No Supercluster)", 600, 0., 4.);
hadOverEm = new TH1F("hadOverEm", "Had/EM distribution", 600, -2., 2.);
// Book histograms
Map3DcalibNoCuts = new TH2F("3DcalibNoCuts", "3Dcalib (Before Cuts)", 173, -86, 86, 362, 0, 361);
e9NoCuts = new TH1F("e9NoCuts", "E9 energy (Before Cuts)", 300, 0., 150.);
e25NoCuts = new TH1F("e25NoCuts", "E25 energy (Before Cuts)", 300, 0., 150.);
scENoCuts = new TH1F("scENoCuts", "SC energy (Before Cuts)", 300, 0., 150.);
trPNoCuts = new TH1F("trPNoCuts", "Trk momentum (Before Cuts)", 300, 0., 150.);
EoPNoCuts = new TH1F("EoPNoCuts", "EoP (Before Cuts)", 600, 0., 3.);
calibsNoCuts = new TH1F("calibNoCuts", "Calibration constants (Before Cuts)", 800, 0., 2.);
e25OverScENoCuts = new TH1F("e25OverscENoCuts", "E25 / SC energy (Before Cuts)", 400, 0., 2.);
E25oPNoCuts = new TH1F("E25oPNoCuts", "E25 / P (Before Cuts)", 750, 0., 1.5);
MapEndCapMinus = new TH2F("MapEndCapMinus", "Nb Events in Crystal (EndCap)", 100, 0, 100, 100, 0, 100);
MapEndCapPlus = new TH2F("MapEndCapPlus", "Nb Events in Crystal (EndCap)", 100, 0, 100, 100, 0, 100);
e9Overe25NoCuts = new TH1F("e9Overe25NoCuts", "E9 / E25 (Before Cuts)", 400, 0., 2.);
PinOverPoutNoCuts = new TH1F("PinOverPoutNoCuts", "pinOverpout (Before Cuts)", 600, 0., 3.);
eSeedOverPoutNoCuts = new TH1F(" eSeedOverPoutNoCuts", "eSeedOverpout (Before Cuts) ", 600, 0., 4.);
PinMinPoutNoCuts = new TH1F("PinMinPoutNoCuts", "(Pin - Pout)/Pin (Before Cuts)", 600, -2.0, 2.0);
// RatioCalibsNoCuts = new TH1F("RatioCalibsNoCuts","Ratio in Calibration Constants (Before Cuts)", 800, 0.5, 2.0);
// DiffCalibsNoCuts = new TH1F("DiffCalibsNoCuts", "Difference in Calibration constants (Before Cuts)", 800, -1.0,1.0);
calibinterNoCuts = new TH1F("calibinterNoCuts", "internal calibration constants", 2000, 0.5, 2.);
MapCor1NoCuts =
new TH2F("MapCor1NoCuts", "Correlation E25/PatCalo versus E25/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor2NoCuts =
new TH2F("MapCor2NoCuts", "Correlation E25/PatCalo versus E/P (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor3NoCuts =
new TH2F("MapCor3NoCuts", "Correlation E25/PatCalo versus Pout/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor4NoCuts =
new TH2F("MapCor4NoCuts", "Correlation E25/PatCalo versus E25/highestP (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor5NoCuts =
new TH2F("MapCor5NoCuts", "Correlation E25/Pcalo versus Pcalo/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor6NoCuts =
new TH2F("MapCor6NoCuts", "Correlation Pout/Pin versus E25/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor7NoCuts =
new TH2F("MapCor7NoCuts", "Correlation Pout/Pin versus Pcalo/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor8NoCuts =
new TH2F("MapCor8NoCuts", "Correlation E25/Pin versus Pcalo/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor9NoCuts =
new TH2F("MapCor9NoCuts", "Correlation E25/Pcalo versus Eseed/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor10NoCuts =
new TH2F("MapCor10NoCuts", "Correlation Eseed/Pout versus Pout/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor11NoCuts =
new TH2F("MapCor11NoCuts", "Correlation Eseed/Pout versus E25/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
// MapCorCalibEndCapMinus = new TH2F ("MapCorCalibEndCapMinus", "Correlation Miscalibration versus Calibration constants (EndCap)", 500, 0.5,1.5, 500, 0.5, 1.5);
// MapCorCalibEndCapPlus = new TH2F ("MapCorCalibEndCapPlus", "Correlation Miscalibration versus Calibration constants (EndCap)", 500, 0.5,1.5, 500, 0.5, 1.5);
Error1NoCuts = new TH1F("Eror1NoCuts", "DeltaP/Pin (Before Cuts)", 800, -1.0, 1.0);
Error2NoCuts = new TH1F("Error2NoCuts", "DeltaP/Pout (Before Cuts)", 800, -1.0, 1.0);
Error3NoCuts = new TH1F("Error3NoCuts", "DeltaP/Pcalo (Before Cuts)", 800, -1.0, 1.0);
eSeedOverPout2NoCuts = new TH1F("eSeedOverPout2NoCuts", "eSeedOverpout (No Supercluster, Before Cuts)", 600, 0., 4.);
hadOverEmNoCuts = new TH1F("hadOverEmNoCuts", "Had/EM distribution (Before Cuts)", 600, -2., 2.);
//Book histograms after ESeed cut
MapCor1ESeed =
new TH2F("MapCor1ESeed", "Correlation E25/Pcalo versus E25/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor2ESeed =
new TH2F("MapCor2ESeed", "Correlation E25/Pcalo versus E/P (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor3ESeed = new TH2F(
"MapCor3ESeed", "Correlation E25/Pcalo versus Pout/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor4ESeed = new TH2F(
"MapCor4ESeed", "Correlation E25/Pcalo versus E25/highestP (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor5ESeed = new TH2F(
"MapCor5ESeed", "Correlation E25/Pcalo versus Pcalo/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor6ESeed =
new TH2F("MapCor6ESeed", "Correlation Pout/Pin versus E25/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor7ESeed = new TH2F(
"MapCor7ESeed", "Correlation Pout/Pin versus Pcalo/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor8ESeed = new TH2F(
"MapCor8ESeed", "Correlation E25/Pin versus Pcalo/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor9ESeed = new TH2F(
"MapCor9ESeed", "Correlation E25/Pcalo versus Eseed/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor10ESeed = new TH2F(
"MapCor10ESeed", "Correlation Eseed/Pout versus Pout/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor11ESeed = new TH2F(
"MapCor11ESeed", "Correlation Eseed/Pout versus E25/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
eSeedOverPout2ESeed =
new TH1F("eSeedOverPout2ESeed", "eSeedOverpout (No Supercluster, after Eseed/Pout cut)", 600, 0., 4.);
hadOverEmESeed = new TH1F("hadOverEmESeed", "Had/EM distribution (after Eseed/Pout cut)", 600, -2., 2.);
//Book histograms without any cut
GeneralMap = new TH2F("GeneralMap", "Map without any cuts", 173, -86, 86, 362, 0, 361);
GeneralMapEndCapMinus = new TH2F("GeneralMapEndCapMinus", "Map without any cuts", 100, 0, 100, 100, 0, 100);
GeneralMapEndCapPlus = new TH2F("GeneralMapEndCapPlus", "Map without any cuts", 100, 0, 100, 100, 0, 100);
GeneralMapBeforePt = new TH2F("GeneralMapBeforePt", "Map without any cuts", 173, -86, 86, 362, 0, 361);
GeneralMapEndCapMinusBeforePt =
new TH2F("GeneralMapEndCapMinusBeforePt", "Map without any cuts", 100, 0, 100, 100, 0, 100);
GeneralMapEndCapPlusBeforePt =
new TH2F("GeneralMapEndCapPlusBeforePt", "Map without any cuts", 100, 0, 100, 100, 0, 100);
calibClusterSize = clusterSize_;
etaMin = int(mineta_);
etaMax = int(maxeta_);
phiMin = int(minphi_);
phiMax = int(maxphi_);
if (calibAlgo_ == "L3") {
MyL3Algo1 = new MinL3Algorithm(keventweight_, calibClusterSize, etaMin, etaMax, phiMin, phiMax);
} else {
if (calibAlgo_ == "L3Univ") {
UnivL3 = new MinL3AlgoUniv<DetId>(keventweight_);
} else {
if (calibAlgo_ == "HH" || calibAlgo_ == "HHReg") {
MyHH = new HouseholderDecomposition(calibClusterSize, etaMin, etaMax, phiMin, phiMax);
} else {
std::cout << " Name of Algorithm is not recognize " << calibAlgo_
<< " Should be either L3, HH or HHReg. Abort! " << std::endl;
}
}
}
read_events = 0;
}
//========================================================================
void ElectronCalibrationUniv::beginRun(edm::Run const&, edm::EventSetup const& iSetup) {
//========================================================================
//To Deal with Geometry:
theCaloTopology_ = &iSetup.getData(topologyToken_);
}
//========================================================================
void ElectronCalibrationUniv::endRun(edm::Run const&, edm::EventSetup const& iSetup) {}
//========================================================================
//========================================================================
void ElectronCalibrationUniv::endJob() {
//========================================================================
f->cd();
time_t start, end;
time_t cpu_time_used;
start = time(nullptr);
//In order to do only one loop to use properly looper properties, ask only for 1 iterations!
int nIterations = 10;
if (calibAlgo_ == "L3") {
solution = MyL3Algo1->iterate(EventMatrix, MaxCCeta, MaxCCphi, EnergyVector, nIterations);
} else {
if (calibAlgo_ == "L3Univ") {
//Univsolution= UnivL3->getSolution();
// std::cout<<" Should derive solution "<<EnergyVector.size()<<std::endl;
Univsolution = UnivL3->iterate(EventMatrix, UnivEventIds, EnergyVector, nIterations);
//std::cout<<" solution size "<<Univsolution.size()<<std::endl;
} else {
if (calibAlgo_ == "HH") {
solution = MyHH->iterate(EventMatrix, MaxCCeta, MaxCCphi, EnergyVector, 1, false);
} else {
if (calibAlgo_ == "HHReg") {
solution = MyHH->runRegional(EventMatrix, MaxCCeta, MaxCCphi, EnergyVector, 2);
} else {
std::cout << " Calibration not run due to problem in Algo Choice..." << std::endl;
return;
}
}
}
}
end = time(nullptr);
cpu_time_used = end - start;
// std::cout<<"222 solution size "<<Univsolution.size()<<std::endl;
calibXMLwriter write_calibrations;
// FILE* MisCalib;
// //char* calibfile="miscalibfile";
// MisCalib = fopen(miscalibfile_.c_str(),"r");
// int fileStatus=0;
// int eta=-1;
// int phi=-1;
// float coeff=-1;
std::map<EBDetId, float> OldCoeff;
// while(fileStatus != EOF) {
// fileStatus = fscanf(MisCalib,"%d %d %f\n", &eta,&phi,&coeff);
// if(eta!=-1&&phi!=-1&& coeff!=-1){
// // std::cout<<" We have read correctly the coefficient " << coeff << " corresponding to eta "<<eta<<" and phi "<<phi<<std::endl;
// OldCoeff.insert(std::make_pair(EBDetId(eta,phi,EBDetId::ETAPHIMODE),coeff ));
// }
// }
// fclose(MisCalib);
// FILE* MisCalibEndCap;
// //char* calibfile="miscalibfile";
// MisCalibEndCap = fopen(miscalibfileEndCap_.c_str(),"r");
// int fileStatus2=0;
// int X=-1;
// int Y=-1;
// float coeff2=-1;
std::map<EEDetId, float> OldCoeffEndCap;
// while(fileStatus2 != EOF) {
// fileStatus2 = fscanf(MisCalibEndCap,"%d %d %f\n", &X,&Y,&coeff2);
// if(X!=-1&&Y!=-1&& coeff2!=-1){
// // std::cout<<" We have read correctly the coefficient " << coeff << " corresponding to eta "<<eta<<" and phi "<<phi<<std::endl;
// if(TestEEvalidDetId(X,Y,1)){
// OldCoeffEndCap.insert(std::make_pair(EEDetId(X,Y,1,EEDetId::XYMODE),coeff2 ));
// }
// }
// }
// fclose(MisCalibEndCap);
std::map<DetId, float>::const_iterator itmap;
for (itmap = Univsolution.begin(); itmap != Univsolution.end(); itmap++) {
const DetId Id(itmap->first);
if (Id.subdetId() == 1) {
const EBDetId IChannelDetId(itmap->first);
if (IChannelDetId.ieta() < mineta_) {
continue;
}
if (IChannelDetId.ieta() > maxeta_) {
continue;
}
if (IChannelDetId.iphi() < minphi_) {
continue;
}
if (IChannelDetId.iphi() > maxphi_) {
continue;
}
// float Compare=1;
// std::map<EBDetId,float>::iterator iter = OldCoeff.find(itmap->first);
// if( iter != OldCoeff.end() )Compare = iter->second;
Map3Dcalib->Fill(IChannelDetId.ieta(), IChannelDetId.iphi(), itmap->second);
calibs->Fill(itmap->second);
//DiffCalibs->Fill(newCalibs[icry]-miscalib[IChannelDetId.ieta()-1][IChannelDetId.iphi()-21]);
//RatioCalibs->Fill(newCalibs[icry]/miscalib[IChannelDetId.ieta()-1][IChannelDetId.iphi()-21]);
if (IChannelDetId.ieta() < mineta_ + 2) {
continue;
}
if (IChannelDetId.ieta() > maxeta_ - 2) {
continue;
}
if (IChannelDetId.iphi() < minphi_ + 2) {
continue;
}
if (IChannelDetId.iphi() > maxphi_ - 2) {
continue;
}
write_calibrations.writeLine(IChannelDetId, itmap->second);
calibinter->Fill(itmap->second);
// MapCorCalib->Fill(itmap->second,Compare);
// DiffCalibs->Fill(itmap->second-Compare);
// RatioCalibs->Fill(itmap->second*Compare);
} else {
const EEDetId IChannelDetId(itmap->first);
// if (IChannelDetId.ix()<0 ){continue;}
// if (IChannelDetId.ix()>100 ){continue;}
// if (IChannelDetId.iy()<0 ){continue;}
// if (IChannelDetId.iy()>100 ){continue;}
// std::map<EEDetId,float>::iterator iter = OldCoeffEndCap.find(itmap->first);
// float Compare=1;
// if( iter != OldCoeffEndCap.end() )Compare = iter->second;
if (IChannelDetId.zside() < 0) {
Map3DcalibEndCapMinus->Fill(IChannelDetId.ix(), IChannelDetId.iy(), itmap->second);
calibsEndCapMinus->Fill(itmap->second);
calibinterEndCapMinus->Fill(itmap->second);
// DiffCalibsEndCapMinus->Fill(itmap->second-Compare);
// RatioCalibsEndCapMinus->Fill(itmap->second*Compare);
// MapCorCalibEndCapMinus->Fill(itmap->second,Compare);
} else {
Map3DcalibEndCapPlus->Fill(IChannelDetId.ix(), IChannelDetId.iy(), itmap->second);
calibsEndCapPlus->Fill(itmap->second);
calibinterEndCapPlus->Fill(itmap->second);
// DiffCalibsEndCapPlus->Fill(itmap->second-Compare);
// RatioCalibsEndCapPlus->Fill(itmap->second*Compare);
// MapCorCalibEndCapPlus->Fill(itmap->second,Compare);
}
write_calibrations.writeLine(IChannelDetId, itmap->second);
}
}
EventsAfterCuts->Write();
// Book histograms
e25->Write();
e9->Write();
scE->Write();
trP->Write();
EoP->Write();
EoP_all->Write();
calibs->Write();
calibsEndCapMinus->Write();
calibsEndCapPlus->Write();
e9Overe25->Write();
e25OverScE->Write();
Map->Write();
E25oP->Write();
PinOverPout->Write();
eSeedOverPout->Write();
// MisCalibs->Write();
// RatioCalibs->Write();
// DiffCalibs->Write();
// RatioCalibsNoCuts->Write();
// DiffCalibsNoCuts->Write();
// MisCalibsEndCapMinus->Write();
// MisCalibsEndCapPlus->Write();
// RatioCalibsEndCapMinus->Write();
// RatioCalibsEndCapPlus->Write();
// DiffCalibsEndCapMinus->Write();
// DiffCalibsEndCapPlus->Write();
e25NoCuts->Write();
e9NoCuts->Write();
scENoCuts->Write();
trPNoCuts->Write();
EoPNoCuts->Write();
calibsNoCuts->Write();
e9Overe25NoCuts->Write();
e25OverScENoCuts->Write();
MapEndCapMinus->Write();
MapEndCapPlus->Write();
E25oPNoCuts->Write();
Map3Dcalib->Write();
Map3DcalibEndCapMinus->Write();
Map3DcalibEndCapPlus->Write();
Map3DcalibNoCuts->Write();
calibinter->Write();
calibinterEndCapMinus->Write();
calibinterEndCapPlus->Write();
calibinterNoCuts->Write();
PinOverPoutNoCuts->Write();
eSeedOverPoutNoCuts->Write();
GeneralMap->Write();
GeneralMapEndCapMinus->Write();
GeneralMapEndCapPlus->Write();
GeneralMapBeforePt->Write();
GeneralMapEndCapMinusBeforePt->Write();
GeneralMapEndCapPlusBeforePt->Write();
MapCor1->Write();
MapCor2->Write();
MapCor3->Write();
MapCor4->Write();
MapCor5->Write();
MapCor6->Write();
MapCor7->Write();
MapCor8->Write();
MapCor9->Write();
MapCor10->Write();
MapCor11->Write();
// MapCorCalib->Write();
MapCor1NoCuts->Write();
MapCor2NoCuts->Write();
MapCor3NoCuts->Write();
MapCor4NoCuts->Write();
MapCor5NoCuts->Write();
MapCor6NoCuts->Write();
MapCor7NoCuts->Write();
MapCor8NoCuts->Write();
MapCor9NoCuts->Write();
MapCor10NoCuts->Write();
MapCor11NoCuts->Write();
// MapCorCalibEndCapMinus->Write();
// MapCorCalibEndCapPlus->Write();
MapCor1ESeed->Write();
MapCor2ESeed->Write();
MapCor3ESeed->Write();
MapCor4ESeed->Write();
MapCor5ESeed->Write();
MapCor6ESeed->Write();
MapCor7ESeed->Write();
MapCor8ESeed->Write();
MapCor9ESeed->Write();
MapCor10ESeed->Write();
MapCor11ESeed->Write();
E25oPvsEta->Write();
E25oPvsEtaEndCapMinus->Write();
E25oPvsEtaEndCapPlus->Write();
PinMinPout->Write();
PinMinPoutNoCuts->Write();
Error1->Write();
Error2->Write();
Error3->Write();
Error1NoCuts->Write();
Error2NoCuts->Write();
Error3NoCuts->Write();
eSeedOverPout2->Write();
eSeedOverPout2NoCuts->Write();
eSeedOverPout2ESeed->Write();
hadOverEm->Write();
hadOverEmNoCuts->Write();
hadOverEmESeed->Write();
f->Write();
f->Close();
// if(MyL3Algo1)delete MyL3Algo1;
// if(UnivL3)delete UnivL3;
// if(MyHH)delete MyHH;
// delete f;
//////////////////////// FINAL STATISTICS ////////////////////
std::cout << " " << std::endl;
std::cout << "************* STATISTICS **************" << std::endl;
std::cout << " Events Studied " << read_events << std::endl;
std::cout << "Timing info:" << std::endl;
std::cout << "CPU time usage -- calibrating: " << cpu_time_used << " sec." << std::endl;
/////////////////////////////////////////////////////////////////////////////
}
DetId ElectronCalibrationUniv::findMaxHit(const std::vector<DetId>& v1,
const EBRecHitCollection* EBhits,
const EERecHitCollection* EEhits) {
//=================================================================================
double currEnergy = 0.;
DetId maxHit;
for (std::vector<DetId>::const_iterator idsIt = v1.begin(); idsIt != v1.end(); ++idsIt) {
if (idsIt->subdetId() == 1) {
EBRecHitCollection::const_iterator itrechit;
itrechit = EBhits->find(*idsIt);
if (itrechit == EBhits->end()) {
std::cout << "ElectronCalibration::findMaxHit: rechit not found! " << (EBDetId)(*idsIt) << std::endl;
continue;
}
if (itrechit->energy() > currEnergy) {
currEnergy = itrechit->energy();
maxHit = *idsIt;
}
} else {
EERecHitCollection::const_iterator itrechit;
itrechit = EEhits->find(*idsIt);
if (itrechit == EEhits->end()) {
std::cout << "ElectronCalibration::findMaxHit: rechit not found! idsIt = " << (EEDetId)(*idsIt) << std::endl;
continue;
}
if (itrechit->energy() > currEnergy) {
currEnergy = itrechit->energy();
maxHit = *idsIt;
}
}
}
return maxHit;
}
bool ElectronCalibrationUniv::TestEEvalidDetId(int crystal_ix, int crystal_iy, int iz) {
bool valid = false;
if (crystal_ix < 1 || crystal_ix > 100 || crystal_iy < 1 || crystal_iy > 100 || abs(iz) != 1) {
return valid;
}
if ((crystal_ix >= 1 && crystal_ix <= 3 && (crystal_iy <= 40 || crystal_iy > 60)) ||
(crystal_ix >= 4 && crystal_ix <= 5 && (crystal_iy <= 35 || crystal_iy > 65)) ||
(crystal_ix >= 6 && crystal_ix <= 8 && (crystal_iy <= 25 || crystal_iy > 75)) ||
(crystal_ix >= 9 && crystal_ix <= 13 && (crystal_iy <= 20 || crystal_iy > 80)) ||
(crystal_ix >= 14 && crystal_ix <= 15 && (crystal_iy <= 15 || crystal_iy > 85)) ||
(crystal_ix >= 16 && crystal_ix <= 20 && (crystal_iy <= 13 || crystal_iy > 87)) ||
(crystal_ix >= 21 && crystal_ix <= 25 && (crystal_iy <= 8 || crystal_iy > 92)) ||
(crystal_ix >= 26 && crystal_ix <= 35 && (crystal_iy <= 5 || crystal_iy > 95)) ||
(crystal_ix >= 36 && crystal_ix <= 39 && (crystal_iy <= 3 || crystal_iy > 97)) ||
(crystal_ix >= 98 && crystal_ix <= 100 && (crystal_iy <= 40 || crystal_iy > 60)) ||
(crystal_ix >= 96 && crystal_ix <= 97 && (crystal_iy <= 35 || crystal_iy > 65)) ||
(crystal_ix >= 93 && crystal_ix <= 95 && (crystal_iy <= 25 || crystal_iy > 75)) ||
(crystal_ix >= 88 && crystal_ix <= 92 && (crystal_iy <= 20 || crystal_iy > 80)) ||
(crystal_ix >= 86 && crystal_ix <= 87 && (crystal_iy <= 15 || crystal_iy > 85)) ||
(crystal_ix >= 81 && crystal_ix <= 85 && (crystal_iy <= 13 || crystal_iy > 87)) ||
(crystal_ix >= 76 && crystal_ix <= 80 && (crystal_iy <= 8 || crystal_iy > 92)) ||
(crystal_ix >= 66 && crystal_ix <= 75 && (crystal_iy <= 5 || crystal_iy > 95)) ||
(crystal_ix >= 62 && crystal_ix <= 65 && (crystal_iy <= 3 || crystal_iy > 97)) ||
((crystal_ix == 40 || crystal_ix == 61) &&
((crystal_iy >= 46 && crystal_iy <= 55) || crystal_iy <= 3 || crystal_iy > 97)) ||
((crystal_ix == 41 || crystal_ix == 60) && crystal_iy >= 44 && crystal_iy <= 57) ||
((crystal_ix == 42 || crystal_ix == 59) && crystal_iy >= 43 && crystal_iy <= 58) ||
((crystal_ix == 43 || crystal_ix == 58) && crystal_iy >= 42 && crystal_iy <= 59) ||
((crystal_ix == 44 || crystal_ix == 45 || crystal_ix == 57 || crystal_ix == 56) && crystal_iy >= 41 &&
crystal_iy <= 60) ||
(crystal_ix >= 46 && crystal_ix <= 55 && crystal_iy >= 40 && crystal_iy <= 61)) {
return valid;
}
valid = true;
return valid;
}
//=================================================================================
void ElectronCalibrationUniv::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
//=================================================================================
using namespace edm;
// Get EBRecHits
edm::Handle<EBRecHitCollection> EBphits;
iEvent.getByToken(ebRecHitToken_, EBphits);
if (!EBphits.isValid()) {
std::cerr << "Error! can't get the product EBRecHitCollection: " << std::endl;
}
const EBRecHitCollection* EBhits = EBphits.product(); // get a ptr to the product
// Get EERecHits
edm::Handle<EERecHitCollection> EEphits;
iEvent.getByToken(eeRecHitToken_, EEphits);
if (!EEphits.isValid()) {
std::cerr << "Error! can't get the product EERecHitCollection: " << std::endl;
}
const EERecHitCollection* EEhits = EEphits.product(); // get a ptr to the product
// Get pixelElectrons
edm::Handle<reco::GsfElectronCollection> pElectrons;
iEvent.getByToken(gsfElectronToken_, pElectrons);
if (!pElectrons.isValid()) {
std::cerr << "Error! can't get the product ElectronCollection: " << std::endl;
}
const reco::GsfElectronCollection* electronCollection = pElectrons.product();
read_events++;
if (read_events % 1000 == 0)
std::cout << "read_events = " << read_events << std::endl;
EventsAfterCuts->Fill(1);
if (!EBhits || !EEhits)
return;
EventsAfterCuts->Fill(2);
if (EBhits->empty() && EEhits->empty())
return;
EventsAfterCuts->Fill(3);
if (!electronCollection)
return;
EventsAfterCuts->Fill(4);
if (electronCollection->empty())
return;
// ////////////////Need to recalibrate the events (copy code from EcalRecHitRecalib):
////////////////////////////////////////////////////////////////////////////////////////
/// START HERE....
///////////////////////////////////////////////////////////////////////////////////////
reco::GsfElectronCollection::const_iterator eleIt = electronCollection->begin();
reco::GsfElectron highPtElectron;
float highestElePt = 0.;
bool found = false;
for (eleIt = electronCollection->begin(); eleIt != electronCollection->end(); eleIt++) {
if (fabs(eleIt->eta()) > 2.4)
continue;
// if(eleIt->eta()<0.0) continue;
if (eleIt->pt() > highestElePt) {
highestElePt = eleIt->pt();
highPtElectron = *eleIt;
found = true;
// std::cout<<" eleIt->pt( "<<eleIt->pt()<<" eleIt->eta() "<<eleIt->eta()<<std::endl;
}
}
EventsAfterCuts->Fill(5);
if (!found)
return;
const reco::SuperCluster& sc = *(highPtElectron.superCluster());
// if(fabs(sc.eta())>1.479){std::cout<<" SC not in Barrel "<<sc.eta()<<std::endl;;}
// const std::vector<DetId> & v1 = sc.getHitsByDetId();
std::vector<DetId> v1;
//Loop to fill the vector of DetIds
for (std::vector<std::pair<DetId, float> >::const_iterator idsIt = sc.hitsAndFractions().begin();
idsIt != sc.hitsAndFractions().end();
++idsIt) {
v1.push_back(idsIt->first);
}
DetId maxHitId;
maxHitId = findMaxHit(v1, (EBhits), (EEhits));
//maxHitId = findMaxHit(v1,EBhits,EEhits);
EventsAfterCuts->Fill(6);
if (maxHitId.null()) {
std::cout << " Null " << std::endl;
return;
}
int maxCC_Eta = 0;
int maxCC_Phi = 0;
int Zside = 0;
if (maxHitId.subdetId() != 1) {
maxCC_Eta = ((EEDetId)maxHitId).ix();
maxCC_Phi = ((EEDetId)maxHitId).iy();
Zside = ((EEDetId)maxHitId).zside();
// std::cout<<" ++++++++ Zside "<<Zside<<std::endl;
} else {
maxCC_Eta = ((EBDetId)maxHitId).ieta();
maxCC_Phi = ((EBDetId)maxHitId).iphi();
}
// if(maxCC_Eta>maxeta_ ) ;
// if(maxCC_Eta<mineta_ ) ;
// number of events per crystal is set
// eventcrystal[maxCC_Eta][maxCC_Phi]+=1;
// if(eventcrystal[maxCC_Eta][maxCC_Phi] > numevent_) ;
// fill cluster energy
std::vector<float> energy;
float energy3x3 = 0.;
float energy5x5 = 0.;
//Should be moved to cfg file!
int ClusterSize = clusterSize_;
const CaloSubdetectorTopology* topology = theCaloTopology_->getSubdetectorTopology(DetId::Ecal, maxHitId.subdetId());
std::vector<DetId> NxNaroundMax = topology->getWindow(maxHitId, ClusterSize, ClusterSize);
//ToCompute 3x3
std::vector<DetId> S9aroundMax = topology->getWindow(maxHitId, 3, 3);
EventsAfterCuts->Fill(7);
if ((int)NxNaroundMax.size() != ClusterSize * ClusterSize)
return;
EventsAfterCuts->Fill(8);
if (S9aroundMax.size() != 9)
return;
// std::cout<<" ******** New Event "<<std::endl;
EventsAfterCuts->Fill(9);
for (int icry = 0; icry < ClusterSize * ClusterSize; icry++) {
if (NxNaroundMax[icry].subdetId() == EcalBarrel) {
EBRecHitCollection::const_iterator itrechit;
itrechit = EBhits->find(NxNaroundMax[icry]);
if (itrechit == EBhits->end()) {
// std::cout << "EB DetId not in e25" << std::endl;
energy.push_back(0.);
energy5x5 += 0.;
continue;
}
if (edm::isNotFinite(itrechit->energy())) {
std::cout << " nan energy " << std::endl;
return;
}
energy.push_back(itrechit->energy());
energy5x5 += itrechit->energy();
//Summing in 3x3 to cut later on:
for (int tt = 0; tt < 9; tt++) {
if (NxNaroundMax[icry] == S9aroundMax[tt])
energy3x3 += itrechit->energy();
}
} else {
EERecHitCollection::const_iterator itrechit;
itrechit = EEhits->find(NxNaroundMax[icry]);
if (itrechit == EEhits->end()) {
// std::cout << "EE DetId not in e25" << std::endl;
// std::cout<<" ******** putting 0 "<<std::endl;
energy.push_back(0.);
energy5x5 += 0.;
continue;
}
if (edm::isNotFinite(itrechit->energy())) {
std::cout << " nan energy " << std::endl;
return;
}
energy.push_back(itrechit->energy());
energy5x5 += itrechit->energy();
//Summing in 3x3 to cut later on:
for (int tt = 0; tt < 9; tt++) {
if (NxNaroundMax[icry] == S9aroundMax[tt])
energy3x3 += itrechit->energy();
}
}
}
// if((read_events-50)%10000 ==0)cout << "++++++++++++ENERGY 5x5 " << energy5x5 << std::endl;
EventsAfterCuts->Fill(10);
// std::cout<<" ******** NxNaroundMax.size() "<<NxNaroundMax.size()<<std::endl;
// std::cout<<" ******** energy.size() "<<energy.size()<<std::endl;
if ((int)energy.size() != ClusterSize * ClusterSize)
return;
if (maxHitId.subdetId() == EcalBarrel) {
GeneralMapBeforePt->Fill(maxCC_Eta, maxCC_Phi);
} else {
if (Zside < 0) {
GeneralMapEndCapMinusBeforePt->Fill(maxCC_Eta, maxCC_Phi);
} else {
GeneralMapEndCapPlusBeforePt->Fill(maxCC_Eta, maxCC_Phi);
}
}
EventsAfterCuts->Fill(11);
if (highestElePt < elePt_)
return;
if (maxHitId.subdetId() == EcalBarrel) {
GeneralMap->Fill(maxCC_Eta, maxCC_Phi);
} else {
if (Zside < 0) {
GeneralMapEndCapMinus->Fill(maxCC_Eta, maxCC_Phi);
} else {
GeneralMapEndCapPlus->Fill(maxCC_Eta, maxCC_Phi);
}
}
EventsAfterCuts->Fill(12);
if (highPtElectron.classification() != elecclass_ && elecclass_ != -1)
return;
float Ptrack_in =
sqrt(pow(highPtElectron.trackMomentumAtVtx().X(), 2) + pow(highPtElectron.trackMomentumAtVtx().Y(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Z(), 2));
float UncorrectedPatCalo =
sqrt(pow(highPtElectron.trackMomentumAtCalo().X(), 2) + pow(highPtElectron.trackMomentumAtCalo().Y(), 2) +
pow(highPtElectron.trackMomentumAtCalo().Z(), 2));
float Ptrack_out =
sqrt(pow(highPtElectron.trackMomentumOut().X(), 2) + pow(highPtElectron.trackMomentumOut().Y(), 2) +
pow(highPtElectron.trackMomentumOut().Z(), 2));
e9NoCuts->Fill(energy3x3);
e25NoCuts->Fill(energy5x5);
e9Overe25NoCuts->Fill(energy3x3 / energy5x5);
scENoCuts->Fill(sc.energy());
trPNoCuts->Fill(UncorrectedPatCalo);
EoPNoCuts->Fill(highPtElectron.eSuperClusterOverP());
e25OverScENoCuts->Fill(energy5x5 / sc.energy());
E25oPNoCuts->Fill(energy5x5 / UncorrectedPatCalo);
PinOverPoutNoCuts->Fill(
sqrt(pow(highPtElectron.trackMomentumAtVtx().X(), 2) + pow(highPtElectron.trackMomentumAtVtx().Y(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Z(), 2)) /
sqrt(pow(highPtElectron.trackMomentumOut().X(), 2) + pow(highPtElectron.trackMomentumOut().Y(), 2) +
pow(highPtElectron.trackMomentumOut().Z(), 2)));
eSeedOverPoutNoCuts->Fill(highPtElectron.eSuperClusterOverP());
MapCor1NoCuts->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / Ptrack_in);
MapCor2NoCuts->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSuperClusterOverP());
MapCor3NoCuts->Fill(energy5x5 / UncorrectedPatCalo, Ptrack_out / Ptrack_in);
MapCor4NoCuts->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / highPtElectron.p());
MapCor5NoCuts->Fill(energy5x5 / UncorrectedPatCalo, UncorrectedPatCalo / Ptrack_out);
MapCor6NoCuts->Fill(Ptrack_out / Ptrack_in, energy5x5 / Ptrack_in);
MapCor7NoCuts->Fill(Ptrack_out / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor8NoCuts->Fill(energy5x5 / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor9NoCuts->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSeedClusterOverPout());
MapCor10NoCuts->Fill(highPtElectron.eSeedClusterOverPout(), Ptrack_out / Ptrack_in);
MapCor11NoCuts->Fill(highPtElectron.eSeedClusterOverPout(), energy5x5 / Ptrack_in);
PinMinPoutNoCuts->Fill((Ptrack_in - Ptrack_out) / Ptrack_in);
Error1NoCuts->Fill(highPtElectron.trackMomentumError() / Ptrack_in);
Error2NoCuts->Fill(highPtElectron.trackMomentumError() / Ptrack_out);
Error3NoCuts->Fill(highPtElectron.trackMomentumError() / UncorrectedPatCalo);
eSeedOverPout2NoCuts->Fill(highPtElectron.eSeedClusterOverPout());
hadOverEmNoCuts->Fill(highPtElectron.hadronicOverEm());
//Cuts!
if ((energy3x3 / energy5x5) < cut1_)
return;
if ((Ptrack_out / Ptrack_in) < cut2_ || (Ptrack_out / Ptrack_in) > cut3_)
return;
if ((energy5x5 / Ptrack_in) < cutEPin1_ || (energy5x5 / Ptrack_in) > cutEPin2_)
return;
// if(!highPtElectron.ecalDriven())return;
// if(!highPtElectron.passingCutBasedPreselection())return;
// // Apply Pietro cuts:
// EventsAfterCuts->Fill(13);
// //Module 1
// if(maxHitId.subdetId() == EcalBarrel){
// //Module 1
// if(maxCC_Eta <= 25){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.4 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// //Module 2
// if( maxCC_Eta > 25&& maxCC_Eta <= 45){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.25 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// //Module 3
// if( maxCC_Eta > 45&& maxCC_Eta <= 65){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }else{
// if( maxCC_Eta > 65&& maxCC_Eta <= 85){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }else{
// return;
// }
// }
// }
// }
// }else{
// //EndCapMinus Side:
// //EndCapPlus Side:
// int iR = sqrt((maxCC_Eta-50)*(maxCC_Eta-50) + (maxCC_Phi-50)*(maxCC_Phi-50));
// if( iR >= 22&& iR < 27){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// if( iR >= 27&& iR < 32){
// if(highPtElectron.eSuperClusterOverP()>1.1 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.25 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// if( iR >= 32&& iR < 37){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// if( iR >= 37&& iR < 42){
// if(highPtElectron.eSuperClusterOverP()>1.1 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }else{
// if( iR >= 42){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }
// }
// }
// }
// }
// }
if (maxHitId.subdetId() == EcalBarrel) {
E25oPvsEta->Fill(maxCC_Eta, energy5x5 / UncorrectedPatCalo);
} else {
float Radius = sqrt((maxCC_Eta) * (maxCC_Eta) + (maxCC_Phi) * (maxCC_Phi));
if (Zside < 0) {
E25oPvsEtaEndCapMinus->Fill(Radius, energy5x5 / UncorrectedPatCalo);
} else {
E25oPvsEtaEndCapPlus->Fill(Radius, energy5x5 / UncorrectedPatCalo);
}
}
e9->Fill(energy3x3);
e25->Fill(energy5x5);
e9Overe25->Fill(energy3x3 / energy5x5);
scE->Fill(sc.energy());
trP->Fill(UncorrectedPatCalo);
EoP->Fill(highPtElectron.eSuperClusterOverP());
e25OverScE->Fill(energy5x5 / sc.energy());
E25oP->Fill(energy5x5 / UncorrectedPatCalo);
if (maxHitId.subdetId() == EcalBarrel) {
Map->Fill(maxCC_Eta, maxCC_Phi);
} else {
if (Zside < 0) {
MapEndCapMinus->Fill(maxCC_Eta, maxCC_Phi);
} else {
MapEndCapPlus->Fill(maxCC_Eta, maxCC_Phi);
}
}
PinOverPout->Fill(sqrt(pow(highPtElectron.trackMomentumAtVtx().X(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Y(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Z(), 2)) /
sqrt(pow(highPtElectron.trackMomentumOut().X(), 2) + pow(highPtElectron.trackMomentumOut().Y(), 2) +
pow(highPtElectron.trackMomentumOut().Z(), 2)));
eSeedOverPout->Fill(highPtElectron.eSuperClusterOverP());
MapCor1->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / Ptrack_in);
MapCor2->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSuperClusterOverP());
MapCor3->Fill(energy5x5 / UncorrectedPatCalo, Ptrack_out / Ptrack_in);
MapCor4->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / highPtElectron.p());
MapCor5->Fill(energy5x5 / UncorrectedPatCalo, UncorrectedPatCalo / Ptrack_out);
MapCor6->Fill(Ptrack_out / Ptrack_in, energy5x5 / Ptrack_in);
MapCor7->Fill(Ptrack_out / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor8->Fill(energy5x5 / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor9->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSeedClusterOverPout());
MapCor10->Fill(highPtElectron.eSeedClusterOverPout(), Ptrack_out / Ptrack_in);
MapCor11->Fill(highPtElectron.eSeedClusterOverPout(), energy5x5 / Ptrack_in);
PinMinPout->Fill((Ptrack_in - Ptrack_out) / Ptrack_in);
Error1->Fill(highPtElectron.trackMomentumError() / Ptrack_in);
Error2->Fill(highPtElectron.trackMomentumError() / Ptrack_out);
Error3->Fill(highPtElectron.trackMomentumError() / UncorrectedPatCalo);
eSeedOverPout2->Fill(highPtElectron.eSeedClusterOverPout());
hadOverEm->Fill(highPtElectron.hadronicOverEm());
UnivEventIds.push_back(NxNaroundMax);
EventMatrix.push_back(energy);
EnergyVector.push_back(UncorrectedPatCalo);
EventsAfterCuts->Fill(14);
if (!highPtElectron.ecalDrivenSeed())
EventsAfterCuts->Fill(15);
return;
}
DEFINE_FWK_MODULE(ElectronCalibrationUniv);
| 45,547 | 19,513 |
#include <iostream>
#include <functional>
#include <unistd.h>
#include "Command_Client_Engine.h"
#include "state.h"
#include "render.h"
#include "engine.h"
using namespace client;
using namespace render;
using namespace engine;
using namespace state;
using namespace std;
Command_Client_Engine::Command_Client_Engine() {
}
Command_Client_Engine::~Command_Client_Engine(){
}
void Command_Client_Engine::execute() {
cout << "TEST ENGINE" << endl;
Engine engine;
engine.getState().setMode("engine");
engine.getState().initPlayers();
engine.getState().initCharacters();
engine.getState().initMapCell();
cout << " INIT DONE" << endl;
sf::RenderWindow window(sf::VideoMode(32 * 26 + 500, 32 * 24), "Zorglub");
StateLayer stateLayer(engine.getState(), window);
stateLayer.initTextureArea(engine.getState());
StateLayer *ptr_stateLayer = &stateLayer;
engine.getState().registerObserver(ptr_stateLayer);
bool booting = true;
bool firstround = true;
bool secondroun = false;
bool thirdround = false;
bool fourround = false;
bool fiveround = false;
bool sixround = false;
int p1X;
int p1Y;
int p2X;
int p2Y;
int priority;
// hard code health bc its loong either wise
engine.getState().getListCharacters(0)[0]->setNewHealth(25);
engine.getState().getListCharacters(0)[0]->setPrecision(15, 15, 15, 15);// precision to 1
engine.getState().getListCharacters(0)[0]->setDodge(8, 8);// set dodge to 0
engine.getState().getListCharacters(1)[0]->setNewHealth(25);
engine.getState().getListCharacters(1)[0]->setPrecision(15, 15, 15, 15);// precision to 1
engine.getState().getListCharacters(1)[0]->setDodge(8, 8);// set dodge to 0
engine.getState().getListCharacters(1)[0]->getCharWeap()->setTypeCapab(TELEPORT); // Teleport Capacity
while (window.isOpen()) {
sf::Event event;
if (booting) {
stateLayer.draw(window);
booting = false;
}
while (1) {
if (firstround) {
p1X = engine.getState().getListCharacters(0)[0]->getPosition().getX();
p1Y = engine.getState().getListCharacters(0)[0]->getPosition().getY();
int priority = 0;
cout << "[Player 1] Character pos( " << engine.getState().getListCharacters(0)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(0)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p1X, ++p1Y};
unique_ptr <engine::Command> ptr_mc1(
new engine::Move_Command(*engine.getState().getListCharacters(0)[0], pos1));
engine.addCommand(move(ptr_mc1), priority++);
cout << "MOVE FROM pos(" << p1X << "," << p1Y << ")" << " TO " << "(" << p1X << "," << p1Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(0)[0]->getMovementLeft() == 0) {
engine.getState().setCurAction(ATTACKING); // Hard set Attacking mode
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
firstround = false;
secondroun = true;
}
engine.update();
}
if (secondroun) {
engine.getState().setCurAction(IDLE);
//Player 2
p2X = engine.getState().getListCharacters(1)[0]->getPosition().getX();
p2Y = engine.getState().getListCharacters(1)[0]->getPosition().getY();
priority = 0;
cout << "[Player 2] Character pos( " << engine.getState().getListCharacters(1)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(1)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p2X, --p2Y};
unique_ptr <engine::Command> ptr_mc2(
new engine::Move_Command(*engine.getState().getListCharacters(1)[0], pos1));
engine.addCommand(move(ptr_mc2), priority++);
cout << "MOVE FROM pos(" << p2X << "," << p2Y << ")" << " TO " << "(" << p2X << "," << p2Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(1)[0]->getMovementLeft() == 0) {
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
secondroun = false;
thirdround = true;
}
engine.update();
}
if (thirdround) {
engine.getState().setCurAction(IDLE);
p1X = engine.getState().getListCharacters(0)[0]->getPosition().getX();
p1Y = engine.getState().getListCharacters(0)[0]->getPosition().getY();
int priority = 0;
cout << "[Player 1] Character pos( " << engine.getState().getListCharacters(0)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(0)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p1X, ++p1Y};
unique_ptr <engine::Command> ptr_mc1(
new engine::Move_Command(*engine.getState().getListCharacters(0)[0], pos1));
engine.addCommand(move(ptr_mc1), priority++);
cout << "MOVE FROM pos(" << p1X << "," << p1Y << ")" << " TO " << "(" << p1X << "," << p1Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(0)[0]->getMovementLeft() == 0) {
engine.getState().setCurAction(ATTACKING); // Hard set Attacking mode
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
thirdround = false;
fourround = true;
}
engine.update();
}
if (fourround) {
engine.getState().setCurAction(IDLE);
//Player 2
p2X = engine.getState().getListCharacters(1)[0]->getPosition().getX();
p2Y = engine.getState().getListCharacters(1)[0]->getPosition().getY();
priority = 0;
cout << "[Player 2] Character pos( " << engine.getState().getListCharacters(1)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(1)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p2X, --p2Y};
unique_ptr <engine::Command> ptr_mc2(
new engine::Move_Command(*engine.getState().getListCharacters(1)[0], pos1));
engine.addCommand(move(ptr_mc2), priority++);
cout << "MOVE FROM pos(" << p2X << "," << p2Y << ")" << " TO " << "(" << p2X << "," << p2Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(1)[0]->getMovementLeft() == 3) { // has reach attack range
// ==3 because the update isn't done yet
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ac2(
new engine::Attack_Command(*engine.getState().getListCharacters(1)[0],
*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_ac2), priority++);
cout << "ATTACKED";
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
fourround = false;
fiveround = true;
}
engine.update();
}
if (fiveround) {
engine.getState().setCurAction(IDLE);
p1X = engine.getState().getListCharacters(0)[0]->getPosition().getX();
p1Y = engine.getState().getListCharacters(0)[0]->getPosition().getY();
int priority = 0;
cout << "[Player 1] Character pos( " << engine.getState().getListCharacters(0)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(0)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ac1(
new engine::Attack_Command(*engine.getState().getListCharacters(0)[0],
*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_ac1), priority++);
cout << "ATTACKED";
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
fiveround = false;
sixround = true;
engine.update();
}
if (sixround) {
engine.getState().setCurAction(IDLE);
//Player 2
p2X = engine.getState().getListCharacters(1)[0]->getPosition().getX();
p2Y = engine.getState().getListCharacters(1)[0]->getPosition().getY();
priority = 0;
cout << "[Player 2] Character pos( " << engine.getState().getListCharacters(1)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(1)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
Position posTeleport{p2X - 2, p2Y - 2};
unique_ptr <engine::Command> ptr_cap(
new engine::Capab_Command(*engine.getState().getListCharacters(1)[0],
*engine.getState().getListCharacters(0)[0], posTeleport));
engine.addCommand(move(ptr_cap), priority++);
cout << "TELEPORTING" << endl;
usleep(1000000);
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ac2(
new engine::Attack_Command(*engine.getState().getListCharacters(1)[0],
*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_ac2), priority++);
cout << "ATTACKED";
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
sixround = false;
engine.update();
}
window.pollEvent(event);
if (event.type == sf::Event::Closed)
window.close();
}
}
} | 14,142 | 4,094 |
/*
* Copyright (C) 2015, UChicago Argonne, LLC
* All Rights Reserved
*
* Generic IO (ANL-15-066)
* Hal Finkel, Argonne National Laboratory
*
* OPEN SOURCE LICENSE
*
* Under the terms of Contract No. DE-AC02-06CH11357 with UChicago Argonne,
* LLC, the U.S. Government retains certain rights in this software.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the names of UChicago Argonne, LLC or the Department of Energy
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* *****************************************************************************
*
* DISCLAIMER
* THE SOFTWARE IS SUPPLIED “AS IS” WITHOUT WARRANTY OF ANY KIND. NEITHER THE
* UNTED STATES GOVERNMENT, NOR THE UNITED STATES DEPARTMENT OF ENERGY, NOR
* UCHICAGO ARGONNE, LLC, NOR ANY OF THEIR EMPLOYEES, MAKES ANY WARRANTY,
* EXPRESS OR IMPLIED, OR ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE
* ACCURACY, COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, DATA, APPARATUS,
* PRODUCT, OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE
* PRIVATELY OWNED RIGHTS.
*
* *****************************************************************************
*/
#define _XOPEN_SOURCE 600
#include "GenericIO.h"
#include "CRC64.h"
#ifndef LANL_GENERICIO_NO_COMPRESSION
extern "C" {
#include "blosc.h"
}
#endif
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <fstream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#ifndef LANL_GENERICIO_NO_MPI
#include <ctime>
#else
#include <time.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef __bgq__
#include <mpix.h>
#endif
namespace lanl
{
#ifndef MPI_UINT64_T
#define MPI_UINT64_T (sizeof(long) == 8 ? MPI_LONG : MPI_LONG_LONG)
#endif
#ifdef _WIN32
#include <Windows.h>
#include <io.h>
#include <stdio.h>
#define S_IRUSR _S_IREAD
#define S_IWUSR _S_IWRITE
#include <direct.h>
#define mkdir(a, b) _mkdir((a))
typedef long long ssize_t;
// Windows-specific functions
void usleep(int waitTime);
int ftruncate(unsigned int fd, size_t size);
int pread(unsigned int fd, void* buf, size_t count, int offset);
int pwrite(unsigned int fd, const void* buf, size_t count, int offset);
void usleep(int waitTime)
{
__int64 time1 = 0, time2 = 0, sysFreq = 0;
QueryPerformanceCounter((LARGE_INTEGER*)&time1);
QueryPerformanceFrequency((LARGE_INTEGER*)&sysFreq);
do
{
QueryPerformanceCounter((LARGE_INTEGER*)&time2);
} while ((time2 - time1) < waitTime);
}
// Convert a POSIX ftruncate to a windows system chsize
int ftruncate(unsigned int fd, size_t size)
{
return _chsize(fd, static_cast<long>(size));
}
// Convert a POSIX read to a windows system read
int pread(unsigned int fd, void* buf, size_t count, int offset)
{
if (_lseek(fd, offset, SEEK_SET) != offset)
return -1;
return _read(fd, (char*)buf, static_cast<unsigned int>(count));
}
// Convert a POSIX write to a windows system write
int pwrite(unsigned int fd, const void* buf, size_t count, int offset)
{
if (_lseek(fd, offset, SEEK_SET) != offset)
return -1;
return _write(fd, (char*)buf, static_cast<unsigned int>(count));
}
#endif
using namespace std;
namespace gio
{
#ifndef LANL_GENERICIO_NO_MPI
GenericFileIO_MPI::~GenericFileIO_MPI()
{
(void)MPI_File_close(&FH);
}
void GenericFileIO_MPI::open(const std::string& FN, bool ForReading)
{
FileName = FN;
int amode = ForReading ? MPI_MODE_RDONLY : (MPI_MODE_WRONLY | MPI_MODE_CREATE);
if (MPI_File_open(Comm, const_cast<char*>(FileName.c_str()), amode, MPI_INFO_NULL, &FH) !=
MPI_SUCCESS)
throw runtime_error(
(!ForReading ? "Unable to create the file: " : "Unable to open the file: ") + FileName);
}
void GenericFileIO_MPI::setSize(size_t sz)
{
if (MPI_File_set_size(FH, sz) != MPI_SUCCESS)
throw runtime_error("Unable to set size for file: " + FileName);
}
void GenericFileIO_MPI::read(void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
MPI_Status status;
if (MPI_File_read_at(FH, offset, buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to read " + D + " from file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
}
}
void GenericFileIO_MPI::write(const void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
MPI_Status status;
if (MPI_File_write_at(FH, offset, (void*)buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to write " + D + " to file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
}
}
void GenericFileIO_MPICollective::read(void* buf, size_t count, off_t offset, const std::string& D)
{
int Continue = 0;
do
{
MPI_Status status;
if (MPI_File_read_at_all(FH, offset, buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to read " + D + " from file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
int NeedContinue = (count > 0);
MPI_Allreduce(&NeedContinue, &Continue, 1, MPI_INT, MPI_SUM, Comm);
} while (Continue);
}
void GenericFileIO_MPICollective::write(
const void* buf, size_t count, off_t offset, const std::string& D)
{
int Continue = 0;
do
{
MPI_Status status;
if (MPI_File_write_at_all(FH, offset, (void*)buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to write " + D + " to file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
int NeedContinue = (count > 0);
MPI_Allreduce(&NeedContinue, &Continue, 1, MPI_INT, MPI_SUM, Comm);
} while (Continue);
}
#endif
GenericFileIO_POSIX::~GenericFileIO_POSIX()
{
if (FH != -1)
close(FH);
}
void GenericFileIO_POSIX::open(const std::string& FN, bool ForReading)
{
FileName = FN;
errno = 0;
#ifdef _WIN32
// Windows POSIX Must explicitly define O_BINARY otherwise it defaults to text mode
int flags = ForReading ? (O_RDONLY | O_BINARY) : (O_WRONLY | O_CREAT | O_BINARY);
int mode = S_IRUSR | S_IWUSR;
if ((FH = lanl::open(FileName.c_str(), flags, mode)) == -1)
#else
int flags = ForReading ? O_RDONLY : (O_WRONLY | O_CREAT);
int mode = S_IRUSR | S_IWUSR | S_IRGRP;
if ((FH = ::open(FileName.c_str(), flags, mode)) == -1)
#endif
throw runtime_error(
(!ForReading ? "Unable to create the file: " : "Unable to open the file: ") + FileName +
": " + strerror(errno));
}
void GenericFileIO_POSIX::setSize(size_t sz)
{
if (ftruncate(FH, sz) == -1)
throw runtime_error("Unable to set size for file: " + FileName);
}
void GenericFileIO_POSIX::read(void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
ssize_t scount;
errno = 0;
if ((scount = pread(FH, buf, count, offset)) == -1)
{
if (errno == EINTR)
continue;
throw runtime_error(
"Unable to read " + D + " from file: " + FileName + ": " + strerror(errno));
}
count -= scount;
buf = ((char*)buf) + scount;
offset += static_cast<off_t>(scount);
}
}
void GenericFileIO_POSIX::write(const void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
ssize_t scount;
errno = 0;
if ((scount = pwrite(FH, buf, count, offset)) == -1)
{
if (errno == EINTR)
continue;
throw runtime_error(
"Unable to write " + D + " to file: " + FileName + ": " + strerror(errno));
}
count -= scount;
buf = ((char*)buf) + scount;
offset += static_cast<off_t>(scount);
}
}
static bool isBigEndian()
{
const uint32_t one = 1;
return !(*((char*)(&one)));
}
static void bswap(void* v, size_t s)
{
char* p = (char*)v;
for (size_t i = 0; i < s / 2; ++i)
std::swap(p[i], p[s - (i + 1)]);
}
// Using #pragma pack here, instead of __attribute__((packed)) because xlc, at
// least as of v12.1, won't take __attribute__((packed)) on non-POD and/or
// templated types.
#pragma pack(1)
template <typename T, bool IsBigEndian>
struct endian_specific_value
{
operator T() const
{
T rvalue = value;
if (IsBigEndian != isBigEndian())
bswap(&rvalue, sizeof(T));
return rvalue;
};
endian_specific_value& operator=(T nvalue)
{
if (IsBigEndian != isBigEndian())
bswap(&nvalue, sizeof(T));
value = nvalue;
return *this;
}
endian_specific_value& operator+=(T nvalue)
{
*this = *this + nvalue;
return *this;
}
endian_specific_value& operator-=(T nvalue)
{
*this = *this - nvalue;
return *this;
}
private:
T value;
};
static const size_t CRCSize = 8;
static const size_t MagicSize = 8;
static const char* MagicBE = "HACC01B";
static const char* MagicLE = "HACC01L";
template <bool IsBigEndian>
struct GlobalHeader
{
char Magic[MagicSize];
endian_specific_value<uint64_t, IsBigEndian> HeaderSize;
endian_specific_value<uint64_t, IsBigEndian> NElems; // The global total
endian_specific_value<uint64_t, IsBigEndian> Dims[3];
endian_specific_value<uint64_t, IsBigEndian> NVars;
endian_specific_value<uint64_t, IsBigEndian> VarsSize;
endian_specific_value<uint64_t, IsBigEndian> VarsStart;
endian_specific_value<uint64_t, IsBigEndian> NRanks;
endian_specific_value<uint64_t, IsBigEndian> RanksSize;
endian_specific_value<uint64_t, IsBigEndian> RanksStart;
endian_specific_value<uint64_t, IsBigEndian> GlobalHeaderSize;
endian_specific_value<double, IsBigEndian> PhysOrigin[3];
endian_specific_value<double, IsBigEndian> PhysScale[3];
endian_specific_value<uint64_t, IsBigEndian> BlocksSize;
endian_specific_value<uint64_t, IsBigEndian> BlocksStart;
};
enum
{
FloatValue = (1 << 0),
SignedValue = (1 << 1),
ValueIsPhysCoordX = (1 << 2),
ValueIsPhysCoordY = (1 << 3),
ValueIsPhysCoordZ = (1 << 4),
ValueMaybePhysGhost = (1 << 5)
};
static const size_t NameSize = 256;
template <bool IsBigEndian>
struct VariableHeader
{
char Name[NameSize];
endian_specific_value<uint64_t, IsBigEndian> Flags;
endian_specific_value<uint64_t, IsBigEndian> Size;
};
template <bool IsBigEndian>
struct RankHeader
{
endian_specific_value<uint64_t, IsBigEndian> Coords[3];
endian_specific_value<uint64_t, IsBigEndian> NElems;
endian_specific_value<uint64_t, IsBigEndian> Start;
endian_specific_value<uint64_t, IsBigEndian> GlobalRank;
};
static const size_t FilterNameSize = 8;
static const size_t MaxFilters = 4;
template <bool IsBigEndian>
struct BlockHeader
{
char Filters[MaxFilters][FilterNameSize];
endian_specific_value<uint64_t, IsBigEndian> Start;
endian_specific_value<uint64_t, IsBigEndian> Size;
};
template <bool IsBigEndian>
struct CompressHeader
{
endian_specific_value<uint64_t, IsBigEndian> OrigCRC;
};
const char* CompressName = "BLOSC";
#pragma pack()
unsigned GenericIO::DefaultFileIOType = FileIOPOSIX;
int GenericIO::DefaultPartition = 0;
bool GenericIO::DefaultShouldCompress = false;
#ifndef LANL_GENERICIO_NO_MPI
std::size_t GenericIO::CollectiveMPIIOThreshold = 0;
#endif
static bool blosc_initialized = false;
#ifndef LANL_GENERICIO_NO_MPI
void GenericIO::write()
{
if (isBigEndian())
write<true>();
else
write<false>();
}
// Note: writing errors are not currently recoverable (one rank may fail
// while the others don't).
template <bool IsBigEndian>
void GenericIO::write()
{
const char* Magic = IsBigEndian ? MagicBE : MagicLE;
uint64_t FileSize = 0;
int NRanks, Rank;
MPI_Comm_rank(Comm, &Rank);
MPI_Comm_size(Comm, &NRanks);
#ifdef __bgq__
MPI_Barrier(Comm);
#endif
MPI_Comm_split(Comm, Partition, Rank, &SplitComm);
int SplitNRanks, SplitRank;
MPI_Comm_rank(SplitComm, &SplitRank);
MPI_Comm_size(SplitComm, &SplitNRanks);
string LocalFileName;
if (SplitNRanks != NRanks)
{
if (Rank == 0)
{
// In split mode, the specified file becomes the rank map, and the real
// data is partitioned.
vector<int> MapRank, MapPartition;
MapRank.resize(NRanks);
for (int i = 0; i < NRanks; ++i)
MapRank[i] = i;
MapPartition.resize(NRanks);
MPI_Gather(&Partition, 1, MPI_INT, &MapPartition[0], 1, MPI_INT, 0, Comm);
GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
GIO.setNumElems(NRanks);
GIO.addVariable("$rank", MapRank); /* this is for use by humans; the reading
code assumes that the partitions are in
rank order */
GIO.addVariable("$partition", MapPartition);
vector<int> CX, CY, CZ;
int TopoStatus;
MPI_Topo_test(Comm, &TopoStatus);
if (TopoStatus == MPI_CART)
{
CX.resize(NRanks);
CY.resize(NRanks);
CZ.resize(NRanks);
for (int i = 0; i < NRanks; ++i)
{
int C[3];
MPI_Cart_coords(Comm, i, 3, C);
CX[i] = C[0];
CY[i] = C[1];
CZ[i] = C[2];
}
GIO.addVariable("$x", CX);
GIO.addVariable("$y", CY);
GIO.addVariable("$z", CZ);
}
GIO.write();
}
else
{
MPI_Gather(&Partition, 1, MPI_INT, 0, 0, MPI_INT, 0, Comm);
}
stringstream ss;
ss << FileName << "#" << Partition;
LocalFileName = ss.str();
}
else
{
LocalFileName = FileName;
}
RankHeader<IsBigEndian> RHLocal;
int Dims[3], Periods[3], Coords[3];
int TopoStatus;
MPI_Topo_test(Comm, &TopoStatus);
if (TopoStatus == MPI_CART)
{
MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
}
else
{
Dims[0] = NRanks;
std::fill(Dims + 1, Dims + 3, 1);
std::fill(Periods, Periods + 3, 0);
Coords[0] = Rank;
std::fill(Coords + 1, Coords + 3, 0);
}
std::copy(Coords, Coords + 3, RHLocal.Coords);
RHLocal.NElems = NElems;
RHLocal.Start = 0;
RHLocal.GlobalRank = Rank;
bool ShouldCompress = DefaultShouldCompress;
const char* EnvStr = getenv("GENERICIO_COMPRESS");
if (EnvStr)
{
int Mod = atoi(EnvStr);
ShouldCompress = (Mod > 0);
}
bool NeedsBlockHeaders = ShouldCompress;
EnvStr = getenv("GENERICIO_FORCE_BLOCKS");
if (!NeedsBlockHeaders && EnvStr)
{
int Mod = atoi(EnvStr);
NeedsBlockHeaders = (Mod > 0);
}
vector<BlockHeader<IsBigEndian> > LocalBlockHeaders;
vector<void*> LocalData;
vector<bool> LocalHasExtraSpace;
vector<vector<unsigned char> > LocalCData;
if (NeedsBlockHeaders)
{
LocalBlockHeaders.resize(Vars.size());
LocalData.resize(Vars.size());
LocalHasExtraSpace.resize(Vars.size());
if (ShouldCompress)
LocalCData.resize(Vars.size());
for (size_t i = 0; i < Vars.size(); ++i)
{
// Filters null by default, leave null starting address (needs to be
// calculated by the header-writing rank).
memset(&LocalBlockHeaders[i], 0, sizeof(BlockHeader<IsBigEndian>));
if (ShouldCompress)
{
LocalCData[i].resize(sizeof(CompressHeader<IsBigEndian>));
CompressHeader<IsBigEndian>* CH = (CompressHeader<IsBigEndian>*)&LocalCData[i][0];
CH->OrigCRC = crc64_omp(Vars[i].Data, Vars[i].Size * NElems);
#ifndef LANL_GENERICIO_NO_COMPRESSION
#ifdef _OPENMP
#pragma omp master
{
#endif
if (!blosc_initialized)
{
blosc_init();
blosc_initialized = true;
}
#ifdef _OPENMP
blosc_set_nthreads(omp_get_max_threads());
}
#endif
LocalCData[i].resize(LocalCData[i].size() + NElems * Vars[i].Size);
if (blosc_compress(9, 1, Vars[i].Size, NElems * Vars[i].Size, Vars[i].Data,
&LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>), NElems * Vars[i].Size) <= 0)
goto nocomp;
strncpy(LocalBlockHeaders[i].Filters[0], CompressName, FilterNameSize);
size_t CNBytes, CCBytes, CBlockSize;
blosc_cbuffer_sizes(
&LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>), &CNBytes, &CCBytes, &CBlockSize);
LocalCData[i].resize(CCBytes + sizeof(CompressHeader<IsBigEndian>));
LocalBlockHeaders[i].Size = LocalCData[i].size();
LocalCData[i].resize(LocalCData[i].size() + CRCSize);
LocalData[i] = &LocalCData[i][0];
LocalHasExtraSpace[i] = true;
#endif // LANL_GENERICIO_NO_COMPRESSION
}
else
{
nocomp:
LocalBlockHeaders[i].Size = NElems * Vars[i].Size;
LocalData[i] = Vars[i].Data;
LocalHasExtraSpace[i] = Vars[i].HasExtraSpace;
}
}
}
double StartTime = MPI_Wtime();
if (SplitRank == 0)
{
uint64_t HeaderSize = sizeof(GlobalHeader<IsBigEndian>) +
Vars.size() * sizeof(VariableHeader<IsBigEndian>) +
SplitNRanks * sizeof(RankHeader<IsBigEndian>) + CRCSize;
if (NeedsBlockHeaders)
HeaderSize += SplitNRanks * Vars.size() * sizeof(BlockHeader<IsBigEndian>);
vector<char> Header(HeaderSize, 0);
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&Header[0];
std::copy(Magic, Magic + MagicSize, GH->Magic);
GH->HeaderSize = HeaderSize - CRCSize;
GH->NElems = NElems; // This will be updated later
std::copy(Dims, Dims + 3, GH->Dims);
GH->NVars = Vars.size();
GH->VarsSize = sizeof(VariableHeader<IsBigEndian>);
GH->VarsStart = sizeof(GlobalHeader<IsBigEndian>);
GH->NRanks = SplitNRanks;
GH->RanksSize = sizeof(RankHeader<IsBigEndian>);
GH->RanksStart = GH->VarsStart + Vars.size() * sizeof(VariableHeader<IsBigEndian>);
GH->GlobalHeaderSize = sizeof(GlobalHeader<IsBigEndian>);
std::copy(PhysOrigin, PhysOrigin + 3, GH->PhysOrigin);
std::copy(PhysScale, PhysScale + 3, GH->PhysScale);
if (!NeedsBlockHeaders)
{
GH->BlocksSize = GH->BlocksStart = 0;
}
else
{
GH->BlocksSize = sizeof(BlockHeader<IsBigEndian>);
GH->BlocksStart = GH->RanksStart + SplitNRanks * sizeof(RankHeader<IsBigEndian>);
}
uint64_t RecordSize = 0;
VariableHeader<IsBigEndian>* VH = (VariableHeader<IsBigEndian>*)&Header[GH->VarsStart];
for (size_t i = 0; i < Vars.size(); ++i, ++VH)
{
string VName(Vars[i].Name);
VName.resize(NameSize);
std::copy(VName.begin(), VName.end(), VH->Name);
uint64_t VFlags = 0;
if (Vars[i].IsFloat)
VFlags |= FloatValue;
if (Vars[i].IsSigned)
VFlags |= SignedValue;
if (Vars[i].IsPhysCoordX)
VFlags |= ValueIsPhysCoordX;
if (Vars[i].IsPhysCoordY)
VFlags |= ValueIsPhysCoordY;
if (Vars[i].IsPhysCoordZ)
VFlags |= ValueIsPhysCoordZ;
if (Vars[i].MaybePhysGhost)
VFlags |= ValueMaybePhysGhost;
VH->Flags = VFlags;
RecordSize += VH->Size = Vars[i].Size;
}
MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE, &Header[GH->RanksStart], sizeof(RHLocal),
MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
{
MPI_Gather(&LocalBlockHeaders[0], Vars.size() * sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
&Header[GH->BlocksStart], Vars.size() * sizeof(BlockHeader<IsBigEndian>), MPI_BYTE, 0,
SplitComm);
BlockHeader<IsBigEndian>* BH = (BlockHeader<IsBigEndian>*)&Header[GH->BlocksStart];
for (int i = 0; i < SplitNRanks; ++i)
for (size_t j = 0; j < Vars.size(); ++j, ++BH)
{
if (i == 0 && j == 0)
BH->Start = HeaderSize;
else
BH->Start = BH[-1].Start + BH[-1].Size + CRCSize;
}
RankHeader<IsBigEndian>* RH = (RankHeader<IsBigEndian>*)&Header[GH->RanksStart];
RH->Start = HeaderSize;
++RH;
for (int i = 1; i < SplitNRanks; ++i, ++RH)
{
RH->Start = ((BlockHeader<IsBigEndian>*)&Header[GH->BlocksStart])[i * Vars.size()].Start;
GH->NElems += RH->NElems;
}
// Compute the total file size.
uint64_t LastData = BH[-1].Size + CRCSize;
FileSize = BH[-1].Start + LastData;
}
else
{
RankHeader<IsBigEndian>* RH = (RankHeader<IsBigEndian>*)&Header[GH->RanksStart];
RH->Start = HeaderSize;
++RH;
for (int i = 1; i < SplitNRanks; ++i, ++RH)
{
uint64_t PrevNElems = RH[-1].NElems;
uint64_t PrevData = PrevNElems * RecordSize + CRCSize * Vars.size();
RH->Start = RH[-1].Start + PrevData;
GH->NElems += RH->NElems;
}
// Compute the total file size.
uint64_t LastNElems = RH[-1].NElems;
uint64_t LastData = LastNElems * RecordSize + CRCSize * Vars.size();
FileSize = RH[-1].Start + LastData;
}
// Now that the starting offset has been computed, send it back to each rank.
MPI_Scatter(&Header[GH->RanksStart], sizeof(RHLocal), MPI_BYTE, &RHLocal, sizeof(RHLocal),
MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
MPI_Scatter(&Header[GH->BlocksStart], sizeof(BlockHeader<IsBigEndian>) * Vars.size(),
MPI_BYTE, &LocalBlockHeaders[0], sizeof(BlockHeader<IsBigEndian>) * Vars.size(), MPI_BYTE,
0, SplitComm);
uint64_t HeaderCRC = crc64_omp(&Header[0], HeaderSize - CRCSize);
crc64_invert(HeaderCRC, &Header[HeaderSize - CRCSize]);
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
else
FH.get() = new GenericFileIO_POSIX();
FH.get()->open(LocalFileName);
FH.get()->setSize(FileSize);
FH.get()->write(&Header[0], HeaderSize, 0, "header");
close();
}
else
{
MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
MPI_Gather(&LocalBlockHeaders[0], Vars.size() * sizeof(BlockHeader<IsBigEndian>), MPI_BYTE, 0,
0, MPI_BYTE, 0, SplitComm);
MPI_Scatter(0, 0, MPI_BYTE, &RHLocal, sizeof(RHLocal), MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
MPI_Scatter(0, 0, MPI_BYTE, &LocalBlockHeaders[0],
sizeof(BlockHeader<IsBigEndian>) * Vars.size(), MPI_BYTE, 0, SplitComm);
}
MPI_Barrier(SplitComm);
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(SplitComm);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(SplitComm);
else
FH.get() = new GenericFileIO_POSIX();
FH.get()->open(LocalFileName);
uint64_t Offset = RHLocal.Start;
for (size_t i = 0; i < Vars.size(); ++i)
{
uint64_t WriteSize = NeedsBlockHeaders ? LocalBlockHeaders[i].Size : NElems * Vars[i].Size;
void* Data = NeedsBlockHeaders ? LocalData[i] : Vars[i].Data;
uint64_t CRC = crc64_omp(Data, WriteSize);
bool HasExtraSpace = NeedsBlockHeaders ? LocalHasExtraSpace[i] : Vars[i].HasExtraSpace;
char* CRCLoc = HasExtraSpace ? ((char*)Data) + WriteSize : (char*)&CRC;
if (NeedsBlockHeaders)
Offset = LocalBlockHeaders[i].Start;
// When using extra space for the CRC write, preserve the original contents.
char CRCSave[CRCSize];
if (HasExtraSpace)
std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
crc64_invert(CRC, CRCLoc);
if (HasExtraSpace)
{
FH.get()->write(Data, WriteSize + CRCSize, Offset, Vars[i].Name + " with CRC");
}
else
{
FH.get()->write(Data, WriteSize, Offset, Vars[i].Name);
FH.get()->write(CRCLoc, CRCSize, Offset + WriteSize, Vars[i].Name + " CRC");
}
if (HasExtraSpace)
std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
Offset += WriteSize + CRCSize;
}
close();
MPI_Barrier(Comm);
double EndTime = MPI_Wtime();
double TotalTime = EndTime - StartTime;
double MaxTotalTime;
MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
if (SplitNRanks != NRanks)
{
uint64_t ContribFileSize = (SplitRank == 0) ? FileSize : 0;
MPI_Reduce(&ContribFileSize, &FileSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
}
if (Rank == 0)
{
double Rate = ((double)FileSize) / MaxTotalTime / (1024. * 1024.);
cout << "Wrote " << Vars.size() << " variables to " << FileName << " (" << FileSize
<< " bytes) in " << MaxTotalTime << "s: " << Rate << " MB/s" << endl;
}
MPI_Comm_free(&SplitComm);
SplitComm = MPI_COMM_NULL;
}
#endif // LANL_GENERICIO_NO_MPI
template <bool IsBigEndian>
void GenericIO::readHeaderLeader(void* GHPtr, MismatchBehavior MB, int NRanks, int Rank,
int SplitNRanks, string& LocalFileName, uint64_t& HeaderSize, vector<char>& Header)
{
// May be unused depending on preprocessor. Since it's a static var, it's
// initialized here to make sure it's in an executable block so the compiler
// will accept it.
(void)blosc_initialized;
GlobalHeader<IsBigEndian>& GH = *(GlobalHeader<IsBigEndian>*)GHPtr;
if (MB == MismatchDisallowed)
{
if (SplitNRanks != (int)GH.NRanks)
{
stringstream ss;
ss << "Won't read " << LocalFileName << ": communicator-size mismatch: "
<< "current: " << SplitNRanks << ", file: " << GH.NRanks;
throw runtime_error(ss.str());
}
#ifndef LANL_GENERICIO_NO_MPI
int TopoStatus;
MPI_Topo_test(Comm, &TopoStatus);
if (TopoStatus == MPI_CART)
{
int Dims[3], Periods[3], Coords[3];
MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
bool DimsMatch = true;
for (int i = 0; i < 3; ++i)
{
if ((uint64_t)Dims[i] != GH.Dims[i])
{
DimsMatch = false;
break;
}
}
if (!DimsMatch)
{
stringstream ss;
ss << "Won't read " << LocalFileName << ": communicator-decomposition mismatch: "
<< "current: " << Dims[0] << "x" << Dims[1] << "x" << Dims[2] << ", file: " << GH.Dims[0]
<< "x" << GH.Dims[1] << "x" << GH.Dims[2];
throw runtime_error(ss.str());
}
}
#endif
}
else if (MB == MismatchRedistribute && !Redistributing)
{
Redistributing = true;
int NFileRanks = RankMap.empty() ? (int)GH.NRanks : (int)RankMap.size();
int NFileRanksPerRank = NFileRanks / NRanks;
int NRemFileRank = NFileRanks % NRanks;
if (!NFileRanksPerRank)
{
// We have only the remainder, so the last NRemFileRank ranks get one
// file rank, and the others don't.
if (NRemFileRank && NRanks - Rank <= NRemFileRank)
SourceRanks.push_back(NRanks - (Rank + 1));
}
else
{
// Since NRemFileRank < NRanks, and we don't want to put any extra memory
// load on rank 0 (because rank 0's memory load is normally higher than
// the other ranks anyway), the last NRemFileRank will each take
// (NFileRanksPerRank+1) file ranks.
int FirstFileRank = 0, LastFileRank = NFileRanksPerRank - 1;
for (int i = 1; i <= Rank; ++i)
{
FirstFileRank = LastFileRank + 1;
LastFileRank = FirstFileRank + NFileRanksPerRank - 1;
if (NRemFileRank && NRanks - i <= NRemFileRank)
++LastFileRank;
}
for (int i = FirstFileRank; i <= LastFileRank; ++i)
SourceRanks.push_back(i);
}
}
HeaderSize = GH.HeaderSize;
Header.resize(HeaderSize + CRCSize, '\xFE' /* poison */);
FH.get()->read(&Header[0], HeaderSize + CRCSize, 0, "header");
uint64_t CRC = crc64_omp(&Header[0], HeaderSize + CRCSize);
if (CRC != (uint64_t)-1)
{
throw runtime_error("Header CRC check failed: " + LocalFileName);
}
}
// Note: Errors from this function should be recoverable. This means that if
// one rank throws an exception, then all ranks should.
void GenericIO::openAndReadHeader(MismatchBehavior MB, int EffRank, bool CheckPartMap)
{
int NRanks, Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
MPI_Comm_size(Comm, &NRanks);
#else
Rank = 0;
NRanks = 1;
#endif
if (EffRank == -1)
EffRank = MB == MismatchRedistribute ? 0 : Rank;
if (RankMap.empty() && CheckPartMap)
{
// First, check to see if the file is a rank map.
unsigned long RanksInMap = 0;
if (Rank == 0)
{
try
{
#ifndef LANL_GENERICIO_NO_MPI
GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
#else
GenericIO GIO(FileName, FileIOType);
#endif
GIO.openAndReadHeader(MismatchDisallowed, 0, false);
RanksInMap = static_cast<unsigned long>(GIO.readNumElems());
RankMap.resize(RanksInMap + GIO.requestedExtraSpace() / sizeof(int));
GIO.addVariable("$partition", RankMap, true);
GIO.readData(0, false);
RankMap.resize(RanksInMap);
}
catch (...)
{
RankMap.clear();
RanksInMap = 0;
}
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&RanksInMap, 1, MPI_UNSIGNED_LONG, 0, Comm);
if (RanksInMap > 0)
{
RankMap.resize(RanksInMap);
MPI_Bcast(&RankMap[0], RanksInMap, MPI_INT, 0, Comm);
}
#endif
}
#ifndef LANL_GENERICIO_NO_MPI
if (SplitComm != MPI_COMM_NULL)
MPI_Comm_free(&SplitComm);
#endif
string LocalFileName;
if (RankMap.empty())
{
LocalFileName = FileName;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_dup(MB == MismatchRedistribute ? MPI_COMM_SELF : Comm, &SplitComm);
#endif
}
else
{
stringstream ss;
ss << FileName << "#" << RankMap[EffRank];
LocalFileName = ss.str();
#ifndef LANL_GENERICIO_NO_MPI
if (MB == MismatchRedistribute)
{
MPI_Comm_dup(MPI_COMM_SELF, &SplitComm);
}
else
{
#ifdef __bgq__
MPI_Barrier(Comm);
#endif
MPI_Comm_split(Comm, RankMap[EffRank], Rank, &SplitComm);
}
#endif
}
if (LocalFileName == OpenFileName)
return;
FH.close();
int SplitNRanks, SplitRank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(SplitComm, &SplitRank);
MPI_Comm_size(SplitComm, &SplitNRanks);
#else
SplitRank = 0;
SplitNRanks = 1;
#endif
uint64_t HeaderSize = 0;
vector<char> Header;
if (SplitRank == 0)
{
#ifndef LANL_GENERICIO_NO_MPI
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
else
#endif
FH.get() = new GenericFileIO_POSIX();
#ifndef LANL_GENERICIO_NO_MPI
char True = 1, False = 0;
#endif
try
{
FH.get()->open(LocalFileName, true);
GlobalHeader<false> GH; // endianness does not matter yet...
FH.get()->read(&GH, sizeof(GlobalHeader<false>), 0, "global header");
if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicLE)
{
readHeaderLeader<false>(
&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName, HeaderSize, Header);
}
else if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicBE)
{
readHeaderLeader<true>(
&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName, HeaderSize, Header);
}
else
{
string Error = "invalid file-type identifier";
throw runtime_error("Won't read " + LocalFileName + ": " + Error);
}
#ifndef LANL_GENERICIO_NO_MPI
close();
MPI_Bcast(&True, 1, MPI_BYTE, 0, SplitComm);
#endif
}
catch (...)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&False, 1, MPI_BYTE, 0, SplitComm);
#endif
close();
throw;
}
}
else
{
#ifndef LANL_GENERICIO_NO_MPI
char Okay;
MPI_Bcast(&Okay, 1, MPI_BYTE, 0, SplitComm);
if (!Okay)
throw runtime_error("Failure broadcast from rank 0");
#endif
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&HeaderSize, 1, MPI_UINT64_T, 0, SplitComm);
#endif
Header.resize(HeaderSize, '\xFD' /* poison */);
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&Header[0], HeaderSize, MPI_BYTE, 0, SplitComm);
#endif
FH.getHeaderCache().clear();
GlobalHeader<false>* GH = (GlobalHeader<false>*)&Header[0];
FH.setIsBigEndian(string(GH->Magic, GH->Magic + MagicSize - 1) == MagicBE);
FH.getHeaderCache().swap(Header);
OpenFileName = LocalFileName;
#ifndef LANL_GENERICIO_NO_MPI
if (!DisableCollErrChecking)
MPI_Barrier(Comm);
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(SplitComm);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(SplitComm);
else
FH.get() = new GenericFileIO_POSIX();
int OpenErr = 0, TotOpenErr;
try
{
FH.get()->open(LocalFileName, true);
MPI_Allreduce(
&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM, DisableCollErrChecking ? MPI_COMM_SELF : Comm);
}
catch (...)
{
OpenErr = 1;
MPI_Allreduce(
&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM, DisableCollErrChecking ? MPI_COMM_SELF : Comm);
throw;
}
if (TotOpenErr > 0)
{
stringstream ss;
ss << TotOpenErr << " ranks failed to open file: " << LocalFileName;
throw runtime_error(ss.str());
}
#endif
}
int GenericIO::readNRanks()
{
if (FH.isBigEndian())
return readNRanks<true>();
return readNRanks<false>();
}
template <bool IsBigEndian>
int GenericIO::readNRanks()
{
if (RankMap.size())
return static_cast<int>(RankMap.size());
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
return (int)GH->NRanks;
}
void GenericIO::readDims(int Dims[3])
{
if (FH.isBigEndian())
readDims<true>(Dims);
else
readDims<false>(Dims);
}
template <bool IsBigEndian>
void GenericIO::readDims(int Dims[3])
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
Dims[0] = static_cast<int>(GH->Dims[0]);
Dims[1] = static_cast<int>(GH->Dims[1]);
Dims[2] = static_cast<int>(GH->Dims[2]);
}
uint64_t GenericIO::readTotalNumElems()
{
if (FH.isBigEndian())
return readTotalNumElems<true>();
return readTotalNumElems<false>();
}
template <bool IsBigEndian>
uint64_t GenericIO::readTotalNumElems()
{
if (RankMap.size())
return (uint64_t)-1;
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
return GH->NElems;
}
void GenericIO::readPhysOrigin(double Origin[3])
{
if (FH.isBigEndian())
readPhysOrigin<true>(Origin);
else
readPhysOrigin<false>(Origin);
}
// Define a "safe" version of offsetof (offsetof itself might not work for
// non-POD types, and at least xlC v12.1 will complain about this if you try).
#define offsetof_safe(S, F) (size_t(&(S)->F) - size_t(S))
template <bool IsBigEndian>
void GenericIO::readPhysOrigin(double Origin[3])
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
if (offsetof_safe(GH, PhysOrigin) >= GH->GlobalHeaderSize)
{
std::fill(Origin, Origin + 3, 0.0);
return;
}
std::copy(GH->PhysOrigin, GH->PhysOrigin + 3, Origin);
}
void GenericIO::readPhysScale(double Scale[3])
{
if (FH.isBigEndian())
readPhysScale<true>(Scale);
else
readPhysScale<false>(Scale);
}
template <bool IsBigEndian>
void GenericIO::readPhysScale(double Scale[3])
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
if (offsetof_safe(GH, PhysScale) >= GH->GlobalHeaderSize)
{
std::fill(Scale, Scale + 3, 0.0);
return;
}
std::copy(GH->PhysScale, GH->PhysScale + 3, Scale);
}
template <bool IsBigEndian>
static size_t getRankIndex(
int EffRank, GlobalHeader<IsBigEndian>* GH, vector<int>& RankMap, vector<char>& HeaderCache)
{
if (RankMap.empty())
return EffRank;
for (size_t i = 0; i < GH->NRanks; ++i)
{
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&HeaderCache[GH->RanksStart + i * GH->RanksSize];
if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
return EffRank;
if ((int)RH->GlobalRank == EffRank)
return i;
}
assert(false && "Index requested of an invalid rank");
return (size_t)-1;
}
int GenericIO::readGlobalRankNumber(int EffRank)
{
if (FH.isBigEndian())
return readGlobalRankNumber<true>(EffRank);
return readGlobalRankNumber<false>(EffRank);
}
template <bool IsBigEndian>
int GenericIO::readGlobalRankNumber(int EffRank)
{
if (EffRank == -1)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &EffRank);
#else
EffRank = 0;
#endif
}
openAndReadHeader(MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
return EffRank;
return (int)RH->GlobalRank;
}
void GenericIO::getSourceRanks(vector<int>& SR)
{
SR.clear();
if (Redistributing)
{
std::copy(SourceRanks.begin(), SourceRanks.end(), std::back_inserter(SR));
return;
}
int Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
#else
Rank = 0;
#endif
SR.push_back(Rank);
}
size_t GenericIO::readNumElems(int EffRank)
{
if (EffRank == -1 && Redistributing)
{
DisableCollErrChecking = true;
size_t TotalSize = 0;
for (size_t i = 0, ie = SourceRanks.size(); i != ie; ++i)
TotalSize += readNumElems(SourceRanks[i]);
DisableCollErrChecking = false;
return TotalSize;
}
if (FH.isBigEndian())
return readNumElems<true>(EffRank);
return readNumElems<false>(EffRank);
}
template <bool IsBigEndian>
size_t GenericIO::readNumElems(int EffRank)
{
if (EffRank == -1)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &EffRank);
#else
EffRank = 0;
#endif
}
openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
return (size_t)RH->NElems;
}
void GenericIO::readDataSection(size_t readOffset, size_t readNumRows, int EffRank,
size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
if (FH.isBigEndian())
readDataSection<true>(readOffset, readNumRows, EffRank, RowOffset, Rank, TotalReadSize, NErrs);
else
readDataSection<false>(readOffset, readNumRows, EffRank, RowOffset, Rank, TotalReadSize, NErrs);
}
void GenericIO::readDataSection(
size_t readOffset, size_t readNumRows, int EffRank, bool PrintStats, bool CollStats)
{
(void)CollStats; // may be unused depending on preprocessor config.
int Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
#else
Rank = 0;
#endif
uint64_t TotalReadSize = 0;
#ifndef LANL_GENERICIO_NO_MPI
double StartTime = MPI_Wtime();
#else
double StartTime = double(clock()) / CLOCKS_PER_SEC;
#endif
int NErrs[3] = { 0, 0, 0 };
if (EffRank == -1 && Redistributing)
{
DisableCollErrChecking = true;
size_t RowOffset = 0;
for (size_t i = 0, ie = SourceRanks.size(); i != ie; ++i)
{
readDataSection(
readOffset, readNumRows, SourceRanks[i], RowOffset, Rank, TotalReadSize, NErrs);
RowOffset += readNumElems(SourceRanks[i]);
}
DisableCollErrChecking = false;
}
else
{
readDataSection(readOffset, readNumRows, EffRank, 0, Rank, TotalReadSize, NErrs);
}
int AllNErrs[3];
#ifndef LANL_GENERICIO_NO_MPI
MPI_Allreduce(NErrs, AllNErrs, 3, MPI_INT, MPI_SUM, Comm);
#else
AllNErrs[0] = NErrs[0];
AllNErrs[1] = NErrs[1];
AllNErrs[2] = NErrs[2];
#endif
if (AllNErrs[0] > 0 || AllNErrs[1] > 0 || AllNErrs[2] > 0)
{
stringstream ss;
ss << "Experienced " << AllNErrs[0] << " I/O error(s), " << AllNErrs[1] << " CRC error(s) and "
<< AllNErrs[2] << " decompression CRC error(s) reading: " << OpenFileName;
throw runtime_error(ss.str());
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Barrier(Comm);
#endif
#ifndef LANL_GENERICIO_NO_MPI
double EndTime = MPI_Wtime();
#else
double EndTime = double(clock()) / CLOCKS_PER_SEC;
#endif
double TotalTime = EndTime - StartTime;
double MaxTotalTime;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
else
#endif
MaxTotalTime = TotalTime;
uint64_t AllTotalReadSize;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalReadSize, &AllTotalReadSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
else
#endif
AllTotalReadSize = TotalReadSize;
if (Rank == 0 && PrintStats)
{
double Rate = ((double)AllTotalReadSize) / MaxTotalTime / (1024. * 1024.);
cout << "Read " << Vars.size() << " variables from " << FileName << " (" << AllTotalReadSize
<< " bytes) in " << MaxTotalTime << "s: " << Rate << " MB/s [excluding header read]"
<< endl;
}
}
// Note: Errors from this function should be recoverable. This means that if
// one rank throws an exception, then all ranks should.
template <bool IsBigEndian>
void GenericIO::readDataSection(size_t readOffset, size_t readNumRows, int EffRank,
size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
if (EffRank == -1)
EffRank = Rank;
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
for (size_t i = 0; i < Vars.size(); ++i)
{
uint64_t Offset = RH->Start;
bool VarFound = false;
for (uint64_t j = 0; j < GH->NVars; ++j)
{
VariableHeader<IsBigEndian>* VH =
(VariableHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->VarsStart + j * GH->VarsSize];
string VName(VH->Name, VH->Name + NameSize);
size_t VNameNull = VName.find('\0');
if (VNameNull < NameSize)
VName.resize(VNameNull);
uint64_t ReadSize = RH->NElems * VH->Size + CRCSize;
if (VName != Vars[i].Name)
{
Offset += ReadSize;
continue;
}
VarFound = true;
bool IsFloat = (VH->Flags & FloatValue) != 0, IsSigned = (VH->Flags & SignedValue) != 0;
if (VH->Size != Vars[i].Size)
{
stringstream ss;
ss << "Size mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << Vars[i].Size << ", file: " << VH->Size;
throw runtime_error(ss.str());
}
else if (IsFloat != Vars[i].IsFloat)
{
string Float("float"), Int("integer");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsFloat ? Float : Int)
<< ", file: " << (IsFloat ? Float : Int);
throw runtime_error(ss.str());
}
else if (IsSigned != Vars[i].IsSigned)
{
string Signed("signed"), Uns("unsigned");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsSigned ? Signed : Uns)
<< ", file: " << (IsSigned ? Signed : Uns);
throw runtime_error(ss.str());
}
size_t VarOffset = RowOffset * Vars[i].Size;
void* VarData = ((char*)Vars[i].Data) + VarOffset;
vector<unsigned char> LData;
void* Data = VarData;
bool HasExtraSpace = Vars[i].HasExtraSpace;
(void)HasExtraSpace; // Only used in assert, unused in release builds.
if (offsetof_safe(GH, BlocksStart) < GH->GlobalHeaderSize && GH->BlocksSize > 0)
{
BlockHeader<IsBigEndian>* BH =
(BlockHeader<IsBigEndian>*)&FH
.getHeaderCache()[GH->BlocksStart + (RankIndex * GH->NVars + j) * GH->BlocksSize];
ReadSize = BH->Size + CRCSize;
Offset = BH->Start;
if (strncmp(BH->Filters[0], CompressName, FilterNameSize) == 0)
{
LData.resize(ReadSize);
Data = &LData[0];
HasExtraSpace = true;
}
else if (BH->Filters[0][0] != '\0')
{
stringstream ss;
ss << "Unknown filter \"" << BH->Filters[0] << "\" on variable " << Vars[i].Name;
throw runtime_error(ss.str());
}
}
assert(HasExtraSpace && "Extra space required for reading");
int Retry = 0;
{
int RetryCount = 300;
const char* EnvStr = getenv("GENERICIO_RETRY_COUNT");
if (EnvStr)
RetryCount = atoi(EnvStr);
int RetrySleep = 100; // ms
EnvStr = getenv("GENERICIO_RETRY_SLEEP");
if (EnvStr)
RetrySleep = atoi(EnvStr);
for (; Retry < RetryCount; ++Retry)
{
try
{
//
// Read section
ReadSize = readNumRows * VH->Size;
Offset = Offset + readOffset * VH->Size;
FH.get()->read(Data, ReadSize, static_cast<off_t>(Offset), Vars[i].Name);
break;
}
catch (...)
{
}
usleep(1000 * RetrySleep);
}
if (Retry == RetryCount)
{
++NErrs[0];
break;
}
else if (Retry > 0)
{
EnvStr = getenv("GENERICIO_VERBOSE");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
std::cerr << "Rank " << RankTmp << ": " << Retry
<< " I/O retries were necessary for reading " << Vars[i].Name
<< " from: " << OpenFileName << "\n";
std::cerr.flush();
}
}
}
}
TotalReadSize += ReadSize;
// Byte swap the data if necessary.
if (IsBigEndian != isBigEndian())
for (size_t k = 0; k < RH->NElems; ++k)
{
char* OffsetTmp = ((char*)VarData) + k * Vars[i].Size;
bswap(OffsetTmp, Vars[i].Size);
}
break;
}
if (!VarFound)
throw runtime_error("Variable " + Vars[i].Name + " not found in: " + OpenFileName);
}
}
void GenericIO::readCoords(int Coords[3], int EffRank)
{
if (EffRank == -1 && Redistributing)
{
std::fill(Coords, Coords + 3, 0);
return;
}
if (FH.isBigEndian())
readCoords<true>(Coords, EffRank);
else
readCoords<false>(Coords, EffRank);
}
template <bool IsBigEndian>
void GenericIO::readCoords(int Coords[3], int EffRank)
{
if (EffRank == -1)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &EffRank);
#else
EffRank = 0;
#endif
}
openAndReadHeader(MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
Coords[0] = static_cast<int>(RH->Coords[0]);
Coords[1] = static_cast<int>(RH->Coords[1]);
Coords[2] = static_cast<int>(RH->Coords[2]);
}
void GenericIO::readData(int EffRank, bool PrintStats, bool CollStats)
{
(void)CollStats; // may be unused depending on preprocessor config.
int Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
#else
Rank = 0;
#endif
uint64_t TotalReadSize = 0;
#ifndef LANL_GENERICIO_NO_MPI
double StartTime = MPI_Wtime();
#else
double StartTime = double(clock()) / CLOCKS_PER_SEC;
#endif
int NErrs[3] = { 0, 0, 0 };
if (EffRank == -1 && Redistributing)
{
DisableCollErrChecking = true;
size_t RowOffset = 0;
for (size_t i = 0, ie = SourceRanks.size(); i != ie; ++i)
{
readData(SourceRanks[i], RowOffset, Rank, TotalReadSize, NErrs);
RowOffset += readNumElems(SourceRanks[i]);
}
DisableCollErrChecking = false;
}
else
{
readData(EffRank, 0, Rank, TotalReadSize, NErrs);
}
int AllNErrs[3];
#ifndef LANL_GENERICIO_NO_MPI
MPI_Allreduce(NErrs, AllNErrs, 3, MPI_INT, MPI_SUM, Comm);
#else
AllNErrs[0] = NErrs[0];
AllNErrs[1] = NErrs[1];
AllNErrs[2] = NErrs[2];
#endif
if (AllNErrs[0] > 0 || AllNErrs[1] > 0 || AllNErrs[2] > 0)
{
stringstream ss;
ss << "Experienced " << AllNErrs[0] << " I/O error(s), " << AllNErrs[1] << " CRC error(s) and "
<< AllNErrs[2] << " decompression CRC error(s) reading: " << OpenFileName;
throw runtime_error(ss.str());
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Barrier(Comm);
#endif
#ifndef LANL_GENERICIO_NO_MPI
double EndTime = MPI_Wtime();
#else
double EndTime = double(clock()) / CLOCKS_PER_SEC;
#endif
double TotalTime = EndTime - StartTime;
double MaxTotalTime;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
else
#endif
MaxTotalTime = TotalTime;
uint64_t AllTotalReadSize;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalReadSize, &AllTotalReadSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
else
#endif
AllTotalReadSize = TotalReadSize;
if (Rank == 0 && PrintStats)
{
double Rate = ((double)AllTotalReadSize) / MaxTotalTime / (1024. * 1024.);
cout << "Read " << Vars.size() << " variables from " << FileName << " (" << AllTotalReadSize
<< " bytes) in " << MaxTotalTime << "s: " << Rate << " MB/s [excluding header read]"
<< endl;
}
}
void GenericIO::readData(
int EffRank, size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
if (FH.isBigEndian())
readData<true>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
else
readData<false>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
}
// Note: Errors from this function should be recoverable. This means that if
// one rank throws an exception, then all ranks should.
template <bool IsBigEndian>
void GenericIO::readData(
int EffRank, size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
if (EffRank == -1)
EffRank = Rank;
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
for (size_t i = 0; i < Vars.size(); ++i)
{
uint64_t Offset = RH->Start;
bool VarFound = false;
for (uint64_t j = 0; j < GH->NVars; ++j)
{
VariableHeader<IsBigEndian>* VH =
(VariableHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->VarsStart + j * GH->VarsSize];
string VName(VH->Name, VH->Name + NameSize);
size_t VNameNull = VName.find('\0');
if (VNameNull < NameSize)
VName.resize(VNameNull);
uint64_t ReadSize = RH->NElems * VH->Size + CRCSize;
if (VName != Vars[i].Name)
{
Offset += ReadSize;
continue;
}
VarFound = true;
bool IsFloat = (VH->Flags & FloatValue) != 0, IsSigned = (VH->Flags & SignedValue) != 0;
if (VH->Size != Vars[i].Size)
{
stringstream ss;
ss << "Size mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << Vars[i].Size << ", file: " << VH->Size;
throw runtime_error(ss.str());
}
else if (IsFloat != Vars[i].IsFloat)
{
string Float("float"), Int("integer");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsFloat ? Float : Int)
<< ", file: " << (IsFloat ? Float : Int);
throw runtime_error(ss.str());
}
else if (IsSigned != Vars[i].IsSigned)
{
string Signed("signed"), Uns("unsigned");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsSigned ? Signed : Uns)
<< ", file: " << (IsSigned ? Signed : Uns);
throw runtime_error(ss.str());
}
size_t VarOffset = RowOffset * Vars[i].Size;
void* VarData = ((char*)Vars[i].Data) + VarOffset;
vector<unsigned char> LData;
void* Data = VarData;
bool HasExtraSpace = Vars[i].HasExtraSpace;
if (offsetof_safe(GH, BlocksStart) < GH->GlobalHeaderSize && GH->BlocksSize > 0)
{
BlockHeader<IsBigEndian>* BH =
(BlockHeader<IsBigEndian>*)&FH
.getHeaderCache()[GH->BlocksStart + (RankIndex * GH->NVars + j) * GH->BlocksSize];
ReadSize = BH->Size + CRCSize;
Offset = BH->Start;
if (strncmp(BH->Filters[0], CompressName, FilterNameSize) == 0)
{
LData.resize(ReadSize);
Data = &LData[0];
HasExtraSpace = true;
}
else if (BH->Filters[0][0] != '\0')
{
stringstream ss;
ss << "Unknown filter \"" << BH->Filters[0] << "\" on variable " << Vars[i].Name;
throw runtime_error(ss.str());
}
}
assert(HasExtraSpace && "Extra space required for reading");
char CRCSave[CRCSize];
char* CRCLoc = ((char*)Data) + ReadSize - CRCSize;
if (HasExtraSpace)
std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
int Retry = 0;
{
int RetryCount = 300;
const char* EnvStr = getenv("GENERICIO_RETRY_COUNT");
if (EnvStr)
RetryCount = atoi(EnvStr);
int RetrySleep = 100; // ms
EnvStr = getenv("GENERICIO_RETRY_SLEEP");
if (EnvStr)
RetrySleep = atoi(EnvStr);
for (; Retry < RetryCount; ++Retry)
{
try
{
FH.get()->read(Data, ReadSize, static_cast<off_t>(Offset), Vars[i].Name);
break;
}
catch (...)
{
}
usleep(1000 * RetrySleep);
}
if (Retry == RetryCount)
{
++NErrs[0];
break;
}
else if (Retry > 0)
{
EnvStr = getenv("GENERICIO_VERBOSE");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
std::cerr << "Rank " << RankTmp << ": " << Retry
<< " I/O retries were necessary for reading " << Vars[i].Name
<< " from: " << OpenFileName << "\n";
std::cerr.flush();
}
}
}
}
TotalReadSize += ReadSize;
uint64_t CRC = crc64_omp(Data, ReadSize);
if (CRC != (uint64_t)-1)
{
++NErrs[1];
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
// All ranks will do this and have a good time!
string dn = "gio_crc_errors";
mkdir(dn.c_str(), 0777);
srand(static_cast<unsigned int>(time(0)));
int DumpNum = rand();
stringstream ssd;
ssd << dn << "/gio_crc_error_dump." << RankTmp << "." << DumpNum << ".bin";
stringstream ss;
ss << dn << "/gio_crc_error_log." << RankTmp << ".txt";
ofstream ofs(ss.str().c_str(), ofstream::out | ofstream::app);
ofs << "On-Disk CRC Error Report:\n";
ofs << "Variable: " << Vars[i].Name << "\n";
ofs << "File: " << OpenFileName << "\n";
ofs << "I/O Retries: " << Retry << "\n";
ofs << "Size: " << ReadSize << " bytes\n";
ofs << "Offset: " << Offset << " bytes\n";
ofs << "CRC: " << CRC << " (expected is -1)\n";
ofs << "Dump file: " << ssd.str() << "\n";
ofs << "\n";
ofs.close();
ofstream dofs(ssd.str().c_str(), ofstream::out);
dofs.write((const char*)Data, ReadSize);
dofs.close();
uint64_t RawCRC = crc64_omp(Data, ReadSize - CRCSize);
unsigned char* UData = (unsigned char*)Data;
crc64_invert(RawCRC, &UData[ReadSize - CRCSize]);
#if 1
crc64_omp(Data, ReadSize);
#else // Commenting because NewCRC cannot == -1 (uint64) and this is debugging code.
// uint64_t NewCRC = crc64_omp(Data, ReadSize);
// std::cerr << "Recalculated CRC: " << NewCRC << ((NewCRC == -1) ? "ok" : "bad") << "\n";
#endif
break;
}
if (HasExtraSpace)
std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
if (LData.size())
{
CompressHeader<IsBigEndian>* CH = (CompressHeader<IsBigEndian>*)&LData[0];
#ifndef LANL_GENERICIO_NO_COMPRESSION
#ifdef _OPENMP
#pragma omp master
{
#endif
if (!blosc_initialized)
{
blosc_init();
blosc_initialized = true;
}
#ifdef _OPENMP
blosc_set_nthreads(omp_get_max_threads());
}
#endif
blosc_decompress(
&LData[0] + sizeof(CompressHeader<IsBigEndian>), VarData, Vars[i].Size * RH->NElems);
#endif // LANL_GENERICIO_NO_COMPRESSION
if (CH->OrigCRC != crc64_omp(VarData, Vars[i].Size * RH->NElems))
{
++NErrs[2];
break;
}
}
// Byte swap the data if necessary.
if (IsBigEndian != isBigEndian())
for (size_t k = 0; k < RH->NElems; ++k)
{
char* OffsetTmp = ((char*)VarData) + k * Vars[i].Size;
bswap(OffsetTmp, Vars[i].Size);
}
break;
}
if (!VarFound)
throw runtime_error("Variable " + Vars[i].Name + " not found in: " + OpenFileName);
// This is for debugging.
if (NErrs[0] || NErrs[1] || NErrs[2])
{
const char* EnvStr = getenv("GENERICIO_VERBOSE");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
std::cerr << "Rank " << RankTmp << ": " << NErrs[0] << " I/O error(s), " << NErrs[1]
<< " CRC error(s) and " << NErrs[2]
<< " decompression CRC error(s) reading: " << Vars[i].Name
<< " from: " << OpenFileName << "\n";
std::cerr.flush();
}
}
}
if (NErrs[0] || NErrs[1] || NErrs[2])
break;
}
}
void GenericIO::getVariableInfo(vector<VariableInfo>& VI)
{
if (FH.isBigEndian())
getVariableInfo<true>(VI);
else
getVariableInfo<false>(VI);
}
template <bool IsBigEndian>
void GenericIO::getVariableInfo(vector<VariableInfo>& VI)
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
for (uint64_t j = 0; j < GH->NVars; ++j)
{
VariableHeader<IsBigEndian>* VH =
(VariableHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->VarsStart + j * GH->VarsSize];
string VName(VH->Name, VH->Name + NameSize);
size_t VNameNull = VName.find('\0');
if (VNameNull < NameSize)
VName.resize(VNameNull);
bool IsFloat = (VH->Flags & FloatValue) != 0, IsSigned = (VH->Flags & SignedValue) != 0,
IsPhysCoordX = ((VH->Flags & ValueIsPhysCoordX) != 0),
IsPhysCoordY = ((VH->Flags & ValueIsPhysCoordY) != 0),
IsPhysCoordZ = ((VH->Flags & ValueIsPhysCoordZ) != 0),
MaybePhysGhost = ((VH->Flags & ValueMaybePhysGhost) != 0);
VI.push_back(VariableInfo(VName, (size_t)VH->Size, IsFloat, IsSigned, IsPhysCoordX,
IsPhysCoordY, IsPhysCoordZ, MaybePhysGhost));
}
}
void GenericIO::setNaturalDefaultPartition()
{
#ifdef __bgq__
DefaultPartition = MPIX_IO_link_id();
#else
#ifndef LANL_GENERICIO_NO_MPI
bool UseName = true;
const char* EnvStr = getenv("GENERICIO_PARTITIONS_USE_NAME");
if (EnvStr)
{
int Mod = atoi(EnvStr);
UseName = (Mod != 0);
}
if (UseName)
{
// This is a heuristic to generate ~256 partitions based on the
// names of the nodes.
char Name[MPI_MAX_PROCESSOR_NAME];
int Len = 0;
MPI_Get_processor_name(Name, &Len);
unsigned char color = 0;
for (int i = 0; i < Len; ++i)
color += (unsigned char)Name[i];
DefaultPartition = color;
}
// This is for debugging.
EnvStr = getenv("GENERICIO_RANK_PARTITIONS");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int Rank;
MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
DefaultPartition += Rank % Mod;
}
}
#endif
#endif
}
} /* END namespace cosmotk */
} /* END namespace lanl */
| 62,983 | 24,363 |
#include "ppl/nn/engines/x86/kernels/onnx/constant_kernel.h"
using namespace std;
using namespace ppl::common;
namespace ppl { namespace nn { namespace x86 {
RetCode ConstantKernel::DoExecute(KernelExecContext* ctx) {
auto output = ctx->GetOutput<TensorImpl>(0);
GetDevice()->CopyFromHost(&output->GetBufferDesc(), param_->data.data(), output->GetShape());
return RC_SUCCESS;
}
}}} // namespace ppl::nn::x86
| 423 | 142 |
class Solution {
public:
bool isdigit(char ch) {
return (ch <= '9' && ch >= '0');
}
int myAtoi(string str) {
#define int long long
int pos = 0, ret = 0, fl = 1;
char ch;
while(pos < (int)str.length() && !isdigit(ch = str[pos++])) if(ch == '-') (fl = -1);
for(ret = ch - '0'; pos < (int)str.length() && isdigit(ch = str[pos++]); ret *= 10, ret += ch - '0');
ret *= fl;
if(ret > INT_MAX) return INT_MAX;
if(ret < INT_MIN) return INT_MIN;
return (int)ret;
#undef int
}
}; | 572 | 215 |
extern "C" {
#include <lai/host.h>
#include <acpispec/tables.h>
}
#include <memory/page_table_manager.h>
#include <memory/page_frame_allocator.h>
#include <utils/abort.h>
#include <utils/log.h>
#include <utils/string.h>
#include <utils/port.h>
#include <pci/pci.h>
#include <timer/timer.h>
#include <acpi/acpi.h>
extern "C" {
void* laihost_map(size_t address, size_t count) {
for (int i = 0; i < count / 0x1000; i++) {
memory::global_page_table_manager.map_memory((void*) (address + i * 0x1000), (void*) (address + i * 0x1000));
}
return (void*) address;
}
void laihost_unmap(void* pointer, size_t count) {
debugf("WARNING: laihost_unmap: %x %d not implemented!\n", pointer, count);
}
void laihost_log(int level, const char* msg) {
switch (level) {
case LAI_WARN_LOG:
debugf("WARNING: %s\n", msg);
break;
case LAI_DEBUG_LOG:
debugf("DEBUG: %s\n", msg);
break;
default:
debugf("UNKNOWN: %s\n", msg);
break;
}
}
__attribute__((noreturn)) void laihost_panic(const char* msg) {
abortf("laihost: %s\n", msg);
}
void* laihost_malloc(size_t size) {
return memory::global_allocator.request_pages(size / 0x1000 + 1);
}
void* laihost_realloc(void *oldptr, size_t newsize, size_t oldsize) {
if (newsize == 0) {
laihost_free(oldptr, oldsize);
return nullptr;
} else if (!oldptr) {
return laihost_malloc(newsize);
} else if (newsize <= oldsize) {
return oldptr;
} else {
void* newptr = laihost_malloc(newsize);
memcpy(newptr, oldptr, oldsize);
return newptr;
}
}
void laihost_free(void *ptr, size_t size) {
memory::global_allocator.free_pages(ptr, size / 0x1000 + 1);
}
void laihost_outb(uint16_t port, uint8_t val) {
outb(port, val);
}
void laihost_outw(uint16_t port, uint16_t val) {
outw(port, val);
}
void laihost_outd(uint16_t port, uint32_t val) {
outl(port, val);
}
uint8_t laihost_inb(uint16_t port) {
return inb(port);
}
uint16_t laihost_inw(uint16_t port) {
return inw(port);
}
uint32_t laihost_ind(uint16_t port) {
return inl(port);
}
void laihost_pci_writeb(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset, uint8_t val) {
pci::pci_writeb(bus, slot, fun, offset, val);
}
void laihost_pci_writew(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset, uint16_t val) {
pci::pci_writew(bus, slot, fun, offset, val);
}
void laihost_pci_writed(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset, uint32_t val) {
pci::pci_writed(bus, slot, fun, offset, val);
}
uint8_t laihost_pci_readb(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset) {
return pci::pci_readb(bus, slot, fun, offset);
}
uint16_t laihost_pci_readw(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset) {
return pci::pci_readw(bus, slot, fun, offset);
}
uint32_t laihost_pci_readd(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset) {
return pci::pci_readd(bus, slot, fun, offset);
}
void laihost_sleep(uint64_t ms) {
timer::global_timer->sleep(ms);
}
uint64_t laihost_timer(void) {
laihost_panic("laihost_timer not implemented! What is that even?");
}
void laihost_handle_amldebug(lai_variable_t* var) {
debugf("DEBUG: laihost_handle_amldebug with %x\n", var);
}
int laihost_sync_wait(struct lai_sync_state *sync, unsigned int val, int64_t timeout) {
debugf("WARNING: laihost_sync_wait not implemented!\n");
return -1;
}
void laihost_sync_wake(struct lai_sync_state *sync) {
debugf("WARNING: laihost_sync_wake not implemented!\n");
}
void* laihost_scan(const char *sig, size_t index) {
if (memcmp(sig, "DSDT", 4) == 0) {
return (void*) (uint64_t) ((acpi_fadt_t*) acpi::find_table(global_bootinfo, (char*) "FACP", 0))->dsdt;
} else {
return acpi::find_table(global_bootinfo, (char*) sig, index);
}
}
} | 3,898 | 1,838 |
/*
* SimpleIniParser
* Copyright (c) 2020 Nichole Mattera
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <iostream>
#include <fstream>
#include <switch.h>
#include <SimpleIniParser.hpp>
#include <vector>
using namespace simpleIniParser;
void writeOption(IniOption * option, bool withTab) {
switch (option->type) {
case IniOptionType::SemicolonComment:
std::cout << ((withTab) ? "\t" : "") << "Type: Semicolon Comment, Value: \"" << option->value << "\"\n";
break;
case IniOptionType::HashtagComment:
std::cout << ((withTab) ? "\t" : "") << "Type: Hashtag Comment, Value: \"" << option->value << "\"\n";
break;
default:
std::cout << ((withTab) ? "\t" : "") << "Type: Option, Key: \"" << option->key << "\", Value: \"" << option->value << "\"\n";
break;
}
}
void writeSection(IniSection * section) {
switch (section->type) {
case IniSectionType::SemicolonComment:
std::cout << "Type: Semicolon Comment, Value: \"" << section->value << "\"\n";
break;
case IniSectionType::HashtagComment:
std::cout << "Type: Hashtag Comment, Value: \"" << section->value << "\"\n";
break;
case IniSectionType::HekateCaption:
std::cout << "Type: Hekate Caption, Value: \"" << section->value << "\"\n";
break;
default:
std::cout << "Type: Section, Value: \"" << section->value << "\"\n";
break;
}
for (auto const& option : section->options) {
writeOption(option, true);
}
std::cout << "\n";
}
int main(int argc, char **argv) {
consoleInit(NULL);
Result rc = romfsInit();
if (R_FAILED(rc)) {
std::cout << "Unable to initialize romfs.\n";
}
else {
Ini * config = Ini::parseFile("romfs:/config.ini");
std::cout << "Reading through an INI file.\n";
std::cout << "=====================================================\n\n";
for (auto const& option : config->options) {
writeOption(option, false);
}
if (config->options.size() > 0)
std::cout << "\n";
for (auto const& section : config->sections) {
writeSection(section);
}
std::cout << "\nGet a specific option from a specific section.\n";
std::cout << "=====================================================\n\n";
std::vector<IniOption *> options = config->findSection("CFW", true, IniSectionType::Section)->findAllOptions("logopath");
for (auto const& option : options) {
writeOption(option, false);
}
IniOption * option = config->findSection("config")->findFirstOption("cUsToMlOgO", false);
std::cout << "Key: \"" << option->key << "\" | Value: \"" << option->value << "\"\n";
IniOption * option2 = config->findSection("CFW", true, IniSectionType::Section)->findFirstOption("option comment test", false, IniOptionType::HashtagComment, IniOptionSearchField::Value);
std::cout << "Key: \"" << option2->key << "\" | Value: \"" << option2->value << "\"\n\n";
delete config;
}
std::cout << "\nPress any key to close.\n";
while(appletMainLoop())
{
hidScanInput();
if (hidKeysDown(CONTROLLER_P1_AUTO))
break;
consoleUpdate(NULL);
}
consoleExit(NULL);
return 0;
} | 4,160 | 1,328 |
// run error mitigation with mitiq with
// $ qcor -qpu aer[noise-model:noise_model.json] -shots 4096 -em mitiq simple_mitiq.cpp
// $ ./a.out
__qpu__ void noisy_zero(qreg q) {
for (int i = 0; i < 100; i++) {
X(q[0]);
}
Measure(q[0]);
}
int main() {
qreg q = qalloc(1);
noisy_zero(q);
std::cout << "Expectation: " << q.exp_val_z() << "\n";
} | 374 | 174 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*++
Module Name:
virtual.cpp
Abstract:
Implementation of virtual memory management functions.
--*/
#include "pal/thread.hpp"
#include "pal/cs.hpp"
#include "pal/malloc.hpp"
#include "pal/file.hpp"
#include "pal/seh.hpp"
#include "pal/dbgmsg.h"
#include "pal/virtual.h"
#include "pal/map.h"
#include "pal/init.h"
#include "common.h"
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#if HAVE_VM_ALLOCATE
#include <mach/vm_map.h>
#include <mach/mach_init.h>
#endif // HAVE_VM_ALLOCATE
using namespace CorUnix;
SET_DEFAULT_DEBUG_CHANNEL(VIRTUAL);
CRITICAL_SECTION virtual_critsec;
// The first node in our list of allocated blocks.
static PCMI pVirtualMemory;
/* We need MAP_ANON. However on some platforms like HP-UX, it is defined as MAP_ANONYMOUS */
#if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
#define MAP_ANON MAP_ANONYMOUS
#endif
/*++
Function:
ReserveVirtualMemory()
Helper function that is used by Virtual* APIs and ExecutableMemoryAllocator
to reserve virtual memory from the OS.
--*/
static LPVOID ReserveVirtualMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize); /* Size of Region */
// A memory allocator that allocates memory from a pre-reserved region
// of virtual memory that is located near the CoreCLR library.
static ExecutableMemoryAllocator g_executableMemoryAllocator;
//
//
// Virtual Memory Logging
//
// We maintain a lightweight in-memory circular buffer recording virtual
// memory operations so that we can better diagnose failures and crashes
// caused by one of these operations mishandling memory in some way.
//
//
namespace VirtualMemoryLogging
{
// Specifies the operation being logged
enum class VirtualOperation
{
Allocate = 0x10,
Reserve = 0x20,
Commit = 0x30,
Decommit = 0x40,
Release = 0x50,
};
// Indicates that the attempted operation has failed
const DWORD FailedOperationMarker = 0x80000000;
// An entry in the in-memory log
struct LogRecord
{
LONG RecordId;
DWORD Operation;
LPVOID CurrentThread;
LPVOID RequestedAddress;
LPVOID ReturnedAddress;
SIZE_T Size;
DWORD AllocationType;
DWORD Protect;
};
// Maximum number of records in the in-memory log
const LONG MaxRecords = 128;
// Buffer used to store the logged data
volatile LogRecord logRecords[MaxRecords];
// Current record number. Use (recordNumber % MaxRecords) to determine
// the current position in the circular buffer.
volatile LONG recordNumber = 0;
// Record an entry in the in-memory log
void LogVaOperation(
IN VirtualOperation operation,
IN LPVOID requestedAddress,
IN SIZE_T size,
IN DWORD flAllocationType,
IN DWORD flProtect,
IN LPVOID returnedAddress,
IN BOOL result)
{
LONG i = InterlockedIncrement(&recordNumber) - 1;
LogRecord* curRec = (LogRecord*)&logRecords[i % MaxRecords];
curRec->RecordId = i;
curRec->CurrentThread = (LPVOID)pthread_self();
curRec->RequestedAddress = requestedAddress;
curRec->ReturnedAddress = returnedAddress;
curRec->Size = size;
curRec->AllocationType = flAllocationType;
curRec->Protect = flProtect;
curRec->Operation = static_cast<DWORD>(operation) | (result ? 0 : FailedOperationMarker);
}
}
/*++
Function:
VIRTUALInitialize()
Initializes this section's critical section.
Return value:
TRUE if initialization succeeded
FALSE otherwise.
--*/
extern "C"
BOOL
VIRTUALInitialize(bool initializeExecutableMemoryAllocator)
{
TRACE("Initializing the Virtual Critical Sections. \n");
InternalInitializeCriticalSection(&virtual_critsec);
pVirtualMemory = NULL;
if (initializeExecutableMemoryAllocator)
{
g_executableMemoryAllocator.Initialize();
}
return TRUE;
}
/***
*
* VIRTUALCleanup()
* Deletes this section's critical section.
*
*/
extern "C"
void VIRTUALCleanup()
{
PCMI pEntry;
PCMI pTempEntry;
CPalThread * pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
// Clean up the allocated memory.
pEntry = pVirtualMemory;
while ( pEntry )
{
WARN( "The memory at %d was not freed through a call to VirtualFree.\n",
pEntry->startBoundary );
free(pEntry->pAllocState);
free(pEntry->pProtectionState );
pTempEntry = pEntry;
pEntry = pEntry->pNext;
free(pTempEntry );
}
pVirtualMemory = NULL;
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
TRACE( "Deleting the Virtual Critical Sections. \n" );
DeleteCriticalSection( &virtual_critsec );
}
/***
*
* VIRTUALContainsInvalidProtectionFlags()
* Returns TRUE if an invalid flag is specified. FALSE otherwise.
*/
static BOOL VIRTUALContainsInvalidProtectionFlags( IN DWORD flProtect )
{
if ( ( flProtect & ~( PAGE_NOACCESS | PAGE_READONLY |
PAGE_READWRITE | PAGE_EXECUTE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE ) ) != 0 )
{
return TRUE;
}
else
{
return FALSE;
}
}
/****
*
* VIRTUALIsPageCommitted
*
* SIZE_T nBitToRetrieve - Which page to check.
*
* Returns TRUE if committed, FALSE otherwise.
*
*/
static BOOL VIRTUALIsPageCommitted( SIZE_T nBitToRetrieve, CONST PCMI pInformation )
{
SIZE_T nByteOffset = 0;
UINT nBitOffset = 0;
UINT byteMask = 0;
if ( !pInformation )
{
ERROR( "pInformation was NULL!\n" );
return FALSE;
}
nByteOffset = nBitToRetrieve / CHAR_BIT;
nBitOffset = nBitToRetrieve % CHAR_BIT;
byteMask = 1 << nBitOffset;
if ( pInformation->pAllocState[ nByteOffset ] & byteMask )
{
return TRUE;
}
else
{
return FALSE;
}
}
/*********
*
* VIRTUALGetAllocationType
*
* IN SIZE_T Index - The page within the range to retrieve
* the state for.
*
* IN pInformation - The virtual memory object.
*
*/
static INT VIRTUALGetAllocationType( SIZE_T Index, CONST PCMI pInformation )
{
if ( VIRTUALIsPageCommitted( Index, pInformation ) )
{
return MEM_COMMIT;
}
else
{
return MEM_RESERVE;
}
}
/****
*
* VIRTUALSetPageBits
*
* IN UINT nStatus - Bit set / reset [0: reset, any other value: set].
* IN SIZE_T nStartingBit - The bit to set.
*
* IN SIZE_T nNumberOfBits - The range of bits to set.
* IN BYTE* pBitArray - A pointer the array to be manipulated.
*
* Returns TRUE on success, FALSE otherwise.
* Turn on/off memory status bits.
*
*/
static BOOL VIRTUALSetPageBits ( UINT nStatus, SIZE_T nStartingBit,
SIZE_T nNumberOfBits, BYTE * pBitArray )
{
/* byte masks for optimized modification of partial bytes (changing less
than 8 bits in a single byte). note that bits are treated in little
endian order : value 1 is bit 0; value 128 is bit 7. in the binary
representations below, bit 0 is on the right */
/* start masks : for modifying bits >= n while preserving bits < n.
example : if nStartignBit%8 is 3, then bits 0, 1, 2 remain unchanged
while bits 3..7 are changed; startmasks[3] can be used for this. */
static const BYTE startmasks[8] = {
0xff, /* start at 0 : 1111 1111 */
0xfe, /* start at 1 : 1111 1110 */
0xfc, /* start at 2 : 1111 1100 */
0xf8, /* start at 3 : 1111 1000 */
0xf0, /* start at 4 : 1111 0000 */
0xe0, /* start at 5 : 1110 0000 */
0xc0, /* start at 6 : 1100 0000 */
0x80 /* start at 7 : 1000 0000 */
};
/* end masks : for modifying bits <= n while preserving bits > n.
example : if the last bit to change is 5, then bits 6 & 7 stay unchanged
while bits 1..5 are changed; endmasks[5] can be used for this. */
static const BYTE endmasks[8] = {
0x01, /* end at 0 : 0000 0001 */
0x03, /* end at 1 : 0000 0011 */
0x07, /* end at 2 : 0000 0111 */
0x0f, /* end at 3 : 0000 1111 */
0x1f, /* end at 4 : 0001 1111 */
0x3f, /* end at 5 : 0011 1111 */
0x7f, /* end at 6 : 0111 1111 */
0xff /* end at 7 : 1111 1111 */
};
/* last example : if only the middle of a byte must be changed, both start
and end masks can be combined (bitwise AND) to obtain the correct mask.
if we want to change bits 2 to 4 :
startmasks[2] : 0xfc 1111 1100 (change 2,3,4,5,6,7)
endmasks[4]: 0x1f 0001 1111 (change 0,1,2,3,4)
bitwise AND : 0x1c 0001 1100 (change 2,3,4)
*/
BYTE byte_mask;
SIZE_T nLastBit;
SIZE_T nFirstByte;
SIZE_T nLastByte;
SIZE_T nFullBytes;
TRACE( "VIRTUALSetPageBits( nStatus = %d, nStartingBit = %d, "
"nNumberOfBits = %d, pBitArray = 0x%p )\n",
nStatus, nStartingBit, nNumberOfBits, pBitArray );
if ( 0 == nNumberOfBits )
{
ERROR( "nNumberOfBits was 0!\n" );
return FALSE;
}
nLastBit = nStartingBit+nNumberOfBits-1;
nFirstByte = nStartingBit / 8;
nLastByte = nLastBit / 8;
/* handle partial first byte (if any) */
if(0 != (nStartingBit % 8))
{
byte_mask = startmasks[nStartingBit % 8];
/* if 1st byte is the only changing byte, combine endmask to preserve
trailing bits (see 3rd example above) */
if( nLastByte == nFirstByte)
{
byte_mask &= endmasks[nLastBit % 8];
}
/* byte_mask contains 1 for bits to change, 0 for bits to leave alone */
if(0 == nStatus)
{
/* bits to change must be set to 0 : invert byte_mask (giving 0 for
bits to change), use bitwise AND */
pBitArray[nFirstByte] &= ~byte_mask;
}
else
{
/* bits to change must be set to 1 : use bitwise OR */
pBitArray[nFirstByte] |= byte_mask;
}
/* stop right away if only 1 byte is being modified */
if(nLastByte == nFirstByte)
{
return TRUE;
}
/* we're done with the 1st byte; skip over it */
nFirstByte++;
}
/* number of bytes to change, excluding the last byte (handled separately)*/
nFullBytes = nLastByte - nFirstByte;
if(0 != nFullBytes)
{
// Turn off/on dirty bits
memset( &(pBitArray[nFirstByte]), (0 == nStatus) ? 0 : 0xFF, nFullBytes );
}
/* handle last (possibly partial) byte */
byte_mask = endmasks[nLastBit % 8];
/* byte_mask contains 1 for bits to change, 0 for bits to leave alone */
if(0 == nStatus)
{
/* bits to change must be set to 0 : invert byte_mask (giving 0 for
bits to change), use bitwise AND */
pBitArray[nLastByte] &= ~byte_mask;
}
else
{
/* bits to change must be set to 1 : use bitwise OR */
pBitArray[nLastByte] |= byte_mask;
}
return TRUE;
}
/****
*
* VIRTUALSetAllocState
*
* IN UINT nAction - Which action to perform.
* IN SIZE_T nStartingBit - The bit to set.
*
* IN SIZE_T nNumberOfBits - The range of bits to set.
* IN PCMI pStateArray - A pointer the array to be manipulated.
*
* Returns TRUE on success, FALSE otherwise.
* Turn bit on to indicate committed, turn bit off to indicate reserved.
*
*/
static BOOL VIRTUALSetAllocState( UINT nAction, SIZE_T nStartingBit,
SIZE_T nNumberOfBits, CONST PCMI pInformation )
{
TRACE( "VIRTUALSetAllocState( nAction = %d, nStartingBit = %d, "
"nNumberOfBits = %d, pStateArray = 0x%p )\n",
nAction, nStartingBit, nNumberOfBits, pInformation );
if ( !pInformation )
{
ERROR( "pInformation was invalid!\n" );
return FALSE;
}
return VIRTUALSetPageBits((MEM_COMMIT == nAction) ? 1 : 0, nStartingBit,
nNumberOfBits, pInformation->pAllocState);
}
/****
*
* VIRTUALFindRegionInformation( )
*
* IN UINT_PTR address - The address to look for.
*
* Returns the PCMI if found, NULL otherwise.
*/
static PCMI VIRTUALFindRegionInformation( IN UINT_PTR address )
{
PCMI pEntry = NULL;
TRACE( "VIRTUALFindRegionInformation( %#x )\n", address );
pEntry = pVirtualMemory;
while( pEntry )
{
if ( pEntry->startBoundary > address )
{
/* Gone past the possible location in the list. */
pEntry = NULL;
break;
}
if ( pEntry->startBoundary + pEntry->memSize > address )
{
break;
}
pEntry = pEntry->pNext;
}
return pEntry;
}
/*++
Function :
VIRTUALReleaseMemory
Removes a PCMI entry from the list.
Returns true on success. FALSE otherwise.
--*/
static BOOL VIRTUALReleaseMemory( PCMI pMemoryToBeReleased )
{
BOOL bRetVal = TRUE;
if ( !pMemoryToBeReleased )
{
ASSERT( "Invalid pointer.\n" );
return FALSE;
}
if ( pMemoryToBeReleased == pVirtualMemory )
{
/* This is either the first entry, or the only entry. */
pVirtualMemory = pMemoryToBeReleased->pNext;
if ( pMemoryToBeReleased->pNext )
{
pMemoryToBeReleased->pNext->pPrevious = NULL;
}
}
else /* Could be anywhere in the list. */
{
/* Delete the entry from the linked list. */
if ( pMemoryToBeReleased->pPrevious )
{
pMemoryToBeReleased->pPrevious->pNext = pMemoryToBeReleased->pNext;
}
if ( pMemoryToBeReleased->pNext )
{
pMemoryToBeReleased->pNext->pPrevious = pMemoryToBeReleased->pPrevious;
}
}
free( pMemoryToBeReleased->pAllocState );
pMemoryToBeReleased->pAllocState = NULL;
free( pMemoryToBeReleased->pProtectionState );
pMemoryToBeReleased->pProtectionState = NULL;
free( pMemoryToBeReleased );
pMemoryToBeReleased = NULL;
return bRetVal;
}
/****
* VIRTUALConvertWinFlags() -
* Converts win32 protection flags to
* internal VIRTUAL flags.
*
*/
static BYTE VIRTUALConvertWinFlags( IN DWORD flProtect )
{
BYTE MemAccessControl = 0;
switch ( flProtect & 0xff )
{
case PAGE_NOACCESS :
MemAccessControl = VIRTUAL_NOACCESS;
break;
case PAGE_READONLY :
MemAccessControl = VIRTUAL_READONLY;
break;
case PAGE_READWRITE :
MemAccessControl = VIRTUAL_READWRITE;
break;
case PAGE_EXECUTE :
MemAccessControl = VIRTUAL_EXECUTE;
break;
case PAGE_EXECUTE_READ :
MemAccessControl = VIRTUAL_EXECUTE_READ;
break;
case PAGE_EXECUTE_READWRITE:
MemAccessControl = VIRTUAL_EXECUTE_READWRITE;
break;
default :
MemAccessControl = 0;
ERROR( "Incorrect or no protection flags specified.\n" );
break;
}
return MemAccessControl;
}
/****
* VIRTUALConvertVirtualFlags() -
* Converts internal virtual protection
* flags to their win32 counterparts.
*/
static DWORD VIRTUALConvertVirtualFlags( IN BYTE VirtualProtect )
{
DWORD MemAccessControl = 0;
if ( VirtualProtect == VIRTUAL_READONLY )
{
MemAccessControl = PAGE_READONLY;
}
else if ( VirtualProtect == VIRTUAL_READWRITE )
{
MemAccessControl = PAGE_READWRITE;
}
else if ( VirtualProtect == VIRTUAL_EXECUTE_READWRITE )
{
MemAccessControl = PAGE_EXECUTE_READWRITE;
}
else if ( VirtualProtect == VIRTUAL_EXECUTE_READ )
{
MemAccessControl = PAGE_EXECUTE_READ;
}
else if ( VirtualProtect == VIRTUAL_EXECUTE )
{
MemAccessControl = PAGE_EXECUTE;
}
else if ( VirtualProtect == VIRTUAL_NOACCESS )
{
MemAccessControl = PAGE_NOACCESS;
}
else
{
MemAccessControl = 0;
ERROR( "Incorrect or no protection flags specified.\n" );
}
return MemAccessControl;
}
/***
* Displays the linked list.
*
*/
#if defined _DEBUG
static void VIRTUALDisplayList( void )
{
if (!DBG_ENABLED(DLI_TRACE, defdbgchan))
return;
PCMI p;
SIZE_T count;
SIZE_T index;
CPalThread * pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
p = pVirtualMemory;
count = 0;
while ( p ) {
DBGOUT( "Entry %d : \n", count );
DBGOUT( "\t startBoundary %#x \n", p->startBoundary );
DBGOUT( "\t memSize %d \n", p->memSize );
DBGOUT( "\t pAllocState " );
for ( index = 0; index < p->memSize / VIRTUAL_PAGE_SIZE; index++)
{
DBGOUT( "[%d] ", VIRTUALGetAllocationType( index, p ) );
}
DBGOUT( "\t pProtectionState " );
for ( index = 0; index < p->memSize / VIRTUAL_PAGE_SIZE; index++ )
{
DBGOUT( "[%d] ", (UINT)p->pProtectionState[ index ] );
}
DBGOUT( "\n" );
DBGOUT( "\t accessProtection %d \n", p->accessProtection );
DBGOUT( "\t allocationType %d \n", p->allocationType );
DBGOUT( "\t pNext %p \n", p->pNext );
DBGOUT( "\t pLast %p \n", p->pPrevious );
count++;
p = p->pNext;
}
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
}
#endif
#ifdef DEBUG
void VerifyRightEntry(PCMI pEntry)
{
volatile PCMI pRight = pEntry->pNext;
SIZE_T endAddress;
if (pRight != nullptr)
{
endAddress = ((SIZE_T)pEntry->startBoundary) + pEntry->memSize;
_ASSERTE(endAddress <= (SIZE_T)pRight->startBoundary);
}
}
void VerifyLeftEntry(PCMI pEntry)
{
volatile PCMI pLeft = pEntry->pPrevious;
SIZE_T endAddress;
if (pLeft != NULL)
{
endAddress = ((SIZE_T)pLeft->startBoundary) + pLeft->memSize;
_ASSERTE(endAddress <= (SIZE_T)pEntry->startBoundary);
}
}
#endif // DEBUG
/****
* VIRTUALStoreAllocationInfo()
*
* Stores the allocation information in the linked list.
* NOTE: The caller must own the critical section.
*/
static BOOL VIRTUALStoreAllocationInfo(
IN UINT_PTR startBoundary, /* Start of the region. */
IN SIZE_T memSize, /* Size of the region. */
IN DWORD flAllocationType, /* Allocation Types. */
IN DWORD flProtection ) /* Protections flags on the memory. */
{
PCMI pNewEntry = nullptr;
PCMI pMemInfo = nullptr;
SIZE_T nBufferSize = 0;
if ((memSize & VIRTUAL_PAGE_MASK) != 0)
{
ERROR("The memory size was not a multiple of the page size. \n");
return FALSE;
}
if (!(pNewEntry = (PCMI)InternalMalloc(sizeof(*pNewEntry))))
{
ERROR( "Unable to allocate memory for the structure.\n");
return FALSE;
}
pNewEntry->startBoundary = startBoundary;
pNewEntry->memSize = memSize;
pNewEntry->allocationType = flAllocationType;
pNewEntry->accessProtection = flProtection;
nBufferSize = memSize / VIRTUAL_PAGE_SIZE / CHAR_BIT;
if ((memSize / VIRTUAL_PAGE_SIZE) % CHAR_BIT != 0)
{
nBufferSize++;
}
pNewEntry->pAllocState = (BYTE*)InternalMalloc(nBufferSize);
pNewEntry->pProtectionState = (BYTE*)InternalMalloc((memSize / VIRTUAL_PAGE_SIZE));
if (pNewEntry->pAllocState && pNewEntry->pProtectionState)
{
/* Set the intial allocation state, and initial allocation protection. */
VIRTUALSetAllocState(MEM_RESERVE, 0, nBufferSize * CHAR_BIT, pNewEntry);
memset(pNewEntry->pProtectionState,
VIRTUALConvertWinFlags(flProtection),
memSize / VIRTUAL_PAGE_SIZE);
}
else
{
ERROR( "Unable to allocate memory for the structure.\n");
if (pNewEntry->pProtectionState) free(pNewEntry->pProtectionState);
pNewEntry->pProtectionState = nullptr;
if (pNewEntry->pAllocState) free(pNewEntry->pAllocState);
pNewEntry->pAllocState = nullptr;
free(pNewEntry);
pNewEntry = nullptr;
return FALSE;
}
pMemInfo = pVirtualMemory;
if (pMemInfo && pMemInfo->startBoundary < startBoundary)
{
/* Look for the correct insert point */
TRACE("Looking for the correct insert location.\n");
while (pMemInfo->pNext && (pMemInfo->pNext->startBoundary < startBoundary))
{
pMemInfo = pMemInfo->pNext;
}
pNewEntry->pNext = pMemInfo->pNext;
pNewEntry->pPrevious = pMemInfo;
if (pNewEntry->pNext)
{
pNewEntry->pNext->pPrevious = pNewEntry;
}
pMemInfo->pNext = pNewEntry;
}
else
{
/* This is the first entry in the list. */
pNewEntry->pNext = pMemInfo;
pNewEntry->pPrevious = nullptr;
if (pNewEntry->pNext)
{
pNewEntry->pNext->pPrevious = pNewEntry;
}
pVirtualMemory = pNewEntry ;
}
#ifdef DEBUG
VerifyRightEntry(pNewEntry);
VerifyLeftEntry(pNewEntry);
#endif // DEBUG
return TRUE;
}
/******
*
* VIRTUALReserveMemory() - Helper function that actually reserves the memory.
*
* NOTE: I call SetLastError in here, because many different error states
* exists, and that would be very complicated to work around.
*
*/
static LPVOID VIRTUALReserveMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize, /* Size of Region */
IN DWORD flAllocationType, /* Type of allocation */
IN DWORD flProtect) /* Type of access protection */
{
LPVOID pRetVal = NULL;
UINT_PTR StartBoundary;
SIZE_T MemSize;
TRACE( "Reserving the memory now..\n");
// First, figure out where we're trying to reserve the memory and
// how much we need. On most systems, requests to mmap must be
// page-aligned and at multiples of the page size.
StartBoundary = (UINT_PTR)lpAddress & ~BOUNDARY_64K;
/* Add the sizes, and round down to the nearest page boundary. */
MemSize = ( ((UINT_PTR)lpAddress + dwSize + VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK ) -
StartBoundary;
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
// If this is a request for special executable (JIT'ed) memory then, first of all,
// try to get memory from the executable memory allocator to satisfy the request.
if (((flAllocationType & MEM_RESERVE_EXECUTABLE) != 0) && (lpAddress == NULL))
{
pRetVal = g_executableMemoryAllocator.AllocateMemory(MemSize);
}
if (pRetVal == NULL)
{
// Try to reserve memory from the OS
pRetVal = ReserveVirtualMemory(pthrCurrent, (LPVOID)StartBoundary, MemSize);
}
if (pRetVal != NULL)
{
if ( !lpAddress )
{
/* Compute the real values instead of the null values. */
StartBoundary = (UINT_PTR)pRetVal & ~VIRTUAL_PAGE_MASK;
MemSize = ( ((UINT_PTR)pRetVal + dwSize + VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK ) -
StartBoundary;
}
if ( !VIRTUALStoreAllocationInfo( StartBoundary, MemSize,
flAllocationType, flProtect ) )
{
ASSERT( "Unable to store the structure in the list.\n");
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
munmap( pRetVal, MemSize );
pRetVal = NULL;
}
}
LogVaOperation(
VirtualMemoryLogging::VirtualOperation::Reserve,
lpAddress,
dwSize,
flAllocationType,
flProtect,
pRetVal,
pRetVal != NULL);
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
return pRetVal;
}
/******
*
* ReserveVirtualMemory() - Helper function that is used by Virtual* APIs
* and ExecutableMemoryAllocator to reserve virtual memory from the OS.
*
*/
static LPVOID ReserveVirtualMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize) /* Size of Region */
{
UINT_PTR StartBoundary = (UINT_PTR)lpAddress;
SIZE_T MemSize = dwSize;
TRACE( "Reserving the memory now.\n");
// Most platforms will only commit memory if it is dirtied,
// so this should not consume too much swap space.
int mmapFlags = 0;
#if HAVE_VM_ALLOCATE
// Allocate with vm_allocate first, then map at the fixed address.
int result = vm_allocate(mach_task_self(),
&StartBoundary,
MemSize,
((LPVOID) StartBoundary != nullptr) ? FALSE : TRUE);
if (result != KERN_SUCCESS)
{
ERROR("vm_allocate failed to allocated the requested region!\n");
pthrCurrent->SetLastError(ERROR_INVALID_ADDRESS);
return nullptr;
}
mmapFlags |= MAP_FIXED;
#endif // HAVE_VM_ALLOCATE
mmapFlags |= MAP_ANON | MAP_PRIVATE;
LPVOID pRetVal = mmap((LPVOID) StartBoundary,
MemSize,
PROT_NONE,
mmapFlags,
-1 /* fd */,
0 /* offset */);
if (pRetVal == MAP_FAILED)
{
ERROR( "Failed due to insufficient memory.\n" );
#if HAVE_VM_ALLOCATE
vm_deallocate(mach_task_self(), StartBoundary, MemSize);
#endif // HAVE_VM_ALLOCATE
pthrCurrent->SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
/* Check to see if the region is what we asked for. */
if (lpAddress != nullptr && StartBoundary != (UINT_PTR)pRetVal)
{
ERROR("We did not get the region we asked for from mmap!\n");
pthrCurrent->SetLastError(ERROR_INVALID_ADDRESS);
munmap(pRetVal, MemSize);
return nullptr;
}
#if MMAP_ANON_IGNORES_PROTECTION
if (mprotect(pRetVal, MemSize, PROT_NONE) != 0)
{
ERROR("mprotect failed to protect the region!\n");
pthrCurrent->SetLastError(ERROR_INVALID_ADDRESS);
munmap(pRetVal, MemSize);
return nullptr;
}
#endif // MMAP_ANON_IGNORES_PROTECTION
return pRetVal;
}
/******
*
* VIRTUALCommitMemory() - Helper function that actually commits the memory.
*
* NOTE: I call SetLastError in here, because many different error states
* exists, and that would be very complicated to work around.
*
*/
static LPVOID
VIRTUALCommitMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize, /* Size of Region */
IN DWORD flAllocationType, /* Type of allocation */
IN DWORD flProtect) /* Type of access protection */
{
UINT_PTR StartBoundary = 0;
SIZE_T MemSize = 0;
PCMI pInformation = 0;
LPVOID pRetVal = NULL;
BOOL IsLocallyReserved = FALSE;
SIZE_T totalPages;
INT allocationType, curAllocationType;
INT protectionState, curProtectionState;
SIZE_T initialRunStart;
SIZE_T runStart;
SIZE_T runLength;
SIZE_T index;
INT nProtect;
INT vProtect;
if ( lpAddress )
{
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
/* Add the sizes, and round down to the nearest page boundary. */
MemSize = ( ((UINT_PTR)lpAddress + dwSize + VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK ) -
StartBoundary;
}
else
{
MemSize = ( dwSize + VIRTUAL_PAGE_MASK ) & ~VIRTUAL_PAGE_MASK;
}
/* See if we have already reserved this memory. */
pInformation = VIRTUALFindRegionInformation( StartBoundary );
if ( !pInformation )
{
/* According to the new MSDN docs, if MEM_COMMIT is specified,
and the memory is not reserved, you reserve and then commit.
*/
LPVOID pReservedMemory =
VIRTUALReserveMemory( pthrCurrent, lpAddress, dwSize,
flAllocationType, flProtect );
TRACE( "Reserve and commit the memory!\n " );
if ( pReservedMemory )
{
/* Re-align the addresses and try again to find the memory. */
StartBoundary = (UINT_PTR)pReservedMemory & ~VIRTUAL_PAGE_MASK;
MemSize = ( ((UINT_PTR)pReservedMemory + dwSize + VIRTUAL_PAGE_MASK)
& ~VIRTUAL_PAGE_MASK ) - StartBoundary;
pInformation = VIRTUALFindRegionInformation( StartBoundary );
if ( !pInformation )
{
ASSERT( "Unable to locate the region information.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
pRetVal = NULL;
goto done;
}
IsLocallyReserved = TRUE;
}
else
{
ERROR( "Unable to reserve the memory.\n" );
/* Don't set last error here, it will already be set. */
pRetVal = NULL;
goto done;
}
}
TRACE( "Committing the memory now..\n");
// Pages that aren't already committed need to be committed. Pages that
// are committed don't need to be committed, but they might need to have
// their permissions changed.
// To get this right, we find runs of pages with similar states and
// permissions. If a run is not committed, we commit it and then set
// its permissions. If a run is committed but has different permissions
// from what we're trying to set, we set its permissions. Finally,
// if a run is already committed and has the right permissions,
// we don't need to do anything to it.
totalPages = MemSize / VIRTUAL_PAGE_SIZE;
runStart = (StartBoundary - pInformation->startBoundary) /
VIRTUAL_PAGE_SIZE; // Page index
initialRunStart = runStart;
allocationType = VIRTUALGetAllocationType(runStart, pInformation);
protectionState = pInformation->pProtectionState[runStart];
curAllocationType = allocationType;
curProtectionState = protectionState;
runLength = 1;
nProtect = W32toUnixAccessControl(flProtect);
vProtect = VIRTUALConvertWinFlags(flProtect);
if (totalPages > pInformation->memSize / VIRTUAL_PAGE_SIZE - runStart)
{
ERROR("Trying to commit beyond the end of the region!\n");
goto error;
}
while(runStart < initialRunStart + totalPages)
{
// Find the next run of pages
for(index = runStart + 1; index < initialRunStart + totalPages;
index++)
{
curAllocationType = VIRTUALGetAllocationType(index, pInformation);
curProtectionState = pInformation->pProtectionState[index];
if (curAllocationType != allocationType ||
curProtectionState != protectionState)
{
break;
}
runLength++;
}
StartBoundary = pInformation->startBoundary + runStart * VIRTUAL_PAGE_SIZE;
MemSize = runLength * VIRTUAL_PAGE_SIZE;
if (allocationType != MEM_COMMIT)
{
// Commit the pages
if (mprotect((void *) StartBoundary, MemSize, PROT_WRITE | PROT_READ) != 0)
{
ERROR("mprotect() failed! Error(%d)=%s\n", errno, strerror(errno));
goto error;
}
VIRTUALSetAllocState(MEM_COMMIT, runStart, runLength, pInformation);
if (nProtect == (PROT_WRITE | PROT_READ))
{
// Handle this case specially so we don't bother
// mprotect'ing the region.
memset(pInformation->pProtectionState + runStart,
vProtect, runLength);
}
protectionState = VIRTUAL_READWRITE;
}
if (protectionState != vProtect)
{
// Change permissions.
if (mprotect((void *) StartBoundary, MemSize, nProtect) != -1)
{
memset(pInformation->pProtectionState + runStart,
vProtect, runLength);
}
else
{
ERROR("mprotect() failed! Error(%d)=%s\n",
errno, strerror(errno));
goto error;
}
}
runStart = index;
runLength = 1;
allocationType = curAllocationType;
protectionState = curProtectionState;
}
pRetVal = (void *) (pInformation->startBoundary + initialRunStart * VIRTUAL_PAGE_SIZE);
goto done;
error:
if ( flAllocationType & MEM_RESERVE || IsLocallyReserved )
{
munmap( pRetVal, MemSize );
if ( VIRTUALReleaseMemory( pInformation ) == FALSE )
{
ASSERT( "Unable to remove the PCMI entry from the list.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
pRetVal = NULL;
goto done;
}
pInformation = NULL;
pRetVal = NULL;
}
done:
LogVaOperation(
VirtualMemoryLogging::VirtualOperation::Commit,
lpAddress,
dwSize,
flAllocationType,
flProtect,
pRetVal,
pRetVal != NULL);
return pRetVal;
}
/*++
Function:
VirtualAlloc
Note:
MEM_TOP_DOWN, MEM_PHYSICAL, MEM_WRITE_WATCH are not supported.
Unsupported flags are ignored.
Page size on i386 is set to 4k.
See MSDN doc.
--*/
LPVOID
PALAPI
VirtualAlloc(
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize, /* Size of Region */
IN DWORD flAllocationType, /* Type of allocation */
IN DWORD flProtect) /* Type of access protection */
{
LPVOID pRetVal = NULL;
CPalThread *pthrCurrent;
PERF_ENTRY(VirtualAlloc);
ENTRY("VirtualAlloc(lpAddress=%p, dwSize=%u, flAllocationType=%#x, \
flProtect=%#x)\n", lpAddress, dwSize, flAllocationType, flProtect);
pthrCurrent = InternalGetCurrentThread();
if ( ( flAllocationType & MEM_WRITE_WATCH ) != 0 )
{
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
goto done;
}
/* Test for un-supported flags. */
if ( ( flAllocationType & ~( MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_RESERVE_EXECUTABLE ) ) != 0 )
{
ASSERT( "flAllocationType can be one, or any combination of MEM_COMMIT, \
MEM_RESERVE, MEM_TOP_DOWN, or MEM_RESERVE_EXECUTABLE.\n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
goto done;
}
if ( VIRTUALContainsInvalidProtectionFlags( flProtect ) )
{
ASSERT( "flProtect can be one of PAGE_READONLY, PAGE_READWRITE, or \
PAGE_EXECUTE_READWRITE || PAGE_NOACCESS. \n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
goto done;
}
if ( flAllocationType & MEM_TOP_DOWN )
{
WARN( "Ignoring the allocation flag MEM_TOP_DOWN.\n" );
}
LogVaOperation(
VirtualMemoryLogging::VirtualOperation::Allocate,
lpAddress,
dwSize,
flAllocationType,
flProtect,
NULL,
TRUE);
if ( flAllocationType & MEM_RESERVE )
{
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
pRetVal = VIRTUALReserveMemory( pthrCurrent, lpAddress, dwSize, flAllocationType, flProtect );
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
if ( !pRetVal )
{
/* Error messages are already displayed, just leave. */
goto done;
}
}
if ( flAllocationType & MEM_COMMIT )
{
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
if ( pRetVal != NULL )
{
/* We are reserving and committing. */
pRetVal = VIRTUALCommitMemory( pthrCurrent, pRetVal, dwSize,
flAllocationType, flProtect );
}
else
{
/* Just a commit. */
pRetVal = VIRTUALCommitMemory( pthrCurrent, lpAddress, dwSize,
flAllocationType, flProtect );
}
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
}
done:
#if defined _DEBUG
VIRTUALDisplayList();
#endif
LOGEXIT("VirtualAlloc returning %p\n ", pRetVal );
PERF_EXIT(VirtualAlloc);
return pRetVal;
}
/*++
Function:
VirtualFree
See MSDN doc.
--*/
BOOL
PALAPI
VirtualFree(
IN LPVOID lpAddress, /* Address of region. */
IN SIZE_T dwSize, /* Size of region. */
IN DWORD dwFreeType ) /* Operation type. */
{
BOOL bRetVal = TRUE;
CPalThread *pthrCurrent;
PERF_ENTRY(VirtualFree);
ENTRY("VirtualFree(lpAddress=%p, dwSize=%u, dwFreeType=%#x)\n",
lpAddress, dwSize, dwFreeType);
pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
/* Sanity Checks. */
if ( !lpAddress )
{
ERROR( "lpAddress cannot be NULL. You must specify the base address of\
regions to be de-committed. \n" );
pthrCurrent->SetLastError( ERROR_INVALID_ADDRESS );
bRetVal = FALSE;
goto VirtualFreeExit;
}
if ( !( dwFreeType & MEM_RELEASE ) && !(dwFreeType & MEM_DECOMMIT ) )
{
ERROR( "dwFreeType must contain one of the following: \
MEM_RELEASE or MEM_DECOMMIT\n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
bRetVal = FALSE;
goto VirtualFreeExit;
}
/* You cannot release and decommit in one call.*/
if ( dwFreeType & MEM_RELEASE && dwFreeType & MEM_DECOMMIT )
{
ERROR( "MEM_RELEASE cannot be combined with MEM_DECOMMIT.\n" );
bRetVal = FALSE;
goto VirtualFreeExit;
}
if ( dwFreeType & MEM_DECOMMIT )
{
UINT_PTR StartBoundary = 0;
SIZE_T MemSize = 0;
if ( dwSize == 0 )
{
ERROR( "dwSize cannot be 0. \n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
bRetVal = FALSE;
goto VirtualFreeExit;
}
/*
* A two byte range straddling 2 pages caues both pages to be either
* released or decommitted. So round the dwSize up to the next page
* boundary and round the lpAddress down to the next page boundary.
*/
MemSize = (((UINT_PTR)(dwSize) + ((UINT_PTR)(lpAddress) & VIRTUAL_PAGE_MASK)
+ VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK);
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
PCMI pUnCommittedMem;
pUnCommittedMem = VIRTUALFindRegionInformation( StartBoundary );
if (!pUnCommittedMem)
{
ASSERT( "Unable to locate the region information.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
bRetVal = FALSE;
goto VirtualFreeExit;
}
TRACE( "Un-committing the following page(s) %d to %d.\n",
StartBoundary, MemSize );
// Explicitly calling mmap instead of mprotect here makes it
// that much more clear to the operating system that we no
// longer need these pages.
if ( mmap( (LPVOID)StartBoundary, MemSize, PROT_NONE,
MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0 ) != MAP_FAILED )
{
#if (MMAP_ANON_IGNORES_PROTECTION)
if (mprotect((LPVOID) StartBoundary, MemSize, PROT_NONE) != 0)
{
ASSERT("mprotect failed to protect the region!\n");
pthrCurrent->SetLastError(ERROR_INTERNAL_ERROR);
munmap((LPVOID) StartBoundary, MemSize);
bRetVal = FALSE;
goto VirtualFreeExit;
}
#endif // MMAP_ANON_IGNORES_PROTECTION
SIZE_T index = 0;
SIZE_T nNumOfPagesToChange = 0;
/* We can now commit this memory by calling VirtualAlloc().*/
index = (StartBoundary - pUnCommittedMem->startBoundary) / VIRTUAL_PAGE_SIZE;
nNumOfPagesToChange = MemSize / VIRTUAL_PAGE_SIZE;
VIRTUALSetAllocState( MEM_RESERVE, index,
nNumOfPagesToChange, pUnCommittedMem );
goto VirtualFreeExit;
}
else
{
ASSERT( "mmap() returned an abnormal value.\n" );
bRetVal = FALSE;
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
goto VirtualFreeExit;
}
}
if ( dwFreeType & MEM_RELEASE )
{
PCMI pMemoryToBeReleased =
VIRTUALFindRegionInformation( (UINT_PTR)lpAddress );
if ( !pMemoryToBeReleased )
{
ERROR( "lpAddress must be the base address returned by VirtualAlloc.\n" );
pthrCurrent->SetLastError( ERROR_INVALID_ADDRESS );
bRetVal = FALSE;
goto VirtualFreeExit;
}
if ( dwSize != 0 )
{
ERROR( "dwSize must be 0 if you are releasing the memory.\n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
bRetVal = FALSE;
goto VirtualFreeExit;
}
TRACE( "Releasing the following memory %d to %d.\n",
pMemoryToBeReleased->startBoundary, pMemoryToBeReleased->memSize );
if ( munmap( (LPVOID)pMemoryToBeReleased->startBoundary,
pMemoryToBeReleased->memSize ) == 0 )
{
if ( VIRTUALReleaseMemory( pMemoryToBeReleased ) == FALSE )
{
ASSERT( "Unable to remove the PCMI entry from the list.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
bRetVal = FALSE;
goto VirtualFreeExit;
}
pMemoryToBeReleased = NULL;
}
else
{
ASSERT( "Unable to unmap the memory, munmap() returned an abnormal value.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
bRetVal = FALSE;
goto VirtualFreeExit;
}
}
VirtualFreeExit:
LogVaOperation(
(dwFreeType & MEM_DECOMMIT) ? VirtualMemoryLogging::VirtualOperation::Decommit
: VirtualMemoryLogging::VirtualOperation::Release,
lpAddress,
dwSize,
dwFreeType,
0,
NULL,
bRetVal);
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
LOGEXIT( "VirtualFree returning %s.\n", bRetVal == TRUE ? "TRUE" : "FALSE" );
PERF_EXIT(VirtualFree);
return bRetVal;
}
/*++
Function:
VirtualProtect
See MSDN doc.
--*/
BOOL
PALAPI
VirtualProtect(
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD flNewProtect,
OUT PDWORD lpflOldProtect)
{
BOOL bRetVal = FALSE;
PCMI pEntry = NULL;
SIZE_T MemSize = 0;
UINT_PTR StartBoundary = 0;
SIZE_T Index = 0;
SIZE_T NumberOfPagesToChange = 0;
SIZE_T OffSet = 0;
CPalThread * pthrCurrent;
PERF_ENTRY(VirtualProtect);
ENTRY("VirtualProtect(lpAddress=%p, dwSize=%u, flNewProtect=%#x, "
"flOldProtect=%p)\n",
lpAddress, dwSize, flNewProtect, lpflOldProtect);
pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
MemSize = (((UINT_PTR)(dwSize) + ((UINT_PTR)(lpAddress) & VIRTUAL_PAGE_MASK)
+ VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK);
if ( VIRTUALContainsInvalidProtectionFlags( flNewProtect ) )
{
ASSERT( "flProtect can be one of PAGE_NOACCESS, PAGE_READONLY, "
"PAGE_READWRITE, PAGE_EXECUTE, PAGE_EXECUTE_READ "
", or PAGE_EXECUTE_READWRITE. \n" );
SetLastError( ERROR_INVALID_PARAMETER );
goto ExitVirtualProtect;
}
if ( !lpflOldProtect)
{
ERROR( "lpflOldProtect was invalid.\n" );
SetLastError( ERROR_NOACCESS );
goto ExitVirtualProtect;
}
pEntry = VIRTUALFindRegionInformation( StartBoundary );
if ( NULL != pEntry )
{
/* See if the pages are committed. */
Index = OffSet = StartBoundary - pEntry->startBoundary == 0 ?
0 : ( StartBoundary - pEntry->startBoundary ) / VIRTUAL_PAGE_SIZE;
NumberOfPagesToChange = MemSize / VIRTUAL_PAGE_SIZE;
TRACE( "Number of pages to check %d, starting page %d \n", NumberOfPagesToChange, Index );
for ( ; Index < NumberOfPagesToChange; Index++ )
{
if ( !VIRTUALIsPageCommitted( Index, pEntry ) )
{
ERROR( "You can only change the protection attributes"
" on committed memory.\n" )
SetLastError( ERROR_INVALID_ADDRESS );
goto ExitVirtualProtect;
}
}
}
if ( 0 == mprotect( (LPVOID)StartBoundary, MemSize,
W32toUnixAccessControl( flNewProtect ) ) )
{
/* Reset the access protection. */
TRACE( "Number of pages to change %d, starting page %d \n",
NumberOfPagesToChange, OffSet );
/*
* Set the old protection flags. We only use the first flag, so
* if there were several regions with each with different flags only the
* first region's protection flag will be returned.
*/
if ( pEntry )
{
*lpflOldProtect =
VIRTUALConvertVirtualFlags( pEntry->pProtectionState[ OffSet ] );
memset( pEntry->pProtectionState + OffSet,
VIRTUALConvertWinFlags( flNewProtect ),
NumberOfPagesToChange );
}
else
{
*lpflOldProtect = PAGE_EXECUTE_READWRITE;
}
bRetVal = TRUE;
}
else
{
ERROR( "%s\n", strerror( errno ) );
if ( errno == EINVAL )
{
SetLastError( ERROR_INVALID_ADDRESS );
}
else if ( errno == EACCES )
{
SetLastError( ERROR_INVALID_ACCESS );
}
}
ExitVirtualProtect:
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
#if defined _DEBUG
VIRTUALDisplayList();
#endif
LOGEXIT( "VirtualProtect returning %s.\n", bRetVal == TRUE ? "TRUE" : "FALSE" );
PERF_EXIT(VirtualProtect);
return bRetVal;
}
#if HAVE_VM_ALLOCATE
//---------------------------------------------------------------------------------------
//
// Convert a vm_prot_t flag on the Mach kernel to the corresponding memory protection on Windows.
//
// Arguments:
// protection - Mach protection to be converted
//
// Return Value:
// Return the corresponding memory protection on Windows (e.g. PAGE_READ_WRITE, etc.)
//
static DWORD VirtualMapMachProtectToWinProtect(vm_prot_t protection)
{
if (protection & VM_PROT_READ)
{
if (protection & VM_PROT_WRITE)
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE_READWRITE;
}
else
{
return PAGE_READWRITE;
}
}
else
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE_READ;
}
else
{
return PAGE_READONLY;
}
}
}
else
{
if (protection & VM_PROT_WRITE)
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE_WRITECOPY;
}
else
{
return PAGE_WRITECOPY;
}
}
else
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE;
}
else
{
return PAGE_NOACCESS;
}
}
}
}
static void VM_ALLOCATE_VirtualQuery(LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer)
{
kern_return_t MachRet;
vm_address_t vm_address;
vm_size_t vm_size;
vm_region_flavor_t vm_flavor;
mach_msg_type_number_t infoCnt;
mach_port_t object_name;
#ifdef BIT64
vm_region_basic_info_data_64_t info;
infoCnt = VM_REGION_BASIC_INFO_COUNT_64;
vm_flavor = VM_REGION_BASIC_INFO_64;
#else
vm_region_basic_info_data_t info;
infoCnt = VM_REGION_BASIC_INFO_COUNT;
vm_flavor = VM_REGION_BASIC_INFO;
#endif
vm_address = (vm_address_t)lpAddress;
#ifdef BIT64
MachRet = vm_region_64(
#else
MachRet = vm_region(
#endif
mach_task_self(),
&vm_address,
&vm_size,
vm_flavor,
(vm_region_info_t)&info,
&infoCnt,
&object_name);
if (MachRet != KERN_SUCCESS) {
return;
}
if (vm_address > (vm_address_t)lpAddress) {
/* lpAddress was pointing into a free region */
lpBuffer->State = MEM_FREE;
return;
}
lpBuffer->BaseAddress = (PVOID)vm_address;
// We don't actually have any information on the Mach kernel which maps to AllocationProtect.
lpBuffer->AllocationProtect = VM_PROT_NONE;
lpBuffer->RegionSize = (SIZE_T)vm_size;
if (info.reserved)
{
lpBuffer->State = MEM_RESERVE;
}
else
{
lpBuffer->State = MEM_COMMIT;
}
lpBuffer->Protect = VirtualMapMachProtectToWinProtect(info.protection);
/* Note that if a mapped region and a private region are adjacent, this
will return MEM_PRIVATE but the region size will span
both the mapped and private regions. */
if (!info.shared)
{
lpBuffer->Type = MEM_PRIVATE;
}
else
{
// What should this be? It's either MEM_MAPPED or MEM_IMAGE, but without an image list,
// we can't determine which one it is.
lpBuffer->Type = MEM_MAPPED;
}
}
#endif // HAVE_VM_ALLOCATE
/*++
Function:
VirtualQuery
See MSDN doc.
--*/
SIZE_T
PALAPI
VirtualQuery(
IN LPCVOID lpAddress,
OUT PMEMORY_BASIC_INFORMATION lpBuffer,
IN SIZE_T dwLength)
{
PCMI pEntry = NULL;
UINT_PTR StartBoundary = 0;
CPalThread * pthrCurrent;
PERF_ENTRY(VirtualQuery);
ENTRY("VirtualQuery(lpAddress=%p, lpBuffer=%p, dwLength=%u)\n",
lpAddress, lpBuffer, dwLength);
pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
if ( !lpBuffer)
{
ERROR( "lpBuffer has to be a valid pointer.\n" );
pthrCurrent->SetLastError( ERROR_NOACCESS );
goto ExitVirtualQuery;
}
if ( dwLength < sizeof( *lpBuffer ) )
{
ERROR( "dwLength cannot be smaller then the size of *lpBuffer.\n" );
pthrCurrent->SetLastError( ERROR_BAD_LENGTH );
goto ExitVirtualQuery;
}
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
#if MMAP_IGNORES_HINT
// Make sure we have memory to map before we try to query it.
VIRTUALGetBackingFile(pthrCurrent);
// If we're suballocating, claim that any memory that isn't in our
// suballocated block is already allocated. This keeps callers from
// using these results to try to allocate those blocks and failing.
if (StartBoundary < (UINT_PTR) gBackingBaseAddress ||
StartBoundary >= (UINT_PTR) gBackingBaseAddress + BACKING_FILE_SIZE)
{
if (StartBoundary < (UINT_PTR) gBackingBaseAddress)
{
lpBuffer->RegionSize = (UINT_PTR) gBackingBaseAddress - StartBoundary;
}
else
{
lpBuffer->RegionSize = -StartBoundary;
}
lpBuffer->BaseAddress = (void *) StartBoundary;
lpBuffer->State = MEM_COMMIT;
lpBuffer->Type = MEM_MAPPED;
lpBuffer->AllocationProtect = 0;
lpBuffer->Protect = 0;
goto ExitVirtualQuery;
}
#endif // MMAP_IGNORES_HINT
/* Find the entry. */
pEntry = VIRTUALFindRegionInformation( StartBoundary );
if ( !pEntry )
{
/* Can't find a match, or no list present. */
/* Next, looking for this region in file maps */
if (!MAPGetRegionInfo((LPVOID)StartBoundary, lpBuffer))
{
// When all else fails, call vm_region() if it's available.
// Initialize the State to be MEM_FREE, in which case AllocationBase, AllocationProtect,
// Protect, and Type are all undefined.
lpBuffer->BaseAddress = (LPVOID)StartBoundary;
lpBuffer->RegionSize = 0;
lpBuffer->State = MEM_FREE;
#if HAVE_VM_ALLOCATE
VM_ALLOCATE_VirtualQuery(lpAddress, lpBuffer);
#endif
}
}
else
{
/* Starting page. */
SIZE_T Index = ( StartBoundary - pEntry->startBoundary ) / VIRTUAL_PAGE_SIZE;
/* Attributes to check for. */
BYTE AccessProtection = pEntry->pProtectionState[ Index ];
INT AllocationType = VIRTUALGetAllocationType( Index, pEntry );
SIZE_T RegionSize = 0;
TRACE( "Index = %d, Number of Pages = %d. \n",
Index, pEntry->memSize / VIRTUAL_PAGE_SIZE );
while ( Index < pEntry->memSize / VIRTUAL_PAGE_SIZE &&
VIRTUALGetAllocationType( Index, pEntry ) == AllocationType &&
pEntry->pProtectionState[ Index ] == AccessProtection )
{
RegionSize += VIRTUAL_PAGE_SIZE;
Index++;
}
TRACE( "RegionSize = %d.\n", RegionSize );
/* Fill the structure.*/
lpBuffer->AllocationProtect = pEntry->accessProtection;
lpBuffer->BaseAddress = (LPVOID)StartBoundary;
lpBuffer->Protect = AllocationType == MEM_COMMIT ?
VIRTUALConvertVirtualFlags( AccessProtection ) : 0;
lpBuffer->RegionSize = RegionSize;
lpBuffer->State =
( AllocationType == MEM_COMMIT ? MEM_COMMIT : MEM_RESERVE );
WARN( "Ignoring lpBuffer->Type. \n" );
}
ExitVirtualQuery:
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
LOGEXIT( "VirtualQuery returning %d.\n", sizeof( *lpBuffer ) );
PERF_EXIT(VirtualQuery);
return sizeof( *lpBuffer );
}
/*++
Function:
GetWriteWatch
See MSDN doc.
--*/
UINT
PALAPI
GetWriteWatch(
IN DWORD dwFlags,
IN PVOID lpBaseAddress,
IN SIZE_T dwRegionSize,
OUT PVOID *lpAddresses,
IN OUT PULONG_PTR lpdwCount,
OUT PULONG lpdwGranularity
)
{
// TODO: implement this method
*lpAddresses = NULL;
*lpdwCount = 0;
// Until it is implemented, return non-zero value as an indicator of failure
return 1;
}
/*++
Function:
ResetWriteWatch
See MSDN doc.
--*/
UINT
PALAPI
ResetWriteWatch(
IN LPVOID lpBaseAddress,
IN SIZE_T dwRegionSize
)
{
// TODO: implement this method
// Until it is implemented, return non-zero value as an indicator of failure
return 1;
}
/*++
Function :
ReserveMemoryFromExecutableAllocator
This function is used to reserve a region of virual memory (not commited)
that is located close to the coreclr library. The memory comes from the virtual
address range that is managed by ExecutableMemoryAllocator.
--*/
void* ReserveMemoryFromExecutableAllocator(CPalThread* pThread, SIZE_T allocationSize)
{
InternalEnterCriticalSection(pThread, &virtual_critsec);
void* mem = g_executableMemoryAllocator.AllocateMemory(allocationSize);
InternalLeaveCriticalSection(pThread, &virtual_critsec);
return mem;
}
/*++
Function:
ExecutableMemoryAllocator::Initialize()
This function initializes the allocator. It should be called early during process startup
(when process address space is pretty much empty) in order to have a chance to reserve
sufficient amount of memory that is close to the coreclr library.
--*/
void ExecutableMemoryAllocator::Initialize()
{
m_startAddress = NULL;
m_nextFreeAddress = NULL;
m_totalSizeOfReservedMemory = 0;
m_remainingReservedMemory = 0;
// Enable the executable memory allocator on 64-bit platforms only
// because 32-bit platforms have limited amount of virtual address space.
#ifdef BIT64
TryReserveInitialMemory();
#endif // BIT64
}
/*++
Function:
ExecutableMemoryAllocator::TryReserveInitialMemory()
This function is called during PAL initialization. It opportunistically tries to reserve
a large chunk of virtual memory that can be later used to store JIT'ed code.\
--*/
void ExecutableMemoryAllocator::TryReserveInitialMemory()
{
CPalThread* pthrCurrent = InternalGetCurrentThread();
int32_t sizeOfAllocation = MaxExecutableMemorySize;
int32_t startAddressIncrement;
UINT_PTR startAddress;
UINT_PTR coreclrLoadAddress;
const int32_t MemoryProbingIncrement = 128 * 1024 * 1024;
// Try to find and reserve an available region of virtual memory that is located
// within 2GB range (defined by the MaxExecutableMemorySize constant) from the
// location of the coreclr library.
// Potentially, as a possible future improvement, we can get precise information
// about available memory ranges by parsing data from '/proc/self/maps'.
// But since this code is called early during process startup, the user address space
// is pretty much empty so the simple algorithm that is implemented below is sufficient
// for this purpose.
// First of all, we need to determine the current address of libcoreclr. Please note that depending on
// the OS implementation, the library is usually loaded either at the end or at the start of the user
// address space. If the library is loaded at low addresses then try to reserve memory above libcoreclr
// (thus avoiding reserving memory below 4GB; besides some operating systems do not allow that).
// If libcoreclr is loaded at high addresses then try to reserve memory below its location.
coreclrLoadAddress = (UINT_PTR)PAL_GetSymbolModuleBase((void*)VirtualAlloc);
if ((coreclrLoadAddress < 0xFFFFFFFF) || ((coreclrLoadAddress - MaxExecutableMemorySize) < 0xFFFFFFFF))
{
// Try to allocate above the location of libcoreclr
startAddress = coreclrLoadAddress + CoreClrLibrarySize;
startAddressIncrement = MemoryProbingIncrement;
}
else
{
// Try to allocate below the location of libcoreclr
startAddress = coreclrLoadAddress - MaxExecutableMemorySize;
startAddressIncrement = 0;
}
// Do actual memory reservation.
do
{
m_startAddress = ReserveVirtualMemory(pthrCurrent, (void*)startAddress, sizeOfAllocation);
if (m_startAddress != NULL)
{
// Memory has been successfully reserved.
m_totalSizeOfReservedMemory = sizeOfAllocation;
// Randomize the location at which we start allocating from the reserved memory range.
int32_t randomOffset = GenerateRandomStartOffset();
m_nextFreeAddress = (void*)(((UINT_PTR)m_startAddress) + randomOffset);
m_remainingReservedMemory = sizeOfAllocation - randomOffset;
break;
}
// Try to allocate a smaller region
sizeOfAllocation -= MemoryProbingIncrement;
startAddress += startAddressIncrement;
} while (sizeOfAllocation >= MemoryProbingIncrement);
}
/*++
Function:
ExecutableMemoryAllocator::AllocateMemory
This function attempts to allocate the requested amount of memory from its reserved virtual
address space. The function will return NULL if the allocation request cannot
be satisfied by the memory that is currently available in the allocator.
Note: This function MUST be called with the virtual_critsec lock held.
--*/
void* ExecutableMemoryAllocator::AllocateMemory(SIZE_T allocationSize)
{
void* allocatedMemory = NULL;
// Allocation size must be in multiples of the virtual page size.
_ASSERTE((allocationSize & VIRTUAL_PAGE_MASK) == 0);
// The code below assumes that the caller owns the virtual_critsec lock.
// So the calculations are not done in thread-safe manner.
if ((allocationSize > 0) && (allocationSize <= m_remainingReservedMemory))
{
allocatedMemory = m_nextFreeAddress;
m_nextFreeAddress = (void*)(((UINT_PTR)m_nextFreeAddress) + allocationSize);
m_remainingReservedMemory -= allocationSize;
}
return allocatedMemory;
}
/*++
Function:
ExecutableMemoryAllocator::GenerateRandomStartOffset()
This function returns a random offset (in multiples of the virtual page size)
at which the allocator should start allocating memory from its reserved memory range.
--*/
int32_t ExecutableMemoryAllocator::GenerateRandomStartOffset()
{
int32_t pageCount;
const int32_t MaxStartPageOffset = 64;
// This code is similar to what coreclr runtime does on Windows.
// It generates a random number of pages to skip between 0...MaxStartPageOffset.
srandom(time(NULL));
pageCount = (int32_t)(MaxStartPageOffset * (int64_t)random() / RAND_MAX);
return pageCount * VIRTUAL_PAGE_SIZE;
}
| 62,359 | 20,147 |
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* stepper.cpp - stepper motor driver: executes motion plans using stepper motors
* Marlin Firmware
*
* Derived from Grbl
* Copyright (c) 2009-2011 Simen Svale Skogsrud
*
* Grbl is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Grbl is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Grbl. If not, see <http://www.gnu.org/licenses/>.
*/
/* The timer calculations of this module informed by the 'RepRap cartesian firmware' by Zack Smith
and Philipp Tiefenbacher. */
#include "Marlin.h"
#include "stepper.h"
#include "planner.h"
#include "temperature.h"
#include "ultralcd.h"
#include "language.h"
#include "cardreader.h"
#include "speed_lookuptable.h"
#if HAS_DIGIPOTSS
#include <SPI.h>
#endif
//===========================================================================
//============================= public variables ============================
//===========================================================================
block_t* current_block; // A pointer to the block currently being traced
#if ENABLED(HAS_Z_MIN_PROBE)
volatile bool z_probe_is_active = false;
#endif
//===========================================================================
//============================= private variables ===========================
//===========================================================================
//static makes it impossible to be called from outside of this file by extern.!
// Variables used by The Stepper Driver Interrupt
static unsigned char out_bits = 0; // The next stepping-bits to be output
static unsigned int cleaning_buffer_counter;
#if ENABLED(Z_DUAL_ENDSTOPS)
static bool performing_homing = false,
locked_z_motor = false,
locked_z2_motor = false;
#endif
// Counter variables for the Bresenham line tracer
static long counter_x, counter_y, counter_z, counter_e;
volatile static unsigned long step_events_completed; // The number of step events executed in the current block
#if ENABLED(ADVANCE)
static long advance_rate, advance, final_advance = 0;
static long old_advance = 0;
static long e_steps[4];
#endif
static long acceleration_time, deceleration_time;
//static unsigned long accelerate_until, decelerate_after, acceleration_rate, initial_rate, final_rate, nominal_rate;
static unsigned short acc_step_rate; // needed for deceleration start point
static uint8_t step_loops;
static uint8_t step_loops_nominal;
static unsigned short OCR1A_nominal;
volatile long endstops_trigsteps[3] = { 0 };
volatile long endstops_stepsTotal, endstops_stepsDone;
static volatile char endstop_hit_bits = 0; // use X_MIN, Y_MIN, Z_MIN and Z_MIN_PROBE as BIT value
#if DISABLED(Z_DUAL_ENDSTOPS)
static byte
#else
static uint16_t
#endif
old_endstop_bits = 0; // use X_MIN, X_MAX... Z_MAX, Z_MIN_PROBE, Z2_MIN, Z2_MAX
#if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
bool abort_on_endstop_hit = false;
#endif
#if HAS_MOTOR_CURRENT_PWM
#ifndef PWM_MOTOR_CURRENT
#define PWM_MOTOR_CURRENT DEFAULT_PWM_MOTOR_CURRENT
#endif
const int motor_current_setting[3] = PWM_MOTOR_CURRENT;
#endif
static bool check_endstops = true;
static bool check_endstops_global =
#if ENABLED(ENDSTOPS_ONLY_FOR_HOMING)
false
#else
true
#endif
;
volatile long count_position[NUM_AXIS] = { 0 }; // Positions of stepper motors, in step units
volatile signed char count_direction[NUM_AXIS] = { 1 };
//===========================================================================
//================================ functions ================================
//===========================================================================
#if ENABLED(DUAL_X_CARRIAGE)
#define X_APPLY_DIR(v,ALWAYS) \
if (extruder_duplication_enabled || ALWAYS) { \
X_DIR_WRITE(v); \
X2_DIR_WRITE(v); \
} \
else { \
if (current_block->active_extruder) X2_DIR_WRITE(v); else X_DIR_WRITE(v); \
}
#define X_APPLY_STEP(v,ALWAYS) \
if (extruder_duplication_enabled || ALWAYS) { \
X_STEP_WRITE(v); \
X2_STEP_WRITE(v); \
} \
else { \
if (current_block->active_extruder != 0) X2_STEP_WRITE(v); else X_STEP_WRITE(v); \
}
#else
#define X_APPLY_DIR(v,Q) X_DIR_WRITE(v)
#define X_APPLY_STEP(v,Q) X_STEP_WRITE(v)
#endif
#if ENABLED(Y_DUAL_STEPPER_DRIVERS)
#define Y_APPLY_DIR(v,Q) { Y_DIR_WRITE(v); Y2_DIR_WRITE((v) != INVERT_Y2_VS_Y_DIR); }
#define Y_APPLY_STEP(v,Q) { Y_STEP_WRITE(v); Y2_STEP_WRITE(v); }
#else
#define Y_APPLY_DIR(v,Q) Y_DIR_WRITE(v)
#define Y_APPLY_STEP(v,Q) Y_STEP_WRITE(v)
#endif
#if ENABLED(Z_DUAL_STEPPER_DRIVERS)
#define Z_APPLY_DIR(v,Q) { Z_DIR_WRITE(v); Z2_DIR_WRITE(v); }
#if ENABLED(Z_DUAL_ENDSTOPS)
#define Z_APPLY_STEP(v,Q) \
if (performing_homing) { \
if (Z_HOME_DIR > 0) {\
if (!(TEST(old_endstop_bits, Z_MAX) && (count_direction[Z_AXIS] > 0)) && !locked_z_motor) Z_STEP_WRITE(v); \
if (!(TEST(old_endstop_bits, Z2_MAX) && (count_direction[Z_AXIS] > 0)) && !locked_z2_motor) Z2_STEP_WRITE(v); \
} \
else { \
if (!(TEST(old_endstop_bits, Z_MIN) && (count_direction[Z_AXIS] < 0)) && !locked_z_motor) Z_STEP_WRITE(v); \
if (!(TEST(old_endstop_bits, Z2_MIN) && (count_direction[Z_AXIS] < 0)) && !locked_z2_motor) Z2_STEP_WRITE(v); \
} \
} \
else { \
Z_STEP_WRITE(v); \
Z2_STEP_WRITE(v); \
}
#else
#define Z_APPLY_STEP(v,Q) { Z_STEP_WRITE(v); Z2_STEP_WRITE(v); }
#endif
#else
#define Z_APPLY_DIR(v,Q) Z_DIR_WRITE(v)
#define Z_APPLY_STEP(v,Q) Z_STEP_WRITE(v)
#endif
#define E_APPLY_STEP(v,Q) E_STEP_WRITE(v)
// intRes = intIn1 * intIn2 >> 16
// uses:
// r26 to store 0
// r27 to store the byte 1 of the 24 bit result
#define MultiU16X8toH16(intRes, charIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %B2 \n\t" \
"movw %A0, r0 \n\t" \
"mul %A1, %A2 \n\t" \
"add %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"lsr r0 \n\t" \
"adc %A0, r26 \n\t" \
"adc %B0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&r" (intRes) \
: \
"d" (charIn1), \
"d" (intIn2) \
: \
"r26" \
)
// intRes = longIn1 * longIn2 >> 24
// uses:
// r26 to store 0
// r27 to store bits 16-23 of the 48bit result. The top bit is used to round the two byte result.
// note that the lower two bytes and the upper byte of the 48bit result are not calculated.
// this can cause the result to be out by one as the lower bytes may cause carries into the upper ones.
// B0 A0 are bits 24-39 and are the returned value
// C1 B1 A1 is longIn1
// D2 C2 B2 A2 is longIn2
//
#define MultiU24X32toH16(intRes, longIn1, longIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %B2 \n\t" \
"mov r27, r1 \n\t" \
"mul %B1, %C2 \n\t" \
"movw %A0, r0 \n\t" \
"mul %C1, %C2 \n\t" \
"add %B0, r0 \n\t" \
"mul %C1, %B2 \n\t" \
"add %A0, r0 \n\t" \
"adc %B0, r1 \n\t" \
"mul %A1, %C2 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mul %B1, %B2 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mul %C1, %A2 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mul %B1, %A2 \n\t" \
"add r27, r1 \n\t" \
"adc %A0, r26 \n\t" \
"adc %B0, r26 \n\t" \
"lsr r27 \n\t" \
"adc %A0, r26 \n\t" \
"adc %B0, r26 \n\t" \
"mul %D2, %A1 \n\t" \
"add %A0, r0 \n\t" \
"adc %B0, r1 \n\t" \
"mul %D2, %B1 \n\t" \
"add %B0, r0 \n\t" \
"clr r1 \n\t" \
: \
"=&r" (intRes) \
: \
"d" (longIn1), \
"d" (longIn2) \
: \
"r26" , "r27" \
)
// Some useful constants
#define ENABLE_STEPPER_DRIVER_INTERRUPT() SBI(TIMSK1, OCIE1A)
#define DISABLE_STEPPER_DRIVER_INTERRUPT() CBI(TIMSK1, OCIE1A)
void enable_endstops(bool check) { check_endstops = check; }
void enable_endstops_globally(bool check) { check_endstops_global = check_endstops = check; }
void endstops_not_homing() { check_endstops = check_endstops_global; }
void endstops_hit_on_purpose() { endstop_hit_bits = 0; }
void checkHitEndstops() {
if (endstop_hit_bits) {
#if ENABLED(ULTRA_LCD)
char chrX = ' ', chrY = ' ', chrZ = ' ', chrP = ' ';
#define _SET_STOP_CHAR(A,C) (chr## A = C)
#else
#define _SET_STOP_CHAR(A,C) ;
#endif
#define _ENDSTOP_HIT_ECHO(A,C) do{ \
SERIAL_ECHOPAIR(" " STRINGIFY(A) ":", endstops_trigsteps[A ##_AXIS] / axis_steps_per_unit[A ##_AXIS]); \
_SET_STOP_CHAR(A,C); }while(0)
#define _ENDSTOP_HIT_TEST(A,C) \
if (TEST(endstop_hit_bits, A ##_MIN) || TEST(endstop_hit_bits, A ##_MAX)) \
_ENDSTOP_HIT_ECHO(A,C)
SERIAL_ECHO_START;
SERIAL_ECHOPGM(MSG_ENDSTOPS_HIT);
_ENDSTOP_HIT_TEST(X, 'X');
_ENDSTOP_HIT_TEST(Y, 'Y');
_ENDSTOP_HIT_TEST(Z, 'Z');
#if ENABLED(Z_MIN_PROBE_ENDSTOP)
#define P_AXIS Z_AXIS
if (TEST(endstop_hit_bits, Z_MIN_PROBE)) _ENDSTOP_HIT_ECHO(P, 'P');
#endif
SERIAL_EOL;
#if ENABLED(ULTRA_LCD)
char msg[3 * strlen(MSG_LCD_ENDSTOPS) + 8 + 1]; // Room for a UTF 8 string
sprintf_P(msg, PSTR(MSG_LCD_ENDSTOPS " %c %c %c %c"), chrX, chrY, chrZ, chrP);
lcd_setstatus(msg);
#endif
endstops_hit_on_purpose();
#if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) && ENABLED(SDSUPPORT)
if (abort_on_endstop_hit) {
card.sdprinting = false;
card.closefile();
quickStop();
disable_all_heaters(); // switch off all heaters.
}
#endif
}
}
// Check endstops - Called from ISR!
inline void update_endstops() {
#if ENABLED(Z_DUAL_ENDSTOPS)
uint16_t
#else
byte
#endif
current_endstop_bits = 0;
#define _ENDSTOP_PIN(AXIS, MINMAX) AXIS ##_## MINMAX ##_PIN
#define _ENDSTOP_INVERTING(AXIS, MINMAX) AXIS ##_## MINMAX ##_ENDSTOP_INVERTING
#define _AXIS(AXIS) AXIS ##_AXIS
#define _ENDSTOP_HIT(AXIS) SBI(endstop_hit_bits, _ENDSTOP(AXIS, MIN))
#define _ENDSTOP(AXIS, MINMAX) AXIS ##_## MINMAX
// SET_ENDSTOP_BIT: set the current endstop bits for an endstop to its status
#define SET_ENDSTOP_BIT(AXIS, MINMAX) SET_BIT(current_endstop_bits, _ENDSTOP(AXIS, MINMAX), (READ(_ENDSTOP_PIN(AXIS, MINMAX)) != _ENDSTOP_INVERTING(AXIS, MINMAX)))
// COPY_BIT: copy the value of COPY_BIT to BIT in bits
#define COPY_BIT(bits, COPY_BIT, BIT) SET_BIT(bits, BIT, TEST(bits, COPY_BIT))
// TEST_ENDSTOP: test the old and the current status of an endstop
#define TEST_ENDSTOP(ENDSTOP) (TEST(current_endstop_bits, ENDSTOP) && TEST(old_endstop_bits, ENDSTOP))
#if ENABLED(COREXY) || ENABLED(COREXZ)
#define _SET_TRIGSTEPS(AXIS) do { \
float axis_pos = count_position[_AXIS(AXIS)]; \
if (_AXIS(AXIS) == A_AXIS) \
axis_pos = (axis_pos + count_position[CORE_AXIS_2]) / 2; \
else if (_AXIS(AXIS) == CORE_AXIS_2) \
axis_pos = (count_position[A_AXIS] - axis_pos) / 2; \
endstops_trigsteps[_AXIS(AXIS)] = axis_pos; \
} while(0)
#else
#define _SET_TRIGSTEPS(AXIS) endstops_trigsteps[_AXIS(AXIS)] = count_position[_AXIS(AXIS)]
#endif // COREXY || COREXZ
#define UPDATE_ENDSTOP(AXIS,MINMAX) do { \
SET_ENDSTOP_BIT(AXIS, MINMAX); \
if (TEST_ENDSTOP(_ENDSTOP(AXIS, MINMAX)) && current_block->steps[_AXIS(AXIS)] > 0) { \
_SET_TRIGSTEPS(AXIS); \
_ENDSTOP_HIT(AXIS); \
step_events_completed = current_block->step_event_count; \
} \
} while(0)
#if ENABLED(COREXY) || ENABLED(COREXZ)
// Head direction in -X axis for CoreXY and CoreXZ bots.
// If Delta1 == -Delta2, the movement is only in Y or Z axis
if ((current_block->steps[A_AXIS] != current_block->steps[CORE_AXIS_2]) || (TEST(out_bits, A_AXIS) == TEST(out_bits, CORE_AXIS_2))) {
if (TEST(out_bits, X_HEAD))
#else
if (TEST(out_bits, X_AXIS)) // stepping along -X axis (regular Cartesian bot)
#endif
{ // -direction
#if ENABLED(DUAL_X_CARRIAGE)
// with 2 x-carriages, endstops are only checked in the homing direction for the active extruder
if ((current_block->active_extruder == 0 && X_HOME_DIR == -1) || (current_block->active_extruder != 0 && X2_HOME_DIR == -1))
#endif
{
#if HAS_X_MIN
UPDATE_ENDSTOP(X, MIN);
#endif
}
}
else { // +direction
#if ENABLED(DUAL_X_CARRIAGE)
// with 2 x-carriages, endstops are only checked in the homing direction for the active extruder
if ((current_block->active_extruder == 0 && X_HOME_DIR == 1) || (current_block->active_extruder != 0 && X2_HOME_DIR == 1))
#endif
{
#if HAS_X_MAX
UPDATE_ENDSTOP(X, MAX);
#endif
}
}
#if ENABLED(COREXY) || ENABLED(COREXZ)
}
#endif
#if ENABLED(COREXY)
// Head direction in -Y axis for CoreXY bots.
// If DeltaX == DeltaY, the movement is only in X axis
if ((current_block->steps[A_AXIS] != current_block->steps[B_AXIS]) || (TEST(out_bits, A_AXIS) != TEST(out_bits, B_AXIS))) {
if (TEST(out_bits, Y_HEAD))
#else
if (TEST(out_bits, Y_AXIS)) // -direction
#endif
{ // -direction
#if HAS_Y_MIN
UPDATE_ENDSTOP(Y, MIN);
#endif
}
else { // +direction
#if HAS_Y_MAX
UPDATE_ENDSTOP(Y, MAX);
#endif
}
#if ENABLED(COREXY)
}
#endif
#if ENABLED(COREXZ)
// Head direction in -Z axis for CoreXZ bots.
// If DeltaX == DeltaZ, the movement is only in X axis
if ((current_block->steps[A_AXIS] != current_block->steps[C_AXIS]) || (TEST(out_bits, A_AXIS) != TEST(out_bits, C_AXIS))) {
if (TEST(out_bits, Z_HEAD))
#else
if (TEST(out_bits, Z_AXIS))
#endif
{ // z -direction
#if HAS_Z_MIN
#if ENABLED(Z_DUAL_ENDSTOPS)
SET_ENDSTOP_BIT(Z, MIN);
#if HAS_Z2_MIN
SET_ENDSTOP_BIT(Z2, MIN);
#else
COPY_BIT(current_endstop_bits, Z_MIN, Z2_MIN);
#endif
byte z_test = TEST_ENDSTOP(Z_MIN) | (TEST_ENDSTOP(Z2_MIN) << 1); // bit 0 for Z, bit 1 for Z2
if (z_test && current_block->steps[Z_AXIS] > 0) { // z_test = Z_MIN || Z2_MIN
endstops_trigsteps[Z_AXIS] = count_position[Z_AXIS];
SBI(endstop_hit_bits, Z_MIN);
if (!performing_homing || (z_test == 0x3)) //if not performing home or if both endstops were trigged during homing...
step_events_completed = current_block->step_event_count;
}
#else // !Z_DUAL_ENDSTOPS
#if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) && ENABLED(HAS_Z_MIN_PROBE)
if (z_probe_is_active) UPDATE_ENDSTOP(Z, MIN);
#else
UPDATE_ENDSTOP(Z, MIN);
#endif
#endif // !Z_DUAL_ENDSTOPS
#endif
#if ENABLED(Z_MIN_PROBE_ENDSTOP) && DISABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) && ENABLED(HAS_Z_MIN_PROBE)
if (z_probe_is_active) {
UPDATE_ENDSTOP(Z, MIN_PROBE);
if (TEST_ENDSTOP(Z_MIN_PROBE)) SBI(endstop_hit_bits, Z_MIN_PROBE);
}
#endif
}
else { // z +direction
#if HAS_Z_MAX
#if ENABLED(Z_DUAL_ENDSTOPS)
SET_ENDSTOP_BIT(Z, MAX);
#if HAS_Z2_MAX
SET_ENDSTOP_BIT(Z2, MAX);
#else
COPY_BIT(current_endstop_bits, Z_MAX, Z2_MAX);
#endif
byte z_test = TEST_ENDSTOP(Z_MAX) | (TEST_ENDSTOP(Z2_MAX) << 1); // bit 0 for Z, bit 1 for Z2
if (z_test && current_block->steps[Z_AXIS] > 0) { // t_test = Z_MAX || Z2_MAX
endstops_trigsteps[Z_AXIS] = count_position[Z_AXIS];
SBI(endstop_hit_bits, Z_MIN);
if (!performing_homing || (z_test == 0x3)) //if not performing home or if both endstops were trigged during homing...
step_events_completed = current_block->step_event_count;
}
#else // !Z_DUAL_ENDSTOPS
UPDATE_ENDSTOP(Z, MAX);
#endif // !Z_DUAL_ENDSTOPS
#endif // Z_MAX_PIN
}
#if ENABLED(COREXZ)
}
#endif
old_endstop_bits = current_endstop_bits;
}
// __________________________
// /| |\ _________________ ^
// / | | \ /| |\ |
// / | | \ / | | \ s
// / | | | | | \ p
// / | | | | | \ e
// +-----+------------------------+---+--+---------------+----+ e
// | BLOCK 1 | BLOCK 2 | d
//
// time ----->
//
// The trapezoid is the shape the speed curve over time. It starts at block->initial_rate, accelerates
// first block->accelerate_until step_events_completed, then keeps going at constant speed until
// step_events_completed reaches block->decelerate_after after which it decelerates until the trapezoid generator is reset.
// The slope of acceleration is calculated using v = u + at where t is the accumulated timer values of the steps so far.
void st_wake_up() {
// TCNT1 = 0;
ENABLE_STEPPER_DRIVER_INTERRUPT();
}
FORCE_INLINE unsigned short calc_timer(unsigned short step_rate) {
unsigned short timer;
NOMORE(step_rate, MAX_STEP_FREQUENCY);
if (step_rate > 20000) { // If steprate > 20kHz >> step 4 times
step_rate = (step_rate >> 2) & 0x3fff;
step_loops = 4;
}
else if (step_rate > 10000) { // If steprate > 10kHz >> step 2 times
step_rate = (step_rate >> 1) & 0x7fff;
step_loops = 2;
}
else {
step_loops = 1;
}
NOLESS(step_rate, F_CPU / 500000);
step_rate -= F_CPU / 500000; // Correct for minimal speed
if (step_rate >= (8 * 256)) { // higher step rate
unsigned short table_address = (unsigned short)&speed_lookuptable_fast[(unsigned char)(step_rate >> 8)][0];
unsigned char tmp_step_rate = (step_rate & 0x00ff);
unsigned short gain = (unsigned short)pgm_read_word_near(table_address + 2);
MultiU16X8toH16(timer, tmp_step_rate, gain);
timer = (unsigned short)pgm_read_word_near(table_address) - timer;
}
else { // lower step rates
unsigned short table_address = (unsigned short)&speed_lookuptable_slow[0][0];
table_address += ((step_rate) >> 1) & 0xfffc;
timer = (unsigned short)pgm_read_word_near(table_address);
timer -= (((unsigned short)pgm_read_word_near(table_address + 2) * (unsigned char)(step_rate & 0x0007)) >> 3);
}
if (timer < 100) { timer = 100; MYSERIAL.print(MSG_STEPPER_TOO_HIGH); MYSERIAL.println(step_rate); }//(20kHz this should never happen)
return timer;
}
/**
* Set the stepper direction of each axis
*
* X_AXIS=A_AXIS and Y_AXIS=B_AXIS for COREXY
* X_AXIS=A_AXIS and Z_AXIS=C_AXIS for COREXZ
*/
void set_stepper_direction() {
#define SET_STEP_DIR(AXIS) \
if (TEST(out_bits, AXIS ##_AXIS)) { \
AXIS ##_APPLY_DIR(INVERT_## AXIS ##_DIR, false); \
count_direction[AXIS ##_AXIS] = -1; \
} \
else { \
AXIS ##_APPLY_DIR(!INVERT_## AXIS ##_DIR, false); \
count_direction[AXIS ##_AXIS] = 1; \
}
SET_STEP_DIR(X); // A
SET_STEP_DIR(Y); // B
SET_STEP_DIR(Z); // C
#if DISABLED(ADVANCE)
if (TEST(out_bits, E_AXIS)) {
REV_E_DIR();
count_direction[E_AXIS] = -1;
}
else {
NORM_E_DIR();
count_direction[E_AXIS] = 1;
}
#endif //!ADVANCE
}
// Initializes the trapezoid generator from the current block. Called whenever a new
// block begins.
FORCE_INLINE void trapezoid_generator_reset() {
static int8_t last_extruder = -1;
if (current_block->direction_bits != out_bits || current_block->active_extruder != last_extruder) {
out_bits = current_block->direction_bits;
last_extruder = current_block->active_extruder;
set_stepper_direction();
}
#if ENABLED(ADVANCE)
advance = current_block->initial_advance;
final_advance = current_block->final_advance;
// Do E steps + advance steps
e_steps[current_block->active_extruder] += ((advance >>8) - old_advance);
old_advance = advance >>8;
#endif
deceleration_time = 0;
// step_rate to timer interval
OCR1A_nominal = calc_timer(current_block->nominal_rate);
// make a note of the number of step loops required at nominal speed
step_loops_nominal = step_loops;
acc_step_rate = current_block->initial_rate;
acceleration_time = calc_timer(acc_step_rate);
OCR1A = acceleration_time;
// SERIAL_ECHO_START;
// SERIAL_ECHOPGM("advance :");
// SERIAL_ECHO(current_block->advance/256.0);
// SERIAL_ECHOPGM("advance rate :");
// SERIAL_ECHO(current_block->advance_rate/256.0);
// SERIAL_ECHOPGM("initial advance :");
// SERIAL_ECHO(current_block->initial_advance/256.0);
// SERIAL_ECHOPGM("final advance :");
// SERIAL_ECHOLN(current_block->final_advance/256.0);
}
// "The Stepper Driver Interrupt" - This timer interrupt is the workhorse.
// It pops blocks from the block_buffer and executes them by pulsing the stepper pins appropriately.
ISR(TIMER1_COMPA_vect) {
if (cleaning_buffer_counter) {
current_block = NULL;
plan_discard_current_block();
#ifdef SD_FINISHED_RELEASECOMMAND
if ((cleaning_buffer_counter == 1) && (SD_FINISHED_STEPPERRELEASE)) enqueue_and_echo_commands_P(PSTR(SD_FINISHED_RELEASECOMMAND));
#endif
cleaning_buffer_counter--;
OCR1A = 200;
return;
}
// If there is no current block, attempt to pop one from the buffer
if (!current_block) {
// Anything in the buffer?
current_block = plan_get_current_block();
if (current_block) {
current_block->busy = true;
trapezoid_generator_reset();
counter_x = -(current_block->step_event_count >> 1);
counter_y = counter_z = counter_e = counter_x;
step_events_completed = 0;
#if ENABLED(Z_LATE_ENABLE)
if (current_block->steps[Z_AXIS] > 0) {
enable_z();
OCR1A = 2000; //1ms wait
return;
}
#endif
// #if ENABLED(ADVANCE)
// e_steps[current_block->active_extruder] = 0;
// #endif
}
else {
OCR1A = 2000; // 1kHz.
}
}
if (current_block != NULL) {
// Update endstops state, if enabled
#if ENABLED(HAS_Z_MIN_PROBE)
if (check_endstops || z_probe_is_active) update_endstops();
#else
if (check_endstops) update_endstops();
#endif
// Take multiple steps per interrupt (For high speed moves)
for (int8_t i = 0; i < step_loops; i++) {
#ifndef USBCON
customizedSerial.checkRx(); // Check for serial chars.
#endif
#if ENABLED(ADVANCE)
counter_e += current_block->steps[E_AXIS];
if (counter_e > 0) {
counter_e -= current_block->step_event_count;
e_steps[current_block->active_extruder] += TEST(out_bits, E_AXIS) ? -1 : 1;
}
#endif //ADVANCE
#define _COUNTER(axis) counter_## axis
#define _APPLY_STEP(AXIS) AXIS ##_APPLY_STEP
#define _INVERT_STEP_PIN(AXIS) INVERT_## AXIS ##_STEP_PIN
#define STEP_ADD(axis, AXIS) \
_COUNTER(axis) += current_block->steps[_AXIS(AXIS)]; \
if (_COUNTER(axis) > 0) { _APPLY_STEP(AXIS)(!_INVERT_STEP_PIN(AXIS),0); }
STEP_ADD(x,X);
STEP_ADD(y,Y);
STEP_ADD(z,Z);
#if DISABLED(ADVANCE)
STEP_ADD(e,E);
#endif
#define STEP_IF_COUNTER(axis, AXIS) \
if (_COUNTER(axis) > 0) { \
_COUNTER(axis) -= current_block->step_event_count; \
count_position[_AXIS(AXIS)] += count_direction[_AXIS(AXIS)]; \
_APPLY_STEP(AXIS)(_INVERT_STEP_PIN(AXIS),0); \
}
STEP_IF_COUNTER(x, X);
STEP_IF_COUNTER(y, Y);
STEP_IF_COUNTER(z, Z);
#if DISABLED(ADVANCE)
STEP_IF_COUNTER(e, E);
#endif
step_events_completed++;
if (step_events_completed >= current_block->step_event_count) break;
}
// Calculate new timer value
unsigned short timer;
unsigned short step_rate;
if (step_events_completed <= (unsigned long)current_block->accelerate_until) {
MultiU24X32toH16(acc_step_rate, acceleration_time, current_block->acceleration_rate);
acc_step_rate += current_block->initial_rate;
// upper limit
NOMORE(acc_step_rate, current_block->nominal_rate);
// step_rate to timer interval
timer = calc_timer(acc_step_rate);
OCR1A = timer;
acceleration_time += timer;
#if ENABLED(ADVANCE)
advance += advance_rate * step_loops;
//NOLESS(advance, current_block->advance);
// Do E steps + advance steps
e_steps[current_block->active_extruder] += ((advance >> 8) - old_advance);
old_advance = advance >> 8;
#endif //ADVANCE
}
else if (step_events_completed > (unsigned long)current_block->decelerate_after) {
MultiU24X32toH16(step_rate, deceleration_time, current_block->acceleration_rate);
if (step_rate <= acc_step_rate) { // Still decelerating?
step_rate = acc_step_rate - step_rate;
NOLESS(step_rate, current_block->final_rate);
}
else
step_rate = current_block->final_rate;
// step_rate to timer interval
timer = calc_timer(step_rate);
OCR1A = timer;
deceleration_time += timer;
#if ENABLED(ADVANCE)
advance -= advance_rate * step_loops;
NOLESS(advance, final_advance);
// Do E steps + advance steps
uint32_t advance_whole = advance >> 8;
e_steps[current_block->active_extruder] += advance_whole - old_advance;
old_advance = advance_whole;
#endif //ADVANCE
}
else {
OCR1A = OCR1A_nominal;
// ensure we're running at the correct step rate, even if we just came off an acceleration
step_loops = step_loops_nominal;
}
OCR1A = (OCR1A < (TCNT1 + 16)) ? (TCNT1 + 16) : OCR1A;
// If current block is finished, reset pointer
if (step_events_completed >= current_block->step_event_count) {
current_block = NULL;
plan_discard_current_block();
}
}
}
#if ENABLED(ADVANCE)
unsigned char old_OCR0A;
// Timer interrupt for E. e_steps is set in the main routine;
// Timer 0 is shared with millies
ISR(TIMER0_COMPA_vect) {
old_OCR0A += 52; // ~10kHz interrupt (250000 / 26 = 9615kHz)
OCR0A = old_OCR0A;
#define STEP_E_ONCE(INDEX) \
if (e_steps[INDEX] != 0) { \
E## INDEX ##_STEP_WRITE(INVERT_E_STEP_PIN); \
if (e_steps[INDEX] < 0) { \
E## INDEX ##_DIR_WRITE(INVERT_E## INDEX ##_DIR); \
e_steps[INDEX]++; \
} \
else if (e_steps[INDEX] > 0) { \
E## INDEX ##_DIR_WRITE(!INVERT_E## INDEX ##_DIR); \
e_steps[INDEX]--; \
} \
E## INDEX ##_STEP_WRITE(!INVERT_E_STEP_PIN); \
}
// Step all E steppers that have steps, up to 4 steps per interrupt
for (unsigned char i = 0; i < 4; i++) {
STEP_E_ONCE(0);
#if EXTRUDERS > 1
STEP_E_ONCE(1);
#if EXTRUDERS > 2
STEP_E_ONCE(2);
#if EXTRUDERS > 3
STEP_E_ONCE(3);
#endif
#endif
#endif
}
}
#endif // ADVANCE
void st_init() {
digipot_init(); //Initialize Digipot Motor Current
microstep_init(); //Initialize Microstepping Pins
// initialise TMC Steppers
#if ENABLED(HAVE_TMCDRIVER)
tmc_init();
#endif
// initialise L6470 Steppers
#if ENABLED(HAVE_L6470DRIVER)
L6470_init();
#endif
// Initialize Dir Pins
#if HAS_X_DIR
X_DIR_INIT;
#endif
#if HAS_X2_DIR
X2_DIR_INIT;
#endif
#if HAS_Y_DIR
Y_DIR_INIT;
#if ENABLED(Y_DUAL_STEPPER_DRIVERS) && HAS_Y2_DIR
Y2_DIR_INIT;
#endif
#endif
#if HAS_Z_DIR
Z_DIR_INIT;
#if ENABLED(Z_DUAL_STEPPER_DRIVERS) && HAS_Z2_DIR
Z2_DIR_INIT;
#endif
#endif
#if HAS_E0_DIR
E0_DIR_INIT;
#endif
#if HAS_E1_DIR
E1_DIR_INIT;
#endif
#if HAS_E2_DIR
E2_DIR_INIT;
#endif
#if HAS_E3_DIR
E3_DIR_INIT;
#endif
//Initialize Enable Pins - steppers default to disabled.
#if HAS_X_ENABLE
X_ENABLE_INIT;
if (!X_ENABLE_ON) X_ENABLE_WRITE(HIGH);
#endif
#if HAS_X2_ENABLE
X2_ENABLE_INIT;
if (!X_ENABLE_ON) X2_ENABLE_WRITE(HIGH);
#endif
#if HAS_Y_ENABLE
Y_ENABLE_INIT;
if (!Y_ENABLE_ON) Y_ENABLE_WRITE(HIGH);
#if ENABLED(Y_DUAL_STEPPER_DRIVERS) && HAS_Y2_ENABLE
Y2_ENABLE_INIT;
if (!Y_ENABLE_ON) Y2_ENABLE_WRITE(HIGH);
#endif
#endif
#if HAS_Z_ENABLE
Z_ENABLE_INIT;
if (!Z_ENABLE_ON) Z_ENABLE_WRITE(HIGH);
#if ENABLED(Z_DUAL_STEPPER_DRIVERS) && HAS_Z2_ENABLE
Z2_ENABLE_INIT;
if (!Z_ENABLE_ON) Z2_ENABLE_WRITE(HIGH);
#endif
#endif
#if HAS_E0_ENABLE
E0_ENABLE_INIT;
if (!E_ENABLE_ON) E0_ENABLE_WRITE(HIGH);
#endif
#if HAS_E1_ENABLE
E1_ENABLE_INIT;
if (!E_ENABLE_ON) E1_ENABLE_WRITE(HIGH);
#endif
#if HAS_E2_ENABLE
E2_ENABLE_INIT;
if (!E_ENABLE_ON) E2_ENABLE_WRITE(HIGH);
#endif
#if HAS_E3_ENABLE
E3_ENABLE_INIT;
if (!E_ENABLE_ON) E3_ENABLE_WRITE(HIGH);
#endif
//endstops and pullups
#if HAS_X_MIN
SET_INPUT(X_MIN_PIN);
#if ENABLED(ENDSTOPPULLUP_XMIN)
WRITE(X_MIN_PIN,HIGH);
#endif
#endif
#if HAS_Y_MIN
SET_INPUT(Y_MIN_PIN);
#if ENABLED(ENDSTOPPULLUP_YMIN)
WRITE(Y_MIN_PIN,HIGH);
#endif
#endif
#if HAS_Z_MIN
SET_INPUT(Z_MIN_PIN);
#if ENABLED(ENDSTOPPULLUP_ZMIN)
WRITE(Z_MIN_PIN,HIGH);
#endif
#endif
#if HAS_Z2_MIN
SET_INPUT(Z2_MIN_PIN);
#if ENABLED(ENDSTOPPULLUP_ZMIN)
WRITE(Z2_MIN_PIN,HIGH);
#endif
#endif
#if HAS_X_MAX
SET_INPUT(X_MAX_PIN);
#if ENABLED(ENDSTOPPULLUP_XMAX)
WRITE(X_MAX_PIN,HIGH);
#endif
#endif
#if HAS_Y_MAX
SET_INPUT(Y_MAX_PIN);
#if ENABLED(ENDSTOPPULLUP_YMAX)
WRITE(Y_MAX_PIN,HIGH);
#endif
#endif
#if HAS_Z_MAX
SET_INPUT(Z_MAX_PIN);
#if ENABLED(ENDSTOPPULLUP_ZMAX)
WRITE(Z_MAX_PIN,HIGH);
#endif
#endif
#if HAS_Z2_MAX
SET_INPUT(Z2_MAX_PIN);
#if ENABLED(ENDSTOPPULLUP_ZMAX)
WRITE(Z2_MAX_PIN,HIGH);
#endif
#endif
#if HAS_Z_PROBE && ENABLED(Z_MIN_PROBE_ENDSTOP) // Check for Z_MIN_PROBE_ENDSTOP so we don't pull a pin high unless it's to be used.
SET_INPUT(Z_MIN_PROBE_PIN);
#if ENABLED(ENDSTOPPULLUP_ZMIN_PROBE)
WRITE(Z_MIN_PROBE_PIN,HIGH);
#endif
#endif
#define _STEP_INIT(AXIS) AXIS ##_STEP_INIT
#define _WRITE_STEP(AXIS, HIGHLOW) AXIS ##_STEP_WRITE(HIGHLOW)
#define _DISABLE(axis) disable_## axis()
#define AXIS_INIT(axis, AXIS, PIN) \
_STEP_INIT(AXIS); \
_WRITE_STEP(AXIS, _INVERT_STEP_PIN(PIN)); \
_DISABLE(axis)
#define E_AXIS_INIT(NUM) AXIS_INIT(e## NUM, E## NUM, E)
// Initialize Step Pins
#if HAS_X_STEP
AXIS_INIT(x, X, X);
#endif
#if HAS_X2_STEP
AXIS_INIT(x, X2, X);
#endif
#if HAS_Y_STEP
#if ENABLED(Y_DUAL_STEPPER_DRIVERS) && HAS_Y2_STEP
Y2_STEP_INIT;
Y2_STEP_WRITE(INVERT_Y_STEP_PIN);
#endif
AXIS_INIT(y, Y, Y);
#endif
#if HAS_Z_STEP
#if ENABLED(Z_DUAL_STEPPER_DRIVERS) && HAS_Z2_STEP
Z2_STEP_INIT;
Z2_STEP_WRITE(INVERT_Z_STEP_PIN);
#endif
AXIS_INIT(z, Z, Z);
#endif
#if HAS_E0_STEP
E_AXIS_INIT(0);
#endif
#if HAS_E1_STEP
E_AXIS_INIT(1);
#endif
#if HAS_E2_STEP
E_AXIS_INIT(2);
#endif
#if HAS_E3_STEP
E_AXIS_INIT(3);
#endif
// waveform generation = 0100 = CTC
CBI(TCCR1B, WGM13);
SBI(TCCR1B, WGM12);
CBI(TCCR1A, WGM11);
CBI(TCCR1A, WGM10);
// output mode = 00 (disconnected)
TCCR1A &= ~(3 << COM1A0);
TCCR1A &= ~(3 << COM1B0);
// Set the timer pre-scaler
// Generally we use a divider of 8, resulting in a 2MHz timer
// frequency on a 16MHz MCU. If you are going to change this, be
// sure to regenerate speed_lookuptable.h with
// create_speed_lookuptable.py
TCCR1B = (TCCR1B & ~(0x07 << CS10)) | (2 << CS10);
OCR1A = 0x4000;
TCNT1 = 0;
ENABLE_STEPPER_DRIVER_INTERRUPT();
#if ENABLED(ADVANCE)
#if defined(TCCR0A) && defined(WGM01)
CBI(TCCR0A, WGM01);
CBI(TCCR0A, WGM00);
#endif
e_steps[0] = e_steps[1] = e_steps[2] = e_steps[3] = 0;
SBI(TIMSK0, OCIE0A);
#endif //ADVANCE
enable_endstops(true); // Start with endstops active. After homing they can be disabled
sei();
set_stepper_direction(); // Init directions to out_bits = 0
}
/**
* Block until all buffered steps are executed
*/
void st_synchronize() { while (blocks_queued()) idle(); }
/**
* Set the stepper positions directly in steps
*
* The input is based on the typical per-axis XYZ steps.
* For CORE machines XYZ needs to be translated to ABC.
*
* This allows st_get_axis_position_mm to correctly
* derive the current XYZ position later on.
*/
void st_set_position(const long& x, const long& y, const long& z, const long& e) {
CRITICAL_SECTION_START;
#if ENABLED(COREXY)
// corexy positioning
// these equations follow the form of the dA and dB equations on http://www.corexy.com/theory.html
count_position[A_AXIS] = x + y;
count_position[B_AXIS] = x - y;
count_position[Z_AXIS] = z;
#elif ENABLED(COREXZ)
// corexz planning
count_position[A_AXIS] = x + z;
count_position[Y_AXIS] = y;
count_position[C_AXIS] = x - z;
#else
// default non-h-bot planning
count_position[X_AXIS] = x;
count_position[Y_AXIS] = y;
count_position[Z_AXIS] = z;
#endif
count_position[E_AXIS] = e;
CRITICAL_SECTION_END;
}
void st_set_e_position(const long& e) {
CRITICAL_SECTION_START;
count_position[E_AXIS] = e;
CRITICAL_SECTION_END;
}
/**
* Get a stepper's position in steps.
*/
long st_get_position(AxisEnum axis) {
CRITICAL_SECTION_START;
long count_pos = count_position[axis];
CRITICAL_SECTION_END;
return count_pos;
}
/**
* Get an axis position according to stepper position(s)
* For CORE machines apply translation from ABC to XYZ.
*/
float st_get_axis_position_mm(AxisEnum axis) {
float axis_steps;
#if ENABLED(COREXY) | ENABLED(COREXZ)
if (axis == X_AXIS || axis == CORE_AXIS_2) {
CRITICAL_SECTION_START;
long pos1 = count_position[A_AXIS],
pos2 = count_position[CORE_AXIS_2];
CRITICAL_SECTION_END;
// ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
// ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
axis_steps = (pos1 + ((axis == X_AXIS) ? pos2 : -pos2)) / 2.0f;
}
else
axis_steps = st_get_position(axis);
#else
axis_steps = st_get_position(axis);
#endif
return axis_steps / axis_steps_per_unit[axis];
}
void finishAndDisableSteppers() {
st_synchronize();
disable_all_steppers();
}
void quickStop() {
cleaning_buffer_counter = 5000;
DISABLE_STEPPER_DRIVER_INTERRUPT();
while (blocks_queued()) plan_discard_current_block();
current_block = NULL;
ENABLE_STEPPER_DRIVER_INTERRUPT();
}
#if ENABLED(BABYSTEPPING)
// MUST ONLY BE CALLED BY AN ISR,
// No other ISR should ever interrupt this!
void babystep(const uint8_t axis, const bool direction) {
#define _ENABLE(axis) enable_## axis()
#define _READ_DIR(AXIS) AXIS ##_DIR_READ
#define _INVERT_DIR(AXIS) INVERT_## AXIS ##_DIR
#define _APPLY_DIR(AXIS, INVERT) AXIS ##_APPLY_DIR(INVERT, true)
#define BABYSTEP_AXIS(axis, AXIS, INVERT) { \
_ENABLE(axis); \
uint8_t old_pin = _READ_DIR(AXIS); \
_APPLY_DIR(AXIS, _INVERT_DIR(AXIS)^direction^INVERT); \
_APPLY_STEP(AXIS)(!_INVERT_STEP_PIN(AXIS), true); \
delayMicroseconds(2); \
_APPLY_STEP(AXIS)(_INVERT_STEP_PIN(AXIS), true); \
_APPLY_DIR(AXIS, old_pin); \
}
switch (axis) {
case X_AXIS:
BABYSTEP_AXIS(x, X, false);
break;
case Y_AXIS:
BABYSTEP_AXIS(y, Y, false);
break;
case Z_AXIS: {
#if DISABLED(DELTA)
BABYSTEP_AXIS(z, Z, BABYSTEP_INVERT_Z);
#else // DELTA
bool z_direction = direction ^ BABYSTEP_INVERT_Z;
enable_x();
enable_y();
enable_z();
uint8_t old_x_dir_pin = X_DIR_READ,
old_y_dir_pin = Y_DIR_READ,
old_z_dir_pin = Z_DIR_READ;
//setup new step
X_DIR_WRITE(INVERT_X_DIR ^ z_direction);
Y_DIR_WRITE(INVERT_Y_DIR ^ z_direction);
Z_DIR_WRITE(INVERT_Z_DIR ^ z_direction);
//perform step
X_STEP_WRITE(!INVERT_X_STEP_PIN);
Y_STEP_WRITE(!INVERT_Y_STEP_PIN);
Z_STEP_WRITE(!INVERT_Z_STEP_PIN);
delayMicroseconds(2);
X_STEP_WRITE(INVERT_X_STEP_PIN);
Y_STEP_WRITE(INVERT_Y_STEP_PIN);
Z_STEP_WRITE(INVERT_Z_STEP_PIN);
//get old pin state back.
X_DIR_WRITE(old_x_dir_pin);
Y_DIR_WRITE(old_y_dir_pin);
Z_DIR_WRITE(old_z_dir_pin);
#endif
} break;
default: break;
}
}
#endif //BABYSTEPPING
#if HAS_DIGIPOTSS
// From Arduino DigitalPotControl example
void digitalPotWrite(int address, int value) {
digitalWrite(DIGIPOTSS_PIN, LOW); // take the SS pin low to select the chip
SPI.transfer(address); // send in the address and value via SPI:
SPI.transfer(value);
digitalWrite(DIGIPOTSS_PIN, HIGH); // take the SS pin high to de-select the chip:
//delay(10);
}
#endif //HAS_DIGIPOTSS
// Initialize Digipot Motor Current
void digipot_init() {
#if HAS_DIGIPOTSS
const uint8_t digipot_motor_current[] = DIGIPOT_MOTOR_CURRENT;
SPI.begin();
pinMode(DIGIPOTSS_PIN, OUTPUT);
for (int i = 0; i < COUNT(digipot_motor_current); i++) {
//digitalPotWrite(digipot_ch[i], digipot_motor_current[i]);
digipot_current(i, digipot_motor_current[i]);
}
#endif
#if HAS_MOTOR_CURRENT_PWM
#if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
pinMode(MOTOR_CURRENT_PWM_XY_PIN, OUTPUT);
digipot_current(0, motor_current_setting[0]);
#endif
#if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
pinMode(MOTOR_CURRENT_PWM_Z_PIN, OUTPUT);
digipot_current(1, motor_current_setting[1]);
#endif
#if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
pinMode(MOTOR_CURRENT_PWM_E_PIN, OUTPUT);
digipot_current(2, motor_current_setting[2]);
#endif
//Set timer5 to 31khz so the PWM of the motor power is as constant as possible. (removes a buzzing noise)
TCCR5B = (TCCR5B & ~(_BV(CS50) | _BV(CS51) | _BV(CS52))) | _BV(CS50);
#endif
}
void digipot_current(uint8_t driver, int current) {
#if HAS_DIGIPOTSS
const uint8_t digipot_ch[] = DIGIPOT_CHANNELS;
digitalPotWrite(digipot_ch[driver], current);
#elif HAS_MOTOR_CURRENT_PWM
#define _WRITE_CURRENT_PWM(P) analogWrite(P, 255L * current / (MOTOR_CURRENT_PWM_RANGE))
switch (driver) {
#if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
case 0: _WRITE_CURRENT_PWM(MOTOR_CURRENT_PWM_XY_PIN); break;
#endif
#if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
case 1: _WRITE_CURRENT_PWM(MOTOR_CURRENT_PWM_Z_PIN); break;
#endif
#if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
case 2: _WRITE_CURRENT_PWM(MOTOR_CURRENT_PWM_E_PIN); break;
#endif
}
#else
UNUSED(driver);
UNUSED(current);
#endif
}
void microstep_init() {
#if HAS_MICROSTEPS_E1
pinMode(E1_MS1_PIN, OUTPUT);
pinMode(E1_MS2_PIN, OUTPUT);
#endif
#if HAS_MICROSTEPS
pinMode(X_MS1_PIN, OUTPUT);
pinMode(X_MS2_PIN, OUTPUT);
pinMode(Y_MS1_PIN, OUTPUT);
pinMode(Y_MS2_PIN, OUTPUT);
pinMode(Z_MS1_PIN, OUTPUT);
pinMode(Z_MS2_PIN, OUTPUT);
pinMode(E0_MS1_PIN, OUTPUT);
pinMode(E0_MS2_PIN, OUTPUT);
const uint8_t microstep_modes[] = MICROSTEP_MODES;
for (uint16_t i = 0; i < COUNT(microstep_modes); i++)
microstep_mode(i, microstep_modes[i]);
#endif
}
void microstep_ms(uint8_t driver, int8_t ms1, int8_t ms2) {
if (ms1 >= 0) switch (driver) {
case 0: digitalWrite(X_MS1_PIN, ms1); break;
case 1: digitalWrite(Y_MS1_PIN, ms1); break;
case 2: digitalWrite(Z_MS1_PIN, ms1); break;
case 3: digitalWrite(E0_MS1_PIN, ms1); break;
#if HAS_MICROSTEPS_E1
case 4: digitalWrite(E1_MS1_PIN, ms1); break;
#endif
}
if (ms2 >= 0) switch (driver) {
case 0: digitalWrite(X_MS2_PIN, ms2); break;
case 1: digitalWrite(Y_MS2_PIN, ms2); break;
case 2: digitalWrite(Z_MS2_PIN, ms2); break;
case 3: digitalWrite(E0_MS2_PIN, ms2); break;
#if PIN_EXISTS(E1_MS2)
case 4: digitalWrite(E1_MS2_PIN, ms2); break;
#endif
}
}
void microstep_mode(uint8_t driver, uint8_t stepping_mode) {
switch (stepping_mode) {
case 1: microstep_ms(driver, MICROSTEP1); break;
case 2: microstep_ms(driver, MICROSTEP2); break;
case 4: microstep_ms(driver, MICROSTEP4); break;
case 8: microstep_ms(driver, MICROSTEP8); break;
case 16: microstep_ms(driver, MICROSTEP16); break;
}
}
void microstep_readings() {
SERIAL_PROTOCOLPGM("MS1,MS2 Pins\n");
SERIAL_PROTOCOLPGM("X: ");
SERIAL_PROTOCOL(digitalRead(X_MS1_PIN));
SERIAL_PROTOCOLLN(digitalRead(X_MS2_PIN));
SERIAL_PROTOCOLPGM("Y: ");
SERIAL_PROTOCOL(digitalRead(Y_MS1_PIN));
SERIAL_PROTOCOLLN(digitalRead(Y_MS2_PIN));
SERIAL_PROTOCOLPGM("Z: ");
SERIAL_PROTOCOL(digitalRead(Z_MS1_PIN));
SERIAL_PROTOCOLLN(digitalRead(Z_MS2_PIN));
SERIAL_PROTOCOLPGM("E0: ");
SERIAL_PROTOCOL(digitalRead(E0_MS1_PIN));
SERIAL_PROTOCOLLN(digitalRead(E0_MS2_PIN));
#if HAS_MICROSTEPS_E1
SERIAL_PROTOCOLPGM("E1: ");
SERIAL_PROTOCOL(digitalRead(E1_MS1_PIN));
SERIAL_PROTOCOLLN(digitalRead(E1_MS2_PIN));
#endif
}
#if ENABLED(Z_DUAL_ENDSTOPS)
void In_Homing_Process(bool state) { performing_homing = state; }
void Lock_z_motor(bool state) { locked_z_motor = state; }
void Lock_z2_motor(bool state) { locked_z2_motor = state; }
#endif
| 44,075 | 17,985 |
#include "port_posix.h"
#include <netdb.h>
#include <pthread.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#define OS_LINUX
namespace handy {
namespace port {
#ifdef OS_LINUX
struct in_addr getHostByName(const std::string &host) {
struct in_addr addr;
char buf[1024];
struct hostent hent;
struct hostent *he = NULL;
int herrno = 0;
memset(&hent, 0, sizeof hent);
int r = gethostbyname_r(host.c_str(), &hent, buf, sizeof buf, &he, &herrno);
if (r == 0 && he && he->h_addrtype == AF_INET) {
addr = *reinterpret_cast<struct in_addr *>(he->h_addr);
} else {
addr.s_addr = INADDR_NONE;
}
return addr;
}
uint64_t gettid() {
return syscall(SYS_gettid);
}
#elif defined(OS_MACOSX)
struct in_addr getHostByName(const std::string &host) {
struct in_addr addr;
struct hostent *he = gethostbyname(host.c_str());
if (he && he->h_addrtype == AF_INET) {
addr = *reinterpret_cast<struct in_addr *>(he->h_addr);
} else {
addr.s_addr = INADDR_NONE;
}
return addr;
}
uint64_t gettid() {
pthread_t tid = pthread_self();
uint64_t uid = 0;
memcpy(&uid, &tid, std::min(sizeof(tid), sizeof(uid)));
return uid;
}
#endif
} // namespace port
} // namespace handy | 1,282 | 516 |
#include "Worker.h"
Worker::Worker(char **argv, int cpu_num, int rank, int size) {
this->job_name = std::string(argv[1]);
this->num_reducer = std::stoi(argv[2]);
this->delay = std::stoi(argv[3]);
this->input_filename = std::string(argv[4]);
this->chunk_size = std::stoi(argv[5]);
this->output_dir = std::string(argv[7]);
this->rank = rank;
this->cpu_num = cpu_num;
this->node_num = rank;
this->available_num = 0;
this->scheduler_index = size - 1;
this->mapper_thread_number = cpu_num - 1;
this->reducer_thread_number = 1;
this->threads = new pthread_t[cpu_num];
this->lock = new std::mutex;
this->send_lock = new std::mutex;
}
Worker::~Worker() {
delete this->lock;
delete this->send_lock;
std::cout << "[Info]: Worker "<< this->rank << " terminate\n";
}
void Worker::DeleteFile(std::string filename) {
int result = 0;
char *f = NULL;
f = (char*)malloc(sizeof(char) * (filename.length() + 1));
for (int i = 0; i < filename.length(); i++) {
f[i] = filename[i];
}
f[filename.length()] = '\0';
result = std::remove(f);
if (result != -1) {
std::cout << "[Info]: Remove file " << filename << " successfully\n";
}
free(f);
}
void Worker::ThreadPoolMapper() {
bool task_finished = false;
MPI_Status status;
int signal = 1;
int request[2];
int chunk_index[2];
this->job_mapper = new std::queue<Chunk>;
this->job_finished = new std::queue<int>;
// allocate mapper thread
for (int i = 0; i < this->mapper_thread_number; i++) {
pthread_create(&this->threads[i], NULL, Worker::MapperFunction, (void*)this);
}
while (!task_finished) {
// check available thread number
while (this->available_num == 0);
request[0] = 0;
request[1] = 0;
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
MPI_Recv(chunk_index, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD, &status);
this->lock->lock();
this->job_mapper->push({chunk_index[0], chunk_index[1]});
this->lock->unlock();
// mapper job done
if (chunk_index[0] == -1) {
task_finished = true;
}
}
// check all mapper thread return
for (int i = 0; i < this->mapper_thread_number; i++) {
pthread_join(this->threads[i], NULL);
}
while (!this->job_finished->empty()) {
request[0] = 1;
request[1] = this->job_finished->front();
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
this->job_finished->pop();
}
// delete queue
delete this->job_mapper;
delete this->job_finished;
MPI_Barrier(MPI_COMM_WORLD);
}
void Worker::ThreadPoolReducer() {
bool task_finished = false;
MPI_Status status;
int signal = 1;
int request[2];
int reducer_index;
this->job_reducer = new std::queue<int>;
this->job_finished = new std::queue<int>;
for (int i = 0; i < this->reducer_thread_number; i++) {
pthread_create(&this->threads[i], NULL, Worker::ReducerFunction, this);
}
while (!task_finished) {
// check available thread
while (this->available_num == 0);
request[0] = 0;
request[1] = 0;
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
MPI_Recv(&reducer_index, 1, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD, &status);
this->lock->lock();
this->job_reducer->push(reducer_index);
this->lock->unlock();
if (reducer_index == -1) { // reducer job done
task_finished = true;
}
}
// check all mapper thread return
for (int i = 0; i < this->reducer_thread_number; i++) {
pthread_join(this->threads[i], NULL);
}
while (!this->job_finished->empty()) {
request[0] = 1;
request[1] = this->job_finished->front();
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
this->job_finished->pop();
}
// delete queue
delete this->job_reducer;
delete this->job_finished;
MPI_Barrier(MPI_COMM_WORLD);
}
void* Worker::MapperFunction(void *input) {
Worker *mapper = (Worker*)input;
Count *word_count = new Count;
Word *words = new Word;
Chunk chunk;
bool task_finished = false;
while (!task_finished) {
chunk.first = -1;
mapper->lock->lock();
if (!mapper->job_mapper->empty()) {
chunk = mapper->job_mapper->front();
if (chunk.first == -1) {
task_finished = true;
} else {
mapper->available_num -= 1;
mapper->job_mapper->pop();
}
}
mapper->lock->unlock();
if (chunk.first != -1) {
if (chunk.second != mapper->rank && WAIT) {
sleep(mapper->delay);
}
word_count->clear();
words->clear();
// Input Split
mapper->InputSplit(chunk.first, word_count, words);
// get word partition number
std::vector<std::vector<std::string>> split_result(mapper->num_reducer + 1);
for (auto word : *words) {
split_result[mapper->Partition(mapper->num_reducer, word)].push_back(word);
}
// generate intermediate file
for (int i = 1; i <= mapper->num_reducer; i++) {
std::string chunk_str = std::to_string(chunk.first);
std::string reducer_num_str = std::to_string(i);
std::string filename = "./intermediate_file/" + chunk_str + "_" + reducer_num_str + ".txt";
std::ofstream myfile(filename);
for (auto word : split_result[i]) {
myfile << word << " " << (*word_count)[word] << "\n";
}
myfile.close();
}
mapper->lock->lock();
mapper->job_finished->push(chunk.first);
mapper->available_num += 1;
mapper->lock->unlock();
}
}
delete word_count;
delete words;
pthread_exit(NULL);
}
void Worker::InputSplit(int chunk, Count *word_count, Word *words) {
int start_pos = 1 + (chunk - 1) * this->chunk_size;
// read chunk file
std::ifstream input_file(this->input_filename);
std::string line;
// find the chunk start position
for (int i = 1; i < start_pos; i++) {
getline(input_file, line);
}
for (int i = 1; i <= this->chunk_size; i++) {
getline(input_file, line);
this->Map(line, word_count, words);
}
input_file.close();
}
void Worker::Map(std::string line, Count *word_count, Word *words) {
int pos = 0;
std::string word;
std::vector<std::string> tmp_words;
while ((pos = line.find(" ")) != std::string::npos) {
word = line.substr(0, pos);
tmp_words.push_back(word);
line.erase(0, pos + 1);
}
if (!line.empty())
tmp_words.push_back(line);
for (auto w : tmp_words) {
if (word_count->count(w) == 0) {
words->push_back(w);
(*word_count)[w] = 1;
} else {
(*word_count)[w] += 1;
}
}
}
int Worker::Partition(int num_reducer, std::string word) {
return ((word.length() % num_reducer) + 1);
}
void* Worker::ReducerFunction(void* input) {
Worker *reducer = (Worker*)input;
Count *word_count = new Count;
Total *total = new Total;
Collect *group = new Collect;
int task;
bool task_finished = false;
while (!task_finished) {
task = -1;
reducer->lock->lock();
if (!reducer->job_reducer->empty()) {
task = reducer->job_reducer->front();
if (task == -1) {
task_finished = true;
} else {
reducer->available_num -= 1;
reducer->job_reducer->pop();
}
}
reducer->lock->unlock();
if (task != -1) {
word_count->clear();
total->clear();
group->clear();
// read intermediate file
reducer->ReadFile(task, total);
// sort words
reducer->Sort(total);
// group
reducer->Group(total, group);
// reduce
reducer->Reduce(group, word_count);
// output
reducer->Output(word_count, task);
reducer->lock->lock();
reducer->job_finished->push(task);
reducer->available_num += 1;
reducer->lock->unlock();
}
}
delete word_count;
delete total;
delete group;
pthread_exit(NULL);
}
void Worker::ReadFile(int task, Total *total) {
std::string filename;
std::string reducer_num_str = std::to_string(task);
std::string word;
int count;
filename = "./intermediate_file/" + reducer_num_str + ".txt";
std::ifstream input_file(filename);
while (input_file >> word >> count) {
total->push_back({word, count});
}
input_file.close();
DeleteFile(filename);
}
bool Worker::cmp(Item a, Item b) {
return a.first < b.first;
}
void Worker::Sort(Total *total) {
sort(total->begin(), total->end(), cmp);
}
void Worker::Group(Total *total, Collect *group) {
for (auto item : *total) {
if (group->count(item.first) == 0) {
std::vector<int> tmp_vec;
tmp_vec.clear();
(*group)[item.first] = tmp_vec;
(*group)[item.first].push_back(item.second);
} else {
(*group)[item.first].push_back(item.second);
}
}
}
void Worker::Reduce(Collect *group, Count *word_count) {
for (auto item : *group) {
(*word_count)[item.first] = 0;
for (auto num : item.second) {
(*word_count)[item.first] += num;
}
}
}
void Worker::Output(Count *word_count, int task) {
std::string task_str = std::to_string(task);
std::string filename = this->output_dir + this->job_name + "-" + task_str + ".out";
std::ofstream myfile(filename);
for (auto word : *word_count) {
myfile << word.first << " " << word.second << "\n";
}
myfile.close();
} | 10,359 | 3,472 |
/*
Copyright (c) 2005-2022, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PLANESTIMULUSCELLFACTORY_HPP_
#define PLANESTIMULUSCELLFACTORY_HPP_
#include <boost/shared_ptr.hpp>
#include "AbstractCardiacCellFactory.hpp"
#include "LogFile.hpp"
#include "SimpleStimulus.hpp"
/**
* PlaneStimulusCellFactory provides cells within 1e-5 of x=0 with a SimpleStimulus.
*/
template<class CELL, unsigned ELEMENT_DIM, unsigned SPACE_DIM = ELEMENT_DIM>
class PlaneStimulusCellFactory : public AbstractCardiacCellFactory<ELEMENT_DIM,SPACE_DIM>
{
protected:
/** The stimulus to apply at stimulated nodes */
boost::shared_ptr<SimpleStimulus> mpStimulus;
public:
/**
* Constructor
* @param stimulusMagnitude The magnitude of the simple stimulus to be applied (defaults to -600).
* @param stimulusDuration The duration of the simple stimulus to be applied (defaults to 0.5ms).
*/
PlaneStimulusCellFactory(double stimulusMagnitude=-600, double stimulusDuration=0.5)
: AbstractCardiacCellFactory<ELEMENT_DIM,SPACE_DIM>()
{
mpStimulus.reset(new SimpleStimulus(stimulusMagnitude, stimulusDuration));
LOG(1, "Defined a PlaneStimulusCellFactory<"<<SPACE_DIM<<"> with SimpleStimulus("<<stimulusMagnitude<<","<< stimulusDuration<< ")\n");
}
/**
* @param pNode Pointer to the node.
* @return A cardiac cell which corresponds to this node.
*/
AbstractCardiacCellInterface* CreateCardiacCellForTissueNode(Node<SPACE_DIM>* pNode)
{
double x = pNode->GetPoint()[0];
///\todo remove magic number? (#1884)
if (x*x<=1e-10)
{
return new CELL(this->mpSolver, mpStimulus);
}
else
{
return new CELL(this->mpSolver, this->mpZeroStimulus);
}
}
};
#endif /*PLANESTIMULUSCELLFACTORY_HPP_*/
| 3,501 | 1,191 |
#include "GameObjectPool.h"
#include <iostream>
#include "GameObjectManager.h"
GameObjectPool::GameObjectPool(string tag, APoolable* poolableCopy, int poolableSize, AGameObject* parent)
{
this->tag = tag;
this->objectCopy = poolableCopy;
this->maxPoolSize = poolableSize;
this->parent = parent;
}
GameObjectPool::~GameObjectPool()
{
//this->objectCopy = NULL;
//this->parent = NULL;
delete this->objectCopy;
delete this->parent;
for (int i = 0; i < this->availableObjects.size(); i++) {
GameObjectManager::getInstance()->deleteObject(this->availableObjects[i]);
}
for (int i = 0; i < this->usedObjects.size(); i++) {
GameObjectManager::getInstance()->deleteObject(this->usedObjects[i]);
}
this->availableObjects.clear(); this->availableObjects.shrink_to_fit();
this->usedObjects.clear(); this->usedObjects.shrink_to_fit();
std::cout << "Object pool " << this->getTag() << " destroyed. \n";
}
//initializes the object pool
void GameObjectPool::initialize()
{
for (int i = 0; i < this->maxPoolSize; i++) {
APoolable* poolableObject = this->objectCopy->clone();
//instantiate object but disable it.
if (this->parent != NULL) {
this->parent->attachChild(poolableObject);
}
else {
GameObjectManager::getInstance()->addObject(poolableObject);
}
poolableObject->setEnabled(false);
this->availableObjects.push_back(poolableObject);
}
}
bool GameObjectPool::hasObjectAvailable(int requestSize)
{
return requestSize <= this->availableObjects.size();
}
APoolable* GameObjectPool::requestPoolable()
{
if (this->hasObjectAvailable(1)) {
APoolable* poolableObject = this->availableObjects[this->availableObjects.size() - 1];
this->availableObjects.erase(this->availableObjects.begin() + this->availableObjects.size() - 1);
this->usedObjects.push_back(poolableObject);
//std::cout << "Requested object. Available: " << this->availableObjects.size() << " Used: " << this->usedObjects.size() << "\n";
this->setEnabled(poolableObject, true);
return poolableObject;
}
else {
std::cout << " No more poolable " + this->objectCopy->getName() + " available! \n";
return NULL;
}
}
ObjectList GameObjectPool::requestPoolableBatch(int size)
{
ObjectList returnList;
if (this->hasObjectAvailable(size)) {
for (int i = 0; i < size; i++) {
returnList.push_back(this->requestPoolable());
}
}
else {
std::cout << "Insufficient " + this->objectCopy->getName() + " available in pool. Count is: " << this->availableObjects.size() <<
" while requested is " << size << "!\n";
}
return returnList;
}
void GameObjectPool::releasePoolable(APoolable* poolableObject)
{
//find object in used
int index = -1;
for (int i = 0; i < this->usedObjects.size(); i++) {
if (this->usedObjects[i] == poolableObject) {
index = i;
break;
}
}
//std::cout << "Poolable index in used: " << index << "\n";
if (index > -1) {
this->usedObjects.erase(this->usedObjects.begin() + index);
this->availableObjects.push_back(poolableObject);
this->setEnabled(poolableObject, false);
}
}
void GameObjectPool::releasePoolableBatch(ObjectList objectList)
{
for (int i = 0; i < objectList.size(); i++) {
this->releasePoolable(objectList[i]);
}
}
string GameObjectPool::getTag()
{
return this->tag;
}
void GameObjectPool::setEnabled(APoolable* poolableObject, bool flag)
{
if (flag) {
poolableObject->setEnabled(true);
poolableObject->onActivate();
}
else {
poolableObject->setEnabled(false);
poolableObject->onRelease();
}
}
| 3,499 | 1,222 |
///////////////////////////////////////////////////////////////////////
// Doubly Linked List
//
// This file should contain you implementation of the doubly-linked
// list data structure as described in the project documentation.
//
// Some functions are provided for you - use these as guides for the
// implementation of the remaining functions.
//
// This code can be tested using the testbench module. See
// testbench.h in the source, and LL_testbench_documentation.pdf in
// the project documentation for more information.
//
// GEORGIA INSTITUTE OF TECHNOLOGY, FALL 2016
///////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include "doubly_linked_list.h"
/**
* create_llnode
*
* Helper function that creates a node by allocating memory for it on the heap,
* and initializing its previous and next pointers to NULL and its data pointer to the input
* data pointer
*
* @param data A void pointer to data the user is adding to the doublely linked list.
* @return A pointer to the linked list node
*/
static LLNode* create_llnode(void* data) {
LLNode* newNode = (LLNode*)malloc(sizeof(LLNode));
newNode->data = data;
newNode->previous = NULL;
newNode->next = NULL;
return newNode;
}
/**
* create_dlinkedlist
*
* Creates a doublely liked list by allocating memory for it on the heap. Initialize the size to zero,
* as well as head, current, and tail pointer to NULL
*
* @return A pointer to an empty dlinkedlist
*/
DLinkedList* create_dlinkedlist(void) {
DLinkedList* newList = (DLinkedList*)malloc(sizeof(DLinkedList));
newList->head = NULL;
newList->tail = NULL;
newList->current = NULL;
newList->size = 0;
return newList;
}
void insertHead(DLinkedList* dll, void* data){
LLNode* newNode = create_llnode(data);
if(dll->head == NULL){
dll->size++;
dll->head = newNode;
dll->tail = newNode;
}else{
dll->size++;
newNode->next = dll->head;
(dll->head)->previous = newNode;
dll->head = newNode;
}
}
void insertTail(DLinkedList* dll, void* data){
LLNode* newNode = create_llnode(data);
if (dll->tail == NULL) {
dll->size++;
dll->head = newNode;
dll->tail = newNode;
} else {
dll->size++;
newNode->previous = dll->tail;
(dll->tail)->next = newNode;
dll->tail = newNode;
}
}
int insertAfter(DLinkedList* dll, void* newData){
LLNode* newNode = create_llnode(newData);
if (dll->current == NULL || dll == NULL) {
return 0;
} else if (dll->current == dll->tail) {
insertTail(dll, newData);
return 1;
} else {
dll->size++;
newNode->next = (dll->current)->next;
newNode->previous = dll->current;
((dll->current)->next)->previous = newNode;
(dll->current)->next = newNode;
return 1;
}
}
int insertBefore(DLinkedList* dll, void* newData){
LLNode* newNode = create_llnode(newData);
if (dll->current == NULL || dll == NULL) {
return 0;
} else if (dll->current == dll->head) {
insertHead(dll, newData);
return 1;
} else {
dll->size++;
newNode->next = dll->current;
newNode->previous = (dll->current)->previous;
((dll->current)->previous)->next = newNode;
(dll->current)->previous = newNode;
return 1;
}
}
void* deleteBackward(DLinkedList* dll, int shouldFree){
LLNode* temp = dll->current;
if (temp == NULL || dll == NULL) {
return NULL;
} else if (dll->size == 1) {
dll->current = NULL;
dll->head = NULL;
dll->tail = NULL;
dll->size--;
if (shouldFree) {
free(temp->data);
}
free(temp);
return NULL;
} else if (temp == dll->head) {
dll->head = temp->next; // move head pointer
(dll->head)->previous = NULL; // new head have no previous pointer
dll->current = NULL;
if (shouldFree) {
free(temp->data);
}
free(temp);
dll->size--;
return NULL;
} else if (temp == dll->tail) {
dll->tail = temp->previous; // move tail
(dll->tail)->next = NULL; // pointer after tail is null
dll->current = dll->tail; // new current
if(shouldFree) {
free(temp->data);
}
free(temp);
dll->size--;
return((dll->current)->data);
} else {
(temp->next)->previous = temp->previous;
(temp->previous)->next = temp->next;
dll->current = temp->previous;
if(shouldFree) {
free(temp->data);
}
free(temp);
dll->size--;
return((dll->current)->data);
}
}
void* deleteForward(DLinkedList* dll, int shouldFree){
LLNode* temp = dll->current;
if (temp == NULL || dll == NULL) {
return NULL;
} else if (dll->size == 1) {
dll->current = NULL;
dll->head = NULL;
dll->tail = NULL;
if (shouldFree) {
free(temp->data);
}
free(temp);
dll->size--;
return NULL;
} else if (temp == dll->head) {
dll->head = temp->next; // move head
(dll->head)->previous = NULL; // set new head prev to null
dll->current = dll->head; // move current
if (shouldFree) {
free(temp->data);
}
free(temp);
dll->size--;
return (dll->current)->data;
} else if (temp == dll->tail) {
dll->tail = temp->previous;
(dll->tail)->next = NULL;
dll->current = NULL;
if (shouldFree) {
free(temp->data);
}
free(temp);
dll->size--;
return NULL;
} else {
((dll->current)->next)->previous = (dll->current)->previous;
((dll->current)->previous)->next = (dll->current)->next;
dll->current = (dll->current)->next;
if (shouldFree) {
free(temp->data);
}
free(temp);
dll->size--;
return (dll->current)->data;
}
}
void destroyList(DLinkedList* dll, int shouldFree){
if(dll->head != NULL){
getHead(dll);
while(deleteForward(dll,shouldFree)){};
}
free(dll);
}
void* getHead(DLinkedList* dll){
if(dll->head != NULL){
dll->current = dll->head;
return (dll->head)->data;
}else{
return NULL;
}
}
void* getTail(DLinkedList* dll){
if(dll->tail != NULL) {
dll->current = dll->tail;
return (dll->tail)->data;
} else {
return NULL;
}
}
void* getCurrent(DLinkedList* dll){
if(dll->current != NULL) {
return (dll->current)->data;
} else {
return NULL;
}
}
void* getNext(DLinkedList* dll){
if((dll->current)->next != NULL) {
dll->current = (dll->current)->next;
return (dll->current)->data;
} else {
return NULL;
}
}
void* getPrevious(DLinkedList* dll){
if((dll->current)->previous != NULL) {
dll->current = (dll->current)->previous;
return (dll->current)->data;
} else {
return NULL;
}
}
int getSize(DLinkedList* dll){
return dll->size;
} | 7,261 | 2,309 |
#include "exahype/solvers/CellWiseCoupling.h"
exahype::solvers::CellWiseCoupling::CellWiseCoupling(double time, double repeat):
SolverCoupling( SolverCoupling::Type::CellWise, time, repeat) {
}
| 198 | 78 |
// AMD AMDUtils code
//
// Copyright(c) 2018 Advanced Micro Devices, Inc.All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "ExtFreeSync2.h"
#include "Misc/Misc.h"
#include <vulkan/vulkan.h>
namespace CAULDRON_VK
{
static PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR g_vkGetPhysicalDeviceSurfaceCapabilities2KHR = nullptr;
static PFN_vkGetDeviceProcAddr g_vkGetDeviceProcAddr = nullptr;
static PFN_vkSetHdrMetadataEXT g_vkSetHdrMetadataEXT = nullptr;
#ifdef _WIN32
static PFN_vkAcquireFullScreenExclusiveModeEXT g_vkAcquireFullScreenExclusiveModeEXT = nullptr;
static PFN_vkReleaseFullScreenExclusiveModeEXT g_vkReleaseFullScreenExclusiveModeEXT = nullptr;
#endif
static PFN_vkGetPhysicalDeviceSurfaceFormats2KHR g_vkGetPhysicalDeviceSurfaceFormats2KHR = nullptr;
#ifdef _WIN32
static PFN_vkGetDeviceGroupSurfacePresentModes2EXT g_vkGetDeviceGroupSurfacePresentModes2EXT = nullptr;
static PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT g_vkGetPhysicalDeviceSurfacePresentModes2EXT = nullptr;
static PFN_vkSetLocalDimmingAMD g_vkSetLocalDimmingAMD = nullptr;
#endif
static PFN_vkGetPhysicalDevicePresentRectanglesKHR g_vkGetPhysicalDevicePresentRectanglesKHR = nullptr;
bool ExtFreeSync2CheckExtensions(DeviceProperties *pDP)
{
bool res = true;
#ifdef _WIN32
std::vector<const char *> required_extension_names = { VK_EXT_HDR_METADATA_EXTENSION_NAME, VK_AMD_DISPLAY_NATIVE_HDR_EXTENSION_NAME, VK_EXT_FULL_SCREEN_EXCLUSIVE_EXTENSION_NAME };
for (auto& ext : required_extension_names)
{
if (pDP->Add(ext) == false)
{
Trace(format("FreeSync2 disabled, missing extension: %s\n", ext));
res = false;
}
}
#else
res = false;
Trace(format("FreeSync2 disabled, unsupported platform"));
#endif
return res;
}
void ExtFreeSync2Init(VkInstance instance)
{
g_vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr");
assert(g_vkGetDeviceProcAddr);
g_vkGetPhysicalDeviceSurfaceFormats2KHR = (PFN_vkGetPhysicalDeviceSurfaceFormats2KHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormats2KHR");
assert(g_vkGetPhysicalDeviceSurfaceFormats2KHR);
#ifdef _WIN32
g_vkGetPhysicalDeviceSurfacePresentModes2EXT = (PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModes2EXT");
assert(g_vkGetPhysicalDeviceSurfacePresentModes2EXT);
g_vkGetDeviceGroupSurfacePresentModes2EXT = (PFN_vkGetDeviceGroupSurfacePresentModes2EXT)vkGetInstanceProcAddr(instance, "vkGetDeviceGroupSurfacePresentModes2EXT");
assert(g_vkGetDeviceGroupSurfacePresentModes2EXT);
#endif
}
void ExtFreeSync2Init(VkDevice device)
{
g_vkSetHdrMetadataEXT = (PFN_vkSetHdrMetadataEXT)g_vkGetDeviceProcAddr(device, "vkSetHdrMetadataEXT");
assert(g_vkSetHdrMetadataEXT);
#ifdef _WIN32
g_vkAcquireFullScreenExclusiveModeEXT = (PFN_vkAcquireFullScreenExclusiveModeEXT)g_vkGetDeviceProcAddr(device, "vkAcquireFullScreenExclusiveModeEXT");
assert(g_vkAcquireFullScreenExclusiveModeEXT);
g_vkReleaseFullScreenExclusiveModeEXT = (PFN_vkReleaseFullScreenExclusiveModeEXT)g_vkGetDeviceProcAddr(device, "vkReleaseFullScreenExclusiveModeEXT");
assert(g_vkReleaseFullScreenExclusiveModeEXT);
g_vkSetLocalDimmingAMD = (PFN_vkSetLocalDimmingAMD)g_vkGetDeviceProcAddr(device, "vkSetLocalDimmingAMD");
assert(g_vkSetLocalDimmingAMD);
#endif
g_vkGetPhysicalDevicePresentRectanglesKHR = (PFN_vkGetPhysicalDevicePresentRectanglesKHR)g_vkGetDeviceProcAddr(device, "vkGetPhysicalDevicePresentRectanglesKHR");
assert(g_vkGetPhysicalDevicePresentRectanglesKHR);
}
} | 5,034 | 1,761 |
// ./CSGNodeTest.sh
#include <vector>
#include <iomanip>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "sutil_vec_math.h"
#include "CSGNode.h"
#include "Sys.h"
void test_copy()
{
glm::mat4 m0(1.f);
glm::mat4 m1(2.f);
glm::mat4 m2(3.f);
m0[0][3] = Sys::int_as_float(42);
m1[0][3] = Sys::int_as_float(52);
m2[0][3] = Sys::int_as_float(62);
std::vector<glm::mat4> node ;
node.push_back(m0);
node.push_back(m1);
node.push_back(m2);
std::vector<CSGNode> node_(3) ;
memcpy( node_.data(), node.data(), sizeof(CSGNode)*node_.size() );
CSGNode* n_ = node_.data();
CSGNode::Dump( n_, node_.size(), "CSGNodeTest" );
}
void test_zero()
{
CSGNode nd = {} ;
assert( nd.gtransformIdx() == 0u );
assert( nd.complement() == false );
unsigned tr = 42u ;
nd.setTransform( tr );
assert( nd.gtransformIdx() == tr );
assert( nd.complement() == false );
nd.setComplement(true);
assert( nd.gtransformIdx() == tr );
assert( nd.complement() == true );
std::cout << nd.desc() << std::endl ;
}
void test_sphere()
{
CSGNode nd = CSGNode::Sphere(100.f);
std::cout << nd.desc() << std::endl ;
}
void test_change_transform()
{
CSGNode nd = {} ;
std::vector<unsigned> uu = {1001, 100, 10, 5, 6, 0, 20, 101, 206 } ;
// checking changing the transform whilst preserving the complement
for(int i=0 ; i < int(uu.size()-1) ; i++)
{
const unsigned& u0 = uu[i] ;
const unsigned& u1 = uu[i+1] ;
nd.setComplement( u0 % 2 == 0 );
nd.setTransform(u0);
bool c0 = nd.complement();
nd.zeroTransformComplement();
nd.setComplement(c0) ;
nd.setTransform( u1 );
bool c1 = nd.complement();
assert( c0 == c1 );
unsigned u1_chk = nd.gtransformIdx();
assert( u1_chk == u1 );
}
}
int main(int argc, char** argv)
{
std::cout << argv[0] << std::endl ;
//test_zero();
//test_sphere();
//test_copy();
test_change_transform();
return 0 ;
}
| 2,110 | 940 |
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return;
int n = matrix.size(), m = matrix[0].size();
bool lastRowZero = false;
for (int j = 0; j < m; ++j)
if (matrix[0][j] == 0)
{
lastRowZero = true;
break;
}
for (int i = 1; i < n; ++i)
{
bool thisRowZero = false;
for (int j = 0; j < m; ++j)
if (matrix[i][j] == 0)
{
thisRowZero = true;
for (int k = i - 1; k >= 0; --k)
matrix[k][j] = 0;
}
for (int j = 0; j < m; ++j)
if (matrix[i-1][j] == 0)
matrix[i][j] = 0;
if (lastRowZero)
for (int j = 0; j < m; ++j)
matrix[i-1][j] = 0;
lastRowZero = thisRowZero;
}
if (lastRowZero)
for (int j = 0; j < m; ++j)
matrix[n-1][j] = 0;
}
}; | 1,101 | 368 |
// Copyright 2019 Nobleo Technology
//
// 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 "rclcpp/executors/static_single_threaded_executor.hpp"
#include <memory>
#include <vector>
#include "rclcpp/scope_exit.hpp"
using rclcpp::executors::StaticSingleThreadedExecutor;
using rclcpp::experimental::ExecutableList;
StaticSingleThreadedExecutor::StaticSingleThreadedExecutor(
const rclcpp::ExecutorOptions & options)
: rclcpp::Executor(options)
{
entities_collector_ = std::make_shared<StaticExecutorEntitiesCollector>();
}
StaticSingleThreadedExecutor::~StaticSingleThreadedExecutor() {}
void
StaticSingleThreadedExecutor::spin()
{
if (spinning.exchange(true)) {
throw std::runtime_error("spin() called while already spinning");
}
RCLCPP_SCOPE_EXIT(this->spinning.store(false); );
// Set memory_strategy_ and exec_list_ based on weak_nodes_
// Prepare wait_set_ based on memory_strategy_
entities_collector_->init(&wait_set_, memory_strategy_, &interrupt_guard_condition_);
RCLCPP_SCOPE_EXIT(entities_collector_->fini());
while (rclcpp::ok(this->context_) && spinning.load()) {
// Refresh wait set and wait for work
entities_collector_->refresh_wait_set();
execute_ready_executables();
}
}
void
StaticSingleThreadedExecutor::add_callback_group(
rclcpp::CallbackGroup::SharedPtr group_ptr,
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr,
bool notify)
{
bool is_new_node = entities_collector_->add_callback_group(group_ptr, node_ptr);
if (is_new_node && notify) {
// Interrupt waiting to handle new node
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
void
StaticSingleThreadedExecutor::add_node(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr, bool notify)
{
bool is_new_node = entities_collector_->add_node(node_ptr);
if (is_new_node && notify) {
// Interrupt waiting to handle new node
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
void
StaticSingleThreadedExecutor::add_node(std::shared_ptr<rclcpp::Node> node_ptr, bool notify)
{
this->add_node(node_ptr->get_node_base_interface(), notify);
}
void
StaticSingleThreadedExecutor::remove_callback_group(
rclcpp::CallbackGroup::SharedPtr group_ptr, bool notify)
{
bool node_removed = entities_collector_->remove_callback_group(group_ptr);
// If the node was matched and removed, interrupt waiting
if (node_removed && notify) {
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
void
StaticSingleThreadedExecutor::remove_node(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr, bool notify)
{
bool node_removed = entities_collector_->remove_node(node_ptr);
if (!node_removed) {
throw std::runtime_error("Node needs to be associated with this executor.");
}
// If the node was matched and removed, interrupt waiting
if (notify) {
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
std::vector<rclcpp::CallbackGroup::WeakPtr>
StaticSingleThreadedExecutor::get_all_callback_groups()
{
return entities_collector_->get_all_callback_groups();
}
std::vector<rclcpp::CallbackGroup::WeakPtr>
StaticSingleThreadedExecutor::get_manually_added_callback_groups()
{
return entities_collector_->get_manually_added_callback_groups();
}
std::vector<rclcpp::CallbackGroup::WeakPtr>
StaticSingleThreadedExecutor::get_automatically_added_callback_groups_from_nodes()
{
return entities_collector_->get_automatically_added_callback_groups_from_nodes();
}
void
StaticSingleThreadedExecutor::remove_node(std::shared_ptr<rclcpp::Node> node_ptr, bool notify)
{
this->remove_node(node_ptr->get_node_base_interface(), notify);
}
void
StaticSingleThreadedExecutor::execute_ready_executables()
{
// Execute all the ready subscriptions
for (size_t i = 0; i < wait_set_.size_of_subscriptions; ++i) {
if (i < entities_collector_->get_number_of_subscriptions()) {
if (wait_set_.subscriptions[i]) {
execute_subscription(entities_collector_->get_subscription(i));
}
}
}
// Execute all the ready timers
for (size_t i = 0; i < wait_set_.size_of_timers; ++i) {
if (i < entities_collector_->get_number_of_timers()) {
if (wait_set_.timers[i] && entities_collector_->get_timer(i)->is_ready()) {
execute_timer(entities_collector_->get_timer(i));
}
}
}
// Execute all the ready services
for (size_t i = 0; i < wait_set_.size_of_services; ++i) {
if (i < entities_collector_->get_number_of_services()) {
if (wait_set_.services[i]) {
execute_service(entities_collector_->get_service(i));
}
}
}
// Execute all the ready clients
for (size_t i = 0; i < wait_set_.size_of_clients; ++i) {
if (i < entities_collector_->get_number_of_clients()) {
if (wait_set_.clients[i]) {
execute_client(entities_collector_->get_client(i));
}
}
}
// Execute all the ready waitables
for (size_t i = 0; i < entities_collector_->get_number_of_waitables(); ++i) {
auto waitable = entities_collector_->get_waitable(i);
if (waitable->is_ready(&wait_set_)) {
auto data = waitable->take_data();
waitable->execute(data);
}
}
}
| 6,054 | 2,035 |
#ifndef HTMLHEADELEMENT_H
#define HTMLHEADELEMENT_H
#include "HTMLElement.hpp"
class HTMLHeadElement : public HTMLElement
{
public:
HTMLHeadElement();
};
#endif
| 176 | 67 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/network_profile_bubble.h"
#include <windows.h>
#include <wtsapi32.h>
// Make sure we link the wtsapi lib file in.
#pragma comment(lib, "wtsapi32.lib")
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "content/public/browser/browser_thread.h"
namespace {
// The duration of the silent period before we start nagging the user again.
const int kSilenceDurationDays = 100;
// The number of warnings to be shown on consequtive starts of Chrome before the
// silent period starts.
const int kMaxWarnings = 2;
// Implementation of chrome::BrowserListObserver used to wait for a browser
// window.
class BrowserListObserver : public chrome::BrowserListObserver {
private:
virtual ~BrowserListObserver();
// Overridden from chrome::BrowserListObserver:
virtual void OnBrowserAdded(Browser* browser) override;
virtual void OnBrowserRemoved(Browser* browser) override;
virtual void OnBrowserSetLastActive(Browser* browser) override;
};
BrowserListObserver::~BrowserListObserver() {
}
void BrowserListObserver::OnBrowserAdded(Browser* browser) {
}
void BrowserListObserver::OnBrowserRemoved(Browser* browser) {
}
void BrowserListObserver::OnBrowserSetLastActive(Browser* browser) {
NetworkProfileBubble::ShowNotification(browser);
// No need to observe anymore.
BrowserList::RemoveObserver(this);
delete this;
}
// The name of the UMA histogram collecting our stats.
const char kMetricNetworkedProfileCheck[] = "NetworkedProfile.Check";
} // namespace
// static
bool NetworkProfileBubble::notification_shown_ = false;
// static
bool NetworkProfileBubble::ShouldCheckNetworkProfile(Profile* profile) {
PrefService* prefs = profile->GetPrefs();
if (prefs->GetInteger(prefs::kNetworkProfileWarningsLeft))
return !notification_shown_;
int64 last_check = prefs->GetInt64(prefs::kNetworkProfileLastWarningTime);
base::TimeDelta time_since_last_check =
base::Time::Now() - base::Time::FromTimeT(last_check);
if (time_since_last_check.InDays() > kSilenceDurationDays) {
prefs->SetInteger(prefs::kNetworkProfileWarningsLeft, kMaxWarnings);
return !notification_shown_;
}
return false;
}
// static
void NetworkProfileBubble::CheckNetworkProfile(
const base::FilePath& profile_folder) {
DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
// On Windows notify the users if their profiles are located on a network
// share as we don't officially support this setup yet.
// However we don't want to bother users on Cytrix setups as those have no
// real choice and their admins must be well aware of the risks associated.
// Also the command line flag --no-network-profile-warning can stop this
// warning from popping up. In this case we can skip the check to make the
// start faster.
// Collect a lot of stats along the way to see which cases do occur in the
// wild often enough.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNoNetworkProfileWarning)) {
RecordUmaEvent(METRIC_CHECK_SUPPRESSED);
return;
}
LPWSTR buffer = NULL;
DWORD buffer_length = 0;
// Checking for RDP is cheaper than checking for a network drive so do this
// one first.
if (!::WTSQuerySessionInformation(WTS_CURRENT_SERVER, WTS_CURRENT_SESSION,
WTSClientProtocolType,
&buffer, &buffer_length)) {
RecordUmaEvent(METRIC_CHECK_FAILED);
return;
}
unsigned short* type = reinterpret_cast<unsigned short*>(buffer);
// We should warn the users if they have their profile on a network share only
// if running on a local session.
if (*type == WTS_PROTOCOL_TYPE_CONSOLE) {
bool profile_on_network = false;
if (!profile_folder.empty()) {
base::FilePath temp_file;
// Try to create some non-empty temp file in the profile dir and use
// it to check if there is a reparse-point free path to it.
if (base::CreateTemporaryFileInDir(profile_folder, &temp_file) &&
(base::WriteFile(temp_file, ".", 1) == 1)) {
base::FilePath normalized_temp_file;
if (!base::NormalizeFilePath(temp_file, &normalized_temp_file))
profile_on_network = true;
} else {
RecordUmaEvent(METRIC_CHECK_IO_FAILED);
}
base::DeleteFile(temp_file, false);
}
if (profile_on_network) {
RecordUmaEvent(METRIC_PROFILE_ON_NETWORK);
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&NotifyNetworkProfileDetected));
} else {
RecordUmaEvent(METRIC_PROFILE_NOT_ON_NETWORK);
}
} else {
RecordUmaEvent(METRIC_REMOTE_SESSION);
}
::WTSFreeMemory(buffer);
}
// static
void NetworkProfileBubble::SetNotificationShown(bool shown) {
notification_shown_ = shown;
}
// static
void NetworkProfileBubble::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kNetworkProfileWarningsLeft,
kMaxWarnings,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterInt64Pref(
prefs::kNetworkProfileLastWarningTime,
0,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
void NetworkProfileBubble::RecordUmaEvent(MetricNetworkedProfileCheck event) {
UMA_HISTOGRAM_ENUMERATION(kMetricNetworkedProfileCheck,
event,
METRIC_NETWORKED_PROFILE_CHECK_SIZE);
}
// static
void NetworkProfileBubble::NotifyNetworkProfileDetected() {
Browser* browser = chrome::FindLastActiveWithHostDesktopType(
chrome::GetActiveDesktop());
if (browser)
ShowNotification(browser);
else
BrowserList::AddObserver(new BrowserListObserver());
}
| 6,496 | 2,017 |
/*************************************************************************
* libjson-rpc-cpp
*************************************************************************
* @file stubgenerator.cpp
* @date 01.05.2013
* @author Peter Spiess-Knafl <dev@spiessknafl.at>
* @license See attached LICENSE.txt
************************************************************************/
#include <algorithm>
#include <fstream>
#include <jsonrpccpp/common/specificationparser.h>
#include <argtable/argtable3.h>
#include "client/cppclientstubgenerator.h"
#include "client/jsclientstubgenerator.h"
#include "client/pyclientstubgenerator.h"
#include "helper/cpphelper.h"
#include "server/cppserverstubgenerator.h"
#include "stubgenerator.h"
using namespace std;
using namespace jsonrpc;
#define EXIT_ERROR(X) \
cerr << X << endl; \
arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); \
return 1;
StubGenerator::StubGenerator(const string &stubname,
std::vector<Procedure> &procedures,
ostream &outputstream)
: CodeGenerator(outputstream), stubname(stubname), procedures(procedures) {}
StubGenerator::StubGenerator(const string &stubname,
std::vector<Procedure> &procedures,
const std::string &filename)
: CodeGenerator(filename), stubname(stubname), procedures(procedures) {}
StubGenerator::~StubGenerator() {}
string StubGenerator::replaceAll(const string &text, const string &fnd,
const string &rep) {
string result = text;
replaceAll2(result, fnd, rep);
return result;
}
void StubGenerator::replaceAll2(string &result, const string &find,
const string &replace) {
size_t pos = result.find(find);
while (pos != string::npos) {
result.replace(pos, find.length(), replace);
pos = result.find(find, pos + replace.length());
}
}
| 2,087 | 581 |
#include <GL/Command/Buffer.hpp>
#include <GL/QueryPool.hpp>
OCRA_DECLARE_HANDLE(OCRA::Command::Buffer);
OCRA_DECLARE_HANDLE(OCRA::QueryPool);
namespace OCRA::Command
{
void BeginQuery(
const Command::Buffer::Handle& a_CommandBuffer,
const QueryPool::Handle& a_QueryPool,
const uint32_t& a_QueryIndex)
{
a_CommandBuffer->PushCommand([queryPool = a_QueryPool, queryIndex = a_QueryIndex](Buffer::ExecutionState& a_ExecutionState) {
queryPool->Begin(queryIndex);
});
}
void EndQuery(
const Command::Buffer::Handle& a_CommandBuffer,
const QueryPool::Handle& a_QueryPool,
const uint32_t& a_QueryIndex)
{
a_CommandBuffer->PushCommand([queryPool = a_QueryPool, queryIndex = a_QueryIndex](Buffer::ExecutionState& a_ExecutionState) {
queryPool->End(queryIndex);
});
}
} | 866 | 277 |
#include "../test.h"
#include <rxcpp/operators/rx-publish.hpp>
#include <rxcpp/operators/rx-connect_forever.hpp>
#include <rxcpp/operators/rx-ref_count.hpp>
#include <rxcpp/operators/rx-map.hpp>
#include <rxcpp/operators/rx-merge.hpp>
SCENARIO("publish range", "[!hide][range][subject][publish][subject][operators]"){
GIVEN("a range"){
WHEN("published"){
auto published = rxs::range<int>(0, 10).publish();
std::cout << "subscribe to published" << std::endl;
published.subscribe(
// on_next
[](int v){std::cout << v << ", ";},
// on_completed
[](){std::cout << " done." << std::endl;});
std::cout << "connect to published" << std::endl;
published.connect();
}
WHEN("ref_count is used"){
auto published = rxs::range<int>(0, 10).publish().ref_count();
std::cout << "subscribe to ref_count" << std::endl;
published.subscribe(
// on_next
[](int v){std::cout << v << ", ";},
// on_completed
[](){std::cout << " done." << std::endl;});
}
WHEN("connect_forever is used"){
auto published = rxs::range<int>(0, 10).publish().connect_forever();
std::cout << "subscribe to connect_forever" << std::endl;
published.subscribe(
// on_next
[](int v){std::cout << v << ", ";},
// on_completed
[](){std::cout << " done." << std::endl;});
}
}
}
SCENARIO("publish ref_count", "[range][subject][publish][ref_count][operators]"){
GIVEN("a range"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<double> on;
const rxsc::test::messages<long> out;
static const long start_created = 0;
static const long start_subscribed = 100;
static const long start_unsubscribed = 200;
static const auto next_time = start_subscribed + 1;
static const auto completed_time = next_time + 1;
auto xs = sc.make_hot_observable({ // [0.0, 10.0]
on.next(next_time, 0.0),
on.next(next_time, 1.0),
on.next(next_time, 2.0),
on.next(next_time, 3.0),
on.next(next_time, 4.0),
on.next(next_time, 5.0),
on.next(next_time, 6.0),
on.next(next_time, 7.0),
on.next(next_time, 8.0),
on.next(next_time, 9.0),
on.next(next_time, 10.0),
on.completed(completed_time)
});
auto xs3 = sc.make_hot_observable({ // [0.0, 3.0]
on.next(next_time, 0.0),
on.next(next_time, 1.0),
on.next(next_time, 2.0),
on.next(next_time, 3.0),
on.completed(completed_time)
});
WHEN("ref_count is used"){
auto res = w.start(
[&xs]() {
return xs
.publish()
.ref_count();
},
start_created,
start_subscribed,
start_unsubscribed
);
THEN("the output contains exactly the input") {
auto required = rxu::to_vector({
on.next(next_time, 0.0),
on.next(next_time, 1.0),
on.next(next_time, 2.0),
on.next(next_time, 3.0),
on.next(next_time, 4.0),
on.next(next_time, 5.0),
on.next(next_time, 6.0),
on.next(next_time, 7.0),
on.next(next_time, 8.0),
on.next(next_time, 9.0),
on.next(next_time, 10.0),
on.completed(completed_time)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
}
WHEN("ref_count(other) is used"){
auto res = w.start(
[&xs]() {
auto published = xs.publish();
auto map_to_int = published.map([](double v) { return (long) v; });
// Ensures that 'ref_count(other)' has the source value type,
// not the publisher's value type.
auto with_ref_count = map_to_int.ref_count(published);
return with_ref_count;
},
start_created,
start_subscribed,
start_unsubscribed
);
THEN("the output contains the long-ified input") {
auto required = rxu::to_vector({
out.next(next_time, 0L),
out.next(next_time, 1L),
out.next(next_time, 2L),
out.next(next_time, 3L),
out.next(next_time, 4L),
out.next(next_time, 5L),
out.next(next_time, 6L),
out.next(next_time, 7L),
out.next(next_time, 8L),
out.next(next_time, 9L),
out.next(next_time, 10L),
out.completed(completed_time)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
}
WHEN("ref_count(other) is used in a diamond"){
auto source = rxs::range<double>(0, 3);
int published_on_next_count = 0;
auto res = w.start(
[&xs3, &published_on_next_count]() {
// Ensure we only subscribe once to 'published' when its in a diamond.
auto next = xs3.map(
[&](double v) {
published_on_next_count++;
return v;
}
);
auto published = next.publish();
// Ensures that 'x.ref_count(other)' has the 'x' value type, not the other's
// value type.
auto map_to_int = published.map([](double v) { return (long) v; });
auto left = map_to_int.map([](long v) { return v * 2; });
auto right = map_to_int.map([](long v) { return v * 100; });
auto merge = left.merge(right);
auto with_ref_count = merge.ref_count(published);
return with_ref_count;
},
start_created,
start_subscribed,
start_unsubscribed
);
THEN("the output is subscribed to only once when its in a diamond") {
// Ensure we only subscribe once to 'published' when its in a diamond.
CHECK(published_on_next_count == 4);
}
THEN("the output left,right is interleaved without being biased towards one side.") {
auto required = rxu::to_vector({
out.next(next_time, 0L),
out.next(next_time, 0L),
out.next(next_time, 2L),
out.next(next_time, 100L),
out.next(next_time, 4L),
out.next(next_time, 200L),
out.next(next_time, 6L),
out.next(next_time, 300L),
out.completed(completed_time)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("publish basic", "[publish][multicast][subject][operators]"){
GIVEN("a test hot observable of longs"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto xs = sc.make_hot_observable({
on.next(110, 7),
on.next(220, 3),
on.next(280, 4),
on.next(290, 1),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(410, 13),
on.next(430, 2),
on.next(450, 9),
on.next(520, 11),
on.next(560, 20),
on.completed(600)
});
auto res = w.make_subscriber<int>();
rx::connectable_observable<int> ys;
WHEN("subscribed and then connected"){
w.schedule_absolute(rxsc::test::created_time,
[&ys, &xs](const rxsc::schedulable&){
ys = xs.publish().as_dynamic();
//ys = xs.publish_last().as_dynamic();
});
w.schedule_absolute(rxsc::test::subscribed_time,
[&ys, &res](const rxsc::schedulable&){
ys.subscribe(res);
});
w.schedule_absolute(rxsc::test::unsubscribed_time,
[&res](const rxsc::schedulable&){
res.unsubscribe();
});
{
rx::composite_subscription connection;
w.schedule_absolute(300,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(400,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(500,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(550,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(650,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(800,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
w.start();
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(520, 11)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there were 3 subscription/unsubscription"){
auto required = rxu::to_vector({
on.subscribe(300, 400),
on.subscribe(500, 550),
on.subscribe(650, 800)
});
auto actual = xs.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("publish error", "[publish][error][multicast][subject][operators]"){
GIVEN("a test hot observable of longs"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
std::runtime_error ex("publish on_error");
auto xs = sc.make_hot_observable({
on.next(110, 7),
on.next(220, 3),
on.next(280, 4),
on.next(290, 1),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(410, 13),
on.next(430, 2),
on.next(450, 9),
on.next(520, 11),
on.next(560, 20),
on.error(600, ex)
});
auto res = w.make_subscriber<int>();
rx::connectable_observable<int> ys;
WHEN("subscribed and then connected"){
w.schedule_absolute(rxsc::test::created_time,
[&ys, &xs](const rxsc::schedulable&){
ys = xs.publish().as_dynamic();
});
w.schedule_absolute(rxsc::test::subscribed_time,
[&ys, &res](const rxsc::schedulable&){
ys.subscribe(res);
});
w.schedule_absolute(rxsc::test::unsubscribed_time,
[&res](const rxsc::schedulable&){
res.unsubscribe();
});
{
rx::composite_subscription connection;
w.schedule_absolute(300,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(400,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(500,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(800,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
w.start();
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(520, 11),
on.next(560, 20),
on.error(600, ex)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there were 3 subscription/unsubscription"){
auto required = rxu::to_vector({
on.subscribe(300, 400),
on.subscribe(500, 600)
});
auto actual = xs.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("publish basic with initial value", "[publish][multicast][behavior][operators]"){
GIVEN("a test hot observable of longs"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto xs = sc.make_hot_observable({
on.next(110, 7),
on.next(220, 3),
on.next(280, 4),
on.next(290, 1),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(410, 13),
on.next(430, 2),
on.next(450, 9),
on.next(520, 11),
on.next(560, 20),
on.completed(600)
});
auto res = w.make_subscriber<int>();
rx::connectable_observable<int> ys;
WHEN("subscribed and then connected"){
w.schedule_absolute(rxsc::test::created_time,
[&ys, &xs](const rxsc::schedulable&){
ys = xs.publish(1979).as_dynamic();
});
w.schedule_absolute(rxsc::test::subscribed_time,
[&ys, &res](const rxsc::schedulable&){
ys.subscribe(res);
});
w.schedule_absolute(rxsc::test::unsubscribed_time,
[&res](const rxsc::schedulable&){
res.unsubscribe();
});
{
rx::composite_subscription connection;
w.schedule_absolute(300,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(400,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(500,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(550,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(650,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(800,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
w.start();
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(200, 1979),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(520, 11)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there were 3 subscription/unsubscription"){
auto required = rxu::to_vector({
on.subscribe(300, 400),
on.subscribe(500, 550),
on.subscribe(650, 800)
});
auto actual = xs.subscriptions();
REQUIRE(required == actual);
}
}
}
}
| 18,192 | 5,469 |
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "AIModulePrivate.h"
#include "AI/Navigation/NavigationSystem.h"
#include "AI/Navigation/NavAgentInterface.h"
#include "EnvironmentQuery/Contexts/EnvQueryContext_Querier.h"
#include "EnvironmentQuery/Items/EnvQueryItemType_VectorBase.h"
#include "EnvironmentQuery/Tests/EnvQueryTest_Pathfinding.h"
#define LOCTEXT_NAMESPACE "EnvQueryGenerator"
UEnvQueryTest_Pathfinding::UEnvQueryTest_Pathfinding(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
Context = UEnvQueryContext_Querier::StaticClass();
Cost = EEnvTestCost::High;
ValidItemType = UEnvQueryItemType_VectorBase::StaticClass();
TestMode = EEnvTestPathfinding::PathExist;
PathFromContext.DefaultValue = true;
SkipUnreachable.DefaultValue = true;
FloatValueMin.DefaultValue = 1000.0f;
FloatValueMax.DefaultValue = 1000.0f;
SetWorkOnFloatValues(TestMode != EEnvTestPathfinding::PathExist);
}
void UEnvQueryTest_Pathfinding::RunTest(FEnvQueryInstance& QueryInstance) const
{
UObject* QueryOwner = QueryInstance.Owner.Get();
BoolValue.BindData(QueryOwner, QueryInstance.QueryID);
PathFromContext.BindData(QueryOwner, QueryInstance.QueryID);
SkipUnreachable.BindData(QueryOwner, QueryInstance.QueryID);
FloatValueMin.BindData(QueryOwner, QueryInstance.QueryID);
FloatValueMax.BindData(QueryOwner, QueryInstance.QueryID);
bool bWantsPath = BoolValue.GetValue();
bool bPathToItem = PathFromContext.GetValue();
bool bDiscardFailed = SkipUnreachable.GetValue();
float MinThresholdValue = FloatValueMin.GetValue();
float MaxThresholdValue = FloatValueMax.GetValue();
UNavigationSystem* NavSys = QueryInstance.World->GetNavigationSystem();
if (NavSys == nullptr)
{
return;
}
ANavigationData* NavData = FindNavigationData(*NavSys, QueryOwner);
if (NavData == nullptr)
{
return;
}
TArray<FVector> ContextLocations;
if (!QueryInstance.PrepareContext(Context, ContextLocations))
{
return;
}
EPathFindingMode::Type PFMode(EPathFindingMode::Regular);
if (GetWorkOnFloatValues())
{
FFindPathSignature FindPathFunc;
FindPathFunc.BindUObject(this, TestMode == EEnvTestPathfinding::PathLength ?
(bPathToItem ? &UEnvQueryTest_Pathfinding::FindPathLengthTo : &UEnvQueryTest_Pathfinding::FindPathLengthFrom) :
(bPathToItem ? &UEnvQueryTest_Pathfinding::FindPathCostTo : &UEnvQueryTest_Pathfinding::FindPathCostFrom) );
NavData->BeginBatchQuery();
for (FEnvQueryInstance::ItemIterator It(this, QueryInstance); It; ++It)
{
const FVector ItemLocation = GetItemLocation(QueryInstance, It.GetIndex());
for (int32 ContextIndex = 0; ContextIndex < ContextLocations.Num(); ContextIndex++)
{
const float PathValue = FindPathFunc.Execute(ItemLocation, ContextLocations[ContextIndex], PFMode, *NavData, *NavSys, QueryOwner);
It.SetScore(TestPurpose, FilterType, PathValue, MinThresholdValue, MaxThresholdValue);
if (bDiscardFailed && PathValue >= BIG_NUMBER)
{
It.ForceItemState(EEnvItemStatus::Failed);
}
}
}
NavData->FinishBatchQuery();
}
else
{
NavData->BeginBatchQuery();
if (bPathToItem)
{
for (FEnvQueryInstance::ItemIterator It(this, QueryInstance); It; ++It)
{
const FVector ItemLocation = GetItemLocation(QueryInstance, It.GetIndex());
for (int32 ContextIndex = 0; ContextIndex < ContextLocations.Num(); ContextIndex++)
{
const bool bFoundPath = TestPathTo(ItemLocation, ContextLocations[ContextIndex], PFMode, *NavData, *NavSys, QueryOwner);
It.SetScore(TestPurpose, FilterType, bFoundPath, bWantsPath);
}
}
}
else
{
for (FEnvQueryInstance::ItemIterator It(this, QueryInstance); It; ++It)
{
const FVector ItemLocation = GetItemLocation(QueryInstance, It.GetIndex());
for (int32 ContextIndex = 0; ContextIndex < ContextLocations.Num(); ContextIndex++)
{
const bool bFoundPath = TestPathFrom(ItemLocation, ContextLocations[ContextIndex], PFMode, *NavData, *NavSys, QueryOwner);
It.SetScore(TestPurpose, FilterType, bFoundPath, bWantsPath);
}
}
}
NavData->FinishBatchQuery();
}
}
FText UEnvQueryTest_Pathfinding::GetDescriptionTitle() const
{
FString ModeDesc[] = { TEXT("PathExist"), TEXT("PathCost"), TEXT("PathLength") };
FString DirectionDesc = PathFromContext.IsDynamic() ?
FString::Printf(TEXT("%s, direction: %s"), *UEnvQueryTypes::DescribeContext(Context).ToString(), *PathFromContext.ToString()) :
FString::Printf(TEXT("%s %s"), PathFromContext.DefaultValue ? TEXT("from") : TEXT("to"), *UEnvQueryTypes::DescribeContext(Context).ToString());
return FText::FromString(FString::Printf(TEXT("%s: %s"), *ModeDesc[TestMode], *DirectionDesc));
}
FText UEnvQueryTest_Pathfinding::GetDescriptionDetails() const
{
FText DiscardDesc = LOCTEXT("DiscardUnreachable", "discard unreachable");
FText Desc2;
if (SkipUnreachable.IsDynamic())
{
Desc2 = FText::Format(FText::FromString("{0}: {1}"), DiscardDesc, FText::FromString(SkipUnreachable.ToString()));
}
else if (SkipUnreachable.DefaultValue)
{
Desc2 = DiscardDesc;
}
FText TestParamDesc = GetWorkOnFloatValues() ? DescribeFloatTestParams() : DescribeBoolTestParams("existing path");
if (!Desc2.IsEmpty())
{
return FText::Format(FText::FromString("{0}\n{1}"), Desc2, TestParamDesc);
}
return TestParamDesc;
}
#if WITH_EDITOR
void UEnvQueryTest_Pathfinding::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (PropertyChangedEvent.Property && PropertyChangedEvent.Property->GetFName() == GET_MEMBER_NAME_CHECKED(UEnvQueryTest_Pathfinding,TestMode))
{
SetWorkOnFloatValues(TestMode != EEnvTestPathfinding::PathExist);
}
}
#endif
void UEnvQueryTest_Pathfinding::PostLoad()
{
Super::PostLoad();
SetWorkOnFloatValues(TestMode != EEnvTestPathfinding::PathExist);
}
bool UEnvQueryTest_Pathfinding::TestPathFrom(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ItemPos, ContextPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
const bool bPathExists = NavSys.TestPathSync(Query, Mode);
return bPathExists;
}
bool UEnvQueryTest_Pathfinding::TestPathTo(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ContextPos, ItemPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
const bool bPathExists = NavSys.TestPathSync(Query, Mode);
return bPathExists;
}
float UEnvQueryTest_Pathfinding::FindPathCostFrom(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ItemPos, ContextPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetCost() : BIG_NUMBER;
}
float UEnvQueryTest_Pathfinding::FindPathCostTo(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ContextPos, ItemPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetCost() : BIG_NUMBER;
}
float UEnvQueryTest_Pathfinding::FindPathLengthFrom(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ItemPos, ContextPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetLength() : BIG_NUMBER;
}
float UEnvQueryTest_Pathfinding::FindPathLengthTo(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ContextPos, ItemPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetLength() : BIG_NUMBER;
}
ANavigationData* UEnvQueryTest_Pathfinding::FindNavigationData(UNavigationSystem& NavSys, UObject* Owner) const
{
INavAgentInterface* NavAgent = Cast<INavAgentInterface>(Owner);
if (NavAgent)
{
return NavSys.GetNavDataForProps(NavAgent->GetNavAgentPropertiesRef());
}
return NavSys.GetMainNavData(FNavigationSystem::DontCreate);
}
#undef LOCTEXT_NAMESPACE
| 9,256 | 3,125 |
AAClip* create_aa_clip()
{
AAClip *clip = malloc(sizeof(AAClip));
clip->bounds.setEmpty();
clip->run_head = nullptr;
return clip;
}
AAClip* create_aa_clip(const AAClip& src)
{
AAClip* clip = malloc(sizeof(AAClip));
clip->run_head = nullptr;
*clip = src;
return clip;
}
void delete_aa_clip(AAClip* clip)
{
free_runs_aa_clip(clip);
}
| 352 | 151 |
/**
* Copyright (c) 2011 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pch.h"
#include "db/pipeline/accumulator.h"
#include "db/jsobj.h"
#include "util/mongoutils/str.h"
namespace mongo {
using namespace mongoutils;
void Accumulator::addOperand(
const intrusive_ptr<Expression> &pExpression) {
uassert(15943, str::stream() << "group accumulator " <<
getOpName() << " only accepts one operand",
vpOperand.size() < 1);
ExpressionNary::addOperand(pExpression);
}
Accumulator::Accumulator():
ExpressionNary() {
}
void Accumulator::opToBson(BSONObjBuilder *pBuilder, StringData opName,
StringData fieldName, bool requireExpression) const {
verify(vpOperand.size() == 1);
BSONObjBuilder builder;
vpOperand[0]->addToBsonObj(&builder, opName, requireExpression);
pBuilder->append(fieldName, builder.done());
}
void Accumulator::addToBsonObj(BSONObjBuilder *pBuilder,
StringData fieldName,
bool requireExpression) const {
opToBson(pBuilder, getOpName(), fieldName, requireExpression);
}
void Accumulator::addToBsonArray(BSONArrayBuilder *pBuilder) const {
verify(false); // these can't appear in arrays
}
void agg_framework_reservedErrors() {
uassert(16030, "reserved error", false);
uassert(16031, "reserved error", false);
uassert(16032, "reserved error", false);
uassert(16033, "reserved error", false);
uassert(16036, "reserved error", false);
uassert(16037, "reserved error", false);
uassert(16038, "reserved error", false);
uassert(16039, "reserved error", false);
uassert(16040, "reserved error", false);
uassert(16041, "reserved error", false);
uassert(16042, "reserved error", false);
uassert(16043, "reserved error", false);
uassert(16044, "reserved error", false);
uassert(16045, "reserved error", false);
uassert(16046, "reserved error", false);
uassert(16047, "reserved error", false);
uassert(16048, "reserved error", false);
uassert(16049, "reserved error", false);
}
}
| 2,892 | 936 |
--- src/core/CLucene/util/BitSet.cpp.orig 2011-03-17 00:21:07 UTC
+++ src/core/CLucene/util/BitSet.cpp
@@ -32,6 +32,25 @@ const uint8_t BitSet::BYTE_COUNTS[256] =
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
+const uint8_t BitSet::BYTE_OFFSETS[256] = {
+ 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
+
+
BitSet::BitSet( const BitSet& copy ) :
_size( copy._size ),
_count(-1)
@@ -180,19 +199,32 @@ BitSet* BitSet::clone() const {
return factor * (4 + (8+40)*count()) < size();
}
- int32_t BitSet::nextSetBit(int32_t fromIndex) const {
+ int32_t BitSet::nextSetBit(int32_t fromIndex) const
+ {
if (fromIndex < 0)
_CLTHROWT(CL_ERR_IndexOutOfBounds, _T("fromIndex < 0"));
if (fromIndex >= _size)
return -1;
- while (true) {
- if ((bits[fromIndex >> 3] & (1 << (fromIndex & 7))) != 0)
- return fromIndex;
- if (++fromIndex == _size)
- return -1;
+ int _max = ( _size+7 ) >> 3;
+
+ unsigned int i = (int)( fromIndex>>3 );
+ unsigned int subIndex = fromIndex & 0x7; // index within the byte
+ uint8_t byte = bits[i] >> subIndex; // skip all the bits to the right of index
+
+ if ( byte != 0 )
+ {
+ return ( ( i<<3 ) + subIndex + BYTE_OFFSETS[ byte ] );
+ }
+
+ while( ++i < _max )
+ {
+ byte = bits[i];
+ if ( byte != 0 )
+ return ( ( i<<3 ) + BYTE_OFFSETS[ byte ] );
}
+ return -1;
}
CL_NS_END
| 2,407 | 1,495 |
// Copyright 2012 the V8 project authors. 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 Google 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 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.
#include <iostream> // NOLINT(readability/streams)
#include "src/v8.h"
#include "src/assembler-inl.h"
#include "src/base/utils/random-number-generator.h"
#include "src/disassembler.h"
#include "src/heap/factory.h"
#include "src/macro-assembler.h"
#include "src/mips/macro-assembler-mips.h"
#include "src/simulator.h"
#include "test/cctest/cctest.h"
namespace v8 {
namespace internal {
// Define these function prototypes to match JSEntryFunction in execution.cc.
// TODO(mips): Refine these signatures per test case.
typedef Object*(F1)(int x, int p1, int p2, int p3, int p4);
typedef Object*(F2)(int x, int y, int p2, int p3, int p4);
typedef Object*(F3)(void* p, int p1, int p2, int p3, int p4);
typedef Object*(F4)(void* p0, void* p1, int p2, int p3, int p4);
#define __ assm.
TEST(MIPS0) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// Addition.
__ addu(v0, a0, a1);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int res = reinterpret_cast<int>(f.Call(0xAB0, 0xC, 0, 0, 0));
CHECK_EQ(static_cast<int32_t>(0xABC), res);
}
TEST(MIPS1) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
__ mov(a1, a0);
__ li(v0, 0);
__ b(&C);
__ nop();
__ bind(&L);
__ addu(v0, v0, a1);
__ addiu(a1, a1, -1);
__ bind(&C);
__ xori(v1, a1, 0);
__ Branch(&L, ne, v1, Operand(0));
__ nop();
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F1>::FromCode(*code);
int res = reinterpret_cast<int>(f.Call(50, 0, 0, 0, 0));
CHECK_EQ(1275, res);
}
TEST(MIPS2) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label exit, error;
// ----- Test all instructions.
// Test lui, ori, and addiu, used in the li pseudo-instruction.
// This way we can then safely load registers with chosen values.
__ ori(t0, zero_reg, 0);
__ lui(t0, 0x1234);
__ ori(t0, t0, 0);
__ ori(t0, t0, 0x0F0F);
__ ori(t0, t0, 0xF0F0);
__ addiu(t1, t0, 1);
__ addiu(t2, t1, -0x10);
// Load values in temporary registers.
__ li(t0, 0x00000004);
__ li(t1, 0x00001234);
__ li(t2, 0x12345678);
__ li(t3, 0x7FFFFFFF);
__ li(t4, 0xFFFFFFFC);
__ li(t5, 0xFFFFEDCC);
__ li(t6, 0xEDCBA988);
__ li(t7, 0x80000000);
// SPECIAL class.
__ srl(v0, t2, 8); // 0x00123456
__ sll(v0, v0, 11); // 0x91A2B000
__ sra(v0, v0, 3); // 0xF2345600
__ srav(v0, v0, t0); // 0xFF234560
__ sllv(v0, v0, t0); // 0xF2345600
__ srlv(v0, v0, t0); // 0x0F234560
__ Branch(&error, ne, v0, Operand(0x0F234560));
__ nop();
__ addu(v0, t0, t1); // 0x00001238
__ subu(v0, v0, t0); // 0x00001234
__ Branch(&error, ne, v0, Operand(0x00001234));
__ nop();
__ addu(v1, t3, t0);
__ Branch(&error, ne, v1, Operand(0x80000003));
__ nop();
__ subu(v1, t7, t0); // 0x7FFFFFFC
__ Branch(&error, ne, v1, Operand(0x7FFFFFFC));
__ nop();
__ and_(v0, t1, t2); // 0x00001230
__ or_(v0, v0, t1); // 0x00001234
__ xor_(v0, v0, t2); // 0x1234444C
__ nor(v0, v0, t2); // 0xEDCBA987
__ Branch(&error, ne, v0, Operand(0xEDCBA983));
__ nop();
__ slt(v0, t7, t3);
__ Branch(&error, ne, v0, Operand(0x1));
__ nop();
__ sltu(v0, t7, t3);
__ Branch(&error, ne, v0, Operand(zero_reg));
__ nop();
// End of SPECIAL class.
__ addiu(v0, zero_reg, 0x7421); // 0x00007421
__ addiu(v0, v0, -0x1); // 0x00007420
__ addiu(v0, v0, -0x20); // 0x00007400
__ Branch(&error, ne, v0, Operand(0x00007400));
__ nop();
__ addiu(v1, t3, 0x1); // 0x80000000
__ Branch(&error, ne, v1, Operand(0x80000000));
__ nop();
__ slti(v0, t1, 0x00002000); // 0x1
__ slti(v0, v0, 0xFFFF8000); // 0x0
__ Branch(&error, ne, v0, Operand(zero_reg));
__ nop();
__ sltiu(v0, t1, 0x00002000); // 0x1
__ sltiu(v0, v0, 0x00008000); // 0x1
__ Branch(&error, ne, v0, Operand(0x1));
__ nop();
__ andi(v0, t1, 0xF0F0); // 0x00001030
__ ori(v0, v0, 0x8A00); // 0x00009A30
__ xori(v0, v0, 0x83CC); // 0x000019FC
__ Branch(&error, ne, v0, Operand(0x000019FC));
__ nop();
__ lui(v1, 0x8123); // 0x81230000
__ Branch(&error, ne, v1, Operand(0x81230000));
__ nop();
// Bit twiddling instructions & conditional moves.
// Uses t0-t7 as set above.
__ Clz(v0, t0); // 29
__ Clz(v1, t1); // 19
__ addu(v0, v0, v1); // 48
__ Clz(v1, t2); // 3
__ addu(v0, v0, v1); // 51
__ Clz(v1, t7); // 0
__ addu(v0, v0, v1); // 51
__ Branch(&error, ne, v0, Operand(51));
__ Movn(a0, t3, t0); // Move a0<-t3 (t0 is NOT 0).
__ Ins(a0, t1, 12, 8); // 0x7FF34FFF
__ Branch(&error, ne, a0, Operand(0x7FF34FFF));
__ Movz(a0, t6, t7); // a0 not updated (t7 is NOT 0).
__ Ext(a1, a0, 8, 12); // 0x34F
__ Branch(&error, ne, a1, Operand(0x34F));
__ Movz(a0, t6, v1); // a0<-t6, v0 is 0, from 8 instr back.
__ Branch(&error, ne, a0, Operand(t6));
// Everything was correctly executed. Load the expected result.
__ li(v0, 0x31415926);
__ b(&exit);
__ nop();
__ bind(&error);
// Got an error. Return a wrong result.
__ li(v0, 666);
__ bind(&exit);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int res = reinterpret_cast<int>(f.Call(0xAB0, 0xC, 0, 0, 0));
CHECK_EQ(static_cast<int32_t>(0x31415926), res);
}
TEST(MIPS3) {
// Test floating point instructions.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
double c;
double d;
double e;
double f;
double g;
double h;
double i;
float fa;
float fb;
float fc;
float fd;
float fe;
float ff;
float fg;
} T;
T t;
// Create a function that accepts &t, and loads, manipulates, and stores
// the doubles t.a ... t.f.
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
// Double precision floating point instructions.
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
__ add_d(f8, f4, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(T, c))); // c = a + b.
__ mov_d(f10, f8); // c
__ neg_d(f12, f6); // -b
__ sub_d(f10, f10, f12);
__ Sdc1(f10, MemOperand(a0, offsetof(T, d))); // d = c - (-b).
__ Sdc1(f4, MemOperand(a0, offsetof(T, b))); // b = a.
__ li(t0, 120);
__ mtc1(t0, f14);
__ cvt_d_w(f14, f14); // f14 = 120.0.
__ mul_d(f10, f10, f14);
__ Sdc1(f10, MemOperand(a0, offsetof(T, e))); // e = d * 120 = 1.8066e16.
__ div_d(f12, f10, f4);
__ Sdc1(f12, MemOperand(a0, offsetof(T, f))); // f = e / a = 120.44.
__ sqrt_d(f14, f12);
__ Sdc1(f14, MemOperand(a0, offsetof(T, g)));
// g = sqrt(f) = 10.97451593465515908537
if (IsMipsArchVariant(kMips32r2)) {
__ Ldc1(f4, MemOperand(a0, offsetof(T, h)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, i)));
__ madd_d(f14, f6, f4, f6);
__ Sdc1(f14, MemOperand(a0, offsetof(T, h)));
}
// Single precision floating point instructions.
__ lwc1(f4, MemOperand(a0, offsetof(T, fa)) );
__ lwc1(f6, MemOperand(a0, offsetof(T, fb)) );
__ add_s(f8, f4, f6);
__ swc1(f8, MemOperand(a0, offsetof(T, fc)) ); // fc = fa + fb.
__ neg_s(f10, f6); // -fb
__ sub_s(f10, f8, f10);
__ swc1(f10, MemOperand(a0, offsetof(T, fd)) ); // fd = fc - (-fb).
__ swc1(f4, MemOperand(a0, offsetof(T, fb)) ); // fb = fa.
__ li(t0, 120);
__ mtc1(t0, f14);
__ cvt_s_w(f14, f14); // f14 = 120.0.
__ mul_s(f10, f10, f14);
__ swc1(f10, MemOperand(a0, offsetof(T, fe)) ); // fe = fd * 120
__ div_s(f12, f10, f4);
__ swc1(f12, MemOperand(a0, offsetof(T, ff)) ); // ff = fe / fa
__ sqrt_s(f14, f12);
__ swc1(f14, MemOperand(a0, offsetof(T, fg)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
// Double test values.
t.a = 1.5e14;
t.b = 2.75e11;
t.c = 0.0;
t.d = 0.0;
t.e = 0.0;
t.f = 0.0;
t.h = 1.5;
t.i = 2.75;
// Single test values.
t.fa = 1.5e6;
t.fb = 2.75e4;
t.fc = 0.0;
t.fd = 0.0;
t.fe = 0.0;
t.ff = 0.0;
f.Call(&t, 0, 0, 0, 0);
// Expected double results.
CHECK_EQ(1.5e14, t.a);
CHECK_EQ(1.5e14, t.b);
CHECK_EQ(1.50275e14, t.c);
CHECK_EQ(1.50550e14, t.d);
CHECK_EQ(1.8066e16, t.e);
CHECK_EQ(120.44, t.f);
CHECK_EQ(10.97451593465515908537, t.g);
if (IsMipsArchVariant(kMips32r2)) {
CHECK_EQ(6.875, t.h);
}
// Expected single results.
CHECK_EQ(1.5e6, t.fa);
CHECK_EQ(1.5e6, t.fb);
CHECK_EQ(1.5275e06, t.fc);
CHECK_EQ(1.5550e06, t.fd);
CHECK_EQ(1.866e08, t.fe);
CHECK_EQ(124.40000152587890625, t.ff);
CHECK_EQ(11.1534748077392578125, t.fg);
}
TEST(MIPS4) {
// Exchange between GP anf FP registers is done through memory
// on FPXX compiled binaries and architectures that do not support
// MTHC1 and MTFC1. If this is the case, skipping this test.
if (IsFpxxMode() &&
(IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson))) {
return;
}
// Test moves between floating point and integer registers.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
double c;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
// Swap f4 and f6, by using four integer registers, t0-t3.
if (IsFp32Mode()) {
__ mfc1(t0, f4);
__ mfc1(t1, f5);
__ mfc1(t2, f6);
__ mfc1(t3, f7);
__ mtc1(t0, f6);
__ mtc1(t1, f7);
__ mtc1(t2, f4);
__ mtc1(t3, f5);
} else {
CHECK(!IsMipsArchVariant(kMips32r1) && !IsMipsArchVariant(kLoongson));
DCHECK(IsFp64Mode() || IsFpxxMode());
__ mfc1(t0, f4);
__ mfhc1(t1, f4);
__ mfc1(t2, f6);
__ mfhc1(t3, f6);
__ mtc1(t0, f6);
__ mthc1(t1, f6);
__ mtc1(t2, f4);
__ mthc1(t3, f4);
}
// Store the swapped f4 and f5 back to memory.
__ Sdc1(f4, MemOperand(a0, offsetof(T, a)));
__ Sdc1(f6, MemOperand(a0, offsetof(T, c)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 1.5e22;
t.b = 2.75e11;
t.c = 17.17;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(2.75e11, t.a);
CHECK_EQ(2.75e11, t.b);
CHECK_EQ(1.5e22, t.c);
}
TEST(MIPS5) {
// Test conversions between doubles and integers.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
int i;
int j;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
// Load all structure elements to registers.
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
__ lw(t0, MemOperand(a0, offsetof(T, i)) );
__ lw(t1, MemOperand(a0, offsetof(T, j)) );
// Convert double in f4 to int in element i.
__ cvt_w_d(f8, f4);
__ mfc1(t2, f8);
__ sw(t2, MemOperand(a0, offsetof(T, i)) );
// Convert double in f6 to int in element j.
__ cvt_w_d(f10, f6);
__ mfc1(t3, f10);
__ sw(t3, MemOperand(a0, offsetof(T, j)) );
// Convert int in original i (t0) to double in a.
__ mtc1(t0, f12);
__ cvt_d_w(f0, f12);
__ Sdc1(f0, MemOperand(a0, offsetof(T, a)));
// Convert int in original j (t1) to double in b.
__ mtc1(t1, f14);
__ cvt_d_w(f2, f14);
__ Sdc1(f2, MemOperand(a0, offsetof(T, b)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 1.5e4;
t.b = 2.75e8;
t.i = 12345678;
t.j = -100000;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(12345678.0, t.a);
CHECK_EQ(-100000.0, t.b);
CHECK_EQ(15000, t.i);
CHECK_EQ(275000000, t.j);
}
TEST(MIPS6) {
// Test simple memory loads and stores.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint32_t ui;
int32_t si;
int32_t r1;
int32_t r2;
int32_t r3;
int32_t r4;
int32_t r5;
int32_t r6;
} T;
T t;
Assembler assm(AssemblerOptions{}, nullptr, 0);
Label L, C;
// Basic word load/store.
__ lw(t0, MemOperand(a0, offsetof(T, ui)) );
__ sw(t0, MemOperand(a0, offsetof(T, r1)) );
// lh with positive data.
__ lh(t1, MemOperand(a0, offsetof(T, ui)) );
__ sw(t1, MemOperand(a0, offsetof(T, r2)) );
// lh with negative data.
__ lh(t2, MemOperand(a0, offsetof(T, si)) );
__ sw(t2, MemOperand(a0, offsetof(T, r3)) );
// lhu with negative data.
__ lhu(t3, MemOperand(a0, offsetof(T, si)) );
__ sw(t3, MemOperand(a0, offsetof(T, r4)) );
// lb with negative data.
__ lb(t4, MemOperand(a0, offsetof(T, si)) );
__ sw(t4, MemOperand(a0, offsetof(T, r5)) );
// sh writes only 1/2 of word.
__ lui(t5, 0x3333);
__ ori(t5, t5, 0x3333);
__ sw(t5, MemOperand(a0, offsetof(T, r6)) );
__ lhu(t5, MemOperand(a0, offsetof(T, si)) );
__ sh(t5, MemOperand(a0, offsetof(T, r6)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.ui = 0x11223344;
t.si = 0x99AABBCC;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.r1);
#if __BYTE_ORDER == __LITTLE_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x3344), t.r2);
CHECK_EQ(static_cast<int32_t>(0xFFFFBBCC), t.r3);
CHECK_EQ(static_cast<int32_t>(0x0000BBCC), t.r4);
CHECK_EQ(static_cast<int32_t>(0xFFFFFFCC), t.r5);
CHECK_EQ(static_cast<int32_t>(0x3333BBCC), t.r6);
#elif __BYTE_ORDER == __BIG_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x1122), t.r2);
CHECK_EQ(static_cast<int32_t>(0xFFFF99AA), t.r3);
CHECK_EQ(static_cast<int32_t>(0x000099AA), t.r4);
CHECK_EQ(static_cast<int32_t>(0xFFFFFF99), t.r5);
CHECK_EQ(static_cast<int32_t>(0x99AA3333), t.r6);
#else
#error Unknown endianness
#endif
}
TEST(MIPS7) {
// Test floating point compare and branch instructions.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
double c;
double d;
double e;
double f;
int32_t result;
} T;
T t;
// Create a function that accepts &t, and loads, manipulates, and stores
// the doubles t.a ... t.f.
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label neither_is_nan, less_than, outa_here;
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
if (!IsMipsArchVariant(kMips32r6)) {
__ c(UN, D, f4, f6);
__ bc1f(&neither_is_nan);
} else {
__ cmp(UN, L, f2, f4, f6);
__ bc1eqz(&neither_is_nan, f2);
}
__ nop();
__ sw(zero_reg, MemOperand(a0, offsetof(T, result)) );
__ Branch(&outa_here);
__ bind(&neither_is_nan);
if (IsMipsArchVariant(kLoongson)) {
__ c(OLT, D, f6, f4);
__ bc1t(&less_than);
} else if (IsMipsArchVariant(kMips32r6)) {
__ cmp(OLT, L, f2, f6, f4);
__ bc1nez(&less_than, f2);
} else {
__ c(OLT, D, f6, f4, 2);
__ bc1t(&less_than, 2);
}
__ nop();
__ sw(zero_reg, MemOperand(a0, offsetof(T, result)) );
__ Branch(&outa_here);
__ bind(&less_than);
__ Addu(t0, zero_reg, Operand(1));
__ sw(t0, MemOperand(a0, offsetof(T, result)) ); // Set true.
// This test-case should have additional tests.
__ bind(&outa_here);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 1.5e14;
t.b = 2.75e11;
t.c = 2.0;
t.d = -4.0;
t.e = 0.0;
t.f = 0.0;
t.result = 0;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(1.5e14, t.a);
CHECK_EQ(2.75e11, t.b);
CHECK_EQ(1, t.result);
}
TEST(MIPS8) {
// Test ROTR and ROTRV instructions.
if (IsMipsArchVariant(kMips32r2)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t input;
int32_t result_rotr_4;
int32_t result_rotr_8;
int32_t result_rotr_12;
int32_t result_rotr_16;
int32_t result_rotr_20;
int32_t result_rotr_24;
int32_t result_rotr_28;
int32_t result_rotrv_4;
int32_t result_rotrv_8;
int32_t result_rotrv_12;
int32_t result_rotrv_16;
int32_t result_rotrv_20;
int32_t result_rotrv_24;
int32_t result_rotrv_28;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// Basic word load.
__ lw(t0, MemOperand(a0, offsetof(T, input)) );
// ROTR instruction (called through the Ror macro).
__ Ror(t1, t0, 0x0004);
__ Ror(t2, t0, 0x0008);
__ Ror(t3, t0, 0x000C);
__ Ror(t4, t0, 0x0010);
__ Ror(t5, t0, 0x0014);
__ Ror(t6, t0, 0x0018);
__ Ror(t7, t0, 0x001C);
// Basic word store.
__ sw(t1, MemOperand(a0, offsetof(T, result_rotr_4)) );
__ sw(t2, MemOperand(a0, offsetof(T, result_rotr_8)) );
__ sw(t3, MemOperand(a0, offsetof(T, result_rotr_12)) );
__ sw(t4, MemOperand(a0, offsetof(T, result_rotr_16)) );
__ sw(t5, MemOperand(a0, offsetof(T, result_rotr_20)) );
__ sw(t6, MemOperand(a0, offsetof(T, result_rotr_24)) );
__ sw(t7, MemOperand(a0, offsetof(T, result_rotr_28)) );
// ROTRV instruction (called through the Ror macro).
__ li(t7, 0x0004);
__ Ror(t1, t0, t7);
__ li(t7, 0x0008);
__ Ror(t2, t0, t7);
__ li(t7, 0x000C);
__ Ror(t3, t0, t7);
__ li(t7, 0x0010);
__ Ror(t4, t0, t7);
__ li(t7, 0x0014);
__ Ror(t5, t0, t7);
__ li(t7, 0x0018);
__ Ror(t6, t0, t7);
__ li(t7, 0x001C);
__ Ror(t7, t0, t7);
// Basic word store.
__ sw(t1, MemOperand(a0, offsetof(T, result_rotrv_4)) );
__ sw(t2, MemOperand(a0, offsetof(T, result_rotrv_8)) );
__ sw(t3, MemOperand(a0, offsetof(T, result_rotrv_12)) );
__ sw(t4, MemOperand(a0, offsetof(T, result_rotrv_16)) );
__ sw(t5, MemOperand(a0, offsetof(T, result_rotrv_20)) );
__ sw(t6, MemOperand(a0, offsetof(T, result_rotrv_24)) );
__ sw(t7, MemOperand(a0, offsetof(T, result_rotrv_28)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.input = 0x12345678;
f.Call(&t, 0x0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x81234567), t.result_rotr_4);
CHECK_EQ(static_cast<int32_t>(0x78123456), t.result_rotr_8);
CHECK_EQ(static_cast<int32_t>(0x67812345), t.result_rotr_12);
CHECK_EQ(static_cast<int32_t>(0x56781234), t.result_rotr_16);
CHECK_EQ(static_cast<int32_t>(0x45678123), t.result_rotr_20);
CHECK_EQ(static_cast<int32_t>(0x34567812), t.result_rotr_24);
CHECK_EQ(static_cast<int32_t>(0x23456781), t.result_rotr_28);
CHECK_EQ(static_cast<int32_t>(0x81234567), t.result_rotrv_4);
CHECK_EQ(static_cast<int32_t>(0x78123456), t.result_rotrv_8);
CHECK_EQ(static_cast<int32_t>(0x67812345), t.result_rotrv_12);
CHECK_EQ(static_cast<int32_t>(0x56781234), t.result_rotrv_16);
CHECK_EQ(static_cast<int32_t>(0x45678123), t.result_rotrv_20);
CHECK_EQ(static_cast<int32_t>(0x34567812), t.result_rotrv_24);
CHECK_EQ(static_cast<int32_t>(0x23456781), t.result_rotrv_28);
}
}
TEST(MIPS9) {
// Test BRANCH improvements.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label exit, exit2, exit3;
__ Branch(&exit, ge, a0, Operand(zero_reg));
__ Branch(&exit2, ge, a0, Operand(0x00001FFF));
__ Branch(&exit3, ge, a0, Operand(0x0001FFFF));
__ bind(&exit);
__ bind(&exit2);
__ bind(&exit3);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
}
TEST(MIPS10) {
// Test conversions between doubles and words.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
int32_t dbl_mant;
int32_t dbl_exp;
int32_t word;
int32_t b_word;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
if (IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson)) return;
// Load all structure elements to registers.
// (f0, f1) = a (fp32), f0 = a (fp64)
__ Ldc1(f0, MemOperand(a0, offsetof(T, a)));
__ mfc1(t0, f0); // t0 = f0(31..0)
__ mfhc1(t1, f0); // t1 = sign_extend(f0(63..32))
__ sw(t0, MemOperand(a0, offsetof(T, dbl_mant))); // dbl_mant = t0
__ sw(t1, MemOperand(a0, offsetof(T, dbl_exp))); // dbl_exp = t1
// Convert double in f0 to word, save hi/lo parts.
__ cvt_w_d(f0, f0); // a_word = (word)a
__ mfc1(t0, f0); // f0 has a 32-bits word. t0 = a_word
__ sw(t0, MemOperand(a0, offsetof(T, word))); // word = a_word
// Convert the b word to double b.
__ lw(t0, MemOperand(a0, offsetof(T, b_word)));
__ mtc1(t0, f8); // f8 has a 32-bits word.
__ cvt_d_w(f10, f8);
__ Sdc1(f10, MemOperand(a0, offsetof(T, b)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 2.147483646e+09; // 0x7FFFFFFE -> 0xFF80000041DFFFFF as double.
t.b_word = 0x0FF00FF0; // 0x0FF00FF0 -> 0x as double.
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x41DFFFFF), t.dbl_exp);
CHECK_EQ(static_cast<int32_t>(0xFF800000), t.dbl_mant);
CHECK_EQ(static_cast<int32_t>(0x7FFFFFFE), t.word);
// 0x0FF00FF0 -> 2.6739096+e08
CHECK_EQ(2.6739096e08, t.b);
}
TEST(MIPS11) {
// Do not run test on MIPS32r6, as these instructions are removed.
if (IsMipsArchVariant(kMips32r6)) return;
// Test LWL, LWR, SWL and SWR instructions.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t reg_init;
int32_t mem_init;
int32_t lwl_0;
int32_t lwl_1;
int32_t lwl_2;
int32_t lwl_3;
int32_t lwr_0;
int32_t lwr_1;
int32_t lwr_2;
int32_t lwr_3;
int32_t swl_0;
int32_t swl_1;
int32_t swl_2;
int32_t swl_3;
int32_t swr_0;
int32_t swr_1;
int32_t swr_2;
int32_t swr_3;
} T;
T t;
Assembler assm(AssemblerOptions{}, nullptr, 0);
// Test all combinations of LWL and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, lwl_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t1, MemOperand(a0, offsetof(T, mem_init) + 1) );
__ sw(t1, MemOperand(a0, offsetof(T, lwl_1)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t2, MemOperand(a0, offsetof(T, mem_init) + 2) );
__ sw(t2, MemOperand(a0, offsetof(T, lwl_2)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t3, MemOperand(a0, offsetof(T, mem_init) + 3) );
__ sw(t3, MemOperand(a0, offsetof(T, lwl_3)) );
// Test all combinations of LWR and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, lwr_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t1, MemOperand(a0, offsetof(T, mem_init) + 1) );
__ sw(t1, MemOperand(a0, offsetof(T, lwr_1)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t2, MemOperand(a0, offsetof(T, mem_init) + 2) );
__ sw(t2, MemOperand(a0, offsetof(T, lwr_2)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t3, MemOperand(a0, offsetof(T, mem_init) + 3) );
__ sw(t3, MemOperand(a0, offsetof(T, lwr_3)) );
// Test all combinations of SWL and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, swl_0)) );
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t0, MemOperand(a0, offsetof(T, swl_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t1, MemOperand(a0, offsetof(T, swl_1)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t1, MemOperand(a0, offsetof(T, swl_1) + 1) );
__ lw(t2, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t2, MemOperand(a0, offsetof(T, swl_2)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t2, MemOperand(a0, offsetof(T, swl_2) + 2) );
__ lw(t3, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t3, MemOperand(a0, offsetof(T, swl_3)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t3, MemOperand(a0, offsetof(T, swl_3) + 3) );
// Test all combinations of SWR and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, swr_0)) );
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t0, MemOperand(a0, offsetof(T, swr_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t1, MemOperand(a0, offsetof(T, swr_1)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t1, MemOperand(a0, offsetof(T, swr_1) + 1) );
__ lw(t2, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t2, MemOperand(a0, offsetof(T, swr_2)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t2, MemOperand(a0, offsetof(T, swr_2) + 2) );
__ lw(t3, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t3, MemOperand(a0, offsetof(T, swr_3)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t3, MemOperand(a0, offsetof(T, swr_3) + 3) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.reg_init = 0xAABBCCDD;
t.mem_init = 0x11223344;
f.Call(&t, 0, 0, 0, 0);
#if __BYTE_ORDER == __LITTLE_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x44BBCCDD), t.lwl_0);
CHECK_EQ(static_cast<int32_t>(0x3344CCDD), t.lwl_1);
CHECK_EQ(static_cast<int32_t>(0x223344DD), t.lwl_2);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwl_3);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwr_0);
CHECK_EQ(static_cast<int32_t>(0xAA112233), t.lwr_1);
CHECK_EQ(static_cast<int32_t>(0xAABB1122), t.lwr_2);
CHECK_EQ(static_cast<int32_t>(0xAABBCC11), t.lwr_3);
CHECK_EQ(static_cast<int32_t>(0x112233AA), t.swl_0);
CHECK_EQ(static_cast<int32_t>(0x1122AABB), t.swl_1);
CHECK_EQ(static_cast<int32_t>(0x11AABBCC), t.swl_2);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swl_3);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swr_0);
CHECK_EQ(static_cast<int32_t>(0xBBCCDD44), t.swr_1);
CHECK_EQ(static_cast<int32_t>(0xCCDD3344), t.swr_2);
CHECK_EQ(static_cast<int32_t>(0xDD223344), t.swr_3);
#elif __BYTE_ORDER == __BIG_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwl_0);
CHECK_EQ(static_cast<int32_t>(0x223344DD), t.lwl_1);
CHECK_EQ(static_cast<int32_t>(0x3344CCDD), t.lwl_2);
CHECK_EQ(static_cast<int32_t>(0x44BBCCDD), t.lwl_3);
CHECK_EQ(static_cast<int32_t>(0xAABBCC11), t.lwr_0);
CHECK_EQ(static_cast<int32_t>(0xAABB1122), t.lwr_1);
CHECK_EQ(static_cast<int32_t>(0xAA112233), t.lwr_2);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwr_3);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swl_0);
CHECK_EQ(static_cast<int32_t>(0x11AABBCC), t.swl_1);
CHECK_EQ(static_cast<int32_t>(0x1122AABB), t.swl_2);
CHECK_EQ(static_cast<int32_t>(0x112233AA), t.swl_3);
CHECK_EQ(static_cast<int32_t>(0xDD223344), t.swr_0);
CHECK_EQ(static_cast<int32_t>(0xCCDD3344), t.swr_1);
CHECK_EQ(static_cast<int32_t>(0xBBCCDD44), t.swr_2);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swr_3);
#else
#error Unknown endianness
#endif
}
TEST(MIPS12) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t x;
int32_t y;
int32_t y1;
int32_t y2;
int32_t y3;
int32_t y4;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ mov(t6, fp); // Save frame pointer.
__ mov(fp, a0); // Access struct T by fp.
__ lw(t0, MemOperand(a0, offsetof(T, y)) );
__ lw(t3, MemOperand(a0, offsetof(T, y4)) );
__ addu(t1, t0, t3);
__ subu(t4, t0, t3);
__ nop();
__ push(t0); // These instructions disappear after opt.
__ Pop();
__ addu(t0, t0, t0);
__ nop();
__ Pop(); // These instructions disappear after opt.
__ push(t3);
__ nop();
__ push(t3); // These instructions disappear after opt.
__ pop(t3);
__ nop();
__ push(t3);
__ pop(t4);
__ nop();
__ sw(t0, MemOperand(fp, offsetof(T, y)) );
__ lw(t0, MemOperand(fp, offsetof(T, y)) );
__ nop();
__ sw(t0, MemOperand(fp, offsetof(T, y)) );
__ lw(t1, MemOperand(fp, offsetof(T, y)) );
__ nop();
__ push(t1);
__ lw(t1, MemOperand(fp, offsetof(T, y)) );
__ pop(t1);
__ nop();
__ push(t1);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t1);
__ nop();
__ push(t1);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t2);
__ nop();
__ push(t2);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t1);
__ nop();
__ push(t1);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t3);
__ nop();
__ mov(fp, t6);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.x = 1;
t.y = 2;
t.y1 = 3;
t.y2 = 4;
t.y3 = 0XBABA;
t.y4 = 0xDEDA;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(3, t.y1);
}
TEST(MIPS13) {
// Test Cvt_d_uw and Trunc_uw_d macros.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double cvt_big_out;
double cvt_small_out;
uint32_t trunc_big_out;
uint32_t trunc_small_out;
uint32_t cvt_big_in;
uint32_t cvt_small_in;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ sw(t0, MemOperand(a0, offsetof(T, cvt_small_in)));
__ Cvt_d_uw(f10, t0, f4);
__ Sdc1(f10, MemOperand(a0, offsetof(T, cvt_small_out)));
__ Trunc_uw_d(f10, f10, f4);
__ swc1(f10, MemOperand(a0, offsetof(T, trunc_small_out)));
__ sw(t0, MemOperand(a0, offsetof(T, cvt_big_in)));
__ Cvt_d_uw(f8, t0, f4);
__ Sdc1(f8, MemOperand(a0, offsetof(T, cvt_big_out)));
__ Trunc_uw_d(f8, f8, f4);
__ swc1(f8, MemOperand(a0, offsetof(T, trunc_big_out)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.cvt_big_in = 0xFFFFFFFF;
t.cvt_small_in = 333;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(t.cvt_big_out, static_cast<double>(t.cvt_big_in));
CHECK_EQ(t.cvt_small_out, static_cast<double>(t.cvt_small_in));
CHECK_EQ(static_cast<int>(t.trunc_big_out), static_cast<int>(t.cvt_big_in));
CHECK_EQ(static_cast<int>(t.trunc_small_out),
static_cast<int>(t.cvt_small_in));
}
TEST(MIPS14) {
// Test round, floor, ceil, trunc, cvt.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
#define ROUND_STRUCT_ELEMENT(x) \
uint32_t x##_isNaN2008; \
int32_t x##_up_out; \
int32_t x##_down_out; \
int32_t neg_##x##_up_out; \
int32_t neg_##x##_down_out; \
uint32_t x##_err1_out; \
uint32_t x##_err2_out; \
uint32_t x##_err3_out; \
uint32_t x##_err4_out; \
int32_t x##_invalid_result;
typedef struct {
double round_up_in;
double round_down_in;
double neg_round_up_in;
double neg_round_down_in;
double err1_in;
double err2_in;
double err3_in;
double err4_in;
ROUND_STRUCT_ELEMENT(round)
ROUND_STRUCT_ELEMENT(floor)
ROUND_STRUCT_ELEMENT(ceil)
ROUND_STRUCT_ELEMENT(trunc)
ROUND_STRUCT_ELEMENT(cvt)
} T;
T t;
#undef ROUND_STRUCT_ELEMENT
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// Save FCSR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
#define RUN_ROUND_TEST(x) \
__ cfc1(t0, FCSR); \
__ sw(t0, MemOperand(a0, offsetof(T, x##_isNaN2008))); \
__ Ldc1(f0, MemOperand(a0, offsetof(T, round_up_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, x##_up_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, round_down_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, x##_down_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, neg_round_up_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, neg_##x##_up_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, neg_round_down_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, neg_##x##_down_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err1_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err1_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err2_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err2_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err3_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err3_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err4_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err4_out))); \
__ swc1(f0, MemOperand(a0, offsetof(T, x##_invalid_result)));
RUN_ROUND_TEST(round)
RUN_ROUND_TEST(floor)
RUN_ROUND_TEST(ceil)
RUN_ROUND_TEST(trunc)
RUN_ROUND_TEST(cvt)
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.round_up_in = 123.51;
t.round_down_in = 123.49;
t.neg_round_up_in = -123.5;
t.neg_round_down_in = -123.49;
t.err1_in = 123.51;
t.err2_in = 1;
t.err3_in = static_cast<double>(1) + 0xFFFFFFFF;
t.err4_in = NAN;
f.Call(&t, 0, 0, 0, 0);
#define GET_FPU_ERR(x) (static_cast<int>(x & kFCSRFlagMask))
#define CHECK_NAN2008(x) (x & kFCSRNaN2008FlagMask)
#define CHECK_ROUND_RESULT(type) \
CHECK(GET_FPU_ERR(t.type##_err1_out) & kFCSRInexactFlagMask); \
CHECK_EQ(0, GET_FPU_ERR(t.type##_err2_out)); \
CHECK(GET_FPU_ERR(t.type##_err3_out) & kFCSRInvalidOpFlagMask); \
CHECK(GET_FPU_ERR(t.type##_err4_out) & kFCSRInvalidOpFlagMask); \
if (CHECK_NAN2008(t.type##_isNaN2008) && kArchVariant == kMips32r6) {\
CHECK_EQ(static_cast<int32_t>(0), t.type##_invalid_result);\
} else {\
CHECK_EQ(static_cast<int32_t>(kFPUInvalidResult), t.type##_invalid_result);\
}
CHECK_ROUND_RESULT(round);
CHECK_ROUND_RESULT(floor);
CHECK_ROUND_RESULT(ceil);
CHECK_ROUND_RESULT(cvt);
}
TEST(MIPS15) {
// Test chaining of label usages within instructions (issue 1644).
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
Label target;
__ beq(v0, v1, &target);
__ nop();
__ bne(v0, v1, &target);
__ nop();
__ bind(&target);
__ nop();
}
// ----------------------mips32r6 specific tests----------------------
TEST(seleqz_selnez) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test {
int a;
int b;
int c;
int d;
double e;
double f;
double g;
double h;
float i;
float j;
float k;
float l;
} Test;
Test test;
// Integer part of test.
__ addiu(t1, zero_reg, 1); // t1 = 1
__ seleqz(t3, t1, zero_reg); // t3 = 1
__ sw(t3, MemOperand(a0, offsetof(Test, a))); // a = 1
__ seleqz(t2, t1, t1); // t2 = 0
__ sw(t2, MemOperand(a0, offsetof(Test, b))); // b = 0
__ selnez(t3, t1, zero_reg); // t3 = 1;
__ sw(t3, MemOperand(a0, offsetof(Test, c))); // c = 0
__ selnez(t3, t1, t1); // t3 = 1
__ sw(t3, MemOperand(a0, offsetof(Test, d))); // d = 1
// Floating point part of test.
__ Ldc1(f0, MemOperand(a0, offsetof(Test, e))); // src
__ Ldc1(f2, MemOperand(a0, offsetof(Test, f))); // test
__ lwc1(f8, MemOperand(a0, offsetof(Test, i)) ); // src
__ lwc1(f10, MemOperand(a0, offsetof(Test, j)) ); // test
__ seleqz_d(f4, f0, f2);
__ selnez_d(f6, f0, f2);
__ seleqz_s(f12, f8, f10);
__ selnez_s(f14, f8, f10);
__ Sdc1(f4, MemOperand(a0, offsetof(Test, g))); // src
__ Sdc1(f6, MemOperand(a0, offsetof(Test, h))); // src
__ swc1(f12, MemOperand(a0, offsetof(Test, k)) ); // src
__ swc1(f14, MemOperand(a0, offsetof(Test, l)) ); // src
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(1, test.a);
CHECK_EQ(0, test.b);
CHECK_EQ(0, test.c);
CHECK_EQ(1, test.d);
const int test_size = 3;
const int input_size = 5;
double inputs_D[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
double outputs_D[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
double tests_D[test_size*2] = {2.8, 2.9, -2.8, -2.9,
18446744073709551616.0, 18446744073709555712.0};
float inputs_S[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
float outputs_S[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
float tests_S[test_size*2] = {2.9, 2.8, -2.9, -2.8,
18446744073709551616.0, 18446746272732807168.0};
for (int j=0; j < test_size; j+=2) {
for (int i=0; i < input_size; i++) {
test.e = inputs_D[i];
test.f = tests_D[j];
test.i = inputs_S[i];
test.j = tests_S[j];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(outputs_D[i], test.g);
CHECK_EQ(0, test.h);
CHECK_EQ(outputs_S[i], test.k);
CHECK_EQ(0, test.l);
test.f = tests_D[j+1];
test.j = tests_S[j+1];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(0, test.g);
CHECK_EQ(outputs_D[i], test.h);
CHECK_EQ(0, test.k);
CHECK_EQ(outputs_S[i], test.l);
}
}
}
}
TEST(min_max) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
struct TestFloat {
double a;
double b;
double c;
double d;
float e;
float f;
float g;
float h;
};
TestFloat test;
const double dnan = std::numeric_limits<double>::quiet_NaN();
const double dinf = std::numeric_limits<double>::infinity();
const double dminf = -std::numeric_limits<double>::infinity();
const float fnan = std::numeric_limits<float>::quiet_NaN();
const float finf = std::numeric_limits<float>::infinity();
const float fminf = std::numeric_limits<float>::infinity();
const int kTableLength = 13;
double inputsa[kTableLength] = {2.0, 3.0, dnan, 3.0, -0.0, 0.0, dinf,
dnan, 42.0, dinf, dminf, dinf, dnan};
double inputsb[kTableLength] = {3.0, 2.0, 3.0, dnan, 0.0, -0.0, dnan,
dinf, dinf, 42.0, dinf, dminf, dnan};
double outputsdmin[kTableLength] = {2.0, 2.0, 3.0, 3.0, -0.0,
-0.0, dinf, dinf, 42.0, 42.0,
dminf, dminf, dnan};
double outputsdmax[kTableLength] = {3.0, 3.0, 3.0, 3.0, 0.0, 0.0, dinf,
dinf, dinf, dinf, dinf, dinf, dnan};
float inputse[kTableLength] = {2.0, 3.0, fnan, 3.0, -0.0, 0.0, finf,
fnan, 42.0, finf, fminf, finf, fnan};
float inputsf[kTableLength] = {3.0, 2.0, 3.0, fnan, 0.0, -0.0, fnan,
finf, finf, 42.0, finf, fminf, fnan};
float outputsfmin[kTableLength] = {2.0, 2.0, 3.0, 3.0, -0.0,
-0.0, finf, finf, 42.0, 42.0,
fminf, fminf, fnan};
float outputsfmax[kTableLength] = {3.0, 3.0, 3.0, 3.0, 0.0, 0.0, finf,
finf, finf, finf, finf, finf, fnan};
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, b)));
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, e)));
__ lwc1(f6, MemOperand(a0, offsetof(TestFloat, f)));
__ min_d(f10, f4, f8);
__ max_d(f12, f4, f8);
__ min_s(f14, f2, f6);
__ max_s(f16, f2, f6);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, c)));
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, d)));
__ swc1(f14, MemOperand(a0, offsetof(TestFloat, g)));
__ swc1(f16, MemOperand(a0, offsetof(TestFloat, h)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputsa[i];
test.b = inputsb[i];
test.e = inputse[i];
test.f = inputsf[i];
f.Call(&test, 0, 0, 0, 0);
CHECK_EQ(0, memcmp(&test.c, &outputsdmin[i], sizeof(test.c)));
CHECK_EQ(0, memcmp(&test.d, &outputsdmax[i], sizeof(test.d)));
CHECK_EQ(0, memcmp(&test.g, &outputsfmin[i], sizeof(test.g)));
CHECK_EQ(0, memcmp(&test.h, &outputsfmax[i], sizeof(test.h)));
}
}
}
TEST(rint_d) {
if (IsMipsArchVariant(kMips32r6)) {
const int kTableLength = 30;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
double b;
int fcsr;
}TestFloat;
TestFloat test;
double inputs[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E+308, 6.27463370218383111104242366943E-307,
309485009821345068724781056.89,
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RN[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 0,
309485009821345068724781057.0,
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RZ[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RP[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 1,
309485009821345068724781057.0,
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RM[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
int fcsr_inputs[4] =
{kRoundToNearest, kRoundToZero, kRoundToPlusInf, kRoundToMinusInf};
double* outputs[4] = {outputs_RN, outputs_RZ, outputs_RP, outputs_RM};
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ lw(t0, MemOperand(a0, offsetof(TestFloat, fcsr)) );
__ cfc1(t1, FCSR);
__ ctc1(t0, FCSR);
__ rint_d(f8, f4);
__ Sdc1(f8, MemOperand(a0, offsetof(TestFloat, b)));
__ ctc1(t1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int j = 0; j < 4; j++) {
test.fcsr = fcsr_inputs[j];
for (int i = 0; i < kTableLength; i++) {
test.a = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs[j][i]);
}
}
}
}
TEST(sel) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test {
double dd;
double ds;
double dt;
float fd;
float fs;
float ft;
} Test;
Test test;
__ Ldc1(f0, MemOperand(a0, offsetof(Test, dd))); // test
__ Ldc1(f2, MemOperand(a0, offsetof(Test, ds))); // src1
__ Ldc1(f4, MemOperand(a0, offsetof(Test, dt))); // src2
__ lwc1(f6, MemOperand(a0, offsetof(Test, fd)) ); // test
__ lwc1(f8, MemOperand(a0, offsetof(Test, fs)) ); // src1
__ lwc1(f10, MemOperand(a0, offsetof(Test, ft)) ); // src2
__ sel_d(f0, f2, f4);
__ sel_s(f6, f8, f10);
__ Sdc1(f0, MemOperand(a0, offsetof(Test, dd)));
__ swc1(f6, MemOperand(a0, offsetof(Test, fd)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
const int test_size = 3;
const int input_size = 5;
double inputs_dt[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
double inputs_ds[input_size] = {0.1, 69.88, -91.325,
18446744073709551625.0, -18446744073709551625.0};
float inputs_ft[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
float inputs_fs[input_size] = {0.1, 69.88, -91.325,
18446744073709551625.0, -18446744073709551625.0};
double tests_D[test_size*2] = {2.8, 2.9, -2.8, -2.9,
18446744073709551616.0, 18446744073709555712.0};
float tests_S[test_size*2] = {2.9, 2.8, -2.9, -2.8,
18446744073709551616.0, 18446746272732807168.0};
for (int j=0; j < test_size; j+=2) {
for (int i=0; i < input_size; i++) {
test.dt = inputs_dt[i];
test.dd = tests_D[j];
test.ds = inputs_ds[i];
test.ft = inputs_ft[i];
test.fd = tests_S[j];
test.fs = inputs_fs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dd, inputs_ds[i]);
CHECK_EQ(test.fd, inputs_fs[i]);
test.dd = tests_D[j+1];
test.fd = tests_S[j+1];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dd, inputs_dt[i]);
CHECK_EQ(test.fd, inputs_ft[i]);
}
}
}
}
TEST(rint_s) {
if (IsMipsArchVariant(kMips32r6)) {
const int kTableLength = 30;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float b;
int fcsr;
}TestFloat;
TestFloat test;
float inputs[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E+38, 6.27463370218383111104242366943E-37,
309485009821345068724781056.89,
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RN[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 0,
309485009821345068724781057.0,
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RZ[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RP[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 1,
309485009821345068724781057.0,
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RM[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
int fcsr_inputs[4] =
{kRoundToNearest, kRoundToZero, kRoundToPlusInf, kRoundToMinusInf};
float* outputs[4] = {outputs_RN, outputs_RZ, outputs_RP, outputs_RM};
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, a)) );
__ lw(t0, MemOperand(a0, offsetof(TestFloat, fcsr)) );
__ cfc1(t1, FCSR);
__ ctc1(t0, FCSR);
__ rint_s(f8, f4);
__ swc1(f8, MemOperand(a0, offsetof(TestFloat, b)) );
__ ctc1(t1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int j = 0; j < 4; j++) {
test.fcsr = fcsr_inputs[j];
for (int i = 0; i < kTableLength; i++) {
test.a = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs[j][i]);
}
}
}
}
TEST(Cvt_d_uw) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_struct {
unsigned input;
uint64_t output;
} TestStruct;
unsigned inputs[] = {0x0, 0xFFFFFFFF, 0x80000000, 0x7FFFFFFF};
uint64_t outputs[] = {0x0, 0x41EFFFFFFFE00000, 0x41E0000000000000,
0x41DFFFFFFFC00000};
int kTableLength = sizeof(inputs)/sizeof(inputs[0]);
TestStruct test;
__ lw(t1, MemOperand(a0, offsetof(TestStruct, input)));
__ Cvt_d_uw(f4, t1, f6);
__ Sdc1(f4, MemOperand(a0, offsetof(TestStruct, output)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.input = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
// Check outputs
CHECK_EQ(test.output, outputs[i]);
}
}
TEST(mina_maxa) {
if (IsMipsArchVariant(kMips32r6)) {
const int kTableLength = 23;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dnan = std::numeric_limits<double>::quiet_NaN();
const double dinf = std::numeric_limits<double>::infinity();
const double dminf = -std::numeric_limits<double>::infinity();
const float fnan = std::numeric_limits<float>::quiet_NaN();
const float finf = std::numeric_limits<float>::infinity();
const float fminf = std::numeric_limits<float>::infinity();
struct TestFloat {
double a;
double b;
double resd;
double resd1;
float c;
float d;
float resf;
float resf1;
};
TestFloat test;
double inputsa[kTableLength] = {
5.3, 4.8, 6.1, 9.8, 9.8, 9.8, -10.0, -8.9, -9.8, -10.0, -8.9, -9.8,
dnan, 3.0, -0.0, 0.0, dinf, dnan, 42.0, dinf, dminf, dinf, dnan};
double inputsb[kTableLength] = {
4.8, 5.3, 6.1, -10.0, -8.9, -9.8, 9.8, 9.8, 9.8, -9.8, -11.2, -9.8,
3.0, dnan, 0.0, -0.0, dnan, dinf, dinf, 42.0, dinf, dminf, dnan};
double resd[kTableLength] = {
4.8, 4.8, 6.1, 9.8, -8.9, -9.8, 9.8, -8.9, -9.8, -9.8, -8.9, -9.8,
3.0, 3.0, -0.0, -0.0, dinf, dinf, 42.0, 42.0, dminf, dminf, dnan};
double resd1[kTableLength] = {
5.3, 5.3, 6.1, -10.0, 9.8, 9.8, -10.0, 9.8, 9.8, -10.0, -11.2, -9.8,
3.0, 3.0, 0.0, 0.0, dinf, dinf, dinf, dinf, dinf, dinf, dnan};
float inputsc[kTableLength] = {
5.3, 4.8, 6.1, 9.8, 9.8, 9.8, -10.0, -8.9, -9.8, -10.0, -8.9, -9.8,
fnan, 3.0, -0.0, 0.0, finf, fnan, 42.0, finf, fminf, finf, fnan};
float inputsd[kTableLength] = {4.8, 5.3, 6.1, -10.0, -8.9, -9.8,
9.8, 9.8, 9.8, -9.8, -11.2, -9.8,
3.0, fnan, -0.0, 0.0, fnan, finf,
finf, 42.0, finf, fminf, fnan};
float resf[kTableLength] = {
4.8, 4.8, 6.1, 9.8, -8.9, -9.8, 9.8, -8.9, -9.8, -9.8, -8.9, -9.8,
3.0, 3.0, -0.0, -0.0, finf, finf, 42.0, 42.0, fminf, fminf, fnan};
float resf1[kTableLength] = {
5.3, 5.3, 6.1, -10.0, 9.8, 9.8, -10.0, 9.8, 9.8, -10.0, -11.2, -9.8,
3.0, 3.0, 0.0, 0.0, finf, finf, finf, finf, finf, finf, fnan};
__ Ldc1(f2, MemOperand(a0, offsetof(TestFloat, a)));
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, b)));
__ lwc1(f8, MemOperand(a0, offsetof(TestFloat, c)) );
__ lwc1(f10, MemOperand(a0, offsetof(TestFloat, d)) );
__ mina_d(f6, f2, f4);
__ mina_s(f12, f8, f10);
__ maxa_d(f14, f2, f4);
__ maxa_s(f16, f8, f10);
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, resf)) );
__ Sdc1(f6, MemOperand(a0, offsetof(TestFloat, resd)));
__ swc1(f16, MemOperand(a0, offsetof(TestFloat, resf1)) );
__ Sdc1(f14, MemOperand(a0, offsetof(TestFloat, resd1)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputsa[i];
test.b = inputsb[i];
test.c = inputsc[i];
test.d = inputsd[i];
(f.Call(&test, 0, 0, 0, 0));
if (i < kTableLength - 1) {
CHECK_EQ(test.resd, resd[i]);
CHECK_EQ(test.resf, resf[i]);
CHECK_EQ(test.resd1, resd1[i]);
CHECK_EQ(test.resf1, resf1[i]);
} else {
CHECK(std::isnan(test.resd));
CHECK(std::isnan(test.resf));
CHECK(std::isnan(test.resd1));
CHECK(std::isnan(test.resf1));
}
}
}
}
// ----------------------mips32r2 specific tests----------------------
TEST(trunc_l) {
if (IsMipsArchVariant(kMips32r2) && IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c; // a trunc result
int64_t d; // b trunc result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ trunc_l_d(f8, f4);
__ trunc_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(movz_movn) {
if (IsMipsArchVariant(kMips32r2)) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
int32_t rt;
double a;
double b;
double bold;
double b1;
double bold1;
float c;
float d;
float dold;
float d1;
float dold1;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
double inputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
float outputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
double outputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
__ Ldc1(f2, MemOperand(a0, offsetof(TestFloat, a)));
__ lwc1(f6, MemOperand(a0, offsetof(TestFloat, c)) );
__ lw(t0, MemOperand(a0, offsetof(TestFloat, rt)) );
__ Move(f12, 0.0);
__ Move(f10, 0.0);
__ Move(f16, 0.0);
__ Move(f14, 0.0);
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, bold)));
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, dold)) );
__ Sdc1(f16, MemOperand(a0, offsetof(TestFloat, bold1)));
__ swc1(f14, MemOperand(a0, offsetof(TestFloat, dold1)) );
__ movz_s(f10, f6, t0);
__ movz_d(f12, f2, t0);
__ movn_s(f14, f6, t0);
__ movn_d(f16, f2, t0);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, d)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, b)));
__ swc1(f14, MemOperand(a0, offsetof(TestFloat, d1)) );
__ Sdc1(f16, MemOperand(a0, offsetof(TestFloat, b1)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.c = inputs_S[i];
test.rt = 1;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, test.bold);
CHECK_EQ(test.d, test.dold);
CHECK_EQ(test.b1, outputs_D[i]);
CHECK_EQ(test.d1, outputs_S[i]);
test.rt = 0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs_D[i]);
CHECK_EQ(test.d, outputs_S[i]);
CHECK_EQ(test.b1, test.bold1);
CHECK_EQ(test.d1, test.dold1);
}
}
}
TEST(movt_movd) {
if (IsMipsArchVariant(kMips32r2)) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
typedef struct test_float {
double srcd;
double dstd;
double dstdold;
double dstd1;
double dstdold1;
float srcf;
float dstf;
float dstfold;
float dstf1;
float dstfold1;
int32_t cc;
int32_t fcsr;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
5.3, -5.3, 20.8, -2.9
};
double inputs_S[kTableLength] = {
4.88, 4.8, -4.8, -0.29
};
float outputs_S[kTableLength] = {
4.88, 4.8, -4.8, -0.29
};
double outputs_D[kTableLength] = {
5.3, -5.3, 20.8, -2.9
};
int condition_flags[8] = {0, 1, 2, 3, 4, 5, 6, 7};
for (int i = 0; i < kTableLength; i++) {
test.srcd = inputs_D[i];
test.srcf = inputs_S[i];
for (int j = 0; j< 8; j++) {
test.cc = condition_flags[j];
if (test.cc == 0) {
test.fcsr = 1 << 23;
} else {
test.fcsr = 1 << (24+condition_flags[j]);
}
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ Ldc1(f2, MemOperand(a0, offsetof(TestFloat, srcd)));
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, srcf)) );
__ lw(t1, MemOperand(a0, offsetof(TestFloat, fcsr)) );
__ cfc1(t0, FCSR);
__ ctc1(t1, FCSR);
__ li(t2, 0x0);
__ mtc1(t2, f12);
__ mtc1(t2, f10);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstdold)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstfold)) );
__ movt_s(f12, f4, test.cc);
__ movt_d(f10, f2, test.cc);
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstf)) );
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstd)));
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstdold1)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstfold1)) );
__ movf_s(f12, f4, test.cc);
__ movf_d(f10, f2, test.cc);
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstf1)) );
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstd1)));
__ ctc1(t0, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dstf, outputs_S[i]);
CHECK_EQ(test.dstd, outputs_D[i]);
CHECK_EQ(test.dstf1, test.dstfold1);
CHECK_EQ(test.dstd1, test.dstdold1);
test.fcsr = 0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dstf, test.dstfold);
CHECK_EQ(test.dstd, test.dstdold);
CHECK_EQ(test.dstf1, outputs_S[i]);
CHECK_EQ(test.dstd1, outputs_D[i]);
}
}
}
}
// ----------------------tests for all archs--------------------------
TEST(cvt_w_d) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
int32_t b;
int32_t fcsr;
}Test;
const int kTableLength = 24;
double inputs[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, 2147483653.0
};
double outputs_RN[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
double outputs_RZ[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
double outputs_RP[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
double outputs_RM[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
int fcsr_inputs[4] =
{kRoundToNearest, kRoundToZero, kRoundToPlusInf, kRoundToMinusInf};
double* outputs[4] = {outputs_RN, outputs_RZ, outputs_RP, outputs_RM};
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lw(t0, MemOperand(a0, offsetof(Test, fcsr)) );
__ cfc1(t1, FCSR);
__ ctc1(t0, FCSR);
__ cvt_w_d(f8, f4);
__ swc1(f8, MemOperand(a0, offsetof(Test, b)) );
__ ctc1(t1, FCSR);
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int j = 0; j < 4; j++) {
test.fcsr = fcsr_inputs[j];
for (int i = 0; i < kTableLength; i++) {
test.a = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs[j][i]);
}
}
}
TEST(trunc_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a trunc result
int32_t d; // b trunc result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult,
0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ trunc_w_d(f8, f4);
__ trunc_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(round_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a trunc result
int32_t d; // b trunc result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
kFPUInvalidResult, 0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ round_w_d(f8, f4);
__ round_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(round_l) {
if (IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c;
int64_t d;
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ round_l_d(f8, f4);
__ round_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(sub) {
const int kTableLength = 12;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float b;
float resultS;
double c;
double d;
double resultD;
}TestFloat;
TestFloat test;
double inputfs_D[kTableLength] = {
5.3, 4.8, 2.9, -5.3, -4.8, -2.9,
5.3, 4.8, 2.9, -5.3, -4.8, -2.9
};
double inputft_D[kTableLength] = {
4.8, 5.3, 2.9, 4.8, 5.3, 2.9,
-4.8, -5.3, -2.9, -4.8, -5.3, -2.9
};
double outputs_D[kTableLength] = {
0.5, -0.5, 0.0, -10.1, -10.1, -5.8,
10.1, 10.1, 5.8, -0.5, 0.5, 0.0
};
float inputfs_S[kTableLength] = {
5.3, 4.8, 2.9, -5.3, -4.8, -2.9,
5.3, 4.8, 2.9, -5.3, -4.8, -2.9
};
float inputft_S[kTableLength] = {
4.8, 5.3, 2.9, 4.8, 5.3, 2.9,
-4.8, -5.3, -2.9, -4.8, -5.3, -2.9
};
float outputs_S[kTableLength] = {
0.5, -0.5, 0.0, -10.1, -10.1, -5.8,
10.1, 10.1, 5.8, -0.5, 0.5, 0.0
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, b)) );
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, c)));
__ Ldc1(f10, MemOperand(a0, offsetof(TestFloat, d)));
__ sub_s(f6, f2, f4);
__ sub_d(f12, f8, f10);
__ swc1(f6, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputfs_S[i];
test.b = inputft_S[i];
test.c = inputfs_D[i];
test.d = inputft_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, outputs_S[i]);
CHECK_EQ(test.resultD, outputs_D[i]);
}
}
TEST(sqrt_rsqrt_recip) {
const int kTableLength = 4;
const double deltaDouble = 2E-15;
const float deltaFloat = 2E-7;
const float sqrt2_s = sqrt(2);
const double sqrt2_d = sqrt(2);
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float resultS;
float resultS1;
float resultS2;
double c;
double resultD;
double resultD1;
double resultD2;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
0.0L, 4.0L, 2.0L, 4e-28L
};
double outputs_D[kTableLength] = {
0.0L, 2.0L, sqrt2_d, 2e-14L
};
float inputs_S[kTableLength] = {
0.0, 4.0, 2.0, 4e-28
};
float outputs_S[kTableLength] = {
0.0, 2.0, sqrt2_s, 2e-14
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, c)));
__ sqrt_s(f6, f2);
__ sqrt_d(f12, f8);
if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
__ rsqrt_d(f14, f8);
__ rsqrt_s(f16, f2);
__ recip_d(f18, f8);
__ recip_s(f4, f2);
}
__ swc1(f6, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
__ swc1(f16, MemOperand(a0, offsetof(TestFloat, resultS1)) );
__ Sdc1(f14, MemOperand(a0, offsetof(TestFloat, resultD1)));
__ swc1(f4, MemOperand(a0, offsetof(TestFloat, resultS2)) );
__ Sdc1(f18, MemOperand(a0, offsetof(TestFloat, resultD2)));
}
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
float f1;
double d1;
test.a = inputs_S[i];
test.c = inputs_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, outputs_S[i]);
CHECK_EQ(test.resultD, outputs_D[i]);
if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
if (i != 0) {
f1 = test.resultS1 - 1.0F/outputs_S[i];
f1 = (f1 < 0) ? f1 : -f1;
CHECK(f1 <= deltaFloat);
d1 = test.resultD1 - 1.0L/outputs_D[i];
d1 = (d1 < 0) ? d1 : -d1;
CHECK(d1 <= deltaDouble);
f1 = test.resultS2 - 1.0F/inputs_S[i];
f1 = (f1 < 0) ? f1 : -f1;
CHECK(f1 <= deltaFloat);
d1 = test.resultD2 - 1.0L/inputs_D[i];
d1 = (d1 < 0) ? d1 : -d1;
CHECK(d1 <= deltaDouble);
} else {
CHECK_EQ(test.resultS1, 1.0F/outputs_S[i]);
CHECK_EQ(test.resultD1, 1.0L/outputs_D[i]);
CHECK_EQ(test.resultS2, 1.0F/inputs_S[i]);
CHECK_EQ(test.resultD2, 1.0L/inputs_D[i]);
}
}
}
}
TEST(neg) {
const int kTableLength = 3;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float resultS;
double c;
double resultD;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
0.0, 4.0, -2.0
};
double outputs_D[kTableLength] = {
0.0, -4.0, 2.0
};
float inputs_S[kTableLength] = {
0.0, 4.0, -2.0
};
float outputs_S[kTableLength] = {
0.0, -4.0, 2.0
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, c)));
__ neg_s(f6, f2);
__ neg_d(f12, f8);
__ swc1(f6, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_S[i];
test.c = inputs_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, outputs_S[i]);
CHECK_EQ(test.resultD, outputs_D[i]);
}
}
TEST(mul) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float b;
float resultS;
double c;
double d;
double resultD;
}TestFloat;
TestFloat test;
double inputfs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
double inputft_D[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
float inputfs_S[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
float inputft_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, b)) );
__ Ldc1(f6, MemOperand(a0, offsetof(TestFloat, c)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, d)));
__ mul_s(f10, f2, f4);
__ mul_d(f12, f6, f8);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputfs_S[i];
test.b = inputft_S[i];
test.c = inputfs_D[i];
test.d = inputft_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, inputfs_S[i]*inputft_S[i]);
CHECK_EQ(test.resultD, inputfs_D[i]*inputft_D[i]);
}
}
TEST(mov) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
double b;
float c;
float d;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
double inputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
float outputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
double outputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ lwc1(f6, MemOperand(a0, offsetof(TestFloat, c)) );
__ mov_s(f8, f6);
__ mov_d(f10, f4);
__ swc1(f8, MemOperand(a0, offsetof(TestFloat, d)) );
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, b)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.c = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs_D[i]);
CHECK_EQ(test.d, outputs_S[i]);
}
}
TEST(floor_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a floor result
int32_t d; // b floor result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
kFPUInvalidResult,
0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ floor_w_d(f8, f4);
__ floor_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(floor_l) {
if (IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c;
int64_t d;
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ floor_l_d(f8, f4);
__ floor_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(ceil_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a floor result
int32_t d; // b floor result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult,
0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ ceil_w_d(f8, f4);
__ ceil_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(ceil_l) {
if (IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c;
int64_t d;
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ ceil_l_d(f8, f4);
__ ceil_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(jump_tables1) {
// Test jump tables with forward jumps.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
const int kNumCases = 512;
int values[kNumCases];
isolate->random_number_generator()->NextBytes(values, sizeof(values));
Label labels[kNumCases];
__ addiu(sp, sp, -4);
__ sw(ra, MemOperand(sp));
Label done;
{
__ BlockTrampolinePoolFor(kNumCases + 7);
PredictableCodeSizeScope predictable(&assm, (kNumCases + 7) * kInstrSize);
__ nal();
__ nop();
__ sll(at, a0, 2);
__ addu(at, at, ra);
__ lw(at, MemOperand(at, 5 * kInstrSize));
__ jr(at);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ dd(&labels[i]);
}
}
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
__ lui(v0, (values[i] >> 16) & 0xFFFF);
__ ori(v0, v0, values[i] & 0xFFFF);
__ b(&done);
__ nop();
}
__ bind(&done);
__ lw(ra, MemOperand(sp));
__ addiu(sp, sp, 4);
__ jr(ra);
__ nop();
CHECK_EQ(0, assm.UnboundLabelsCount());
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F1>::FromCode(*code);
for (int i = 0; i < kNumCases; ++i) {
int res = reinterpret_cast<int>(f.Call(i, 0, 0, 0, 0));
::printf("f(%d) = %d\n", i, res);
CHECK_EQ(values[i], res);
}
}
TEST(jump_tables2) {
// Test jump tables with backward jumps.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
const int kNumCases = 512;
int values[kNumCases];
isolate->random_number_generator()->NextBytes(values, sizeof(values));
Label labels[kNumCases];
__ addiu(sp, sp, -4);
__ sw(ra, MemOperand(sp));
Label done, dispatch;
__ b(&dispatch);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
__ lui(v0, (values[i] >> 16) & 0xFFFF);
__ ori(v0, v0, values[i] & 0xFFFF);
__ b(&done);
__ nop();
}
__ bind(&dispatch);
{
__ BlockTrampolinePoolFor(kNumCases + 7);
PredictableCodeSizeScope predictable(&assm, (kNumCases + 7) * kInstrSize);
__ nal();
__ nop();
__ sll(at, a0, 2);
__ addu(at, at, ra);
__ lw(at, MemOperand(at, 5 * kInstrSize));
__ jr(at);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ dd(&labels[i]);
}
}
__ bind(&done);
__ lw(ra, MemOperand(sp));
__ addiu(sp, sp, 4);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F1>::FromCode(*code);
for (int i = 0; i < kNumCases; ++i) {
int res = reinterpret_cast<int>(f.Call(i, 0, 0, 0, 0));
::printf("f(%d) = %d\n", i, res);
CHECK_EQ(values[i], res);
}
}
TEST(jump_tables3) {
// Test jump tables with backward jumps and embedded heap objects.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
const int kNumCases = 256;
Handle<Object> values[kNumCases];
for (int i = 0; i < kNumCases; ++i) {
double value = isolate->random_number_generator()->NextDouble();
values[i] = isolate->factory()->NewHeapNumber(value, TENURED);
}
Label labels[kNumCases];
Object* obj;
int32_t imm32;
__ addiu(sp, sp, -4);
__ sw(ra, MemOperand(sp));
Label done, dispatch;
__ b(&dispatch);
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
obj = *values[i];
imm32 = reinterpret_cast<intptr_t>(obj);
__ lui(v0, (imm32 >> 16) & 0xFFFF);
__ ori(v0, v0, imm32 & 0xFFFF);
__ b(&done);
__ nop();
}
__ bind(&dispatch);
{
__ BlockTrampolinePoolFor(kNumCases + 7);
PredictableCodeSizeScope predictable(&assm, (kNumCases + 7) * kInstrSize);
__ nal();
__ nop();
__ sll(at, a0, 2);
__ addu(at, at, ra);
__ lw(at, MemOperand(at, 5 * kInstrSize));
__ jr(at);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ dd(&labels[i]);
}
}
__ bind(&done);
__ lw(ra, MemOperand(sp));
__ addiu(sp, sp, 4);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F1>::FromCode(*code);
for (int i = 0; i < kNumCases; ++i) {
Handle<Object> result(f.Call(i, 0, 0, 0, 0), isolate);
#ifdef OBJECT_PRINT
::printf("f(%d) = ", i);
result->Print(std::cout);
::printf("\n");
#endif
CHECK(values[i].is_identical_to(result));
}
}
TEST(BITSWAP) {
// Test BITSWAP
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t r1;
int32_t r2;
int32_t r3;
int32_t r4;
} T;
T t;
Assembler assm(AssemblerOptions{}, nullptr, 0);
__ lw(a2, MemOperand(a0, offsetof(T, r1)));
__ nop();
__ bitswap(a1, a2);
__ sw(a1, MemOperand(a0, offsetof(T, r1)));
__ lw(a2, MemOperand(a0, offsetof(T, r2)));
__ nop();
__ bitswap(a1, a2);
__ sw(a1, MemOperand(a0, offsetof(T, r2)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.r1 = 0x781A15C3;
t.r2 = 0x8B71FCDE;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x1E58A8C3), t.r1);
CHECK_EQ(static_cast<int32_t>(0xD18E3F7B), t.r2);
}
}
TEST(class_fmt) {
if (IsMipsArchVariant(kMips32r6)) {
// Test CLASS.fmt instruction.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double dSignalingNan;
double dQuietNan;
double dNegInf;
double dNegNorm;
double dNegSubnorm;
double dNegZero;
double dPosInf;
double dPosNorm;
double dPosSubnorm;
double dPosZero;
float fSignalingNan;
float fQuietNan;
float fNegInf;
float fNegNorm;
float fNegSubnorm;
float fNegZero;
float fPosInf;
float fPosNorm;
float fPosSubnorm;
float fPosZero; } T;
T t;
// Create a function that accepts &t, and loads, manipulates, and stores
// the doubles t.a ... t.f.
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ Ldc1(f4, MemOperand(a0, offsetof(T, dSignalingNan)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dSignalingNan)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dQuietNan)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dQuietNan)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegInf)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegInf)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegNorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegNorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegSubnorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegSubnorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegZero)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegZero)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosInf)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosInf)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosNorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosNorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosSubnorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosSubnorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosZero)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosZero)));
// Testing instruction CLASS.S
__ lwc1(f4, MemOperand(a0, offsetof(T, fSignalingNan)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fSignalingNan)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fQuietNan)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fQuietNan)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegInf)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegInf)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegNorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegNorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegSubnorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegSubnorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegZero)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegZero)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosInf)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosInf)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosNorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosNorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosSubnorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosSubnorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosZero)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosZero)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.dSignalingNan = std::numeric_limits<double>::signaling_NaN();
t.dQuietNan = std::numeric_limits<double>::quiet_NaN();
t.dNegInf = -1.0 / 0.0;
t.dNegNorm = -5.0;
t.dNegSubnorm = -DBL_MIN / 2.0;
t.dNegZero = -0.0;
t.dPosInf = 2.0 / 0.0;
t.dPosNorm = 275.35;
t.dPosSubnorm = DBL_MIN / 2.0;
t.dPosZero = +0.0;
// Float test values
t.fSignalingNan = std::numeric_limits<float>::signaling_NaN();
t.fQuietNan = std::numeric_limits<float>::quiet_NaN();
t.fNegInf = -0.5/0.0;
t.fNegNorm = -FLT_MIN;
t.fNegSubnorm = -FLT_MIN / 1.5;
t.fNegZero = -0.0;
t.fPosInf = 100000.0 / 0.0;
t.fPosNorm = FLT_MAX;
t.fPosSubnorm = FLT_MIN / 20.0;
t.fPosZero = +0.0;
f.Call(&t, 0, 0, 0, 0);
// Expected double results.
CHECK_EQ(bit_cast<int64_t>(t.dSignalingNan), 0x001);
CHECK_EQ(bit_cast<int64_t>(t.dQuietNan), 0x002);
CHECK_EQ(bit_cast<int64_t>(t.dNegInf), 0x004);
CHECK_EQ(bit_cast<int64_t>(t.dNegNorm), 0x008);
CHECK_EQ(bit_cast<int64_t>(t.dNegSubnorm), 0x010);
CHECK_EQ(bit_cast<int64_t>(t.dNegZero), 0x020);
CHECK_EQ(bit_cast<int64_t>(t.dPosInf), 0x040);
CHECK_EQ(bit_cast<int64_t>(t.dPosNorm), 0x080);
CHECK_EQ(bit_cast<int64_t>(t.dPosSubnorm), 0x100);
CHECK_EQ(bit_cast<int64_t>(t.dPosZero), 0x200);
// Expected float results.
CHECK_EQ(bit_cast<int32_t>(t.fSignalingNan), 0x001);
CHECK_EQ(bit_cast<int32_t>(t.fQuietNan), 0x002);
CHECK_EQ(bit_cast<int32_t>(t.fNegInf), 0x004);
CHECK_EQ(bit_cast<int32_t>(t.fNegNorm), 0x008);
CHECK_EQ(bit_cast<int32_t>(t.fNegSubnorm), 0x010);
CHECK_EQ(bit_cast<int32_t>(t.fNegZero), 0x020);
CHECK_EQ(bit_cast<int32_t>(t.fPosInf), 0x040);
CHECK_EQ(bit_cast<int32_t>(t.fPosNorm), 0x080);
CHECK_EQ(bit_cast<int32_t>(t.fPosSubnorm), 0x100);
CHECK_EQ(bit_cast<int32_t>(t.fPosZero), 0x200);
}
}
TEST(ABS) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
int64_t fir;
double a;
float b;
double fcsr;
} TestFloat;
TestFloat test;
// Save FIR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ abs_d(f10, f4);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, a)));
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, b)));
__ abs_s(f10, f4);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, b)));
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.a = -2.0;
test.b = -2.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, 2.0);
CHECK_EQ(test.b, 2.0);
test.a = 2.0;
test.b = 2.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, 2.0);
CHECK_EQ(test.b, 2.0);
// Testing biggest positive number
test.a = std::numeric_limits<double>::max();
test.b = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::max());
CHECK_EQ(test.b, std::numeric_limits<float>::max());
// Testing smallest negative number
test.a = -std::numeric_limits<double>::max(); // lowest()
test.b = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::max());
CHECK_EQ(test.b, std::numeric_limits<float>::max());
// Testing smallest positive number
test.a = -std::numeric_limits<double>::min();
test.b = -std::numeric_limits<float>::min();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::min());
CHECK_EQ(test.b, std::numeric_limits<float>::min());
// Testing infinity
test.a = -std::numeric_limits<double>::max()
/ std::numeric_limits<double>::min();
test.b = -std::numeric_limits<float>::max()
/ std::numeric_limits<float>::min();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::max()
/ std::numeric_limits<double>::min());
CHECK_EQ(test.b, std::numeric_limits<float>::max()
/ std::numeric_limits<float>::min());
test.a = std::numeric_limits<double>::quiet_NaN();
test.b = std::numeric_limits<float>::quiet_NaN();
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.a));
CHECK(std::isnan(test.b));
test.a = std::numeric_limits<double>::signaling_NaN();
test.b = std::numeric_limits<float>::signaling_NaN();
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.a));
CHECK(std::isnan(test.b));
}
TEST(ADD_FMT) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
double b;
double c;
float fa;
float fb;
float fc;
} TestFloat;
TestFloat test;
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, b)));
__ add_d(f10, f8, f4);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, c)));
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, fa)));
__ lwc1(f8, MemOperand(a0, offsetof(TestFloat, fb)));
__ add_s(f10, f8, f4);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, fc)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.a = 2.0;
test.b = 3.0;
test.fa = 2.0;
test.fb = 3.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.c, 5.0);
CHECK_EQ(test.fc, 5.0);
test.a = std::numeric_limits<double>::max();
test.b = -std::numeric_limits<double>::max(); // lowest()
test.fa = std::numeric_limits<float>::max();
test.fb = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.c, 0.0);
CHECK_EQ(test.fc, 0.0);
test.a = std::numeric_limits<double>::max();
test.b = std::numeric_limits<double>::max();
test.fa = std::numeric_limits<float>::max();
test.fb = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK(!std::isfinite(test.c));
CHECK(!std::isfinite(test.fc));
test.a = 5.0;
test.b = std::numeric_limits<double>::signaling_NaN();
test.fa = 5.0;
test.fb = std::numeric_limits<float>::signaling_NaN();
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.c));
CHECK(std::isnan(test.fc));
}
TEST(C_COND_FMT) {
if ((IsMipsArchVariant(kMips32r1)) || (IsMipsArchVariant(kMips32r2))) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double dOp1;
double dOp2;
uint32_t dF;
uint32_t dUn;
uint32_t dEq;
uint32_t dUeq;
uint32_t dOlt;
uint32_t dUlt;
uint32_t dOle;
uint32_t dUle;
float fOp1;
float fOp2;
uint32_t fF;
uint32_t fUn;
uint32_t fEq;
uint32_t fUeq;
uint32_t fOlt;
uint32_t fUlt;
uint32_t fOle;
uint32_t fUle;
} TestFloat;
TestFloat test;
__ li(t1, 1);
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, dOp1)));
__ Ldc1(f6, MemOperand(a0, offsetof(TestFloat, dOp2)));
__ lwc1(f14, MemOperand(a0, offsetof(TestFloat, fOp1)));
__ lwc1(f16, MemOperand(a0, offsetof(TestFloat, fOp2)));
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(F, f4, f6, 0);
__ c_s(F, f14, f16, 2);
__ movt(t2, t1, 0);
__ movt(t3, t1, 2);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dF)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fF)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(UN, f4, f6, 2);
__ c_s(UN, f14, f16, 4);
__ movt(t2, t1, 2);
__ movt(t3, t1, 4);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUn)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUn)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(EQ, f4, f6, 4);
__ c_s(EQ, f14, f16, 6);
__ movt(t2, t1, 4);
__ movt(t3, t1, 6);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dEq)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fEq)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(UEQ, f4, f6, 6);
__ c_s(UEQ, f14, f16, 0);
__ movt(t2, t1, 6);
__ movt(t3, t1, 0);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUeq)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUeq)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(OLT, f4, f6, 0);
__ c_s(OLT, f14, f16, 2);
__ movt(t2, t1, 0);
__ movt(t3, t1, 2);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dOlt)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fOlt)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(ULT, f4, f6, 2);
__ c_s(ULT, f14, f16, 4);
__ movt(t2, t1, 2);
__ movt(t3, t1, 4);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUlt)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUlt)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(OLE, f4, f6, 4);
__ c_s(OLE, f14, f16, 6);
__ movt(t2, t1, 4);
__ movt(t3, t1, 6);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dOle)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fOle)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(ULE, f4, f6, 6);
__ c_s(ULE, f14, f16, 0);
__ movt(t2, t1, 6);
__ movt(t3, t1, 0);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUle)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUle)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.dOp1 = 2.0;
test.dOp2 = 3.0;
test.fOp1 = 2.0;
test.fOp2 = 3.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 0U);
CHECK_EQ(test.dEq, 0U);
CHECK_EQ(test.dUeq, 0U);
CHECK_EQ(test.dOlt, 1U);
CHECK_EQ(test.dUlt, 1U);
CHECK_EQ(test.dOle, 1U);
CHECK_EQ(test.dUle, 1U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 0U);
CHECK_EQ(test.fEq, 0U);
CHECK_EQ(test.fUeq, 0U);
CHECK_EQ(test.fOlt, 1U);
CHECK_EQ(test.fUlt, 1U);
CHECK_EQ(test.fOle, 1U);
CHECK_EQ(test.fUle, 1U);
test.dOp1 = std::numeric_limits<double>::max();
test.dOp2 = std::numeric_limits<double>::min();
test.fOp1 = std::numeric_limits<float>::min();
test.fOp2 = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 0U);
CHECK_EQ(test.dEq, 0U);
CHECK_EQ(test.dUeq, 0U);
CHECK_EQ(test.dOlt, 0U);
CHECK_EQ(test.dUlt, 0U);
CHECK_EQ(test.dOle, 0U);
CHECK_EQ(test.dUle, 0U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 0U);
CHECK_EQ(test.fEq, 0U);
CHECK_EQ(test.fUeq, 0U);
CHECK_EQ(test.fOlt, 0U);
CHECK_EQ(test.fUlt, 0U);
CHECK_EQ(test.fOle, 0U);
CHECK_EQ(test.fUle, 0U);
test.dOp1 = -std::numeric_limits<double>::max(); // lowest()
test.dOp2 = -std::numeric_limits<double>::max(); // lowest()
test.fOp1 = std::numeric_limits<float>::max();
test.fOp2 = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 0U);
CHECK_EQ(test.dEq, 1U);
CHECK_EQ(test.dUeq, 1U);
CHECK_EQ(test.dOlt, 0U);
CHECK_EQ(test.dUlt, 0U);
CHECK_EQ(test.dOle, 1U);
CHECK_EQ(test.dUle, 1U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 0U);
CHECK_EQ(test.fEq, 1U);
CHECK_EQ(test.fUeq, 1U);
CHECK_EQ(test.fOlt, 0U);
CHECK_EQ(test.fUlt, 0U);
CHECK_EQ(test.fOle, 1U);
CHECK_EQ(test.fUle, 1U);
test.dOp1 = std::numeric_limits<double>::quiet_NaN();
test.dOp2 = 0.0;
test.fOp1 = std::numeric_limits<float>::quiet_NaN();
test.fOp2 = 0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 1U);
CHECK_EQ(test.dEq, 0U);
CHECK_EQ(test.dUeq, 1U);
CHECK_EQ(test.dOlt, 0U);
CHECK_EQ(test.dUlt, 1U);
CHECK_EQ(test.dOle, 0U);
CHECK_EQ(test.dUle, 1U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 1U);
CHECK_EQ(test.fEq, 0U);
CHECK_EQ(test.fUeq, 1U);
CHECK_EQ(test.fOlt, 0U);
CHECK_EQ(test.fUlt, 1U);
CHECK_EQ(test.fOle, 0U);
CHECK_EQ(test.fUle, 1U);
}
}
TEST(CMP_COND_FMT) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double dOp1;
double dOp2;
double dF;
double dUn;
double dEq;
double dUeq;
double dOlt;
double dUlt;
double dOle;
double dUle;
double dOr;
double dUne;
double dNe;
float fOp1;
float fOp2;
float fF;
float fUn;
float fEq;
float fUeq;
float fOlt;
float fUlt;
float fOle;
float fUle;
float fOr;
float fUne;
float fNe;
} TestFloat;
TestFloat test;
__ li(t1, 1);
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, dOp1)));
__ Ldc1(f6, MemOperand(a0, offsetof(TestFloat, dOp2)));
__ lwc1(f14, MemOperand(a0, offsetof(TestFloat, fOp1)));
__ lwc1(f16, MemOperand(a0, offsetof(TestFloat, fOp2)));
__ cmp_d(F, f2, f4, f6);
__ cmp_s(F, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dF)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fF)) );
__ cmp_d(UN, f2, f4, f6);
__ cmp_s(UN, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUn)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUn)) );
__ cmp_d(EQ, f2, f4, f6);
__ cmp_s(EQ, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dEq)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fEq)) );
__ cmp_d(UEQ, f2, f4, f6);
__ cmp_s(UEQ, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUeq)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUeq)) );
__ cmp_d(LT, f2, f4, f6);
__ cmp_s(LT, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dOlt)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fOlt)) );
__ cmp_d(ULT, f2, f4, f6);
__ cmp_s(ULT, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUlt)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUlt)) );
__ cmp_d(LE, f2, f4, f6);
__ cmp_s(LE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dOle)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fOle)) );
__ cmp_d(ULE, f2, f4, f6);
__ cmp_s(ULE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUle)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUle)) );
__ cmp_d(ORD, f2, f4, f6);
__ cmp_s(ORD, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dOr)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fOr)) );
__ cmp_d(UNE, f2, f4, f6);
__ cmp_s(UNE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUne)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUne)) );
__ cmp_d(NE, f2, f4, f6);
__ cmp_s(NE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dNe)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fNe)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
uint64_t dTrue = 0xFFFFFFFFFFFFFFFF;
uint64_t dFalse = 0x0000000000000000;
uint32_t fTrue = 0xFFFFFFFF;
uint32_t fFalse = 0x00000000;
test.dOp1 = 2.0;
test.dOp2 = 3.0;
test.fOp1 = 2.0;
test.fOp2 = 3.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fTrue);
test.dOp1 = std::numeric_limits<double>::max();
test.dOp2 = std::numeric_limits<double>::min();
test.fOp1 = std::numeric_limits<float>::min();
test.fOp2 = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fFalse);
test.dOp1 = -std::numeric_limits<double>::max(); // lowest()
test.dOp2 = -std::numeric_limits<double>::max(); // lowest()
test.fOp1 = std::numeric_limits<float>::max();
test.fOp2 = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fTrue);
test.dOp1 = std::numeric_limits<double>::quiet_NaN();
test.dOp2 = 0.0;
test.fOp1 = std::numeric_limits<float>::quiet_NaN();
test.fOp2 = 0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fTrue);
}
}
TEST(CVT) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float cvt_d_s_in;
double cvt_d_s_out;
int32_t cvt_d_w_in;
double cvt_d_w_out;
int64_t cvt_d_l_in;
double cvt_d_l_out;
float cvt_l_s_in;
int64_t cvt_l_s_out;
double cvt_l_d_in;
int64_t cvt_l_d_out;
double cvt_s_d_in;
float cvt_s_d_out;
int32_t cvt_s_w_in;
float cvt_s_w_out;
int64_t cvt_s_l_in;
float cvt_s_l_out;
float cvt_w_s_in;
int32_t cvt_w_s_out;
double cvt_w_d_in;
int32_t cvt_w_d_out;
} TestFloat;
TestFloat test;
// Save FCSR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
#define GENERATE_CVT_TEST(x, y, z) \
__ y##c1(f0, MemOperand(a0, offsetof(TestFloat, x##_in))); \
__ x(f0, f0); \
__ nop(); \
__ z##c1(f0, MemOperand(a0, offsetof(TestFloat, x##_out)));
GENERATE_CVT_TEST(cvt_d_s, lw, Sd)
GENERATE_CVT_TEST(cvt_d_w, lw, Sd)
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
GENERATE_CVT_TEST(cvt_d_l, Ld, Sd)
}
if (IsFp64Mode()) {
GENERATE_CVT_TEST(cvt_l_s, lw, Sd)
GENERATE_CVT_TEST(cvt_l_d, Ld, Sd)
}
GENERATE_CVT_TEST(cvt_s_d, Ld, sw)
GENERATE_CVT_TEST(cvt_s_w, lw, sw)
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
GENERATE_CVT_TEST(cvt_s_l, Ld, sw)
}
GENERATE_CVT_TEST(cvt_w_s, lw, sw)
GENERATE_CVT_TEST(cvt_w_d, Ld, sw)
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.cvt_d_s_in = -0.51;
test.cvt_d_w_in = -1;
test.cvt_d_l_in = -1;
test.cvt_l_s_in = -0.51;
test.cvt_l_d_in = -0.51;
test.cvt_s_d_in = -0.51;
test.cvt_s_w_in = -1;
test.cvt_s_l_in = -1;
test.cvt_w_s_in = -0.51;
test.cvt_w_d_in = -0.51;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(-1, test.cvt_l_s_out);
CHECK_EQ(-1, test.cvt_l_d_out);
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(-1, test.cvt_w_s_out);
CHECK_EQ(-1, test.cvt_w_d_out);
test.cvt_d_s_in = 0.49;
test.cvt_d_w_in = 1;
test.cvt_d_l_in = 1;
test.cvt_l_s_in = 0.49;
test.cvt_l_d_in = 0.49;
test.cvt_s_d_in = 0.49;
test.cvt_s_w_in = 1;
test.cvt_s_l_in = 1;
test.cvt_w_s_in = 0.49;
test.cvt_w_d_in = 0.49;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(0, test.cvt_l_s_out);
CHECK_EQ(0, test.cvt_l_d_out);
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(0, test.cvt_w_s_out);
CHECK_EQ(0, test.cvt_w_d_out);
test.cvt_d_s_in = std::numeric_limits<float>::max();
test.cvt_d_w_in = std::numeric_limits<int32_t>::max();
test.cvt_d_l_in = std::numeric_limits<int64_t>::max();
test.cvt_l_s_in = std::numeric_limits<float>::max();
test.cvt_l_d_in = std::numeric_limits<double>::max();
test.cvt_s_d_in = std::numeric_limits<double>::max();
test.cvt_s_w_in = std::numeric_limits<int32_t>::max();
test.cvt_s_l_in = std::numeric_limits<int64_t>::max();
test.cvt_w_s_in = std::numeric_limits<float>::max();
test.cvt_w_d_in = std::numeric_limits<double>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(test.cvt_l_s_out, std::numeric_limits<int64_t>::max());
CHECK_EQ(test.cvt_l_d_out, std::numeric_limits<int64_t>::max());
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(test.cvt_w_s_out, std::numeric_limits<int32_t>::max());
CHECK_EQ(test.cvt_w_d_out, std::numeric_limits<int32_t>::max());
test.cvt_d_s_in = -std::numeric_limits<float>::max(); // lowest()
test.cvt_d_w_in = std::numeric_limits<int32_t>::min(); // lowest()
test.cvt_d_l_in = std::numeric_limits<int64_t>::min(); // lowest()
test.cvt_l_s_in = -std::numeric_limits<float>::max(); // lowest()
test.cvt_l_d_in = -std::numeric_limits<double>::max(); // lowest()
test.cvt_s_d_in = -std::numeric_limits<double>::max(); // lowest()
test.cvt_s_w_in = std::numeric_limits<int32_t>::min(); // lowest()
test.cvt_s_l_in = std::numeric_limits<int64_t>::min(); // lowest()
test.cvt_w_s_in = -std::numeric_limits<float>::max(); // lowest()
test.cvt_w_d_in = -std::numeric_limits<double>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
// The returned value when converting from fixed-point to float-point
// is not consistent between board, simulator and specification
// in this test case, therefore modifying the test
if (IsFp64Mode()) {
CHECK(test.cvt_l_s_out == std::numeric_limits<int64_t>::min() ||
test.cvt_l_s_out == std::numeric_limits<int64_t>::max());
CHECK(test.cvt_l_d_out == std::numeric_limits<int64_t>::min() ||
test.cvt_l_d_out == std::numeric_limits<int64_t>::max());
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK(test.cvt_w_s_out == std::numeric_limits<int32_t>::min() ||
test.cvt_w_s_out == std::numeric_limits<int32_t>::max());
CHECK(test.cvt_w_d_out == std::numeric_limits<int32_t>::min() ||
test.cvt_w_d_out == std::numeric_limits<int32_t>::max());
test.cvt_d_s_in = std::numeric_limits<float>::min();
test.cvt_d_w_in = std::numeric_limits<int32_t>::min();
test.cvt_d_l_in = std::numeric_limits<int64_t>::min();
test.cvt_l_s_in = std::numeric_limits<float>::min();
test.cvt_l_d_in = std::numeric_limits<double>::min();
test.cvt_s_d_in = std::numeric_limits<double>::min();
test.cvt_s_w_in = std::numeric_limits<int32_t>::min();
test.cvt_s_l_in = std::numeric_limits<int64_t>::min();
test.cvt_w_s_in = std::numeric_limits<float>::min();
test.cvt_w_d_in = std::numeric_limits<double>::min();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(0, test.cvt_l_s_out);
CHECK_EQ(0, test.cvt_l_d_out);
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(0, test.cvt_w_s_out);
CHECK_EQ(0, test.cvt_w_d_out);
}
TEST(DIV_FMT) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test {
double dOp1;
double dOp2;
double dRes;
float fOp1;
float fOp2;
float fRes;
} Test;
Test test;
// Save FCSR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
__ Ldc1(f4, MemOperand(a0, offsetof(Test, dOp1)));
__ Ldc1(f2, MemOperand(a0, offsetof(Test, dOp2)));
__ nop();
__ div_d(f6, f4, f2);
__ Sdc1(f6, MemOperand(a0, offsetof(Test, dRes)));
__ lwc1(f4, MemOperand(a0, offsetof(Test, fOp1)) );
__ lwc1(f2, MemOperand(a0, offsetof(Test, fOp2)) );
__ nop();
__ div_s(f6, f4, f2);
__ swc1(f6, MemOperand(a0, offsetof(Test, fRes)) );
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&test, 0, 0, 0, 0));
const int test_size = 3;
double dOp1[test_size] = {
5.0,
DBL_MAX,
DBL_MAX,
};
double dOp2[test_size] = {
2.0,
2.0,
-DBL_MAX,
};
double dRes[test_size] = {
2.5,
DBL_MAX / 2.0,
-1.0,
};
float fOp1[test_size] = {
5.0,
FLT_MAX,
FLT_MAX,
};
float fOp2[test_size] = {
2.0,
2.0,
-FLT_MAX,
};
float fRes[test_size] = {
2.5,
FLT_MAX / 2.0,
-1.0,
};
for (int i = 0; i < test_size; i++) {
test.dOp1 = dOp1[i];
test.dOp2 = dOp2[i];
test.fOp1 = fOp1[i];
test.fOp2 = fOp2[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dRes, dRes[i]);
CHECK_EQ(test.fRes, fRes[i]);
}
test.dOp1 = DBL_MAX;
test.dOp2 = -0.0;
test.fOp1 = FLT_MAX;
test.fOp2 = -0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK(!std::isfinite(test.dRes));
CHECK(!std::isfinite(test.fRes));
test.dOp1 = 0.0;
test.dOp2 = -0.0;
test.fOp1 = 0.0;
test.fOp2 = -0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.dRes));
CHECK(std::isnan(test.fRes));
test.dOp1 = std::numeric_limits<double>::quiet_NaN();
test.dOp2 = -5.0;
test.fOp1 = std::numeric_limits<float>::quiet_NaN();
test.fOp2 = -5.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.dRes));
CHECK(std::isnan(test.fRes));
}
uint32_t run_align(uint32_t rs_value, uint32_t rt_value, uint8_t bp) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ align(v0, a0, a1, bp);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res =
reinterpret_cast<uint32_t>(f.Call(rs_value, rt_value, 0, 0, 0));
return res;
}
TEST(r6_align) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAlign {
uint32_t rs_value;
uint32_t rt_value;
uint8_t bp;
uint32_t expected_res;
};
// clang-format off
struct TestCaseAlign tc[] = {
// rs_value, rt_value, bp, expected_res
{0x11223344, 0xAABBCCDD, 0, 0xAABBCCDD},
{0x11223344, 0xAABBCCDD, 1, 0xBBCCDD11},
{0x11223344, 0xAABBCCDD, 2, 0xCCDD1122},
{0x11223344, 0xAABBCCDD, 3, 0xDD112233},
};
// clang-format on
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAlign);
for (size_t i = 0; i < nr_test_cases; ++i) {
CHECK_EQ(tc[i].expected_res, run_align(tc[i].rs_value,
tc[i].rt_value, tc[i].bp));
}
}
}
uint32_t PC; // The program counter.
uint32_t run_aluipc(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ aluipc(v0, offset);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
PC = (uint32_t)code->entry(); // Set the program counter.
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_aluipc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAluipc {
int16_t offset;
};
struct TestCaseAluipc tc[] = {
// offset
{ -32768 }, // 0x8000
{ -1 }, // 0xFFFF
{ 0 },
{ 1 },
{ 32767 }, // 0x7FFF
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAluipc);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_aluipc(tc[i].offset);
// Now, the program_counter (PC) is set.
uint32_t expected_res = ~0x0FFFF & (PC + (tc[i].offset << 16));
CHECK_EQ(expected_res, res);
}
}
}
uint32_t run_auipc(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ auipc(v0, offset);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
PC = (uint32_t)code->entry(); // Set the program counter.
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_auipc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAuipc {
int16_t offset;
};
struct TestCaseAuipc tc[] = {
// offset
{ -32768 }, // 0x8000
{ -1 }, // 0xFFFF
{ 0 },
{ 1 },
{ 32767 }, // 0x7FFF
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAuipc);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_auipc(tc[i].offset);
// Now, the program_counter (PC) is set.
uint32_t expected_res = PC + (tc[i].offset << 16);
CHECK_EQ(expected_res, res);
}
}
}
uint32_t run_lwpc(int offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// 256k instructions; 2^8k
// addiu t7, t0, 0xFFFF; (0x250FFFFF)
// ...
// addiu t4, t0, 0x0000; (0x250C0000)
uint32_t addiu_start_1 = 0x25000000;
for (int32_t i = 0xFFFFF; i >= 0xC0000; --i) {
uint32_t addiu_new = addiu_start_1 + i;
__ dd(addiu_new);
}
__ lwpc(t8, offset); // offset 0; 0xEF080000 (t8 register)
__ mov(v0, t8);
// 256k instructions; 2^8k
// addiu t0, t0, 0x0000; (0x25080000)
// ...
// addiu t3, t0, 0xFFFF; (0x250BFFFF)
uint32_t addiu_start_2 = 0x25000000;
for (int32_t i = 0x80000; i <= 0xBFFFF; ++i) {
uint32_t addiu_new = addiu_start_2 + i;
__ dd(addiu_new);
}
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_lwpc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseLwpc {
int offset;
uint32_t expected_res;
};
// clang-format off
struct TestCaseLwpc tc[] = {
// offset, expected_res
{ -262144, 0x250FFFFF }, // offset 0x40000
{ -4, 0x250C0003 },
{ -1, 0x250C0000 },
{ 0, 0xEF080000 },
{ 1, 0x03001025 }, // mov(v0, t8)
{ 2, 0x25080000 },
{ 4, 0x25080002 },
{ 262143, 0x250BFFFD }, // offset 0x3FFFF
};
// clang-format on
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseLwpc);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_lwpc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
uint32_t run_jic(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label get_program_counter, stop_execution;
__ push(ra);
__ li(v0, 0);
__ li(t1, 0x66);
__ addiu(v0, v0, 0x1); // <-- offset = -32
__ addiu(v0, v0, 0x2);
__ addiu(v0, v0, 0x10);
__ addiu(v0, v0, 0x20);
__ beq(v0, t1, &stop_execution);
__ nop();
__ nal(); // t0 <- program counter
__ mov(t0, ra);
__ jic(t0, offset);
__ addiu(v0, v0, 0x100);
__ addiu(v0, v0, 0x200);
__ addiu(v0, v0, 0x1000);
__ addiu(v0, v0, 0x2000); // <--- offset = 16
__ pop(ra);
__ jr(ra);
__ nop();
__ bind(&stop_execution);
__ pop(ra);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_jic) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseJic {
// As rt will be used t0 register which will have value of
// the program counter for the jic instruction.
int16_t offset;
uint32_t expected_res;
};
struct TestCaseJic tc[] = {
// offset, expected_result
{ 16, 0x2033 },
{ 4, 0x3333 },
{ -32, 0x66 },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseJic);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_jic(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
uint64_t run_beqzc(int32_t value, int32_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label stop_execution;
__ li(v0, 0);
__ li(t1, 0x66);
__ addiu(v0, v0, 0x1); // <-- offset = -32
__ addiu(v0, v0, 0x2);
__ addiu(v0, v0, 0x10);
__ addiu(v0, v0, 0x20);
__ beq(v0, t1, &stop_execution);
__ nop();
__ beqzc(a0, offset); // BEQZC rs, offset
__ addiu(v0, v0, 0x1);
__ addiu(v0, v0, 0x100);
__ addiu(v0, v0, 0x200);
__ addiu(v0, v0, 0x1000);
__ addiu(v0, v0, 0x2000); // <--- offset = 16
__ jr(ra);
__ nop();
__ bind(&stop_execution);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(value, 0, 0, 0, 0));
return res;
}
TEST(r6_beqzc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseBeqzc {
uint32_t value;
int32_t offset;
uint32_t expected_res;
};
// clang-format off
struct TestCaseBeqzc tc[] = {
// value, offset, expected_res
{ 0x0, -8, 0x66 },
{ 0x0, 0, 0x3334 },
{ 0x0, 1, 0x3333 },
{ 0xABC, 1, 0x3334 },
{ 0x0, 4, 0x2033 },
};
// clang-format on
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBeqzc);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_beqzc(tc[i].value, tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
void load_elements_of_vector(MacroAssembler& assm, const uint64_t elements[],
MSARegister w, Register t0, Register t1) {
__ li(t0, static_cast<uint32_t>(elements[0] & 0xFFFFFFFF));
__ li(t1, static_cast<uint32_t>((elements[0] >> 32) & 0xFFFFFFFF));
__ insert_w(w, 0, t0);
__ insert_w(w, 1, t1);
__ li(t0, static_cast<uint32_t>(elements[1] & 0xFFFFFFFF));
__ li(t1, static_cast<uint32_t>((elements[1] >> 32) & 0xFFFFFFFF));
__ insert_w(w, 2, t0);
__ insert_w(w, 3, t1);
}
inline void store_elements_of_vector(MacroAssembler& assm, MSARegister w,
Register a) {
__ st_d(w, MemOperand(a, 0));
}
typedef union {
uint8_t b[16];
uint16_t h[8];
uint32_t w[4];
uint64_t d[2];
} msa_reg_t;
struct TestCaseMsaBranch {
uint64_t wt_lo;
uint64_t wt_hi;
};
template <typename Branch>
void run_bz_bnz(TestCaseMsaBranch* input, Branch GenerateBranch,
bool branched) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, NULL, 0, v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
typedef struct {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wd_lo;
uint64_t wd_hi;
} T;
T t = {0x20B9CC4F1A83E0C5, 0xA27E1B5F2F5BB18A, 0x0000000000000000,
0x0000000000000000};
msa_reg_t res;
Label do_not_move_w0_to_w2;
load_elements_of_vector(assm, &t.ws_lo, w0, t0, t1);
load_elements_of_vector(assm, &t.wd_lo, w2, t0, t1);
load_elements_of_vector(assm, &input->wt_lo, w1, t0, t1);
GenerateBranch(assm, do_not_move_w0_to_w2);
__ nop();
__ move_v(w2, w0);
__ bind(&do_not_move_w0_to_w2);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
if (branched) {
CHECK_EQ(t.wd_lo, res.d[0]);
CHECK_EQ(t.wd_hi, res.d[1]);
} else {
CHECK_EQ(t.ws_lo, res.d[0]);
CHECK_EQ(t.ws_hi, res.d[1]);
}
}
TEST(MSA_bz_bnz) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
TestCaseMsaBranch tz_v[] = {
{0x0, 0x0}, {0xABC, 0x0}, {0x0, 0xABC}, {0xABC, 0xABC}};
for (unsigned i = 0; i < arraysize(tz_v); ++i) {
run_bz_bnz(
&tz_v[i],
[](MacroAssembler& assm, Label& br_target) { __ bz_v(w1, &br_target); },
tz_v[i].wt_lo == 0 && tz_v[i].wt_hi == 0);
}
#define TEST_BZ_DF(input_array, lanes, instruction, int_type) \
for (unsigned i = 0; i < arraysize(input_array); ++i) { \
int j; \
int_type* element = reinterpret_cast<int_type*>(&input_array[i]); \
for (j = 0; j < lanes; ++j) { \
if (element[j] == 0) { \
break; \
} \
} \
run_bz_bnz(&input_array[i], \
[](MacroAssembler& assm, Label& br_target) { \
__ instruction(w1, &br_target); \
}, \
j != lanes); \
}
TestCaseMsaBranch tz_b[] = {{0x0, 0x0},
{0xBC0000, 0x0},
{0x0, 0xAB000000000000CD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_b, kMSALanesByte, bz_b, int8_t)
TestCaseMsaBranch tz_h[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_h, kMSALanesHalf, bz_h, int16_t)
TestCaseMsaBranch tz_w[] = {{0x0, 0x0},
{0xBCDE123400000000, 0x0},
{0x0, 0x000000001234ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_w, kMSALanesWord, bz_w, int32_t)
TestCaseMsaBranch tz_d[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_d, kMSALanesDword, bz_d, int64_t)
#undef TEST_BZ_DF
TestCaseMsaBranch tnz_v[] = {
{0x0, 0x0}, {0xABC, 0x0}, {0x0, 0xABC}, {0xABC, 0xABC}};
for (unsigned i = 0; i < arraysize(tnz_v); ++i) {
run_bz_bnz(&tnz_v[i],
[](MacroAssembler& assm, Label& br_target) {
__ bnz_v(w1, &br_target);
},
tnz_v[i].wt_lo != 0 || tnz_v[i].wt_hi != 0);
}
#define TEST_BNZ_DF(input_array, lanes, instruction, int_type) \
for (unsigned i = 0; i < arraysize(input_array); ++i) { \
int j; \
int_type* element = reinterpret_cast<int_type*>(&input_array[i]); \
for (j = 0; j < lanes; ++j) { \
if (element[j] == 0) { \
break; \
} \
} \
run_bz_bnz(&input_array[i], \
[](MacroAssembler& assm, Label& br_target) { \
__ instruction(w1, &br_target); \
}, \
j == lanes); \
}
TestCaseMsaBranch tnz_b[] = {{0x0, 0x0},
{0xBC0000, 0x0},
{0x0, 0xAB000000000000CD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_b, 16, bnz_b, int8_t)
TestCaseMsaBranch tnz_h[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_h, 8, bnz_h, int16_t)
TestCaseMsaBranch tnz_w[] = {{0x0, 0x0},
{0xBCDE123400000000, 0x0},
{0x0, 0x000000001234ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_w, 4, bnz_w, int32_t)
TestCaseMsaBranch tnz_d[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_d, 2, bnz_d, int64_t)
#undef TEST_BNZ_DF
}
uint32_t run_jialc(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label main_block, get_program_counter;
__ push(ra);
__ li(v0, 0);
__ beq(v0, v0, &main_block);
__ nop();
// Block 1
__ addiu(v0, v0, 0x1); // <-- offset = -40
__ addiu(v0, v0, 0x2);
__ jr(ra);
__ nop();
// Block 2
__ addiu(v0, v0, 0x10); // <-- offset = -24
__ addiu(v0, v0, 0x20);
__ jr(ra);
__ nop();
// Block 3 (Main)
__ bind(&main_block);
__ nal(); // t0 <- program counter
__ mov(t0, ra);
__ jialc(t0, offset);
__ addiu(v0, v0, 0x4);
__ pop(ra);
__ jr(ra);
__ nop();
// Block 4
__ addiu(v0, v0, 0x100); // <-- offset = 20
__ addiu(v0, v0, 0x200);
__ jr(ra);
__ nop();
// Block 5
__ addiu(v0, v0, 0x1000); // <--- offset = 36
__ addiu(v0, v0, 0x2000);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_jialc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseJialc {
int16_t offset;
uint32_t expected_res;
};
struct TestCaseJialc tc[] = {
// offset, expected_res
{ -40, 0x7 },
{ -24, 0x34 },
{ 20, 0x304 },
{ 36, 0x3004 }
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseJialc);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_jialc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
static uint32_t run_addiupc(int32_t imm19) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ addiupc(v0, imm19);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
PC = (uint32_t)code->entry(); // Set the program counter.
uint32_t rs = reinterpret_cast<uint32_t>(f.Call(imm19, 0, 0, 0, 0));
return rs;
}
TEST(r6_addiupc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAddiupc {
int32_t imm19;
};
TestCaseAddiupc tc[] = {
// imm19
{-262144}, // 0x40000
{-1}, // 0x7FFFF
{0},
{1}, // 0x00001
{262143} // 0x3FFFF
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAddiupc);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_addiupc(tc[i].imm19);
// Now, the program_counter (PC) is set.
uint32_t expected_res = PC + (tc[i].imm19 << 2);
CHECK_EQ(expected_res, res);
}
}
}
int32_t run_bc(int32_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label continue_1, stop_execution;
__ push(ra);
__ li(v0, 0);
__ li(t8, 0);
__ li(t9, 2); // A condition for stopping execution.
for (int32_t i = -100; i <= -11; ++i) {
__ addiu(v0, v0, 1);
}
__ addiu(t8, t8, 1); // -10
__ beq(t8, t9, &stop_execution); // -9
__ nop(); // -8
__ beq(t8, t8, &continue_1); // -7
__ nop(); // -6
__ bind(&stop_execution);
__ pop(ra); // -5, -4
__ jr(ra); // -3
__ nop(); // -2
__ bind(&continue_1);
__ bc(offset); // -1
for (int32_t i = 0; i <= 99; ++i) {
__ addiu(v0, v0, 1);
}
__ pop(ra);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int32_t res = reinterpret_cast<int32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_bc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseBc {
int32_t offset;
int32_t expected_res;
};
struct TestCaseBc tc[] = {
// offset, expected_result
{ -100, (abs(-100) - 10) * 2 },
{ -11, (abs(-100) - 10 + 1) },
{ 0, (abs(-100) - 10 + 1 + 99) },
{ 1, (abs(-100) - 10 + 99) },
{ 99, (abs(-100) - 10 + 1) },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBc);
for (size_t i = 0; i < nr_test_cases; ++i) {
int32_t res = run_bc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
int32_t run_balc(int32_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label continue_1, stop_execution;
__ push(ra);
__ li(v0, 0);
__ li(t8, 0);
__ li(t9, 2); // A condition for stopping execution.
__ beq(t8, t8, &continue_1);
__ nop();
uint32_t instruction_addiu = 0x24420001; // addiu v0, v0, 1
for (int32_t i = -117; i <= -57; ++i) {
__ dd(instruction_addiu);
}
__ jr(ra); // -56
__ nop(); // -55
for (int32_t i = -54; i <= -4; ++i) {
__ dd(instruction_addiu);
}
__ jr(ra); // -3
__ nop(); // -2
__ bind(&continue_1);
__ balc(offset); // -1
__ pop(ra); // 0, 1
__ jr(ra); // 2
__ nop(); // 3
for (int32_t i = 4; i <= 44; ++i) {
__ dd(instruction_addiu);
}
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int32_t res = reinterpret_cast<int32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
uint32_t run_aui(uint32_t rs, uint16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ li(t0, rs);
__ aui(v0, t0, offset);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_aui) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAui {
uint32_t rs;
uint16_t offset;
uint32_t ref_res;
};
struct TestCaseAui tc[] = {
// input, offset, result
{0xFFFEFFFF, 1, 0xFFFFFFFF},
{0xFFFFFFFF, 0, 0xFFFFFFFF},
{0, 0xFFFF, 0xFFFF0000},
{0x0008FFFF, 0xFFF7, 0xFFFFFFFF},
{32767, 32767, 0x7FFF7FFF},
// overflow cases
{0xFFFFFFFF, 0x1, 0x0000FFFF},
{0xFFFFFFFF, 0xFFFF, 0xFFFEFFFF},
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAui);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_aui(tc[i].rs, tc[i].offset);
CHECK_EQ(tc[i].ref_res, res);
}
}
}
TEST(r6_balc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseBalc {
int32_t offset;
int32_t expected_res;
};
struct TestCaseBalc tc[] = {
// offset, expected_result
{ -117, 61 },
{ -54, 51 },
{ 0, 0 },
{ 4, 41 },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBalc);
for (size_t i = 0; i < nr_test_cases; ++i) {
int32_t res = run_balc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
uint32_t run_bal(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ mov(t0, ra);
__ bal(offset); // Equivalent for "BGEZAL zero_reg, offset".
__ nop();
__ mov(ra, t0);
__ jr(ra);
__ nop();
__ li(v0, 1);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(bal) {
CcTest::InitializeVM();
struct TestCaseBal {
int16_t offset;
uint32_t expected_res;
};
struct TestCaseBal tc[] = {
// offset, expected_res
{ 4, 1 },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBal);
for (size_t i = 0; i < nr_test_cases; ++i) {
CHECK_EQ(tc[i].expected_res, run_bal(tc[i].offset));
}
}
TEST(Trampoline) {
// Private member of Assembler class.
static const int kMaxBranchOffset = (1 << (18 - 1)) - 1;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label done;
size_t nr_calls = kMaxBranchOffset / (2 * kInstrSize) + 2;
for (size_t i = 0; i < nr_calls; ++i) {
__ BranchShort(&done, eq, a0, Operand(a1));
}
__ bind(&done);
__ Ret(USE_DELAY_SLOT);
__ mov(v0, zero_reg);
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int32_t res = reinterpret_cast<int32_t>(f.Call(42, 42, 0, 0, 0));
CHECK_EQ(0, res);
}
template <class T>
struct TestCaseMaddMsub {
T fr, fs, ft, fd_add, fd_sub;
};
template <typename T, typename F>
void helper_madd_msub_maddf_msubf(F func) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
T x = std::sqrt(static_cast<T>(2.0));
T y = std::sqrt(static_cast<T>(3.0));
T z = std::sqrt(static_cast<T>(5.0));
T x2 = 11.11, y2 = 22.22, z2 = 33.33;
TestCaseMaddMsub<T> test_cases[] = {
{x, y, z, 0.0, 0.0},
{x, y, -z, 0.0, 0.0},
{x, -y, z, 0.0, 0.0},
{x, -y, -z, 0.0, 0.0},
{-x, y, z, 0.0, 0.0},
{-x, y, -z, 0.0, 0.0},
{-x, -y, z, 0.0, 0.0},
{-x, -y, -z, 0.0, 0.0},
{-3.14, 0.2345, -123.000056, 0.0, 0.0},
{7.3, -23.257, -357.1357, 0.0, 0.0},
{x2, y2, z2, 0.0, 0.0},
{x2, y2, -z2, 0.0, 0.0},
{x2, -y2, z2, 0.0, 0.0},
{x2, -y2, -z2, 0.0, 0.0},
{-x2, y2, z2, 0.0, 0.0},
{-x2, y2, -z2, 0.0, 0.0},
{-x2, -y2, z2, 0.0, 0.0},
{-x2, -y2, -z2, 0.0, 0.0},
};
if (std::is_same<T, float>::value) {
__ lwc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
__ lwc1(f6, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fs)));
__ lwc1(f8, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, ft)));
__ lwc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
} else if (std::is_same<T, double>::value) {
__ Ldc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
__ Ldc1(f6, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fs)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, ft)));
__ Ldc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
} else {
UNREACHABLE();
}
func(assm);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
const size_t kTableLength = sizeof(test_cases) / sizeof(TestCaseMaddMsub<T>);
TestCaseMaddMsub<T> tc;
for (size_t i = 0; i < kTableLength; i++) {
tc.fr = test_cases[i].fr;
tc.fs = test_cases[i].fs;
tc.ft = test_cases[i].ft;
(f.Call(&tc, 0, 0, 0, 0));
T res_add = 0;
T res_sub = 0;
if (IsMipsArchVariant(kMips32r2)) {
res_add = (tc.fs * tc.ft) + tc.fr;
res_sub = (tc.fs * tc.ft) - tc.fr;
} else if (IsMipsArchVariant(kMips32r6)) {
res_add = std::fma(tc.fs, tc.ft, tc.fr);
res_sub = std::fma(-tc.fs, tc.ft, tc.fr);
} else {
UNREACHABLE();
}
CHECK_EQ(tc.fd_add, res_add);
CHECK_EQ(tc.fd_sub, res_sub);
}
}
TEST(madd_msub_s) {
if (!IsMipsArchVariant(kMips32r2)) return;
helper_madd_msub_maddf_msubf<float>([](MacroAssembler& assm) {
__ madd_s(f10, f4, f6, f8);
__ swc1(f10, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_add)));
__ msub_s(f16, f4, f6, f8);
__ swc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_sub)));
});
}
TEST(madd_msub_d) {
if (!IsMipsArchVariant(kMips32r2)) return;
helper_madd_msub_maddf_msubf<double>([](MacroAssembler& assm) {
__ madd_d(f10, f4, f6, f8);
__ Sdc1(f10, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_add)));
__ msub_d(f16, f4, f6, f8);
__ Sdc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_sub)));
});
}
TEST(maddf_msubf_s) {
if (!IsMipsArchVariant(kMips32r6)) return;
helper_madd_msub_maddf_msubf<float>([](MacroAssembler& assm) {
__ maddf_s(f4, f6, f8);
__ swc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_add)));
__ msubf_s(f16, f6, f8);
__ swc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_sub)));
});
}
TEST(maddf_msubf_d) {
if (!IsMipsArchVariant(kMips32r6)) return;
helper_madd_msub_maddf_msubf<double>([](MacroAssembler& assm) {
__ maddf_d(f4, f6, f8);
__ Sdc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_add)));
__ msubf_d(f16, f6, f8);
__ Sdc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_sub)));
});
}
uint32_t run_Subu(uint32_t imm, int32_t num_instr) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label code_start;
__ bind(&code_start);
__ Subu(v0, zero_reg, imm);
CHECK_EQ(assm.SizeOfCodeGeneratedSince(&code_start), num_instr * kInstrSize);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(Subu) {
CcTest::InitializeVM();
// Test Subu macro-instruction for min_int16 and max_int16 border cases.
// For subtracting int16 immediate values we use addiu.
struct TestCaseSubu {
uint32_t imm;
uint32_t expected_res;
int32_t num_instr;
};
// We call Subu(v0, zero_reg, imm) to test cases listed below.
// 0 - imm = expected_res
struct TestCaseSubu tc[] = {
// imm, expected_res, num_instr
{0xFFFF8000, 0x8000, 2}, // min_int16
// Generates ori + addu
// We can't have just addiu because -min_int16 > max_int16 so use
// register. We can load min_int16 to at register with addiu and then
// subtract at with subu, but now we use ori + addu because -min_int16 can
// be loaded using ori.
{0x8000, 0xFFFF8000, 1}, // max_int16 + 1
// Generates addiu
// max_int16 + 1 is not int16 but -(max_int16 + 1) is, just use addiu.
{0xFFFF7FFF, 0x8001, 2}, // min_int16 - 1
// Generates ori + addu
// To load this value to at we need two instructions and another one to
// subtract, lui + ori + subu. But we can load -value to at using just
// ori and then add at register with addu.
{0x8001, 0xFFFF7FFF, 2}, // max_int16 + 2
// Generates ori + subu
// Not int16 but is uint16, load value to at with ori and subtract with
// subu.
{0x00010000, 0xFFFF0000, 2},
// Generates lui + subu
// Load value using lui to at and subtract with subu.
{0x00010001, 0xFFFEFFFF, 3},
// Generates lui + ori + subu
// We have to generate three instructions in this case.
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseSubu);
for (size_t i = 0; i < nr_test_cases; ++i) {
CHECK_EQ(tc[i].expected_res, run_Subu(tc[i].imm, tc[i].num_instr));
}
}
TEST(MSA_fill_copy) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint32_t u8;
uint32_t u16;
uint32_t u32;
uint32_t s8;
uint32_t s16;
uint32_t s32;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
{
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, 0xA512B683);
__ fill_b(w0, t0);
__ fill_h(w2, t0);
__ fill_w(w4, t0);
__ copy_u_b(t1, w0, 11);
__ sw(t1, MemOperand(a0, offsetof(T, u8)));
__ copy_u_h(t1, w2, 6);
__ sw(t1, MemOperand(a0, offsetof(T, u16)));
__ copy_u_w(t1, w4, 3);
__ sw(t1, MemOperand(a0, offsetof(T, u32)));
__ copy_s_b(t1, w0, 8);
__ sw(t1, MemOperand(a0, offsetof(T, s8)));
__ copy_s_h(t1, w2, 5);
__ sw(t1, MemOperand(a0, offsetof(T, s16)));
__ copy_s_w(t1, w4, 1);
__ sw(t1, MemOperand(a0, offsetof(T, s32)));
__ jr(ra);
__ nop();
}
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(0x83u, t.u8);
CHECK_EQ(0xB683u, t.u16);
CHECK_EQ(0xA512B683u, t.u32);
CHECK_EQ(0xFFFFFF83u, t.s8);
CHECK_EQ(0xFFFFB683u, t.s16);
CHECK_EQ(0xA512B683u, t.s32);
}
TEST(MSA_fill_copy_2) {
// Similar to MSA_fill_copy test, but also check overlaping between MSA and
// FPU registers with same numbers
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint32_t w0;
uint32_t w1;
uint32_t w2;
uint32_t w3;
} T;
T t[2];
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
{
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, 0xAAAAAAAA);
__ li(t1, 0x55555555);
__ fill_w(w0, t0);
__ fill_w(w2, t0);
__ FmoveLow(f0, t1);
__ FmoveHigh(f2, t1);
#define STORE_MSA_REG(w_reg, base, scratch) \
__ copy_u_w(scratch, w_reg, 0); \
__ sw(scratch, MemOperand(base, offsetof(T, w0))); \
__ copy_u_w(scratch, w_reg, 1); \
__ sw(scratch, MemOperand(base, offsetof(T, w1))); \
__ copy_u_w(scratch, w_reg, 2); \
__ sw(scratch, MemOperand(base, offsetof(T, w2))); \
__ copy_u_w(scratch, w_reg, 3); \
__ sw(scratch, MemOperand(base, offsetof(T, w3)));
STORE_MSA_REG(w0, a0, t2)
STORE_MSA_REG(w2, a1, t2)
#undef STORE_MSA_REG
__ jr(ra);
__ nop();
}
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F4>::FromCode(*code);
f.Call(&t[0], &t[1], 0, 0, 0);
CHECK_EQ(0x55555555, t[0].w0);
CHECK_EQ(0xAAAAAAAA, t[0].w1);
CHECK_EQ(0xAAAAAAAA, t[0].w2);
CHECK_EQ(0xAAAAAAAA, t[0].w3);
CHECK_EQ(0xAAAAAAAA, t[1].w0);
CHECK_EQ(0x55555555, t[1].w1);
CHECK_EQ(0xAAAAAAAA, t[1].w2);
CHECK_EQ(0xAAAAAAAA, t[1].w3);
}
TEST(MSA_fill_copy_3) {
// Similar to MSA_fill_copy test, but also check overlaping between MSA and
// FPU registers with same numbers
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint64_t d0;
uint64_t d1;
} T;
T t[2];
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
{
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, 0xAAAAAAAA);
__ li(t1, 0x55555555);
__ Move(f0, t0, t0);
__ Move(f2, t0, t0);
__ fill_w(w0, t1);
__ fill_w(w2, t1);
__ Sdc1(f0, MemOperand(a0, offsetof(T, d0)));
__ Sdc1(f2, MemOperand(a1, offsetof(T, d0)));
__ jr(ra);
__ nop();
}
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F4>::FromCode(*code);
f.Call(&t[0], &t[1], 0, 0, 0);
CHECK_EQ(0x5555555555555555, t[0].d0);
CHECK_EQ(0x5555555555555555, t[1].d0);
}
template <typename T>
void run_msa_insert(int32_t rs_value, int n, msa_reg_t* w) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, -1);
__ li(t1, rs_value);
__ fill_w(w0, t0);
if (std::is_same<T, int8_t>::value) {
DCHECK_LT(n, 16);
__ insert_b(w0, n, t1);
} else if (std::is_same<T, int16_t>::value) {
DCHECK_LT(n, 8);
__ insert_h(w0, n, t1);
} else if (std::is_same<T, int32_t>::value) {
DCHECK_LT(n, 4);
__ insert_w(w0, n, t1);
} else {
UNREACHABLE();
}
store_elements_of_vector(assm, w0, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(w, 0, 0, 0, 0));
}
TEST(MSA_insert) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseInsert {
uint32_t input;
int n;
uint64_t exp_res_lo;
uint64_t exp_res_hi;
};
struct TestCaseInsert tc_b[] = {
// input, n, exp_res_lo, exp_res_hi
{0xA2, 13, 0xFFFFFFFFFFFFFFFFu, 0xFFFFA2FFFFFFFFFFu},
{0x73, 10, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFF73FFFFu},
{0x3494, 5, 0xFFFF94FFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu},
{0xA6B8, 1, 0xFFFFFFFFFFFFB8FFu, 0xFFFFFFFFFFFFFFFFu}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseInsert); ++i) {
msa_reg_t res;
run_msa_insert<int8_t>(tc_b[i].input, tc_b[i].n, &res);
CHECK_EQ(tc_b[i].exp_res_lo, res.d[0]);
CHECK_EQ(tc_b[i].exp_res_hi, res.d[1]);
}
struct TestCaseInsert tc_h[] = {
// input, n, exp_res_lo, exp_res_hi
{0x85A2, 7, 0xFFFFFFFFFFFFFFFFu, 0x85A2FFFFFFFFFFFFu},
{0xE873, 5, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFE873FFFFu},
{0x3494, 3, 0x3494FFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu},
{0xA6B8, 1, 0xFFFFFFFFA6B8FFFFu, 0xFFFFFFFFFFFFFFFFu}};
for (size_t i = 0; i < sizeof(tc_h) / sizeof(TestCaseInsert); ++i) {
msa_reg_t res;
run_msa_insert<int16_t>(tc_h[i].input, tc_h[i].n, &res);
CHECK_EQ(tc_h[i].exp_res_lo, res.d[0]);
CHECK_EQ(tc_h[i].exp_res_hi, res.d[1]);
}
struct TestCaseInsert tc_w[] = {
// input, n, exp_res_lo, exp_res_hi
{0xD2F085A2u, 3, 0xFFFFFFFFFFFFFFFFu, 0xD2F085A2FFFFFFFFu},
{0x4567E873u, 2, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFF4567E873u},
{0xACDB3494u, 1, 0xACDB3494FFFFFFFFu, 0xFFFFFFFFFFFFFFFFu},
{0x89ABA6B8u, 0, 0xFFFFFFFF89ABA6B8u, 0xFFFFFFFFFFFFFFFFu}};
for (size_t i = 0; i < sizeof(tc_w) / sizeof(TestCaseInsert); ++i) {
msa_reg_t res;
run_msa_insert<int32_t>(tc_w[i].input, tc_w[i].n, &res);
CHECK_EQ(tc_w[i].exp_res_lo, res.d[0]);
CHECK_EQ(tc_w[i].exp_res_hi, res.d[1]);
}
}
TEST(MSA_move_v) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wd_lo;
uint64_t wd_hi;
} T;
T t[] = {{0x20B9CC4F1A83E0C5, 0xA27E1B5F2F5BB18A, 0x1E86678B52F8E1FF,
0x706E51290AC76FB9},
{0x4414AED7883FFD18, 0x047D183A06B67016, 0x4EF258CF8D822870,
0x2686B73484C2E843},
{0xD38FF9D048884FFC, 0x6DC63A57C0943CA7, 0x8520CA2F3E97C426,
0xA9913868FB819C59}};
for (unsigned i = 0; i < arraysize(t); ++i) {
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
load_elements_of_vector(assm, &t[i].ws_lo, w0, t0, t1);
load_elements_of_vector(assm, &t[i].wd_lo, w2, t0, t1);
__ move_v(w2, w0);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&t[i].wd_lo, 0, 0, 0, 0));
CHECK_EQ(t[i].ws_lo, t[i].wd_lo);
CHECK_EQ(t[i].ws_hi, t[i].wd_hi);
}
}
template <typename ExpectFunc, typename OperFunc>
void run_msa_sldi(OperFunc GenerateOperation,
ExpectFunc GenerateExpectedResult) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wd_lo;
uint64_t wd_hi;
} T;
T t[] = {{0x20B9CC4F1A83E0C5, 0xA27E1B5F2F5BB18A, 0x1E86678B52F8E1FF,
0x706E51290AC76FB9},
{0x4414AED7883FFD18, 0x047D183A06B67016, 0x4EF258CF8D822870,
0x2686B73484C2E843},
{0xD38FF9D048884FFC, 0x6DC63A57C0943CA7, 0x8520CA2F3E97C426,
0xA9913868FB819C59}};
uint64_t res[2];
for (unsigned i = 0; i < arraysize(t); ++i) {
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
load_elements_of_vector(assm, &t[i].ws_lo, w0, t0, t1);
load_elements_of_vector(assm, &t[i].wd_lo, w2, t0, t1);
GenerateOperation(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res[0], 0, 0, 0, 0));
GenerateExpectedResult(reinterpret_cast<uint8_t*>(&t[i].ws_lo),
reinterpret_cast<uint8_t*>(&t[i].wd_lo));
CHECK_EQ(res[0], t[i].wd_lo);
CHECK_EQ(res[1], t[i].wd_hi);
}
}
TEST(MSA_sldi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
#define SLDI_DF(s, k) \
uint8_t v[32]; \
for (unsigned i = 0; i < s; i++) { \
v[i] = ws[s * k + i]; \
v[i + s] = wd[s * k + i]; \
} \
for (unsigned i = 0; i < s; i++) { \
wd[s * k + i] = v[i + n]; \
}
for (int n = 0; n < 16; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_b(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
SLDI_DF(kMSARegSize / sizeof(int8_t) / kBitsPerByte, 0)
});
}
for (int n = 0; n < 8; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_h(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
for (int k = 0; k < 2; ++k) {
SLDI_DF(kMSARegSize / sizeof(int16_t) / kBitsPerByte, k)
}
});
}
for (int n = 0; n < 4; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_w(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
for (int k = 0; k < 4; ++k) {
SLDI_DF(kMSARegSize / sizeof(int32_t) / kBitsPerByte, k)
}
});
}
for (int n = 0; n < 2; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_d(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
for (int k = 0; k < 8; ++k) {
SLDI_DF(kMSARegSize / sizeof(int64_t) / kBitsPerByte, k)
}
});
}
#undef SLDI_DF
}
void run_msa_ctc_cfc(uint32_t value) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, value);
__ li(t2, 0);
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ cfcmsa(t2, msareg);
__ ctcmsa(msareg, t1);
__ sw(t2, MemOperand(a0, 0));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
uint32_t res;
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(value & 0x0167FFFF, res);
}
TEST(MSA_cfc_ctc) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const uint32_t mask_without_cause = 0xFF9C0FFF;
const uint32_t mask_always_zero = 0x0167FFFF;
const uint32_t mask_enables = 0x00000F80;
uint32_t test_case[] = {0x2D5EDE31, 0x07955425, 0x15B7DBE3, 0x2BF8BC37,
0xE6AAE923, 0x24D0F68D, 0x41AFA84C, 0x2D6BF64F,
0x925014BD, 0x4DBA7E61};
for (unsigned i = 0; i < arraysize(test_case); i++) {
// Setting enable bits and corresponding cause bits could result in
// exception raised and this prevents that from happening
test_case[i] = (~test_case[i] & mask_enables) << 5 |
(test_case[i] & mask_without_cause);
run_msa_ctc_cfc(test_case[i] & mask_always_zero);
}
}
struct ExpResShf {
uint8_t i8;
uint64_t lo;
uint64_t hi;
};
void run_msa_i8(SecondaryField opcode, uint64_t ws_lo, uint64_t ws_hi,
uint8_t i8) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
uint64_t wd_lo = 0xF35862E13E38F8B0;
uint64_t wd_hi = 0x4F41FFDEF2BFE636;
#define LOAD_W_REG(lo, hi, w_reg) \
__ li(t0, static_cast<uint32_t>(lo & 0xFFFFFFFF)); \
__ li(t1, static_cast<uint32_t>((lo >> 32) & 0xFFFFFFFF)); \
__ insert_w(w_reg, 0, t0); \
__ insert_w(w_reg, 1, t1); \
__ li(t0, static_cast<uint32_t>(hi & 0xFFFFFFFF)); \
__ li(t1, static_cast<uint32_t>((hi >> 32) & 0xFFFFFFFF)); \
__ insert_w(w_reg, 2, t0); \
__ insert_w(w_reg, 3, t1);
LOAD_W_REG(ws_lo, ws_hi, w0)
switch (opcode) {
case ANDI_B:
__ andi_b(w2, w0, i8);
break;
case ORI_B:
__ ori_b(w2, w0, i8);
break;
case NORI_B:
__ nori_b(w2, w0, i8);
break;
case XORI_B:
__ xori_b(w2, w0, i8);
break;
case BMNZI_B:
LOAD_W_REG(wd_lo, wd_hi, w2);
__ bmnzi_b(w2, w0, i8);
break;
case BMZI_B:
LOAD_W_REG(wd_lo, wd_hi, w2);
__ bmzi_b(w2, w0, i8);
break;
case BSELI_B:
LOAD_W_REG(wd_lo, wd_hi, w2);
__ bseli_b(w2, w0, i8);
break;
case SHF_B:
__ shf_b(w2, w0, i8);
break;
case SHF_H:
__ shf_h(w2, w0, i8);
break;
case SHF_W:
__ shf_w(w2, w0, i8);
break;
default:
UNREACHABLE();
}
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
#undef LOAD_W_REG
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
uint64_t mask = i8 * 0x0101010101010101ull;
switch (opcode) {
case ANDI_B:
CHECK_EQ(ws_lo & mask, res.d[0]);
CHECK_EQ(ws_hi & mask, res.d[1]);
break;
case ORI_B:
CHECK_EQ(ws_lo | mask, res.d[0]);
CHECK_EQ(ws_hi | mask, res.d[1]);
break;
case NORI_B:
CHECK_EQ(~(ws_lo | mask), res.d[0]);
CHECK_EQ(~(ws_hi | mask), res.d[1]);
break;
case XORI_B:
CHECK_EQ(ws_lo ^ mask, res.d[0]);
CHECK_EQ(ws_hi ^ mask, res.d[1]);
break;
case BMNZI_B:
CHECK_EQ((ws_lo & mask) | (wd_lo & ~mask), res.d[0]);
CHECK_EQ((ws_hi & mask) | (wd_hi & ~mask), res.d[1]);
break;
case BMZI_B:
CHECK_EQ((ws_lo & ~mask) | (wd_lo & mask), res.d[0]);
CHECK_EQ((ws_hi & ~mask) | (wd_hi & mask), res.d[1]);
break;
case BSELI_B:
CHECK_EQ((ws_lo & ~wd_lo) | (mask & wd_lo), res.d[0]);
CHECK_EQ((ws_hi & ~wd_hi) | (mask & wd_hi), res.d[1]);
break;
case SHF_B: {
struct ExpResShf exp_b[] = {
// i8, exp_lo, exp_hi
{0xFFu, 0x11111111B9B9B9B9, 0xF7F7F7F7C8C8C8C8},
{0x0u, 0x62626262DFDFDFDF, 0xD6D6D6D6C8C8C8C8},
{0xE4u, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636},
{0x1Bu, 0x1B756911C3D9A7B9, 0xAE94A5F79C8AEFC8},
{0xB1u, 0x662B6253E8C4DF12, 0x0D3AD6803F8BC88B},
{0x4Eu, 0x62E1F358F8B03E38, 0xFFDE4F41E636F2BF},
{0x27u, 0x1B697511C3A7D9B9, 0xAEA594F79CEF8AC8}};
for (size_t i = 0; i < sizeof(exp_b) / sizeof(ExpResShf); ++i) {
if (exp_b[i].i8 == i8) {
CHECK_EQ(exp_b[i].lo, res.d[0]);
CHECK_EQ(exp_b[i].hi, res.d[1]);
}
}
} break;
case SHF_H: {
struct ExpResShf exp_h[] = {
// i8, exp_lo, exp_hi
{0xFFu, 0x1169116911691169, 0xF7A5F7A5F7A5F7A5},
{0x0u, 0x12DF12DF12DF12DF, 0x8BC88BC88BC88BC8},
{0xE4u, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636},
{0x1Bu, 0xD9C3B9A7751B1169, 0x8A9CC8EF94AEF7A5},
{0xB1u, 0x53622B6612DFC4E8, 0x80D63A0D8BC88B3F},
{0x4Eu, 0x3E38F8B0F35862E1, 0xF2BFE6364F41FFDE},
{0x27u, 0xD9C3751BB9A71169, 0x8A9C94AEC8EFF7A5}};
for (size_t i = 0; i < sizeof(exp_h) / sizeof(ExpResShf); ++i) {
if (exp_h[i].i8 == i8) {
CHECK_EQ(exp_h[i].lo, res.d[0]);
CHECK_EQ(exp_h[i].hi, res.d[1]);
}
}
} break;
case SHF_W: {
struct ExpResShf exp_w[] = {
// i8, exp_lo, exp_hi
{0xFFu, 0xF7A594AEF7A594AE, 0xF7A594AEF7A594AE},
{0x0u, 0xC4E812DFC4E812DF, 0xC4E812DFC4E812DF},
{0xE4u, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636},
{0x1Bu, 0xC8EF8A9CF7A594AE, 0xB9A7D9C31169751B},
{0xB1u, 0xC4E812DF2B665362, 0x8B3F8BC83A0D80D6},
{0x4Eu, 0x4F41FFDEF2BFE636, 0xF35862E13E38F8B0},
{0x27u, 0x1169751BF7A594AE, 0xB9A7D9C3C8EF8A9C}};
for (size_t i = 0; i < sizeof(exp_w) / sizeof(ExpResShf); ++i) {
if (exp_w[i].i8 == i8) {
CHECK_EQ(exp_w[i].lo, res.d[0]);
CHECK_EQ(exp_w[i].hi, res.d[1]);
}
}
} break;
default:
UNREACHABLE();
}
}
struct TestCaseMsaI8 {
uint64_t input_lo;
uint64_t input_hi;
uint8_t i8;
};
TEST(MSA_andi_ori_nori_xori) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI8 tc[] = {// input_lo, input_hi, i8
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0xFFu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0u},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x3Bu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0xD9u}};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI8); ++i) {
run_msa_i8(ANDI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(ORI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(NORI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(XORI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
}
}
TEST(MSA_bmnzi_bmzi_bseli) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI8 tc[] = {// input_lo, input_hi, i8
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0xFFu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0u},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x3Bu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0xD9u}};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI8); ++i) {
run_msa_i8(BMNZI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(BMZI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(BSELI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
}
}
TEST(MSA_shf) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI8 tc[] = {
// input_lo, input_hi, i8
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0xFFu}, // 3333
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0u}, // 0000
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0xE4u}, // 3210
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x1Bu}, // 0123
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0xB1u}, // 2301
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x4Eu}, // 1032
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x27u} // 0213
};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI8); ++i) {
run_msa_i8(SHF_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(SHF_H, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(SHF_W, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
}
}
uint32_t run_Ins(uint32_t imm, uint32_t source, uint16_t pos, uint16_t size) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ li(v0, imm);
__ li(t0, source);
__ Ins(v0, t0, pos, size);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(Ins) {
CcTest::InitializeVM();
// run_Ins(rt_value, rs_value, pos, size), expected_result
CHECK_EQ(run_Ins(0x55555555, 0xABCDEF01, 31, 1), 0xD5555555);
CHECK_EQ(run_Ins(0x55555555, 0xABCDEF02, 30, 2), 0x95555555);
CHECK_EQ(run_Ins(0x01234567, 0xFABCDEFF, 0, 32), 0xFABCDEFF);
// Results with positive sign.
CHECK_EQ(run_Ins(0x55555550, 0x80000001, 0, 1), 0x55555551);
CHECK_EQ(run_Ins(0x55555555, 0x40000001, 0, 32), 0x40000001);
CHECK_EQ(run_Ins(0x55555555, 0x20000001, 1, 31), 0x40000003);
CHECK_EQ(run_Ins(0x55555555, 0x80700001, 8, 24), 0x70000155);
CHECK_EQ(run_Ins(0x55555555, 0x80007001, 16, 16), 0x70015555);
CHECK_EQ(run_Ins(0x55555555, 0x80000071, 24, 8), 0x71555555);
CHECK_EQ(run_Ins(0x75555555, 0x40000000, 31, 1), 0x75555555);
// Results with negative sign.
CHECK_EQ(run_Ins(0x85555550, 0x80000001, 0, 1), 0x85555551);
CHECK_EQ(run_Ins(0x55555555, 0x80000001, 0, 32), 0x80000001);
CHECK_EQ(run_Ins(0x55555555, 0x40000001, 1, 31), 0x80000003);
CHECK_EQ(run_Ins(0x55555555, 0x80800001, 8, 24), 0x80000155);
CHECK_EQ(run_Ins(0x55555555, 0x80008001, 16, 16), 0x80015555);
CHECK_EQ(run_Ins(0x55555555, 0x80000081, 24, 8), 0x81555555);
CHECK_EQ(run_Ins(0x75555555, 0x00000001, 31, 1), 0xF5555555);
}
uint32_t run_Ext(uint32_t source, uint16_t pos, uint16_t size) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ li(v0, 0xFFFFFFFF);
__ li(t0, source);
__ Ext(v0, t0, pos, size);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(Ext) {
CcTest::InitializeVM();
// Source values with negative sign.
// run_Ext(rs_value, pos, size), expected_result
CHECK_EQ(run_Ext(0x80000001, 0, 1), 0x00000001);
CHECK_EQ(run_Ext(0x80000001, 0, 32), 0x80000001);
CHECK_EQ(run_Ext(0x80000002, 1, 31), 0x40000001);
CHECK_EQ(run_Ext(0x80000100, 8, 24), 0x00800001);
CHECK_EQ(run_Ext(0x80010000, 16, 16), 0x00008001);
CHECK_EQ(run_Ext(0x81000000, 24, 8), 0x00000081);
CHECK_EQ(run_Ext(0x80000000, 31, 1), 0x00000001);
// Source values with positive sign.
CHECK_EQ(run_Ext(0x00000001, 0, 1), 0x00000001);
CHECK_EQ(run_Ext(0x40000001, 0, 32), 0x40000001);
CHECK_EQ(run_Ext(0x40000002, 1, 31), 0x20000001);
CHECK_EQ(run_Ext(0x40000100, 8, 24), 0x00400001);
CHECK_EQ(run_Ext(0x40010000, 16, 16), 0x00004001);
CHECK_EQ(run_Ext(0x41000000, 24, 8), 0x00000041);
CHECK_EQ(run_Ext(0x40000000, 31, 1), 0x00000000);
}
struct TestCaseMsaI5 {
uint64_t ws_lo;
uint64_t ws_hi;
uint32_t i5;
};
template <typename InstFunc, typename OperFunc>
void run_msa_i5(struct TestCaseMsaI5* input, bool i5_sign_ext,
InstFunc GenerateI5InstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
int32_t i5 =
i5_sign_ext ? static_cast<int32_t>(input->i5 << 27) >> 27 : input->i5;
load_elements_of_vector(assm, &(input->ws_lo), w0, t0, t1);
GenerateI5InstructionFunc(assm, i5);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input->ws_lo, input->i5), res.d[0]);
CHECK_EQ(GenerateOperationFunc(input->ws_hi, input->i5), res.d[1]);
}
TEST(MSA_addvi_subvi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI5 tc[] = {
// ws_lo, ws_hi, i5
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x0000001F},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0000000F},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x00000005},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x00000010},
{0xFFAB807F807FFFCD, 0x7F23FF80FF567F80, 0x0000000F},
{0x80FFEFFF7F12807F, 0x807F80FF7FDEFF78, 0x00000010}};
#define ADDVI_DF(lanes, mask) \
uint64_t res = 0; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = (kMSARegSize / lanes) * i; \
res |= ((((ws >> shift) & mask) + i5) & mask) << shift; \
} \
return res
#define SUBVI_DF(lanes, mask) \
uint64_t res = 0; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = (kMSARegSize / lanes) * i; \
res |= ((((ws >> shift) & mask) - i5) & mask) << shift; \
} \
return res
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI5); ++i) {
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_b(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesByte, UINT8_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_h(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesHalf, UINT16_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_w(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesWord, UINT32_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_d(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesDword, UINT64_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_b(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesByte, UINT8_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_h(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesHalf, UINT16_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_w(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesWord, UINT32_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_d(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesDword, UINT64_MAX); });
}
#undef ADDVI_DF
#undef SUBVI_DF
}
TEST(MSA_maxi_mini) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI5 tc[] = {
// ws_lo, ws_hi, i5
{0x7F80FF3480FF7F00, 0x8D7FFF80FF7F6780, 0x0000001F},
{0x7F80FF3480FF7F00, 0x8D7FFF80FF7F6780, 0x0000000F},
{0x7F80FF3480FF7F00, 0x8D7FFF80FF7F6780, 0x00000010},
{0x80007FFF91DAFFFF, 0x7FFF8000FFFF5678, 0x0000001F},
{0x80007FFF91DAFFFF, 0x7FFF8000FFFF5678, 0x0000000F},
{0x80007FFF91DAFFFF, 0x7FFF8000FFFF5678, 0x00000010},
{0x7FFFFFFF80000000, 0x12345678FFFFFFFF, 0x0000001F},
{0x7FFFFFFF80000000, 0x12345678FFFFFFFF, 0x0000000F},
{0x7FFFFFFF80000000, 0x12345678FFFFFFFF, 0x00000010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x0000001F},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0000000F},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x00000010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x00000015},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x00000009},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x00000003}};
#define MAXI_MINI_S_DF(lanes, mask, func) \
[](uint64_t ws, uint32_t ui5) { \
uint64_t res = 0; \
int64_t i5 = ArithmeticShiftRight(static_cast<int64_t>(ui5) << 59, 59); \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
int64_t elem = \
static_cast<int64_t>(((ws >> shift) & mask) << (64 - elem_size)) >> \
(64 - elem_size); \
res |= static_cast<uint64_t>(func(elem, i5) & mask) << shift; \
} \
return res; \
}
#define MAXI_MINI_U_DF(lanes, mask, func) \
[](uint64_t ws, uint32_t ui5) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= (func(elem, static_cast<uint64_t>(ui5)) & mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI5); ++i) {
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_b(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesByte, UINT8_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_h(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesHalf, UINT16_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_w(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesWord, UINT32_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_d(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesDword, UINT64_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_b(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesByte, UINT8_MAX, Min));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_h(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesHalf, UINT16_MAX, Min));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_w(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesWord, UINT32_MAX, Min));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_d(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesDword, UINT64_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_b(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesByte, UINT8_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_h(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesHalf, UINT16_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_w(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesWord, UINT32_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_d(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesDword, UINT64_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_b(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesByte, UINT8_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_h(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesHalf, UINT16_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_w(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesWord, UINT32_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_d(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesDword, UINT64_MAX, Min));
}
#undef MAXI_MINI_S_DF
#undef MAXI_MINI_U_DF
}
TEST(MSA_ceqi_clti_clei) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI5 tc[] = {
{0xFF69751BB9A7D9C3, 0xF7A594AEC8FF8A9C, 0x0000001F},
{0xE669FFFFB9A7D9C3, 0xF7A594AEFFFF8A9C, 0x0000001F},
{0xFFFFFFFFB9A7D9C3, 0xF7A594AEFFFFFFFF, 0x0000001F},
{0x2B0B5362C4E812DF, 0x3A0D80D68B3F0BC8, 0x0000000B},
{0x2B66000BC4E812DF, 0x3A0D000B8B3F8BC8, 0x0000000B},
{0x0000000BC4E812DF, 0x3A0D80D60000000B, 0x0000000B},
{0xF38062E13E38F8B0, 0x8041FFDEF2BFE636, 0x00000010},
{0xF35880003E38F8B0, 0x4F41FFDEF2BF8000, 0x00000010},
{0xF35862E180000000, 0x80000000F2BFE636, 0x00000010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x00000015},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x00000009},
{0xF30062E13E38F800, 0x4F00FFDEF2BF0036, 0x00000000}};
#define CEQI_CLTI_CLEI_S_DF(lanes, mask, func) \
[](uint64_t ws, uint32_t ui5) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
int64_t i5 = ArithmeticShiftRight(static_cast<int64_t>(ui5) << 59, 59); \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
int64_t elem = \
static_cast<int64_t>(((ws >> shift) & mask) << (64 - elem_size)) >> \
(64 - elem_size); \
res |= static_cast<uint64_t>((func)&mask) << shift; \
} \
return res; \
}
#define CEQI_CLTI_CLEI_U_DF(lanes, mask, func) \
[](uint64_t ws, uint64_t ui5) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI5); ++i) {
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_b(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesByte, UINT8_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_h(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesHalf, UINT16_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_w(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesWord, UINT32_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_d(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesDword, UINT64_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_b(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, i5) == -1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_h(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, i5) == -1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_w(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, i5) == -1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_d(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, i5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_b(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, i5) != 1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_h(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, i5) != 1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_w(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, i5) != 1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_d(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, i5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_b(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_h(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_w(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_d(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_b(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_h(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_w(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_d(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
}
#undef CEQI_CLTI_CLEI_S_DF
#undef CEQI_CLTI_CLEI_U_DF
}
struct TestCaseMsa2R {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t exp_res_lo;
uint64_t exp_res_hi;
};
template <typename Func>
void run_msa_2r(const struct TestCaseMsa2R* input,
Func Generate2RInstructionFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, reinterpret_cast<const uint64_t*>(input), w0,
t0, t1);
Generate2RInstructionFunc(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(input->exp_res_lo, res.d[0]);
CHECK_EQ(input->exp_res_hi, res.d[1]);
}
TEST(MSA_pcnt) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2R tc_b[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0808080808080808, 0x0808080808080808},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C,
0x0204050405050504, 0x0704030503070304},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8,
0x0404040303040207, 0x0403010504060403},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636,
0x0603030405030503, 0x0502080605070504}};
struct TestCaseMsa2R tc_h[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0010001000100010, 0x0010001000100010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C,
0x00060009000A0009, 0x000B0008000A0007},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8,
0x0008000700070009, 0x00070006000A0007},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636,
0x0009000700080008, 0x0007000E000C0009}};
struct TestCaseMsa2R tc_w[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0000002000000020, 0x0000002000000020},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C,
0x0000000F00000013, 0x0000001300000011},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8,
0x0000000F00000010, 0x0000000D00000011},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636,
0x0000001000000010, 0x0000001500000015}};
struct TestCaseMsa2R tc_d[] = {
// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0x40, 0x40},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x22, 0x24},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x1F, 0x1E},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x20, 0x2A}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseMsa2R); ++i) {
run_msa_2r(&tc_b[i], [](MacroAssembler& assm) { __ pcnt_b(w2, w0); });
run_msa_2r(&tc_h[i], [](MacroAssembler& assm) { __ pcnt_h(w2, w0); });
run_msa_2r(&tc_w[i], [](MacroAssembler& assm) { __ pcnt_w(w2, w0); });
run_msa_2r(&tc_d[i], [](MacroAssembler& assm) { __ pcnt_d(w2, w0); });
}
}
TEST(MSA_nlzc) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2R tc_b[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000,
0x0808080808080808, 0x0808080808080808},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x1169350B07030100, 0x7F011402381F0A6C,
0x0301020405060708, 0x0107030602030401},
{0x010806003478121F, 0x03013016073F7B08,
0x0704050802010303, 0x0607020305020104},
{0x0168321100083803, 0x07113F03013F1676,
0x0701020308040206, 0x0503020607020301}};
struct TestCaseMsa2R tc_h[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000,
0x0010001000100010, 0x0010001000100010},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x00010007000A003C, 0x37A5001E00010002,
0x000F000D000C000A, 0x0002000B000F000E},
{0x0026066200780EDF, 0x003D0003000F00C8,
0x000A000500090004, 0x000A000E000C0008},
{0x335807E100480030, 0x01410FDE12BF5636,
0x000200050009000A, 0x0007000400030001}};
struct TestCaseMsa2R tc_w[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000,
0x0000002000000020, 0x0000002000000020},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x00000005000007C3, 0x000014AE00006A9C,
0x0000001D00000015, 0x0000001300000011},
{0x00009362000112DF, 0x000380D6003F8BC8,
0x000000100000000F, 0x0000000E0000000A},
{0x135862E17E38F8B0, 0x0061FFDE03BFE636,
0x0000000300000001, 0x0000000900000006}};
struct TestCaseMsa2R tc_d[] = {
// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0x40, 0x40},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x000000000000014E, 0x00000000000176DA, 0x37, 0x2F},
{0x00000062C4E812DF, 0x000065D68B3F8BC8, 0x19, 0x11},
{0x00000000E338F8B0, 0x0754534ACAB32654, 0x20, 0x5}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseMsa2R); ++i) {
run_msa_2r(&tc_b[i], [](MacroAssembler& assm) { __ nlzc_b(w2, w0); });
run_msa_2r(&tc_h[i], [](MacroAssembler& assm) { __ nlzc_h(w2, w0); });
run_msa_2r(&tc_w[i], [](MacroAssembler& assm) { __ nlzc_w(w2, w0); });
run_msa_2r(&tc_d[i], [](MacroAssembler& assm) { __ nlzc_d(w2, w0); });
}
}
TEST(MSA_nloc) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2R tc_b[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0808080808080808, 0x0808080808080808},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xEE96CAF4F8FCFEFF, 0x80FEEBFDC7E0F593,
0x0301020405060708, 0x0107030602030401},
{0xFEF7F9FFCB87EDE0, 0xFCFECFE9F8C084F7,
0x0704050802010303, 0x0607020305020104},
{0xFE97CDEEFFF7C7FC, 0xF8EEC0FCFEC0E989,
0x0701020308040206, 0x0503020607020301}};
struct TestCaseMsa2R tc_h[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0010001000100010, 0x0010001000100010},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFEFFF8FFF5FFC3, 0xC85AFFE1FFFEFFFD,
0x000F000D000C000A, 0x0002000B000F000E},
{0xFFD9F99DFF87F120, 0xFFC2FFFCFFF0FF37,
0x000A000500090004, 0x000A000E000C0008},
{0xCCA7F81EFFB7FFCF, 0xFEBEF021ED40A9C9,
0x000200050009000A, 0x0007000400030001}};
struct TestCaseMsa2R tc_w[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0000002000000020, 0x0000002000000020},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFAFFFFF83C, 0xFFFFEB51FFFF9563,
0x0000001D00000015, 0x0000001300000011},
{0xFFFF6C9DFFFEED20, 0xFFFC7F29FFC07437,
0x000000100000000F, 0x0000000E0000000A},
{0xECA79D1E81C7074F, 0xFF9E0021FC4019C9,
0x0000000300000001, 0x0000000900000006}};
struct TestCaseMsa2R tc_d[] = {
// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0x40, 0x40},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFEB1, 0xFFFFFFFFFFFE8925, 0x37, 0x2F},
{0xFFFFFF9D3B17ED20, 0xFFFF9A2974C07437, 0x19, 0x11},
{0xFFFFFFFF1CC7074F, 0xF8ABACB5354CD9AB, 0x20, 0x5}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseMsa2R); ++i) {
run_msa_2r(&tc_b[i], [](MacroAssembler& assm) { __ nloc_b(w2, w0); });
run_msa_2r(&tc_h[i], [](MacroAssembler& assm) { __ nloc_h(w2, w0); });
run_msa_2r(&tc_w[i], [](MacroAssembler& assm) { __ nloc_w(w2, w0); });
run_msa_2r(&tc_d[i], [](MacroAssembler& assm) { __ nloc_d(w2, w0); });
}
}
struct TestCaseMsa2RF_F_U {
float ws1;
float ws2;
float ws3;
float ws4;
uint32_t exp_res_1;
uint32_t exp_res_2;
uint32_t exp_res_3;
uint32_t exp_res_4;
};
struct TestCaseMsa2RF_D_U {
double ws1;
double ws2;
uint64_t exp_res_1;
uint64_t exp_res_2;
};
TEST(MSA_fclass) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
#define BIT(n) (0x1 << n)
#define SNAN_BIT BIT(0)
#define QNAN_BIT BIT(1)
#define NEG_INFINITY_BIT BIT((2))
#define NEG_NORMAL_BIT BIT(3)
#define NEG_SUBNORMAL_BIT BIT(4)
#define NEG_ZERO_BIT BIT(5)
#define POS_INFINITY_BIT BIT(6)
#define POS_NORMAL_BIT BIT(7)
#define POS_SUBNORMAL_BIT BIT(8)
#define POS_ZERO_BIT BIT(9)
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_U tc_s[] = {
{1.f, -0.00001, 208e10f, -34.8e-30f, POS_NORMAL_BIT, NEG_NORMAL_BIT,
POS_NORMAL_BIT, NEG_NORMAL_BIT},
{inf_float, -inf_float, 0, -0.f, POS_INFINITY_BIT, NEG_INFINITY_BIT,
POS_ZERO_BIT, NEG_ZERO_BIT},
{3.036e-40f, -6.392e-43f, 1.41e-45f, -1.17e-38f, POS_SUBNORMAL_BIT,
NEG_SUBNORMAL_BIT, POS_SUBNORMAL_BIT, NEG_SUBNORMAL_BIT}};
const struct TestCaseMsa2RF_D_U tc_d[] = {
{1., -0.00000001, POS_NORMAL_BIT, NEG_NORMAL_BIT},
{208e10, -34.8e-300, POS_NORMAL_BIT, NEG_NORMAL_BIT},
{inf_double, -inf_double, POS_INFINITY_BIT, NEG_INFINITY_BIT},
{0, -0., POS_ZERO_BIT, NEG_ZERO_BIT},
{1.036e-308, -6.392e-309, POS_SUBNORMAL_BIT, NEG_SUBNORMAL_BIT},
{1.41e-323, -3.17e208, POS_SUBNORMAL_BIT, NEG_NORMAL_BIT}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fclass_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fclass_d(w2, w0); });
}
#undef BIT
#undef SNAN_BIT
#undef QNAN_BIT
#undef NEG_INFINITY_BIT
#undef NEG_NORMAL_BIT
#undef NEG_SUBNORMAL_BIT
#undef NEG_ZERO_BIT
#undef POS_INFINITY_BIT
#undef POS_NORMAL_BIT
#undef POS_SUBNORMAL_BIT
#undef POS_ZERO_BIT
}
struct TestCaseMsa2RF_F_I {
float ws1;
float ws2;
float ws3;
float ws4;
int32_t exp_res_1;
int32_t exp_res_2;
int32_t exp_res_3;
int32_t exp_res_4;
};
struct TestCaseMsa2RF_D_I {
double ws1;
double ws2;
int64_t exp_res_1;
int64_t exp_res_2;
};
TEST(MSA_ftrunc_s) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const float qNaN_float = std::numeric_limits<float>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const double qNaN_double = std::numeric_limits<double>::quiet_NaN();
const int32_t max_int32 = std::numeric_limits<int32_t>::max();
const int32_t min_int32 = std::numeric_limits<int32_t>::min();
const int64_t max_int64 = std::numeric_limits<int64_t>::max();
const int64_t min_int64 = std::numeric_limits<int64_t>::min();
const struct TestCaseMsa2RF_F_I tc_s[] = {
{inf_float, 2.345f, -324.9235f, 30004.51f, max_int32, 2, -324, 30004},
{-inf_float, -0.983f, 0.0832f, static_cast<float>(max_int32) * 3.f,
min_int32, 0, 0, max_int32},
{-23.125f, qNaN_float, 2 * static_cast<float>(min_int32), -0.f, -23, 0,
min_int32, 0}};
const struct TestCaseMsa2RF_D_I tc_d[] = {
{inf_double, 2.345, max_int64, 2},
{-324.9235, 246569139.51, -324, 246569139},
{-inf_double, -0.983, min_int64, 0},
{0.0832, 6 * static_cast<double>(max_int64), 0, max_int64},
{-21453889872.94, qNaN_double, -21453889872, 0},
{2 * static_cast<double>(min_int64), -0., min_int64, 0}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ftrunc_s_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ftrunc_s_d(w2, w0); });
}
}
TEST(MSA_ftrunc_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const float qNaN_float = std::numeric_limits<float>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const double qNaN_double = std::numeric_limits<double>::quiet_NaN();
const uint32_t max_uint32 = std::numeric_limits<uint32_t>::max();
const uint64_t max_uint64 = std::numeric_limits<uint64_t>::max();
const struct TestCaseMsa2RF_F_U tc_s[] = {
{inf_float, 2.345f, -324.9235f, 30004.51f, max_uint32, 2, 0, 30004},
{-inf_float, 0.983f, 0.0832f, static_cast<float>(max_uint32) * 3., 0, 0,
0, max_uint32},
{23.125f, qNaN_float, -0.982, -0.f, 23, 0, 0, 0}};
const struct TestCaseMsa2RF_D_U tc_d[] = {
{inf_double, 2.345, max_uint64, 2},
{-324.9235, 246569139.51, 0, 246569139},
{-inf_double, -0.983, 0, 0},
{0.0832, 6 * static_cast<double>(max_uint64), 0, max_uint64},
{21453889872.94, qNaN_double, 21453889872, 0},
{0.9889, -0., 0, 0}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ftrunc_u_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ftrunc_u_d(w2, w0); });
}
}
struct TestCaseMsa2RF_F_F {
float ws1;
float ws2;
float ws3;
float ws4;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_D_D {
double ws1;
double ws2;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_fsqrt) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_F tc_s[] = {
{81.f, 576.f, inf_float, -0.f, 9.f, 24.f, inf_float, -0.f}};
const struct TestCaseMsa2RF_D_D tc_d[] = {{81., inf_double, 9., inf_double},
{331776., -0., 576, -0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fsqrt_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fsqrt_d(w2, w0); });
}
}
TEST(MSA_frsqrt) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_F tc_s[] = {
{81.f, 576.f, inf_float, -0.f, 1.f / 9.f, 1.f / 24.f, 0.f, -inf_float},
{0.f, 1.f / 576.f, 1.f / 81.f, 1.f / 4.f, inf_float, 24.f, 9.f, 2.f}};
const struct TestCaseMsa2RF_D_D tc_d[] = {
{81., inf_double, 1. / 9., 0.},
{331776., -0., 1. / 576., -inf_double},
{0., 1. / 81, inf_double, 9.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ frsqrt_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ frsqrt_d(w2, w0); });
}
}
TEST(MSA_frcp) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_F tc_s[] = {
{12.f, 576.f, inf_float, -0.f, 1.f / 12.f, 1.f / 576.f, 0.f, -inf_float},
{0.f, 1.f / 576.f, -inf_float, 1.f / 400.f, inf_float, 576.f, -0.f,
400.f}};
const struct TestCaseMsa2RF_D_D tc_d[] = {
{81., inf_double, 1. / 81., 0.},
{331777., -0., 1. / 331777., -inf_double},
{0., 1. / 80, inf_double, 80.},
{1. / 40000., -inf_double, 40000., -0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ frcp_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ frcp_d(w2, w0); });
}
}
void test_frint_s(size_t data_size, TestCaseMsa2RF_F_F tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ frint_w(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
void test_frint_d(size_t data_size, TestCaseMsa2RF_D_D tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ frint_d(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
TEST(MSA_frint) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_F_F tc_s1[] = {
{0.f, 4.51f, 1.49f, -12.51f, 0.f, 5.f, 1.f, -13.f},
{-1.32f, -23.38f, 2.8f, -32.5f, -1.f, -23.f, 3.f, -32.f}};
struct TestCaseMsa2RF_D_D tc_d1[] = {{0., 4.51, 0., 5.},
{1.49, -12.51, 1., -13.},
{-1.32, -23.38, -1., -23.},
{2.8, -32.6, 3., -33.}};
test_frint_s(sizeof(tc_s1), tc_s1, kRoundToNearest);
test_frint_d(sizeof(tc_d1), tc_d1, kRoundToNearest);
struct TestCaseMsa2RF_F_F tc_s2[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0.f, 4.f, 1.f, -12.f},
{-1.f, -23.38f, 2.8f, -32.6f, -1.f, -23.f, 2.f, -32.f}};
struct TestCaseMsa2RF_D_D tc_d2[] = {{0., 4.5, 0., 4.},
{1.49, -12.51, 1., -12.},
{-1., -23.38, -1., -23.},
{2.8, -32.6, 2., -32.}};
test_frint_s(sizeof(tc_s2), tc_s2, kRoundToZero);
test_frint_d(sizeof(tc_d2), tc_d2, kRoundToZero);
struct TestCaseMsa2RF_F_F tc_s3[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0.f, 5.f, 2.f, -12.f},
{-1.f, -23.38f, 2.8f, -32.6f, -1.f, -23.f, 3.f, -32.f}};
struct TestCaseMsa2RF_D_D tc_d3[] = {{0., 4.5, 0., 5.},
{1.49, -12.51, 2., -12.},
{-1., -23.38, -1., -23.},
{2.8, -32.6, 3., -32.}};
test_frint_s(sizeof(tc_s3), tc_s3, kRoundToPlusInf);
test_frint_d(sizeof(tc_d3), tc_d3, kRoundToPlusInf);
struct TestCaseMsa2RF_F_F tc_s4[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0.f, 4.f, 1.f, -13.f},
{-1.f, -23.38f, 2.8f, -32.6f, -1.f, -24.f, 2.f, -33.f}};
struct TestCaseMsa2RF_D_D tc_d4[] = {{0., 4.5, 0., 4.},
{1.49, -12.51, 1., -13.},
{-1., -23.38, -1., -24.},
{2.8, -32.6, 2., -33.}};
test_frint_s(sizeof(tc_s4), tc_s4, kRoundToMinusInf);
test_frint_d(sizeof(tc_d4), tc_d4, kRoundToMinusInf);
}
TEST(MSA_flog2) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
struct TestCaseMsa2RF_F_F tc_s[] = {
{std::ldexp(0.58f, -48), std::ldexp(0.5f, 110), std::ldexp(1.11f, -130),
inf_float, -49.f, 109.f, -130.f, inf_float},
{0.f, -0.f, std::ldexp(0.89f, -12), std::ldexp(0.32f, 126), -inf_float,
-inf_float, -13.f, 124.f}};
struct TestCaseMsa2RF_D_D tc_d[] = {
{std::ldexp(0.58, -48), std::ldexp(0.5, 110), -49., 109.},
{std::ldexp(1.11, -1050), inf_double, -1050., inf_double},
{0., -0., -inf_double, -inf_double},
{std::ldexp(0.32, 1021), std::ldexp(1.23, -123), 1019., -123.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ flog2_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ flog2_d(w2, w0); });
}
}
void test_ftint_s_s(size_t data_size, TestCaseMsa2RF_F_I tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_F_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_s_w(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
void test_ftint_s_d(size_t data_size, TestCaseMsa2RF_D_I tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_D_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_s_d(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
TEST(MSA_ftint_s) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const int32_t int32_max = std::numeric_limits<int32_t>::max();
const int32_t int32_min = std::numeric_limits<int32_t>::min();
const int64_t int64_max = std::numeric_limits<int64_t>::max();
const int64_t int64_min = std::numeric_limits<int64_t>::min();
struct TestCaseMsa2RF_F_I tc_s1[] = {
{0.f, 4.51f, 1.49f, -12.51f, 0, 5, 1, -13},
{-0.32f, -23.38f, 2.8f, -32.6f, 0, -23, 3, -33},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d1[] = {
{0., 4.51, 0, 5},
{1.49, -12.51, 1, -13},
{-0.32, -23.38, 0, -23},
{2.8, -32.6, 3, -33},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s1), tc_s1, kRoundToNearest);
test_ftint_s_d(sizeof(tc_d1), tc_d1, kRoundToNearest);
struct TestCaseMsa2RF_F_I tc_s2[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, -12},
{-0.f, -23.38f, 2.8f, -32.6f, -0, -23, 2, -32},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d2[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, -12},
{-0., -23.38, -0, -23},
{2.8, -32.6, 2, -32},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s2), tc_s2, kRoundToZero);
test_ftint_s_d(sizeof(tc_d2), tc_d2, kRoundToZero);
struct TestCaseMsa2RF_F_I tc_s3[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 5, 2, -12},
{-0.f, -23.38f, 2.8f, -32.6f, -0, -23, 3, -32},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d3[] = {
{0., 4.5, 0, 5},
{1.49, -12.51, 2, -12},
{-0., -23.38, -0, -23},
{2.8, -32.6, 3, -32},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s3), tc_s3, kRoundToPlusInf);
test_ftint_s_d(sizeof(tc_d3), tc_d3, kRoundToPlusInf);
struct TestCaseMsa2RF_F_I tc_s4[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, -13},
{-0.f, -23.38f, 2.8f, -32.6f, -0, -24, 2, -33},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d4[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, -13},
{-0., -23.38, -0, -24},
{2.8, -32.6, 2, -33},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s4), tc_s4, kRoundToMinusInf);
test_ftint_s_d(sizeof(tc_d4), tc_d4, kRoundToMinusInf);
}
void test_ftint_u_s(size_t data_size, TestCaseMsa2RF_F_U tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_F_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_u_w(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
void test_ftint_u_d(size_t data_size, TestCaseMsa2RF_D_U tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_D_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_u_d(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
TEST(MSA_ftint_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const uint32_t uint32_max = std::numeric_limits<uint32_t>::max();
const uint64_t uint64_max = std::numeric_limits<uint64_t>::max();
struct TestCaseMsa2RF_F_U tc_s1[] = {
{0.f, 4.51f, 1.49f, -12.51f, 0, 5, 1, 0},
{-0.32f, 23.38f, 2.8f, 32.6f, 0, 23, 3, 33},
{inf_float, -inf_float, 0, 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d1[] = {
{0., 4.51, 0, 5},
{1.49, -12.51, 1, 0},
{-0.32, 23.38, 0, 23},
{2.8, 32.6, 3, 33},
{inf_double, -inf_double, uint64_max, 0},
{-0., 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s1), tc_s1, kRoundToNearest);
test_ftint_u_d(sizeof(tc_d1), tc_d1, kRoundToNearest);
struct TestCaseMsa2RF_F_U tc_s2[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, 0},
{-0.f, 23.38f, 2.8f, 32.6f, 0, 23, 2, 32},
{inf_float, -inf_float, 0., 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d2[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, 0},
{-0., 23.38, 0, 23},
{2.8, 32.6, 2, 32},
{inf_double, -inf_double, uint64_max, 0},
{-0.2345, 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s2), tc_s2, kRoundToZero);
test_ftint_u_d(sizeof(tc_d2), tc_d2, kRoundToZero);
struct TestCaseMsa2RF_F_U tc_s3[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 5, 2, 0},
{-0.f, 23.38f, 2.8f, 32.6f, 0, 24, 3, 33},
{inf_float, -inf_float, 0, 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d3[] = {
{0., 4.5, 0, 5},
{1.49, -12.51, 2, 0},
{-0., 23.38, -0, 24},
{2.8, 32.6, 3, 33},
{inf_double, -inf_double, uint64_max, 0},
{-0.5252, 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s3), tc_s3, kRoundToPlusInf);
test_ftint_u_d(sizeof(tc_d3), tc_d3, kRoundToPlusInf);
struct TestCaseMsa2RF_F_U tc_s4[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, 0},
{-0.f, 23.38f, 2.8f, 32.6f, 0, 23, 2, 32},
{inf_float, -inf_float, 0, 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d4[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, 0},
{-0., 23.38, -0, 23},
{2.8, 32.6, 2, 32},
{inf_double, -inf_double, uint64_max, 0},
{-0.098797, 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s4), tc_s4, kRoundToMinusInf);
test_ftint_u_d(sizeof(tc_d4), tc_d4, kRoundToMinusInf);
}
struct TestCaseMsa2RF_U_F {
uint32_t ws1;
uint32_t ws2;
uint32_t ws3;
uint32_t ws4;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_U_D {
uint64_t ws1;
uint64_t ws2;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_ffint_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_U_F tc_s[] = {
{0, 345, 234, 1000, 0.f, 345.f, 234.f, 1000.f}};
struct TestCaseMsa2RF_U_D tc_d[] = {{0, 345, 0., 345.},
{234, 1000, 234., 1000.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffint_u_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_U_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffint_u_d(w2, w0); });
}
}
struct TestCaseMsa2RF_I_F {
int32_t ws1;
int32_t ws2;
int32_t ws3;
int32_t ws4;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_I_D {
int64_t ws1;
int64_t ws2;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_ffint_s) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_I_F tc_s[] = {
{0, 345, -234, 1000, 0.f, 345.f, -234.f, 1000.f}};
struct TestCaseMsa2RF_I_D tc_d[] = {{0, 345, 0., 345.},
{-234, 1000, -234., 1000.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_I_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffint_s_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_I_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffint_s_d(w2, w0); });
}
}
struct TestCaseMsa2RF_U16_F {
uint16_t ws1;
uint16_t ws2;
uint16_t ws3;
uint16_t ws4;
uint16_t ws5;
uint16_t ws6;
uint16_t ws7;
uint16_t ws8;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_F_D {
float ws1;
float ws2;
float ws3;
float ws4;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_fexupl) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
struct TestCaseMsa2RF_U16_F tc_s[] = {
{1, 2, 0x7C00, 0x0C00, 0, 0x7C00, 0xFC00, 0x8000, 0.f, inf_float,
-inf_float, -0.f},
{0xFC00, 0xFFFF, 0x00FF, 0x8000, 0x81FE, 0x8000, 0x0345, 0xAAAA,
-3.0398368835e-5f, -0.f, 4.9889088e-5f, -5.2062988281e-2f},
{3, 4, 0x5555, 6, 0x2AAA, 0x8700, 0x7777, 0x6A8B, 5.2062988281e-2f,
-1.06811523458e-4f, 3.0576e4f, 3.35e3f}};
struct TestCaseMsa2RF_F_D tc_d[] = {
{0.f, 123.456f, inf_float, -0.f, inf_double, -0.},
{-inf_float, -3.f, 0.f, -inf_float, 0., -inf_double},
{2.3f, 3., 1.37747639043129518071e-41f, -3.22084585277826e35f,
1.37747639043129518071e-41, -3.22084585277826e35}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fexupl_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_F_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fexupl_d(w2, w0); });
}
}
TEST(MSA_fexupr) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
struct TestCaseMsa2RF_U16_F tc_s[] = {
{0, 0x7C00, 0xFC00, 0x8000, 1, 2, 0x7C00, 0x0C00, 0.f, inf_float,
-inf_float, -0.f},
{0x81FE, 0x8000, 0x0345, 0xAAAA, 0xFC00, 0xFFFF, 0x00FF, 0x8000,
-3.0398368835e-5f, -0.f, 4.9889088e-5f, -5.2062988281e-2f},
{0x2AAA, 0x8700, 0x7777, 0x6A8B, 3, 4, 0x5555, 6, 5.2062988281e-2f,
-1.06811523458e-4f, 3.0576e4f, 3.35e3f}};
struct TestCaseMsa2RF_F_D tc_d[] = {
{inf_float, -0.f, 0.f, 123.456f, inf_double, -0.},
{0.f, -inf_float, -inf_float, -3.f, 0., -inf_double},
{1.37747639043129518071e-41f, -3.22084585277826e35f, 2.3f, 3.,
1.37747639043129518071e-41, -3.22084585277826e35}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fexupr_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_F_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fexupr_d(w2, w0); });
}
}
struct TestCaseMsa2RF_U32_D {
uint32_t ws1;
uint32_t ws2;
uint32_t ws3;
uint32_t ws4;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_ffql) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_U16_F tc_s[] = {{0, 3, 0xFFFF, 0x8000, 0x8000, 0xE000,
0x0FF0, 0, -1.f, -0.25f,
0.12451171875f, 0.f}};
struct TestCaseMsa2RF_U32_D tc_d[] = {
{0, 45, 0x80000000, 0xE0000000, -1., -0.25},
{0x28379, 0xAAAA5555, 0x024903D3, 0, 17.853239085525274277e-3, 0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffql_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_U32_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffql_d(w2, w0); });
}
}
TEST(MSA_ffqr) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_U16_F tc_s[] = {{0x8000, 0xE000, 0x0FF0, 0, 0, 3,
0xFFFF, 0x8000, -1.f, -0.25f,
0.12451171875f, 0.f}};
struct TestCaseMsa2RF_U32_D tc_d[] = {
{0x80000000, 0xE0000000, 0, 45, -1., -0.25},
{0x024903D3, 0, 0x28379, 0xAAAA5555, 17.853239085525274277e-3, 0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffqr_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_U32_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffqr_d(w2, w0); });
}
}
struct TestCaseMsaVector {
uint64_t wd_lo;
uint64_t wd_hi;
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wt_lo;
uint64_t wt_hi;
};
template <typename InstFunc, typename OperFunc>
void run_msa_vector(struct TestCaseMsaVector* input,
InstFunc GenerateVectorInstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, &(input->ws_lo), w0, t0, t1);
load_elements_of_vector(assm, &(input->wt_lo), w2, t0, t1);
load_elements_of_vector(assm, &(input->wd_lo), w4, t0, t1);
GenerateVectorInstructionFunc(assm);
store_elements_of_vector(assm, w4, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input->wd_lo, input->ws_lo, input->wt_lo),
res.d[0]);
CHECK_EQ(GenerateOperationFunc(input->wd_hi, input->ws_hi, input->wt_hi),
res.d[1]);
}
TEST(MSA_vector) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaVector tc[] = {
// wd_lo, wd_hi, ws_lo, ws_hi, wt_lo, wt_hi
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0xDCD39D91F9057627,
0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 0x49547AAD691DA4CA},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x401614523D830549,
0xD7C46D613F50EDDD, 0x52284CBC60A1562B, 0x1756ED510D8849CD},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0xD6E2D2EBCB40D72F,
0x13A619AFCE67B079, 0x36CCE284343E40F9, 0xB4E8F44FD148BF7F}};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaVector); ++i) {
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ and_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ws & wt; });
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ or_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ws | wt; });
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ nor_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ~(ws | wt); });
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ xor_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ws ^ wt; });
run_msa_vector(&tc[i], [](MacroAssembler& assm) { __ bmnz_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) {
return (ws & wt) | (wd & ~wt);
});
run_msa_vector(&tc[i], [](MacroAssembler& assm) { __ bmz_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) {
return (ws & ~wt) | (wd & wt);
});
run_msa_vector(&tc[i], [](MacroAssembler& assm) { __ bsel_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) {
return (ws & ~wd) | (wt & wd);
});
}
}
struct TestCaseMsaBit {
uint64_t wd_lo;
uint64_t wd_hi;
uint64_t ws_lo;
uint64_t ws_hi;
uint32_t m;
};
template <typename InstFunc, typename OperFunc>
void run_msa_bit(struct TestCaseMsaBit* input, InstFunc GenerateInstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, &(input->ws_lo), w0, t0, t1);
load_elements_of_vector(assm, &(input->wd_lo), w2, t0, t1);
GenerateInstructionFunc(assm, input->m);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input->wd_lo, input->ws_lo, input->m),
res.d[0]);
CHECK_EQ(GenerateOperationFunc(input->wd_hi, input->ws_hi, input->m),
res.d[1]);
}
TEST(MSA_slli_srai_srli) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {
// wd_lo, wd_hi ws_lo, ws_hi, m
{0, 0, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 3},
{0, 0, 0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0, 0, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0, 0, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0, 0, 0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0, 0, 0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0, 0, 0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0, 0, 0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define SLLI_SRLI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
return res; \
}
#define SRAI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
int64_t elem = \
static_cast<int64_t>(((ws >> shift) & mask) << (64 - elem_size)) >> \
(64 - elem_size); \
res |= static_cast<uint64_t>((func)&mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_b(w2, w0, m % 8); },
SLLI_SRLI_DF(kMSALanesByte, UINT8_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_h(w2, w0, m % 16); },
SLLI_SRLI_DF(kMSALanesHalf, UINT16_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_w(w2, w0, m % 32); },
SLLI_SRLI_DF(kMSALanesWord, UINT32_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_d(w2, w0, m % 64); },
SLLI_SRLI_DF(kMSALanesDword, UINT64_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_b(w2, w0, m % 8); },
SLLI_SRLI_DF(kMSALanesByte, UINT8_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_h(w2, w0, m % 16); },
SLLI_SRLI_DF(kMSALanesHalf, UINT16_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_w(w2, w0, m % 32); },
SLLI_SRLI_DF(kMSALanesWord, UINT32_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_d(w2, w0, m % 64); },
SLLI_SRLI_DF(kMSALanesDword, UINT64_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_b(w2, w0, m % 8); },
SLLI_SRLI_DF(
kMSALanesByte, UINT8_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_h(w2, w0, m % 16); },
SLLI_SRLI_DF(
kMSALanesHalf, UINT16_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_w(w2, w0, m % 32); },
SLLI_SRLI_DF(
kMSALanesWord, UINT32_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_d(w2, w0, m % 64); },
SLLI_SRLI_DF(
kMSALanesDword, UINT64_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_b(w2, w0, m % 8); },
SRAI_DF(kMSALanesByte, UINT8_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_h(w2, w0, m % 16); },
SRAI_DF(kMSALanesHalf, UINT16_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_w(w2, w0, m % 32); },
SRAI_DF(kMSALanesWord, UINT32_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_d(w2, w0, m % 64); },
SRAI_DF(kMSALanesDword, UINT64_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_b(w2, w0, m % 8); },
SRAI_DF(kMSALanesByte, UINT8_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_h(w2, w0, m % 16); },
SRAI_DF(kMSALanesHalf, UINT16_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_w(w2, w0, m % 32); },
SRAI_DF(kMSALanesWord, UINT32_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_d(w2, w0, m % 64); },
SRAI_DF(kMSALanesDword, UINT64_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
}
#undef SLLI_SRLI_DF
#undef SRAI_DF
}
TEST(MSA_bclri_bseti_bnegi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {
// wd_lo, wd_hi, ws_lo, ws_hi, m
{0, 0, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 3},
{0, 0, 0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0, 0, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0, 0, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0, 0, 0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0, 0, 0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0, 0, 0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0, 0, 0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define BCLRI_BSETI_BNEGI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_b(w2, w0, m % 8); },
BCLRI_BSETI_BNEGI_DF(kMSALanesByte, UINT8_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_h(w2, w0, m % 16); },
BCLRI_BSETI_BNEGI_DF(kMSALanesHalf, UINT16_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_w(w2, w0, m % 32); },
BCLRI_BSETI_BNEGI_DF(kMSALanesWord, UINT32_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_d(w2, w0, m % 64); },
BCLRI_BSETI_BNEGI_DF(kMSALanesDword, UINT64_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_b(w2, w0, m % 8); },
BCLRI_BSETI_BNEGI_DF(kMSALanesByte, UINT8_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_h(w2, w0, m % 16); },
BCLRI_BSETI_BNEGI_DF(kMSALanesHalf, UINT16_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_w(w2, w0, m % 32); },
BCLRI_BSETI_BNEGI_DF(kMSALanesWord, UINT32_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_d(w2, w0, m % 64); },
BCLRI_BSETI_BNEGI_DF(kMSALanesDword, UINT64_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_b(w2, w0, m % 8); },
BCLRI_BSETI_BNEGI_DF(kMSALanesByte, UINT8_MAX,
((1ull << (m % elem_size)) ^ elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_h(w2, w0, m % 16); },
BCLRI_BSETI_BNEGI_DF(kMSALanesHalf, UINT16_MAX,
((1ull << (m % elem_size)) ^ elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_w(w2, w0, m % 32); },
BCLRI_BSETI_BNEGI_DF(kMSALanesWord, UINT32_MAX,
((1ull << (m % elem_size)) ^ elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_d(w2, w0, m % 64); },
BCLRI_BSETI_BNEGI_DF(kMSALanesDword, UINT64_MAX,
((1ull << (m % elem_size)) ^ elem)));
}
#undef BCLRI_BSETI_BNEGI_DF
}
TEST(MSA_binsli_binsri) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {// wd_lo, wd_hi, ws_lo, ws_hi, m
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 3},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define BINSLI_BINSRI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
int bits = m % elem_size + 1; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t ws_elem = (ws >> shift) & mask; \
if (bits == elem_size) { \
res |= (ws_elem & mask) << shift; \
} else { \
uint64_t r_mask = (1ull << bits) - 1; \
uint64_t l_mask = r_mask << (elem_size - bits); \
USE(l_mask); \
uint64_t wd_elem = (wd >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_b(w2, w0, m % 8); },
BINSLI_BINSRI_DF(kMSALanesByte, UINT8_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_h(w2, w0, m % 16); },
BINSLI_BINSRI_DF(kMSALanesHalf, UINT16_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_w(w2, w0, m % 32); },
BINSLI_BINSRI_DF(kMSALanesWord, UINT32_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_d(w2, w0, m % 64); },
BINSLI_BINSRI_DF(kMSALanesDword, UINT64_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_b(w2, w0, m % 8); },
BINSLI_BINSRI_DF(kMSALanesByte, UINT8_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_h(w2, w0, m % 16); },
BINSLI_BINSRI_DF(kMSALanesHalf, UINT16_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_w(w2, w0, m % 32); },
BINSLI_BINSRI_DF(kMSALanesWord, UINT32_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_d(w2, w0, m % 64); },
BINSLI_BINSRI_DF(kMSALanesDword, UINT64_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
}
#undef BINSLI_BINSRI_DF
}
TEST(MSA_sat_s_sat_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {
// wd_lo, wd_hi, ws_lo, ws_hi, m
{0, 0, 0xF35862E13E3808B0, 0x4F41FFDEF2BFE636, 3},
{0, 0, 0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0, 0, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0, 0, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0, 0, 0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0, 0, 0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0, 0, 0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0, 0, 0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define SAT_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
m %= elem_size; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem_u64 = (ws >> shift) & mask; \
int64_t elem_i64 = static_cast<int64_t>(elem_u64 << (64 - elem_size)) >> \
(64 - elem_size); \
USE(elem_i64); \
res |= ((func)&mask) << shift; \
} \
return res; \
}
#define M_MAX_INT(x) static_cast<int64_t>((1LL << ((x)-1)) - 1)
#define M_MIN_INT(x) static_cast<int64_t>(-(1LL << ((x)-1)))
#define M_MAX_UINT(x) static_cast<uint64_t>(-1ULL >> (64 - (x)))
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_b(w2, w0, m % 8); },
SAT_DF(kMSALanesByte, UINT8_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_h(w2, w0, m % 16); },
SAT_DF(kMSALanesHalf, UINT16_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_w(w2, w0, m % 32); },
SAT_DF(kMSALanesWord, UINT32_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_d(w2, w0, m % 64); },
SAT_DF(kMSALanesDword, UINT64_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_b(w2, w0, m % 8); },
SAT_DF(
kMSALanesByte, UINT8_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_h(w2, w0, m % 16); },
SAT_DF(
kMSALanesHalf, UINT16_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_w(w2, w0, m % 32); },
SAT_DF(
kMSALanesWord, UINT32_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_d(w2, w0, m % 64); },
SAT_DF(
kMSALanesDword, UINT64_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
}
#undef SAT_DF
#undef M_MAX_INT
#undef M_MIN_INT
#undef M_MAX_UINT
}
template <typename InstFunc, typename OperFunc>
void run_msa_i10(int32_t input, InstFunc GenerateVectorInstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
GenerateVectorInstructionFunc(assm, input);
store_elements_of_vector(assm, w0, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input), res.d[0]);
CHECK_EQ(GenerateOperationFunc(input), res.d[1]);
}
TEST(MSA_ldi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
// signed 10bit integers: -512 .. 511
int32_t tc[] = {0, -1, 1, 256, -256, -178, 352, -512, 511};
#define LDI_DF(lanes, mask) \
[](int32_t s10) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
int64_t s10_64 = \
ArithmeticShiftRight(static_cast<int64_t>(s10) << 54, 54); \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
res |= static_cast<uint64_t>(s10_64 & mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(int32_t); ++i) {
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_b(w0, s10); },
LDI_DF(kMSALanesByte, UINT8_MAX));
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_h(w0, s10); },
LDI_DF(kMSALanesHalf, UINT16_MAX));
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_w(w0, s10); },
LDI_DF(kMSALanesWord, UINT32_MAX));
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_d(w0, s10); },
LDI_DF(kMSALanesDword, UINT64_MAX));
}
#undef LDI_DF
}
template <typename T, typename InstFunc>
void run_msa_mi10(InstFunc GenerateVectorInstructionFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
T in_test_vector[1024];
T out_test_vector[1024];
T* in_array_middle = in_test_vector + arraysize(in_test_vector) / 2;
T* out_array_middle = out_test_vector + arraysize(out_test_vector) / 2;
v8::base::RandomNumberGenerator rand_gen(FLAG_random_seed);
for (unsigned int i = 0; i < arraysize(in_test_vector); i++) {
in_test_vector[i] = static_cast<T>(rand_gen.NextInt());
out_test_vector[i] = 0;
}
GenerateVectorInstructionFunc(assm);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F4>::FromCode(*code);
(f.Call(in_array_middle, out_array_middle, 0, 0, 0));
CHECK_EQ(memcmp(in_test_vector, out_test_vector, arraysize(in_test_vector)),
0);
}
TEST(MSA_load_store_vector) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
run_msa_mi10<uint8_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 16) {
__ ld_b(w0, MemOperand(a0, i));
__ st_b(w0, MemOperand(a1, i));
}
});
run_msa_mi10<uint16_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 8) {
__ ld_h(w0, MemOperand(a0, i));
__ st_h(w0, MemOperand(a1, i));
}
});
run_msa_mi10<uint32_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 4) {
__ ld_w(w0, MemOperand(a0, i));
__ st_w(w0, MemOperand(a1, i));
}
});
run_msa_mi10<uint64_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 2) {
__ ld_d(w0, MemOperand(a0, i));
__ st_d(w0, MemOperand(a1, i));
}
});
}
struct TestCaseMsa3R {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wt_lo;
uint64_t wt_hi;
uint64_t wd_lo;
uint64_t wd_hi;
};
static const uint64_t Unpredictable = 0x312014017725ll;
template <typename InstFunc, typename OperFunc>
void run_msa_3r(struct TestCaseMsa3R* input, InstFunc GenerateI5InstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, &(input->wt_lo), w0, t0, t1);
load_elements_of_vector(assm, &(input->ws_lo), w1, t0, t1);
load_elements_of_vector(assm, &(input->wd_lo), w2, t0, t1);
GenerateI5InstructionFunc(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
GenerateOperationFunc(&input->ws_lo, &input->wt_lo, &input->wd_lo);
if (input->wd_lo != Unpredictable) {
CHECK_EQ(input->wd_lo, res.d[0]);
}
if (input->wd_hi != Unpredictable) {
CHECK_EQ(input->wd_hi, res.d[1]);
}
}
TEST(MSA_3R_instructions) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa3R tc[] = {
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3,
0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF,
0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3,
0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF,
0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8},
{0xFFAB807F807FFFCD, 0x7F23FF80FF567F80, 0xFFAB807F807FFFCD,
0x7F23FF80FF567F80, 0xFFAB807F807FFFCD, 0x7F23FF80FF567F80},
{0x80FFEFFF7F12807F, 0x807F80FF7FDEFF78, 0x80FFEFFF7F12807F,
0x807F80FF7FDEFF78, 0x80FFEFFF7F12807F, 0x807F80FF7FDEFF78},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF},
{0x0000000000000000, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0000000000000000, 0x0000000000000000, 0xFFFFFFFFFFFFFFFF},
{0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000,
0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000},
{0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00,
0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00},
{0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0,
0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0},
{0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF,
0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF},
{0xFFFF00000000FFFF, 0xFFFF00000000FFFF, 0xFFFF00000000FFFF,
0xFFFF00000000FFFF, 0xFFFF00000000FFFF, 0xFFFF00000000FFFF}};
#define SLL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>((wt[i] >> shift) & mask) % size_in_bits; \
res |= (static_cast<uint64_t>(src_op << shift_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define SRA_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = ((wt[i] >> shift) & mask) % size_in_bits; \
res |= (static_cast<uint64_t>(ArithmeticShiftRight(src_op, shift_op) & \
mask)) \
<< shift; \
} \
wd[i] = res; \
}
#define SRL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
res |= (static_cast<uint64_t>(src_op >> shift_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define BCRL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
T r = (static_cast<T>(~(1ull << shift_op)) & src_op) & mask; \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BSET_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
T r = (static_cast<T>(1ull << shift_op) | src_op) & mask; \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BNEG_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
T r = (static_cast<T>(1ull << shift_op) ^ src_op) & mask; \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BINSL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
int bits = shift_op + 1; \
T r; \
if (bits == size_in_bits) { \
r = static_cast<T>(ws_op); \
} else { \
uint64_t mask2 = ((1ull << bits) - 1) << (size_in_bits - bits); \
r = static_cast<T>((static_cast<T>(mask2) & ws_op) | \
(static_cast<T>(~mask2) & wd_op)); \
} \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BINSR_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
int bits = shift_op + 1; \
T r; \
if (bits == size_in_bits) { \
r = static_cast<T>(ws_op); \
} else { \
uint64_t mask2 = (1ull << bits) - 1; \
r = static_cast<T>((static_cast<T>(mask2) & ws_op) | \
(static_cast<T>(~mask2) & wd_op)); \
} \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define ADDV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op + wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define SUBV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op - wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MAX_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Max<T>(ws_op, wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define MIN_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Min<T>(ws_op, wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define MAXA_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= \
(static_cast<uint64_t>(Nabs(ws_op) < Nabs(wt_op) ? ws_op : wt_op) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define MINA_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= \
(static_cast<uint64_t>(Nabs(ws_op) > Nabs(wt_op) ? ws_op : wt_op) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define CEQ_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(!Compare(ws_op, wt_op) ? -1ull : 0ull) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define CLT_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>((Compare(ws_op, wt_op) == -1) ? -1ull \
: 0ull) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define CLE_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>((Compare(ws_op, wt_op) != 1) ? -1ull \
: 0ull) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define ADD_A_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Abs(ws_op) + Abs(wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define ADDS_A_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = Nabs(static_cast<T>((ws[i] >> shift) & mask)); \
T wt_op = Nabs(static_cast<T>((wt[i] >> shift) & mask)); \
T r; \
if (ws_op < -std::numeric_limits<T>::max() - wt_op) { \
r = std::numeric_limits<T>::max(); \
} else { \
r = -(ws_op + wt_op); \
} \
res |= (static_cast<uint64_t>(r) & mask) << shift; \
} \
wd[i] = res; \
}
#define ADDS_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(SaturateAdd(ws_op, wt_op)) & mask) \
<< shift; \
} \
wd[i] = res; \
}
#define AVE_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>( \
((wt_op & ws_op) + ((ws_op ^ wt_op) >> 1)) & mask)) \
<< shift; \
} \
wd[i] = res; \
}
#define AVER_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>( \
((wt_op | ws_op) - ((ws_op ^ wt_op) >> 1)) & mask)) \
<< shift; \
} \
wd[i] = res; \
}
#define SUBS_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(SaturateSub(ws_op, wt_op)) & mask) \
<< shift; \
} \
wd[i] = res; \
}
#define SUBSUS_U_DF(T, lanes, mask) \
typedef typename std::make_unsigned<T>::type uT; \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
uT ws_op = static_cast<uT>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
T r; \
if (wt_op > 0) { \
uT wtu = static_cast<uT>(wt_op); \
if (wtu > ws_op) { \
r = 0; \
} else { \
r = static_cast<T>(ws_op - wtu); \
} \
} else { \
if (ws_op > std::numeric_limits<uT>::max() + wt_op) { \
r = static_cast<T>(std::numeric_limits<uT>::max()); \
} else { \
r = static_cast<T>(ws_op - wt_op); \
} \
} \
res |= (static_cast<uint64_t>(r) & mask) << shift; \
} \
wd[i] = res; \
}
#define SUBSUU_S_DF(T, lanes, mask) \
typedef typename std::make_unsigned<T>::type uT; \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
uT ws_op = static_cast<uT>((ws[i] >> shift) & mask); \
uT wt_op = static_cast<uT>((wt[i] >> shift) & mask); \
uT wdu; \
T r; \
if (ws_op > wt_op) { \
wdu = ws_op - wt_op; \
if (wdu > std::numeric_limits<T>::max()) { \
r = std::numeric_limits<T>::max(); \
} else { \
r = static_cast<T>(wdu); \
} \
} else { \
wdu = wt_op - ws_op; \
CHECK(-std::numeric_limits<T>::max() == \
std::numeric_limits<T>::min() + 1); \
if (wdu <= std::numeric_limits<T>::max()) { \
r = -static_cast<T>(wdu); \
} else { \
r = std::numeric_limits<T>::min(); \
} \
} \
res |= (static_cast<uint64_t>(r) & mask) << shift; \
} \
wd[i] = res; \
}
#define ASUB_S_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Abs(ws_op - wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define ASUB_U_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op > wt_op ? ws_op - wt_op \
: wt_op - ws_op) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define MULV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op * wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MADDV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(wd_op + ws_op * wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MSUBV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(wd_op - ws_op * wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define DIV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
if (wt_op == 0) { \
res = Unpredictable; \
break; \
} \
res |= (static_cast<uint64_t>(ws_op / wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MOD_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
if (wt_op == 0) { \
res = Unpredictable; \
break; \
} \
res |= (static_cast<uint64_t>(wt_op != 0 ? ws_op % wt_op : 0) & mask) \
<< shift; \
} \
wd[i] = res; \
}
#define SRAR_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = ((wt[i] >> shift) & mask) % size_in_bits; \
uint32_t bit = shift_op == 0 ? 0 : src_op >> (shift_op - 1) & 1; \
res |= (static_cast<uint64_t>(ArithmeticShiftRight(src_op, shift_op) + \
bit) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define PCKEV_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[i] = wt_p[2 * i]; \
wd_p[i + lanes / 2] = ws_p[2 * i]; \
}
#define PCKOD_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[i] = wt_p[2 * i + 1]; \
wd_p[i + lanes / 2] = ws_p[2 * i + 1]; \
}
#define ILVL_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[i + lanes / 2]; \
wd_p[2 * i + 1] = ws_p[i + lanes / 2]; \
}
#define ILVR_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[i]; \
wd_p[2 * i + 1] = ws_p[i]; \
}
#define ILVEV_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[2 * i]; \
wd_p[2 * i + 1] = ws_p[2 * i]; \
}
#define ILVOD_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[2 * i + 1]; \
wd_p[2 * i + 1] = ws_p[2 * i + 1]; \
}
#define VSHF_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
const int mask_not_valid = 0xC0; \
const int mask_6bits = 0x3F; \
for (int i = 0; i < lanes; ++i) { \
if ((wd_p[i] & mask_not_valid)) { \
wd_p[i] = 0; \
} else { \
int k = (wd_p[i] & mask_6bits) % (lanes * 2); \
wd_p[i] = k > lanes ? ws_p[k - lanes] : wt_p[k]; \
} \
}
#define HADD_DF(T, T_small, lanes) \
T_small* ws_p = reinterpret_cast<T_small*>(ws); \
T_small* wt_p = reinterpret_cast<T_small*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes; ++i) { \
wd_p[i] = static_cast<T>(ws_p[2 * i + 1]) + static_cast<T>(wt_p[2 * i]); \
}
#define HSUB_DF(T, T_small, lanes) \
T_small* ws_p = reinterpret_cast<T_small*>(ws); \
T_small* wt_p = reinterpret_cast<T_small*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes; ++i) { \
wd_p[i] = static_cast<T>(ws_p[2 * i + 1]) - static_cast<T>(wt_p[2 * i]); \
}
#define TEST_CASE(V) \
V(sll_b, SLL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(sll_h, SLL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(sll_w, SLL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(sll_d, SLL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(srl_b, SRL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(srl_h, SRL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(srl_w, SRL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(srl_d, SRL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(bclr_b, BCRL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(bclr_h, BCRL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(bclr_w, BCRL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(bclr_d, BCRL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(bset_b, BSET_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(bset_h, BSET_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(bset_w, BSET_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(bset_d, BSET_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(bneg_b, BNEG_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(bneg_h, BNEG_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(bneg_w, BNEG_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(bneg_d, BNEG_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(binsl_b, BINSL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(binsl_h, BINSL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(binsl_w, BINSL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(binsl_d, BINSL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(binsr_b, BINSR_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(binsr_h, BINSR_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(binsr_w, BINSR_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(binsr_d, BINSR_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(addv_b, ADDV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(addv_h, ADDV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(addv_w, ADDV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(addv_d, ADDV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(subv_b, SUBV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subv_h, SUBV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subv_w, SUBV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subv_d, SUBV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(max_s_b, MAX_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(max_s_h, MAX_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(max_s_w, MAX_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(max_s_d, MAX_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(max_u_b, MAX_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(max_u_h, MAX_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(max_u_w, MAX_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(max_u_d, MAX_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(min_s_b, MIN_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(min_s_h, MIN_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(min_s_w, MIN_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(min_s_d, MIN_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(min_u_b, MIN_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(min_u_h, MIN_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(min_u_w, MIN_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(min_u_d, MIN_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(max_a_b, MAXA_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(max_a_h, MAXA_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(max_a_w, MAXA_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(max_a_d, MAXA_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(min_a_b, MINA_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(min_a_h, MINA_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(min_a_w, MINA_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(min_a_d, MINA_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(ceq_b, CEQ_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ceq_h, CEQ_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ceq_w, CEQ_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ceq_d, CEQ_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(clt_s_b, CLT_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(clt_s_h, CLT_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(clt_s_w, CLT_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(clt_s_d, CLT_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(clt_u_b, CLT_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(clt_u_h, CLT_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(clt_u_w, CLT_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(clt_u_d, CLT_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(cle_s_b, CLE_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(cle_s_h, CLE_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(cle_s_w, CLE_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(cle_s_d, CLE_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(cle_u_b, CLE_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(cle_u_h, CLE_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(cle_u_w, CLE_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(cle_u_d, CLE_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(add_a_b, ADD_A_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(add_a_h, ADD_A_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(add_a_w, ADD_A_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(add_a_d, ADD_A_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(adds_a_b, ADDS_A_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(adds_a_h, ADDS_A_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(adds_a_w, ADDS_A_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(adds_a_d, ADDS_A_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(adds_s_b, ADDS_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(adds_s_h, ADDS_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(adds_s_w, ADDS_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(adds_s_d, ADDS_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(adds_u_b, ADDS_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(adds_u_h, ADDS_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(adds_u_w, ADDS_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(adds_u_d, ADDS_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ave_s_b, AVE_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(ave_s_h, AVE_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(ave_s_w, AVE_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(ave_s_d, AVE_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(ave_u_b, AVE_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ave_u_h, AVE_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ave_u_w, AVE_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ave_u_d, AVE_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(aver_s_b, AVER_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(aver_s_h, AVER_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(aver_s_w, AVER_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(aver_s_d, AVER_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(aver_u_b, AVER_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(aver_u_h, AVER_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(aver_u_w, AVER_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(aver_u_d, AVER_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(subs_s_b, SUBS_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subs_s_h, SUBS_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subs_s_w, SUBS_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subs_s_d, SUBS_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(subs_u_b, SUBS_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(subs_u_h, SUBS_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(subs_u_w, SUBS_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(subs_u_d, SUBS_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(subsus_u_b, SUBSUS_U_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subsus_u_h, SUBSUS_U_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subsus_u_w, SUBSUS_U_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subsus_u_d, SUBSUS_U_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(subsuu_s_b, SUBSUU_S_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subsuu_s_h, SUBSUU_S_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subsuu_s_w, SUBSUU_S_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subsuu_s_d, SUBSUU_S_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(asub_s_b, ASUB_S_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(asub_s_h, ASUB_S_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(asub_s_w, ASUB_S_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(asub_s_d, ASUB_S_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(asub_u_b, ASUB_U_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(asub_u_h, ASUB_U_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(asub_u_w, ASUB_U_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(asub_u_d, ASUB_U_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(mulv_b, MULV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(mulv_h, MULV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(mulv_w, MULV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(mulv_d, MULV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(maddv_b, MADDV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(maddv_h, MADDV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(maddv_w, MADDV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(maddv_d, MADDV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(msubv_b, MSUBV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(msubv_h, MSUBV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(msubv_w, MSUBV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(msubv_d, MSUBV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(div_s_b, DIV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(div_s_h, DIV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(div_s_w, DIV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(div_s_d, DIV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(div_u_b, DIV_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(div_u_h, DIV_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(div_u_w, DIV_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(div_u_d, DIV_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(mod_s_b, MOD_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(mod_s_h, MOD_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(mod_s_w, MOD_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(mod_s_d, MOD_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(mod_u_b, MOD_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(mod_u_h, MOD_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(mod_u_w, MOD_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(mod_u_d, MOD_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(srlr_b, SRAR_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(srlr_h, SRAR_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(srlr_w, SRAR_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(srlr_d, SRAR_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(pckev_b, PCKEV_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(pckev_h, PCKEV_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(pckev_w, PCKEV_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(pckev_d, PCKEV_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(pckod_b, PCKOD_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(pckod_h, PCKOD_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(pckod_w, PCKOD_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(pckod_d, PCKOD_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvl_b, ILVL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvl_h, ILVL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvl_w, ILVL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvl_d, ILVL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvr_b, ILVR_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvr_h, ILVR_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvr_w, ILVR_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvr_d, ILVR_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvev_b, ILVEV_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvev_h, ILVEV_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvev_w, ILVEV_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvev_d, ILVEV_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvod_b, ILVOD_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvod_h, ILVOD_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvod_w, ILVOD_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvod_d, ILVOD_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(vshf_b, VSHF_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(vshf_h, VSHF_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(vshf_w, VSHF_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(vshf_d, VSHF_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(hadd_s_h, HADD_DF, int16_t, int8_t, kMSALanesHalf) \
V(hadd_s_w, HADD_DF, int32_t, int16_t, kMSALanesWord) \
V(hadd_s_d, HADD_DF, int64_t, int32_t, kMSALanesDword) \
V(hadd_u_h, HADD_DF, uint16_t, uint8_t, kMSALanesHalf) \
V(hadd_u_w, HADD_DF, uint32_t, uint16_t, kMSALanesWord) \
V(hadd_u_d, HADD_DF, uint64_t, uint32_t, kMSALanesDword) \
V(hsub_s_h, HSUB_DF, int16_t, int8_t, kMSALanesHalf) \
V(hsub_s_w, HSUB_DF, int32_t, int16_t, kMSALanesWord) \
V(hsub_s_d, HSUB_DF, int64_t, int32_t, kMSALanesDword) \
V(hsub_u_h, HSUB_DF, uint16_t, uint8_t, kMSALanesHalf) \
V(hsub_u_w, HSUB_DF, uint32_t, uint16_t, kMSALanesWord) \
V(hsub_u_d, HSUB_DF, uint64_t, uint32_t, kMSALanesDword)
#define RUN_TEST(instr, verify, type, lanes, mask) \
run_msa_3r(&tc[i], [](MacroAssembler& assm) { __ instr(w2, w1, w0); }, \
[](uint64_t* ws, uint64_t* wt, uint64_t* wd) { \
verify(type, lanes, mask); \
});
for (size_t i = 0; i < arraysize(tc); ++i) {
TEST_CASE(RUN_TEST)
}
#define RUN_TEST2(instr, verify, type, lanes, mask) \
for (unsigned i = 0; i < arraysize(tc); i++) { \
for (unsigned j = 0; j < 3; j++) { \
for (unsigned k = 0; k < lanes; k++) { \
type* element = reinterpret_cast<type*>(&tc[i]); \
element[k + j * lanes] &= std::numeric_limits<type>::max(); \
} \
} \
} \
run_msa_3r(&tc[i], [](MacroAssembler& assm) { __ instr(w2, w1, w0); }, \
[](uint64_t* ws, uint64_t* wt, uint64_t* wd) { \
verify(type, lanes, mask); \
});
#define TEST_CASE2(V) \
V(sra_b, SRA_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(sra_h, SRA_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(sra_w, SRA_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(sra_d, SRA_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(srar_b, SRAR_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(srar_h, SRAR_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(srar_w, SRAR_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(srar_d, SRAR_DF, int64_t, kMSALanesDword, UINT64_MAX)
for (size_t i = 0; i < arraysize(tc); ++i) {
TEST_CASE2(RUN_TEST2)
}
#undef TEST_CASE
#undef TEST_CASE2
#undef RUN_TEST
#undef RUN_TEST2
#undef SLL_DF
#undef SRL_DF
#undef SRA_DF
#undef BCRL_DF
#undef BSET_DF
#undef BNEG_DF
#undef BINSL_DF
#undef BINSR_DF
#undef ADDV_DF
#undef SUBV_DF
#undef MAX_DF
#undef MIN_DF
#undef MAXA_DF
#undef MINA_DF
#undef CEQ_DF
#undef CLT_DF
#undef CLE_DF
#undef ADD_A_DF
#undef ADDS_A_DF
#undef ADDS_DF
#undef AVE_DF
#undef AVER_DF
#undef SUBS_DF
#undef SUBSUS_U_DF
#undef SUBSUU_S_DF
#undef ASUB_S_DF
#undef ASUB_U_DF
#undef MULV_DF
#undef MADDV_DF
#undef MSUBV_DF
#undef DIV_DF
#undef MOD_DF
#undef SRAR_DF
#undef PCKEV_DF
#undef PCKOD_DF
#undef ILVL_DF
#undef ILVR_DF
#undef ILVEV_DF
#undef ILVOD_DF
#undef VSHF_DF
#undef HADD_DF
#undef HSUB_DF
} // namespace internal
struct TestCaseMsa3RF {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wt_lo;
uint64_t wt_hi;
uint64_t wd_lo;
uint64_t wd_hi;
};
struct ExpectedResult_MSA3RF {
uint64_t exp_res_lo;
uint64_t exp_res_hi;
};
template <typename Func>
void run_msa_3rf(const struct TestCaseMsa3RF* input,
const struct ExpectedResult_MSA3RF* output,
Func Generate2RInstructionFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, NULL, 0, v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(
assm, reinterpret_cast<const uint64_t*>(&input->ws_lo), w0, t0, t1);
load_elements_of_vector(
assm, reinterpret_cast<const uint64_t*>(&input->wt_lo), w1, t0, t1);
load_elements_of_vector(
assm, reinterpret_cast<const uint64_t*>(&input->wd_lo), w2, t0, t1);
Generate2RInstructionFunc(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(output->exp_res_lo, res.d[0]);
CHECK_EQ(output->exp_res_hi, res.d[1]);
}
struct TestCaseMsa3RF_F {
float ws_1, ws_2, ws_3, ws_4;
float wt_1, wt_2, wt_3, wt_4;
float wd_1, wd_2, wd_3, wd_4;
};
struct ExpRes_32I {
int32_t exp_res_1;
int32_t exp_res_2;
int32_t exp_res_3;
int32_t exp_res_4;
};
struct TestCaseMsa3RF_D {
double ws_lo, ws_hi;
double wt_lo, wt_hi;
double wd_lo, wd_hi;
};
struct ExpRes_64I {
int64_t exp_res_lo;
int64_t exp_res_hi;
};
TEST(MSA_floating_point_quiet_compare) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float qnan_f = std::numeric_limits<float>::quiet_NaN();
const double qnan_d = std::numeric_limits<double>::quiet_NaN();
const float inf_f = std::numeric_limits<float>::infinity();
const double inf_d = std::numeric_limits<double>::infinity();
const int32_t ones = -1;
const struct TestCaseMsa3RF_F tc_w[]{
{qnan_f, -qnan_f, inf_f, 2.14e9f, // ws
qnan_f, 0.f, qnan_f, -2.14e9f, // wt
0, 0, 0, 0}, // wd
{inf_f, -inf_f, -3.4e38f, 1.5e-45f, -inf_f, -inf_f, -inf_f, inf_f, 0, 0,
0, 0},
{0.f, 19.871e24f, -1.5e-45f, -1.5e-45f, -19.871e24f, 19.871e24f, 1.5e-45f,
-1.5e-45f, 0, 0, 0, 0}};
const struct TestCaseMsa3RF_D tc_d[]{
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{qnan_d, -qnan_d, qnan_f, 0., 0, 0},
{inf_d, 9.22e18, qnan_d, -9.22e18, 0, 0},
{inf_d, inf_d, -inf_d, inf_d, 0, 0},
{-2.3e-308, 5e-324, -inf_d, inf_d, 0, 0},
{0., 24.1e87, -1.6e308, 24.1e87, 0, 0},
{-5e-324, -5e-324, 5e-324, -5e-324, 0, 0}};
const struct ExpectedResult_MSA3RF exp_res_fcaf = {0, 0};
const struct ExpRes_32I exp_res_fcun_w[] = {
{ones, ones, ones, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
const struct ExpRes_64I exp_res_fcun_d[] = {{ones, ones}, {ones, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}};
const struct ExpRes_32I exp_res_fceq_w[] = {
{0, 0, 0, 0}, {0, ones, 0, 0}, {0, ones, 0, ones}};
const struct ExpRes_64I exp_res_fceq_d[] = {{0, 0}, {0, 0}, {0, ones},
{0, 0}, {0, ones}, {0, ones}};
const struct ExpRes_32I exp_res_fcueq_w[] = {
{ones, ones, ones, 0}, {0, ones, 0, 0}, {0, ones, 0, ones}};
const struct ExpRes_64I exp_res_fcueq_d[] = {
{ones, ones}, {ones, 0}, {0, ones}, {0, 0}, {0, ones}, {0, ones}};
const struct ExpRes_32I exp_res_fclt_w[] = {
{0, 0, 0, 0}, {0, 0, 0, ones}, {0, 0, ones, 0}};
const struct ExpRes_64I exp_res_fclt_d[] = {{0, 0}, {0, 0}, {0, 0},
{0, ones}, {0, 0}, {ones, 0}};
const struct ExpRes_32I exp_res_fcult_w[] = {
{ones, ones, ones, 0}, {0, 0, 0, ones}, {0, 0, ones, 0}};
const struct ExpRes_64I exp_res_fcult_d[] = {
{ones, ones}, {ones, 0}, {0, 0}, {0, ones}, {0, 0}, {ones, 0}};
const struct ExpRes_32I exp_res_fcle_w[] = {
{0, 0, 0, 0}, {0, ones, 0, ones}, {0, ones, ones, ones}};
const struct ExpRes_64I exp_res_fcle_d[] = {
{0, 0}, {0, 0}, {0, ones}, {0, ones}, {0, ones}, {ones, ones}};
const struct ExpRes_32I exp_res_fcule_w[] = {
{ones, ones, ones, 0}, {0, ones, 0, ones}, {0, ones, ones, ones}};
const struct ExpRes_64I exp_res_fcule_d[] = {
{ones, ones}, {ones, 0}, {0, ones}, {0, ones}, {0, ones}, {ones, ones}};
const struct ExpRes_32I exp_res_fcor_w[] = {
{0, 0, 0, ones}, {ones, ones, ones, ones}, {ones, ones, ones, ones}};
const struct ExpRes_64I exp_res_fcor_d[] = {{0, 0}, {0, ones},
{ones, ones}, {ones, ones},
{ones, ones}, {ones, ones}};
const struct ExpRes_32I exp_res_fcune_w[] = {
{ones, ones, ones, ones}, {ones, 0, ones, ones}, {ones, 0, ones, 0}};
const struct ExpRes_64I exp_res_fcune_d[] = {{ones, ones}, {ones, ones},
{ones, 0}, {ones, ones},
{ones, 0}, {ones, 0}};
const struct ExpRes_32I exp_res_fcne_w[] = {
{0, 0, 0, ones}, {ones, 0, ones, ones}, {ones, 0, ones, 0}};
const struct ExpRes_64I exp_res_fcne_d[] = {
{0, 0}, {0, ones}, {ones, 0}, {ones, ones}, {ones, 0}, {ones, 0}};
#define TEST_FP_QUIET_COMPARE_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FP_QUIET_COMPARE_D(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FP_QUIET_COMPARE_W(fcaf_w, &tc_w[i], &exp_res_fcaf)
TEST_FP_QUIET_COMPARE_W(fcun_w, &tc_w[i], &exp_res_fcun_w[i])
TEST_FP_QUIET_COMPARE_W(fceq_w, &tc_w[i], &exp_res_fceq_w[i])
TEST_FP_QUIET_COMPARE_W(fcueq_w, &tc_w[i], &exp_res_fcueq_w[i])
TEST_FP_QUIET_COMPARE_W(fclt_w, &tc_w[i], &exp_res_fclt_w[i])
TEST_FP_QUIET_COMPARE_W(fcult_w, &tc_w[i], &exp_res_fcult_w[i])
TEST_FP_QUIET_COMPARE_W(fcle_w, &tc_w[i], &exp_res_fcle_w[i])
TEST_FP_QUIET_COMPARE_W(fcule_w, &tc_w[i], &exp_res_fcule_w[i])
TEST_FP_QUIET_COMPARE_W(fcor_w, &tc_w[i], &exp_res_fcor_w[i])
TEST_FP_QUIET_COMPARE_W(fcune_w, &tc_w[i], &exp_res_fcune_w[i])
TEST_FP_QUIET_COMPARE_W(fcne_w, &tc_w[i], &exp_res_fcne_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FP_QUIET_COMPARE_D(fcaf_d, &tc_d[i], &exp_res_fcaf)
TEST_FP_QUIET_COMPARE_D(fcun_d, &tc_d[i], &exp_res_fcun_d[i])
TEST_FP_QUIET_COMPARE_D(fceq_d, &tc_d[i], &exp_res_fceq_d[i])
TEST_FP_QUIET_COMPARE_D(fcueq_d, &tc_d[i], &exp_res_fcueq_d[i])
TEST_FP_QUIET_COMPARE_D(fclt_d, &tc_d[i], &exp_res_fclt_d[i])
TEST_FP_QUIET_COMPARE_D(fcult_d, &tc_d[i], &exp_res_fcult_d[i])
TEST_FP_QUIET_COMPARE_D(fcle_d, &tc_d[i], &exp_res_fcle_d[i])
TEST_FP_QUIET_COMPARE_D(fcule_d, &tc_d[i], &exp_res_fcule_d[i])
TEST_FP_QUIET_COMPARE_D(fcor_d, &tc_d[i], &exp_res_fcor_d[i])
TEST_FP_QUIET_COMPARE_D(fcune_d, &tc_d[i], &exp_res_fcune_d[i])
TEST_FP_QUIET_COMPARE_D(fcne_d, &tc_d[i], &exp_res_fcne_d[i])
}
#undef TEST_FP_QUIET_COMPARE_W
#undef TEST_FP_QUIET_COMPARE_D
}
template <typename T>
inline const T* fadd_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] + src2[i];
}
return dst;
}
template <typename T>
inline const T* fsub_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] - src2[i];
}
return dst;
}
template <typename T>
inline const T* fmul_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] * src2[i];
}
return dst;
}
template <typename T>
inline const T* fdiv_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] / src2[i];
}
return dst;
}
template <typename T>
inline const T* fmadd_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = std::fma(src1[i], src2[i], src3[i]);
}
return dst;
}
template <typename T>
inline const T* fmsub_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = std::fma(src1[i], -src2[i], src3[i]);
}
return dst;
}
TEST(MSA_floating_point_arithmetic) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_f = std::numeric_limits<float>::infinity();
const double inf_d = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
{0.3, -2.14e13f, inf_f, 0.f, // ws
-inf_f, std::sqrt(8.e-26f), -23.e34, -2.14e9f, // wt
-1e30f, 4.6e12f, 0, 2.14e9f}, // wd
{3.4e38f, -1.2e-38f, 1e19f, -1e19f, 3.4e38f, 1.2e-38f, -1e19f, -1e-19f,
3.4e38f, 1.2e-38f * 3, 3.4e38f, -4e19f},
{-3e-31f, 3e10f, 1e25f, 123.f, 1e-14f, 1e-34f, 4e25f, 321.f, 3e-17f,
2e-24f, 2.f, -123456.f}};
const struct TestCaseMsa3RF_D tc_d[] = {
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{0.3, -2.14e103, -inf_d, std::sqrt(8.e-206), -1e30, 4.6e102},
{inf_d, 0., -23.e304, -2.104e9, 0, 2.104e9},
{3.4e307, -1.2e-307, 3.4e307, 1.2e-307, 3.4e307, 1.2e-307 * 3},
{1e154, -1e154, -1e154, -1e-154, 2.9e38, -4e19},
{-3e-301, 3e100, 1e-104, 1e-304, 3e-107, 2e-204},
{1e205, 123., 4e205, 321., 2., -123456.}};
struct ExpectedResult_MSA3RF dst_container;
#define FP_ARITHMETIC_DF_W(instr, function, src1, src2, src3) \
run_msa_3rf( \
reinterpret_cast<const struct TestCaseMsa3RF*>(src1), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(function( \
src1, src2, src3, reinterpret_cast<float*>(&dst_container))), \
[](MacroAssembler& assm) { __ instr(w2, w0, w1); });
#define FP_ARITHMETIC_DF_D(instr, function, src1, src2, src3) \
run_msa_3rf( \
reinterpret_cast<const struct TestCaseMsa3RF*>(src1), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(function( \
src1, src2, src3, reinterpret_cast<double*>(&dst_container))), \
[](MacroAssembler& assm) { __ instr(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
FP_ARITHMETIC_DF_W(fadd_w, fadd_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fsub_w, fsub_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fmul_w, fmul_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fdiv_w, fdiv_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fmadd_w, fmadd_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fmsub_w, fmsub_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
FP_ARITHMETIC_DF_D(fadd_d, fadd_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fsub_d, fsub_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fmul_d, fmul_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fdiv_d, fdiv_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fmadd_d, fmadd_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fmsub_d, fmsub_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
}
#undef FP_ARITHMETIC_DF_W
#undef FP_ARITHMETIC_DF_D
}
struct ExpRes_F {
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct ExpRes_D {
double exp_res_1;
double exp_res_2;
};
TEST(MSA_fmin_fmin_a_fmax_fmax_a) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_f = std::numeric_limits<float>::infinity();
const double inf_d = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
{0.3f, -2.14e13f, inf_f, -0.f, // ws
-inf_f, -std::sqrt(8.e26f), -23.e34f, -2.14e9f, // wt
0, 0, 0, 0}, // wd
{3.4e38f, 1.2e-41f, 1e19f, 1e19f, // ws
3.4e38f, -1.1e-41f, -1e-42f, -1e29f, // wt
0, 0, 0, 0}}; // wd
const struct TestCaseMsa3RF_D tc_d[] = {
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{0.3, -2.14e103, -inf_d, -std::sqrt(8e206), 0, 0},
{inf_d, -0., -23e304, -2.14e90, 0, 0},
{3.4e307, 1.2e-320, 3.4e307, -1.1e-320, 0, 0},
{1e154, 1e154, -1e-321, -1e174, 0, 0}};
const struct ExpRes_F exp_res_fmax_w[] = {{0.3f, -2.14e13f, inf_f, -0.f},
{3.4e38f, 1.2e-41f, 1e19f, 1e19f}};
const struct ExpRes_F exp_res_fmax_a_w[] = {
{-inf_f, -std::sqrt(8e26f), inf_f, -2.14e9f},
{3.4e38f, 1.2e-41f, 1e19f, -1e29f}};
const struct ExpRes_F exp_res_fmin_w[] = {
{-inf_f, -std::sqrt(8.e26f), -23e34f, -2.14e9f},
{3.4e38f, -1.1e-41f, -1e-42f, -1e29f}};
const struct ExpRes_F exp_res_fmin_a_w[] = {
{0.3, -2.14e13f, -23.e34f, -0.f}, {3.4e38f, -1.1e-41f, -1e-42f, 1e19f}};
const struct ExpRes_D exp_res_fmax_d[] = {
{0.3, -2.14e103}, {inf_d, -0.}, {3.4e307, 1.2e-320}, {1e154, 1e154}};
const struct ExpRes_D exp_res_fmax_a_d[] = {{-inf_d, -std::sqrt(8e206)},
{inf_d, -2.14e90},
{3.4e307, 1.2e-320},
{1e154, -1e174}};
const struct ExpRes_D exp_res_fmin_d[] = {{-inf_d, -std::sqrt(8e206)},
{-23e304, -2.14e90},
{3.4e307, -1.1e-320},
{-1e-321, -1e174}};
const struct ExpRes_D exp_res_fmin_a_d[] = {
{0.3, -2.14e103}, {-23e304, -0.}, {3.4e307, -1.1e-320}, {-1e-321, 1e154}};
#define TEST_FP_MIN_MAX_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FP_MIN_MAX_D(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FP_MIN_MAX_W(fmax_w, &tc_w[i], &exp_res_fmax_w[i])
TEST_FP_MIN_MAX_W(fmax_a_w, &tc_w[i], &exp_res_fmax_a_w[i])
TEST_FP_MIN_MAX_W(fmin_w, &tc_w[i], &exp_res_fmin_w[i])
TEST_FP_MIN_MAX_W(fmin_a_w, &tc_w[i], &exp_res_fmin_a_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FP_MIN_MAX_D(fmax_d, &tc_d[i], &exp_res_fmax_d[i])
TEST_FP_MIN_MAX_D(fmax_a_d, &tc_d[i], &exp_res_fmax_a_d[i])
TEST_FP_MIN_MAX_D(fmin_d, &tc_d[i], &exp_res_fmin_d[i])
TEST_FP_MIN_MAX_D(fmin_a_d, &tc_d[i], &exp_res_fmin_a_d[i])
}
#undef TEST_FP_MIN_MAX_W
#undef TEST_FP_MIN_MAX_D
}
struct TestCaseMsa3RF_16I {
int16_t ws_1, ws_2, ws_3, ws_4, ws_5, ws_6, ws_7, ws_8;
int16_t wt_1, wt_2, wt_3, wt_4, wt_5, wt_6, wt_7, wt_8;
int16_t wd_1, wd_2, wd_3, wd_4, wd_5, wd_6, wd_7, wd_8;
};
struct ExpRes_16I {
int16_t exp_res_1;
int16_t exp_res_2;
int16_t exp_res_3;
int16_t exp_res_4;
int16_t exp_res_5;
int16_t exp_res_6;
int16_t exp_res_7;
int16_t exp_res_8;
};
struct TestCaseMsa3RF_32I {
int32_t ws_1, ws_2, ws_3, ws_4;
int32_t wt_1, wt_2, wt_3, wt_4;
int32_t wd_1, wd_2, wd_3, wd_4;
};
TEST(MSA_fixed_point_arithmetic) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const struct TestCaseMsa3RF tc_h[]{
{0x800080007FFF7FFF, 0xE1ED8000FAD3863A, 0x80007FFF00AF7FFF,
0x800015A77FFFA0EB, 0x7FFF800080007FFF, 0x80007FFF1F207364},
{0x800080007FFF006A, 0x002AFFC4329AD87B, 0x80007FFF7FFF00F3,
0xFFECFFB4D0D7F429, 0x80007FFF80007C33, 0x54AC6BBCE53B8C91}};
const struct TestCaseMsa3RF tc_w[]{
{0x8000000080000000, 0x7FFFFFFF7FFFFFFF, 0x800000007FFFFFFF,
0x00001FF37FFFFFFF, 0x7FFFFFFF80000000, 0x800000007FFFFFFF},
{0xE1ED035580000000, 0xFAD3863AED462C0B, 0x8000000015A70AEC,
0x7FFFFFFFA0EBD354, 0x800000007FFFFFFF, 0xD0D7F4291F207364},
{0x8000000080000000, 0x7FFFFFFF0000DA1F, 0x800000007FFFFFFF,
0x7FFFFFFF00F39C3B, 0x800000007FFFFFFF, 0x800000007C33F2FD},
{0x0000AC33FFFF329A, 0x54AC6BBCE53BD87B, 0xFFFFE2B4D0D7F429,
0x0355ED462C0B1FF3, 0xB5DEB625939DD3F9, 0xE642ADFA69519596}};
const struct ExpectedResult_MSA3RF exp_res_mul_q_h[] = {
{0x7FFF800100AE7FFE, 0x1E13EA59FAD35A74},
{0x7FFF80017FFE0000, 0xFFFF0000ED5B03A7}};
const struct ExpectedResult_MSA3RF exp_res_madd_q_h[] = {
{0x7FFF800080AE7FFF, 0x9E136A5819F37FFF},
{0x00000000FFFE7C33, 0x54AB6BBCD2969038}};
const struct ExpectedResult_MSA3RF exp_res_msub_q_h[] = {
{0xFFFFFFFF80000000, 0x80007FFF244C18EF},
{0x80007FFF80007C32, 0x54AC6BBBF7DF88E9}};
const struct ExpectedResult_MSA3RF exp_res_mulr_q_h[] = {
{0x7FFF800100AF7FFE, 0x1E13EA59FAD35A75},
{0x7FFF80017FFE0001, 0x00000000ED5B03A8}};
const struct ExpectedResult_MSA3RF exp_res_maddr_q_h[] = {
{0x7FFF800080AF7FFF, 0x9E136A5819F37FFF},
{0x00000000FFFE7C34, 0x54AC6BBCD2969039}};
const struct ExpectedResult_MSA3RF exp_res_msubr_q_h[] = {
{0xFFFFFFFF80000001, 0x80007FFF244D18EF},
{0x80007FFF80007C32, 0x54AC6BBCF7E088E9}};
const struct ExpectedResult_MSA3RF exp_res_mul_q_w[] = {
{0x7FFFFFFF80000001, 0x00001FF27FFFFFFE},
{0x1E12FCABEA58F514, 0xFAD3863A0DE8DEE1},
{0x7FFFFFFF80000001, 0x7FFFFFFE0000019F},
{0xFFFFFFFF00004BAB, 0x0234E1FBF6CA3EE0}};
const struct ExpectedResult_MSA3RF exp_res_madd_q_w[] = {
{0x7FFFFFFF80000000, 0x80001FF27FFFFFFF},
{0x9E12FCAB6A58F513, 0xCBAB7A632D095245},
{0x0000000000000000, 0xFFFFFFFE7C33F49C},
{0xB5DEB624939E1FA4, 0xE8778FF5601BD476}};
const struct ExpectedResult_MSA3RF exp_res_msub_q_w[] = {
{0xFFFFFFFFFFFFFFFF, 0x8000000000000000},
{0x800000007FFFFFFF, 0xD6046DEE11379482},
{0x800000007FFFFFFF, 0x800000007C33F15D},
{0xB5DEB625939D884D, 0xE40DCBFE728756B5}};
const struct ExpectedResult_MSA3RF exp_res_mulr_q_w[] = {
{0x7FFFFFFF80000001, 0x00001FF37FFFFFFE},
{0x1E12FCABEA58F514, 0xFAD3863A0DE8DEE2},
{0x7FFFFFFF80000001, 0x7FFFFFFE0000019F},
{0x0000000000004BAC, 0x0234E1FCF6CA3EE1}};
const struct ExpectedResult_MSA3RF exp_res_maddr_q_w[] = {
{0x7FFFFFFF80000000, 0x80001FF37FFFFFFF},
{0x9E12FCAB6A58F513, 0xCBAB7A632D095246},
{0x0000000000000000, 0xFFFFFFFE7C33F49C},
{0xB5DEB625939E1FA5, 0xE8778FF6601BD477}};
const struct ExpectedResult_MSA3RF exp_res_msubr_q_w[] = {
{0xFFFFFFFFFFFFFFFF, 0x8000000000000001},
{0x800000007FFFFFFF, 0xD6046DEF11379482},
{0x800000007FFFFFFF, 0x800000007C33F15E},
{0xB5DEB625939D884D, 0xE40DCBFE728756B5}};
#define TEST_FIXED_POINT_DF_H(instruction, src, exp_res) \
run_msa_3rf((src), (exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FIXED_POINT_DF_W(instruction, src, exp_res) \
run_msa_3rf((src), (exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_h); i++) {
TEST_FIXED_POINT_DF_H(mul_q_h, &tc_h[i], &exp_res_mul_q_h[i])
TEST_FIXED_POINT_DF_H(madd_q_h, &tc_h[i], &exp_res_madd_q_h[i])
TEST_FIXED_POINT_DF_H(msub_q_h, &tc_h[i], &exp_res_msub_q_h[i])
TEST_FIXED_POINT_DF_H(mulr_q_h, &tc_h[i], &exp_res_mulr_q_h[i])
TEST_FIXED_POINT_DF_H(maddr_q_h, &tc_h[i], &exp_res_maddr_q_h[i])
TEST_FIXED_POINT_DF_H(msubr_q_h, &tc_h[i], &exp_res_msubr_q_h[i])
}
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FIXED_POINT_DF_W(mul_q_w, &tc_w[i], &exp_res_mul_q_w[i])
TEST_FIXED_POINT_DF_W(madd_q_w, &tc_w[i], &exp_res_madd_q_w[i])
TEST_FIXED_POINT_DF_W(msub_q_w, &tc_w[i], &exp_res_msub_q_w[i])
TEST_FIXED_POINT_DF_W(mulr_q_w, &tc_w[i], &exp_res_mulr_q_w[i])
TEST_FIXED_POINT_DF_W(maddr_q_w, &tc_w[i], &exp_res_maddr_q_w[i])
TEST_FIXED_POINT_DF_W(msubr_q_w, &tc_w[i], &exp_res_msubr_q_w[i])
}
#undef TEST_FIXED_POINT_DF_H
#undef TEST_FIXED_POINT_DF_W
}
TEST(MSA_fexdo) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const float nan_float = std::numeric_limits<float>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
// ws_1, ws_2, ws_3, ws_4, wt_1, wt_2, wt_3, wt_4, wd_1, wd_2, wd_3, wd_4
{inf_float, nan_float, 66505.f, 65504.f, 6.2e-5f, 5e-5f, -32.42f,
-inf_float, 0, 0, 0, 0},
{-0.f, 0.f, 123.567f, -765.321f, -6e-8f, 5.9e-8f, 1e-7f, -1e-20f, 0, 0, 0,
0},
{1e-36f, 1e20f, -1e20f, 2e-20f, 6e-8f, -2.9e-8f, -66505.f, -65504.f, 0, 0,
0, 0}};
const struct TestCaseMsa3RF_D tc_d[] = {
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{inf_double, -1234., 4e38, 3.4e38, 0, 0},
{1.2e-38, 1.1e-39, -38.92f, -inf_double, 0, 0},
{-0., 0., 123.567e31, -765.321e33, 0, 0},
{-1.5e-45, 1.3e-45, 1e-42, -1e-200, 0, 0},
{1e-202, 1e158, -1e159, 1e14, 0, 0},
{1.5e-42, 1.3e-46, -123.567e31, 765.321e33, 0, 0}};
const struct ExpRes_16I exp_res_fexdo_w[] = {
{static_cast<int16_t>(0x0410), static_cast<int16_t>(0x0347),
static_cast<int16_t>(0xD00D), static_cast<int16_t>(0xFC00),
static_cast<int16_t>(0x7C00), static_cast<int16_t>(0x7DFF),
static_cast<int16_t>(0x7C00), static_cast<int16_t>(0x7BFF)},
{static_cast<int16_t>(0x8001), static_cast<int16_t>(0x0001),
static_cast<int16_t>(0x0002), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0x8000), static_cast<int16_t>(0x0000),
static_cast<int16_t>(0x57B9), static_cast<int16_t>(0xE1FB)},
{static_cast<int16_t>(0x0001), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0xFC00), static_cast<int16_t>(0xFBFF),
static_cast<int16_t>(0x0000), static_cast<int16_t>(0x7C00),
static_cast<int16_t>(0xFC00), static_cast<int16_t>(0x0000)}};
const struct ExpRes_32I exp_res_fexdo_d[] = {
{bit_cast<int32_t>(0x7F800000), bit_cast<int32_t>(0x7F7FC99E),
bit_cast<int32_t>(0x7F800000), bit_cast<int32_t>(0xC49A4000)},
{bit_cast<int32_t>(0xC21BAE14), bit_cast<int32_t>(0xFF800000),
bit_cast<int32_t>(0x0082AB1E), bit_cast<int32_t>(0x000BFA5A)},
{bit_cast<int32_t>(0x7673B164), bit_cast<int32_t>(0xFB13653D),
bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x00000000)},
{bit_cast<int32_t>(0x000002CA), bit_cast<int32_t>(0x80000000),
bit_cast<int32_t>(0x80000001), bit_cast<int32_t>(0x00000001)},
{bit_cast<int32_t>(0xFF800000), bit_cast<int32_t>(0x56B5E621),
bit_cast<int32_t>(0x00000000), bit_cast<int32_t>(0x7F800000)},
{bit_cast<int32_t>(0xF673B164), bit_cast<int32_t>(0x7B13653D),
bit_cast<int32_t>(0x0000042E), bit_cast<int32_t>(0x00000000)}};
#define TEST_FEXDO_H(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FEXDO_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FEXDO_H(fexdo_h, &tc_w[i], &exp_res_fexdo_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FEXDO_W(fexdo_w, &tc_d[i], &exp_res_fexdo_d[i])
}
#undef TEST_FEXDO_H
#undef TEST_FEXDO_W
}
TEST(MSA_ftq) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float nan_float = std::numeric_limits<float>::quiet_NaN();
const float inf_float = std::numeric_limits<float>::infinity();
const double nan_double = std::numeric_limits<double>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
{1.f, -0.999f, 1.5f, -31e-6, 1e-7, -0.598, 0.0023, -0.f, 0, 0, 0, 0},
{100.f, -102.f, -1.1f, 1.3f, 0.f, -1.f, 0.9999f, -0.000322, 0, 0, 0, 0},
{nan_float, inf_float, -inf_float, -nan_float, -1e-40, 3e-44, 8.3e36,
-0.00003, 0, 0, 0, 0}};
const struct TestCaseMsa3RF_D tc_d[] = {
{1., -0.999, 1.5, -31e-6, 0, 0},
{1e-7, -0.598, 0.0023, -0.f, 0, 0},
{100.f, -102.f, -1.1f, 1.3f, 0, 0},
{0.f, -1.f, 0.9999f, -0.000322, 0, 0},
{nan_double, inf_double, -inf_double, -nan_double, 0, 0},
{-3e306, 2e-307, 9e307, 2e-307, 0, 0}};
const struct ExpRes_16I exp_res_ftq_w[] = {
{static_cast<int16_t>(0x0000), static_cast<int16_t>(0xB375),
static_cast<int16_t>(0x004B), static_cast<int16_t>(0x0000),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0x8021),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0xFFFF)},
{static_cast<int16_t>(0x0000), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0x7FFD), static_cast<int16_t>(0xFFF5),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0x8000), static_cast<int16_t>(0x7FFF)},
{static_cast<int16_t>(0x0000), static_cast<int16_t>(0x0000),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0xFFFF),
static_cast<int16_t>(0x0000), static_cast<int16_t>(0x7FFF),
static_cast<int16_t>(0x8000), static_cast<int16_t>(0x0000)}};
const struct ExpRes_32I exp_res_ftq_d[] = {
{bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0xFFFEFBF4),
bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0x8020C49C)},
{bit_cast<int32_t>(0x004B5DCC), bit_cast<int32_t>(0x00000000),
bit_cast<int32_t>(0x000000D7), bit_cast<int32_t>(0xB374BC6A)},
{bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x7FFFFFFF),
bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0x80000000)},
{bit_cast<int32_t>(0x7FFCB900), bit_cast<int32_t>(0xFFF572DE),
bit_cast<int32_t>(0x00000000), bit_cast<int32_t>(0x80000000)},
{bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x00000000),
bit_cast<int32_t>(0x00000000), bit_cast<int32_t>(0x7FFFFFFF)},
{bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0x00000000),
bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x00000000)}};
#define TEST_FTQ_H(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FTQ_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FTQ_H(ftq_h, &tc_w[i], &exp_res_ftq_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FTQ_W(ftq_w, &tc_d[i], &exp_res_ftq_d[i])
}
#undef TEST_FTQ_H
#undef TEST_FTQ_W
}
#undef __
} // namespace internal
} // namespace v8
| 376,712 | 178,459 |
/*
* Copyright 2011 University of Sheffield.
* Author: Dr Paul Richmond
* Contact: p.richmond@sheffield.ac.uk (http://www.paulrichmond.staff.shef.ac.uk)
*
* University of Sheffield retain all intellectual property and
* proprietary rights in and to this software and related documentation.
* Any use, reproduction, disclosure, or distribution of this software
* and related documentation without an express license agreement from
* University of Sheffield is strictly prohibited.
*
* For terms of licence agreement please attached licence or view licence
* on www.flamegpu.com website.
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <GL/glew.h>
#include <GL/glut.h>
#include "PedestrianPopulation.h"
#include "OBJModel.h"
#include "BufferObjects.h"
#include "NavMapPopulation.h"
#include "CustomVisualisation.h"
/** Pedestrian Model Scale */
float PEDESTRIAN_MODEL_SCALE = 0.0025f;
//pedestrian instances
GLuint p_instances_data1_tbo;
GLuint p_instances_data1_tex;
cudaGraphicsResource_t p_instances_data1_cgr;
GLuint p_instances_data2_tbo;
GLuint p_instances_data2_tex;
cudaGraphicsResource_t p_instances_data2_cgr;
GLuint pvs_active_exit;
//MODEL DATA FOR LOD 1
//primative count
int lod1_v_count;
int lod1_f_count;
//reft keyframe primative data
glm::vec3* lod1l_vertices;
glm::vec3* lod1l_normals;
glm::ivec3* lod1l_faces;
//right keyframe primative data
glm::vec3* lod1r_vertices;
glm::vec3* lod1r_normals;
glm::ivec3* lod1r_faces;
//buffer objects
GLuint lod1_elem_vbo;
GLuint lod1l_verts_vbo;
GLuint lod1l_norms_vbo;
GLuint lod1r_verts_vbo;
GLuint lod1r_norms_vbo;
//Shader and shader attributes
GLuint p_vertexShader;
GLuint p_shaderProgram;
GLuint pvs_data1_map;
GLuint pvs_data2_map;
GLuint pvs_instance_index;
GLuint pvs_position_l;
GLuint pvs_position_r;
GLuint pvs_normal_l;
GLuint pvs_normal_r;
//external prototypes imported from FLAME GPU
extern int get_agent_agent_MAX_count();
//PRIVATE PROTOTYPES
/** initPedestrianShader
* Creates all Buffer Objects for instancing and model data
*/
void initPedestrianShader();
/** createPedestrianBufferObjects
* Initialises the Pedestrian Shader and shader attributes
*/
void createPedestrianBufferObjects();
void initPedestrianPopulation()
{
//LOD 1
lod1_v_count = 354;
lod1_f_count = 704;
//Left
char lod1LeftString[] = "../../media/person-lod1-left.obj";
allocateObjModel(lod1_v_count, lod1_f_count, &lod1l_vertices, &lod1l_normals, &lod1l_faces);
loadObjFromFile(lod1LeftString, lod1_v_count, lod1_f_count, lod1l_vertices, lod1l_normals, lod1l_faces);
scaleObj(PEDESTRIAN_MODEL_SCALE, lod1_v_count, lod1l_vertices);
//Right
char lod1RightString[] = "../../media/person-lod1-right.obj";
allocateObjModel(lod1_v_count, lod1_f_count, &lod1r_vertices, &lod1r_normals, &lod1r_faces);
loadObjFromFile(lod1RightString, lod1_v_count, lod1_f_count, lod1r_vertices, lod1r_normals, lod1r_faces);
scaleObj(PEDESTRIAN_MODEL_SCALE, lod1_v_count, lod1r_vertices);
createPedestrianBufferObjects();
initPedestrianShader();
}
void renderPedestrianPopulation()
{
int i;
int count=0;
//run CUDA
generate_pedestrian_instances(&p_instances_data1_tbo, &p_instances_data2_tbo, &p_instances_data1_cgr, &p_instances_data2_cgr);
glUseProgram(p_shaderProgram);
//bind instance data
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_BUFFER_EXT, p_instances_data1_tex);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_BUFFER_EXT, p_instances_data2_tex);
glUniform1i(pvs_active_exit, getActiveExit());
//draw lod 0 geometry
for (i=0; i<getPedestrianCount(); i++)
{
glVertexAttrib1f(pvs_instance_index, (float)count);
count++;
glBindBuffer(GL_ARRAY_BUFFER, lod1l_verts_vbo);
glVertexPointer(3, GL_FLOAT, 0, 0);
glEnableVertexAttribArray(pvs_position_r);
glBindBuffer(GL_ARRAY_BUFFER, lod1r_verts_vbo);
glVertexAttribPointer(pvs_position_r, 3, GL_FLOAT, 0, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lod1_elem_vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_ELEMENT_ARRAY_BUFFER);
glDrawElements(GL_TRIANGLES, lod1_f_count*3, GL_UNSIGNED_INT, 0);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_ELEMENT_ARRAY_BUFFER);
glDisableVertexAttribArray(lod1r_verts_vbo);
}
glUseProgram(0);
}
void createPedestrianBufferObjects()
{
//create TBO
createTBO(&p_instances_data1_tbo, &p_instances_data1_tex, get_agent_agent_MAX_count()* sizeof(glm::vec4));
createTBO(&p_instances_data2_tbo, &p_instances_data2_tex, get_agent_agent_MAX_count()* sizeof(glm::vec4));
registerBO(&p_instances_data1_cgr, &p_instances_data1_tbo);
registerBO(&p_instances_data2_cgr, &p_instances_data2_tbo);
//create VBOs
createVBO(&lod1l_verts_vbo, GL_ARRAY_BUFFER, lod1_v_count*sizeof(glm::vec3));
createVBO(&lod1_elem_vbo, GL_ELEMENT_ARRAY_BUFFER, lod1_f_count*sizeof(glm::ivec3));
createVBO(&lod1r_verts_vbo, GL_ARRAY_BUFFER, lod1_v_count*sizeof(glm::vec3));
//bind VBOs LOD1
glBindBuffer(GL_ARRAY_BUFFER, lod1l_verts_vbo);
glBufferData(GL_ARRAY_BUFFER, lod1_v_count*sizeof(glm::vec3), lod1l_vertices, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lod1_elem_vbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, lod1_f_count*sizeof(glm::ivec3), lod1l_faces, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, lod1r_verts_vbo);
glBufferData(GL_ARRAY_BUFFER, lod1_v_count*sizeof(glm::vec3), lod1r_vertices, GL_DYNAMIC_DRAW);
}
void initPedestrianShader()
{
const char* v = pedestrian_vshader_source;
int status;
//vertex shader
p_vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(p_vertexShader, 1, &v, 0);
glCompileShader(p_vertexShader);
//program
p_shaderProgram = glCreateProgram();
glAttachShader(p_shaderProgram, p_vertexShader);
glLinkProgram(p_shaderProgram);
// check for errors
glGetShaderiv(p_vertexShader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE){
char data[1024];
int len;
printf("ERROR: Shader Compilation Error\n");
glGetShaderInfoLog(p_vertexShader, 1024, &len, data);
printf("%s", data);
}
glGetProgramiv(p_shaderProgram, GL_LINK_STATUS, &status);
if (status == GL_FALSE){
printf("ERROR: Shader Program Link Error\n");
}
// get shader variables
pvs_data1_map = glGetUniformLocation(p_shaderProgram, "data1_map");
pvs_data2_map = glGetUniformLocation(p_shaderProgram, "data2_map");
pvs_instance_index = glGetAttribLocation(p_shaderProgram, "instance_index");
pvs_position_r = glGetAttribLocation(p_shaderProgram, "position_r");
pvs_active_exit = glGetUniformLocation(p_shaderProgram, "active_exit");
//set shader uniforms
glUseProgram(p_shaderProgram);
glUniform1i(pvs_data1_map, 0);
glUniform1i(pvs_data2_map, 1);
glUseProgram(0);
}
| 6,771 | 2,879 |
/**
* MIT License
*
* Copyright (c) 2021 Markus Worchel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "atlas.hpp"
#include "options.hpp"
#include "utils.hpp"
#include <cstdint>
#include <fstream>
#include <iostream>
#include <optional>
#include <stdexcept>
#include <string>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <xatlas.h>
namespace py = pybind11;
auto parametrize(ContiguousArray<float> const& positions,
ContiguousArray<std::uint32_t> const& indices,
std::optional<ContiguousArray<float>> normals = std::nullopt,
std::optional<ContiguousArray<float>> uvs = std::nullopt)
{
Atlas atlas;
atlas.addMesh(positions, indices, normals, uvs);
atlas.generate();
return atlas.getMesh(0);
}
void exportObj(std::string const& path,
ContiguousArray<float> const& positions,
std::optional<ContiguousArray<std::uint32_t>> indices = std::nullopt,
std::optional<ContiguousArray<float>> uvs = std::nullopt,
std::optional<ContiguousArray<float>> normals = std::nullopt)
{
// Perform sanity checks on the inputs
checkShape("Position", positions, 3);
if (indices)
{
checkShape("Index", *indices, 3);
}
if (normals)
{
checkShape("Normal", *normals, 3, positions.shape(0));
}
if (uvs)
{
checkShape("Texture coordinates", *uvs, 2, positions.shape(0));
}
std::ofstream file(path);
if (!file.is_open())
{
throw std::invalid_argument("Cannot open path " + path);
}
// Write the vertex positions
for (py::ssize_t v = 0; v < positions.shape(0); ++v)
{
float const* position = positions.data(v, 0);
file << "v " << position[0] << " " << position[1] << " " << position[2] << std::endl;
}
// Write the vertex normals
if (normals)
{
for (py::ssize_t v = 0; v < (*normals).shape(0); ++v)
{
float const* normal = (*normals).data(v, 0);
file << "vn " << normal[0] << " " << normal[1] << " " << normal[2] << std::endl;
}
}
// Write the vertex uv coordinates
if (uvs)
{
for (py::ssize_t v = 0; v < (*uvs).shape(0); ++v)
{
float const* uv = (*uvs).data(v, 0);
file << "vt " << uv[0] << " " << uv[1] << std::endl;
}
}
if (indices)
{
std::function<std::string(size_t)> formatFace = [](size_t index) { return std::to_string(index); };
if (normals && uvs)
{
formatFace = [](size_t index) { return std::to_string(index) + "/" + std::to_string(index) + "/" + std::to_string(index); };
}
else if (normals)
{
formatFace = [](size_t index) { return std::to_string(index) + "//" + std::to_string(index); };
}
else if (uvs)
{
formatFace = [](size_t index) { return std::to_string(index) + "/" + std::to_string(index); };
}
// Write the faces
for (py::ssize_t f = 0; f < (*indices).shape(0); ++f)
{
std::uint32_t const* face = (*indices).data(f, 0);
file << "f " << formatFace(static_cast<size_t>(face[0]) + 1) << " " << formatFace(static_cast<size_t>(face[1]) + 1) << " " << formatFace(static_cast<size_t>(face[2]) + 1) << std::endl;
}
}
}
PYBIND11_MODULE(xatlas, m)
{
// Bindings
ChartOptions::bind(m);
PackOptions::bind(m);
Atlas::bind(m);
// Convenience functions
m.def("parametrize", ¶metrize, py::arg("positions"), py::arg("indices"), py::arg("normals") = std::nullopt, py::arg("uvs") = std::nullopt);
// I/O functions
m.def("export", &exportObj, py::arg("path"), py::arg("positions"), py::arg("indices") = std::nullopt, py::arg("uvs") = std::nullopt, py::arg("normals") = std::nullopt);
} | 5,045 | 1,764 |
//g++-5 --std=c++11 -Wall -g -o ds_list_missing_number ds_list_missing_number.cc
/**
* @file Find Missing Number from Array
* @brief Given array containing n distinct integers [0, n) find missing integer
*/
// https://leetcode.com/problems/missing-number/
#include <iostream> /* std::cout */
#include <iomanip> /* std::setw */
#include <cmath> /* pow */
#include <cassert> /* assert */
#include <algorithm> /* std::max */
#include <vector> /* std::vector */
#include <string> /* std::string, */
#include <cstring> /* std::strtok */
#include <unordered_map> /* std::unordered_map container */
using namespace std;
/**
* Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find
* the one that is missing from the array.
* For example,
* Given nums = [0, 1, 3] return 2.
* Note:
* Your algorithm should run in linear runtime complexity. Could you implement it
* using only constant extra space complexity?
*/
/* Since numbers are in a specific sequence [0, n), use AP *
* to deduce what should be the total of all numbers. Next *
* subtract this from observed total to find missing elem */
int missingNumber(vector<int>& nums) {
/* sum of n numbers (1, 2, 3, ... n) = n(n+1)/2. *
* Handle 0 as a spl case */
int n = nums.size();
unsigned long obs_sum = 0, calc_sum = n * (n + 1) / 2;
for(int i = 0; i < (int)nums.size(); ++i) obs_sum += nums[i];
return calc_sum - obs_sum;
}
int main()
{
int ans, exp;
vector<int> nums;
nums = {0}; exp = 1;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
nums = {1}; exp = 0;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
nums = {5, 4, 6, 3, 1, 2}; exp = 0;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
nums = {5, 0, 6, 3, 1, 2}; exp = 4;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
cout << "All test-cases passed." << endl;
return 0;
Errmain:
cout << "Error: Missing Integer failed for - ";
for(auto val: nums) cout << val << ", "; cout << endl;
cout << "Expected = " << exp << " Got = " << ans << endl;
return -1;
}
| 2,412 | 812 |
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include <bullet/BulletCollision/Gimpact/btContactProcessing.h>
#define MAX_COINCIDENT 8
struct CONTACT_KEY_TOKEN
{
unsigned int m_key;
int m_value;
CONTACT_KEY_TOKEN()
{
}
CONTACT_KEY_TOKEN(unsigned int key, int token)
{
m_key = key;
m_value = token;
}
CONTACT_KEY_TOKEN(const CONTACT_KEY_TOKEN& rtoken)
{
m_key = rtoken.m_key;
m_value = rtoken.m_value;
}
inline bool operator<(const CONTACT_KEY_TOKEN& other) const
{
return (m_key < other.m_key);
}
inline bool operator>(const CONTACT_KEY_TOKEN& other) const
{
return (m_key > other.m_key);
}
};
class CONTACT_KEY_TOKEN_COMP
{
public:
bool operator()(const CONTACT_KEY_TOKEN& a, const CONTACT_KEY_TOKEN& b) const
{
return (a < b);
}
};
void btContactArray::merge_contacts(
const btContactArray& contacts, bool normal_contact_average)
{
clear();
int i;
if (contacts.size() == 0) return;
if (contacts.size() == 1)
{
push_back(contacts[0]);
return;
}
btAlignedObjectArray<CONTACT_KEY_TOKEN> keycontacts;
keycontacts.reserve(contacts.size());
//fill key contacts
for (i = 0; i < contacts.size(); i++)
{
keycontacts.push_back(CONTACT_KEY_TOKEN(contacts[i].calc_key_contact(), i));
}
//sort keys
keycontacts.quickSort(CONTACT_KEY_TOKEN_COMP());
// Merge contacts
int coincident_count = 0;
btVector3 coincident_normals[MAX_COINCIDENT];
unsigned int last_key = keycontacts[0].m_key;
unsigned int key = 0;
push_back(contacts[keycontacts[0].m_value]);
GIM_CONTACT* pcontact = &(*this)[0];
for (i = 1; i < keycontacts.size(); i++)
{
key = keycontacts[i].m_key;
const GIM_CONTACT* scontact = &contacts[keycontacts[i].m_value];
if (last_key == key) //same points
{
//merge contact
if (pcontact->m_depth - CONTACT_DIFF_EPSILON > scontact->m_depth) //)
{
*pcontact = *scontact;
coincident_count = 0;
}
else if (normal_contact_average)
{
if (btFabs(pcontact->m_depth - scontact->m_depth) < CONTACT_DIFF_EPSILON)
{
if (coincident_count < MAX_COINCIDENT)
{
coincident_normals[coincident_count] = scontact->m_normal;
coincident_count++;
}
}
}
}
else
{ //add new contact
if (normal_contact_average && coincident_count > 0)
{
pcontact->interpolate_normals(coincident_normals, coincident_count);
coincident_count = 0;
}
push_back(*scontact);
pcontact = &(*this)[this->size() - 1];
}
last_key = key;
}
}
void btContactArray::merge_contacts_unique(const btContactArray& contacts)
{
clear();
if (contacts.size() == 0) return;
if (contacts.size() == 1)
{
push_back(contacts[0]);
return;
}
GIM_CONTACT average_contact = contacts[0];
for (int i = 1; i < contacts.size(); i++)
{
average_contact.m_point += contacts[i].m_point;
average_contact.m_normal += contacts[i].m_normal * contacts[i].m_depth;
}
//divide
btScalar divide_average = 1.0f / ((btScalar)contacts.size());
average_contact.m_point *= divide_average;
average_contact.m_normal *= divide_average;
average_contact.m_depth = average_contact.m_normal.length();
average_contact.m_normal /= average_contact.m_depth;
}
| 4,137 | 1,674 |
/***************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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.
***************************************************************************/
#include "stdafx.h"
#include "D3D12Resource.h"
#include "Utils/StringUtils.h"
namespace Falcor
{
const D3D12_HEAP_PROPERTIES kDefaultHeapProps =
{
D3D12_HEAP_TYPE_DEFAULT,
D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
D3D12_MEMORY_POOL_UNKNOWN,
0,
0
};
const D3D12_HEAP_PROPERTIES kUploadHeapProps =
{
D3D12_HEAP_TYPE_UPLOAD,
D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
D3D12_MEMORY_POOL_UNKNOWN,
0,
0,
};
const D3D12_HEAP_PROPERTIES kReadbackHeapProps =
{
D3D12_HEAP_TYPE_READBACK,
D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
D3D12_MEMORY_POOL_UNKNOWN,
0,
0
};
D3D12_RESOURCE_FLAGS getD3D12ResourceFlags(Resource::BindFlags flags)
{
D3D12_RESOURCE_FLAGS d3d = D3D12_RESOURCE_FLAG_NONE;
bool uavRequired = is_set(flags, Resource::BindFlags::UnorderedAccess) || is_set(flags, Resource::BindFlags::AccelerationStructure);
if (uavRequired)
{
d3d |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
}
if (is_set(flags, Resource::BindFlags::DepthStencil))
{
if (is_set(flags, Resource::BindFlags::ShaderResource) == false)
{
d3d |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
}
d3d |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
}
if (is_set(flags, Resource::BindFlags::RenderTarget))
{
d3d |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
}
return d3d;
}
D3D12_RESOURCE_STATES getD3D12ResourceState(Resource::State s)
{
switch (s)
{
case Resource::State::Undefined:
case Resource::State::Common:
return D3D12_RESOURCE_STATE_COMMON;
case Resource::State::ConstantBuffer:
case Resource::State::VertexBuffer:
return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
case Resource::State::CopyDest:
return D3D12_RESOURCE_STATE_COPY_DEST;
case Resource::State::CopySource:
return D3D12_RESOURCE_STATE_COPY_SOURCE;
case Resource::State::DepthStencil:
return D3D12_RESOURCE_STATE_DEPTH_WRITE; // If depth-writes are disabled, return D3D12_RESOURCE_STATE_DEPTH_WRITE
case Resource::State::IndexBuffer:
return D3D12_RESOURCE_STATE_INDEX_BUFFER;
case Resource::State::IndirectArg:
return D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
case Resource::State::Predication:
return D3D12_RESOURCE_STATE_PREDICATION;
case Resource::State::Present:
return D3D12_RESOURCE_STATE_PRESENT;
case Resource::State::RenderTarget:
return D3D12_RESOURCE_STATE_RENDER_TARGET;
case Resource::State::ResolveDest:
return D3D12_RESOURCE_STATE_RESOLVE_DEST;
case Resource::State::ResolveSource:
return D3D12_RESOURCE_STATE_RESOLVE_SOURCE;
case Resource::State::ShaderResource:
return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; // Need the shader usage mask in case the SRV is used by non-PS
case Resource::State::StreamOut:
return D3D12_RESOURCE_STATE_STREAM_OUT;
case Resource::State::UnorderedAccess:
return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
case Resource::State::GenericRead:
return D3D12_RESOURCE_STATE_GENERIC_READ;
case Resource::State::NonPixelShader:
return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
case Resource::State::AccelerationStructure:
return D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE;
default:
should_not_get_here();
return D3D12_RESOURCE_STATE_GENERIC_READ;
}
}
void Resource::apiSetName()
{
std::wstring ws = string_2_wstring(mName);
mApiHandle->SetName(ws.c_str());
}
SharedResourceApiHandle Resource::createSharedApiHandle()
{
ID3D12DevicePtr pDevicePtr = gpDevice->getApiHandle();
auto s = string_2_wstring(mName);
SharedResourceApiHandle pHandle;
HRESULT res = pDevicePtr->CreateSharedHandle(mApiHandle, 0, GENERIC_ALL, s.c_str(), &pHandle);
if (res == S_OK) return pHandle;
else return nullptr;
}
}
| 6,047 | 2,141 |
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
if (inorder.empty())
return NULL;
int value = preorder[0];
preorder.erase(preorder.begin());
TreeNode *root = new TreeNode(value);
vector<int>::iterator index = std::find(inorder.begin(), inorder.end(), value);
vector<int> left(inorder.begin(), index);
root->left = buildTree(preorder, left);
vector<int> right(index + 1, inorder.end());
root->right = buildTree(preorder, right);
return root;
}
};
int main()
{
}
| 823 | 264 |
// Copyright 2018-2020 VMware, all rights reserved
//
// KV Blockchain replica implementation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "ReplicaImp.h"
#include <inttypes.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <exception>
#include <utility>
#include "assertUtils.hpp"
#include "communication/CommDefs.hpp"
#include "kv_types.hpp"
#include "hex_tools.h"
#include "replica_state_sync.h"
#include "sliver.hpp"
#include "bftengine/DbMetadataStorage.hpp"
using bft::communication::ICommunication;
using bftEngine::bcst::StateTransferDigest;
using namespace concord::diagnostics;
using concord::storage::DBMetadataStorage;
namespace concord::kvbc {
/**
* Opens the database and creates the replica thread. Replica state moves to
* Starting.
*/
Status ReplicaImp::start() {
LOG_INFO(logger, "ReplicaImp::Start() id = " << m_replicaConfig.replicaId);
if (m_currentRepStatus != RepStatus::Idle) {
return Status::IllegalOperation("todo");
}
m_currentRepStatus = RepStatus::Starting;
if (m_replicaConfig.isReadOnly) {
LOG_INFO(logger, "ReadOnly mode");
m_replicaPtr =
bftEngine::IReplica::createNewRoReplica(m_replicaConfig, m_stateTransfer, m_ptrComm, m_metadataStorage);
} else {
createReplicaAndSyncState();
}
m_replicaPtr->setControlStateManager(controlStateManager_);
m_replicaPtr->SetAggregator(aggregator_);
m_replicaPtr->start();
m_currentRepStatus = RepStatus::Running;
/// TODO(IG, GG)
/// add return value to start/stop
return Status::OK();
}
void ReplicaImp::createReplicaAndSyncState() {
bool isNewStorage = m_metadataStorage->isNewStorage();
bool erasedMetaData;
m_replicaPtr = bftEngine::IReplica::createNewReplica(
m_replicaConfig, m_cmdHandler, m_stateTransfer, m_ptrComm, m_metadataStorage, erasedMetaData);
if (erasedMetaData) isNewStorage = true;
LOG_INFO(logger, "createReplicaAndSyncState: isNewStorage= " << isNewStorage);
if (!isNewStorage && !m_stateTransfer->isCollectingState()) {
uint64_t removedBlocksNum = replicaStateSync_->execute(
logger, *m_bcDbAdapter, getLastReachableBlockNum(), m_replicaPtr->getLastExecutedSequenceNum());
LOG_INFO(logger,
"createReplicaAndSyncState: removedBlocksNum = "
<< removedBlocksNum << ", new m_lastBlock = " << getLastBlockNum()
<< ", new m_lastReachableBlock = " << getLastReachableBlockNum());
}
}
/**
* Closes the database. Call `wait()` after this to wait for thread to stop.
*/
Status ReplicaImp::stop() {
m_currentRepStatus = RepStatus::Stopping;
m_replicaPtr->stop();
m_currentRepStatus = RepStatus::Idle;
return Status::OK();
}
ReplicaImp::RepStatus ReplicaImp::getReplicaStatus() const { return m_currentRepStatus; }
const ILocalKeyValueStorageReadOnly &ReplicaImp::getReadOnlyStorage() { return *this; }
Status ReplicaImp::addBlockToIdleReplica(const SetOfKeyValuePairs &updates) {
if (getReplicaStatus() != IReplica::RepStatus::Idle) {
return Status::IllegalOperation("");
}
BlockId d;
return addBlockInternal(updates, d);
}
Status ReplicaImp::get(const Sliver &key, Sliver &outValue) const {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
TimeRecorder scoped_timer(*histograms_.get_value);
BlockId dummy;
return getInternal(getLastBlockNum(), key, outValue, dummy);
}
Status ReplicaImp::get(BlockId readVersion, const Sliver &key, Sliver &outValue, BlockId &outBlock) const {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
TimeRecorder scoped_timer(*histograms_.get_block);
return getInternal(readVersion, key, outValue, outBlock);
}
Status ReplicaImp::getBlockData(BlockId blockId, SetOfKeyValuePairs &outBlockData) const {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
try {
TimeRecorder scoped_timer(*histograms_.get_block_data);
Sliver block = getBlockInternal(blockId);
outBlockData = m_bcDbAdapter->getBlockData(block);
} catch (const NotFoundException &e) {
LOG_ERROR(logger, e.what());
return Status::NotFound("todo");
}
return Status::OK();
}
Status ReplicaImp::mayHaveConflictBetween(const Sliver &key, BlockId fromBlock, BlockId toBlock, bool &outRes) const {
// TODO(GG): add assert or print warning if fromBlock==0 (all keys have a
// conflict in block 0)
TimeRecorder scoped_timer(*histograms_.may_have_conflict_between);
// we conservatively assume that we have a conflict
outRes = true;
Sliver dummy;
BlockId block = 0;
Status s = getInternal(toBlock, key, dummy, block);
if (s.isOK() && block < fromBlock) {
outRes = false;
}
return s;
}
Status ReplicaImp::addBlock(const SetOfKeyValuePairs &updates,
BlockId &outBlockId,
const concordUtils::SpanWrapper & /*parent_span*/) {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
// TODO(GG): what do we want to do with several identical keys in the same
// block?
TimeRecorder scoped_timer(*histograms_.add_block);
return addBlockInternal(updates, outBlockId);
}
void ReplicaImp::deleteGenesisBlock() {
const auto genesisBlock = m_bcDbAdapter->getGenesisBlockId();
if (genesisBlock == 0) {
throw std::logic_error{"Cannot delete the genesis block from an empty blockchain"};
}
m_bcDbAdapter->deleteBlock(genesisBlock);
}
BlockId ReplicaImp::deleteBlocksUntil(BlockId until) {
const auto genesisBlock = m_bcDbAdapter->getGenesisBlockId();
if (genesisBlock == 0) {
throw std::logic_error{"Cannot delete a block range from an empty blockchain"};
} else if (until <= genesisBlock) {
throw std::invalid_argument{"Invalid 'until' value passed to deleteBlocksUntil()"};
}
const auto lastBlock = getLastBlock();
const auto lastDeletedBlock = std::min(lastBlock, until - 1);
for (auto i = genesisBlock; i <= lastDeletedBlock; ++i) {
m_bcDbAdapter->deleteBlock(i);
}
return lastDeletedBlock;
}
void ReplicaImp::set_command_handler(ICommandsHandler *handler) {
m_cmdHandler = handler;
m_cmdHandler->setControlStateManager(controlStateManager_);
}
ReplicaImp::ReplicaImp(ICommunication *comm,
const bftEngine::ReplicaConfig &replicaConfig,
std::unique_ptr<IStorageFactory> storageFactory,
std::shared_ptr<concordMetrics::Aggregator> aggregator)
: logger(logging::getLogger("skvbc.replicaImp")),
m_currentRepStatus(RepStatus::Idle),
m_ptrComm(comm),
m_replicaConfig(replicaConfig),
aggregator_(aggregator) {
bftEngine::bcst::Config state_transfer_config;
state_transfer_config.myReplicaId = m_replicaConfig.replicaId;
state_transfer_config.cVal = m_replicaConfig.cVal;
state_transfer_config.fVal = m_replicaConfig.fVal;
state_transfer_config.numReplicas = m_replicaConfig.numReplicas + m_replicaConfig.numRoReplicas;
state_transfer_config.metricsDumpIntervalSeconds = std::chrono::seconds(m_replicaConfig.metricsDumpIntervalSeconds);
state_transfer_config.isReadOnly = replicaConfig.isReadOnly;
if (replicaConfig.maxNumOfReservedPages > 0)
state_transfer_config.maxNumOfReservedPages = replicaConfig.maxNumOfReservedPages;
if (replicaConfig.sizeOfReservedPage > 0) state_transfer_config.sizeOfReservedPage = replicaConfig.sizeOfReservedPage;
state_transfer_config.sourceReplicaReplacementTimeoutMilli =
replicaConfig.get("sourceReplicaReplacementTimeoutMilli", 5000);
auto dbSet = storageFactory->newDatabaseSet();
m_bcDbAdapter = std::move(dbSet.dbAdapter);
dbSet.dataDBClient->setAggregator(aggregator);
dbSet.metadataDBClient->setAggregator(aggregator);
m_metadataDBClient = dbSet.metadataDBClient;
auto stKeyManipulator = std::shared_ptr<storage::ISTKeyManipulator>{storageFactory->newSTKeyManipulator()};
m_stateTransfer =
bftEngine::bcst::create(state_transfer_config, this, m_metadataDBClient, stKeyManipulator, aggregator_);
m_metadataStorage = new DBMetadataStorage(m_metadataDBClient.get(), storageFactory->newMetadataKeyManipulator());
controlStateManager_ =
std::make_shared<bftEngine::ControlStateManager>(m_stateTransfer, m_replicaConfig.sizeOfReservedPage);
}
ReplicaImp::~ReplicaImp() {
if (m_replicaPtr) {
if (m_replicaPtr->isRunning()) {
m_replicaPtr->stop();
}
}
}
Status ReplicaImp::addBlockInternal(const SetOfKeyValuePairs &updates, BlockId &outBlockId) {
outBlockId = m_bcDbAdapter->addBlock(updates);
return Status::OK();
}
Status ReplicaImp::getInternal(BlockId readVersion, const Key &key, Sliver &outValue, BlockId &outBlock) const {
const auto clear = [&outValue, &outBlock]() {
outValue = Sliver{};
outBlock = 0;
};
try {
std::tie(outValue, outBlock) = m_bcDbAdapter->getValue(key, readVersion);
} catch (const NotFoundException &) {
clear();
} catch (const std::exception &e) {
clear();
return Status::GeneralError(std::string{"getInternal() failed to get value due to a DBAdapter error: "} + e.what());
} catch (...) {
clear();
return Status::GeneralError("getInternal() failed to get value due to an unknown DBAdapter error");
}
return Status::OK();
}
/*
* This method can't return false by current insertBlockInternal impl.
* It is used only by State Transfer to synchronize state between replicas.
*/
bool ReplicaImp::putBlock(const uint64_t blockId, const char *block_data, const uint32_t blockSize) {
Sliver block = Sliver::copy(block_data, blockSize);
if (m_bcDbAdapter->hasBlock(blockId)) {
// if we already have a block with the same ID
RawBlock existingBlock = m_bcDbAdapter->getRawBlock(blockId);
if (existingBlock.length() != block.length() || memcmp(existingBlock.data(), block.data(), block.length()) != 0) {
// the replica is corrupted !
LOG_ERROR(logger,
"found block " << blockId << ", size in db is " << existingBlock.length() << ", inserted is "
<< block.length() << ", data in db " << existingBlock << ", data inserted " << block);
LOG_ERROR(logger,
"Block size test " << (existingBlock.length() != block.length()) << ", block data test "
<< (memcmp(existingBlock.data(), block.data(), block.length())));
m_bcDbAdapter->deleteBlock(blockId);
throw std::runtime_error(__PRETTY_FUNCTION__ + std::string("data corrupted blockId: ") + std::to_string(blockId));
}
} else {
m_bcDbAdapter->addRawBlock(block, blockId);
}
return true;
}
RawBlock ReplicaImp::getBlockInternal(BlockId blockId) const { return m_bcDbAdapter->getRawBlock(blockId); }
/*
* This method assumes that *outBlock is big enough to hold block content
* The caller is the owner of the memory
*/
bool ReplicaImp::getBlock(uint64_t blockId, char *outBlock, uint32_t *outBlockSize) {
try {
RawBlock block = getBlockInternal(blockId);
*outBlockSize = block.length();
memcpy(outBlock, block.data(), block.length());
return true;
} catch (const NotFoundException &e) {
LOG_FATAL(logger, e.what());
throw;
}
}
bool ReplicaImp::hasBlock(BlockId blockId) const { return m_bcDbAdapter->hasBlock(blockId); }
bool ReplicaImp::getPrevDigestFromBlock(BlockId blockId, StateTransferDigest *outPrevBlockDigest) {
ConcordAssert(blockId > 0);
try {
RawBlock result = getBlockInternal(blockId);
auto parentDigest = m_bcDbAdapter->getParentDigest(result);
ConcordAssert(outPrevBlockDigest != nullptr);
static_assert(parentDigest.size() == BLOCK_DIGEST_SIZE);
static_assert(sizeof(StateTransferDigest) == BLOCK_DIGEST_SIZE);
memcpy(outPrevBlockDigest, parentDigest.data(), BLOCK_DIGEST_SIZE);
return true;
} catch (const NotFoundException &e) {
LOG_FATAL(logger, "Block not found for parent digest, ID: " << blockId << " " << e.what());
throw;
}
}
} // namespace concord::kvbc
| 12,220 | 3,936 |
#ifndef _DIYEXT_SCATTER_HH
#define _DIYEXT_SCATTER_HH
#include <ftk/external/diy/mpi.hpp>
#include <ftk/utils/serialization.hh>
#include <numeric>
namespace diy { namespace mpi {
template <typename Obj>
inline void scatterv(const communicator& comm,
const std::vector<Obj> &ins,
Obj &out,
int root = 0)
{
#if FTK_HAVE_MPI
assert(ins.size() == comm.size());
const int np = comm.size(), rank = comm.rank();
// prepare sendbuf
std::string sendbuf;
StringBuffer sb(sendbuf);
std::vector<int> sendcounts(np), displs(np);
for (int i = 0; i < ins.size(); i ++) {
displs[i] = sendbuf.size();
save(sb, ins[i]);
sendcounts[i] = sendbuf.size() - displs[i];
}
// bcast counts and displs
broadcast(comm, sendcounts, root);
broadcast(comm, displs, root);
// prepare recvbuf
std::string recvbuf;
recvbuf.resize( sendcounts[rank] );
// call MPI_Scatterv
MPI_Scatterv(&sendbuf[0], &sendcounts[0], &displs[0], MPI_CHAR,
&recvbuf[0], recvbuf.size(), MPI_CHAR,
root, comm);
// unseralize
StringBuffer bb(recvbuf);
load(bb, out);
#else
out = ins[0];
#endif
}
}}
#endif
| 1,139 | 472 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _MATHMLIMPORT_HXX_
#define _MATHMLIMPORT_HXX_
#include <xmloff/xmlimp.hxx>
#include <xmloff/xmlexp.hxx>
#include <xmloff/DocumentSettingsContext.hxx>
#include <xmloff/xmltoken.hxx>
#include <node.hxx>
class SfxMedium;
namespace com { namespace sun { namespace star {
namespace io {
class XInputStream;
class XOutputStream; }
namespace beans {
class XPropertySet; }
} } }
////////////////////////////////////////////////////////////
class SmXMLImportWrapper
{
com::sun::star::uno::Reference<com::sun::star::frame::XModel> xModel;
public:
SmXMLImportWrapper(com::sun::star::uno::Reference<com::sun::star::frame::XModel> &rRef)
: xModel(rRef) {}
sal_uLong Import(SfxMedium &rMedium);
sal_uLong ReadThroughComponent(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xInputStream,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xModelComponent,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rFactory,
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropSet,
const sal_Char* pFilterName,
sal_Bool bEncrypted );
sal_uLong ReadThroughComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xModelComponent,
const sal_Char* pStreamName,
const sal_Char* pCompatibilityStreamName,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rFactory,
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropSet,
const sal_Char* pFilterName );
};
////////////////////////////////////////////////////////////
class SmXMLImport : public SvXMLImport
{
SvXMLTokenMap *pPresLayoutElemTokenMap;
SvXMLTokenMap *pPresLayoutAttrTokenMap;
SvXMLTokenMap *pFencedAttrTokenMap;
SvXMLTokenMap *pOperatorAttrTokenMap;
SvXMLTokenMap *pAnnotationAttrTokenMap;
SvXMLTokenMap *pPresElemTokenMap;
SvXMLTokenMap *pPresScriptEmptyElemTokenMap;
SvXMLTokenMap *pPresTableElemTokenMap;
SvXMLTokenMap *pColorTokenMap;
SmNodeStack aNodeStack;
sal_Bool bSuccess;
String aText;
public:
// #110680#
SmXMLImport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
sal_uInt16 nImportFlags=IMPORT_ALL);
virtual ~SmXMLImport() throw ();
// XServiceInfo (override parent method)
::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
// XUnoTunnel
sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rId ) throw(::com::sun::star::uno::RuntimeException);
static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
void SAL_CALL endDocument(void)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
SvXMLImportContext *CreateContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateMathContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateRowContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateFracContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateNumberContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTextContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateAnnotationContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateStringContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateIdentifierContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateOperatorContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSpaceContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSqrtContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateRootContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateStyleContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreatePaddedContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreatePhantomContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateFencedContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateErrorContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSubContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSupContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSubSupContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateUnderContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateOverContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateUnderOverContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateMultiScriptsContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateNoneContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreatePrescriptsContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTableContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTableRowContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTableCellContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateAlignGroupContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateActionContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
const SvXMLTokenMap &GetPresLayoutElemTokenMap();
const SvXMLTokenMap &GetPresLayoutAttrTokenMap();
const SvXMLTokenMap &GetFencedAttrTokenMap();
const SvXMLTokenMap &GetOperatorAttrTokenMap();
const SvXMLTokenMap &GetAnnotationAttrTokenMap();
const SvXMLTokenMap &GetPresElemTokenMap();
const SvXMLTokenMap &GetPresScriptEmptyElemTokenMap();
const SvXMLTokenMap &GetPresTableElemTokenMap();
const SvXMLTokenMap &GetColorTokenMap();
SmNodeStack & GetNodeStack() { return aNodeStack; }
SmNode *GetTree() { return aNodeStack.Pop(); }
sal_Bool GetSuccess() { return bSuccess; }
String &GetText() { return aText; }
virtual void SetViewSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps);
virtual void SetConfigurationSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps);
};
////////////////////////////////////////////////////////////
enum SmXMLMathElemTokenMap
{
XML_TOK_MATH
};
enum SmXMLPresLayoutElemTokenMap
{
XML_TOK_SEMANTICS,
XML_TOK_MSTYLE,
XML_TOK_MERROR,
XML_TOK_MPHANTOM,
XML_TOK_MROW,
XML_TOK_MFRAC,
XML_TOK_MSQRT,
XML_TOK_MROOT,
XML_TOK_MSUB,
XML_TOK_MSUP,
XML_TOK_MSUBSUP,
XML_TOK_MMULTISCRIPTS,
XML_TOK_MUNDER,
XML_TOK_MOVER,
XML_TOK_MUNDEROVER,
XML_TOK_MTABLE,
XML_TOK_MACTION,
XML_TOK_MFENCED,
XML_TOK_MPADDED
};
enum SmXMLPresLayoutAttrTokenMap
{
XML_TOK_FONTWEIGHT,
XML_TOK_FONTSTYLE,
XML_TOK_FONTSIZE,
XML_TOK_FONTFAMILY,
XML_TOK_COLOR,
XML_TOK_MATHCOLOR
};
enum SmXMLFencedAttrTokenMap
{
XML_TOK_OPEN,
XML_TOK_CLOSE
};
enum SmXMLPresTableElemTokenMap
{
XML_TOK_MTR,
XML_TOK_MTD
};
enum SmXMLPresElemTokenMap
{
XML_TOK_ANNOTATION,
XML_TOK_MI,
XML_TOK_MN,
XML_TOK_MO,
XML_TOK_MTEXT,
XML_TOK_MSPACE,
XML_TOK_MS,
XML_TOK_MALIGNGROUP
};
enum SmXMLPresScriptEmptyElemTokenMap
{
XML_TOK_MPRESCRIPTS,
XML_TOK_NONE
};
enum SmXMLOperatorAttrTokenMap
{
XML_TOK_STRETCHY
};
enum SmXMLAnnotationAttrTokenMap
{
XML_TOK_ENCODING
};
////////////////////////////////////////////////////////////
#endif
| 13,324 | 4,349 |
#include <tst/set.hpp>
#include <tst/check.hpp>
#include <morda/gui.hpp>
#include <morda/widgets/group/column.hpp>
#include "../../harness/util/dummy_context.hpp"
namespace{
tst::set set("get_all_widgets", [](tst::suite& suite){
suite.add("get_all_widgets_function", []{
morda::gui m(make_dummy_context());
auto w = m.context->inflater.inflate(treeml::read(R"qwertyuiop(
@container{
@column{
id{1}
}
@column{
id{2}
@column{
id{3}
}
@row{
id{4}
@pile{
id{8}
@column{
id{9}
}
}
}
}
@pile{
id{5}
@column{
id{6}
@row{
id{7}
}
}
}
}
)qwertyuiop"));
std::vector<std::string> expected_ids = {{
"1", "2", "3", "6", "9"
}};
tst::check(w != nullptr, SL);
auto aaas = w->get_all_widgets<morda::column>();
tst::check_ne(aaas.size(), size_t(0), SL);
for(const auto& id : expected_ids){
auto i = std::find_if(
aaas.begin(),
aaas.end(),
[&id](const decltype(aaas)::value_type& wg) -> bool {
return wg->id == id;
}
);
tst::check(i != aaas.end(), SL) << "id = '" << id <<"' not found";
}
});
});
}
| 1,229 | 684 |
//---------------------------------------------------------------------------
//
// FCST: Fuel Cell Simulation Toolbox
//
// Copyright (C) 2013 by Energy Systems Design Laboratory, University of Alberta
//
// This software is distributed under the MIT License.
// For more information, see the README file in /doc/LICENSE
//
// - Class: catalyst_layer.cc
// - Description: Base Catalyst Layer Class. It implements the interface for other catalyst layer class
// and some common methods.
// - Developers: Marc Secanell (2011-2013) and Madhur Bhaiya (2013)
// - $Id: catalyst_layer.cc 2605 2014-08-15 03:36:44Z secanell $
//
//---------------------------------------------------------------------------
#include <layers/catalyst_layer.h>
namespace NAME = FuelCellShop::Layer;
//---------------------------------------------------------------------------
template <int dim>
NAME::CatalystLayer<dim>::CatalystLayer(const std::string& name)
: NAME::PorousLayer<dim>(name)
{
this->reactant = nothing;
//this->constant_solutions[temperature_of_REV] = 0.; // For debug checking purposes
this->constant_solutions[total_pressure] = 0.; // For debug checking purposes
electrolyte = boost::shared_ptr<FuelCellShop::Material::PolymerElectrolyteBase > ();
catalyst_support = boost::shared_ptr< FuelCellShop::Material::CatalystSupportBase > ();
catalyst = boost::shared_ptr< FuelCellShop::Material::CatalystBase > ();
default_materials = true;
kinetics = boost::shared_ptr< FuelCellShop::Kinetics::BaseKinetics > ();
}
//---------------------------------------------------------------------------
template <int dim>
NAME::CatalystLayer<dim>::CatalystLayer()
: NAME::PorousLayer<dim> ()
{
this->reactant = nothing;
//this->constant_solutions[temperature_of_REV] = 0.; // For debug checking purposes
this->constant_solutions[total_pressure] = 0.; // For debug checking purposes
}
//---------------------------------------------------------------------------
template <int dim>
NAME::CatalystLayer<dim>::~CatalystLayer()
{
// No need to delete boost pointers since boost manages memory allocation
}
//---------------------------------------------------------------------------
template <int dim>
void
NAME::CatalystLayer<dim>::declare_parameters (const std::string& name,
ParameterHandler ¶m) const
{
FuelCellShop::Layer::PorousLayer<dim>::declare_parameters(name,param);
param.enter_subsection("Fuel cell data");
{
param.enter_subsection(name);
{
param.declare_entry("Catalyst layer type",
"DummyCL",
Patterns::Selection("DummyCL | HomogeneousCL | MultiScaleCL"),
" ");
param.declare_entry("Catalyst type",
"Platinum",
Patterns::Selection("Platinum"),
" ");
param.declare_entry("Catalyst support type",
"CarbonBlack",
Patterns::Selection("CarbonBlack"),
" ");
param.declare_entry("Electrolyte type",
"Nafion",
Patterns::Selection("Nafion"),
" ");
param.declare_entry("Kinetics type",
"TafelKinetics",
Patterns::Selection("TafelKinetics | ButlerVolmerKinetics | DoubleTrapKinetics | DualPathKinetics"),
" ");
// Note: This must be called within the section of the CL
FuelCellShop::Material::CatalystBase::declare_Catalyst_parameters(param);
FuelCellShop::Material::CatalystSupportBase::declare_CatalystSupport_parameters(param);
FuelCellShop::Material::PolymerElectrolyteBase::declare_PolymerElectrolyte_parameters(param);
FuelCellShop::Kinetics::BaseKinetics::declare_Kinetics_parameters(param);
}
param.leave_subsection();
}
param.leave_subsection();
}
//---------------------------------------------------------------------------
template <int dim>
void
NAME::CatalystLayer<dim>::initialize (ParameterHandler ¶m)
{
NAME::PorousLayer<dim>::initialize(param);
param.enter_subsection("Fuel cell data");
{
param.enter_subsection(this->name);
{
catalyst_type = param.get("Catalyst type");
catalyst_support_type = param.get("Catalyst support type");
electrolyte_type = param.get("Electrolyte type");
kinetics_type = param.get("Kinetics type");
catalyst = FuelCellShop::Material::CatalystBase::create_Catalyst(param, catalyst_type);
catalyst_support = FuelCellShop::Material::CatalystSupportBase::create_CatalystSupport(param, catalyst_support_type);
electrolyte = FuelCellShop::Material::PolymerElectrolyteBase::create_PolymerElectrolyte(param, electrolyte_type);
kinetics = FuelCellShop::Kinetics::BaseKinetics::create_Kinetics(param, kinetics_type);
kinetics->set_catalyst(catalyst.get());
kinetics->set_electrolyte(electrolyte.get());
}
param.leave_subsection();
}
param.leave_subsection();
}
//---------------------------------------------------------------------------
template <int dim>
void
NAME::CatalystLayer<dim>::set_solution(const std::vector< SolutionVariable >& sols)
{
Assert( std::find_if(sols.begin(), sols.end(), FuelCellShop::is_phiS) != sols.end(), ExcMessage("VariableNames::electronic_electrical_potential should exist in input vector to CatalystLayer::set_solution.") );
Assert( std::find_if(sols.begin(), sols.end(), FuelCellShop::is_phiM) != sols.end(), ExcMessage("VariableNames::protonic_electrical_potential should exist in input vector to CatalystLayer::set_solution.") );
std::vector<SolutionVariable> reactant_concentrations;
//-- Check if the problem is isothermal or non-isothermal and extract index for T:
int index_T = -1;
for (unsigned int s=0; s < sols.size(); ++s) {
if (sols[s].get_variablename() == temperature_of_REV){
index_T = s;
break;
}
}
//Ensure that we only compute with "current" solutions
this->solutions.clear();
for (unsigned int i=0; i < sols.size(); ++i)
{
if (sols[i].get_variablename() == electronic_electrical_potential)
{
this->kinetics->set_solid_potential(sols.at(i));
this->solutions[electronic_electrical_potential] = sols.at(i);
}
else if (sols[i].get_variablename() == protonic_electrical_potential)
{
this->kinetics->set_electrolyte_potential(sols.at(i));
this->solutions[protonic_electrical_potential] = sols.at(i);
}
else if( sols[i].get_variablename() == hydrogen_concentration )
{
AssertThrow( this->electrolyte->get_H_H2() != 0, ExcMessage("Henry's constant for hydrogen not initialized in the electrolyte object of the catalyst layer.") );
std::vector<double> hydrogen_concentration_old_GL(sols[i].size());
if (index_T >= 0) // Non-isothermal
for(unsigned int q = 0; q < hydrogen_concentration_old_GL.size(); ++q)
hydrogen_concentration_old_GL[q] = Constants::R()*sols.at(index_T)[q]*sols.at(i)[q]/(this->electrolyte->get_H_H2()*1.0e-6);
else
{
AssertThrow( this->constant_solutions.at(temperature_of_REV) != 0., ExcMessage("Temperature not initialized in the catalyst layer using set_T method.") );
for(unsigned int q = 0; q < hydrogen_concentration_old_GL.size(); ++q)
hydrogen_concentration_old_GL[q] = Constants::R()*this->constant_solutions.at(temperature_of_REV)*sols.at(i)[q]/(this->electrolyte->get_H_H2()*1.0e-6);
}
this->solutions[VariableNames::hydrogen_concentration] = FuelCellShop::SolutionVariable( hydrogen_concentration_old_GL,
VariableNames::hydrogen_concentration);
this->reactant = VariableNames::hydrogen_concentration;
reactant_concentrations.push_back( FuelCellShop::SolutionVariable( hydrogen_concentration_old_GL,
VariableNames::hydrogen_concentration) );
}
else if( sols[i].get_variablename() == oxygen_concentration )
{
AssertThrow( this->electrolyte->get_H_O2() != 0, ExcMessage("Henry's constant for oxygen not initialized in the electrolyte object of the catalyst layer.") );
std::vector<double> oxygen_concentration_old_GL(sols[i].size());
if (index_T >= 0) // Non-isothermal
{
for(unsigned int q = 0; q < oxygen_concentration_old_GL.size(); ++q)
oxygen_concentration_old_GL[q] = Constants::R()*sols.at(index_T)[q]*sols.at(i)[q]/(this->electrolyte->get_H_O2()*1.0e-6);
}
else
{
AssertThrow( this->constant_solutions.at(temperature_of_REV) != 0., ExcMessage("Temperature not initialized in the catalyst layer using set_T method.") );
for(unsigned int q = 0; q < oxygen_concentration_old_GL.size(); ++q)
oxygen_concentration_old_GL[q] = Constants::R()*this->constant_solutions.at(temperature_of_REV)*sols.at(i)[q]/(this->electrolyte->get_H_O2()*1.0e-6);
}
this->solutions[VariableNames::oxygen_concentration] = FuelCellShop::SolutionVariable( oxygen_concentration_old_GL,
VariableNames::oxygen_concentration);
this->reactant = VariableNames::oxygen_concentration;
reactant_concentrations.push_back( FuelCellShop::SolutionVariable( oxygen_concentration_old_GL, VariableNames::oxygen_concentration) );
}
else if (sols[i].get_variablename() == temperature_of_REV)
{
this->kinetics->set_temperature(sols.at(i));
this->solutions[temperature_of_REV] = sols.at(i);
}
else if (sols[i].get_variablename() == membrane_water_content)
{
this->solutions[membrane_water_content] = sols.at(i);
}
else if (sols[i].get_variablename() == oxygen_molar_fraction)
{
Assert( this->constant_solutions.at(total_pressure) != 0., ExcMessage("Total pressure not initialized in the catalyst layer using set_P method.") );
AssertThrow( this->electrolyte->get_H_O2() != 0, ExcMessage("Henry's constant for oxygen not initialized in the electrolyte object of the catalyst layer.") );
this->solutions[oxygen_molar_fraction] = sols.at(i);
this->reactant = oxygen_molar_fraction;
std::vector<double> oxy(sols[i].size());
for (unsigned int q=0; q<oxy.size(); ++q)
oxy[q] = sols.at(i)[q] * (this->constant_solutions.at(total_pressure)/this->electrolyte->get_H_O2());
reactant_concentrations.push_back( SolutionVariable(oxy, oxygen_concentration) );
}
else if (sols[i].get_variablename() == hydrogen_molar_fraction)
{
Assert( this->constant_solutions.at(total_pressure) != 0., ExcMessage("Total pressure not initialized in the catalyst layer using set_P method.") );
AssertThrow( this->electrolyte->get_H_H2() != 0, ExcMessage("Henry's constant for hydrogen not initialized in the electrolyte object of the catalyst layer.") );
this->solutions[hydrogen_molar_fraction] = sols.at(i);
this->reactant = hydrogen_molar_fraction;
std::vector<double> hyd(sols[i].size());
for (unsigned int q=0; q<hyd.size(); ++q)
hyd[q] = sols.at(i)[q] * (this->constant_solutions.at(total_pressure)/this->electrolyte->get_H_H2());
reactant_concentrations.push_back( SolutionVariable(hyd, hydrogen_concentration) );
}
}
Assert( reactant_concentrations.size() > 0, ExcMessage("At least one reactant concentration/molar fraction is required in input vector to CatalystLayer::set_solution.") );
this->kinetics->set_reactant_concentrations(reactant_concentrations);
this->n_quad = this->solutions[protonic_electrical_potential].size();
//Check for temperature, initialize if needed be
if (this->solutions.find(temperature_of_REV) == this->solutions.end())
{
Assert( this->constant_solutions.at(temperature_of_REV) != 0., ExcMessage("Temperature not initialized in the catalyst layer using set_T method for isothermal case.") );
this->solutions[temperature_of_REV] = SolutionVariable(this->constant_solutions.at(temperature_of_REV), this->n_quad, temperature_of_REV);
this->kinetics->set_temperature( this->solutions[temperature_of_REV] );
}
//Check for lambda, initialize if needed be
if (this->solutions.find(membrane_water_content) == this->solutions.end())
{
this->solutions[membrane_water_content] = SolutionVariable(12.0, this->n_quad, membrane_water_content);
}
//If anything that was being supplied before is no longer being supplied,
#ifdef DEBUG
std::vector<VariableNames> current_names;
for(unsigned int j =0; j < sols.size(); j++)
current_names.push_back(sols[j].get_variablename());
/*
Assert( std::is_permutation(common_names.begin(), common_names.end(), current_names.begin()), ExcMessage("Inconsistent provision of solutions to catalyst layer from application, "
"be consistent and always provide the same set of solutions"));
common_names = current_names;
*/
#endif
}
//---------------------------------------------------------------------------
template <int dim>
FuelCellShop::SolutionMap
NAME::CatalystLayer<dim>::get_coverages(){
SolutionMap sols;
if(this->kinetics->has_coverage(OH_coverage)){
std::vector<double> OH_c;
this->kinetics->OH_coverage(OH_c);
sols.push_back(SolutionVariable(OH_c, OH_coverage));
}
else
sols.push_back(SolutionVariable(0.0, this->solutions.size(), OH_coverage));
if(this->kinetics->has_coverage(O_coverage)){
std::vector<double> O_c;
this->kinetics->O_coverage(O_c);
sols.push_back(SolutionVariable(O_c, O_coverage));
}
else
sols.push_back(SolutionVariable(0.0, this->solutions.size(), O_coverage));
return sols;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Explicit instantiations.
template class NAME::CatalystLayer<deal_II_dimension>;
| 15,362 | 4,605 |
/*
* Copyright 2007 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/testutils.h"
namespace webrtc {
namespace testing {
StreamSink::StreamSink() = default;
StreamSink::~StreamSink() = default;
StreamSource::StreamSource() {
Clear();
}
StreamSource::~StreamSource() = default;
StreamState StreamSource::GetState() const {
return state_;
}
StreamResult StreamSource::Read(void* buffer,
size_t buffer_len,
size_t* read,
int* error) {
if (SS_CLOSED == state_) {
if (error)
*error = -1;
return SR_ERROR;
}
if ((SS_OPENING == state_) || (readable_data_.size() <= read_block_)) {
return SR_BLOCK;
}
size_t count = std::min(buffer_len, readable_data_.size() - read_block_);
memcpy(buffer, &readable_data_[0], count);
size_t new_size = readable_data_.size() - count;
// Avoid undefined access beyond the last element of the vector.
// This only happens when new_size is 0.
if (count < readable_data_.size()) {
memmove(&readable_data_[0], &readable_data_[count], new_size);
}
readable_data_.resize(new_size);
if (read)
*read = count;
return SR_SUCCESS;
}
StreamResult StreamSource::Write(const void* data,
size_t data_len,
size_t* written,
int* error) {
if (SS_CLOSED == state_) {
if (error)
*error = -1;
return SR_ERROR;
}
if (SS_OPENING == state_) {
return SR_BLOCK;
}
if (SIZE_UNKNOWN != write_block_) {
if (written_data_.size() >= write_block_) {
return SR_BLOCK;
}
if (data_len > (write_block_ - written_data_.size())) {
data_len = write_block_ - written_data_.size();
}
}
if (written)
*written = data_len;
const char* cdata = static_cast<const char*>(data);
written_data_.insert(written_data_.end(), cdata, cdata + data_len);
return SR_SUCCESS;
}
void StreamSource::Close() {
state_ = SS_CLOSED;
}
} // namespace testing
} // namespace webrtc
| 2,437 | 798 |
/**
* @file bksge_core_render_frame_buffer.cpp
*
* @brief FrameBuffer の実装
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#if !defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/inl/frame_buffer_inl.hpp>
#endif
| 243 | 120 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mobile.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_theme_engine.h"
#include "third_party/blink/renderer/core/scroll/scrollbar.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
namespace blink {
static const WebThemeEngine::ScrollbarStyle& ScrollbarStyle() {
static bool initialized = false;
DEFINE_STATIC_LOCAL(WebThemeEngine::ScrollbarStyle, style,
(WebThemeEngine::ScrollbarStyle{3, 4, 0x80808080}));
if (!initialized) {
// During device emulation, the chrome WebThemeEngine implementation may not
// be the mobile theme which can provide the overlay scrollbar styles.
// In the case the following call will do nothing and we'll use the default
// styles specified above.
Platform::Current()->ThemeEngine()->GetOverlayScrollbarStyle(&style);
DCHECK(style.thumb_thickness);
initialized = true;
}
return style;
}
ScrollbarThemeOverlayMobile& ScrollbarThemeOverlayMobile::GetInstance() {
// For unit tests which don't have Platform::Current()->ThemeEngine().
if (MockScrollbarsEnabled()) {
DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, theme, ());
return theme;
}
DEFINE_STATIC_LOCAL(
ScrollbarThemeOverlayMobile, theme,
(ScrollbarStyle().thumb_thickness, ScrollbarStyle().scrollbar_margin,
ScrollbarStyle().color));
return theme;
}
ScrollbarThemeOverlayMobile::ScrollbarThemeOverlayMobile(int thumb_thickness,
int scrollbar_margin,
Color color)
: ScrollbarThemeOverlay(thumb_thickness, scrollbar_margin), color_(color) {}
void ScrollbarThemeOverlayMobile::PaintThumb(GraphicsContext& context,
const Scrollbar& scrollbar,
const IntRect& rect) {
if (!scrollbar.Enabled())
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(context, scrollbar,
DisplayItem::kScrollbarThumb))
return;
DrawingRecorder recorder(context, scrollbar, DisplayItem::kScrollbarThumb);
context.FillRect(rect, color_);
}
} // namespace blink
| 2,691 | 775 |
// keypatterntests.cpp - Tests for the KeyPattern class
//
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/db/keypattern.h"
#include "mongo/dbtests/dbtests.h"
namespace KeyPatternTests {
class ExtendRangeBoundTests {
public:
void run() {
BSONObj bound = BSON( "a" << 55 );
BSONObj longBound = BSON("a" << 55 << "b" << 66);
//test keyPattern shorter than bound, should fail
{
KeyPattern keyPat( BSON( "a" << 1 ) );
ASSERT_THROWS( keyPat.extendRangeBound( longBound, false ), MsgAssertionException );
}
//test keyPattern doesn't match bound, should fail
{
KeyPattern keyPat( BSON( "b" << 1 ) );
ASSERT_THROWS( keyPat.extendRangeBound( bound, false ), MsgAssertionException );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "c" << 1) );
ASSERT_THROWS( keyPat.extendRangeBound( longBound, false ), MsgAssertionException );
}
//test keyPattern same as bound
{
KeyPattern keyPat( BSON( "a" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55) );
}
{
KeyPattern keyPat( BSON( "a" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55) );
}
//test keyPattern longer than bound, simple
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << 1) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MINKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << 1) );
BSONObj newB = keyPat.extendRangeBound( bound, true );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MAXKEY ) );
}
//test keyPattern longer than bound, more complex pattern directions
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MAXKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1) );
BSONObj newB = keyPat.extendRangeBound( bound, true );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MINKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1 << "c" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MAXKEY << "c" << MINKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1 << "c" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, true );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MINKEY << "c" << MAXKEY ) );
}
}
};
class All : public Suite {
public:
All() : Suite( "keypattern" ) {
}
void setupTests() {
add< ExtendRangeBoundTests >();
}
} myall;
} // namespace KeyPatternTests
| 4,881 | 1,487 |
/*
* (C) Copyright 1996- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
// File ThreadPool.cc
// Baudouin Raoult - (c) ECMWF Feb 12
#include "eckit/thread/ThreadPool.h"
#include "eckit/runtime/Monitor.h"
#include "eckit/thread/AutoLock.h"
#include "eckit/thread/Thread.h"
#include "eckit/thread/ThreadControler.h"
//----------------------------------------------------------------------------------------------------------------------
namespace eckit {
//----------------------------------------------------------------------------------------------------------------------
class ThreadPoolThread : public Thread {
ThreadPool& owner_;
void run();
public:
ThreadPoolThread(ThreadPool& owner) :
owner_(owner) {}
};
void ThreadPoolThread::run() {
owner_.notifyStart();
Monitor::instance().name(owner_.name());
// Log::info() << "Start of ThreadPoolThread " << std::endl;
for (;;) {
Monitor::instance().show(false);
Log::status() << "-" << std::endl;
ThreadPoolTask* r = owner_.next();
if (!r)
break;
Monitor::instance().show(true);
r->pool_ = &owner_;
try {
r->execute();
}
catch (std::exception& e) {
Log::error() << "** " << e.what() << " Caught in " << Here() << std::endl;
Log::error() << "** Exception is reported" << std::endl;
owner_.error(e.what());
}
try {
delete r;
}
catch (std::exception& e) {
Log::error() << "** " << e.what() << " Caught in " << Here() << std::endl;
Log::error() << "** Exception is reported" << std::endl;
owner_.error(e.what());
}
owner_.endTask();
}
// Log::info() << "End of ThreadPoolThread " << std::endl;
owner_.notifyEnd();
}
ThreadPool::ThreadPool(const std::string& name, size_t count, size_t stack) :
count_(0), stack_(stack), running_(0), tasks_(0), name_(name), error_(false) {
// Log::info() << "ThreadPool::ThreadPool " << nme_ << " " << count << std::endl;
resize(count);
}
ThreadPool::~ThreadPool() {
// Log::info() << "ThreadPool::~ThreadPool " << name_ << std::endl;
try {
waitForThreads();
}
catch (std::exception& e) {
Log::error() << "** " << e.what() << " Caught in " << Here() << std::endl;
Log::error() << "** Exception is ignored" << std::endl;
}
}
void ThreadPool::waitForThreads() {
for (size_t i = 0; i < count_; i++) {
push(0);
}
AutoLock<MutexCond> lock(done_);
// Log::info() << "ThreadPool::waitForThreads " << name_ << " running: " << running_ << std::endl;
while (running_) {
// Log::info() << "ThreadPool::waitForThreads " << name_ << " running: " << running_ << std::endl;
done_.wait();
}
if (error_) {
error_ = false;
throw SeriousBug(std::string("ThreadPool::waitForThreads: ") + errorMessage_);
}
}
void ThreadPool::notifyStart() {
AutoLock<MutexCond> lock(done_);
running_++;
done_.signal();
// Log::info() << "ThreadPool::notifyStart " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::notifyEnd() {
AutoLock<MutexCond> lock(done_);
running_--;
done_.signal();
// Log::info() << "ThreadPool::notifyEnd " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::startTask() {
AutoLock<MutexCond> lock(active_);
tasks_++;
active_.signal();
// Log::info() << "ThreadPool::notifyStart " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::endTask() {
AutoLock<MutexCond> lock(active_);
tasks_--;
active_.signal();
// Log::info() << "ThreadPool::notifyStart " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::error(const std::string& msg) {
AutoLock<MutexCond> lock(done_);
if (error_)
errorMessage_ += " | ";
error_ = true;
errorMessage_ += msg;
}
void ThreadPool::push(ThreadPoolTask* r) {
if (r) {
startTask();
}
AutoLock<MutexCond> lock(ready_);
queue_.push_back(r);
ready_.signal();
}
void ThreadPool::push(std::list<ThreadPoolTask*>& l) {
AutoLock<MutexCond> lock(ready_);
for (std::list<ThreadPoolTask*>::iterator j = l.begin(); j != l.end(); ++j)
queue_.push_back((*j));
l.clear();
ready_.signal();
}
ThreadPoolTask* ThreadPool::next() {
AutoLock<MutexCond> lock(ready_);
while (queue_.empty())
ready_.wait();
ThreadPoolTask* r = queue_.front();
queue_.pop_front();
if (!queue_.empty())
ready_.signal();
return r;
}
void ThreadPool::wait() {
AutoLock<MutexCond> lock(active_);
while (tasks_) {
active_.wait();
}
}
void ThreadPool::resize(size_t size) {
while (count_ > size) {
push(0);
count_--;
}
while (count_ < size) {
ThreadControler c(new ThreadPoolThread(*this), true, stack_);
c.start();
count_++;
}
}
ThreadPoolTask::~ThreadPoolTask() {}
//----------------------------------------------------------------------------------------------------------------------
} // namespace eckit
| 5,565 | 1,752 |
/*
* urAPI.c
* urMus
*
* Created by Georg Essl on 6/20/09.
* Copyright 2009 Georg Essl. All rights reserved. See LICENSE.txt for license details.
*
*/
#include "urAPI.h"
#include "urGraphics.h"
#include "MachTimer.h"
//TODO//#include "RIOAudioUnitLayer.h"
#include "urSound.h"
#include "httpServer.h"
// Make EAGLview global so lua interface can grab it without breaking a leg over IMP
#ifdef TARGET_IPHONE
extern EAGLView* g_glView;
#endif
// This is to transport error and print messages to EAGLview
extern string errorstr;
extern bool newerror;
// Global lua state
lua_State *lua;
// Region based API below, this is inspired by WoW's frame API with many modifications and expansions.
// Our engine supports paging, region horizontal and vertical scrolling, full multi-touch and more.
// Hardcoded for now... lazy me
#define MAX_PAGES 30
int currentPage;
urAPI_Region_t* firstRegion[MAX_PAGES] = {nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil};
urAPI_Region_t* lastRegion[MAX_PAGES] = {nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil};
int numRegions[MAX_PAGES] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
urAPI_Region_t* UIParent = nil;
ursAPI_FlowBox_t* FBNope = nil;
MachTimer* systimer;
const char DEFAULT_RPOINT[] = "BOTTOMLEFT";
#define STRATA_PARENT 0
#define STRATA_BACKGROUND 1
#define STRATA_LOW 2
#define STRATA_MEDIUM 3
#define STRATA_HIGH 4
#define STRATA_DIALOG 5
#define STRATA_FULLSCREEN 6
#define STRATA_FULLSCREEN_DIALOG 7
#define STRATA_TOOLTIP 8
#define LAYER_BACKGROUND 1
#define LAYER_BORDER 2
#define LAYER_ARTWORK 3
#define LAYER_OVERLAY 4
#define LAYER_HIGHLIGHT 5
urAPI_Region_t* findRegionHit(float x, float y)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage] */; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
return nil;
}
void callAllOnLeaveRegions(float x, float y)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil ; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height
&& t->OnLeave != 0)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
{
t->entered = false;
callScript(t->OnLeave, t);
}
}
}
void callAllOnEnterLeaveRegions(int nr, float* x, float* y, float* ox, float* oy)
{
bool didenter;
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage] */; t=t->prev)
{
for(int i=0; i<nr; i++)
{
if(!(x[i] >= t->left && x[i] <= t->left+t->width &&
y[i] >= t->bottom && y[i] <= t->bottom+t->height) &&
ox[i] >= t->left && ox[i] <= t->left+t->width &&
oy[i] >= t->bottom && oy[i] <= t->bottom+t->height
&& t->OnLeave != 0)
{
// if(t->entered)
// {
t->entered = false;
callScript(t->OnLeave, t);
// }
// else
// {
// int a=0;
// }
}
else if(x[i] >= t->left && x[i] <= t->left+t->width &&
y[i] >= t->bottom && y[i] <= t->bottom+t->height &&
(!(ox[i] >= t->left && ox[i] <= t->left+t->width &&
oy[i] >= t->bottom && oy[i] <= t->bottom+t->height) || !t->entered)
&& t->OnEnter != 0)
{
// didenter = true;
// if(!t->entered)
// {
t->entered = true;
callScript(t->OnEnter, t);
// }
// else
// {
// int a=0;
// }
}
}
// if(t->entered && !didenter)
// {
// t->entered = false;
// callScript(t->OnLeave, t);
// }
// didenter = false;
}
}
urAPI_Region_t* findRegionDraggable(float x, float y)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage]*/; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isMovable && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
return nil;
}
urAPI_Region_t* findRegionXScrolled(float x, float y, float dx)
{
if(fabs(dx) > 0.9)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage]*/; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isScrollXEnabled && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
}
return nil;
}
urAPI_Region_t* findRegionYScrolled(float x, float y, float dy)
{
if(fabs(dy) > 0.9*3)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage]*/; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isScrollYEnabled && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
}
return nil;
}
void layoutchildren(urAPI_Region_t* region)
{
urAPI_Region_t* child = region->firstchild;
while(child!=NULL)
{
child->update = true;
layout(child);
child = child->nextchild;
}
}
bool visibleparent(urAPI_Region_t* region)
{
if(region == UIParent)
return true;
urAPI_Region_t* parent = region->parent;
while(parent != UIParent && parent->isVisible == true)
{
parent = parent->parent;
}
if(parent == UIParent)
return true;
else
return false;
}
void showchildren(urAPI_Region_t* region)
{
urAPI_Region_t* child = region->firstchild;
while(child!=NULL)
{
if(child->isShown)
{
child->isVisible = true;
if(region->OnShow != 0)
callScript(region->OnShow, region);
showchildren(child);
}
child = child->nextchild;
}
}
void hidechildren(urAPI_Region_t* region)
{
urAPI_Region_t* child = region->firstchild;
while(child!=NULL)
{
if(child->isVisible)
{
child->isVisible = false;
if(region->OnHide != 0)
callScript(region->OnHide, region);
hidechildren(child);
}
child = child->nextchild;
}
}
// This function is heavily informed by Jerry's base.lua in wowsim function, which is covered by a BSD-style (open) license.
// (EDIT) Fixed it up. Was buggy as is and didn't properly align for most anchor sides.
bool layout(urAPI_Region_t* region)
{
if(region == nil) return false;
bool update = region->update;
if(!update)
{
if(region->relativeRegion)
update = layout(region->relativeRegion);
else
update = layout(region->parent);
}
if(!update) return false;
float left, right, top, bottom, width, height, cx, cy,x,y;
left = right = top = bottom = width = height = cx = cy = x = y = -1000000;
const char* point = region->point;
if(point == nil)
point = DEFAULT_RPOINT;
urAPI_Region_t* relativeRegion = region->relativeRegion;
if(relativeRegion == nil)
relativeRegion = region->parent;
if(relativeRegion == nil)
relativeRegion = UIParent; // This should be another layer but we don't care for now
const char* relativePoint = region->relativePoint;
if(relativePoint == nil)
relativePoint = DEFAULT_RPOINT;
if(!strcmp(relativePoint, "ALL"))
{
left = relativeRegion->left;
bottom = relativeRegion->bottom;
width = relativeRegion->width;
height = relativeRegion->height;
}
else if(!strcmp(relativePoint,"TOPLEFT"))
{
x = relativeRegion->left;
y = relativeRegion->top;
}
else if(!strcmp(relativePoint,"TOPRIGHT"))
{
x = relativeRegion->right;
y = relativeRegion->top;
}
else if(!strcmp(relativePoint,"TOP"))
{
x = relativeRegion->cx;
y = relativeRegion->top;
}
else if(!strcmp(relativePoint,"LEFT"))
{
x = relativeRegion->left;
y = relativeRegion->cy;
}
else if(!strcmp(relativePoint,"RIGHT"))
{
x = relativeRegion->right;
y = relativeRegion->cy;
}
else if(!strcmp(relativePoint,"CENTER"))
{
x = relativeRegion->cx;
y = relativeRegion->cy;
}
else if(!strcmp(relativePoint,"BOTTOMLEFT"))
{
x = relativeRegion->left;
y = relativeRegion->bottom;
}
else if(!strcmp(relativePoint,"BOTTOMRIGHT"))
{
x = relativeRegion->right;
y = relativeRegion->bottom;
}
else if(!strcmp(relativePoint,"BOTTOM"))
{
x = relativeRegion->cx;
y = relativeRegion->bottom;
}
else
{
// Error!!
luaL_error(lua, "Unknown relativePoint when layouting regions.");
return false;
}
x = x+region->ofsx;
y = y+region->ofsy;
if(!strcmp(point,"TOPLEFT"))
{
left = x;
top = y;
}
else if(!strcmp(point,"TOPRIGHT"))
{
right = x;
top = y;
}
else if(!strcmp(point,"TOP"))
{
cx = x;
top = y;
}
else if(!strcmp(point,"LEFT"))
{
left = x;
cy = y; // Another typo here
}
else if(!strcmp(point,"RIGHT"))
{
right = x;
cy = y;
}
else if(!strcmp(point,"CENTER"))
{
cx = x;
cy = y;
}
else if(!strcmp(point,"BOTTOMLEFT"))
{
left = x;
bottom = y;
}
else if(!strcmp(point,"BOTTOMRIGHT"))
{
right = x;
bottom = y;
}
else if(!strcmp(point,"BOTTOM"))
{
cx = x;
bottom = y;
}
else
{
// Error!!
luaL_error(lua, "Unknown relativePoint when layouting regions.");
return false;
}
if(left > 0 && right > 0)
{
width = right - left;
}
if(top > 0 && bottom > 0)
{
height = top - bottom;
}
if(width == -1000000 && region->width > 0) width = region->width;
if(height == -1000000 && region->height > 0) height = region->height;
if(left == -1000000 && width > 0)
{
if(right>0) left = right - width;
else if(cx>0)
{
left = cx - width/2; // This was buggy. Fixing it up.
right = cx + width/2;
}
}
if(bottom == -1000000 && height > 0)
{
if(top>0) bottom = top - height;
if(cy>0)
{
bottom = cy - height/2; // This was buggy. Fixing it up.
top = cy + height/2;
}
}
update = false;
if(left != region->left || bottom != region->bottom || width != region->width || height != region->height)
update = true;
region->left = left;
region->bottom = bottom;
region->width = width;
region->height = height;
region->cx = left + width/2;
region->cy = bottom + height/2;
top = bottom + height; // All this was missing with bad effects
region->top = top;
right = left + width;
region->right = right;
region->update = false;
if(update)
{
layoutchildren(region);
// callScript("OnSizeChanged", width, height)
}
return update;
}
//------------------------------------------------------------------------------
// Our custom lua API
//------------------------------------------------------------------------------
static urAPI_Region_t *checkregion(lua_State *lua, int nr)
{
// void *region = luaL_checkudata(lua, nr, "URAPI.region");
luaL_checktype(lua, nr, LUA_TTABLE);
lua_rawgeti(lua, nr, 0);
void *region = lua_touserdata(lua, -1);
lua_pop(lua,1);
luaL_argcheck(lua, region!= NULL, nr, "'region' expected");
return (urAPI_Region_t*)region;
}
static urAPI_Texture_t *checktexture(lua_State *lua, int nr)
{
void *texture = luaL_checkudata(lua, nr, "URAPI.texture");
luaL_argcheck(lua, texture!= NULL, nr, "'texture' expected");
return (urAPI_Texture_t*)texture;
}
static urAPI_TextLabel_t *checktextlabel(lua_State *lua, int nr)
{
void *textlabel = luaL_checkudata(lua, nr, "URAPI.textlabel");
luaL_argcheck(lua, textlabel!= NULL, nr, "'textlabel' expected");
return (urAPI_TextLabel_t*)textlabel;
}
static ursAPI_FlowBox_t *checkflowbox(lua_State *lua, int nr)
{
luaL_checktype(lua, nr, LUA_TTABLE);
lua_rawgeti(lua, nr, 0);
void *flowbox = lua_touserdata(lua, -1);
lua_pop(lua,1);
luaL_argcheck(lua, flowbox!= NULL, nr, "'flowbox' expected");
return (ursAPI_FlowBox_t*)flowbox;
}
// NEW!!
static int l_NumRegions(lua_State *lua)
{
lua_pushnumber(lua, numRegions[currentPage]);
return 1;
}
static int l_EnumerateRegions(lua_State *lua)
{
urAPI_Region_t* region;
if(lua_isnil(lua,1))
{
region = UIParent->next;
}
else
{
region = checkregion(lua,1);
if(region!=nil)
region = region->next;
}
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
return 1;
}
// Region events to support
// OnDragStart
// OnDragStop
// OnEnter
// OnEvent
// OnHide
// OnLeave
// OnTouchDown
// OnTouchUp
// OnReceiveDrag (NYI)
// OnShow
// OnSizeChanged
// OnUpdate
// OnDoubleTap (UR!)
bool callAllOnUpdate(float time)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnUpdate != 0)
callScriptWith1Args(t->OnUpdate, t,time);
}
return true;
}
bool callAllOnPageEntered(float page)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnPageEntered != 0)
callScriptWith1Args(t->OnPageEntered, t,page);
}
return true;
}
bool callAllOnPageLeft(float page)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnPageLeft != 0)
callScriptWith1Args(t->OnPageLeft, t,page);
}
return true;
}
bool callAllOnLocation(float latitude, float longitude)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnLocation != 0)
callScriptWith2Args(t->OnLocation,t,latitude, longitude);
}
return true;
}
bool callAllOnHeading(float x, float y, float z, float north)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnHeading != 0)
callScriptWith4Args(t->OnHeading,t,x,y,z,north);
}
return true;
}
bool callAllOnAccelerate(float x, float y, float z)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnAccelerate != 0)
callScriptWith3Args(t->OnAccelerate,t,x,y,z);
}
return true;
}
bool callAllOnNetIn(float a)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnNetIn != 0)
callScriptWith1Args(t->OnNetIn,t,a);
}
return true;
}
bool callAllOnNetConnect(const char* name)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnNetConnect != 0)
callScriptWith1String(t->OnNetConnect,t,name);
}
return true;
}
bool callAllOnNetDisconnect(const char* name)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnNetDisconnect != 0)
callScriptWith1String(t->OnNetDisconnect,t,name);
}
return true;
}
#ifdef SANDWICH_SUPPORT
bool callAllOnPressure(float p)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnPressure != 0)
callScriptWith1Args(t->OnPressure,t,p);
}
return true;
}
#endif
bool callAllOnMicrophone(SInt32* mic_buffer, UInt32 bufferlen)
{
lua_getglobal(lua, "urMicData");
if(lua_isnil(lua, -1) || !lua_istable(lua,-1)) // Channel doesn't exist or is falsely set up
{
lua_pop(lua,1);
return false;
}
for(UInt32 i=0;i<bufferlen; i++)
{
lua_pushnumber(lua, mic_buffer[i]);
lua_rawseti(lua, -2, i+1);
}
lua_setglobal(lua, "urMicData");
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnMicrophone != 0)
callScriptWith1Global(t->OnMicrophone, t, "urMicData");
}
return true;
}
bool callScriptWith4Args(int func_ref, urAPI_Region_t* region, float a, float b, float c, float d)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
lua_pushnumber(lua,b);
lua_pushnumber(lua,c);
lua_pushnumber(lua,d);
if(lua_pcall(lua,5,0,0) != 0)
{
// Error!!
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith3Args(int func_ref, urAPI_Region_t* region, float a, float b, float c)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
lua_pushnumber(lua,b);
lua_pushnumber(lua,c);
if(lua_pcall(lua,4,0,0) != 0)
{
// Error!!
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith2Args(int func_ref, urAPI_Region_t* region, float a, float b)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
lua_pushnumber(lua,b);
if(lua_pcall(lua,3,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith1Args(int func_ref, urAPI_Region_t* region, float a)
{
if(func_ref == 0) return false;
// int func_ref = region->OnDragging;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
if(lua_pcall(lua,2,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith1Global(int func_ref, urAPI_Region_t* region, const char* globaldata)
{
if(func_ref == 0) return false;
// int func_ref = region->OnDragging;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_getglobal(lua, globaldata);
if(lua_pcall(lua,2,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith1String(int func_ref, urAPI_Region_t* region, const char* name)
{
if(func_ref == 0) return false;
// int func_ref = region->OnDragging;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushstring(lua, name);
if(lua_pcall(lua,2,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScript(int func_ref, urAPI_Region_t* region)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
if(lua_pcall(lua,1,0,0) != 0) // find table of udata here!!
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
int region_Handle(lua_State* lua)
{
urAPI_Region_t* region
= checkregion(lua,1);
//get parameter
const char* handler = luaL_checkstring(lua, 2);
if(lua_isnil(lua,3))
{
if(!strcmp(handler, "OnDragStart"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnDragStart);
region->OnDragStart = 0;
}
else if(!strcmp(handler, "OnDragStop"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnDragStop);
region->OnDragStop = 0;
}
else if(!strcmp(handler, "OnEnter"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnEnter);
region->OnEnter = 0;
}
else if(!strcmp(handler, "OnEvent"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnEvent);
region->OnEvent = 0;
}
else if(!strcmp(handler, "OnHide"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnHide);
region->OnHide = 0;
}
else if(!strcmp(handler, "OnLeave"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnLeave);
region->OnLeave = 0;
}
else if(!strcmp(handler, "OnTouchDown"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnTouchDown);
region->OnTouchDown = 0;
}
else if(!strcmp(handler, "OnTouchUp"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnTouchUp);
region->OnTouchUp = 0;
}
else if(!strcmp(handler, "OnShow"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnShow);
region->OnShow = 0;
}
else if(!strcmp(handler, "OnSizeChanged"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnSizeChanged);
region->OnSizeChanged = 0;
}
else if(!strcmp(handler, "OnUpdate"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnUpdate);
region->OnUpdate = 0;
}
else if(!strcmp(handler, "OnDoubleTap"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnDoubleTap);
region->OnDoubleTap = 0;
}
else if(!strcmp(handler, "OnAccelerate"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnAccelerate);
region->OnAccelerate = 0;
}
else if(!strcmp(handler, "OnNetIn"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnNetIn);
region->OnNetIn = 0;
}
else if(!strcmp(handler, "OnNetConnect"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnNetConnect);
region->OnNetConnect = 0;
}
else if(!strcmp(handler, "OnNetDisconnect"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnNetDisconnect);
region->OnNetDisconnect = 0;
}
#ifdef SANDWICH_SUPPORT
else if(!strcmp(handler, "OnPressure"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnPressure);
region->OnPressure = 0;
}
#endif
else if(!strcmp(handler, "OnHeading"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnHeading);
region->OnHeading = 0;
}
else if(!strcmp(handler, "OnLocation"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnLocation);
region->OnLocation = 0;
}
else if(!strcmp(handler, "OnMicrophone"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnMicrophone);
region->OnMicrophone = 0;
}
else if(!strcmp(handler, "OnHorizontalScroll"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnHorizontalScroll);
region->OnHorizontalScroll = 0;
}
else if(!strcmp(handler, "OnVerticalScroll"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnVerticalScroll);
region->OnVerticalScroll = 0;
}
else if(!strcmp(handler, "OnPageEntered"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnPageEntered);
region->OnPageEntered = 0;
}
else if(!strcmp(handler, "OnPageLeft"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnPageLeft);
region->OnPageLeft = 0;
}
else
luaL_error(lua, "Trying to set a script for an unknown event: %s",handler);
return 0; // Error, unknown event
return 1;
}
else
{
luaL_argcheck(lua, lua_isfunction(lua,3), 3, "'function' expected");
if(lua_isfunction(lua,3))
{
/* char* func = (char*)lua_topointer(lua,3);
// <Also get some other info like function name, argument count>
// Load the function to memory
luaL_loadbuffer(lua,func,strlen(func),"LuaFunction");
lua_pop(lua,1);
*/
// Store funtion reference
lua_pushvalue(lua, 3);
int func_ref = luaL_ref(lua, LUA_REGISTRYINDEX);
// OnDragStart
// OnDragStop
// OnEnter
// OnEvent
// OnHide
// OnLeave
// OnTouchDown
// OnTouchUp
// OnReceiveDrag (NYI)
// OnShow
// OnSizeChanged
// OnUpdate
// OnDoubleTap (UR!)
if(!strcmp(handler, "OnDragStart"))
region->OnDragStart = func_ref;
else if(!strcmp(handler, "OnDragStop"))
region->OnDragStop = func_ref;
else if(!strcmp(handler, "OnEnter"))
region->OnEnter = func_ref;
else if(!strcmp(handler, "OnEvent"))
region->OnEvent = func_ref;
else if(!strcmp(handler, "OnHide"))
region->OnHide = func_ref;
else if(!strcmp(handler, "OnLeave"))
region->OnLeave = func_ref;
else if(!strcmp(handler, "OnTouchDown"))
region->OnTouchDown = func_ref;
else if(!strcmp(handler, "OnTouchUp"))
region->OnTouchUp = func_ref;
else if(!strcmp(handler, "OnShow"))
region->OnShow = func_ref;
else if(!strcmp(handler, "OnSizeChanged"))
region->OnSizeChanged = func_ref;
else if(!strcmp(handler, "OnUpdate"))
region->OnUpdate = func_ref;
else if(!strcmp(handler, "OnDoubleTap"))
region->OnDoubleTap = func_ref;
else if(!strcmp(handler, "OnAccelerate"))
region->OnAccelerate = func_ref;
else if(!strcmp(handler, "OnNetIn"))
region->OnNetIn = func_ref;
else if(!strcmp(handler, "OnNetConnect"))
region->OnNetConnect = func_ref;
else if(!strcmp(handler, "OnNetDisconnect"))
region->OnNetDisconnect = func_ref;
#ifdef SANDWICH_SUPPORT
else if(!strcmp(handler, "OnPressure"))
region->OnPressure = func_ref;
#endif
else if(!strcmp(handler, "OnHeading"))
region->OnHeading = func_ref;
else if(!strcmp(handler, "OnLocation"))
region->OnLocation = func_ref;
else if(!strcmp(handler, "OnMicrophone"))
region->OnMicrophone = func_ref;
else if(!strcmp(handler, "OnHorizontalScroll"))
region->OnHorizontalScroll = func_ref;
else if(!strcmp(handler, "OnVerticalScroll"))
region->OnVerticalScroll = func_ref;
else if(!strcmp(handler, "OnPageEntered"))
region->OnPageEntered = func_ref;
else if(!strcmp(handler, "OnPageLeft"))
region->OnPageLeft = func_ref;
else
luaL_unref(lua, LUA_REGISTRYINDEX, func_ref);
// OK!
return 1;
}
return 0;
}
}
int region_SetHeight(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_Number height = luaL_checknumber(lua,2);
region->height=height;
if(region->textlabel!=NULL)
region->textlabel->updatestring = true;
region->update = true;
if(!layout(region)) // Change may not have had a layouting effect on parent, but still could affect children that are anchored to Y
layoutchildren(region);
return 0;
}
int region_SetWidth(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_Number width = luaL_checknumber(lua,2);
region->width=width;
if(region->textlabel!=NULL)
region->textlabel->updatestring = true;
region->update = true;
if(!layout(region)) // Change may not have had a layouting effect on parent, but still could affect children that are anchored to X
layoutchildren(region);
return 0;
}
int region_EnableInput(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enableinput = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isTouchEnabled = enableinput;
return 0;
}
int region_EnableHorizontalScroll(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enablescrollx = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isScrollXEnabled = enablescrollx;
return 0;
}
int region_EnableVerticalScroll(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enablescrolly = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isScrollYEnabled = enablescrolly;
return 0;
}
int region_EnableClipping(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enableclipping = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isClipping = enableclipping;
return 0;
}
int region_SetClipRegion(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
t->clipleft = luaL_checknumber(lua, 2);
t->clipbottom = luaL_checknumber(lua, 3);
t->clipwidth = luaL_checknumber(lua, 4);
t->clipheight = luaL_checknumber(lua, 5);
return 0;
}
int region_ClipRegion(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
lua_pushnumber(lua, t->clipleft);
lua_pushnumber(lua, t->clipbottom);
lua_pushnumber(lua, t->clipwidth);
lua_pushnumber(lua, t->clipheight);
return 4;
}
int region_EnableMoving(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool setmovable = lua_toboolean(lua,2);//!lua_isnil(lua,2);
region->isMovable = setmovable;
return 0;
}
int region_EnableResizing(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool setresizable = lua_toboolean(lua,2);//!lua_isnil(lua,2);
region->isResizable = setresizable;
return 0;
}
void ClampRegion(urAPI_Region_t* region);
int region_SetAnchor(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region==UIParent) return 0;
lua_Number ofsx;
lua_Number ofsy;
urAPI_Region_t* relativeRegion = UIParent;
const char* point = luaL_checkstring(lua, 2);
const char* relativePoint = DEFAULT_RPOINT;
if(lua_isnil(lua,3)) // SetAnchor(point);
{
}
else
{
if(lua_isnumber(lua, 3) && lua_isnumber(lua, 4)) // SetAnchor(point, x,y);
{
ofsx = luaL_checknumber(lua, 3);
ofsy = luaL_checknumber(lua, 4);
}
else
{
if(lua_isstring(lua, 3)) // SetAnchor(point, "relativeRegion")
{
// find parent here
}
else // SetAnchor(point, relativeRegion)
relativeRegion = checkregion(lua, 3);
if(lua_isstring(lua, 4))
relativePoint = luaL_checkstring(lua, 4);
if(lua_isnumber(lua, 5) && lua_isnumber(lua, 6)) // SetAnchor(point, x,y);
{
ofsx = luaL_checknumber(lua, 5);
ofsy = luaL_checknumber(lua, 6);
}
}
}
if(relativeRegion == region)
{
luaL_error(lua, "Cannot anchor a region to itself.");
return 0;
}
if(region->point != NULL)
free(region->point);
region->point = (char*)malloc(strlen(point)+1);
strcpy(region->point, point);
region->relativeRegion = relativeRegion;
if(relativeRegion != region->parent)
{
removeChild(region->parent, region);
region->parent = relativeRegion;
addChild(relativeRegion, region);
}
if(region->relativePoint != NULL)
free(region->relativePoint);
region->relativePoint = (char*)malloc(strlen(relativePoint)+1);
strcpy(region->relativePoint, relativePoint);
region->ofsx = ofsx;
region->ofsy = ofsy;
region->update = true;
layout(region);
if(region->isClamped)
ClampRegion(region);
return true;
}
int region_Show(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
region->isShown = true;
if(visibleparent(region)) // Check visibility change for children
{
region->isVisible = true;
if(region->OnShow != 0)
callScript(region->OnShow, region);
showchildren(region);
}
return 0;
}
int region_Hide(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
region->isVisible = false;
region->isShown = false;
if(region->OnHide != 0)
callScript(region->OnHide, region);
hidechildren(region); // parent got hidden so hide children too.
return 0;
}
const char STRATASTRING_PARENT[] = "PARENT";
const char STRATASTRING_BACKGROUND[] = "BACKGROUND";
const char STRATASTRING_LOW[] = "LOW";
const char STRATASTRING_MEDIUM[] = "MEDIUM";
const char STRATASTRING_HIGH[] = "HIGH";
const char STRATASTRING_DIALOG[] = "DIALOG";
const char STRATASTRING_FULLSCREEN[] = "FULLSCREEN";
const char STRATASTRING_FULLSCREEN_DIALOG[] = "FULLSCREEN_DIALOG";
const char STRATASTRING_TOOLTIP[] = "TOOLTIP";
const char* region_strataindex2str(int strataidx)
{
switch(strataidx)
{
case STRATA_PARENT:
return STRATASTRING_PARENT;
case STRATA_BACKGROUND:
return STRATASTRING_BACKGROUND;
case STRATA_LOW:
return STRATASTRING_LOW;
case STRATA_MEDIUM:
return STRATASTRING_MEDIUM;
case STRATA_HIGH:
return STRATASTRING_HIGH;
case STRATA_FULLSCREEN:
return STRATASTRING_FULLSCREEN;
case STRATA_FULLSCREEN_DIALOG:
return STRATASTRING_FULLSCREEN_DIALOG;
case STRATA_TOOLTIP:
return STRATASTRING_TOOLTIP;
default:
return nil;
}
}
int region_strata2index(const char* strata)
{
if(!strcmp(strata, "PARENT"))
return STRATA_PARENT;
else if(!strcmp(strata, "BACKGROUND"))
return STRATA_BACKGROUND;
else if(!strcmp(strata, "LOW"))
return STRATA_LOW;
else if(!strcmp(strata, "MEDIUM"))
return STRATA_MEDIUM;
else if(!strcmp(strata, "HIGH"))
return STRATA_HIGH;
else if(!strcmp(strata, "DIALOG"))
return STRATA_DIALOG;
else if(!strcmp(strata, "FULLSCREEN"))
return STRATA_FULLSCREEN;
else if(!strcmp(strata, "FULLSCREEN_DIALOG"))
return STRATA_FULLSCREEN_DIALOG;
else if(!strcmp(strata, "TOOLTIP"))
return STRATA_TOOLTIP;
else
{
return -1; // unknown strata
}
}
const char LAYERSTRING_BACKGROUND[] = "BACKGROUND";
const char LAYERSTRING_BORDER[] = "BORDER";
const char LAYERSTRING_ARTWORK[] = "ARTWORK";
const char LAYERSTRING_OVERLAY[] = "OVERLAY";
const char LAYERSTRING_HIGHLIGHT[] = "HIGHLIGHT";
const char* region_layerindex2str(int layeridx)
{
switch(layeridx)
{
case LAYER_BACKGROUND:
return LAYERSTRING_BACKGROUND;
case LAYER_BORDER:
return LAYERSTRING_BORDER;
case LAYER_ARTWORK:
return LAYERSTRING_ARTWORK;
case LAYER_OVERLAY:
return LAYERSTRING_OVERLAY;
case LAYER_HIGHLIGHT:
return LAYERSTRING_HIGHLIGHT;
default:
return nil;
}
}
int region_layer2index(const char* layer)
{
if(!strcmp(layer, "BACKGROUND"))
return LAYER_BACKGROUND;
else if(!strcmp(layer, "BORDER"))
return LAYER_BORDER;
else if(!strcmp(layer, "ARTWORK"))
return LAYER_ARTWORK;
else if(!strcmp(layer, "OVERLAY"))
return LAYER_OVERLAY;
else if(!strcmp(layer, "HIGHLIGHT"))
return LAYER_HIGHLIGHT;
else
{
return -1; // unknown layer
}
}
const char WRAPSTRING_WORD[] = "WORD";
const char WRAPSTRING_CHAR[] = "CHAR";
const char WRAPSTRING_CLIP[] = "CLIP";
const char* textlabel_wrapindex2str(int wrapidx)
{
switch(wrapidx)
{
case WRAP_WORD:
return WRAPSTRING_WORD;
case WRAP_CHAR:
return WRAPSTRING_CHAR;
case WRAP_CLIP:
return WRAPSTRING_CLIP;
default:
return nil;
}
}
int textlabel_wrap2index(const char* wrap)
{
if(!strcmp(wrap, "WORD"))
return WRAP_WORD;
else if(!strcmp(wrap, "CHAR"))
return WRAP_CHAR;
else if(!strcmp(wrap, "CLIP"))
return WRAP_CLIP;
else
{
return -1; // unknown wrap
}
}
void l_SortStrata(urAPI_Region_t* region, int strata)
{
if(region->prev == nil && firstRegion[currentPage] == region) // first region!
{
firstRegion[currentPage] = region->next; // unlink!
firstRegion[currentPage]->prev = nil;
}
else if(region->next == nil && lastRegion[currentPage] == region) // last region!
{
lastRegion[currentPage] = region->prev; // unlink!
lastRegion[currentPage]->next = nil;
}
else if(region->prev != NULL && region->next !=NULL)
{
region->prev->next = region->next; // unlink!
region->next->prev = region->prev;
}
for(urAPI_Region_t* t=firstRegion[currentPage]; t!=NULL; t=t->next)
{
if(t->strata!=STRATA_PARENT) // ignoring PARENT strata regions.
{
if(t->strata > strata) // insert here!
{
if(t == firstRegion[currentPage])
firstRegion[currentPage] = region;
region->prev = t->prev;
if(t->prev != NULL) // Again, may be the first.
t->prev->next = region;
region->next = t; // Link in
t->prev = region; // fix links
region->strata = strata;
// region->prev->next = region;
return; // Done.
}
}
}
if(region!=lastRegion[currentPage])
{
region->prev = lastRegion[currentPage];
region->next = nil;
lastRegion[currentPage]->next = region;
lastRegion[currentPage] = region;
}
else
{
lastRegion[currentPage] = nil;
}
}
void l_setstrataindex(urAPI_Region_t* region , int strataindex)
{
if(strataindex == STRATA_PARENT)
{
region->strata = strataindex;
urAPI_Region_t* p = region->parent;
int newstrataindex = 1;
do
{
if (p->strata != STRATA_PARENT) newstrataindex = p->strata;
p = p->parent;
}
while(p!=NULL && p->strata == 0);
l_SortStrata(region, newstrataindex);
}
if (strataindex > 0 && strataindex != region->strata)
{
region->strata = strataindex;
l_SortStrata(region, strataindex);
}
}
int region_SetLayer(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
const char* strata = luaL_checkstring(lua,2);
if(strata)
{
int strataindex = region_strata2index(strata);
if( region == firstRegion[currentPage] && region == lastRegion[currentPage])
{
// This is a sole region, no need to stratify
}
else
l_setstrataindex(region , strataindex);
region->strata = strataindex;
}
return 0;
}
int region_Parent(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region != nil)
{
region = region->parent;
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
return 1;
}
else
return 0;
}
int region_Children(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
urAPI_Region_t* child = region->firstchild;
int childcount = 0;
while(child!=NULL)
{
childcount++;
lua_rawgeti(lua,LUA_REGISTRYINDEX, child->tableref);
child = child->nextchild;
}
return childcount;
}
int region_Alpha(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->alpha);
return 1;
}
int region_SetAlpha(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_Number alpha = luaL_checknumber(lua,2);
if(alpha > 1.0) alpha = 1.0;
else if(alpha < 0.0) alpha = 0.0;
region->alpha=alpha;
return 0;
}
int region_Name(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushstring(lua, region->name);
return 1;
}
int region_Bottom(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->bottom);
return 1;
}
int region_Center(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->cx);
lua_pushnumber(lua, region->cy);
return 2;
}
int region_Height(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->height);
return 1;
}
int region_Left(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->left);
return 1;
}
int region_Right(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->right);
return 1;
}
int region_Top(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->top);
return 1;
}
int region_Width(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->width);
return 1;
}
int region_NumAnchors(lua_State* lua)
{
// urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, 1); // NYI always 1 point for now
return 1;
}
int region_Anchor(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushstring(lua, region->point);
if(region->relativeRegion)
{
lua_rawgeti(lua, LUA_REGISTRYINDEX, region->relativeRegion->tableref);
}
else
lua_pushnil(lua);
lua_pushstring(lua, region->relativePoint);
lua_pushnumber(lua, region->ofsx);
lua_pushnumber(lua, region->ofsy);
return 5;
}
int region_IsShown(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushboolean(lua, region->isVisible);
return 1;
}
int region_IsVisible(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool visible = false;
if(region->parent!=NULL)
visible = region->isVisible && region->parent->isVisible;
else
visible = region->isVisible;
lua_pushboolean(lua, visible );
return 1;
}
void setParent(urAPI_Region_t* region, urAPI_Region_t* parent)
{
if(region!= NULL && parent!= NULL && region != parent)
{
region->relativeRegion = parent;
removeChild(region->parent, region);
if(parent == UIParent)
region->parent = UIParent;
else
{
region->parent = parent;
addChild(parent, region);
}
}
}
int region_SetParent(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
urAPI_Region_t* parent = checkregion(lua, 2);
setParent(region, parent);
region->update = true;
layout(region);
return 0;
}
int region_Layer(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushstring(lua, region_strataindex2str(region->strata));
return 1;
}
// NEW!!
int region_Lower(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region->prev != nil)
{
urAPI_Region_t* temp = region->prev;
region->prev = temp->prev;
temp->next = region->next;
temp->prev = region;
region->next = temp;
}
return 0;
}
int region_Raise(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region->next != nil)
{
urAPI_Region_t* temp = region->next;
region->next = temp->next;
temp->prev = region->prev;
temp->next = region;
region->prev = temp;
}
return 0;
}
void removeRegion(urAPI_Region_t* region)
{
int currentPage = region->page;
if(firstRegion[currentPage] == region)
firstRegion[currentPage] = region->next;
if(region->prev != NULL)
region->prev->next = region->next;
if(region->next != NULL)
region->next->prev = region->prev;
if(lastRegion[currentPage] == region)
lastRegion[currentPage] = region->prev;
numRegions[currentPage]--;
}
void freeTexture(urAPI_Texture_t* texture)
{
if(texture->backgroundTex!= NULL)
delete texture->backgroundTex;
// free(texture); // GC should take care of this ... maybe
}
void freeTextLabel(urAPI_TextLabel_t* textlabel)
{
if(textlabel->textlabelTex != NULL)
delete textlabel->textlabelTex;
// delete textlabel; // GC should take care of this ... maybe
}
void freeRegion(urAPI_Region_t* region)
{
removeChild(region->parent, region);
removeRegion(region);
if(region->texture != NULL)
freeTexture(region->texture);
if(region->textlabel != NULL)
freeTextLabel(region->textlabel);
delete region;
}
int region_Free(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
freeRegion(region);
}
int l_FreeAllRegions(lua_State* lua)
{
urAPI_Region_t* t=lastRegion[currentPage];
urAPI_Region_t* p;
while(t != nil)
{
t->isVisible = false;
t->isShown = false;
t->isMovable = false;
t->isResizable = false;
t->isTouchEnabled = false;
t->isScrollXEnabled = false;
t->isScrollYEnabled = false;
t->isVisible = false;
t->isShown = false;
t->isDragged = false;
t->isResized = false;
t->isClamped = false;
t->isClipping = false;
p=t->prev;
freeRegion(t);
t = p;
}
return 0;
}
int region_IsToplevel(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool istop = false;
if(region == lastRegion[currentPage])
{
istop = true;
}
lua_pushboolean(lua, istop);
return 1;
}
int region_MoveToTop(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region != lastRegion[currentPage])
{
if(region->prev != nil) // Could be first region!
region->prev->next = region->next; // unlink!
region->next->prev = region->prev;
// and make last
lastRegion[currentPage]->next = region;
region->next = nil;
lastRegion[currentPage] = region;
}
return 0;
}
// ENDNEW!!
void instantiateTexture(urAPI_Region_t* t);
char TEXTURE_SOLID[] = "Solid Texture";
#define GRADIENT_ORIENTATION_VERTICAL 0
#define GRADIENT_ORIENTATION_HORIZONTAL 1
#define GRADIENT_ORIENTATION_DOWNWARD 2
#define GRADIENT_ORIENTATION_UPWARD 3
int region_Texture(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
const char* texturename;
const char* texturelayer;
int texturelayerindex=1;
float r,g,b,a;
r = 255;
g = 255;
b = 255;
a = 255;
if(lua_gettop(lua)<2 || lua_isnil(lua,2)) // this can legitimately be nil.
texturename = nil;
else
{
if(lua_isstring(lua,2) && lua_gettop(lua) <4)
{
texturename = luaL_checkstring(lua,2);
if(lua_gettop(lua)==3 && !lua_isnil(lua,3)) // this should be set.
{
texturelayer = luaL_checkstring(lua,3);
texturelayerindex = region_layer2index(texturelayer);
}
// NYI arg3.. are inheritsFrom regions
}
else if(lua_isnumber(lua,2)) {
texturename = nil;
r = luaL_checknumber(lua, 2);
if(lua_gettop(lua)>2)
{
g = luaL_checknumber(lua,3);
if(lua_gettop(lua)>3)
{
b = luaL_checknumber(lua,4);
a = 255;
if(lua_gettop(lua)>4)
a = luaL_checknumber(lua,5);
}
else
{
g = r;
b = r;
a = g;
}
}
else {
g = r;
b = r;
a = 255;
}
}
}
urAPI_Texture_t* mytexture = (urAPI_Texture_t*)lua_newuserdata(lua, sizeof(urAPI_Texture_t));
mytexture->blendmode = BLEND_DISABLED;
mytexture->texcoords[0] = 0.0;
mytexture->texcoords[1] = 1.0;
mytexture->texcoords[2] = 1.0;
mytexture->texcoords[3] = 1.0;
mytexture->texcoords[4] = 0.0;
mytexture->texcoords[5] = 0.0;
mytexture->texcoords[6] = 1.0;
mytexture->texcoords[7] = 0.0;
if(texturename == NULL)
mytexture->texturepath = TEXTURE_SOLID;
else
{
mytexture->texturepath = (char*)malloc(strlen(texturename)+1);
strcpy(mytexture->texturepath, texturename);
// mytexture->texturepath = texturename;
}
mytexture->modifyRect = false;
mytexture->isDesaturated = false;
mytexture->isTiled = true;
mytexture->fill = false;
// mytexture->gradientOrientation = GRADIENT_ORIENTATION_VERTICAL; OBSOLETE
mytexture->gradientUL[0] = 255; // R
mytexture->gradientUL[1] = 255; // G
mytexture->gradientUL[2] = 255; // B
mytexture->gradientUL[3] = 255; // A
mytexture->gradientUR[0] = 255; // R
mytexture->gradientUR[1] = 255; // G
mytexture->gradientUR[2] = 255; // B
mytexture->gradientUR[3] = 255; // A
mytexture->gradientBL[0] = 255; // R
mytexture->gradientBL[1] = 255; // G
mytexture->gradientBL[2] = 255; // B
mytexture->gradientBL[3] = 255; // A
mytexture->gradientBR[0] = 255; // R
mytexture->gradientBR[1] = 255; // G
mytexture->gradientBR[2] = 255; // B
mytexture->gradientBR[3] = 255; // A
mytexture->texturesolidcolor[0] = r; // R for solid
mytexture->texturesolidcolor[1] = g; // G
mytexture->texturesolidcolor[2] = b; // B
mytexture->texturesolidcolor[3] = a; // A
mytexture->backgroundTex = NULL;
region->texture = mytexture; // HACK
mytexture->region = region;
luaL_getmetatable(lua, "URAPI.texture");
lua_setmetatable(lua, -2);
if(mytexture->backgroundTex == nil && mytexture->texturepath != TEXTURE_SOLID)
{
instantiateTexture(mytexture->region);
}
return 1;
}
char textlabel_empty[] = "";
const char textlabel_defaultfont[] = "Helvetica";
int region_TextLabel(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
const char* texturename;
const char* texturelayer;
int texturelayerindex=1;
if(lua_gettop(lua)<2 || lua_isnil(lua,2)) // this can legitimately be nil.
texturename = nil;
else
if(!lua_isnil(lua,3)) // this should be set.
{
texturelayer = luaL_checkstring(lua,3);
texturelayerindex = region_layer2index(texturelayer);
}
// NYI arg3.. are inheritsFrom regions
urAPI_TextLabel_t* mytextlabel = (urAPI_TextLabel_t*)lua_newuserdata(lua, sizeof(urAPI_TextLabel_t));
region->textlabel = mytextlabel; // HACK
mytextlabel->text = textlabel_empty;
mytextlabel->updatestring = true;
mytextlabel->font = textlabel_defaultfont;
mytextlabel->justifyh = JUSTIFYH_CENTER;
mytextlabel->justifyv = JUSTIFYV_MIDDLE;
mytextlabel->shadowcolor[0] = 0.0;
mytextlabel->shadowcolor[1] = 0.0;
mytextlabel->shadowcolor[2] = 0.0;
mytextlabel->shadowcolor[3] = 128.0;
mytextlabel->shadowoffset[0] = 0.0;
mytextlabel->shadowoffset[1] = 0.0;
mytextlabel->shadowblur = 0.0;
mytextlabel->drawshadow = false;
mytextlabel->linespacing = 2;
mytextlabel->textcolor[0] = 255.0;
mytextlabel->textcolor[1] = 255.0;
mytextlabel->textcolor[2] = 255.0;
mytextlabel->textcolor[3] = 255.0;
mytextlabel->textheight = 12;
mytextlabel->wrap = WRAP_WORD;
mytextlabel->rotation = 0.0;
mytextlabel->textlabelTex = nil;
luaL_getmetatable(lua, "URAPI.textlabel");
lua_setmetatable(lua, -2);
return 1;
}
#include <vector>
#include <string>
static std::vector<std::string> ur_log;
void ur_Log(const char * str) {
ur_log.push_back(str);
}
extern "C" {
char * ur_GetLog(int since, int *nlog);
}
char * ur_GetLog(int since, int *nlog) {
if(since<0) since=0;
std::string str="";
for(int i=since;i<ur_log.size();i++) {
str+=ur_log[i];
str+="\n";
}
char *result=(char *)malloc(str.length()+1);
strcpy(result, str.c_str());
*nlog=ur_log.size();
return result;
}
int l_DPrint(lua_State* lua)
{
const char* str = luaL_checkstring(lua,1);
if(str!=nil)
{
ur_Log(str);
errorstr = str;
newerror = true;
}
return 0;
}
int l_InputFocus(lua_State* lua)
{
// NYI
return 0;
}
int l_HasInput(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
bool isover = false;
float x,y;
// NYI
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height /*&& t->isTouchEnabled*/)
isover = true;
lua_pushboolean(lua, isover);
return 1;
}
extern int SCREEN_WIDTH;
extern int SCREEN_HEIGHT;
int l_ScreenHeight(lua_State* lua)
{
lua_pushnumber(lua, SCREEN_HEIGHT);
return 1;
}
int l_ScreenWidth(lua_State* lua)
{
lua_pushnumber(lua, SCREEN_WIDTH);
return 1;
}
extern float cursorpositionx[MAX_FINGERS];
extern float cursorpositiony[MAX_FINGERS];
// UR: New arg "finger" allows to specify which finger to get position for. nil defaults to 0.
int l_InputPosition(lua_State* lua)
{
int finger = 0;
if(lua_gettop(lua) > 0 && !lua_isnil(lua, 1))
finger = luaL_checknumber(lua, 1);
lua_pushnumber(lua, cursorpositionx[finger]);
lua_pushnumber(lua, SCREEN_HEIGHT-cursorpositiony[finger]);
return 2;
}
int l_Time(lua_State* lua)
{
#ifdef TARGET_IPHONE
lua_pushnumber(lua, [systimer elapsedSec]);
#else
lua_pushnumber(lua, systimer->elapsedSec());
#endif
return 1;
}
int l_RunScript(lua_State* lua)
{
const char* script = luaL_checkstring(lua,1);
if(script != NULL)
luaL_dostring(lua,script);
return 0;
}
int l_StartHTTPServer(lua_State *lua)
{
#ifdef TARGET_IPHONE
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSArray *paths;
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath;
if ([paths count] > 0)
documentPath = [paths objectAtIndex:0];
// start off http server
http_start([resourcePath UTF8String],
[documentPath UTF8String]);
#else
// TODO : use internal storage path
#endif
return 0;
}
int l_StopHTTPServer(lua_State *lua)
{
http_stop();
return 0;
}
int l_HTTPServer(lua_State *lua)
{
const char *ip = http_ip_address();
if (ip) {
lua_pushstring(lua, ip);
lua_pushstring(lua, http_ip_port());
return 2;
} else {
return 0;
}
}
static int audio_initialized = false;
int l_StartAudio(lua_State* lua)
{
#ifdef TARGET_IPHONE
if(!audio_initialized)
{
initializeRIOAudioLayer();
}
else
playRIOAudioLayer();
#else
//TODO// audio stuff
#endif
return 0;
}
int l_PauseAudio(lua_State* lua)
{
#ifdef TARGET_IPHONE
stopRIOAudioLayer();
#else
//TODO// audio stuff
#endif
return 0;
}
static int l_setanimspeed(lua_State *lua)
{
double ds = luaL_checknumber(lua, 1);
#ifdef TARGET_IPHONE
g_glView.animationInterval = ds;
#endif
return 0;
}
int texture_SetTexture(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
if(lua_isnumber(lua,2) && lua_isnumber(lua,3) && lua_isnumber(lua,4))
{
t->texturepath = TEXTURE_SOLID;
t->texturesolidcolor[0] = luaL_checknumber(lua, 2);
t->texturesolidcolor[1] = luaL_checknumber(lua, 3);
t->texturesolidcolor[2] = luaL_checknumber(lua, 4);
if(lua_isnumber(lua, 5))
t->texturesolidcolor[3] = luaL_checknumber(lua, 5);
else
t->texturesolidcolor[3] = 255;
}
else
{
const char* texturename = luaL_checkstring(lua,2);
if(t->texturepath != TEXTURE_SOLID && t->texturepath != NULL)
free(t->texturepath);
t->texturepath = (char*)malloc(strlen(texturename)+1);
strcpy(t->texturepath, texturename);
if(t->backgroundTex != NULL) delete t->backgroundTex; // Antileak
t->backgroundTex = nil;
instantiateTexture(t->region);
}
return 0;
}
int texture_SetGradientColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
const char* orientation = luaL_checkstring(lua, 2);
float minR = luaL_checknumber(lua, 3);
float minG = luaL_checknumber(lua, 4);
float minB = luaL_checknumber(lua, 5);
float minA = luaL_checknumber(lua, 6);
float maxR = luaL_checknumber(lua, 7);
float maxG = luaL_checknumber(lua, 8);
float maxB = luaL_checknumber(lua, 9);
float maxA = luaL_checknumber(lua, 10);
if(!strcmp(orientation, "HORIZONTAL"))
{
t->gradientUL[0] = minR;
t->gradientUL[1] = minG;
t->gradientUL[2] = minB;
t->gradientUL[3] = minA;
t->gradientBL[0] = minR;
t->gradientBL[1] = minG;
t->gradientBL[2] = minB;
t->gradientBL[3] = minA;
t->gradientUR[0] = maxR;
t->gradientUR[1] = maxG;
t->gradientUR[2] = maxB;
t->gradientUR[3] = maxA;
t->gradientBR[0] = maxR;
t->gradientBR[1] = maxG;
t->gradientBR[2] = maxB;
t->gradientBR[3] = maxA;
}
else if(!strcmp(orientation, "VERTICAL"))
{
t->gradientUL[0] = minR;
t->gradientUL[1] = minG;
t->gradientUL[2] = minB;
t->gradientUL[3] = minA;
t->gradientUR[0] = minR;
t->gradientUR[1] = minG;
t->gradientUR[2] = minB;
t->gradientUR[3] = minA;
t->gradientBL[0] = maxR;
t->gradientBL[1] = maxG;
t->gradientBL[2] = maxB;
t->gradientBL[3] = maxA;
t->gradientBR[0] = maxR;
t->gradientBR[1] = maxG;
t->gradientBR[2] = maxB;
t->gradientBR[3] = maxA;
}
else if(!strcmp(orientation, "TOP")) // UR! Allows to set the full gradient in 2 calls.
{
t->gradientUL[0] = minR;
t->gradientUL[1] = minG;
t->gradientUL[2] = minB;
t->gradientUL[3] = minA;
t->gradientUR[0] = maxR;
t->gradientUR[1] = maxG;
t->gradientUR[2] = maxB;
t->gradientUR[3] = maxA;
}
else if(!strcmp(orientation, "BOTTOM")) // UR!
{
t->gradientBL[0] = minR;
t->gradientBL[1] = minG;
t->gradientBL[2] = minB;
t->gradientBL[3] = minA;
t->gradientBR[0] = maxR;
t->gradientBR[1] = maxG;
t->gradientBR[2] = maxB;
t->gradientBR[3] = maxA;
}
return 0;
}
int texture_Texture(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
// NYI still don't know how to return user values
return 0;
}
int texture_SetSolidColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float vertR = luaL_checknumber(lua, 2);
float vertG = luaL_checknumber(lua, 3);
float vertB = luaL_checknumber(lua, 4);
float vertA = 255;
if(lua_gettop(lua)==5)
vertA = luaL_checknumber(lua, 5);
t->texturesolidcolor[0] = vertR;
t->texturesolidcolor[1] = vertG;
t->texturesolidcolor[2] = vertB;
t->texturesolidcolor[3] = vertA;
return 0;
}
int texture_SolidColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->texturesolidcolor[0]);
lua_pushnumber(lua, t->texturesolidcolor[1]);
lua_pushnumber(lua, t->texturesolidcolor[2]);
lua_pushnumber(lua, t->texturesolidcolor[3]);
return 4;
}
int texture_SetTexCoord(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
if(lua_gettop(lua)==5)
{
float left = luaL_checknumber(lua, 2);
float right = luaL_checknumber(lua, 3);
float top = luaL_checknumber(lua, 4);
float bottom = luaL_checknumber(lua, 5);
t->texcoords[0] = left; //ULx
t->texcoords[1] = top; // ULy
t->texcoords[2] = right; // URx
t->texcoords[3] = top; // URy
t->texcoords[4] = left; // BLx
t->texcoords[5] = bottom; // BLy
t->texcoords[6] = right; // BRx
t->texcoords[7] = bottom; // BRy
}
else if(lua_gettop(lua)==9)
{
t->texcoords[0] = luaL_checknumber(lua, 2);
t->texcoords[1] = luaL_checknumber(lua, 3);
t->texcoords[2] = luaL_checknumber(lua, 4);
t->texcoords[3] = luaL_checknumber(lua, 5);
t->texcoords[4] = luaL_checknumber(lua, 6);
t->texcoords[5] = luaL_checknumber(lua, 7);
t->texcoords[6] = luaL_checknumber(lua, 8);
t->texcoords[7] = luaL_checknumber(lua, 9);
}
return 0;
}
int texture_TexCoord(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->texcoords[0]);
lua_pushnumber(lua, t->texcoords[1]);
lua_pushnumber(lua, t->texcoords[2]);
lua_pushnumber(lua, t->texcoords[3]);
lua_pushnumber(lua, t->texcoords[4]);
lua_pushnumber(lua, t->texcoords[5]);
lua_pushnumber(lua, t->texcoords[6]);
lua_pushnumber(lua, t->texcoords[7]);
return 8;
}
int texture_SetRotation(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float angle = luaL_checknumber(lua, 2);
float s = sqrt(2.0)/2.0*sin(angle);
float c = sqrt(2.0)/2.0*cos(angle);
// x = r*math.sin(angle+math.pi/4)
// y = r*math.cos(angle+math.pi/4)
// hand.t:SetTexCoord(.5-x,.5+y, .5+y,.5+x, .5-y,.5-x, .5+x,.5-y)
// r = math.sqrt(2)/2
t->texcoords[0] = 0.5-s;
t->texcoords[1] = 0.5+c;
t->texcoords[2] = 0.5+c;
t->texcoords[3] = 0.5+s;
t->texcoords[4] = 0.5-c;
t->texcoords[5] = 0.5-s;
t->texcoords[6] = 0.5+s;
t->texcoords[7] = 0.5-c;
return 0;
}
int texture_SetTiling(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
t->isTiled = lua_toboolean(lua,2);
return 0;
}
int region_EnableClamping(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool clamped = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isClamped = clamped;
return 0;
}
int region_RegionOverlap(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
urAPI_Region_t* region2 = checkregion(lua,2);
if( region->left < region2->right &&
region2->left < region->right &&
region->bottom < region2->top &&
region2->bottom < region->top)
{
lua_pushboolean(lua, true);
return 1;
}
return 0;
}
int texture_SetTexCoordModifiesRect(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
bool modifyrect = lua_toboolean(lua,2); //!lua_isnil(lua,2);
t->modifyRect = modifyrect;
return 0;
}
int texture_TexCoordModifiesRect(lua_State* lua)
{
urAPI_Texture_t* t= checktexture(lua, 1);
lua_pushboolean(lua, t->modifyRect);
return 1;
}
int texture_SetDesaturated(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
bool isDesaturated = lua_toboolean(lua,2); //!lua_isnil(lua,2);
t->isDesaturated = isDesaturated;
return 0;
}
int texture_IsDesaturated(lua_State* lua)
{
urAPI_Texture_t* t= checktexture(lua, 1);
lua_pushboolean(lua, t->isDesaturated);
return 1;
}
const char BLENDSTR_DISABLED[] = "DISABLED";
const char BLENDSTR_BLEND[] = "BLEND";
const char BLENDSTR_ALPHAKEY[] = "ALPHAKEY";
const char BLENDSTR_ADD[] = "ADD";
const char BLENDSTR_MOD[] = "MOD";
const char BLENDSTR_SUB[] = "SUB";
int texture_SetBlendMode(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
const char* blendmode = luaL_checkstring(lua, 2);
if(!strcmp(blendmode, BLENDSTR_DISABLED))
t->blendmode = BLEND_DISABLED;
else if(!strcmp(blendmode, BLENDSTR_BLEND))
t->blendmode = BLEND_BLEND;
else if(!strcmp(blendmode, BLENDSTR_ALPHAKEY))
t->blendmode = BLEND_ALPHAKEY;
else if(!strcmp(blendmode, BLENDSTR_ADD))
t->blendmode = BLEND_ADD;
else if(!strcmp(blendmode, BLENDSTR_MOD))
t->blendmode = BLEND_MOD;
else if(!strcmp(blendmode, BLENDSTR_SUB))
t->blendmode = BLEND_SUB;
else
{
// NYI unknown blend
}
return 0;
}
int texture_BlendMode(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
const char* returnstr;
switch(t->blendmode)
{
case BLEND_DISABLED:
returnstr = BLENDSTR_DISABLED;
break;
case BLEND_BLEND:
returnstr = BLENDSTR_BLEND;
break;
case BLEND_ALPHAKEY:
returnstr = BLENDSTR_ALPHAKEY;
break;
case BLEND_ADD:
returnstr = BLENDSTR_ADD;
break;
case BLEND_MOD:
returnstr = BLENDSTR_MOD;
break;
case BLEND_SUB:
returnstr = BLENDSTR_SUB;
break;
default:
luaL_error(lua, "Bogus blend mode found! Please report.");
return 0; // Error, unknown event
// returnstr = BLENDSTR_DISABLED; // This should never happen!! Error case NYI
break;
}
lua_pushstring(lua, returnstr);
return 1;
}
void drawLineToTexture(urAPI_Texture_t *texture, float startx, float starty, float endx, float endy);
int texture_Line(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float startx = luaL_checknumber(lua, 2);
float starty = luaL_checknumber(lua, 3);
float endx = luaL_checknumber(lua, 4);
float endy = luaL_checknumber(lua, 5);
if(t->backgroundTex != nil)
drawLineToTexture(t, startx, starty, endx, endy);
return 0;
}
void drawEllipseToTexture(urAPI_Texture_t *texture, float x, float y, float w, float h);
int texture_Ellipse(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x = luaL_checknumber(lua, 2);
float y = luaL_checknumber(lua, 3);
float w = luaL_checknumber(lua, 4);
float h = luaL_checknumber(lua, 5);
if(t->backgroundTex != nil)
drawEllipseToTexture(t, x, y, w, h);
return 0;
}
void drawQuadToTexture(urAPI_Texture_t *texture, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4);
int texture_Quad(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x1 = luaL_checknumber(lua, 2);
float y1 = luaL_checknumber(lua, 3);
float x2 = luaL_checknumber(lua, 4);
float y2 = luaL_checknumber(lua, 5);
float x3 = luaL_checknumber(lua, 6);
float y3 = luaL_checknumber(lua, 7);
float x4 = luaL_checknumber(lua, 8);
float y4 = luaL_checknumber(lua, 9);
if(t->backgroundTex != nil)
drawQuadToTexture(t, x1, y1, x2, y2, x3, y3, x4, y4);
return 0;
}
int texture_Rect(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x = luaL_checknumber(lua, 2);
float y = luaL_checknumber(lua, 3);
float w = luaL_checknumber(lua, 4);
float h = luaL_checknumber(lua, 5);
if(t->backgroundTex != nil)
drawQuadToTexture(t, x, y, x+w, y, x+w, y+h, x, y+h);
return 0;
}
int texture_SetFill(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
bool fill = lua_toboolean(lua,2); //!lua_isnil(lua,2);
t->fill = fill;
return 0;
}
void clearTexture(urTexture* t, float r, float g, float b, float a);
int texture_Clear(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float r = 0.0;
float g = 0.0;
float b = 0.0;
float a = 1.0;
if(lua_gettop(lua)>3)
{
r = luaL_checknumber(lua, 2)/255.0;
g = luaL_checknumber(lua, 3)/255.0;
b = luaL_checknumber(lua, 4)/255.0;
}
if(lua_gettop(lua)==5)
{
a = luaL_checknumber(lua, 5)/255.0;
}
if(t->backgroundTex == nil && t->texturepath != TEXTURE_SOLID)
instantiateTexture(t->region);
if(t->backgroundTex != nil)
clearTexture(t->backgroundTex,r,g,b,a);
return 0;
}
int texture_Width(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->width);
return 1;
}
int texture_Height(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->height);
return 1;
}
void ClearBrushTexture();
int texture_ClearBrush(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
delete t->backgroundTex;
t->backgroundTex = nil;
ClearBrushTexture();
}
void drawPointToTexture(urAPI_Texture_t *texture, float x, float y);
int texture_Point(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x = luaL_checknumber(lua, 2);
float y = luaL_checknumber(lua, 3);
if(t->backgroundTex != nil)
drawPointToTexture(t, x, y);
return 0;
}
void SetBrushSize(float size);
int texture_SetBrushSize(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float size = luaL_checknumber(lua, 2);
SetBrushSize(size);
return 0;
}
int texture_SetBrushColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float vertR = luaL_checknumber(lua, 2);
float vertG = luaL_checknumber(lua, 3);
float vertB = luaL_checknumber(lua, 4);
float vertA = 255;
if(lua_gettop(lua)==5)
vertA = luaL_checknumber(lua, 5);
t->texturebrushcolor[0] = vertR;
t->texturebrushcolor[1] = vertG;
t->texturebrushcolor[2] = vertB;
t->texturebrushcolor[3] = vertA;
return 0;
}
float BrushSize();
int texture_BrushSize(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float size = BrushSize();
lua_pushnumber(lua, size);
return 1;
}
void SetBrushTexture(urTexture* t);
int region_UseAsBrush(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
if(t->texture->backgroundTex == nil && t->texture->texturepath != TEXTURE_SOLID)
instantiateTexture(t);
SetBrushTexture(t->texture->backgroundTex);
return 0;
}
int textlabel_Font(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushstring(lua, t->font);
return 1;
}
int textlabel_SetFont(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->font = luaL_checkstring(lua,2); // NYI
return 0;
}
const char JUSTIFYH_STRING_CENTER[] = "CENTER";
const char JUSTIFYH_STRING_LEFT[] = "LEFT";
const char JUSTIFYH_STRING_RIGHT[] = "RIGHT";
const char JUSTIFYV_STRING_MIDDLE[] = "MIDDLE";
const char JUSTIFYV_STRING_TOP[] = "TOP";
const char JUSTIFYV_STRING_BOTTOM[] = "BOTTOM";
int textlabel_HorizontalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyh;
switch(t->justifyh)
{
case JUSTIFYH_CENTER:
justifyh = JUSTIFYH_STRING_CENTER;
break;
case JUSTIFYH_LEFT:
justifyh = JUSTIFYH_STRING_LEFT;
break;
case JUSTIFYH_RIGHT:
justifyh = JUSTIFYH_STRING_RIGHT;
break;
}
lua_pushstring(lua, justifyh);
return 1;
}
int textlabel_SetHorizontalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyh = luaL_checkstring(lua, 2);
if(!strcmp(justifyh, JUSTIFYH_STRING_CENTER))
t->justifyh = JUSTIFYH_CENTER;
else if(!strcmp(justifyh, JUSTIFYH_STRING_LEFT))
t->justifyh = JUSTIFYH_LEFT;
else if(!strcmp(justifyh, JUSTIFYH_STRING_RIGHT))
t->justifyh = JUSTIFYH_RIGHT;
return 0;
}
int textlabel_VerticalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyv;
switch(t->justifyv)
{
case JUSTIFYV_MIDDLE:
justifyv = JUSTIFYV_STRING_MIDDLE;
break;
case JUSTIFYV_TOP:
justifyv = JUSTIFYV_STRING_TOP;
break;
case JUSTIFYV_BOTTOM:
justifyv = JUSTIFYV_STRING_BOTTOM;
break;
}
lua_pushstring(lua, justifyv);
return 1;
}
int textlabel_SetVerticalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyv = luaL_checkstring(lua, 2);
if(!strcmp(justifyv, JUSTIFYV_STRING_MIDDLE))
t->justifyv = JUSTIFYV_MIDDLE;
else if(!strcmp(justifyv, JUSTIFYV_STRING_TOP))
t->justifyv = JUSTIFYV_TOP;
else if(!strcmp(justifyv, JUSTIFYV_STRING_BOTTOM))
t->justifyv = JUSTIFYV_BOTTOM;
return 0;
}
int textlabel_SetWrap(lua_State* lua)
{
urAPI_TextLabel_t* textlabel = checktextlabel(lua,1);
const char* wrap = luaL_checkstring(lua,2);
if(wrap)
{
textlabel->wrap = textlabel_wrap2index(wrap);
}
return 0;
}
int textlabel_Wrap(lua_State* lua)
{
urAPI_TextLabel_t* textlabel = checktextlabel(lua,1);
lua_pushstring(lua, textlabel_wrapindex2str(textlabel->wrap));
return 1;
}
int textlabel_ShadowColor(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->shadowcolor[0]);
lua_pushnumber(lua, t->shadowcolor[1]);
lua_pushnumber(lua, t->shadowcolor[2]);
lua_pushnumber(lua, t->shadowcolor[3]);
return 4;
}
int textlabel_SetShadowColor(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->shadowcolor[0] = luaL_checknumber(lua,2);
t->shadowcolor[1] = luaL_checknumber(lua,3);
t->shadowcolor[2] = luaL_checknumber(lua,4);
t->shadowcolor[3] = luaL_checknumber(lua,5);
t->drawshadow = true;
t->updatestring = true;
return 0;
}
int textlabel_ShadowOffset(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->shadowoffset[0]);
lua_pushnumber(lua, t->shadowoffset[1]);
return 2;
}
int textlabel_SetShadowOffset(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->shadowoffset[0] = luaL_checknumber(lua,2);
t->shadowoffset[1] = luaL_checknumber(lua,3);
t->updatestring = true;
return 0;
}
int textlabel_ShadowBlur(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->shadowblur);
return 1;
}
int textlabel_SetShadowBlur(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->shadowblur = luaL_checknumber(lua,2);
t->updatestring = true;
return 0;
}
int textlabel_Spacing(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->linespacing);
return 1;
}
int textlabel_SetSpacing(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->linespacing = luaL_checknumber(lua,2);
return 0;
}
int textlabel_Color(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->textcolor[0]);
lua_pushnumber(lua, t->textcolor[1]);
lua_pushnumber(lua, t->textcolor[2]);
lua_pushnumber(lua, t->textcolor[3]);
return 4;
}
int textlabel_SetColor(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->textcolor[0] = luaL_checknumber(lua,2);
t->textcolor[1] = luaL_checknumber(lua,3);
t->textcolor[2] = luaL_checknumber(lua,4);
t->textcolor[3] = luaL_checknumber(lua,5);
return 0;
}
int textlabel_Height(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->stringheight); // NYI
return 1;
}
int textlabel_Width(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->stringwidth); // NYI
return 1;
}
int textlabel_SetLabelHeight(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->textheight = luaL_checknumber(lua,2);
return 0;
}
int textlabel_Label(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushstring(lua, t->text);
return 1;
}
int textlabel_SetLabel(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* text = luaL_checkstring(lua,2);
if(t->text != NULL && t->text != textlabel_empty)
free(t->text);
t->text = (char*)malloc(strlen(text)+1);
strcpy(t->text, text);
t->updatestring = true;
return 0;
}
int textlabel_SetFormattedText(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* text = luaL_checkstring(lua,2);
if(t->text != NULL && t->text != textlabel_empty)
free(t->text);
t->text = (char*)malloc(strlen(text)+1);
strcpy(t->text, text);
// NYI
return 0;
}
int textlabel_SetRotation(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->rotation = luaL_checknumber(lua,2);
return 0;
}
static const struct luaL_reg textlabelfuncs [] =
{
{"Font", textlabel_Font},
{"HorizontalAlign", textlabel_HorizontalAlign},
{"VerticalAlign", textlabel_VerticalAlign},
{"ShadowColor", textlabel_ShadowColor},
{"ShadowOffset", textlabel_ShadowOffset},
{"ShadowBlur", textlabel_ShadowBlur},
{"Spacing", textlabel_Spacing},
{"Color", textlabel_Color},
{"SetFont", textlabel_SetFont},
{"SetHorizontalAlign", textlabel_SetHorizontalAlign},
{"SetVerticalAlign", textlabel_SetVerticalAlign},
{"SetShadowColor", textlabel_SetShadowColor},
{"SetShadowOffset", textlabel_SetShadowOffset},
{"SetShadowBlur", textlabel_SetShadowBlur},
{"SetSpacing", textlabel_SetSpacing},
{"SetColor", textlabel_SetColor},
{"Height", textlabel_Height},
{"Width", textlabel_Width},
{"Label", textlabel_Label},
{"SetFormattedText", textlabel_SetFormattedText},
{"SetWrap", textlabel_SetWrap},
{"Wrap", textlabel_Wrap},
{"SetLabel", textlabel_SetLabel},
{"SetLabelHeight", textlabel_SetLabelHeight},
{"SetRotation", textlabel_SetRotation},
{NULL, NULL}
};
int texture_gc(lua_State* lua)
{
urAPI_Texture_t* region = checktexture(lua,1);
int a = 0;
return 0;
}
static const struct luaL_reg texturefuncs [] =
{
{"SetTexture", texture_SetTexture},
// {"SetGradient", texture_SetGradient},
{"SetGradientColor", texture_SetGradientColor},
{"Texture", texture_Texture},
{"SetSolidColor", texture_SetSolidColor},
{"SolidColor", texture_SolidColor},
{"SetTexCoord", texture_SetTexCoord},
{"TexCoord", texture_TexCoord},
{"SetRotation", texture_SetRotation},
{"SetTexCoordModifiesRect", texture_SetTexCoordModifiesRect},
{"TexCoordModifiesRect", texture_TexCoordModifiesRect},
{"SetDesaturated", texture_SetDesaturated},
{"IsDesaturated", texture_IsDesaturated},
{"SetBlendMode", texture_SetBlendMode},
{"BlendMode", texture_BlendMode},
{"Line", texture_Line},
{"Point", texture_Point},
{"Ellipse", texture_Ellipse},
{"Quad", texture_Quad},
{"Rect", texture_Rect},
{"Clear", texture_Clear},
{"ClearBrush", texture_ClearBrush},
{"SetFill", texture_SetFill},
{"SetBrushSize", texture_SetBrushSize},
{"BrushSize", texture_BrushSize},
{"SetBrushColor", texture_SetBrushColor},
{"SetTiling", texture_SetTiling},
{"Width", texture_Width},
{"Height", texture_Height},
// {"__gc", texture_gc},
{NULL, NULL}
};
int region_gc(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
int a = 0;
return 0;
}
static const struct luaL_reg regionfuncs [] =
{
{"EnableMoving", region_EnableMoving},
{"EnableResizing", region_EnableResizing},
{"Handle", region_Handle},
{"SetHeight", region_SetHeight},
{"SetWidth", region_SetWidth},
{"Show", region_Show},
{"Hide", region_Hide},
{"EnableInput", region_EnableInput},
{"EnableHorizontalScroll", region_EnableHorizontalScroll},
{"EnableVerticalScroll", region_EnableVerticalScroll},
{"SetAnchor", region_SetAnchor},
{"SetLayer", region_SetLayer},
{"Parent", region_Parent},
{"Children", region_Children},
{"Name", region_Name},
{"Bottom", region_Bottom},
{"Center", region_Center},
{"Height", region_Height},
{"Left", region_Left},
{"NumAnchors", region_NumAnchors},
{"Anchor", region_Anchor},
{"Right", region_Right},
{"Top", region_Top},
{"Width", region_Width},
{"IsShown", region_IsShown},
{"IsVisible", region_IsVisible},
{"SetParent", region_SetParent},
{"SetAlpha", region_SetAlpha},
{"Alpha", region_Alpha},
{"Layer", region_Layer},
{"Texture", region_Texture},
{"TextLabel", region_TextLabel},
// NEW!!
{"Lower", region_Lower},
{"Raise", region_Raise},
{"IsToplevel", region_IsToplevel},
{"MoveToTop", region_MoveToTop},
{"EnableClamping", region_EnableClamping},
// ENDNEW!!
{"RegionOverlap", region_RegionOverlap},
{"UseAsBrush", region_UseAsBrush},
{"EnableClipping", region_EnableClipping},
{"SetClipRegion", region_SetClipRegion},
{"ClipRegion", region_ClipRegion},
{"__gc", region_gc},
{NULL, NULL}
};
static const luaL_reg regionmetas[] = {
{"__gc", region_gc},
{0, 0}
};
void addChild(urAPI_Region_t *parent, urAPI_Region_t *child)
{
if(parent->firstchild == NULL)
parent->firstchild = child;
else
{
urAPI_Region_t *findlast = parent->firstchild;
while(findlast->nextchild != NULL)
{
findlast = findlast->nextchild;
}
if(findlast->nextchild != child)
findlast->nextchild = child;
}
}
void removeChild(urAPI_Region_t *parent, urAPI_Region_t *child)
{
if(parent->firstchild != NULL)
{
if(parent->firstchild == child)
{
parent->firstchild = parent->firstchild->nextchild;
}
else
{
urAPI_Region_t *findlast = parent->firstchild;
while(findlast->nextchild != NULL && findlast->nextchild != child)
{
findlast = findlast->nextchild;
}
if(findlast->nextchild == child)
{
findlast->nextchild = findlast->nextchild->nextchild;
child->nextchild = NULL;
}
else
{
int a = 0;
}
}
}
}
static int l_Region(lua_State *lua)
{
const char *regiontype = NULL;
const char *regionName = NULL;
urAPI_Region_t *parentRegion = NULL;
if(lua_gettop(lua)>0) // Allow for no arg construction
{
regiontype = luaL_checkstring(lua, 1);
regionName = luaL_checkstring(lua, 2);
// urAPI_Region_t *parentRegion = (urAPI_Region_t*)luaL_checkudata(lua, 4, "URAPI.region");
luaL_checktype(lua, 3, LUA_TTABLE);
lua_rawgeti(lua, 3, 0);
parentRegion = (urAPI_Region_t*)lua_touserdata(lua,4);
luaL_argcheck(lua, parentRegion!= NULL, 4, "'region' expected");
// const char *inheritsRegion = luaL_checkstring(lua, 1); //NYI
}
else
{
parentRegion = UIParent;
}
// NEW!! Return region in a table at index 0
lua_newtable(lua);
luaL_register(lua, NULL, regionfuncs);
// urAPI_Region_t *myregion = (urAPI_Region_t*)lua_newuserdata(lua, sizeof(urAPI_Region_t)); // User data is our value
urAPI_Region_t *myregion = (urAPI_Region_t*)malloc(sizeof(urAPI_Region_t)); // User data is our value
lua_pushlightuserdata(lua, myregion);
// luaL_register(lua, NULL, regionmetas);
// luaL_openlib(lua, 0, regionmetas, 0); /* fill metatable */
lua_rawseti(lua, -2, 0); // Set this to index 0
myregion->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myregion->tableref);
lua_pushliteral(lua, "__gc"); /* mutex destructor */
lua_pushcfunction(lua, region_gc);
lua_rawset(lua, -3);
// ENDNEW!!
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myregion->next = nil;
myregion->parent = parentRegion;
myregion->firstchild = NULL;
myregion->nextchild = NULL;
// addChild(parentRegion, myregion);
// myregion->name = regionName; // NYI
// Link it into the global region list
myregion->name = regionName;
myregion->type = regiontype;
myregion->ofsx = 0.0;
myregion->ofsy = 0.0;
myregion->width = 160.0;
myregion->height = 160.0;
myregion->bottom = 1.0;
myregion->left = 1.0;
myregion->top = myregion->bottom + myregion->height;
myregion->right = myregion->left + myregion->width;
myregion->cx = 80.0;
myregion->cy = 80.0;
myregion->ofsx = 0.0;
myregion->ofsy = 0.0;
myregion->clipleft = 0.0;
myregion->clipbottom = 0.0;
myregion->clipwidth = SCREEN_WIDTH;
myregion->clipheight = SCREEN_HEIGHT;
myregion->alpha = 1.0;
myregion->isMovable = false;
myregion->isResizable = false;
myregion->isTouchEnabled = false;
myregion->isScrollXEnabled = false;
myregion->isScrollYEnabled = false;
myregion->isVisible = false;
myregion->isDragged = false;
myregion->isClamped = false;
myregion->isClipping = false;
myregion->entered = false;
myregion->strata = STRATA_PARENT;
myregion->OnDragStart = 0;
myregion->OnDragStop = 0;
myregion->OnEnter = 0;
myregion->OnEvent = 0;
myregion->OnHide = 0;
myregion->OnLeave = 0;
myregion->OnTouchDown = 0;
myregion->OnTouchUp = 0;
myregion->OnShow = 0;
myregion->OnShow = 0;
myregion->OnSizeChanged = 0; // needs args (NYI)
myregion->OnUpdate = 0;
myregion->OnDoubleTap = 0; // (UR!)
// All UR!
myregion->OnAccelerate = 0;
myregion->OnNetIn = 0;
myregion->OnNetConnect = 0;
myregion->OnNetDisconnect = 0;
#ifdef SANDWICH_SUPPORT
myregion->OnPressure = 0;
#endif
myregion->OnHeading = 0;
myregion->OnLocation = 0;
myregion->OnMicrophone = 0;
myregion->OnHorizontalScroll = 0;
myregion->OnVerticalScroll = 0;
myregion->OnPageEntered = 0;
myregion->OnPageLeft = 0;
myregion->texture = NULL;
myregion->textlabel = NULL;
myregion->point = NULL;
myregion->relativePoint = NULL;
myregion->relativeRegion = NULL;
myregion->page = currentPage;
if(firstRegion[currentPage] == nil) // first region ever
{
firstRegion[currentPage] = myregion;
lastRegion[currentPage] = myregion;
myregion->next = NULL;
myregion->prev = NULL;
}
else
{
myregion->prev = lastRegion[currentPage];
lastRegion[currentPage]->next = myregion;
lastRegion[currentPage] = myregion;
l_setstrataindex(myregion , myregion->strata);
}
// NEW!!
numRegions[currentPage] ++;
// ENDNEW!!
setParent(myregion, parentRegion);
return 1;
}
int flowbox_Name(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushstring(lua, fb->object->name);
return 1;
}
// Object to to PushOut from.
// In to PushOut into.
// Needs ID on specific IN
int flowbox_SetPushLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int outindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int inindex = luaL_checknumber(lua, 4);
if(outindex >= fb->object->nr_outs || inindex >= target->object->nr_ins)
{
return 0;
}
fb->object->AddPushOut(outindex, &target->object->ins[inindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_SetPullLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int inindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int outindex = luaL_checknumber(lua, 4);
if(inindex >= fb->object->nr_ins || outindex >= target->object->nr_outs)
{
return 0;
}
fb->object->AddPullIn(inindex, &target->object->outs[outindex]);
if(!strcmp(fb->object->name,dacobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveDacTickSinkList.AddSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,visobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveVisTickSinkList.AddSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,netobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveNetTickSinkList.AddSink(&target->object->outs[outindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_IsPushed(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int outindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int inindex = luaL_checknumber(lua, 4);
if(outindex >= fb->object->nr_outs || inindex >= target->object->nr_ins)
{
return 0;
}
if(fb->object->IsPushedOut(outindex, &target->object->ins[inindex]))
{
lua_pushboolean(lua,1);
return 1;
}
else
return 0;
}
int flowbox_IsPulled(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int inindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int outindex = luaL_checknumber(lua, 4);
if(inindex >= fb->object->nr_ins || outindex >= target->object->nr_outs)
{
return 0;
}
if(fb->object->IsPulledIn(inindex, &target->object->outs[outindex]))
{
lua_pushboolean(lua, 1);
return 1;
}
else
return 0;
}
int flowbox_RemovePushLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int outindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int inindex = luaL_checknumber(lua, 4);
if(outindex >= fb->object->nr_outs || inindex >= target->object->nr_ins)
{
return 0;
}
fb->object->RemovePushOut(outindex, &target->object->ins[inindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_RemovePullLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int inindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int outindex = luaL_checknumber(lua, 4);
if(inindex >= fb->object->nr_ins || outindex >= target->object->nr_outs)
{
return 0;
}
fb->object->RemovePullIn(inindex, &target->object->outs[outindex]);
if(!strcmp(fb->object->name,dacobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveDacTickSinkList.RemoveSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,visobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveVisTickSinkList.RemoveSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,netobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveNetTickSinkList.RemoveSink(&target->object->outs[outindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_IsPushing(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int index = luaL_checknumber(lua,2);
lua_pushboolean(lua, fb->object->firstpullin[index]!=NULL);
return 1;
}
int flowbox_IsPulling(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int index = luaL_checknumber(lua,2);
lua_pushboolean(lua, fb->object->firstpushout[index]!=NULL);
return 1;
}
int flowbox_IsPlaced(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int index = luaL_checknumber(lua,2);
lua_pushboolean(lua, fb->object->ins[index].isplaced);
return 1;
}
int flowbox_NumIns(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->nr_ins);
return 1;
}
int flowbox_NumOuts(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->nr_outs);
return 1;
}
int flowbox_Ins(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int nrins = fb->object->lastin;
for(int j=0; j< nrins; j++)
// if(fb->object->ins[j].name!=(void*)0x1)
lua_pushstring(lua, fb->object->ins[j].name);
// else {
// int a=2;
// }
return nrins;
}
int flowbox_Outs(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int nrouts = fb->object->lastout;
for(int j=0; j< nrouts; j++)
lua_pushstring(lua, fb->object->outs[j].name);
return nrouts;
}
int flowbox_Push(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
float indata = luaL_checknumber(lua, 2);
fb->object->CallAllPushOuts(indata);
/* if(fb->object->firstpushout[0]!=NULL)
{
ursObject* inobject;
urSoundPushOut* pushto = fb->object->firstpushout[0];
for(;pushto!=NULL; pushto = pushto->next)
{
urSoundIn* in = pushto->in;
inobject = in->object;
in->inFuncTick(inobject, indata);
}
}*/
// callAllPushSources(indata);
return 0;
}
int flowbox_Pull(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
float indata = luaL_checknumber(lua, 2);
fb->object->CallAllPushOuts(indata);
return 0;
}
extern double visoutdata;
int flowbox_Get(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
// float indata = luaL_checknumber(lua, 2);
lua_pushnumber(lua, visoutdata);
return 1;
}
int flowbox_AddFile(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
const char* filename = luaL_checkstring(lua, 2);
if(!strcmp(fb->object->name, "Sample"))
{
Sample_AddFile(fb->object, filename);
}
}
int flowbox_IsInstantiable(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushboolean(lua, !fb->object->noninstantiable);
return 1;
}
int flowbox_InstanceNumber(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->instancenumber);
return 1;
}
int flowbox_NumberInstances(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->instancelist->Last());
return 1;
}
int flowbox_Couple(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
if(fb->object->iscoupled)
{
lua_pushnumber(lua, fb->object->couple_in);
lua_pushnumber(lua, fb->object->couple_out);
return 2;
}
else
return 0;
}
int flowbox_IsCoupled(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushboolean(lua, fb->object->iscoupled);
return 1;
}
// Methods table for the flowbox API
static const struct luaL_reg flowboxfuncs [] =
{
{"Name", flowbox_Name},
{"NumIns", flowbox_NumIns},
{"NumOuts", flowbox_NumOuts},
{"Ins", flowbox_Ins},
{"Outs", flowbox_Outs},
{"SetPushLink", flowbox_SetPushLink},
{"SetPullLink", flowbox_SetPullLink},
{"RemovePushLink", flowbox_RemovePushLink},
{"RemovePullLink", flowbox_RemovePullLink},
{"IsPushed", flowbox_IsPushed},
{"IsPulled", flowbox_IsPulled},
{"Push", flowbox_Push},
{"Pull", flowbox_Pull},
{"Get", flowbox_Get},
{"AddFile", flowbox_AddFile},
{"IsInstantiable", flowbox_IsInstantiable},
{"InstanceNumber", flowbox_InstanceNumber},
{"NumberInstances", flowbox_NumberInstances},
{"Couple", flowbox_Couple},
{"IsCoupled", flowbox_IsCoupled},
{NULL, NULL}
};
static int l_FlowBox(lua_State* lua)
{
const char *flowboxtype = luaL_checkstring(lua, 1);
const char *flowboxName = luaL_checkstring(lua, 2);
// urAPI_flowbox_t *parentflowbox = (urAPI_flowbox_t*)luaL_checkudata(lua, 4, "URAPI.flowbox");
luaL_checktype(lua, 3, LUA_TTABLE);
lua_rawgeti(lua, 3, 0);
ursAPI_FlowBox_t *parentFlowBox = (ursAPI_FlowBox_t*)lua_touserdata(lua,4);
luaL_argcheck(lua, parentFlowBox!= NULL, 4, "'flowbox' expected");
// const char *inheritsflowbox = luaL_checkstring(lua, 1); //NYI
// NEW!! Return flowbox in a table at index 0
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
myflowbox->object = parentFlowBox->object->Clone();
// myflowbox->object->instancenumber = parentFlowBox->object->instancenumber + 1;
// ENDNEW!!
// luaL_getmetatable(lua, "URAPI.flowbox");
// lua_setmetatable(lua, -2);
return 1;
}
void ur_GetSoundBuffer(SInt32* buffer, int channel, int size)
{
lua_getglobal(lua,"urSoundData");
lua_rawgeti(lua, -1, channel);
if(lua_isnil(lua, -1) || !lua_istable(lua,-1)) // Channel doesn't exist or is falsely set up
{
lua_pop(lua,1);
return;
}
for(int i=0; i<size; i++)
{
lua_rawgeti(lua, -1, i+1);
if(lua_isnumber(lua, -1))
buffer[i] = lua_tonumber(lua, -1);
lua_pop(lua,1);
}
lua_pop(lua, 2);
}
int l_SourceNames(lua_State *lua)
{
int nr = urs_NumUrSourceObjects();
for(int i=0; i<nr; i++)
{
lua_pushstring(lua, urs_GetSourceObjectName(i));
}
return nr;
}
int l_ManipulatorNames(lua_State *lua)
{
int nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
lua_pushstring(lua, urs_GetManipulatorObjectName(i));
}
return nr;
}
int l_SinkNames(lua_State *lua)
{
int nr = urs_NumUrSinkObjects();
for(int i=0; i<nr; i++)
{
lua_pushstring(lua, urs_GetSinkObjectName(i));
}
return nr;
}
#ifdef ALLOW_DEFUNCT
int l_NumUrIns(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrManipulatorIns(i));
return 1;
}
}
nr = urs_NumUrSinkObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSinkObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrSinkIns(i));
return 1;
}
}
return 0;
}
int l_NumUrOuts(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrSourceObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSourceObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrSourceOuts(i));
return 1;
}
}
nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrManipulatorOuts(i));
return 1;
}
}
return 0;
}
int l_GetUrIns(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
int nrins = urs_NumUrManipulatorIns(i);
for(int j=0; j< nrins; j++)
lua_pushstring(lua, urs_GetManipulatorIn(i, j));
return nrins;
}
}
nr = urs_NumUrSinkObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSinkObjectName(i)))
{
int nrins = urs_NumUrSinkIns(i);
for(int j=0; j< nrins; j++)
lua_pushstring(lua, urs_GetSinkIn(i, j));
return nrins;
}
}
return 0;
}
int l_GetUrOuts(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrSourceObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSourceObjectName(i)))
{
int nrouts = urs_NumUrSourceOuts(i);
for(int j=0; j< nrouts; j++)
lua_pushstring(lua, urs_GetSourceOut(i, j));
return nrouts;
}
}
nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
int nrouts = urs_NumUrManipulatorOuts(i);
for(int j=0; j< nrouts; j++)
lua_pushstring(lua, urs_GetManipulatorOut(i, j));
return nrouts;
}
}
return 0;
}
#endif
int l_SystemPath(lua_State *lua)
{
#ifdef TARGET_IPHONE
const char* filename = luaL_checkstring(lua,1);
NSString *filename2 = [[NSString alloc] initWithCString:filename];
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:filename2];
const char* filestr = [filePath UTF8String];
lua_pushstring(lua, filestr);
#else
// TODO // find system path
#endif
return 1;
}
int l_DocumentPath(lua_State *lua)
{
#ifdef TARGET_IPHONE
const char* filename = luaL_checkstring(lua,1);
NSString *filename2 = [[NSString alloc] initWithCString:filename];
NSArray *paths;
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0) {
NSString *filePath = [paths objectAtIndex:0];
NSString *resultPath = [NSString stringWithFormat:@"%@/%@", filePath, filename2];
const char* filestr = [resultPath UTF8String];
lua_pushstring(lua, filestr);
}
else
{
luaL_error(lua, "Cannot find the Document path.");
}
#else
// TODO // find document path
#endif
return 1;
}
int l_NumMaxPages(lua_State *lua)
{
int max = MAX_PAGES;
lua_pushnumber(lua, max);
return 1;
}
int l_Page(lua_State *lua)
{
lua_pushnumber(lua, currentPage+1);
return 1;
}
int l_SetPage(lua_State *lua)
{
int oldcurrent;
int num = luaL_checknumber(lua,1);
if(num >= 1 and num <= MAX_PAGES)
{
callAllOnPageLeft(num-1);
oldcurrent = currentPage;
currentPage = num-1;
callAllOnPageEntered(oldcurrent);
}
else
{
// Error!!
luaL_error(lua, "Invalid page number: %d",num);
}
return 0;
}
//------------------------------------------------------------------------------
// Register our API
//------------------------------------------------------------------------------
void l_setupAPI(lua_State *lua)
{
#ifdef TARGET_IPHONE
CGRect screendimensions = [[UIScreen mainScreen] bounds];
SCREEN_WIDTH = screendimensions.size.width;
SCREEN_HEIGHT = screendimensions.size.height;
#else
// for android, SCREEN_WIDTH and SCREEN_HEIGHT are set up in urMus.init(int,int) native function
#endif
// Set global userdata
// Create UIParent
// luaL_newmetatable(lua, "URAPI.region");
// lua_pushstring(lua, "__index");
// lua_pushvalue(lua, -2);
// lua_settable(lua, -3);
// luaL_openlib(lua, NULL, regionfuncs, 0);
lua_newtable(lua);
luaL_register(lua, NULL, regionfuncs);
// urAPI_Region_t *myregion = (urAPI_Region_t*)lua_newuserdata(lua, sizeof(urAPI_Region_t)); // User data is our value
urAPI_Region_t *myregion = (urAPI_Region_t*)malloc(sizeof(urAPI_Region_t)); // User data is our value
lua_pushlightuserdata(lua, myregion);
lua_rawseti(lua, -2, 0); // Set this to index 0
myregion->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myregion->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myregion->strata = STRATA_BACKGROUND;
myregion->parent = NULL;
myregion->top = SCREEN_HEIGHT;
myregion->bottom = 0;
myregion->left = 0;
myregion->right = SCREEN_WIDTH;
myregion->cx = SCREEN_WIDTH/2;
myregion->cy = SCREEN_HEIGHT/2;
myregion->firstchild = NULL;
myregion->point = NULL;
myregion->relativePoint = NULL;
UIParent = myregion;
lua_setglobal(lua, "UIParent");
urs_SetupObjects();
char fbname[255];
for(int source=0; source<ursourceobjectlist.Last(); source++)
{
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myflowbox->object = ursourceobjectlist[source];
FBNope = myflowbox;
strcpy(fbname, "FB");
strcat(fbname, myflowbox->object->name);
lua_setglobal(lua, fbname);
}
for(int manipulator=0; manipulator<urmanipulatorobjectlist.Last(); manipulator++)
{
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myflowbox->object = urmanipulatorobjectlist[manipulator];
FBNope = myflowbox;
strcpy(fbname, "FB");
strcat(fbname, myflowbox->object->name);
lua_setglobal(lua, fbname);
}
for(int sink=0; sink<ursinkobjectlist.Last(); sink++)
{
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myflowbox->object = ursinkobjectlist[sink];
FBNope = myflowbox;
strcpy(fbname, "FB");
strcat(fbname, myflowbox->object->name);
lua_setglobal(lua, fbname);
}
luaL_newmetatable(lua, "URAPI.texture");
lua_pushstring(lua, "__index");
lua_pushvalue(lua, -2);
lua_settable(lua, -3);
// luaL_openlib(lua, NULL, texturefuncs, 0);
luaL_register(lua, NULL, texturefuncs);
luaL_newmetatable(lua, "URAPI.textlabel");
lua_pushstring(lua, "__index");
lua_pushvalue(lua, -2);
lua_settable(lua, -3);
// luaL_openlib(lua, NULL, textlabelfuncs, 0);
luaL_register(lua, NULL, textlabelfuncs);
// Compats
lua_pushcfunction(lua, l_Region);
lua_setglobal(lua, "Region");
// NEW!!
lua_pushcfunction(lua, l_NumRegions);
lua_setglobal(lua, "NumRegions");
// ENDNEW!!
lua_pushcfunction(lua, l_InputFocus);
lua_setglobal(lua, "InputFocus");
lua_pushcfunction(lua, l_HasInput);
lua_setglobal(lua, "HasInput");
lua_pushcfunction(lua, l_InputPosition);
lua_setglobal(lua, "InputPosition");
lua_pushcfunction(lua, l_ScreenHeight);
lua_setglobal(lua, "ScreenHeight");
lua_pushcfunction(lua, l_ScreenWidth);
lua_setglobal(lua, "ScreenWidth");
lua_pushcfunction(lua, l_Time);
lua_setglobal(lua, "Time");
lua_pushcfunction(lua, l_RunScript);
lua_setglobal(lua, "RunScript");
lua_pushcfunction(lua,l_StartAudio);
lua_setglobal(lua,"StartAudio");
lua_pushcfunction(lua,l_PauseAudio);
lua_setglobal(lua,"PauseAudio");
// HTTP
lua_pushcfunction(lua,l_StartHTTPServer);
lua_setglobal(lua,"StartHTTPServer");
lua_pushcfunction(lua,l_StopHTTPServer);
lua_setglobal(lua,"StopHTTPServer");
lua_pushcfunction(lua,l_HTTPServer);
lua_setglobal(lua,"HTTPServer");
// UR!
lua_pushcfunction(lua, l_setanimspeed);
lua_setglobal(lua, "SetFrameRate");
lua_pushcfunction(lua, l_DPrint);
lua_setglobal(lua, "DPrint");
// URSound!
lua_pushcfunction(lua, l_SourceNames);
lua_setglobal(lua, "SourceNames");
lua_pushcfunction(lua, l_ManipulatorNames);
lua_setglobal(lua, "ManipulatorNames");
lua_pushcfunction(lua, l_SinkNames);
lua_setglobal(lua, "SinkNames");
#ifdef ALLOW_DEFUNCT
lua_pushcfunction(lua, l_NumUrIns);
lua_setglobal(lua, "NumUrIns");
lua_pushcfunction(lua, l_NumUrOuts);
lua_setglobal(lua, "NumUrOuts");
lua_pushcfunction(lua, l_GetUrIns);
lua_setglobal(lua, "GetUrIns");
lua_pushcfunction(lua, l_GetUrOuts);
lua_setglobal(lua, "GetUrOuts");
#endif
lua_pushcfunction(lua, l_FlowBox);
lua_setglobal(lua, "FlowBox");
lua_pushcfunction(lua, l_SystemPath);
lua_setglobal(lua, "SystemPath");
lua_pushcfunction(lua, l_DocumentPath);
lua_setglobal(lua, "DocumentPath");
lua_pushcfunction(lua, l_NumMaxPages);
lua_setglobal(lua, "NumMaxPages");
lua_pushcfunction(lua, l_Page);
lua_setglobal(lua, "Page");
lua_pushcfunction(lua, l_SetPage);
lua_setglobal(lua, "SetPage");
lua_pushcfunction(lua, l_FreeAllRegions);
lua_setglobal(lua, "FreeAllRegions");
// Initialize the global mic buffer table
#ifdef MIC_ARRAY
lua_newtable(lua);
lua_setglobal(lua, "urMicData");
#endif
#ifdef SOUND_ARRAY
// NOTE: SOMETHING IS WEIRD HERE. CAUSES VARIOUS BUGS IF ONE WRITES TO THIS TABLE
lua_newtable(lua);
lua_newtable(lua);
lua_rawseti(lua, -2, 1); // Setting up for stereo for now
lua_newtable(lua);
lua_rawseti(lua, -2, 2); // Can be extended to any number of channels here
lua_setglobal(lua,"urSoundData");
#endif
#ifdef TARGET_IPHONE
systimer = [MachTimer alloc];
[systimer start];
#else
systimer = new MachTimer();
systimer->start();
#endif
}
| 99,824 | 43,197 |
/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <map>
#include "config.h"
#include "generator_helpers.h"
#include "node_generator.h"
#include "node_generator_helpers.h"
using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;
namespace grpc_node_generator {
namespace {
// Returns the alias we assign to the module of the given .proto filename
// when importing. Copied entirely from
// github:google/protobuf/src/google/protobuf/compiler/js/js_generator.cc#L154
grpc::string ModuleAlias(const grpc::string filename) {
// This scheme could technically cause problems if a file includes any 2 of:
// foo/bar_baz.proto
// foo_bar_baz.proto
// foo_bar/baz.proto
//
// We'll worry about this problem if/when we actually see it. This name isn't
// exposed to users so we can change it later if we need to.
grpc::string basename = grpc_generator::StripProto(filename);
basename = grpc_generator::StringReplace(basename, "-", "$");
basename = grpc_generator::StringReplace(basename, "/", "_");
basename = grpc_generator::StringReplace(basename, ".", "_");
return basename + "_pb";
}
// Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
// message file foo/bar/baz.js
grpc::string GetJSMessageFilename(const grpc::string& filename) {
grpc::string name = filename;
return grpc_generator::StripProto(name) + "_pb.js";
}
// Given a filename like foo/bar/baz.proto, returns the root directory
// path ../../
grpc::string GetRootPath(const grpc::string& from_filename,
const grpc::string& to_filename) {
if (to_filename.find("google/protobuf") == 0) {
// Well-known types (.proto files in the google/protobuf directory) are
// assumed to come from the 'google-protobuf' npm package. We may want to
// generalize this exception later by letting others put generated code in
// their own npm packages.
return "google-protobuf/";
}
size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
if (slashes == 0) {
return "./";
}
grpc::string result = "";
for (size_t i = 0; i < slashes; i++) {
result += "../";
}
return result;
}
// Return the relative path to load to_file from the directory containing
// from_file, assuming that both paths are relative to the same directory
grpc::string GetRelativePath(const grpc::string& from_file,
const grpc::string& to_file) {
return GetRootPath(from_file, to_file) + to_file;
}
/* Finds all message types used in all services in the file, and returns them
* as a map of fully qualified message type name to message descriptor */
map<grpc::string, const Descriptor*> GetAllMessages(
const FileDescriptor* file) {
map<grpc::string, const Descriptor*> message_types;
for (int service_num = 0; service_num < file->service_count();
service_num++) {
const ServiceDescriptor* service = file->service(service_num);
for (int method_num = 0; method_num < service->method_count();
method_num++) {
const MethodDescriptor* method = service->method(method_num);
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
message_types[input_type->full_name()] = input_type;
message_types[output_type->full_name()] = output_type;
}
}
return message_types;
}
grpc::string MessageIdentifierName(const grpc::string& name) {
return grpc_generator::StringReplace(name, ".", "_");
}
grpc::string NodeObjectPath(const Descriptor* descriptor) {
grpc::string module_alias = ModuleAlias(descriptor->file()->name());
grpc::string name = descriptor->full_name();
grpc_generator::StripPrefix(&name, descriptor->file()->package() + ".");
return module_alias + "." + name;
}
// Prints out the message serializer and deserializer functions
void PrintMessageTransformer(const Descriptor* descriptor, Printer* out) {
map<grpc::string, grpc::string> template_vars;
grpc::string full_name = descriptor->full_name();
template_vars["identifier_name"] = MessageIdentifierName(full_name);
template_vars["name"] = full_name;
template_vars["node_name"] = NodeObjectPath(descriptor);
// Print the serializer
out->Print(template_vars, "function serialize_$identifier_name$(arg) {\n");
out->Indent();
out->Print(template_vars, "if (!(arg instanceof $node_name$)) {\n");
out->Indent();
out->Print(template_vars,
"throw new Error('Expected argument of type $name$');\n");
out->Outdent();
out->Print("}\n");
out->Print("return Buffer.from(arg.serializeBinary());\n");
out->Outdent();
out->Print("}\n\n");
// Print the deserializer
out->Print(template_vars,
"function deserialize_$identifier_name$(buffer_arg) {\n");
out->Indent();
out->Print(
template_vars,
"return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\n");
out->Outdent();
out->Print("}\n\n");
}
void PrintMethod(const MethodDescriptor* method, Printer* out) {
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
map<grpc::string, grpc::string> vars;
vars["service_name"] = method->service()->full_name();
vars["name"] = method->name();
vars["input_type"] = NodeObjectPath(input_type);
vars["input_type_id"] = MessageIdentifierName(input_type->full_name());
vars["output_type"] = NodeObjectPath(output_type);
vars["output_type_id"] = MessageIdentifierName(output_type->full_name());
vars["client_stream"] = method->client_streaming() ? "true" : "false";
vars["server_stream"] = method->server_streaming() ? "true" : "false";
out->Print("{\n");
out->Indent();
out->Print(vars, "path: '/$service_name$/$name$',\n");
out->Print(vars, "requestStream: $client_stream$,\n");
out->Print(vars, "responseStream: $server_stream$,\n");
out->Print(vars, "requestType: $input_type$,\n");
out->Print(vars, "responseType: $output_type$,\n");
out->Print(vars, "requestSerialize: serialize_$input_type_id$,\n");
out->Print(vars, "requestDeserialize: deserialize_$input_type_id$,\n");
out->Print(vars, "responseSerialize: serialize_$output_type_id$,\n");
out->Print(vars, "responseDeserialize: deserialize_$output_type_id$,\n");
out->Outdent();
out->Print("}");
}
// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service, Printer* out,
const Parameters& params) {
map<grpc::string, grpc::string> template_vars;
out->PrintRaw(GetNodeComments(service, true).c_str());
template_vars["name"] = service->name();
template_vars["full_name"] = service->full_name();
if (params.generate_package_definition) {
out->Print(template_vars, "var $name$Service = exports['$full_name$'] = {\n");
} else {
out->Print(template_vars, "var $name$Service = exports.$name$Service = {\n");
}
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
grpc::string method_name =
grpc_generator::LowercaseFirstLetter(service->method(i)->name());
out->PrintRaw(GetNodeComments(service->method(i), true).c_str());
out->Print("$method_name$: ", "method_name", method_name);
PrintMethod(service->method(i), out);
out->Print(",\n");
out->PrintRaw(GetNodeComments(service->method(i), false).c_str());
}
out->Outdent();
out->Print("};\n\n");
if (!params.generate_package_definition) {
out->Print(template_vars,
"exports.$name$Client = "
"grpc.makeGenericClientConstructor($name$Service);\n");
}
out->PrintRaw(GetNodeComments(service, false).c_str());
}
void PrintImports(const FileDescriptor* file, Printer* out,
const Parameters& params) {
if (!params.generate_package_definition) {
grpc::string package = params.grpc_js ? "@grpc/grpc-js" : "grpc";
out->Print("var grpc = require('$package$');\n", "package", package);
}
if (file->message_type_count() > 0) {
grpc::string file_path =
GetRelativePath(file->name(), GetJSMessageFilename(file->name()));
out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
ModuleAlias(file->name()), "file_path", file_path);
}
for (int i = 0; i < file->dependency_count(); i++) {
grpc::string file_path = GetRelativePath(
file->name(), GetJSMessageFilename(file->dependency(i)->name()));
out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
ModuleAlias(file->dependency(i)->name()), "file_path",
file_path);
}
out->Print("\n");
}
void PrintTransformers(const FileDescriptor* file, Printer* out) {
map<grpc::string, const Descriptor*> messages = GetAllMessages(file);
for (std::map<grpc::string, const Descriptor*>::iterator it =
messages.begin();
it != messages.end(); it++) {
PrintMessageTransformer(it->second, out);
}
out->Print("\n");
}
void PrintServices(const FileDescriptor* file, Printer* out,
const Parameters& params) {
for (int i = 0; i < file->service_count(); i++) {
PrintService(file->service(i), out, params);
}
}
} // namespace
grpc::string GenerateFile(const FileDescriptor* file,
const Parameters& params) {
grpc::string output;
{
StringOutputStream output_stream(&output);
Printer out(&output_stream, '$');
if (file->service_count() == 0) {
output = "// GENERATED CODE -- NO SERVICES IN PROTO";
return output;
}
out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
grpc::string leading_comments = GetNodeComments(file, true);
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
out.PrintRaw(leading_comments.c_str());
}
out.Print("'use strict';\n");
PrintImports(file, &out, params);
PrintTransformers(file, &out);
PrintServices(file, &out, params);
out.PrintRaw(GetNodeComments(file, false).c_str());
}
return output;
}
} // namespace grpc_node_generator
| 10,817 | 3,431 |
#include "glew.h"
#include "freeglut.h"
#include "glm.hpp"
#include "Path.h"
#include "Renderer\RenderableManager.h"
#include "Renderer\Camera.h"
#include "Renderer\ShaderLoader.h"
#include "Renderer\WindowManager.h"
#include "Game\InputManager.h"
#include "Game\GameManager.h"
#include <iostream>
#include <vector>
extern void SetupOpenGLWindow(int argc, char** argv);
extern void OnKeyboardInput(unsigned char key, int x, int y);
extern void OnMouseInput(int button, int state, int x, int y);
extern void OnRender();
extern void SetupScene();
extern void OnClose();
extern void OnTick(int timerId);
Game::GameManager* gameManager;
int main(int argc, char** argv)
{
SetupOpenGLWindow( argc, argv );
return 0;
}
void SetupOpenGLWindow(int argc, char** argv)
{
const int windowWidth = 1600;
const int windowHeight = 800;
const float aspectRatio = (float)windowHeight / windowWidth;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
Renderer::WindowManager::Create();
Renderer::WindowManager::Instance().InitialiseWindow(glm::vec2(100, 100), glm::vec2(windowWidth, windowHeight));
glewInit();
if (glewIsSupported("GL_VERSION_4_5"))
{
std::cout << "GLEW Version 4.5 is supported." << std::endl;
}
else
{
std::cout << "ERROR - GLEW 4.5 Not Supported" << std::endl;
int temp;
std::cin >> temp;
return;
}
glEnable(GL_DEPTH_TEST);
glutKeyboardFunc(OnKeyboardInput);
glutMouseFunc(OnMouseInput);
glutDisplayFunc(OnRender);
glutCloseFunc(OnClose);
glutTimerFunc(1, OnTick, 0);
Renderer::RenderableManager::Create();
Renderer::Camera::Create();
Renderer::Camera::Instance().Scale = glm::vec3(aspectRatio, 1.0f, 1.0f);
gameManager = new Game::GameManager();
glutMainLoop();
}
void OnKeyboardInput(unsigned char key, int x, int y)
{
Game::InputManager::Instance().OnKeyboardInput(key);
}
void OnMouseInput(int button, int state, int x, int y)
{
Game::InputManager::Instance().OnMouseInput(button, state, x, y);
}
void OnUpdate(float dt)
{
gameManager->OnUpdate( dt );
}
void OnRender()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
Renderer::RenderableManager::Instance().Render();
gameManager->OnRender();
glutSwapBuffers();
}
void OnTick(int timerId)
{
OnUpdate(1.0f/60.0f);
OnRender();
glutTimerFunc(1000 / 60, OnTick, 0);
}
void OnClose()
{
glutLeaveMainLoop();
delete gameManager;
Renderer::RenderableManager::Destroy();
Renderer::Camera::Destroy();
Renderer::ShaderLoader::DestroyAllShaders();
} | 2,552 | 1,002 |
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2019-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 <array>
#include <unordered_map>
#include <cstdint>
#include <cstddef>
#include <iostream>
#include <mutex>
#include "consensus.pb.h"
#include "group_signature_manager.hpp"
#include "messages.hpp"
namespace fetch {
namespace consensus {
/**
* This class implemnents defines the functions required for the DKG
*/
template<class CryptoType, class CryptoVerificationKey>
class BaseDkg {
public:
using PrivateKey = typename CryptoType::PrivateKey;
using Signature = typename CryptoType::Signature;
using GroupPublicKey = typename CryptoType::GroupPublicKey;
using VerificationKey = CryptoVerificationKey;
using MessagePayload = std::string;
struct DkgOutput {
GroupPublicKey groupPublicKey;
std::vector<VerificationKey> publicKeyShares;
PrivateKey privateKey;
DkgOutput(GroupPublicKey groupPublicKey1, std::vector<VerificationKey> publicKeyShares1,
const PrivateKey &privateKey1)
: groupPublicKey{std::move(groupPublicKey1)}, publicKeyShares{std::move(publicKeyShares1)},
privateKey{privateKey1} {}
};
BaseDkg(uint32_t committeeSize, uint32_t threshold) : committeeSize_{committeeSize}, polynomialDegree_{threshold - 1},
groupSignatureManager_{threshold} {
static bool once = []() {
CryptoType::initCrypto();
return true;
}();
CryptoType::setGenerators(this->G, this->H);
if (!once) {
std::cerr << "Node::initPairing failed.\n"; // just to eliminate warnings from the compiler.
}
this->publicKeyShares_.resize(this->committeeSize_);
init(this->C_ik_, this->committeeSize_, this->polynomialDegree_ + 1);
init(this->A_ik_, this->committeeSize_, this->polynomialDegree_ + 1);
init(this->s_ij_, this->committeeSize_, this->committeeSize_);
init(this->sprime_ij_, this->committeeSize_, this->committeeSize_);
init(this->g__s_ij_, this->committeeSize_, this->committeeSize_);
}
virtual ~BaseDkg() = default;
virtual std::pair<fetch::consensus::pb::Broadcast, std::vector<fetch::consensus::pb::PrivateShares>>
createCoefficientsAndShares(uint32_t rank) = 0;
virtual void computeQualCoefficient(fetch::consensus::pb::Broadcast_Coefficients &coefs, uint32_t rank) = 0;
virtual bool setQualCoefficient(uint32_t from, uint32_t i, const std::string &coef) = 0;
virtual bool verifyQualCoefficient(uint32_t rank, uint32_t i) const = 0;
virtual std::pair<bool, bool> verifyQualComplaint(uint32_t nodeIndex, uint32_t fromIndex, const std::string &first,
const std::string &second) = 0;
virtual bool runReconstruction(const std::unordered_map<std::string, uint32_t> &nodesMap) = 0;
virtual void
computePublicKeys(const std::set<std::string> &qual, const std::unordered_map<std::string, uint32_t> &nodesMap) = 0;
virtual SignaturesShare getSignatureShare(const MessagePayload &message, uint32_t rank) = 0;
virtual bool
addSignatureShare(const fetch::consensus::pb::Gossip_SignatureShare &share_msg, uint32_t miner_index) = 0;
/**
* Adds new shares from another DKG member
*
* @param from Index of the sender
* @param rank Our index
* @param shares The private shares message received from the sender
* @return bool indicating whether the shares deserialised correctly
*/
bool setShare(uint32_t from, uint32_t rank, const fetch::consensus::pb::PrivateShares &shares) {
return s_ij_[from][rank].assign(shares.first()) && sprime_ij_[from][rank].assign(shares.second());
}
/**
* Add new coeffcients
*
* @param from Index of the sender
* @param i Index in vector of coefficients
* @param coef Value of coefficient vector at index i as string
* @return bool indicating whether coefficient deserialised correctly
*/
bool setCoefficient(uint32_t from, uint32_t i, const std::string &coef) {
if (C_ik_[from][i].isZero()) {
return C_ik_[from][i].assign(coef);
}
return false;
}
/**
* Checks coefficients broadcasted by cabinet member c_i is consistent with the secret shares
* received from c_i. If false then add to complaints
*
* @return Set of muddle addresses of nodes we complain against
*/
std::set<std::string> computeComplaints(const std::set<std::string> &miners, uint32_t rank) {
std::set<std::string> complaints_local;
uint32_t i = 0;
for (auto &miner : miners) {
if (i != rank) {
if (!C_ik_[i][0].isZero() && !s_ij_[i][rank].isZero()) {
VerificationKey rhs, lhs;
lhs = computeLHS(g__s_ij_[i][rank], G, H, s_ij_[i][rank], sprime_ij_[i][rank]);
rhs = computeRHS(rank, C_ik_[i]);
if (lhs != rhs)
complaints_local.insert(miner);
} else {
complaints_local.insert(miner);
}
}
++i;
}
return complaints_local;
}
/**
* Broadcast private shares after processing complaints
*
* @param shares Shares msg to be broadcasted
* @param reporter String id of the complaint filer
* @param from Owner of original shares
* @param to Recipient of original shares
*/
void broadcastShare(fetch::consensus::pb::Broadcast_Shares &shares, const std::string &reporter,
uint32_t from, uint32_t to) const {
shares.add_first(s_ij_[from][to].toString());
shares.add_second(sprime_ij_[from][to].toString());
shares.add_reporter(reporter);
}
/**
* Verify private shares received
*
* @param reporterIndex Index of member filing complaint
* @param fromIndex Index of the sender of the shares
* @param rank Our index
* @param first First share as string
* @param second Second share as string
* @return bool for whether the shares pass verification with broadcasted coefficients
*/
bool verifyShare(uint32_t reporterIndex, uint32_t fromIndex, uint32_t rank, const std::string &first,
const std::string &second) {
PrivateKey s, sprime;
VerificationKey lhsG, rhsG;
if (s.assign(first) && sprime.assign(second)) {
rhsG = computeRHS(reporterIndex, C_ik_[fromIndex]);
lhsG = computeLHS(G, H, s, sprime);
if (lhsG == rhsG) {
if (reporterIndex == rank) {
s_ij_[fromIndex][rank] = s;
sprime_ij_[fromIndex][rank] = sprime;
g__s_ij_[fromIndex][rank].setZero();
g__s_ij_[fromIndex][rank].mult(G, s_ij_[fromIndex][rank]);
}
return true;
}
return false;
}
return false;
}
/**
* Compute own private key
*
* @param rank Our index
* @param quals Indices of qualified members
*/
void computePrivateKey(uint32_t rank, const std::vector<uint32_t> &quals) {
std::lock_guard<std::mutex> lock(mutex_);
privateKey_.setZero();
xprime_i_.setZero();
for (auto &iq_index : quals) {
privateKey_.add(privateKey_, s_ij_[iq_index][rank]);
xprime_i_.add(xprime_i_, sprime_ij_[iq_index][rank]);
}
}
/**
* Inserting reconstruction shares
*
* @param id String id of member being reconstructed
* @param index Index of member being reconstructed
* @param rank Our index
*/
void newReconstructionShare(const std::string &id, uint32_t index, uint32_t rank) {
std::lock_guard<std::mutex> lock(mutex_);
if (reconstructionShares_.find(id) == reconstructionShares_.end()) {
reconstructionShares_.insert({id, {{}, std::vector<PrivateKey>(committeeSize_)}});
}
reconstructionShares_.at(id).first.insert(rank);
reconstructionShares_.at(id).second[rank] = s_ij_[index][rank];
}
/**
* Verify reconstruction shares received
*
* @param nodeIndex Index of node who is being reconstructed
* @param fromIndex Index of the sender of the shares
* @param reporter Index of the person filing complaint
* @param first First secret share as string
* @param second Second secret share as string
*/
void verifyReconstructionShare(uint32_t nodeIndex, uint32_t fromIndex, const std::string &reporter,
const std::string &first,
const std::string &second) {
std::lock_guard<std::mutex> lock(mutex_);
VerificationKey lhs, rhs;
PrivateKey s, sprime;
if (s.assign(first) and sprime.assign(second)) {
lhs = computeLHS(G, H, s, sprime);
rhs = computeRHS(fromIndex, C_ik_[nodeIndex]);
bool check = lhs == rhs;
if (check) {
if (reconstructionShares_.find(reporter) == reconstructionShares_.end()) {
reconstructionShares_.insert(
{reporter, {{}, std::vector<PrivateKey>(committeeSize_)}});
} else if (reconstructionShares_.at(reporter).second[fromIndex].isZero()) {
return;
}
reconstructionShares_.at(reporter).first.insert(fromIndex); // good share received
reconstructionShares_.at(reporter).second[fromIndex] = s;
}
}
}
std::string computeGroupSignature(const MessagePayload &message) {
std::lock_guard<std::mutex> lock(mutex_);
assert(groupSignatureManager_.numSignatureShares(message) > polynomialDegree_);
Signature sig{lagrangeInterpolation(groupSignatureManager_.signatureShares(message))};
groupSignatureManager_.addSignedMessage(message, sig);
return sig.toString();
}
void setDkgOutput(const DkgOutput &output) {
std::lock_guard<std::mutex> lock(mutex_);
groupPublicKey_ = output.groupPublicKey;
privateKey_ = output.privateKey;
for (size_t i = 0; i < publicKeyShares_.size(); i++) {
publicKeyShares_[i] = output.publicKeyShares[i];
}
}
/// Getter functions
/// @{
std::string groupPublicKey() const {
if (groupPublicKey_.isZero()) {
return "";
}
return groupPublicKey_.toString();
}
std::vector<std::string> publicKeyShares() const {
std::vector<std::string> public_key_shares;
for (uint32_t i = 0; i < committeeSize_; ++i) {
assert(!publicKeyShares_[i].isZero());
public_key_shares.push_back(publicKeyShares_[i].toString());
assert(!public_key_shares[i].empty());
}
return public_key_shares;
}
/// @}
/// Threshold Signing Methods
/// @{
std::string groupSignature(const MessagePayload &message) const {
return groupSignatureManager_.groupSignature(message);
}
bool groupSignatureCompleted(const MessagePayload &message) const {
return groupSignatureManager_.signatureCompleted(message);
}
size_t numSignatureShares(const MessagePayload &message) const {
return groupSignatureManager_.numSignatureShares(message);
}
bool isFinished(const MessagePayload &message) const {
return groupSignatureManager_.numSignatureShares(message) > polynomialDegree_;
}
/// @}
static void initCrypto() {
CryptoType::initCrypto();
}
template<class Generator>
static void setGenerator(Generator &generator) {
CryptoType::setGenerator(generator);
}
template<class Generator>
static void setGenerators(Generator &generator1, Generator &generator2) {
CryptoType::setGenerators(generator1, generator2);
}
/**
* Computes signature share of a message
*
* @param message Message to be signed
* @param privateKey Secret key share
* @return Signature share
*/
static Signature sign(const MessagePayload &message, const PrivateKey &privateKey) {
Signature PH;
Signature sign;
PH.hashAndMap(message);
sign.mult(PH, privateKey);
return sign;
}
/**
* Computes the group signature using the indices and signature shares of threshold_ + 1
* parties
*
* @param shares Unordered map of indices and their corresponding signature shares
* @return Group signature
*/
static Signature lagrangeInterpolation(const std::unordered_map<uint32_t, typename CryptoType::Signature> &shares) {
assert(!shares.empty());
if (shares.size() == 1) {
return shares.begin()->second;
}
Signature res;
PrivateKey a{1};
for (auto &p : shares) {
a.mult(a, typename CryptoType::PrivateKey{uint32_t(p.first + 1)});
}
for (auto &p1 : shares) {
typename CryptoType::PrivateKey b{uint32_t(p1.first + 1)};
for (auto &p2 : shares) {
if (p2.first != p1.first) {
typename CryptoType::PrivateKey local_share1{uint32_t(p1.first)}, local_share2{uint32_t(p2.first)};
local_share2.sub(local_share2, local_share1);
b.mult(b, local_share2);
}
}
b.inv(b);
b.mult(a, b);
typename CryptoType::Signature t;
t.mult(p1.second, b);
res.add(res, t);
}
return res;
}
/**
* Generates the group public key, public key shares and private key share for a number of
* parties and a given signature threshold. Nodes must be allocated the outputs according
* to their index in the cabinet.
*
* @param committeeSize Number of parties for which private key shares are generated
* @param threshold Number of parties required to generate a group signature
* @return Vector of DkgOutputs containing the data to be given to each party
*/
static std::vector<DkgOutput> trustedDealer(uint32_t committeeSize, uint32_t threshold) {
std::vector<DkgOutput> output;
VerificationKey generator;
GroupPublicKey generator2;
setGenerator(generator);
setGenerator(generator2);
// Construct polynomial of degree threshold - 1
std::vector<PrivateKey> vec_a;
vec_a.resize(threshold);
for (uint32_t ii = 0; ii < threshold; ++ii) {
vec_a[ii].random();
}
std::vector<VerificationKey> publicKeyShares(committeeSize);
std::vector<PrivateKey> privateKeyShares(committeeSize);
// Group secret key is polynomial evaluated at 0
GroupPublicKey groupPublicKey;
PrivateKey group_private_key = vec_a[0];
groupPublicKey.mult(generator2, group_private_key);
// Generate committee public keys from their private key contributions
for (uint32_t i = 0; i < committeeSize; ++i) {
PrivateKey pow{i + 1}, tmpF, privateKey, cryptoRank{i + 1};
// Private key is polynomial evaluated at index i
privateKey = vec_a[0];
for (uint32_t k = 1; k < vec_a.size(); k++) {
tmpF.mult(pow, vec_a[k]);
privateKey.add(privateKey, tmpF);
pow.mult(pow, cryptoRank); // adjust index in computation
}
// Public key from private
VerificationKey publicKey;
publicKey.mult(generator, privateKey);
publicKeyShares[i] = publicKey;
privateKeyShares[i] = privateKey;
}
assert(publicKeyShares.size() == committeeSize);
assert(privateKeyShares.size() == committeeSize);
// Compute outputs for each member
for (uint32_t i = 0; i < committeeSize; ++i) {
output.emplace_back(groupPublicKey, publicKeyShares, privateKeyShares[i]);
}
return output;
}
protected:
const uint32_t committeeSize_; ///< Number of participants in DKG
uint32_t polynomialDegree_; ///< Degree of polynomial in DKG
GroupSignatureManager<BaseDkg> groupSignatureManager_;
VerificationKey G;
VerificationKey H;
/// Output of the DKG
/// @{
PrivateKey privateKey_;
GroupPublicKey groupPublicKey_;
std::vector<VerificationKey> publicKeyShares_;
/// @}
/// Temporary variables in DKG
/// @{
PrivateKey xprime_i_;
std::vector<std::vector<PrivateKey> > s_ij_, sprime_ij_;
std::vector<std::vector<VerificationKey>> C_ik_;
std::vector<std::vector<VerificationKey>> A_ik_;
std::vector<std::vector<VerificationKey>> g__s_ij_;
/// @}
std::unordered_map<std::string, std::pair<std::set<std::size_t>, std::vector<PrivateKey>>> reconstructionShares_;
///< Map from id of node_i in complaints to a pair <parties which
///< exposed shares of node_i, the shares that were exposed>
std::mutex mutex_;
virtual fetch::consensus::pb::Broadcast
createCoefficients(const std::vector<PrivateKey> &a_i, const std::vector<PrivateKey> &b_i, uint32_t rank) = 0;
template<typename T>
static void init(std::vector<std::vector<T>> &data, uint32_t i, uint32_t j) {
data.resize(i);
for (auto &data_i : data) {
data_i.resize(j);
}
}
std::vector<fetch::consensus::pb::PrivateShares>
createShares(const std::vector<PrivateKey> &a_i, const std::vector<PrivateKey> &b_i, uint32_t rank) {
std::vector<fetch::consensus::pb::PrivateShares> res;
for (size_t j = 0; j < committeeSize_; ++j) {
computeShares(s_ij_[rank][j], sprime_ij_[rank][j], a_i, b_i, j);
if (j != rank) {
PrivateShares shares{s_ij_[rank][j].toString(), sprime_ij_[rank][j].toString()};
res.emplace_back(shares.handle());
}
}
return res;
}
/**
* LHS and RHS functions are used for checking consistency between publicly broadcasted coefficients
* and secret shares distributed privately
*/
static VerificationKey
computeLHS(VerificationKey &tmpG, const VerificationKey &G,
const VerificationKey &H, const PrivateKey &share1,
const PrivateKey &share2) {
{
VerificationKey tmp2G, lhsG;
tmpG.mult(G, share1);
tmp2G.mult(H, share2);
lhsG.add(tmpG, tmp2G);
return lhsG;
}
}
static VerificationKey
computeLHS(const VerificationKey &G, const VerificationKey &H,
const PrivateKey &share1, const PrivateKey &share2) {
VerificationKey tmpG;
return computeLHS(tmpG, G, H, share1, share2);
}
static void updateRHS(size_t rank, VerificationKey &rhsG,
const std::vector<VerificationKey> &input) {
PrivateKey tmpF{uint32_t(rank + 1)}, cryptoRank{uint32_t(rank + 1)};
VerificationKey tmpG;
assert(input.size() > 0);
for (size_t k = 1; k < input.size(); k++) {
tmpG.mult(input[k], tmpF);
rhsG.add(rhsG, tmpG);
tmpF.mult(tmpF, cryptoRank); // adjust index $i$ in computation
}
}
static VerificationKey
computeRHS(size_t rank, const std::vector<VerificationKey> &input) {
VerificationKey rhsG{input[0]};
assert(input.size() > 0);
updateRHS(rank, rhsG, input);
return rhsG;
}
/**
* Given two polynomials (f and f') with coefficients a_i and b_i, we compute the evaluation of
* these polynomials at different points
*
* @param s_i The value of f(rank)
* @param sprime_i The value of f'(rank)
* @param a_i The vector of coefficients for f
* @param b_i The vector of coefficients for f'
* @param rank The point at which you evaluate the polynomial
*/
static void
computeShares(PrivateKey &s_i, PrivateKey &sprime_i,
const std::vector<PrivateKey> &a_i,
const std::vector<PrivateKey> &b_i,
size_t rank) {
PrivateKey pow{uint32_t(rank + 1)}, tmpF, cryptoRank{uint32_t(rank + 1)};
assert(a_i.size() == b_i.size());
assert(a_i.size() > 0);
s_i = a_i[0];
sprime_i = b_i[0];
for (size_t k = 1; k < a_i.size(); k++) {
tmpF.mult(pow, b_i[k]);
sprime_i.add(sprime_i, tmpF);
tmpF.mult(pow, a_i[k]);
s_i.add(s_i, tmpF);
pow.mult(pow, cryptoRank); // adjust index $j$ in computation
}
}
/**
* Computes the coefficients of a polynomial
*
* @param a Points at which polynomial has been evaluated
* @param b Value of the polynomial at points a
* @return The vector of coefficients of the polynomial
*/
static std::vector<PrivateKey>
interpolatePolynom(const std::vector<PrivateKey> &a,
const std::vector<PrivateKey> &b) {
size_t m = a.size();
if ((b.size() != m) || (m == 0))
throw std::invalid_argument("mcl_interpolate_polynom: bad m");
std::vector<PrivateKey> prod{a}, res(m);
for (size_t k = 0; k < m; k++) {
PrivateKey t1{1};
for (long i = k - 1; i >= 0; i--) {
t1.mult(t1, a[k]);
t1.add(t1, prod[i]);
}
PrivateKey t2;
for (long i = k - 1; i >= 0; i--) {
t2.mult(t2, a[k]);
t2.add(t2, res[i]);
}
t2.sub(b[k], t2);
t1.div(t2, t1);
for (size_t i = 0; i < k; i++) {
t2.mult(prod[i], t1);
res[i].add(res[i], t2);
}
res[k] = t1;
if (k < (m - 1)) {
if (k == 0)
prod[0].negate(prod[0]);
else {
t1.negate(a[k]);
prod[k].add(t1, prod[k - 1]);
for (long i = k - 1; i >= 1; i--) {
t2.mult(prod[i], t1);
prod[i].add(t2, prod[i - 1]);
}
prod[0].mult(prod[0], t1);
}
}
}
return res;
}
};
}
} | 21,270 | 7,029 |
auto SA1::IRAM::conflict() const -> bool {
if(configuration.hacks.coprocessor.delayedSync) return false;
if((cpu.r.mar & 0x40f800) == 0x003000) return cpu.refresh() == 0; //00-3f,80-bf:3000-37ff
return false;
}
auto SA1::IRAM::read(uint address, uint8 data) -> uint8 {
if(!size()) return data;
address = bus.mirror(address, size());
return WritableMemory::read(address, data);
}
auto SA1::IRAM::write(uint address, uint8 data) -> void {
if(!size()) return;
address = bus.mirror(address, size());
return WritableMemory::write(address, data);
}
auto SA1::IRAM::readCPU(uint address, uint8 data) -> uint8 {
cpu.synchronizeCoprocessors();
return read(address, data);
}
auto SA1::IRAM::writeCPU(uint address, uint8 data) -> void {
cpu.synchronizeCoprocessors();
return write(address, data);
}
auto SA1::IRAM::readSA1(uint address, uint8 data) -> uint8 {
return read(address, data);
}
auto SA1::IRAM::writeSA1(uint address, uint8 data) -> void {
return write(address, data);
}
| 1,009 | 384 |
#include <stan/math/prim/scal.hpp>
#include <stan/math/rev/core/var.hpp>
#include <gtest/gtest.h>
#include <boost/typeof/typeof.hpp>
#include <type_traits>
using stan::math::promote_elements;
using stan::math::var;
TEST(MathFunctionsScalPromote_Elements, int2double) {
int from;
promote_elements<double, int> p;
typedef BOOST_TYPEOF(p.promote(from)) result_t;
bool same = std::is_same<double, result_t>::value;
EXPECT_TRUE(same);
}
TEST(MathFunctionsScalPromote_Elements, double2double) {
double from;
promote_elements<double, double> p;
typedef BOOST_TYPEOF(p.promote(from)) result_t;
bool same = std::is_same<double, result_t>::value;
EXPECT_TRUE(same);
}
TEST(MathFunctionsScalPromote_Elements, double2var) {
double from;
promote_elements<var, double> p;
typedef BOOST_TYPEOF(p.promote(from)) result_t;
bool same = std::is_same<var, result_t>::value;
EXPECT_TRUE(same);
}
| 909 | 342 |
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/lang/Number.hpp>
#include <java/lang/Comparable.hpp>
struct default_init_tag;
class java::lang::Integer final
: public Number
, public Comparable
{
public:
typedef Number super;
static constexpr int32_t BYTES { int32_t(4) };
private:
static ::char16_tArray* DigitOnes_;
static ::char16_tArray* DigitTens_;
public:
static constexpr int32_t MAX_VALUE { int32_t(2147483647) };
static constexpr int32_t MIN_VALUE { int32_t(-0x7fffffff-1) };
static constexpr int32_t SIZE { int32_t(32) };
private:
static Class* TYPE_;
static ::char16_tArray* digits_;
static constexpr int64_t serialVersionUID { int64_t(1360826667806852920LL) };
static ::int32_tArray* sizeTable_;
int32_t value { };
protected:
void ctor(int32_t value);
void ctor(String* s);
public:
static int32_t bitCount(int32_t i);
int8_t byteValue() override;
static int32_t compare(int32_t x, int32_t y);
int32_t compareTo(Integer* anotherInteger);
static int32_t compareUnsigned(int32_t x, int32_t y);
static Integer* decode(String* nm);
static int32_t divideUnsigned(int32_t dividend, int32_t divisor);
double doubleValue() override;
bool equals(Object* obj) override;
float floatValue() override;
public: /* package */
static int32_t formatUnsignedInt(int32_t val, int32_t shift, ::char16_tArray* buf, int32_t offset, int32_t len);
static void getChars(int32_t i, int32_t index, ::char16_tArray* buf);
public:
static Integer* getInteger(String* nm);
static Integer* getInteger(String* nm, int32_t val);
static Integer* getInteger(String* nm, Integer* val);
int32_t hashCode() override;
static int32_t hashCode(int32_t value);
static int32_t highestOneBit(int32_t i);
int32_t intValue() override;
int64_t longValue() override;
static int32_t lowestOneBit(int32_t i);
static int32_t max(int32_t a, int32_t b);
static int32_t min(int32_t a, int32_t b);
static int32_t numberOfLeadingZeros(int32_t i);
static int32_t numberOfTrailingZeros(int32_t i);
static int32_t parseInt(String* s);
static int32_t parseInt(String* s, int32_t radix);
static int32_t parseUnsignedInt(String* s);
static int32_t parseUnsignedInt(String* s, int32_t radix);
static int32_t remainderUnsigned(int32_t dividend, int32_t divisor);
static int32_t reverse(int32_t i);
static int32_t reverseBytes(int32_t i);
static int32_t rotateLeft(int32_t i, int32_t distance);
static int32_t rotateRight(int32_t i, int32_t distance);
int16_t shortValue() override;
static int32_t signum(int32_t i);
public: /* package */
static int32_t stringSize(int32_t x);
public:
static int32_t sum(int32_t a, int32_t b);
static String* toBinaryString(int32_t i);
static String* toHexString(int32_t i);
static String* toOctalString(int32_t i);
String* toString() override;
static String* toString(int32_t i);
static String* toString(int32_t i, int32_t radix);
static int64_t toUnsignedLong(int32_t x);
static String* toUnsignedString(int32_t i);
static String* toUnsignedString(int32_t i, int32_t radix);
/*static String* toUnsignedString0(int32_t val, int32_t shift); (private) */
static Integer* valueOf(String* s);
static Integer* valueOf(int32_t i);
static Integer* valueOf(String* s, int32_t radix);
// Generated
Integer(int32_t value);
Integer(String* s);
protected:
Integer(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
virtual int32_t compareTo(Object* o) override;
public: /* package */
static ::char16_tArray*& DigitOnes();
static ::char16_tArray*& DigitTens();
public:
static Class*& TYPE();
public: /* package */
static ::char16_tArray*& digits();
static ::int32_tArray*& sizeTable();
private:
virtual ::java::lang::Class* getClass0();
};
| 4,101 | 1,602 |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp" // must be the first include
#include "IECorePython/ScopedGILRelease.h"
#include "Gaffer/Reference.h"
#include "Gaffer/StringPlug.h"
#include "GafferBindings/ReferenceBinding.h"
#include "GafferBindings/NodeBinding.h"
#include "GafferBindings/ExceptionAlgo.h"
#include "GafferBindings/SignalBinding.h"
using namespace boost::python;
using namespace Gaffer;
using namespace GafferBindings;
namespace
{
struct ReferenceLoadedSlotCaller
{
boost::signals::detail::unusable operator()( boost::python::object slot, ReferencePtr r )
{
try
{
slot( r );
}
catch( const error_already_set &e )
{
translatePythonException();
}
return boost::signals::detail::unusable();
}
};
class ReferenceSerialiser : public NodeSerialiser
{
virtual std::string postConstructor( const Gaffer::GraphComponent *graphComponent, const std::string &identifier, const Serialisation &serialisation ) const
{
const Reference *r = static_cast<const Reference *>( graphComponent );
const std::string &fileName = r->fileName();
if( fileName.empty() )
{
return "";
};
return identifier + ".load( \"" + fileName + "\" )\n";
}
};
void load( Reference &r, const std::string &f )
{
IECorePython::ScopedGILRelease gilRelease;
r.load( f );
}
} // namespace
void GafferBindings::bindReference()
{
NodeClass<Reference>()
.def( "load", &load )
.def( "fileName", &Reference::fileName, return_value_policy<copy_const_reference>() )
.def( "referenceLoadedSignal", &Reference::referenceLoadedSignal, return_internal_reference<1>() )
;
SignalClass<Reference::ReferenceLoadedSignal, DefaultSignalCaller<Reference::ReferenceLoadedSignal>, ReferenceLoadedSlotCaller >( "ReferenceLoadedSignal" );
Serialisation::registerSerialiser( Reference::staticTypeId(), new ReferenceSerialiser );
}
| 3,665 | 1,188 |
#include "App.hpp"
namespace Tetris
{
#define MIN_SIZE_WIDTH 600
#define MIN_SIZE_HEIGHT 400
App::App(/* args */) : m_strTitle("Tetris"),
m_iWidth(800),
m_iHeight(600)
{
}
App::~App()
{
}
App::App(std::string title, int width, int height) : m_strTitle(title),
m_iWidth(width),
m_iHeight(height)
{
}
bool App::init()
{
// initiate SDL
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
TETRIS_ERROR("SDL init failed");
return false;
}
// set OpenGL attributes
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
// set profile contetnt for opengl
SDL_GL_SetAttribute(
SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
std::string glsl_version = "#version 330";
#ifdef __APPLE__
// GL 4.1 Core + GLSL 410
glsl_version = "#version 410";
SDL_GL_SetAttribute( // required on Mac OS
SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
#elif __linux__
// GL 4.3 Core + GLSL 430
glsl_version = "#version 430";
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#elif _WIN32
// GL 3.3 + GLSL 330
glsl_version = "#version 330";
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#endif
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
m_sdl2Window = SDL_CreateWindow(
m_strTitle.c_str(),
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
m_iWidth,
m_iHeight,
window_flags);
SDL_SetWindowMinimumSize(m_sdl2Window, MIN_SIZE_WIDTH, MIN_SIZE_HEIGHT);
m_glContext = SDL_GL_CreateContext(m_sdl2Window);
if (m_glContext == nullptr)
{
TETRIS_ERROR("Can't init GLContent");
}
SDL_GL_MakeCurrent(m_sdl2Window, m_glContext);
// enable VSync
SDL_GL_SetSwapInterval(1);
if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
{
TETRIS_ERROR("Couldn't initialize glad");
return false;
}
glViewport(0, 0, m_iWidth, m_iHeight);
glClearColor(0.0f, 0.0f,0.0f, 0.0f);
return true;
}
void App::update()
{
m_isRunning = true;
SDL_Event e;
while (m_isRunning)
{
while (SDL_PollEvent(&e))
{
if (e.type == SDL_QUIT)
{
m_isRunning = false;
}
else {
switch (e.key.keysym.sym)
{
case SDLK_ESCAPE:
m_isRunning = false;
break;
default:
break;
}
}
if (e.type == SDL_WINDOWEVENT)
{
switch (e.window.event)
{
case SDL_WINDOWEVENT_RESIZED:
m_iWidth = e.window.data1;
m_iHeight = e.window.data2;
TETRIS_INFO( m_iWidth);
TETRIS_INFO( m_iHeight);
SDL_SetWindowSize(m_sdl2Window, m_iWidth, m_iHeight);
break;
default:
break;
}
}
}
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
SDL_GL_SwapWindow(m_sdl2Window);
}
}
void App::clean()
{
SDL_GL_DeleteContext(m_glContext);
SDL_DestroyWindow(m_sdl2Window);
SDL_Quit();
}
} | 4,441 | 1,564 |
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
float a,b,c;
cin>>a>>b>>c;
printf("NUMBER = %.0f\n",a);
printf("SALARY = U$ %.2f\n",b*c);
return 0;
} | 178 | 84 |
/*
* Copyright 2018 Universidad Carlos III de Madrid
*
* 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.
*/
// Standard library
#include <iostream>
#include <vector>
#include <fstream>
#include <chrono>
#include <string>
#include <numeric>
#include <stdexcept>
// grppi
#include "grppi/grppi.h"
// Samples shared utilities
#include "../../util/util.h"
void compute_avg(grppi::dynamic_execution & e, int n) {
using namespace std;
vector<long long> in;
generate_n(back_inserter(in), n,
[i=0]() mutable { i++; return i*i; });
vector<double> out(n);
grppi::stencil(e, begin(in), end(in), begin(out),
[](auto it, auto n) {
return (*it + std::accumulate(begin(n), end(n), 0)) / double(n.size()+1);
},
[&in](auto it) {
vector<double> r;
if (it!=begin(in)) r.push_back(*prev(it));
if (std::distance(it,end(in))>1) r.push_back(*next(it));
return r;
}
);
copy(begin(out), end(out), ostream_iterator<double>(cout, " "));
cout << endl;
}
void print_message(const std::string & prog, const std::string & msg) {
using namespace std;
cerr << msg << endl;
cerr << "Usage: " << prog << " size mode" << endl;
cerr << " size: Integer value with problem size" << endl;
cerr << " mode:" << endl;
print_available_modes(cerr);
}
int main(int argc, char **argv) {
using namespace std;
if(argc < 3){
print_message(argv[0], "Invalid number of arguments.");
return -1;
}
int n = stoi(argv[1]);
if(n <= 0){
print_message(argv[0], "Invalid problem size. Use a positive number.");
return -1;
}
if (!run_test(argv[2], compute_avg, n)) {
print_message(argv[0], "Invalid policy.");
return -1;
}
return 0;
}
| 2,228 | 791 |
/* $Id$ */
// Copyright (C) 2004, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef ClpDynamicExampleMatrix_H
#define ClpDynamicExampleMatrix_H
#include "CoinPragma.hpp"
#include "ClpDynamicMatrix.hpp"
class ClpSimplex;
/** This implements a dynamic matrix when we have a limit on the number of
"interesting rows". This version inherits from ClpDynamicMatrix and knows that
the real matrix is gub. This acts just like ClpDynamicMatrix but generates columns.
This "generates" columns by choosing from stored set. It is maent as a starting point
as to how you could use shortest path to generate columns.
So it has its own copy of all data needed. It populates ClpDynamicWatrix with enough
to allow for gub keys and active variables. In turn ClpDynamicMatrix populates
a CoinPackedMatrix with active columns and rows.
As there is one copy here and one in ClpDynamicmatrix these names end in Gen_
It is obviously more efficient to just use ClpDynamicMatrix but the ideas is to
show how much code a user would have to write.
This does not work very well with bounds
*/
class ClpDynamicExampleMatrix : public ClpDynamicMatrix {
public:
/**@name Main functions provided */
//@{
/// Partial pricing
virtual void partialPricing(ClpSimplex * model, double start, double end,
int & bestSequence, int & numberWanted);
/** Creates a variable. This is called after partial pricing and will modify matrix.
Will update bestSequence.
*/
virtual void createVariable(ClpSimplex * model, int & bestSequence);
/** If addColumn forces compression then this allows descendant to know what to do.
If >= then entry stayed in, if -1 then entry went out to lower bound.of zero.
Entries at upper bound (really nonzero) never go out (at present).
*/
virtual void packDown(const int * in, int numberToPack);
//@}
/**@name Constructors, destructor */
//@{
/** Default constructor. */
ClpDynamicExampleMatrix();
/** This is the real constructor.
It assumes factorization frequency will not be changed.
This resizes model !!!!
The contents of original matrix in model will be taken over and original matrix
will be sanitized so can be deleted (to avoid a very small memory leak)
*/
ClpDynamicExampleMatrix(ClpSimplex * model, int numberSets,
int numberColumns, const int * starts,
const double * lower, const double * upper,
const int * startColumn, const int * row,
const double * element, const double * cost,
const double * columnLower = NULL, const double * columnUpper = NULL,
const unsigned char * status = NULL,
const unsigned char * dynamicStatus = NULL,
int numberIds = 0, const int *ids = NULL);
#if 0
/// This constructor just takes over ownership (except for lower, upper)
ClpDynamicExampleMatrix(ClpSimplex * model, int numberSets,
int numberColumns, int * starts,
const double * lower, const double * upper,
int * startColumn, int * row,
double * element, double * cost,
double * columnLower = NULL, double * columnUpper = NULL,
const unsigned char * status = NULL,
const unsigned char * dynamicStatus = NULL,
int numberIds = 0, const int *ids = NULL);
#endif
/** Destructor */
virtual ~ClpDynamicExampleMatrix();
//@}
/**@name Copy method */
//@{
/** The copy constructor. */
ClpDynamicExampleMatrix(const ClpDynamicExampleMatrix&);
ClpDynamicExampleMatrix& operator=(const ClpDynamicExampleMatrix&);
/// Clone
virtual ClpMatrixBase * clone() const ;
//@}
/**@name gets and sets */
//@{
/// Starts of each column
inline CoinBigIndex * startColumnGen() const {
return startColumnGen_;
}
/// rows
inline int * rowGen() const {
return rowGen_;
}
/// elements
inline double * elementGen() const {
return elementGen_;
}
/// costs
inline double * costGen() const {
return costGen_;
}
/// full starts
inline int * fullStartGen() const {
return fullStartGen_;
}
/// ids in next level matrix
inline int * idGen() const {
return idGen_;
}
/// Optional lower bounds on columns
inline double * columnLowerGen() const {
return columnLowerGen_;
}
/// Optional upper bounds on columns
inline double * columnUpperGen() const {
return columnUpperGen_;
}
/// size
inline int numberColumns() const {
return numberColumns_;
}
inline void setDynamicStatusGen(int sequence, DynamicStatus status) {
unsigned char & st_byte = dynamicStatusGen_[sequence];
st_byte = static_cast<unsigned char>(st_byte & ~7);
st_byte = static_cast<unsigned char>(st_byte | status);
}
inline DynamicStatus getDynamicStatusGen(int sequence) const {
return static_cast<DynamicStatus> (dynamicStatusGen_[sequence] & 7);
}
/// Whether flagged
inline bool flaggedGen(int i) const {
return (dynamicStatusGen_[i] & 8) != 0;
}
inline void setFlaggedGen(int i) {
dynamicStatusGen_[i] = static_cast<unsigned char>(dynamicStatusGen_[i] | 8);
}
inline void unsetFlagged(int i) {
dynamicStatusGen_[i] = static_cast<unsigned char>(dynamicStatusGen_[i] & ~8);
}
//@}
protected:
/**@name Data members
The data members are protected to allow access for derived classes. */
//@{
/// size
int numberColumns_;
/// Starts of each column
CoinBigIndex * startColumnGen_;
/// rows
int * rowGen_;
/// elements
double * elementGen_;
/// costs
double * costGen_;
/// start of each set
int * fullStartGen_;
/// for status and which bound
unsigned char * dynamicStatusGen_;
/** identifier for each variable up one level (startColumn_, etc). This is
of length maximumGubColumns_. For this version it is just sequence number
at this level */
int * idGen_;
/// Optional lower bounds on columns
double * columnLowerGen_;
/// Optional upper bounds on columns
double * columnUpperGen_;
//@}
};
#endif
| 6,914 | 1,743 |
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "NodeGraph.h"
namespace GraphLanguage
{
const std::string s_resultName = "result";
const std::string ParameterName_NodeInstantiation = "<instantiation>";
NodeGraph::NodeGraph() {}
NodeGraph::~NodeGraph() {}
void NodeGraph::Add(Node&& a) { _nodes.emplace_back(std::move(a)); }
void NodeGraph::Add(Connection&& a) { _connections.emplace_back(std::move(a)); }
bool NodeGraph::IsUpstream(NodeId startNode, NodeId searchingForNode)
{
// Starting at 'startNode', search upstream and see if we find 'searchingForNode'
if (startNode == searchingForNode) {
return true;
}
for (auto i=_connections.cbegin(); i!=_connections.cend(); ++i) {
if (i->OutputNodeId() == startNode) {
auto inputNode = i->InputNodeId();
if (inputNode != NodeId_Interface && inputNode != NodeId_Constant && IsUpstream(i->InputNodeId(), searchingForNode)) {
return true;
}
}
}
return false;
}
bool NodeGraph::IsDownstream(
NodeId startNode,
const NodeId* searchingForNodesStart, const NodeId* searchingForNodesEnd)
{
if (std::find(searchingForNodesStart, searchingForNodesEnd, startNode) != searchingForNodesEnd) {
return true;
}
for (auto i=_connections.cbegin(); i!=_connections.cend(); ++i) {
if (i->InputNodeId() == startNode) {
auto outputNode = i->OutputNodeId();
if (outputNode != NodeId_Interface && outputNode != NodeId_Constant && IsDownstream(outputNode, searchingForNodesStart, searchingForNodesEnd)) {
return true;
}
}
}
return false;
}
bool NodeGraph::HasNode(NodeId nodeId)
{
// Special case node ids are considered to always exist (particularly required when called from Trim())
if (nodeId == NodeId_Interface || nodeId == NodeId_Constant) return true;
return std::find_if(_nodes.begin(), _nodes.end(),
[=](const Node& node) { return node.NodeId() == nodeId; }) != _nodes.end();
}
const Node* NodeGraph::GetNode(NodeId nodeId) const
{
auto res = std::find_if(
_nodes.cbegin(), _nodes.cend(),
[=](const Node& n) { return n.NodeId() == nodeId; });
if (res != _nodes.cend()) {
return &*res;
}
return nullptr;
}
void NodeGraph::Trim(NodeId previewNode)
{
Trim(&previewNode, &previewNode+1);
}
void NodeGraph::Trim(const NodeId* trimNodesBegin, const NodeId* trimNodesEnd)
{
//
// Trim out all of the nodes that are upstream of
// 'previewNode' (except for output nodes that are
// directly written by one of the trim nodes)
//
// Simply
// 1. remove all nodes, unless they are downstream
// of 'previewNode'
// 2. remove all connections that refer to nodes
// that no longer exist
//
// Generally, there won't be an output connection attached
// to the previewNode at the end of the process. So, we
// may need to create one.
//
_nodes.erase(
std::remove_if(
_nodes.begin(), _nodes.end(),
[=](const Node& node) { return !IsDownstream(node.NodeId(), trimNodesBegin, trimNodesEnd); }),
_nodes.end());
_connections.erase(
std::remove_if(
_connections.begin(), _connections.end(),
[=](const Connection& connection)
{ return !HasNode(connection.InputNodeId()) || !HasNode(connection.OutputNodeId()) || connection.OutputNodeId() == NodeId_Interface; }),
_connections.end());
}
///////////////////////////////////////////////////////////////////////////////////////////////////
static void OrderNodes(IteratorRange<NodeId*> range)
{
// We need to sort the upstreams in some way that maintains a
// consistant ordering. The simplied way is just to use node id.
// However we may sometimes want to set priorities for nodes.
// For example, nodes that can "discard" pixels should be priortized
// higher.
std::sort(range.begin(), range.end());
}
static bool SortNodesFunction(
NodeId node,
std::vector<NodeId>& presorted,
std::vector<NodeId>& sorted,
std::vector<NodeId>& marks,
const NodeGraph& graph)
{
if (std::find(presorted.begin(), presorted.end(), node) == presorted.end()) {
return false; // hit a cycle
}
if (std::find(marks.begin(), marks.end(), node) != marks.end()) {
return false; // hit a cycle
}
marks.push_back(node);
std::vector<NodeId> upstream;
upstream.reserve(graph.GetConnections().size());
for (const auto& i:graph.GetConnections())
if (i.OutputNodeId() == node)
upstream.push_back(i.InputNodeId());
OrderNodes(MakeIteratorRange(upstream));
for (const auto& i2:upstream)
SortNodesFunction(i2, presorted, sorted, marks, graph);
sorted.push_back(node);
presorted.erase(std::find(presorted.begin(), presorted.end(), node));
return true;
}
std::vector<NodeId> SortNodes(const NodeGraph& graph, bool& isAcyclic)
{
/*
We need to create a directed acyclic graph from the nodes in 'graph'
-- and then we need to do a topological sort.
This will tell us the order in which to call each function
Basic algorithms:
L <- Empty list that will contain the sorted elements
S <- Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
Depth first sort:
L <- Empty list that will contain the sorted nodes
while there are unmarked nodes do
select an unmarked node n
visit(n)
function visit(node n)
if n has a temporary mark then stop (not a DAG)
if n is not marked (i.e. has not been visited yet) then
mark n temporarily
for each node m with an edge from n to m do
visit(m)
mark n permanently
add n to head of L
*/
std::vector<NodeId> presortedNodes, sortedNodes;
sortedNodes.reserve(graph.GetNodes().size());
for (const auto& i:graph.GetNodes())
presortedNodes.push_back(i.NodeId());
OrderNodes(MakeIteratorRange(presortedNodes));
isAcyclic = true;
while (!presortedNodes.empty()) {
std::vector<NodeId> temporaryMarks;
bool sortReturn = SortNodesFunction(
presortedNodes[0],
presortedNodes, sortedNodes,
temporaryMarks, graph);
if (!sortReturn) {
isAcyclic = false;
break;
}
}
return sortedNodes;
}
}
| 8,093 | 2,169 |
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main() {
unsigned long orig,i,j,tmp;
cin >> orig;
tmp = orig;
if (orig == 1){
cout << "1=1"<<endl;
goto endapp;
}
cout << orig << '=';
for (i = 2; tmp != 1 && i<=orig; ++i){
while (tmp%i == 0){
cout << i;
tmp /= i;
if (tmp != 1) cout << '*';
}
}
cout << endl;
//system("pause>nul");
endapp:
return 0;
} | 496 | 190 |
/**
* ScriptDev3 is an extension for mangos providing enhanced features for
* area triggers, creatures, game objects, instances, items, and spells beyond
* the default database scripting in mangos.
*
* Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/>
* Copyright (C) 2014-2022 MaNGOS <https://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/**
* ScriptData
* SDName: Instance_ZulGurub
* SD%Complete: 80
* SDComment: Missing reset function after killing a boss for Ohgan, Thekal.
* SDCategory: Zul'Gurub
* EndScriptData
*/
#include "precompiled.h"
#include "zulgurub.h"
struct is_zulgurub : public InstanceScript
{
is_zulgurub() : InstanceScript("instance_zulgurub") {}
class instance_zulgurub : public ScriptedInstance
{
public:
instance_zulgurub(Map* pMap) : ScriptedInstance(pMap),
m_bHasIntroYelled(false),
m_bHasAltarYelled(false)
{
Initialize();
}
~instance_zulgurub() {}
void Initialize() override
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
}
// IsEncounterInProgress() const override { return false; } // not active in Zul'Gurub
void OnCreatureCreate(Creature* pCreature) override
{
switch (pCreature->GetEntry())
{
case NPC_LORKHAN:
case NPC_ZATH:
case NPC_THEKAL:
case NPC_JINDO:
case NPC_HAKKAR:
case NPC_BLOODLORD_MANDOKIR:
case NPC_MARLI:
m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();
break;
case NPC_PANTHER_TRIGGER:
if (pCreature->GetPositionY() < -1626)
{
m_lLeftPantherTriggerGUIDList.push_back(pCreature->GetObjectGuid());
}
else
{
m_lRightPantherTriggerGUIDList.push_back(pCreature->GetObjectGuid());
}
break;
}
}
void OnObjectCreate(GameObject* pGo) override
{
switch (pGo->GetEntry())
{
case GO_GONG_OF_BETHEKK:
case GO_FORCEFIELD:
break;
case GO_SPIDER_EGG:
m_lSpiderEggGUIDList.push_back(pGo->GetObjectGuid());
return;
}
m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid();
}
void SetData(uint32 uiType, uint32 uiData) override
{
switch (uiType)
{
case TYPE_JEKLIK:
case TYPE_VENOXIS:
case TYPE_THEKAL:
m_auiEncounter[uiType] = uiData;
if (uiData == DONE)
{
DoLowerHakkarHitPoints();
}
break;
case TYPE_MARLI:
m_auiEncounter[uiType] = uiData;
if (uiData == DONE)
{
DoLowerHakkarHitPoints();
}
if (uiData == FAIL)
{
for (GuidList::const_iterator itr = m_lSpiderEggGUIDList.begin(); itr != m_lSpiderEggGUIDList.end(); ++itr)
{
if (GameObject* pEgg = instance->GetGameObject(*itr))
{
// Note: this type of Gameobject needs to be respawned manually
pEgg->SetRespawnTime(2 * DAY);
pEgg->Respawn();
}
}
}
break;
case TYPE_ARLOKK:
m_auiEncounter[uiType] = uiData;
DoUseDoorOrButton(GO_FORCEFIELD);
if (uiData == DONE)
{
DoLowerHakkarHitPoints();
}
if (uiData == FAIL)
{
// Note: this gameobject should change flags - currently it despawns which isn't correct
if (GameObject* pGong = GetSingleGameObjectFromStorage(GO_GONG_OF_BETHEKK))
{
pGong->SetRespawnTime(2 * DAY);
pGong->Respawn();
}
}
break;
case TYPE_OHGAN:
// Note: SPECIAL instance data is set via ACID!
if (uiData == SPECIAL)
{
if (Creature* pMandokir = GetSingleCreatureFromStorage(NPC_BLOODLORD_MANDOKIR))
{
pMandokir->SetWalk(false);
pMandokir->GetMotionMaster()->MovePoint(1, aMandokirDownstairsPos[0], aMandokirDownstairsPos[1], aMandokirDownstairsPos[2]);
}
}
m_auiEncounter[uiType] = uiData;
break;
case TYPE_LORKHAN:
case TYPE_ZATH:
m_auiEncounter[uiType] = uiData;
break;
case TYPE_SIGNAL_1:
DoYellAtTriggerIfCan(uiData);
return;
}
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " "
<< m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5] << " "
<< m_auiEncounter[6] << " " << m_auiEncounter[7];
m_strInstData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
uint32 GetData(uint32 uiType) const override
{
if (uiType < MAX_ENCOUNTER)
{
return m_auiEncounter[uiType];
}
return 0;
}
uint64 GetData64(uint32 type) const override
{
switch (type)
{
case TYPE_SIGNAL_2:
case TYPE_SIGNAL_3:
if (Creature *p = (const_cast<instance_zulgurub*>(this))->SelectRandomPantherTrigger(type == TYPE_SIGNAL_2))
{
return p->GetObjectGuid().GetRawValue();
}
break;
default:
break;
}
return 0;
}
const char* Save() const override { return m_strInstData.c_str(); }
void Load(const char* chrIn) override
{
if (!chrIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(chrIn);
std::istringstream loadStream(chrIn);
loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3]
>> m_auiEncounter[4] >> m_auiEncounter[5] >> m_auiEncounter[6] >> m_auiEncounter[7];
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (m_auiEncounter[i] == IN_PROGRESS)
{
m_auiEncounter[i] = NOT_STARTED;
}
}
OUT_LOAD_INST_DATA_COMPLETE;
}
private:
void DoLowerHakkarHitPoints()
{
if (Creature* pHakkar = GetSingleCreatureFromStorage(NPC_HAKKAR))
{
if (pHakkar->IsAlive() && pHakkar->GetMaxHealth() > HP_LOSS_PER_PRIEST)
{
pHakkar->SetMaxHealth(pHakkar->GetMaxHealth() - HP_LOSS_PER_PRIEST);
pHakkar->SetHealth(pHakkar->GetHealth() - HP_LOSS_PER_PRIEST);
}
}
}
void DoYellAtTriggerIfCan(uint32 uiTriggerId)
{
if (uiTriggerId == AREATRIGGER_ENTER && !m_bHasIntroYelled)
{
DoOrSimulateScriptTextForThisInstance(SAY_HAKKAR_PROTECT, NPC_HAKKAR);
m_bHasIntroYelled = true;
}
else if (uiTriggerId == AREATRIGGER_ALTAR && !m_bHasAltarYelled)
{
DoOrSimulateScriptTextForThisInstance(SAY_MINION_DESTROY, NPC_HAKKAR);
m_bHasAltarYelled = true;
}
}
Creature* SelectRandomPantherTrigger(bool bIsLeft)
{
GuidList* plTempList = bIsLeft ? &m_lLeftPantherTriggerGUIDList : &m_lRightPantherTriggerGUIDList;
std::vector<Creature*> vTriggers;
vTriggers.reserve(plTempList->size());
for (GuidList::const_iterator itr = plTempList->begin(); itr != plTempList->end(); ++itr)
{
if (Creature* pTemp = instance->GetCreature(*itr))
{
vTriggers.push_back(pTemp);
}
}
if (vTriggers.empty())
{
return nullptr;
}
return vTriggers[urand(0, vTriggers.size() - 1)];
}
uint32 m_auiEncounter[MAX_ENCOUNTER];
std::string m_strInstData;
GuidList m_lRightPantherTriggerGUIDList;
GuidList m_lLeftPantherTriggerGUIDList;
GuidList m_lSpiderEggGUIDList;
bool m_bHasIntroYelled;
bool m_bHasAltarYelled;
};
InstanceData* GetInstanceData(Map* pMap) override
{
return new instance_zulgurub(pMap);
}
};
struct at_zulgurub : public AreaTriggerScript
{
at_zulgurub() : AreaTriggerScript("at_zulgurub") {}
bool AreaTrigger_at_zulgurub(Player* pPlayer, AreaTriggerEntry const* pAt)
{
if (pAt->id == AREATRIGGER_ENTER || pAt->id == AREATRIGGER_ALTAR)
{
if (pPlayer->isGameMaster() || pPlayer->IsDead())
{
return false;
}
if (ScriptedInstance* pInstance = (ScriptedInstance*)pPlayer->GetInstanceData())
{
pInstance->SetData(TYPE_SIGNAL_1, pAt->id);
}
}
return false;
}
};
void AddSC_instance_zulgurub()
{
Script* s;
s = new is_zulgurub();
s->RegisterSelf();
s = new at_zulgurub();
s->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "instance_zulgurub";
//pNewScript->GetInstanceData = &GetInstanceData_instance_zulgurub;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "at_zulgurub";
//pNewScript->pAreaTrigger = &AreaTrigger_at_zulgurub;
//pNewScript->RegisterSelf();
}
| 11,416 | 3,590 |
//
// PauseLayer.hpp
// TurboRace
//
// Created by Carlos Eduardo Pinan Indacochea on 21/02/22.
//
#ifndef PauseLayer_hpp
#define PauseLayer_hpp
#include "cocos2d.h"
enum PauseButtons
{
kTagPauseResumeGame = 0,
kTagPauseGoHome = 1,
kTagPausePlayAgain = 2
};
class PauseLayer : public cocos2d::LayerColor {
public:
PauseLayer();
private:
void onOptionsTapped(cocos2d::Ref* sender);
};
#endif /* PauseLayer_hpp */
| 441 | 189 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
//------------------------------------------------------
// testcomponent - Loads a service and its testcomponent from dlls performs a test.
// Expands the dll-names depending on the actual environment.
// Example : testcomponent stardiv.uno.io.Pipe stm
//
// Therefor the testcode must exist in teststm and the testservice must be named test.stardiv.uno.io.Pipe
//
#include <stdio.h>
#include <smart/com/sun/star/registry/XImplementationRegistration.hxx>
#include <smart/com/sun/star/lang/XComponent.hxx>
//#include <com/sun/star/registry/ stardiv/uno/repos/simplreg.hxx>
#include <vos/dynload.hxx>
#include <vos/diagnose.hxx>
#include <usr/services.hxx>
#include <vcl/svapp.hxx>
#include <usr/ustring.hxx>
#include <tools/string.hxx>
#include <vos/conditn.hxx>
#include <smart/com/sun/star/test/XSimpleTest.hxx>
using namespace rtl;
using namespace vos;
using namespace usr;
// Needed to switch on solaris threads
#ifdef SOLARIS
extern "C" void ChangeGlobalInit();
#endif
int __LOADONCALLAPI main (int argc, char **argv)
{
if( argc < 3) {
printf( "usage : testcomponent service dll [additional dlls]\n" );
exit( 0 );
}
#ifdef SOLARIS
// switch on threads in solaris
ChangeGlobalInit();
#endif
// create service manager
// XMultiServiceFactoryRef xSMgr = getProcessServiceManager();
XMultiServiceFactoryRef xSMgr = createRegistryServiceManager();
OSL_ASSERT( xSMgr.is() );
registerUsrServices( xSMgr );
setProcessServiceManager( xSMgr );
XImplementationRegistrationRef xReg;
XSimpleRegistryRef xSimpleReg;
try {
// Create registration service
XInterfaceRef x = xSMgr->createInstance(
UString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
x->queryInterface( XImplementationRegistration::getSmartUik() , xReg );
/* x = xSMgr->createInstance( L"stardiv.uno.repos.SimpleRegistry" );
OSL_ASSERT( x.is() );
x->queryInterface( XSimpleRegistry::getSmartUik() , xSimpleReg );
OSL_ASSERT( xSimpleReg.is() );
xSimpleReg->open( L"testcomp.rdb" , FALSE , TRUE );
*/ }
catch( Exception& e ) {
printf( "%s\n" , OWStringToOString( e.getName() , CHARSET_SYSTEM ).getStr() );
exit(1);
}
sal_Char szBuf[1024];
OString sTestName;
try {
// Load dll for the tested component
for( int n = 2 ; n <argc ; n ++ ) {
ORealDynamicLoader::computeModuleName( argv[n] , szBuf, 1024 );
UString aDllName( OStringToOWString( szBuf, CHARSET_SYSTEM ) );
xReg->registerImplementation(
UString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName,
xSimpleReg );
}
}
catch( Exception& e ) {
printf( "Couldn't reach dll %s\n" , szBuf );
printf( "%s\n" , OWStringToOString( e.getName() , CHARSET_SYSTEM ).getStr() );
exit(1);
}
try {
// Load dll for the test component
sTestName = "test";
sTestName += argv[2];
ORealDynamicLoader::computeModuleName( sTestName.getStr() , szBuf, 1024 );
UString aDllName = OStringToOWString( szBuf, CHARSET_SYSTEM );
xReg->registerImplementation(
UString::createFromAscii( "com.sun.star.loader.SharedLibrary" ) ,
aDllName,
xSimpleReg );
}
catch( Exception& e ) {
printf( "Couldn't reach dll %s\n" , szBuf );
printf( "%s\n" , OWStringToOString( e.getName() , CHARSET_SYSTEM ).getStr() );
exit(1);
}
// Instantiate test service
sTestName = "test.";
sTestName += argv[1];
XInterfaceRef xIntTest = xSMgr->createInstance( OStringToOWString( sTestName , CHARSET_SYSTEM ) );
XSimpleTestRef xTest( xIntTest , USR_QUERY );
if( ! xTest.is() ) {
printf( "Couldn't instantiate test service \n" );
exit( 1 );
}
INT32 nHandle = 0;
INT32 nNewHandle;
INT32 nErrorCount = 0;
INT32 nWarningCount = 0;
// loop until all test are performed
while( nHandle != -1 ) {
// Instantiate serivce
XInterfaceRef x = xSMgr->createInstance( OStringToOWString( argv[1] , CHARSET_SYSTEM ) );
if( ! x.is() ) {
printf( "Couldn't instantiate service !\n" );
exit( 1 );
}
// do the test
try {
nNewHandle = xTest->test( OStringToOWString( argv[1] , CHARSET_SYSTEM ) , x , nHandle );
}
catch ( Exception& e ) {
printf( "testcomponent : uncaught exception %s\n" ,
OWStringToOString( e.getName(), CHARSET_SYSTEM ).getStr() );
exit(1);
}
catch(...) {
printf( "testcomponent : uncaught unknown exception\n" );
exit(1);
}
// print errors and warning
Sequence<UString> seqErrors = xTest->getErrors();
Sequence<UString> seqWarnings = xTest->getWarnings();
if( seqWarnings.getLen() > nWarningCount ) {
printf( "Warnings during test %d!\n" , nHandle );
for( ; nWarningCount < seqWarnings.getLen() ; nWarningCount ++ ) {
printf( "Warning\n%s\n---------\n" ,
OWStringToOString( seqWarnings.getArray()[nWarningCount], CHARSET_SYSTEM ).getStr() );
}
}
if( seqErrors.getLen() > nErrorCount ) {
printf( "Errors during test %d!\n" , nHandle );
for( ; nErrorCount < seqErrors.getLen() ; nErrorCount ++ ) {
printf( "%s\n" ,
OWStringToOString(
seqErrors.getArray()[nErrorCount], CHARSET_SYSTEM ).getStr() );
}
}
nHandle = nNewHandle;
}
if( xTest->testPassed() ) {
printf( "Test passed !\n" );
}
else {
printf( "Test failed !\n" );
}
XComponentRef rComp( xSMgr , USR_QUERY );
rComp->dispose();
return 0;
}
| 6,335 | 2,399 |
#include "TaskRunner.h"
#include <stdexcept>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
std::vector<TaskPtr> TaskRunner::getResults()
{
int status;
pid_t child;
std::vector<TaskPtr> result;
while ((child = waitpid(-1, &status, WNOHANG)) > 0) {
TaskPtr task = getResult(child);
if (!task) continue;
if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM)
task->output = "timeout expired\n";
result.emplace_back(task);
}
return result;
}
TaskPtr TaskRunner::getResult(pid_t pid)
{
const auto item = tasks.find(pid);
if (item == tasks.end()) return TaskPtr();
TaskPtr result = item->second;
std::vector<int8_t> buffer(maxBufferSize);
int nBytes = 0;
do {
nBytes = read(result->fd[0], &buffer[0], buffer.size());
if (nBytes > 0) result->output.append(buffer.cbegin(), buffer.cbegin() + nBytes);
} while (nBytes == maxBufferSize);
close(result->fd[0]);
tasks.erase(pid);
return result;
}
void TaskRunner::runTask(const std::vector<std::string>& cmd, const std::string& id)
{
if (cmd.empty()) return;
TaskPtr task = std::make_shared<Task>();
task->id = id;
if (pipe(task->fd) < 0) {
throw std::runtime_error(strerror(errno));
}
pid_t pid = fork();
if (pid < 0) {
throw std::runtime_error(strerror(errno));
}
if (pid == 0) {
close(task->fd[0]);
alarm(timeout);
std::vector<char*> params;
params.reserve(cmd.size());
for (const std::string& str : cmd) {
params.push_back(const_cast<char*>(str.c_str()));
};
params.push_back(nullptr);
dup2(task->fd[1], fileno(stdout));
dup2(task->fd[1], fileno(stderr));
execvp(params[0], ¶ms[0]);
exit(0);
} else {
close(task->fd[1]);
tasks.emplace(pid, task);
}
}
| 1,918 | 678 |
/*
Copyright (c) 2008, Arvid Norberg
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 author 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.
*/
#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h> // for exit()
#include "setup_transfer.hpp" // for tests_failure
int test_main();
#include "libtorrent/assert.hpp"
#include "libtorrent/file.hpp"
#include <signal.h>
void sig_handler(int sig)
{
char stack_text[10000];
#if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS
print_backtrace(stack_text, sizeof(stack_text), 30);
#elif defined __FUNCTION__
strcat(stack_text, __FUNCTION__);
#else
stack_text[0] = 0;
#endif
char const* sig_name = 0;
switch (sig)
{
#define SIG(x) case x: sig_name = #x; break
SIG(SIGSEGV);
#ifdef SIGBUS
SIG(SIGBUS);
#endif
SIG(SIGILL);
SIG(SIGABRT);
SIG(SIGFPE);
#ifdef SIGSYS
SIG(SIGSYS);
#endif
#undef SIG
};
fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
exit(138);
}
using namespace libtorrent;
int main()
{
#ifdef O_NONBLOCK
// on darwin, stdout is set to non-blocking mode by default
// which sometimes causes tests to fail with EAGAIN just
// by printing logs
int flags = fcntl(fileno(stdout), F_GETFL, 0);
fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
flags = fcntl(fileno(stderr), F_GETFL, 0);
fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif
signal(SIGSEGV, &sig_handler);
#ifdef SIGBUS
signal(SIGBUS, &sig_handler);
#endif
signal(SIGILL, &sig_handler);
signal(SIGABRT, &sig_handler);
signal(SIGFPE, &sig_handler);
#ifdef SIGSYS
signal(SIGSYS, &sig_handler);
#endif
char dir[40];
snprintf(dir, sizeof(dir), "test_tmp_%u", rand());
std::string test_dir = complete(dir);
error_code ec;
create_directory(test_dir, ec);
if (ec)
{
fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str());
return 1;
}
#ifdef TORRENT_WINDOWS
SetCurrentDirectoryA(dir);
#else
chdir(dir);
#endif
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
test_main();
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception const& e)
{
std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
tests_failure = true;
}
catch (...)
{
std::cerr << "Terminated with unknown exception\n";
tests_failure = true;
}
#endif
fflush(stdout);
fflush(stderr);
remove_all(test_dir, ec);
if (ec)
fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str());
return tests_failure ? 1 : 0;
}
| 3,882 | 1,546 |
// Copyright (c) 2014 Baidu, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Authors: Ge,Jun (gejun@baidu.com)
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <butil/macros.h>
#include <butil/file_util.h>
#include <bvar/bvar.h>
#include <bthread/bthread.h>
#include <brpc/channel.h>
#include <brpc/server.h>
#include <brpc/rpc_dump.h>
#include <brpc/serialized_request.h>
#include "info_thread.h"
DEFINE_string(dir, "", "The directory of dumped requests");
DEFINE_int32(times, 1, "Repeat replaying for so many times");
DEFINE_int32(qps, 0, "Limit QPS if this flag is positive");
DEFINE_int32(thread_num, 0, "Number of threads for replaying");
DEFINE_bool(use_bthread, true, "Use bthread to replay");
DEFINE_string(connection_type, "", "Connection type, choose automatically "
"according to protocol by default");
DEFINE_string(server, "0.0.0.0:8002", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Maximum retry times");
DEFINE_int32(dummy_port, 8899, "Port of dummy server(to monitor replaying)");
bvar::LatencyRecorder g_latency_recorder("rpc_replay");
bvar::Adder<int64_t> g_error_count("rpc_replay_error_count");
bvar::Adder<int64_t> g_sent_count;
// Include channels for all protocols that support both client and server.
class ChannelGroup {
public:
int Init();
~ChannelGroup();
// Get channel by protocol type.
brpc::Channel* channel(brpc::ProtocolType type) {
if ((size_t)type < _chans.size()) {
return _chans[(size_t)type];
}
return NULL;
}
private:
std::vector<brpc::Channel*> _chans;
};
int ChannelGroup::Init() {
{
// force global initialization of rpc.
brpc::Channel dummy_channel;
}
std::vector<std::pair<brpc::ProtocolType, brpc::Protocol> > protocols;
brpc::ListProtocols(&protocols);
size_t max_protocol_size = 0;
for (size_t i = 0; i < protocols.size(); ++i) {
max_protocol_size = std::max(max_protocol_size,
(size_t)protocols[i].first);
}
_chans.resize(max_protocol_size);
for (size_t i = 0; i < protocols.size(); ++i) {
if (protocols[i].second.support_client() &&
protocols[i].second.support_server()) {
const brpc::ProtocolType prot = protocols[i].first;
brpc::Channel* chan = new brpc::Channel;
brpc::ChannelOptions options;
options.protocol = prot;
options.connection_type = FLAGS_connection_type;
options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
options.max_retry = FLAGS_max_retry;
if (chan->Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(),
&options) != 0) {
LOG(ERROR) << "Fail to initialize channel";
return -1;
}
_chans[prot] = chan;
}
}
return 0;
}
ChannelGroup::~ChannelGroup() {
for (size_t i = 0; i < _chans.size(); ++i) {
delete _chans[i];
}
_chans.clear();
}
static void handle_response(brpc::Controller* cntl, int64_t start_time,
bool sleep_on_error/*note*/) {
// TODO(gejun): some bthreads are starved when new bthreads are created
// continuously, which happens when server is down and RPC keeps failing.
// Sleep a while on error to avoid that now.
const int64_t end_time = butil::gettimeofday_us();
const int64_t elp = end_time - start_time;
if (!cntl->Failed()) {
g_latency_recorder << elp;
} else {
g_error_count << 1;
if (sleep_on_error) {
bthread_usleep(10000);
}
}
delete cntl;
}
butil::atomic<int> g_thread_offset(0);
static void* replay_thread(void* arg) {
ChannelGroup* chan_group = static_cast<ChannelGroup*>(arg);
const int thread_offset = g_thread_offset.fetch_add(1, butil::memory_order_relaxed);
double req_rate = FLAGS_qps / (double)FLAGS_thread_num;
brpc::SerializedRequest req;
std::deque<int64_t> timeq;
size_t MAX_QUEUE_SIZE = (size_t)req_rate;
if (MAX_QUEUE_SIZE < 100) {
MAX_QUEUE_SIZE = 100;
} else if (MAX_QUEUE_SIZE > 2000) {
MAX_QUEUE_SIZE = 2000;
}
timeq.push_back(butil::gettimeofday_us());
for (int i = 0; !brpc::IsAskedToQuit() && i < FLAGS_times; ++i) {
brpc::SampleIterator it(FLAGS_dir);
int j = 0;
for (brpc::SampledRequest* sample = it.Next();
!brpc::IsAskedToQuit() && sample != NULL; sample = it.Next(), ++j) {
std::unique_ptr<brpc::SampledRequest> sample_guard(sample);
if ((j % FLAGS_thread_num) != thread_offset) {
continue;
}
brpc::Channel* chan =
chan_group->channel(sample->protocol_type());
if (chan == NULL) {
LOG(ERROR) << "No channel on protocol="
<< sample->protocol_type();
continue;
}
brpc::Controller* cntl = new brpc::Controller;
req.Clear();
cntl->reset_rpc_dump_meta(sample_guard.release());
if (sample->attachment_size() > 0) {
sample->request.cutn(
&req.serialized_data(),
sample->request.size() - sample->attachment_size());
cntl->request_attachment() = sample->request.movable();
} else {
req.serialized_data() = sample->request.movable();
}
g_sent_count << 1;
const int64_t start_time = butil::gettimeofday_us();
if (FLAGS_qps <= 0) {
chan->CallMethod(NULL/*use rpc_dump_context in cntl instead*/,
cntl, &req, NULL/*ignore response*/, NULL);
handle_response(cntl, start_time, true);
} else {
google::protobuf::Closure* done =
brpc::NewCallback(handle_response, cntl, start_time, false);
chan->CallMethod(NULL/*use rpc_dump_context in cntl instead*/,
cntl, &req, NULL/*ignore response*/, done);
const int64_t end_time = butil::gettimeofday_us();
int64_t expected_elp = 0;
int64_t actual_elp = 0;
timeq.push_back(end_time);
if (timeq.size() > MAX_QUEUE_SIZE) {
actual_elp = end_time - timeq.front();
timeq.pop_front();
expected_elp = (size_t)(1000000 * timeq.size() / req_rate);
} else {
actual_elp = end_time - timeq.front();
expected_elp = (size_t)(1000000 * (timeq.size() - 1) / req_rate);
}
if (actual_elp < expected_elp) {
bthread_usleep(expected_elp - actual_elp);
}
}
}
}
return NULL;
}
int main(int argc, char* argv[]) {
// Parse gflags. We recommend you to use gflags as well.
GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_dir.empty() ||
!butil::DirectoryExists(butil::FilePath(FLAGS_dir))) {
LOG(ERROR) << "--dir=<dir-of-dumped-files> is required";
return -1;
}
if (FLAGS_dummy_port >= 0) {
brpc::StartDummyServerAt(FLAGS_dummy_port);
}
ChannelGroup chan_group;
if (chan_group.Init() != 0) {
LOG(ERROR) << "Fail to init ChannelGroup";
return -1;
}
if (FLAGS_thread_num <= 0) {
if (FLAGS_qps <= 0) { // unlimited qps
FLAGS_thread_num = 50;
} else {
FLAGS_thread_num = FLAGS_qps / 10000;
if (FLAGS_thread_num < 1) {
FLAGS_thread_num = 1;
}
if (FLAGS_thread_num > 50) {
FLAGS_thread_num = 50;
}
}
}
std::vector<bthread_t> tids;
tids.resize(FLAGS_thread_num);
if (!FLAGS_use_bthread) {
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (pthread_create(&tids[i], NULL, replay_thread, &chan_group) != 0) {
LOG(ERROR) << "Fail to create pthread";
return -1;
}
}
} else {
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (bthread_start_background(
&tids[i], NULL, replay_thread, &chan_group) != 0) {
LOG(ERROR) << "Fail to create bthread";
return -1;
}
}
}
brpc::InfoThread info_thr;
brpc::InfoThreadOptions info_thr_opt;
info_thr_opt.latency_recorder = &g_latency_recorder;
info_thr_opt.error_count = &g_error_count;
info_thr_opt.sent_count = &g_sent_count;
if (!info_thr.start(info_thr_opt)) {
LOG(ERROR) << "Fail to create info_thread";
return -1;
}
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (!FLAGS_use_bthread) {
pthread_join(tids[i], NULL);
} else {
bthread_join(tids[i], NULL);
}
}
info_thr.stop();
return 0;
}
| 9,822 | 3,338 |
#pragma once
#include "../../../JObject.hpp"
namespace android::app
{
class NotificationChannel;
}
namespace android::content::pm
{
class ShortcutInfo;
}
class JString;
class JObject;
class JString;
namespace android::service::notification
{
class NotificationListenerService_Ranking : public JObject
{
public:
// Fields
static jint USER_SENTIMENT_NEGATIVE();
static jint USER_SENTIMENT_NEUTRAL();
static jint USER_SENTIMENT_POSITIVE();
static jint VISIBILITY_NO_OVERRIDE();
// QJniObject forward
template<typename ...Ts> explicit NotificationListenerService_Ranking(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
NotificationListenerService_Ranking(QJniObject obj);
// Constructors
NotificationListenerService_Ranking();
// Methods
jboolean canBubble() const;
jboolean canShowBadge() const;
jboolean equals(JObject arg0) const;
android::app::NotificationChannel getChannel() const;
android::content::pm::ShortcutInfo getConversationShortcutInfo() const;
jint getImportance() const;
JString getImportanceExplanation() const;
JString getKey() const;
jlong getLastAudiblyAlertedMillis() const;
jint getLockscreenVisibilityOverride() const;
JString getOverrideGroupKey() const;
jint getRank() const;
JObject getSmartActions() const;
JObject getSmartReplies() const;
jint getSuppressedVisualEffects() const;
jint getUserSentiment() const;
jboolean isAmbient() const;
jboolean isConversation() const;
jboolean isSuspended() const;
jboolean matchesInterruptionFilter() const;
};
} // namespace android::service::notification
| 1,658 | 568 |
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils/callbacks_ge.h"
#include "pybind11/pybind11.h"
#include "transform/df_graph_manager.h"
#include "transform/util.h"
#include "pipeline/parse/data_converter.h"
#include "pipeline/parse/python_adapter.h"
#include "utils/visible.h"
namespace mindspore {
namespace callbacks {
const char PYTHON_MOD_CALLBACK_MODULE[] = "mindspore.train.callback";
const char PYTHON_FUN_PROCESS_CHECKPOINT[] = "_checkpoint_cb_for_save_op";
const char PYTHON_FUN_PROCESS_SUMMARY[] = "_summary_cb_for_save_op";
const char kSummary[] = "Summary";
const char kCheckPoint[] = "Save";
const int ONE_SHAPE = 1;
using mindspore::transform::Status;
using mindspore::transform::TransformUtil;
bool GetParameterShape(const FuncGraphPtr &graph, const std::string ¶m_name,
const std::shared_ptr<std::vector<int>> &shape) {
if (graph == nullptr) {
MS_LOG(ERROR) << "Graph is null, can not get graph parameter";
return false;
}
auto parameter_nodes = graph->parameters();
for (auto &node : parameter_nodes) {
ParameterPtr param_node = std::static_pointer_cast<Parameter>(node);
if (param_node == nullptr) {
MS_LOG(ERROR) << "Parameter node is null, can not get graph parameter";
return false;
}
if (param_node->name() == param_name) {
py::object parameter = param_node->default_param();
ValuePtr value = parse::data_converter::PyDataToValue(parameter);
TensorPtr tensor = std::dynamic_pointer_cast<tensor::Tensor>(value);
if (tensor == nullptr) {
shape->push_back(ONE_SHAPE);
} else {
*shape = tensor->shape();
}
return true;
}
}
MS_LOG(ERROR) << "Can not find parameter of name:" << param_name;
return false;
}
static TensorPtr GetMeTensorTransformed(uint32_t graph_id, const std::string ¶meter_name,
const std::shared_ptr<ge::Tensor> &ge_tensor_ptr) {
FuncGraphPtr anf_graph = transform::DfGraphManager::GetInstance().GetAnfGraph(graph_id);
if (anf_graph == nullptr) {
MS_LOG(ERROR) << "Get anf graph failed during callback";
return nullptr;
}
std::shared_ptr<std::vector<int>> parameter_shape_ptr = std::make_shared<std::vector<int>>();
if (!GetParameterShape(anf_graph, parameter_name, parameter_shape_ptr)) {
MS_LOG(ERROR) << "Can not get parameter shape during callback";
return nullptr;
}
return TransformUtil::ConvertGeTensor(ge_tensor_ptr, *parameter_shape_ptr);
}
uint32_t CheckpointSaveCallback(uint32_t graph_id, const std::map<std::string, ge::Tensor> ¶ms_list) {
// Acquire GIL before calling Python code
py::gil_scoped_acquire acquire;
MS_LOG(DEBUG) << "Start the checkpoint save callback function in checkpoint save process.";
py::list parameter_list = py::list();
for (auto &item : params_list) {
std::string name = item.first;
std::shared_ptr<ge::Tensor> ge_tensor_ptr = std::make_shared<ge::Tensor>(item.second);
TensorPtr tensor_ptr = GetMeTensorTransformed(graph_id, name, ge_tensor_ptr);
if (tensor_ptr == nullptr) {
MS_LOG(EXCEPTION) << "Transform ge tensor to me tensor failed";
}
py::dict param_dict;
param_dict["name"] = name;
param_dict["data"] = tensor_ptr;
parameter_list.append(param_dict);
}
py::bool_ ret =
parse::python_adapter::CallPyFn(PYTHON_MOD_CALLBACK_MODULE, PYTHON_FUN_PROCESS_CHECKPOINT, parameter_list);
auto bool_ret = py::cast<bool>(ret);
uint32_t status = Status::SUCCESS;
if (!bool_ret) {
status = Status::FAILED;
MS_LOG(ERROR) << "Python checkpoint return false during callback";
}
return status;
}
static TensorPtr GetMeTensorForSummary(const std::string &name, const std::shared_ptr<ge::Tensor> &ge_tensor_ptr) {
// confirm the type by name
// Format: xxx[:Scalar] xxx[:Image] xxx[:Tensor]
if (name.empty()) {
MS_LOG(EXCEPTION) << "The summary name is empty.";
}
auto bpos = name.rfind("[:");
if (bpos >= name.size()) {
MS_LOG(EXCEPTION) << "The summary name(" << name << ") is invalid.";
}
auto tname = name.substr(bpos);
if (tname == "[:Scalar]") {
MS_LOG(DEBUG) << "The summary(" << name << ") is Scalar";
// process the scalar type summary
// Because the ge tensor is dim = 4, so set the (1,1,1,1)-->(1,)
// We do the (1,) shape is scalar
auto shape = std::vector<int>({ONE_SHAPE});
return TransformUtil::ConvertGeTensor(ge_tensor_ptr, shape);
}
if (tname == "[:Tensor]" || tname == "[:Histogram]") {
MS_LOG(DEBUG) << "The summary(" << name << ") is Tensor";
// process the tensor summary
// Now we can't get the real shape, so we keep same shape with GE
return TransformUtil::ConvertGeTensor(ge_tensor_ptr);
}
if (tname == "[:Image]") {
MS_LOG(DEBUG) << "The summary(" << name << ") is Image";
// process the Image summary
// Image dim = 4, is same with ge, so we keep same shape with GE
return TransformUtil::ConvertGeTensor(ge_tensor_ptr);
}
MS_LOG(EXCEPTION) << "The summary name(" << name << ") is invalid.";
}
// Cache the summary callback data
// Output Format: [{"name": tag_name, "data": tensor}, {"name": tag_name, "data": tensor},...]
uint32_t MS_EXPORT SummarySaveCallback(uint32_t graph_id, const std::map<std::string, ge::Tensor> ¶ms_list) {
// Acquire GIL before calling Python code
py::gil_scoped_acquire acquire;
MS_LOG(DEBUG) << "Start the summary save callback function for graph " << graph_id << ".";
py::list summary_list = py::list();
MS_LOG(DEBUG) << "Param list size = " << params_list.size();
for (auto &item : params_list) {
std::string tag_name = item.first;
std::shared_ptr<ge::Tensor> ge_tensor_ptr = std::make_shared<ge::Tensor>(item.second);
TensorPtr tensor_ptr = GetMeTensorForSummary(tag_name, ge_tensor_ptr);
if (tensor_ptr == nullptr) {
MS_LOG(EXCEPTION) << "ConvertGeTensor return tensor is null";
}
py::dict summary_value_dict;
summary_value_dict["name"] = tag_name;
summary_value_dict["data"] = tensor_ptr;
summary_list.append(summary_value_dict);
}
py::bool_ ret = parse::python_adapter::CallPyFn(PYTHON_MOD_CALLBACK_MODULE, PYTHON_FUN_PROCESS_SUMMARY, summary_list);
auto bool_ret = py::cast<bool>(ret);
if (!bool_ret) {
MS_LOG(ERROR) << "Python checkpoint return false during callback";
return Status::FAILED;
}
MS_LOG(DEBUG) << "End the summary save callback function.";
return Status::SUCCESS;
}
} // namespace callbacks
} // namespace mindspore
| 7,119 | 2,406 |
// Copyright 2019 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 "base/callback_helpers.h"
#include "base/run_loop.h"
#include "chrome/browser/ui/autofill/payments/virtual_card_selection_dialog_controller_impl.h"
#include "chrome/browser/ui/autofill/payments/virtual_card_selection_dialog_view.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/browser/ui/views/autofill/payments/virtual_card_selection_dialog_view_impl.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "content/public/test/browser_test.h"
#include "ui/views/controls/button/label_button.h"
namespace autofill {
namespace {
constexpr char kOneCardTest[] = "OneCard";
constexpr char kTwoCardsTest[] = "TwoCards";
} // namespace
class VirtualCardSelectionDialogBrowserTest : public DialogBrowserTest {
public:
VirtualCardSelectionDialogBrowserTest() = default;
// DialogBrowserTest:
void ShowUi(const std::string& name) override {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Do lazy initialization of VirtualCardSelectionDialogControllerImpl.
VirtualCardSelectionDialogControllerImpl::CreateForWebContents(
web_contents);
CreditCard card1 = test::GetFullServerCard();
if (name == kOneCardTest) {
controller()->ShowDialog({&card1}, base::DoNothing());
} else if (name == kTwoCardsTest) {
CreditCard card2 = test::GetFullServerCard();
controller()->ShowDialog({&card1, &card2}, base::DoNothing());
}
}
VirtualCardSelectionDialogViewImpl* GetDialog() {
if (!controller())
return nullptr;
VirtualCardSelectionDialogView* dialog_view = controller()->dialog_view();
if (!dialog_view)
return nullptr;
return static_cast<VirtualCardSelectionDialogViewImpl*>(dialog_view);
}
VirtualCardSelectionDialogControllerImpl* controller() {
if (!browser() || !browser()->tab_strip_model() ||
!browser()->tab_strip_model()->GetActiveWebContents())
return nullptr;
return VirtualCardSelectionDialogControllerImpl::FromWebContents(
browser()->tab_strip_model()->GetActiveWebContents());
}
private:
DISALLOW_COPY_AND_ASSIGN(VirtualCardSelectionDialogBrowserTest);
};
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
InvokeUi_OneCard) {
ShowAndVerifyUi();
}
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
CanCloseTabWhileDialogShowing) {
ShowUi(kOneCardTest);
VerifyUi();
browser()->tab_strip_model()->GetActiveWebContents()->Close();
base::RunLoop().RunUntilIdle();
}
// Ensures closing browser while dialog being visible is correctly handled.
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
CanCloseBrowserWhileDialogShowing) {
ShowUi(kOneCardTest);
VerifyUi();
browser()->window()->Close();
base::RunLoop().RunUntilIdle();
}
// Ensures dialog is closed when ok button is clicked when there is one card
// available.
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
ClickOkButton_OneCard) {
ShowUi(kOneCardTest);
VerifyUi();
ASSERT_TRUE(GetDialog()->GetOkButton()->GetEnabled());
GetDialog()->AcceptDialog();
base::RunLoop().RunUntilIdle();
}
// TODO(crbug.com/1020740): Add browser test for OK button when there are two
// cards. The logic to update button state will be implemented in the CL adding
// card list in the dialog.
// Ensures dialog is closed when cancel button is clicked.
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
ClickCancelButton) {
ShowUi(kOneCardTest);
VerifyUi();
GetDialog()->CancelDialog();
base::RunLoop().RunUntilIdle();
}
// TODO(crbug.com/1020740): Add more browsertests for interactions.
} // namespace autofill
| 4,070 | 1,240 |